docs: ${{ steps.filter.outputs.docs }}
steps:
- uses: actions/checkout@v4
- # For pull requests it's not necessary to checkout the code but for master it is
+ # For pull requests it's not necessary to checkout the code but for the main branch it is
- uses: dorny/paths-filter@v3
id: filter
with:
- docs/**
- docs_src/**
- requirements-docs.txt
+ - requirements-docs-insiders.txt
- pyproject.toml
- mkdocs.yml
- mkdocs.insiders.yml
+ - mkdocs.maybe-insiders.yml
+ - mkdocs.no-insiders.yml
- .github/workflows/build-docs.yml
- .github/workflows/deploy-docs.yml
langs:
id: cache
with:
path: ${{ env.pythonLocation }}
- key: ${{ runner.os }}-python-docs-${{ env.pythonLocation }}-${{ hashFiles('pyproject.toml', 'requirements-docs.txt', 'requirements-docs-tests.txt') }}-v07
+ key: ${{ runner.os }}-python-docs-${{ env.pythonLocation }}-${{ hashFiles('pyproject.toml', 'requirements-docs.txt', 'requirements-docs-insiders.txt', 'requirements-docs-tests.txt') }}-v08
- name: Install docs extras
if: steps.cache.outputs.cache-hit != 'true'
run: pip install -r requirements-docs.txt
# Install MkDocs Material Insiders here just to put it in the cache for the rest of the steps
- name: Install Material for MkDocs Insiders
if: ( github.event_name != 'pull_request' || github.secret_source == 'Actions' ) && steps.cache.outputs.cache-hit != 'true'
- run: |
- pip install git+https://${{ secrets.FASTAPI_MKDOCS_MATERIAL_INSIDERS }}@github.com/squidfunk/mkdocs-material-insiders.git
- pip install git+https://${{ secrets.FASTAPI_MKDOCS_MATERIAL_INSIDERS }}@github.com/pawamoy-insiders/griffe-typing-deprecated.git
- pip install git+https://${{ secrets.FASTAPI_MKDOCS_MATERIAL_INSIDERS }}@github.com/pawamoy-insiders/mkdocstrings-python.git
+ run: pip install -r requirements-docs-insiders.txt
+ env:
+ TOKEN: ${{ secrets.FASTAPI_MKDOCS_MATERIAL_INSIDERS }}
- name: Verify Docs
run: python ./scripts/docs.py verify-docs
- name: Export Language Codes
id: cache
with:
path: ${{ env.pythonLocation }}
- key: ${{ runner.os }}-python-docs-${{ env.pythonLocation }}-${{ hashFiles('pyproject.toml', 'requirements-docs.txt', 'requirements-docs-tests.txt') }}-v08
+ key: ${{ runner.os }}-python-docs-${{ env.pythonLocation }}-${{ hashFiles('pyproject.toml', 'requirements-docs.txt', 'requirements-docs-insiders.txt', 'requirements-docs-tests.txt') }}-v08
- name: Install docs extras
if: steps.cache.outputs.cache-hit != 'true'
run: pip install -r requirements-docs.txt
- name: Install Material for MkDocs Insiders
if: ( github.event_name != 'pull_request' || github.secret_source == 'Actions' ) && steps.cache.outputs.cache-hit != 'true'
- run: |
- pip install git+https://${{ secrets.FASTAPI_MKDOCS_MATERIAL_INSIDERS }}@github.com/squidfunk/mkdocs-material-insiders.git
- pip install git+https://${{ secrets.FASTAPI_MKDOCS_MATERIAL_INSIDERS }}@github.com/pawamoy-insiders/griffe-typing-deprecated.git
- pip install git+https://${{ secrets.FASTAPI_MKDOCS_MATERIAL_INSIDERS }}@github.com/pawamoy-insiders/mkdocstrings-python.git
+ run: pip install -r requirements-docs-insiders.txt
+ env:
+ TOKEN: ${{ secrets.FASTAPI_MKDOCS_MATERIAL_INSIDERS }}
- name: Update Languages
run: python ./scripts/docs.py update-languages
- uses: actions/cache@v4
তবে, আপনি যদি কখনো **FastAPI** ব্যবহার নাও করেন, তবুও এগুলি সম্পর্কে একটু শেখা আপনার উপকারে আসবে।
-!!! Note
- যদি আপনি একজন Python বিশেষজ্ঞ হন, এবং টাইপ হিন্ট সম্পর্কে সবকিছু জানেন, তাহলে পরবর্তী অধ্যায়ে চলে যান।
+/// note
+
+যদি আপনি একজন Python বিশেষজ্ঞ হন, এবং টাইপ হিন্ট সম্পর্কে সবকিছু জানেন, তাহলে পরবর্তী অধ্যায়ে চলে যান।
+
+///
## প্রেরণা
উদাহরণস্বরূপ, একটি ভেরিয়েবলকে `str`-এর একটি `list` হিসেবে সংজ্ঞায়িত করা যাক।
-=== "Python 3.9+"
+//// tab | Python 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!}
+```
-=== "Python 3.8+"
+////
- `typing` থেকে `List` (বড় হাতের `L` দিয়ে) ইমপোর্ট করুন:
+//// tab | Python 3.8+
- ``` Python hl_lines="1"
- {!> ../../../docs_src/python_types/tutorial006.py!}
- ```
+`typing` থেকে `List` (বড় হাতের `L` দিয়ে) ইমপোর্ট করুন:
- ভেরিয়েবলটি ঘোষণা করুন, একই কোলন (`:`) সিনট্যাক্স ব্যবহার করে।
+``` Python hl_lines="1"
+{!> ../../../docs_src/python_types/tutorial006.py!}
+```
- টাইপ হিসেবে, `typing` থেকে আপনার ইম্পোর্ট করা `List` ব্যবহার করুন।
+ভেরিয়েবলটি ঘোষণা করুন, একই কোলন (`:`) সিনট্যাক্স ব্যবহার করে।
+
+টাইপ হিসেবে, `typing` থেকে আপনার ইম্পোর্ট করা `List` ব্যবহার করুন।
+
+যেহেতু লিস্ট এমন একটি টাইপ যা অভ্যন্তরীণ টাইপগুলি ধারণ করে, আপনি তাদের স্কোয়ার ব্রাকেটের ভিতরে করুন:
+
+```Python hl_lines="4"
+{!> ../../../docs_src/python_types/tutorial006.py!}
+```
- যেহেতু লিস্ট এমন একটি টাইপ যা অভ্যন্তরীণ টাইপগুলি ধারণ করে, আপনি তাদের স্কোয়ার ব্রাকেটের ভিতরে করুন:
+////
- ```Python hl_lines="4"
- {!> ../../../docs_src/python_types/tutorial006.py!}
- ```
+/// info
-!!! Info
- স্কোয়ার ব্রাকেট এর ভিতরে ব্যবহৃত এইসব অভন্তরীন টাইপগুলোকে "ইন্টারনাল টাইপ" বলে।
+স্কোয়ার ব্রাকেট এর ভিতরে ব্যবহৃত এইসব অভন্তরীন টাইপগুলোকে "ইন্টারনাল টাইপ" বলে।
- এই উদাহরণে, এটি হচ্ছে `List`(অথবা পাইথন ৩.৯ বা তার উপরের সংস্করণের ক্ষেত্রে `list`) এ পাস করা টাইপ প্যারামিটার।
+এই উদাহরণে, এটি হচ্ছে `List`(অথবা পাইথন ৩.৯ বা তার উপরের সংস্করণের ক্ষেত্রে `list`) এ পাস করা টাইপ প্যারামিটার।
+
+///
এর অর্থ হচ্ছে: "ভেরিয়েবল `items` একটি `list`, এবং এই লিস্টের প্রতিটি আইটেম একটি `str`।"
-!!! Tip
- যদি আপনি Python 3.9 বা তার উপরে ব্যবহার করেন, আপনার `typing` থেকে `List` আমদানি করতে হবে না, আপনি সাধারণ `list` ওই টাইপের পরিবর্তে ব্যবহার করতে পারেন।
+/// tip
+
+যদি আপনি Python 3.9 বা তার উপরে ব্যবহার করেন, আপনার `typing` থেকে `List` আমদানি করতে হবে না, আপনি সাধারণ `list` ওই টাইপের পরিবর্তে ব্যবহার করতে পারেন।
+
+///
এর মাধ্যমে, আপনার এডিটর লিস্ট থেকে আইটেম প্রসেস করার সময় সাপোর্ট প্রদান করতে পারবে:
আপনি `tuple` এবং `set` ঘোষণা করার জন্য একই প্রক্রিয়া অনুসরণ করবেন:
-=== "Python 3.9+"
+//// tab | Python 3.9+
+
+```Python hl_lines="1"
+{!> ../../../docs_src/python_types/tutorial007_py39.py!}
+```
- ```Python hl_lines="1"
- {!> ../../../docs_src/python_types/tutorial007_py39.py!}
- ```
+////
-=== "Python 3.8+"
+//// tab | Python 3.8+
- ```Python hl_lines="1 4"
- {!> ../../../docs_src/python_types/tutorial007.py!}
- ```
+```Python hl_lines="1 4"
+{!> ../../../docs_src/python_types/tutorial007.py!}
+```
+
+////
এর মানে হল:
দ্বিতীয় টাইপ প্যারামিটারটি হল `dict`-এর মানগুলির জন্য:
-=== "Python 3.9+"
+//// tab | Python 3.9+
+
+```Python hl_lines="1"
+{!> ../../../docs_src/python_types/tutorial008_py39.py!}
+```
- ```Python hl_lines="1"
- {!> ../../../docs_src/python_types/tutorial008_py39.py!}
- ```
+////
-=== "Python 3.8+"
+//// tab | Python 3.8+
- ```Python hl_lines="1 4"
- {!> ../../../docs_src/python_types/tutorial008.py!}
- ```
+```Python hl_lines="1 4"
+{!> ../../../docs_src/python_types/tutorial008.py!}
+```
+////
এর মানে হল:
Python 3.10-এ একটি **নতুন সিনট্যাক্স** আছে যেখানে আপনি সম্ভাব্য টাইপগুলিকে একটি <abbr title="উল্লম্ব বারালকে 'বিটওয়াইজ বা অপারেটর' বলা হয়, কিন্তু সেই অর্থ এখানে প্রাসঙ্গিক নয়">ভার্টিকাল বার (`|`)</abbr> দ্বারা পৃথক করতে পারেন।
-=== "Python 3.10+"
+//// tab | Python 3.10+
+
+```Python hl_lines="1"
+{!> ../../../docs_src/python_types/tutorial008b_py310.py!}
+```
+
+////
- ```Python hl_lines="1"
- {!> ../../../docs_src/python_types/tutorial008b_py310.py!}
- ```
+//// tab | Python 3.8+
-=== "Python 3.8+"
+```Python hl_lines="1 4"
+{!> ../../../docs_src/python_types/tutorial008b.py!}
+```
- ```Python hl_lines="1 4"
- {!> ../../../docs_src/python_types/tutorial008b.py!}
- ```
+////
উভয় ক্ষেত্রেই এর মানে হল যে `item` হতে পারে একটি `int` অথবা `str`।
এর মানে হল, Python 3.10-এ, আপনি টাইপগুলির ইউনিয়ন ঘোষণা করতে `Something | None` ব্যবহার করতে পারেন:
-=== "Python 3.10+"
+//// tab | Python 3.10+
- ```Python hl_lines="1"
- {!> ../../../docs_src/python_types/tutorial009_py310.py!}
- ```
+```Python hl_lines="1"
+{!> ../../../docs_src/python_types/tutorial009_py310.py!}
+```
-=== "Python 3.8+"
+////
- ```Python hl_lines="1 4"
- {!> ../../../docs_src/python_types/tutorial009.py!}
- ```
+//// tab | Python 3.8+
-=== "Python 3.8+ বিকল্প"
+```Python hl_lines="1 4"
+{!> ../../../docs_src/python_types/tutorial009.py!}
+```
- ```Python hl_lines="1 4"
- {!> ../../../docs_src/python_types/tutorial009b.py!}
- ```
+////
+
+//// tab | Python 3.8+ বিকল্প
+
+```Python hl_lines="1 4"
+{!> ../../../docs_src/python_types/tutorial009b.py!}
+```
+
+////
#### `Union` বা `Optional` ব্যবহার
স্কোয়ার ব্র্যাকেটে টাইপ প্যারামিটার নেওয়া এই টাইপগুলিকে **জেনেরিক টাইপ** বা **জেনেরিকস** বলা হয়, যেমন:
-=== "Python 3.10+"
- আপনি সেই একই বিল্টইন টাইপ জেনেরিক্স হিসেবে ব্যবহার করতে পারবেন(ভিতরে টাইপ সহ স্কয়ারে ব্রাকেট দিয়ে):
+//// tab | Python 3.10+
+
+আপনি সেই একই বিল্টইন টাইপ জেনেরিক্স হিসেবে ব্যবহার করতে পারবেন(ভিতরে টাইপ সহ স্কয়ারে ব্রাকেট দিয়ে):
+
+* `list`
+* `tuple`
+* `set`
+* `dict`
+
+এবং Python 3.8 এর মতোই, `typing` মডিউল থেকে:
- * `list`
- * `tuple`
- * `set`
- * `dict`
+* `Union`
+* `Optional` (Python 3.8 এর মতোই)
+* ...এবং অন্যান্য।
- এবং Python 3.8 এর মতোই, `typing` মডিউল থেকে:
+Python 3.10-এ, `Union` এবং `Optional` জেনেরিকস ব্যবহার করার বিকল্প হিসেবে, আপনি টাইপগুলির ইউনিয়ন ঘোষণা করতে <abbr title="উল্লম্ব বারালকে 'বিটওয়াইজ বা অপারেটর' বলা হয়, কিন্তু সেই অর্থ এখানে প্রাসঙ্গিক নয়">ভার্টিকাল বার (`|`)</abbr> ব্যবহার করতে পারেন, যা ওদের থেকে অনেক ভালো এবং সহজ।
- * `Union`
- * `Optional` (Python 3.8 এর মতোই)
- * ...এবং অন্যান্য।
+////
- Python 3.10-এ, `Union` এবং `Optional` জেনেরিকস ব্যবহার করার বিকল্প হিসেবে, আপনি টাইপগুলির ইউনিয়ন ঘোষণা করতে <abbr title="উল্লম্ব বারালকে 'বিটওয়াইজ বা অপারেটর' বলা হয়, কিন্তু সেই অর্থ এখানে প্রাসঙ্গিক নয়">ভার্টিকাল বার (`|`)</abbr> ব্যবহার করতে পারেন, যা ওদের থেকে অনেক ভালো এবং সহজ।
+//// tab | Python 3.9+
-=== "Python 3.9+"
+আপনি সেই একই বিল্টইন টাইপ জেনেরিক্স হিসেবে ব্যবহার করতে পারবেন(ভিতরে টাইপ সহ স্কয়ারে ব্রাকেট দিয়ে):
- আপনি সেই একই বিল্টইন টাইপ জেনেরিক্স হিসেবে ব্যবহার করতে পারবেন(ভিতরে টাইপ সহ স্কয়ারে ব্রাকেট দিয়ে):
+* `list`
+* `tuple`
+* `set`
+* `dict`
- * `list`
- * `tuple`
- * `set`
- * `dict`
+এবং Python 3.8 এর মতোই, `typing` মডিউল থেকে:
- এবং Python 3.8 এর মতোই, `typing` মডিউল থেকে:
+* `Union`
+* `Optional`
+* ...এবং অন্যান্য।
- * `Union`
- * `Optional`
- * ...এবং অন্যান্য।
+////
-=== "Python 3.8+"
+//// tab | Python 3.8+
- * `List`
- * `Tuple`
- * `Set`
- * `Dict`
- * `Union`
- * `Optional`
- * ...এবং অন্যান্য।
+* `List`
+* `Tuple`
+* `Set`
+* `Dict`
+* `Union`
+* `Optional`
+* ...এবং অন্যান্য।
+
+////
### ক্লাস হিসেবে টাইপস
অফিসিয়াল Pydantic ডক্স থেকে একটি উদাহরণ:
-=== "Python 3.10+"
+//// tab | Python 3.10+
+
+```Python
+{!> ../../../docs_src/python_types/tutorial011_py310.py!}
+```
+
+////
+
+//// tab | Python 3.9+
+
+```Python
+{!> ../../../docs_src/python_types/tutorial011_py39.py!}
+```
+
+////
- ```Python
- {!> ../../../docs_src/python_types/tutorial011_py310.py!}
- ```
+//// tab | Python 3.8+
-=== "Python 3.9+"
+```Python
+{!> ../../../docs_src/python_types/tutorial011.py!}
+```
- ```Python
- {!> ../../../docs_src/python_types/tutorial011_py39.py!}
- ```
+////
-=== "Python 3.8+"
+/// info
- ```Python
- {!> ../../../docs_src/python_types/tutorial011.py!}
- ```
+[Pydantic সম্পর্কে আরও জানতে, এর ডকুমেন্টেশন দেখুন](https://docs.pydantic.dev/)।
-!!! Info
- [Pydantic সম্পর্কে আরও জানতে, এর ডকুমেন্টেশন দেখুন](https://docs.pydantic.dev/)।
+///
**FastAPI** মূলত Pydantic-এর উপর নির্মিত।
আপনি এই সমস্ত কিছুর অনেক বাস্তবসম্মত উদাহরণ পাবেন [টিউটোরিয়াল - ইউজার গাইডে](https://fastapi.tiangolo.com/tutorial/)।
-!!! Tip
- যখন আপনি `Optional` বা `Union[Something, None]` ব্যবহার করেন এবং কোনো ডিফল্ট মান না থাকে, Pydantic-এর একটি বিশেষ আচরণ রয়েছে, আপনি Pydantic ডকুমেন্টেশনে [Required Optional fields](https://docs.pydantic.dev/latest/concepts/models/#required-optional-fields) সম্পর্কে আরও পড়তে পারেন।
+/// tip
+
+যখন আপনি `Optional` বা `Union[Something, None]` ব্যবহার করেন এবং কোনো ডিফল্ট মান না থাকে, Pydantic-এর একটি বিশেষ আচরণ রয়েছে, আপনি Pydantic ডকুমেন্টেশনে [Required Optional fields](https://docs.pydantic.dev/latest/concepts/models/#required-optional-fields) সম্পর্কে আরও পড়তে পারেন।
+
+///
## মেটাডাটা অ্যানোটেশন সহ টাইপ হিন্টস
Python-এ এমন একটি ফিচার আছে যা `Annotated` ব্যবহার করে এই টাইপ হিন্টগুলিতে **অতিরিক্ত মেটাডাটা** রাখতে দেয়।
-=== "Python 3.9+"
+//// tab | Python 3.9+
+
+Python 3.9-এ, `Annotated` স্ট্যান্ডার্ড লাইব্রেরিতে অন্তর্ভুক্ত, তাই আপনি এটি `typing` থেকে ইমপোর্ট করতে পারেন।
+
+```Python hl_lines="1 4"
+{!> ../../../docs_src/python_types/tutorial013_py39.py!}
+```
- Python 3.9-এ, `Annotated` স্ট্যান্ডার্ড লাইব্রেরিতে অন্তর্ভুক্ত, তাই আপনি এটি `typing` থেকে ইমপোর্ট করতে পারেন।
+////
- ```Python hl_lines="1 4"
- {!> ../../../docs_src/python_types/tutorial013_py39.py!}
- ```
+//// tab | Python 3.8+
-=== "Python 3.8+"
+Python 3.9-এর নীচের সংস্করণগুলিতে, আপনি `Annotated`-কে `typing_extensions` থেকে ইমপোর্ট করেন।
- Python 3.9-এর নীচের সংস্করণগুলিতে, আপনি `Annotated`-কে `typing_extensions` থেকে ইমপোর্ট করেন।
+এটি **FastAPI** এর সাথে ইতিমদ্ধে ইনস্টল হয়ে থাকবে।
- এটি **FastAPI** এর সাথে ইতিমদ্ধে ইনস্টল হয়ে থাকবে।
+```Python hl_lines="1 4"
+{!> ../../../docs_src/python_types/tutorial013.py!}
+```
- ```Python hl_lines="1 4"
- {!> ../../../docs_src/python_types/tutorial013.py!}
- ```
+////
Python নিজে এই `Annotated` দিয়ে কিছুই করে না। এবং এডিটর এবং অন্যান্য টুলগুলির জন্য, টাইপটি এখনও `str`।
পরবর্তীতে আপনি দেখবেন এটি কতটা **শক্তিশালী** হতে পারে।
-!!! Tip
- এটি **স্ট্যান্ডার্ড Python** হওয়ার মানে হল আপনি আপনার এডিটরে, আপনি যে টুলগুলি কোড বিশ্লেষণ এবং রিফ্যাক্টর করার জন্য ব্যবহার করেন তাতে **সেরা সম্ভাব্য ডেভেলপার এক্সপেরিয়েন্স** পাবেন। ✨
+/// tip
- এবং এছাড়াও আপনার কোড অন্যান্য অনেক Python টুল এবং লাইব্রেরিগুলির সাথে খুব সামঞ্জস্যপূর্ণ হবে। 🚀
+এটি **স্ট্যান্ডার্ড Python** হওয়ার মানে হল আপনি আপনার এডিটরে, আপনি যে টুলগুলি কোড বিশ্লেষণ এবং রিফ্যাক্টর করার জন্য ব্যবহার করেন তাতে **সেরা সম্ভাব্য ডেভেলপার এক্সপেরিয়েন্স** পাবেন। ✨
+
+এবং এছাড়াও আপনার কোড অন্যান্য অনেক Python টুল এবং লাইব্রেরিগুলির সাথে খুব সামঞ্জস্যপূর্ণ হবে। 🚀
+
+///
## **FastAPI**-এ টাইপ হিন্টস
গুরুত্বপূর্ণ বিষয় হল, আপনি যদি স্ট্যান্ডার্ড Python টাইপগুলি ব্যবহার করেন, তবে আরও বেশি ক্লাস, ডেকোরেটর ইত্যাদি যোগ না করেই একই স্থানে **FastAPI** আপনার অনেক কাজ করে দিবে।
-!!! Info
- যদি আপনি টিউটোরিয়ালের সমস্ত বিষয় পড়ে ফেলে থাকেন এবং টাইপ সম্পর্কে আরও জানতে চান, তবে একটি ভালো রিসোর্স হল [mypy এর "cheat sheet"](https://mypy.readthedocs.io/en/latest/cheat_sheet_py3.html)। এই "cheat sheet" এ আপনি Python টাইপ হিন্ট সম্পর্কে বেসিক থেকে উন্নত লেভেলের ধারণা পেতে পারেন, যা আপনার কোডে টাইপ সেফটি এবং স্পষ্টতা বাড়াতে সাহায্য করবে।
+/// info
+
+যদি আপনি টিউটোরিয়ালের সমস্ত বিষয় পড়ে ফেলে থাকেন এবং টাইপ সম্পর্কে আরও জানতে চান, তবে একটি ভালো রিসোর্স হল [mypy এর "cheat sheet"](https://mypy.readthedocs.io/en/latest/cheat_sheet_py3.html)। এই "cheat sheet" এ আপনি Python টাইপ হিন্ট সম্পর্কে বেসিক থেকে উন্নত লেভেলের ধারণা পেতে পারেন, যা আপনার কোডে টাইপ সেফটি এবং স্পষ্টতা বাড়াতে সাহায্য করবে।
+
+///
# Zusätzliche Responses in OpenAPI
-!!! warning "Achtung"
- Dies ist ein eher fortgeschrittenes Thema.
+/// warning | "Achtung"
- Wenn Sie mit **FastAPI** beginnen, benötigen Sie dies möglicherweise nicht.
+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.
{!../../../docs_src/additional_responses/tutorial001.py!}
```
-!!! note "Hinweis"
- Beachten Sie, dass Sie die `JSONResponse` direkt zurückgeben müssen.
+/// note | "Hinweis"
+
+Beachten Sie, dass Sie die `JSONResponse` direkt zurückgeben müssen.
+
+///
+
+/// info
-!!! info
- Der `model`-Schlüssel ist nicht Teil von OpenAPI.
+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.
+**FastAPI** nimmt das Pydantic-Modell von dort, generiert das JSON-Schema und fügt es an der richtigen Stelle ein.
- Die richtige Stelle ist:
+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.
+* 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:
{!../../../docs_src/additional_responses/tutorial002.py!}
```
-!!! note "Hinweis"
- Beachten Sie, dass Sie das Bild direkt mit einer `FileResponse` zurückgeben müssen.
+/// 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`).
-!!! 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.
- 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
Um dies zu erreichen, importieren Sie `JSONResponse`, und geben Sie Ihren Inhalt direkt zurück, indem Sie den gewünschten `status_code` setzen:
-=== "Python 3.10+"
+//// tab | Python 3.10+
- ```Python hl_lines="4 25"
- {!> ../../../docs_src/additional_status_codes/tutorial001_an_py310.py!}
- ```
+```Python hl_lines="4 25"
+{!> ../../../docs_src/additional_status_codes/tutorial001_an_py310.py!}
+```
-=== "Python 3.9+"
+////
- ```Python hl_lines="4 25"
- {!> ../../../docs_src/additional_status_codes/tutorial001_an_py39.py!}
- ```
+//// tab | Python 3.9+
-=== "Python 3.8+"
+```Python hl_lines="4 25"
+{!> ../../../docs_src/additional_status_codes/tutorial001_an_py39.py!}
+```
- ```Python hl_lines="4 26"
- {!> ../../../docs_src/additional_status_codes/tutorial001_an.py!}
- ```
+////
-=== "Python 3.10+ nicht annotiert"
+//// tab | Python 3.8+
- !!! tip "Tipp"
- Bevorzugen Sie die `Annotated`-Version, falls möglich.
+```Python hl_lines="4 26"
+{!> ../../../docs_src/additional_status_codes/tutorial001_an.py!}
+```
- ```Python hl_lines="2 23"
- {!> ../../../docs_src/additional_status_codes/tutorial001_py310.py!}
- ```
+////
-=== "Python 3.8+ nicht annotiert"
+//// tab | Python 3.10+ nicht annotiert
- !!! tip "Tipp"
- Bevorzugen Sie die `Annotated`-Version, falls möglich.
+/// tip | "Tipp"
- ```Python hl_lines="4 25"
- {!> ../../../docs_src/additional_status_codes/tutorial001.py!}
- ```
+Bevorzugen Sie die `Annotated`-Version, falls möglich.
-!!! warning "Achtung"
- Wenn Sie eine `Response` direkt zurückgeben, wie im obigen Beispiel, wird sie direkt zurückgegeben.
+///
- Sie wird nicht mit einem Modell usw. serialisiert.
+```Python hl_lines="2 23"
+{!> ../../../docs_src/additional_status_codes/tutorial001_py310.py!}
+```
- Stellen Sie sicher, dass sie die gewünschten Daten enthält und dass die Werte gültiges JSON sind (wenn Sie `JSONResponse` verwenden).
+////
-!!! note "Technische Details"
- Sie können auch `from starlette.responses import JSONResponse` verwenden.
+//// tab | Python 3.8+ nicht annotiert
- **FastAPI** bietet dieselben `starlette.responses` auch via `fastapi.responses` an, als Annehmlichkeit für Sie, den Entwickler. Die meisten verfügbaren Responses kommen aber direkt von Starlette. Das Gleiche gilt für `status`.
+/// tip | "Tipp"
+
+Bevorzugen Sie die `Annotated`-Version, falls möglich.
+
+///
+
+```Python hl_lines="4 25"
+{!> ../../../docs_src/additional_status_codes/tutorial001.py!}
+```
+
+////
+
+/// warning | "Achtung"
+
+Wenn Sie eine `Response` direkt zurückgeben, wie im obigen Beispiel, wird sie direkt zurückgegeben.
+
+Sie wird nicht mit einem Modell usw. serialisiert.
+
+Stellen Sie sicher, dass sie die gewünschten Daten enthält und dass die Werte gültiges JSON sind (wenn Sie `JSONResponse` verwenden).
+
+///
+
+/// note | "Technische Details"
+
+Sie können auch `from starlette.responses import JSONResponse` verwenden.
+
+**FastAPI** bietet dieselben `starlette.responses` auch via `fastapi.responses` an, als Annehmlichkeit für Sie, den Entwickler. Die meisten verfügbaren Responses kommen aber direkt von Starlette. Das Gleiche gilt für `status`.
+
+///
## OpenAPI- und API-Dokumentation
Dazu deklarieren wir eine Methode `__call__`:
-=== "Python 3.9+"
+//// tab | Python 3.9+
- ```Python hl_lines="12"
- {!> ../../../docs_src/dependencies/tutorial011_an_py39.py!}
- ```
+```Python hl_lines="12"
+{!> ../../../docs_src/dependencies/tutorial011_an_py39.py!}
+```
+
+////
+
+//// tab | Python 3.8+
+
+```Python hl_lines="11"
+{!> ../../../docs_src/dependencies/tutorial011_an.py!}
+```
-=== "Python 3.8+"
+////
- ```Python hl_lines="11"
- {!> ../../../docs_src/dependencies/tutorial011_an.py!}
- ```
+//// tab | Python 3.8+ nicht annotiert
-=== "Python 3.8+ nicht annotiert"
+/// tip | "Tipp"
- !!! tip "Tipp"
- Bevorzugen Sie die `Annotated`-Version, falls möglich.
+Bevorzugen Sie die `Annotated`-Version, falls möglich.
- ```Python hl_lines="10"
- {!> ../../../docs_src/dependencies/tutorial011.py!}
- ```
+///
+
+```Python hl_lines="10"
+{!> ../../../docs_src/dependencies/tutorial011.py!}
+```
+
+////
In diesem Fall ist dieses `__call__` das, was **FastAPI** verwendet, um nach zusätzlichen Parametern und Unterabhängigkeiten zu suchen, und das ist es auch, was später aufgerufen wird, um einen Wert an den Parameter in Ihrer *Pfadoperation-Funktion* zu übergeben.
Und jetzt können wir `__init__` verwenden, um die Parameter der Instanz zu deklarieren, die wir zum `Parametrisieren` der Abhängigkeit verwenden können:
-=== "Python 3.9+"
+//// tab | Python 3.9+
- ```Python hl_lines="9"
- {!> ../../../docs_src/dependencies/tutorial011_an_py39.py!}
- ```
+```Python hl_lines="9"
+{!> ../../../docs_src/dependencies/tutorial011_an_py39.py!}
+```
-=== "Python 3.8+"
+////
- ```Python hl_lines="8"
- {!> ../../../docs_src/dependencies/tutorial011_an.py!}
- ```
+//// tab | Python 3.8+
-=== "Python 3.8+ nicht annotiert"
+```Python hl_lines="8"
+{!> ../../../docs_src/dependencies/tutorial011_an.py!}
+```
+
+////
+
+//// tab | Python 3.8+ nicht annotiert
+
+/// tip | "Tipp"
- !!! tip "Tipp"
- Bevorzugen Sie die `Annotated`-Version, falls möglich.
+Bevorzugen Sie die `Annotated`-Version, falls möglich.
- ```Python hl_lines="7"
- {!> ../../../docs_src/dependencies/tutorial011.py!}
- ```
+///
+
+```Python hl_lines="7"
+{!> ../../../docs_src/dependencies/tutorial011.py!}
+```
+
+////
In diesem Fall wird **FastAPI** `__init__` nie berühren oder sich darum kümmern, wir werden es direkt in unserem Code verwenden.
Wir könnten eine Instanz dieser Klasse erstellen mit:
-=== "Python 3.9+"
+//// tab | Python 3.9+
+
+```Python hl_lines="18"
+{!> ../../../docs_src/dependencies/tutorial011_an_py39.py!}
+```
+
+////
- ```Python hl_lines="18"
- {!> ../../../docs_src/dependencies/tutorial011_an_py39.py!}
- ```
+//// tab | Python 3.8+
-=== "Python 3.8+"
+```Python hl_lines="17"
+{!> ../../../docs_src/dependencies/tutorial011_an.py!}
+```
- ```Python hl_lines="17"
- {!> ../../../docs_src/dependencies/tutorial011_an.py!}
- ```
+////
-=== "Python 3.8+ nicht annotiert"
+//// tab | Python 3.8+ nicht annotiert
- !!! tip "Tipp"
- Bevorzugen Sie die `Annotated`-Version, falls möglich.
+/// tip | "Tipp"
- ```Python hl_lines="16"
- {!> ../../../docs_src/dependencies/tutorial011.py!}
- ```
+Bevorzugen Sie die `Annotated`-Version, falls möglich.
+
+///
+
+```Python hl_lines="16"
+{!> ../../../docs_src/dependencies/tutorial011.py!}
+```
+
+////
Und auf diese Weise können wir unsere Abhängigkeit „parametrisieren“, die jetzt `"bar"` enthält, als das Attribut `checker.fixed_content`.
... und übergibt, was immer das als Wert dieser Abhängigkeit in unserer *Pfadoperation-Funktion* zurückgibt, als den Parameter `fixed_content_included`:
-=== "Python 3.9+"
+//// tab | Python 3.9+
+
+```Python hl_lines="22"
+{!> ../../../docs_src/dependencies/tutorial011_an_py39.py!}
+```
- ```Python hl_lines="22"
- {!> ../../../docs_src/dependencies/tutorial011_an_py39.py!}
- ```
+////
-=== "Python 3.8+"
+//// tab | Python 3.8+
- ```Python hl_lines="21"
- {!> ../../../docs_src/dependencies/tutorial011_an.py!}
- ```
+```Python hl_lines="21"
+{!> ../../../docs_src/dependencies/tutorial011_an.py!}
+```
+
+////
+
+//// tab | Python 3.8+ nicht annotiert
+
+/// tip | "Tipp"
+
+Bevorzugen Sie die `Annotated`-Version, falls möglich.
+
+///
+
+```Python hl_lines="20"
+{!> ../../../docs_src/dependencies/tutorial011.py!}
+```
-=== "Python 3.8+ nicht annotiert"
+////
- !!! tip "Tipp"
- Bevorzugen Sie die `Annotated`-Version, falls möglich.
+/// tip | "Tipp"
- ```Python hl_lines="20"
- {!> ../../../docs_src/dependencies/tutorial011.py!}
- ```
+Das alles mag gekünstelt wirken. Und es ist möglicherweise noch nicht ganz klar, welchen Nutzen das hat.
-!!! tip "Tipp"
- Das alles mag gekünstelt wirken. Und es ist möglicherweise noch nicht ganz klar, welchen Nutzen das hat.
+Diese Beispiele sind bewusst einfach gehalten, zeigen aber, wie alles funktioniert.
- Diese Beispiele sind bewusst einfach gehalten, zeigen aber, wie alles funktioniert.
+In den Kapiteln zum Thema Sicherheit gibt es Hilfsfunktionen, die auf die gleiche Weise implementiert werden.
- In den Kapiteln zum Thema Sicherheit gibt es Hilfsfunktionen, die auf die gleiche Weise implementiert werden.
+Wenn Sie das hier alles verstanden haben, wissen Sie bereits, wie diese Sicherheits-Hilfswerkzeuge unter der Haube funktionieren.
- Wenn Sie das hier alles verstanden haben, wissen Sie bereits, wie diese Sicherheits-Hilfswerkzeuge unter der Haube funktionieren.
+///
{!../../../docs_src/async_tests/test_main.py!}
```
-!!! tip "Tipp"
- Beachten Sie, dass die Testfunktion jetzt `async def` ist und nicht nur `def` wie zuvor, wenn Sie den `TestClient` verwenden.
+/// tip | "Tipp"
+
+Beachten Sie, dass die Testfunktion jetzt `async def` ist und nicht nur `def` wie zuvor, wenn Sie den `TestClient` verwenden.
+
+///
Dann können wir einen `AsyncClient` mit der App erstellen und mit `await` asynchrone Requests an ihn senden.
... welches wir verwendet haben, um unsere Requests mit dem `TestClient` zu machen.
-!!! tip "Tipp"
- Beachten Sie, dass wir async/await mit dem neuen `AsyncClient` verwenden – der Request ist asynchron.
+/// tip | "Tipp"
+
+Beachten Sie, dass wir async/await mit dem neuen `AsyncClient` verwenden – der Request ist asynchron.
+
+///
-!!! warning "Achtung"
- Falls Ihre Anwendung auf Lifespan-Events angewiesen ist, der `AsyncClient` löst diese Events nicht aus. Um sicherzustellen, dass sie ausgelöst werden, verwenden Sie `LifespanManager` von <a href="https://github.com/florimondmanca/asgi-lifespan#usage" class="external-link" target="_blank">florimondmanca/asgi-lifespan</a>.
+/// warning | "Achtung"
+
+Falls Ihre Anwendung auf Lifespan-Events angewiesen ist, der `AsyncClient` löst diese Events nicht aus. Um sicherzustellen, dass sie ausgelöst werden, verwenden Sie `LifespanManager` von <a href="https://github.com/florimondmanca/asgi-lifespan#usage" class="external-link" target="_blank">florimondmanca/asgi-lifespan</a>.
+
+///
## Andere asynchrone Funktionsaufrufe
Da die Testfunktion jetzt asynchron ist, können Sie in Ihren Tests neben dem Senden von Requests an Ihre FastAPI-Anwendung jetzt auch andere `async`hrone Funktionen aufrufen (und `await`en), genau so, wie Sie diese an anderer Stelle in Ihrem Code aufrufen würden.
-!!! tip "Tipp"
- Wenn Sie einen `RuntimeError: Task attached to a different loop` erhalten, wenn Sie asynchrone Funktionsaufrufe in Ihre Tests integrieren (z. B. bei Verwendung von <a href="https://stackoverflow.com/questions/41584243/runtimeerror-task-attached-to-a-different-loop" class="external-link" target="_blank">MongoDBs MotorClient</a>), dann denken Sie daran, Objekte zu instanziieren, die einen Event Loop nur innerhalb asynchroner Funktionen benötigen, z. B. einen `@app.on_event("startup")`-Callback.
+/// tip | "Tipp"
+
+Wenn Sie einen `RuntimeError: Task attached to a different loop` erhalten, wenn Sie asynchrone Funktionsaufrufe in Ihre Tests integrieren (z. B. bei Verwendung von <a href="https://stackoverflow.com/questions/41584243/runtimeerror-task-attached-to-a-different-loop" class="external-link" target="_blank">MongoDBs MotorClient</a>), dann denken Sie daran, Objekte zu instanziieren, die einen Event Loop nur innerhalb asynchroner Funktionen benötigen, z. B. einen `@app.on_event("startup")`-Callback.
+
+///
proxy --> server
```
-!!! tip "Tipp"
- Die IP `0.0.0.0` wird üblicherweise verwendet, um anzudeuten, dass das Programm alle auf diesem Computer/Server verfügbaren IPs abhört.
+/// tip | "Tipp"
+
+Die IP `0.0.0.0` wird üblicherweise verwendet, um anzudeuten, dass das Programm alle auf diesem Computer/Server verfügbaren IPs abhört.
+
+///
Die Benutzeroberfläche der Dokumentation würde benötigen, dass das OpenAPI-Schema deklariert, dass sich dieser API-`server` unter `/api/v1` (hinter dem Proxy) befindet. Zum Beispiel:
Falls Sie Hypercorn verwenden, das hat auch die Option `--root-path`.
-!!! note "Technische Details"
- Die ASGI-Spezifikation definiert einen `root_path` für diesen Anwendungsfall.
+/// note | "Technische Details"
+
+Die ASGI-Spezifikation definiert einen `root_path` für diesen Anwendungsfall.
+
+Und die Kommandozeilenoption `--root-path` stellt diesen `root_path` bereit.
- Und die Kommandozeilenoption `--root-path` stellt diesen `root_path` bereit.
+///
### Überprüfen des aktuellen `root_path`
Dadurch wird Traefik angewiesen, Port 9999 abzuhören und eine andere Datei `routes.toml` zu verwenden.
-!!! tip "Tipp"
- Wir verwenden Port 9999 anstelle des Standard-HTTP-Ports 80, damit Sie ihn nicht mit Administratorrechten (`sudo`) ausführen müssen.
+/// tip | "Tipp"
+
+Wir verwenden Port 9999 anstelle des Standard-HTTP-Ports 80, damit Sie ihn nicht mit Administratorrechten (`sudo`) ausführen müssen.
+
+///
Erstellen Sie nun die andere Datei `routes.toml`:
}
```
-!!! tip "Tipp"
- Beachten Sie, dass, obwohl Sie unter `http://127.0.0.1:8000/app` darauf zugreifen, als `root_path` angezeigt wird `/api/v1`, welches aus der Option `--root-path` stammt.
+/// tip | "Tipp"
+
+Beachten Sie, dass, obwohl Sie unter `http://127.0.0.1:8000/app` darauf zugreifen, als `root_path` angezeigt wird `/api/v1`, welches aus der Option `--root-path` stammt.
+
+///
Öffnen Sie nun die URL mit dem Port für Traefik, einschließlich des Pfadpräfixes: <a href="http://127.0.0.1:9999/api/v1/app" class="external-link" target="_blank">http://127.0.0.1:9999/api/v1/app</a>.
## Zusätzliche Server
-!!! warning "Achtung"
- Dies ist ein fortgeschrittener Anwendungsfall. Überspringen Sie das gerne.
+/// warning | "Achtung"
+
+Dies ist ein fortgeschrittener Anwendungsfall. Überspringen Sie das gerne.
+
+///
Standardmäßig erstellt **FastAPI** einen `server` im OpenAPI-Schema mit der URL für den `root_path`.
}
```
-!!! tip "Tipp"
- Beachten Sie den automatisch generierten Server mit dem `URL`-Wert `/api/v1`, welcher vom `root_path` stammt.
+/// tip | "Tipp"
+
+Beachten Sie den automatisch generierten Server mit dem `URL`-Wert `/api/v1`, welcher vom `root_path` stammt.
+
+///
In der Dokumentationsoberfläche unter <a href="http://127.0.0.1:9999/api/v1/docs" class="external-link" target="_blank">http://127.0.0.1:9999/api/v1/docs</a> würde es so aussehen:
<img src="/img/tutorial/behind-a-proxy/image03.png">
-!!! tip "Tipp"
- Die Dokumentationsoberfläche interagiert mit dem von Ihnen ausgewählten Server.
+/// tip | "Tipp"
+
+Die Dokumentationsoberfläche interagiert mit dem von Ihnen ausgewählten Server.
+
+///
### Den automatischen Server von `root_path` deaktivieren
Und wenn diese `Response` einen JSON-Medientyp (`application/json`) hat, wie es bei `JSONResponse` und `UJSONResponse` der Fall ist, werden die von Ihnen zurückgegebenen Daten automatisch mit jedem Pydantic `response_model` konvertiert (und gefiltert), das Sie im *Pfadoperation-Dekorator* deklariert haben.
-!!! note "Hinweis"
- Wenn Sie eine Response-Klasse ohne Medientyp verwenden, erwartet FastAPI, dass Ihre Response keinen Inhalt hat, und dokumentiert daher das Format der Response nicht in deren generierter OpenAPI-Dokumentation.
+/// note | "Hinweis"
+
+Wenn Sie eine Response-Klasse ohne Medientyp verwenden, erwartet FastAPI, dass Ihre Response keinen Inhalt hat, und dokumentiert daher das Format der Response nicht in deren generierter OpenAPI-Dokumentation.
+
+///
## `ORJSONResponse` verwenden
{!../../../docs_src/custom_response/tutorial001b.py!}
```
-!!! info
- Der Parameter `response_class` wird auch verwendet, um den „Medientyp“ der Response zu definieren.
+/// info
+
+Der Parameter `response_class` wird auch verwendet, um den „Medientyp“ der Response zu definieren.
+
+In diesem Fall wird der HTTP-Header `Content-Type` auf `application/json` gesetzt.
+
+Und er wird als solcher in OpenAPI dokumentiert.
+
+///
- In diesem Fall wird der HTTP-Header `Content-Type` auf `application/json` gesetzt.
+/// tip | "Tipp"
- Und er wird als solcher in OpenAPI dokumentiert.
+Die `ORJSONResponse` ist derzeit nur in FastAPI verfügbar, nicht in Starlette.
-!!! tip "Tipp"
- Die `ORJSONResponse` ist derzeit nur in FastAPI verfügbar, nicht in Starlette.
+///
## HTML-Response
{!../../../docs_src/custom_response/tutorial002.py!}
```
-!!! info
- Der Parameter `response_class` wird auch verwendet, um den „Medientyp“ der Response zu definieren.
+/// info
- In diesem Fall wird der HTTP-Header `Content-Type` auf `text/html` gesetzt.
+Der Parameter `response_class` wird auch verwendet, um den „Medientyp“ der Response zu definieren.
- Und er wird als solcher in OpenAPI dokumentiert.
+In diesem Fall wird der HTTP-Header `Content-Type` auf `text/html` gesetzt.
+
+Und er wird als solcher in OpenAPI dokumentiert.
+
+///
### Eine `Response` zurückgeben
{!../../../docs_src/custom_response/tutorial003.py!}
```
-!!! warning "Achtung"
- Eine `Response`, die direkt von Ihrer *Pfadoperation-Funktion* zurückgegeben wird, wird in OpenAPI nicht dokumentiert (zum Beispiel wird der `Content-Type` nicht dokumentiert) und ist in der automatischen interaktiven Dokumentation nicht sichtbar.
+/// warning | "Achtung"
+
+Eine `Response`, die direkt von Ihrer *Pfadoperation-Funktion* zurückgegeben wird, wird in OpenAPI nicht dokumentiert (zum Beispiel wird der `Content-Type` nicht dokumentiert) und ist in der automatischen interaktiven Dokumentation nicht sichtbar.
+
+///
+
+/// info
-!!! info
- Natürlich stammen der eigentliche `Content-Type`-Header, der Statuscode, usw., aus dem `Response`-Objekt, das Sie zurückgegeben haben.
+Natürlich stammen der eigentliche `Content-Type`-Header, der Statuscode, usw., aus dem `Response`-Objekt, das Sie zurückgegeben haben.
+
+///
### In OpenAPI dokumentieren und `Response` überschreiben
Bedenken Sie, dass Sie `Response` verwenden können, um alles andere zurückzugeben, oder sogar eine benutzerdefinierte Unterklasse zu erstellen.
-!!! note "Technische Details"
- Sie können auch `from starlette.responses import HTMLResponse` verwenden.
+/// 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.
- **FastAPI** bietet dieselben `starlette.responses` auch via `fastapi.responses` an, als Annehmlichkeit für Sie, den Entwickler. Die meisten verfügbaren Responses kommen aber direkt von Starlette.
+///
### `Response`
Eine alternative JSON-Response mit <a href="https://github.com/ultrajson/ultrajson" class="external-link" target="_blank">`ujson`</a>.
-!!! warning "Achtung"
- `ujson` ist bei der Behandlung einiger Sonderfälle weniger sorgfältig als Pythons eingebaute Implementierung.
+/// warning | "Achtung"
+
+`ujson` ist bei der Behandlung einiger Sonderfälle weniger sorgfältig als Pythons eingebaute Implementierung.
+
+///
```Python hl_lines="2 7"
{!../../../docs_src/custom_response/tutorial001.py!}
```
-!!! tip "Tipp"
- Möglicherweise ist `ORJSONResponse` eine schnellere Alternative.
+/// tip | "Tipp"
+
+Möglicherweise ist `ORJSONResponse` eine schnellere Alternative.
+
+///
### `RedirectResponse`
Auf diese Weise können wir das Ganze in einen `with`-Block einfügen und so sicherstellen, dass das dateiartige Objekt nach Abschluss geschlossen wird.
-!!! tip "Tipp"
- Beachten Sie, dass wir, da wir Standard-`open()` verwenden, welches `async` und `await` nicht unterstützt, hier die Pfadoperation mit normalen `def` deklarieren.
+/// tip | "Tipp"
+
+Beachten Sie, dass wir, da wir Standard-`open()` verwenden, welches `async` und `await` nicht unterstützt, hier die Pfadoperation mit normalen `def` deklarieren.
+
+///
### `FileResponse`
{!../../../docs_src/custom_response/tutorial010.py!}
```
-!!! tip "Tipp"
- Sie können dennoch weiterhin `response_class` in *Pfadoperationen* überschreiben, wie bisher.
+/// tip | "Tipp"
+
+Sie können dennoch weiterhin `response_class` in *Pfadoperationen* überschreiben, wie bisher.
+
+///
## Zusätzliche Dokumentation
Das funktioniert genauso wie mit Pydantic-Modellen. Und tatsächlich wird es unter der Haube mittels Pydantic auf die gleiche Weise bewerkstelligt.
-!!! info
- Bedenken Sie, dass Datenklassen nicht alles können, was Pydantic-Modelle können.
+/// info
- Daher müssen Sie möglicherweise weiterhin Pydantic-Modelle verwenden.
+Bedenken Sie, dass Datenklassen nicht alles können, was Pydantic-Modelle können.
- Wenn Sie jedoch eine Menge Datenklassen herumliegen haben, ist dies ein guter Trick, um sie für eine Web-API mithilfe von FastAPI zu verwenden. 🤓
+Daher müssen Sie möglicherweise weiterhin Pydantic-Modelle verwenden.
+
+Wenn Sie jedoch eine Menge Datenklassen herumliegen haben, ist dies ein guter Trick, um sie für eine Web-API mithilfe von FastAPI zu verwenden. 🤓
+
+///
## Datenklassen als `response_model`
Und dann, direkt nach dem `yield`, entladen wir das Modell. Dieser Code wird unmittelbar vor dem *Herunterfahren* ausgeführt, **nachdem** die Anwendung **die Bearbeitung von Requests abgeschlossen hat**. Dadurch könnten beispielsweise Ressourcen wie Arbeitsspeicher oder eine GPU freigegeben werden.
-!!! tip "Tipp"
- Das *Herunterfahren* würde erfolgen, wenn Sie die Anwendung **stoppen**.
+/// tip | "Tipp"
- Möglicherweise müssen Sie eine neue Version starten, oder Sie haben es einfach satt, sie auszuführen. 🤷
+Das *Herunterfahren* würde erfolgen, wenn Sie die Anwendung **stoppen**.
+
+Möglicherweise müssen Sie eine neue Version starten, oder Sie haben es einfach satt, sie auszuführen. 🤷
+
+///
### Lifespan-Funktion
## Alternative Events (deprecated)
-!!! warning "Achtung"
- Der empfohlene Weg, das *Hochfahren* und *Herunterfahren* zu handhaben, ist die Verwendung des `lifespan`-Parameters der `FastAPI`-App, wie oben beschrieben. Wenn Sie einen `lifespan`-Parameter übergeben, werden die `startup`- und `shutdown`-Eventhandler nicht mehr aufgerufen. Es ist entweder alles `lifespan` oder alles Events, nicht beides.
+/// warning | "Achtung"
+
+Der empfohlene Weg, das *Hochfahren* und *Herunterfahren* zu handhaben, ist die Verwendung des `lifespan`-Parameters der `FastAPI`-App, wie oben beschrieben. Wenn Sie einen `lifespan`-Parameter übergeben, werden die `startup`- und `shutdown`-Eventhandler nicht mehr aufgerufen. Es ist entweder alles `lifespan` oder alles Events, nicht beides.
- Sie können diesen Teil wahrscheinlich überspringen.
+Sie können diesen Teil wahrscheinlich überspringen.
+
+///
Es gibt eine alternative Möglichkeit, diese Logik zu definieren, sodass sie beim *Hochfahren* und beim *Herunterfahren* ausgeführt wird.
Hier schreibt die `shutdown`-Eventhandler-Funktion eine Textzeile `"Application shutdown"` in eine Datei `log.txt`.
-!!! info
- In der Funktion `open()` bedeutet `mode="a"` „append“ („anhängen“), sodass die Zeile nach dem, was sich in dieser Datei befindet, hinzugefügt wird, ohne den vorherigen Inhalt zu überschreiben.
+/// info
+
+In der Funktion `open()` bedeutet `mode="a"` „append“ („anhängen“), sodass die Zeile nach dem, was sich in dieser Datei befindet, hinzugefügt wird, ohne den vorherigen Inhalt zu überschreiben.
-!!! tip "Tipp"
- Beachten Sie, dass wir in diesem Fall eine Standard-Python-Funktion `open()` verwenden, die mit einer Datei interagiert.
+///
- Es handelt sich also um I/O (Input/Output), welches „Warten“ erfordert, bis Dinge auf die Festplatte geschrieben werden.
+/// tip | "Tipp"
- Aber `open()` verwendet nicht `async` und `await`.
+Beachten Sie, dass wir in diesem Fall eine Standard-Python-Funktion `open()` verwenden, die mit einer Datei interagiert.
- Daher deklarieren wir die Eventhandler-Funktion mit Standard-`def` statt mit `async def`.
+Es handelt sich also um I/O (Input/Output), welches „Warten“ erfordert, bis Dinge auf die Festplatte geschrieben werden.
+
+Aber `open()` verwendet nicht `async` und `await`.
+
+Daher deklarieren wir die Eventhandler-Funktion mit Standard-`def` statt mit `async def`.
+
+///
### `startup` und `shutdown` zusammen
In der technischen ASGI-Spezifikation ist dies Teil des <a href="https://asgi.readthedocs.io/en/latest/specs/lifespan.html" class="external-link" target="_blank">Lifespan Protokolls</a> und definiert Events namens `startup` und `shutdown`.
-!!! info
- Weitere Informationen zu Starlettes `lifespan`-Handlern finden Sie in <a href="https://www.starlette.io/lifespan/" class="external-link" target="_blank">Starlettes Lifespan-Dokumentation</a>.
+/// info
+
+Weitere Informationen zu Starlettes `lifespan`-Handlern finden Sie in <a href="https://www.starlette.io/lifespan/" class="external-link" target="_blank">Starlettes Lifespan-Dokumentation</a>.
+
+Einschließlich, wie man Lifespan-Zustand handhabt, der in anderen Bereichen Ihres Codes verwendet werden kann.
- Einschließlich, wie man Lifespan-Zustand handhabt, der in anderen Bereichen Ihres Codes verwendet werden kann.
+///
## Unteranwendungen
Beginnen wir mit einer einfachen FastAPI-Anwendung:
-=== "Python 3.9+"
+//// tab | Python 3.9+
- ```Python hl_lines="7-9 12-13 16-17 21"
- {!> ../../../docs_src/generate_clients/tutorial001_py39.py!}
- ```
+```Python hl_lines="7-9 12-13 16-17 21"
+{!> ../../../docs_src/generate_clients/tutorial001_py39.py!}
+```
+
+////
-=== "Python 3.8+"
+//// tab | Python 3.8+
- ```Python hl_lines="9-11 14-15 18 19 23"
- {!> ../../../docs_src/generate_clients/tutorial001.py!}
- ```
+```Python hl_lines="9-11 14-15 18 19 23"
+{!> ../../../docs_src/generate_clients/tutorial001.py!}
+```
+
+////
Beachten Sie, dass die *Pfadoperationen* die Modelle definieren, welche diese für die Request- und Response-<abbr title="Die eigentlichen Nutzdaten, abzüglich der Metadaten">Payload</abbr> verwenden, indem sie die Modelle `Item` und `ResponseMessage` verwenden.
<img src="/img/tutorial/generate-clients/image03.png">
-!!! tip "Tipp"
- Beachten Sie die automatische Vervollständigung für `name` und `price`, welche in der FastAPI-Anwendung im `Item`-Modell definiert wurden.
+/// tip | "Tipp"
+
+Beachten Sie die automatische Vervollständigung für `name` und `price`, welche in der FastAPI-Anwendung im `Item`-Modell definiert wurden.
+
+///
Sie erhalten Inline-Fehlerberichte für die von Ihnen gesendeten Daten:
Beispielsweise könnten Sie einen Abschnitt für **Items (Artikel)** und einen weiteren Abschnitt für **Users (Benutzer)** haben, und diese könnten durch Tags getrennt sein:
-=== "Python 3.9+"
+//// tab | Python 3.9+
+
+```Python hl_lines="21 26 34"
+{!> ../../../docs_src/generate_clients/tutorial002_py39.py!}
+```
+
+////
- ```Python hl_lines="21 26 34"
- {!> ../../../docs_src/generate_clients/tutorial002_py39.py!}
- ```
+//// tab | Python 3.8+
-=== "Python 3.8+"
+```Python hl_lines="23 28 36"
+{!> ../../../docs_src/generate_clients/tutorial002.py!}
+```
- ```Python hl_lines="23 28 36"
- {!> ../../../docs_src/generate_clients/tutorial002.py!}
- ```
+////
### Einen TypeScript-Client mit Tags generieren
Anschließend können Sie diese benutzerdefinierte Funktion als Parameter `generate_unique_id_function` an **FastAPI** übergeben:
-=== "Python 3.9+"
+//// tab | Python 3.9+
+
+```Python hl_lines="6-7 10"
+{!> ../../../docs_src/generate_clients/tutorial003_py39.py!}
+```
- ```Python hl_lines="6-7 10"
- {!> ../../../docs_src/generate_clients/tutorial003_py39.py!}
- ```
+////
-=== "Python 3.8+"
+//// tab | Python 3.8+
+
+```Python hl_lines="8-9 12"
+{!> ../../../docs_src/generate_clients/tutorial003.py!}
+```
- ```Python hl_lines="8-9 12"
- {!> ../../../docs_src/generate_clients/tutorial003.py!}
- ```
+////
### Einen TypeScript-Client mit benutzerdefinierten Operation-IDs generieren
Wir könnten das OpenAPI-JSON in eine Datei `openapi.json` herunterladen und dann mit einem Skript wie dem folgenden **den vorangestellten Tag entfernen**:
-=== "Python"
+//// tab | Python
- ```Python
- {!> ../../../docs_src/generate_clients/tutorial004.py!}
- ```
+```Python
+{!> ../../../docs_src/generate_clients/tutorial004.py!}
+```
+
+////
-=== "Node.js"
+//// tab | Node.js
+
+```Javascript
+{!> ../../../docs_src/generate_clients/tutorial004.js!}
+```
- ```Javascript
- {!> ../../../docs_src/generate_clients/tutorial004.js!}
- ```
+////
Damit würden die Operation-IDs von Dingen wie `items-get_items` in `get_items` umbenannt, sodass der Client-Generator einfachere Methodennamen generieren kann.
In den nächsten Abschnitten sehen Sie weitere Optionen, Konfigurationen und zusätzliche Funktionen.
-!!! tip "Tipp"
- Die nächsten Abschnitte sind **nicht unbedingt „fortgeschritten“**.
+/// tip | "Tipp"
- Und es ist möglich, dass für Ihren Anwendungsfall die Lösung in einem davon liegt.
+Die nächsten Abschnitte sind **nicht unbedingt „fortgeschritten“**.
+
+Und es ist möglich, dass für Ihren Anwendungsfall die Lösung in einem davon liegt.
+
+///
## Lesen Sie zuerst das Tutorial
**FastAPI** enthält mehrere Middlewares für gängige Anwendungsfälle. Wir werden als Nächstes sehen, wie man sie verwendet.
-!!! note "Technische Details"
- Für die nächsten Beispiele könnten Sie auch `from starlette.middleware.something import SomethingMiddleware` verwenden.
+/// note | "Technische Details"
- **FastAPI** bietet mehrere Middlewares via `fastapi.middleware` an, als Annehmlichkeit für Sie, den Entwickler. Die meisten verfügbaren Middlewares kommen aber direkt von Starlette.
+Für die nächsten Beispiele könnten Sie auch `from starlette.middleware.something import SomethingMiddleware` verwenden.
+
+**FastAPI** bietet mehrere Middlewares via `fastapi.middleware` an, als Annehmlichkeit für Sie, den Entwickler. Die meisten verfügbaren Middlewares kommen aber direkt von Starlette.
+
+///
## `HTTPSRedirectMiddleware`
{!../../../docs_src/openapi_callbacks/tutorial001.py!}
```
-!!! tip "Tipp"
- Der Query-Parameter `callback_url` verwendet einen Pydantic-<a href="https://docs.pydantic.dev/latest/api/networks/" class="external-link" target="_blank">Url</a>-Typ.
+/// tip | "Tipp"
+
+Der Query-Parameter `callback_url` verwendet einen Pydantic-<a href="https://docs.pydantic.dev/latest/api/networks/" class="external-link" target="_blank">Url</a>-Typ.
+
+///
Das einzig Neue ist `callbacks=invoices_callback_router.routes` als Argument für den *Pfadoperation-Dekorator*. Wir werden als Nächstes sehen, was das ist.
In diesem Beispiel wird nicht der Callback selbst implementiert (das könnte nur eine Codezeile sein), sondern nur der Dokumentationsteil.
-!!! tip "Tipp"
- Der eigentliche Callback ist nur ein HTTP-Request.
+/// tip | "Tipp"
+
+Der eigentliche Callback ist nur ein HTTP-Request.
- Wenn Sie den Callback selbst implementieren, können Sie beispielsweise <a href="https://www.python-httpx.org" class="external-link" target="_blank">HTTPX</a> oder <a href="https://requests.readthedocs.io/" class="external-link" target="_blank">Requests</a> verwenden.
+Wenn Sie den Callback selbst implementieren, können Sie beispielsweise <a href="https://www.python-httpx.org" class="external-link" target="_blank">HTTPX</a> oder <a href="https://requests.readthedocs.io/" class="external-link" target="_blank">Requests</a> verwenden.
+
+///
## Schreiben des Codes, der den Callback dokumentiert
Daher werden wir dasselbe Wissen nutzen, um zu dokumentieren, wie die *externe API* aussehen sollte ... indem wir die *Pfadoperation(en)* erstellen, welche die externe API implementieren soll (die, welche Ihre API aufruft).
-!!! tip "Tipp"
- Wenn Sie den Code zum Dokumentieren eines Callbacks schreiben, kann es hilfreich sein, sich vorzustellen, dass Sie dieser *externe Entwickler* sind. Und dass Sie derzeit die *externe API* implementieren, nicht *Ihre API*.
+/// tip | "Tipp"
+
+Wenn Sie den Code zum Dokumentieren eines Callbacks schreiben, kann es hilfreich sein, sich vorzustellen, dass Sie dieser *externe Entwickler* sind. Und dass Sie derzeit die *externe API* implementieren, nicht *Ihre API*.
- Wenn Sie diese Sichtweise (des *externen Entwicklers*) vorübergehend übernehmen, wird es offensichtlicher, wo die Parameter, das Pydantic-Modell für den Body, die Response, usw. für diese *externe API* hingehören.
+Wenn Sie diese Sichtweise (des *externen Entwicklers*) vorübergehend übernehmen, wird es offensichtlicher, wo die Parameter, das Pydantic-Modell für den Body, die Response, usw. für diese *externe API* hingehören.
+
+///
### Einen Callback-`APIRouter` erstellen
}
```
-!!! tip "Tipp"
- Beachten Sie, dass die verwendete Callback-URL die URL enthält, die als Query-Parameter in `callback_url` (`https://www.external.org/events`) empfangen wurde, und auch die Rechnungs-`id` aus dem JSON-Body (`2expen51ve`).
+/// tip | "Tipp"
+
+Beachten Sie, dass die verwendete Callback-URL die URL enthält, die als Query-Parameter in `callback_url` (`https://www.external.org/events`) empfangen wurde, und auch die Rechnungs-`id` aus dem JSON-Body (`2expen51ve`).
+
+///
### Den Callback-Router hinzufügen
{!../../../docs_src/openapi_callbacks/tutorial001.py!}
```
-!!! tip "Tipp"
- Beachten Sie, dass Sie nicht den Router selbst (`invoices_callback_router`) an `callback=` übergeben, sondern das Attribut `.routes`, wie in `invoices_callback_router.routes`.
+/// tip | "Tipp"
+
+Beachten Sie, dass Sie nicht den Router selbst (`invoices_callback_router`) an `callback=` übergeben, sondern das Attribut `.routes`, wie in `invoices_callback_router.routes`.
+
+///
### Es in der Dokumentation ansehen
Dies kann es Ihren Benutzern viel einfacher machen, **deren APIs zu implementieren**, um Ihre **Webhook**-Requests zu empfangen. Möglicherweise können diese sogar einen Teil des eigenem API-Codes automatisch generieren.
-!!! info
- Webhooks sind in OpenAPI 3.1.0 und höher verfügbar und werden von FastAPI `0.99.0` und höher unterstützt.
+/// info
+
+Webhooks sind in OpenAPI 3.1.0 und höher verfügbar und werden von FastAPI `0.99.0` und höher unterstützt.
+
+///
## Eine Anwendung mit Webhooks
Die von Ihnen definierten Webhooks landen im **OpenAPI**-Schema und der automatischen **Dokumentations-Oberfläche**.
-!!! info
- Das `app.webhooks`-Objekt ist eigentlich nur ein `APIRouter`, derselbe Typ, den Sie verwenden würden, wenn Sie Ihre Anwendung mit mehreren Dateien strukturieren.
+/// info
+
+Das `app.webhooks`-Objekt ist eigentlich nur ein `APIRouter`, derselbe Typ, den Sie verwenden würden, wenn Sie Ihre Anwendung mit mehreren Dateien strukturieren.
+
+///
Beachten Sie, dass Sie bei Webhooks tatsächlich keinen *Pfad* (wie `/items/`) deklarieren, sondern dass der Text, den Sie dort übergeben, lediglich eine **Kennzeichnung** des Webhooks (der Name des Events) ist. Zum Beispiel ist in `@app.webhooks.post("new-subscription")` der Webhook-Name `new-subscription`.
## OpenAPI operationId
-!!! warning "Achtung"
- Wenn Sie kein „Experte“ für OpenAPI sind, brauchen Sie dies wahrscheinlich nicht.
+/// warning | "Achtung"
+
+Wenn Sie kein „Experte“ für OpenAPI sind, brauchen Sie dies wahrscheinlich nicht.
+
+///
Mit dem Parameter `operation_id` können Sie die OpenAPI `operationId` festlegen, die in Ihrer *Pfadoperation* verwendet werden soll.
{!../../../docs_src/path_operation_advanced_configuration/tutorial002.py!}
```
-!!! tip "Tipp"
- Wenn Sie `app.openapi()` manuell aufrufen, sollten Sie vorher die `operationId`s aktualisiert haben.
+/// tip | "Tipp"
+
+Wenn Sie `app.openapi()` manuell aufrufen, sollten Sie vorher die `operationId`s aktualisiert haben.
+
+///
+
+/// warning | "Achtung"
+
+Wenn Sie dies tun, müssen Sie sicherstellen, dass jede Ihrer *Pfadoperation-Funktionen* einen eindeutigen Namen hat.
-!!! warning "Achtung"
- Wenn Sie dies tun, müssen Sie sicherstellen, dass jede Ihrer *Pfadoperation-Funktionen* einen eindeutigen Namen hat.
+Auch wenn diese sich in unterschiedlichen Modulen (Python-Dateien) befinden.
- Auch wenn diese sich in unterschiedlichen Modulen (Python-Dateien) befinden.
+///
## Von OpenAPI ausschließen
Wenn Sie in Ihrer Anwendung eine *Pfadoperation* deklarieren, generiert **FastAPI** automatisch die relevanten Metadaten dieser *Pfadoperation*, die in das OpenAPI-Schema aufgenommen werden sollen.
-!!! note "Technische Details"
- In der OpenAPI-Spezifikation wird das <a href="https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.3.md#operation-object" class="external-link" target="_blank">Operationsobjekt</a> genannt.
+/// note | "Technische Details"
+
+In der OpenAPI-Spezifikation wird das <a href="https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.3.md#operation-object" class="external-link" target="_blank">Operationsobjekt</a> genannt.
+
+///
Es hat alle Informationen zur *Pfadoperation* und wird zur Erstellung der automatischen Dokumentation verwendet.
Dieses *Pfadoperation*-spezifische OpenAPI-Schema wird normalerweise automatisch von **FastAPI** generiert, Sie können es aber auch erweitern.
-!!! tip "Tipp"
- Dies ist ein Low-Level Erweiterungspunkt.
+/// tip | "Tipp"
+
+Dies ist ein Low-Level Erweiterungspunkt.
- Wenn Sie nur zusätzliche Responses deklarieren müssen, können Sie dies bequemer mit [Zusätzliche Responses in OpenAPI](additional-responses.md){.internal-link target=_blank} tun.
+Wenn Sie nur zusätzliche Responses deklarieren müssen, können Sie dies bequemer mit [Zusätzliche Responses in OpenAPI](additional-responses.md){.internal-link target=_blank} tun.
+
+///
Sie können das OpenAPI-Schema für eine *Pfadoperation* erweitern, indem Sie den Parameter `openapi_extra` verwenden.
In der folgenden Anwendung verwenden wir beispielsweise weder die integrierte Funktionalität von FastAPI zum Extrahieren des JSON-Schemas aus Pydantic-Modellen noch die automatische Validierung für JSON. Tatsächlich deklarieren wir den Request-Content-Type als YAML und nicht als JSON:
-=== "Pydantic v2"
+//// tab | Pydantic v2
+
+```Python hl_lines="17-22 24"
+{!> ../../../docs_src/path_operation_advanced_configuration/tutorial007.py!}
+```
+
+////
+
+//// tab | Pydantic v1
+
+```Python hl_lines="17-22 24"
+{!> ../../../docs_src/path_operation_advanced_configuration/tutorial007_pv1.py!}
+```
- ```Python hl_lines="17-22 24"
- {!> ../../../docs_src/path_operation_advanced_configuration/tutorial007.py!}
- ```
+////
-=== "Pydantic v1"
+/// info
- ```Python hl_lines="17-22 24"
- {!> ../../../docs_src/path_operation_advanced_configuration/tutorial007_pv1.py!}
- ```
+In Pydantic Version 1 hieß die Methode zum Abrufen des JSON-Schemas für ein Modell `Item.schema()`, in Pydantic Version 2 heißt die Methode `Item.model_json_schema()`.
-!!! info
- In Pydantic Version 1 hieß die Methode zum Abrufen des JSON-Schemas für ein Modell `Item.schema()`, in Pydantic Version 2 heißt die Methode `Item.model_json_schema()`.
+///
Obwohl wir nicht die standardmäßig integrierte Funktionalität verwenden, verwenden wir dennoch ein Pydantic-Modell, um das JSON-Schema für die Daten, die wir in YAML empfangen möchten, manuell zu generieren.
Und dann parsen wir in unserem Code diesen YAML-Inhalt direkt und verwenden dann wieder dasselbe Pydantic-Modell, um den YAML-Inhalt zu validieren:
-=== "Pydantic v2"
+//// tab | Pydantic v2
+
+```Python hl_lines="26-33"
+{!> ../../../docs_src/path_operation_advanced_configuration/tutorial007.py!}
+```
+
+////
+
+//// tab | Pydantic v1
+
+```Python hl_lines="26-33"
+{!> ../../../docs_src/path_operation_advanced_configuration/tutorial007_pv1.py!}
+```
+
+////
+
+/// info
- ```Python hl_lines="26-33"
- {!> ../../../docs_src/path_operation_advanced_configuration/tutorial007.py!}
- ```
+In Pydantic Version 1 war die Methode zum Parsen und Validieren eines Objekts `Item.parse_obj()`, in Pydantic Version 2 heißt die Methode `Item.model_validate()`.
-=== "Pydantic v1"
+///
- ```Python hl_lines="26-33"
- {!> ../../../docs_src/path_operation_advanced_configuration/tutorial007_pv1.py!}
- ```
+/// tip | "Tipp"
-!!! info
- In Pydantic Version 1 war die Methode zum Parsen und Validieren eines Objekts `Item.parse_obj()`, in Pydantic Version 2 heißt die Methode `Item.model_validate()`.
+Hier verwenden wir dasselbe Pydantic-Modell wieder.
-!!! tip "Tipp"
- Hier verwenden wir dasselbe Pydantic-Modell wieder.
+Aber genauso hätten wir es auch auf andere Weise validieren können.
- Aber genauso hätten wir es auch auf andere Weise validieren können.
+///
{!../../../docs_src/response_cookies/tutorial001.py!}
```
-!!! tip "Tipp"
- Beachten Sie, dass, wenn Sie eine Response direkt zurückgeben, anstatt den `Response`-Parameter zu verwenden, FastAPI diese direkt zurückgibt.
+/// tip | "Tipp"
- Sie müssen also sicherstellen, dass Ihre Daten vom richtigen Typ sind. Z. B. sollten diese mit JSON kompatibel sein, wenn Sie eine `JSONResponse` zurückgeben.
+Beachten Sie, dass, wenn Sie eine Response direkt zurückgeben, anstatt den `Response`-Parameter zu verwenden, FastAPI diese direkt zurückgibt.
- Und auch, dass Sie keine Daten senden, die durch ein `response_model` hätten gefiltert werden sollen.
+Sie müssen also sicherstellen, dass Ihre Daten vom richtigen Typ sind. Z. B. sollten diese mit JSON kompatibel sein, wenn Sie eine `JSONResponse` zurückgeben.
+
+Und auch, dass Sie keine Daten senden, die durch ein `response_model` hätten gefiltert werden sollen.
+
+///
### Mehr Informationen
-!!! note "Technische Details"
- Sie können auch `from starlette.responses import Response` oder `from starlette.responses import JSONResponse` verwenden.
+/// note | "Technische Details"
+
+Sie können auch `from starlette.responses import Response` oder `from starlette.responses import JSONResponse` verwenden.
+
+**FastAPI** bietet dieselben `starlette.responses` auch via `fastapi.responses` an, als Annehmlichkeit für Sie, den Entwickler. Die meisten verfügbaren Responses kommen aber direkt von Starlette.
- **FastAPI** bietet dieselben `starlette.responses` auch via `fastapi.responses` an, als Annehmlichkeit für Sie, den Entwickler. Die meisten verfügbaren Responses kommen aber direkt von Starlette.
+Und da die `Response` häufig zum Setzen von Headern und Cookies verwendet wird, stellt **FastAPI** diese auch unter `fastapi.Response` bereit.
- Und da die `Response` häufig zum Setzen von Headern und Cookies verwendet wird, stellt **FastAPI** diese auch unter `fastapi.Response` bereit.
+///
Um alle verfügbaren Parameter und Optionen anzuzeigen, sehen Sie sich deren <a href="https://www.starlette.io/responses/#set-cookie" class="external-link" target="_blank">Dokumentation in Starlette</a> an.
Tatsächlich können Sie jede `Response` oder jede Unterklasse davon zurückgeben.
-!!! tip "Tipp"
- `JSONResponse` selbst ist eine Unterklasse von `Response`.
+/// tip | "Tipp"
+
+`JSONResponse` selbst ist eine Unterklasse von `Response`.
+
+///
Und wenn Sie eine `Response` zurückgeben, wird **FastAPI** diese direkt weiterleiten.
{!../../../docs_src/response_directly/tutorial001.py!}
```
-!!! note "Technische Details"
- Sie können auch `from starlette.responses import JSONResponse` verwenden.
+/// note | "Technische Details"
+
+Sie können auch `from starlette.responses import JSONResponse` verwenden.
+
+**FastAPI** bietet dieselben `starlette.responses` auch via `fastapi.responses` an, als Annehmlichkeit für Sie, den Entwickler. Die meisten verfügbaren Responses kommen aber direkt von Starlette.
- **FastAPI** bietet dieselben `starlette.responses` auch via `fastapi.responses` an, als Annehmlichkeit für Sie, den Entwickler. Die meisten verfügbaren Responses kommen aber direkt von Starlette.
+///
## Eine benutzerdefinierte `Response` zurückgeben
{!../../../docs_src/response_headers/tutorial001.py!}
```
-!!! note "Technische Details"
- Sie können auch `from starlette.responses import Response` oder `from starlette.responses import JSONResponse` verwenden.
+/// note | "Technische Details"
- **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.
+Sie können auch `from starlette.responses import Response` oder `from starlette.responses import JSONResponse` verwenden.
- Und da die `Response` häufig zum Setzen von Headern und Cookies verwendet wird, stellt **FastAPI** diese auch unter `fastapi.Response` bereit.
+**FastAPI** bietet dieselben `starlette.responses` auch via `fastapi.responses` an, als Annehmlichkeit für Sie, den Entwickler. Die meisten verfügbaren Responses kommen aber direkt von Starlette.
+
+Und da die `Response` häufig zum Setzen von Headern und Cookies verwendet wird, stellt **FastAPI** diese auch unter `fastapi.Response` bereit.
+
+///
## Benutzerdefinierte Header
* Diese gibt ein Objekt vom Typ `HTTPBasicCredentials` zurück:
* Es enthält den gesendeten `username` und das gesendete `password`.
-=== "Python 3.9+"
+//// tab | Python 3.9+
- ```Python hl_lines="4 8 12"
- {!> ../../../docs_src/security/tutorial006_an_py39.py!}
- ```
+```Python hl_lines="4 8 12"
+{!> ../../../docs_src/security/tutorial006_an_py39.py!}
+```
+
+////
+
+//// tab | Python 3.8+
+
+```Python hl_lines="2 7 11"
+{!> ../../../docs_src/security/tutorial006_an.py!}
+```
+
+////
-=== "Python 3.8+"
+//// tab | Python 3.8+ nicht annotiert
- ```Python hl_lines="2 7 11"
- {!> ../../../docs_src/security/tutorial006_an.py!}
- ```
+/// tip | "Tipp"
-=== "Python 3.8+ nicht annotiert"
+Bevorzugen Sie die `Annotated`-Version, falls möglich.
- !!! tip "Tipp"
- Bevorzugen Sie die `Annotated`-Version, falls möglich.
+///
- ```Python hl_lines="2 6 10"
- {!> ../../../docs_src/security/tutorial006.py!}
- ```
+```Python hl_lines="2 6 10"
+{!> ../../../docs_src/security/tutorial006.py!}
+```
+
+////
Wenn Sie versuchen, die URL zum ersten Mal zu öffnen (oder in der Dokumentation auf den Button „Execute“ zu klicken), wird der Browser Sie nach Ihrem Benutzernamen und Passwort fragen:
Dann können wir `secrets.compare_digest()` verwenden, um sicherzustellen, dass `credentials.username` `"stanleyjobson"` und `credentials.password` `"swordfish"` ist.
-=== "Python 3.9+"
+//// tab | Python 3.9+
+
+```Python hl_lines="1 12-24"
+{!> ../../../docs_src/security/tutorial007_an_py39.py!}
+```
+
+////
+
+//// tab | Python 3.8+
- ```Python hl_lines="1 12-24"
- {!> ../../../docs_src/security/tutorial007_an_py39.py!}
- ```
+```Python hl_lines="1 12-24"
+{!> ../../../docs_src/security/tutorial007_an.py!}
+```
+
+////
+
+//// tab | Python 3.8+ nicht annotiert
-=== "Python 3.8+"
+/// tip | "Tipp"
- ```Python hl_lines="1 12-24"
- {!> ../../../docs_src/security/tutorial007_an.py!}
- ```
+Bevorzugen Sie die `Annotated`-Version, falls möglich.
-=== "Python 3.8+ nicht annotiert"
+///
- !!! tip "Tipp"
- Bevorzugen Sie die `Annotated`-Version, falls möglich.
+```Python hl_lines="1 11-21"
+{!> ../../../docs_src/security/tutorial007.py!}
+```
- ```Python hl_lines="1 11-21"
- {!> ../../../docs_src/security/tutorial007.py!}
- ```
+////
Dies wäre das gleiche wie:
Nachdem Sie festgestellt haben, dass die Anmeldeinformationen falsch sind, geben Sie eine `HTTPException` mit dem Statuscode 401 zurück (derselbe, der auch zurückgegeben wird, wenn keine Anmeldeinformationen angegeben werden) und fügen den Header `WWW-Authenticate` hinzu, damit der Browser die Anmeldeaufforderung erneut anzeigt:
-=== "Python 3.9+"
+//// tab | Python 3.9+
+
+```Python hl_lines="26-30"
+{!> ../../../docs_src/security/tutorial007_an_py39.py!}
+```
+
+////
+
+//// tab | Python 3.8+
+
+```Python hl_lines="26-30"
+{!> ../../../docs_src/security/tutorial007_an.py!}
+```
+
+////
- ```Python hl_lines="26-30"
- {!> ../../../docs_src/security/tutorial007_an_py39.py!}
- ```
+//// tab | Python 3.8+ nicht annotiert
-=== "Python 3.8+"
+/// tip | "Tipp"
- ```Python hl_lines="26-30"
- {!> ../../../docs_src/security/tutorial007_an.py!}
- ```
+Bevorzugen Sie die `Annotated`-Version, falls möglich.
-=== "Python 3.8+ nicht annotiert"
+///
- !!! tip "Tipp"
- Bevorzugen Sie die `Annotated`-Version, falls möglich.
+```Python hl_lines="23-27"
+{!> ../../../docs_src/security/tutorial007.py!}
+```
- ```Python hl_lines="23-27"
- {!> ../../../docs_src/security/tutorial007.py!}
- ```
+////
Neben den in [Tutorial – Benutzerhandbuch: Sicherheit](../../tutorial/security/index.md){.internal-link target=_blank} behandelten Funktionen gibt es noch einige zusätzliche Funktionen zur Handhabung der Sicherheit.
-!!! tip "Tipp"
- Die nächsten Abschnitte sind **nicht unbedingt „fortgeschritten“**.
+/// tip | "Tipp"
- Und es ist möglich, dass für Ihren Anwendungsfall die Lösung in einem davon liegt.
+Die nächsten Abschnitte sind **nicht unbedingt „fortgeschritten“**.
+
+Und es ist möglich, dass für Ihren Anwendungsfall die Lösung in einem davon liegt.
+
+///
## Lesen Sie zuerst das Tutorial
In diesem Abschnitt erfahren Sie, wie Sie Authentifizierung und Autorisierung mit demselben OAuth2, mit Scopes in Ihrer **FastAPI**-Anwendung verwalten.
-!!! warning "Achtung"
- Dies ist ein mehr oder weniger fortgeschrittener Abschnitt. Wenn Sie gerade erst anfangen, können Sie ihn überspringen.
+/// warning | "Achtung"
- Sie benötigen nicht unbedingt OAuth2-Scopes, und Sie können die Authentifizierung und Autorisierung handhaben wie Sie möchten.
+Dies ist ein mehr oder weniger fortgeschrittener Abschnitt. Wenn Sie gerade erst anfangen, können Sie ihn überspringen.
- Aber OAuth2 mit Scopes kann bequem in Ihre API (mit OpenAPI) und deren API-Dokumentation integriert werden.
+Sie benötigen nicht unbedingt OAuth2-Scopes, und Sie können die Authentifizierung und Autorisierung handhaben wie Sie möchten.
- Dennoch, verwenden Sie solche Scopes oder andere Sicherheits-/Autorisierungsanforderungen in Ihrem Code so wie Sie es möchten.
+Aber OAuth2 mit Scopes kann bequem in Ihre API (mit OpenAPI) und deren API-Dokumentation integriert werden.
- In vielen Fällen kann OAuth2 mit Scopes ein Overkill sein.
+Dennoch, verwenden Sie solche Scopes oder andere Sicherheits-/Autorisierungsanforderungen in Ihrem Code so wie Sie es möchten.
- Aber wenn Sie wissen, dass Sie es brauchen oder neugierig sind, lesen Sie weiter.
+In vielen Fällen kann OAuth2 mit Scopes ein Overkill sein.
+
+Aber wenn Sie wissen, dass Sie es brauchen oder neugierig sind, lesen Sie weiter.
+
+///
## OAuth2-Scopes und OpenAPI
* `instagram_basic` wird von Facebook / Instagram verwendet.
* `https://www.googleapis.com/auth/drive` wird von Google verwendet.
-!!! info
- In OAuth2 ist ein „Scope“ nur ein String, der eine bestimmte erforderliche Berechtigung deklariert.
+/// info
+
+In OAuth2 ist ein „Scope“ nur ein String, der eine bestimmte erforderliche Berechtigung deklariert.
+
+Es spielt keine Rolle, ob er andere Zeichen wie `:` enthält oder ob es eine URL ist.
- Es spielt keine Rolle, ob er andere Zeichen wie `:` enthält oder ob es eine URL ist.
+Diese Details sind implementierungsspezifisch.
- Diese Details sind implementierungsspezifisch.
+Für OAuth2 sind es einfach nur Strings.
- Für OAuth2 sind es einfach nur Strings.
+///
## Gesamtübersicht
Sehen wir uns zunächst kurz die Teile an, die sich gegenüber den Beispielen im Haupt-**Tutorial – Benutzerhandbuch** für [OAuth2 mit Password (und Hashing), Bearer mit JWT-Tokens](../../tutorial/security/oauth2-jwt.md){.internal-link target=_blank} ändern. Diesmal verwenden wir OAuth2-Scopes:
-=== "Python 3.10+"
+//// tab | Python 3.10+
+
+```Python hl_lines="4 8 12 46 64 105 107-115 121-124 128-134 139 155"
+{!> ../../../docs_src/security/tutorial005_an_py310.py!}
+```
+
+////
+
+//// tab | Python 3.9+
+
+```Python hl_lines="2 4 8 12 46 64 105 107-115 121-124 128-134 139 155"
+{!> ../../../docs_src/security/tutorial005_an_py39.py!}
+```
+
+////
+
+//// tab | Python 3.8+
+
+```Python hl_lines="2 4 8 12 47 65 106 108-116 122-125 129-135 140 156"
+{!> ../../../docs_src/security/tutorial005_an.py!}
+```
+
+////
+
+//// tab | Python 3.10+ nicht annotiert
+
+/// tip | "Tipp"
- ```Python hl_lines="4 8 12 46 64 105 107-115 121-124 128-134 139 155"
- {!> ../../../docs_src/security/tutorial005_an_py310.py!}
- ```
+Bevorzugen Sie die `Annotated`-Version, falls möglich.
-=== "Python 3.9+"
+///
- ```Python hl_lines="2 4 8 12 46 64 105 107-115 121-124 128-134 139 155"
- {!> ../../../docs_src/security/tutorial005_an_py39.py!}
- ```
+```Python hl_lines="3 7 11 45 63 104 106-114 120-123 127-133 138 154"
+{!> ../../../docs_src/security/tutorial005_py310.py!}
+```
-=== "Python 3.8+"
+////
- ```Python hl_lines="2 4 8 12 47 65 106 108-116 122-125 129-135 140 156"
- {!> ../../../docs_src/security/tutorial005_an.py!}
- ```
+//// tab | Python 3.9+ nicht annotiert
-=== "Python 3.10+ nicht annotiert"
+/// tip | "Tipp"
- !!! tip "Tipp"
- Bevorzugen Sie die `Annotated`-Version, falls möglich.
+Bevorzugen Sie die `Annotated`-Version, falls möglich.
- ```Python hl_lines="3 7 11 45 63 104 106-114 120-123 127-133 138 154"
- {!> ../../../docs_src/security/tutorial005_py310.py!}
- ```
+///
-=== "Python 3.9+ nicht annotiert"
+```Python hl_lines="2 4 8 12 46 64 105 107-115 121-124 128-134 139 155"
+{!> ../../../docs_src/security/tutorial005_py39.py!}
+```
- !!! tip "Tipp"
- Bevorzugen Sie die `Annotated`-Version, falls möglich.
+////
- ```Python hl_lines="2 4 8 12 46 64 105 107-115 121-124 128-134 139 155"
- {!> ../../../docs_src/security/tutorial005_py39.py!}
- ```
+//// tab | Python 3.8+ nicht annotiert
-=== "Python 3.8+ nicht annotiert"
+/// tip | "Tipp"
- !!! tip "Tipp"
- Bevorzugen Sie die `Annotated`-Version, falls möglich.
+Bevorzugen Sie die `Annotated`-Version, falls möglich.
- ```Python hl_lines="2 4 8 12 46 64 105 107-115 121-124 128-134 139 155"
- {!> ../../../docs_src/security/tutorial005.py!}
- ```
+///
+
+```Python hl_lines="2 4 8 12 46 64 105 107-115 121-124 128-134 139 155"
+{!> ../../../docs_src/security/tutorial005.py!}
+```
+
+////
Sehen wir uns diese Änderungen nun Schritt für Schritt an.
Der `scopes`-Parameter erhält ein `dict` mit jedem Scope als Schlüssel und dessen Beschreibung als Wert:
-=== "Python 3.10+"
+//// tab | Python 3.10+
+
+```Python hl_lines="62-65"
+{!> ../../../docs_src/security/tutorial005_an_py310.py!}
+```
+
+////
+
+//// tab | Python 3.9+
+
+```Python hl_lines="62-65"
+{!> ../../../docs_src/security/tutorial005_an_py39.py!}
+```
+
+////
- ```Python hl_lines="62-65"
- {!> ../../../docs_src/security/tutorial005_an_py310.py!}
- ```
+//// tab | Python 3.8+
-=== "Python 3.9+"
+```Python hl_lines="63-66"
+{!> ../../../docs_src/security/tutorial005_an.py!}
+```
- ```Python hl_lines="62-65"
- {!> ../../../docs_src/security/tutorial005_an_py39.py!}
- ```
+////
-=== "Python 3.8+"
+//// tab | Python 3.10+ nicht annotiert
- ```Python hl_lines="63-66"
- {!> ../../../docs_src/security/tutorial005_an.py!}
- ```
+/// tip | "Tipp"
-=== "Python 3.10+ nicht annotiert"
+Bevorzugen Sie die `Annotated`-Version, falls möglich.
- !!! tip "Tipp"
- Bevorzugen Sie die `Annotated`-Version, falls möglich.
+///
- ```Python hl_lines="61-64"
- {!> ../../../docs_src/security/tutorial005_py310.py!}
- ```
+```Python hl_lines="61-64"
+{!> ../../../docs_src/security/tutorial005_py310.py!}
+```
+////
-=== "Python 3.9+ nicht annotiert"
+//// tab | Python 3.9+ nicht annotiert
- !!! tip "Tipp"
- Bevorzugen Sie die `Annotated`-Version, falls möglich.
+/// tip | "Tipp"
- ```Python hl_lines="62-65"
- {!> ../../../docs_src/security/tutorial005_py39.py!}
- ```
+Bevorzugen Sie die `Annotated`-Version, falls möglich.
-=== "Python 3.8+ nicht annotiert"
+///
- !!! tip "Tipp"
- Bevorzugen Sie die `Annotated`-Version, falls möglich.
+```Python hl_lines="62-65"
+{!> ../../../docs_src/security/tutorial005_py39.py!}
+```
- ```Python hl_lines="62-65"
- {!> ../../../docs_src/security/tutorial005.py!}
- ```
+////
+
+//// tab | Python 3.8+ nicht annotiert
+
+/// tip | "Tipp"
+
+Bevorzugen Sie die `Annotated`-Version, falls möglich.
+
+///
+
+```Python hl_lines="62-65"
+{!> ../../../docs_src/security/tutorial005.py!}
+```
+
+////
Da wir diese Scopes jetzt deklarieren, werden sie in der API-Dokumentation angezeigt, wenn Sie sich einloggen/autorisieren.
Und wir geben die Scopes als Teil des JWT-Tokens zurück.
-!!! danger "Gefahr"
- Der Einfachheit halber fügen wir hier die empfangenen Scopes direkt zum Token hinzu.
+/// danger | "Gefahr"
+
+Der Einfachheit halber fügen wir hier die empfangenen Scopes direkt zum Token hinzu.
- Aus Sicherheitsgründen sollten Sie jedoch sicherstellen, dass Sie in Ihrer Anwendung nur die Scopes hinzufügen, die der Benutzer tatsächlich haben kann, oder die Sie vordefiniert haben.
+Aus Sicherheitsgründen sollten Sie jedoch sicherstellen, dass Sie in Ihrer Anwendung nur die Scopes hinzufügen, die der Benutzer tatsächlich haben kann, oder die Sie vordefiniert haben.
-=== "Python 3.10+"
+///
- ```Python hl_lines="155"
- {!> ../../../docs_src/security/tutorial005_an_py310.py!}
- ```
+//// tab | Python 3.10+
-=== "Python 3.9+"
+```Python hl_lines="155"
+{!> ../../../docs_src/security/tutorial005_an_py310.py!}
+```
- ```Python hl_lines="155"
- {!> ../../../docs_src/security/tutorial005_an_py39.py!}
- ```
+////
-=== "Python 3.8+"
+//// tab | Python 3.9+
- ```Python hl_lines="156"
- {!> ../../../docs_src/security/tutorial005_an.py!}
- ```
+```Python hl_lines="155"
+{!> ../../../docs_src/security/tutorial005_an_py39.py!}
+```
-=== "Python 3.10+ nicht annotiert"
+////
- !!! tip "Tipp"
- Bevorzugen Sie die `Annotated`-Version, falls möglich.
+//// tab | Python 3.8+
- ```Python hl_lines="154"
- {!> ../../../docs_src/security/tutorial005_py310.py!}
- ```
+```Python hl_lines="156"
+{!> ../../../docs_src/security/tutorial005_an.py!}
+```
-=== "Python 3.9+ nicht annotiert"
+////
- !!! tip "Tipp"
- Bevorzugen Sie die `Annotated`-Version, falls möglich.
+//// tab | Python 3.10+ nicht annotiert
- ```Python hl_lines="155"
- {!> ../../../docs_src/security/tutorial005_py39.py!}
- ```
+/// tip | "Tipp"
-=== "Python 3.8+ nicht annotiert"
+Bevorzugen Sie die `Annotated`-Version, falls möglich.
- !!! tip "Tipp"
- Bevorzugen Sie die `Annotated`-Version, falls möglich.
+///
- ```Python hl_lines="155"
- {!> ../../../docs_src/security/tutorial005.py!}
- ```
+```Python hl_lines="154"
+{!> ../../../docs_src/security/tutorial005_py310.py!}
+```
+
+////
+
+//// tab | Python 3.9+ nicht annotiert
+
+/// tip | "Tipp"
+
+Bevorzugen Sie die `Annotated`-Version, falls möglich.
+
+///
+
+```Python hl_lines="155"
+{!> ../../../docs_src/security/tutorial005_py39.py!}
+```
+
+////
+
+//// tab | Python 3.8+ nicht annotiert
+
+/// tip | "Tipp"
+
+Bevorzugen Sie die `Annotated`-Version, falls möglich.
+
+///
+
+```Python hl_lines="155"
+{!> ../../../docs_src/security/tutorial005.py!}
+```
+
+////
## Scopes in *Pfadoperationen* und Abhängigkeiten deklarieren
In diesem Fall erfordert sie den Scope `me` (sie könnte mehr als einen Scope erfordern).
-!!! note "Hinweis"
- Sie müssen nicht unbedingt an verschiedenen Stellen verschiedene Scopes hinzufügen.
+/// note | "Hinweis"
+
+Sie müssen nicht unbedingt an verschiedenen Stellen verschiedene Scopes hinzufügen.
+
+Wir tun dies hier, um zu demonstrieren, wie **FastAPI** auf verschiedenen Ebenen deklarierte Scopes verarbeitet.
+
+///
+
+//// tab | Python 3.10+
+
+```Python hl_lines="4 139 170"
+{!> ../../../docs_src/security/tutorial005_an_py310.py!}
+```
+
+////
+
+//// tab | Python 3.9+
+
+```Python hl_lines="4 139 170"
+{!> ../../../docs_src/security/tutorial005_an_py39.py!}
+```
+
+////
+
+//// tab | Python 3.8+
+
+```Python hl_lines="4 140 171"
+{!> ../../../docs_src/security/tutorial005_an.py!}
+```
+
+////
+
+//// tab | Python 3.10+ nicht annotiert
+
+/// tip | "Tipp"
- Wir tun dies hier, um zu demonstrieren, wie **FastAPI** auf verschiedenen Ebenen deklarierte Scopes verarbeitet.
+Bevorzugen Sie die `Annotated`-Version, falls möglich.
-=== "Python 3.10+"
+///
- ```Python hl_lines="4 139 170"
- {!> ../../../docs_src/security/tutorial005_an_py310.py!}
- ```
+```Python hl_lines="3 138 167"
+{!> ../../../docs_src/security/tutorial005_py310.py!}
+```
-=== "Python 3.9+"
+////
- ```Python hl_lines="4 139 170"
- {!> ../../../docs_src/security/tutorial005_an_py39.py!}
- ```
+//// tab | Python 3.9+ nicht annotiert
-=== "Python 3.8+"
+/// tip | "Tipp"
- ```Python hl_lines="4 140 171"
- {!> ../../../docs_src/security/tutorial005_an.py!}
- ```
+Bevorzugen Sie die `Annotated`-Version, falls möglich.
-=== "Python 3.10+ nicht annotiert"
+///
- !!! tip "Tipp"
- Bevorzugen Sie die `Annotated`-Version, falls möglich.
+```Python hl_lines="4 139 168"
+{!> ../../../docs_src/security/tutorial005_py39.py!}
+```
- ```Python hl_lines="3 138 167"
- {!> ../../../docs_src/security/tutorial005_py310.py!}
- ```
+////
-=== "Python 3.9+ nicht annotiert"
+//// tab | Python 3.8+ nicht annotiert
- !!! tip "Tipp"
- Bevorzugen Sie die `Annotated`-Version, falls möglich.
+/// tip | "Tipp"
- ```Python hl_lines="4 139 168"
- {!> ../../../docs_src/security/tutorial005_py39.py!}
- ```
+Bevorzugen Sie die `Annotated`-Version, falls möglich.
-=== "Python 3.8+ nicht annotiert"
+///
- !!! tip "Tipp"
- Bevorzugen Sie die `Annotated`-Version, falls möglich.
+```Python hl_lines="4 139 168"
+{!> ../../../docs_src/security/tutorial005.py!}
+```
- ```Python hl_lines="4 139 168"
- {!> ../../../docs_src/security/tutorial005.py!}
- ```
+////
-!!! info "Technische Details"
- `Security` ist tatsächlich eine Unterklasse von `Depends` und hat nur noch einen zusätzlichen Parameter, den wir später kennenlernen werden.
+/// info | "Technische Details"
- Durch die Verwendung von `Security` anstelle von `Depends` weiß **FastAPI** jedoch, dass es Sicherheits-Scopes deklarieren, intern verwenden und die API mit OpenAPI dokumentieren kann.
+`Security` ist tatsächlich eine Unterklasse von `Depends` und hat nur noch einen zusätzlichen Parameter, den wir später kennenlernen werden.
- Wenn Sie jedoch `Query`, `Path`, `Depends`, `Security` und andere von `fastapi` importieren, handelt es sich tatsächlich um Funktionen, die spezielle Klassen zurückgeben.
+Durch die Verwendung von `Security` anstelle von `Depends` weiß **FastAPI** jedoch, dass es Sicherheits-Scopes deklarieren, intern verwenden und die API mit OpenAPI dokumentieren kann.
+
+Wenn Sie jedoch `Query`, `Path`, `Depends`, `Security` und andere von `fastapi` importieren, handelt es sich tatsächlich um Funktionen, die spezielle Klassen zurückgeben.
+
+///
## `SecurityScopes` verwenden
Diese `SecurityScopes`-Klasse ähnelt `Request` (`Request` wurde verwendet, um das Request-Objekt direkt zu erhalten).
-=== "Python 3.10+"
+//// tab | Python 3.10+
+
+```Python hl_lines="8 105"
+{!> ../../../docs_src/security/tutorial005_an_py310.py!}
+```
+
+////
+
+//// tab | Python 3.9+
+
+```Python hl_lines="8 105"
+{!> ../../../docs_src/security/tutorial005_an_py39.py!}
+```
+
+////
+
+//// tab | Python 3.8+
+
+```Python hl_lines="8 106"
+{!> ../../../docs_src/security/tutorial005_an.py!}
+```
+
+////
+
+//// tab | Python 3.10+ nicht annotiert
+
+/// tip | "Tipp"
+
+Bevorzugen Sie die `Annotated`-Version, falls möglich.
+
+///
- ```Python hl_lines="8 105"
- {!> ../../../docs_src/security/tutorial005_an_py310.py!}
- ```
+```Python hl_lines="7 104"
+{!> ../../../docs_src/security/tutorial005_py310.py!}
+```
-=== "Python 3.9+"
+////
- ```Python hl_lines="8 105"
- {!> ../../../docs_src/security/tutorial005_an_py39.py!}
- ```
+//// tab | Python 3.9+ nicht annotiert
-=== "Python 3.8+"
+/// tip | "Tipp"
- ```Python hl_lines="8 106"
- {!> ../../../docs_src/security/tutorial005_an.py!}
- ```
+Bevorzugen Sie die `Annotated`-Version, falls möglich.
-=== "Python 3.10+ nicht annotiert"
+///
- !!! tip "Tipp"
- Bevorzugen Sie die `Annotated`-Version, falls möglich.
+```Python hl_lines="8 105"
+{!> ../../../docs_src/security/tutorial005_py39.py!}
+```
- ```Python hl_lines="7 104"
- {!> ../../../docs_src/security/tutorial005_py310.py!}
- ```
+////
-=== "Python 3.9+ nicht annotiert"
+//// tab | Python 3.8+ nicht annotiert
- !!! tip "Tipp"
- Bevorzugen Sie die `Annotated`-Version, falls möglich.
+/// tip | "Tipp"
- ```Python hl_lines="8 105"
- {!> ../../../docs_src/security/tutorial005_py39.py!}
- ```
+Bevorzugen Sie die `Annotated`-Version, falls möglich.
-=== "Python 3.8+ nicht annotiert"
+///
- !!! tip "Tipp"
- Bevorzugen Sie die `Annotated`-Version, falls möglich.
+```Python hl_lines="8 105"
+{!> ../../../docs_src/security/tutorial005.py!}
+```
- ```Python hl_lines="8 105"
- {!> ../../../docs_src/security/tutorial005.py!}
- ```
+////
## Die `scopes` verwenden
In diese Exception fügen wir (falls vorhanden) die erforderlichen Scopes als durch Leerzeichen getrennten String ein (unter Verwendung von `scope_str`). Wir fügen diesen String mit den Scopes in den Header `WWW-Authenticate` ein (das ist Teil der Spezifikation).
-=== "Python 3.10+"
+//// tab | Python 3.10+
- ```Python hl_lines="105 107-115"
- {!> ../../../docs_src/security/tutorial005_an_py310.py!}
- ```
+```Python hl_lines="105 107-115"
+{!> ../../../docs_src/security/tutorial005_an_py310.py!}
+```
-=== "Python 3.9+"
+////
- ```Python hl_lines="105 107-115"
- {!> ../../../docs_src/security/tutorial005_an_py39.py!}
- ```
+//// tab | Python 3.9+
-=== "Python 3.8+"
+```Python hl_lines="105 107-115"
+{!> ../../../docs_src/security/tutorial005_an_py39.py!}
+```
- ```Python hl_lines="106 108-116"
- {!> ../../../docs_src/security/tutorial005_an.py!}
- ```
+////
-=== "Python 3.10+ nicht annotiert"
+//// tab | Python 3.8+
- !!! tip "Tipp"
- Bevorzugen Sie die `Annotated`-Version, falls möglich.
+```Python hl_lines="106 108-116"
+{!> ../../../docs_src/security/tutorial005_an.py!}
+```
- ```Python hl_lines="104 106-114"
- {!> ../../../docs_src/security/tutorial005_py310.py!}
- ```
+////
-=== "Python 3.9+ nicht annotiert"
+//// tab | Python 3.10+ nicht annotiert
- !!! tip "Tipp"
- Bevorzugen Sie die `Annotated`-Version, falls möglich.
+/// tip | "Tipp"
- ```Python hl_lines="105 107-115"
- {!> ../../../docs_src/security/tutorial005_py39.py!}
- ```
+Bevorzugen Sie die `Annotated`-Version, falls möglich.
-=== "Python 3.8+ nicht annotiert"
+///
- !!! tip "Tipp"
- Bevorzugen Sie die `Annotated`-Version, falls möglich.
+```Python hl_lines="104 106-114"
+{!> ../../../docs_src/security/tutorial005_py310.py!}
+```
- ```Python hl_lines="105 107-115"
- {!> ../../../docs_src/security/tutorial005.py!}
- ```
+////
+
+//// tab | Python 3.9+ nicht annotiert
+
+/// tip | "Tipp"
+
+Bevorzugen Sie die `Annotated`-Version, falls möglich.
+
+///
+
+```Python hl_lines="105 107-115"
+{!> ../../../docs_src/security/tutorial005_py39.py!}
+```
+
+////
+
+//// tab | Python 3.8+ nicht annotiert
+
+/// tip | "Tipp"
+
+Bevorzugen Sie die `Annotated`-Version, falls möglich.
+
+///
+
+```Python hl_lines="105 107-115"
+{!> ../../../docs_src/security/tutorial005.py!}
+```
+
+////
## Den `username` und das Format der Daten überprüfen
Wir verifizieren auch, dass wir einen Benutzer mit diesem Benutzernamen haben, und wenn nicht, lösen wir dieselbe Exception aus, die wir zuvor erstellt haben.
-=== "Python 3.10+"
+//// tab | Python 3.10+
+
+```Python hl_lines="46 116-127"
+{!> ../../../docs_src/security/tutorial005_an_py310.py!}
+```
- ```Python hl_lines="46 116-127"
- {!> ../../../docs_src/security/tutorial005_an_py310.py!}
- ```
+////
-=== "Python 3.9+"
+//// tab | Python 3.9+
- ```Python hl_lines="46 116-127"
- {!> ../../../docs_src/security/tutorial005_an_py39.py!}
- ```
+```Python hl_lines="46 116-127"
+{!> ../../../docs_src/security/tutorial005_an_py39.py!}
+```
-=== "Python 3.8+"
+////
- ```Python hl_lines="47 117-128"
- {!> ../../../docs_src/security/tutorial005_an.py!}
- ```
+//// tab | Python 3.8+
-=== "Python 3.10+ nicht annotiert"
+```Python hl_lines="47 117-128"
+{!> ../../../docs_src/security/tutorial005_an.py!}
+```
- !!! tip "Tipp"
- Bevorzugen Sie die `Annotated`-Version, falls möglich.
+////
- ```Python hl_lines="45 115-126"
- {!> ../../../docs_src/security/tutorial005_py310.py!}
- ```
+//// tab | Python 3.10+ nicht annotiert
-=== "Python 3.9+ nicht annotiert"
+/// tip | "Tipp"
- !!! tip "Tipp"
- Bevorzugen Sie die `Annotated`-Version, falls möglich.
+Bevorzugen Sie die `Annotated`-Version, falls möglich.
- ```Python hl_lines="46 116-127"
- {!> ../../../docs_src/security/tutorial005_py39.py!}
- ```
+///
-=== "Python 3.8+ nicht annotiert"
+```Python hl_lines="45 115-126"
+{!> ../../../docs_src/security/tutorial005_py310.py!}
+```
- !!! tip "Tipp"
- Bevorzugen Sie die `Annotated`-Version, falls möglich.
+////
- ```Python hl_lines="46 116-127"
- {!> ../../../docs_src/security/tutorial005.py!}
- ```
+//// tab | Python 3.9+ nicht annotiert
+
+/// tip | "Tipp"
+
+Bevorzugen Sie die `Annotated`-Version, falls möglich.
+
+///
+
+```Python hl_lines="46 116-127"
+{!> ../../../docs_src/security/tutorial005_py39.py!}
+```
+
+////
+
+//// tab | Python 3.8+ nicht annotiert
+
+/// tip | "Tipp"
+
+Bevorzugen Sie die `Annotated`-Version, falls möglich.
+
+///
+
+```Python hl_lines="46 116-127"
+{!> ../../../docs_src/security/tutorial005.py!}
+```
+
+////
## Die `scopes` verifizieren
Hierzu verwenden wir `security_scopes.scopes`, das eine `list`e mit allen diesen Scopes als `str` enthält.
-=== "Python 3.10+"
+//// tab | Python 3.10+
+
+```Python hl_lines="128-134"
+{!> ../../../docs_src/security/tutorial005_an_py310.py!}
+```
+
+////
+
+//// tab | Python 3.9+
- ```Python hl_lines="128-134"
- {!> ../../../docs_src/security/tutorial005_an_py310.py!}
- ```
+```Python hl_lines="128-134"
+{!> ../../../docs_src/security/tutorial005_an_py39.py!}
+```
-=== "Python 3.9+"
+////
- ```Python hl_lines="128-134"
- {!> ../../../docs_src/security/tutorial005_an_py39.py!}
- ```
+//// tab | Python 3.8+
-=== "Python 3.8+"
+```Python hl_lines="129-135"
+{!> ../../../docs_src/security/tutorial005_an.py!}
+```
- ```Python hl_lines="129-135"
- {!> ../../../docs_src/security/tutorial005_an.py!}
- ```
+////
-=== "Python 3.10+ nicht annotiert"
+//// tab | Python 3.10+ nicht annotiert
- !!! tip "Tipp"
- Bevorzugen Sie die `Annotated`-Version, falls möglich.
+/// tip | "Tipp"
- ```Python hl_lines="127-133"
- {!> ../../../docs_src/security/tutorial005_py310.py!}
- ```
+Bevorzugen Sie die `Annotated`-Version, falls möglich.
-=== "Python 3.9+ nicht annotiert"
+///
- !!! tip "Tipp"
- Bevorzugen Sie die `Annotated`-Version, falls möglich.
+```Python hl_lines="127-133"
+{!> ../../../docs_src/security/tutorial005_py310.py!}
+```
- ```Python hl_lines="128-134"
- {!> ../../../docs_src/security/tutorial005_py39.py!}
- ```
+////
-=== "Python 3.8+ nicht annotiert"
+//// tab | Python 3.9+ nicht annotiert
- !!! tip "Tipp"
- Bevorzugen Sie die `Annotated`-Version, falls möglich.
+/// tip | "Tipp"
- ```Python hl_lines="128-134"
- {!> ../../../docs_src/security/tutorial005.py!}
- ```
+Bevorzugen Sie die `Annotated`-Version, falls möglich.
+
+///
+
+```Python hl_lines="128-134"
+{!> ../../../docs_src/security/tutorial005_py39.py!}
+```
+
+////
+
+//// tab | Python 3.8+ nicht annotiert
+
+/// tip | "Tipp"
+
+Bevorzugen Sie die `Annotated`-Version, falls möglich.
+
+///
+
+```Python hl_lines="128-134"
+{!> ../../../docs_src/security/tutorial005.py!}
+```
+
+////
## Abhängigkeitsbaum und Scopes
* `security_scopes.scopes` enthält `["me"]` für die *Pfadoperation* `read_users_me`, da das in der Abhängigkeit `get_current_active_user` deklariert ist.
* `security_scopes.scopes` wird `[]` (nichts) für die *Pfadoperation* `read_system_status` enthalten, da diese keine `Security` mit `scopes` deklariert hat, und deren Abhängigkeit `get_current_user` ebenfalls keinerlei `scopes` deklariert.
-!!! tip "Tipp"
- Das Wichtige und „Magische“ hier ist, dass `get_current_user` für jede *Pfadoperation* eine andere Liste von `scopes` hat, die überprüft werden.
+/// tip | "Tipp"
+
+Das Wichtige und „Magische“ hier ist, dass `get_current_user` für jede *Pfadoperation* eine andere Liste von `scopes` hat, die überprüft werden.
- Alles hängt von den „Scopes“ ab, die in jeder *Pfadoperation* und jeder Abhängigkeit im Abhängigkeitsbaum für diese bestimmte *Pfadoperation* deklariert wurden.
+Alles hängt von den „Scopes“ ab, die in jeder *Pfadoperation* und jeder Abhängigkeit im Abhängigkeitsbaum für diese bestimmte *Pfadoperation* deklariert wurden.
+
+///
## Weitere Details zu `SecurityScopes`.
Am sichersten ist der „Code“-Flow, die Implementierung ist jedoch komplexer, da mehr Schritte erforderlich sind. Da er komplexer ist, schlagen viele Anbieter letztendlich den „Implicit“-Flow vor.
-!!! note "Hinweis"
- Es ist üblich, dass jeder Authentifizierungsanbieter seine Flows anders benennt, um sie zu einem Teil seiner Marke zu machen.
+/// note | "Hinweis"
+
+Es ist üblich, dass jeder Authentifizierungsanbieter seine Flows anders benennt, um sie zu einem Teil seiner Marke zu machen.
+
+Aber am Ende implementieren sie denselben OAuth2-Standard.
- Aber am Ende implementieren sie denselben OAuth2-Standard.
+///
**FastAPI** enthält Werkzeuge für alle diese OAuth2-Authentifizierungs-Flows in `fastapi.security.oauth2`.
## Umgebungsvariablen
-!!! tip "Tipp"
- Wenn Sie bereits wissen, was „Umgebungsvariablen“ sind und wie man sie verwendet, können Sie gerne mit dem nächsten Abschnitt weiter unten fortfahren.
+/// tip | "Tipp"
+
+Wenn Sie bereits wissen, was „Umgebungsvariablen“ sind und wie man sie verwendet, können Sie gerne mit dem nächsten Abschnitt weiter unten fortfahren.
+
+///
Eine <a href="https://de.wikipedia.org/wiki/Umgebungsvariable" class="external-link" target="_blank">Umgebungsvariable</a> (auch bekannt als „env var“) ist eine Variable, die sich außerhalb des Python-Codes im Betriebssystem befindet und von Ihrem Python-Code (oder auch von anderen Programmen) gelesen werden kann.
Sie können Umgebungsvariablen in der Shell erstellen und verwenden, ohne Python zu benötigen:
-=== "Linux, macOS, Windows Bash"
+//// tab | Linux, macOS, Windows Bash
- <div class="termy">
+<div class="termy">
- ```console
- // Sie könnten eine Umgebungsvariable MY_NAME erstellen mittels
- $ export MY_NAME="Wade Wilson"
+```console
+// Sie könnten eine Umgebungsvariable MY_NAME erstellen mittels
+$ export MY_NAME="Wade Wilson"
- // Dann könnten Sie diese mit anderen Programmen verwenden, etwa
- $ echo "Hello $MY_NAME"
+// Dann könnten Sie diese mit anderen Programmen verwenden, etwa
+$ echo "Hello $MY_NAME"
+
+Hello Wade Wilson
+```
+
+</div>
- Hello Wade Wilson
- ```
+////
- </div>
+//// tab | Windows PowerShell
-=== "Windows PowerShell"
+<div class="termy">
- <div class="termy">
+```console
+// Erstelle eine Umgebungsvariable MY_NAME
+$ $Env:MY_NAME = "Wade Wilson"
- ```console
- // Erstelle eine Umgebungsvariable MY_NAME
- $ $Env:MY_NAME = "Wade Wilson"
+// Verwende sie mit anderen Programmen, etwa
+$ echo "Hello $Env:MY_NAME"
- // Verwende sie mit anderen Programmen, etwa
- $ echo "Hello $Env:MY_NAME"
+Hello Wade Wilson
+```
- Hello Wade Wilson
- ```
+</div>
- </div>
+////
### Umgebungsvariablen mit Python auslesen
print(f"Hello {name} from Python")
```
-!!! tip "Tipp"
- Das zweite Argument für <a href="https://docs.python.org/3.8/library/os.html#os.getenv" class="external-link" target="_blank">`os.getenv()`</a> ist der zurückzugebende Defaultwert.
+/// tip | "Tipp"
+
+Das zweite Argument für <a href="https://docs.python.org/3.8/library/os.html#os.getenv" class="external-link" target="_blank">`os.getenv()`</a> ist der zurückzugebende Defaultwert.
- Wenn nicht angegeben, ist er standardmäßig `None`. Hier übergeben wir `"World"` als Defaultwert.
+Wenn nicht angegeben, ist er standardmäßig `None`. Hier übergeben wir `"World"` als Defaultwert.
+
+///
Dann könnten Sie dieses Python-Programm aufrufen:
</div>
-!!! tip "Tipp"
- Weitere Informationen dazu finden Sie unter <a href="https://12factor.net/config" class="external-link" target="_blank">The Twelve-Factor App: Config</a>.
+/// tip | "Tipp"
+
+Weitere Informationen dazu finden Sie unter <a href="https://12factor.net/config" class="external-link" target="_blank">The Twelve-Factor App: Config</a>.
+
+///
### Typen und Validierung
</div>
-!!! info
- In Pydantic v1 war das im Hauptpackage enthalten. Jetzt wird es als unabhängiges Package verteilt, sodass Sie wählen können, ob Sie es installieren möchten oder nicht, falls Sie die Funktionalität nicht benötigen.
+/// info
+
+In Pydantic v1 war das im Hauptpackage enthalten. Jetzt wird es als unabhängiges Package verteilt, sodass Sie wählen können, ob Sie es installieren möchten oder nicht, falls Sie die Funktionalität nicht benötigen.
+
+///
### Das `Settings`-Objekt erstellen
Sie können dieselben Validierungs-Funktionen und -Tools verwenden, die Sie für Pydantic-Modelle verwenden, z. B. verschiedene Datentypen und zusätzliche Validierungen mit `Field()`.
-=== "Pydantic v2"
+//// tab | Pydantic v2
+
+```Python hl_lines="2 5-8 11"
+{!> ../../../docs_src/settings/tutorial001.py!}
+```
+
+////
+
+//// tab | Pydantic v1
- ```Python hl_lines="2 5-8 11"
- {!> ../../../docs_src/settings/tutorial001.py!}
- ```
+/// info
+
+In Pydantic v1 würden Sie `BaseSettings` direkt von `pydantic` statt von `pydantic_settings` importieren.
+
+///
+
+```Python hl_lines="2 5-8 11"
+{!> ../../../docs_src/settings/tutorial001_pv1.py!}
+```
-=== "Pydantic v1"
+////
- !!! info
- In Pydantic v1 würden Sie `BaseSettings` direkt von `pydantic` statt von `pydantic_settings` importieren.
+/// tip | "Tipp"
- ```Python hl_lines="2 5-8 11"
- {!> ../../../docs_src/settings/tutorial001_pv1.py!}
- ```
+Für ein schnelles Copy-and-paste verwenden Sie nicht dieses Beispiel, sondern das letzte unten.
-!!! tip "Tipp"
- Für ein schnelles Copy-and-paste verwenden Sie nicht dieses Beispiel, sondern das letzte unten.
+///
Wenn Sie dann eine Instanz dieser `Settings`-Klasse erstellen (in diesem Fall als `settings`-Objekt), liest Pydantic die Umgebungsvariablen ohne Berücksichtigung der Groß- und Kleinschreibung. Eine Variable `APP_NAME` in Großbuchstaben wird also als Attribut `app_name` gelesen.
</div>
-!!! tip "Tipp"
- Um mehrere Umgebungsvariablen für einen einzelnen Befehl festzulegen, trennen Sie diese einfach durch ein Leerzeichen und fügen Sie alle vor dem Befehl ein.
+/// tip | "Tipp"
+
+Um mehrere Umgebungsvariablen für einen einzelnen Befehl festzulegen, trennen Sie diese einfach durch ein Leerzeichen und fügen Sie alle vor dem Befehl ein.
+
+///
Und dann würde die Einstellung `admin_email` auf `"deadpool@example.com"` gesetzt.
{!../../../docs_src/settings/app01/main.py!}
```
-!!! tip "Tipp"
- Sie benötigen außerdem eine Datei `__init__.py`, wie in [Größere Anwendungen – mehrere Dateien](../tutorial/bigger-applications.md){.internal-link target=_blank} gesehen.
+/// tip | "Tipp"
+
+Sie benötigen außerdem eine Datei `__init__.py`, wie in [Größere Anwendungen – mehrere Dateien](../tutorial/bigger-applications.md){.internal-link target=_blank} gesehen.
+
+///
## Einstellungen in einer Abhängigkeit
Jetzt erstellen wir eine Abhängigkeit, die ein neues `config.Settings()` zurückgibt.
-=== "Python 3.9+"
+//// tab | Python 3.9+
- ```Python hl_lines="6 12-13"
- {!> ../../../docs_src/settings/app02_an_py39/main.py!}
- ```
+```Python hl_lines="6 12-13"
+{!> ../../../docs_src/settings/app02_an_py39/main.py!}
+```
-=== "Python 3.8+"
+////
- ```Python hl_lines="6 12-13"
- {!> ../../../docs_src/settings/app02_an/main.py!}
- ```
+//// tab | Python 3.8+
-=== "Python 3.8+ nicht annotiert"
+```Python hl_lines="6 12-13"
+{!> ../../../docs_src/settings/app02_an/main.py!}
+```
+
+////
- !!! tip "Tipp"
- Bevorzugen Sie die `Annotated`-Version, falls möglich.
+//// tab | Python 3.8+ nicht annotiert
- ```Python hl_lines="5 11-12"
- {!> ../../../docs_src/settings/app02/main.py!}
- ```
+/// tip | "Tipp"
-!!! tip "Tipp"
- Wir werden das `@lru_cache` in Kürze besprechen.
+Bevorzugen Sie die `Annotated`-Version, falls möglich.
- Im Moment nehmen Sie an, dass `get_settings()` eine normale Funktion ist.
+///
+
+```Python hl_lines="5 11-12"
+{!> ../../../docs_src/settings/app02/main.py!}
+```
+
+////
+
+/// tip | "Tipp"
+
+Wir werden das `@lru_cache` in Kürze besprechen.
+
+Im Moment nehmen Sie an, dass `get_settings()` eine normale Funktion ist.
+
+///
Und dann können wir das von der *Pfadoperation-Funktion* als Abhängigkeit einfordern und es überall dort verwenden, wo wir es brauchen.
-=== "Python 3.9+"
+//// tab | Python 3.9+
+
+```Python hl_lines="17 19-21"
+{!> ../../../docs_src/settings/app02_an_py39/main.py!}
+```
+
+////
+
+//// tab | Python 3.8+
- ```Python hl_lines="17 19-21"
- {!> ../../../docs_src/settings/app02_an_py39/main.py!}
- ```
+```Python hl_lines="17 19-21"
+{!> ../../../docs_src/settings/app02_an/main.py!}
+```
+
+////
-=== "Python 3.8+"
+//// tab | Python 3.8+ nicht annotiert
- ```Python hl_lines="17 19-21"
- {!> ../../../docs_src/settings/app02_an/main.py!}
- ```
+/// tip | "Tipp"
-=== "Python 3.8+ nicht annotiert"
+Bevorzugen Sie die `Annotated`-Version, falls möglich.
- !!! tip "Tipp"
- Bevorzugen Sie die `Annotated`-Version, falls möglich.
+///
- ```Python hl_lines="16 18-20"
- {!> ../../../docs_src/settings/app02/main.py!}
- ```
+```Python hl_lines="16 18-20"
+{!> ../../../docs_src/settings/app02/main.py!}
+```
+
+////
### Einstellungen und Tests
Diese Praxis ist so weit verbreitet, dass sie einen Namen hat. Diese Umgebungsvariablen werden üblicherweise in einer Datei `.env` abgelegt und die Datei wird „dotenv“ genannt.
-!!! tip "Tipp"
- Eine Datei, die mit einem Punkt (`.`) beginnt, ist eine versteckte Datei in Unix-ähnlichen Systemen wie Linux und macOS.
+/// tip | "Tipp"
+
+Eine Datei, die mit einem Punkt (`.`) beginnt, ist eine versteckte Datei in Unix-ähnlichen Systemen wie Linux und macOS.
- Aber eine dotenv-Datei muss nicht unbedingt genau diesen Dateinamen haben.
+Aber eine dotenv-Datei muss nicht unbedingt genau diesen Dateinamen haben.
+
+///
Pydantic unterstützt das Lesen dieser Dateitypen mithilfe einer externen Bibliothek. Weitere Informationen finden Sie unter <a href="https://docs.pydantic.dev/latest/concepts/pydantic_settings/#dotenv-env-support" class="external-link" target="_blank">Pydantic Settings: Dotenv (.env) support</a>.
-!!! tip "Tipp"
- Damit das funktioniert, müssen Sie `pip install python-dotenv` ausführen.
+/// tip | "Tipp"
+
+Damit das funktioniert, müssen Sie `pip install python-dotenv` ausführen.
+
+///
### Die `.env`-Datei
Und dann aktualisieren Sie Ihre `config.py` mit:
-=== "Pydantic v2"
+//// tab | Pydantic v2
- ```Python hl_lines="9"
- {!> ../../../docs_src/settings/app03_an/config.py!}
- ```
+```Python hl_lines="9"
+{!> ../../../docs_src/settings/app03_an/config.py!}
+```
- !!! tip "Tipp"
- Das Attribut `model_config` wird nur für die Pydantic-Konfiguration verwendet. Weitere Informationen finden Sie unter <a href="https://docs.pydantic.dev/latest/concepts/config/" class="external-link" target="_blank">Pydantic: Configuration</a>.
+/// tip | "Tipp"
-=== "Pydantic v1"
+Das Attribut `model_config` wird nur für die Pydantic-Konfiguration verwendet. Weitere Informationen finden Sie unter <a href="https://docs.pydantic.dev/latest/concepts/config/" class="external-link" target="_blank">Pydantic: Configuration</a>.
- ```Python hl_lines="9-10"
- {!> ../../../docs_src/settings/app03_an/config_pv1.py!}
- ```
+///
- !!! tip "Tipp"
- Die Klasse `Config` wird nur für die Pydantic-Konfiguration verwendet. Weitere Informationen finden Sie unter <a href="https://docs.pydantic.dev/1.10/usage/model_config/" class="external-link" target="_blank">Pydantic Model Config</a>.
+////
-!!! info
- In Pydantic Version 1 erfolgte die Konfiguration in einer internen Klasse `Config`, in Pydantic Version 2 erfolgt sie in einem Attribut `model_config`. Dieses Attribut akzeptiert ein `dict`. Um automatische Codevervollständigung und Inline-Fehlerberichte zu erhalten, können Sie `SettingsConfigDict` importieren und verwenden, um dieses `dict` zu definieren.
+//// tab | Pydantic v1
+
+```Python hl_lines="9-10"
+{!> ../../../docs_src/settings/app03_an/config_pv1.py!}
+```
+
+/// tip | "Tipp"
+
+Die Klasse `Config` wird nur für die Pydantic-Konfiguration verwendet. Weitere Informationen finden Sie unter <a href="https://docs.pydantic.dev/1.10/usage/model_config/" class="external-link" target="_blank">Pydantic Model Config</a>.
+
+///
+
+////
+
+/// info
+
+In Pydantic Version 1 erfolgte die Konfiguration in einer internen Klasse `Config`, in Pydantic Version 2 erfolgt sie in einem Attribut `model_config`. Dieses Attribut akzeptiert ein `dict`. Um automatische Codevervollständigung und Inline-Fehlerberichte zu erhalten, können Sie `SettingsConfigDict` importieren und verwenden, um dieses `dict` zu definieren.
+
+///
Hier definieren wir die Konfiguration `env_file` innerhalb Ihrer Pydantic-`Settings`-Klasse und setzen den Wert auf den Dateinamen mit der dotenv-Datei, die wir verwenden möchten.
Da wir jedoch den `@lru_cache`-Dekorator oben verwenden, wird das `Settings`-Objekt nur einmal erstellt, nämlich beim ersten Aufruf. ✔️
-=== "Python 3.9+"
+//// tab | Python 3.9+
- ```Python hl_lines="1 11"
- {!> ../../../docs_src/settings/app03_an_py39/main.py!}
- ```
+```Python hl_lines="1 11"
+{!> ../../../docs_src/settings/app03_an_py39/main.py!}
+```
+
+////
+
+//// tab | Python 3.8+
+
+```Python hl_lines="1 11"
+{!> ../../../docs_src/settings/app03_an/main.py!}
+```
+
+////
-=== "Python 3.8+"
+//// tab | Python 3.8+ nicht annotiert
- ```Python hl_lines="1 11"
- {!> ../../../docs_src/settings/app03_an/main.py!}
- ```
+/// tip | "Tipp"
-=== "Python 3.8+ nicht annotiert"
+Bevorzugen Sie die `Annotated`-Version, falls möglich.
- !!! tip "Tipp"
- Bevorzugen Sie die `Annotated`-Version, falls möglich.
+///
+
+```Python hl_lines="1 10"
+{!> ../../../docs_src/settings/app03/main.py!}
+```
- ```Python hl_lines="1 10"
- {!> ../../../docs_src/settings/app03/main.py!}
- ```
+////
Dann wird bei allen nachfolgenden Aufrufen von `get_settings()`, in den Abhängigkeiten für darauffolgende Requests, dasselbe Objekt zurückgegeben, das beim ersten Aufruf zurückgegeben wurde, anstatt den Code von `get_settings()` erneut auszuführen und ein neues `Settings`-Objekt zu erstellen.
{!../../../docs_src/templates/tutorial001.py!}
```
-!!! note "Hinweis"
- Vor FastAPI 0.108.0 und Starlette 0.29.0 war `name` der erste Parameter.
+/// note | "Hinweis"
- Außerdem wurde in früheren Versionen das `request`-Objekt als Teil der Schlüssel-Wert-Paare im Kontext für Jinja2 übergeben.
+Vor FastAPI 0.108.0 und Starlette 0.29.0 war `name` der erste Parameter.
-!!! tip "Tipp"
- Durch die Deklaration von `response_class=HTMLResponse` kann die Dokumentationsoberfläche erkennen, dass die Response HTML sein wird.
+Außerdem wurde in früheren Versionen das `request`-Objekt als Teil der Schlüssel-Wert-Paare im Kontext für Jinja2 übergeben.
-!!! note "Technische Details"
- Sie können auch `from starlette.templating import Jinja2Templates` verwenden.
+///
- **FastAPI** bietet dasselbe `starlette.templating` auch via `fastapi.templating` an, als Annehmlichkeit für Sie, den Entwickler. Es kommt aber direkt von Starlette. Das Gleiche gilt für `Request` und `StaticFiles`.
+/// tip | "Tipp"
+
+Durch die Deklaration von `response_class=HTMLResponse` kann die Dokumentationsoberfläche erkennen, dass die Response HTML sein wird.
+
+///
+
+/// note | "Technische Details"
+
+Sie können auch `from starlette.templating import Jinja2Templates` verwenden.
+
+**FastAPI** bietet dasselbe `starlette.templating` auch via `fastapi.templating` an, als Annehmlichkeit für Sie, den Entwickler. Es kommt aber direkt von Starlette. Das Gleiche gilt für `Request` und `StaticFiles`.
+
+///
## Templates erstellen
Und dann ruft **FastAPI** diese Überschreibung anstelle der ursprünglichen Abhängigkeit auf.
-=== "Python 3.10+"
+//// tab | Python 3.10+
- ```Python hl_lines="26-27 30"
- {!> ../../../docs_src/dependency_testing/tutorial001_an_py310.py!}
- ```
+```Python hl_lines="26-27 30"
+{!> ../../../docs_src/dependency_testing/tutorial001_an_py310.py!}
+```
+
+////
+
+//// tab | Python 3.9+
+
+```Python hl_lines="28-29 32"
+{!> ../../../docs_src/dependency_testing/tutorial001_an_py39.py!}
+```
+
+////
+
+//// tab | Python 3.8+
+
+```Python hl_lines="29-30 33"
+{!> ../../../docs_src/dependency_testing/tutorial001_an.py!}
+```
-=== "Python 3.9+"
+////
- ```Python hl_lines="28-29 32"
- {!> ../../../docs_src/dependency_testing/tutorial001_an_py39.py!}
- ```
+//// tab | Python 3.10+ nicht annotiert
-=== "Python 3.8+"
+/// tip | "Tipp"
- ```Python hl_lines="29-30 33"
- {!> ../../../docs_src/dependency_testing/tutorial001_an.py!}
- ```
+Bevorzugen Sie die `Annotated`-Version, falls möglich.
-=== "Python 3.10+ nicht annotiert"
+///
- !!! tip "Tipp"
- Bevorzugen Sie die `Annotated`-Version, falls möglich.
+```Python hl_lines="24-25 28"
+{!> ../../../docs_src/dependency_testing/tutorial001_py310.py!}
+```
+
+////
+
+//// tab | Python 3.8+ nicht annotiert
- ```Python hl_lines="24-25 28"
- {!> ../../../docs_src/dependency_testing/tutorial001_py310.py!}
- ```
+/// tip | "Tipp"
-=== "Python 3.8+ nicht annotiert"
+Bevorzugen Sie die `Annotated`-Version, falls möglich.
- !!! tip "Tipp"
- Bevorzugen Sie die `Annotated`-Version, falls möglich.
+///
+
+```Python hl_lines="28-29 32"
+{!> ../../../docs_src/dependency_testing/tutorial001.py!}
+```
- ```Python hl_lines="28-29 32"
- {!> ../../../docs_src/dependency_testing/tutorial001.py!}
- ```
+////
-!!! tip "Tipp"
- Sie können eine Überschreibung für eine Abhängigkeit festlegen, die an einer beliebigen Stelle in Ihrer **FastAPI**-Anwendung verwendet wird.
+/// tip | "Tipp"
- Die ursprüngliche Abhängigkeit könnte in einer *Pfadoperation-Funktion*, einem *Pfadoperation-Dekorator* (wenn Sie den Rückgabewert nicht verwenden), einem `.include_router()`-Aufruf, usw. verwendet werden.
+Sie können eine Überschreibung für eine Abhängigkeit festlegen, die an einer beliebigen Stelle in Ihrer **FastAPI**-Anwendung verwendet wird.
- FastAPI kann sie in jedem Fall überschreiben.
+Die ursprüngliche Abhängigkeit könnte in einer *Pfadoperation-Funktion*, einem *Pfadoperation-Dekorator* (wenn Sie den Rückgabewert nicht verwenden), einem `.include_router()`-Aufruf, usw. verwendet werden.
+
+FastAPI kann sie in jedem Fall überschreiben.
+
+///
Anschließend können Sie Ihre Überschreibungen zurücksetzen (entfernen), indem Sie `app.dependency_overrides` auf ein leeres `dict` setzen:
app.dependency_overrides = {}
```
-!!! tip "Tipp"
- Wenn Sie eine Abhängigkeit nur während einiger Tests überschreiben möchten, können Sie die Überschreibung zu Beginn des Tests (innerhalb der Testfunktion) festlegen und am Ende (am Ende der Testfunktion) zurücksetzen.
+/// tip | "Tipp"
+
+Wenn Sie eine Abhängigkeit nur während einiger Tests überschreiben möchten, können Sie die Überschreibung zu Beginn des Tests (innerhalb der Testfunktion) festlegen und am Ende (am Ende der Testfunktion) zurücksetzen.
+
+///
{!../../../docs_src/app_testing/tutorial002.py!}
```
-!!! note "Hinweis"
- Weitere Informationen finden Sie in der Starlette-Dokumentation zum <a href="https://www.starlette.io/testclient/#testing-websocket-sessions" class="external-link" target="_blank">Testen von WebSockets</a>.
+/// note | "Hinweis"
+
+Weitere Informationen finden Sie in der Starlette-Dokumentation zum <a href="https://www.starlette.io/testclient/#testing-websocket-sessions" class="external-link" target="_blank">Testen von WebSockets</a>.
+
+///
Durch die Deklaration eines *Pfadoperation-Funktionsparameters*, dessen Typ der `Request` ist, weiß **FastAPI**, dass es den `Request` diesem Parameter übergeben soll.
-!!! tip "Tipp"
- Beachten Sie, dass wir in diesem Fall einen Pfad-Parameter zusätzlich zum Request-Parameter deklarieren.
+/// tip | "Tipp"
- Der Pfad-Parameter wird also extrahiert, validiert, in den spezifizierten Typ konvertiert und mit OpenAPI annotiert.
+Beachten Sie, dass wir in diesem Fall einen Pfad-Parameter zusätzlich zum Request-Parameter deklarieren.
- Auf die gleiche Weise können Sie wie gewohnt jeden anderen Parameter deklarieren und zusätzlich auch den `Request` erhalten.
+Der Pfad-Parameter wird also extrahiert, validiert, in den spezifizierten Typ konvertiert und mit OpenAPI annotiert.
+
+Auf die gleiche Weise können Sie wie gewohnt jeden anderen Parameter deklarieren und zusätzlich auch den `Request` erhalten.
+
+///
## `Request`-Dokumentation
Weitere Details zum <a href="https://www.starlette.io/requests/" class="external-link" target="_blank">`Request`-Objekt finden Sie in der offiziellen Starlette-Dokumentation</a>.
-!!! note "Technische Details"
- Sie können auch `from starlette.requests import Request` verwenden.
+/// note | "Technische Details"
+
+Sie können auch `from starlette.requests import Request` verwenden.
+
+**FastAPI** stellt es direkt zur Verfügung, als Komfort für Sie, den Entwickler. Es kommt aber direkt von Starlette.
- **FastAPI** stellt es direkt zur Verfügung, als Komfort für Sie, den Entwickler. Es kommt aber direkt von Starlette.
+///
{!../../../docs_src/websockets/tutorial001.py!}
```
-!!! note "Technische Details"
- Sie können auch `from starlette.websockets import WebSocket` verwenden.
+/// note | "Technische Details"
- **FastAPI** stellt den gleichen `WebSocket` direkt zur Verfügung, als Annehmlichkeit für Sie, den Entwickler. Er kommt aber direkt von Starlette.
+Sie können auch `from starlette.websockets import WebSocket` verwenden.
+
+**FastAPI** stellt den gleichen `WebSocket` direkt zur Verfügung, als Annehmlichkeit für Sie, den Entwickler. Er kommt aber direkt von Starlette.
+
+///
## Nachrichten erwarten und Nachrichten senden
Diese funktionieren auf die gleiche Weise wie für andere FastAPI-Endpunkte/*Pfadoperationen*:
-=== "Python 3.10+"
+//// tab | Python 3.10+
+
+```Python hl_lines="68-69 82"
+{!> ../../../docs_src/websockets/tutorial002_an_py310.py!}
+```
+
+////
+
+//// tab | Python 3.9+
+
+```Python hl_lines="68-69 82"
+{!> ../../../docs_src/websockets/tutorial002_an_py39.py!}
+```
+
+////
+
+//// tab | Python 3.8+
+
+```Python hl_lines="69-70 83"
+{!> ../../../docs_src/websockets/tutorial002_an.py!}
+```
+
+////
- ```Python hl_lines="68-69 82"
- {!> ../../../docs_src/websockets/tutorial002_an_py310.py!}
- ```
+//// tab | Python 3.10+ nicht annotiert
-=== "Python 3.9+"
+/// tip | "Tipp"
- ```Python hl_lines="68-69 82"
- {!> ../../../docs_src/websockets/tutorial002_an_py39.py!}
- ```
+Bevorzugen Sie die `Annotated`-Version, falls möglich.
-=== "Python 3.8+"
+///
- ```Python hl_lines="69-70 83"
- {!> ../../../docs_src/websockets/tutorial002_an.py!}
- ```
+```Python hl_lines="66-67 79"
+{!> ../../../docs_src/websockets/tutorial002_py310.py!}
+```
+
+////
-=== "Python 3.10+ nicht annotiert"
+//// tab | Python 3.8+ nicht annotiert
- !!! tip "Tipp"
- Bevorzugen Sie die `Annotated`-Version, falls möglich.
+/// tip | "Tipp"
- ```Python hl_lines="66-67 79"
- {!> ../../../docs_src/websockets/tutorial002_py310.py!}
- ```
+Bevorzugen Sie die `Annotated`-Version, falls möglich.
-=== "Python 3.8+ nicht annotiert"
+///
+
+```Python hl_lines="68-69 81"
+{!> ../../../docs_src/websockets/tutorial002.py!}
+```
- !!! tip "Tipp"
- Bevorzugen Sie die `Annotated`-Version, falls möglich.
+////
- ```Python hl_lines="68-69 81"
- {!> ../../../docs_src/websockets/tutorial002.py!}
- ```
+/// info
-!!! info
- Da es sich um einen WebSocket handelt, macht es keinen Sinn, eine `HTTPException` auszulösen, stattdessen lösen wir eine `WebSocketException` aus.
+Da es sich um einen WebSocket handelt, macht es keinen Sinn, eine `HTTPException` auszulösen, stattdessen lösen wir eine `WebSocketException` aus.
- Sie können einen „Closing“-Code verwenden, aus den <a href="https://tools.ietf.org/html/rfc6455#section-7.4.1" class="external-link" target="_blank">gültigen Codes, die in der Spezifikation definiert sind</a>.
+Sie können einen „Closing“-Code verwenden, aus den <a href="https://tools.ietf.org/html/rfc6455#section-7.4.1" class="external-link" target="_blank">gültigen Codes, die in der Spezifikation definiert sind</a>.
+
+///
### WebSockets mit Abhängigkeiten ausprobieren
* Die „Item ID“, die im Pfad verwendet wird.
* Das „Token“, das als Query-Parameter verwendet wird.
-!!! tip "Tipp"
- Beachten Sie, dass der Query-„Token“ von einer Abhängigkeit verarbeitet wird.
+/// tip | "Tipp"
+
+Beachten Sie, dass der Query-„Token“ von einer Abhängigkeit verarbeitet wird.
+
+///
Damit können Sie den WebSocket verbinden und dann Nachrichten senden und empfangen:
Wenn eine WebSocket-Verbindung geschlossen wird, löst `await websocket.receive_text()` eine `WebSocketDisconnect`-Exception aus, die Sie dann wie in folgendem Beispiel abfangen und behandeln können.
-=== "Python 3.9+"
+//// tab | Python 3.9+
- ```Python hl_lines="79-81"
- {!> ../../../docs_src/websockets/tutorial003_py39.py!}
- ```
+```Python hl_lines="79-81"
+{!> ../../../docs_src/websockets/tutorial003_py39.py!}
+```
+
+////
+
+//// tab | Python 3.8+
-=== "Python 3.8+"
+```Python hl_lines="81-83"
+{!> ../../../docs_src/websockets/tutorial003.py!}
+```
- ```Python hl_lines="81-83"
- {!> ../../../docs_src/websockets/tutorial003.py!}
- ```
+////
Zum Ausprobieren:
Client #1596980209979 left the chat
```
-!!! tip "Tipp"
- Die obige Anwendung ist ein minimales und einfaches Beispiel, das zeigt, wie Nachrichten verarbeitet und an mehrere WebSocket-Verbindungen gesendet werden.
+/// tip | "Tipp"
+
+Die obige Anwendung ist ein minimales und einfaches Beispiel, das zeigt, wie Nachrichten verarbeitet und an mehrere WebSocket-Verbindungen gesendet werden.
+
+Beachten Sie jedoch, dass, da alles nur im Speicher in einer einzigen Liste verwaltet wird, es nur funktioniert, während der Prozess ausgeführt wird, und nur mit einem einzelnen Prozess.
- Beachten Sie jedoch, dass, da alles nur im Speicher in einer einzigen Liste verwaltet wird, es nur funktioniert, während der Prozess ausgeführt wird, und nur mit einem einzelnen Prozess.
+Wenn Sie etwas benötigen, das sich leicht in FastAPI integrieren lässt, aber robuster ist und von Redis, PostgreSQL und anderen unterstützt wird, sehen Sie sich <a href="https://github.com/encode/broadcaster" class="external-link" target="_blank">encode/broadcaster</a> an.
- Wenn Sie etwas benötigen, das sich leicht in FastAPI integrieren lässt, aber robuster ist und von Redis, PostgreSQL und anderen unterstützt wird, sehen Sie sich <a href="https://github.com/encode/broadcaster" class="external-link" target="_blank">encode/broadcaster</a> an.
+///
## Mehr Informationen
Es war eines der ersten Beispiele für **automatische API-Dokumentation**, und dies war insbesondere eine der ersten Ideen, welche „die Suche nach“ **FastAPI** inspirierten.
-!!! note "Hinweis"
- Das Django REST Framework wurde von Tom Christie erstellt. Derselbe Schöpfer von Starlette und Uvicorn, auf denen **FastAPI** basiert.
+/// note | "Hinweis"
+Das Django REST Framework wurde von Tom Christie erstellt. Derselbe Schöpfer von Starlette und Uvicorn, auf denen **FastAPI** basiert.
-!!! check "Inspirierte **FastAPI**"
- Eine automatische API-Dokumentationsoberfläche zu haben.
+///
+
+/// check | "Inspirierte **FastAPI**"
+
+Eine automatische API-Dokumentationsoberfläche zu haben.
+
+///
### <a href="https://flask.palletsprojects.com" class="external-link" target="_blank">Flask</a>
Angesichts der Einfachheit von Flask schien es eine gute Ergänzung zum Erstellen von APIs zu sein. Als Nächstes musste ein „Django REST Framework“ für Flask gefunden werden.
-!!! check "Inspirierte **FastAPI**"
- Ein Mikroframework zu sein. Es einfach zu machen, die benötigten Tools und Teile zu kombinieren.
+/// check | "Inspirierte **FastAPI**"
- Über ein einfaches und benutzerfreundliches Routingsystem zu verfügen.
+Ein Mikroframework zu sein. Es einfach zu machen, die benötigten Tools und Teile zu kombinieren.
+Über ein einfaches und benutzerfreundliches Routingsystem zu verfügen.
+
+///
### <a href="https://requests.readthedocs.io" class="external-link" target="_blank">Requests</a>
Sehen Sie sich die Ähnlichkeiten in `requests.get(...)` und `@app.get(...)` an.
-!!! check "Inspirierte **FastAPI**"
- * Über eine einfache und intuitive API zu verfügen.
- * HTTP-Methodennamen (Operationen) direkt, auf einfache und intuitive Weise zu verwenden.
- * Vernünftige Standardeinstellungen zu haben, aber auch mächtige Einstellungsmöglichkeiten.
+/// check | "Inspirierte **FastAPI**"
+
+* Über eine einfache und intuitive API zu verfügen.
+* HTTP-Methodennamen (Operationen) direkt, auf einfache und intuitive Weise zu verwenden.
+* Vernünftige Standardeinstellungen zu haben, aber auch mächtige Einstellungsmöglichkeiten.
+///
### <a href="https://swagger.io/" class="external-link" target="_blank">Swagger</a> / <a href="https://github.com/OAI/OpenAPI-Specification/" class="external-link" target="_blank">OpenAPI</a>
Aus diesem Grund spricht man bei Version 2.0 häufig von „Swagger“ und ab Version 3 von „OpenAPI“.
-!!! check "Inspirierte **FastAPI**"
- Einen offenen Standard für API-Spezifikationen zu übernehmen und zu verwenden, anstelle eines benutzerdefinierten Schemas.
+/// check | "Inspirierte **FastAPI**"
+
+Einen offenen Standard für API-Spezifikationen zu übernehmen und zu verwenden, anstelle eines benutzerdefinierten Schemas.
- Und Standard-basierte Tools für die Oberfläche zu integrieren:
+Und Standard-basierte Tools für die Oberfläche zu integrieren:
- * <a href="https://github.com/swagger-api/swagger-ui" class="external-link" target="_blank">Swagger UI</a>
- * <a href="https://github.com/Rebilly/ReDoc" class="external-link" target="_blank">ReDoc</a>
+* <a href="https://github.com/swagger-api/swagger-ui" class="external-link" target="_blank">Swagger UI</a>
+* <a href="https://github.com/Rebilly/ReDoc" class="external-link" target="_blank">ReDoc</a>
- Diese beiden wurden ausgewählt, weil sie ziemlich beliebt und stabil sind, aber bei einer schnellen Suche könnten Sie Dutzende alternativer Benutzeroberflächen für OpenAPI finden (welche Sie mit **FastAPI** verwenden können).
+Diese beiden wurden ausgewählt, weil sie ziemlich beliebt und stabil sind, aber bei einer schnellen Suche könnten Sie Dutzende alternativer Benutzeroberflächen für OpenAPI finden (welche Sie mit **FastAPI** verwenden können).
+
+///
### Flask REST Frameworks
Aber sie wurde erstellt, bevor Typhinweise in Python existierten. Um also ein <abbr title="die Definition, wie Daten geformt sein werden sollen">Schema</abbr> zu definieren, müssen Sie bestimmte Werkzeuge und Klassen verwenden, die von Marshmallow bereitgestellt werden.
-!!! check "Inspirierte **FastAPI**"
- Code zu verwenden, um „Schemas“ zu definieren, welche Datentypen und Validierung automatisch bereitstellen.
+/// check | "Inspirierte **FastAPI**"
+
+Code zu verwenden, um „Schemas“ zu definieren, welche Datentypen und Validierung automatisch bereitstellen.
+
+///
### <a href="https://webargs.readthedocs.io/en/latest/" class="external-link" target="_blank">Webargs</a>
Es ist ein großartiges Tool und ich habe es auch oft verwendet, bevor ich **FastAPI** hatte.
-!!! info
- Webargs wurde von denselben Marshmallow-Entwicklern erstellt.
+/// info
+
+Webargs wurde von denselben Marshmallow-Entwicklern erstellt.
+
+///
+
+/// check | "Inspirierte **FastAPI**"
-!!! check "Inspirierte **FastAPI**"
- Eingehende Requestdaten automatisch zu validieren.
+Eingehende Requestdaten automatisch zu validieren.
+
+///
### <a href="https://apispec.readthedocs.io/en/stable/" class="external-link" target="_blank">APISpec</a>
Der Texteditor kann dabei nicht viel helfen. Und wenn wir Parameter oder Marshmallow-Schemas ändern und vergessen, auch den YAML-Docstring zu ändern, wäre das generierte Schema veraltet.
-!!! info
- APISpec wurde von denselben Marshmallow-Entwicklern erstellt.
+/// info
+
+APISpec wurde von denselben Marshmallow-Entwicklern erstellt.
+
+///
+/// check | "Inspirierte **FastAPI**"
-!!! check "Inspirierte **FastAPI**"
- Den offenen Standard für APIs, OpenAPI, zu unterstützen.
+Den offenen Standard für APIs, OpenAPI, zu unterstützen.
+
+///
### <a href="https://flask-apispec.readthedocs.io/en/latest/" class="external-link" target="_blank">Flask-apispec</a>
Und dieselben Full-Stack-Generatoren bildeten die Basis der [**FastAPI**-Projektgeneratoren](project-generation.md){.internal-link target=_blank}.
-!!! info
- Flask-apispec wurde von denselben Marshmallow-Entwicklern erstellt.
+/// info
+
+Flask-apispec wurde von denselben Marshmallow-Entwicklern erstellt.
+
+///
-!!! check "Inspirierte **FastAPI**"
- Das OpenAPI-Schema automatisch zu generieren, aus demselben Code, welcher die Serialisierung und Validierung definiert.
+/// check | "Inspirierte **FastAPI**"
+
+Das OpenAPI-Schema automatisch zu generieren, aus demselben Code, welcher die Serialisierung und Validierung definiert.
+
+///
### <a href="https://nestjs.com/" class="external-link" target="_blank">NestJS</a> (und <a href="https://angular.io/" class="external-link" target="_blank">Angular</a>)
Es kann nicht sehr gut mit verschachtelten Modellen umgehen. Wenn es sich beim JSON-Body in der Anfrage also um ein JSON-Objekt mit inneren Feldern handelt, die wiederum verschachtelte JSON-Objekte sind, kann er nicht richtig dokumentiert und validiert werden.
-!!! check "Inspirierte **FastAPI**"
- Python-Typen zu verwenden, um eine hervorragende Editorunterstützung zu erhalten.
+/// check | "Inspirierte **FastAPI**"
+
+Python-Typen zu verwenden, um eine hervorragende Editorunterstützung zu erhalten.
- Über ein leistungsstarkes Dependency Injection System zu verfügen. Eine Möglichkeit zu finden, Codeverdoppelung zu minimieren.
+Über ein leistungsstarkes Dependency Injection System zu verfügen. Eine Möglichkeit zu finden, Codeverdoppelung zu minimieren.
+
+///
### <a href="https://sanic.readthedocs.io/en/latest/" class="external-link" target="_blank">Sanic</a>
Es war eines der ersten extrem schnellen Python-Frameworks, welches auf `asyncio` basierte. Es wurde so gestaltet, dass es Flask sehr ähnlich ist.
-!!! note "Technische Details"
- Es verwendete <a href="https://github.com/MagicStack/uvloop" class="external-link" target="_blank">`uvloop`</a> anstelle der standardmäßigen Python-`asyncio`-Schleife. Das hat es so schnell gemacht.
+/// note | "Technische Details"
+
+Es verwendete <a href="https://github.com/MagicStack/uvloop" class="external-link" target="_blank">`uvloop`</a> anstelle der standardmäßigen Python-`asyncio`-Schleife. Das hat es so schnell gemacht.
- Hat eindeutig Uvicorn und Starlette inspiriert, welche derzeit in offenen Benchmarks schneller als Sanic sind.
+Hat eindeutig Uvicorn und Starlette inspiriert, welche derzeit in offenen Benchmarks schneller als Sanic sind.
-!!! check "Inspirierte **FastAPI**"
- Einen Weg zu finden, eine hervorragende Performanz zu haben.
+///
- Aus diesem Grund basiert **FastAPI** auf Starlette, da dieses das schnellste verfügbare Framework ist (getestet in Benchmarks von Dritten).
+/// check | "Inspirierte **FastAPI**"
+
+Einen Weg zu finden, eine hervorragende Performanz zu haben.
+
+Aus diesem Grund basiert **FastAPI** auf Starlette, da dieses das schnellste verfügbare Framework ist (getestet in Benchmarks von Dritten).
+
+///
### <a href="https://falconframework.org/" class="external-link" target="_blank">Falcon</a>
Daher müssen Datenvalidierung, Serialisierung und Dokumentation im Code und nicht automatisch erfolgen. Oder sie müssen als Framework oberhalb von Falcon implementiert werden, so wie Hug. Dieselbe Unterscheidung findet auch in anderen Frameworks statt, die vom Design von Falcon inspiriert sind und ein Requestobjekt und ein Responseobjekt als Parameter haben.
-!!! check "Inspirierte **FastAPI**"
- Wege zu finden, eine großartige Performanz zu erzielen.
+/// check | "Inspirierte **FastAPI**"
- Zusammen mit Hug (da Hug auf Falcon basiert), einen `response`-Parameter in Funktionen zu deklarieren.
+Wege zu finden, eine großartige Performanz zu erzielen.
- Obwohl er in FastAPI optional ist und hauptsächlich zum Festlegen von Headern, Cookies und alternativen Statuscodes verwendet wird.
+Zusammen mit Hug (da Hug auf Falcon basiert), einen `response`-Parameter in Funktionen zu deklarieren.
+
+Obwohl er in FastAPI optional ist und hauptsächlich zum Festlegen von Headern, Cookies und alternativen Statuscodes verwendet wird.
+
+///
### <a href="https://moltenframework.com/" class="external-link" target="_blank">Molten</a>
Routen werden an einer einzigen Stelle deklariert, indem Funktionen verwendet werden, die an anderen Stellen deklariert wurden (anstatt Dekoratoren zu verwenden, welche direkt über der Funktion platziert werden können, welche den Endpunkt verarbeitet). Dies ähnelt eher der Vorgehensweise von Django als der Vorgehensweise von Flask (und Starlette). Es trennt im Code Dinge, die relativ eng miteinander gekoppelt sind.
-!!! check "Inspirierte **FastAPI**"
- Zusätzliche Validierungen für Datentypen zu definieren, mithilfe des „Default“-Werts von Modellattributen. Dies verbessert die Editorunterstützung und war zuvor in Pydantic nicht verfügbar.
+/// check | "Inspirierte **FastAPI**"
+
+Zusätzliche Validierungen für Datentypen zu definieren, mithilfe des „Default“-Werts von Modellattributen. Dies verbessert die Editorunterstützung und war zuvor in Pydantic nicht verfügbar.
- Das hat tatsächlich dazu geführt, dass Teile von Pydantic aktualisiert wurden, um denselben Validierungsdeklarationsstil zu unterstützen (diese gesamte Funktionalität ist jetzt bereits in Pydantic verfügbar).
+Das hat tatsächlich dazu geführt, dass Teile von Pydantic aktualisiert wurden, um denselben Validierungsdeklarationsstil zu unterstützen (diese gesamte Funktionalität ist jetzt bereits in Pydantic verfügbar).
+
+///
### <a href="https://www.hug.rest/" class="external-link" target="_blank">Hug</a>
Da es auf dem bisherigen Standard für synchrone Python-Webframeworks (WSGI) basiert, kann es nicht mit Websockets und anderen Dingen umgehen, verfügt aber dennoch über eine hohe Performanz.
-!!! info
- Hug wurde von Timothy Crosley erstellt, dem gleichen Schöpfer von <a href="https://github.com/timothycrosley/isort" class="external-link" target="_blank">`isort`</a>, einem großartigen Tool zum automatischen Sortieren von Importen in Python-Dateien.
+/// info
+
+Hug wurde von Timothy Crosley erstellt, dem gleichen Schöpfer von <a href="https://github.com/timothycrosley/isort" class="external-link" target="_blank">`isort`</a>, einem großartigen Tool zum automatischen Sortieren von Importen in Python-Dateien.
+
+///
-!!! check "Ideen, die **FastAPI** inspiriert haben"
- Hug inspirierte Teile von APIStar und war eines der Tools, die ich am vielversprechendsten fand, neben APIStar.
+/// check | "Ideen, die **FastAPI** inspiriert haben"
- Hug hat dazu beigetragen, **FastAPI** dazu zu inspirieren, Python-Typhinweise zum Deklarieren von Parametern zu verwenden und ein Schema zu generieren, das die API automatisch definiert.
+Hug inspirierte Teile von APIStar und war eines der Tools, die ich am vielversprechendsten fand, neben APIStar.
- Hug inspirierte **FastAPI** dazu, einen `response`-Parameter in Funktionen zu deklarieren, um Header und Cookies zu setzen.
+Hug hat dazu beigetragen, **FastAPI** dazu zu inspirieren, Python-Typhinweise zum Deklarieren von Parametern zu verwenden und ein Schema zu generieren, das die API automatisch definiert.
+
+Hug inspirierte **FastAPI** dazu, einen `response`-Parameter in Funktionen zu deklarieren, um Header und Cookies zu setzen.
+
+///
### <a href="https://github.com/encode/apistar" class="external-link" target="_blank">APIStar</a> (≦ 0.5)
Jetzt handelt es sich bei APIStar um eine Reihe von Tools zur Validierung von OpenAPI-Spezifikationen, nicht um ein Webframework.
-!!! info
- APIStar wurde von Tom Christie erstellt. Derselbe, welcher Folgendes erstellt hat:
+/// info
+
+APIStar wurde von Tom Christie erstellt. Derselbe, welcher Folgendes erstellt hat:
- * Django REST Framework
- * Starlette (auf welchem **FastAPI** basiert)
- * Uvicorn (verwendet von Starlette und **FastAPI**)
+* Django REST Framework
+* Starlette (auf welchem **FastAPI** basiert)
+* Uvicorn (verwendet von Starlette und **FastAPI**)
-!!! check "Inspirierte **FastAPI**"
- Zu existieren.
+///
- Die Idee, mehrere Dinge (Datenvalidierung, Serialisierung und Dokumentation) mit denselben Python-Typen zu deklarieren, welche gleichzeitig eine hervorragende Editorunterstützung bieten, hielt ich für eine brillante Idee.
+/// check | "Inspirierte **FastAPI**"
- Und nach einer langen Suche nach einem ähnlichen Framework und dem Testen vieler verschiedener Alternativen, war APIStar die beste verfügbare Option.
+Zu existieren.
- Dann hörte APIStar auf, als Server zu existieren, und Starlette wurde geschaffen, welches eine neue, bessere Grundlage für ein solches System bildete. Das war die finale Inspiration für die Entwicklung von **FastAPI**.
+Die Idee, mehrere Dinge (Datenvalidierung, Serialisierung und Dokumentation) mit denselben Python-Typen zu deklarieren, welche gleichzeitig eine hervorragende Editorunterstützung bieten, hielt ich für eine brillante Idee.
- Ich betrachte **FastAPI** als einen „spirituellen Nachfolger“ von APIStar, welcher die Funktionen, das Typsystem und andere Teile verbessert und erweitert, basierend auf den Erkenntnissen aus all diesen früheren Tools.
+Und nach einer langen Suche nach einem ähnlichen Framework und dem Testen vieler verschiedener Alternativen, war APIStar die beste verfügbare Option.
+
+Dann hörte APIStar auf, als Server zu existieren, und Starlette wurde geschaffen, welches eine neue, bessere Grundlage für ein solches System bildete. Das war die finale Inspiration für die Entwicklung von **FastAPI**.
+
+Ich betrachte **FastAPI** als einen „spirituellen Nachfolger“ von APIStar, welcher die Funktionen, das Typsystem und andere Teile verbessert und erweitert, basierend auf den Erkenntnissen aus all diesen früheren Tools.
+
+///
## Verwendet von **FastAPI**
Es ist vergleichbar mit Marshmallow. Obwohl es in Benchmarks schneller als Marshmallow ist. Und da es auf den gleichen Python-Typhinweisen basiert, ist die Editorunterstützung großartig.
-!!! check "**FastAPI** verwendet es, um"
- Die gesamte Datenvalidierung, Datenserialisierung und automatische Modelldokumentation (basierend auf JSON Schema) zu erledigen.
+/// check | "**FastAPI** verwendet es, um"
- **FastAPI** nimmt dann, abgesehen von all den anderen Dingen, die es tut, dieses JSON-Schema und fügt es in OpenAPI ein.
+Die gesamte Datenvalidierung, Datenserialisierung und automatische Modelldokumentation (basierend auf JSON Schema) zu erledigen.
+
+**FastAPI** nimmt dann, abgesehen von all den anderen Dingen, die es tut, dieses JSON-Schema und fügt es in OpenAPI ein.
+
+///
### <a href="https://www.starlette.io/" class="external-link" target="_blank">Starlette</a>
Das ist eines der wichtigsten Dinge, welche **FastAPI** hinzufügt, alles basierend auf Python-Typhinweisen (mit Pydantic). Das, plus, das Dependency Injection System, Sicherheitswerkzeuge, OpenAPI-Schemagenerierung, usw.
-!!! note "Technische Details"
- ASGI ist ein neuer „Standard“, welcher von Mitgliedern des Django-Kernteams entwickelt wird. Es handelt sich immer noch nicht um einen „Python-Standard“ (ein PEP), obwohl sie gerade dabei sind, das zu tun.
+/// note | "Technische Details"
+
+ASGI ist ein neuer „Standard“, welcher von Mitgliedern des Django-Kernteams entwickelt wird. Es handelt sich immer noch nicht um einen „Python-Standard“ (ein PEP), obwohl sie gerade dabei sind, das zu tun.
- Dennoch wird es bereits von mehreren Tools als „Standard“ verwendet. Das verbessert die Interoperabilität erheblich, da Sie Uvicorn mit jeden anderen ASGI-Server (wie Daphne oder Hypercorn) tauschen oder ASGI-kompatible Tools wie `python-socketio` hinzufügen können.
+Dennoch wird es bereits von mehreren Tools als „Standard“ verwendet. Das verbessert die Interoperabilität erheblich, da Sie Uvicorn mit jeden anderen ASGI-Server (wie Daphne oder Hypercorn) tauschen oder ASGI-kompatible Tools wie `python-socketio` hinzufügen können.
-!!! check "**FastAPI** verwendet es, um"
- Alle Kern-Webaspekte zu handhaben. Und fügt Funktionen obenauf.
+///
- Die Klasse `FastAPI` selbst erbt direkt von der Klasse `Starlette`.
+/// check | "**FastAPI** verwendet es, um"
- Alles, was Sie also mit Starlette machen können, können Sie direkt mit **FastAPI** machen, da es sich im Grunde um Starlette auf Steroiden handelt.
+Alle Kern-Webaspekte zu handhaben. Und fügt Funktionen obenauf.
+
+Die Klasse `FastAPI` selbst erbt direkt von der Klasse `Starlette`.
+
+Alles, was Sie also mit Starlette machen können, können Sie direkt mit **FastAPI** machen, da es sich im Grunde um Starlette auf Steroiden handelt.
+
+///
### <a href="https://www.uvicorn.org/" class="external-link" target="_blank">Uvicorn</a>
Es ist der empfohlene Server für Starlette und **FastAPI**.
-!!! check "**FastAPI** empfiehlt es als"
- Hauptwebserver zum Ausführen von **FastAPI**-Anwendungen.
+/// check | "**FastAPI** empfiehlt es als"
+
+Hauptwebserver zum Ausführen von **FastAPI**-Anwendungen.
+
+Sie können ihn mit Gunicorn kombinieren, um einen asynchronen Multiprozess-Server zu erhalten.
- Sie können ihn mit Gunicorn kombinieren, um einen asynchronen Multiprozess-Server zu erhalten.
+Weitere Details finden Sie im Abschnitt [Deployment](deployment/index.md){.internal-link target=_blank}.
- Weitere Details finden Sie im Abschnitt [Deployment](deployment/index.md){.internal-link target=_blank}.
+///
## Benchmarks und Geschwindigkeit
return results
```
-!!! note
- Sie können `await` nur innerhalb von Funktionen verwenden, die mit `async def` erstellt wurden.
+/// note
+
+Sie können `await` nur innerhalb von Funktionen verwenden, die mit `async def` erstellt wurden.
+
+///
---
<img src="/img/async/concurrent-burgers/concurrent-burgers-07.png" class="illustration">
-!!! info
- Die wunderschönen Illustrationen stammen von <a href="https://www.instagram.com/ketrinadrawsalot" class="external-link" target="_blank">Ketrina Thompson</a>. 🎨
+/// info
+
+Die wunderschönen Illustrationen stammen von <a href="https://www.instagram.com/ketrinadrawsalot" class="external-link" target="_blank">Ketrina Thompson</a>. 🎨
+
+///
---
Es wurde nicht viel geredet oder geflirtet, da die meiste Zeit mit Warten 🕙 vor der Theke verbracht wurde. 😞
-!!! info
- Die wunderschönen Illustrationen stammen von <a href="https://www.instagram.com/ketrinadrawsalot" class="external-link" target="_blank">Ketrina Thompson</a>. 🎨
+/// info
+
+Die wunderschönen Illustrationen stammen von <a href="https://www.instagram.com/ketrinadrawsalot" class="external-link" target="_blank">Ketrina Thompson</a>. 🎨
+
+///
---
## Sehr technische Details
-!!! warning "Achtung"
- Das folgende können Sie wahrscheinlich überspringen.
+/// warning | "Achtung"
+
+Das folgende können Sie wahrscheinlich überspringen.
+
+Dies sind sehr technische Details darüber, wie **FastAPI** unter der Haube funktioniert.
- Dies sind sehr technische Details darüber, wie **FastAPI** unter der Haube funktioniert.
+Wenn Sie über gute technische Kenntnisse verfügen (Coroutinen, Threads, Blocking, usw.) und neugierig sind, wie FastAPI mit `async def`s im Vergleich zu normalen `def`s umgeht, fahren Sie fort.
- Wenn Sie über gute technische Kenntnisse verfügen (Coroutinen, Threads, Blocking, usw.) und neugierig sind, wie FastAPI mit `async def`s im Vergleich zu normalen `def`s umgeht, fahren Sie fort.
+///
### Pfadoperation-Funktionen
Aktivieren Sie die neue Umgebung mit:
-=== "Linux, macOS"
+//// tab | Linux, macOS
- <div class="termy">
+<div class="termy">
- ```console
- $ source ./env/bin/activate
- ```
+```console
+$ source ./env/bin/activate
+```
- </div>
+</div>
-=== "Windows PowerShell"
+////
- <div class="termy">
+//// tab | Windows PowerShell
- ```console
- $ .\env\Scripts\Activate.ps1
- ```
+<div class="termy">
- </div>
+```console
+$ .\env\Scripts\Activate.ps1
+```
-=== "Windows Bash"
+</div>
+
+////
+
+//// tab | Windows Bash
- Oder, wenn Sie Bash für Windows verwenden (z. B. <a href="https://gitforwindows.org/" class="external-link" target="_blank">Git Bash</a>):
+Oder, wenn Sie Bash für Windows verwenden (z. B. <a href="https://gitforwindows.org/" class="external-link" target="_blank">Git Bash</a>):
- <div class="termy">
+<div class="termy">
+
+```console
+$ source ./env/Scripts/activate
+```
- ```console
- $ source ./env/Scripts/activate
- ```
+</div>
- </div>
+////
Um zu überprüfen, ob es funktioniert hat, geben Sie ein:
-=== "Linux, macOS, Windows Bash"
+//// tab | Linux, macOS, Windows Bash
- <div class="termy">
+<div class="termy">
- ```console
- $ which pip
+```console
+$ which pip
- some/directory/fastapi/env/bin/pip
- ```
+some/directory/fastapi/env/bin/pip
+```
- </div>
+</div>
-=== "Windows PowerShell"
+////
- <div class="termy">
+//// tab | Windows PowerShell
- ```console
- $ Get-Command pip
+<div class="termy">
- some/directory/fastapi/env/bin/pip
- ```
+```console
+$ Get-Command pip
+
+some/directory/fastapi/env/bin/pip
+```
- </div>
+</div>
+
+////
Wenn die `pip` Binärdatei unter `env/bin/pip` angezeigt wird, hat es funktioniert. 🎉
</div>
-!!! tip "Tipp"
- Aktivieren Sie jedes Mal, wenn Sie ein neues Package mit `pip` in dieser Umgebung installieren, die Umgebung erneut.
+/// tip | "Tipp"
+
+Aktivieren Sie jedes Mal, wenn Sie ein neues Package mit `pip` in dieser Umgebung installieren, die Umgebung erneut.
- Dadurch wird sichergestellt, dass Sie, wenn Sie ein von diesem Package installiertes Terminalprogramm verwenden, das Programm aus Ihrer lokalen Umgebung verwenden und kein anderes, das global installiert sein könnte.
+Dadurch wird sichergestellt, dass Sie, wenn Sie ein von diesem Package installiertes Terminalprogramm verwenden, das Programm aus Ihrer lokalen Umgebung verwenden und kein anderes, das global installiert sein könnte.
+
+///
### Benötigtes mit pip installieren
Auf diese Weise müssen Sie Ihre lokale Version nicht „installieren“, um jede Änderung testen zu können.
-!!! note "Technische Details"
- Das geschieht nur, wenn Sie die Installation mit der enthaltenen `requirements.txt` durchführen, anstatt `pip install fastapi` direkt auszuführen.
+/// note | "Technische Details"
+
+Das geschieht nur, wenn Sie die Installation mit der enthaltenen `requirements.txt` durchführen, anstatt `pip install fastapi` direkt auszuführen.
- Das liegt daran, dass in der Datei `requirements.txt` die lokale Version von FastAPI mit der Option `-e` für die Installation im „editierbaren“ Modus markiert ist.
+Das liegt daran, dass in der Datei `requirements.txt` die lokale Version von FastAPI mit der Option `-e` für die Installation im „editierbaren“ Modus markiert ist.
+
+///
### Den Code formatieren
Auf diese Weise können Sie die Dokumentation/Quelldateien bearbeiten und die Änderungen live sehen.
-!!! tip "Tipp"
- Alternativ können Sie die Schritte des Skripts auch manuell ausführen.
+/// tip | "Tipp"
- Gehen Sie in das Verzeichnis für die entsprechende Sprache. Das für die englischsprachige Hauptdokumentation befindet sich unter `docs/en/`:
+Alternativ können Sie die Schritte des Skripts auch manuell ausführen.
- ```console
- $ cd docs/en/
- ```
+Gehen Sie in das Verzeichnis für die entsprechende Sprache. Das für die englischsprachige Hauptdokumentation befindet sich unter `docs/en/`:
- Führen Sie dann `mkdocs` in diesem Verzeichnis aus:
+```console
+$ cd docs/en/
+```
- ```console
- $ mkdocs serve --dev-addr 8008
- ```
+Führen Sie dann `mkdocs` in diesem Verzeichnis aus:
+
+```console
+$ mkdocs serve --dev-addr 8008
+```
+
+///
#### Typer-CLI (optional)
Und es gibt zusätzliche Tools/Skripte für Übersetzungen, in `./scripts/docs.py`.
-!!! tip "Tipp"
- Sie müssen sich den Code in `./scripts/docs.py` nicht anschauen, verwenden Sie ihn einfach in der Kommandozeile.
+/// tip | "Tipp"
+
+Sie müssen sich den Code in `./scripts/docs.py` nicht anschauen, verwenden Sie ihn einfach in der Kommandozeile.
+
+///
Die gesamte Dokumentation befindet sich im Markdown-Format im Verzeichnis `./docs/en/`.
* Sehen Sie diese Pull Requests durch (Review), schlagen Sie Änderungen vor, oder segnen Sie sie ab (Approval). Bei den Sprachen, die ich nicht spreche, warte ich, bis mehrere andere die Übersetzung durchgesehen haben, bevor ich den Pull Request merge.
-!!! tip "Tipp"
- Sie können <a href="https://help.github.com/en/github/collaborating-with-issues-and-pull-requests/commenting-on-a-pull-request" class="external-link" target="_blank">Kommentare mit Änderungsvorschlägen</a> zu vorhandenen Pull Requests hinzufügen.
+/// tip | "Tipp"
+
+Sie können <a href="https://help.github.com/en/github/collaborating-with-issues-and-pull-requests/commenting-on-a-pull-request" class="external-link" target="_blank">Kommentare mit Änderungsvorschlägen</a> zu vorhandenen Pull Requests hinzufügen.
+
+Schauen Sie sich die Dokumentation an, <a href="https://help.github.com/en/github/collaborating-with-issues-and-pull-requests/about-pull-request-reviews" class="external-link" target="_blank">wie man ein Review zu einem Pull Request hinzufügt</a>, welches den PR absegnet oder Änderungen vorschlägt.
- Schauen Sie sich die Dokumentation an, <a href="https://help.github.com/en/github/collaborating-with-issues-and-pull-requests/about-pull-request-reviews" class="external-link" target="_blank">wie man ein Review zu einem Pull Request hinzufügt</a>, welches den PR absegnet oder Änderungen vorschlägt.
+///
* Überprüfen Sie, ob es eine <a href="https://github.com/fastapi/fastapi/discussions/categories/translations" class="external-link" target="_blank">GitHub-Diskussion</a> gibt, die Übersetzungen für Ihre Sprache koordiniert. Sie können sie abonnieren, und wenn ein neuer Pull Request zum Review vorliegt, wird der Diskussion automatisch ein Kommentar hinzugefügt.
Im Spanischen lautet der Zwei-Buchstaben-Code `es`. Das Verzeichnis für spanische Übersetzungen befindet sich also unter `docs/es/`.
-!!! tip "Tipp"
- Die Haupt („offizielle“) Sprache ist Englisch und befindet sich unter `docs/en/`.
+/// tip | "Tipp"
+
+Die Haupt („offizielle“) Sprache ist Englisch und befindet sich unter `docs/en/`.
+
+///
Führen Sie nun den Live-Server für die Dokumentation auf Spanisch aus:
</div>
-!!! tip "Tipp"
- Alternativ können Sie die Schritte des Skripts auch manuell ausführen.
+/// tip | "Tipp"
+
+Alternativ können Sie die Schritte des Skripts auch manuell ausführen.
- Gehen Sie in das Sprachverzeichnis, für die spanischen Übersetzungen ist das `docs/es/`:
+Gehen Sie in das Sprachverzeichnis, für die spanischen Übersetzungen ist das `docs/es/`:
+
+```console
+$ cd docs/es/
+```
- ```console
- $ cd docs/es/
- ```
+Dann führen Sie in dem Verzeichnis `mkdocs` aus:
- Dann führen Sie in dem Verzeichnis `mkdocs` aus:
+```console
+$ mkdocs serve --dev-addr 8008
+```
- ```console
- $ mkdocs serve --dev-addr 8008
- ```
+///
Jetzt können Sie auf <a href="http://127.0.0.1:8008" class="external-link" target="_blank">http://127.0.0.1:8008</a> gehen und Ihre Änderungen live sehen.
docs/es/docs/features.md
```
-!!! tip "Tipp"
- Beachten Sie, dass die einzige Änderung in Pfad und Dateiname der Sprachcode ist, von `en` zu `es`.
+/// tip | "Tipp"
+
+Beachten Sie, dass die einzige Änderung in Pfad und Dateiname der Sprachcode ist, von `en` zu `es`.
+
+///
Wenn Sie in Ihrem Browser nachsehen, werden Sie feststellen, dass die Dokumentation jetzt Ihren neuen Abschnitt anzeigt (die Info-Box oben ist verschwunden). 🎉
INHERIT: ../en/mkdocs.yml
```
-!!! tip "Tipp"
- Sie können diese Datei mit diesem Inhalt auch einfach manuell erstellen.
+/// tip | "Tipp"
+
+Sie können diese Datei mit diesem Inhalt auch einfach manuell erstellen.
+
+///
Das Kommando hat auch eine Dummy-Datei `docs/ht/index.md` für die Hauptseite erstellt. Sie können mit der Übersetzung dieser Datei beginnen.
Aber in den Fällen mit wirklich schwerwiegenden Fehlern, die den laufenden **Prozess** zum Absturz bringen, benötigen Sie eine externe Komponente, die den Prozess **neu startet**, zumindest ein paar Mal ...
-!!! tip "Tipp"
- ... Obwohl es wahrscheinlich keinen Sinn macht, sie immer wieder neu zu starten, wenn die gesamte Anwendung einfach **sofort abstürzt**. Aber in diesen Fällen werden Sie es wahrscheinlich während der Entwicklung oder zumindest direkt nach dem Deployment bemerken.
+/// tip | "Tipp"
- Konzentrieren wir uns also auf die Hauptfälle, in denen die Anwendung in bestimmten Fällen **in der Zukunft** völlig abstürzen könnte und es dann dennoch sinnvoll ist, sie neu zu starten.
+... Obwohl es wahrscheinlich keinen Sinn macht, sie immer wieder neu zu starten, wenn die gesamte Anwendung einfach **sofort abstürzt**. Aber in diesen Fällen werden Sie es wahrscheinlich während der Entwicklung oder zumindest direkt nach dem Deployment bemerken.
+
+Konzentrieren wir uns also auf die Hauptfälle, in denen die Anwendung in bestimmten Fällen **in der Zukunft** völlig abstürzen könnte und es dann dennoch sinnvoll ist, sie neu zu starten.
+
+///
Sie möchten wahrscheinlich, dass eine **externe Komponente** für den Neustart Ihrer Anwendung verantwortlich ist, da zu diesem Zeitpunkt dieselbe Anwendung mit Uvicorn und Python bereits abgestürzt ist und es daher nichts im selben Code derselben Anwendung gibt, was etwas dagegen tun kann.
* **Cloud-Dienste**, welche das für Sie erledigen
* Der Cloud-Dienst wird wahrscheinlich **die Replikation für Sie übernehmen**. Er würde Sie möglicherweise **einen auszuführenden Prozess** oder ein **zu verwendendes Container-Image** definieren lassen, in jedem Fall wäre es höchstwahrscheinlich **ein einzelner Uvicorn-Prozess**, und der Cloud-Dienst wäre auch verantwortlich für die Replikation.
-!!! tip "Tipp"
- Machen Sie sich keine Sorgen, wenn einige dieser Punkte zu **Containern**, Docker oder Kubernetes noch nicht viel Sinn ergeben.
+/// tip | "Tipp"
+
+Machen Sie sich keine Sorgen, wenn einige dieser Punkte zu **Containern**, Docker oder Kubernetes noch nicht viel Sinn ergeben.
+
+Ich werde Ihnen in einem zukünftigen Kapitel mehr über Container-Images, Docker, Kubernetes, usw. erzählen: [FastAPI in Containern – Docker](docker.md){.internal-link target=_blank}.
- Ich werde Ihnen in einem zukünftigen Kapitel mehr über Container-Images, Docker, Kubernetes, usw. erzählen: [FastAPI in Containern – Docker](docker.md){.internal-link target=_blank}.
+///
## Schritte vor dem Start
Natürlich gibt es Fälle, in denen es kein Problem darstellt, die Vorab-Schritte mehrmals auszuführen. In diesem Fall ist die Handhabung viel einfacher.
-!!! tip "Tipp"
- Bedenken Sie außerdem, dass Sie, abhängig von Ihrer Einrichtung, in manchen Fällen **gar keine Vorab-Schritte** benötigen, bevor Sie die Anwendung starten.
+/// tip | "Tipp"
- In diesem Fall müssen Sie sich darüber keine Sorgen machen. 🤷
+Bedenken Sie außerdem, dass Sie, abhängig von Ihrer Einrichtung, in manchen Fällen **gar keine Vorab-Schritte** benötigen, bevor Sie die Anwendung starten.
+
+In diesem Fall müssen Sie sich darüber keine Sorgen machen. 🤷
+
+///
### Beispiele für Strategien für Vorab-Schritte
* Ein Bash-Skript, das die Vorab-Schritte ausführt und dann Ihre Anwendung startet
* Sie benötigen immer noch eine Möglichkeit, *dieses* Bash-Skript zu starten/neu zu starten, Fehler zu erkennen, usw.
-!!! tip "Tipp"
- Konkretere Beispiele hierfür mit Containern gebe ich Ihnen in einem späteren Kapitel: [FastAPI in Containern – Docker](docker.md){.internal-link target=_blank}.
+/// tip | "Tipp"
+
+Konkretere Beispiele hierfür mit Containern gebe ich Ihnen in einem späteren Kapitel: [FastAPI in Containern – Docker](docker.md){.internal-link target=_blank}.
+
+///
## Ressourcennutzung
Die Verwendung von Linux-Containern bietet mehrere Vorteile, darunter **Sicherheit**, **Replizierbarkeit**, **Einfachheit** und andere.
-!!! tip "Tipp"
- Sie haben es eilig und kennen sich bereits aus? Springen Sie zum [`Dockerfile` unten 👇](#ein-docker-image-fur-fastapi-erstellen).
+/// tip | "Tipp"
+
+Sie haben es eilig und kennen sich bereits aus? Springen Sie zum [`Dockerfile` unten 👇](#ein-docker-image-fur-fastapi-erstellen).
+
+///
<Details>
<summary>Dockerfile-Vorschau 👀</summary>
</div>
-!!! info
- Es gibt andere Formate und Tools zum Definieren und Installieren von Paketabhängigkeiten.
+/// info
+
+Es gibt andere Formate und Tools zum Definieren und Installieren von Paketabhängigkeiten.
- Ich zeige Ihnen später in einem Abschnitt unten ein Beispiel unter Verwendung von Poetry. 👇
+Ich zeige Ihnen später in einem Abschnitt unten ein Beispiel unter Verwendung von Poetry. 👇
+
+///
### Den **FastAPI**-Code erstellen
Da das Programm unter `/code` gestartet wird und sich darin das Verzeichnis `./app` mit Ihrem Code befindet, kann **Uvicorn** `app` sehen und aus `app.main` **importieren**.
-!!! tip "Tipp"
- Lernen Sie, was jede Zeile bewirkt, indem Sie auf die Zahlenblasen im Code klicken. 👆
+/// tip | "Tipp"
+
+Lernen Sie, was jede Zeile bewirkt, indem Sie auf die Zahlenblasen im Code klicken. 👆
+
+///
Sie sollten jetzt eine Verzeichnisstruktur wie diese haben:
</div>
-!!! tip "Tipp"
- Beachten Sie das `.` am Ende, es entspricht `./` und teilt Docker mit, welches Verzeichnis zum Erstellen des Containerimages verwendet werden soll.
+/// tip | "Tipp"
+
+Beachten Sie das `.` am Ende, es entspricht `./` und teilt Docker mit, welches Verzeichnis zum Erstellen des Containerimages verwendet werden soll.
+
+In diesem Fall handelt es sich um dasselbe aktuelle Verzeichnis (`.`).
- In diesem Fall handelt es sich um dasselbe aktuelle Verzeichnis (`.`).
+///
### Den Docker-Container starten
Es könnte sich um einen anderen Container handeln, zum Beispiel mit <a href="https://traefik.io/" class="external-link" target="_blank">Traefik</a>, welcher **HTTPS** und **automatischen** Erwerb von **Zertifikaten** handhabt.
-!!! tip "Tipp"
- Traefik verfügt über Integrationen mit Docker, Kubernetes und anderen, sodass Sie damit ganz einfach HTTPS für Ihre Container einrichten und konfigurieren können.
+/// tip | "Tipp"
+
+Traefik verfügt über Integrationen mit Docker, Kubernetes und anderen, sodass Sie damit ganz einfach HTTPS für Ihre Container einrichten und konfigurieren können.
+
+///
Alternativ könnte HTTPS von einem Cloud-Anbieter als einer seiner Dienste gehandhabt werden (während die Anwendung weiterhin in einem Container ausgeführt wird).
Da diese Komponente die **Last** an Requests aufnehmen und diese (hoffentlich) **ausgewogen** auf die Worker verteilen würde, wird sie üblicherweise auch **Load Balancer** – Lastverteiler – genannt.
-!!! tip "Tipp"
- Die gleiche **TLS-Terminierungsproxy**-Komponente, die für HTTPS verwendet wird, wäre wahrscheinlich auch ein **Load Balancer**.
+/// tip | "Tipp"
+
+Die gleiche **TLS-Terminierungsproxy**-Komponente, die für HTTPS verwendet wird, wäre wahrscheinlich auch ein **Load Balancer**.
+
+///
Und wenn Sie mit Containern arbeiten, verfügt das gleiche System, mit dem Sie diese starten und verwalten, bereits über interne Tools, um die **Netzwerkkommunikation** (z. B. HTTP-Requests) von diesem **Load Balancer** (das könnte auch ein **TLS-Terminierungsproxy** sein) zu den Containern mit Ihrer Anwendung weiterzuleiten.
Wenn Sie **mehrere Container** haben, von denen wahrscheinlich jeder einen **einzelnen Prozess** ausführt (z. B. in einem **Kubernetes**-Cluster), dann möchten Sie wahrscheinlich einen **separaten Container** haben, welcher die Arbeit der **Vorab-Schritte** in einem einzelnen Container, mit einem einzelnenen Prozess ausführt, **bevor** die replizierten Workercontainer ausgeführt werden.
-!!! info
- Wenn Sie Kubernetes verwenden, wäre dies wahrscheinlich ein <a href="https://kubernetes.io/docs/concepts/workloads/pods/init-containers/" class="external-link" target="_blank">Init-Container</a>.
+/// info
+
+Wenn Sie Kubernetes verwenden, wäre dies wahrscheinlich ein <a href="https://kubernetes.io/docs/concepts/workloads/pods/init-containers/" class="external-link" target="_blank">Init-Container</a>.
+
+///
Wenn es in Ihrem Anwendungsfall kein Problem darstellt, diese vorherigen Schritte **mehrmals parallel** auszuführen (z. B. wenn Sie keine Datenbankmigrationen ausführen, sondern nur prüfen, ob die Datenbank bereits bereit ist), können Sie sie auch einfach in jedem Container direkt vor dem Start des Hauptprozesses einfügen.
* <a href="https://github.com/tiangolo/uvicorn-gunicorn-fastapi-docker" class="external-link" target="_blank">tiangolo/uvicorn-gunicorn-fastapi</a>.
-!!! warning "Achtung"
- Es besteht eine hohe Wahrscheinlichkeit, dass Sie dieses oder ein ähnliches Basisimage **nicht** benötigen und es besser wäre, wenn Sie das Image von Grund auf neu erstellen würden, wie [oben beschrieben in: Ein Docker-Image für FastAPI erstellen](#ein-docker-image-fur-fastapi-erstellen).
+/// warning | "Achtung"
+
+Es besteht eine hohe Wahrscheinlichkeit, dass Sie dieses oder ein ähnliches Basisimage **nicht** benötigen und es besser wäre, wenn Sie das Image von Grund auf neu erstellen würden, wie [oben beschrieben in: Ein Docker-Image für FastAPI erstellen](#ein-docker-image-fur-fastapi-erstellen).
+
+///
Dieses Image verfügt über einen **Auto-Tuning**-Mechanismus, um die **Anzahl der Arbeitsprozesse** basierend auf den verfügbaren CPU-Kernen festzulegen.
Es unterstützt auch die Ausführung von <a href="https://github.com/tiangolo/uvicorn-gunicorn-fastapi-docker#pre_start_path" class="external-link" target="_blank">**Vorab-Schritten vor dem Start** </a> mit einem Skript.
-!!! tip "Tipp"
- Um alle Konfigurationen und Optionen anzuzeigen, gehen Sie zur Docker-Image-Seite: <a href="https://github.com/tiangolo/uvicorn-gunicorn-fastapi-docker" class="external-link" target="_blank">tiangolo/uvicorn-gunicorn-fastapi</a>.
+/// tip | "Tipp"
+
+Um alle Konfigurationen und Optionen anzuzeigen, gehen Sie zur Docker-Image-Seite: <a href="https://github.com/tiangolo/uvicorn-gunicorn-fastapi-docker" class="external-link" target="_blank">tiangolo/uvicorn-gunicorn-fastapi</a>.
+
+///
### Anzahl der Prozesse auf dem offiziellen Docker-Image
11. Führe den Befehl `uvicorn` aus und weise ihn an, das aus `app.main` importierte `app`-Objekt zu verwenden.
-!!! tip "Tipp"
- Klicken Sie auf die Zahlenblasen, um zu sehen, was jede Zeile bewirkt.
+/// tip | "Tipp"
+
+Klicken Sie auf die Zahlenblasen, um zu sehen, was jede Zeile bewirkt.
+
+///
Eine **Docker-Phase** ist ein Teil eines `Dockerfile`s, welcher als **temporäres Containerimage** fungiert und nur zum Generieren einiger Dateien für die spätere Verwendung verwendet wird.
Aber es ist viel komplexer als das.
-!!! tip "Tipp"
- Wenn Sie es eilig haben oder es Ihnen egal ist, fahren Sie mit den nächsten Abschnitten fort, um Schritt-für-Schritt-Anleitungen für die Einrichtung der verschiedenen Technologien zu erhalten.
+/// tip | "Tipp"
+
+Wenn Sie es eilig haben oder es Ihnen egal ist, fahren Sie mit den nächsten Abschnitten fort, um Schritt-für-Schritt-Anleitungen für die Einrichtung der verschiedenen Technologien zu erhalten.
+
+///
Um **die Grundlagen von HTTPS** aus Sicht des Benutzers zu erlernen, schauen Sie sich <a href="https://howhttps.works/" class="external-link" target="_blank">https://howhttps.works/</a> an.
Sie würden dies wahrscheinlich nur einmal tun, beim ersten Mal, wenn Sie alles einrichten.
-!!! tip "Tipp"
- Dieser Domainnamen-Aspekt liegt weit vor HTTPS, aber da alles von der Domain und der IP-Adresse abhängt, lohnt es sich, das hier zu erwähnen.
+/// tip | "Tipp"
+
+Dieser Domainnamen-Aspekt liegt weit vor HTTPS, aber da alles von der Domain und der IP-Adresse abhängt, lohnt es sich, das hier zu erwähnen.
+
+///
### DNS
Und genau das ist **HTTPS**, es ist einfach **HTTP** innerhalb einer **sicheren TLS-Verbindung**, statt einer puren (unverschlüsselten) TCP-Verbindung.
-!!! tip "Tipp"
- Beachten Sie, dass die Verschlüsselung der Kommunikation auf der **TCP-Ebene** und nicht auf der HTTP-Ebene erfolgt.
+/// tip | "Tipp"
+
+Beachten Sie, dass die Verschlüsselung der Kommunikation auf der **TCP-Ebene** und nicht auf der HTTP-Ebene erfolgt.
+
+///
### HTTPS-Request
Sie können einen ASGI-kompatiblen Server installieren mit:
-=== "Uvicorn"
+//// tab | Uvicorn
- * <a href="https://www.uvicorn.org/" class="external-link" target="_blank">Uvicorn</a>, ein blitzschneller ASGI-Server, basierend auf uvloop und httptools.
+* <a href="https://www.uvicorn.org/" class="external-link" target="_blank">Uvicorn</a>, ein blitzschneller ASGI-Server, basierend auf uvloop und httptools.
- <div class="termy">
+<div class="termy">
+
+```console
+$ pip install "uvicorn[standard]"
- ```console
- $ pip install "uvicorn[standard]"
+---> 100%
+```
+
+</div>
- ---> 100%
- ```
+/// tip | "Tipp"
- </div>
+Durch das Hinzufügen von `standard` installiert und verwendet Uvicorn einige empfohlene zusätzliche Abhängigkeiten.
- !!! tip "Tipp"
- Durch das Hinzufügen von `standard` installiert und verwendet Uvicorn einige empfohlene zusätzliche Abhängigkeiten.
+Inklusive `uvloop`, einen hochperformanten Drop-in-Ersatz für `asyncio`, welcher für einen großen Leistungsschub bei der Nebenläufigkeit sorgt.
- Inklusive `uvloop`, einen hochperformanten Drop-in-Ersatz für `asyncio`, welcher für einen großen Leistungsschub bei der Nebenläufigkeit sorgt.
+///
-=== "Hypercorn"
+////
- * <a href="https://github.com/pgjones/hypercorn" class="external-link" target="_blank">Hypercorn</a>, ein ASGI-Server, der auch mit HTTP/2 kompatibel ist.
+//// tab | Hypercorn
- <div class="termy">
+* <a href="https://github.com/pgjones/hypercorn" class="external-link" target="_blank">Hypercorn</a>, ein ASGI-Server, der auch mit HTTP/2 kompatibel ist.
- ```console
- $ pip install hypercorn
+<div class="termy">
+
+```console
+$ pip install hypercorn
+
+---> 100%
+```
- ---> 100%
- ```
+</div>
- </div>
+... oder jeden anderen ASGI-Server.
- ... oder jeden anderen ASGI-Server.
+////
## Das Serverprogramm ausführen
Anschließend können Sie Ihre Anwendung auf die gleiche Weise ausführen, wie Sie es in den Tutorials getan haben, jedoch ohne die Option `--reload`, z. B.:
-=== "Uvicorn"
+//// tab | Uvicorn
- <div class="termy">
+<div class="termy">
- ```console
- $ uvicorn main:app --host 0.0.0.0 --port 80
+```console
+$ uvicorn main:app --host 0.0.0.0 --port 80
- <span style="color: green;">INFO</span>: Uvicorn running on http://0.0.0.0:80 (Press CTRL+C to quit)
- ```
+<span style="color: green;">INFO</span>: Uvicorn running on http://0.0.0.0:80 (Press CTRL+C to quit)
+```
- </div>
+</div>
+
+////
-=== "Hypercorn"
+//// tab | Hypercorn
- <div class="termy">
+<div class="termy">
+
+```console
+$ hypercorn main:app --bind 0.0.0.0:80
+
+Running on 0.0.0.0:8080 over http (CTRL + C to quit)
+```
+
+</div>
- ```console
- $ hypercorn main:app --bind 0.0.0.0:80
+////
- Running on 0.0.0.0:8080 over http (CTRL + C to quit)
- ```
+/// warning | "Achtung"
- </div>
+Denken Sie daran, die Option `--reload` zu entfernen, wenn Sie diese verwendet haben.
-!!! warning "Achtung"
- Denken Sie daran, die Option `--reload` zu entfernen, wenn Sie diese verwendet haben.
+Die Option `--reload` verbraucht viel mehr Ressourcen, ist instabiler, usw.
- Die Option `--reload` verbraucht viel mehr Ressourcen, ist instabiler, usw.
+Sie hilft sehr während der **Entwicklung**, aber Sie sollten sie **nicht** in der **Produktion** verwenden.
- Sie hilft sehr während der **Entwicklung**, aber Sie sollten sie **nicht** in der **Produktion** verwenden.
+///
## Hypercorn mit Trio
Hier zeige ich Ihnen, wie Sie <a href="https://gunicorn.org/" class="external-link" target="_blank">**Gunicorn**</a> mit **Uvicorn Workerprozessen** verwenden.
-!!! info
- Wenn Sie Container verwenden, beispielsweise mit Docker oder Kubernetes, erzähle ich Ihnen mehr darüber im nächsten Kapitel: [FastAPI in Containern – Docker](docker.md){.internal-link target=_blank}.
+/// info
- Insbesondere wenn die Anwendung auf **Kubernetes** läuft, werden Sie Gunicorn wahrscheinlich **nicht** verwenden wollen und stattdessen **einen einzelnen Uvicorn-Prozess pro Container** ausführen wollen, aber ich werde Ihnen später in diesem Kapitel mehr darüber erzählen.
+Wenn Sie Container verwenden, beispielsweise mit Docker oder Kubernetes, erzähle ich Ihnen mehr darüber im nächsten Kapitel: [FastAPI in Containern – Docker](docker.md){.internal-link target=_blank}.
+
+Insbesondere wenn die Anwendung auf **Kubernetes** läuft, werden Sie Gunicorn wahrscheinlich **nicht** verwenden wollen und stattdessen **einen einzelnen Uvicorn-Prozess pro Container** ausführen wollen, aber ich werde Ihnen später in diesem Kapitel mehr darüber erzählen.
+
+///
## Gunicorn mit Uvicorn-Workern
FastAPI folgt auch der Konvention, dass jede „PATCH“-Versionsänderung für Bugfixes und abwärtskompatible Änderungen gedacht ist.
-!!! tip "Tipp"
- Der „PATCH“ ist die letzte Zahl, zum Beispiel ist in `0.2.3` die PATCH-Version `3`.
+/// tip | "Tipp"
+
+Der „PATCH“ ist die letzte Zahl, zum Beispiel ist in `0.2.3` die PATCH-Version `3`.
+
+///
Sie sollten also in der Lage sein, eine Version wie folgt anzupinnen:
Nicht abwärtskompatible Änderungen und neue Funktionen werden in „MINOR“-Versionen hinzugefügt.
-!!! tip "Tipp"
- „MINOR“ ist die Zahl in der Mitte, zum Beispiel ist in `0.2.3` die MINOR-Version `2`.
+/// tip | "Tipp"
+
+„MINOR“ ist die Zahl in der Mitte, zum Beispiel ist in `0.2.3` die MINOR-Version `2`.
+
+///
## Upgrade der FastAPI-Versionen
Hier ist eine unvollständige Liste einiger davon.
-!!! tip "Tipp"
- Wenn Sie einen Artikel, ein Projekt, ein Tool oder irgendetwas im Zusammenhang mit **FastAPI** haben, was hier noch nicht aufgeführt ist, erstellen Sie einen <a href="https://github.com/fastapi/fastapi/edit/master/docs/en/data/external_links.yml" class="external-link" target="_blank">Pull Request und fügen Sie es hinzu</a>.
+/// tip | "Tipp"
-!!! note "Hinweis Deutsche Übersetzung"
- Die folgenden Überschriften und Links werden aus einer <a href="https://github.com/fastapi/fastapi/blob/master/docs/en/data/external_links.yml" class="external-link" target="_blank">anderen Datei</a> gelesen und sind daher nicht ins Deutsche übersetzt.
+Wenn Sie einen Artikel, ein Projekt, ein Tool oder irgendetwas im Zusammenhang mit **FastAPI** haben, was hier noch nicht aufgeführt ist, erstellen Sie einen <a href="https://github.com/fastapi/fastapi/edit/master/docs/en/data/external_links.yml" class="external-link" target="_blank">Pull Request und fügen Sie es hinzu</a>.
+
+///
+
+/// note | "Hinweis Deutsche Übersetzung"
+
+Die folgenden Überschriften und Links werden aus einer <a href="https://github.com/fastapi/fastapi/blob/master/docs/en/data/external_links.yml" class="external-link" target="_blank">anderen Datei</a> gelesen und sind daher nicht ins Deutsche übersetzt.
+
+///
{% for section_name, section_content in external_links.items() %}
my_second_user: User = User(**second_user_data)
```
-!!! info
- `**second_user_data` bedeutet:
+/// info
- Nimm die Schlüssel-Wert-Paare des `second_user_data` <abbr title="Dictionary – Wörterbuch: In anderen Programmiersprachen auch Hash, Map, Objekt, Assoziatives Array genannt">Dicts</abbr> und übergib sie direkt als Schlüsselwort-Argumente. Äquivalent zu: `User(id=4, name="Mary", joined="2018-11-30")`.
+`**second_user_data` bedeutet:
+
+Nimm die Schlüssel-Wert-Paare des `second_user_data` <abbr title="Dictionary – Wörterbuch: In anderen Programmiersprachen auch Hash, Map, Objekt, Assoziatives Array genannt">Dicts</abbr> und übergib sie direkt als Schlüsselwort-Argumente. Äquivalent zu: `User(id=4, name="Mary", joined="2018-11-30")`.
+
+///
### Editor Unterstützung
* Schreiben Sie dann einen **Kommentar** und berichten, dass Sie das getan haben. So weiß ich, dass Sie ihn wirklich überprüft haben.
-!!! info
- Leider kann ich PRs, nur weil sie von Mehreren gutgeheißen wurden, nicht einfach vertrauen.
+/// info
- Es ist mehrmals passiert, dass es PRs mit drei, fünf oder mehr Zustimmungen gibt, wahrscheinlich weil die Beschreibung ansprechend ist, aber wenn ich die PRs überprüfe, sind sie tatsächlich fehlerhaft, haben einen Bug, oder lösen das Problem nicht, welches sie behaupten, zu lösen. 😅
+Leider kann ich PRs, nur weil sie von Mehreren gutgeheißen wurden, nicht einfach vertrauen.
- Daher ist es wirklich wichtig, dass Sie den Code tatsächlich lesen und ausführen und mir in den Kommentaren mitteilen, dass Sie dies getan haben. 🤓
+Es ist mehrmals passiert, dass es PRs mit drei, fünf oder mehr Zustimmungen gibt, wahrscheinlich weil die Beschreibung ansprechend ist, aber wenn ich die PRs überprüfe, sind sie tatsächlich fehlerhaft, haben einen Bug, oder lösen das Problem nicht, welches sie behaupten, zu lösen. 😅
+
+Daher ist es wirklich wichtig, dass Sie den Code tatsächlich lesen und ausführen und mir in den Kommentaren mitteilen, dass Sie dies getan haben. 🤓
+
+///
* Wenn der PR irgendwie vereinfacht werden kann, fragen Sie ruhig danach, aber seien Sie nicht zu wählerisch, es gibt viele subjektive Standpunkte (und ich habe auch meinen eigenen 🙈), also ist es besser, wenn man sich auf die wesentlichen Dinge konzentriert.
Treten Sie dem 👥 <a href="https://discord.gg/VQjSZaeJmf" class="external-link" target="_blank">Discord-Chatserver</a> 👥 bei und treffen Sie sich mit anderen Mitgliedern der FastAPI-Community.
-!!! tip "Tipp"
- Wenn Sie Fragen haben, stellen Sie sie bei <a href="https://github.com/fastapi/fastapi/discussions/new?category=questions" class="external-link" target="_blank">GitHub Diskussionen</a>, es besteht eine viel bessere Chance, dass Sie hier Hilfe von den [FastAPI-Experten](fastapi-people.md#experten){.internal-link target=_blank} erhalten.
+/// tip | "Tipp"
+
+Wenn Sie Fragen haben, stellen Sie sie bei <a href="https://github.com/fastapi/fastapi/discussions/new?category=questions" class="external-link" target="_blank">GitHub Diskussionen</a>, es besteht eine viel bessere Chance, dass Sie hier Hilfe von den [FastAPI-Experten](fastapi-people.md#experten){.internal-link target=_blank} erhalten.
+
+Nutzen Sie den Chat nur für andere allgemeine Gespräche.
- Nutzen Sie den Chat nur für andere allgemeine Gespräche.
+///
### Den Chat nicht für Fragen verwenden
{!../../../docs_src/custom_docs_ui/tutorial001.py!}
```
-!!! tip "Tipp"
- Die *Pfadoperation* für `swagger_ui_redirect` ist ein Hilfsmittel bei der Verwendung von OAuth2.
+/// tip | "Tipp"
- Wenn Sie Ihre API mit einem OAuth2-Anbieter integrieren, können Sie sich authentifizieren und mit den erworbenen Anmeldeinformationen zur API-Dokumentation zurückkehren. Und mit ihr interagieren, die echte OAuth2-Authentifizierung verwendend.
+Die *Pfadoperation* für `swagger_ui_redirect` ist ein Hilfsmittel bei der Verwendung von OAuth2.
- Swagger UI erledigt das hinter den Kulissen für Sie, benötigt aber diesen „Umleitungs“-Helfer.
+Wenn Sie Ihre API mit einem OAuth2-Anbieter integrieren, können Sie sich authentifizieren und mit den erworbenen Anmeldeinformationen zur API-Dokumentation zurückkehren. Und mit ihr interagieren, die echte OAuth2-Authentifizierung verwendend.
+
+Swagger UI erledigt das hinter den Kulissen für Sie, benötigt aber diesen „Umleitungs“-Helfer.
+
+///
### Eine *Pfadoperation* erstellen, um es zu testen
{!../../../docs_src/custom_docs_ui/tutorial002.py!}
```
-!!! tip "Tipp"
- Die *Pfadoperation* für `swagger_ui_redirect` ist ein Hilfsmittel bei der Verwendung von OAuth2.
+/// tip | "Tipp"
+
+Die *Pfadoperation* für `swagger_ui_redirect` ist ein Hilfsmittel bei der Verwendung von OAuth2.
+
+Wenn Sie Ihre API mit einem OAuth2-Anbieter integrieren, können Sie sich authentifizieren und mit den erworbenen Anmeldeinformationen zur API-Dokumentation zurückkehren. Und mit ihr interagieren, die echte OAuth2-Authentifizierung verwendend.
- Wenn Sie Ihre API mit einem OAuth2-Anbieter integrieren, können Sie sich authentifizieren und mit den erworbenen Anmeldeinformationen zur API-Dokumentation zurückkehren. Und mit ihr interagieren, die echte OAuth2-Authentifizierung verwendend.
+Swagger UI erledigt das hinter den Kulissen für Sie, benötigt aber diesen „Umleitungs“-Helfer.
- Swagger UI erledigt das hinter den Kulissen für Sie, benötigt aber diesen „Umleitungs“-Helfer.
+///
### Eine *Pfadoperation* erstellen, um statische Dateien zu testen
Wenn Sie beispielsweise den Requestbody lesen oder manipulieren möchten, bevor er von Ihrer Anwendung verarbeitet wird.
-!!! danger "Gefahr"
- Dies ist eine „fortgeschrittene“ Funktion.
+/// danger | "Gefahr"
- Wenn Sie gerade erst mit **FastAPI** beginnen, möchten Sie diesen Abschnitt vielleicht überspringen.
+Dies ist eine „fortgeschrittene“ Funktion.
+
+Wenn Sie gerade erst mit **FastAPI** beginnen, möchten Sie diesen Abschnitt vielleicht überspringen.
+
+///
## Anwendungsfälle
### Eine benutzerdefinierte `GzipRequest`-Klasse erstellen
-!!! tip "Tipp"
- Dies ist nur ein einfaches Beispiel, um zu demonstrieren, wie es funktioniert. Wenn Sie Gzip-Unterstützung benötigen, können Sie die bereitgestellte [`GzipMiddleware`](../advanced/middleware.md#gzipmiddleware){.internal-link target=_blank} verwenden.
+/// tip | "Tipp"
+
+Dies ist nur ein einfaches Beispiel, um zu demonstrieren, wie es funktioniert. Wenn Sie Gzip-Unterstützung benötigen, können Sie die bereitgestellte [`GzipMiddleware`](../advanced/middleware.md#gzipmiddleware){.internal-link target=_blank} verwenden.
+
+///
Zuerst erstellen wir eine `GzipRequest`-Klasse, welche die Methode `Request.body()` überschreibt, um den Body bei Vorhandensein eines entsprechenden Headers zu dekomprimieren.
{!../../../docs_src/custom_request_and_route/tutorial001.py!}
```
-!!! note "Technische Details"
- Ein `Request` hat ein `request.scope`-Attribut, welches einfach ein Python-`dict` ist, welches die mit dem Request verbundenen Metadaten enthält.
+/// note | "Technische Details"
- Ein `Request` hat auch ein `request.receive`, welches eine Funktion ist, die den Hauptteil des Requests empfängt.
+Ein `Request` hat ein `request.scope`-Attribut, welches einfach ein Python-`dict` ist, welches die mit dem Request verbundenen Metadaten enthält.
- Das `scope`-`dict` und die `receive`-Funktion sind beide Teil der ASGI-Spezifikation.
+Ein `Request` hat auch ein `request.receive`, welches eine Funktion ist, die den Hauptteil des Requests empfängt.
- Und diese beiden Dinge, `scope` und `receive`, werden benötigt, um eine neue `Request`-Instanz zu erstellen.
+Das `scope`-`dict` und die `receive`-Funktion sind beide Teil der ASGI-Spezifikation.
- Um mehr über den `Request` zu erfahren, schauen Sie sich <a href="https://www.starlette.io/requests/" class="external-link" target="_blank">Starlettes Dokumentation zu Requests</a> an.
+Und diese beiden Dinge, `scope` und `receive`, werden benötigt, um eine neue `Request`-Instanz zu erstellen.
+
+Um mehr über den `Request` zu erfahren, schauen Sie sich <a href="https://www.starlette.io/requests/" class="external-link" target="_blank">Starlettes Dokumentation zu Requests</a> an.
+
+///
Das Einzige, was die von `GzipRequest.get_route_handler` zurückgegebene Funktion anders macht, ist die Konvertierung von `Request` in ein `GzipRequest`.
## Zugriff auf den Requestbody in einem Exceptionhandler
-!!! tip "Tipp"
- Um dasselbe Problem zu lösen, ist es wahrscheinlich viel einfacher, den `body` in einem benutzerdefinierten Handler für `RequestValidationError` zu verwenden ([Fehlerbehandlung](../tutorial/handling-errors.md#den-requestvalidationerror-body-verwenden){.internal-link target=_blank}).
+/// tip | "Tipp"
+
+Um dasselbe Problem zu lösen, ist es wahrscheinlich viel einfacher, den `body` in einem benutzerdefinierten Handler für `RequestValidationError` zu verwenden ([Fehlerbehandlung](../tutorial/handling-errors.md#den-requestvalidationerror-body-verwenden){.internal-link target=_blank}).
+
+Dieses Beispiel ist jedoch immer noch gültig und zeigt, wie mit den internen Komponenten interagiert wird.
- Dieses Beispiel ist jedoch immer noch gültig und zeigt, wie mit den internen Komponenten interagiert wird.
+///
Wir können denselben Ansatz auch verwenden, um in einem Exceptionhandler auf den Requestbody zuzugreifen.
* `description`: Die Beschreibung Ihrer API. Dies kann Markdown enthalten und wird in der Dokumentation angezeigt.
* `routes`: Eine Liste von Routen, dies sind alle registrierten *Pfadoperationen*. Sie stammen von `app.routes`.
-!!! info
- Der Parameter `summary` ist in OpenAPI 3.1.0 und höher verfügbar und wird von FastAPI 0.99.0 und höher unterstützt.
+/// info
+
+Der Parameter `summary` ist in OpenAPI 3.1.0 und höher verfügbar und wird von FastAPI 0.99.0 und höher unterstützt.
+
+///
## Überschreiben der Standardeinstellungen
Sie können normale FastAPI-*Pfadoperationen* mit GraphQL in derselben Anwendung kombinieren.
-!!! tip "Tipp"
- **GraphQL** löst einige sehr spezifische Anwendungsfälle.
+/// tip | "Tipp"
- Es hat **Vorteile** und **Nachteile** im Vergleich zu gängigen **Web-APIs**.
+**GraphQL** löst einige sehr spezifische Anwendungsfälle.
- Wiegen Sie ab, ob die **Vorteile** für Ihren Anwendungsfall die **Nachteile** ausgleichen. 🤓
+Es hat **Vorteile** und **Nachteile** im Vergleich zu gängigen **Web-APIs**.
+
+Wiegen Sie ab, ob die **Vorteile** für Ihren Anwendungsfall die **Nachteile** ausgleichen. 🤓
+
+///
## GraphQL-Bibliotheken
Das wurde von Starlette deprecated, aber wenn Sie Code haben, der das verwendet, können Sie einfach zu <a href="https://github.com/ciscorn/starlette-graphene3" class="external-link" target="_blank">starlette-graphene3</a> **migrieren**, welches denselben Anwendungsfall abdeckt und über eine **fast identische Schnittstelle** verfügt.
-!!! tip "Tipp"
- Wenn Sie GraphQL benötigen, würde ich Ihnen trotzdem empfehlen, sich <a href="https://strawberry.rocks/" class="external-link" target="_blank">Strawberry</a> anzuschauen, da es auf Typannotationen basiert, statt auf benutzerdefinierten Klassen und Typen.
+/// tip | "Tipp"
+
+Wenn Sie GraphQL benötigen, würde ich Ihnen trotzdem empfehlen, sich <a href="https://strawberry.rocks/" class="external-link" target="_blank">Strawberry</a> anzuschauen, da es auf Typannotationen basiert, statt auf benutzerdefinierten Klassen und Typen.
+
+///
## Mehr darüber lernen
Wenn etwas für Ihr Projekt interessant und nützlich erscheint, lesen Sie es, andernfalls überspringen Sie es einfach.
-!!! tip "Tipp"
- Wenn Sie strukturiert **FastAPI lernen** möchten (empfohlen), lesen Sie stattdessen Kapitel für Kapitel das [Tutorial – Benutzerhandbuch](../tutorial/index.md){.internal-link target=_blank}.
+/// tip | "Tipp"
+
+Wenn Sie strukturiert **FastAPI lernen** möchten (empfohlen), lesen Sie stattdessen Kapitel für Kapitel das [Tutorial – Benutzerhandbuch](../tutorial/index.md){.internal-link target=_blank}.
+
+///
Nehmen wir an, Sie haben ein Pydantic-Modell mit Defaultwerten wie dieses:
-=== "Python 3.10+"
+//// tab | Python 3.10+
- ```Python hl_lines="7"
- {!> ../../../docs_src/separate_openapi_schemas/tutorial001_py310.py[ln:1-7]!}
+```Python hl_lines="7"
+{!> ../../../docs_src/separate_openapi_schemas/tutorial001_py310.py[ln:1-7]!}
- # Code unterhalb weggelassen 👇
- ```
+# Code unterhalb weggelassen 👇
+```
- <details>
- <summary>👀 Vollständige Dateivorschau</summary>
+<details>
+<summary>👀 Vollständige Dateivorschau</summary>
- ```Python
- {!> ../../../docs_src/separate_openapi_schemas/tutorial001_py310.py!}
- ```
+```Python
+{!> ../../../docs_src/separate_openapi_schemas/tutorial001_py310.py!}
+```
- </details>
+</details>
-=== "Python 3.9+"
+////
- ```Python hl_lines="9"
- {!> ../../../docs_src/separate_openapi_schemas/tutorial001_py39.py[ln:1-9]!}
+//// tab | Python 3.9+
- # Code unterhalb weggelassen 👇
- ```
+```Python hl_lines="9"
+{!> ../../../docs_src/separate_openapi_schemas/tutorial001_py39.py[ln:1-9]!}
- <details>
- <summary>👀 Vollständige Dateivorschau</summary>
+# Code unterhalb weggelassen 👇
+```
- ```Python
- {!> ../../../docs_src/separate_openapi_schemas/tutorial001_py39.py!}
- ```
+<details>
+<summary>👀 Vollständige Dateivorschau</summary>
- </details>
+```Python
+{!> ../../../docs_src/separate_openapi_schemas/tutorial001_py39.py!}
+```
-=== "Python 3.8+"
+</details>
- ```Python hl_lines="9"
- {!> ../../../docs_src/separate_openapi_schemas/tutorial001.py[ln:1-9]!}
+////
- # Code unterhalb weggelassen 👇
- ```
+//// tab | Python 3.8+
- <details>
- <summary>👀 Vollständige Dateivorschau</summary>
+```Python hl_lines="9"
+{!> ../../../docs_src/separate_openapi_schemas/tutorial001.py[ln:1-9]!}
- ```Python
- {!> ../../../docs_src/separate_openapi_schemas/tutorial001.py!}
- ```
+# Code unterhalb weggelassen 👇
+```
- </details>
+<details>
+<summary>👀 Vollständige Dateivorschau</summary>
+
+```Python
+{!> ../../../docs_src/separate_openapi_schemas/tutorial001.py!}
+```
+
+</details>
+
+////
### Modell für Eingabe
Wenn Sie dieses Modell wie hier als Eingabe verwenden:
-=== "Python 3.10+"
+//// tab | Python 3.10+
+
+```Python hl_lines="14"
+{!> ../../../docs_src/separate_openapi_schemas/tutorial001_py310.py[ln:1-15]!}
- ```Python hl_lines="14"
- {!> ../../../docs_src/separate_openapi_schemas/tutorial001_py310.py[ln:1-15]!}
+# Code unterhalb weggelassen 👇
+```
- # Code unterhalb weggelassen 👇
- ```
+<details>
+<summary>👀 Vollständige Dateivorschau</summary>
- <details>
- <summary>👀 Vollständige Dateivorschau</summary>
+```Python
+{!> ../../../docs_src/separate_openapi_schemas/tutorial001_py310.py!}
+```
- ```Python
- {!> ../../../docs_src/separate_openapi_schemas/tutorial001_py310.py!}
- ```
+</details>
- </details>
+////
-=== "Python 3.9+"
+//// tab | Python 3.9+
- ```Python hl_lines="16"
- {!> ../../../docs_src/separate_openapi_schemas/tutorial001_py39.py[ln:1-17]!}
+```Python hl_lines="16"
+{!> ../../../docs_src/separate_openapi_schemas/tutorial001_py39.py[ln:1-17]!}
- # Code unterhalb weggelassen 👇
- ```
+# Code unterhalb weggelassen 👇
+```
- <details>
- <summary>👀 Vollständige Dateivorschau</summary>
+<details>
+<summary>👀 Vollständige Dateivorschau</summary>
- ```Python
- {!> ../../../docs_src/separate_openapi_schemas/tutorial001_py39.py!}
- ```
+```Python
+{!> ../../../docs_src/separate_openapi_schemas/tutorial001_py39.py!}
+```
- </details>
+</details>
-=== "Python 3.8+"
+////
- ```Python hl_lines="16"
- {!> ../../../docs_src/separate_openapi_schemas/tutorial001.py[ln:1-17]!}
+//// tab | Python 3.8+
- # Code unterhalb weggelassen 👇
- ```
+```Python hl_lines="16"
+{!> ../../../docs_src/separate_openapi_schemas/tutorial001.py[ln:1-17]!}
- <details>
- <summary>👀 Vollständige Dateivorschau</summary>
+# Code unterhalb weggelassen 👇
+```
- ```Python
- {!> ../../../docs_src/separate_openapi_schemas/tutorial001.py!}
- ```
+<details>
+<summary>👀 Vollständige Dateivorschau</summary>
- </details>
+```Python
+{!> ../../../docs_src/separate_openapi_schemas/tutorial001.py!}
+```
+
+</details>
+
+////
... dann ist das Feld `description` **nicht erforderlich**. Weil es den Defaultwert `None` hat.
Wenn Sie jedoch dasselbe Modell als Ausgabe verwenden, wie hier:
-=== "Python 3.10+"
+//// tab | Python 3.10+
+
+```Python hl_lines="19"
+{!> ../../../docs_src/separate_openapi_schemas/tutorial001_py310.py!}
+```
- ```Python hl_lines="19"
- {!> ../../../docs_src/separate_openapi_schemas/tutorial001_py310.py!}
- ```
+////
-=== "Python 3.9+"
+//// tab | Python 3.9+
- ```Python hl_lines="21"
- {!> ../../../docs_src/separate_openapi_schemas/tutorial001_py39.py!}
- ```
+```Python hl_lines="21"
+{!> ../../../docs_src/separate_openapi_schemas/tutorial001_py39.py!}
+```
-=== "Python 3.8+"
+////
- ```Python hl_lines="21"
- {!> ../../../docs_src/separate_openapi_schemas/tutorial001.py!}
- ```
+//// tab | Python 3.8+
+
+```Python hl_lines="21"
+{!> ../../../docs_src/separate_openapi_schemas/tutorial001.py!}
+```
+
+////
... dann, weil `description` einen Defaultwert hat, wird es, wenn Sie für dieses Feld **nichts zurückgeben**, immer noch diesen **Defaultwert** haben.
In diesem Fall können Sie diese Funktion in **FastAPI** mit dem Parameter `separate_input_output_schemas=False` deaktivieren.
-!!! info
- Unterstützung für `separate_input_output_schemas` wurde in FastAPI `0.102.0` hinzugefügt. 🤓
+/// info
+
+Unterstützung für `separate_input_output_schemas` wurde in FastAPI `0.102.0` hinzugefügt. 🤓
+
+///
+
+//// tab | Python 3.10+
+
+```Python hl_lines="10"
+{!> ../../../docs_src/separate_openapi_schemas/tutorial002_py310.py!}
+```
+
+////
-=== "Python 3.10+"
+//// tab | Python 3.9+
- ```Python hl_lines="10"
- {!> ../../../docs_src/separate_openapi_schemas/tutorial002_py310.py!}
- ```
+```Python hl_lines="12"
+{!> ../../../docs_src/separate_openapi_schemas/tutorial002_py39.py!}
+```
-=== "Python 3.9+"
+////
- ```Python hl_lines="12"
- {!> ../../../docs_src/separate_openapi_schemas/tutorial002_py39.py!}
- ```
+//// tab | Python 3.8+
-=== "Python 3.8+"
+```Python hl_lines="12"
+{!> ../../../docs_src/separate_openapi_schemas/tutorial002.py!}
+```
- ```Python hl_lines="12"
- {!> ../../../docs_src/separate_openapi_schemas/tutorial002.py!}
- ```
+////
### Gleiches Schema für Eingabe- und Ausgabemodelle in der Dokumentation
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.
+/// 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
Definieren wir zum Beispiel eine Variable, die eine `list` von `str` – eine Liste von Strings – sein soll.
-=== "Python 3.9+"
+//// tab | Python 3.9+
- Deklarieren Sie die Variable mit der gleichen Doppelpunkt-Syntax (`:`).
+Deklarieren Sie die Variable mit der gleichen Doppelpunkt-Syntax (`:`).
- Als Typ nehmen Sie `list`.
+Als Typ nehmen Sie `list`.
- Da die Liste ein Typ ist, welcher innere Typen enthält, werden diese von eckigen Klammern umfasst:
+Da die Liste ein Typ ist, welcher innere Typen enthält, werden diese von eckigen Klammern umfasst:
- ```Python hl_lines="1"
- {!> ../../../docs_src/python_types/tutorial006_py39.py!}
- ```
+```Python hl_lines="1"
+{!> ../../../docs_src/python_types/tutorial006_py39.py!}
+```
-=== "Python 3.8+"
+////
- Von `typing` importieren Sie `List` (mit Großbuchstaben `L`):
+//// tab | Python 3.8+
- ```Python hl_lines="1"
- {!> ../../../docs_src/python_types/tutorial006.py!}
- ```
+Von `typing` importieren Sie `List` (mit Großbuchstaben `L`):
- Deklarieren Sie die Variable mit der gleichen Doppelpunkt-Syntax (`:`).
+```Python hl_lines="1"
+{!> ../../../docs_src/python_types/tutorial006.py!}
+```
+
+Deklarieren Sie die Variable mit der gleichen Doppelpunkt-Syntax (`:`).
- Als Typ nehmen Sie das `List`, das Sie von `typing` importiert haben.
+Als Typ nehmen Sie das `List`, das Sie von `typing` importiert haben.
- Da die Liste ein Typ ist, welcher innere Typen enthält, werden diese von eckigen Klammern umfasst:
+Da die Liste ein Typ ist, welcher innere Typen enthält, werden diese von eckigen Klammern umfasst:
+
+```Python hl_lines="4"
+{!> ../../../docs_src/python_types/tutorial006.py!}
+```
- ```Python hl_lines="4"
- {!> ../../../docs_src/python_types/tutorial006.py!}
- ```
+////
-!!! tip "Tipp"
- Die inneren Typen in den eckigen Klammern werden als „Typ-Parameter“ bezeichnet.
+/// tip | "Tipp"
- In diesem Fall ist `str` der Typ-Parameter, der an `List` übergeben wird (oder `list` in Python 3.9 und darüber).
+Die inneren Typen in den eckigen Klammern werden als „Typ-Parameter“ bezeichnet.
+
+In diesem Fall ist `str` der Typ-Parameter, der an `List` übergeben wird (oder `list` in Python 3.9 und darüber).
+
+///
Das bedeutet: Die Variable `items` ist eine Liste – `list` – und jedes der Elemente in dieser Liste ist ein String – `str`.
-!!! tip "Tipp"
- Wenn Sie Python 3.9 oder höher verwenden, müssen Sie `List` nicht von `typing` importieren, Sie können stattdessen den regulären `list`-Typ verwenden.
+/// tip | "Tipp"
+
+Wenn Sie Python 3.9 oder höher verwenden, müssen Sie `List` nicht von `typing` importieren, Sie können stattdessen den regulären `list`-Typ verwenden.
+
+///
Auf diese Weise kann Ihr Editor Sie auch bei der Bearbeitung von Einträgen aus der Liste unterstützen:
Das Gleiche gilt für die Deklaration eines Tupels – `tuple` – und einer Menge – `set`:
-=== "Python 3.9+"
+//// tab | Python 3.9+
- ```Python hl_lines="1"
- {!> ../../../docs_src/python_types/tutorial007_py39.py!}
- ```
+```Python hl_lines="1"
+{!> ../../../docs_src/python_types/tutorial007_py39.py!}
+```
-=== "Python 3.8+"
+////
- ```Python hl_lines="1 4"
- {!> ../../../docs_src/python_types/tutorial007.py!}
- ```
+//// tab | Python 3.8+
+
+```Python hl_lines="1 4"
+{!> ../../../docs_src/python_types/tutorial007.py!}
+```
+
+////
Das bedeutet:
Der zweite Typ-Parameter ist für die Werte des `dict`:
-=== "Python 3.9+"
+//// tab | Python 3.9+
+
+```Python hl_lines="1"
+{!> ../../../docs_src/python_types/tutorial008_py39.py!}
+```
+
+////
- ```Python hl_lines="1"
- {!> ../../../docs_src/python_types/tutorial008_py39.py!}
- ```
+//// tab | Python 3.8+
-=== "Python 3.8+"
+```Python hl_lines="1 4"
+{!> ../../../docs_src/python_types/tutorial008.py!}
+```
- ```Python hl_lines="1 4"
- {!> ../../../docs_src/python_types/tutorial008.py!}
- ```
+////
Das bedeutet:
In Python 3.10 gibt es zusätzlich eine **neue Syntax**, die es erlaubt, die möglichen Typen getrennt von einem <abbr title='Allgemein: „oder“. In anderem Zusammenhang auch „Bitweises ODER“, aber letztere Bedeutung ist hier nicht relevant'>vertikalen Balken (`|`)</abbr> aufzulisten.
-=== "Python 3.10+"
+//// tab | Python 3.10+
- ```Python hl_lines="1"
- {!> ../../../docs_src/python_types/tutorial008b_py310.py!}
- ```
+```Python hl_lines="1"
+{!> ../../../docs_src/python_types/tutorial008b_py310.py!}
+```
+
+////
+
+//// tab | Python 3.8+
-=== "Python 3.8+"
+```Python hl_lines="1 4"
+{!> ../../../docs_src/python_types/tutorial008b.py!}
+```
- ```Python hl_lines="1 4"
- {!> ../../../docs_src/python_types/tutorial008b.py!}
- ```
+////
In beiden Fällen bedeutet das, dass `item` ein `int` oder ein `str` sein kann.
Das bedeutet auch, dass Sie in Python 3.10 `Something | None` verwenden können:
-=== "Python 3.10+"
+//// tab | Python 3.10+
+
+```Python hl_lines="1"
+{!> ../../../docs_src/python_types/tutorial009_py310.py!}
+```
+
+////
- ```Python hl_lines="1"
- {!> ../../../docs_src/python_types/tutorial009_py310.py!}
- ```
+//// tab | Python 3.8+
-=== "Python 3.8+"
+```Python hl_lines="1 4"
+{!> ../../../docs_src/python_types/tutorial009.py!}
+```
- ```Python hl_lines="1 4"
- {!> ../../../docs_src/python_types/tutorial009.py!}
- ```
+////
-=== "Python 3.8+ Alternative"
+//// tab | Python 3.8+ Alternative
- ```Python hl_lines="1 4"
- {!> ../../../docs_src/python_types/tutorial009b.py!}
- ```
+```Python hl_lines="1 4"
+{!> ../../../docs_src/python_types/tutorial009b.py!}
+```
+
+////
#### `Union` oder `Optional` verwenden?
Diese Typen, die Typ-Parameter in eckigen Klammern akzeptieren, werden **generische Typen** oder **Generics** genannt.
-=== "Python 3.10+"
+//// tab | Python 3.10+
+
+Sie können die eingebauten Typen als Generics verwenden (mit eckigen Klammern und Typen darin):
+
+* `list`
+* `tuple`
+* `set`
+* `dict`
- Sie können die eingebauten Typen als Generics verwenden (mit eckigen Klammern und Typen darin):
+Verwenden Sie für den Rest, wie unter Python 3.8, das `typing`-Modul:
- * `list`
- * `tuple`
- * `set`
- * `dict`
+* `Union`
+* `Optional` (so wie unter Python 3.8)
+* ... und andere.
- Verwenden Sie für den Rest, wie unter Python 3.8, das `typing`-Modul:
+In Python 3.10 können Sie als Alternative zu den Generics `Union` und `Optional` den <abbr title='Allgemein: „oder“. In anderem Zusammenhang auch „Bitweises ODER“, aber letztere Bedeutung ist hier nicht relevant'>vertikalen Balken (`|`)</abbr> verwenden, um Vereinigungen von Typen zu deklarieren, das ist besser und einfacher.
- * `Union`
- * `Optional` (so wie unter Python 3.8)
- * ... und andere.
+////
- In Python 3.10 können Sie als Alternative zu den Generics `Union` und `Optional` den <abbr title='Allgemein: „oder“. In anderem Zusammenhang auch „Bitweises ODER“, aber letztere Bedeutung ist hier nicht relevant'>vertikalen Balken (`|`)</abbr> verwenden, um Vereinigungen von Typen zu deklarieren, das ist besser und einfacher.
+//// tab | Python 3.9+
-=== "Python 3.9+"
+Sie können die eingebauten Typen als Generics verwenden (mit eckigen Klammern und Typen darin):
- Sie können die eingebauten Typen als Generics verwenden (mit eckigen Klammern und Typen darin):
+* `list`
+* `tuple`
+* `set`
+* `dict`
- * `list`
- * `tuple`
- * `set`
- * `dict`
+Verwenden Sie für den Rest, wie unter Python 3.8, das `typing`-Modul:
- Verwenden Sie für den Rest, wie unter Python 3.8, das `typing`-Modul:
+* `Union`
+* `Optional`
+* ... und andere.
- * `Union`
- * `Optional`
- * ... und andere.
+////
-=== "Python 3.8+"
+//// tab | Python 3.8+
- * `List`
- * `Tuple`
- * `Set`
- * `Dict`
- * `Union`
- * `Optional`
- * ... und andere.
+* `List`
+* `Tuple`
+* `Set`
+* `Dict`
+* `Union`
+* `Optional`
+* ... und andere.
+
+////
### Klassen als Typen
Ein Beispiel aus der offiziellen Pydantic Dokumentation:
-=== "Python 3.10+"
+//// tab | Python 3.10+
+
+```Python
+{!> ../../../docs_src/python_types/tutorial011_py310.py!}
+```
- ```Python
- {!> ../../../docs_src/python_types/tutorial011_py310.py!}
- ```
+////
-=== "Python 3.9+"
+//// tab | Python 3.9+
- ```Python
- {!> ../../../docs_src/python_types/tutorial011_py39.py!}
- ```
+```Python
+{!> ../../../docs_src/python_types/tutorial011_py39.py!}
+```
-=== "Python 3.8+"
+////
- ```Python
- {!> ../../../docs_src/python_types/tutorial011.py!}
- ```
+//// tab | Python 3.8+
-!!! info
- Um mehr über <a href="https://pydantic-docs.helpmanual.io/" class="external-link" target="_blank">Pydantic zu erfahren, schauen Sie sich dessen Dokumentation an</a>.
+```Python
+{!> ../../../docs_src/python_types/tutorial011.py!}
+```
+
+////
+
+/// info
+
+Um mehr über <a href="https://pydantic-docs.helpmanual.io/" class="external-link" target="_blank">Pydantic zu erfahren, schauen Sie sich dessen Dokumentation an</a>.
+
+///
**FastAPI** basiert vollständig auf Pydantic.
Viel mehr von all dem werden Sie in praktischer Anwendung im [Tutorial - Benutzerhandbuch](tutorial/index.md){.internal-link target=_blank} sehen.
-!!! tip "Tipp"
- Pydantic verhält sich speziell, wenn Sie `Optional` oder `Union[Etwas, None]` ohne einen Default-Wert verwenden. Sie können darüber in der Pydantic Dokumentation unter <a href="https://docs.pydantic.dev/2.3/usage/models/#required-fields" class="external-link" target="_blank">Required fields</a> mehr erfahren.
+/// tip | "Tipp"
+
+Pydantic verhält sich speziell, wenn Sie `Optional` oder `Union[Etwas, None]` ohne einen Default-Wert verwenden. Sie können darüber in der Pydantic Dokumentation unter <a href="https://docs.pydantic.dev/2.3/usage/models/#required-fields" class="external-link" target="_blank">Required fields</a> mehr erfahren.
+
+///
## Typhinweise mit Metadaten-Annotationen
Python bietet auch die Möglichkeit, **zusätzliche Metadaten** in Typhinweisen unterzubringen, mittels `Annotated`.
-=== "Python 3.9+"
+//// tab | Python 3.9+
+
+In Python 3.9 ist `Annotated` ein Teil der Standardbibliothek, Sie können es von `typing` importieren.
+
+```Python hl_lines="1 4"
+{!> ../../../docs_src/python_types/tutorial013_py39.py!}
+```
- In Python 3.9 ist `Annotated` ein Teil der Standardbibliothek, Sie können es von `typing` importieren.
+////
- ```Python hl_lines="1 4"
- {!> ../../../docs_src/python_types/tutorial013_py39.py!}
- ```
+//// tab | Python 3.8+
-=== "Python 3.8+"
+In Versionen niedriger als Python 3.9 importieren Sie `Annotated` von `typing_extensions`.
- In Versionen niedriger als Python 3.9 importieren Sie `Annotated` von `typing_extensions`.
+Es wird bereits mit **FastAPI** installiert sein.
- Es wird bereits mit **FastAPI** installiert sein.
+```Python hl_lines="1 4"
+{!> ../../../docs_src/python_types/tutorial013.py!}
+```
- ```Python hl_lines="1 4"
- {!> ../../../docs_src/python_types/tutorial013.py!}
- ```
+////
Python selbst macht nichts mit `Annotated`. Für Editoren und andere Tools ist der Typ immer noch `str`.
Später werden Sie sehen, wie **mächtig** es sein kann.
-!!! tip "Tipp"
- Der Umstand, dass es **Standard-Python** ist, bedeutet, dass Sie immer noch die **bestmögliche Entwickler-Erfahrung** in ihrem Editor haben, sowie mit den Tools, die Sie nutzen, um ihren Code zu analysieren, zu refaktorisieren, usw. ✨
+/// tip | "Tipp"
- Und ebenfalls, dass Ihr Code sehr kompatibel mit vielen anderen Python-Tools und -Bibliotheken sein wird. 🚀
+Der Umstand, dass es **Standard-Python** ist, bedeutet, dass Sie immer noch die **bestmögliche Entwickler-Erfahrung** in ihrem Editor haben, sowie mit den Tools, die Sie nutzen, um ihren Code zu analysieren, zu refaktorisieren, usw. ✨
+
+Und ebenfalls, dass Ihr Code sehr kompatibel mit vielen anderen Python-Tools und -Bibliotheken sein wird. 🚀
+
+///
## Typhinweise in **FastAPI**
Das Wichtigste ist, dass **FastAPI** durch die Verwendung von Standard-Python-Typen an einer einzigen Stelle (anstatt weitere Klassen, Dekoratoren usw. hinzuzufügen) einen Großteil der Arbeit für Sie erledigt.
-!!! info
- Wenn Sie bereits das ganze Tutorial durchgearbeitet haben und mehr über Typen erfahren wollen, dann ist eine gute Ressource <a href="https://mypy.readthedocs.io/en/latest/cheat_sheet_py3.html" class="external-link" target="_blank">der „Cheat Sheet“ von `mypy`</a>.
+/// info
+
+Wenn Sie bereits das ganze Tutorial durchgearbeitet haben und mehr über Typen erfahren wollen, dann ist eine gute Ressource <a href="https://mypy.readthedocs.io/en/latest/cheat_sheet_py3.html" class="external-link" target="_blank">der „Cheat Sheet“ von `mypy`</a>.
+
+///
Wenn Sie **FastAPI** lernen möchten, ist es viel besser, das [FastAPI-Tutorial](https://fastapi.tiangolo.com/tutorial/) zu lesen.
-!!! note "Hinweis Deutsche Übersetzung"
- Die nachfolgende API wird aus der Quelltext-Dokumentation erstellt, daher sind nur die Einleitungen auf Deutsch.
+/// note | "Hinweis Deutsche Übersetzung"
+
+Die nachfolgende API wird aus der Quelltext-Dokumentation erstellt, daher sind nur die Einleitungen auf Deutsch.
+
+///
from fastapi import Request
```
-!!! tip "Tipp"
- Wenn Sie Abhängigkeiten definieren möchten, die sowohl mit HTTP als auch mit WebSockets kompatibel sein sollen, können Sie einen Parameter definieren, der eine `HTTPConnection` anstelle eines `Request` oder eines `WebSocket` akzeptiert.
+/// tip | "Tipp"
+
+Wenn Sie Abhängigkeiten definieren möchten, die sowohl mit HTTP als auch mit WebSockets kompatibel sein sollen, können Sie einen Parameter definieren, der eine `HTTPConnection` anstelle eines `Request` oder eines `WebSocket` akzeptiert.
+
+///
::: fastapi.Request
from fastapi import WebSocket
```
-!!! tip "Tipp"
- Wenn Sie Abhängigkeiten definieren möchten, die sowohl mit HTTP als auch mit WebSockets kompatibel sein sollen, können Sie einen Parameter definieren, der eine `HTTPConnection` anstelle eines `Request` oder eines `WebSocket` akzeptiert.
+/// tip | "Tipp"
+
+Wenn Sie Abhängigkeiten definieren möchten, die sowohl mit HTTP als auch mit WebSockets kompatibel sein sollen, können Sie einen Parameter definieren, der eine `HTTPConnection` anstelle eines `Request` oder eines `WebSocket` akzeptiert.
+
+///
::: fastapi.WebSocket
options:
**FastAPI** weiß, was jeweils zu tun ist und wie dasselbe Objekt wiederverwendet werden kann, sodass alle Hintergrundtasks zusammengeführt und anschließend im Hintergrund ausgeführt werden:
-=== "Python 3.10+"
+//// tab | Python 3.10+
- ```Python hl_lines="13 15 22 25"
- {!> ../../../docs_src/background_tasks/tutorial002_an_py310.py!}
- ```
+```Python hl_lines="13 15 22 25"
+{!> ../../../docs_src/background_tasks/tutorial002_an_py310.py!}
+```
+
+////
+
+//// tab | Python 3.9+
+
+```Python hl_lines="13 15 22 25"
+{!> ../../../docs_src/background_tasks/tutorial002_an_py39.py!}
+```
+
+////
+
+//// tab | Python 3.8+
-=== "Python 3.9+"
+```Python hl_lines="14 16 23 26"
+{!> ../../../docs_src/background_tasks/tutorial002_an.py!}
+```
+
+////
- ```Python hl_lines="13 15 22 25"
- {!> ../../../docs_src/background_tasks/tutorial002_an_py39.py!}
- ```
+//// tab | Python 3.10+ nicht annotiert
-=== "Python 3.8+"
+/// tip | "Tipp"
- ```Python hl_lines="14 16 23 26"
- {!> ../../../docs_src/background_tasks/tutorial002_an.py!}
- ```
+Bevorzugen Sie die `Annotated`-Version, falls möglich.
-=== "Python 3.10+ nicht annotiert"
+///
+
+```Python hl_lines="11 13 20 23"
+{!> ../../../docs_src/background_tasks/tutorial002_py310.py!}
+```
- !!! tip "Tipp"
- Bevorzugen Sie die `Annotated`-Version, falls möglich.
+////
- ```Python hl_lines="11 13 20 23"
- {!> ../../../docs_src/background_tasks/tutorial002_py310.py!}
- ```
+//// tab | Python 3.8+ nicht annotiert
-=== "Python 3.8+ nicht annotiert"
+/// tip | "Tipp"
- !!! tip "Tipp"
- Bevorzugen Sie die `Annotated`-Version, falls möglich.
+Bevorzugen Sie die `Annotated`-Version, falls möglich.
+
+///
+
+```Python hl_lines="13 15 22 25"
+{!> ../../../docs_src/background_tasks/tutorial002.py!}
+```
- ```Python hl_lines="13 15 22 25"
- {!> ../../../docs_src/background_tasks/tutorial002.py!}
- ```
+////
In obigem Beispiel werden die Nachrichten, *nachdem* die Response gesendet wurde, in die Datei `log.txt` geschrieben.
**FastAPI** bietet ein praktisches Werkzeug zur Strukturierung Ihrer Anwendung bei gleichzeitiger Wahrung der Flexibilität.
-!!! info
- Wenn Sie von Flask kommen, wäre dies das Äquivalent zu Flasks Blueprints.
+/// info
+
+Wenn Sie von Flask kommen, wäre dies das Äquivalent zu Flasks Blueprints.
+
+///
## Eine Beispiel-Dateistruktur
│ └── admin.py
```
-!!! tip "Tipp"
- Es gibt mehrere `__init__.py`-Dateien: eine in jedem Verzeichnis oder Unterverzeichnis.
+/// tip | "Tipp"
+
+Es gibt mehrere `__init__.py`-Dateien: eine in jedem Verzeichnis oder Unterverzeichnis.
- Das ermöglicht den Import von Code aus einer Datei in eine andere.
+Das ermöglicht den Import von Code aus einer Datei in eine andere.
- In `app/main.py` könnten Sie beispielsweise eine Zeile wie diese haben:
+In `app/main.py` könnten Sie beispielsweise eine Zeile wie diese haben:
+
+```
+from app.routers import items
+```
- ```
- from app.routers import items
- ```
+///
* Das Verzeichnis `app` enthält alles. Und es hat eine leere Datei `app/__init__.py`, es handelt sich also um ein „Python-Package“ (eine Sammlung von „Python-Modulen“): `app`.
* Es enthält eine Datei `app/main.py`. Da sie sich in einem Python-Package (einem Verzeichnis mit einer Datei `__init__.py`) befindet, ist sie ein „Modul“ dieses Packages: `app.main`.
Alle die gleichen `parameters`, `responses`, `dependencies`, `tags`, usw.
-!!! tip "Tipp"
- In diesem Beispiel heißt die Variable `router`, aber Sie können ihr einen beliebigen Namen geben.
+/// tip | "Tipp"
+
+In diesem Beispiel heißt die Variable `router`, aber Sie können ihr einen beliebigen Namen geben.
+
+///
Wir werden diesen `APIRouter` in die Hauptanwendung `FastAPI` einbinden, aber zuerst kümmern wir uns um die Abhängigkeiten und einen anderen `APIRouter`.
Wir werden nun eine einfache Abhängigkeit verwenden, um einen benutzerdefinierten `X-Token`-Header zu lesen:
-=== "Python 3.9+"
+//// tab | Python 3.9+
+
+```Python hl_lines="3 6-8" title="app/dependencies.py"
+{!> ../../../docs_src/bigger_applications/app_an_py39/dependencies.py!}
+```
- ```Python hl_lines="3 6-8" title="app/dependencies.py"
- {!> ../../../docs_src/bigger_applications/app_an_py39/dependencies.py!}
- ```
+////
-=== "Python 3.8+"
+//// tab | Python 3.8+
- ```Python hl_lines="1 5-7" title="app/dependencies.py"
- {!> ../../../docs_src/bigger_applications/app_an/dependencies.py!}
- ```
+```Python hl_lines="1 5-7" title="app/dependencies.py"
+{!> ../../../docs_src/bigger_applications/app_an/dependencies.py!}
+```
-=== "Python 3.8+ nicht annotiert"
+////
- !!! tip "Tipp"
- Bevorzugen Sie die `Annotated`-Version, falls möglich.
+//// tab | Python 3.8+ nicht annotiert
- ```Python hl_lines="1 4-6" title="app/dependencies.py"
- {!> ../../../docs_src/bigger_applications/app/dependencies.py!}
- ```
+/// tip | "Tipp"
-!!! tip "Tipp"
- Um dieses Beispiel zu vereinfachen, verwenden wir einen erfundenen Header.
+Bevorzugen Sie die `Annotated`-Version, falls möglich.
- Aber in der Praxis werden Sie mit den integrierten [Sicherheits-Werkzeugen](security/index.md){.internal-link target=_blank} bessere Ergebnisse erzielen.
+///
+
+```Python hl_lines="1 4-6" title="app/dependencies.py"
+{!> ../../../docs_src/bigger_applications/app/dependencies.py!}
+```
+
+////
+
+/// tip | "Tipp"
+
+Um dieses Beispiel zu vereinfachen, verwenden wir einen erfundenen Header.
+
+Aber in der Praxis werden Sie mit den integrierten [Sicherheits-Werkzeugen](security/index.md){.internal-link target=_blank} bessere Ergebnisse erzielen.
+
+///
## Ein weiteres Modul mit `APIRouter`.
Und wir können eine Liste von `dependencies` hinzufügen, die allen *Pfadoperationen* im Router hinzugefügt und für jeden an sie gerichteten Request ausgeführt/aufgelöst werden.
-!!! tip "Tipp"
- Beachten Sie, dass ähnlich wie bei [Abhängigkeiten in *Pfadoperation-Dekoratoren*](dependencies/dependencies-in-path-operation-decorators.md){.internal-link target=_blank} kein Wert an Ihre *Pfadoperation-Funktion* übergeben wird.
+/// tip | "Tipp"
+
+Beachten Sie, dass ähnlich wie bei [Abhängigkeiten in *Pfadoperation-Dekoratoren*](dependencies/dependencies-in-path-operation-decorators.md){.internal-link target=_blank} kein Wert an Ihre *Pfadoperation-Funktion* übergeben wird.
+
+///
Das Endergebnis ist, dass die Pfade für diese Artikel jetzt wie folgt lauten:
* Zuerst werden die Router-Abhängigkeiten ausgeführt, dann die [`dependencies` im Dekorator](dependencies/dependencies-in-path-operation-decorators.md){.internal-link target=_blank} und dann die normalen Parameterabhängigkeiten.
* Sie können auch [`Security`-Abhängigkeiten mit `scopes`](../advanced/security/oauth2-scopes.md){.internal-link target=_blank} hinzufügen.
-!!! tip "Tipp"
- `dependencies` im `APIRouter` können beispielsweise verwendet werden, um eine Authentifizierung für eine ganze Gruppe von *Pfadoperationen* zu erfordern. Selbst wenn die Abhängigkeiten nicht jeder einzeln hinzugefügt werden.
+/// tip | "Tipp"
+
+`dependencies` im `APIRouter` können beispielsweise verwendet werden, um eine Authentifizierung für eine ganze Gruppe von *Pfadoperationen* zu erfordern. Selbst wenn die Abhängigkeiten nicht jeder einzeln hinzugefügt werden.
+
+///
+
+/// check
-!!! check
- Die Parameter `prefix`, `tags`, `responses` und `dependencies` sind (wie in vielen anderen Fällen) nur ein Feature von **FastAPI**, um Ihnen dabei zu helfen, Codeverdoppelung zu vermeiden.
+Die Parameter `prefix`, `tags`, `responses` und `dependencies` sind (wie in vielen anderen Fällen) nur ein Feature von **FastAPI**, um Ihnen dabei zu helfen, Codeverdoppelung zu vermeiden.
+
+///
### Die Abhängigkeiten importieren
#### Wie relative Importe funktionieren
-!!! tip "Tipp"
- Wenn Sie genau wissen, wie Importe funktionieren, fahren Sie mit dem nächsten Abschnitt unten fort.
+/// tip | "Tipp"
+
+Wenn Sie genau wissen, wie Importe funktionieren, fahren Sie mit dem nächsten Abschnitt unten fort.
+
+///
Ein einzelner Punkt `.`, wie in:
{!../../../docs_src/bigger_applications/app/routers/items.py!}
```
-!!! tip "Tipp"
- Diese letzte Pfadoperation wird eine Kombination von Tags haben: `["items", "custom"]`.
+/// tip | "Tipp"
- Und sie wird auch beide Responses in der Dokumentation haben, eine für `404` und eine für `403`.
+Diese letzte Pfadoperation wird eine Kombination von Tags haben: `["items", "custom"]`.
+
+Und sie wird auch beide Responses in der Dokumentation haben, eine für `404` und eine für `403`.
+
+///
## Das Haupt-`FastAPI`.
from app.routers import items, users
```
-!!! info
- Die erste Version ist ein „relativer Import“:
+/// info
- ```Python
- from .routers import items, users
- ```
+Die erste Version ist ein „relativer Import“:
- Die zweite Version ist ein „absoluter Import“:
+```Python
+from .routers import items, users
+```
+
+Die zweite Version ist ein „absoluter Import“:
+
+```Python
+from app.routers import items, users
+```
- ```Python
- from app.routers import items, users
- ```
+Um mehr über Python-Packages und -Module zu erfahren, lesen Sie <a href="https://docs.python.org/3/tutorial/modules.html" class="external-link" target="_blank">die offizielle Python-Dokumentation über Module</a>.
- Um mehr über Python-Packages und -Module zu erfahren, lesen Sie <a href="https://docs.python.org/3/tutorial/modules.html" class="external-link" target="_blank">die offizielle Python-Dokumentation über Module</a>.
+///
### Namenskollisionen vermeiden
{!../../../docs_src/bigger_applications/app/main.py!}
```
-!!! info
- `users.router` enthält den `APIRouter` in der Datei `app/routers/users.py`.
+/// info
+
+`users.router` enthält den `APIRouter` in der Datei `app/routers/users.py`.
- Und `items.router` enthält den `APIRouter` in der Datei `app/routers/items.py`.
+Und `items.router` enthält den `APIRouter` in der Datei `app/routers/items.py`.
+
+///
Mit `app.include_router()` können wir jeden `APIRouter` zur Hauptanwendung `FastAPI` hinzufügen.
Es wird alle Routen von diesem Router als Teil von dieser inkludieren.
-!!! note "Technische Details"
- Tatsächlich wird intern eine *Pfadoperation* für jede *Pfadoperation* erstellt, die im `APIRouter` deklariert wurde.
+/// note | "Technische Details"
+
+Tatsächlich wird intern eine *Pfadoperation* für jede *Pfadoperation* erstellt, die im `APIRouter` deklariert wurde.
+
+Hinter den Kulissen wird es also tatsächlich so funktionieren, als ob alles dieselbe einzige Anwendung wäre.
- Hinter den Kulissen wird es also tatsächlich so funktionieren, als ob alles dieselbe einzige Anwendung wäre.
+///
-!!! check
- Bei der Einbindung von Routern müssen Sie sich keine Gedanken über die Performanz machen.
+/// check
- Dies dauert Mikrosekunden und geschieht nur beim Start.
+Bei der Einbindung von Routern müssen Sie sich keine Gedanken über die Performanz machen.
- Es hat also keinen Einfluss auf die Leistung. ⚡
+Dies dauert Mikrosekunden und geschieht nur beim Start.
+
+Es hat also keinen Einfluss auf die Leistung. ⚡
+
+///
### Einen `APIRouter` mit benutzerdefinierten `prefix`, `tags`, `responses` und `dependencies` einfügen
und es wird korrekt funktionieren, zusammen mit allen anderen *Pfadoperationen*, die mit `app.include_router()` hinzugefügt wurden.
-!!! info "Sehr technische Details"
- **Hinweis**: Dies ist ein sehr technisches Detail, das Sie wahrscheinlich **einfach überspringen** können.
+/// info | "Sehr technische Details"
+
+**Hinweis**: Dies ist ein sehr technisches Detail, das Sie wahrscheinlich **einfach überspringen** können.
+
+---
- ---
+Die `APIRouter` sind nicht „gemountet“, sie sind nicht vom Rest der Anwendung isoliert.
- Die `APIRouter` sind nicht „gemountet“, sie sind nicht vom Rest der Anwendung isoliert.
+Das liegt daran, dass wir deren *Pfadoperationen* in das OpenAPI-Schema und die Benutzeroberflächen einbinden möchten.
- Das liegt daran, dass wir deren *Pfadoperationen* in das OpenAPI-Schema und die Benutzeroberflächen einbinden möchten.
+Da wir sie nicht einfach isolieren und unabhängig vom Rest „mounten“ können, werden die *Pfadoperationen* „geklont“ (neu erstellt) und nicht direkt einbezogen.
- Da wir sie nicht einfach isolieren und unabhängig vom Rest „mounten“ können, werden die *Pfadoperationen* „geklont“ (neu erstellt) und nicht direkt einbezogen.
+///
## Es in der automatischen API-Dokumentation ansehen
Importieren Sie es zuerst:
-=== "Python 3.10+"
+//// tab | Python 3.10+
- ```Python hl_lines="4"
- {!> ../../../docs_src/body_fields/tutorial001_an_py310.py!}
- ```
+```Python hl_lines="4"
+{!> ../../../docs_src/body_fields/tutorial001_an_py310.py!}
+```
-=== "Python 3.9+"
+////
- ```Python hl_lines="4"
- {!> ../../../docs_src/body_fields/tutorial001_an_py39.py!}
- ```
+//// tab | Python 3.9+
-=== "Python 3.8+"
+```Python hl_lines="4"
+{!> ../../../docs_src/body_fields/tutorial001_an_py39.py!}
+```
- ```Python hl_lines="4"
- {!> ../../../docs_src/body_fields/tutorial001_an.py!}
- ```
+////
-=== "Python 3.10+ nicht annotiert"
+//// tab | Python 3.8+
- !!! tip "Tipp"
- Bevorzugen Sie die `Annotated`-Version, falls möglich.
+```Python hl_lines="4"
+{!> ../../../docs_src/body_fields/tutorial001_an.py!}
+```
- ```Python hl_lines="2"
- {!> ../../../docs_src/body_fields/tutorial001_py310.py!}
- ```
+////
-=== "Python 3.8+ nicht annotiert"
+//// tab | Python 3.10+ nicht annotiert
- !!! tip "Tipp"
- Bevorzugen Sie die `Annotated`-Version, falls möglich.
+/// tip | "Tipp"
- ```Python hl_lines="4"
- {!> ../../../docs_src/body_fields/tutorial001.py!}
- ```
+Bevorzugen Sie die `Annotated`-Version, falls möglich.
-!!! warning "Achtung"
- Beachten Sie, dass `Field` direkt von `pydantic` importiert wird, nicht von `fastapi`, wie die anderen (`Query`, `Path`, `Body`, usw.)
+///
+
+```Python hl_lines="2"
+{!> ../../../docs_src/body_fields/tutorial001_py310.py!}
+```
+
+////
+
+//// tab | Python 3.8+ nicht annotiert
+
+/// tip | "Tipp"
+
+Bevorzugen Sie die `Annotated`-Version, falls möglich.
+
+///
+
+```Python hl_lines="4"
+{!> ../../../docs_src/body_fields/tutorial001.py!}
+```
+
+////
+
+/// warning | "Achtung"
+
+Beachten Sie, dass `Field` direkt von `pydantic` importiert wird, nicht von `fastapi`, wie die anderen (`Query`, `Path`, `Body`, usw.)
+
+///
## Modellattribute deklarieren
Dann können Sie `Field` mit Modellattributen deklarieren:
-=== "Python 3.10+"
+//// tab | Python 3.10+
+
+```Python hl_lines="11-14"
+{!> ../../../docs_src/body_fields/tutorial001_an_py310.py!}
+```
+
+////
- ```Python hl_lines="11-14"
- {!> ../../../docs_src/body_fields/tutorial001_an_py310.py!}
- ```
+//// tab | Python 3.9+
-=== "Python 3.9+"
+```Python hl_lines="11-14"
+{!> ../../../docs_src/body_fields/tutorial001_an_py39.py!}
+```
- ```Python hl_lines="11-14"
- {!> ../../../docs_src/body_fields/tutorial001_an_py39.py!}
- ```
+////
-=== "Python 3.8+"
+//// tab | Python 3.8+
- ```Python hl_lines="12-15"
- {!> ../../../docs_src/body_fields/tutorial001_an.py!}
- ```
+```Python hl_lines="12-15"
+{!> ../../../docs_src/body_fields/tutorial001_an.py!}
+```
-=== "Python 3.10+ nicht annotiert"
+////
- !!! tip "Tipp"
- Bevorzugen Sie die `Annotated`-Version, falls möglich.
+//// tab | Python 3.10+ nicht annotiert
- ```Python hl_lines="9-12"
- {!> ../../../docs_src/body_fields/tutorial001_py310.py!}
- ```
+/// tip | "Tipp"
-=== "Python 3.8+ nicht annotiert"
+Bevorzugen Sie die `Annotated`-Version, falls möglich.
- !!! tip "Tipp"
- Bevorzugen Sie die `Annotated`-Version, falls möglich.
+///
- ```Python hl_lines="11-14"
- {!> ../../../docs_src/body_fields/tutorial001.py!}
- ```
+```Python hl_lines="9-12"
+{!> ../../../docs_src/body_fields/tutorial001_py310.py!}
+```
+
+////
+
+//// tab | Python 3.8+ nicht annotiert
+
+/// tip | "Tipp"
+
+Bevorzugen Sie die `Annotated`-Version, falls möglich.
+
+///
+
+```Python hl_lines="11-14"
+{!> ../../../docs_src/body_fields/tutorial001.py!}
+```
+
+////
`Field` funktioniert genauso wie `Query`, `Path` und `Body`, es hat die gleichen Parameter, usw.
-!!! note "Technische Details"
- Tatsächlich erstellen `Query`, `Path` und andere, die sie kennenlernen werden, Instanzen von Unterklassen einer allgemeinen Klasse `Param`, die ihrerseits eine Unterklasse von Pydantics `FieldInfo`-Klasse ist.
+/// note | "Technische Details"
- Und Pydantics `Field` gibt ebenfalls eine Instanz von `FieldInfo` zurück.
+Tatsächlich erstellen `Query`, `Path` und andere, die sie kennenlernen werden, Instanzen von Unterklassen einer allgemeinen Klasse `Param`, die ihrerseits eine Unterklasse von Pydantics `FieldInfo`-Klasse ist.
- `Body` gibt auch Instanzen einer Unterklasse von `FieldInfo` zurück. Und später werden Sie andere sehen, die Unterklassen der `Body`-Klasse sind.
+Und Pydantics `Field` gibt ebenfalls eine Instanz von `FieldInfo` zurück.
- Denken Sie daran, dass `Query`, `Path` und andere von `fastapi` tatsächlich Funktionen sind, die spezielle Klassen zurückgeben.
+`Body` gibt auch Instanzen einer Unterklasse von `FieldInfo` zurück. Und später werden Sie andere sehen, die Unterklassen der `Body`-Klasse sind.
-!!! tip "Tipp"
- Beachten Sie, dass jedes Modellattribut mit einem Typ, Defaultwert und `Field` die gleiche Struktur hat wie ein Parameter einer Pfadoperation-Funktion, nur mit `Field` statt `Path`, `Query`, `Body`.
+Denken Sie daran, dass `Query`, `Path` und andere von `fastapi` tatsächlich Funktionen sind, die spezielle Klassen zurückgeben.
+
+///
+
+/// tip | "Tipp"
+
+Beachten Sie, dass jedes Modellattribut mit einem Typ, Defaultwert und `Field` die gleiche Struktur hat wie ein Parameter einer Pfadoperation-Funktion, nur mit `Field` statt `Path`, `Query`, `Body`.
+
+///
## Zusätzliche Information hinzufügen
Sie werden später mehr darüber lernen, wie man zusätzliche Information unterbringt, wenn Sie lernen, Beispiele zu deklarieren.
-!!! warning "Achtung"
- Extra-Schlüssel, die `Field` überreicht werden, werden auch im resultierenden OpenAPI-Schema Ihrer Anwendung gelistet. Da diese Schlüssel nicht notwendigerweise Teil der OpenAPI-Spezifikation sind, könnten einige OpenAPI-Tools, wie etwa [der OpenAPI-Validator](https://validator.swagger.io/), nicht mit Ihrem generierten Schema funktionieren.
+/// warning | "Achtung"
+
+Extra-Schlüssel, die `Field` überreicht werden, werden auch im resultierenden OpenAPI-Schema Ihrer Anwendung gelistet. Da diese Schlüssel nicht notwendigerweise Teil der OpenAPI-Spezifikation sind, könnten einige OpenAPI-Tools, wie etwa [der OpenAPI-Validator](https://validator.swagger.io/), nicht mit Ihrem generierten Schema funktionieren.
+
+///
## Zusammenfassung
Und Sie können auch Body-Parameter als optional kennzeichnen, indem Sie den Defaultwert auf `None` setzen:
-=== "Python 3.10+"
+//// tab | Python 3.10+
- ```Python hl_lines="18-20"
- {!> ../../../docs_src/body_multiple_params/tutorial001_an_py310.py!}
- ```
+```Python hl_lines="18-20"
+{!> ../../../docs_src/body_multiple_params/tutorial001_an_py310.py!}
+```
+
+////
-=== "Python 3.9+"
+//// tab | Python 3.9+
- ```Python hl_lines="18-20"
- {!> ../../../docs_src/body_multiple_params/tutorial001_an_py39.py!}
- ```
+```Python hl_lines="18-20"
+{!> ../../../docs_src/body_multiple_params/tutorial001_an_py39.py!}
+```
-=== "Python 3.8+"
+////
- ```Python hl_lines="19-21"
- {!> ../../../docs_src/body_multiple_params/tutorial001_an.py!}
- ```
+//// tab | Python 3.8+
+
+```Python hl_lines="19-21"
+{!> ../../../docs_src/body_multiple_params/tutorial001_an.py!}
+```
-=== "Python 3.10+ nicht annotiert"
+////
- !!! tip "Tipp"
- Bevorzugen Sie die `Annotated`-Version, falls möglich.
+//// tab | Python 3.10+ nicht annotiert
- ```Python hl_lines="17-19"
- {!> ../../../docs_src/body_multiple_params/tutorial001_py310.py!}
- ```
+/// tip | "Tipp"
+
+Bevorzugen Sie die `Annotated`-Version, falls möglich.
+
+///
+
+```Python hl_lines="17-19"
+{!> ../../../docs_src/body_multiple_params/tutorial001_py310.py!}
+```
-=== "Python 3.8+ nicht annotiert"
+////
- !!! tip "Tipp"
- Bevorzugen Sie die `Annotated`-Version, falls möglich.
+//// tab | Python 3.8+ nicht annotiert
- ```Python hl_lines="19-21"
- {!> ../../../docs_src/body_multiple_params/tutorial001.py!}
- ```
+/// tip | "Tipp"
-!!! note "Hinweis"
- Beachten Sie, dass in diesem Fall das `item`, welches vom Body genommen wird, optional ist. Da es `None` als Defaultwert hat.
+Bevorzugen Sie die `Annotated`-Version, falls möglich.
+
+///
+
+```Python hl_lines="19-21"
+{!> ../../../docs_src/body_multiple_params/tutorial001.py!}
+```
+
+////
+
+/// note | "Hinweis"
+
+Beachten Sie, dass in diesem Fall das `item`, welches vom Body genommen wird, optional ist. Da es `None` als Defaultwert hat.
+
+///
## Mehrere Body-Parameter
Aber Sie können auch mehrere Body-Parameter deklarieren, z. B. `item` und `user`:
-=== "Python 3.10+"
+//// tab | Python 3.10+
- ```Python hl_lines="20"
- {!> ../../../docs_src/body_multiple_params/tutorial002_py310.py!}
- ```
+```Python hl_lines="20"
+{!> ../../../docs_src/body_multiple_params/tutorial002_py310.py!}
+```
-=== "Python 3.8+"
+////
- ```Python hl_lines="22"
- {!> ../../../docs_src/body_multiple_params/tutorial002.py!}
- ```
+//// tab | Python 3.8+
+
+```Python hl_lines="22"
+{!> ../../../docs_src/body_multiple_params/tutorial002.py!}
+```
+
+////
In diesem Fall wird **FastAPI** bemerken, dass es mehr als einen Body-Parameter in der Funktion gibt (zwei Parameter, die Pydantic-Modelle sind).
}
```
-!!! note "Hinweis"
- Beachten Sie, dass, obwohl `item` wie zuvor deklariert wurde, es nun unter einem Schlüssel `item` im Body erwartet wird.
+/// note | "Hinweis"
+
+Beachten Sie, dass, obwohl `item` wie zuvor deklariert wurde, es nun unter einem Schlüssel `item` im Body erwartet wird.
+
+///
**FastAPI** wird die automatische Konvertierung des Requests übernehmen, sodass der Parameter `item` seinen spezifischen Inhalt bekommt, genau so wie der Parameter `user`.
Aber Sie können **FastAPI** instruieren, ihn als weiteren Body-Schlüssel zu erkennen, indem Sie `Body` verwenden:
-=== "Python 3.10+"
+//// tab | Python 3.10+
+
+```Python hl_lines="23"
+{!> ../../../docs_src/body_multiple_params/tutorial003_an_py310.py!}
+```
+
+////
+
+//// tab | Python 3.9+
+
+```Python hl_lines="23"
+{!> ../../../docs_src/body_multiple_params/tutorial003_an_py39.py!}
+```
+
+////
+
+//// tab | Python 3.8+
+
+```Python hl_lines="24"
+{!> ../../../docs_src/body_multiple_params/tutorial003_an.py!}
+```
+
+////
- ```Python hl_lines="23"
- {!> ../../../docs_src/body_multiple_params/tutorial003_an_py310.py!}
- ```
+//// tab | Python 3.10+ nicht annotiert
-=== "Python 3.9+"
+/// tip | "Tipp"
- ```Python hl_lines="23"
- {!> ../../../docs_src/body_multiple_params/tutorial003_an_py39.py!}
- ```
+Bevorzugen Sie die `Annotated`-Version, falls möglich.
-=== "Python 3.8+"
+///
- ```Python hl_lines="24"
- {!> ../../../docs_src/body_multiple_params/tutorial003_an.py!}
- ```
+```Python hl_lines="20"
+{!> ../../../docs_src/body_multiple_params/tutorial003_py310.py!}
+```
+
+////
-=== "Python 3.10+ nicht annotiert"
+//// tab | Python 3.8+ nicht annotiert
- !!! tip "Tipp"
- Bevorzugen Sie die `Annotated`-Version, falls möglich.
+/// tip | "Tipp"
- ```Python hl_lines="20"
- {!> ../../../docs_src/body_multiple_params/tutorial003_py310.py!}
- ```
+Bevorzugen Sie die `Annotated`-Version, falls möglich.
-=== "Python 3.8+ nicht annotiert"
+///
- !!! tip "Tipp"
- Bevorzugen Sie die `Annotated`-Version, falls möglich.
+```Python hl_lines="22"
+{!> ../../../docs_src/body_multiple_params/tutorial003.py!}
+```
- ```Python hl_lines="22"
- {!> ../../../docs_src/body_multiple_params/tutorial003.py!}
- ```
+////
In diesem Fall erwartet **FastAPI** einen Body wie:
Zum Beispiel:
-=== "Python 3.10+"
+//// tab | Python 3.10+
- ```Python hl_lines="27"
- {!> ../../../docs_src/body_multiple_params/tutorial004_an_py310.py!}
- ```
+```Python hl_lines="27"
+{!> ../../../docs_src/body_multiple_params/tutorial004_an_py310.py!}
+```
-=== "Python 3.9+"
+////
- ```Python hl_lines="27"
- {!> ../../../docs_src/body_multiple_params/tutorial004_an_py39.py!}
- ```
+//// tab | Python 3.9+
-=== "Python 3.8+"
+```Python hl_lines="27"
+{!> ../../../docs_src/body_multiple_params/tutorial004_an_py39.py!}
+```
+
+////
+
+//// tab | Python 3.8+
+
+```Python hl_lines="28"
+{!> ../../../docs_src/body_multiple_params/tutorial004_an.py!}
+```
- ```Python hl_lines="28"
- {!> ../../../docs_src/body_multiple_params/tutorial004_an.py!}
- ```
+////
-=== "Python 3.10+ nicht annotiert"
+//// tab | Python 3.10+ nicht annotiert
- !!! tip "Tipp"
- Bevorzugen Sie die `Annotated`-Version, falls möglich.
+/// tip | "Tipp"
- ```Python hl_lines="25"
- {!> ../../../docs_src/body_multiple_params/tutorial004_py310.py!}
- ```
+Bevorzugen Sie die `Annotated`-Version, falls möglich.
-=== "Python 3.8+ nicht annotiert"
+///
- !!! tip "Tipp"
- Bevorzugen Sie die `Annotated`-Version, falls möglich.
+```Python hl_lines="25"
+{!> ../../../docs_src/body_multiple_params/tutorial004_py310.py!}
+```
+
+////
+
+//// tab | Python 3.8+ nicht annotiert
+
+/// tip | "Tipp"
+
+Bevorzugen Sie die `Annotated`-Version, falls möglich.
+
+///
+
+```Python hl_lines="27"
+{!> ../../../docs_src/body_multiple_params/tutorial004.py!}
+```
- ```Python hl_lines="27"
- {!> ../../../docs_src/body_multiple_params/tutorial004.py!}
- ```
+////
-!!! info
- `Body` hat die gleichen zusätzlichen Validierungs- und Metadaten-Parameter wie `Query` und `Path` und andere, die Sie später kennenlernen.
+/// info
+
+`Body` hat die gleichen zusätzlichen Validierungs- und Metadaten-Parameter wie `Query` und `Path` und andere, die Sie später kennenlernen.
+
+///
## Einen einzelnen Body-Parameter einbetten
so wie in:
-=== "Python 3.10+"
+//// tab | Python 3.10+
+
+```Python hl_lines="17"
+{!> ../../../docs_src/body_multiple_params/tutorial005_an_py310.py!}
+```
+
+////
+
+//// tab | Python 3.9+
+
+```Python hl_lines="17"
+{!> ../../../docs_src/body_multiple_params/tutorial005_an_py39.py!}
+```
+
+////
+
+//// tab | Python 3.8+
+
+```Python hl_lines="18"
+{!> ../../../docs_src/body_multiple_params/tutorial005_an.py!}
+```
+
+////
+
+//// tab | Python 3.10+ nicht annotiert
- ```Python hl_lines="17"
- {!> ../../../docs_src/body_multiple_params/tutorial005_an_py310.py!}
- ```
+/// tip | "Tipp"
-=== "Python 3.9+"
+Bevorzugen Sie die `Annotated`-Version, falls möglich.
- ```Python hl_lines="17"
- {!> ../../../docs_src/body_multiple_params/tutorial005_an_py39.py!}
- ```
+///
-=== "Python 3.8+"
+```Python hl_lines="15"
+{!> ../../../docs_src/body_multiple_params/tutorial005_py310.py!}
+```
- ```Python hl_lines="18"
- {!> ../../../docs_src/body_multiple_params/tutorial005_an.py!}
- ```
+////
-=== "Python 3.10+ nicht annotiert"
+//// tab | Python 3.8+ nicht annotiert
- !!! tip "Tipp"
- Bevorzugen Sie die `Annotated`-Version, falls möglich.
+/// tip | "Tipp"
- ```Python hl_lines="15"
- {!> ../../../docs_src/body_multiple_params/tutorial005_py310.py!}
- ```
+Bevorzugen Sie die `Annotated`-Version, falls möglich.
-=== "Python 3.8+ nicht annotiert"
+///
- !!! tip "Tipp"
- Bevorzugen Sie die `Annotated`-Version, falls möglich.
+```Python hl_lines="17"
+{!> ../../../docs_src/body_multiple_params/tutorial005.py!}
+```
- ```Python hl_lines="17"
- {!> ../../../docs_src/body_multiple_params/tutorial005.py!}
- ```
+////
In diesem Fall erwartet **FastAPI** einen Body wie:
Sie können ein Attribut als Kindtyp definieren, zum Beispiel eine Python-`list`e.
-=== "Python 3.10+"
+//// tab | Python 3.10+
- ```Python hl_lines="12"
- {!> ../../../docs_src/body_nested_models/tutorial001_py310.py!}
- ```
+```Python hl_lines="12"
+{!> ../../../docs_src/body_nested_models/tutorial001_py310.py!}
+```
+
+////
-=== "Python 3.8+"
+//// tab | Python 3.8+
+
+```Python hl_lines="14"
+{!> ../../../docs_src/body_nested_models/tutorial001.py!}
+```
- ```Python hl_lines="14"
- {!> ../../../docs_src/body_nested_models/tutorial001.py!}
- ```
+////
Das bewirkt, dass `tags` eine Liste ist, wenngleich es nichts über den Typ der Elemente der Liste aussagt.
In unserem Beispiel können wir also bewirken, dass `tags` spezifisch eine „Liste von Strings“ ist:
-=== "Python 3.10+"
+//// tab | Python 3.10+
+
+```Python hl_lines="12"
+{!> ../../../docs_src/body_nested_models/tutorial002_py310.py!}
+```
+
+////
+
+//// tab | Python 3.9+
- ```Python hl_lines="12"
- {!> ../../../docs_src/body_nested_models/tutorial002_py310.py!}
- ```
+```Python hl_lines="14"
+{!> ../../../docs_src/body_nested_models/tutorial002_py39.py!}
+```
-=== "Python 3.9+"
+////
- ```Python hl_lines="14"
- {!> ../../../docs_src/body_nested_models/tutorial002_py39.py!}
- ```
+//// tab | Python 3.8+
-=== "Python 3.8+"
+```Python hl_lines="14"
+{!> ../../../docs_src/body_nested_models/tutorial002.py!}
+```
- ```Python hl_lines="14"
- {!> ../../../docs_src/body_nested_models/tutorial002.py!}
- ```
+////
## Set-Typen
Deklarieren wir also `tags` als Set von Strings.
-=== "Python 3.10+"
+//// tab | Python 3.10+
+
+```Python hl_lines="12"
+{!> ../../../docs_src/body_nested_models/tutorial003_py310.py!}
+```
+
+////
- ```Python hl_lines="12"
- {!> ../../../docs_src/body_nested_models/tutorial003_py310.py!}
- ```
+//// tab | Python 3.9+
-=== "Python 3.9+"
+```Python hl_lines="14"
+{!> ../../../docs_src/body_nested_models/tutorial003_py39.py!}
+```
- ```Python hl_lines="14"
- {!> ../../../docs_src/body_nested_models/tutorial003_py39.py!}
- ```
+////
-=== "Python 3.8+"
+//// tab | Python 3.8+
- ```Python hl_lines="1 14"
- {!> ../../../docs_src/body_nested_models/tutorial003.py!}
- ```
+```Python hl_lines="1 14"
+{!> ../../../docs_src/body_nested_models/tutorial003.py!}
+```
+
+////
Jetzt, selbst wenn Sie einen Request mit duplizierten Daten erhalten, werden diese zu einem Set eindeutiger Dinge konvertiert.
Wir können zum Beispiel ein `Image`-Modell definieren.
-=== "Python 3.10+"
+//// tab | Python 3.10+
+
+```Python hl_lines="7-9"
+{!> ../../../docs_src/body_nested_models/tutorial004_py310.py!}
+```
+
+////
- ```Python hl_lines="7-9"
- {!> ../../../docs_src/body_nested_models/tutorial004_py310.py!}
- ```
+//// tab | Python 3.9+
-=== "Python 3.9+"
+```Python hl_lines="9-11"
+{!> ../../../docs_src/body_nested_models/tutorial004_py39.py!}
+```
+
+////
- ```Python hl_lines="9-11"
- {!> ../../../docs_src/body_nested_models/tutorial004_py39.py!}
- ```
+//// tab | Python 3.8+
-=== "Python 3.8+"
+```Python hl_lines="9-11"
+{!> ../../../docs_src/body_nested_models/tutorial004.py!}
+```
- ```Python hl_lines="9-11"
- {!> ../../../docs_src/body_nested_models/tutorial004.py!}
- ```
+////
### Das Kindmodell als Typ verwenden
Und dann können wir es als Typ eines Attributes verwenden.
-=== "Python 3.10+"
+//// tab | Python 3.10+
- ```Python hl_lines="18"
- {!> ../../../docs_src/body_nested_models/tutorial004_py310.py!}
- ```
+```Python hl_lines="18"
+{!> ../../../docs_src/body_nested_models/tutorial004_py310.py!}
+```
-=== "Python 3.9+"
+////
- ```Python hl_lines="20"
- {!> ../../../docs_src/body_nested_models/tutorial004_py39.py!}
- ```
+//// tab | Python 3.9+
-=== "Python 3.8+"
+```Python hl_lines="20"
+{!> ../../../docs_src/body_nested_models/tutorial004_py39.py!}
+```
+
+////
- ```Python hl_lines="20"
- {!> ../../../docs_src/body_nested_models/tutorial004.py!}
- ```
+//// tab | Python 3.8+
+
+```Python hl_lines="20"
+{!> ../../../docs_src/body_nested_models/tutorial004.py!}
+```
+
+////
Das würde bedeuten, dass **FastAPI** einen Body erwartet wie:
Da wir zum Beispiel im `Image`-Modell ein Feld `url` haben, können wir deklarieren, dass das eine Instanz von Pydantics `HttpUrl` sein soll, anstelle eines `str`:
-=== "Python 3.10+"
+//// tab | Python 3.10+
- ```Python hl_lines="2 8"
- {!> ../../../docs_src/body_nested_models/tutorial005_py310.py!}
- ```
+```Python hl_lines="2 8"
+{!> ../../../docs_src/body_nested_models/tutorial005_py310.py!}
+```
-=== "Python 3.9+"
+////
- ```Python hl_lines="4 10"
- {!> ../../../docs_src/body_nested_models/tutorial005_py39.py!}
- ```
+//// tab | Python 3.9+
-=== "Python 3.8+"
+```Python hl_lines="4 10"
+{!> ../../../docs_src/body_nested_models/tutorial005_py39.py!}
+```
- ```Python hl_lines="4 10"
- {!> ../../../docs_src/body_nested_models/tutorial005.py!}
- ```
+////
+
+//// tab | Python 3.8+
+
+```Python hl_lines="4 10"
+{!> ../../../docs_src/body_nested_models/tutorial005.py!}
+```
+
+////
Es wird getestet, ob der String eine gültige URL ist, und als solche wird er in JSON Schema / OpenAPI dokumentiert.
Sie können Pydantic-Modelle auch als Typen innerhalb von `list`, `set`, usw. verwenden:
-=== "Python 3.10+"
+//// tab | Python 3.10+
- ```Python hl_lines="18"
- {!> ../../../docs_src/body_nested_models/tutorial006_py310.py!}
- ```
+```Python hl_lines="18"
+{!> ../../../docs_src/body_nested_models/tutorial006_py310.py!}
+```
+
+////
-=== "Python 3.9+"
+//// tab | Python 3.9+
- ```Python hl_lines="20"
- {!> ../../../docs_src/body_nested_models/tutorial006_py39.py!}
- ```
+```Python hl_lines="20"
+{!> ../../../docs_src/body_nested_models/tutorial006_py39.py!}
+```
-=== "Python 3.8+"
+////
- ```Python hl_lines="20"
- {!> ../../../docs_src/body_nested_models/tutorial006.py!}
- ```
+//// tab | Python 3.8+
+
+```Python hl_lines="20"
+{!> ../../../docs_src/body_nested_models/tutorial006.py!}
+```
+
+////
Das wird einen JSON-Body erwarten (konvertieren, validieren, dokumentieren), wie:
}
```
-!!! info
- Beachten Sie, dass der `images`-Schlüssel jetzt eine Liste von Bild-Objekten hat.
+/// info
+
+Beachten Sie, dass der `images`-Schlüssel jetzt eine Liste von Bild-Objekten hat.
+
+///
## Tief verschachtelte Modelle
Sie können beliebig tief verschachtelte Modelle definieren:
-=== "Python 3.10+"
+//// tab | Python 3.10+
+
+```Python hl_lines="7 12 18 21 25"
+{!> ../../../docs_src/body_nested_models/tutorial007_py310.py!}
+```
+
+////
- ```Python hl_lines="7 12 18 21 25"
- {!> ../../../docs_src/body_nested_models/tutorial007_py310.py!}
- ```
+//// tab | Python 3.9+
-=== "Python 3.9+"
+```Python hl_lines="9 14 20 23 27"
+{!> ../../../docs_src/body_nested_models/tutorial007_py39.py!}
+```
+
+////
+
+//// tab | Python 3.8+
+
+```Python hl_lines="9 14 20 23 27"
+{!> ../../../docs_src/body_nested_models/tutorial007.py!}
+```
- ```Python hl_lines="9 14 20 23 27"
- {!> ../../../docs_src/body_nested_models/tutorial007_py39.py!}
- ```
+////
-=== "Python 3.8+"
+/// info
- ```Python hl_lines="9 14 20 23 27"
- {!> ../../../docs_src/body_nested_models/tutorial007.py!}
- ```
+Beachten Sie, wie `Offer` eine Liste von `Item`s hat, von denen jedes seinerseits eine optionale Liste von `Image`s hat.
-!!! info
- Beachten Sie, wie `Offer` eine Liste von `Item`s hat, von denen jedes seinerseits eine optionale Liste von `Image`s hat.
+///
## Bodys aus reinen Listen
so wie in:
-=== "Python 3.9+"
+//// tab | Python 3.9+
+
+```Python hl_lines="13"
+{!> ../../../docs_src/body_nested_models/tutorial008_py39.py!}
+```
- ```Python hl_lines="13"
- {!> ../../../docs_src/body_nested_models/tutorial008_py39.py!}
- ```
+////
-=== "Python 3.8+"
+//// tab | Python 3.8+
- ```Python hl_lines="15"
- {!> ../../../docs_src/body_nested_models/tutorial008.py!}
- ```
+```Python hl_lines="15"
+{!> ../../../docs_src/body_nested_models/tutorial008.py!}
+```
+
+////
## Editor-Unterstützung überall
Im folgenden Beispiel akzeptieren Sie irgendein `dict`, solange es `int`-Schlüssel und `float`-Werte hat.
-=== "Python 3.9+"
+//// tab | Python 3.9+
+
+```Python hl_lines="7"
+{!> ../../../docs_src/body_nested_models/tutorial009_py39.py!}
+```
+
+////
+
+//// tab | Python 3.8+
+
+```Python hl_lines="9"
+{!> ../../../docs_src/body_nested_models/tutorial009.py!}
+```
- ```Python hl_lines="7"
- {!> ../../../docs_src/body_nested_models/tutorial009_py39.py!}
- ```
+////
-=== "Python 3.8+"
+/// tip | "Tipp"
- ```Python hl_lines="9"
- {!> ../../../docs_src/body_nested_models/tutorial009.py!}
- ```
+Bedenken Sie, dass JSON nur `str` als Schlüssel unterstützt.
-!!! tip "Tipp"
- Bedenken Sie, dass JSON nur `str` als Schlüssel unterstützt.
+Aber Pydantic hat automatische Datenkonvertierung.
- Aber Pydantic hat automatische Datenkonvertierung.
+Das bedeutet, dass Ihre API-Clients nur Strings senden können, aber solange diese Strings nur Zahlen enthalten, wird Pydantic sie konvertieren und validieren.
- Das bedeutet, dass Ihre API-Clients nur Strings senden können, aber solange diese Strings nur Zahlen enthalten, wird Pydantic sie konvertieren und validieren.
+Und das `dict` welches Sie als `weights` erhalten, wird `int`-Schlüssel und `float`-Werte haben.
- Und das `dict` welches Sie als `weights` erhalten, wird `int`-Schlüssel und `float`-Werte haben.
+///
## Zusammenfassung
Sie können den `jsonable_encoder` verwenden, um die empfangenen Daten in etwas zu konvertieren, das als JSON gespeichert werden kann (in z. B. einer NoSQL-Datenbank). Zum Beispiel, um ein `datetime` in einen `str` zu konvertieren.
-=== "Python 3.10+"
+//// tab | Python 3.10+
- ```Python hl_lines="28-33"
- {!> ../../../docs_src/body_updates/tutorial001_py310.py!}
- ```
+```Python hl_lines="28-33"
+{!> ../../../docs_src/body_updates/tutorial001_py310.py!}
+```
+
+////
-=== "Python 3.9+"
+//// tab | Python 3.9+
- ```Python hl_lines="30-35"
- {!> ../../../docs_src/body_updates/tutorial001_py39.py!}
- ```
+```Python hl_lines="30-35"
+{!> ../../../docs_src/body_updates/tutorial001_py39.py!}
+```
-=== "Python 3.8+"
+////
- ```Python hl_lines="30-35"
- {!> ../../../docs_src/body_updates/tutorial001.py!}
- ```
+//// tab | Python 3.8+
+
+```Python hl_lines="30-35"
+{!> ../../../docs_src/body_updates/tutorial001.py!}
+```
+
+////
`PUT` wird verwendet, um Daten zu empfangen, die die existierenden Daten ersetzen sollen.
Das bedeutet, sie senden nur die Daten, die Sie aktualisieren wollen, der Rest bleibt unverändert.
-!!! note "Hinweis"
- `PATCH` wird seltener verwendet und ist weniger bekannt als `PUT`.
+/// note | "Hinweis"
+
+`PATCH` wird seltener verwendet und ist weniger bekannt als `PUT`.
- Und viele Teams verwenden ausschließlich `PUT`, selbst für nur Teil-Aktualisierungen.
+Und viele Teams verwenden ausschließlich `PUT`, selbst für nur Teil-Aktualisierungen.
- Es steht Ihnen **frei**, das zu verwenden, was Sie möchten, **FastAPI** legt Ihnen keine Einschränkungen auf.
+Es steht Ihnen **frei**, das zu verwenden, was Sie möchten, **FastAPI** legt Ihnen keine Einschränkungen auf.
- Aber dieser Leitfaden zeigt Ihnen mehr oder weniger, wie die beiden normalerweise verwendet werden.
+Aber dieser Leitfaden zeigt Ihnen mehr oder weniger, wie die beiden normalerweise verwendet werden.
+
+///
### Pydantics `exclude_unset`-Parameter verwenden
Wie in `item.model_dump(exclude_unset=True)`.
-!!! info
- In Pydantic v1 hieß diese Methode `.dict()`, in Pydantic v2 wurde sie deprecated (aber immer noch unterstützt) und in `.model_dump()` umbenannt.
+/// info
+
+In Pydantic v1 hieß diese Methode `.dict()`, in Pydantic v2 wurde sie deprecated (aber immer noch unterstützt) und in `.model_dump()` umbenannt.
- Die Beispiele hier verwenden `.dict()` für die Kompatibilität mit Pydantic v1, Sie sollten jedoch stattdessen `.model_dump()` verwenden, wenn Sie Pydantic v2 verwenden können.
+Die Beispiele hier verwenden `.dict()` für die Kompatibilität mit Pydantic v1, Sie sollten jedoch stattdessen `.model_dump()` verwenden, wenn Sie Pydantic v2 verwenden können.
+
+///
Das wird ein `dict` erstellen, mit nur den Daten, die gesetzt wurden als das `item`-Modell erstellt wurde, Defaultwerte ausgeschlossen.
Sie können das verwenden, um ein `dict` zu erstellen, das nur die (im Request) gesendeten Daten enthält, ohne Defaultwerte:
-=== "Python 3.10+"
+//// tab | Python 3.10+
+
+```Python hl_lines="32"
+{!> ../../../docs_src/body_updates/tutorial002_py310.py!}
+```
+
+////
- ```Python hl_lines="32"
- {!> ../../../docs_src/body_updates/tutorial002_py310.py!}
- ```
+//// tab | Python 3.9+
-=== "Python 3.9+"
+```Python hl_lines="34"
+{!> ../../../docs_src/body_updates/tutorial002_py39.py!}
+```
+
+////
- ```Python hl_lines="34"
- {!> ../../../docs_src/body_updates/tutorial002_py39.py!}
- ```
+//// tab | Python 3.8+
-=== "Python 3.8+"
+```Python hl_lines="34"
+{!> ../../../docs_src/body_updates/tutorial002.py!}
+```
- ```Python hl_lines="34"
- {!> ../../../docs_src/body_updates/tutorial002.py!}
- ```
+////
### Pydantics `update`-Parameter verwenden
Jetzt können Sie eine Kopie des existierenden Modells mittels `.model_copy()` erstellen, wobei Sie dem `update`-Parameter ein `dict` mit den zu ändernden Daten übergeben.
-!!! info
- In Pydantic v1 hieß diese Methode `.copy()`, in Pydantic v2 wurde sie deprecated (aber immer noch unterstützt) und in `.model_copy()` umbenannt.
+/// info
+
+In Pydantic v1 hieß diese Methode `.copy()`, in Pydantic v2 wurde sie deprecated (aber immer noch unterstützt) und in `.model_copy()` umbenannt.
- Die Beispiele hier verwenden `.copy()` für die Kompatibilität mit Pydantic v1, Sie sollten jedoch stattdessen `.model_copy()` verwenden, wenn Sie Pydantic v2 verwenden können.
+Die Beispiele hier verwenden `.copy()` für die Kompatibilität mit Pydantic v1, Sie sollten jedoch stattdessen `.model_copy()` verwenden, wenn Sie Pydantic v2 verwenden können.
+
+///
Wie in `stored_item_model.model_copy(update=update_data)`:
-=== "Python 3.10+"
+//// tab | Python 3.10+
- ```Python hl_lines="33"
- {!> ../../../docs_src/body_updates/tutorial002_py310.py!}
- ```
+```Python hl_lines="33"
+{!> ../../../docs_src/body_updates/tutorial002_py310.py!}
+```
-=== "Python 3.9+"
+////
- ```Python hl_lines="35"
- {!> ../../../docs_src/body_updates/tutorial002_py39.py!}
- ```
+//// tab | Python 3.9+
-=== "Python 3.8+"
+```Python hl_lines="35"
+{!> ../../../docs_src/body_updates/tutorial002_py39.py!}
+```
- ```Python hl_lines="35"
- {!> ../../../docs_src/body_updates/tutorial002.py!}
- ```
+////
+
+//// tab | Python 3.8+
+
+```Python hl_lines="35"
+{!> ../../../docs_src/body_updates/tutorial002.py!}
+```
+
+////
### Rekapitulation zum teilweisen Ersetzen
* Speichern Sie die Daten in Ihrer Datenbank.
* Geben Sie das aktualisierte Modell zurück.
-=== "Python 3.10+"
+//// tab | Python 3.10+
+
+```Python hl_lines="28-35"
+{!> ../../../docs_src/body_updates/tutorial002_py310.py!}
+```
+
+////
+
+//// tab | Python 3.9+
+
+```Python hl_lines="30-37"
+{!> ../../../docs_src/body_updates/tutorial002_py39.py!}
+```
+
+////
+
+//// tab | Python 3.8+
+
+```Python hl_lines="30-37"
+{!> ../../../docs_src/body_updates/tutorial002.py!}
+```
- ```Python hl_lines="28-35"
- {!> ../../../docs_src/body_updates/tutorial002_py310.py!}
- ```
+////
-=== "Python 3.9+"
+/// tip | "Tipp"
- ```Python hl_lines="30-37"
- {!> ../../../docs_src/body_updates/tutorial002_py39.py!}
- ```
+Sie können tatsächlich die gleiche Technik mit einer HTTP `PUT` Operation verwenden.
-=== "Python 3.8+"
+Aber dieses Beispiel verwendet `PATCH`, da dieses für solche Anwendungsfälle geschaffen wurde.
- ```Python hl_lines="30-37"
- {!> ../../../docs_src/body_updates/tutorial002.py!}
- ```
+///
-!!! tip "Tipp"
- Sie können tatsächlich die gleiche Technik mit einer HTTP `PUT` Operation verwenden.
+/// note | "Hinweis"
- Aber dieses Beispiel verwendet `PATCH`, da dieses für solche Anwendungsfälle geschaffen wurde.
+Beachten Sie, dass das hereinkommende Modell immer noch validiert wird.
-!!! note "Hinweis"
- Beachten Sie, dass das hereinkommende Modell immer noch validiert wird.
+Wenn Sie also Teil-Aktualisierungen empfangen wollen, die alle Attribute auslassen können, müssen Sie ein Modell haben, dessen Attribute alle als optional gekennzeichnet sind (mit Defaultwerten oder `None`).
- Wenn Sie also Teil-Aktualisierungen empfangen wollen, die alle Attribute auslassen können, müssen Sie ein Modell haben, dessen Attribute alle als optional gekennzeichnet sind (mit Defaultwerten oder `None`).
+Um zu unterscheiden zwischen Modellen für **Aktualisierungen**, mit lauter optionalen Werten, und solchen für die **Erzeugung**, mit benötigten Werten, können Sie die Techniken verwenden, die in [Extramodelle](extra-models.md){.internal-link target=_blank} beschrieben wurden.
- Um zu unterscheiden zwischen Modellen für **Aktualisierungen**, mit lauter optionalen Werten, und solchen für die **Erzeugung**, mit benötigten Werten, können Sie die Techniken verwenden, die in [Extramodelle](extra-models.md){.internal-link target=_blank} beschrieben wurden.
+///
Um einen **Request**body zu deklarieren, verwenden Sie <a href="https://docs.pydantic.dev/" class="external-link" target="_blank">Pydantic</a>-Modelle mit allen deren Fähigkeiten und Vorzügen.
-!!! info
- Um Daten zu versenden, sollten Sie eines von: `POST` (meistverwendet), `PUT`, `DELETE` oder `PATCH` verwenden.
+/// info
- Senden Sie einen Body mit einem `GET`-Request, dann führt das laut Spezifikation zu undefiniertem Verhalten. Trotzdem wird es von FastAPI unterstützt, für sehr komplexe/extreme Anwendungsfälle.
+Um Daten zu versenden, sollten Sie eines von: `POST` (meistverwendet), `PUT`, `DELETE` oder `PATCH` verwenden.
- Da aber davon abgeraten wird, zeigt die interaktive Dokumentation mit Swagger-Benutzeroberfläche die Dokumentation für den Body auch nicht an, wenn `GET` verwendet wird. Dazwischengeschaltete Proxys unterstützen es möglicherweise auch nicht.
+Senden Sie einen Body mit einem `GET`-Request, dann führt das laut Spezifikation zu undefiniertem Verhalten. Trotzdem wird es von FastAPI unterstützt, für sehr komplexe/extreme Anwendungsfälle.
+
+Da aber davon abgeraten wird, zeigt die interaktive Dokumentation mit Swagger-Benutzeroberfläche die Dokumentation für den Body auch nicht an, wenn `GET` verwendet wird. Dazwischengeschaltete Proxys unterstützen es möglicherweise auch nicht.
+
+///
## Importieren Sie Pydantics `BaseModel`
Zuerst müssen Sie `BaseModel` von `pydantic` importieren:
-=== "Python 3.10+"
+//// tab | Python 3.10+
+
+```Python hl_lines="2"
+{!> ../../../docs_src/body/tutorial001_py310.py!}
+```
+
+////
- ```Python hl_lines="2"
- {!> ../../../docs_src/body/tutorial001_py310.py!}
- ```
+//// tab | Python 3.8+
-=== "Python 3.8+"
+```Python hl_lines="4"
+{!> ../../../docs_src/body/tutorial001.py!}
+```
- ```Python hl_lines="4"
- {!> ../../../docs_src/body/tutorial001.py!}
- ```
+////
## Erstellen Sie Ihr Datenmodell
Verwenden Sie Standard-Python-Typen für die Klassenattribute:
-=== "Python 3.10+"
+//// tab | Python 3.10+
- ```Python hl_lines="5-9"
- {!> ../../../docs_src/body/tutorial001_py310.py!}
- ```
+```Python hl_lines="5-9"
+{!> ../../../docs_src/body/tutorial001_py310.py!}
+```
-=== "Python 3.8+"
+////
- ```Python hl_lines="7-11"
- {!> ../../../docs_src/body/tutorial001.py!}
- ```
+//// tab | Python 3.8+
+
+```Python hl_lines="7-11"
+{!> ../../../docs_src/body/tutorial001.py!}
+```
+
+////
Wie auch bei Query-Parametern gilt, wenn ein Modellattribut einen Defaultwert hat, ist das Attribut nicht erforderlich. Ansonsten ist es erforderlich. Verwenden Sie `None`, um es als optional zu kennzeichnen.
Um es zu Ihrer *Pfadoperation* hinzuzufügen, deklarieren Sie es auf die gleiche Weise, wie Sie Pfad- und Query-Parameter deklariert haben:
-=== "Python 3.10+"
+//// tab | Python 3.10+
- ```Python hl_lines="16"
- {!> ../../../docs_src/body/tutorial001_py310.py!}
- ```
+```Python hl_lines="16"
+{!> ../../../docs_src/body/tutorial001_py310.py!}
+```
-=== "Python 3.8+"
+////
- ```Python hl_lines="18"
- {!> ../../../docs_src/body/tutorial001.py!}
- ```
+//// tab | Python 3.8+
+
+```Python hl_lines="18"
+{!> ../../../docs_src/body/tutorial001.py!}
+```
+
+////
... und deklarieren Sie seinen Typ als das Modell, welches Sie erstellt haben, `Item`.
<img src="/img/tutorial/body/image05.png">
-!!! tip "Tipp"
- Wenn Sie <a href="https://www.jetbrains.com/pycharm/" class="external-link" target="_blank">PyCharm</a> als Ihren Editor verwenden, probieren Sie das <a href="https://github.com/koxudaxi/pydantic-pycharm-plugin/" class="external-link" target="_blank">Pydantic PyCharm Plugin</a> aus.
+/// tip | "Tipp"
+
+Wenn Sie <a href="https://www.jetbrains.com/pycharm/" class="external-link" target="_blank">PyCharm</a> als Ihren Editor verwenden, probieren Sie das <a href="https://github.com/koxudaxi/pydantic-pycharm-plugin/" class="external-link" target="_blank">Pydantic PyCharm Plugin</a> aus.
- Es verbessert die Editor-Unterstützung für Pydantic-Modelle, mit:
+Es verbessert die Editor-Unterstützung für Pydantic-Modelle, mit:
- * Code-Vervollständigung
- * Typüberprüfungen
- * Refaktorisierung
- * Suchen
- * Inspektionen
+* Code-Vervollständigung
+* Typüberprüfungen
+* Refaktorisierung
+* Suchen
+* Inspektionen
+
+///
## Das Modell verwenden
Innerhalb der Funktion können Sie alle Attribute des Modells direkt verwenden:
-=== "Python 3.10+"
+//// tab | Python 3.10+
+
+```Python hl_lines="19"
+{!> ../../../docs_src/body/tutorial002_py310.py!}
+```
+
+////
- ```Python hl_lines="19"
- {!> ../../../docs_src/body/tutorial002_py310.py!}
- ```
+//// tab | Python 3.8+
-=== "Python 3.8+"
+```Python hl_lines="21"
+{!> ../../../docs_src/body/tutorial002.py!}
+```
- ```Python hl_lines="21"
- {!> ../../../docs_src/body/tutorial002.py!}
- ```
+////
## Requestbody- + Pfad-Parameter
**FastAPI** erkennt, dass Funktionsparameter, die mit Pfad-Parametern übereinstimmen, **vom Pfad genommen** werden sollen, und dass Funktionsparameter, welche Pydantic-Modelle sind, **vom Requestbody genommen** werden sollen.
-=== "Python 3.10+"
+//// tab | Python 3.10+
+
+```Python hl_lines="15-16"
+{!> ../../../docs_src/body/tutorial003_py310.py!}
+```
- ```Python hl_lines="15-16"
- {!> ../../../docs_src/body/tutorial003_py310.py!}
- ```
+////
-=== "Python 3.8+"
+//// tab | Python 3.8+
- ```Python hl_lines="17-18"
- {!> ../../../docs_src/body/tutorial003.py!}
- ```
+```Python hl_lines="17-18"
+{!> ../../../docs_src/body/tutorial003.py!}
+```
+
+////
## Requestbody- + Pfad- + Query-Parameter
**FastAPI** wird jeden Parameter korrekt erkennen und die Daten vom richtigen Ort holen.
-=== "Python 3.10+"
+//// tab | Python 3.10+
+
+```Python hl_lines="16"
+{!> ../../../docs_src/body/tutorial004_py310.py!}
+```
- ```Python hl_lines="16"
- {!> ../../../docs_src/body/tutorial004_py310.py!}
- ```
+////
-=== "Python 3.8+"
+//// tab | Python 3.8+
- ```Python hl_lines="18"
- {!> ../../../docs_src/body/tutorial004.py!}
- ```
+```Python hl_lines="18"
+{!> ../../../docs_src/body/tutorial004.py!}
+```
+
+////
Die Funktionsparameter werden wie folgt erkannt:
* Wenn der Parameter ein **einfacher Typ** ist (wie `int`, `float`, `str`, `bool`, usw.), wird er als **Query**-Parameter interpretiert.
* Wenn der Parameter vom Typ eines **Pydantic-Modells** ist, wird er als Request**body** interpretiert.
-!!! note "Hinweis"
- FastAPI weiß, dass der Wert von `q` nicht erforderlich ist, wegen des definierten Defaultwertes `= None`
+/// note | "Hinweis"
+
+FastAPI weiß, dass der Wert von `q` nicht erforderlich ist, wegen des definierten Defaultwertes `= None`
+
+Das `Union` in `Union[str, None]` wird von FastAPI nicht verwendet, aber es erlaubt Ihrem Editor, Sie besser zu unterstützen und Fehler zu erkennen.
- Das `Union` in `Union[str, None]` wird von FastAPI nicht verwendet, aber es erlaubt Ihrem Editor, Sie besser zu unterstützen und Fehler zu erkennen.
+///
## Ohne Pydantic
Importieren Sie zuerst `Cookie`:
-=== "Python 3.10+"
+//// tab | Python 3.10+
- ```Python hl_lines="3"
- {!> ../../../docs_src/cookie_params/tutorial001_an_py310.py!}
- ```
+```Python hl_lines="3"
+{!> ../../../docs_src/cookie_params/tutorial001_an_py310.py!}
+```
-=== "Python 3.9+"
+////
- ```Python hl_lines="3"
- {!> ../../../docs_src/cookie_params/tutorial001_an_py39.py!}
- ```
+//// tab | Python 3.9+
-=== "Python 3.8+"
+```Python hl_lines="3"
+{!> ../../../docs_src/cookie_params/tutorial001_an_py39.py!}
+```
- ```Python hl_lines="3"
- {!> ../../../docs_src/cookie_params/tutorial001_an.py!}
- ```
+////
-=== "Python 3.10+ nicht annotiert"
+//// tab | Python 3.8+
- !!! tip "Tipp"
- Bevorzugen Sie die `Annotated`-Version, falls möglich.
+```Python hl_lines="3"
+{!> ../../../docs_src/cookie_params/tutorial001_an.py!}
+```
- ```Python hl_lines="1"
- {!> ../../../docs_src/cookie_params/tutorial001_py310.py!}
- ```
+////
-=== "Python 3.8+ nicht annotiert"
+//// tab | Python 3.10+ nicht annotiert
- !!! tip "Tipp"
- Bevorzugen Sie die `Annotated`-Version, falls möglich.
+/// tip | "Tipp"
- ```Python hl_lines="3"
- {!> ../../../docs_src/cookie_params/tutorial001.py!}
- ```
+Bevorzugen Sie die `Annotated`-Version, falls möglich.
+
+///
+
+```Python hl_lines="1"
+{!> ../../../docs_src/cookie_params/tutorial001_py310.py!}
+```
+
+////
+
+//// tab | Python 3.8+ nicht annotiert
+
+/// tip | "Tipp"
+
+Bevorzugen Sie die `Annotated`-Version, falls möglich.
+
+///
+
+```Python hl_lines="3"
+{!> ../../../docs_src/cookie_params/tutorial001.py!}
+```
+
+////
## `Cookie`-Parameter deklarieren
Der erste Wert ist der Typ. Sie können `Cookie` die gehabten Extra Validierungs- und Beschreibungsparameter hinzufügen. Danach können Sie einen Defaultwert vergeben:
-=== "Python 3.10+"
+//// tab | Python 3.10+
+
+```Python hl_lines="9"
+{!> ../../../docs_src/cookie_params/tutorial001_an_py310.py!}
+```
+
+////
+
+//// tab | Python 3.9+
+
+```Python hl_lines="9"
+{!> ../../../docs_src/cookie_params/tutorial001_an_py39.py!}
+```
+
+////
+
+//// tab | Python 3.8+
+
+```Python hl_lines="10"
+{!> ../../../docs_src/cookie_params/tutorial001_an.py!}
+```
+
+////
+
+//// tab | Python 3.10+ nicht annotiert
+
+/// tip | "Tipp"
+
+Bevorzugen Sie die `Annotated`-Version, falls möglich.
+
+///
+
+```Python hl_lines="7"
+{!> ../../../docs_src/cookie_params/tutorial001_py310.py!}
+```
- ```Python hl_lines="9"
- {!> ../../../docs_src/cookie_params/tutorial001_an_py310.py!}
- ```
+////
-=== "Python 3.9+"
+//// tab | Python 3.8+ nicht annotiert
- ```Python hl_lines="9"
- {!> ../../../docs_src/cookie_params/tutorial001_an_py39.py!}
- ```
+/// tip | "Tipp"
-=== "Python 3.8+"
+Bevorzugen Sie die `Annotated`-Version, falls möglich.
- ```Python hl_lines="10"
- {!> ../../../docs_src/cookie_params/tutorial001_an.py!}
- ```
+///
-=== "Python 3.10+ nicht annotiert"
+```Python hl_lines="9"
+{!> ../../../docs_src/cookie_params/tutorial001.py!}
+```
- !!! tip "Tipp"
- Bevorzugen Sie die `Annotated`-Version, falls möglich.
+////
- ```Python hl_lines="7"
- {!> ../../../docs_src/cookie_params/tutorial001_py310.py!}
- ```
+/// note | "Technische Details"
-=== "Python 3.8+ nicht annotiert"
+`Cookie` ist eine Schwesterklasse von `Path` und `Query`. Sie erbt von derselben gemeinsamen `Param`-Elternklasse.
- !!! tip "Tipp"
- Bevorzugen Sie die `Annotated`-Version, falls möglich.
+Aber erinnern Sie sich, dass, wenn Sie `Query`, `Path`, `Cookie` und andere von `fastapi` importieren, diese tatsächlich Funktionen sind, welche spezielle Klassen zurückgeben.
- ```Python hl_lines="9"
- {!> ../../../docs_src/cookie_params/tutorial001.py!}
- ```
+///
-!!! note "Technische Details"
- `Cookie` ist eine Schwesterklasse von `Path` und `Query`. Sie erbt von derselben gemeinsamen `Param`-Elternklasse.
+/// info
- Aber erinnern Sie sich, dass, wenn Sie `Query`, `Path`, `Cookie` und andere von `fastapi` importieren, diese tatsächlich Funktionen sind, welche spezielle Klassen zurückgeben.
+Um Cookies zu deklarieren, müssen Sie `Cookie` verwenden, da diese Parameter sonst als Query-Parameter interpretiert werden würden.
-!!! info
- Um Cookies zu deklarieren, müssen Sie `Cookie` verwenden, da diese Parameter sonst als Query-Parameter interpretiert werden würden.
+///
## Zusammenfassung
Im vorherigen Beispiel haben wir ein `dict` von unserer Abhängigkeit („Dependable“) zurückgegeben:
-=== "Python 3.10+"
+//// tab | Python 3.10+
- ```Python hl_lines="9"
- {!> ../../../docs_src/dependencies/tutorial001_an_py310.py!}
- ```
+```Python hl_lines="9"
+{!> ../../../docs_src/dependencies/tutorial001_an_py310.py!}
+```
+
+////
+
+//// tab | Python 3.9+
+
+```Python hl_lines="11"
+{!> ../../../docs_src/dependencies/tutorial001_an_py39.py!}
+```
-=== "Python 3.9+"
+////
- ```Python hl_lines="11"
- {!> ../../../docs_src/dependencies/tutorial001_an_py39.py!}
- ```
+//// tab | Python 3.8+
-=== "Python 3.8+"
+```Python hl_lines="12"
+{!> ../../../docs_src/dependencies/tutorial001_an.py!}
+```
+
+////
+
+//// tab | Python 3.10+ nicht annotiert
- ```Python hl_lines="12"
- {!> ../../../docs_src/dependencies/tutorial001_an.py!}
- ```
+/// tip | "Tipp"
-=== "Python 3.10+ nicht annotiert"
+Bevorzugen Sie die `Annotated`-Version, falls möglich.
- !!! tip "Tipp"
- Bevorzugen Sie die `Annotated`-Version, falls möglich.
+///
+
+```Python hl_lines="7"
+{!> ../../../docs_src/dependencies/tutorial001_py310.py!}
+```
- ```Python hl_lines="7"
- {!> ../../../docs_src/dependencies/tutorial001_py310.py!}
- ```
+////
-=== "Python 3.8+ nicht annotiert"
+//// tab | Python 3.8+ nicht annotiert
- !!! tip "Tipp"
- Bevorzugen Sie die `Annotated`-Version, falls möglich.
+/// tip | "Tipp"
- ```Python hl_lines="11"
- {!> ../../../docs_src/dependencies/tutorial001.py!}
- ```
+Bevorzugen Sie die `Annotated`-Version, falls möglich.
+
+///
+
+```Python hl_lines="11"
+{!> ../../../docs_src/dependencies/tutorial001.py!}
+```
+
+////
Aber dann haben wir ein `dict` im Parameter `commons` der *Pfadoperation-Funktion*.
Dann können wir das „Dependable“ `common_parameters` der Abhängigkeit von oben in die Klasse `CommonQueryParams` ändern:
-=== "Python 3.10+"
+//// tab | Python 3.10+
- ```Python hl_lines="11-15"
- {!> ../../../docs_src/dependencies/tutorial002_an_py310.py!}
- ```
+```Python hl_lines="11-15"
+{!> ../../../docs_src/dependencies/tutorial002_an_py310.py!}
+```
-=== "Python 3.9+"
+////
- ```Python hl_lines="11-15"
- {!> ../../../docs_src/dependencies/tutorial002_an_py39.py!}
- ```
+//// tab | Python 3.9+
-=== "Python 3.8+"
+```Python hl_lines="11-15"
+{!> ../../../docs_src/dependencies/tutorial002_an_py39.py!}
+```
+
+////
- ```Python hl_lines="12-16"
- {!> ../../../docs_src/dependencies/tutorial002_an.py!}
- ```
+//// tab | Python 3.8+
-=== "Python 3.10+ nicht annotiert"
+```Python hl_lines="12-16"
+{!> ../../../docs_src/dependencies/tutorial002_an.py!}
+```
- !!! tip "Tipp"
- Bevorzugen Sie die `Annotated`-Version, falls möglich.
+////
- ```Python hl_lines="9-13"
- {!> ../../../docs_src/dependencies/tutorial002_py310.py!}
- ```
+//// tab | Python 3.10+ nicht annotiert
-=== "Python 3.8+ nicht annotiert"
+/// tip | "Tipp"
- !!! tip "Tipp"
- Bevorzugen Sie die `Annotated`-Version, falls möglich.
+Bevorzugen Sie die `Annotated`-Version, falls möglich.
- ```Python hl_lines="11-15"
- {!> ../../../docs_src/dependencies/tutorial002.py!}
- ```
+///
+
+```Python hl_lines="9-13"
+{!> ../../../docs_src/dependencies/tutorial002_py310.py!}
+```
+
+////
+
+//// tab | Python 3.8+ nicht annotiert
+
+/// tip | "Tipp"
+
+Bevorzugen Sie die `Annotated`-Version, falls möglich.
+
+///
+
+```Python hl_lines="11-15"
+{!> ../../../docs_src/dependencies/tutorial002.py!}
+```
+
+////
Achten Sie auf die Methode `__init__`, die zum Erstellen der Instanz der Klasse verwendet wird:
-=== "Python 3.10+"
+//// tab | Python 3.10+
+
+```Python hl_lines="12"
+{!> ../../../docs_src/dependencies/tutorial002_an_py310.py!}
+```
+
+////
+
+//// tab | Python 3.9+
+
+```Python hl_lines="12"
+{!> ../../../docs_src/dependencies/tutorial002_an_py39.py!}
+```
+
+////
+
+//// tab | Python 3.8+
+
+```Python hl_lines="13"
+{!> ../../../docs_src/dependencies/tutorial002_an.py!}
+```
+
+////
- ```Python hl_lines="12"
- {!> ../../../docs_src/dependencies/tutorial002_an_py310.py!}
- ```
+//// tab | Python 3.10+ nicht annotiert
-=== "Python 3.9+"
+/// tip | "Tipp"
- ```Python hl_lines="12"
- {!> ../../../docs_src/dependencies/tutorial002_an_py39.py!}
- ```
+Bevorzugen Sie die `Annotated`-Version, falls möglich.
-=== "Python 3.8+"
+///
- ```Python hl_lines="13"
- {!> ../../../docs_src/dependencies/tutorial002_an.py!}
- ```
+```Python hl_lines="10"
+{!> ../../../docs_src/dependencies/tutorial002_py310.py!}
+```
-=== "Python 3.10+ nicht annotiert"
+////
- !!! tip "Tipp"
- Bevorzugen Sie die `Annotated`-Version, falls möglich.
+//// tab | Python 3.8+ nicht annotiert
- ```Python hl_lines="10"
- {!> ../../../docs_src/dependencies/tutorial002_py310.py!}
- ```
+/// tip | "Tipp"
-=== "Python 3.8+ nicht annotiert"
+Bevorzugen Sie die `Annotated`-Version, falls möglich.
- !!! tip "Tipp"
- Bevorzugen Sie die `Annotated`-Version, falls möglich.
+///
+
+```Python hl_lines="12"
+{!> ../../../docs_src/dependencies/tutorial002.py!}
+```
- ```Python hl_lines="12"
- {!> ../../../docs_src/dependencies/tutorial002.py!}
- ```
+////
... sie hat die gleichen Parameter wie unsere vorherige `common_parameters`:
-=== "Python 3.10+"
+//// tab | Python 3.10+
- ```Python hl_lines="8"
- {!> ../../../docs_src/dependencies/tutorial001_an_py310.py!}
- ```
+```Python hl_lines="8"
+{!> ../../../docs_src/dependencies/tutorial001_an_py310.py!}
+```
+
+////
-=== "Python 3.9+"
+//// tab | Python 3.9+
- ```Python hl_lines="9"
- {!> ../../../docs_src/dependencies/tutorial001_an_py39.py!}
- ```
+```Python hl_lines="9"
+{!> ../../../docs_src/dependencies/tutorial001_an_py39.py!}
+```
-=== "Python 3.8+"
+////
- ```Python hl_lines="10"
- {!> ../../../docs_src/dependencies/tutorial001_an.py!}
- ```
+//// tab | Python 3.8+
+
+```Python hl_lines="10"
+{!> ../../../docs_src/dependencies/tutorial001_an.py!}
+```
-=== "Python 3.10+ nicht annotiert"
+////
- !!! tip "Tipp"
- Bevorzugen Sie die `Annotated`-Version, falls möglich.
+//// tab | Python 3.10+ nicht annotiert
- ```Python hl_lines="6"
- {!> ../../../docs_src/dependencies/tutorial001_py310.py!}
- ```
+/// tip | "Tipp"
-=== "Python 3.8+ nicht annotiert"
+Bevorzugen Sie die `Annotated`-Version, falls möglich.
- !!! tip "Tipp"
- Bevorzugen Sie die `Annotated`-Version, falls möglich.
+///
+
+```Python hl_lines="6"
+{!> ../../../docs_src/dependencies/tutorial001_py310.py!}
+```
+
+////
+
+//// tab | Python 3.8+ nicht annotiert
+
+/// tip | "Tipp"
+
+Bevorzugen Sie die `Annotated`-Version, falls möglich.
+
+///
+
+```Python hl_lines="9"
+{!> ../../../docs_src/dependencies/tutorial001.py!}
+```
- ```Python hl_lines="9"
- {!> ../../../docs_src/dependencies/tutorial001.py!}
- ```
+////
Diese Parameter werden von **FastAPI** verwendet, um die Abhängigkeit „aufzulösen“.
Jetzt können Sie Ihre Abhängigkeit mithilfe dieser Klasse deklarieren.
-=== "Python 3.10+"
+//// tab | Python 3.10+
- ```Python hl_lines="19"
- {!> ../../../docs_src/dependencies/tutorial002_an_py310.py!}
- ```
+```Python hl_lines="19"
+{!> ../../../docs_src/dependencies/tutorial002_an_py310.py!}
+```
+
+////
+
+//// tab | Python 3.9+
+
+```Python hl_lines="19"
+{!> ../../../docs_src/dependencies/tutorial002_an_py39.py!}
+```
+
+////
+
+//// tab | Python 3.8+
+
+```Python hl_lines="20"
+{!> ../../../docs_src/dependencies/tutorial002_an.py!}
+```
-=== "Python 3.9+"
+////
- ```Python hl_lines="19"
- {!> ../../../docs_src/dependencies/tutorial002_an_py39.py!}
- ```
+//// tab | Python 3.10+ nicht annotiert
-=== "Python 3.8+"
+/// tip | "Tipp"
- ```Python hl_lines="20"
- {!> ../../../docs_src/dependencies/tutorial002_an.py!}
- ```
+Bevorzugen Sie die `Annotated`-Version, falls möglich.
-=== "Python 3.10+ nicht annotiert"
+///
- !!! tip "Tipp"
- Bevorzugen Sie die `Annotated`-Version, falls möglich.
+```Python hl_lines="17"
+{!> ../../../docs_src/dependencies/tutorial002_py310.py!}
+```
+
+////
+
+//// tab | Python 3.8+ nicht annotiert
- ```Python hl_lines="17"
- {!> ../../../docs_src/dependencies/tutorial002_py310.py!}
- ```
+/// tip | "Tipp"
-=== "Python 3.8+ nicht annotiert"
+Bevorzugen Sie die `Annotated`-Version, falls möglich.
- !!! tip "Tipp"
- Bevorzugen Sie die `Annotated`-Version, falls möglich.
+///
+
+```Python hl_lines="19"
+{!> ../../../docs_src/dependencies/tutorial002.py!}
+```
- ```Python hl_lines="19"
- {!> ../../../docs_src/dependencies/tutorial002.py!}
- ```
+////
**FastAPI** ruft die Klasse `CommonQueryParams` auf. Dadurch wird eine „Instanz“ dieser Klasse erstellt und die Instanz wird als Parameter `commons` an Ihre Funktion überreicht.
Beachten Sie, wie wir `CommonQueryParams` im obigen Code zweimal schreiben:
-=== "Python 3.8+"
+//// tab | Python 3.8+
+
+```Python
+commons: Annotated[CommonQueryParams, Depends(CommonQueryParams)]
+```
+
+////
- ```Python
- commons: Annotated[CommonQueryParams, Depends(CommonQueryParams)]
- ```
+//// tab | Python 3.8+ nicht annotiert
-=== "Python 3.8+ nicht annotiert"
+/// tip | "Tipp"
- !!! tip "Tipp"
- Bevorzugen Sie die `Annotated`-Version, falls möglich.
+Bevorzugen Sie die `Annotated`-Version, falls möglich.
- ```Python
- commons: CommonQueryParams = Depends(CommonQueryParams)
- ```
+///
+
+```Python
+commons: CommonQueryParams = Depends(CommonQueryParams)
+```
+
+////
Das letzte `CommonQueryParams`, in:
In diesem Fall hat das erste `CommonQueryParams` in:
-=== "Python 3.8+"
+//// tab | Python 3.8+
+
+```Python
+commons: Annotated[CommonQueryParams, ...
+```
+
+////
- ```Python
- commons: Annotated[CommonQueryParams, ...
- ```
+//// tab | Python 3.8+ nicht annotiert
-=== "Python 3.8+ nicht annotiert"
+/// tip | "Tipp"
- !!! tip "Tipp"
- Bevorzugen Sie die `Annotated`-Version, falls möglich.
+Bevorzugen Sie die `Annotated`-Version, falls möglich.
- ```Python
- commons: CommonQueryParams ...
- ```
+///
+
+```Python
+commons: CommonQueryParams ...
+```
+
+////
... keine besondere Bedeutung für **FastAPI**. FastAPI verwendet es nicht für die Datenkonvertierung, -validierung, usw. (da es dafür `Depends(CommonQueryParams)` verwendet).
Sie könnten tatsächlich einfach schreiben:
-=== "Python 3.8+"
+//// tab | Python 3.8+
+
+```Python
+commons: Annotated[Any, Depends(CommonQueryParams)]
+```
- ```Python
- commons: Annotated[Any, Depends(CommonQueryParams)]
- ```
+////
-=== "Python 3.8+ nicht annotiert"
+//// tab | Python 3.8+ nicht annotiert
- !!! tip "Tipp"
- Bevorzugen Sie die `Annotated`-Version, falls möglich.
+/// tip | "Tipp"
- ```Python
- commons = Depends(CommonQueryParams)
- ```
+Bevorzugen Sie die `Annotated`-Version, falls möglich.
+
+///
+
+```Python
+commons = Depends(CommonQueryParams)
+```
+
+////
... wie in:
-=== "Python 3.10+"
+//// tab | Python 3.10+
+
+```Python hl_lines="19"
+{!> ../../../docs_src/dependencies/tutorial003_an_py310.py!}
+```
+
+////
+
+//// tab | Python 3.9+
+
+```Python hl_lines="19"
+{!> ../../../docs_src/dependencies/tutorial003_an_py39.py!}
+```
+
+////
+
+//// tab | Python 3.8+
- ```Python hl_lines="19"
- {!> ../../../docs_src/dependencies/tutorial003_an_py310.py!}
- ```
+```Python hl_lines="20"
+{!> ../../../docs_src/dependencies/tutorial003_an.py!}
+```
+
+////
-=== "Python 3.9+"
+//// tab | Python 3.10+ nicht annotiert
- ```Python hl_lines="19"
- {!> ../../../docs_src/dependencies/tutorial003_an_py39.py!}
- ```
+/// tip | "Tipp"
-=== "Python 3.8+"
+Bevorzugen Sie die `Annotated`-Version, falls möglich.
- ```Python hl_lines="20"
- {!> ../../../docs_src/dependencies/tutorial003_an.py!}
- ```
+///
-=== "Python 3.10+ nicht annotiert"
+```Python hl_lines="17"
+{!> ../../../docs_src/dependencies/tutorial003_py310.py!}
+```
- !!! tip "Tipp"
- Bevorzugen Sie die `Annotated`-Version, falls möglich.
+////
- ```Python hl_lines="17"
- {!> ../../../docs_src/dependencies/tutorial003_py310.py!}
- ```
+//// tab | Python 3.8+ nicht annotiert
-=== "Python 3.8+ nicht annotiert"
+/// tip | "Tipp"
- !!! tip "Tipp"
- Bevorzugen Sie die `Annotated`-Version, falls möglich.
+Bevorzugen Sie die `Annotated`-Version, falls möglich.
- ```Python hl_lines="19"
- {!> ../../../docs_src/dependencies/tutorial003.py!}
- ```
+///
+
+```Python hl_lines="19"
+{!> ../../../docs_src/dependencies/tutorial003.py!}
+```
+
+////
Es wird jedoch empfohlen, den Typ zu deklarieren, da Ihr Editor so weiß, was als Parameter `commons` übergeben wird, und Ihnen dann bei der Codevervollständigung, Typprüfungen, usw. helfen kann:
Aber Sie sehen, dass wir hier etwas Codeduplizierung haben, indem wir `CommonQueryParams` zweimal schreiben:
-=== "Python 3.8+"
+//// tab | Python 3.8+
+
+```Python
+commons: Annotated[CommonQueryParams, Depends(CommonQueryParams)]
+```
+
+////
+
+//// tab | Python 3.8+ nicht annotiert
+
+/// tip | "Tipp"
- ```Python
- commons: Annotated[CommonQueryParams, Depends(CommonQueryParams)]
- ```
+Bevorzugen Sie die `Annotated`-Version, falls möglich.
-=== "Python 3.8+ nicht annotiert"
+///
- !!! tip "Tipp"
- Bevorzugen Sie die `Annotated`-Version, falls möglich.
+```Python
+commons: CommonQueryParams = Depends(CommonQueryParams)
+```
- ```Python
- commons: CommonQueryParams = Depends(CommonQueryParams)
- ```
+////
**FastAPI** bietet eine Abkürzung für diese Fälle, wo die Abhängigkeit *speziell* eine Klasse ist, welche **FastAPI** aufruft, um eine Instanz der Klasse selbst zu erstellen.
Anstatt zu schreiben:
-=== "Python 3.8+"
+//// tab | Python 3.8+
- ```Python
- commons: Annotated[CommonQueryParams, Depends(CommonQueryParams)]
- ```
+```Python
+commons: Annotated[CommonQueryParams, Depends(CommonQueryParams)]
+```
+
+////
-=== "Python 3.8+ nicht annotiert"
+//// tab | Python 3.8+ nicht annotiert
- !!! tip "Tipp"
- Bevorzugen Sie die `Annotated`-Version, falls möglich.
+/// tip | "Tipp"
- ```Python
- commons: CommonQueryParams = Depends(CommonQueryParams)
- ```
+Bevorzugen Sie die `Annotated`-Version, falls möglich.
+
+///
+
+```Python
+commons: CommonQueryParams = Depends(CommonQueryParams)
+```
+
+////
... schreiben Sie:
-=== "Python 3.8+"
+//// tab | Python 3.8+
- ```Python
- commons: Annotated[CommonQueryParams, Depends()]
- ```
+```Python
+commons: Annotated[CommonQueryParams, Depends()]
+```
-=== "Python 3.8 nicht annotiert"
+////
- !!! tip "Tipp"
- Bevorzugen Sie die `Annotated`-Version, falls möglich.
+//// tab | Python 3.8 nicht annotiert
- ```Python
- commons: CommonQueryParams = Depends()
- ```
+/// tip | "Tipp"
+
+Bevorzugen Sie die `Annotated`-Version, falls möglich.
+
+///
+
+```Python
+commons: CommonQueryParams = Depends()
+```
+
+////
Sie deklarieren die Abhängigkeit als Typ des Parameters und verwenden `Depends()` ohne Parameter, anstatt die vollständige Klasse *erneut* in `Depends(CommonQueryParams)` schreiben zu müssen.
Dasselbe Beispiel würde dann so aussehen:
-=== "Python 3.10+"
+//// tab | Python 3.10+
+
+```Python hl_lines="19"
+{!> ../../../docs_src/dependencies/tutorial004_an_py310.py!}
+```
+
+////
+
+//// tab | Python 3.9+
+
+```Python hl_lines="19"
+{!> ../../../docs_src/dependencies/tutorial004_an_py39.py!}
+```
+
+////
- ```Python hl_lines="19"
- {!> ../../../docs_src/dependencies/tutorial004_an_py310.py!}
- ```
+//// tab | Python 3.8+
-=== "Python 3.9+"
+```Python hl_lines="20"
+{!> ../../../docs_src/dependencies/tutorial004_an.py!}
+```
+
+////
- ```Python hl_lines="19"
- {!> ../../../docs_src/dependencies/tutorial004_an_py39.py!}
- ```
+//// tab | Python 3.10+ nicht annotiert
-=== "Python 3.8+"
+/// tip | "Tipp"
- ```Python hl_lines="20"
- {!> ../../../docs_src/dependencies/tutorial004_an.py!}
- ```
+Bevorzugen Sie die `Annotated`-Version, falls möglich.
-=== "Python 3.10+ nicht annotiert"
+///
- !!! tip "Tipp"
- Bevorzugen Sie die `Annotated`-Version, falls möglich.
+```Python hl_lines="17"
+{!> ../../../docs_src/dependencies/tutorial004_py310.py!}
+```
- ```Python hl_lines="17"
- {!> ../../../docs_src/dependencies/tutorial004_py310.py!}
- ```
+////
-=== "Python 3.8+ nicht annotiert"
+//// tab | Python 3.8+ nicht annotiert
- !!! tip "Tipp"
- Bevorzugen Sie die `Annotated`-Version, falls möglich.
+/// tip | "Tipp"
- ```Python hl_lines="19"
- {!> ../../../docs_src/dependencies/tutorial004.py!}
- ```
+Bevorzugen Sie die `Annotated`-Version, falls möglich.
+
+///
+
+```Python hl_lines="19"
+{!> ../../../docs_src/dependencies/tutorial004.py!}
+```
+
+////
... und **FastAPI** wird wissen, was zu tun ist.
-!!! tip "Tipp"
- Wenn Sie das eher verwirrt, als Ihnen zu helfen, ignorieren Sie es, Sie *brauchen* es nicht.
+/// tip | "Tipp"
+
+Wenn Sie das eher verwirrt, als Ihnen zu helfen, ignorieren Sie es, Sie *brauchen* es nicht.
+
+Es ist nur eine Abkürzung. Es geht **FastAPI** darum, Ihnen dabei zu helfen, Codeverdoppelung zu minimieren.
- Es ist nur eine Abkürzung. Es geht **FastAPI** darum, Ihnen dabei zu helfen, Codeverdoppelung zu minimieren.
+///
Es sollte eine `list`e von `Depends()` sein:
-=== "Python 3.9+"
+//// tab | Python 3.9+
- ```Python hl_lines="19"
- {!> ../../../docs_src/dependencies/tutorial006_an_py39.py!}
- ```
+```Python hl_lines="19"
+{!> ../../../docs_src/dependencies/tutorial006_an_py39.py!}
+```
-=== "Python 3.8+"
+////
- ```Python hl_lines="18"
- {!> ../../../docs_src/dependencies/tutorial006_an.py!}
- ```
+//// tab | Python 3.8+
-=== "Python 3.8 nicht annotiert"
+```Python hl_lines="18"
+{!> ../../../docs_src/dependencies/tutorial006_an.py!}
+```
- !!! tip "Tipp"
- Bevorzugen Sie die `Annotated`-Version, falls möglich.
+////
- ```Python hl_lines="17"
- {!> ../../../docs_src/dependencies/tutorial006.py!}
- ```
+//// tab | Python 3.8 nicht annotiert
+
+/// tip | "Tipp"
+
+Bevorzugen Sie die `Annotated`-Version, falls möglich.
+
+///
+
+```Python hl_lines="17"
+{!> ../../../docs_src/dependencies/tutorial006.py!}
+```
+
+////
Diese Abhängigkeiten werden auf die gleiche Weise wie normale Abhängigkeiten ausgeführt/aufgelöst. Aber ihr Wert (falls sie einen zurückgeben) wird nicht an Ihre *Pfadoperation-Funktion* übergeben.
-!!! tip "Tipp"
- Einige Editoren prüfen, ob Funktionsparameter nicht verwendet werden, und zeigen das als Fehler an.
+/// tip | "Tipp"
+
+Einige Editoren prüfen, ob Funktionsparameter nicht verwendet werden, und zeigen das als Fehler an.
- Wenn Sie `dependencies` im *Pfadoperation-Dekorator* verwenden, stellen Sie sicher, dass sie ausgeführt werden, während gleichzeitig Ihr Editor/Ihre Tools keine Fehlermeldungen ausgeben.
+Wenn Sie `dependencies` im *Pfadoperation-Dekorator* verwenden, stellen Sie sicher, dass sie ausgeführt werden, während gleichzeitig Ihr Editor/Ihre Tools keine Fehlermeldungen ausgeben.
- Damit wird auch vermieden, neue Entwickler möglicherweise zu verwirren, die einen nicht verwendeten Parameter in Ihrem Code sehen und ihn für unnötig halten könnten.
+Damit wird auch vermieden, neue Entwickler möglicherweise zu verwirren, die einen nicht verwendeten Parameter in Ihrem Code sehen und ihn für unnötig halten könnten.
-!!! info
- In diesem Beispiel verwenden wir zwei erfundene benutzerdefinierte Header `X-Key` und `X-Token`.
+///
- Aber in realen Fällen würden Sie bei der Implementierung von Sicherheit mehr Vorteile durch die Verwendung der integrierten [Sicherheits-Werkzeuge (siehe nächstes Kapitel)](../security/index.md){.internal-link target=_blank} erzielen.
+/// info
+
+In diesem Beispiel verwenden wir zwei erfundene benutzerdefinierte Header `X-Key` und `X-Token`.
+
+Aber in realen Fällen würden Sie bei der Implementierung von Sicherheit mehr Vorteile durch die Verwendung der integrierten [Sicherheits-Werkzeuge (siehe nächstes Kapitel)](../security/index.md){.internal-link target=_blank} erzielen.
+
+///
## Abhängigkeitsfehler und -Rückgabewerte
Sie können Anforderungen für einen Request (wie Header) oder andere Unterabhängigkeiten deklarieren:
-=== "Python 3.9+"
+//// tab | Python 3.9+
+
+```Python hl_lines="8 13"
+{!> ../../../docs_src/dependencies/tutorial006_an_py39.py!}
+```
+
+////
+
+//// tab | Python 3.8+
- ```Python hl_lines="8 13"
- {!> ../../../docs_src/dependencies/tutorial006_an_py39.py!}
- ```
+```Python hl_lines="7 12"
+{!> ../../../docs_src/dependencies/tutorial006_an.py!}
+```
-=== "Python 3.8+"
+////
- ```Python hl_lines="7 12"
- {!> ../../../docs_src/dependencies/tutorial006_an.py!}
- ```
+//// tab | Python 3.8 nicht annotiert
-=== "Python 3.8 nicht annotiert"
+/// tip | "Tipp"
- !!! tip "Tipp"
- Bevorzugen Sie die `Annotated`-Version, falls möglich.
+Bevorzugen Sie die `Annotated`-Version, falls möglich.
- ```Python hl_lines="6 11"
- {!> ../../../docs_src/dependencies/tutorial006.py!}
- ```
+///
+
+```Python hl_lines="6 11"
+{!> ../../../docs_src/dependencies/tutorial006.py!}
+```
+
+////
### Exceptions auslösen
Die Abhängigkeiten können Exceptions `raise`n, genau wie normale Abhängigkeiten:
-=== "Python 3.9+"
+//// tab | Python 3.9+
+
+```Python hl_lines="10 15"
+{!> ../../../docs_src/dependencies/tutorial006_an_py39.py!}
+```
+
+////
+
+//// tab | Python 3.8+
+
+```Python hl_lines="9 14"
+{!> ../../../docs_src/dependencies/tutorial006_an.py!}
+```
- ```Python hl_lines="10 15"
- {!> ../../../docs_src/dependencies/tutorial006_an_py39.py!}
- ```
+////
-=== "Python 3.8+"
+//// tab | Python 3.8 nicht annotiert
- ```Python hl_lines="9 14"
- {!> ../../../docs_src/dependencies/tutorial006_an.py!}
- ```
+/// tip | "Tipp"
-=== "Python 3.8 nicht annotiert"
+Bevorzugen Sie die `Annotated`-Version, falls möglich.
- !!! tip "Tipp"
- Bevorzugen Sie die `Annotated`-Version, falls möglich.
+///
- ```Python hl_lines="8 13"
- {!> ../../../docs_src/dependencies/tutorial006.py!}
- ```
+```Python hl_lines="8 13"
+{!> ../../../docs_src/dependencies/tutorial006.py!}
+```
+
+////
### Rückgabewerte
Sie können also eine normale Abhängigkeit (die einen Wert zurückgibt), die Sie bereits an anderer Stelle verwenden, wiederverwenden, und auch wenn der Wert nicht verwendet wird, wird die Abhängigkeit ausgeführt:
-=== "Python 3.9+"
+//// tab | Python 3.9+
+
+```Python hl_lines="11 16"
+{!> ../../../docs_src/dependencies/tutorial006_an_py39.py!}
+```
+
+////
+
+//// tab | Python 3.8+
+
+```Python hl_lines="10 15"
+{!> ../../../docs_src/dependencies/tutorial006_an.py!}
+```
+
+////
- ```Python hl_lines="11 16"
- {!> ../../../docs_src/dependencies/tutorial006_an_py39.py!}
- ```
+//// tab | Python 3.8 nicht annotiert
-=== "Python 3.8+"
+/// tip | "Tipp"
- ```Python hl_lines="10 15"
- {!> ../../../docs_src/dependencies/tutorial006_an.py!}
- ```
+Bevorzugen Sie die `Annotated`-Version, falls möglich.
-=== "Python 3.8 nicht annotiert"
+///
- !!! tip "Tipp"
- Bevorzugen Sie die `Annotated`-Version, falls möglich.
+```Python hl_lines="9 14"
+{!> ../../../docs_src/dependencies/tutorial006.py!}
+```
- ```Python hl_lines="9 14"
- {!> ../../../docs_src/dependencies/tutorial006.py!}
- ```
+////
## Abhängigkeiten für eine Gruppe von *Pfadoperationen*
Verwenden Sie dazu `yield` statt `return` und schreiben Sie die zusätzlichen Schritte / den zusätzlichen Code danach.
-!!! tip "Tipp"
- Stellen Sie sicher, dass Sie `yield` nur einmal pro Abhängigkeit verwenden.
+/// tip | "Tipp"
-!!! note "Technische Details"
- Jede Funktion, die dekoriert werden kann mit:
+Stellen Sie sicher, dass Sie `yield` nur einmal pro Abhängigkeit verwenden.
- * <a href="https://docs.python.org/3/library/contextlib.html#contextlib.contextmanager" class="external-link" target="_blank">`@contextlib.contextmanager`</a> oder
- * <a href="https://docs.python.org/3/library/contextlib.html#contextlib.asynccontextmanager" class="external-link" target="_blank">`@contextlib.asynccontextmanager`</a>
+///
- kann auch als gültige **FastAPI**-Abhängigkeit verwendet werden.
+/// note | "Technische Details"
- Tatsächlich verwendet FastAPI diese beiden Dekoratoren intern.
+Jede Funktion, die dekoriert werden kann mit:
+
+* <a href="https://docs.python.org/3/library/contextlib.html#contextlib.contextmanager" class="external-link" target="_blank">`@contextlib.contextmanager`</a> oder
+* <a href="https://docs.python.org/3/library/contextlib.html#contextlib.asynccontextmanager" class="external-link" target="_blank">`@contextlib.asynccontextmanager`</a>
+
+kann auch als gültige **FastAPI**-Abhängigkeit verwendet werden.
+
+Tatsächlich verwendet FastAPI diese beiden Dekoratoren intern.
+
+///
## Eine Datenbank-Abhängigkeit mit `yield`.
{!../../../docs_src/dependencies/tutorial007.py!}
```
-!!! tip "Tipp"
- Sie können `async`hrone oder reguläre Funktionen verwenden.
+/// tip | "Tipp"
+
+Sie können `async`hrone oder reguläre Funktionen verwenden.
+
+**FastAPI** wird bei jeder das Richtige tun, so wie auch bei normalen Abhängigkeiten.
- **FastAPI** wird bei jeder das Richtige tun, so wie auch bei normalen Abhängigkeiten.
+///
## Eine Abhängigkeit mit `yield` und `try`.
Beispielsweise kann `dependency_c` von `dependency_b` und `dependency_b` von `dependency_a` abhängen:
-=== "Python 3.9+"
+//// tab | Python 3.9+
+
+```Python hl_lines="6 14 22"
+{!> ../../../docs_src/dependencies/tutorial008_an_py39.py!}
+```
+
+////
+
+//// tab | Python 3.8+
+
+```Python hl_lines="5 13 21"
+{!> ../../../docs_src/dependencies/tutorial008_an.py!}
+```
+
+////
- ```Python hl_lines="6 14 22"
- {!> ../../../docs_src/dependencies/tutorial008_an_py39.py!}
- ```
+//// tab | Python 3.8+ nicht annotiert
-=== "Python 3.8+"
+/// tip | "Tipp"
- ```Python hl_lines="5 13 21"
- {!> ../../../docs_src/dependencies/tutorial008_an.py!}
- ```
+Bevorzugen Sie die `Annotated`-Version, falls möglich.
-=== "Python 3.8+ nicht annotiert"
+///
- !!! tip "Tipp"
- Bevorzugen Sie die `Annotated`-Version, falls möglich.
+```Python hl_lines="4 12 20"
+{!> ../../../docs_src/dependencies/tutorial008.py!}
+```
- ```Python hl_lines="4 12 20"
- {!> ../../../docs_src/dependencies/tutorial008.py!}
- ```
+////
Und alle können `yield` verwenden.
Und wiederum benötigt `dependency_b` den Wert von `dependency_a` (hier `dep_a` genannt) für seinen Exit-Code.
-=== "Python 3.9+"
+//// tab | Python 3.9+
- ```Python hl_lines="18-19 26-27"
- {!> ../../../docs_src/dependencies/tutorial008_an_py39.py!}
- ```
+```Python hl_lines="18-19 26-27"
+{!> ../../../docs_src/dependencies/tutorial008_an_py39.py!}
+```
+
+////
-=== "Python 3.8+"
+//// tab | Python 3.8+
- ```Python hl_lines="17-18 25-26"
- {!> ../../../docs_src/dependencies/tutorial008_an.py!}
- ```
+```Python hl_lines="17-18 25-26"
+{!> ../../../docs_src/dependencies/tutorial008_an.py!}
+```
-=== "Python 3.8+ nicht annotiert"
+////
- !!! tip "Tipp"
- Bevorzugen Sie die `Annotated`-Version, falls möglich.
+//// tab | Python 3.8+ nicht annotiert
+
+/// tip | "Tipp"
+
+Bevorzugen Sie die `Annotated`-Version, falls möglich.
+
+///
+
+```Python hl_lines="16-17 24-25"
+{!> ../../../docs_src/dependencies/tutorial008.py!}
+```
- ```Python hl_lines="16-17 24-25"
- {!> ../../../docs_src/dependencies/tutorial008.py!}
- ```
+////
Auf die gleiche Weise könnten Sie einige Abhängigkeiten mit `yield` und einige andere Abhängigkeiten mit `return` haben, und alle können beliebig voneinander abhängen.
**FastAPI** stellt sicher, dass alles in der richtigen Reihenfolge ausgeführt wird.
-!!! note "Technische Details"
- Dieses funktioniert dank Pythons <a href="https://docs.python.org/3/library/contextlib.html" class="external-link" target="_blank">Kontextmanager</a>.
+/// note | "Technische Details"
- **FastAPI** verwendet sie intern, um das zu erreichen.
+Dieses funktioniert dank Pythons <a href="https://docs.python.org/3/library/contextlib.html" class="external-link" target="_blank">Kontextmanager</a>.
+
+**FastAPI** verwendet sie intern, um das zu erreichen.
+
+///
## Abhängigkeiten mit `yield` und `HTTPException`.
Auf die gleiche Weise könnten Sie im Exit-Code nach dem `yield` eine `HTTPException` oder ähnliches auslösen.
-!!! tip "Tipp"
+/// tip | "Tipp"
+
+Dies ist eine etwas fortgeschrittene Technik, die Sie in den meisten Fällen nicht wirklich benötigen, da Sie Exceptions (einschließlich `HTTPException`) innerhalb des restlichen Anwendungscodes auslösen können, beispielsweise in der *Pfadoperation-Funktion*.
- Dies ist eine etwas fortgeschrittene Technik, die Sie in den meisten Fällen nicht wirklich benötigen, da Sie Exceptions (einschließlich `HTTPException`) innerhalb des restlichen Anwendungscodes auslösen können, beispielsweise in der *Pfadoperation-Funktion*.
+Aber es ist für Sie da, wenn Sie es brauchen. 🤓
- Aber es ist für Sie da, wenn Sie es brauchen. 🤓
+///
-=== "Python 3.9+"
+//// tab | Python 3.9+
- ```Python hl_lines="18-22 31"
- {!> ../../../docs_src/dependencies/tutorial008b_an_py39.py!}
- ```
+```Python hl_lines="18-22 31"
+{!> ../../../docs_src/dependencies/tutorial008b_an_py39.py!}
+```
+
+////
-=== "Python 3.8+"
+//// tab | Python 3.8+
- ```Python hl_lines="17-21 30"
- {!> ../../../docs_src/dependencies/tutorial008b_an.py!}
- ```
+```Python hl_lines="17-21 30"
+{!> ../../../docs_src/dependencies/tutorial008b_an.py!}
+```
-=== "Python 3.8+ nicht annotiert"
+////
- !!! tip "Tipp"
- Bevorzugen Sie die `Annotated`-Version, falls möglich.
+//// tab | Python 3.8+ nicht annotiert
+
+/// tip | "Tipp"
+
+Bevorzugen Sie die `Annotated`-Version, falls möglich.
+
+///
+
+```Python hl_lines="16-20 29"
+{!> ../../../docs_src/dependencies/tutorial008b.py!}
+```
- ```Python hl_lines="16-20 29"
- {!> ../../../docs_src/dependencies/tutorial008b.py!}
- ```
+////
Eine Alternative zum Abfangen von Exceptions (und möglicherweise auch zum Auslösen einer weiteren `HTTPException`) besteht darin, einen [benutzerdefinierten Exceptionhandler](../handling-errors.md#benutzerdefinierte-exceptionhandler-definieren){.internal-link target=_blank} zu erstellen.
end
```
-!!! info
- Es wird nur **eine Response** an den Client gesendet. Es kann eine Error-Response oder die Response der *Pfadoperation* sein.
+/// info
- Nachdem eine dieser Responses gesendet wurde, kann keine weitere Response gesendet werden.
+Es wird nur **eine Response** an den Client gesendet. Es kann eine Error-Response oder die Response der *Pfadoperation* sein.
-!!! tip "Tipp"
- Obiges Diagramm verwendet `HTTPException`, aber Sie können auch jede andere Exception auslösen, die Sie in einer Abhängigkeit mit `yield` abfangen, oder mit einem [benutzerdefinierten Exceptionhandler](../handling-errors.md#benutzerdefinierte-exceptionhandler-definieren){.internal-link target=_blank} erstellt haben.
+Nachdem eine dieser Responses gesendet wurde, kann keine weitere Response gesendet werden.
- Wenn Sie eine Exception auslösen, wird diese mit yield an die Abhängigkeiten übergeben, einschließlich `HTTPException`, und dann **erneut** an die Exceptionhandler. Wenn es für diese Exception keinen Exceptionhandler gibt, wird sie von der internen Default-`ServerErrorMiddleware` gehandhabt, was einen HTTP-Statuscode 500 zurückgibt, um den Client darüber zu informieren, dass ein Fehler auf dem Server aufgetreten ist.
+///
+
+/// tip | "Tipp"
+
+Obiges Diagramm verwendet `HTTPException`, aber Sie können auch jede andere Exception auslösen, die Sie in einer Abhängigkeit mit `yield` abfangen, oder mit einem [benutzerdefinierten Exceptionhandler](../handling-errors.md#benutzerdefinierte-exceptionhandler-definieren){.internal-link target=_blank} erstellt haben.
+
+Wenn Sie eine Exception auslösen, wird diese mit yield an die Abhängigkeiten übergeben, einschließlich `HTTPException`, und dann **erneut** an die Exceptionhandler. Wenn es für diese Exception keinen Exceptionhandler gibt, wird sie von der internen Default-`ServerErrorMiddleware` gehandhabt, was einen HTTP-Statuscode 500 zurückgibt, um den Client darüber zu informieren, dass ein Fehler auf dem Server aufgetreten ist.
+
+///
## Abhängigkeiten mit `yield`, `HTTPException` und Hintergrundtasks
-!!! warning "Achtung"
- Sie benötigen diese technischen Details höchstwahrscheinlich nicht, Sie können diesen Abschnitt überspringen und weiter unten fortfahren.
+/// warning | "Achtung"
+
+Sie benötigen diese technischen Details höchstwahrscheinlich nicht, Sie können diesen Abschnitt überspringen und weiter unten fortfahren.
+
+Diese Details sind vor allem dann nützlich, wenn Sie eine Version von FastAPI vor 0.106.0 verwendet haben und Ressourcen aus Abhängigkeiten mit `yield` in Hintergrundtasks verwendet haben.
- Diese Details sind vor allem dann nützlich, wenn Sie eine Version von FastAPI vor 0.106.0 verwendet haben und Ressourcen aus Abhängigkeiten mit `yield` in Hintergrundtasks verwendet haben.
+///
Vor FastAPI 0.106.0 war das Auslösen von Exceptions nach `yield` nicht möglich, der Exit-Code in Abhängigkeiten mit `yield` wurde ausgeführt, *nachdem* die Response gesendet wurde, die [Exceptionhandler](../handling-errors.md#benutzerdefinierte-exceptionhandler-definieren){.internal-link target=_blank} wären also bereits ausgeführt worden.
Da dies jedoch bedeuten würde, darauf zu warten, dass die Response durch das Netzwerk reist, während eine Ressource unnötigerweise in einer Abhängigkeit mit yield gehalten wird (z. B. eine Datenbankverbindung), wurde dies in FastAPI 0.106.0 geändert.
-!!! tip "Tipp"
+/// tip | "Tipp"
- Darüber hinaus handelt es sich bei einem Hintergrundtask normalerweise um einen unabhängigen Satz von Logik, der separat behandelt werden sollte, mit eigenen Ressourcen (z. B. einer eigenen Datenbankverbindung).
+Darüber hinaus handelt es sich bei einem Hintergrundtask normalerweise um einen unabhängigen Satz von Logik, der separat behandelt werden sollte, mit eigenen Ressourcen (z. B. einer eigenen Datenbankverbindung).
- Auf diese Weise erhalten Sie wahrscheinlich saubereren Code.
+Auf diese Weise erhalten Sie wahrscheinlich saubereren Code.
+
+///
Wenn Sie sich früher auf dieses Verhalten verlassen haben, sollten Sie jetzt die Ressourcen für Hintergrundtasks innerhalb des Hintergrundtasks selbst erstellen und intern nur Daten verwenden, die nicht von den Ressourcen von Abhängigkeiten mit `yield` abhängen.
### Kontextmanager in Abhängigkeiten mit `yield` verwenden
-!!! warning "Achtung"
- Dies ist mehr oder weniger eine „fortgeschrittene“ Idee.
+/// warning | "Achtung"
+
+Dies ist mehr oder weniger eine „fortgeschrittene“ Idee.
+
+Wenn Sie gerade erst mit **FastAPI** beginnen, möchten Sie das vielleicht vorerst überspringen.
- Wenn Sie gerade erst mit **FastAPI** beginnen, möchten Sie das vielleicht vorerst überspringen.
+///
In Python können Sie Kontextmanager erstellen, indem Sie <a href="https://docs.python.org/3/reference/datamodel.html#context-managers" class="external-link" target="_blank">eine Klasse mit zwei Methoden erzeugen: `__enter__()` und `__exit__()`</a>.
{!../../../docs_src/dependencies/tutorial010.py!}
```
-!!! tip "Tipp"
- Andere Möglichkeiten, einen Kontextmanager zu erstellen, sind:
+/// tip | "Tipp"
+
+Andere Möglichkeiten, einen Kontextmanager zu erstellen, sind:
+
+* <a href="https://docs.python.org/3/library/contextlib.html#contextlib.contextmanager" class="external-link" target="_blank">`@contextlib.contextmanager`</a> oder
+* <a href="https://docs.python.org/3/library/contextlib.html#contextlib.asynccontextmanager" class="external-link" target="_blank">`@contextlib.asynccontextmanager`</a>
- * <a href="https://docs.python.org/3/library/contextlib.html#contextlib.contextmanager" class="external-link" target="_blank">`@contextlib.contextmanager`</a> oder
- * <a href="https://docs.python.org/3/library/contextlib.html#contextlib.asynccontextmanager" class="external-link" target="_blank">`@contextlib.asynccontextmanager`</a>
+Verwenden Sie diese, um eine Funktion zu dekorieren, die ein einziges `yield` hat.
- Verwenden Sie diese, um eine Funktion zu dekorieren, die ein einziges `yield` hat.
+Das ist es auch, was **FastAPI** intern für Abhängigkeiten mit `yield` verwendet.
- Das ist es auch, was **FastAPI** intern für Abhängigkeiten mit `yield` verwendet.
+Aber Sie müssen die Dekoratoren nicht für FastAPI-Abhängigkeiten verwenden (und das sollten Sie auch nicht).
- Aber Sie müssen die Dekoratoren nicht für FastAPI-Abhängigkeiten verwenden (und das sollten Sie auch nicht).
+FastAPI erledigt das intern für Sie.
- FastAPI erledigt das intern für Sie.
+///
In diesem Fall werden sie auf alle *Pfadoperationen* in der Anwendung angewendet:
-=== "Python 3.9+"
+//// tab | Python 3.9+
- ```Python hl_lines="16"
- {!> ../../../docs_src/dependencies/tutorial012_an_py39.py!}
- ```
+```Python hl_lines="16"
+{!> ../../../docs_src/dependencies/tutorial012_an_py39.py!}
+```
-=== "Python 3.8+"
+////
- ```Python hl_lines="16"
- {!> ../../../docs_src/dependencies/tutorial012_an.py!}
- ```
+//// tab | Python 3.8+
-=== "Python 3.8 nicht annotiert"
+```Python hl_lines="16"
+{!> ../../../docs_src/dependencies/tutorial012_an.py!}
+```
- !!! tip "Tipp"
- Bevorzugen Sie die `Annotated`-Version, falls möglich.
+////
- ```Python hl_lines="15"
- {!> ../../../docs_src/dependencies/tutorial012.py!}
- ```
+//// tab | Python 3.8 nicht annotiert
+
+/// tip | "Tipp"
+
+Bevorzugen Sie die `Annotated`-Version, falls möglich.
+
+///
+
+```Python hl_lines="15"
+{!> ../../../docs_src/dependencies/tutorial012.py!}
+```
+
+////
Und alle Ideen aus dem Abschnitt über das [Hinzufügen von `dependencies` zu den *Pfadoperation-Dekoratoren*](dependencies-in-path-operation-decorators.md){.internal-link target=_blank} gelten weiterhin, aber in diesem Fall für alle *Pfadoperationen* in der Anwendung.
Konzentrieren wir uns zunächst auf die Abhängigkeit - die Dependency.
Es handelt sich einfach um eine Funktion, die die gleichen Parameter entgegennimmt wie eine *Pfadoperation-Funktion*:
-=== "Python 3.10+"
+//// tab | Python 3.10+
- ```Python hl_lines="8-9"
- {!> ../../../docs_src/dependencies/tutorial001_an_py310.py!}
- ```
+```Python hl_lines="8-9"
+{!> ../../../docs_src/dependencies/tutorial001_an_py310.py!}
+```
+
+////
+
+//// tab | Python 3.9+
+
+```Python hl_lines="8-11"
+{!> ../../../docs_src/dependencies/tutorial001_an_py39.py!}
+```
+
+////
-=== "Python 3.9+"
+//// tab | Python 3.8+
- ```Python hl_lines="8-11"
- {!> ../../../docs_src/dependencies/tutorial001_an_py39.py!}
- ```
+```Python hl_lines="9-12"
+{!> ../../../docs_src/dependencies/tutorial001_an.py!}
+```
-=== "Python 3.8+"
+////
- ```Python hl_lines="9-12"
- {!> ../../../docs_src/dependencies/tutorial001_an.py!}
- ```
+//// tab | Python 3.10+ nicht annotiert
-=== "Python 3.10+ nicht annotiert"
+/// tip | "Tipp"
- !!! tip "Tipp"
- Bevorzugen Sie die `Annotated`-Version, falls möglich.
+Bevorzugen Sie die `Annotated`-Version, falls möglich.
- ```Python hl_lines="6-7"
- {!> ../../../docs_src/dependencies/tutorial001_py310.py!}
- ```
+///
-=== "Python 3.8+ nicht annotiert"
+```Python hl_lines="6-7"
+{!> ../../../docs_src/dependencies/tutorial001_py310.py!}
+```
- !!! tip "Tipp"
- Bevorzugen Sie die `Annotated`-Version, falls möglich.
+////
- ```Python hl_lines="8-11"
- {!> ../../../docs_src/dependencies/tutorial001.py!}
- ```
+//// tab | Python 3.8+ nicht annotiert
+
+/// tip | "Tipp"
+
+Bevorzugen Sie die `Annotated`-Version, falls möglich.
+
+///
+
+```Python hl_lines="8-11"
+{!> ../../../docs_src/dependencies/tutorial001.py!}
+```
+
+////
Das war's schon.
Und dann wird einfach ein `dict` zurückgegeben, welches diese Werte enthält.
-!!! info
- FastAPI unterstützt (und empfiehlt die Verwendung von) `Annotated` seit Version 0.95.0.
+/// info
+
+FastAPI unterstützt (und empfiehlt die Verwendung von) `Annotated` seit Version 0.95.0.
- Wenn Sie eine ältere Version haben, werden Sie Fehler angezeigt bekommen, wenn Sie versuchen, `Annotated` zu verwenden.
+Wenn Sie eine ältere Version haben, werden Sie Fehler angezeigt bekommen, wenn Sie versuchen, `Annotated` zu verwenden.
- Bitte [aktualisieren Sie FastAPI](../../deployment/versions.md#upgrade-der-fastapi-versionen){.internal-link target=_blank} daher mindestens zu Version 0.95.1, bevor Sie `Annotated` verwenden.
+Bitte [aktualisieren Sie FastAPI](../../deployment/versions.md#upgrade-der-fastapi-versionen){.internal-link target=_blank} daher mindestens zu Version 0.95.1, bevor Sie `Annotated` verwenden.
+
+///
### `Depends` importieren
-=== "Python 3.10+"
+//// tab | Python 3.10+
+
+```Python hl_lines="3"
+{!> ../../../docs_src/dependencies/tutorial001_an_py310.py!}
+```
+
+////
+
+//// tab | Python 3.9+
+
+```Python hl_lines="3"
+{!> ../../../docs_src/dependencies/tutorial001_an_py39.py!}
+```
+
+////
+
+//// tab | Python 3.8+
+
+```Python hl_lines="3"
+{!> ../../../docs_src/dependencies/tutorial001_an.py!}
+```
- ```Python hl_lines="3"
- {!> ../../../docs_src/dependencies/tutorial001_an_py310.py!}
- ```
+////
-=== "Python 3.9+"
+//// tab | Python 3.10+ nicht annotiert
- ```Python hl_lines="3"
- {!> ../../../docs_src/dependencies/tutorial001_an_py39.py!}
- ```
+/// tip | "Tipp"
-=== "Python 3.8+"
+Bevorzugen Sie die `Annotated`-Version, falls möglich.
+
+///
+
+```Python hl_lines="1"
+{!> ../../../docs_src/dependencies/tutorial001_py310.py!}
+```
- ```Python hl_lines="3"
- {!> ../../../docs_src/dependencies/tutorial001_an.py!}
- ```
+////
-=== "Python 3.10+ nicht annotiert"
+//// tab | Python 3.8+ nicht annotiert
- !!! tip "Tipp"
- Bevorzugen Sie die `Annotated`-Version, falls möglich.
+/// tip | "Tipp"
- ```Python hl_lines="1"
- {!> ../../../docs_src/dependencies/tutorial001_py310.py!}
- ```
+Bevorzugen Sie die `Annotated`-Version, falls möglich.
-=== "Python 3.8+ nicht annotiert"
+///
- !!! tip "Tipp"
- Bevorzugen Sie die `Annotated`-Version, falls möglich.
+```Python hl_lines="3"
+{!> ../../../docs_src/dependencies/tutorial001.py!}
+```
- ```Python hl_lines="3"
- {!> ../../../docs_src/dependencies/tutorial001.py!}
- ```
+////
### Deklarieren der Abhängigkeit im <abbr title="Das Abhängige, der Verwender der Abhängigkeit">„Dependant“</abbr>
So wie auch `Body`, `Query`, usw., verwenden Sie `Depends` mit den Parametern Ihrer *Pfadoperation-Funktion*:
-=== "Python 3.10+"
+//// tab | Python 3.10+
+
+```Python hl_lines="13 18"
+{!> ../../../docs_src/dependencies/tutorial001_an_py310.py!}
+```
+
+////
- ```Python hl_lines="13 18"
- {!> ../../../docs_src/dependencies/tutorial001_an_py310.py!}
- ```
+//// tab | Python 3.9+
-=== "Python 3.9+"
+```Python hl_lines="15 20"
+{!> ../../../docs_src/dependencies/tutorial001_an_py39.py!}
+```
+
+////
- ```Python hl_lines="15 20"
- {!> ../../../docs_src/dependencies/tutorial001_an_py39.py!}
- ```
+//// tab | Python 3.8+
-=== "Python 3.8+"
+```Python hl_lines="16 21"
+{!> ../../../docs_src/dependencies/tutorial001_an.py!}
+```
- ```Python hl_lines="16 21"
- {!> ../../../docs_src/dependencies/tutorial001_an.py!}
- ```
+////
-=== "Python 3.10+ nicht annotiert"
+//// tab | Python 3.10+ nicht annotiert
- !!! tip "Tipp"
- Bevorzugen Sie die `Annotated`-Version, falls möglich.
+/// tip | "Tipp"
- ```Python hl_lines="11 16"
- {!> ../../../docs_src/dependencies/tutorial001_py310.py!}
- ```
+Bevorzugen Sie die `Annotated`-Version, falls möglich.
-=== "Python 3.8+ nicht annotiert"
+///
- !!! tip "Tipp"
- Bevorzugen Sie die `Annotated`-Version, falls möglich.
+```Python hl_lines="11 16"
+{!> ../../../docs_src/dependencies/tutorial001_py310.py!}
+```
+
+////
+
+//// tab | Python 3.8+ nicht annotiert
+
+/// tip | "Tipp"
+
+Bevorzugen Sie die `Annotated`-Version, falls möglich.
+
+///
+
+```Python hl_lines="15 20"
+{!> ../../../docs_src/dependencies/tutorial001.py!}
+```
- ```Python hl_lines="15 20"
- {!> ../../../docs_src/dependencies/tutorial001.py!}
- ```
+////
Obwohl Sie `Depends` in den Parametern Ihrer Funktion genauso verwenden wie `Body`, `Query`, usw., funktioniert `Depends` etwas anders.
Und diese Funktion akzeptiert Parameter auf die gleiche Weise wie *Pfadoperation-Funktionen*.
-!!! tip "Tipp"
- Im nächsten Kapitel erfahren Sie, welche anderen „Dinge“, außer Funktionen, Sie als Abhängigkeiten verwenden können.
+/// tip | "Tipp"
+
+Im nächsten Kapitel erfahren Sie, welche anderen „Dinge“, außer Funktionen, Sie als Abhängigkeiten verwenden können.
+
+///
Immer wenn ein neuer Request eintrifft, kümmert sich **FastAPI** darum:
Auf diese Weise schreiben Sie gemeinsam genutzten Code nur einmal, und **FastAPI** kümmert sich darum, ihn für Ihre *Pfadoperationen* aufzurufen.
-!!! check
- Beachten Sie, dass Sie keine spezielle Klasse erstellen und diese irgendwo an **FastAPI** übergeben müssen, um sie zu „registrieren“ oder so ähnlich.
+/// check
+
+Beachten Sie, dass Sie keine spezielle Klasse erstellen und diese irgendwo an **FastAPI** übergeben müssen, um sie zu „registrieren“ oder so ähnlich.
+
+Sie übergeben es einfach an `Depends` und **FastAPI** weiß, wie der Rest erledigt wird.
- Sie übergeben es einfach an `Depends` und **FastAPI** weiß, wie der Rest erledigt wird.
+///
## `Annotated`-Abhängigkeiten wiederverwenden
Da wir jedoch `Annotated` verwenden, können wir diesen `Annotated`-Wert in einer Variablen speichern und an mehreren Stellen verwenden:
-=== "Python 3.10+"
+//// tab | Python 3.10+
+
+```Python hl_lines="12 16 21"
+{!> ../../../docs_src/dependencies/tutorial001_02_an_py310.py!}
+```
+
+////
- ```Python hl_lines="12 16 21"
- {!> ../../../docs_src/dependencies/tutorial001_02_an_py310.py!}
- ```
+//// tab | Python 3.9+
-=== "Python 3.9+"
+```Python hl_lines="14 18 23"
+{!> ../../../docs_src/dependencies/tutorial001_02_an_py39.py!}
+```
+
+////
- ```Python hl_lines="14 18 23"
- {!> ../../../docs_src/dependencies/tutorial001_02_an_py39.py!}
- ```
+//// tab | Python 3.8+
+
+```Python hl_lines="15 19 24"
+{!> ../../../docs_src/dependencies/tutorial001_02_an.py!}
+```
-=== "Python 3.8+"
+////
- ```Python hl_lines="15 19 24"
- {!> ../../../docs_src/dependencies/tutorial001_02_an.py!}
- ```
+/// tip | "Tipp"
-!!! tip "Tipp"
- Das ist schlicht Standard-Python, es wird als „Typalias“ bezeichnet und ist eigentlich nicht **FastAPI**-spezifisch.
+Das ist schlicht Standard-Python, es wird als „Typalias“ bezeichnet und ist eigentlich nicht **FastAPI**-spezifisch.
- Da **FastAPI** jedoch auf Standard-Python, einschließlich `Annotated`, basiert, können Sie diesen Trick in Ihrem Code verwenden. 😎
+Da **FastAPI** jedoch auf Standard-Python, einschließlich `Annotated`, basiert, können Sie diesen Trick in Ihrem Code verwenden. 😎
+
+///
Die Abhängigkeiten funktionieren weiterhin wie erwartet, und das **Beste daran** ist, dass die **Typinformationen erhalten bleiben**, was bedeutet, dass Ihr Editor Ihnen weiterhin **automatische Vervollständigung**, **Inline-Fehler**, usw. bieten kann. Das Gleiche gilt für andere Tools wie `mypy`.
Es spielt keine Rolle. **FastAPI** weiß, was zu tun ist.
-!!! note "Hinweis"
- Wenn Ihnen das nichts sagt, lesen Sie den [Async: *„In Eile?“*](../../async.md#in-eile){.internal-link target=_blank}-Abschnitt über `async` und `await` in der Dokumentation.
+/// note | "Hinweis"
+
+Wenn Ihnen das nichts sagt, lesen Sie den [Async: *„In Eile?“*](../../async.md#in-eile){.internal-link target=_blank}-Abschnitt über `async` und `await` in der Dokumentation.
+
+///
## Integriert in OpenAPI
Sie könnten eine erste Abhängigkeit („Dependable“) wie folgt erstellen:
-=== "Python 3.10+"
+//// tab | Python 3.10+
- ```Python hl_lines="8-9"
- {!> ../../../docs_src/dependencies/tutorial005_an_py310.py!}
- ```
+```Python hl_lines="8-9"
+{!> ../../../docs_src/dependencies/tutorial005_an_py310.py!}
+```
+
+////
-=== "Python 3.9+"
+//// tab | Python 3.9+
+
+```Python hl_lines="8-9"
+{!> ../../../docs_src/dependencies/tutorial005_an_py39.py!}
+```
- ```Python hl_lines="8-9"
- {!> ../../../docs_src/dependencies/tutorial005_an_py39.py!}
- ```
+////
+
+//// tab | Python 3.8+
+
+```Python hl_lines="9-10"
+{!> ../../../docs_src/dependencies/tutorial005_an.py!}
+```
-=== "Python 3.8+"
+////
+
+//// tab | Python 3.10 nicht annotiert
+
+/// tip | "Tipp"
+
+Bevorzugen Sie die `Annotated`-Version, falls möglich.
+
+///
+
+```Python hl_lines="6-7"
+{!> ../../../docs_src/dependencies/tutorial005_py310.py!}
+```
- ```Python hl_lines="9-10"
- {!> ../../../docs_src/dependencies/tutorial005_an.py!}
- ```
+////
-=== "Python 3.10 nicht annotiert"
+//// tab | Python 3.8 nicht annotiert
- !!! tip "Tipp"
- Bevorzugen Sie die `Annotated`-Version, falls möglich.
+/// tip | "Tipp"
- ```Python hl_lines="6-7"
- {!> ../../../docs_src/dependencies/tutorial005_py310.py!}
- ```
+Bevorzugen Sie die `Annotated`-Version, falls möglich.
-=== "Python 3.8 nicht annotiert"
+///
- !!! tip "Tipp"
- Bevorzugen Sie die `Annotated`-Version, falls möglich.
+```Python hl_lines="8-9"
+{!> ../../../docs_src/dependencies/tutorial005.py!}
+```
- ```Python hl_lines="8-9"
- {!> ../../../docs_src/dependencies/tutorial005.py!}
- ```
+////
Diese deklariert einen optionalen Abfrageparameter `q` vom Typ `str` und gibt ihn dann einfach zurück.
Dann können Sie eine weitere Abhängigkeitsfunktion (ein „Dependable“) erstellen, die gleichzeitig eine eigene Abhängigkeit deklariert (also auch ein „Dependant“ ist):
-=== "Python 3.10+"
+//// tab | Python 3.10+
+
+```Python hl_lines="13"
+{!> ../../../docs_src/dependencies/tutorial005_an_py310.py!}
+```
+
+////
+
+//// tab | Python 3.9+
+
+```Python hl_lines="13"
+{!> ../../../docs_src/dependencies/tutorial005_an_py39.py!}
+```
+
+////
+
+//// tab | Python 3.8+
+
+```Python hl_lines="14"
+{!> ../../../docs_src/dependencies/tutorial005_an.py!}
+```
+
+////
+
+//// tab | Python 3.10 nicht annotiert
- ```Python hl_lines="13"
- {!> ../../../docs_src/dependencies/tutorial005_an_py310.py!}
- ```
+/// tip | "Tipp"
-=== "Python 3.9+"
+Bevorzugen Sie die `Annotated`-Version, falls möglich.
- ```Python hl_lines="13"
- {!> ../../../docs_src/dependencies/tutorial005_an_py39.py!}
- ```
+///
-=== "Python 3.8+"
+```Python hl_lines="11"
+{!> ../../../docs_src/dependencies/tutorial005_py310.py!}
+```
- ```Python hl_lines="14"
- {!> ../../../docs_src/dependencies/tutorial005_an.py!}
- ```
+////
-=== "Python 3.10 nicht annotiert"
+//// tab | Python 3.8 nicht annotiert
- !!! tip "Tipp"
- Bevorzugen Sie die `Annotated`-Version, falls möglich.
+/// tip | "Tipp"
- ```Python hl_lines="11"
- {!> ../../../docs_src/dependencies/tutorial005_py310.py!}
- ```
+Bevorzugen Sie die `Annotated`-Version, falls möglich.
-=== "Python 3.8 nicht annotiert"
+///
- !!! tip "Tipp"
- Bevorzugen Sie die `Annotated`-Version, falls möglich.
+```Python hl_lines="13"
+{!> ../../../docs_src/dependencies/tutorial005.py!}
+```
- ```Python hl_lines="13"
- {!> ../../../docs_src/dependencies/tutorial005.py!}
- ```
+////
Betrachten wir die deklarierten Parameter:
Diese Abhängigkeit verwenden wir nun wie folgt:
-=== "Python 3.10+"
+//// tab | Python 3.10+
+
+```Python hl_lines="23"
+{!> ../../../docs_src/dependencies/tutorial005_an_py310.py!}
+```
+
+////
+
+//// tab | Python 3.9+
+
+```Python hl_lines="23"
+{!> ../../../docs_src/dependencies/tutorial005_an_py39.py!}
+```
+
+////
+
+//// tab | Python 3.8+
+
+```Python hl_lines="24"
+{!> ../../../docs_src/dependencies/tutorial005_an.py!}
+```
+
+////
- ```Python hl_lines="23"
- {!> ../../../docs_src/dependencies/tutorial005_an_py310.py!}
- ```
+//// tab | Python 3.10 nicht annotiert
-=== "Python 3.9+"
+/// tip | "Tipp"
- ```Python hl_lines="23"
- {!> ../../../docs_src/dependencies/tutorial005_an_py39.py!}
- ```
+Bevorzugen Sie die `Annotated`-Version, falls möglich.
-=== "Python 3.8+"
+///
- ```Python hl_lines="24"
- {!> ../../../docs_src/dependencies/tutorial005_an.py!}
- ```
+```Python hl_lines="19"
+{!> ../../../docs_src/dependencies/tutorial005_py310.py!}
+```
+
+////
-=== "Python 3.10 nicht annotiert"
+//// tab | Python 3.8 nicht annotiert
- !!! tip "Tipp"
- Bevorzugen Sie die `Annotated`-Version, falls möglich.
+/// tip | "Tipp"
- ```Python hl_lines="19"
- {!> ../../../docs_src/dependencies/tutorial005_py310.py!}
- ```
+Bevorzugen Sie die `Annotated`-Version, falls möglich.
-=== "Python 3.8 nicht annotiert"
+///
+
+```Python hl_lines="22"
+{!> ../../../docs_src/dependencies/tutorial005.py!}
+```
- !!! tip "Tipp"
- Bevorzugen Sie die `Annotated`-Version, falls möglich.
+////
- ```Python hl_lines="22"
- {!> ../../../docs_src/dependencies/tutorial005.py!}
- ```
+/// info
-!!! info
- Beachten Sie, dass wir in der *Pfadoperation-Funktion* nur eine einzige Abhängigkeit deklarieren, den `query_or_cookie_extractor`.
+Beachten Sie, dass wir in der *Pfadoperation-Funktion* nur eine einzige Abhängigkeit deklarieren, den `query_or_cookie_extractor`.
- Aber **FastAPI** wird wissen, dass es zuerst `query_extractor` auflösen muss, um dessen Resultat `query_or_cookie_extractor` zu übergeben, wenn dieses aufgerufen wird.
+Aber **FastAPI** wird wissen, dass es zuerst `query_extractor` auflösen muss, um dessen Resultat `query_or_cookie_extractor` zu übergeben, wenn dieses aufgerufen wird.
+
+///
```mermaid
graph TB
In einem fortgeschrittenen Szenario, bei dem Sie wissen, dass die Abhängigkeit bei jedem Schritt (möglicherweise mehrmals) in derselben Anfrage aufgerufen werden muss, anstatt den zwischengespeicherten Wert zu verwenden, können Sie den Parameter `use_cache=False` festlegen, wenn Sie `Depends` verwenden:
-=== "Python 3.8+"
+//// tab | Python 3.8+
+
+```Python hl_lines="1"
+async def needy_dependency(fresh_value: Annotated[str, Depends(get_value, use_cache=False)]):
+ return {"fresh_value": fresh_value}
+```
- ```Python hl_lines="1"
- async def needy_dependency(fresh_value: Annotated[str, Depends(get_value, use_cache=False)]):
- return {"fresh_value": fresh_value}
- ```
+////
-=== "Python 3.8+ nicht annotiert"
+//// tab | Python 3.8+ nicht annotiert
- !!! tip "Tipp"
- Bevorzugen Sie die `Annotated`-Version, falls möglich.
+/// tip | "Tipp"
- ```Python hl_lines="1"
- async def needy_dependency(fresh_value: str = Depends(get_value, use_cache=False)):
- return {"fresh_value": fresh_value}
- ```
+Bevorzugen Sie die `Annotated`-Version, falls möglich.
+
+///
+
+```Python hl_lines="1"
+async def needy_dependency(fresh_value: str = Depends(get_value, use_cache=False)):
+ return {"fresh_value": fresh_value}
+```
+
+////
## Zusammenfassung
Dennoch ist es sehr mächtig und ermöglicht Ihnen die Deklaration beliebig tief verschachtelter Abhängigkeits-„Graphen“ (Bäume).
-!!! tip "Tipp"
- All dies scheint angesichts dieser einfachen Beispiele möglicherweise nicht so nützlich zu sein.
+/// tip | "Tipp"
+
+All dies scheint angesichts dieser einfachen Beispiele möglicherweise nicht so nützlich zu sein.
+
+Aber Sie werden in den Kapiteln über **Sicherheit** sehen, wie nützlich das ist.
- Aber Sie werden in den Kapiteln über **Sicherheit** sehen, wie nützlich das ist.
+Und Sie werden auch sehen, wie viel Code Sie dadurch einsparen.
- Und Sie werden auch sehen, wie viel Code Sie dadurch einsparen.
+///
Es nimmt ein Objekt entgegen, wie etwa ein Pydantic-Modell, und gibt eine JSON-kompatible Version zurück:
-=== "Python 3.10+"
+//// tab | Python 3.10+
- ```Python hl_lines="4 21"
- {!> ../../../docs_src/encoder/tutorial001_py310.py!}
- ```
+```Python hl_lines="4 21"
+{!> ../../../docs_src/encoder/tutorial001_py310.py!}
+```
-=== "Python 3.8+"
+////
- ```Python hl_lines="5 22"
- {!> ../../../docs_src/encoder/tutorial001.py!}
- ```
+//// tab | Python 3.8+
+
+```Python hl_lines="5 22"
+{!> ../../../docs_src/encoder/tutorial001.py!}
+```
+
+////
In diesem Beispiel wird das Pydantic-Modell in ein `dict`, und das `datetime`-Objekt in ein `str` konvertiert.
Es wird also kein großer `str` zurückgegeben, der die Daten im JSON-Format (als String) enthält. Es wird eine Python-Standarddatenstruktur (z. B. ein `dict`) zurückgegeben, mit Werten und Unterwerten, die alle mit JSON kompatibel sind.
-!!! note "Hinweis"
- `jsonable_encoder` wird tatsächlich von **FastAPI** intern verwendet, um Daten zu konvertieren. Aber es ist in vielen anderen Szenarien hilfreich.
+/// note | "Hinweis"
+
+`jsonable_encoder` wird tatsächlich von **FastAPI** intern verwendet, um Daten zu konvertieren. Aber es ist in vielen anderen Szenarien hilfreich.
+
+///
Hier ist ein Beispiel für eine *Pfadoperation* mit Parametern, die einige der oben genannten Typen verwenden.
-=== "Python 3.10+"
+//// tab | Python 3.10+
- ```Python hl_lines="1 3 12-16"
- {!> ../../../docs_src/extra_data_types/tutorial001_an_py310.py!}
- ```
+```Python hl_lines="1 3 12-16"
+{!> ../../../docs_src/extra_data_types/tutorial001_an_py310.py!}
+```
-=== "Python 3.9+"
+////
- ```Python hl_lines="1 3 12-16"
- {!> ../../../docs_src/extra_data_types/tutorial001_an_py39.py!}
- ```
+//// tab | Python 3.9+
-=== "Python 3.8+"
+```Python hl_lines="1 3 12-16"
+{!> ../../../docs_src/extra_data_types/tutorial001_an_py39.py!}
+```
- ```Python hl_lines="1 3 13-17"
- {!> ../../../docs_src/extra_data_types/tutorial001_an.py!}
- ```
+////
-=== "Python 3.10+ nicht annotiert"
+//// tab | Python 3.8+
- !!! tip
- Bevorzugen Sie die `Annotated`-Version, falls möglich.
+```Python hl_lines="1 3 13-17"
+{!> ../../../docs_src/extra_data_types/tutorial001_an.py!}
+```
- ```Python hl_lines="1 2 11-15"
- {!> ../../../docs_src/extra_data_types/tutorial001_py310.py!}
- ```
+////
-=== "Python 3.8+ nicht annotiert"
+//// tab | Python 3.10+ nicht annotiert
- !!! tip
- Bevorzugen Sie die `Annotated`-Version, falls möglich.
+/// tip
- ```Python hl_lines="1 2 12-16"
- {!> ../../../docs_src/extra_data_types/tutorial001.py!}
- ```
+Bevorzugen Sie die `Annotated`-Version, falls möglich.
+
+///
+
+```Python hl_lines="1 2 11-15"
+{!> ../../../docs_src/extra_data_types/tutorial001_py310.py!}
+```
+
+////
+
+//// tab | Python 3.8+ nicht annotiert
+
+/// tip
+
+Bevorzugen Sie die `Annotated`-Version, falls möglich.
+
+///
+
+```Python hl_lines="1 2 12-16"
+{!> ../../../docs_src/extra_data_types/tutorial001.py!}
+```
+
+////
Beachten Sie, dass die Parameter innerhalb der Funktion ihren natürlichen Datentyp haben und Sie beispielsweise normale Datumsmanipulationen durchführen können, wie zum Beispiel:
-=== "Python 3.10+"
+//// tab | Python 3.10+
+
+```Python hl_lines="18-19"
+{!> ../../../docs_src/extra_data_types/tutorial001_an_py310.py!}
+```
+
+////
+
+//// tab | Python 3.9+
+
+```Python hl_lines="18-19"
+{!> ../../../docs_src/extra_data_types/tutorial001_an_py39.py!}
+```
+
+////
+
+//// tab | Python 3.8+
+
+```Python hl_lines="19-20"
+{!> ../../../docs_src/extra_data_types/tutorial001_an.py!}
+```
+
+////
+
+//// tab | Python 3.10+ nicht annotiert
- ```Python hl_lines="18-19"
- {!> ../../../docs_src/extra_data_types/tutorial001_an_py310.py!}
- ```
+/// tip
-=== "Python 3.9+"
+Bevorzugen Sie die `Annotated`-Version, falls möglich.
- ```Python hl_lines="18-19"
- {!> ../../../docs_src/extra_data_types/tutorial001_an_py39.py!}
- ```
+///
-=== "Python 3.8+"
+```Python hl_lines="17-18"
+{!> ../../../docs_src/extra_data_types/tutorial001_py310.py!}
+```
- ```Python hl_lines="19-20"
- {!> ../../../docs_src/extra_data_types/tutorial001_an.py!}
- ```
+////
-=== "Python 3.10+ nicht annotiert"
+//// tab | Python 3.8+ nicht annotiert
- !!! tip
- Bevorzugen Sie die `Annotated`-Version, falls möglich.
+/// tip
- ```Python hl_lines="17-18"
- {!> ../../../docs_src/extra_data_types/tutorial001_py310.py!}
- ```
+Bevorzugen Sie die `Annotated`-Version, falls möglich.
-=== "Python 3.8+ nicht annotiert"
+///
- !!! tip
- Bevorzugen Sie die `Annotated`-Version, falls möglich.
+```Python hl_lines="18-19"
+{!> ../../../docs_src/extra_data_types/tutorial001.py!}
+```
- ```Python hl_lines="18-19"
- {!> ../../../docs_src/extra_data_types/tutorial001.py!}
- ```
+////
* Das **herausgehende Modell** sollte kein Passwort haben.
* Das **Datenbankmodell** sollte wahrscheinlich ein <abbr title='Ein aus scheinbar zufälligen Zeichen bestehender „Fingerabdruck“ eines Textes. Der Inhalt des Textes kann nicht eingesehen werden.'>gehashtes</abbr> Passwort haben.
-!!! danger "Gefahr"
- Speichern Sie niemals das Klartext-Passwort eines Benutzers. Speichern Sie immer den „sicheren Hash“, den Sie verifizieren können.
+/// danger | "Gefahr"
- Falls Ihnen das nichts sagt, in den [Sicherheits-Kapiteln](security/simple-oauth2.md#passwort-hashing){.internal-link target=_blank} werden Sie lernen, was ein „Passwort-Hash“ ist.
+Speichern Sie niemals das Klartext-Passwort eines Benutzers. Speichern Sie immer den „sicheren Hash“, den Sie verifizieren können.
+
+Falls Ihnen das nichts sagt, in den [Sicherheits-Kapiteln](security/simple-oauth2.md#passwort-hashing){.internal-link target=_blank} werden Sie lernen, was ein „Passwort-Hash“ ist.
+
+///
## Mehrere Modelle
Hier der generelle Weg, wie die Modelle mit ihren Passwort-Feldern aussehen könnten, und an welchen Orten sie verwendet werden würden.
-=== "Python 3.10+"
+//// tab | Python 3.10+
+
+```Python hl_lines="7 9 14 20 22 27-28 31-33 38-39"
+{!> ../../../docs_src/extra_models/tutorial001_py310.py!}
+```
+
+////
+
+//// tab | Python 3.8+
+
+```Python hl_lines="9 11 16 22 24 29-30 33-35 40-41"
+{!> ../../../docs_src/extra_models/tutorial001.py!}
+```
- ```Python hl_lines="7 9 14 20 22 27-28 31-33 38-39"
- {!> ../../../docs_src/extra_models/tutorial001_py310.py!}
- ```
+////
-=== "Python 3.8+"
+/// info
- ```Python hl_lines="9 11 16 22 24 29-30 33-35 40-41"
- {!> ../../../docs_src/extra_models/tutorial001.py!}
- ```
+In Pydantic v1 hieß diese Methode `.dict()`, in Pydantic v2 wurde sie deprecated (aber immer noch unterstützt) und in `.model_dump()` umbenannt.
-!!! info
- In Pydantic v1 hieß diese Methode `.dict()`, in Pydantic v2 wurde sie deprecated (aber immer noch unterstützt) und in `.model_dump()` umbenannt.
+Die Beispiele hier verwenden `.dict()` für die Kompatibilität mit Pydantic v1, Sie sollten jedoch stattdessen `.model_dump()` verwenden, wenn Sie Pydantic v2 verwenden können.
- Die Beispiele hier verwenden `.dict()` für die Kompatibilität mit Pydantic v1, Sie sollten jedoch stattdessen `.model_dump()` verwenden, wenn Sie Pydantic v2 verwenden können.
+///
### Über `**user_in.dict()`
)
```
-!!! warning "Achtung"
- Die Hilfsfunktionen `fake_password_hasher` und `fake_save_user` demonstrieren nur den möglichen Fluss der Daten und bieten natürlich keine echte Sicherheit.
+/// warning | "Achtung"
+
+Die Hilfsfunktionen `fake_password_hasher` und `fake_save_user` demonstrieren nur den möglichen Fluss der Daten und bieten natürlich keine echte Sicherheit.
+
+///
## Verdopplung vermeiden
Auf diese Weise beschreiben wir nur noch die Unterschiede zwischen den Modellen (mit Klartext-`password`, mit `hashed_password`, und ohne Passwort):
-=== "Python 3.10+"
+//// tab | Python 3.10+
- ```Python hl_lines="7 13-14 17-18 21-22"
- {!> ../../../docs_src/extra_models/tutorial002_py310.py!}
- ```
+```Python hl_lines="7 13-14 17-18 21-22"
+{!> ../../../docs_src/extra_models/tutorial002_py310.py!}
+```
-=== "Python 3.8+"
+////
+
+//// tab | Python 3.8+
+
+```Python hl_lines="9 15-16 19-20 23-24"
+{!> ../../../docs_src/extra_models/tutorial002.py!}
+```
- ```Python hl_lines="9 15-16 19-20 23-24"
- {!> ../../../docs_src/extra_models/tutorial002.py!}
- ```
+////
## `Union`, oder `anyOf`
Um das zu tun, verwenden Sie Pythons Standard-Typhinweis <a href="https://docs.python.org/3/library/typing.html#typing.Union" class="external-link" target="_blank">`typing.Union`</a>:
-!!! note "Hinweis"
- Listen Sie, wenn Sie eine <a href="https://pydantic-docs.helpmanual.io/usage/types/#unions" class="external-link" target="_blank">`Union`</a> definieren, denjenigen Typ zuerst, der am spezifischsten ist, gefolgt von den weniger spezifischen Typen. Im Beispiel oben, in `Union[PlaneItem, CarItem]` also den spezifischeren `PlaneItem` vor dem weniger spezifischen `CarItem`.
+/// note | "Hinweis"
-=== "Python 3.10+"
+Listen Sie, wenn Sie eine <a href="https://pydantic-docs.helpmanual.io/usage/types/#unions" class="external-link" target="_blank">`Union`</a> definieren, denjenigen Typ zuerst, der am spezifischsten ist, gefolgt von den weniger spezifischen Typen. Im Beispiel oben, in `Union[PlaneItem, CarItem]` also den spezifischeren `PlaneItem` vor dem weniger spezifischen `CarItem`.
- ```Python hl_lines="1 14-15 18-20 33"
- {!> ../../../docs_src/extra_models/tutorial003_py310.py!}
- ```
+///
-=== "Python 3.8+"
+//// tab | Python 3.10+
- ```Python hl_lines="1 14-15 18-20 33"
- {!> ../../../docs_src/extra_models/tutorial003.py!}
- ```
+```Python hl_lines="1 14-15 18-20 33"
+{!> ../../../docs_src/extra_models/tutorial003_py310.py!}
+```
+
+////
+
+//// tab | Python 3.8+
+
+```Python hl_lines="1 14-15 18-20 33"
+{!> ../../../docs_src/extra_models/tutorial003.py!}
+```
+
+////
### `Union` in Python 3.10
Verwenden Sie dafür Pythons Standard `typing.List` (oder nur `list` in Python 3.9 und darüber):
-=== "Python 3.9+"
+//// tab | Python 3.9+
+
+```Python hl_lines="18"
+{!> ../../../docs_src/extra_models/tutorial004_py39.py!}
+```
+
+////
- ```Python hl_lines="18"
- {!> ../../../docs_src/extra_models/tutorial004_py39.py!}
- ```
+//// tab | Python 3.8+
-=== "Python 3.8+"
+```Python hl_lines="1 20"
+{!> ../../../docs_src/extra_models/tutorial004.py!}
+```
- ```Python hl_lines="1 20"
- {!> ../../../docs_src/extra_models/tutorial004.py!}
- ```
+////
## Response mit beliebigem `dict`
In diesem Fall können Sie `typing.Dict` verwenden (oder nur `dict` in Python 3.9 und darüber):
-=== "Python 3.9+"
+//// tab | Python 3.9+
- ```Python hl_lines="6"
- {!> ../../../docs_src/extra_models/tutorial005_py39.py!}
- ```
+```Python hl_lines="6"
+{!> ../../../docs_src/extra_models/tutorial005_py39.py!}
+```
-=== "Python 3.8+"
+////
+
+//// tab | Python 3.8+
+
+```Python hl_lines="1 8"
+{!> ../../../docs_src/extra_models/tutorial005.py!}
+```
- ```Python hl_lines="1 8"
- {!> ../../../docs_src/extra_models/tutorial005.py!}
- ```
+////
## Zusammenfassung
</div>
-!!! note "Hinweis"
- Der Befehl `uvicorn main:app` bezieht sich auf:
+/// note | "Hinweis"
- * `main`: die Datei `main.py` (das sogenannte Python-„Modul“).
- * `app`: das Objekt, welches in der Datei `main.py` mit der Zeile `app = FastAPI()` erzeugt wurde.
- * `--reload`: lässt den Server nach Codeänderungen neu starten. Verwenden Sie das nur während der Entwicklung.
+Der Befehl `uvicorn main:app` bezieht sich auf:
+
+* `main`: die Datei `main.py` (das sogenannte Python-„Modul“).
+* `app`: das Objekt, welches in der Datei `main.py` mit der Zeile `app = FastAPI()` erzeugt wurde.
+* `--reload`: lässt den Server nach Codeänderungen neu starten. Verwenden Sie das nur während der Entwicklung.
+
+///
In der Konsolenausgabe sollte es eine Zeile geben, die ungefähr so aussieht:
`FastAPI` ist eine Python-Klasse, die die gesamte Funktionalität für Ihre API bereitstellt.
-!!! note "Technische Details"
- `FastAPI` ist eine Klasse, die direkt von `Starlette` erbt.
+/// note | "Technische Details"
+
+`FastAPI` ist eine Klasse, die direkt von `Starlette` erbt.
- Sie können alle <a href="https://www.starlette.io/" class="external-link" target="_blank">Starlette</a>-Funktionalitäten auch mit `FastAPI` nutzen.
+Sie können alle <a href="https://www.starlette.io/" class="external-link" target="_blank">Starlette</a>-Funktionalitäten auch mit `FastAPI` nutzen.
+
+///
### Schritt 2: Erzeugen einer `FastAPI`-„Instanz“
/items/foo
```
-!!! info
- Ein „Pfad“ wird häufig auch als „Endpunkt“ oder „Route“ bezeichnet.
+/// info
+
+Ein „Pfad“ wird häufig auch als „Endpunkt“ oder „Route“ bezeichnet.
+
+///
Bei der Erstellung einer API ist der „Pfad“ die wichtigste Möglichkeit zur Trennung von „Anliegen“ und „Ressourcen“.
* den Pfad `/`
* unter der Verwendung der <abbr title="eine HTTP GET Methode"><code>get</code>-Operation</abbr> gehen
-!!! info "`@decorator` Information"
- Diese `@something`-Syntax wird in Python „Dekorator“ genannt.
+/// info | "`@decorator` Information"
- Sie platzieren ihn über einer Funktion. Wie ein hübscher, dekorativer Hut (daher kommt wohl der Begriff).
+Diese `@something`-Syntax wird in Python „Dekorator“ genannt.
- Ein „Dekorator“ nimmt die darunter stehende Funktion und macht etwas damit.
+Sie platzieren ihn über einer Funktion. Wie ein hübscher, dekorativer Hut (daher kommt wohl der Begriff).
- In unserem Fall teilt dieser Dekorator **FastAPI** mit, dass die folgende Funktion mit dem **Pfad** `/` und der **Operation** `get` zusammenhängt.
+Ein „Dekorator“ nimmt die darunter stehende Funktion und macht etwas damit.
- Dies ist der „**Pfadoperation-Dekorator**“.
+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.patch()`
* `@app.trace()`
-!!! tip "Tipp"
- Es steht Ihnen frei, jede Operation (HTTP-Methode) so zu verwenden, wie Sie es möchten.
+/// tip | "Tipp"
+
+Es steht Ihnen frei, jede Operation (HTTP-Methode) so zu verwenden, wie Sie es möchten.
- **FastAPI** erzwingt keine bestimmte Bedeutung.
+**FastAPI** erzwingt keine bestimmte Bedeutung.
- Die hier aufgeführten Informationen dienen als Leitfaden und sind nicht verbindlich.
+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.
+Wenn Sie beispielsweise GraphQL verwenden, führen Sie normalerweise alle Aktionen nur mit „POST“-Operationen durch.
+
+///
### Schritt 4: Definieren der **Pfadoperation-Funktion**
{!../../../docs_src/first_steps/tutorial003.py!}
```
-!!! note "Hinweis"
- Wenn Sie den Unterschied nicht kennen, lesen Sie [Async: *„In Eile?“*](../async.md#in-eile){.internal-link target=_blank}.
+/// 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
}
```
-!!! 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`.
+/// tip | "Tipp"
- Zum Beispiel ein `dict`, eine `list`, usw.
+Wenn Sie eine `HTTPException` auslösen, können Sie dem Parameter `detail` jeden Wert übergeben, der nach JSON konvertiert werden kann, nicht nur `str`.
- Das wird automatisch von **FastAPI** gehandhabt und der Wert nach JSON konvertiert.
+Zum Beispiel ein `dict`, eine `list`, usw.
+
+Das wird automatisch von **FastAPI** gehandhabt und der Wert nach JSON konvertiert.
+
+///
## Benutzerdefinierte Header hinzufügen
{"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.
+/// 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`.
- **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
#### `RequestValidationError` vs. `ValidationError`
-!!! warning "Achtung"
- Das folgende sind technische Details, die Sie überspringen können, wenn sie für Sie nicht wichtig sind.
+/// 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 <a href="https://pydantic-docs.helpmanual.io/usage/models/#error-handling" class="external-link" target="_blank">`ValidationError`</a>.
{!../../../docs_src/handling_errors/tutorial004.py!}
```
-!!! note "Technische Details"
- Sie können auch `from starlette.responses import PlainTextResponse` verwenden.
+/// 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.
- **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
Importieren Sie zuerst `Header`:
-=== "Python 3.10+"
+//// tab | Python 3.10+
- ```Python hl_lines="3"
- {!> ../../../docs_src/header_params/tutorial001_an_py310.py!}
- ```
+```Python hl_lines="3"
+{!> ../../../docs_src/header_params/tutorial001_an_py310.py!}
+```
+
+////
-=== "Python 3.9+"
+//// tab | Python 3.9+
- ```Python hl_lines="3"
- {!> ../../../docs_src/header_params/tutorial001_an_py39.py!}
- ```
+```Python hl_lines="3"
+{!> ../../../docs_src/header_params/tutorial001_an_py39.py!}
+```
-=== "Python 3.8+"
+////
- ```Python hl_lines="3"
- {!> ../../../docs_src/header_params/tutorial001_an.py!}
- ```
+//// tab | Python 3.8+
+
+```Python hl_lines="3"
+{!> ../../../docs_src/header_params/tutorial001_an.py!}
+```
-=== "Python 3.10+ nicht annotiert"
+////
- !!! tip "Tipp"
- Bevorzugen Sie die `Annotated`-Version, falls möglich.
+//// tab | Python 3.10+ nicht annotiert
- ```Python hl_lines="1"
- {!> ../../../docs_src/header_params/tutorial001_py310.py!}
- ```
+/// tip | "Tipp"
+
+Bevorzugen Sie die `Annotated`-Version, falls möglich.
+
+///
+
+```Python hl_lines="1"
+{!> ../../../docs_src/header_params/tutorial001_py310.py!}
+```
-=== "Python 3.8+ nicht annotiert"
+////
- !!! tip "Tipp"
- Bevorzugen Sie die `Annotated`-Version, falls möglich.
+//// tab | Python 3.8+ nicht annotiert
- ```Python hl_lines="3"
- {!> ../../../docs_src/header_params/tutorial001.py!}
- ```
+/// tip | "Tipp"
+
+Bevorzugen Sie die `Annotated`-Version, falls möglich.
+
+///
+
+```Python hl_lines="3"
+{!> ../../../docs_src/header_params/tutorial001.py!}
+```
+
+////
## `Header`-Parameter deklarieren
Der erste Wert ist der Typ. Sie können `Header` die gehabten Extra Validierungs- und Beschreibungsparameter hinzufügen. Danach können Sie einen Defaultwert vergeben:
-=== "Python 3.10+"
+//// tab | Python 3.10+
- ```Python hl_lines="9"
- {!> ../../../docs_src/header_params/tutorial001_an_py310.py!}
- ```
+```Python hl_lines="9"
+{!> ../../../docs_src/header_params/tutorial001_an_py310.py!}
+```
-=== "Python 3.9+"
+////
- ```Python hl_lines="9"
- {!> ../../../docs_src/header_params/tutorial001_an_py39.py!}
- ```
+//// tab | Python 3.9+
-=== "Python 3.8+"
+```Python hl_lines="9"
+{!> ../../../docs_src/header_params/tutorial001_an_py39.py!}
+```
- ```Python hl_lines="10"
- {!> ../../../docs_src/header_params/tutorial001_an.py!}
- ```
+////
-=== "Python 3.10+ nicht annotiert"
+//// tab | Python 3.8+
- !!! tip "Tipp"
- Bevorzugen Sie die `Annotated`-Version, falls möglich.
+```Python hl_lines="10"
+{!> ../../../docs_src/header_params/tutorial001_an.py!}
+```
- ```Python hl_lines="7"
- {!> ../../../docs_src/header_params/tutorial001_py310.py!}
- ```
+////
-=== "Python 3.8+ nicht annotiert"
+//// tab | Python 3.10+ nicht annotiert
- !!! tip "Tipp"
- Bevorzugen Sie die `Annotated`-Version, falls möglich.
+/// tip | "Tipp"
- ```Python hl_lines="9"
- {!> ../../../docs_src/header_params/tutorial001.py!}
- ```
+Bevorzugen Sie die `Annotated`-Version, falls möglich.
-!!! 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.
+```Python hl_lines="7"
+{!> ../../../docs_src/header_params/tutorial001_py310.py!}
+```
+
+////
+
+//// tab | Python 3.8+ nicht annotiert
+
+/// tip | "Tipp"
+
+Bevorzugen Sie die `Annotated`-Version, falls möglich.
+
+///
+
+```Python hl_lines="9"
+{!> ../../../docs_src/header_params/tutorial001.py!}
+```
-!!! info
- Um Header zu deklarieren, müssen Sie `Header` verwenden, da diese Parameter sonst als Query-Parameter interpretiert werden würden.
+////
+
+/// 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
Wenn Sie aus irgendeinem Grund das automatische Konvertieren von Unterstrichen zu Bindestrichen abschalten möchten, setzen Sie den Parameter `convert_underscores` auf `False`.
-=== "Python 3.10+"
+//// tab | Python 3.10+
+
+```Python hl_lines="10"
+{!> ../../../docs_src/header_params/tutorial002_an_py310.py!}
+```
+
+////
- ```Python hl_lines="10"
- {!> ../../../docs_src/header_params/tutorial002_an_py310.py!}
- ```
+//// tab | Python 3.9+
-=== "Python 3.9+"
+```Python hl_lines="11"
+{!> ../../../docs_src/header_params/tutorial002_an_py39.py!}
+```
- ```Python hl_lines="11"
- {!> ../../../docs_src/header_params/tutorial002_an_py39.py!}
- ```
+////
-=== "Python 3.8+"
+//// tab | Python 3.8+
+
+```Python hl_lines="12"
+{!> ../../../docs_src/header_params/tutorial002_an.py!}
+```
- ```Python hl_lines="12"
- {!> ../../../docs_src/header_params/tutorial002_an.py!}
- ```
+////
-=== "Python 3.10+ nicht annotiert"
+//// tab | Python 3.10+ nicht annotiert
- !!! tip "Tipp"
- Bevorzugen Sie die `Annotated`-Version, falls möglich.
+/// tip | "Tipp"
+
+Bevorzugen Sie die `Annotated`-Version, falls möglich.
+
+///
+
+```Python hl_lines="8"
+{!> ../../../docs_src/header_params/tutorial002_py310.py!}
+```
- ```Python hl_lines="8"
- {!> ../../../docs_src/header_params/tutorial002_py310.py!}
- ```
+////
-=== "Python 3.8+ nicht annotiert"
+//// tab | Python 3.8+ nicht annotiert
- !!! tip "Tipp"
- Bevorzugen Sie die `Annotated`-Version, falls möglich.
+/// tip | "Tipp"
- ```Python hl_lines="10"
- {!> ../../../docs_src/header_params/tutorial002.py!}
- ```
+Bevorzugen Sie die `Annotated`-Version, falls möglich.
-!!! 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.
+///
+
+```Python hl_lines="10"
+{!> ../../../docs_src/header_params/tutorial002.py!}
+```
+
+////
+
+/// warning | "Achtung"
+
+Bevor Sie `convert_underscores` auf `False` setzen, bedenken Sie, dass manche HTTP-Proxys und Server die Verwendung von Headern mit Unterstrichen nicht erlauben.
+
+///
## Doppelte Header
Um zum Beispiel einen Header `X-Token` zu deklarieren, der mehrmals vorkommen kann, schreiben Sie:
-=== "Python 3.10+"
+//// tab | Python 3.10+
- ```Python hl_lines="9"
- {!> ../../../docs_src/header_params/tutorial003_an_py310.py!}
- ```
+```Python hl_lines="9"
+{!> ../../../docs_src/header_params/tutorial003_an_py310.py!}
+```
-=== "Python 3.9+"
+////
- ```Python hl_lines="9"
- {!> ../../../docs_src/header_params/tutorial003_an_py39.py!}
- ```
+//// tab | Python 3.9+
-=== "Python 3.8+"
+```Python hl_lines="9"
+{!> ../../../docs_src/header_params/tutorial003_an_py39.py!}
+```
- ```Python hl_lines="10"
- {!> ../../../docs_src/header_params/tutorial003_an.py!}
- ```
+////
-=== "Python 3.10+ nicht annotiert"
+//// tab | Python 3.8+
- !!! tip "Tipp"
- Bevorzugen Sie die `Annotated`-Version, falls möglich.
+```Python hl_lines="10"
+{!> ../../../docs_src/header_params/tutorial003_an.py!}
+```
+
+////
+
+//// tab | Python 3.10+ nicht annotiert
+
+/// tip | "Tipp"
+
+Bevorzugen Sie die `Annotated`-Version, falls möglich.
+
+///
+
+```Python hl_lines="7"
+{!> ../../../docs_src/header_params/tutorial003_py310.py!}
+```
- ```Python hl_lines="7"
- {!> ../../../docs_src/header_params/tutorial003_py310.py!}
- ```
+////
-=== "Python 3.9+ nicht annotiert"
+//// tab | Python 3.9+ nicht annotiert
- !!! tip "Tipp"
- Bevorzugen Sie die `Annotated`-Version, falls möglich.
+/// tip | "Tipp"
- ```Python hl_lines="9"
- {!> ../../../docs_src/header_params/tutorial003_py39.py!}
- ```
+Bevorzugen Sie die `Annotated`-Version, falls möglich.
-=== "Python 3.8+ nicht annotiert"
+///
- !!! tip "Tipp"
- Bevorzugen Sie die `Annotated`-Version, falls möglich.
+```Python hl_lines="9"
+{!> ../../../docs_src/header_params/tutorial003_py39.py!}
+```
+
+////
+
+//// tab | Python 3.8+ nicht annotiert
+
+/// tip | "Tipp"
+
+Bevorzugen Sie die `Annotated`-Version, falls möglich.
+
+///
+
+```Python hl_lines="9"
+{!> ../../../docs_src/header_params/tutorial003.py!}
+```
- ```Python hl_lines="9"
- {!> ../../../docs_src/header_params/tutorial003.py!}
- ```
+////
Wenn Sie mit einer *Pfadoperation* kommunizieren, die zwei HTTP-Header sendet, wie:
... das beinhaltet auch `uvicorn`, welchen Sie als Server verwenden können, der ihren Code ausführt.
-!!! note "Hinweis"
- Sie können die einzelnen Teile auch separat installieren.
+/// note | "Hinweis"
- Das folgende würden Sie wahrscheinlich tun, wenn Sie Ihre Anwendung in der Produktion einsetzen:
+Sie können die einzelnen Teile auch separat installieren.
- ```
- pip install fastapi
- ```
+Das folgende würden Sie wahrscheinlich tun, wenn Sie Ihre Anwendung in der Produktion einsetzen:
- Installieren Sie auch `uvicorn` als Server:
+```
+pip install fastapi
+```
+
+Installieren Sie auch `uvicorn` als Server:
+
+```
+pip install "uvicorn[standard]"
+```
- ```
- pip install "uvicorn[standard]"
- ```
+Das gleiche gilt für jede der optionalen Abhängigkeiten, die Sie verwenden möchten.
- Das gleiche gilt für jede der optionalen Abhängigkeiten, die Sie verwenden möchten.
+///
## Handbuch für fortgeschrittene Benutzer
{!../../../docs_src/metadata/tutorial001.py!}
```
-!!! tip "Tipp"
- Sie können Markdown in das Feld `description` schreiben und es wird in der Ausgabe gerendert.
+/// tip | "Tipp"
+
+Sie können Markdown in das Feld `description` schreiben und es wird in der Ausgabe gerendert.
+
+///
Mit dieser Konfiguration würde die automatische API-Dokumentation wie folgt aussehen:
Beachten Sie, dass Sie Markdown in den Beschreibungen verwenden können. Beispielsweise wird „login“ in Fettschrift (**login**) und „fancy“ in Kursivschrift (_fancy_) angezeigt.
-!!! tip "Tipp"
- Sie müssen nicht für alle von Ihnen verwendeten Tags Metadaten hinzufügen.
+/// tip | "Tipp"
+
+Sie müssen nicht für alle von Ihnen verwendeten Tags Metadaten hinzufügen.
+
+///
### Ihre Tags verwenden
{!../../../docs_src/metadata/tutorial004.py!}
```
-!!! info
- Lesen Sie mehr zu Tags unter [Pfadoperation-Konfiguration](path-operation-configuration.md#tags){.internal-link target=_blank}.
+/// info
+
+Lesen Sie mehr zu Tags unter [Pfadoperation-Konfiguration](path-operation-configuration.md#tags){.internal-link target=_blank}.
+
+///
### Die Dokumentation anschauen
* Sie kann etwas mit dieser **Response** tun oder beliebigen Code ausführen.
* Dann gibt sie die **Response** zurück.
-!!! note "Technische Details"
- Wenn Sie Abhängigkeiten mit `yield` haben, wird der Exit-Code *nach* der Middleware ausgeführt.
+/// note | "Technische Details"
- Wenn es Hintergrundaufgaben gab (später dokumentiert), werden sie *nach* allen Middlewares ausgeführt.
+Wenn Sie Abhängigkeiten mit `yield` haben, wird der Exit-Code *nach* der Middleware ausgeführt.
+
+Wenn es Hintergrundaufgaben gab (später dokumentiert), werden sie *nach* allen Middlewares ausgeführt.
+
+///
## Erstellung einer Middleware
{!../../../docs_src/middleware/tutorial001.py!}
```
-!!! tip "Tipp"
- Beachten Sie, dass benutzerdefinierte proprietäre Header hinzugefügt werden können. <a href="https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers" class="external-link" target="_blank">Verwenden Sie dafür das Präfix 'X-'</a>.
+/// tip | "Tipp"
+
+Beachten Sie, dass benutzerdefinierte proprietäre Header hinzugefügt werden können. <a href="https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers" class="external-link" target="_blank">Verwenden Sie dafür das Präfix 'X-'</a>.
+
+Wenn Sie jedoch benutzerdefinierte Header haben, die ein Client in einem Browser sehen soll, müssen Sie sie zu Ihrer CORS-Konfigurationen ([CORS (Cross-Origin Resource Sharing)](cors.md){.internal-link target=_blank}) hinzufügen, indem Sie den Parameter `expose_headers` verwenden, der in der <a href="https://www.starlette.io/middleware/#corsmiddleware" class="external-link" target="_blank">Starlette-CORS-Dokumentation</a> dokumentiert ist.
+
+///
+
+/// note | "Technische Details"
- Wenn Sie jedoch benutzerdefinierte Header haben, die ein Client in einem Browser sehen soll, müssen Sie sie zu Ihrer CORS-Konfigurationen ([CORS (Cross-Origin Resource Sharing)](cors.md){.internal-link target=_blank}) hinzufügen, indem Sie den Parameter `expose_headers` verwenden, der in der <a href="https://www.starlette.io/middleware/#corsmiddleware" class="external-link" target="_blank">Starlette-CORS-Dokumentation</a> dokumentiert ist.
+Sie könnten auch `from starlette.requests import Request` verwenden.
-!!! note "Technische Details"
- Sie könnten auch `from starlette.requests import Request` verwenden.
+**FastAPI** bietet es als Komfort für Sie, den Entwickler, an. Aber es stammt direkt von Starlette.
- **FastAPI** bietet es als Komfort für Sie, den Entwickler, an. Aber es stammt direkt von Starlette.
+///
### Vor und nach der `response`
Es gibt mehrere Konfigurations-Parameter, die Sie Ihrem *Pfadoperation-Dekorator* übergeben können.
-!!! warning "Achtung"
- Beachten Sie, dass diese Parameter direkt dem *Pfadoperation-Dekorator* übergeben werden, nicht der *Pfadoperation-Funktion*.
+/// warning | "Achtung"
+
+Beachten Sie, dass diese Parameter direkt dem *Pfadoperation-Dekorator* übergeben werden, nicht der *Pfadoperation-Funktion*.
+
+///
## Response-Statuscode
Aber falls Sie sich nicht mehr erinnern, wofür jede Nummer steht, können Sie die Abkürzungs-Konstanten in `status` verwenden:
-=== "Python 3.10+"
+//// tab | Python 3.10+
+
+```Python hl_lines="1 15"
+{!> ../../../docs_src/path_operation_configuration/tutorial001_py310.py!}
+```
+
+////
- ```Python hl_lines="1 15"
- {!> ../../../docs_src/path_operation_configuration/tutorial001_py310.py!}
- ```
+//// tab | Python 3.9+
-=== "Python 3.9+"
+```Python hl_lines="3 17"
+{!> ../../../docs_src/path_operation_configuration/tutorial001_py39.py!}
+```
+
+////
- ```Python hl_lines="3 17"
- {!> ../../../docs_src/path_operation_configuration/tutorial001_py39.py!}
- ```
+//// tab | Python 3.8+
-=== "Python 3.8+"
+```Python hl_lines="3 17"
+{!> ../../../docs_src/path_operation_configuration/tutorial001.py!}
+```
- ```Python hl_lines="3 17"
- {!> ../../../docs_src/path_operation_configuration/tutorial001.py!}
- ```
+////
Dieser Statuscode wird in der Response verwendet und zum OpenAPI-Schema hinzugefügt.
-!!! note "Technische Details"
- Sie können auch `from starlette import status` verwenden.
+/// note | "Technische Details"
+
+Sie können auch `from starlette import status` verwenden.
+
+**FastAPI** bietet dieselben `starlette.status`-Codes auch via `fastapi.status` an, als Annehmlichkeit für Sie, den Entwickler. Sie kommen aber direkt von Starlette.
- **FastAPI** bietet dieselben `starlette.status`-Codes auch via `fastapi.status` an, als Annehmlichkeit für Sie, den Entwickler. Sie kommen aber direkt von Starlette.
+///
## Tags
Sie können Ihrer *Pfadoperation* Tags hinzufügen, mittels des Parameters `tags`, dem eine `list`e von `str`s übergeben wird (in der Regel nur ein `str`):
-=== "Python 3.10+"
+//// tab | Python 3.10+
- ```Python hl_lines="15 20 25"
- {!> ../../../docs_src/path_operation_configuration/tutorial002_py310.py!}
- ```
+```Python hl_lines="15 20 25"
+{!> ../../../docs_src/path_operation_configuration/tutorial002_py310.py!}
+```
+
+////
-=== "Python 3.9+"
+//// tab | Python 3.9+
- ```Python hl_lines="17 22 27"
- {!> ../../../docs_src/path_operation_configuration/tutorial002_py39.py!}
- ```
+```Python hl_lines="17 22 27"
+{!> ../../../docs_src/path_operation_configuration/tutorial002_py39.py!}
+```
-=== "Python 3.8+"
+////
- ```Python hl_lines="17 22 27"
- {!> ../../../docs_src/path_operation_configuration/tutorial002.py!}
- ```
+//// tab | Python 3.8+
+
+```Python hl_lines="17 22 27"
+{!> ../../../docs_src/path_operation_configuration/tutorial002.py!}
+```
+
+////
Diese werden zum OpenAPI-Schema hinzugefügt und von den automatischen Dokumentations-Benutzeroberflächen verwendet:
Sie können eine Zusammenfassung (`summary`) und eine Beschreibung (`description`) hinzufügen:
-=== "Python 3.10+"
+//// tab | Python 3.10+
+
+```Python hl_lines="18-19"
+{!> ../../../docs_src/path_operation_configuration/tutorial003_py310.py!}
+```
+
+////
- ```Python hl_lines="18-19"
- {!> ../../../docs_src/path_operation_configuration/tutorial003_py310.py!}
- ```
+//// tab | Python 3.9+
-=== "Python 3.9+"
+```Python hl_lines="20-21"
+{!> ../../../docs_src/path_operation_configuration/tutorial003_py39.py!}
+```
+
+////
- ```Python hl_lines="20-21"
- {!> ../../../docs_src/path_operation_configuration/tutorial003_py39.py!}
- ```
+//// tab | Python 3.8+
-=== "Python 3.8+"
+```Python hl_lines="20-21"
+{!> ../../../docs_src/path_operation_configuration/tutorial003.py!}
+```
- ```Python hl_lines="20-21"
- {!> ../../../docs_src/path_operation_configuration/tutorial003.py!}
- ```
+////
## Beschreibung mittels Docstring
Sie können im Docstring <a href="https://en.wikipedia.org/wiki/Markdown" class="external-link" target="_blank">Markdown</a> schreiben, es wird korrekt interpretiert und angezeigt (die Einrückung des Docstring beachtend).
-=== "Python 3.10+"
+//// tab | Python 3.10+
+
+```Python hl_lines="17-25"
+{!> ../../../docs_src/path_operation_configuration/tutorial004_py310.py!}
+```
+
+////
- ```Python hl_lines="17-25"
- {!> ../../../docs_src/path_operation_configuration/tutorial004_py310.py!}
- ```
+//// tab | Python 3.9+
-=== "Python 3.9+"
+```Python hl_lines="19-27"
+{!> ../../../docs_src/path_operation_configuration/tutorial004_py39.py!}
+```
- ```Python hl_lines="19-27"
- {!> ../../../docs_src/path_operation_configuration/tutorial004_py39.py!}
- ```
+////
-=== "Python 3.8+"
+//// tab | Python 3.8+
- ```Python hl_lines="19-27"
- {!> ../../../docs_src/path_operation_configuration/tutorial004.py!}
- ```
+```Python hl_lines="19-27"
+{!> ../../../docs_src/path_operation_configuration/tutorial004.py!}
+```
+
+////
In der interaktiven Dokumentation sieht das dann so aus:
Die Response können Sie mit dem Parameter `response_description` beschreiben:
-=== "Python 3.10+"
+//// tab | Python 3.10+
+
+```Python hl_lines="19"
+{!> ../../../docs_src/path_operation_configuration/tutorial005_py310.py!}
+```
+
+////
+
+//// tab | Python 3.9+
+
+```Python hl_lines="21"
+{!> ../../../docs_src/path_operation_configuration/tutorial005_py39.py!}
+```
+
+////
+
+//// tab | Python 3.8+
+
+```Python hl_lines="21"
+{!> ../../../docs_src/path_operation_configuration/tutorial005.py!}
+```
- ```Python hl_lines="19"
- {!> ../../../docs_src/path_operation_configuration/tutorial005_py310.py!}
- ```
+////
-=== "Python 3.9+"
+/// info
- ```Python hl_lines="21"
- {!> ../../../docs_src/path_operation_configuration/tutorial005_py39.py!}
- ```
+beachten Sie, dass sich `response_description` speziell auf die Response bezieht, während `description` sich generell auf die *Pfadoperation* bezieht.
-=== "Python 3.8+"
+///
- ```Python hl_lines="21"
- {!> ../../../docs_src/path_operation_configuration/tutorial005.py!}
- ```
+/// check
-!!! info
- beachten Sie, dass sich `response_description` speziell auf die Response bezieht, während `description` sich generell auf die *Pfadoperation* bezieht.
+OpenAPI verlangt, dass jede *Pfadoperation* über eine Beschreibung der Response verfügt.
-!!! check
- OpenAPI verlangt, dass jede *Pfadoperation* über eine Beschreibung der Response verfügt.
+Daher, wenn Sie keine vergeben, wird **FastAPI** automatisch eine für „Erfolgreiche Response“ erstellen.
- Daher, wenn Sie keine vergeben, wird **FastAPI** automatisch eine für „Erfolgreiche Response“ erstellen.
+///
<img src="/img/tutorial/path-operation-configuration/image03.png">
Importieren Sie zuerst `Path` von `fastapi`, und importieren Sie `Annotated`.
-=== "Python 3.10+"
+//// tab | Python 3.10+
- ```Python hl_lines="1 3"
- {!> ../../../docs_src/path_params_numeric_validations/tutorial001_an_py310.py!}
- ```
+```Python hl_lines="1 3"
+{!> ../../../docs_src/path_params_numeric_validations/tutorial001_an_py310.py!}
+```
+
+////
+
+//// tab | Python 3.9+
+
+```Python hl_lines="1 3"
+{!> ../../../docs_src/path_params_numeric_validations/tutorial001_an_py39.py!}
+```
+
+////
+
+//// tab | Python 3.8+
+
+```Python hl_lines="3-4"
+{!> ../../../docs_src/path_params_numeric_validations/tutorial001_an.py!}
+```
+
+////
-=== "Python 3.9+"
+//// tab | Python 3.10+ nicht annotiert
- ```Python hl_lines="1 3"
- {!> ../../../docs_src/path_params_numeric_validations/tutorial001_an_py39.py!}
- ```
+/// tip | "Tipp"
-=== "Python 3.8+"
+Bevorzugen Sie die `Annotated`-Version, falls möglich.
- ```Python hl_lines="3-4"
- {!> ../../../docs_src/path_params_numeric_validations/tutorial001_an.py!}
- ```
+///
-=== "Python 3.10+ nicht annotiert"
+```Python hl_lines="1"
+{!> ../../../docs_src/path_params_numeric_validations/tutorial001_py310.py!}
+```
+
+////
+
+//// tab | Python 3.8+ nicht annotiert
+
+/// tip | "Tipp"
+
+Bevorzugen Sie die `Annotated`-Version, falls möglich.
- !!! tip "Tipp"
- Bevorzugen Sie die `Annotated`-Version, falls möglich.
+///
- ```Python hl_lines="1"
- {!> ../../../docs_src/path_params_numeric_validations/tutorial001_py310.py!}
- ```
+```Python hl_lines="3"
+{!> ../../../docs_src/path_params_numeric_validations/tutorial001.py!}
+```
-=== "Python 3.8+ nicht annotiert"
+////
- !!! tip "Tipp"
- Bevorzugen Sie die `Annotated`-Version, falls möglich.
+/// info
- ```Python hl_lines="3"
- {!> ../../../docs_src/path_params_numeric_validations/tutorial001.py!}
- ```
+FastAPI unterstützt (und empfiehlt die Verwendung von) `Annotated` seit Version 0.95.0.
-!!! info
- FastAPI unterstützt (und empfiehlt die Verwendung von) `Annotated` seit Version 0.95.0.
+Wenn Sie eine ältere Version haben, werden Sie Fehler angezeigt bekommen, wenn Sie versuchen, `Annotated` zu verwenden.
- Wenn Sie eine ältere Version haben, werden Sie Fehler angezeigt bekommen, wenn Sie versuchen, `Annotated` zu verwenden.
+Bitte [aktualisieren Sie FastAPI](../deployment/versions.md#upgrade-der-fastapi-versionen){.internal-link target=_blank} daher mindestens zu Version 0.95.1, bevor Sie `Annotated` verwenden.
- Bitte [aktualisieren Sie FastAPI](../deployment/versions.md#upgrade-der-fastapi-versionen){.internal-link target=_blank} daher mindestens zu Version 0.95.1, bevor Sie `Annotated` verwenden.
+///
## Metadaten deklarieren
Um zum Beispiel einen `title`-Metadaten-Wert für den Pfad-Parameter `item_id` zu deklarieren, schreiben Sie:
-=== "Python 3.10+"
+//// tab | Python 3.10+
- ```Python hl_lines="10"
- {!> ../../../docs_src/path_params_numeric_validations/tutorial001_an_py310.py!}
- ```
+```Python hl_lines="10"
+{!> ../../../docs_src/path_params_numeric_validations/tutorial001_an_py310.py!}
+```
-=== "Python 3.9+"
+////
- ```Python hl_lines="10"
- {!> ../../../docs_src/path_params_numeric_validations/tutorial001_an_py39.py!}
- ```
+//// tab | Python 3.9+
-=== "Python 3.8+"
+```Python hl_lines="10"
+{!> ../../../docs_src/path_params_numeric_validations/tutorial001_an_py39.py!}
+```
- ```Python hl_lines="11"
- {!> ../../../docs_src/path_params_numeric_validations/tutorial001_an.py!}
- ```
+////
-=== "Python 3.10+ nicht annotiert"
+//// tab | Python 3.8+
- !!! tip "Tipp"
- Bevorzugen Sie die `Annotated`-Version, falls möglich.
+```Python hl_lines="11"
+{!> ../../../docs_src/path_params_numeric_validations/tutorial001_an.py!}
+```
- ```Python hl_lines="8"
- {!> ../../../docs_src/path_params_numeric_validations/tutorial001_py310.py!}
- ```
+////
-=== "Python 3.8+ nicht annotiert"
+//// tab | Python 3.10+ nicht annotiert
- !!! tip "Tipp"
- Bevorzugen Sie die `Annotated`-Version, falls möglich.
+/// tip | "Tipp"
- ```Python hl_lines="10"
- {!> ../../../docs_src/path_params_numeric_validations/tutorial001.py!}
- ```
+Bevorzugen Sie die `Annotated`-Version, falls möglich.
-!!! note "Hinweis"
- Ein Pfad-Parameter ist immer erforderlich, weil er Teil des Pfads sein muss.
+///
- Sie sollten ihn daher mit `...` deklarieren, um ihn als erforderlich auszuzeichnen.
+```Python hl_lines="8"
+{!> ../../../docs_src/path_params_numeric_validations/tutorial001_py310.py!}
+```
- Doch selbst wenn Sie ihn mit `None` deklarieren, oder einen Defaultwert setzen, bewirkt das nichts, er bleibt immer erforderlich.
+////
+
+//// tab | Python 3.8+ nicht annotiert
+
+/// tip | "Tipp"
+
+Bevorzugen Sie die `Annotated`-Version, falls möglich.
+
+///
+
+```Python hl_lines="10"
+{!> ../../../docs_src/path_params_numeric_validations/tutorial001.py!}
+```
+
+////
+
+/// note | "Hinweis"
+
+Ein Pfad-Parameter ist immer erforderlich, weil er Teil des Pfads sein muss.
+
+Sie sollten ihn daher mit `...` deklarieren, um ihn als erforderlich auszuzeichnen.
+
+Doch selbst wenn Sie ihn mit `None` deklarieren, oder einen Defaultwert setzen, bewirkt das nichts, er bleibt immer erforderlich.
+
+///
## Sortieren Sie die Parameter, wie Sie möchten
-!!! tip "Tipp"
- Wenn Sie `Annotated` verwenden, ist das folgende nicht so wichtig / nicht notwendig.
+/// tip | "Tipp"
+
+Wenn Sie `Annotated` verwenden, ist das folgende nicht so wichtig / nicht notwendig.
+
+///
Nehmen wir an, Sie möchten den Query-Parameter `q` als erforderlichen `str` deklarieren.
Sie können Ihre Funktion also so deklarieren:
-=== "Python 3.8 nicht annotiert"
+//// tab | Python 3.8 nicht annotiert
+
+/// tip | "Tipp"
- !!! tip "Tipp"
- Bevorzugen Sie die `Annotated`-Version, falls möglich.
+Bevorzugen Sie die `Annotated`-Version, falls möglich.
+
+///
+
+```Python hl_lines="7"
+{!> ../../../docs_src/path_params_numeric_validations/tutorial002.py!}
+```
- ```Python hl_lines="7"
- {!> ../../../docs_src/path_params_numeric_validations/tutorial002.py!}
- ```
+////
Aber bedenken Sie, dass Sie dieses Problem nicht haben, wenn Sie `Annotated` verwenden, da Sie nicht die Funktions-Parameter-Defaultwerte für `Query()` oder `Path()` verwenden.
-=== "Python 3.9+"
+//// tab | Python 3.9+
- ```Python hl_lines="10"
- {!> ../../../docs_src/path_params_numeric_validations/tutorial002_an_py39.py!}
- ```
+```Python hl_lines="10"
+{!> ../../../docs_src/path_params_numeric_validations/tutorial002_an_py39.py!}
+```
+
+////
-=== "Python 3.8+"
+//// tab | Python 3.8+
- ```Python hl_lines="9"
- {!> ../../../docs_src/path_params_numeric_validations/tutorial002_an.py!}
- ```
+```Python hl_lines="9"
+{!> ../../../docs_src/path_params_numeric_validations/tutorial002_an.py!}
+```
+
+////
## Sortieren Sie die Parameter wie Sie möchten: Tricks
-!!! tip "Tipp"
- Wenn Sie `Annotated` verwenden, ist das folgende nicht so wichtig / nicht notwendig.
+/// tip | "Tipp"
+
+Wenn Sie `Annotated` verwenden, ist das folgende nicht so wichtig / nicht notwendig.
+
+///
Hier ein **kleiner Trick**, der nützlich sein kann, aber Sie werden ihn nicht oft brauchen.
Bedenken Sie, dass Sie, wenn Sie `Annotated` verwenden, dieses Problem nicht haben, weil Sie keine Defaultwerte für Ihre Funktionsparameter haben. Sie müssen daher wahrscheinlich auch nicht `*` verwenden.
-=== "Python 3.9+"
+//// tab | Python 3.9+
+
+```Python hl_lines="10"
+{!> ../../../docs_src/path_params_numeric_validations/tutorial003_an_py39.py!}
+```
- ```Python hl_lines="10"
- {!> ../../../docs_src/path_params_numeric_validations/tutorial003_an_py39.py!}
- ```
+////
-=== "Python 3.8+"
+//// tab | Python 3.8+
+
+```Python hl_lines="9"
+{!> ../../../docs_src/path_params_numeric_validations/tutorial003_an.py!}
+```
- ```Python hl_lines="9"
- {!> ../../../docs_src/path_params_numeric_validations/tutorial003_an.py!}
- ```
+////
## Validierung von Zahlen: Größer oder gleich
Mit `Query` und `Path` (und anderen, die Sie später kennenlernen), können Sie Zahlenbeschränkungen deklarieren.
Hier, mit `ge=1`, wird festgelegt, dass `item_id` eine Ganzzahl benötigt, die größer oder gleich `1` ist (`g`reater than or `e`qual).
-=== "Python 3.9+"
+//// tab | Python 3.9+
- ```Python hl_lines="10"
- {!> ../../../docs_src/path_params_numeric_validations/tutorial004_an_py39.py!}
- ```
+```Python hl_lines="10"
+{!> ../../../docs_src/path_params_numeric_validations/tutorial004_an_py39.py!}
+```
+
+////
+
+//// tab | Python 3.8+
+
+```Python hl_lines="9"
+{!> ../../../docs_src/path_params_numeric_validations/tutorial004_an.py!}
+```
-=== "Python 3.8+"
+////
- ```Python hl_lines="9"
- {!> ../../../docs_src/path_params_numeric_validations/tutorial004_an.py!}
- ```
+//// tab | Python 3.8+ nicht annotiert
-=== "Python 3.8+ nicht annotiert"
+/// tip | "Tipp"
- !!! tip "Tipp"
- Bevorzugen Sie die `Annotated`-Version, falls möglich.
+Bevorzugen Sie die `Annotated`-Version, falls möglich.
- ```Python hl_lines="8"
- {!> ../../../docs_src/path_params_numeric_validations/tutorial004.py!}
- ```
+///
+
+```Python hl_lines="8"
+{!> ../../../docs_src/path_params_numeric_validations/tutorial004.py!}
+```
+
+////
## Validierung von Zahlen: Größer und kleiner oder gleich
* `gt`: `g`reater `t`han – größer als
* `le`: `l`ess than or `e`qual – kleiner oder gleich
-=== "Python 3.9+"
+//// tab | Python 3.9+
+
+```Python hl_lines="10"
+{!> ../../../docs_src/path_params_numeric_validations/tutorial005_an_py39.py!}
+```
+
+////
+
+//// tab | Python 3.8+
+
+```Python hl_lines="9"
+{!> ../../../docs_src/path_params_numeric_validations/tutorial005_an.py!}
+```
- ```Python hl_lines="10"
- {!> ../../../docs_src/path_params_numeric_validations/tutorial005_an_py39.py!}
- ```
+////
-=== "Python 3.8+"
+//// tab | Python 3.8+ nicht annotiert
- ```Python hl_lines="9"
- {!> ../../../docs_src/path_params_numeric_validations/tutorial005_an.py!}
- ```
+/// tip | "Tipp"
-=== "Python 3.8+ nicht annotiert"
+Bevorzugen Sie die `Annotated`-Version, falls möglich.
- !!! tip "Tipp"
- Bevorzugen Sie die `Annotated`-Version, falls möglich.
+///
- ```Python hl_lines="9"
- {!> ../../../docs_src/path_params_numeric_validations/tutorial005.py!}
- ```
+```Python hl_lines="9"
+{!> ../../../docs_src/path_params_numeric_validations/tutorial005.py!}
+```
+
+////
## Validierung von Zahlen: Floats, größer und kleiner
Das gleiche gilt für <abbr title="less than – kleiner als"><code>lt</code></abbr>.
-=== "Python 3.9+"
+//// tab | Python 3.9+
- ```Python hl_lines="13"
- {!> ../../../docs_src/path_params_numeric_validations/tutorial006_an_py39.py!}
- ```
+```Python hl_lines="13"
+{!> ../../../docs_src/path_params_numeric_validations/tutorial006_an_py39.py!}
+```
-=== "Python 3.8+"
+////
- ```Python hl_lines="12"
- {!> ../../../docs_src/path_params_numeric_validations/tutorial006_an.py!}
- ```
+//// tab | Python 3.8+
+
+```Python hl_lines="12"
+{!> ../../../docs_src/path_params_numeric_validations/tutorial006_an.py!}
+```
-=== "Python 3.8+ nicht annotiert"
+////
- !!! tip "Tipp"
- Bevorzugen Sie die `Annotated`-Version, falls möglich.
+//// tab | Python 3.8+ nicht annotiert
- ```Python hl_lines="11"
- {!> ../../../docs_src/path_params_numeric_validations/tutorial006.py!}
- ```
+/// tip | "Tipp"
+
+Bevorzugen Sie die `Annotated`-Version, falls möglich.
+
+///
+
+```Python hl_lines="11"
+{!> ../../../docs_src/path_params_numeric_validations/tutorial006.py!}
+```
+
+////
## Zusammenfassung
* `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.
+/// 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"
- Sie alle teilen die gleichen Parameter für zusätzliche Validierung und Metadaten, die Sie gesehen haben.
+`Query`, `Path` und andere, die Sie von `fastapi` importieren, sind tatsächlich Funktionen.
-!!! 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.
- 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.
- 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.
- 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.
- Auf diese Weise können Sie Ihren Editor und Ihre Programmier-Tools verwenden, ohne besondere Einstellungen vornehmen zu müssen, um diese Fehlermeldungen stummzuschalten.
+///
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.
+/// check
+
+Dadurch erhalten Sie Editor-Unterstützung innerhalb Ihrer Funktion, mit Fehlerprüfungen, Codevervollständigung, usw.
+
+///
## Daten-<abbr title="Auch bekannt als: Serialisierung, Parsen, Marshalling">Konversion</abbr>
{"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`.
+/// 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 <abbr title="Den String, der von einer HTTP Anfrage kommt, in Python-Objekte konvertieren">„parsen“</abbr>.
- Sprich, mit dieser Typdeklaration wird **FastAPI** die Anfrage automatisch <abbr title="Den String, der von einer HTTP Anfrage kommt, in Python-Objekte konvertieren">„parsen“</abbr>.
+///
## Datenvalidierung
Die gleiche Fehlermeldung würde angezeigt werden, wenn Sie ein `float` (also eine Kommazahl) statt eines `int`s übergeben würden, wie etwa in: <a href="http://127.0.0.1:8000/items/4.2" class="external-link" target="_blank">http://127.0.0.1:8000/items/4.2</a>
-!!! check
- Sprich, mit der gleichen Python-Typdeklaration gibt Ihnen **FastAPI** Datenvalidierung.
+/// check
- Beachten Sie, dass die Fehlermeldung auch direkt die Stelle anzeigt, wo die Validierung nicht erfolgreich war.
+Sprich, mit der gleichen Python-Typdeklaration gibt Ihnen **FastAPI** Datenvalidierung.
- Das ist unglaublich hilfreich, wenn Sie Code entwickeln und debuggen, welcher mit ihrer API interagiert.
+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
<img src="/img/tutorial/path-params/image01.png">
-!!! check
- Wiederum, mit dieser gleichen Python-Typdeklaration gibt Ihnen **FastAPI** eine automatische, interaktive Dokumentation (verwendet die Swagger-Benutzeroberfläche).
+/// check
+
+Wiederum, mit dieser gleichen Python-Typdeklaration gibt Ihnen **FastAPI** eine automatische, interaktive Dokumentation (verwendet die Swagger-Benutzeroberfläche).
+
+Beachten Sie, dass der Pfad-Parameter dort als Ganzzahl deklariert ist.
- Beachten Sie, dass der Pfad-Parameter dort als Ganzzahl deklariert ist.
+///
## Nützliche Standards. Alternative Dokumentation
{!../../../docs_src/path_params/tutorial005.py!}
```
-!!! info
- <a href="https://docs.python.org/3/library/enum.html" class="external-link" target="_blank">Enumerationen (oder kurz Enums)</a> gibt es in Python seit Version 3.4.
+/// info
-!!! tip "Tipp"
- Falls Sie sich fragen, was „AlexNet“, „ResNet“ und „LeNet“ ist, das sind Namen von <abbr title="Genau genommen, Deep-Learning-Modellarchitekturen">Modellen</abbr> für maschinelles Lernen.
+<a href="https://docs.python.org/3/library/enum.html" class="external-link" target="_blank">Enumerationen (oder kurz Enums)</a> gibt es in Python seit Version 3.4.
+
+///
+
+/// tip | "Tipp"
+
+Falls Sie sich fragen, was „AlexNet“, „ResNet“ und „LeNet“ ist, das sind Namen von <abbr title="Genau genommen, Deep-Learning-Modellarchitekturen">Modellen</abbr> für maschinelles Lernen.
+
+///
### Deklarieren Sie einen *Pfad-Parameter*
{!../../../docs_src/path_params/tutorial005.py!}
```
-!!! tip "Tipp"
- Sie können den Wert `"lenet"` außerdem mittels `ModelName.lenet.value` abrufen.
+/// tip | "Tipp"
+
+Sie können den Wert `"lenet"` außerdem mittels `ModelName.lenet.value` abrufen.
+
+///
#### *Enum-Member* zurückgeben
{!../../../docs_src/path_params/tutorial004.py!}
```
-!!! tip "Tipp"
- Der Parameter könnte einen führenden Schrägstrich (`/`) haben, wie etwa in `/home/johndoe/myfile.txt`.
+/// tip | "Tipp"
+
+Der Parameter könnte einen führenden Schrägstrich (`/`) haben, wie etwa in `/home/johndoe/myfile.txt`.
+
+In dem Fall wäre die URL: `/files//home/johndoe/myfile.txt`, mit einem doppelten Schrägstrich (`//`) zwischen `files` und `home`.
- In dem Fall wäre die URL: `/files//home/johndoe/myfile.txt`, mit einem doppelten Schrägstrich (`//`) zwischen `files` und `home`.
+///
## Zusammenfassung
Nehmen wir als Beispiel die folgende Anwendung:
-=== "Python 3.10+"
+//// tab | Python 3.10+
- ```Python hl_lines="7"
- {!> ../../../docs_src/query_params_str_validations/tutorial001_py310.py!}
- ```
+```Python hl_lines="7"
+{!> ../../../docs_src/query_params_str_validations/tutorial001_py310.py!}
+```
+
+////
-=== "Python 3.8+"
+//// tab | Python 3.8+
+
+```Python hl_lines="9"
+{!> ../../../docs_src/query_params_str_validations/tutorial001.py!}
+```
- ```Python hl_lines="9"
- {!> ../../../docs_src/query_params_str_validations/tutorial001.py!}
- ```
+////
Der Query-Parameter `q` hat den Typ `Union[str, None]` (oder `str | None` in Python 3.10), was bedeutet, er ist entweder ein `str` oder `None`. Der Defaultwert ist `None`, also weiß FastAPI, der Parameter ist nicht erforderlich.
-!!! note "Hinweis"
- FastAPI weiß nur dank des definierten Defaultwertes `=None`, dass der Wert von `q` nicht erforderlich ist
+/// note | "Hinweis"
- `Union[str, None]` hingegen erlaubt ihren Editor, Sie besser zu unterstützen und Fehler zu erkennen.
+FastAPI weiß nur dank des definierten Defaultwertes `=None`, dass der Wert von `q` nicht erforderlich ist
+
+`Union[str, None]` hingegen erlaubt ihren Editor, Sie besser zu unterstützen und Fehler zu erkennen.
+
+///
## Zusätzliche Validierung
* `Query` von `fastapi`
* `Annotated` von `typing` (oder von `typing_extensions` in Python unter 3.9)
-=== "Python 3.10+"
+//// tab | Python 3.10+
- In Python 3.9 oder darüber, ist `Annotated` Teil der Standardbibliothek, also können Sie es von `typing` importieren.
+In Python 3.9 oder darüber, ist `Annotated` Teil der Standardbibliothek, also können Sie es von `typing` importieren.
- ```Python hl_lines="1 3"
- {!> ../../../docs_src/query_params_str_validations/tutorial002_an_py310.py!}
- ```
+```Python hl_lines="1 3"
+{!> ../../../docs_src/query_params_str_validations/tutorial002_an_py310.py!}
+```
-=== "Python 3.8+"
+////
- In Versionen unter Python 3.9 importieren Sie `Annotated` von `typing_extensions`.
+//// tab | Python 3.8+
- Es wird bereits mit FastAPI installiert sein.
+In Versionen unter Python 3.9 importieren Sie `Annotated` von `typing_extensions`.
- ```Python hl_lines="3-4"
- {!> ../../../docs_src/query_params_str_validations/tutorial002_an.py!}
- ```
+Es wird bereits mit FastAPI installiert sein.
-!!! info
- FastAPI unterstützt (und empfiehlt die Verwendung von) `Annotated` seit Version 0.95.0.
+```Python hl_lines="3-4"
+{!> ../../../docs_src/query_params_str_validations/tutorial002_an.py!}
+```
- Wenn Sie eine ältere Version haben, werden Sie Fehler angezeigt bekommen, wenn Sie versuchen, `Annotated` zu verwenden.
+////
- Bitte [aktualisieren Sie FastAPI](../deployment/versions.md#upgrade-der-fastapi-versionen){.internal-link target=_blank} daher mindestens zu Version 0.95.1, bevor Sie `Annotated` verwenden.
+/// info
+
+FastAPI unterstützt (und empfiehlt die Verwendung von) `Annotated` seit Version 0.95.0.
+
+Wenn Sie eine ältere Version haben, werden Sie Fehler angezeigt bekommen, wenn Sie versuchen, `Annotated` zu verwenden.
+
+Bitte [aktualisieren Sie FastAPI](../deployment/versions.md#upgrade-der-fastapi-versionen){.internal-link target=_blank} daher mindestens zu Version 0.95.1, bevor Sie `Annotated` verwenden.
+
+///
## `Annotated` im Typ des `q`-Parameters verwenden
Wir hatten diese Typannotation:
-=== "Python 3.10+"
+//// tab | Python 3.10+
+
+```Python
+q: str | None = None
+```
+
+////
- ```Python
- q: str | None = None
- ```
+//// tab | Python 3.8+
-=== "Python 3.8+"
+```Python
+q: Union[str, None] = None
+```
- ```Python
- q: Union[str, None] = None
- ```
+////
Wir wrappen das nun in `Annotated`, sodass daraus wird:
-=== "Python 3.10+"
+//// tab | Python 3.10+
- ```Python
- q: Annotated[str | None] = None
- ```
+```Python
+q: Annotated[str | None] = None
+```
-=== "Python 3.8+"
+////
- ```Python
- q: Annotated[Union[str, None]] = None
- ```
+//// tab | Python 3.8+
+
+```Python
+q: Annotated[Union[str, None]] = None
+```
+
+////
Beide Versionen bedeuten dasselbe: `q` ist ein Parameter, der `str` oder `None` sein kann. Standardmäßig ist er `None`.
Jetzt, da wir `Annotated` für unsere Metadaten deklariert haben, fügen Sie `Query` hinzu, und setzen Sie den Parameter `max_length` auf `50`:
-=== "Python 3.10+"
+//// tab | Python 3.10+
- ```Python hl_lines="9"
- {!> ../../../docs_src/query_params_str_validations/tutorial002_an_py310.py!}
- ```
+```Python hl_lines="9"
+{!> ../../../docs_src/query_params_str_validations/tutorial002_an_py310.py!}
+```
-=== "Python 3.8+"
+////
+
+//// tab | Python 3.8+
+
+```Python hl_lines="10"
+{!> ../../../docs_src/query_params_str_validations/tutorial002_an.py!}
+```
- ```Python hl_lines="10"
- {!> ../../../docs_src/query_params_str_validations/tutorial002_an.py!}
- ```
+////
Beachten Sie, dass der Defaultwert immer noch `None` ist, sodass der Parameter immer noch optional ist.
Frühere Versionen von FastAPI (vor <abbr title="vor 2023-03">0.95.0</abbr>) benötigten `Query` als Defaultwert des Parameters, statt es innerhalb von `Annotated` unterzubringen. Die Chance ist groß, dass Sie Quellcode sehen, der das immer noch so macht, darum erkläre ich es Ihnen.
-!!! tip "Tipp"
- Verwenden Sie für neuen Code, und wann immer möglich, `Annotated`, wie oben erklärt. Es gibt mehrere Vorteile (unten erläutert) und keine Nachteile. 🍰
+/// tip | "Tipp"
+
+Verwenden Sie für neuen Code, und wann immer möglich, `Annotated`, wie oben erklärt. Es gibt mehrere Vorteile (unten erläutert) und keine Nachteile. 🍰
+
+///
So würden Sie `Query()` als Defaultwert Ihres Funktionsparameters verwenden, den Parameter `max_length` auf 50 gesetzt:
-=== "Python 3.10+"
+//// tab | Python 3.10+
+
+```Python hl_lines="7"
+{!> ../../../docs_src/query_params_str_validations/tutorial002_py310.py!}
+```
+
+////
- ```Python hl_lines="7"
- {!> ../../../docs_src/query_params_str_validations/tutorial002_py310.py!}
- ```
+//// tab | Python 3.8+
-=== "Python 3.8+"
+```Python hl_lines="9"
+{!> ../../../docs_src/query_params_str_validations/tutorial002.py!}
+```
- ```Python hl_lines="9"
- {!> ../../../docs_src/query_params_str_validations/tutorial002.py!}
- ```
+////
Da wir in diesem Fall (ohne die Verwendung von `Annotated`) den Parameter-Defaultwert `None` mit `Query()` ersetzen, müssen wir nun dessen Defaultwert mit dem Parameter `Query(default=None)` deklarieren. Das dient demselben Zweck, `None` als Defaultwert für den Funktionsparameter zu setzen (zumindest für FastAPI).
Nur, dass die `Query`-Versionen den Parameter explizit als Query-Parameter deklarieren.
-!!! info
- Bedenken Sie, dass:
+/// info
- ```Python
- = None
- ```
+Bedenken Sie, dass:
- oder:
+```Python
+= None
+```
- ```Python
- = Query(default=None)
- ```
+oder:
- der wichtigste Teil ist, um einen Parameter optional zu machen, da dieses `None` der Defaultwert ist, und das ist es, was diesen Parameter **nicht erforderlich** macht.
+```Python
+= Query(default=None)
+```
+
+der wichtigste Teil ist, um einen Parameter optional zu machen, da dieses `None` der Defaultwert ist, und das ist es, was diesen Parameter **nicht erforderlich** macht.
+
+Der Teil mit `Union[str, None]` erlaubt es Ihrem Editor, Sie besser zu unterstützen, aber er sagt FastAPI nicht, dass dieser Parameter optional ist.
- Der Teil mit `Union[str, None]` erlaubt es Ihrem Editor, Sie besser zu unterstützen, aber er sagt FastAPI nicht, dass dieser Parameter optional ist.
+///
Jetzt können wir `Query` weitere Parameter übergeben. Fangen wir mit dem `max_length` Parameter an, der auf Strings angewendet wird:
Sie können auch einen Parameter `min_length` hinzufügen:
-=== "Python 3.10+"
+//// tab | Python 3.10+
+
+```Python hl_lines="10"
+{!> ../../../docs_src/query_params_str_validations/tutorial003_an_py310.py!}
+```
+
+////
- ```Python hl_lines="10"
- {!> ../../../docs_src/query_params_str_validations/tutorial003_an_py310.py!}
- ```
+//// tab | Python 3.9+
-=== "Python 3.9+"
+```Python hl_lines="10"
+{!> ../../../docs_src/query_params_str_validations/tutorial003_an_py39.py!}
+```
+
+////
+
+//// tab | Python 3.8+
+
+```Python hl_lines="11"
+{!> ../../../docs_src/query_params_str_validations/tutorial003_an.py!}
+```
+
+////
- ```Python hl_lines="10"
- {!> ../../../docs_src/query_params_str_validations/tutorial003_an_py39.py!}
- ```
+//// tab | Python 3.10+ nicht annotiert
-=== "Python 3.8+"
+/// tip | "Tipp"
- ```Python hl_lines="11"
- {!> ../../../docs_src/query_params_str_validations/tutorial003_an.py!}
- ```
+Bevorzugen Sie die `Annotated`-Version, falls möglich.
-=== "Python 3.10+ nicht annotiert"
+///
+
+```Python hl_lines="7"
+{!> ../../../docs_src/query_params_str_validations/tutorial003_py310.py!}
+```
- !!! tip "Tipp"
- Bevorzugen Sie die `Annotated`-Version, falls möglich.
+////
- ```Python hl_lines="7"
- {!> ../../../docs_src/query_params_str_validations/tutorial003_py310.py!}
- ```
+//// tab | Python 3.8+ nicht annotiert
-=== "Python 3.8+ nicht annotiert"
+/// tip | "Tipp"
- !!! tip "Tipp"
- Bevorzugen Sie die `Annotated`-Version, falls möglich.
+Bevorzugen Sie die `Annotated`-Version, falls möglich.
- ```Python hl_lines="10"
- {!> ../../../docs_src/query_params_str_validations/tutorial003.py!}
- ```
+///
+
+```Python hl_lines="10"
+{!> ../../../docs_src/query_params_str_validations/tutorial003.py!}
+```
+
+////
## Reguläre Ausdrücke hinzufügen
Sie können einen <abbr title="Ein regulärer Ausdruck, auch regex oder regexp genannt, ist eine Zeichensequenz, die ein Suchmuster für Strings definiert.">Regulären Ausdruck</abbr> `pattern` definieren, mit dem der Parameter übereinstimmen muss:
-=== "Python 3.10+"
+//// tab | Python 3.10+
+
+```Python hl_lines="11"
+{!> ../../../docs_src/query_params_str_validations/tutorial004_an_py310.py!}
+```
+
+////
+
+//// tab | Python 3.9+
- ```Python hl_lines="11"
- {!> ../../../docs_src/query_params_str_validations/tutorial004_an_py310.py!}
- ```
+```Python hl_lines="11"
+{!> ../../../docs_src/query_params_str_validations/tutorial004_an_py39.py!}
+```
+
+////
+
+//// tab | Python 3.8+
+
+```Python hl_lines="12"
+{!> ../../../docs_src/query_params_str_validations/tutorial004_an.py!}
+```
+
+////
-=== "Python 3.9+"
+//// tab | Python 3.10+ nicht annotiert
- ```Python hl_lines="11"
- {!> ../../../docs_src/query_params_str_validations/tutorial004_an_py39.py!}
- ```
+/// tip | "Tipp"
-=== "Python 3.8+"
+Bevorzugen Sie die `Annotated`-Version, falls möglich.
- ```Python hl_lines="12"
- {!> ../../../docs_src/query_params_str_validations/tutorial004_an.py!}
- ```
+///
-=== "Python 3.10+ nicht annotiert"
+```Python hl_lines="9"
+{!> ../../../docs_src/query_params_str_validations/tutorial004_py310.py!}
+```
- !!! tip "Tipp"
- Bevorzugen Sie die `Annotated`-Version, falls möglich.
+////
- ```Python hl_lines="9"
- {!> ../../../docs_src/query_params_str_validations/tutorial004_py310.py!}
- ```
+//// tab | Python 3.8+ nicht annotiert
-=== "Python 3.8+ nicht annotiert"
+/// tip | "Tipp"
- !!! tip "Tipp"
- Bevorzugen Sie die `Annotated`-Version, falls möglich.
+Bevorzugen Sie die `Annotated`-Version, falls möglich.
- ```Python hl_lines="11"
- {!> ../../../docs_src/query_params_str_validations/tutorial004.py!}
- ```
+///
+
+```Python hl_lines="11"
+{!> ../../../docs_src/query_params_str_validations/tutorial004.py!}
+```
+
+////
Dieses bestimmte reguläre Suchmuster prüft, ob der erhaltene Parameter-Wert:
Sie könnten immer noch Code sehen, der den alten Namen verwendet:
-=== "Python 3.10+ Pydantic v1"
+//// tab | Python 3.10+ Pydantic v1
+
+```Python hl_lines="11"
+{!> ../../../docs_src/query_params_str_validations/tutorial004_an_py310_regex.py!}
+```
- ```Python hl_lines="11"
- {!> ../../../docs_src/query_params_str_validations/tutorial004_an_py310_regex.py!}
- ```
+////
Beachten Sie aber, dass das deprecated ist, und zum neuen Namen `pattern` geändert werden sollte. 🤓
Beispielsweise könnten Sie den `q` Query-Parameter so deklarieren, dass er eine `min_length` von `3` hat, und den Defaultwert `"fixedquery"`:
-=== "Python 3.9+"
+//// tab | Python 3.9+
+
+```Python hl_lines="9"
+{!> ../../../docs_src/query_params_str_validations/tutorial005_an_py39.py!}
+```
+
+////
- ```Python hl_lines="9"
- {!> ../../../docs_src/query_params_str_validations/tutorial005_an_py39.py!}
- ```
+//// tab | Python 3.8+
-=== "Python 3.8+"
+```Python hl_lines="8"
+{!> ../../../docs_src/query_params_str_validations/tutorial005_an.py!}
+```
+
+////
+
+//// tab | Python 3.8+ nicht annotiert
+
+/// tip | "Tipp"
- ```Python hl_lines="8"
- {!> ../../../docs_src/query_params_str_validations/tutorial005_an.py!}
- ```
+Bevorzugen Sie die `Annotated`-Version, falls möglich.
-=== "Python 3.8+ nicht annotiert"
+///
- !!! tip "Tipp"
- Bevorzugen Sie die `Annotated`-Version, falls möglich.
+```Python hl_lines="7"
+{!> ../../../docs_src/query_params_str_validations/tutorial005.py!}
+```
+
+////
- ```Python hl_lines="7"
- {!> ../../../docs_src/query_params_str_validations/tutorial005.py!}
- ```
+/// note | "Hinweis"
-!!! note "Hinweis"
- Ein Parameter ist optional (nicht erforderlich), wenn er irgendeinen Defaultwert, auch `None`, hat.
+Ein Parameter ist optional (nicht erforderlich), wenn er irgendeinen Defaultwert, auch `None`, hat.
+
+///
## Erforderliche Parameter
Aber jetzt deklarieren wir den Parameter mit `Query`, wie in:
-=== "Annotiert"
+//// tab | Annotiert
- ```Python
- q: Annotated[Union[str, None], Query(min_length=3)] = None
- ```
+```Python
+q: Annotated[Union[str, None], Query(min_length=3)] = None
+```
+
+////
-=== "Nicht annotiert"
+//// tab | Nicht annotiert
- ```Python
- q: Union[str, None] = Query(default=None, min_length=3)
- ```
+```Python
+q: Union[str, None] = Query(default=None, min_length=3)
+```
+
+////
Wenn Sie einen Parameter erforderlich machen wollen, während Sie `Query` verwenden, deklarieren Sie ebenfalls einfach keinen Defaultwert:
-=== "Python 3.9+"
+//// tab | Python 3.9+
+
+```Python hl_lines="9"
+{!> ../../../docs_src/query_params_str_validations/tutorial006_an_py39.py!}
+```
+
+////
+
+//// tab | Python 3.8+
+
+```Python hl_lines="8"
+{!> ../../../docs_src/query_params_str_validations/tutorial006_an.py!}
+```
+
+////
+
+//// tab | Python 3.8+ nicht annotiert
- ```Python hl_lines="9"
- {!> ../../../docs_src/query_params_str_validations/tutorial006_an_py39.py!}
- ```
+/// tip | "Tipp"
-=== "Python 3.8+"
+Bevorzugen Sie die `Annotated`-Version, falls möglich.
- ```Python hl_lines="8"
- {!> ../../../docs_src/query_params_str_validations/tutorial006_an.py!}
- ```
+///
+
+```Python hl_lines="7"
+{!> ../../../docs_src/query_params_str_validations/tutorial006.py!}
+```
-=== "Python 3.8+ nicht annotiert"
+/// tip | "Tipp"
- !!! tip "Tipp"
- Bevorzugen Sie die `Annotated`-Version, falls möglich.
+Beachten Sie, dass, obwohl in diesem Fall `Query()` der Funktionsparameter-Defaultwert ist, wir nicht `default=None` zu `Query()` hinzufügen.
- ```Python hl_lines="7"
- {!> ../../../docs_src/query_params_str_validations/tutorial006.py!}
- ```
+Verwenden Sie bitte trotzdem die `Annotated`-Version. 😉
- !!! tip "Tipp"
- Beachten Sie, dass, obwohl in diesem Fall `Query()` der Funktionsparameter-Defaultwert ist, wir nicht `default=None` zu `Query()` hinzufügen.
+///
- Verwenden Sie bitte trotzdem die `Annotated`-Version. 😉
+////
### Erforderlich mit Ellipse (`...`)
Es gibt eine Alternative, die explizit deklariert, dass ein Wert erforderlich ist. Sie können als Default das <abbr title='Zeichenfolge, die einen Wert direkt darstellt, etwa 1, "hallowelt", True, None'>Literal</abbr> `...` setzen:
-=== "Python 3.9+"
+//// tab | Python 3.9+
+
+```Python hl_lines="9"
+{!> ../../../docs_src/query_params_str_validations/tutorial006b_an_py39.py!}
+```
+
+////
+
+//// tab | Python 3.8+
+
+```Python hl_lines="8"
+{!> ../../../docs_src/query_params_str_validations/tutorial006b_an.py!}
+```
+
+////
- ```Python hl_lines="9"
- {!> ../../../docs_src/query_params_str_validations/tutorial006b_an_py39.py!}
- ```
+//// tab | Python 3.8+ nicht annotiert
-=== "Python 3.8+"
+/// tip | "Tipp"
- ```Python hl_lines="8"
- {!> ../../../docs_src/query_params_str_validations/tutorial006b_an.py!}
- ```
+Bevorzugen Sie die `Annotated`-Version, falls möglich.
-=== "Python 3.8+ nicht annotiert"
+///
- !!! tip "Tipp"
- Bevorzugen Sie die `Annotated`-Version, falls möglich.
+```Python hl_lines="7"
+{!> ../../../docs_src/query_params_str_validations/tutorial006b.py!}
+```
+
+////
- ```Python hl_lines="7"
- {!> ../../../docs_src/query_params_str_validations/tutorial006b.py!}
- ```
+/// info
-!!! info
- Falls Sie das `...` bisher noch nicht gesehen haben: Es ist ein spezieller einzelner Wert, <a href="https://docs.python.org/3/library/constants.html#Ellipsis" class="external-link" target="_blank">Teil von Python und wird „Ellipsis“ genannt</a> (Deutsch: Ellipse).
+Falls Sie das `...` bisher noch nicht gesehen haben: Es ist ein spezieller einzelner Wert, <a href="https://docs.python.org/3/library/constants.html#Ellipsis" class="external-link" target="_blank">Teil von Python und wird „Ellipsis“ genannt</a> (Deutsch: Ellipse).
- Es wird von Pydantic und FastAPI verwendet, um explizit zu deklarieren, dass ein Wert erforderlich ist.
+Es wird von Pydantic und FastAPI verwendet, um explizit zu deklarieren, dass ein Wert erforderlich ist.
+
+///
Dies wird **FastAPI** wissen lassen, dass dieser Parameter erforderlich ist.
Um das zu machen, deklarieren Sie, dass `None` ein gültiger Typ ist, aber verwenden Sie dennoch `...` als Default:
-=== "Python 3.10+"
+//// tab | Python 3.10+
+
+```Python hl_lines="9"
+{!> ../../../docs_src/query_params_str_validations/tutorial006c_an_py310.py!}
+```
+
+////
+
+//// tab | Python 3.9+
+
+```Python hl_lines="9"
+{!> ../../../docs_src/query_params_str_validations/tutorial006c_an_py39.py!}
+```
+
+////
+
+//// tab | Python 3.8+
+
+```Python hl_lines="10"
+{!> ../../../docs_src/query_params_str_validations/tutorial006c_an.py!}
+```
+
+////
+
+//// tab | Python 3.10+ nicht annotiert
- ```Python hl_lines="9"
- {!> ../../../docs_src/query_params_str_validations/tutorial006c_an_py310.py!}
- ```
+/// tip | "Tipp"
-=== "Python 3.9+"
+Bevorzugen Sie die `Annotated`-Version, falls möglich.
- ```Python hl_lines="9"
- {!> ../../../docs_src/query_params_str_validations/tutorial006c_an_py39.py!}
- ```
+///
-=== "Python 3.8+"
+```Python hl_lines="7"
+{!> ../../../docs_src/query_params_str_validations/tutorial006c_py310.py!}
+```
+
+////
+
+//// tab | Python 3.8+ nicht annotiert
+
+/// tip | "Tipp"
- ```Python hl_lines="10"
- {!> ../../../docs_src/query_params_str_validations/tutorial006c_an.py!}
- ```
+Bevorzugen Sie die `Annotated`-Version, falls möglich.
-=== "Python 3.10+ nicht annotiert"
+///
- !!! tip "Tipp"
- Bevorzugen Sie die `Annotated`-Version, falls möglich.
+```Python hl_lines="9"
+{!> ../../../docs_src/query_params_str_validations/tutorial006c.py!}
+```
+
+////
- ```Python hl_lines="7"
- {!> ../../../docs_src/query_params_str_validations/tutorial006c_py310.py!}
- ```
+/// tip | "Tipp"
-=== "Python 3.8+ nicht annotiert"
+Pydantic, welches die gesamte Datenvalidierung und Serialisierung in FastAPI antreibt, hat ein spezielles Verhalten, wenn Sie `Optional` oder `Union[Something, None]` ohne Defaultwert verwenden, Sie können mehr darüber in der Pydantic-Dokumentation unter <a href="https://docs.pydantic.dev/2.3/usage/models/#required-fields" class="external-link" target="_blank">Required fields</a> erfahren.
- !!! tip "Tipp"
- Bevorzugen Sie die `Annotated`-Version, falls möglich.
+///
- ```Python hl_lines="9"
- {!> ../../../docs_src/query_params_str_validations/tutorial006c.py!}
- ```
+/// tip | "Tipp"
-!!! tip "Tipp"
- Pydantic, welches die gesamte Datenvalidierung und Serialisierung in FastAPI antreibt, hat ein spezielles Verhalten, wenn Sie `Optional` oder `Union[Something, None]` ohne Defaultwert verwenden, Sie können mehr darüber in der Pydantic-Dokumentation unter <a href="https://docs.pydantic.dev/2.3/usage/models/#required-fields" class="external-link" target="_blank">Required fields</a> erfahren.
+Denken Sie daran, dass Sie in den meisten Fällen, wenn etwas erforderlich ist, einfach den Defaultwert weglassen können. Sie müssen also normalerweise `...` nicht verwenden.
-!!! tip "Tipp"
- Denken Sie daran, dass Sie in den meisten Fällen, wenn etwas erforderlich ist, einfach den Defaultwert weglassen können. Sie müssen also normalerweise `...` nicht verwenden.
+///
## Query-Parameter-Liste / Mehrere Werte
Um zum Beispiel einen Query-Parameter `q` zu deklarieren, der mehrere Male in der URL vorkommen kann, schreiben Sie:
-=== "Python 3.10+"
+//// tab | Python 3.10+
+
+```Python hl_lines="9"
+{!> ../../../docs_src/query_params_str_validations/tutorial011_an_py310.py!}
+```
+
+////
+
+//// tab | Python 3.9+
+
+```Python hl_lines="9"
+{!> ../../../docs_src/query_params_str_validations/tutorial011_an_py39.py!}
+```
+
+////
+
+//// tab | Python 3.8+
+
+```Python hl_lines="10"
+{!> ../../../docs_src/query_params_str_validations/tutorial011_an.py!}
+```
+
+////
+
+//// tab | Python 3.10+ nicht annotiert
+
+/// tip | "Tipp"
- ```Python hl_lines="9"
- {!> ../../../docs_src/query_params_str_validations/tutorial011_an_py310.py!}
- ```
+Bevorzugen Sie die `Annotated`-Version, falls möglich.
-=== "Python 3.9+"
+///
- ```Python hl_lines="9"
- {!> ../../../docs_src/query_params_str_validations/tutorial011_an_py39.py!}
- ```
+```Python hl_lines="7"
+{!> ../../../docs_src/query_params_str_validations/tutorial011_py310.py!}
+```
+
+////
-=== "Python 3.8+"
+//// tab | Python 3.9+ nicht annotiert
- ```Python hl_lines="10"
- {!> ../../../docs_src/query_params_str_validations/tutorial011_an.py!}
- ```
+/// tip | "Tipp"
-=== "Python 3.10+ nicht annotiert"
+Bevorzugen Sie die `Annotated`-Version, falls möglich.
- !!! tip "Tipp"
- Bevorzugen Sie die `Annotated`-Version, falls möglich.
+///
- ```Python hl_lines="7"
- {!> ../../../docs_src/query_params_str_validations/tutorial011_py310.py!}
- ```
+```Python hl_lines="9"
+{!> ../../../docs_src/query_params_str_validations/tutorial011_py39.py!}
+```
-=== "Python 3.9+ nicht annotiert"
+////
- !!! tip "Tipp"
- Bevorzugen Sie die `Annotated`-Version, falls möglich.
+//// tab | Python 3.8+ nicht annotiert
- ```Python hl_lines="9"
- {!> ../../../docs_src/query_params_str_validations/tutorial011_py39.py!}
- ```
+/// tip | "Tipp"
-=== "Python 3.8+ nicht annotiert"
+Bevorzugen Sie die `Annotated`-Version, falls möglich.
- !!! tip "Tipp"
- Bevorzugen Sie die `Annotated`-Version, falls möglich.
+///
- ```Python hl_lines="9"
- {!> ../../../docs_src/query_params_str_validations/tutorial011.py!}
- ```
+```Python hl_lines="9"
+{!> ../../../docs_src/query_params_str_validations/tutorial011.py!}
+```
+
+////
Dann, mit einer URL wie:
}
```
-!!! tip "Tipp"
- Um einen Query-Parameter vom Typ `list` zu deklarieren, wie im Beispiel oben, müssen Sie explizit `Query` verwenden, sonst würde der Parameter als Requestbody interpretiert werden.
+/// tip | "Tipp"
+
+Um einen Query-Parameter vom Typ `list` zu deklarieren, wie im Beispiel oben, müssen Sie explizit `Query` verwenden, sonst würde der Parameter als Requestbody interpretiert werden.
+
+///
Die interaktive API-Dokumentation wird entsprechend aktualisiert und erlaubt jetzt mehrere Werte.
Und Sie können auch eine Default-`list`e von Werten definieren, wenn keine übergeben werden:
-=== "Python 3.9+"
+//// tab | Python 3.9+
+
+```Python hl_lines="9"
+{!> ../../../docs_src/query_params_str_validations/tutorial012_an_py39.py!}
+```
+
+////
+
+//// tab | Python 3.8+
- ```Python hl_lines="9"
- {!> ../../../docs_src/query_params_str_validations/tutorial012_an_py39.py!}
- ```
+```Python hl_lines="10"
+{!> ../../../docs_src/query_params_str_validations/tutorial012_an.py!}
+```
+
+////
+
+//// tab | Python 3.9+ nicht annotiert
+
+/// tip | "Tipp"
-=== "Python 3.8+"
+Bevorzugen Sie die `Annotated`-Version, falls möglich.
- ```Python hl_lines="10"
- {!> ../../../docs_src/query_params_str_validations/tutorial012_an.py!}
- ```
+///
-=== "Python 3.9+ nicht annotiert"
+```Python hl_lines="7"
+{!> ../../../docs_src/query_params_str_validations/tutorial012_py39.py!}
+```
+
+////
- !!! tip "Tipp"
- Bevorzugen Sie die `Annotated`-Version, falls möglich.
+//// tab | Python 3.8+ nicht annotiert
- ```Python hl_lines="7"
- {!> ../../../docs_src/query_params_str_validations/tutorial012_py39.py!}
- ```
+/// tip | "Tipp"
-=== "Python 3.8+ nicht annotiert"
+Bevorzugen Sie die `Annotated`-Version, falls möglich.
- !!! tip "Tipp"
- Bevorzugen Sie die `Annotated`-Version, falls möglich.
+///
+
+```Python hl_lines="9"
+{!> ../../../docs_src/query_params_str_validations/tutorial012.py!}
+```
- ```Python hl_lines="9"
- {!> ../../../docs_src/query_params_str_validations/tutorial012.py!}
- ```
+////
Wenn Sie auf:
Sie können auch `list` direkt verwenden, anstelle von `List[str]` (oder `list[str]` in Python 3.9+):
-=== "Python 3.9+"
+//// tab | Python 3.9+
+
+```Python hl_lines="9"
+{!> ../../../docs_src/query_params_str_validations/tutorial013_an_py39.py!}
+```
+
+////
+
+//// tab | Python 3.8+
+
+```Python hl_lines="8"
+{!> ../../../docs_src/query_params_str_validations/tutorial013_an.py!}
+```
+
+////
- ```Python hl_lines="9"
- {!> ../../../docs_src/query_params_str_validations/tutorial013_an_py39.py!}
- ```
+//// tab | Python 3.8+ nicht annotiert
-=== "Python 3.8+"
+/// tip | "Tipp"
- ```Python hl_lines="8"
- {!> ../../../docs_src/query_params_str_validations/tutorial013_an.py!}
- ```
+Bevorzugen Sie die `Annotated`-Version, falls möglich.
-=== "Python 3.8+ nicht annotiert"
+///
- !!! tip "Tipp"
- Bevorzugen Sie die `Annotated`-Version, falls möglich.
+```Python hl_lines="7"
+{!> ../../../docs_src/query_params_str_validations/tutorial013.py!}
+```
+
+////
- ```Python hl_lines="7"
- {!> ../../../docs_src/query_params_str_validations/tutorial013.py!}
- ```
+/// note | "Hinweis"
-!!! note "Hinweis"
- Beachten Sie, dass FastAPI in diesem Fall den Inhalt der Liste nicht überprüft.
+Beachten Sie, dass FastAPI in diesem Fall den Inhalt der Liste nicht überprüft.
- Zum Beispiel würde `List[int]` überprüfen (und dokumentieren) dass die Liste Ganzzahlen enthält. `list` alleine macht das nicht.
+Zum Beispiel würde `List[int]` überprüfen (und dokumentieren) dass die Liste Ganzzahlen enthält. `list` alleine macht das nicht.
+
+///
## Deklarieren von mehr Metadaten
Diese Informationen werden zur generierten OpenAPI hinzugefügt, und von den Dokumentations-Oberflächen und von externen Tools verwendet.
-!!! note "Hinweis"
- Beachten Sie, dass verschiedene Tools OpenAPI möglicherweise unterschiedlich gut unterstützen.
+/// note | "Hinweis"
+
+Beachten Sie, dass verschiedene Tools OpenAPI möglicherweise unterschiedlich gut unterstützen.
- Einige könnten noch nicht alle zusätzlichen Informationen anzeigen, die Sie deklariert haben, obwohl in den meisten Fällen geplant ist, das fehlende Feature zu implementieren.
+Einige könnten noch nicht alle zusätzlichen Informationen anzeigen, die Sie deklariert haben, obwohl in den meisten Fällen geplant ist, das fehlende Feature zu implementieren.
+
+///
Sie können einen Titel hinzufügen – `title`:
-=== "Python 3.10+"
+//// tab | Python 3.10+
+
+```Python hl_lines="10"
+{!> ../../../docs_src/query_params_str_validations/tutorial007_an_py310.py!}
+```
+
+////
+
+//// tab | Python 3.9+
+
+```Python hl_lines="10"
+{!> ../../../docs_src/query_params_str_validations/tutorial007_an_py39.py!}
+```
+
+////
+
+//// tab | Python 3.8+
+
+```Python hl_lines="11"
+{!> ../../../docs_src/query_params_str_validations/tutorial007_an.py!}
+```
+
+////
+
+//// tab | Python 3.10+ nicht annotiert
- ```Python hl_lines="10"
- {!> ../../../docs_src/query_params_str_validations/tutorial007_an_py310.py!}
- ```
+/// tip | "Tipp"
-=== "Python 3.9+"
+Bevorzugen Sie die `Annotated`-Version, falls möglich.
- ```Python hl_lines="10"
- {!> ../../../docs_src/query_params_str_validations/tutorial007_an_py39.py!}
- ```
+///
-=== "Python 3.8+"
+```Python hl_lines="8"
+{!> ../../../docs_src/query_params_str_validations/tutorial007_py310.py!}
+```
- ```Python hl_lines="11"
- {!> ../../../docs_src/query_params_str_validations/tutorial007_an.py!}
- ```
+////
-=== "Python 3.10+ nicht annotiert"
+//// tab | Python 3.8+ nicht annotiert
- !!! tip "Tipp"
- Bevorzugen Sie die `Annotated`-Version, falls möglich.
+/// tip | "Tipp"
- ```Python hl_lines="8"
- {!> ../../../docs_src/query_params_str_validations/tutorial007_py310.py!}
- ```
+Bevorzugen Sie die `Annotated`-Version, falls möglich.
-=== "Python 3.8+ nicht annotiert"
+///
- !!! tip "Tipp"
- Bevorzugen Sie die `Annotated`-Version, falls möglich.
+```Python hl_lines="10"
+{!> ../../../docs_src/query_params_str_validations/tutorial007.py!}
+```
- ```Python hl_lines="10"
- {!> ../../../docs_src/query_params_str_validations/tutorial007.py!}
- ```
+////
Und eine Beschreibung – `description`:
-=== "Python 3.10+"
+//// tab | Python 3.10+
+
+```Python hl_lines="14"
+{!> ../../../docs_src/query_params_str_validations/tutorial008_an_py310.py!}
+```
+
+////
+
+//// tab | Python 3.9+
+
+```Python hl_lines="14"
+{!> ../../../docs_src/query_params_str_validations/tutorial008_an_py39.py!}
+```
+
+////
+
+//// tab | Python 3.8+
+
+```Python hl_lines="15"
+{!> ../../../docs_src/query_params_str_validations/tutorial008_an.py!}
+```
+
+////
- ```Python hl_lines="14"
- {!> ../../../docs_src/query_params_str_validations/tutorial008_an_py310.py!}
- ```
+//// tab | Python 3.10+ nicht annotiert
-=== "Python 3.9+"
+/// tip | "Tipp"
- ```Python hl_lines="14"
- {!> ../../../docs_src/query_params_str_validations/tutorial008_an_py39.py!}
- ```
+Bevorzugen Sie die `Annotated`-Version, falls möglich.
-=== "Python 3.8+"
+///
- ```Python hl_lines="15"
- {!> ../../../docs_src/query_params_str_validations/tutorial008_an.py!}
- ```
+```Python hl_lines="11"
+{!> ../../../docs_src/query_params_str_validations/tutorial008_py310.py!}
+```
+
+////
-=== "Python 3.10+ nicht annotiert"
+//// tab | Python 3.8+ nicht annotiert
- !!! tip "Tipp"
- Bevorzugen Sie die `Annotated`-Version, falls möglich.
+/// tip | "Tipp"
- ```Python hl_lines="11"
- {!> ../../../docs_src/query_params_str_validations/tutorial008_py310.py!}
- ```
+Bevorzugen Sie die `Annotated`-Version, falls möglich.
-=== "Python 3.8+ nicht annotiert"
+///
- !!! tip "Tipp"
- Bevorzugen Sie die `Annotated`-Version, falls möglich.
+```Python hl_lines="13"
+{!> ../../../docs_src/query_params_str_validations/tutorial008.py!}
+```
- ```Python hl_lines="13"
- {!> ../../../docs_src/query_params_str_validations/tutorial008.py!}
- ```
+////
## Alias-Parameter
Dann können Sie einen `alias` deklarieren, und dieser Alias wird verwendet, um den Parameter-Wert zu finden:
-=== "Python 3.10+"
+//// tab | Python 3.10+
+
+```Python hl_lines="9"
+{!> ../../../docs_src/query_params_str_validations/tutorial009_an_py310.py!}
+```
+
+////
+
+//// tab | Python 3.9+
+
+```Python hl_lines="9"
+{!> ../../../docs_src/query_params_str_validations/tutorial009_an_py39.py!}
+```
+
+////
+
+//// tab | Python 3.8+
+
+```Python hl_lines="10"
+{!> ../../../docs_src/query_params_str_validations/tutorial009_an.py!}
+```
+
+////
+
+//// tab | Python 3.10+ nicht annotiert
- ```Python hl_lines="9"
- {!> ../../../docs_src/query_params_str_validations/tutorial009_an_py310.py!}
- ```
+/// tip | "Tipp"
-=== "Python 3.9+"
+Bevorzugen Sie die `Annotated`-Version, falls möglich.
- ```Python hl_lines="9"
- {!> ../../../docs_src/query_params_str_validations/tutorial009_an_py39.py!}
- ```
+///
-=== "Python 3.8+"
+```Python hl_lines="7"
+{!> ../../../docs_src/query_params_str_validations/tutorial009_py310.py!}
+```
- ```Python hl_lines="10"
- {!> ../../../docs_src/query_params_str_validations/tutorial009_an.py!}
- ```
+////
-=== "Python 3.10+ nicht annotiert"
+//// tab | Python 3.8+ nicht annotiert
- !!! tip "Tipp"
- Bevorzugen Sie die `Annotated`-Version, falls möglich.
+/// tip | "Tipp"
- ```Python hl_lines="7"
- {!> ../../../docs_src/query_params_str_validations/tutorial009_py310.py!}
- ```
+Bevorzugen Sie die `Annotated`-Version, falls möglich.
-=== "Python 3.8+ nicht annotiert"
+///
- !!! tip "Tipp"
- Bevorzugen Sie die `Annotated`-Version, falls möglich.
+```Python hl_lines="9"
+{!> ../../../docs_src/query_params_str_validations/tutorial009.py!}
+```
- ```Python hl_lines="9"
- {!> ../../../docs_src/query_params_str_validations/tutorial009.py!}
- ```
+////
## Parameter als deprecated ausweisen
In diesem Fall fügen Sie den Parameter `deprecated=True` zu `Query` hinzu.
-=== "Python 3.10+"
+//// tab | Python 3.10+
+
+```Python hl_lines="19"
+{!> ../../../docs_src/query_params_str_validations/tutorial010_an_py310.py!}
+```
+
+////
+
+//// tab | Python 3.9+
- ```Python hl_lines="19"
- {!> ../../../docs_src/query_params_str_validations/tutorial010_an_py310.py!}
- ```
+```Python hl_lines="19"
+{!> ../../../docs_src/query_params_str_validations/tutorial010_an_py39.py!}
+```
-=== "Python 3.9+"
+////
- ```Python hl_lines="19"
- {!> ../../../docs_src/query_params_str_validations/tutorial010_an_py39.py!}
- ```
+//// tab | Python 3.8+
-=== "Python 3.8+"
+```Python hl_lines="20"
+{!> ../../../docs_src/query_params_str_validations/tutorial010_an.py!}
+```
+
+////
+
+//// tab | Python 3.10+ nicht annotiert
+
+/// tip | "Tipp"
+
+Bevorzugen Sie die `Annotated`-Version, falls möglich.
+
+///
+
+```Python hl_lines="16"
+{!> ../../../docs_src/query_params_str_validations/tutorial010_py310.py!}
+```
- ```Python hl_lines="20"
- {!> ../../../docs_src/query_params_str_validations/tutorial010_an.py!}
- ```
+////
-=== "Python 3.10+ nicht annotiert"
+//// tab | Python 3.8+ nicht annotiert
- !!! tip "Tipp"
- Bevorzugen Sie die `Annotated`-Version, falls möglich.
+/// tip | "Tipp"
- ```Python hl_lines="16"
- {!> ../../../docs_src/query_params_str_validations/tutorial010_py310.py!}
- ```
+Bevorzugen Sie die `Annotated`-Version, falls möglich.
-=== "Python 3.8+ nicht annotiert"
+///
- !!! tip "Tipp"
- Bevorzugen Sie die `Annotated`-Version, falls möglich.
+```Python hl_lines="18"
+{!> ../../../docs_src/query_params_str_validations/tutorial010.py!}
+```
- ```Python hl_lines="18"
- {!> ../../../docs_src/query_params_str_validations/tutorial010.py!}
- ```
+////
Die Dokumentation wird das so anzeigen:
Um einen Query-Parameter vom generierten OpenAPI-Schema auszuschließen (und daher von automatischen Dokumentations-Systemen), setzen Sie den Parameter `include_in_schema` in `Query` auf `False`.
-=== "Python 3.10+"
+//// tab | Python 3.10+
+
+```Python hl_lines="10"
+{!> ../../../docs_src/query_params_str_validations/tutorial014_an_py310.py!}
+```
+
+////
- ```Python hl_lines="10"
- {!> ../../../docs_src/query_params_str_validations/tutorial014_an_py310.py!}
- ```
+//// tab | Python 3.9+
-=== "Python 3.9+"
+```Python hl_lines="10"
+{!> ../../../docs_src/query_params_str_validations/tutorial014_an_py39.py!}
+```
+
+////
- ```Python hl_lines="10"
- {!> ../../../docs_src/query_params_str_validations/tutorial014_an_py39.py!}
- ```
+//// tab | Python 3.8+
-=== "Python 3.8+"
+```Python hl_lines="11"
+{!> ../../../docs_src/query_params_str_validations/tutorial014_an.py!}
+```
- ```Python hl_lines="11"
- {!> ../../../docs_src/query_params_str_validations/tutorial014_an.py!}
- ```
+////
-=== "Python 3.10+ nicht annotiert"
+//// tab | Python 3.10+ nicht annotiert
- !!! tip "Tipp"
- Bevorzugen Sie die `Annotated`-Version, falls möglich.
+/// tip | "Tipp"
- ```Python hl_lines="8"
- {!> ../../../docs_src/query_params_str_validations/tutorial014_py310.py!}
- ```
+Bevorzugen Sie die `Annotated`-Version, falls möglich.
-=== "Python 3.8+ nicht annotiert"
+///
- !!! tip "Tipp"
- Bevorzugen Sie die `Annotated`-Version, falls möglich.
+```Python hl_lines="8"
+{!> ../../../docs_src/query_params_str_validations/tutorial014_py310.py!}
+```
+
+////
+
+//// tab | Python 3.8+ nicht annotiert
+
+/// tip | "Tipp"
+
+Bevorzugen Sie die `Annotated`-Version, falls möglich.
+
+///
+
+```Python hl_lines="10"
+{!> ../../../docs_src/query_params_str_validations/tutorial014.py!}
+```
- ```Python hl_lines="10"
- {!> ../../../docs_src/query_params_str_validations/tutorial014.py!}
- ```
+////
## Zusammenfassung
Auf die gleiche Weise können Sie optionale Query-Parameter deklarieren, indem Sie deren Defaultwert auf `None` setzen:
-=== "Python 3.10+"
+//// tab | Python 3.10+
- ```Python hl_lines="7"
- {!> ../../../docs_src/query_params/tutorial002_py310.py!}
- ```
+```Python hl_lines="7"
+{!> ../../../docs_src/query_params/tutorial002_py310.py!}
+```
+
+////
+
+//// tab | Python 3.8+
-=== "Python 3.8+"
+```Python hl_lines="9"
+{!> ../../../docs_src/query_params/tutorial002.py!}
+```
- ```Python hl_lines="9"
- {!> ../../../docs_src/query_params/tutorial002.py!}
- ```
+////
In diesem Fall wird der Funktionsparameter `q` optional, und standardmäßig `None` sein.
-!!! check
- Beachten Sie auch, dass **FastAPI** intelligent genug ist, um zu erkennen, dass `item_id` ein Pfad-Parameter ist und `q` keiner, daher muss letzteres ein Query-Parameter sein.
+/// check
+
+Beachten Sie auch, dass **FastAPI** intelligent genug ist, um zu erkennen, dass `item_id` ein Pfad-Parameter ist und `q` keiner, daher muss letzteres ein Query-Parameter sein.
+
+///
## Query-Parameter Typkonvertierung
Sie können auch `bool`-Typen deklarieren und sie werden konvertiert:
-=== "Python 3.10+"
+//// tab | Python 3.10+
+
+```Python hl_lines="7"
+{!> ../../../docs_src/query_params/tutorial003_py310.py!}
+```
- ```Python hl_lines="7"
- {!> ../../../docs_src/query_params/tutorial003_py310.py!}
- ```
+////
-=== "Python 3.8+"
+//// tab | Python 3.8+
+
+```Python hl_lines="9"
+{!> ../../../docs_src/query_params/tutorial003.py!}
+```
- ```Python hl_lines="9"
- {!> ../../../docs_src/query_params/tutorial003.py!}
- ```
+////
Wenn Sie nun zu:
Parameter werden anhand ihres Namens erkannt:
-=== "Python 3.10+"
+//// tab | Python 3.10+
+
+```Python hl_lines="6 8"
+{!> ../../../docs_src/query_params/tutorial004_py310.py!}
+```
+
+////
- ```Python hl_lines="6 8"
- {!> ../../../docs_src/query_params/tutorial004_py310.py!}
- ```
+//// tab | Python 3.8+
-=== "Python 3.8+"
+```Python hl_lines="8 10"
+{!> ../../../docs_src/query_params/tutorial004.py!}
+```
- ```Python hl_lines="8 10"
- {!> ../../../docs_src/query_params/tutorial004.py!}
- ```
+////
## Erforderliche Query-Parameter
Und natürlich können Sie einige Parameter als erforderlich, einige mit Defaultwert, und einige als vollständig optional definieren:
-=== "Python 3.10+"
+//// tab | Python 3.10+
- ```Python hl_lines="8"
- {!> ../../../docs_src/query_params/tutorial006_py310.py!}
- ```
+```Python hl_lines="8"
+{!> ../../../docs_src/query_params/tutorial006_py310.py!}
+```
-=== "Python 3.8+"
+////
- ```Python hl_lines="10"
- {!> ../../../docs_src/query_params/tutorial006.py!}
- ```
+//// tab | Python 3.8+
+
+```Python hl_lines="10"
+{!> ../../../docs_src/query_params/tutorial006.py!}
+```
+
+////
In diesem Fall gibt es drei Query-Parameter:
* `skip`, ein `int` mit einem Defaultwert `0`.
* `limit`, ein optionales `int`.
-!!! tip "Tipp"
- Sie können auch `Enum`s verwenden, auf die gleiche Weise wie mit [Pfad-Parametern](path-params.md#vordefinierte-parameterwerte){.internal-link target=_blank}.
+/// tip | "Tipp"
+
+Sie können auch `Enum`s verwenden, auf die gleiche Weise wie mit [Pfad-Parametern](path-params.md#vordefinierte-parameterwerte){.internal-link target=_blank}.
+
+///
Mit `File` können sie vom Client hochzuladende Dateien definieren.
-!!! info
- Um hochgeladene Dateien zu empfangen, installieren Sie zuerst <a href="https://andrew-d.github.io/python-multipart/" class="external-link" target="_blank">`python-multipart`</a>.
+/// info
- Z. B. `pip install python-multipart`.
+Um hochgeladene Dateien zu empfangen, installieren Sie zuerst <a href="https://andrew-d.github.io/python-multipart/" class="external-link" target="_blank">`python-multipart`</a>.
- Das, weil hochgeladene Dateien als „Formulardaten“ gesendet werden.
+Z. B. `pip install python-multipart`.
+
+Das, weil hochgeladene Dateien als „Formulardaten“ gesendet werden.
+
+///
## `File` importieren
Importieren Sie `File` und `UploadFile` von `fastapi`:
-=== "Python 3.9+"
+//// tab | Python 3.9+
+
+```Python hl_lines="3"
+{!> ../../../docs_src/request_files/tutorial001_an_py39.py!}
+```
+
+////
- ```Python hl_lines="3"
- {!> ../../../docs_src/request_files/tutorial001_an_py39.py!}
- ```
+//// tab | Python 3.8+
-=== "Python 3.8+"
+```Python hl_lines="1"
+{!> ../../../docs_src/request_files/tutorial001_an.py!}
+```
- ```Python hl_lines="1"
- {!> ../../../docs_src/request_files/tutorial001_an.py!}
- ```
+////
-=== "Python 3.8+ nicht annotiert"
+//// tab | Python 3.8+ nicht annotiert
- !!! tip "Tipp"
- Bevorzugen Sie die `Annotated`-Version, falls möglich.
+/// tip | "Tipp"
- ```Python hl_lines="1"
- {!> ../../../docs_src/request_files/tutorial001.py!}
- ```
+Bevorzugen Sie die `Annotated`-Version, falls möglich.
+
+///
+
+```Python hl_lines="1"
+{!> ../../../docs_src/request_files/tutorial001.py!}
+```
+
+////
## `File`-Parameter definieren
Erstellen Sie Datei-Parameter, so wie Sie es auch mit `Body` und `Form` machen würden:
-=== "Python 3.9+"
+//// tab | Python 3.9+
+
+```Python hl_lines="9"
+{!> ../../../docs_src/request_files/tutorial001_an_py39.py!}
+```
+
+////
+
+//// tab | Python 3.8+
+
+```Python hl_lines="8"
+{!> ../../../docs_src/request_files/tutorial001_an.py!}
+```
+
+////
- ```Python hl_lines="9"
- {!> ../../../docs_src/request_files/tutorial001_an_py39.py!}
- ```
+//// tab | Python 3.8+ nicht annotiert
+
+/// tip | "Tipp"
+
+Bevorzugen Sie die `Annotated`-Version, falls möglich.
+
+///
+
+```Python hl_lines="7"
+{!> ../../../docs_src/request_files/tutorial001.py!}
+```
-=== "Python 3.8+"
+////
- ```Python hl_lines="8"
- {!> ../../../docs_src/request_files/tutorial001_an.py!}
- ```
+/// info
-=== "Python 3.8+ nicht annotiert"
+`File` ist eine Klasse, die direkt von `Form` erbt.
- !!! tip "Tipp"
- Bevorzugen Sie die `Annotated`-Version, falls möglich.
+Aber erinnern Sie sich, dass, wenn Sie `Query`, `Path`, `File` und andere von `fastapi` importieren, diese tatsächlich Funktionen sind, welche spezielle Klassen zurückgeben
- ```Python hl_lines="7"
- {!> ../../../docs_src/request_files/tutorial001.py!}
- ```
+///
-!!! info
- `File` ist eine Klasse, die direkt von `Form` erbt.
+/// tip | "Tipp"
- Aber erinnern Sie sich, dass, wenn Sie `Query`, `Path`, `File` und andere von `fastapi` importieren, diese tatsächlich Funktionen sind, welche spezielle Klassen zurückgeben
+Um Dateibodys zu deklarieren, müssen Sie `File` verwenden, da diese Parameter sonst als Query-Parameter oder Body(-JSON)-Parameter interpretiert werden würden.
-!!! tip "Tipp"
- Um Dateibodys zu deklarieren, müssen Sie `File` verwenden, da diese Parameter sonst als Query-Parameter oder Body(-JSON)-Parameter interpretiert werden würden.
+///
Die Dateien werden als „Formulardaten“ hochgeladen.
Definieren Sie einen Datei-Parameter mit dem Typ `UploadFile`:
-=== "Python 3.9+"
+//// tab | Python 3.9+
- ```Python hl_lines="14"
- {!> ../../../docs_src/request_files/tutorial001_an_py39.py!}
- ```
+```Python hl_lines="14"
+{!> ../../../docs_src/request_files/tutorial001_an_py39.py!}
+```
+
+////
+
+//// tab | Python 3.8+
-=== "Python 3.8+"
+```Python hl_lines="13"
+{!> ../../../docs_src/request_files/tutorial001_an.py!}
+```
+
+////
- ```Python hl_lines="13"
- {!> ../../../docs_src/request_files/tutorial001_an.py!}
- ```
+//// tab | Python 3.8+ nicht annotiert
-=== "Python 3.8+ nicht annotiert"
+/// tip | "Tipp"
- !!! tip "Tipp"
- Bevorzugen Sie die `Annotated`-Version, falls möglich.
+Bevorzugen Sie die `Annotated`-Version, falls möglich.
- ```Python hl_lines="12"
- {!> ../../../docs_src/request_files/tutorial001.py!}
- ```
+///
+
+```Python hl_lines="12"
+{!> ../../../docs_src/request_files/tutorial001.py!}
+```
+
+////
`UploadFile` zu verwenden, hat mehrere Vorzüge gegenüber `bytes`:
contents = myfile.file.read()
```
-!!! note "Technische Details zu `async`"
- Wenn Sie die `async`-Methoden verwenden, führt **FastAPI** die Datei-Methoden in einem <abbr title="Mehrere unabhängige Kindprozesse">Threadpool</abbr> aus und erwartet sie.
+/// note | "Technische Details zu `async`"
+
+Wenn Sie die `async`-Methoden verwenden, führt **FastAPI** die Datei-Methoden in einem <abbr title="Mehrere unabhängige Kindprozesse">Threadpool</abbr> aus und erwartet sie.
+
+///
+
+/// note | "Technische Details zu Starlette"
-!!! note "Technische Details zu Starlette"
- **FastAPI**s `UploadFile` erbt direkt von **Starlette**s `UploadFile`, fügt aber ein paar notwendige Teile hinzu, um es kompatibel mit **Pydantic** und anderen Teilen von FastAPI zu machen.
+**FastAPI**s `UploadFile` erbt direkt von **Starlette**s `UploadFile`, fügt aber ein paar notwendige Teile hinzu, um es kompatibel mit **Pydantic** und anderen Teilen von FastAPI zu machen.
+
+///
## Was sind „Formulardaten“
**FastAPI** stellt sicher, dass diese Daten korrekt ausgelesen werden, statt JSON zu erwarten.
-!!! note "Technische Details"
- Daten aus Formularen werden, wenn es keine Dateien sind, normalerweise mit dem <abbr title='Media type – Medientyp, Typ des Mediums'>„media type“</abbr> `application/x-www-form-urlencoded` kodiert.
+/// note | "Technische Details"
+
+Daten aus Formularen werden, wenn es keine Dateien sind, normalerweise mit dem <abbr title='Media type – Medientyp, Typ des Mediums'>„media type“</abbr> `application/x-www-form-urlencoded` kodiert.
+
+Sollte das Formular aber Dateien enthalten, dann werden diese mit `multipart/form-data` kodiert. Wenn Sie `File` verwenden, wird **FastAPI** wissen, dass es die Dateien vom korrekten Teil des Bodys holen muss.
+
+Wenn Sie mehr über Formularfelder und ihre Kodierungen lesen möchten, besuchen Sie die <a href="https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods/POST" class="external-link" target="_blank"><abbr title="Mozilla Developer Network – Mozilla-Entwickler-Netzwerk">MDN</abbr>-Webdokumentation für <code>POST</code></a>.
+
+///
- Sollte das Formular aber Dateien enthalten, dann werden diese mit `multipart/form-data` kodiert. Wenn Sie `File` verwenden, wird **FastAPI** wissen, dass es die Dateien vom korrekten Teil des Bodys holen muss.
+/// warning | "Achtung"
- Wenn Sie mehr über Formularfelder und ihre Kodierungen lesen möchten, besuchen Sie die <a href="https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods/POST" class="external-link" target="_blank"><abbr title="Mozilla Developer Network – Mozilla-Entwickler-Netzwerk">MDN</abbr>-Webdokumentation für <code>POST</code></a>.
+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.
-!!! 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.
- Das ist keine Limitation von **FastAPI**, sondern Teil des HTTP-Protokolls.
+///
## Optionaler Datei-Upload
Sie können eine Datei optional machen, indem Sie Standard-Typannotationen verwenden und den Defaultwert auf `None` setzen:
-=== "Python 3.10+"
+//// tab | Python 3.10+
+
+```Python hl_lines="9 17"
+{!> ../../../docs_src/request_files/tutorial001_02_an_py310.py!}
+```
+
+////
+
+//// tab | Python 3.9+
+
+```Python hl_lines="9 17"
+{!> ../../../docs_src/request_files/tutorial001_02_an_py39.py!}
+```
+
+////
+
+//// tab | Python 3.8+
- ```Python hl_lines="9 17"
- {!> ../../../docs_src/request_files/tutorial001_02_an_py310.py!}
- ```
+```Python hl_lines="10 18"
+{!> ../../../docs_src/request_files/tutorial001_02_an.py!}
+```
+
+////
-=== "Python 3.9+"
+//// tab | Python 3.10+ nicht annotiert
- ```Python hl_lines="9 17"
- {!> ../../../docs_src/request_files/tutorial001_02_an_py39.py!}
- ```
+/// tip | "Tipp"
-=== "Python 3.8+"
+Bevorzugen Sie die `Annotated`-Version, falls möglich.
- ```Python hl_lines="10 18"
- {!> ../../../docs_src/request_files/tutorial001_02_an.py!}
- ```
+///
-=== "Python 3.10+ nicht annotiert"
+```Python hl_lines="7 15"
+{!> ../../../docs_src/request_files/tutorial001_02_py310.py!}
+```
- !!! tip "Tipp"
- Bevorzugen Sie die `Annotated`-Version, falls möglich.
+////
- ```Python hl_lines="7 15"
- {!> ../../../docs_src/request_files/tutorial001_02_py310.py!}
- ```
+//// tab | Python 3.8+ nicht annotiert
-=== "Python 3.8+ nicht annotiert"
+/// tip | "Tipp"
- !!! tip "Tipp"
- Bevorzugen Sie die `Annotated`-Version, falls möglich.
+Bevorzugen Sie die `Annotated`-Version, falls möglich.
- ```Python hl_lines="9 17"
- {!> ../../../docs_src/request_files/tutorial001_02.py!}
- ```
+///
+
+```Python hl_lines="9 17"
+{!> ../../../docs_src/request_files/tutorial001_02.py!}
+```
+
+////
## `UploadFile` mit zusätzlichen Metadaten
Sie können auch `File()` zusammen mit `UploadFile` verwenden, um zum Beispiel zusätzliche Metadaten zu setzen:
-=== "Python 3.9+"
+//// tab | Python 3.9+
+
+```Python hl_lines="9 15"
+{!> ../../../docs_src/request_files/tutorial001_03_an_py39.py!}
+```
+
+////
+
+//// tab | Python 3.8+
+
+```Python hl_lines="8 14"
+{!> ../../../docs_src/request_files/tutorial001_03_an.py!}
+```
+
+////
- ```Python hl_lines="9 15"
- {!> ../../../docs_src/request_files/tutorial001_03_an_py39.py!}
- ```
+//// tab | Python 3.8+ nicht annotiert
-=== "Python 3.8+"
+/// tip | "Tipp"
- ```Python hl_lines="8 14"
- {!> ../../../docs_src/request_files/tutorial001_03_an.py!}
- ```
+Bevorzugen Sie die `Annotated`-Version, falls möglich.
-=== "Python 3.8+ nicht annotiert"
+///
- !!! tip "Tipp"
- Bevorzugen Sie die `Annotated`-Version, falls möglich.
+```Python hl_lines="7 13"
+{!> ../../../docs_src/request_files/tutorial001_03.py!}
+```
- ```Python hl_lines="7 13"
- {!> ../../../docs_src/request_files/tutorial001_03.py!}
- ```
+////
## Mehrere Datei-Uploads
Um das zu machen, deklarieren Sie eine Liste von `bytes` oder `UploadFile`s:
-=== "Python 3.9+"
+//// tab | Python 3.9+
- ```Python hl_lines="10 15"
- {!> ../../../docs_src/request_files/tutorial002_an_py39.py!}
- ```
+```Python hl_lines="10 15"
+{!> ../../../docs_src/request_files/tutorial002_an_py39.py!}
+```
+
+////
-=== "Python 3.8+"
+//// tab | Python 3.8+
- ```Python hl_lines="11 16"
- {!> ../../../docs_src/request_files/tutorial002_an.py!}
- ```
+```Python hl_lines="11 16"
+{!> ../../../docs_src/request_files/tutorial002_an.py!}
+```
-=== "Python 3.9+ nicht annotiert"
+////
- !!! tip "Tipp"
- Bevorzugen Sie die `Annotated`-Version, falls möglich.
+//// tab | Python 3.9+ nicht annotiert
- ```Python hl_lines="8 13"
- {!> ../../../docs_src/request_files/tutorial002_py39.py!}
- ```
+/// tip | "Tipp"
-=== "Python 3.8+ nicht annotiert"
+Bevorzugen Sie die `Annotated`-Version, falls möglich.
- !!! tip "Tipp"
- Bevorzugen Sie die `Annotated`-Version, falls möglich.
+///
+
+```Python hl_lines="8 13"
+{!> ../../../docs_src/request_files/tutorial002_py39.py!}
+```
- ```Python hl_lines="10 15"
- {!> ../../../docs_src/request_files/tutorial002.py!}
- ```
+////
+
+//// tab | Python 3.8+ nicht annotiert
+
+/// tip | "Tipp"
+
+Bevorzugen Sie die `Annotated`-Version, falls möglich.
+
+///
+
+```Python hl_lines="10 15"
+{!> ../../../docs_src/request_files/tutorial002.py!}
+```
+
+////
Sie erhalten, wie deklariert, eine `list`e von `bytes` oder `UploadFile`s.
-!!! note "Technische Details"
- Sie können auch `from starlette.responses import HTMLResponse` verwenden.
+/// 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.
- **FastAPI** bietet dieselben `starlette.responses` auch via `fastapi.responses` an, als Annehmlichkeit für Sie, den Entwickler. Die meisten verfügbaren Responses kommen aber direkt von Starlette.
+///
### Mehrere Datei-Uploads mit zusätzlichen Metadaten
Und so wie zuvor können Sie `File()` verwenden, um zusätzliche Parameter zu setzen, sogar für `UploadFile`:
-=== "Python 3.9+"
+//// tab | Python 3.9+
- ```Python hl_lines="11 18-20"
- {!> ../../../docs_src/request_files/tutorial003_an_py39.py!}
- ```
+```Python hl_lines="11 18-20"
+{!> ../../../docs_src/request_files/tutorial003_an_py39.py!}
+```
-=== "Python 3.8+"
+////
- ```Python hl_lines="12 19-21"
- {!> ../../../docs_src/request_files/tutorial003_an.py!}
- ```
+//// tab | Python 3.8+
-=== "Python 3.9+ nicht annotiert"
+```Python hl_lines="12 19-21"
+{!> ../../../docs_src/request_files/tutorial003_an.py!}
+```
- !!! tip "Tipp"
- Bevorzugen Sie die `Annotated`-Version, falls möglich.
+////
- ```Python hl_lines="9 16"
- {!> ../../../docs_src/request_files/tutorial003_py39.py!}
- ```
+//// tab | Python 3.9+ nicht annotiert
-=== "Python 3.8+ nicht annotiert"
+/// tip | "Tipp"
- !!! tip "Tipp"
- Bevorzugen Sie die `Annotated`-Version, falls möglich.
+Bevorzugen Sie die `Annotated`-Version, falls möglich.
+
+///
+
+```Python hl_lines="9 16"
+{!> ../../../docs_src/request_files/tutorial003_py39.py!}
+```
+
+////
+
+//// tab | Python 3.8+ nicht annotiert
+
+/// tip | "Tipp"
+
+Bevorzugen Sie die `Annotated`-Version, falls möglich.
+
+///
+
+```Python hl_lines="11 18"
+{!> ../../../docs_src/request_files/tutorial003.py!}
+```
- ```Python hl_lines="11 18"
- {!> ../../../docs_src/request_files/tutorial003.py!}
- ```
+////
## Zusammenfassung
Sie können gleichzeitig Dateien und Formulardaten mit `File` und `Form` definieren.
-!!! info
- Um hochgeladene Dateien und/oder Formulardaten zu empfangen, installieren Sie zuerst <a href="https://andrew-d.github.io/python-multipart/" class="external-link" target="_blank">`python-multipart`</a>.
+/// info
- Z. B. `pip install python-multipart`.
+Um hochgeladene Dateien und/oder Formulardaten zu empfangen, installieren Sie zuerst <a href="https://andrew-d.github.io/python-multipart/" class="external-link" target="_blank">`python-multipart`</a>.
+
+Z. B. `pip install python-multipart`.
+
+///
## `File` und `Form` importieren
-=== "Python 3.9+"
+//// tab | Python 3.9+
+
+```Python hl_lines="3"
+{!> ../../../docs_src/request_forms_and_files/tutorial001_an_py39.py!}
+```
+
+////
+
+//// tab | Python 3.8+
+
+```Python hl_lines="1"
+{!> ../../../docs_src/request_forms_and_files/tutorial001_an.py!}
+```
+
+////
- ```Python hl_lines="3"
- {!> ../../../docs_src/request_forms_and_files/tutorial001_an_py39.py!}
- ```
+//// tab | Python 3.8+ nicht annotiert
-=== "Python 3.8+"
+/// tip | "Tipp"
- ```Python hl_lines="1"
- {!> ../../../docs_src/request_forms_and_files/tutorial001_an.py!}
- ```
+Bevorzugen Sie die `Annotated`-Version, falls möglich.
-=== "Python 3.8+ nicht annotiert"
+///
- !!! tip "Tipp"
- Bevorzugen Sie die `Annotated`-Version, falls möglich.
+```Python hl_lines="1"
+{!> ../../../docs_src/request_forms_and_files/tutorial001.py!}
+```
- ```Python hl_lines="1"
- {!> ../../../docs_src/request_forms_and_files/tutorial001.py!}
- ```
+////
## `File` und `Form`-Parameter definieren
Erstellen Sie Datei- und Formularparameter, so wie Sie es auch mit `Body` und `Query` machen würden:
-=== "Python 3.9+"
+//// tab | Python 3.9+
- ```Python hl_lines="10-12"
- {!> ../../../docs_src/request_forms_and_files/tutorial001_an_py39.py!}
- ```
+```Python hl_lines="10-12"
+{!> ../../../docs_src/request_forms_and_files/tutorial001_an_py39.py!}
+```
-=== "Python 3.8+"
+////
- ```Python hl_lines="9-11"
- {!> ../../../docs_src/request_forms_and_files/tutorial001_an.py!}
- ```
+//// tab | Python 3.8+
-=== "Python 3.8+ nicht annotiert"
+```Python hl_lines="9-11"
+{!> ../../../docs_src/request_forms_and_files/tutorial001_an.py!}
+```
- !!! tip "Tipp"
- Bevorzugen Sie die `Annotated`-Version, falls möglich.
+////
- ```Python hl_lines="8"
- {!> ../../../docs_src/request_forms_and_files/tutorial001.py!}
- ```
+//// tab | Python 3.8+ nicht annotiert
+
+/// tip | "Tipp"
+
+Bevorzugen Sie die `Annotated`-Version, falls möglich.
+
+///
+
+```Python hl_lines="8"
+{!> ../../../docs_src/request_forms_and_files/tutorial001.py!}
+```
+
+////
Die Datei- und Formularfelder werden als Formulardaten hochgeladen, und Sie erhalten diese Dateien und Formularfelder.
Und Sie können einige der Dateien als `bytes` und einige als `UploadFile` deklarieren.
-!!! warning "Achtung"
- Sie können mehrere `File`- und `Form`-Parameter in einer *Pfadoperation* deklarieren, aber Sie können nicht gleichzeitig auch `Body`-Felder deklarieren, welche Sie als JSON erwarten, da der Request den Body mittels `multipart/form-data` statt `application/json` kodiert.
+/// 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.
- Das ist keine Limitation von **FastAPI**, sondern Teil des HTTP-Protokolls.
+///
## Zusammenfassung
Wenn Sie Felder aus Formularen statt JSON empfangen müssen, können Sie `Form` verwenden.
-!!! info
- Um Formulare zu verwenden, installieren Sie zuerst <a href="https://andrew-d.github.io/python-multipart/" class="external-link" target="_blank">`python-multipart`</a>.
+/// info
- Z. B. `pip install python-multipart`.
+Um Formulare zu verwenden, installieren Sie zuerst <a href="https://andrew-d.github.io/python-multipart/" class="external-link" target="_blank">`python-multipart`</a>.
+
+Z. B. `pip install python-multipart`.
+
+///
## `Form` importieren
Importieren Sie `Form` von `fastapi`:
-=== "Python 3.9+"
+//// tab | Python 3.9+
+
+```Python hl_lines="3"
+{!> ../../../docs_src/request_forms/tutorial001_an_py39.py!}
+```
+
+////
+
+//// tab | Python 3.8+
- ```Python hl_lines="3"
- {!> ../../../docs_src/request_forms/tutorial001_an_py39.py!}
- ```
+```Python hl_lines="1"
+{!> ../../../docs_src/request_forms/tutorial001_an.py!}
+```
-=== "Python 3.8+"
+////
- ```Python hl_lines="1"
- {!> ../../../docs_src/request_forms/tutorial001_an.py!}
- ```
+//// tab | Python 3.8+ nicht annotiert
-=== "Python 3.8+ nicht annotiert"
+/// tip | "Tipp"
- !!! tip "Tipp"
- Bevorzugen Sie die `Annotated`-Version, falls möglich.
+Bevorzugen Sie die `Annotated`-Version, falls möglich.
- ```Python hl_lines="1"
- {!> ../../../docs_src/request_forms/tutorial001.py!}
- ```
+///
+
+```Python hl_lines="1"
+{!> ../../../docs_src/request_forms/tutorial001.py!}
+```
+
+////
## `Form`-Parameter definieren
Erstellen Sie Formular-Parameter, so wie Sie es auch mit `Body` und `Query` machen würden:
-=== "Python 3.9+"
+//// tab | Python 3.9+
+
+```Python hl_lines="9"
+{!> ../../../docs_src/request_forms/tutorial001_an_py39.py!}
+```
+
+////
+
+//// tab | Python 3.8+
- ```Python hl_lines="9"
- {!> ../../../docs_src/request_forms/tutorial001_an_py39.py!}
- ```
+```Python hl_lines="8"
+{!> ../../../docs_src/request_forms/tutorial001_an.py!}
+```
-=== "Python 3.8+"
+////
- ```Python hl_lines="8"
- {!> ../../../docs_src/request_forms/tutorial001_an.py!}
- ```
+//// tab | Python 3.8+ nicht annotiert
-=== "Python 3.8+ nicht annotiert"
+/// tip | "Tipp"
- !!! tip "Tipp"
- Bevorzugen Sie die `Annotated`-Version, falls möglich.
+Bevorzugen Sie die `Annotated`-Version, falls möglich.
- ```Python hl_lines="7"
- {!> ../../../docs_src/request_forms/tutorial001.py!}
- ```
+///
+
+```Python hl_lines="7"
+{!> ../../../docs_src/request_forms/tutorial001.py!}
+```
+
+////
Zum Beispiel stellt eine der Möglichkeiten, die OAuth2 Spezifikation zu verwenden (genannt <abbr title='„Passwort-Fluss“'>„password flow“</abbr>), die Bedingung, einen `username` und ein `password` als Formularfelder zu senden.
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.
+/// info
+
+`Form` ist eine Klasse, die direkt von `Body` erbt.
+
+///
+
+/// tip | "Tipp"
-!!! 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.
+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“
**FastAPI** stellt sicher, dass diese Daten korrekt ausgelesen werden, statt JSON zu erwarten.
-!!! note "Technische Details"
- Daten aus Formularen werden normalerweise mit dem <abbr title='Media type – Medientyp, Typ des Mediums'>„media type“</abbr> `application/x-www-form-urlencoded` kodiert.
+/// note | "Technische Details"
+
+Daten aus Formularen werden normalerweise mit dem <abbr title='Media type – Medientyp, Typ des Mediums'>„media type“</abbr> `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 <a href="https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods/POST" class="external-link" target="_blank"><abbr title="Mozilla Developer Network – Mozilla-Entwickler-Netzwerk">MDN</abbr>-Webdokumentation für <code>POST</code></a>.
+
+///
- 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.
+/// warning | "Achtung"
- Wenn Sie mehr über Formularfelder und ihre Kodierungen lesen möchten, besuchen Sie die <a href="https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods/POST" class="external-link" target="_blank"><abbr title="Mozilla Developer Network – Mozilla-Entwickler-Netzwerk">MDN</abbr>-Webdokumentation für <code>POST</code></a>.
+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.
-!!! 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.
- Das ist keine Limitation von **FastAPI**, sondern Teil des HTTP-Protokolls.
+///
## Zusammenfassung
Hierbei können Sie **Typannotationen** genauso verwenden, wie Sie es bei Werten von Funktions-**Parametern** machen; verwenden Sie Pydantic-Modelle, Listen, Dicts und skalare Werte wie Nummern, Booleans, usw.
-=== "Python 3.10+"
+//// tab | Python 3.10+
- ```Python hl_lines="16 21"
- {!> ../../../docs_src/response_model/tutorial001_01_py310.py!}
- ```
+```Python hl_lines="16 21"
+{!> ../../../docs_src/response_model/tutorial001_01_py310.py!}
+```
+
+////
+
+//// tab | Python 3.9+
-=== "Python 3.9+"
+```Python hl_lines="18 23"
+{!> ../../../docs_src/response_model/tutorial001_01_py39.py!}
+```
+
+////
- ```Python hl_lines="18 23"
- {!> ../../../docs_src/response_model/tutorial001_01_py39.py!}
- ```
+//// tab | Python 3.8+
-=== "Python 3.8+"
+```Python hl_lines="18 23"
+{!> ../../../docs_src/response_model/tutorial001_01.py!}
+```
- ```Python hl_lines="18 23"
- {!> ../../../docs_src/response_model/tutorial001_01.py!}
- ```
+////
FastAPI wird diesen Rückgabetyp verwenden, um:
* `@app.delete()`
* usw.
-=== "Python 3.10+"
+//// tab | Python 3.10+
- ```Python hl_lines="17 22 24-27"
- {!> ../../../docs_src/response_model/tutorial001_py310.py!}
- ```
+```Python hl_lines="17 22 24-27"
+{!> ../../../docs_src/response_model/tutorial001_py310.py!}
+```
+
+////
-=== "Python 3.9+"
+//// tab | Python 3.9+
- ```Python hl_lines="17 22 24-27"
- {!> ../../../docs_src/response_model/tutorial001_py39.py!}
- ```
+```Python hl_lines="17 22 24-27"
+{!> ../../../docs_src/response_model/tutorial001_py39.py!}
+```
-=== "Python 3.8+"
+////
- ```Python hl_lines="17 22 24-27"
- {!> ../../../docs_src/response_model/tutorial001.py!}
- ```
+//// tab | Python 3.8+
+
+```Python hl_lines="17 22 24-27"
+{!> ../../../docs_src/response_model/tutorial001.py!}
+```
-!!! note "Hinweis"
- Beachten Sie, dass `response_model` ein Parameter der „Dekorator“-Methode ist (`get`, `post`, usw.). Nicht der *Pfadoperation-Funktion*, so wie die anderen Parameter.
+////
+
+/// 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 <abbr title='„Irgend etwas“'>`Any`</abbr> deklarieren.
+/// tip | "Tipp"
+
+Wenn Sie in Ihrem Editor strikte Typchecks haben, mypy, usw., können Sie den Funktions-Rückgabetyp als <abbr title='„Irgend etwas“'>`Any`</abbr> 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`.
- 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
Im Folgenden deklarieren wir ein `UserIn`-Modell; es enthält ein Klartext-Passwort:
-=== "Python 3.10+"
+//// tab | Python 3.10+
+
+```Python hl_lines="7 9"
+{!> ../../../docs_src/response_model/tutorial002_py310.py!}
+```
+
+////
+
+//// tab | Python 3.8+
+
+```Python hl_lines="9 11"
+{!> ../../../docs_src/response_model/tutorial002.py!}
+```
- ```Python hl_lines="7 9"
- {!> ../../../docs_src/response_model/tutorial002_py310.py!}
- ```
+////
-=== "Python 3.8+"
+/// info
- ```Python hl_lines="9 11"
- {!> ../../../docs_src/response_model/tutorial002.py!}
- ```
+Um `EmailStr` zu verwenden, installieren Sie zuerst <a href="https://github.com/JoshData/python-email-validator" class="external-link" target="_blank">`email_validator`</a>.
-!!! info
- Um `EmailStr` zu verwenden, installieren Sie zuerst <a href="https://github.com/JoshData/python-email-validator" class="external-link" target="_blank">`email_validator`</a>.
+Z. B. `pip install email-validator`
+oder `pip install pydantic[email]`.
- Z. B. `pip install email-validator`
- oder `pip install pydantic[email]`.
+///
Wir verwenden dieses Modell, um sowohl unsere Eingabe- als auch Ausgabedaten zu deklarieren:
-=== "Python 3.10+"
+//// tab | Python 3.10+
+
+```Python hl_lines="16"
+{!> ../../../docs_src/response_model/tutorial002_py310.py!}
+```
+
+////
- ```Python hl_lines="16"
- {!> ../../../docs_src/response_model/tutorial002_py310.py!}
- ```
+//// tab | Python 3.8+
-=== "Python 3.8+"
+```Python hl_lines="18"
+{!> ../../../docs_src/response_model/tutorial002.py!}
+```
- ```Python hl_lines="18"
- {!> ../../../docs_src/response_model/tutorial002.py!}
- ```
+////
Immer wenn jetzt ein Browser einen Benutzer mit Passwort erzeugt, gibt die API dasselbe Passwort in der Response zurück.
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.
+/// danger | "Gefahr"
+
+Speichern Sie niemals das Klartext-Passwort eines Benutzers, oder versenden Sie es in einer Response wie dieser, wenn Sie sich nicht der resultierenden Gefahren bewusst sind und nicht wissen, was Sie tun.
+
+///
## Ausgabemodell hinzufügen
Wir können stattdessen ein Eingabemodell mit dem Klartext-Passwort, und ein Ausgabemodell ohne das Passwort erstellen:
-=== "Python 3.10+"
+//// tab | Python 3.10+
+
+```Python hl_lines="9 11 16"
+{!> ../../../docs_src/response_model/tutorial003_py310.py!}
+```
- ```Python hl_lines="9 11 16"
- {!> ../../../docs_src/response_model/tutorial003_py310.py!}
- ```
+////
-=== "Python 3.8+"
+//// tab | Python 3.8+
+
+```Python hl_lines="9 11 16"
+{!> ../../../docs_src/response_model/tutorial003.py!}
+```
- ```Python hl_lines="9 11 16"
- {!> ../../../docs_src/response_model/tutorial003.py!}
- ```
+////
Obwohl unsere *Pfadoperation-Funktion* hier denselben `user` von der Eingabe zurückgibt, der das Passwort enthält:
-=== "Python 3.10+"
+//// tab | Python 3.10+
- ```Python hl_lines="24"
- {!> ../../../docs_src/response_model/tutorial003_py310.py!}
- ```
+```Python hl_lines="24"
+{!> ../../../docs_src/response_model/tutorial003_py310.py!}
+```
+
+////
-=== "Python 3.8+"
+//// tab | Python 3.8+
- ```Python hl_lines="24"
- {!> ../../../docs_src/response_model/tutorial003.py!}
- ```
+```Python hl_lines="24"
+{!> ../../../docs_src/response_model/tutorial003.py!}
+```
+
+////
... haben wir deklariert, dass `response_model` das Modell `UserOut` ist, welches das Passwort nicht enthält:
-=== "Python 3.10+"
+//// tab | Python 3.10+
+
+```Python hl_lines="22"
+{!> ../../../docs_src/response_model/tutorial003_py310.py!}
+```
+
+////
- ```Python hl_lines="22"
- {!> ../../../docs_src/response_model/tutorial003_py310.py!}
- ```
+//// tab | Python 3.8+
-=== "Python 3.8+"
+```Python hl_lines="22"
+{!> ../../../docs_src/response_model/tutorial003.py!}
+```
- ```Python hl_lines="22"
- {!> ../../../docs_src/response_model/tutorial003.py!}
- ```
+////
Darum wird **FastAPI** sich darum kümmern, dass alle Daten, die nicht im Ausgabemodell deklariert sind, herausgefiltert werden (mittels Pydantic).
Und in solchen Fällen können wir Klassen und Vererbung verwenden, um Vorteil aus den Typannotationen in der Funktion zu ziehen, was vom Editor und von Tools besser unterstützt wird, während wir gleichzeitig FastAPIs **Datenfilterung** behalten.
-=== "Python 3.10+"
+//// tab | Python 3.10+
+
+```Python hl_lines="7-10 13-14 18"
+{!> ../../../docs_src/response_model/tutorial003_01_py310.py!}
+```
+
+////
- ```Python hl_lines="7-10 13-14 18"
- {!> ../../../docs_src/response_model/tutorial003_01_py310.py!}
- ```
+//// tab | Python 3.8+
-=== "Python 3.8+"
+```Python hl_lines="9-13 15-16 20"
+{!> ../../../docs_src/response_model/tutorial003_01.py!}
+```
- ```Python hl_lines="9-13 15-16 20"
- {!> ../../../docs_src/response_model/tutorial003_01.py!}
- ```
+////
Damit erhalten wir Tool-Unterstützung, vom Editor und mypy, da dieser Code hinsichtlich der Typen korrekt ist, aber wir erhalten auch die Datenfilterung von FastAPI.
Das gleiche wird passieren, wenn Sie eine <abbr title='Eine Union mehrerer Typen bedeutet: „Irgendeiner dieser Typen“'>Union</abbr> mehrerer Typen haben, und einer oder mehrere sind nicht gültige Pydantic-Typen. Zum Beispiel funktioniert folgendes nicht 💥:
-=== "Python 3.10+"
+//// tab | Python 3.10+
+
+```Python hl_lines="8"
+{!> ../../../docs_src/response_model/tutorial003_04_py310.py!}
+```
+
+////
- ```Python hl_lines="8"
- {!> ../../../docs_src/response_model/tutorial003_04_py310.py!}
- ```
+//// tab | Python 3.8+
-=== "Python 3.8+"
+```Python hl_lines="10"
+{!> ../../../docs_src/response_model/tutorial003_04.py!}
+```
- ```Python hl_lines="10"
- {!> ../../../docs_src/response_model/tutorial003_04.py!}
- ```
+////
... das scheitert, da die Typannotation kein Pydantic-Typ ist, und auch keine einzelne `Response`-Klasse, oder -Unterklasse, es ist eine Union (eines von beiden) von `Response` und `dict`.
In diesem Fall können Sie die Generierung des Responsemodells abschalten, indem Sie `response_model=None` setzen:
-=== "Python 3.10+"
+//// tab | Python 3.10+
- ```Python hl_lines="7"
- {!> ../../../docs_src/response_model/tutorial003_05_py310.py!}
- ```
+```Python hl_lines="7"
+{!> ../../../docs_src/response_model/tutorial003_05_py310.py!}
+```
+
+////
-=== "Python 3.8+"
+//// tab | Python 3.8+
- ```Python hl_lines="9"
- {!> ../../../docs_src/response_model/tutorial003_05.py!}
- ```
+```Python hl_lines="9"
+{!> ../../../docs_src/response_model/tutorial003_05.py!}
+```
+
+////
Das bewirkt, dass FastAPI die Generierung des Responsemodells unterlässt, und damit können Sie jede gewünschte Rückgabetyp-Annotation haben, ohne dass es Ihre FastAPI-Anwendung beeinflusst. 🤓
Ihr Responsemodell könnte Defaultwerte haben, wie:
-=== "Python 3.10+"
+//// tab | Python 3.10+
- ```Python hl_lines="9 11-12"
- {!> ../../../docs_src/response_model/tutorial004_py310.py!}
- ```
+```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!}
- ```
+//// tab | Python 3.9+
-=== "Python 3.8+"
+```Python hl_lines="11 13-14"
+{!> ../../../docs_src/response_model/tutorial004_py39.py!}
+```
+
+////
+
+//// tab | Python 3.8+
+
+```Python hl_lines="11 13-14"
+{!> ../../../docs_src/response_model/tutorial004.py!}
+```
- ```Python hl_lines="11 13-14"
- {!> ../../../docs_src/response_model/tutorial004.py!}
- ```
+////
* `description: Union[str, None] = None` (oder `str | None = None` in Python 3.10) hat einen Defaultwert `None`.
* `tax: float = 10.5` hat einen Defaultwert `10.5`.
Sie können den *Pfadoperation-Dekorator*-Parameter `response_model_exclude_unset=True` setzen:
-=== "Python 3.10+"
+//// tab | Python 3.10+
- ```Python hl_lines="22"
- {!> ../../../docs_src/response_model/tutorial004_py310.py!}
- ```
+```Python hl_lines="22"
+{!> ../../../docs_src/response_model/tutorial004_py310.py!}
+```
+
+////
+
+//// tab | Python 3.9+
+
+```Python hl_lines="24"
+{!> ../../../docs_src/response_model/tutorial004_py39.py!}
+```
-=== "Python 3.9+"
+////
- ```Python hl_lines="24"
- {!> ../../../docs_src/response_model/tutorial004_py39.py!}
- ```
+//// tab | Python 3.8+
-=== "Python 3.8+"
+```Python hl_lines="24"
+{!> ../../../docs_src/response_model/tutorial004.py!}
+```
- ```Python hl_lines="24"
- {!> ../../../docs_src/response_model/tutorial004.py!}
- ```
+////
Die Defaultwerte werden dann nicht in der Response enthalten sein, sondern nur die tatsächlich gesetzten Werte.
}
```
-!!! info
- In Pydantic v1 hieß diese Methode `.dict()`, in Pydantic v2 wurde sie deprecated (aber immer noch unterstützt) und in `.model_dump()` umbenannt.
+/// info
+
+In Pydantic v1 hieß diese Methode `.dict()`, in Pydantic v2 wurde sie deprecated (aber immer noch unterstützt) und in `.model_dump()` umbenannt.
+
+Die Beispiele hier verwenden `.dict()` für die Kompatibilität mit Pydantic v1, Sie sollten jedoch stattdessen `.model_dump()` verwenden, wenn Sie Pydantic v2 verwenden können.
+
+///
+
+/// info
+
+FastAPI verwendet `.dict()` von Pydantic Modellen, <a href="https://docs.pydantic.dev/1.10/usage/exporting_models/#modeldict" class="external-link" target="_blank">mit dessen `exclude_unset`-Parameter</a>, um das zu erreichen.
- Die Beispiele hier verwenden `.dict()` für die Kompatibilität mit Pydantic v1, Sie sollten jedoch stattdessen `.model_dump()` verwenden, wenn Sie Pydantic v2 verwenden können.
+///
-!!! info
- FastAPI verwendet `.dict()` von Pydantic Modellen, <a href="https://docs.pydantic.dev/1.10/usage/exporting_models/#modeldict" class="external-link" target="_blank">mit dessen `exclude_unset`-Parameter</a>, um das zu erreichen.
+/// info
-!!! info
- Sie können auch:
+Sie können auch:
- * `response_model_exclude_defaults=True`
- * `response_model_exclude_none=True`
+* `response_model_exclude_defaults=True`
+* `response_model_exclude_none=True`
- verwenden, wie in der <a href="https://docs.pydantic.dev/1.10/usage/exporting_models/#modeldict" class="external-link" target="_blank">Pydantic Dokumentation</a> für `exclude_defaults` und `exclude_none` beschrieben.
+verwenden, wie in der <a href="https://docs.pydantic.dev/1.10/usage/exporting_models/#modeldict" class="external-link" target="_blank">Pydantic Dokumentation</a> für `exclude_defaults` und `exclude_none` beschrieben.
+
+///
#### Daten mit Werten für Felder mit Defaultwerten
Diese Felder werden also in der JSON-Response enthalten sein.
-!!! tip "Tipp"
- Beachten Sie, dass Defaultwerte alles Mögliche sein können, nicht nur `None`.
+/// tip | "Tipp"
+
+Beachten Sie, dass Defaultwerte alles Mögliche sein können, nicht nur `None`.
+
+Sie können eine Liste (`[]`), ein `float` `10.5`, usw. sein.
- Sie können eine Liste (`[]`), ein `float` `10.5`, usw. sein.
+///
### `response_model_include` und `response_model_exclude`
Das kann als schnelle Abkürzung verwendet werden, wenn Sie nur ein Pydantic-Modell haben und ein paar Daten von der Ausgabe ausschließen wollen.
-!!! tip "Tipp"
- Es wird dennoch empfohlen, dass Sie die Ideen von oben verwenden, also mehrere Klassen statt dieser Parameter.
+/// tip | "Tipp"
- Der Grund ist, dass das das generierte JSON-Schema in der OpenAPI ihrer Anwendung (und deren Dokumentation) dennoch das komplette Modell abbildet, selbst wenn Sie `response_model_include` oder `response_model_exclude` verwenden, um einige Attribute auszuschließen.
+Es wird dennoch empfohlen, dass Sie die Ideen von oben verwenden, also mehrere Klassen statt dieser Parameter.
- Das trifft auch auf `response_model_by_alias` zu, welches ähnlich funktioniert.
+Der Grund ist, dass das das generierte JSON-Schema in der OpenAPI ihrer Anwendung (und deren Dokumentation) dennoch das komplette Modell abbildet, selbst wenn Sie `response_model_include` oder `response_model_exclude` verwenden, um einige Attribute auszuschließen.
-=== "Python 3.10+"
+Das trifft auch auf `response_model_by_alias` zu, welches ähnlich funktioniert.
- ```Python hl_lines="29 35"
- {!> ../../../docs_src/response_model/tutorial005_py310.py!}
- ```
+///
-=== "Python 3.8+"
+//// tab | Python 3.10+
- ```Python hl_lines="31 37"
- {!> ../../../docs_src/response_model/tutorial005.py!}
- ```
+```Python hl_lines="29 35"
+{!> ../../../docs_src/response_model/tutorial005_py310.py!}
+```
-!!! tip "Tipp"
- Die Syntax `{"name", "description"}` erzeugt ein `set` mit diesen zwei Werten.
+////
- Äquivalent zu `set(["name", "description"])`.
+//// tab | Python 3.8+
+
+```Python hl_lines="31 37"
+{!> ../../../docs_src/response_model/tutorial005.py!}
+```
+
+////
+
+/// tip | "Tipp"
+
+Die Syntax `{"name", "description"}` erzeugt ein `set` mit diesen zwei Werten.
+
+Äquivalent zu `set(["name", "description"])`.
+
+///
#### `list`en statt `set`s verwenden
Wenn Sie vergessen, ein `set` zu verwenden, und stattdessen eine `list`e oder ein `tuple` übergeben, wird FastAPI die dennoch in ein `set` konvertieren, und es wird korrekt funktionieren:
-=== "Python 3.10+"
+//// tab | Python 3.10+
+
+```Python hl_lines="29 35"
+{!> ../../../docs_src/response_model/tutorial006_py310.py!}
+```
- ```Python hl_lines="29 35"
- {!> ../../../docs_src/response_model/tutorial006_py310.py!}
- ```
+////
-=== "Python 3.8+"
+//// tab | Python 3.8+
+
+```Python hl_lines="31 37"
+{!> ../../../docs_src/response_model/tutorial006.py!}
+```
- ```Python hl_lines="31 37"
- {!> ../../../docs_src/response_model/tutorial006.py!}
- ```
+////
## Zusammenfassung
{!../../../docs_src/response_status_code/tutorial001.py!}
```
-!!! note "Hinweis"
- Beachten Sie, dass `status_code` ein Parameter der „Dekorator“-Methode ist (`get`, `post`, usw.). Nicht der *Pfadoperation-Funktion*, so wie die anderen Parameter und der Body.
+/// note | "Hinweis"
+
+Beachten Sie, dass `status_code` ein Parameter der „Dekorator“-Methode ist (`get`, `post`, usw.). Nicht der *Pfadoperation-Funktion*, so wie die anderen Parameter und der Body.
+
+///
Dem `status_code`-Parameter wird eine Zahl mit dem HTTP-Statuscode übergeben.
-!!! info
- Alternativ kann `status_code` auch ein `IntEnum` erhalten, so wie Pythons <a href="https://docs.python.org/3/library/http.html#http.HTTPStatus" class="external-link" target="_blank">`http.HTTPStatus`</a>.
+/// info
+
+Alternativ kann `status_code` auch ein `IntEnum` erhalten, so wie Pythons <a href="https://docs.python.org/3/library/http.html#http.HTTPStatus" class="external-link" target="_blank">`http.HTTPStatus`</a>.
+
+///
Das wird:
<img src="/img/tutorial/response-status-code/image01.png">
-!!! note "Hinweis"
- Einige Responsecodes (siehe nächster Abschnitt) kennzeichnen, dass die Response keinen Body hat.
+/// note | "Hinweis"
+
+Einige Responsecodes (siehe nächster Abschnitt) kennzeichnen, dass die Response keinen Body hat.
+
+FastAPI versteht das und wird in der OpenAPI-Dokumentation anzeigen, dass es keinen Responsebody gibt.
- FastAPI versteht das und wird in der OpenAPI-Dokumentation anzeigen, dass es keinen Responsebody gibt.
+///
## Über HTTP-Statuscodes
-!!! note "Hinweis"
- Wenn Sie bereits wissen, was HTTP-Statuscodes sind, überspringen Sie dieses Kapitel und fahren Sie mit dem nächsten fort.
+/// note | "Hinweis"
+
+Wenn Sie bereits wissen, was HTTP-Statuscodes sind, überspringen Sie dieses Kapitel und fahren Sie mit dem nächsten fort.
+
+///
In HTTP senden Sie als Teil der Response einen aus drei Ziffern bestehenden numerischen Statuscode.
* Für allgemeine Fehler beim Client können Sie einfach `400` verwenden.
* `500` und darüber stehen für Server-Fehler. Diese verwenden Sie fast nie direkt. Wenn etwas an irgendeiner Stelle in Ihrem Anwendungscode oder im Server schiefläuft, wird automatisch einer dieser Fehler-Statuscodes zurückgegeben.
-!!! tip "Tipp"
- Um mehr über Statuscodes zu lernen, und welcher wofür verwendet wird, lesen Sie die <a href="https://developer.mozilla.org/en-US/docs/Web/HTTP/Status" class="external-link" target="_blank"><abbr title="Mozilla Developer Network – Mozilla-Entwickler-Netzwerk">MDN</abbr> Dokumentation über HTTP-Statuscodes</a>.
+/// tip | "Tipp"
+
+Um mehr über Statuscodes zu lernen, und welcher wofür verwendet wird, lesen Sie die <a href="https://developer.mozilla.org/en-US/docs/Web/HTTP/Status" class="external-link" target="_blank"><abbr title="Mozilla Developer Network – Mozilla-Entwickler-Netzwerk">MDN</abbr> Dokumentation über HTTP-Statuscodes</a>.
+
+///
## Abkürzung, um die Namen zu erinnern
<img src="/img/tutorial/response-status-code/image02.png">
-!!! note "Technische Details"
- Sie können auch `from starlette import status` verwenden.
+/// note | "Technische Details"
+
+Sie können auch `from starlette import status` verwenden.
+
+**FastAPI** bietet dieselben `starlette.status`-Codes auch via `fastapi.status` an, als Annehmlichkeit für Sie, den Entwickler. Sie kommen aber direkt von Starlette.
- **FastAPI** bietet dieselben `starlette.status`-Codes auch via `fastapi.status` an, als Annehmlichkeit für Sie, den Entwickler. Sie kommen aber direkt von Starlette.
+///
## Den Defaultwert ändern
Sie können `examples` („Beispiele“) für ein Pydantic-Modell deklarieren, welche dem generierten JSON-Schema hinzugefügt werden.
-=== "Python 3.10+ Pydantic v2"
+//// tab | Python 3.10+ Pydantic v2
- ```Python hl_lines="13-24"
- {!> ../../../docs_src/schema_extra_example/tutorial001_py310.py!}
- ```
+```Python hl_lines="13-24"
+{!> ../../../docs_src/schema_extra_example/tutorial001_py310.py!}
+```
-=== "Python 3.10+ Pydantic v1"
+////
- ```Python hl_lines="13-23"
- {!> ../../../docs_src/schema_extra_example/tutorial001_py310_pv1.py!}
- ```
+//// tab | Python 3.10+ Pydantic v1
-=== "Python 3.8+ Pydantic v2"
+```Python hl_lines="13-23"
+{!> ../../../docs_src/schema_extra_example/tutorial001_py310_pv1.py!}
+```
- ```Python hl_lines="15-26"
- {!> ../../../docs_src/schema_extra_example/tutorial001.py!}
- ```
+////
-=== "Python 3.8+ Pydantic v1"
+//// tab | Python 3.8+ Pydantic v2
- ```Python hl_lines="15-25"
- {!> ../../../docs_src/schema_extra_example/tutorial001_pv1.py!}
- ```
+```Python hl_lines="15-26"
+{!> ../../../docs_src/schema_extra_example/tutorial001.py!}
+```
+
+////
+
+//// tab | Python 3.8+ Pydantic v1
+
+```Python hl_lines="15-25"
+{!> ../../../docs_src/schema_extra_example/tutorial001_pv1.py!}
+```
+
+////
Diese zusätzlichen Informationen werden unverändert zum für dieses Modell ausgegebenen **JSON-Schema** hinzugefügt und in der API-Dokumentation verwendet.
-=== "Pydantic v2"
+//// tab | Pydantic v2
+
+In Pydantic Version 2 würden Sie das Attribut `model_config` verwenden, das ein `dict` akzeptiert, wie beschrieben in <a href="https://docs.pydantic.dev/latest/api/config/" class="external-link" target="_blank">Pydantic-Dokumentation: Configuration</a>.
+
+Sie können `json_schema_extra` setzen, mit einem `dict`, das alle zusätzlichen Daten enthält, die im generierten JSON-Schema angezeigt werden sollen, einschließlich `examples`.
- In Pydantic Version 2 würden Sie das Attribut `model_config` verwenden, das ein `dict` akzeptiert, wie beschrieben in <a href="https://docs.pydantic.dev/latest/api/config/" class="external-link" target="_blank">Pydantic-Dokumentation: Configuration</a>.
+////
- Sie können `json_schema_extra` setzen, mit einem `dict`, das alle zusätzlichen Daten enthält, die im generierten JSON-Schema angezeigt werden sollen, einschließlich `examples`.
+//// tab | Pydantic v1
-=== "Pydantic v1"
+In Pydantic Version 1 würden Sie eine interne Klasse `Config` und `schema_extra` verwenden, wie beschrieben in <a href="https://docs.pydantic.dev/1.10/usage/schema/#schema-customization" class="external-link" target="_blank">Pydantic-Dokumentation: Schema customization</a>.
- In Pydantic Version 1 würden Sie eine interne Klasse `Config` und `schema_extra` verwenden, wie beschrieben in <a href="https://docs.pydantic.dev/1.10/usage/schema/#schema-customization" class="external-link" target="_blank">Pydantic-Dokumentation: Schema customization</a>.
+Sie können `schema_extra` setzen, mit einem `dict`, das alle zusätzlichen Daten enthält, die im generierten JSON-Schema angezeigt werden sollen, einschließlich `examples`.
- Sie können `schema_extra` setzen, mit einem `dict`, das alle zusätzlichen Daten enthält, die im generierten JSON-Schema angezeigt werden sollen, einschließlich `examples`.
+////
-!!! tip "Tipp"
- Mit derselben Technik können Sie das JSON-Schema erweitern und Ihre eigenen benutzerdefinierten Zusatzinformationen hinzufügen.
+/// tip | "Tipp"
- Sie könnten das beispielsweise verwenden, um Metadaten für eine Frontend-Benutzeroberfläche usw. hinzuzufügen.
+Mit derselben Technik können Sie das JSON-Schema erweitern und Ihre eigenen benutzerdefinierten Zusatzinformationen hinzufügen.
-!!! info
- OpenAPI 3.1.0 (verwendet seit FastAPI 0.99.0) hat Unterstützung für `examples` hinzugefügt, was Teil des **JSON Schema** Standards ist.
+Sie könnten das beispielsweise verwenden, um Metadaten für eine Frontend-Benutzeroberfläche usw. hinzuzufügen.
- Zuvor unterstützte es nur das Schlüsselwort `example` mit einem einzigen Beispiel. Dieses wird weiterhin von OpenAPI 3.1.0 unterstützt, ist jedoch <abbr title="deprecated – obsolet, veraltet: Es soll nicht mehr verwendet werden">deprecated</abbr> und nicht Teil des JSON Schema Standards. Wir empfehlen Ihnen daher, von `example` nach `examples` zu migrieren. 🤓
+///
- Mehr erfahren Sie am Ende dieser Seite.
+/// info
+
+OpenAPI 3.1.0 (verwendet seit FastAPI 0.99.0) hat Unterstützung für `examples` hinzugefügt, was Teil des **JSON Schema** Standards ist.
+
+Zuvor unterstützte es nur das Schlüsselwort `example` mit einem einzigen Beispiel. Dieses wird weiterhin von OpenAPI 3.1.0 unterstützt, ist jedoch <abbr title="deprecated – obsolet, veraltet: Es soll nicht mehr verwendet werden">deprecated</abbr> und nicht Teil des JSON Schema Standards. Wir empfehlen Ihnen daher, von `example` nach `examples` zu migrieren. 🤓
+
+Mehr erfahren Sie am Ende dieser Seite.
+
+///
## Zusätzliche Argumente für `Field`
Wenn Sie `Field()` mit Pydantic-Modellen verwenden, können Sie ebenfalls zusätzliche `examples` deklarieren:
-=== "Python 3.10+"
+//// tab | Python 3.10+
+
+```Python hl_lines="2 8-11"
+{!> ../../../docs_src/schema_extra_example/tutorial002_py310.py!}
+```
+
+////
- ```Python hl_lines="2 8-11"
- {!> ../../../docs_src/schema_extra_example/tutorial002_py310.py!}
- ```
+//// tab | Python 3.8+
-=== "Python 3.8+"
+```Python hl_lines="4 10-13"
+{!> ../../../docs_src/schema_extra_example/tutorial002.py!}
+```
- ```Python hl_lines="4 10-13"
- {!> ../../../docs_src/schema_extra_example/tutorial002.py!}
- ```
+////
## `examples` im JSON-Schema – OpenAPI
Hier übergeben wir `examples`, welches ein einzelnes Beispiel für die in `Body()` erwarteten Daten enthält:
-=== "Python 3.10+"
+//// tab | Python 3.10+
- ```Python hl_lines="22-29"
- {!> ../../../docs_src/schema_extra_example/tutorial003_an_py310.py!}
- ```
+```Python hl_lines="22-29"
+{!> ../../../docs_src/schema_extra_example/tutorial003_an_py310.py!}
+```
-=== "Python 3.9+"
+////
- ```Python hl_lines="22-29"
- {!> ../../../docs_src/schema_extra_example/tutorial003_an_py39.py!}
- ```
+//// tab | Python 3.9+
-=== "Python 3.8+"
+```Python hl_lines="22-29"
+{!> ../../../docs_src/schema_extra_example/tutorial003_an_py39.py!}
+```
- ```Python hl_lines="23-30"
- {!> ../../../docs_src/schema_extra_example/tutorial003_an.py!}
- ```
+////
-=== "Python 3.10+ nicht annotiert"
+//// tab | Python 3.8+
- !!! tip "Tipp"
- Bevorzugen Sie die `Annotated`-Version, falls möglich.
+```Python hl_lines="23-30"
+{!> ../../../docs_src/schema_extra_example/tutorial003_an.py!}
+```
- ```Python hl_lines="18-25"
- {!> ../../../docs_src/schema_extra_example/tutorial003_py310.py!}
- ```
+////
-=== "Python 3.8+ nicht annotiert"
+//// tab | Python 3.10+ nicht annotiert
- !!! tip "Tipp"
- Bevorzugen Sie die `Annotated`-Version, falls möglich.
+/// tip | "Tipp"
- ```Python hl_lines="20-27"
- {!> ../../../docs_src/schema_extra_example/tutorial003.py!}
- ```
+Bevorzugen Sie die `Annotated`-Version, falls möglich.
+
+///
+
+```Python hl_lines="18-25"
+{!> ../../../docs_src/schema_extra_example/tutorial003_py310.py!}
+```
+
+////
+
+//// tab | Python 3.8+ nicht annotiert
+
+/// tip | "Tipp"
+
+Bevorzugen Sie die `Annotated`-Version, falls möglich.
+
+///
+
+```Python hl_lines="20-27"
+{!> ../../../docs_src/schema_extra_example/tutorial003.py!}
+```
+
+////
### Beispiel in der Dokumentations-Benutzeroberfläche
Sie können natürlich auch mehrere `examples` übergeben:
-=== "Python 3.10+"
+//// tab | Python 3.10+
+
+```Python hl_lines="23-38"
+{!> ../../../docs_src/schema_extra_example/tutorial004_an_py310.py!}
+```
+
+////
+
+//// tab | Python 3.9+
- ```Python hl_lines="23-38"
- {!> ../../../docs_src/schema_extra_example/tutorial004_an_py310.py!}
- ```
+```Python hl_lines="23-38"
+{!> ../../../docs_src/schema_extra_example/tutorial004_an_py39.py!}
+```
-=== "Python 3.9+"
+////
- ```Python hl_lines="23-38"
- {!> ../../../docs_src/schema_extra_example/tutorial004_an_py39.py!}
- ```
+//// tab | Python 3.8+
-=== "Python 3.8+"
+```Python hl_lines="24-39"
+{!> ../../../docs_src/schema_extra_example/tutorial004_an.py!}
+```
- ```Python hl_lines="24-39"
- {!> ../../../docs_src/schema_extra_example/tutorial004_an.py!}
- ```
+////
-=== "Python 3.10+ nicht annotiert"
+//// tab | Python 3.10+ nicht annotiert
- !!! tip "Tipp"
- Bevorzugen Sie die `Annotated`-Version, falls möglich.
+/// tip | "Tipp"
- ```Python hl_lines="19-34"
- {!> ../../../docs_src/schema_extra_example/tutorial004_py310.py!}
- ```
+Bevorzugen Sie die `Annotated`-Version, falls möglich.
-=== "Python 3.8+ nicht annotiert"
+///
- !!! tip "Tipp"
- Bevorzugen Sie die `Annotated`-Version, falls möglich.
+```Python hl_lines="19-34"
+{!> ../../../docs_src/schema_extra_example/tutorial004_py310.py!}
+```
- ```Python hl_lines="21-36"
- {!> ../../../docs_src/schema_extra_example/tutorial004.py!}
- ```
+////
+
+//// tab | Python 3.8+ nicht annotiert
+
+/// tip | "Tipp"
+
+Bevorzugen Sie die `Annotated`-Version, falls möglich.
+
+///
+
+```Python hl_lines="21-36"
+{!> ../../../docs_src/schema_extra_example/tutorial004.py!}
+```
+
+////
Wenn Sie das tun, werden die Beispiele Teil des internen **JSON-Schemas** für diese Body-Daten.
Sie können es so verwenden:
-=== "Python 3.10+"
+//// tab | Python 3.10+
+
+```Python hl_lines="23-49"
+{!> ../../../docs_src/schema_extra_example/tutorial005_an_py310.py!}
+```
+
+////
+
+//// tab | Python 3.9+
+
+```Python hl_lines="23-49"
+{!> ../../../docs_src/schema_extra_example/tutorial005_an_py39.py!}
+```
+
+////
+
+//// tab | Python 3.8+
- ```Python hl_lines="23-49"
- {!> ../../../docs_src/schema_extra_example/tutorial005_an_py310.py!}
- ```
+```Python hl_lines="24-50"
+{!> ../../../docs_src/schema_extra_example/tutorial005_an.py!}
+```
-=== "Python 3.9+"
+////
- ```Python hl_lines="23-49"
- {!> ../../../docs_src/schema_extra_example/tutorial005_an_py39.py!}
- ```
+//// tab | Python 3.10+ nicht annotiert
-=== "Python 3.8+"
+/// tip | "Tipp"
- ```Python hl_lines="24-50"
- {!> ../../../docs_src/schema_extra_example/tutorial005_an.py!}
- ```
+Bevorzugen Sie die `Annotated`-Version, falls möglich.
-=== "Python 3.10+ nicht annotiert"
+///
- !!! tip "Tipp"
- Bevorzugen Sie die `Annotated`-Version, falls möglich.
+```Python hl_lines="19-45"
+{!> ../../../docs_src/schema_extra_example/tutorial005_py310.py!}
+```
- ```Python hl_lines="19-45"
- {!> ../../../docs_src/schema_extra_example/tutorial005_py310.py!}
- ```
+////
-=== "Python 3.8+ nicht annotiert"
+//// tab | Python 3.8+ nicht annotiert
- !!! tip "Tipp"
- Bevorzugen Sie die `Annotated`-Version, falls möglich.
+/// tip | "Tipp"
- ```Python hl_lines="21-47"
- {!> ../../../docs_src/schema_extra_example/tutorial005.py!}
- ```
+Bevorzugen Sie die `Annotated`-Version, falls möglich.
+
+///
+
+```Python hl_lines="21-47"
+{!> ../../../docs_src/schema_extra_example/tutorial005.py!}
+```
+
+////
### OpenAPI-Beispiele in der Dokumentations-Benutzeroberfläche
## Technische Details
-!!! tip "Tipp"
- Wenn Sie bereits **FastAPI** Version **0.99.0 oder höher** verwenden, können Sie diese Details wahrscheinlich **überspringen**.
+/// tip | "Tipp"
+
+Wenn Sie bereits **FastAPI** Version **0.99.0 oder höher** verwenden, können Sie diese Details wahrscheinlich **überspringen**.
+
+Sie sind für ältere Versionen relevanter, bevor OpenAPI 3.1.0 verfügbar war.
+
+Sie können dies als eine kurze **Geschichtsstunde** zu OpenAPI und JSON Schema betrachten. 🤓
- Sie sind für ältere Versionen relevanter, bevor OpenAPI 3.1.0 verfügbar war.
+///
- Sie können dies als eine kurze **Geschichtsstunde** zu OpenAPI und JSON Schema betrachten. 🤓
+/// warning | "Achtung"
-!!! warning "Achtung"
- Dies sind sehr technische Details zu den Standards **JSON Schema** und **OpenAPI**.
+Dies sind sehr technische Details zu den Standards **JSON Schema** und **OpenAPI**.
- Wenn die oben genannten Ideen bereits für Sie funktionieren, reicht das möglicherweise aus und Sie benötigen diese Details wahrscheinlich nicht, überspringen Sie sie gerne.
+Wenn die oben genannten Ideen bereits für Sie funktionieren, reicht das möglicherweise aus und Sie benötigen diese Details wahrscheinlich nicht, überspringen Sie sie gerne.
+
+///
Vor OpenAPI 3.1.0 verwendete OpenAPI eine ältere und modifizierte Version von **JSON Schema**.
* `File()`
* `Form()`
-!!! info
- Dieser alte, OpenAPI-spezifische `examples`-Parameter heißt seit FastAPI `0.103.0` jetzt `openapi_examples`.
+/// info
+
+Dieser alte, OpenAPI-spezifische `examples`-Parameter heißt seit FastAPI `0.103.0` jetzt `openapi_examples`.
+
+///
### JSON Schemas Feld `examples`
Dieses neue `examples`-Feld in JSON Schema ist **nur eine `list`e** von Beispielen, kein Dict mit zusätzlichen Metadaten wie an den anderen Stellen in OpenAPI (oben beschrieben).
-!!! info
- Selbst, nachdem OpenAPI 3.1.0 veröffentlicht wurde, mit dieser neuen, einfacheren Integration mit JSON Schema, unterstützte Swagger UI, das Tool, das die automatische Dokumentation bereitstellt, eine Zeit lang OpenAPI 3.1.0 nicht (das tut es seit Version 5.0.0 🎉).
+/// info
+
+Selbst, nachdem OpenAPI 3.1.0 veröffentlicht wurde, mit dieser neuen, einfacheren Integration mit JSON Schema, unterstützte Swagger UI, das Tool, das die automatische Dokumentation bereitstellt, eine Zeit lang OpenAPI 3.1.0 nicht (das tut es seit Version 5.0.0 🎉).
+
+Aus diesem Grund verwendeten Versionen von FastAPI vor 0.99.0 immer noch Versionen von OpenAPI vor 3.1.0.
- Aus diesem Grund verwendeten Versionen von FastAPI vor 0.99.0 immer noch Versionen von OpenAPI vor 3.1.0.
+///
### Pydantic- und FastAPI-`examples`
Kopieren Sie das Beispiel in eine Datei `main.py`:
-=== "Python 3.9+"
+//// tab | Python 3.9+
- ```Python
- {!> ../../../docs_src/security/tutorial001_an_py39.py!}
- ```
+```Python
+{!> ../../../docs_src/security/tutorial001_an_py39.py!}
+```
+
+////
-=== "Python 3.8+"
+//// tab | Python 3.8+
+
+```Python
+{!> ../../../docs_src/security/tutorial001_an.py!}
+```
- ```Python
- {!> ../../../docs_src/security/tutorial001_an.py!}
- ```
+////
-=== "Python 3.8+ nicht annotiert"
+//// tab | Python 3.8+ nicht annotiert
- !!! tip "Tipp"
- Bevorzugen Sie die `Annotated`-Version, falls möglich.
+/// tip | "Tipp"
+
+Bevorzugen Sie die `Annotated`-Version, falls möglich.
+
+///
+
+```Python
+{!> ../../../docs_src/security/tutorial001.py!}
+```
- ```Python
- {!> ../../../docs_src/security/tutorial001.py!}
- ```
+////
## Ausführen
-!!! info
- Um hochgeladene Dateien zu empfangen, installieren Sie zuerst <a href="https://andrew-d.github.io/python-multipart/" class="external-link" target="_blank">`python-multipart`</a>.
+/// info
- Z. B. `pip install python-multipart`.
+Um hochgeladene Dateien zu empfangen, installieren Sie zuerst <a href="https://andrew-d.github.io/python-multipart/" class="external-link" target="_blank">`python-multipart`</a>.
- Das, weil **OAuth2** „Formulardaten“ zum Senden von `username` und `password` verwendet.
+Z. B. `pip install python-multipart`.
+
+Das, weil **OAuth2** „Formulardaten“ zum Senden von `username` und `password` verwendet.
+
+///
Führen Sie das Beispiel aus mit:
<img src="/img/tutorial/security/image01.png">
-!!! check "Authorize-Button!"
- Sie haben bereits einen glänzenden, neuen „Authorize“-Button.
+/// check | "Authorize-Button!"
+
+Sie haben bereits einen glänzenden, neuen „Authorize“-Button.
- Und Ihre *Pfadoperation* hat in der oberen rechten Ecke ein kleines Schloss, auf das Sie klicken können.
+Und Ihre *Pfadoperation* hat in der oberen rechten Ecke ein kleines Schloss, auf das Sie klicken können.
+
+///
Und wenn Sie darauf klicken, erhalten Sie ein kleines Anmeldeformular zur Eingabe eines `username` und `password` (und anderer optionaler Felder):
<img src="/img/tutorial/security/image02.png">
-!!! note "Hinweis"
- Es spielt keine Rolle, was Sie in das Formular eingeben, es wird noch nicht funktionieren. Wir kommen dahin.
+/// note | "Hinweis"
+
+Es spielt keine Rolle, was Sie in das Formular eingeben, es wird noch nicht funktionieren. Wir kommen dahin.
+
+///
Dies ist natürlich nicht das Frontend für die Endbenutzer, aber es ist ein großartiges automatisches Tool, um Ihre gesamte API interaktiv zu dokumentieren.
In diesem Beispiel verwenden wir **OAuth2** mit dem **Password**-Flow und einem **Bearer**-Token. Wir machen das mit der Klasse `OAuth2PasswordBearer`.
-!!! info
- Ein „Bearer“-Token ist nicht die einzige Option.
+/// info
+
+Ein „Bearer“-Token ist nicht die einzige Option.
+
+Aber es ist die beste für unseren Anwendungsfall.
- Aber es ist die beste für unseren Anwendungsfall.
+Und es ist wahrscheinlich auch für die meisten anderen Anwendungsfälle die beste, es sei denn, Sie sind ein OAuth2-Experte und wissen genau, warum es eine andere Option gibt, die Ihren Anforderungen besser entspricht.
- Und es ist wahrscheinlich auch für die meisten anderen Anwendungsfälle die beste, es sei denn, Sie sind ein OAuth2-Experte und wissen genau, warum es eine andere Option gibt, die Ihren Anforderungen besser entspricht.
+In dem Fall gibt Ihnen **FastAPI** ebenfalls die Tools, die Sie zum Erstellen brauchen.
- In dem Fall gibt Ihnen **FastAPI** ebenfalls die Tools, die Sie zum Erstellen brauchen.
+///
Wenn wir eine Instanz der Klasse `OAuth2PasswordBearer` erstellen, übergeben wir den Parameter `tokenUrl`. Dieser Parameter enthält die URL, die der Client (das Frontend, das im Browser des Benutzers ausgeführt wird) verwendet, wenn er den `username` und das `password` sendet, um einen Token zu erhalten.
-=== "Python 3.9+"
+//// tab | Python 3.9+
- ```Python hl_lines="8"
- {!> ../../../docs_src/security/tutorial001_an_py39.py!}
- ```
+```Python hl_lines="8"
+{!> ../../../docs_src/security/tutorial001_an_py39.py!}
+```
-=== "Python 3.8+"
+////
- ```Python hl_lines="7"
- {!> ../../../docs_src/security/tutorial001_an.py!}
- ```
+//// tab | Python 3.8+
-=== "Python 3.8+ nicht annotiert"
+```Python hl_lines="7"
+{!> ../../../docs_src/security/tutorial001_an.py!}
+```
- !!! tip "Tipp"
- Bevorzugen Sie die `Annotated`-Version, falls möglich.
+////
- ```Python hl_lines="6"
- {!> ../../../docs_src/security/tutorial001.py!}
- ```
+//// tab | Python 3.8+ nicht annotiert
-!!! tip "Tipp"
- Hier bezieht sich `tokenUrl="token"` auf eine relative URL `token`, die wir noch nicht erstellt haben. Da es sich um eine relative URL handelt, entspricht sie `./token`.
+/// tip | "Tipp"
- Da wir eine relative URL verwenden, würde sich das, wenn sich Ihre API unter `https://example.com/` befindet, auf `https://example.com/token` beziehen. Wenn sich Ihre API jedoch unter `https://example.com/api/v1/` befände, würde es sich auf `https://example.com/api/v1/token` beziehen.
+Bevorzugen Sie die `Annotated`-Version, falls möglich.
- Die Verwendung einer relativen URL ist wichtig, um sicherzustellen, dass Ihre Anwendung auch in einem fortgeschrittenen Anwendungsfall, wie [hinter einem Proxy](../../advanced/behind-a-proxy.md){.internal-link target=_blank}, weiterhin funktioniert.
+///
+
+```Python hl_lines="6"
+{!> ../../../docs_src/security/tutorial001.py!}
+```
+
+////
+
+/// tip | "Tipp"
+
+Hier bezieht sich `tokenUrl="token"` auf eine relative URL `token`, die wir noch nicht erstellt haben. Da es sich um eine relative URL handelt, entspricht sie `./token`.
+
+Da wir eine relative URL verwenden, würde sich das, wenn sich Ihre API unter `https://example.com/` befindet, auf `https://example.com/token` beziehen. Wenn sich Ihre API jedoch unter `https://example.com/api/v1/` befände, würde es sich auf `https://example.com/api/v1/token` beziehen.
+
+Die Verwendung einer relativen URL ist wichtig, um sicherzustellen, dass Ihre Anwendung auch in einem fortgeschrittenen Anwendungsfall, wie [hinter einem Proxy](../../advanced/behind-a-proxy.md){.internal-link target=_blank}, weiterhin funktioniert.
+
+///
Dieser Parameter erstellt nicht diesen Endpunkt / diese *Pfadoperation*, sondern deklariert, dass die URL `/token` diejenige sein wird, die der Client verwenden soll, um den Token abzurufen. Diese Information wird in OpenAPI und dann in den interaktiven API-Dokumentationssystemen verwendet.
Wir werden demnächst auch die eigentliche Pfadoperation erstellen.
-!!! info
- Wenn Sie ein sehr strenger „Pythonista“ sind, missfällt Ihnen möglicherweise die Schreibweise des Parameternamens `tokenUrl` anstelle von `token_url`.
+/// info
+
+Wenn Sie ein sehr strenger „Pythonista“ sind, missfällt Ihnen möglicherweise die Schreibweise des Parameternamens `tokenUrl` anstelle von `token_url`.
+
+Das liegt daran, dass FastAPI denselben Namen wie in der OpenAPI-Spezifikation verwendet. Sodass Sie, wenn Sie mehr über eines dieser Sicherheitsschemas herausfinden möchten, den Namen einfach kopieren und einfügen können, um weitere Informationen darüber zu erhalten.
- Das liegt daran, dass FastAPI denselben Namen wie in der OpenAPI-Spezifikation verwendet. Sodass Sie, wenn Sie mehr über eines dieser Sicherheitsschemas herausfinden möchten, den Namen einfach kopieren und einfügen können, um weitere Informationen darüber zu erhalten.
+///
Die Variable `oauth2_scheme` ist eine Instanz von `OAuth2PasswordBearer`, aber auch ein „Callable“.
Jetzt können Sie dieses `oauth2_scheme` als Abhängigkeit `Depends` übergeben.
-=== "Python 3.9+"
+//// tab | Python 3.9+
- ```Python hl_lines="12"
- {!> ../../../docs_src/security/tutorial001_an_py39.py!}
- ```
+```Python hl_lines="12"
+{!> ../../../docs_src/security/tutorial001_an_py39.py!}
+```
+
+////
+
+//// tab | Python 3.8+
+
+```Python hl_lines="11"
+{!> ../../../docs_src/security/tutorial001_an.py!}
+```
-=== "Python 3.8+"
+////
- ```Python hl_lines="11"
- {!> ../../../docs_src/security/tutorial001_an.py!}
- ```
+//// tab | Python 3.8+ nicht annotiert
-=== "Python 3.8+ nicht annotiert"
+/// tip | "Tipp"
- !!! tip "Tipp"
- Bevorzugen Sie die `Annotated`-Version, falls möglich.
+Bevorzugen Sie die `Annotated`-Version, falls möglich.
- ```Python hl_lines="10"
- {!> ../../../docs_src/security/tutorial001.py!}
- ```
+///
+
+```Python hl_lines="10"
+{!> ../../../docs_src/security/tutorial001.py!}
+```
+
+////
Diese Abhängigkeit stellt einen `str` bereit, der dem Parameter `token` der *Pfadoperation-Funktion* zugewiesen wird.
**FastAPI** weiß, dass es diese Abhängigkeit verwenden kann, um ein „Sicherheitsschema“ im OpenAPI-Schema (und der automatischen API-Dokumentation) zu definieren.
-!!! info "Technische Details"
- **FastAPI** weiß, dass es die Klasse `OAuth2PasswordBearer` (deklariert in einer Abhängigkeit) verwenden kann, um das Sicherheitsschema in OpenAPI zu definieren, da es von `fastapi.security.oauth2.OAuth2` erbt, das wiederum von `fastapi.security.base.SecurityBase` erbt.
+/// info | "Technische Details"
+
+**FastAPI** weiß, dass es die Klasse `OAuth2PasswordBearer` (deklariert in einer Abhängigkeit) verwenden kann, um das Sicherheitsschema in OpenAPI zu definieren, da es von `fastapi.security.oauth2.OAuth2` erbt, das wiederum von `fastapi.security.base.SecurityBase` erbt.
+
+Alle Sicherheits-Werkzeuge, die in OpenAPI integriert sind (und die automatische API-Dokumentation), erben von `SecurityBase`, so weiß **FastAPI**, wie es sie in OpenAPI integrieren muss.
- Alle Sicherheits-Werkzeuge, die in OpenAPI integriert sind (und die automatische API-Dokumentation), erben von `SecurityBase`, so weiß **FastAPI**, wie es sie in OpenAPI integrieren muss.
+///
## Was es macht
Im vorherigen Kapitel hat das Sicherheitssystem (das auf dem Dependency Injection System basiert) der *Pfadoperation-Funktion* einen `token` vom Typ `str` überreicht:
-=== "Python 3.9+"
+//// tab | Python 3.9+
- ```Python hl_lines="12"
- {!> ../../../docs_src/security/tutorial001_an_py39.py!}
- ```
+```Python hl_lines="12"
+{!> ../../../docs_src/security/tutorial001_an_py39.py!}
+```
-=== "Python 3.8+"
+////
- ```Python hl_lines="11"
- {!> ../../../docs_src/security/tutorial001_an.py!}
- ```
+//// tab | Python 3.8+
-=== "Python 3.8+ nicht annotiert"
+```Python hl_lines="11"
+{!> ../../../docs_src/security/tutorial001_an.py!}
+```
- !!! tip "Tipp"
- Bevorzugen Sie die `Annotated`-Version, falls möglich.
+////
- ```Python hl_lines="10"
- {!> ../../../docs_src/security/tutorial001.py!}
- ```
+//// tab | Python 3.8+ nicht annotiert
+
+/// tip | "Tipp"
+
+Bevorzugen Sie die `Annotated`-Version, falls möglich.
+
+///
+
+```Python hl_lines="10"
+{!> ../../../docs_src/security/tutorial001.py!}
+```
+
+////
Aber das ist immer noch nicht so nützlich.
So wie wir Pydantic zum Deklarieren von Bodys verwenden, können wir es auch überall sonst verwenden:
-=== "Python 3.10+"
+//// tab | Python 3.10+
+
+```Python hl_lines="5 12-16"
+{!> ../../../docs_src/security/tutorial002_an_py310.py!}
+```
+
+////
+
+//// tab | Python 3.9+
+
+```Python hl_lines="5 12-16"
+{!> ../../../docs_src/security/tutorial002_an_py39.py!}
+```
+
+////
+
+//// tab | Python 3.8+
+
+```Python hl_lines="5 13-17"
+{!> ../../../docs_src/security/tutorial002_an.py!}
+```
+
+////
+
+//// tab | Python 3.10+ nicht annotiert
- ```Python hl_lines="5 12-16"
- {!> ../../../docs_src/security/tutorial002_an_py310.py!}
- ```
+/// tip | "Tipp"
-=== "Python 3.9+"
+Bevorzugen Sie die `Annotated`-Version, falls möglich.
- ```Python hl_lines="5 12-16"
- {!> ../../../docs_src/security/tutorial002_an_py39.py!}
- ```
+///
-=== "Python 3.8+"
+```Python hl_lines="3 10-14"
+{!> ../../../docs_src/security/tutorial002_py310.py!}
+```
- ```Python hl_lines="5 13-17"
- {!> ../../../docs_src/security/tutorial002_an.py!}
- ```
+////
-=== "Python 3.10+ nicht annotiert"
+//// tab | Python 3.8+ nicht annotiert
- !!! tip "Tipp"
- Bevorzugen Sie die `Annotated`-Version, falls möglich.
+/// tip | "Tipp"
- ```Python hl_lines="3 10-14"
- {!> ../../../docs_src/security/tutorial002_py310.py!}
- ```
+Bevorzugen Sie die `Annotated`-Version, falls möglich.
-=== "Python 3.8+ nicht annotiert"
+///
- !!! tip "Tipp"
- Bevorzugen Sie die `Annotated`-Version, falls möglich.
+```Python hl_lines="5 12-16"
+{!> ../../../docs_src/security/tutorial002.py!}
+```
- ```Python hl_lines="5 12-16"
- {!> ../../../docs_src/security/tutorial002.py!}
- ```
+////
## Eine `get_current_user`-Abhängigkeit erstellen
So wie wir es zuvor in der *Pfadoperation* direkt gemacht haben, erhält unsere neue Abhängigkeit `get_current_user` von der Unterabhängigkeit `oauth2_scheme` einen `token` vom Typ `str`:
-=== "Python 3.10+"
+//// tab | Python 3.10+
- ```Python hl_lines="25"
- {!> ../../../docs_src/security/tutorial002_an_py310.py!}
- ```
+```Python hl_lines="25"
+{!> ../../../docs_src/security/tutorial002_an_py310.py!}
+```
-=== "Python 3.9+"
+////
- ```Python hl_lines="25"
- {!> ../../../docs_src/security/tutorial002_an_py39.py!}
- ```
+//// tab | Python 3.9+
-=== "Python 3.8+"
+```Python hl_lines="25"
+{!> ../../../docs_src/security/tutorial002_an_py39.py!}
+```
- ```Python hl_lines="26"
- {!> ../../../docs_src/security/tutorial002_an.py!}
- ```
+////
-=== "Python 3.10+ nicht annotiert"
+//// tab | Python 3.8+
- !!! tip "Tipp"
- Bevorzugen Sie die `Annotated`-Version, falls möglich.
+```Python hl_lines="26"
+{!> ../../../docs_src/security/tutorial002_an.py!}
+```
- ```Python hl_lines="23"
- {!> ../../../docs_src/security/tutorial002_py310.py!}
- ```
+////
-=== "Python 3.8+ nicht annotiert"
+//// tab | Python 3.10+ nicht annotiert
- !!! tip "Tipp"
- Bevorzugen Sie die `Annotated`-Version, falls möglich.
+/// tip | "Tipp"
- ```Python hl_lines="25"
- {!> ../../../docs_src/security/tutorial002.py!}
- ```
+Bevorzugen Sie die `Annotated`-Version, falls möglich.
+
+///
+
+```Python hl_lines="23"
+{!> ../../../docs_src/security/tutorial002_py310.py!}
+```
+
+////
+
+//// tab | Python 3.8+ nicht annotiert
+
+/// tip | "Tipp"
+
+Bevorzugen Sie die `Annotated`-Version, falls möglich.
+
+///
+
+```Python hl_lines="25"
+{!> ../../../docs_src/security/tutorial002.py!}
+```
+
+////
## Den Benutzer holen
`get_current_user` wird eine von uns erstellte (gefakte) Hilfsfunktion verwenden, welche einen Token vom Typ `str` entgegennimmt und unser Pydantic-`User`-Modell zurückgibt:
-=== "Python 3.10+"
+//// tab | Python 3.10+
+
+```Python hl_lines="19-22 26-27"
+{!> ../../../docs_src/security/tutorial002_an_py310.py!}
+```
+
+////
+
+//// tab | Python 3.9+
+
+```Python hl_lines="19-22 26-27"
+{!> ../../../docs_src/security/tutorial002_an_py39.py!}
+```
- ```Python hl_lines="19-22 26-27"
- {!> ../../../docs_src/security/tutorial002_an_py310.py!}
- ```
+////
-=== "Python 3.9+"
+//// tab | Python 3.8+
- ```Python hl_lines="19-22 26-27"
- {!> ../../../docs_src/security/tutorial002_an_py39.py!}
- ```
+```Python hl_lines="20-23 27-28"
+{!> ../../../docs_src/security/tutorial002_an.py!}
+```
-=== "Python 3.8+"
+////
- ```Python hl_lines="20-23 27-28"
- {!> ../../../docs_src/security/tutorial002_an.py!}
- ```
+//// tab | Python 3.10+ nicht annotiert
-=== "Python 3.10+ nicht annotiert"
+/// tip | "Tipp"
- !!! tip "Tipp"
- Bevorzugen Sie die `Annotated`-Version, falls möglich.
+Bevorzugen Sie die `Annotated`-Version, falls möglich.
- ```Python hl_lines="17-20 24-25"
- {!> ../../../docs_src/security/tutorial002_py310.py!}
- ```
+///
-=== "Python 3.8+ nicht annotiert"
+```Python hl_lines="17-20 24-25"
+{!> ../../../docs_src/security/tutorial002_py310.py!}
+```
- !!! tip "Tipp"
- Bevorzugen Sie die `Annotated`-Version, falls möglich.
+////
- ```Python hl_lines="19-22 26-27"
- {!> ../../../docs_src/security/tutorial002.py!}
- ```
+//// tab | Python 3.8+ nicht annotiert
+
+/// tip | "Tipp"
+
+Bevorzugen Sie die `Annotated`-Version, falls möglich.
+
+///
+
+```Python hl_lines="19-22 26-27"
+{!> ../../../docs_src/security/tutorial002.py!}
+```
+
+////
## Den aktuellen Benutzer einfügen
Und jetzt können wir wiederum `Depends` mit unserem `get_current_user` in der *Pfadoperation* verwenden:
-=== "Python 3.10+"
+//// tab | Python 3.10+
+
+```Python hl_lines="31"
+{!> ../../../docs_src/security/tutorial002_an_py310.py!}
+```
+
+////
+
+//// tab | Python 3.9+
+
+```Python hl_lines="31"
+{!> ../../../docs_src/security/tutorial002_an_py39.py!}
+```
+
+////
+
+//// tab | Python 3.8+
+
+```Python hl_lines="32"
+{!> ../../../docs_src/security/tutorial002_an.py!}
+```
+
+////
+
+//// tab | Python 3.10+ nicht annotiert
- ```Python hl_lines="31"
- {!> ../../../docs_src/security/tutorial002_an_py310.py!}
- ```
+/// tip | "Tipp"
-=== "Python 3.9+"
+Bevorzugen Sie die `Annotated`-Version, falls möglich.
- ```Python hl_lines="31"
- {!> ../../../docs_src/security/tutorial002_an_py39.py!}
- ```
+///
-=== "Python 3.8+"
+```Python hl_lines="29"
+{!> ../../../docs_src/security/tutorial002_py310.py!}
+```
- ```Python hl_lines="32"
- {!> ../../../docs_src/security/tutorial002_an.py!}
- ```
+////
-=== "Python 3.10+ nicht annotiert"
+//// tab | Python 3.8+ nicht annotiert
- !!! tip "Tipp"
- Bevorzugen Sie die `Annotated`-Version, falls möglich.
+/// tip | "Tipp"
- ```Python hl_lines="29"
- {!> ../../../docs_src/security/tutorial002_py310.py!}
- ```
+Bevorzugen Sie die `Annotated`-Version, falls möglich.
-=== "Python 3.8+ nicht annotiert"
+///
- !!! tip "Tipp"
- Bevorzugen Sie die `Annotated`-Version, falls möglich.
+```Python hl_lines="31"
+{!> ../../../docs_src/security/tutorial002.py!}
+```
- ```Python hl_lines="31"
- {!> ../../../docs_src/security/tutorial002.py!}
- ```
+////
Beachten Sie, dass wir als Typ von `current_user` das Pydantic-Modell `User` deklarieren.
Das wird uns innerhalb der Funktion bei Codevervollständigung und Typprüfungen helfen.
-!!! tip "Tipp"
- Sie erinnern sich vielleicht, dass Requestbodys ebenfalls mit Pydantic-Modellen deklariert werden.
+/// tip | "Tipp"
- Weil Sie `Depends` verwenden, wird **FastAPI** hier aber nicht verwirrt.
+Sie erinnern sich vielleicht, dass Requestbodys ebenfalls mit Pydantic-Modellen deklariert werden.
-!!! check
- Die Art und Weise, wie dieses System von Abhängigkeiten konzipiert ist, ermöglicht es uns, verschiedene Abhängigkeiten (verschiedene „Dependables“) zu haben, die alle ein `User`-Modell zurückgeben.
+Weil Sie `Depends` verwenden, wird **FastAPI** hier aber nicht verwirrt.
- Wir sind nicht darauf beschränkt, nur eine Abhängigkeit zu haben, die diesen Typ von Daten zurückgeben kann.
+///
+
+/// check
+
+Die Art und Weise, wie dieses System von Abhängigkeiten konzipiert ist, ermöglicht es uns, verschiedene Abhängigkeiten (verschiedene „Dependables“) zu haben, die alle ein `User`-Modell zurückgeben.
+
+Wir sind nicht darauf beschränkt, nur eine Abhängigkeit zu haben, die diesen Typ von Daten zurückgeben kann.
+
+///
## Andere Modelle
Und alle diese Tausenden von *Pfadoperationen* können nur drei Zeilen lang sein:
-=== "Python 3.10+"
+//// tab | Python 3.10+
+
+```Python hl_lines="30-32"
+{!> ../../../docs_src/security/tutorial002_an_py310.py!}
+```
+
+////
+
+//// tab | Python 3.9+
+
+```Python hl_lines="30-32"
+{!> ../../../docs_src/security/tutorial002_an_py39.py!}
+```
+
+////
+
+//// tab | Python 3.8+
+
+```Python hl_lines="31-33"
+{!> ../../../docs_src/security/tutorial002_an.py!}
+```
+
+////
+
+//// tab | Python 3.10+ nicht annotiert
- ```Python hl_lines="30-32"
- {!> ../../../docs_src/security/tutorial002_an_py310.py!}
- ```
+/// tip | "Tipp"
-=== "Python 3.9+"
+Bevorzugen Sie die `Annotated`-Version, falls möglich.
- ```Python hl_lines="30-32"
- {!> ../../../docs_src/security/tutorial002_an_py39.py!}
- ```
+///
-=== "Python 3.8+"
+```Python hl_lines="28-30"
+{!> ../../../docs_src/security/tutorial002_py310.py!}
+```
- ```Python hl_lines="31-33"
- {!> ../../../docs_src/security/tutorial002_an.py!}
- ```
+////
-=== "Python 3.10+ nicht annotiert"
+//// tab | Python 3.8+ nicht annotiert
- !!! tip "Tipp"
- Bevorzugen Sie die `Annotated`-Version, falls möglich.
+/// tip | "Tipp"
- ```Python hl_lines="28-30"
- {!> ../../../docs_src/security/tutorial002_py310.py!}
- ```
+Bevorzugen Sie die `Annotated`-Version, falls möglich.
-=== "Python 3.8+ nicht annotiert"
+///
- !!! tip "Tipp"
- Bevorzugen Sie die `Annotated`-Version, falls möglich.
+```Python hl_lines="30-32"
+{!> ../../../docs_src/security/tutorial002.py!}
+```
- ```Python hl_lines="30-32"
- {!> ../../../docs_src/security/tutorial002.py!}
- ```
+////
## Zusammenfassung
OAuth2 spezifiziert nicht, wie die Kommunikation verschlüsselt werden soll, sondern erwartet, dass Ihre Anwendung mit HTTPS bereitgestellt wird.
-!!! tip "Tipp"
- Im Abschnitt über **Deployment** erfahren Sie, wie Sie HTTPS mithilfe von Traefik und Let's Encrypt kostenlos einrichten.
+/// tip | "Tipp"
+Im Abschnitt über **Deployment** erfahren Sie, wie Sie HTTPS mithilfe von Traefik und Let's Encrypt kostenlos einrichten.
+
+///
## OpenID Connect
* Diese automatische Erkennung ist es, die in der OpenID Connect Spezifikation definiert ist.
-!!! tip "Tipp"
- Auch die Integration anderer Authentifizierungs-/Autorisierungsanbieter wie Google, Facebook, Twitter, GitHub, usw. ist möglich und relativ einfach.
+/// tip | "Tipp"
+
+Auch die Integration anderer Authentifizierungs-/Autorisierungsanbieter wie Google, Facebook, Twitter, GitHub, usw. ist möglich und relativ einfach.
+
+Das komplexeste Problem besteht darin, einen Authentifizierungs-/Autorisierungsanbieter wie solche aufzubauen, aber **FastAPI** reicht Ihnen die Tools, das einfach zu erledigen, während Ihnen die schwere Arbeit abgenommen wird.
- Das komplexeste Problem besteht darin, einen Authentifizierungs-/Autorisierungsanbieter wie solche aufzubauen, aber **FastAPI** reicht Ihnen die Tools, das einfach zu erledigen, während Ihnen die schwere Arbeit abgenommen wird.
+///
## **FastAPI** Tools
Hier verwenden wir das empfohlene: <a href="https://cryptography.io/" class="external-link" target="_blank">pyca/cryptography</a>.
-!!! tip "Tipp"
- Dieses Tutorial verwendete zuvor <a href="https://pyjwt.readthedocs.io/" class="external-link" target="_blank">PyJWT</a>.
+/// tip | "Tipp"
- Es wurde jedoch aktualisiert, stattdessen python-jose zu verwenden, da dieses alle Funktionen von PyJWT sowie einige Extras bietet, die Sie später möglicherweise benötigen, wenn Sie Integrationen mit anderen Tools erstellen.
+Dieses Tutorial verwendete zuvor <a href="https://pyjwt.readthedocs.io/" class="external-link" target="_blank">PyJWT</a>.
+
+Es wurde jedoch aktualisiert, stattdessen python-jose zu verwenden, da dieses alle Funktionen von PyJWT sowie einige Extras bietet, die Sie später möglicherweise benötigen, wenn Sie Integrationen mit anderen Tools erstellen.
+
+///
## Passwort-Hashing
</div>
-!!! tip "Tipp"
- Mit `passlib` können Sie sogar konfigurieren, Passwörter zu lesen, die von **Django**, einem **Flask**-Sicherheit-Plugin, oder vielen anderen erstellt wurden.
+/// tip | "Tipp"
+
+Mit `passlib` können Sie sogar konfigurieren, Passwörter zu lesen, die von **Django**, einem **Flask**-Sicherheit-Plugin, oder vielen anderen erstellt wurden.
- So könnten Sie beispielsweise die gleichen Daten aus einer Django-Anwendung in einer Datenbank mit einer FastAPI-Anwendung teilen. Oder schrittweise eine Django-Anwendung migrieren, während Sie dieselbe Datenbank verwenden.
+So könnten Sie beispielsweise die gleichen Daten aus einer Django-Anwendung in einer Datenbank mit einer FastAPI-Anwendung teilen. Oder schrittweise eine Django-Anwendung migrieren, während Sie dieselbe Datenbank verwenden.
- Und Ihre Benutzer könnten sich gleichzeitig über Ihre Django-Anwendung oder Ihre **FastAPI**-Anwendung anmelden.
+Und Ihre Benutzer könnten sich gleichzeitig über Ihre Django-Anwendung oder Ihre **FastAPI**-Anwendung anmelden.
+
+///
## Die Passwörter hashen und überprüfen
Erstellen Sie einen PassLib-„Kontext“. Der wird für das Hashen und Verifizieren von Passwörtern verwendet.
-!!! tip "Tipp"
- Der PassLib-Kontext kann auch andere Hashing-Algorithmen verwenden, einschließlich deprecateter Alter, um etwa nur eine Verifizierung usw. zu ermöglichen.
+/// tip | "Tipp"
+
+Der PassLib-Kontext kann auch andere Hashing-Algorithmen verwenden, einschließlich deprecateter Alter, um etwa nur eine Verifizierung usw. zu ermöglichen.
- Sie könnten ihn beispielsweise verwenden, um von einem anderen System (wie Django) generierte Passwörter zu lesen und zu verifizieren, aber alle neuen Passwörter mit einem anderen Algorithmus wie Bcrypt zu hashen.
+Sie könnten ihn beispielsweise verwenden, um von einem anderen System (wie Django) generierte Passwörter zu lesen und zu verifizieren, aber alle neuen Passwörter mit einem anderen Algorithmus wie Bcrypt zu hashen.
- Und mit allen gleichzeitig kompatibel sein.
+Und mit allen gleichzeitig kompatibel sein.
+
+///
Erstellen Sie eine Hilfsfunktion, um ein vom Benutzer stammendes Passwort zu hashen.
Und noch eine, um einen Benutzer zu authentifizieren und zurückzugeben.
-=== "Python 3.10+"
+//// tab | Python 3.10+
+
+```Python hl_lines="7 48 55-56 59-60 69-75"
+{!> ../../../docs_src/security/tutorial004_an_py310.py!}
+```
+
+////
+
+//// tab | Python 3.9+
+
+```Python hl_lines="7 48 55-56 59-60 69-75"
+{!> ../../../docs_src/security/tutorial004_an_py39.py!}
+```
+
+////
+
+//// tab | Python 3.8+
+
+```Python hl_lines="7 49 56-57 60-61 70-76"
+{!> ../../../docs_src/security/tutorial004_an.py!}
+```
+
+////
- ```Python hl_lines="7 48 55-56 59-60 69-75"
- {!> ../../../docs_src/security/tutorial004_an_py310.py!}
- ```
+//// tab | Python 3.10+ nicht annotiert
-=== "Python 3.9+"
+/// tip | "Tipp"
- ```Python hl_lines="7 48 55-56 59-60 69-75"
- {!> ../../../docs_src/security/tutorial004_an_py39.py!}
- ```
+Bevorzugen Sie die `Annotated`-Version, falls möglich.
-=== "Python 3.8+"
+///
- ```Python hl_lines="7 49 56-57 60-61 70-76"
- {!> ../../../docs_src/security/tutorial004_an.py!}
- ```
+```Python hl_lines="6 47 54-55 58-59 68-74"
+{!> ../../../docs_src/security/tutorial004_py310.py!}
+```
+
+////
+
+//// tab | Python 3.8+ nicht annotiert
-=== "Python 3.10+ nicht annotiert"
+/// tip | "Tipp"
- !!! tip "Tipp"
- Bevorzugen Sie die `Annotated`-Version, falls möglich.
+Bevorzugen Sie die `Annotated`-Version, falls möglich.
- ```Python hl_lines="6 47 54-55 58-59 68-74"
- {!> ../../../docs_src/security/tutorial004_py310.py!}
- ```
+///
+
+```Python hl_lines="7 48 55-56 59-60 69-75"
+{!> ../../../docs_src/security/tutorial004.py!}
+```
-=== "Python 3.8+ nicht annotiert"
+////
- !!! tip "Tipp"
- Bevorzugen Sie die `Annotated`-Version, falls möglich.
+/// note | "Hinweis"
- ```Python hl_lines="7 48 55-56 59-60 69-75"
- {!> ../../../docs_src/security/tutorial004.py!}
- ```
+Wenn Sie sich die neue (gefakte) Datenbank `fake_users_db` anschauen, sehen Sie, wie das gehashte Passwort jetzt aussieht: `"$2b$12$EixZaYVK1fsbw1ZfbX3OXePaWxn96p36WQoeG6Lruj3vjPGga31lW"`.
-!!! note "Hinweis"
- Wenn Sie sich die neue (gefakte) Datenbank `fake_users_db` anschauen, sehen Sie, wie das gehashte Passwort jetzt aussieht: `"$2b$12$EixZaYVK1fsbw1ZfbX3OXePaWxn96p36WQoeG6Lruj3vjPGga31lW"`.
+///
## JWT-Token verarbeiten
Erstellen Sie eine Hilfsfunktion, um einen neuen Zugriffstoken zu generieren.
-=== "Python 3.10+"
+//// tab | Python 3.10+
+
+```Python hl_lines="6 12-14 28-30 78-86"
+{!> ../../../docs_src/security/tutorial004_an_py310.py!}
+```
+
+////
+
+//// tab | Python 3.9+
+
+```Python hl_lines="6 12-14 28-30 78-86"
+{!> ../../../docs_src/security/tutorial004_an_py39.py!}
+```
+
+////
+
+//// tab | Python 3.8+
+
+```Python hl_lines="6 13-15 29-31 79-87"
+{!> ../../../docs_src/security/tutorial004_an.py!}
+```
+
+////
+
+//// tab | Python 3.10+ nicht annotiert
- ```Python hl_lines="6 12-14 28-30 78-86"
- {!> ../../../docs_src/security/tutorial004_an_py310.py!}
- ```
+/// tip | "Tipp"
-=== "Python 3.9+"
+Bevorzugen Sie die `Annotated`-Version, falls möglich.
- ```Python hl_lines="6 12-14 28-30 78-86"
- {!> ../../../docs_src/security/tutorial004_an_py39.py!}
- ```
+///
-=== "Python 3.8+"
+```Python hl_lines="5 11-13 27-29 77-85"
+{!> ../../../docs_src/security/tutorial004_py310.py!}
+```
- ```Python hl_lines="6 13-15 29-31 79-87"
- {!> ../../../docs_src/security/tutorial004_an.py!}
- ```
+////
-=== "Python 3.10+ nicht annotiert"
+//// tab | Python 3.8+ nicht annotiert
- !!! tip "Tipp"
- Bevorzugen Sie die `Annotated`-Version, falls möglich.
+/// tip | "Tipp"
- ```Python hl_lines="5 11-13 27-29 77-85"
- {!> ../../../docs_src/security/tutorial004_py310.py!}
- ```
+Bevorzugen Sie die `Annotated`-Version, falls möglich.
-=== "Python 3.8+ nicht annotiert"
+///
- !!! tip "Tipp"
- Bevorzugen Sie die `Annotated`-Version, falls möglich.
+```Python hl_lines="6 12-14 28-30 78-86"
+{!> ../../../docs_src/security/tutorial004.py!}
+```
- ```Python hl_lines="6 12-14 28-30 78-86"
- {!> ../../../docs_src/security/tutorial004.py!}
- ```
+////
## Die Abhängigkeiten aktualisieren
Wenn der Token ungültig ist, geben Sie sofort einen HTTP-Fehler zurück.
-=== "Python 3.10+"
+//// tab | Python 3.10+
- ```Python hl_lines="89-106"
- {!> ../../../docs_src/security/tutorial004_an_py310.py!}
- ```
+```Python hl_lines="89-106"
+{!> ../../../docs_src/security/tutorial004_an_py310.py!}
+```
-=== "Python 3.9+"
+////
- ```Python hl_lines="89-106"
- {!> ../../../docs_src/security/tutorial004_an_py39.py!}
- ```
+//// tab | Python 3.9+
-=== "Python 3.8+"
+```Python hl_lines="89-106"
+{!> ../../../docs_src/security/tutorial004_an_py39.py!}
+```
- ```Python hl_lines="90-107"
- {!> ../../../docs_src/security/tutorial004_an.py!}
- ```
+////
-=== "Python 3.10+ nicht annotiert"
+//// tab | Python 3.8+
- !!! tip "Tipp"
- Bevorzugen Sie die `Annotated`-Version, falls möglich.
+```Python hl_lines="90-107"
+{!> ../../../docs_src/security/tutorial004_an.py!}
+```
- ```Python hl_lines="88-105"
- {!> ../../../docs_src/security/tutorial004_py310.py!}
- ```
+////
-=== "Python 3.8+ nicht annotiert"
+//// tab | Python 3.10+ nicht annotiert
- !!! tip "Tipp"
- Bevorzugen Sie die `Annotated`-Version, falls möglich.
+/// tip | "Tipp"
+
+Bevorzugen Sie die `Annotated`-Version, falls möglich.
+
+///
+
+```Python hl_lines="88-105"
+{!> ../../../docs_src/security/tutorial004_py310.py!}
+```
- ```Python hl_lines="89-106"
- {!> ../../../docs_src/security/tutorial004.py!}
- ```
+////
+
+//// tab | Python 3.8+ nicht annotiert
+
+/// tip | "Tipp"
+
+Bevorzugen Sie die `Annotated`-Version, falls möglich.
+
+///
+
+```Python hl_lines="89-106"
+{!> ../../../docs_src/security/tutorial004.py!}
+```
+
+////
## Die *Pfadoperation* `/token` aktualisieren
Erstellen Sie einen echten JWT-Zugriffstoken und geben Sie ihn zurück.
-=== "Python 3.10+"
+//// tab | Python 3.10+
+
+```Python hl_lines="117-132"
+{!> ../../../docs_src/security/tutorial004_an_py310.py!}
+```
+
+////
- ```Python hl_lines="117-132"
- {!> ../../../docs_src/security/tutorial004_an_py310.py!}
- ```
+//// tab | Python 3.9+
-=== "Python 3.9+"
+```Python hl_lines="117-132"
+{!> ../../../docs_src/security/tutorial004_an_py39.py!}
+```
- ```Python hl_lines="117-132"
- {!> ../../../docs_src/security/tutorial004_an_py39.py!}
- ```
+////
-=== "Python 3.8+"
+//// tab | Python 3.8+
+
+```Python hl_lines="118-133"
+{!> ../../../docs_src/security/tutorial004_an.py!}
+```
- ```Python hl_lines="118-133"
- {!> ../../../docs_src/security/tutorial004_an.py!}
- ```
+////
-=== "Python 3.10+ nicht annotiert"
+//// tab | Python 3.10+ nicht annotiert
- !!! tip "Tipp"
- Bevorzugen Sie die `Annotated`-Version, falls möglich.
+/// tip | "Tipp"
+
+Bevorzugen Sie die `Annotated`-Version, falls möglich.
+
+///
+
+```Python hl_lines="114-129"
+{!> ../../../docs_src/security/tutorial004_py310.py!}
+```
- ```Python hl_lines="114-129"
- {!> ../../../docs_src/security/tutorial004_py310.py!}
- ```
+////
-=== "Python 3.8+ nicht annotiert"
+//// tab | Python 3.8+ nicht annotiert
- !!! tip "Tipp"
- Bevorzugen Sie die `Annotated`-Version, falls möglich.
+/// tip | "Tipp"
- ```Python hl_lines="115-130"
- {!> ../../../docs_src/security/tutorial004.py!}
- ```
+Bevorzugen Sie die `Annotated`-Version, falls möglich.
+
+///
+
+```Python hl_lines="115-130"
+{!> ../../../docs_src/security/tutorial004.py!}
+```
+
+////
### Technische Details zum JWT-„Subjekt“ `sub`
Benutzername: `johndoe`
Passwort: `secret`.
-!!! check
- Beachten Sie, dass im Code nirgendwo das Klartext-Passwort "`secret`" steht, wir haben nur die gehashte Version.
+/// check
+
+Beachten Sie, dass im Code nirgendwo das Klartext-Passwort "`secret`" steht, wir haben nur die gehashte Version.
+
+///
<img src="/img/tutorial/security/image08.png">
<img src="/img/tutorial/security/image10.png">
-!!! note "Hinweis"
- Beachten Sie den Header `Authorization` mit einem Wert, der mit `Bearer` beginnt.
+/// note | "Hinweis"
+
+Beachten Sie den Header `Authorization` mit einem Wert, der mit `Bearer` beginnt.
+
+///
## Fortgeschrittene Verwendung mit `scopes`
* `instagram_basic` wird von Facebook / Instagram verwendet.
* `https://www.googleapis.com/auth/drive` wird von Google verwendet.
-!!! info
- In OAuth2 ist ein „Scope“ nur ein String, der eine bestimmte erforderliche Berechtigung deklariert.
+/// info
- Es spielt keine Rolle, ob er andere Zeichen wie `:` enthält oder ob es eine URL ist.
+In OAuth2 ist ein „Scope“ nur ein String, der eine bestimmte erforderliche Berechtigung deklariert.
- Diese Details sind implementierungsspezifisch.
+Es spielt keine Rolle, ob er andere Zeichen wie `:` enthält oder ob es eine URL ist.
- Für OAuth2 sind es einfach nur Strings.
+Diese Details sind implementierungsspezifisch.
+
+Für OAuth2 sind es einfach nur Strings.
+
+///
## Code, um `username` und `password` entgegenzunehmen.
Importieren Sie zunächst `OAuth2PasswordRequestForm` und verwenden Sie es als Abhängigkeit mit `Depends` in der *Pfadoperation* für `/token`:
-=== "Python 3.10+"
+//// tab | Python 3.10+
+
+```Python hl_lines="4 78"
+{!> ../../../docs_src/security/tutorial003_an_py310.py!}
+```
+
+////
+
+//// tab | Python 3.9+
+
+```Python hl_lines="4 78"
+{!> ../../../docs_src/security/tutorial003_an_py39.py!}
+```
+
+////
+
+//// tab | Python 3.8+
+
+```Python hl_lines="4 79"
+{!> ../../../docs_src/security/tutorial003_an.py!}
+```
+
+////
+
+//// tab | Python 3.10+ nicht annotiert
- ```Python hl_lines="4 78"
- {!> ../../../docs_src/security/tutorial003_an_py310.py!}
- ```
+/// tip | "Tipp"
-=== "Python 3.9+"
+Bevorzugen Sie die `Annotated`-Version, falls möglich.
- ```Python hl_lines="4 78"
- {!> ../../../docs_src/security/tutorial003_an_py39.py!}
- ```
+///
-=== "Python 3.8+"
+```Python hl_lines="2 74"
+{!> ../../../docs_src/security/tutorial003_py310.py!}
+```
- ```Python hl_lines="4 79"
- {!> ../../../docs_src/security/tutorial003_an.py!}
- ```
+////
-=== "Python 3.10+ nicht annotiert"
+//// tab | Python 3.8+ nicht annotiert
- !!! tip "Tipp"
- Bevorzugen Sie die `Annotated`-Version, falls möglich.
+/// tip | "Tipp"
- ```Python hl_lines="2 74"
- {!> ../../../docs_src/security/tutorial003_py310.py!}
- ```
+Bevorzugen Sie die `Annotated`-Version, falls möglich.
-=== "Python 3.8+ nicht annotiert"
+///
- !!! tip "Tipp"
- Bevorzugen Sie die `Annotated`-Version, falls möglich.
+```Python hl_lines="4 76"
+{!> ../../../docs_src/security/tutorial003.py!}
+```
- ```Python hl_lines="4 76"
- {!> ../../../docs_src/security/tutorial003.py!}
- ```
+////
`OAuth2PasswordRequestForm` ist eine Klassenabhängigkeit, die einen Formularbody deklariert mit:
* Einem optionalen `scope`-Feld als langem String, bestehend aus durch Leerzeichen getrennten Strings.
* Einem optionalen `grant_type` („Art der Anmeldung“).
-!!! tip "Tipp"
- Die OAuth2-Spezifikation *erfordert* tatsächlich ein Feld `grant_type` mit dem festen Wert `password`, aber `OAuth2PasswordRequestForm` erzwingt dies nicht.
+/// tip | "Tipp"
+
+Die OAuth2-Spezifikation *erfordert* tatsächlich ein Feld `grant_type` mit dem festen Wert `password`, aber `OAuth2PasswordRequestForm` erzwingt dies nicht.
- Wenn Sie es erzwingen müssen, verwenden Sie `OAuth2PasswordRequestFormStrict` anstelle von `OAuth2PasswordRequestForm`.
+Wenn Sie es erzwingen müssen, verwenden Sie `OAuth2PasswordRequestFormStrict` anstelle von `OAuth2PasswordRequestForm`.
+
+///
* Eine optionale `client_id` (benötigen wir für unser Beispiel nicht).
* Ein optionales `client_secret` (benötigen wir für unser Beispiel nicht).
-!!! info
- `OAuth2PasswordRequestForm` ist keine spezielle Klasse für **FastAPI**, so wie `OAuth2PasswordBearer`.
+/// info
+
+`OAuth2PasswordRequestForm` ist keine spezielle Klasse für **FastAPI**, so wie `OAuth2PasswordBearer`.
+
+`OAuth2PasswordBearer` lässt **FastAPI** wissen, dass es sich um ein Sicherheitsschema handelt. Daher wird es auf diese Weise zu OpenAPI hinzugefügt.
- `OAuth2PasswordBearer` lässt **FastAPI** wissen, dass es sich um ein Sicherheitsschema handelt. Daher wird es auf diese Weise zu OpenAPI hinzugefügt.
+Aber `OAuth2PasswordRequestForm` ist nur eine Klassenabhängigkeit, die Sie selbst hätten schreiben können, oder Sie hätten `Form`ular-Parameter direkt deklarieren können.
- Aber `OAuth2PasswordRequestForm` ist nur eine Klassenabhängigkeit, die Sie selbst hätten schreiben können, oder Sie hätten `Form`ular-Parameter direkt deklarieren können.
+Da es sich jedoch um einen häufigen Anwendungsfall handelt, wird er zur Vereinfachung direkt von **FastAPI** bereitgestellt.
- Da es sich jedoch um einen häufigen Anwendungsfall handelt, wird er zur Vereinfachung direkt von **FastAPI** bereitgestellt.
+///
### Die Formulardaten verwenden
-!!! tip "Tipp"
- Die Instanz der Klassenabhängigkeit `OAuth2PasswordRequestForm` verfügt, statt eines Attributs `scope` mit dem durch Leerzeichen getrennten langen String, über das Attribut `scopes` mit einer tatsächlichen Liste von Strings, einem für jeden gesendeten Scope.
+/// tip | "Tipp"
+
+Die Instanz der Klassenabhängigkeit `OAuth2PasswordRequestForm` verfügt, statt eines Attributs `scope` mit dem durch Leerzeichen getrennten langen String, über das Attribut `scopes` mit einer tatsächlichen Liste von Strings, einem für jeden gesendeten Scope.
+
+In diesem Beispiel verwenden wir keine `scopes`, aber die Funktionalität ist vorhanden, wenn Sie sie benötigen.
- In diesem Beispiel verwenden wir keine `scopes`, aber die Funktionalität ist vorhanden, wenn Sie sie benötigen.
+///
Rufen Sie nun die Benutzerdaten aus der (gefakten) Datenbank ab, für diesen `username` aus dem Formularfeld.
Für den Fehler verwenden wir die Exception `HTTPException`:
-=== "Python 3.10+"
+//// tab | Python 3.10+
- ```Python hl_lines="3 79-81"
- {!> ../../../docs_src/security/tutorial003_an_py310.py!}
- ```
+```Python hl_lines="3 79-81"
+{!> ../../../docs_src/security/tutorial003_an_py310.py!}
+```
+
+////
+
+//// tab | Python 3.9+
-=== "Python 3.9+"
+```Python hl_lines="3 79-81"
+{!> ../../../docs_src/security/tutorial003_an_py39.py!}
+```
+
+////
- ```Python hl_lines="3 79-81"
- {!> ../../../docs_src/security/tutorial003_an_py39.py!}
- ```
+//// tab | Python 3.8+
-=== "Python 3.8+"
+```Python hl_lines="3 80-82"
+{!> ../../../docs_src/security/tutorial003_an.py!}
+```
- ```Python hl_lines="3 80-82"
- {!> ../../../docs_src/security/tutorial003_an.py!}
- ```
+////
-=== "Python 3.10+ nicht annotiert"
+//// tab | Python 3.10+ nicht annotiert
+
+/// tip | "Tipp"
+
+Bevorzugen Sie die `Annotated`-Version, falls möglich.
+
+///
+
+```Python hl_lines="1 75-77"
+{!> ../../../docs_src/security/tutorial003_py310.py!}
+```
- !!! tip "Tipp"
- Bevorzugen Sie die `Annotated`-Version, falls möglich.
+////
- ```Python hl_lines="1 75-77"
- {!> ../../../docs_src/security/tutorial003_py310.py!}
- ```
+//// tab | Python 3.8+ nicht annotiert
-=== "Python 3.8+ nicht annotiert"
+/// tip | "Tipp"
- !!! tip "Tipp"
- Bevorzugen Sie die `Annotated`-Version, falls möglich.
+Bevorzugen Sie die `Annotated`-Version, falls möglich.
- ```Python hl_lines="3 77-79"
- {!> ../../../docs_src/security/tutorial003.py!}
- ```
+///
+
+```Python hl_lines="3 77-79"
+{!> ../../../docs_src/security/tutorial003.py!}
+```
+
+////
### Das Passwort überprüfen
Der Dieb kann also nicht versuchen, die gleichen Passwörter in einem anderen System zu verwenden (da viele Benutzer überall das gleiche Passwort verwenden, wäre dies gefährlich).
-=== "Python 3.10+"
+//// tab | Python 3.10+
+
+```Python hl_lines="82-85"
+{!> ../../../docs_src/security/tutorial003_an_py310.py!}
+```
+
+////
+
+//// tab | Python 3.9+
+
+```Python hl_lines="82-85"
+{!> ../../../docs_src/security/tutorial003_an_py39.py!}
+```
+
+////
- ```Python hl_lines="82-85"
- {!> ../../../docs_src/security/tutorial003_an_py310.py!}
- ```
+//// tab | Python 3.8+
-=== "Python 3.9+"
+```Python hl_lines="83-86"
+{!> ../../../docs_src/security/tutorial003_an.py!}
+```
+
+////
+
+//// tab | Python 3.10+ nicht annotiert
- ```Python hl_lines="82-85"
- {!> ../../../docs_src/security/tutorial003_an_py39.py!}
- ```
+/// tip | "Tipp"
-=== "Python 3.8+"
+Bevorzugen Sie die `Annotated`-Version, falls möglich.
- ```Python hl_lines="83-86"
- {!> ../../../docs_src/security/tutorial003_an.py!}
- ```
+///
-=== "Python 3.10+ nicht annotiert"
+```Python hl_lines="78-81"
+{!> ../../../docs_src/security/tutorial003_py310.py!}
+```
+
+////
- !!! tip "Tipp"
- Bevorzugen Sie die `Annotated`-Version, falls möglich.
+//// tab | Python 3.8+ nicht annotiert
- ```Python hl_lines="78-81"
- {!> ../../../docs_src/security/tutorial003_py310.py!}
- ```
+/// tip | "Tipp"
-=== "Python 3.8+ nicht annotiert"
+Bevorzugen Sie die `Annotated`-Version, falls möglich.
- !!! tip "Tipp"
- Bevorzugen Sie die `Annotated`-Version, falls möglich.
+///
- ```Python hl_lines="80-83"
- {!> ../../../docs_src/security/tutorial003.py!}
- ```
+```Python hl_lines="80-83"
+{!> ../../../docs_src/security/tutorial003.py!}
+```
+
+////
#### Über `**user_dict`
)
```
-!!! info
- Eine ausführlichere Erklärung von `**user_dict` finden Sie in [der Dokumentation für **Extra Modelle**](../extra-models.md#uber-user_indict){.internal-link target=_blank}.
+/// info
+
+Eine ausführlichere Erklärung von `**user_dict` finden Sie in [der Dokumentation für **Extra Modelle**](../extra-models.md#uber-user_indict){.internal-link target=_blank}.
+
+///
## Den Token zurückgeben
In diesem einfachen Beispiel gehen wir einfach völlig unsicher vor und geben denselben `username` wie der Token zurück.
-!!! tip "Tipp"
- Im nächsten Kapitel sehen Sie eine wirklich sichere Implementierung mit Passwort-Hashing und <abbr title="JSON Web Tokens">JWT</abbr>-Tokens.
+/// tip | "Tipp"
+
+Im nächsten Kapitel sehen Sie eine wirklich sichere Implementierung mit Passwort-Hashing und <abbr title="JSON Web Tokens">JWT</abbr>-Tokens.
+
+Aber konzentrieren wir uns zunächst auf die spezifischen Details, die wir benötigen.
- Aber konzentrieren wir uns zunächst auf die spezifischen Details, die wir benötigen.
+///
-=== "Python 3.10+"
+//// tab | Python 3.10+
- ```Python hl_lines="87"
- {!> ../../../docs_src/security/tutorial003_an_py310.py!}
- ```
+```Python hl_lines="87"
+{!> ../../../docs_src/security/tutorial003_an_py310.py!}
+```
+
+////
+
+//// tab | Python 3.9+
-=== "Python 3.9+"
+```Python hl_lines="87"
+{!> ../../../docs_src/security/tutorial003_an_py39.py!}
+```
- ```Python hl_lines="87"
- {!> ../../../docs_src/security/tutorial003_an_py39.py!}
- ```
+////
-=== "Python 3.8+"
+//// tab | Python 3.8+
- ```Python hl_lines="88"
- {!> ../../../docs_src/security/tutorial003_an.py!}
- ```
+```Python hl_lines="88"
+{!> ../../../docs_src/security/tutorial003_an.py!}
+```
-=== "Python 3.10+ nicht annotiert"
+////
- !!! tip "Tipp"
- Bevorzugen Sie die `Annotated`-Version, falls möglich.
+//// tab | Python 3.10+ nicht annotiert
- ```Python hl_lines="83"
- {!> ../../../docs_src/security/tutorial003_py310.py!}
- ```
+/// tip | "Tipp"
-=== "Python 3.8+ nicht annotiert"
+Bevorzugen Sie die `Annotated`-Version, falls möglich.
- !!! tip "Tipp"
- Bevorzugen Sie die `Annotated`-Version, falls möglich.
+///
- ```Python hl_lines="85"
- {!> ../../../docs_src/security/tutorial003.py!}
- ```
+```Python hl_lines="83"
+{!> ../../../docs_src/security/tutorial003_py310.py!}
+```
-!!! tip "Tipp"
- Gemäß der Spezifikation sollten Sie ein JSON mit einem `access_token` und einem `token_type` zurückgeben, genau wie in diesem Beispiel.
+////
- Das müssen Sie selbst in Ihrem Code tun und sicherstellen, dass Sie diese JSON-Schlüssel verwenden.
+//// tab | Python 3.8+ nicht annotiert
+
+/// tip | "Tipp"
+
+Bevorzugen Sie die `Annotated`-Version, falls möglich.
+
+///
+
+```Python hl_lines="85"
+{!> ../../../docs_src/security/tutorial003.py!}
+```
- Es ist fast das Einzige, woran Sie denken müssen, es selbst richtigzumachen und die Spezifikationen einzuhalten.
+////
- Den Rest erledigt **FastAPI** für Sie.
+/// tip | "Tipp"
+
+Gemäß der Spezifikation sollten Sie ein JSON mit einem `access_token` und einem `token_type` zurückgeben, genau wie in diesem Beispiel.
+
+Das müssen Sie selbst in Ihrem Code tun und sicherstellen, dass Sie diese JSON-Schlüssel verwenden.
+
+Es ist fast das Einzige, woran Sie denken müssen, es selbst richtigzumachen und die Spezifikationen einzuhalten.
+
+Den Rest erledigt **FastAPI** für Sie.
+
+///
## Die Abhängigkeiten aktualisieren
In unserem Endpunkt erhalten wir also nur dann einen Benutzer, wenn der Benutzer existiert, korrekt authentifiziert wurde und aktiv ist:
-=== "Python 3.10+"
+//// tab | Python 3.10+
- ```Python hl_lines="58-66 69-74 94"
- {!> ../../../docs_src/security/tutorial003_an_py310.py!}
- ```
+```Python hl_lines="58-66 69-74 94"
+{!> ../../../docs_src/security/tutorial003_an_py310.py!}
+```
-=== "Python 3.9+"
+////
- ```Python hl_lines="58-66 69-74 94"
- {!> ../../../docs_src/security/tutorial003_an_py39.py!}
- ```
+//// tab | Python 3.9+
-=== "Python 3.8+"
+```Python hl_lines="58-66 69-74 94"
+{!> ../../../docs_src/security/tutorial003_an_py39.py!}
+```
+
+////
+
+//// tab | Python 3.8+
+
+```Python hl_lines="59-67 70-75 95"
+{!> ../../../docs_src/security/tutorial003_an.py!}
+```
- ```Python hl_lines="59-67 70-75 95"
- {!> ../../../docs_src/security/tutorial003_an.py!}
- ```
+////
-=== "Python 3.10+ nicht annotiert"
+//// tab | Python 3.10+ nicht annotiert
- !!! tip "Tipp"
- Bevorzugen Sie die `Annotated`-Version, falls möglich.
+/// tip | "Tipp"
- ```Python hl_lines="56-64 67-70 88"
- {!> ../../../docs_src/security/tutorial003_py310.py!}
- ```
+Bevorzugen Sie die `Annotated`-Version, falls möglich.
+
+///
+
+```Python hl_lines="56-64 67-70 88"
+{!> ../../../docs_src/security/tutorial003_py310.py!}
+```
+
+////
+
+//// tab | Python 3.8+ nicht annotiert
+
+/// tip | "Tipp"
+
+Bevorzugen Sie die `Annotated`-Version, falls möglich.
+
+///
+
+```Python hl_lines="58-66 69-72 90"
+{!> ../../../docs_src/security/tutorial003.py!}
+```
-=== "Python 3.8+ nicht annotiert"
+////
- !!! tip "Tipp"
- Bevorzugen Sie die `Annotated`-Version, falls möglich.
+/// info
- ```Python hl_lines="58-66 69-72 90"
- {!> ../../../docs_src/security/tutorial003.py!}
- ```
+Der zusätzliche Header `WWW-Authenticate` mit dem Wert `Bearer`, den wir hier zurückgeben, ist ebenfalls Teil der Spezifikation.
-!!! info
- Der zusätzliche Header `WWW-Authenticate` mit dem Wert `Bearer`, den wir hier zurückgeben, ist ebenfalls Teil der Spezifikation.
+Jeder HTTP-(Fehler-)Statuscode 401 „UNAUTHORIZED“ soll auch einen `WWW-Authenticate`-Header zurückgeben.
- Jeder HTTP-(Fehler-)Statuscode 401 „UNAUTHORIZED“ soll auch einen `WWW-Authenticate`-Header zurückgeben.
+Im Fall von Bearer-Tokens (in unserem Fall) sollte der Wert dieses Headers `Bearer` lauten.
- Im Fall von Bearer-Tokens (in unserem Fall) sollte der Wert dieses Headers `Bearer` lauten.
+Sie können diesen zusätzlichen Header tatsächlich weglassen und es würde trotzdem funktionieren.
- Sie können diesen zusätzlichen Header tatsächlich weglassen und es würde trotzdem funktionieren.
+Aber er wird hier bereitgestellt, um den Spezifikationen zu entsprechen.
- Aber er wird hier bereitgestellt, um den Spezifikationen zu entsprechen.
+Außerdem gibt es möglicherweise Tools, die ihn erwarten und verwenden (jetzt oder in der Zukunft) und das könnte für Sie oder Ihre Benutzer jetzt oder in der Zukunft nützlich sein.
- Außerdem gibt es möglicherweise Tools, die ihn erwarten und verwenden (jetzt oder in der Zukunft) und das könnte für Sie oder Ihre Benutzer jetzt oder in der Zukunft nützlich sein.
+Das ist der Vorteil von Standards ...
- Das ist der Vorteil von Standards ...
+///
## Es in Aktion sehen
{!../../../docs_src/static_files/tutorial001.py!}
```
-!!! note "Technische Details"
- Sie könnten auch `from starlette.staticfiles import StaticFiles` verwenden.
+/// note | "Technische Details"
- **FastAPI** stellt dasselbe `starlette.staticfiles` auch via `fastapi.staticfiles` bereit, als Annehmlichkeit für Sie, den Entwickler. Es kommt aber tatsächlich direkt von Starlette.
+Sie könnten auch `from starlette.staticfiles import StaticFiles` verwenden.
+
+**FastAPI** stellt dasselbe `starlette.staticfiles` auch via `fastapi.staticfiles` bereit, als Annehmlichkeit für Sie, den Entwickler. Es kommt aber tatsächlich direkt von Starlette.
+
+///
### Was ist „Mounten“?
## Verwendung von `TestClient`
-!!! info
- Um `TestClient` zu verwenden, installieren Sie zunächst <a href="https://www.python-httpx.org" class="external-link" target="_blank">`httpx`</a>.
+/// info
- Z. B. `pip install httpx`.
+Um `TestClient` zu verwenden, installieren Sie zunächst <a href="https://www.python-httpx.org" class="external-link" target="_blank">`httpx`</a>.
+
+Z. B. `pip install httpx`.
+
+///
Importieren Sie `TestClient`.
{!../../../docs_src/app_testing/tutorial001.py!}
```
-!!! tip "Tipp"
- Beachten Sie, dass die Testfunktionen normal `def` und nicht `async def` sind.
+/// tip | "Tipp"
+
+Beachten Sie, dass die Testfunktionen normal `def` und nicht `async def` sind.
+
+Und die Anrufe an den Client sind ebenfalls normale Anrufe, die nicht `await` verwenden.
+
+Dadurch können Sie `pytest` ohne Komplikationen direkt nutzen.
+
+///
+
+/// note | "Technische Details"
+
+Sie könnten auch `from starlette.testclient import TestClient` verwenden.
- Und die Anrufe an den Client sind ebenfalls normale Anrufe, die nicht `await` verwenden.
+**FastAPI** stellt denselben `starlette.testclient` auch via `fastapi.testclient` bereit, als Annehmlichkeit für Sie, den Entwickler. Es kommt aber tatsächlich direkt von Starlette.
- Dadurch können Sie `pytest` ohne Komplikationen direkt nutzen.
+///
-!!! note "Technische Details"
- Sie könnten auch `from starlette.testclient import TestClient` verwenden.
+/// tip | "Tipp"
- **FastAPI** stellt denselben `starlette.testclient` auch via `fastapi.testclient` bereit, als Annehmlichkeit für Sie, den Entwickler. Es kommt aber tatsächlich direkt von Starlette.
+Wenn Sie in Ihren Tests neben dem Senden von Anfragen an Ihre FastAPI-Anwendung auch `async`-Funktionen aufrufen möchten (z. B. asynchrone Datenbankfunktionen), werfen Sie einen Blick auf die [Async-Tests](../advanced/async-tests.md){.internal-link target=_blank} im Handbuch für fortgeschrittene Benutzer.
-!!! tip "Tipp"
- Wenn Sie in Ihren Tests neben dem Senden von Anfragen an Ihre FastAPI-Anwendung auch `async`-Funktionen aufrufen möchten (z. B. asynchrone Datenbankfunktionen), werfen Sie einen Blick auf die [Async-Tests](../advanced/async-tests.md){.internal-link target=_blank} im Handbuch für fortgeschrittene Benutzer.
+///
## Tests separieren
Beide *Pfadoperationen* erfordern einen `X-Token`-Header.
-=== "Python 3.10+"
+//// tab | Python 3.10+
- ```Python
- {!> ../../../docs_src/app_testing/app_b_an_py310/main.py!}
- ```
+```Python
+{!> ../../../docs_src/app_testing/app_b_an_py310/main.py!}
+```
-=== "Python 3.9+"
+////
- ```Python
- {!> ../../../docs_src/app_testing/app_b_an_py39/main.py!}
- ```
+//// tab | Python 3.9+
-=== "Python 3.8+"
+```Python
+{!> ../../../docs_src/app_testing/app_b_an_py39/main.py!}
+```
- ```Python
- {!> ../../../docs_src/app_testing/app_b_an/main.py!}
- ```
+////
-=== "Python 3.10+ nicht annotiert"
+//// tab | Python 3.8+
+
+```Python
+{!> ../../../docs_src/app_testing/app_b_an/main.py!}
+```
- !!! tip "Tipp"
- Bevorzugen Sie die `Annotated`-Version, falls möglich.
+////
- ```Python
- {!> ../../../docs_src/app_testing/app_b_py310/main.py!}
- ```
+//// tab | Python 3.10+ nicht annotiert
-=== "Python 3.8+ nicht annotiert"
+/// tip | "Tipp"
- !!! tip "Tipp"
- Bevorzugen Sie die `Annotated`-Version, falls möglich.
+Bevorzugen Sie die `Annotated`-Version, falls möglich.
- ```Python
- {!> ../../../docs_src/app_testing/app_b/main.py!}
- ```
+///
+
+```Python
+{!> ../../../docs_src/app_testing/app_b_py310/main.py!}
+```
+
+////
+
+//// tab | Python 3.8+ nicht annotiert
+
+/// tip | "Tipp"
+
+Bevorzugen Sie die `Annotated`-Version, falls möglich.
+
+///
+
+```Python
+{!> ../../../docs_src/app_testing/app_b/main.py!}
+```
+
+////
### Erweiterte Testdatei
Weitere Informationen zum Übergeben von Daten an das Backend (mithilfe von `httpx` oder dem `TestClient`) finden Sie in der <a href="https://www.python-httpx.org" class="external-link" target="_blank">HTTPX-Dokumentation</a>.
-!!! info
- Beachten Sie, dass der `TestClient` Daten empfängt, die nach JSON konvertiert werden können, keine Pydantic-Modelle.
+/// info
+
+Beachten Sie, dass der `TestClient` Daten empfängt, die nach JSON konvertiert werden können, keine Pydantic-Modelle.
+
+Wenn Sie ein Pydantic-Modell in Ihrem Test haben und dessen Daten während des Testens an die Anwendung senden möchten, können Sie den `jsonable_encoder` verwenden, der in [JSON-kompatibler Encoder](encoder.md){.internal-link target=_blank} beschrieben wird.
- Wenn Sie ein Pydantic-Modell in Ihrem Test haben und dessen Daten während des Testens an die Anwendung senden möchten, können Sie den `jsonable_encoder` verwenden, der in [JSON-kompatibler Encoder](encoder.md){.internal-link target=_blank} beschrieben wird.
+///
## Tests ausführen
# 🌖 📨 🗄
-!!! warning
- 👉 👍 🏧 ❔.
+/// warning
- 🚥 👆 ▶️ ⏮️ **FastAPI**, 👆 💪 🚫 💪 👉.
+👉 👍 🏧 ❔.
+
+🚥 👆 ▶️ ⏮️ **FastAPI**, 👆 💪 🚫 💪 👉.
+
+///
👆 💪 📣 🌖 📨, ⏮️ 🌖 👔 📟, 🔉 🆎, 📛, ♒️.
{!../../../docs_src/additional_responses/tutorial001.py!}
```
-!!! note
- ✔️ 🤯 👈 👆 ✔️ 📨 `JSONResponse` 🔗.
+/// note
+
+✔️ 🤯 👈 👆 ✔️ 📨 `JSONResponse` 🔗.
+
+///
+
+/// info
-!!! info
- `model` 🔑 🚫 🍕 🗄.
+`model` 🔑 🚫 🍕 🗄.
- **FastAPI** 🔜 ✊ Pydantic 🏷 ⚪️➡️ 📤, 🏗 `JSON Schema`, & 🚮 ⚫️ ☑ 🥉.
+**FastAPI** 🔜 ✊ Pydantic 🏷 ⚪️➡️ 📤, 🏗 `JSON Schema`, & 🚮 ⚫️ ☑ 🥉.
- ☑ 🥉:
+☑ 🥉:
- * 🔑 `content`, 👈 ✔️ 💲 ➕1️⃣ 🎻 🎚 (`dict`) 👈 🔌:
- * 🔑 ⏮️ 📻 🆎, ✅ `application/json`, 👈 🔌 💲 ➕1️⃣ 🎻 🎚, 👈 🔌:
- * 🔑 `schema`, 👈 ✔️ 💲 🎻 🔗 ⚪️➡️ 🏷, 📥 ☑ 🥉.
- * **FastAPI** 🚮 🔗 📥 🌐 🎻 🔗 ➕1️⃣ 🥉 👆 🗄 ↩️ ✅ ⚫️ 🔗. 👉 🌌, 🎏 🈸 & 👩💻 💪 ⚙️ 👈 🎻 🔗 🔗, 🚚 👻 📟 ⚡ 🧰, ♒️.
+* 🔑 `content`, 👈 ✔️ 💲 ➕1️⃣ 🎻 🎚 (`dict`) 👈 🔌:
+ * 🔑 ⏮️ 📻 🆎, ✅ `application/json`, 👈 🔌 💲 ➕1️⃣ 🎻 🎚, 👈 🔌:
+ * 🔑 `schema`, 👈 ✔️ 💲 🎻 🔗 ⚪️➡️ 🏷, 📥 ☑ 🥉.
+ * **FastAPI** 🚮 🔗 📥 🌐 🎻 🔗 ➕1️⃣ 🥉 👆 🗄 ↩️ ✅ ⚫️ 🔗. 👉 🌌, 🎏 🈸 & 👩💻 💪 ⚙️ 👈 🎻 🔗 🔗, 🚚 👻 📟 ⚡ 🧰, ♒️.
+
+///
🏗 📨 🗄 👉 *➡ 🛠️* 🔜:
{!../../../docs_src/additional_responses/tutorial002.py!}
```
-!!! note
- 👀 👈 👆 ✔️ 📨 🖼 ⚙️ `FileResponse` 🔗.
+/// note
+
+👀 👈 👆 ✔️ 📨 🖼 ⚙️ `FileResponse` 🔗.
+
+///
+
+/// info
+
+🚥 👆 ✔ 🎏 📻 🆎 🎯 👆 `responses` 🔢, FastAPI 🔜 🤔 📨 ✔️ 🎏 📻 🆎 👑 📨 🎓 (🔢 `application/json`).
-!!! info
- 🚥 👆 ✔ 🎏 📻 🆎 🎯 👆 `responses` 🔢, FastAPI 🔜 🤔 📨 ✔️ 🎏 📻 🆎 👑 📨 🎓 (🔢 `application/json`).
+✋️ 🚥 👆 ✔️ ✔ 🛃 📨 🎓 ⏮️ `None` 🚮 📻 🆎, FastAPI 🔜 ⚙️ `application/json` 🙆 🌖 📨 👈 ✔️ 👨💼 🏷.
- ✋️ 🚥 👆 ✔️ ✔ 🛃 📨 🎓 ⏮️ `None` 🚮 📻 🆎, FastAPI 🔜 ⚙️ `application/json` 🙆 🌖 📨 👈 ✔️ 👨💼 🏷.
+///
## 🌀 ℹ
{!../../../docs_src/additional_status_codes/tutorial001.py!}
```
-!!! warning
- 🕐❔ 👆 📨 `Response` 🔗, 💖 🖼 🔛, ⚫️ 🔜 📨 🔗.
+/// warning
- ⚫️ 🏆 🚫 🎻 ⏮️ 🏷, ♒️.
+🕐❔ 👆 📨 `Response` 🔗, 💖 🖼 🔛, ⚫️ 🔜 📨 🔗.
- ⚒ 💭 ⚫️ ✔️ 📊 👆 💚 ⚫️ ✔️, & 👈 💲 ☑ 🎻 (🚥 👆 ⚙️ `JSONResponse`).
+⚫️ 🏆 🚫 🎻 ⏮️ 🏷, ♒️.
-!!! note "📡 ℹ"
- 👆 💪 ⚙️ `from starlette.responses import JSONResponse`.
+⚒ 💭 ⚫️ ✔️ 📊 👆 💚 ⚫️ ✔️, & 👈 💲 ☑ 🎻 (🚥 👆 ⚙️ `JSONResponse`).
- **FastAPI** 🚚 🎏 `starlette.responses` `fastapi.responses` 🏪 👆, 👩💻. ✋️ 🌅 💪 📨 👟 🔗 ⚪️➡️ 💃. 🎏 ⏮️ `status`.
+///
+
+/// note | "📡 ℹ"
+
+👆 💪 ⚙️ `from starlette.responses import JSONResponse`.
+
+**FastAPI** 🚚 🎏 `starlette.responses` `fastapi.responses` 🏪 👆, 👩💻. ✋️ 🌅 💪 📨 👟 🔗 ⚪️➡️ 💃. 🎏 ⏮️ `status`.
+
+///
## 🗄 & 🛠️ 🩺
{!../../../docs_src/dependencies/tutorial011.py!}
```
-!!! tip
- 🌐 👉 💪 😑 🎭. & ⚫️ 💪 🚫 📶 🆑 ❔ ⚫️ ⚠.
+/// tip
- 👫 🖼 😫 🙅, ✋️ 🎦 ❔ ⚫️ 🌐 👷.
+🌐 👉 💪 😑 🎭. & ⚫️ 💪 🚫 📶 🆑 ❔ ⚫️ ⚠.
- 📃 🔃 💂♂, 📤 🚙 🔢 👈 🛠️ 👉 🎏 🌌.
+👫 🖼 😫 🙅, ✋️ 🎦 ❔ ⚫️ 🌐 👷.
- 🚥 👆 🤔 🌐 👉, 👆 ⏪ 💭 ❔ 👈 🚙 🧰 💂♂ 👷 🔘.
+📃 🔃 💂♂, 📤 🚙 🔢 👈 🛠️ 👉 🎏 🌌.
+
+🚥 👆 🤔 🌐 👉, 👆 ⏪ 💭 ❔ 👈 🚙 🧰 💂♂ 👷 🔘.
+
+///
{!../../../docs_src/async_tests/test_main.py!}
```
-!!! tip
- 🗒 👈 💯 🔢 🔜 `async def` ↩️ `def` ⏭ 🕐❔ ⚙️ `TestClient`.
+/// tip
+
+🗒 👈 💯 🔢 🔜 `async def` ↩️ `def` ⏭ 🕐❔ ⚙️ `TestClient`.
+
+///
⤴️ 👥 💪 ✍ `AsyncClient` ⏮️ 📱, & 📨 🔁 📨 ⚫️, ⚙️ `await`.
...👈 👥 ⚙️ ⚒ 👆 📨 ⏮️ `TestClient`.
-!!! tip
- 🗒 👈 👥 ⚙️ 🔁/⌛ ⏮️ 🆕 `AsyncClient` - 📨 🔁.
+/// tip
+
+🗒 👈 👥 ⚙️ 🔁/⌛ ⏮️ 🆕 `AsyncClient` - 📨 🔁.
+
+///
## 🎏 🔁 🔢 🤙
🔬 🔢 🔜 🔁, 👆 💪 🔜 🤙 (& `await`) 🎏 `async` 🔢 ↖️ ⚪️➡️ 📨 📨 👆 FastAPI 🈸 👆 💯, ⚫️❔ 👆 🔜 🤙 👫 🙆 🙆 👆 📟.
-!!! tip
- 🚥 👆 ⚔ `RuntimeError: Task attached to a different loop` 🕐❔ 🛠️ 🔁 🔢 🤙 👆 💯 (✅ 🕐❔ ⚙️ <a href="https://stackoverflow.com/questions/41584243/runtimeerror-task-attached-to-a-different-loop" class="external-link" target="_blank">✳ MotorClient</a>) 💭 🔗 🎚 👈 💪 🎉 ➰ 🕴 🏞 🔁 🔢, ✅ `'@app.on_event("startup")` ⏲.
+/// tip
+
+🚥 👆 ⚔ `RuntimeError: Task attached to a different loop` 🕐❔ 🛠️ 🔁 🔢 🤙 👆 💯 (✅ 🕐❔ ⚙️ <a href="https://stackoverflow.com/questions/41584243/runtimeerror-task-attached-to-a-different-loop" class="external-link" target="_blank">✳ MotorClient</a>) 💭 🔗 🎚 👈 💪 🎉 ➰ 🕴 🏞 🔁 🔢, ✅ `'@app.on_event("startup")` ⏲.
+
+///
proxy --> server
```
-!!! tip
- 📢 `0.0.0.0` 🛎 ⚙️ ⛓ 👈 📋 👂 🔛 🌐 📢 💪 👈 🎰/💽.
+/// tip
+
+📢 `0.0.0.0` 🛎 ⚙️ ⛓ 👈 📋 👂 🔛 🌐 📢 💪 👈 🎰/💽.
+
+///
🩺 🎚 🔜 💪 🗄 🔗 📣 👈 👉 🛠️ `server` 🔎 `/api/v1` (⛅ 🗳). 🖼:
🚥 👆 ⚙️ Hypercorn, ⚫️ ✔️ 🎛 `--root-path`.
-!!! note "📡 ℹ"
- 🔫 🔧 🔬 `root_path` 👉 ⚙️ 💼.
+/// note | "📡 ℹ"
+
+🔫 🔧 🔬 `root_path` 👉 ⚙️ 💼.
+
+ & `--root-path` 📋 ⏸ 🎛 🚚 👈 `root_path`.
- & `--root-path` 📋 ⏸ 🎛 🚚 👈 `root_path`.
+///
### ✅ ⏮️ `root_path`
👉 💬 Traefik 👂 🔛 ⛴ 9️⃣9️⃣9️⃣9️⃣ & ⚙️ ➕1️⃣ 📁 `routes.toml`.
-!!! tip
- 👥 ⚙️ ⛴ 9️⃣9️⃣9️⃣9️⃣ ↩️ 🐩 🇺🇸🔍 ⛴ 8️⃣0️⃣ 👈 👆 🚫 ✔️ 🏃 ⚫️ ⏮️ 📡 (`sudo`) 😌.
+/// tip
+
+👥 ⚙️ ⛴ 9️⃣9️⃣9️⃣9️⃣ ↩️ 🐩 🇺🇸🔍 ⛴ 8️⃣0️⃣ 👈 👆 🚫 ✔️ 🏃 ⚫️ ⏮️ 📡 (`sudo`) 😌.
+
+///
🔜 ✍ 👈 🎏 📁 `routes.toml`:
}
```
-!!! tip
- 👀 👈 ✋️ 👆 🔐 ⚫️ `http://127.0.0.1:8000/app` ⚫️ 🎦 `root_path` `/api/v1`, ✊ ⚪️➡️ 🎛 `--root-path`.
+/// tip
+
+👀 👈 ✋️ 👆 🔐 ⚫️ `http://127.0.0.1:8000/app` ⚫️ 🎦 `root_path` `/api/v1`, ✊ ⚪️➡️ 🎛 `--root-path`.
+
+///
& 🔜 📂 📛 ⏮️ ⛴ Traefik, ✅ ➡ 🔡: <a href="http://127.0.0.1:9999/api/v1/app" class="external-link" target="_blank">http://127.0.0.1:9999/api/v1/app</a>.
## 🌖 💽
-!!! warning
- 👉 🌅 🏧 ⚙️ 💼. 💭 🆓 🚶 ⚫️.
+/// warning
+
+👉 🌅 🏧 ⚙️ 💼. 💭 🆓 🚶 ⚫️.
+
+///
🔢, **FastAPI** 🔜 ✍ `server` 🗄 🔗 ⏮️ 📛 `root_path`.
}
```
-!!! tip
- 👀 🚘-🏗 💽 ⏮️ `url` 💲 `/api/v1`, ✊ ⚪️➡️ `root_path`.
+/// tip
+
+👀 🚘-🏗 💽 ⏮️ `url` 💲 `/api/v1`, ✊ ⚪️➡️ `root_path`.
+
+///
🩺 🎚 <a href="http://127.0.0.1:9999/api/v1/docs" class="external-link" target="_blank">http://127.0.0.1:9999/api/v1/docs</a> ⚫️ 🔜 👀 💖:
<img src="/img/tutorial/behind-a-proxy/image03.png">
-!!! tip
- 🩺 🎚 🔜 🔗 ⏮️ 💽 👈 👆 🖊.
+/// tip
+
+🩺 🎚 🔜 🔗 ⏮️ 💽 👈 👆 🖊.
+
+///
### ❎ 🏧 💽 ⚪️➡️ `root_path`
& 🚥 👈 `Response` ✔️ 🎻 📻 🆎 (`application/json`), 💖 💼 ⏮️ `JSONResponse` & `UJSONResponse`, 💽 👆 📨 🔜 🔁 🗜 (& ⛽) ⏮️ 🙆 Pydantic `response_model` 👈 👆 📣 *➡ 🛠️ 👨🎨*.
-!!! note
- 🚥 👆 ⚙️ 📨 🎓 ⏮️ 🙅♂ 📻 🆎, FastAPI 🔜 ⌛ 👆 📨 ✔️ 🙅♂ 🎚, ⚫️ 🔜 🚫 📄 📨 📁 🚮 🏗 🗄 🩺.
+/// note
+
+🚥 👆 ⚙️ 📨 🎓 ⏮️ 🙅♂ 📻 🆎, FastAPI 🔜 ⌛ 👆 📨 ✔️ 🙅♂ 🎚, ⚫️ 🔜 🚫 📄 📨 📁 🚮 🏗 🗄 🩺.
+
+///
## ⚙️ `ORJSONResponse`
{!../../../docs_src/custom_response/tutorial001b.py!}
```
-!!! info
- 🔢 `response_class` 🔜 ⚙️ 🔬 "📻 🆎" 📨.
+/// info
+
+🔢 `response_class` 🔜 ⚙️ 🔬 "📻 🆎" 📨.
+
+👉 💼, 🇺🇸🔍 🎚 `Content-Type` 🔜 ⚒ `application/json`.
+
+ & ⚫️ 🔜 📄 ✅ 🗄.
+
+///
- 👉 💼, 🇺🇸🔍 🎚 `Content-Type` 🔜 ⚒ `application/json`.
+/// tip
- & ⚫️ 🔜 📄 ✅ 🗄.
+`ORJSONResponse` ⏳ 🕴 💪 FastAPI, 🚫 💃.
-!!! tip
- `ORJSONResponse` ⏳ 🕴 💪 FastAPI, 🚫 💃.
+///
## 🕸 📨
{!../../../docs_src/custom_response/tutorial002.py!}
```
-!!! info
- 🔢 `response_class` 🔜 ⚙️ 🔬 "📻 🆎" 📨.
+/// info
- 👉 💼, 🇺🇸🔍 🎚 `Content-Type` 🔜 ⚒ `text/html`.
+🔢 `response_class` 🔜 ⚙️ 🔬 "📻 🆎" 📨.
- & ⚫️ 🔜 📄 ✅ 🗄.
+👉 💼, 🇺🇸🔍 🎚 `Content-Type` 🔜 ⚒ `text/html`.
+
+ & ⚫️ 🔜 📄 ✅ 🗄.
+
+///
### 📨 `Response`
{!../../../docs_src/custom_response/tutorial003.py!}
```
-!!! warning
- `Response` 📨 🔗 👆 *➡ 🛠️ 🔢* 🏆 🚫 📄 🗄 (🖼, `Content-Type` 🏆 🚫 📄) & 🏆 🚫 ⭐ 🏧 🎓 🩺.
+/// warning
+
+`Response` 📨 🔗 👆 *➡ 🛠️ 🔢* 🏆 🚫 📄 🗄 (🖼, `Content-Type` 🏆 🚫 📄) & 🏆 🚫 ⭐ 🏧 🎓 🩺.
+
+///
+
+/// info
-!!! info
- ↗️, ☑ `Content-Type` 🎚, 👔 📟, ♒️, 🔜 👟 ⚪️➡️ `Response` 🎚 👆 📨.
+↗️, ☑ `Content-Type` 🎚, 👔 📟, ♒️, 🔜 👟 ⚪️➡️ `Response` 🎚 👆 📨.
+
+///
### 📄 🗄 & 🔐 `Response`
✔️ 🤯 👈 👆 💪 ⚙️ `Response` 📨 🕳 🙆, ⚖️ ✍ 🛃 🎧-🎓.
-!!! note "📡 ℹ"
- 👆 💪 ⚙️ `from starlette.responses import HTMLResponse`.
+/// note | "📡 ℹ"
+
+👆 💪 ⚙️ `from starlette.responses import HTMLResponse`.
+
+**FastAPI** 🚚 🎏 `starlette.responses` `fastapi.responses` 🏪 👆, 👩💻. ✋️ 🌅 💪 📨 👟 🔗 ⚪️➡️ 💃.
- **FastAPI** 🚚 🎏 `starlette.responses` `fastapi.responses` 🏪 👆, 👩💻. ✋️ 🌅 💪 📨 👟 🔗 ⚪️➡️ 💃.
+///
### `Response`
🎛 🎻 📨 ⚙️ <a href="https://github.com/ultrajson/ultrajson" class="external-link" target="_blank">`ujson`</a>.
-!!! warning
- `ujson` 🌘 💛 🌘 🐍 🏗-🛠️ ❔ ⚫️ 🍵 📐-💼.
+/// warning
+
+`ujson` 🌘 💛 🌘 🐍 🏗-🛠️ ❔ ⚫️ 🍵 📐-💼.
+
+///
```Python hl_lines="2 7"
{!../../../docs_src/custom_response/tutorial001.py!}
```
-!!! tip
- ⚫️ 💪 👈 `ORJSONResponse` 💪 ⏩ 🎛.
+/// tip
+
+⚫️ 💪 👈 `ORJSONResponse` 💪 ⏩ 🎛.
+
+///
### `RedirectResponse`
🔨 ⚫️ 👉 🌌, 👥 💪 🚮 ⚫️ `with` 🍫, & 👈 🌌, 🚚 👈 ⚫️ 📪 ⏮️ 🏁.
-!!! tip
- 👀 👈 📥 👥 ⚙️ 🐩 `open()` 👈 🚫 🐕🦺 `async` & `await`, 👥 📣 ➡ 🛠️ ⏮️ 😐 `def`.
+/// tip
+
+👀 👈 📥 👥 ⚙️ 🐩 `open()` 👈 🚫 🐕🦺 `async` & `await`, 👥 📣 ➡ 🛠️ ⏮️ 😐 `def`.
+
+///
### `FileResponse`
{!../../../docs_src/custom_response/tutorial010.py!}
```
-!!! tip
- 👆 💪 🔐 `response_class` *➡ 🛠️* ⏭.
+/// tip
+
+👆 💪 🔐 `response_class` *➡ 🛠️* ⏭.
+
+///
## 🌖 🧾
👉 👷 🎏 🌌 ⏮️ Pydantic 🏷. & ⚫️ 🤙 🏆 🎏 🌌 🔘, ⚙️ Pydantic.
-!!! info
- ✔️ 🤯 👈 🎻 💪 🚫 🌐 Pydantic 🏷 💪.
+/// info
- , 👆 5️⃣📆 💪 ⚙️ Pydantic 🏷.
+✔️ 🤯 👈 🎻 💪 🚫 🌐 Pydantic 🏷 💪.
- ✋️ 🚥 👆 ✔️ 📚 🎻 🤥 🤭, 👉 👌 🎱 ⚙️ 👫 🏋️ 🕸 🛠️ ⚙️ FastAPI. 👶
+, 👆 5️⃣📆 💪 ⚙️ Pydantic 🏷.
+
+✋️ 🚥 👆 ✔️ 📚 🎻 🤥 🤭, 👉 👌 🎱 ⚙️ 👫 🏋️ 🕸 🛠️ ⚙️ FastAPI. 👶
+
+///
## 🎻 `response_model`
& ⤴️, ▶️️ ⏮️ `yield`, 👥 🚚 🏷. 👉 📟 🔜 🛠️ **⏮️** 🈸 **🏁 🚚 📨**, ▶️️ ⏭ *🤫*. 👉 💪, 🖼, 🚀 ℹ 💖 💾 ⚖️ 💻.
-!!! tip
- `shutdown` 🔜 🔨 🕐❔ 👆 **⛔️** 🈸.
+/// tip
- 🎲 👆 💪 ▶️ 🆕 ⏬, ⚖️ 👆 🤚 🎡 🏃 ⚫️. 🤷
+`shutdown` 🔜 🔨 🕐❔ 👆 **⛔️** 🈸.
+
+🎲 👆 💪 ▶️ 🆕 ⏬, ⚖️ 👆 🤚 🎡 🏃 ⚫️. 🤷
+
+///
### 🔆 🔢
## 🎛 🎉 (😢)
-!!! warning
- 👍 🌌 🍵 *🕴* & *🤫* ⚙️ `lifespan` 🔢 `FastAPI` 📱 🔬 🔛.
+/// warning
+
+👍 🌌 🍵 *🕴* & *🤫* ⚙️ `lifespan` 🔢 `FastAPI` 📱 🔬 🔛.
- 👆 💪 🎲 🚶 👉 🍕.
+👆 💪 🎲 🚶 👉 🍕.
+
+///
📤 🎛 🌌 🔬 👉 ⚛ 🛠️ ⏮️ *🕴* & ⏮️ *🤫*.
📥, `shutdown` 🎉 🐕🦺 🔢 🔜 ✍ ✍ ⏸ `"Application shutdown"` 📁 `log.txt`.
-!!! info
- `open()` 🔢, `mode="a"` ⛓ "🎻",, ⏸ 🔜 🚮 ⏮️ ⚫️❔ 🔛 👈 📁, 🍵 📁 ⏮️ 🎚.
+/// info
+
+`open()` 🔢, `mode="a"` ⛓ "🎻",, ⏸ 🔜 🚮 ⏮️ ⚫️❔ 🔛 👈 📁, 🍵 📁 ⏮️ 🎚.
+
+///
+
+/// tip
+
+👀 👈 👉 💼 👥 ⚙️ 🐩 🐍 `open()` 🔢 👈 🔗 ⏮️ 📁.
+
+, ⚫️ 🔌 👤/🅾 (🔢/🔢), 👈 🚚 "⌛" 👜 ✍ 💾.
+
+✋️ `open()` 🚫 ⚙️ `async` & `await`.
-!!! tip
- 👀 👈 👉 💼 👥 ⚙️ 🐩 🐍 `open()` 🔢 👈 🔗 ⏮️ 📁.
+, 👥 📣 🎉 🐕🦺 🔢 ⏮️ 🐩 `def` ↩️ `async def`.
- , ⚫️ 🔌 👤/🅾 (🔢/🔢), 👈 🚚 "⌛" 👜 ✍ 💾.
+///
- ✋️ `open()` 🚫 ⚙️ `async` & `await`.
+/// info
- , 👥 📣 🎉 🐕🦺 🔢 ⏮️ 🐩 `def` ↩️ `async def`.
+👆 💪 ✍ 🌅 🔃 👫 🎉 🐕🦺 <a href="https://www.starlette.io/events/" class="external-link" target="_blank">💃 🎉' 🩺</a>.
-!!! info
- 👆 💪 ✍ 🌅 🔃 👫 🎉 🐕🦺 <a href="https://www.starlette.io/events/" class="external-link" target="_blank">💃 🎉' 🩺</a>.
+///
### `startup` & `shutdown` 👯♂️
➡️ ▶️ ⏮️ 🙅 FastAPI 🈸:
-=== "🐍 3️⃣.6️⃣ & 🔛"
+//// tab | 🐍 3️⃣.6️⃣ & 🔛
- ```Python hl_lines="9-11 14-15 18 19 23"
- {!> ../../../docs_src/generate_clients/tutorial001.py!}
- ```
+```Python hl_lines="9-11 14-15 18 19 23"
+{!> ../../../docs_src/generate_clients/tutorial001.py!}
+```
+
+////
-=== "🐍 3️⃣.9️⃣ & 🔛"
+//// tab | 🐍 3️⃣.9️⃣ & 🔛
+
+```Python hl_lines="7-9 12-13 16-17 21"
+{!> ../../../docs_src/generate_clients/tutorial001_py39.py!}
+```
- ```Python hl_lines="7-9 12-13 16-17 21"
- {!> ../../../docs_src/generate_clients/tutorial001_py39.py!}
- ```
+////
👀 👈 *➡ 🛠️* 🔬 🏷 👫 ⚙️ 📨 🚀 & 📨 🚀, ⚙️ 🏷 `Item` & `ResponseMessage`.
<img src="/img/tutorial/generate-clients/image03.png">
-!!! tip
- 👀 ✍ `name` & `price`, 👈 🔬 FastAPI 🈸, `Item` 🏷.
+/// tip
+
+👀 ✍ `name` & `price`, 👈 🔬 FastAPI 🈸, `Item` 🏷.
+
+///
👆 🔜 ✔️ ⏸ ❌ 📊 👈 👆 📨:
🖼, 👆 💪 ✔️ 📄 **🏬** & ➕1️⃣ 📄 **👩💻**, & 👫 💪 👽 🔖:
-=== "🐍 3️⃣.6️⃣ & 🔛"
+//// tab | 🐍 3️⃣.6️⃣ & 🔛
+
+```Python hl_lines="23 28 36"
+{!> ../../../docs_src/generate_clients/tutorial002.py!}
+```
+
+////
- ```Python hl_lines="23 28 36"
- {!> ../../../docs_src/generate_clients/tutorial002.py!}
- ```
+//// tab | 🐍 3️⃣.9️⃣ & 🔛
-=== "🐍 3️⃣.9️⃣ & 🔛"
+```Python hl_lines="21 26 34"
+{!> ../../../docs_src/generate_clients/tutorial002_py39.py!}
+```
- ```Python hl_lines="21 26 34"
- {!> ../../../docs_src/generate_clients/tutorial002_py39.py!}
- ```
+////
### 🏗 📕 👩💻 ⏮️ 🔖
👆 💪 ⤴️ 🚶♀️ 👈 🛃 🔢 **FastAPI** `generate_unique_id_function` 🔢:
-=== "🐍 3️⃣.6️⃣ & 🔛"
+//// tab | 🐍 3️⃣.6️⃣ & 🔛
- ```Python hl_lines="8-9 12"
- {!> ../../../docs_src/generate_clients/tutorial003.py!}
- ```
+```Python hl_lines="8-9 12"
+{!> ../../../docs_src/generate_clients/tutorial003.py!}
+```
-=== "🐍 3️⃣.9️⃣ & 🔛"
+////
+
+//// tab | 🐍 3️⃣.9️⃣ & 🔛
+
+```Python hl_lines="6-7 10"
+{!> ../../../docs_src/generate_clients/tutorial003_py39.py!}
+```
- ```Python hl_lines="6-7 10"
- {!> ../../../docs_src/generate_clients/tutorial003_py39.py!}
- ```
+////
### 🏗 📕 👩💻 ⏮️ 🛃 🛠️ 🆔
⏭ 📄 👆 🔜 👀 🎏 🎛, 📳, & 🌖 ⚒.
-!!! tip
- ⏭ 📄 **🚫 🎯 "🏧"**.
+/// tip
- & ⚫️ 💪 👈 👆 ⚙️ 💼, ⚗ 1️⃣ 👫.
+⏭ 📄 **🚫 🎯 "🏧"**.
+
+ & ⚫️ 💪 👈 👆 ⚙️ 💼, ⚗ 1️⃣ 👫.
+
+///
## ✍ 🔰 🥇
**FastAPI** 🔌 📚 🛠️ ⚠ ⚙️ 💼, 👥 🔜 👀 ⏭ ❔ ⚙️ 👫.
-!!! note "📡 ℹ"
- ⏭ 🖼, 👆 💪 ⚙️ `from starlette.middleware.something import SomethingMiddleware`.
+/// note | "📡 ℹ"
- **FastAPI** 🚚 📚 🛠️ `fastapi.middleware` 🏪 👆, 👩💻. ✋️ 🌅 💪 🛠️ 👟 🔗 ⚪️➡️ 💃.
+⏭ 🖼, 👆 💪 ⚙️ `from starlette.middleware.something import SomethingMiddleware`.
+
+**FastAPI** 🚚 📚 🛠️ `fastapi.middleware` 🏪 👆, 👩💻. ✋️ 🌅 💪 🛠️ 👟 🔗 ⚪️➡️ 💃.
+
+///
## `HTTPSRedirectMiddleware`
{!../../../docs_src/openapi_callbacks/tutorial001.py!}
```
-!!! tip
- `callback_url` 🔢 🔢 ⚙️ Pydantic <a href="https://docs.pydantic.dev/latest/concepts/types/#urls" class="external-link" target="_blank">📛</a> 🆎.
+/// tip
+
+`callback_url` 🔢 🔢 ⚙️ Pydantic <a href="https://docs.pydantic.dev/latest/concepts/types/#urls" class="external-link" target="_blank">📛</a> 🆎.
+
+///
🕴 🆕 👜 `callbacks=messages_callback_router.routes` ❌ *➡ 🛠️ 👨🎨*. 👥 🔜 👀 ⚫️❔ 👈 ⏭.
👉 🖼 🚫 🛠️ ⏲ ⚫️ (👈 💪 ⏸ 📟), 🕴 🧾 🍕.
-!!! tip
- ☑ ⏲ 🇺🇸🔍 📨.
+/// tip
+
+☑ ⏲ 🇺🇸🔍 📨.
- 🕐❔ 🛠️ ⏲ 👆, 👆 💪 ⚙️ 🕳 💖 <a href="https://www.python-httpx.org" class="external-link" target="_blank">🇸🇲</a> ⚖️ <a href="https://requests.readthedocs.io/" class="external-link" target="_blank">📨</a>.
+🕐❔ 🛠️ ⏲ 👆, 👆 💪 ⚙️ 🕳 💖 <a href="https://www.python-httpx.org" class="external-link" target="_blank">🇸🇲</a> ⚖️ <a href="https://requests.readthedocs.io/" class="external-link" target="_blank">📨</a>.
+
+///
## ✍ ⏲ 🧾 📟
👥 🔜 ⚙️ 👈 🎏 💡 📄 ❔ *🔢 🛠️* 🔜 👀 💖... 🏗 *➡ 🛠️(Ⓜ)* 👈 🔢 🛠️ 🔜 🛠️ (🕐 👆 🛠️ 🔜 🤙).
-!!! tip
- 🕐❔ ✍ 📟 📄 ⏲, ⚫️ 💪 ⚠ 🌈 👈 👆 👈 *🔢 👩💻*. & 👈 👆 ⏳ 🛠️ *🔢 🛠️*, 🚫 *👆 🛠️*.
+/// tip
+
+🕐❔ ✍ 📟 📄 ⏲, ⚫️ 💪 ⚠ 🌈 👈 👆 👈 *🔢 👩💻*. & 👈 👆 ⏳ 🛠️ *🔢 🛠️*, 🚫 *👆 🛠️*.
- 🍕 🛠️ 👉 ☝ 🎑 ( *🔢 👩💻*) 💪 ℹ 👆 💭 💖 ⚫️ 🌅 ⭐ 🌐❔ 🚮 🔢, Pydantic 🏷 💪, 📨, ♒️. 👈 *🔢 🛠️*.
+🍕 🛠️ 👉 ☝ 🎑 ( *🔢 👩💻*) 💪 ℹ 👆 💭 💖 ⚫️ 🌅 ⭐ 🌐❔ 🚮 🔢, Pydantic 🏷 💪, 📨, ♒️. 👈 *🔢 🛠️*.
+
+///
### ✍ ⏲ `APIRouter`
}
```
-!!! tip
- 👀 ❔ ⏲ 📛 ⚙️ 🔌 📛 📨 🔢 🔢 `callback_url` (`https://www.external.org/events`) & 🧾 `id` ⚪️➡️ 🔘 🎻 💪 (`2expen51ve`).
+/// tip
+
+👀 ❔ ⏲ 📛 ⚙️ 🔌 📛 📨 🔢 🔢 `callback_url` (`https://www.external.org/events`) & 🧾 `id` ⚪️➡️ 🔘 🎻 💪 (`2expen51ve`).
+
+///
### 🚮 ⏲ 📻
{!../../../docs_src/openapi_callbacks/tutorial001.py!}
```
-!!! tip
- 👀 👈 👆 🚫 🚶♀️ 📻 ⚫️ (`invoices_callback_router`) `callback=`, ✋️ 🔢 `.routes`, `invoices_callback_router.routes`.
+/// tip
+
+👀 👈 👆 🚫 🚶♀️ 📻 ⚫️ (`invoices_callback_router`) `callback=`, ✋️ 🔢 `.routes`, `invoices_callback_router.routes`.
+
+///
### ✅ 🩺
## 🗄 {
-!!! warning
- 🚥 👆 🚫 "🕴" 🗄, 👆 🎲 🚫 💪 👉.
+/// warning
+
+🚥 👆 🚫 "🕴" 🗄, 👆 🎲 🚫 💪 👉.
+
+///
👆 💪 ⚒ 🗄 `operationId` ⚙️ 👆 *➡ 🛠️* ⏮️ 🔢 `operation_id`.
{!../../../docs_src/path_operation_advanced_configuration/tutorial002.py!}
```
-!!! tip
- 🚥 👆 ❎ 🤙 `app.openapi()`, 👆 🔜 ℹ `operationId`Ⓜ ⏭ 👈.
+/// tip
+
+🚥 👆 ❎ 🤙 `app.openapi()`, 👆 🔜 ℹ `operationId`Ⓜ ⏭ 👈.
+
+///
+
+/// warning
+
+🚥 👆 👉, 👆 ✔️ ⚒ 💭 🔠 1️⃣ 👆 *➡ 🛠️ 🔢* ✔️ 😍 📛.
-!!! warning
- 🚥 👆 👉, 👆 ✔️ ⚒ 💭 🔠 1️⃣ 👆 *➡ 🛠️ 🔢* ✔️ 😍 📛.
+🚥 👫 🎏 🕹 (🐍 📁).
- 🚥 👫 🎏 🕹 (🐍 📁).
+///
## 🚫 ⚪️➡️ 🗄
🕐❔ 👆 📣 *➡ 🛠️* 👆 🈸, **FastAPI** 🔁 🏗 🔗 🗃 🔃 👈 *➡ 🛠️* 🔌 🗄 🔗.
-!!! note "📡 ℹ"
- 🗄 🔧 ⚫️ 🤙 <a href="https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.3.md#operation-object" class="external-link" target="_blank">🛠️ 🎚</a>.
+/// note | "📡 ℹ"
+
+🗄 🔧 ⚫️ 🤙 <a href="https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.3.md#operation-object" class="external-link" target="_blank">🛠️ 🎚</a>.
+
+///
⚫️ ✔️ 🌐 ℹ 🔃 *➡ 🛠️* & ⚙️ 🏗 🏧 🧾.
👉 *➡ 🛠️*-🎯 🗄 🔗 🛎 🏗 🔁 **FastAPI**, ✋️ 👆 💪 ↔ ⚫️.
-!!! tip
- 👉 🔅 🎚 ↔ ☝.
+/// tip
+
+👉 🔅 🎚 ↔ ☝.
- 🚥 👆 🕴 💪 📣 🌖 📨, 🌅 🏪 🌌 ⚫️ ⏮️ [🌖 📨 🗄](additional-responses.md){.internal-link target=_blank}.
+🚥 👆 🕴 💪 📣 🌖 📨, 🌅 🏪 🌌 ⚫️ ⏮️ [🌖 📨 🗄](additional-responses.md){.internal-link target=_blank}.
+
+///
👆 💪 ↔ 🗄 🔗 *➡ 🛠️* ⚙️ 🔢 `openapi_extra`.
{!../../../docs_src/path_operation_advanced_configuration/tutorial007.py!}
```
-!!! tip
- 📥 👥 🏤-⚙️ 🎏 Pydantic 🏷.
+/// tip
+
+📥 👥 🏤-⚙️ 🎏 Pydantic 🏷.
+
+✋️ 🎏 🌌, 👥 💪 ✔️ ✔ ⚫️ 🎏 🌌.
- ✋️ 🎏 🌌, 👥 💪 ✔️ ✔ ⚫️ 🎏 🌌.
+///
{!../../../docs_src/response_cookies/tutorial001.py!}
```
-!!! 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`.
+///
👀 🌐 💪 🔢 & 🎛, ✅ <a href="https://www.starlette.io/responses/#set-cookie" class="external-link" target="_blank">🧾 💃</a>.
👐, 👆 💪 📨 🙆 `Response` ⚖️ 🙆 🎧-🎓 ⚫️.
-!!! tip
- `JSONResponse` ⚫️ 🎧-🎓 `Response`.
+/// tip
+
+`JSONResponse` ⚫️ 🎧-🎓 `Response`.
+
+///
& 🕐❔ 👆 📨 `Response`, **FastAPI** 🔜 🚶♀️ ⚫️ 🔗.
{!../../../docs_src/response_directly/tutorial001.py!}
```
-!!! note "📡 ℹ"
- 👆 💪 ⚙️ `from starlette.responses import JSONResponse`.
+/// note | "📡 ℹ"
+
+👆 💪 ⚙️ `from starlette.responses import JSONResponse`.
+
+**FastAPI** 🚚 🎏 `starlette.responses` `fastapi.responses` 🏪 👆, 👩💻. ✋️ 🌅 💪 📨 👟 🔗 ⚪️➡️ 💃.
- **FastAPI** 🚚 🎏 `starlette.responses` `fastapi.responses` 🏪 👆, 👩💻. ✋️ 🌅 💪 📨 👟 🔗 ⚪️➡️ 💃.
+///
## 🛬 🛃 `Response`
{!../../../docs_src/response_headers/tutorial001.py!}
```
-!!! 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`.
+
+///
## 🛃 🎚
📤 ➕ ⚒ 🍵 💂♂ ↖️ ⚪️➡️ 🕐 📔 [🔰 - 👩💻 🦮: 💂♂](../../tutorial/security/index.md){.internal-link target=_blank}.
-!!! tip
- ⏭ 📄 **🚫 🎯 "🏧"**.
+/// tip
- & ⚫️ 💪 👈 👆 ⚙️ 💼, ⚗ 1️⃣ 👫.
+⏭ 📄 **🚫 🎯 "🏧"**.
+
+ & ⚫️ 💪 👈 👆 ⚙️ 💼, ⚗ 1️⃣ 👫.
+
+///
## ✍ 🔰 🥇
👉 📄 👆 🔜 👀 ❔ 🛠️ 🤝 & ✔ ⏮️ 🎏 Oauth2️⃣ ⏮️ ↔ 👆 **FastAPI** 🈸.
-!!! warning
- 👉 🌅 ⚖️ 🌘 🏧 📄. 🚥 👆 ▶️, 👆 💪 🚶 ⚫️.
+/// warning
- 👆 🚫 🎯 💪 Oauth2️⃣ ↔, & 👆 💪 🍵 🤝 & ✔ 👐 👆 💚.
+👉 🌅 ⚖️ 🌘 🏧 📄. 🚥 👆 ▶️, 👆 💪 🚶 ⚫️.
- ✋️ Oauth2️⃣ ⏮️ ↔ 💪 🎆 🛠️ 🔘 👆 🛠️ (⏮️ 🗄) & 👆 🛠️ 🩺.
+👆 🚫 🎯 💪 Oauth2️⃣ ↔, & 👆 💪 🍵 🤝 & ✔ 👐 👆 💚.
- 👐, 👆 🛠️ 📚 ↔, ⚖️ 🙆 🎏 💂♂/✔ 📄, 👐 👆 💪, 👆 📟.
+✋️ Oauth2️⃣ ⏮️ ↔ 💪 🎆 🛠️ 🔘 👆 🛠️ (⏮️ 🗄) & 👆 🛠️ 🩺.
- 📚 💼, Oauth2️⃣ ⏮️ ↔ 💪 👹.
+👐, 👆 🛠️ 📚 ↔, ⚖️ 🙆 🎏 💂♂/✔ 📄, 👐 👆 💪, 👆 📟.
- ✋️ 🚥 👆 💭 👆 💪 ⚫️, ⚖️ 👆 😟, 🚧 👂.
+📚 💼, Oauth2️⃣ ⏮️ ↔ 💪 👹.
+
+✋️ 🚥 👆 💭 👆 💪 ⚫️, ⚖️ 👆 😟, 🚧 👂.
+
+///
## Oauth2️⃣ ↔ & 🗄
* `instagram_basic` ⚙️ 👱📔 / 👱📔.
* `https://www.googleapis.com/auth/drive` ⚙️ 🇺🇸🔍.
-!!! info
- Oauth2️⃣ "↔" 🎻 👈 📣 🎯 ✔ ✔.
+/// info
+
+Oauth2️⃣ "↔" 🎻 👈 📣 🎯 ✔ ✔.
+
+⚫️ 🚫 🤔 🚥 ⚫️ ✔️ 🎏 🦹 💖 `:` ⚖️ 🚥 ⚫️ 📛.
- ⚫️ 🚫 🤔 🚥 ⚫️ ✔️ 🎏 🦹 💖 `:` ⚖️ 🚥 ⚫️ 📛.
+👈 ℹ 🛠️ 🎯.
- 👈 ℹ 🛠️ 🎯.
+Oauth2️⃣ 👫 🎻.
- Oauth2️⃣ 👫 🎻.
+///
## 🌐 🎑
& 👥 📨 ↔ 🍕 🥙 🤝.
-!!! danger
- 🦁, 📥 👥 ❎ ↔ 📨 🔗 🤝.
+/// danger
- ✋️ 👆 🈸, 💂♂, 👆 🔜 ⚒ 💭 👆 🕴 🚮 ↔ 👈 👩💻 🤙 💪 ✔️, ⚖️ 🕐 👆 ✔️ 🔁.
+🦁, 📥 👥 ❎ ↔ 📨 🔗 🤝.
+
+✋️ 👆 🈸, 💂♂, 👆 🔜 ⚒ 💭 👆 🕴 🚮 ↔ 👈 👩💻 🤙 💪 ✔️, ⚖️ 🕐 👆 ✔️ 🔁.
+
+///
```Python hl_lines="155"
{!../../../docs_src/security/tutorial005.py!}
👉 💼, ⚫️ 🚚 ↔ `me` (⚫️ 💪 🚚 🌅 🌘 1️⃣ ↔).
-!!! note
- 👆 🚫 🎯 💪 🚮 🎏 ↔ 🎏 🥉.
+/// note
+
+👆 🚫 🎯 💪 🚮 🎏 ↔ 🎏 🥉.
- 👥 🔨 ⚫️ 📥 🎦 ❔ **FastAPI** 🍵 ↔ 📣 🎏 🎚.
+👥 🔨 ⚫️ 📥 🎦 ❔ **FastAPI** 🍵 ↔ 📣 🎏 🎚.
+
+///
```Python hl_lines="4 139 168"
{!../../../docs_src/security/tutorial005.py!}
```
-!!! info "📡 ℹ"
- `Security` 🤙 🏿 `Depends`, & ⚫️ ✔️ 1️⃣ ➕ 🔢 👈 👥 🔜 👀 ⏪.
+/// info | "📡 ℹ"
+
+`Security` 🤙 🏿 `Depends`, & ⚫️ ✔️ 1️⃣ ➕ 🔢 👈 👥 🔜 👀 ⏪.
- ✋️ ⚙️ `Security` ↩️ `Depends`, **FastAPI** 🔜 💭 👈 ⚫️ 💪 📣 💂♂ ↔, ⚙️ 👫 🔘, & 📄 🛠️ ⏮️ 🗄.
+✋️ ⚙️ `Security` ↩️ `Depends`, **FastAPI** 🔜 💭 👈 ⚫️ 💪 📣 💂♂ ↔, ⚙️ 👫 🔘, & 📄 🛠️ ⏮️ 🗄.
- ✋️ 🕐❔ 👆 🗄 `Query`, `Path`, `Depends`, `Security` & 🎏 ⚪️➡️ `fastapi`, 👈 🤙 🔢 👈 📨 🎁 🎓.
+✋️ 🕐❔ 👆 🗄 `Query`, `Path`, `Depends`, `Security` & 🎏 ⚪️➡️ `fastapi`, 👈 🤙 🔢 👈 📨 🎁 🎓.
+
+///
## ⚙️ `SecurityScopes`
* `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`
🏆 🔐 📟 💧, ✋️ 🌖 🏗 🛠️ ⚫️ 🚚 🌅 📶. ⚫️ 🌅 🏗, 📚 🐕🦺 🔚 🆙 ✔ 🔑 💧.
-!!! note
- ⚫️ ⚠ 👈 🔠 🤝 🐕🦺 📛 👫 💧 🎏 🌌, ⚒ ⚫️ 🍕 👫 🏷.
+/// note
+
+⚫️ ⚠ 👈 🔠 🤝 🐕🦺 📛 👫 💧 🎏 🌌, ⚒ ⚫️ 🍕 👫 🏷.
+
+✋️ 🔚, 👫 🛠️ 🎏 Oauth2️⃣ 🐩.
- ✋️ 🔚, 👫 🛠️ 🎏 Oauth2️⃣ 🐩.
+///
**FastAPI** 🔌 🚙 🌐 👫 Oauth2️⃣ 🤝 💧 `fastapi.security.oauth2`.
## 🌐 🔢
-!!! tip
- 🚥 👆 ⏪ 💭 ⚫️❔ "🌐 🔢" & ❔ ⚙️ 👫, 💭 🆓 🚶 ⏭ 📄 🔛.
+/// tip
+
+🚥 👆 ⏪ 💭 ⚫️❔ "🌐 🔢" & ❔ ⚙️ 👫, 💭 🆓 🚶 ⏭ 📄 🔛.
+
+///
<a href="https://en.wikipedia.org/wiki/Environment_variable" class="external-link" target="_blank">🌐 🔢</a> (💭 "🇨🇻 {") 🔢 👈 🖖 🏞 🐍 📟, 🏃♂ ⚙️, & 💪 ✍ 👆 🐍 📟 (⚖️ 🎏 📋 👍).
👆 💪 ✍ & ⚙️ 🌐 🔢 🐚, 🍵 💆♂ 🐍:
-=== "💾, 🇸🇻, 🚪 🎉"
+//// tab | 💾, 🇸🇻, 🚪 🎉
+
+<div class="termy">
+
+```console
+// You could create an env var MY_NAME with
+$ export MY_NAME="Wade Wilson"
- <div class="termy">
+// Then you could use it with other programs, like
+$ echo "Hello $MY_NAME"
- ```console
- // You could create an env var MY_NAME with
- $ export MY_NAME="Wade Wilson"
+Hello Wade Wilson
+```
- // Then you could use it with other programs, like
- $ echo "Hello $MY_NAME"
+</div>
- Hello Wade Wilson
- ```
+////
- </div>
+//// tab | 🚪 📋
-=== "🚪 📋"
+<div class="termy">
- <div class="termy">
+```console
+// Create an env var MY_NAME
+$ $Env:MY_NAME = "Wade Wilson"
- ```console
- // Create an env var MY_NAME
- $ $Env:MY_NAME = "Wade Wilson"
+// Use it with other programs, like
+$ echo "Hello $Env:MY_NAME"
- // Use it with other programs, like
- $ echo "Hello $Env:MY_NAME"
+Hello Wade Wilson
+```
- Hello Wade Wilson
- ```
+</div>
- </div>
+////
### ✍ 🇨🇻 {🐍
print(f"Hello {name} from Python")
```
-!!! tip
- 🥈 ❌ <a href="https://docs.python.org/3.8/library/os.html#os.getenv" class="external-link" target="_blank">`os.getenv()`</a> 🔢 💲 📨.
+/// tip
+
+🥈 ❌ <a href="https://docs.python.org/3.8/library/os.html#os.getenv" class="external-link" target="_blank">`os.getenv()`</a> 🔢 💲 📨.
- 🚥 🚫 🚚, ⚫️ `None` 🔢, 📥 👥 🚚 `"World"` 🔢 💲 ⚙️.
+🚥 🚫 🚚, ⚫️ `None` 🔢, 📥 👥 🚚 `"World"` 🔢 💲 ⚙️.
+
+///
⤴️ 👆 💪 🤙 👈 🐍 📋:
</div>
-!!! tip
- 👆 💪 ✍ 🌅 🔃 ⚫️ <a href="https://12factor.net/config" class="external-link" target="_blank">1️⃣2️⃣-⚖ 📱: 📁</a>.
+/// tip
+
+👆 💪 ✍ 🌅 🔃 ⚫️ <a href="https://12factor.net/config" class="external-link" target="_blank">1️⃣2️⃣-⚖ 📱: 📁</a>.
+
+///
### 🆎 & 🔬
{!../../../docs_src/settings/tutorial001.py!}
```
-!!! tip
- 🚥 👆 💚 🕳 ⏩ 📁 & 📋, 🚫 ⚙️ 👉 🖼, ⚙️ 🏁 1️⃣ 🔛.
+/// tip
+
+🚥 👆 💚 🕳 ⏩ 📁 & 📋, 🚫 ⚙️ 👉 🖼, ⚙️ 🏁 1️⃣ 🔛.
+
+///
⤴️, 🕐❔ 👆 ✍ 👐 👈 `Settings` 🎓 (👉 💼, `settings` 🎚), Pydantic 🔜 ✍ 🌐 🔢 💼-😛 🌌,, ↖-💼 🔢 `APP_NAME` 🔜 ✍ 🔢 `app_name`.
</div>
-!!! tip
- ⚒ 💗 🇨🇻 {👁 📋 🎏 👫 ⏮️ 🚀, & 🚮 👫 🌐 ⏭ 📋.
+/// tip
+
+⚒ 💗 🇨🇻 {👁 📋 🎏 👫 ⏮️ 🚀, & 🚮 👫 🌐 ⏭ 📋.
+
+///
& ⤴️ `admin_email` ⚒ 🔜 ⚒ `"deadpool@example.com"`.
{!../../../docs_src/settings/app01/main.py!}
```
-!!! tip
- 👆 🔜 💪 📁 `__init__.py` 👆 👀 🔛 [🦏 🈸 - 💗 📁](../tutorial/bigger-applications.md){.internal-link target=_blank}.
+/// tip
+
+👆 🔜 💪 📁 `__init__.py` 👆 👀 🔛 [🦏 🈸 - 💗 📁](../tutorial/bigger-applications.md){.internal-link target=_blank}.
+
+///
## ⚒ 🔗
{!../../../docs_src/settings/app02/main.py!}
```
-!!! tip
- 👥 🔜 🔬 `@lru_cache` 🍖.
+/// tip
+
+👥 🔜 🔬 `@lru_cache` 🍖.
- 🔜 👆 💪 🤔 `get_settings()` 😐 🔢.
+🔜 👆 💪 🤔 `get_settings()` 😐 🔢.
+
+///
& ⤴️ 👥 💪 🚚 ⚫️ ⚪️➡️ *➡ 🛠️ 🔢* 🔗 & ⚙️ ⚫️ 🙆 👥 💪 ⚫️.
👉 💡 ⚠ 🥃 👈 ⚫️ ✔️ 📛, 👫 🌐 🔢 🛎 🥉 📁 `.env`, & 📁 🤙 "🇨🇻".
-!!! tip
- 📁 ▶️ ⏮️ ❣ (`.`) 🕵♂ 📁 🖥-💖 ⚙️, 💖 💾 & 🇸🇻.
+/// tip
+
+📁 ▶️ ⏮️ ❣ (`.`) 🕵♂ 📁 🖥-💖 ⚙️, 💖 💾 & 🇸🇻.
- ✋️ 🇨🇻 📁 🚫 🤙 ✔️ ✔️ 👈 ☑ 📁.
+✋️ 🇨🇻 📁 🚫 🤙 ✔️ ✔️ 👈 ☑ 📁.
+
+///
Pydantic ✔️ 🐕🦺 👂 ⚪️➡️ 👉 🆎 📁 ⚙️ 🔢 🗃. 👆 💪 ✍ 🌖 <a href="https://docs.pydantic.dev/latest/concepts/pydantic_settings/#dotenv-env-support" class="external-link" target="_blank">Pydantic ⚒: 🇨🇻 (.🇨🇻) 🐕🦺</a>.
-!!! tip
- 👉 👷, 👆 💪 `pip install python-dotenv`.
+/// tip
+
+👉 👷, 👆 💪 `pip install python-dotenv`.
+
+///
### `.env` 📁
📥 👥 ✍ 🎓 `Config` 🔘 👆 Pydantic `Settings` 🎓, & ⚒ `env_file` 📁 ⏮️ 🇨🇻 📁 👥 💚 ⚙️.
-!!! tip
- `Config` 🎓 ⚙️ Pydantic 📳. 👆 💪 ✍ 🌖 <a href="https://docs.pydantic.dev/latest/api/config/" class="external-link" target="_blank">Pydantic 🏷 📁</a>
+/// tip
+
+`Config` 🎓 ⚙️ Pydantic 📳. 👆 💪 ✍ 🌖 <a href="https://docs.pydantic.dev/latest/api/config/" class="external-link" target="_blank">Pydantic 🏷 📁</a>
+
+///
### 🏗 `Settings` 🕴 🕐 ⏮️ `lru_cache`
{!../../../docs_src/templates/tutorial001.py!}
```
-!!! note
- 👀 👈 👆 ✔️ 🚶♀️ `request` 🍕 🔑-💲 👫 🔑 Jinja2️⃣. , 👆 ✔️ 📣 ⚫️ 👆 *➡ 🛠️*.
+/// note
-!!! tip
- 📣 `response_class=HTMLResponse` 🩺 🎚 🔜 💪 💭 👈 📨 🔜 🕸.
+👀 👈 👆 ✔️ 🚶♀️ `request` 🍕 🔑-💲 👫 🔑 Jinja2️⃣. , 👆 ✔️ 📣 ⚫️ 👆 *➡ 🛠️*.
-!!! note "📡 ℹ"
- 👆 💪 ⚙️ `from starlette.templating import Jinja2Templates`.
+///
- **FastAPI** 🚚 🎏 `starlette.templating` `fastapi.templating` 🏪 👆, 👩💻. ✋️ 🌅 💪 📨 👟 🔗 ⚪️➡️ 💃. 🎏 ⏮️ `Request` & `StaticFiles`.
+/// tip
+
+📣 `response_class=HTMLResponse` 🩺 🎚 🔜 💪 💭 👈 📨 🔜 🕸.
+
+///
+
+/// note | "📡 ℹ"
+
+👆 💪 ⚙️ `from starlette.templating import Jinja2Templates`.
+
+**FastAPI** 🚚 🎏 `starlette.templating` `fastapi.templating` 🏪 👆, 👩💻. ✋️ 🌅 💪 📨 👟 🔗 ⚪️➡️ 💃. 🎏 ⏮️ `Request` & `StaticFiles`.
+
+///
## ✍ 📄
{!../../../docs_src/sql_databases/sql_app/tests/test_sql_app.py!}
```
-!!! tip
- 👆 💪 📉 ❎ 👈 📟 🚮 ⚫️ 🔢 & ⚙️ ⚫️ ⚪️➡️ 👯♂️ `database.py` & `tests/test_sql_app.py`.
+/// tip
- 🦁 & 🎯 🔛 🎯 🔬 📟, 👥 🖨 ⚫️.
+👆 💪 📉 ❎ 👈 📟 🚮 ⚫️ 🔢 & ⚙️ ⚫️ ⚪️➡️ 👯♂️ `database.py` & `tests/test_sql_app.py`.
+
+🦁 & 🎯 🔛 🎯 🔬 📟, 👥 🖨 ⚫️.
+
+///
## ✍ 💽
{!../../../docs_src/sql_databases/sql_app/tests/test_sql_app.py!}
```
-!!! tip
- 📟 `override_get_db()` 🌖 ⚫️❔ 🎏 `get_db()`, ✋️ `override_get_db()` 👥 ⚙️ `TestingSessionLocal` 🔬 💽 ↩️.
+/// tip
+
+📟 `override_get_db()` 🌖 ⚫️❔ 🎏 `get_db()`, ✋️ `override_get_db()` 👥 ⚙️ `TestingSessionLocal` 🔬 💽 ↩️.
+
+///
## 💯 📱
{!../../../docs_src/dependency_testing/tutorial001.py!}
```
-!!! tip
- 👆 💪 ⚒ 🔗 🔐 🔗 ⚙️ 🙆 👆 **FastAPI** 🈸.
+/// tip
- ⏮️ 🔗 💪 ⚙️ *➡ 🛠️ 🔢*, *➡ 🛠️ 👨🎨* (🕐❔ 👆 🚫 ⚙️ 📨 💲), `.include_router()` 🤙, ♒️.
+👆 💪 ⚒ 🔗 🔐 🔗 ⚙️ 🙆 👆 **FastAPI** 🈸.
- FastAPI 🔜 💪 🔐 ⚫️.
+⏮️ 🔗 💪 ⚙️ *➡ 🛠️ 🔢*, *➡ 🛠️ 👨🎨* (🕐❔ 👆 🚫 ⚙️ 📨 💲), `.include_router()` 🤙, ♒️.
+
+FastAPI 🔜 💪 🔐 ⚫️.
+
+///
⤴️ 👆 💪 ⏲ 👆 🔐 (❎ 👫) ⚒ `app.dependency_overrides` 🛁 `dict`:
app.dependency_overrides = {}
```
-!!! tip
- 🚥 👆 💚 🔐 🔗 🕴 ⏮️ 💯, 👆 💪 ⚒ 🔐 ▶️ 💯 (🔘 💯 🔢) & ⏲ ⚫️ 🔚 (🔚 💯 🔢).
+/// tip
+
+🚥 👆 💚 🔐 🔗 🕴 ⏮️ 💯, 👆 💪 ⚒ 🔐 ▶️ 💯 (🔘 💯 🔢) & ⏲ ⚫️ 🔚 (🔚 💯 🔢).
+
+///
{!../../../docs_src/app_testing/tutorial002.py!}
```
-!!! note
- 🌅 ℹ, ✅ 💃 🧾 <a href="https://www.starlette.io/testclient/#testing-websocket-sessions" class="external-link" target="_blank">🔬 *️⃣ </a>.
+/// note
+
+🌅 ℹ, ✅ 💃 🧾 <a href="https://www.starlette.io/testclient/#testing-websocket-sessions" class="external-link" target="_blank">🔬 *️⃣ </a>.
+
+///
📣 *➡ 🛠️ 🔢* 🔢 ⏮️ 🆎 ➖ `Request` **FastAPI** 🔜 💭 🚶♀️ `Request` 👈 🔢.
-!!! tip
- 🗒 👈 👉 💼, 👥 📣 ➡ 🔢 ⤴️ 📨 🔢.
+/// tip
- , ➡ 🔢 🔜 ⚗, ✔, 🗜 ✔ 🆎 & ✍ ⏮️ 🗄.
+🗒 👈 👉 💼, 👥 📣 ➡ 🔢 ⤴️ 📨 🔢.
- 🎏 🌌, 👆 💪 📣 🙆 🎏 🔢 🛎, & ➡, 🤚 `Request` 💁♂️.
+, ➡ 🔢 🔜 ⚗, ✔, 🗜 ✔ 🆎 & ✍ ⏮️ 🗄.
+
+🎏 🌌, 👆 💪 📣 🙆 🎏 🔢 🛎, & ➡, 🤚 `Request` 💁♂️.
+
+///
## `Request` 🧾
👆 💪 ✍ 🌅 ℹ 🔃 <a href="https://www.starlette.io/requests/" class="external-link" target="_blank">`Request` 🎚 🛂 💃 🧾 🕸</a>.
-!!! note "📡 ℹ"
- 👆 💪 ⚙️ `from starlette.requests import Request`.
+/// note | "📡 ℹ"
+
+👆 💪 ⚙️ `from starlette.requests import Request`.
+
+**FastAPI** 🚚 ⚫️ 🔗 🏪 👆, 👩💻. ✋️ ⚫️ 👟 🔗 ⚪️➡️ 💃.
- **FastAPI** 🚚 ⚫️ 🔗 🏪 👆, 👩💻. ✋️ ⚫️ 👟 🔗 ⚪️➡️ 💃.
+///
{!../../../docs_src/websockets/tutorial001.py!}
```
-!!! note "📡 ℹ"
- 👆 💪 ⚙️ `from starlette.websockets import WebSocket`.
+/// note | "📡 ℹ"
- **FastAPI** 🚚 🎏 `WebSocket` 🔗 🏪 👆, 👩💻. ✋️ ⚫️ 👟 🔗 ⚪️➡️ 💃.
+👆 💪 ⚙️ `from starlette.websockets import WebSocket`.
+
+**FastAPI** 🚚 🎏 `WebSocket` 🔗 🏪 👆, 👩💻. ✋️ ⚫️ 👟 🔗 ⚪️➡️ 💃.
+
+///
## ⌛ 📧 & 📨 📧
{!../../../docs_src/websockets/tutorial002.py!}
```
-!!! info
- 👉 *️⃣ ⚫️ 🚫 🤙 ⚒ 🔑 🤚 `HTTPException`, ↩️ 👥 🤚 `WebSocketException`.
+/// info
+
+👉 *️⃣ ⚫️ 🚫 🤙 ⚒ 🔑 🤚 `HTTPException`, ↩️ 👥 🤚 `WebSocketException`.
+
+👆 💪 ⚙️ 📪 📟 ⚪️➡️ <a href="https://tools.ietf.org/html/rfc6455#section-7.4.1" class="external-link" target="_blank">☑ 📟 🔬 🔧</a>.
- 👆 💪 ⚙️ 📪 📟 ⚪️➡️ <a href="https://tools.ietf.org/html/rfc6455#section-7.4.1" class="external-link" target="_blank">☑ 📟 🔬 🔧</a>.
+///
### 🔄 *️⃣ ⏮️ 🔗
* "🏬 🆔", ⚙️ ➡.
* "🤝" ⚙️ 🔢 🔢.
-!!! tip
- 👀 👈 🔢 `token` 🔜 🍵 🔗.
+/// tip
+
+👀 👈 🔢 `token` 🔜 🍵 🔗.
+
+///
⏮️ 👈 👆 💪 🔗 *️⃣ & ⤴️ 📨 & 📨 📧:
Client #1596980209979 left the chat
```
-!!! tip
- 📱 🔛 ⭐ & 🙅 🖼 🎦 ❔ 🍵 & 📻 📧 📚 *️⃣ 🔗.
+/// tip
+
+📱 🔛 ⭐ & 🙅 🖼 🎦 ❔ 🍵 & 📻 📧 📚 *️⃣ 🔗.
+
+✋️ ✔️ 🤯 👈, 🌐 🍵 💾, 👁 📇, ⚫️ 🔜 🕴 👷 ⏪ 🛠️ 🏃, & 🔜 🕴 👷 ⏮️ 👁 🛠️.
- ✋️ ✔️ 🤯 👈, 🌐 🍵 💾, 👁 📇, ⚫️ 🔜 🕴 👷 ⏪ 🛠️ 🏃, & 🔜 🕴 👷 ⏮️ 👁 🛠️.
+🚥 👆 💪 🕳 ⏩ 🛠️ ⏮️ FastAPI ✋️ 👈 🌖 🏋️, 🐕🦺 ✳, ✳ ⚖️ 🎏, ✅ <a href="https://github.com/encode/broadcaster" class="external-link" target="_blank">🗜/📻</a>.
- 🚥 👆 💪 🕳 ⏩ 🛠️ ⏮️ FastAPI ✋️ 👈 🌖 🏋️, 🐕🦺 ✳, ✳ ⚖️ 🎏, ✅ <a href="https://github.com/encode/broadcaster" class="external-link" target="_blank">🗜/📻</a>.
+///
## 🌅 ℹ
⚫️ 🕐 🥇 🖼 **🏧 🛠️ 🧾**, & 👉 🎯 🕐 🥇 💭 👈 😮 "🔎" **FastAPI**.
-!!! note
- ✳ 🎂 🛠️ ✍ ✡ 🇺🇸🏛. 🎏 👼 💃 & Uvicorn, 🔛 ❔ **FastAPI** ⚓️.
+/// note
+✳ 🎂 🛠️ ✍ ✡ 🇺🇸🏛. 🎏 👼 💃 & Uvicorn, 🔛 ❔ **FastAPI** ⚓️.
-!!! check "😮 **FastAPI** "
- ✔️ 🏧 🛠️ 🧾 🕸 👩💻 🔢.
+///
+
+/// check | "😮 **FastAPI** "
+
+✔️ 🏧 🛠️ 🧾 🕸 👩💻 🔢.
+
+///
### <a href="https://flask.palletsprojects.com" class="external-link" target="_blank">🏺</a>
👐 🦁 🏺, ⚫️ 😑 💖 👍 🏏 🏗 🔗. ⏭ 👜 🔎 "✳ 🎂 🛠️" 🏺.
-!!! check "😮 **FastAPI** "
- ◾-🛠️. ⚒ ⚫️ ⏩ 🌀 & 🏏 🧰 & 🍕 💪.
+/// check | "😮 **FastAPI** "
- ✔️ 🙅 & ⏩ ⚙️ 🕹 ⚙️.
+◾-🛠️. ⚒ ⚫️ ⏩ 🌀 & 🏏 🧰 & 🍕 💪.
+✔️ 🙅 & ⏩ ⚙️ 🕹 ⚙️.
+
+///
### <a href="https://requests.readthedocs.io" class="external-link" target="_blank">📨</a>
👀 🔀 `requests.get(...)` & `@app.get(...)`.
-!!! check "😮 **FastAPI** "
- * ✔️ 🙅 & 🏋️ 🛠️.
- * ⚙️ 🇺🇸🔍 👩🔬 📛 (🛠️) 🔗, 🎯 & 🏋️ 🌌.
- * ✔️ 🤔 🔢, ✋️ 🏋️ 🛃.
+/// check | "😮 **FastAPI** "
+
+* ✔️ 🙅 & 🏋️ 🛠️.
+* ⚙️ 🇺🇸🔍 👩🔬 📛 (🛠️) 🔗, 🎯 & 🏋️ 🌌.
+* ✔️ 🤔 🔢, ✋️ 🏋️ 🛃.
+///
### <a href="https://swagger.io/" class="external-link" target="_blank">🦁</a> / <a href="https://github.com/OAI/OpenAPI-Specification/" class="external-link" target="_blank">🗄</a>
👈 ⚫️❔ 🕐❔ 💬 🔃 ⏬ 2️⃣.0️⃣ ⚫️ ⚠ 💬 "🦁", & ⏬ 3️⃣ ➕ "🗄".
-!!! check "😮 **FastAPI** "
- 🛠️ & ⚙️ 📂 🐩 🛠️ 🔧, ↩️ 🛃 🔗.
+/// check | "😮 **FastAPI** "
+
+🛠️ & ⚙️ 📂 🐩 🛠️ 🔧, ↩️ 🛃 🔗.
- & 🛠️ 🐩-⚓️ 👩💻 🔢 🧰:
+ & 🛠️ 🐩-⚓️ 👩💻 🔢 🧰:
- * <a href="https://github.com/swagger-api/swagger-ui" class="external-link" target="_blank">🦁 🎚</a>
- * <a href="https://github.com/Rebilly/ReDoc" class="external-link" target="_blank">📄</a>
+* <a href="https://github.com/swagger-api/swagger-ui" class="external-link" target="_blank">🦁 🎚</a>
+* <a href="https://github.com/Rebilly/ReDoc" class="external-link" target="_blank">📄</a>
- 👫 2️⃣ 👐 ➖ 📶 🌟 & ⚖, ✋️ 🔨 ⏩ 🔎, 👆 💪 🔎 💯 🌖 🎛 👩💻 🔢 🗄 (👈 👆 💪 ⚙️ ⏮️ **FastAPI**).
+👫 2️⃣ 👐 ➖ 📶 🌟 & ⚖, ✋️ 🔨 ⏩ 🔎, 👆 💪 🔎 💯 🌖 🎛 👩💻 🔢 🗄 (👈 👆 💪 ⚙️ ⏮️ **FastAPI**).
+
+///
### 🏺 🎂 🛠️
✋️ ⚫️ ✍ ⏭ 📤 🔀 🐍 🆎 🔑. , 🔬 🔠 <abbr title="the definition of how data should be formed">🔗</abbr> 👆 💪 ⚙️ 🎯 🇨🇻 & 🎓 🚚 🍭.
-!!! check "😮 **FastAPI** "
- ⚙️ 📟 🔬 "🔗" 👈 🚚 💽 🆎 & 🔬, 🔁.
+/// check | "😮 **FastAPI** "
+
+⚙️ 📟 🔬 "🔗" 👈 🚚 💽 🆎 & 🔬, 🔁.
+
+///
### <a href="https://webargs.readthedocs.io/en/latest/" class="external-link" target="_blank">Webarg</a>
⚫️ 👑 🧰 & 👤 ✔️ ⚙️ ⚫️ 📚 💁♂️, ⏭ ✔️ **FastAPI**.
-!!! info
- Webarg ✍ 🎏 🍭 👩💻.
+/// info
+
+Webarg ✍ 🎏 🍭 👩💻.
+
+///
+
+/// check | "😮 **FastAPI** "
-!!! check "😮 **FastAPI** "
- ✔️ 🏧 🔬 📨 📨 💽.
+✔️ 🏧 🔬 📨 📨 💽.
+
+///
### <a href="https://apispec.readthedocs.io/en/stable/" class="external-link" target="_blank">APISpec</a>
👨🎨 💪 🚫 ℹ 🌅 ⏮️ 👈. & 🚥 👥 🔀 🔢 ⚖️ 🍭 🔗 & 💭 🔀 👈 📁#️⃣, 🏗 🔗 🔜 ❌.
-!!! info
- APISpec ✍ 🎏 🍭 👩💻.
+/// info
+
+APISpec ✍ 🎏 🍭 👩💻.
+
+///
+/// check | "😮 **FastAPI** "
-!!! check "😮 **FastAPI** "
- 🐕🦺 📂 🐩 🛠️, 🗄.
+🐕🦺 📂 🐩 🛠️, 🗄.
+
+///
### <a href="https://flask-apispec.readthedocs.io/en/latest/" class="external-link" target="_blank">🏺-Apispec</a>
& 👫 🎏 🌕-📚 🚂 🧢 [**FastAPI** 🏗 🚂](project-generation.md){.internal-link target=_blank}.
-!!! info
- 🏺-Apispec ✍ 🎏 🍭 👩💻.
+/// info
+
+🏺-Apispec ✍ 🎏 🍭 👩💻.
+
+///
-!!! check "😮 **FastAPI** "
- 🏗 🗄 🔗 🔁, ⚪️➡️ 🎏 📟 👈 🔬 🛠️ & 🔬.
+/// check | "😮 **FastAPI** "
+
+🏗 🗄 🔗 🔁, ⚪️➡️ 🎏 📟 👈 🔬 🛠️ & 🔬.
+
+///
### <a href="https://nestjs.com/" class="external-link" target="_blank">NestJS</a> (& <a href="https://angular.io/" class="external-link" target="_blank">📐</a>)
⚫️ 💪 🚫 🍵 🔁 🏷 📶 👍. , 🚥 🎻 💪 📨 🎻 🎚 👈 ✔️ 🔘 🏑 👈 🔄 🐦 🎻 🎚, ⚫️ 🚫🔜 ☑ 📄 & ✔.
-!!! check "😮 **FastAPI** "
- ⚙️ 🐍 🆎 ✔️ 👑 👨🎨 🐕🦺.
+/// check | "😮 **FastAPI** "
+
+⚙️ 🐍 🆎 ✔️ 👑 👨🎨 🐕🦺.
- ✔️ 🏋️ 🔗 💉 ⚙️. 🔎 🌌 📉 📟 🔁.
+✔️ 🏋️ 🔗 💉 ⚙️. 🔎 🌌 📉 📟 🔁.
+
+///
### <a href="https://sanic.readthedocs.io/en/latest/" class="external-link" target="_blank">🤣</a>
⚫️ 🕐 🥇 📶 ⏩ 🐍 🛠️ ⚓️ 🔛 `asyncio`. ⚫️ ⚒ 📶 🎏 🏺.
-!!! note "📡 ℹ"
- ⚫️ ⚙️ <a href="https://github.com/MagicStack/uvloop" class="external-link" target="_blank">`uvloop`</a> ↩️ 🔢 🐍 `asyncio` ➰. 👈 ⚫️❔ ⚒ ⚫️ ⏩.
+/// note | "📡 ℹ"
+
+⚫️ ⚙️ <a href="https://github.com/MagicStack/uvloop" class="external-link" target="_blank">`uvloop`</a> ↩️ 🔢 🐍 `asyncio` ➰. 👈 ⚫️❔ ⚒ ⚫️ ⏩.
- ⚫️ 🎯 😮 Uvicorn & 💃, 👈 ⏳ ⏩ 🌘 🤣 📂 📇.
+⚫️ 🎯 😮 Uvicorn & 💃, 👈 ⏳ ⏩ 🌘 🤣 📂 📇.
-!!! check "😮 **FastAPI** "
- 🔎 🌌 ✔️ 😜 🎭.
+///
- 👈 ⚫️❔ **FastAPI** ⚓️ 🔛 💃, ⚫️ ⏩ 🛠️ 💪 (💯 🥉-🥳 📇).
+/// check | "😮 **FastAPI** "
+
+🔎 🌌 ✔️ 😜 🎭.
+
+👈 ⚫️❔ **FastAPI** ⚓️ 🔛 💃, ⚫️ ⏩ 🛠️ 💪 (💯 🥉-🥳 📇).
+
+///
### <a href="https://falconframework.org/" class="external-link" target="_blank">🦅</a>
, 💽 🔬, 🛠️, & 🧾, ✔️ ⌛ 📟, 🚫 🔁. ⚖️ 👫 ✔️ 🛠️ 🛠️ 🔛 🔝 🦅, 💖 🤗. 👉 🎏 🔺 🔨 🎏 🛠️ 👈 😮 🦅 🔧, ✔️ 1️⃣ 📨 🎚 & 1️⃣ 📨 🎚 🔢.
-!!! check "😮 **FastAPI** "
- 🔎 🌌 🤚 👑 🎭.
+/// check | "😮 **FastAPI** "
- ⤴️ ⏮️ 🤗 (🤗 ⚓️ 🔛 🦅) 😮 **FastAPI** 📣 `response` 🔢 🔢.
+🔎 🌌 🤚 👑 🎭.
- 👐 FastAPI ⚫️ 📦, & ⚙️ ✴️ ⚒ 🎚, 🍪, & 🎛 👔 📟.
+⤴️ ⏮️ 🤗 (🤗 ⚓️ 🔛 🦅) 😮 **FastAPI** 📣 `response` 🔢 🔢.
+
+👐 FastAPI ⚫️ 📦, & ⚙️ ✴️ ⚒ 🎚, 🍪, & 🎛 👔 📟.
+
+///
### <a href="https://moltenframework.com/" class="external-link" target="_blank">♨</a>
🛣 📣 👁 🥉, ⚙️ 🔢 📣 🎏 🥉 (↩️ ⚙️ 👨🎨 👈 💪 🥉 ▶️️ 🔛 🔝 🔢 👈 🍵 🔗). 👉 🔐 ❔ ✳ 🔨 ⚫️ 🌘 ❔ 🏺 (& 💃) 🔨 ⚫️. ⚫️ 🎏 📟 👜 👈 📶 😆 🔗.
-!!! check "😮 **FastAPI** "
- 🔬 ➕ 🔬 💽 🆎 ⚙️ "🔢" 💲 🏷 🔢. 👉 📉 👨🎨 🐕🦺, & ⚫️ 🚫 💪 Pydantic ⏭.
+/// check | "😮 **FastAPI** "
+
+🔬 ➕ 🔬 💽 🆎 ⚙️ "🔢" 💲 🏷 🔢. 👉 📉 👨🎨 🐕🦺, & ⚫️ 🚫 💪 Pydantic ⏭.
- 👉 🤙 😮 🛠️ 🍕 Pydantic, 🐕🦺 🎏 🔬 📄 👗 (🌐 👉 🛠️ 🔜 ⏪ 💪 Pydantic).
+👉 🤙 😮 🛠️ 🍕 Pydantic, 🐕🦺 🎏 🔬 📄 👗 (🌐 👉 🛠️ 🔜 ⏪ 💪 Pydantic).
+
+///
### <a href="https://www.hug.rest/" class="external-link" target="_blank">🤗</a>
⚫️ ⚓️ 🔛 ⏮️ 🐩 🔁 🐍 🕸 🛠️ (🇨🇻), ⚫️ 💪 🚫 🍵 *️⃣ & 🎏 👜, 👐 ⚫️ ✔️ ↕ 🎭 💁♂️.
-!!! info
- 🤗 ✍ ✡ 🗄, 🎏 👼 <a href="https://github.com/timothycrosley/isort" class="external-link" target="_blank">`isort`</a>, 👑 🧰 🔁 😇 🗄 🐍 📁.
+/// info
+
+🤗 ✍ ✡ 🗄, 🎏 👼 <a href="https://github.com/timothycrosley/isort" class="external-link" target="_blank">`isort`</a>, 👑 🧰 🔁 😇 🗄 🐍 📁.
+
+///
-!!! check "💭 😮 **FastAPI**"
- 🤗 😮 🍕 APIStar, & 1️⃣ 🧰 👤 🔎 🏆 👍, 🌟 APIStar.
+/// check | "💭 😮 **FastAPI**"
- 🤗 ℹ 😍 **FastAPI** ⚙️ 🐍 🆎 🔑 📣 🔢, & 🏗 🔗 ⚖ 🛠️ 🔁.
+🤗 😮 🍕 APIStar, & 1️⃣ 🧰 👤 🔎 🏆 👍, 🌟 APIStar.
- 🤗 😮 **FastAPI** 📣 `response` 🔢 🔢 ⚒ 🎚 & 🍪.
+🤗 ℹ 😍 **FastAPI** ⚙️ 🐍 🆎 🔑 📣 🔢, & 🏗 🔗 ⚖ 🛠️ 🔁.
+
+🤗 😮 **FastAPI** 📣 `response` 🔢 🔢 ⚒ 🎚 & 🍪.
+
+///
### <a href="https://github.com/encode/apistar" class="external-link" target="_blank">APIStar</a> (<= 0️⃣.5️⃣)
🔜 APIStar ⚒ 🧰 ✔ 🗄 🔧, 🚫 🕸 🛠️.
-!!! info
- APIStar ✍ ✡ 🇺🇸🏛. 🎏 👨 👈 ✍:
+/// info
+
+APIStar ✍ ✡ 🇺🇸🏛. 🎏 👨 👈 ✍:
- * ✳ 🎂 🛠️
- * 💃 (❔ **FastAPI** ⚓️)
- * Uvicorn (⚙️ 💃 & **FastAPI**)
+* ✳ 🎂 🛠️
+* 💃 (❔ **FastAPI** ⚓️)
+* Uvicorn (⚙️ 💃 & **FastAPI**)
-!!! check "😮 **FastAPI** "
- 🔀.
+///
- 💭 📣 💗 👜 (💽 🔬, 🛠️ & 🧾) ⏮️ 🎏 🐍 🆎, 👈 🎏 🕰 🚚 👑 👨🎨 🐕🦺, 🕳 👤 🤔 💎 💭.
+/// check | "😮 **FastAPI** "
- & ⏮️ 🔎 📏 🕰 🎏 🛠️ & 🔬 📚 🎏 🎛, APIStar 🏆 🎛 💪.
+🔀.
- ⤴️ APIStar ⛔️ 🔀 💽 & 💃 ✍, & 🆕 👻 🏛 ✅ ⚙️. 👈 🏁 🌈 🏗 **FastAPI**.
+💭 📣 💗 👜 (💽 🔬, 🛠️ & 🧾) ⏮️ 🎏 🐍 🆎, 👈 🎏 🕰 🚚 👑 👨🎨 🐕🦺, 🕳 👤 🤔 💎 💭.
- 👤 🤔 **FastAPI** "🛐 👨💼" APIStar, ⏪ 📉 & 📈 ⚒, ⌨ ⚙️, & 🎏 🍕, ⚓️ 🔛 🏫 ⚪️➡️ 🌐 👉 ⏮️ 🧰.
+ & ⏮️ 🔎 📏 🕰 🎏 🛠️ & 🔬 📚 🎏 🎛, APIStar 🏆 🎛 💪.
+
+⤴️ APIStar ⛔️ 🔀 💽 & 💃 ✍, & 🆕 👻 🏛 ✅ ⚙️. 👈 🏁 🌈 🏗 **FastAPI**.
+
+👤 🤔 **FastAPI** "🛐 👨💼" APIStar, ⏪ 📉 & 📈 ⚒, ⌨ ⚙️, & 🎏 🍕, ⚓️ 🔛 🏫 ⚪️➡️ 🌐 👉 ⏮️ 🧰.
+
+///
## ⚙️ **FastAPI**
⚫️ ⭐ 🍭. 👐 ⚫️ ⏩ 🌘 🍭 📇. & ⚫️ ⚓️ 🔛 🎏 🐍 🆎 🔑, 👨🎨 🐕🦺 👑.
-!!! check "**FastAPI** ⚙️ ⚫️"
- 🍵 🌐 💽 🔬, 💽 🛠️ & 🏧 🏷 🧾 (⚓️ 🔛 🎻 🔗).
+/// check | "**FastAPI** ⚙️ ⚫️"
- **FastAPI** ⤴️ ✊ 👈 🎻 🔗 💽 & 🚮 ⚫️ 🗄, ↖️ ⚪️➡️ 🌐 🎏 👜 ⚫️ 🔨.
+🍵 🌐 💽 🔬, 💽 🛠️ & 🏧 🏷 🧾 (⚓️ 🔛 🎻 🔗).
+
+**FastAPI** ⤴️ ✊ 👈 🎻 🔗 💽 & 🚮 ⚫️ 🗄, ↖️ ⚪️➡️ 🌐 🎏 👜 ⚫️ 🔨.
+
+///
### <a href="https://www.starlette.io/" class="external-link" target="_blank">💃</a>
👈 1️⃣ 👑 👜 👈 **FastAPI** 🚮 🔛 🔝, 🌐 ⚓️ 🔛 🐍 🆎 🔑 (⚙️ Pydantic). 👈, ➕ 🔗 💉 ⚙️, 💂♂ 🚙, 🗄 🔗 ⚡, ♒️.
-!!! note "📡 ℹ"
- 🔫 🆕 "🐩" ➖ 🛠️ ✳ 🐚 🏉 👨🎓. ⚫️ 🚫 "🐍 🐩" (🇩🇬), 👐 👫 🛠️ 🔨 👈.
+/// note | "📡 ℹ"
+
+🔫 🆕 "🐩" ➖ 🛠️ ✳ 🐚 🏉 👨🎓. ⚫️ 🚫 "🐍 🐩" (🇩🇬), 👐 👫 🛠️ 🔨 👈.
- 👐, ⚫️ ⏪ ➖ ⚙️ "🐩" 📚 🧰. 👉 📉 📉 🛠️, 👆 💪 🎛 Uvicorn 🙆 🎏 🔫 💽 (💖 👸 ⚖️ Hypercorn), ⚖️ 👆 💪 🚮 🔫 🔗 🧰, 💖 `python-socketio`.
+👐, ⚫️ ⏪ ➖ ⚙️ "🐩" 📚 🧰. 👉 📉 📉 🛠️, 👆 💪 🎛 Uvicorn 🙆 🎏 🔫 💽 (💖 👸 ⚖️ Hypercorn), ⚖️ 👆 💪 🚮 🔫 🔗 🧰, 💖 `python-socketio`.
-!!! check "**FastAPI** ⚙️ ⚫️"
- 🍵 🌐 🐚 🕸 🍕. ❎ ⚒ 🔛 🔝.
+///
- 🎓 `FastAPI` ⚫️ 😖 🔗 ⚪️➡️ 🎓 `Starlette`.
+/// check | "**FastAPI** ⚙️ ⚫️"
- , 🕳 👈 👆 💪 ⏮️ 💃, 👆 💪 ⚫️ 🔗 ⏮️ **FastAPI**, ⚫️ 🌖 💃 🔛 💊.
+🍵 🌐 🐚 🕸 🍕. ❎ ⚒ 🔛 🔝.
+
+🎓 `FastAPI` ⚫️ 😖 🔗 ⚪️➡️ 🎓 `Starlette`.
+
+, 🕳 👈 👆 💪 ⏮️ 💃, 👆 💪 ⚫️ 🔗 ⏮️ **FastAPI**, ⚫️ 🌖 💃 🔛 💊.
+
+///
### <a href="https://www.uvicorn.org/" class="external-link" target="_blank">Uvicorn</a>
⚫️ 👍 💽 💃 & **FastAPI**.
-!!! check "**FastAPI** 👍 ⚫️"
- 👑 🕸 💽 🏃 **FastAPI** 🈸.
+/// check | "**FastAPI** 👍 ⚫️"
+
+👑 🕸 💽 🏃 **FastAPI** 🈸.
+
+👆 💪 🌀 ⚫️ ⏮️ 🐁, ✔️ 🔁 👁-🛠️ 💽.
- 👆 💪 🌀 ⚫️ ⏮️ 🐁, ✔️ 🔁 👁-🛠️ 💽.
+✅ 🌅 ℹ [🛠️](deployment/index.md){.internal-link target=_blank} 📄.
- ✅ 🌅 ℹ [🛠️](deployment/index.md){.internal-link target=_blank} 📄.
+///
## 📇 & 🚅
return results
```
-!!! note
- 👆 💪 🕴 ⚙️ `await` 🔘 🔢 ✍ ⏮️ `async def`.
+/// note
+
+👆 💪 🕴 ⚙️ `await` 🔘 🔢 ✍ ⏮️ `async def`.
+
+///
---
<img src="/img/async/concurrent-burgers/concurrent-burgers-07.png" class="illustration">
-!!! info
- 🌹 🖼 <a href="https://www.instagram.com/ketrinadrawsalot" class="external-link" target="_blank">👯 🍏</a>. 👶
+/// info
+
+🌹 🖼 <a href="https://www.instagram.com/ketrinadrawsalot" class="external-link" target="_blank">👯 🍏</a>. 👶
+
+///
---
📤 🚫 🌅 💬 ⚖️ 😏 🌅 🕰 💸 ⌛ 👶 🚪 ⏲. 👶
-!!! info
- 🌹 🖼 <a href="https://www.instagram.com/ketrinadrawsalot" class="external-link" target="_blank">👯 🍏</a>. 👶
+/// info
+
+🌹 🖼 <a href="https://www.instagram.com/ketrinadrawsalot" class="external-link" target="_blank">👯 🍏</a>. 👶
+
+///
---
## 📶 📡 ℹ
-!!! warning
- 👆 💪 🎲 🚶 👉.
+/// warning
+
+👆 💪 🎲 🚶 👉.
+
+👉 📶 📡 ℹ ❔ **FastAPI** 👷 🔘.
- 👉 📶 📡 ℹ ❔ **FastAPI** 👷 🔘.
+🚥 👆 ✔️ 📡 💡 (🈶-🏋, 🧵, 🍫, ♒️.) & 😟 🔃 ❔ FastAPI 🍵 `async def` 🆚 😐 `def`, 🚶 ⤴️.
- 🚥 👆 ✔️ 📡 💡 (🈶-🏋, 🧵, 🍫, ♒️.) & 😟 🔃 ❔ FastAPI 🍵 `async def` 🆚 😐 `def`, 🚶 ⤴️.
+///
### ➡ 🛠️ 🔢
🔓 🆕 🌐 ⏮️:
-=== "💾, 🇸🇻"
+//// tab | 💾, 🇸🇻
- <div class="termy">
+<div class="termy">
- ```console
- $ source ./env/bin/activate
- ```
+```console
+$ source ./env/bin/activate
+```
- </div>
+</div>
-=== "🚪 📋"
+////
- <div class="termy">
+//// tab | 🚪 📋
- ```console
- $ .\env\Scripts\Activate.ps1
- ```
+<div class="termy">
- </div>
+```console
+$ .\env\Scripts\Activate.ps1
+```
-=== "🚪 🎉"
+</div>
- ⚖️ 🚥 👆 ⚙️ 🎉 🖥 (✅ <a href="https://gitforwindows.org/" class="external-link" target="_blank">🐛 🎉</a>):
+////
- <div class="termy">
+//// tab | 🚪 🎉
- ```console
- $ source ./env/Scripts/activate
- ```
+⚖️ 🚥 👆 ⚙️ 🎉 🖥 (✅ <a href="https://gitforwindows.org/" class="external-link" target="_blank">🐛 🎉</a>):
- </div>
+<div class="termy">
+
+```console
+$ source ./env/Scripts/activate
+```
+
+</div>
+
+////
✅ ⚫️ 👷, ⚙️:
-=== "💾, 🇸🇻, 🚪 🎉"
+//// tab | 💾, 🇸🇻, 🚪 🎉
- <div class="termy">
+<div class="termy">
- ```console
- $ which pip
+```console
+$ which pip
- some/directory/fastapi/env/bin/pip
- ```
+some/directory/fastapi/env/bin/pip
+```
- </div>
+</div>
-=== "🚪 📋"
+////
- <div class="termy">
+//// tab | 🚪 📋
- ```console
- $ Get-Command pip
+<div class="termy">
- some/directory/fastapi/env/bin/pip
- ```
+```console
+$ Get-Command pip
- </div>
+some/directory/fastapi/env/bin/pip
+```
+
+</div>
+
+////
🚥 ⚫️ 🎦 `pip` 💱 `env/bin/pip` ⤴️ ⚫️ 👷. 👶
</div>
-!!! tip
- 🔠 🕰 👆 ❎ 🆕 📦 ⏮️ `pip` 🔽 👈 🌐, 🔓 🌐 🔄.
+/// tip
+
+🔠 🕰 👆 ❎ 🆕 📦 ⏮️ `pip` 🔽 👈 🌐, 🔓 🌐 🔄.
- 👉 ⚒ 💭 👈 🚥 👆 ⚙️ 📶 📋 ❎ 👈 📦, 👆 ⚙️ 1️⃣ ⚪️➡️ 👆 🇧🇿 🌐 & 🚫 🙆 🎏 👈 💪 ❎ 🌐.
+👉 ⚒ 💭 👈 🚥 👆 ⚙️ 📶 📋 ❎ 👈 📦, 👆 ⚙️ 1️⃣ ⚪️➡️ 👆 🇧🇿 🌐 & 🚫 🙆 🎏 👈 💪 ❎ 🌐.
+
+///
### 🐖
& 📤 ➕ 🧰/✍ 🥉 🍵 ✍ `./scripts/docs.py`.
-!!! tip
- 👆 🚫 💪 👀 📟 `./scripts/docs.py`, 👆 ⚙️ ⚫️ 📋 ⏸.
+/// tip
+
+👆 🚫 💪 👀 📟 `./scripts/docs.py`, 👆 ⚙️ ⚫️ 📋 ⏸.
+
+///
🌐 🧾 ✍ 📁 📁 `./docs/en/`.
* ✅ ⏳ <a href="https://github.com/fastapi/fastapi/pulls" class="external-link" target="_blank">♻ 🚲 📨</a> 👆 🇪🇸 & 🚮 📄 ✔ 🔀 ⚖️ ✔ 👫.
-!!! tip
- 👆 💪 <a href="https://help.github.com/en/github/collaborating-with-issues-and-pull-requests/commenting-on-a-pull-request" class="external-link" target="_blank">🚮 🏤 ⏮️ 🔀 🔑</a> ♻ 🚲 📨.
+/// tip
+
+👆 💪 <a href="https://help.github.com/en/github/collaborating-with-issues-and-pull-requests/commenting-on-a-pull-request" class="external-link" target="_blank">🚮 🏤 ⏮️ 🔀 🔑</a> ♻ 🚲 📨.
+
+✅ 🩺 🔃 <a href="https://help.github.com/en/github/collaborating-with-issues-and-pull-requests/about-pull-request-reviews" class="external-link" target="_blank">❎ 🚲 📨 📄</a> ✔ ⚫️ ⚖️ 📨 🔀.
- ✅ 🩺 🔃 <a href="https://help.github.com/en/github/collaborating-with-issues-and-pull-requests/about-pull-request-reviews" class="external-link" target="_blank">❎ 🚲 📨 📄</a> ✔ ⚫️ ⚖️ 📨 🔀.
+///
* ✅ <a href="https://github.com/fastapi/fastapi/issues" class="external-link" target="_blank">❔</a> 👀 🚥 📤 1️⃣ 🛠️ ✍ 👆 🇪🇸.
💼 🇪🇸, 2️⃣-🔤 📟 `es`. , 📁 🇪🇸 ✍ 🔎 `docs/es/`.
-!!! tip
- 👑 ("🛂") 🇪🇸 🇪🇸, 🔎 `docs/en/`.
+/// tip
+
+👑 ("🛂") 🇪🇸 🇪🇸, 🔎 `docs/en/`.
+
+///
🔜 🏃 🖖 💽 🩺 🇪🇸:
docs/es/docs/features.md
```
-!!! tip
- 👀 👈 🕴 🔀 ➡ & 📁 📛 🇪🇸 📟, ⚪️➡️ `en` `es`.
+/// tip
+
+👀 👈 🕴 🔀 ➡ & 📁 📛 🇪🇸 📟, ⚪️➡️ `en` `es`.
+
+///
* 🔜 📂 ⬜ 📁 📁 🇪🇸:
🔜 👆 💪 ✅ 👆 📟 👨🎨 ⏳ ✍ 📁 `docs/ht/`.
-!!! tip
- ✍ 🥇 🚲 📨 ⏮️ 👉, ⚒ 🆙 📳 🆕 🇪🇸, ⏭ ❎ ✍.
+/// tip
+
+✍ 🥇 🚲 📨 ⏮️ 👉, ⚒ 🆙 📳 🆕 🇪🇸, ⏭ ❎ ✍.
+
+👈 🌌 🎏 💪 ℹ ⏮️ 🎏 📃 ⏪ 👆 👷 🔛 🥇 🕐. 👶
- 👈 🌌 🎏 💪 ℹ ⏮️ 🎏 📃 ⏪ 👆 👷 🔛 🥇 🕐. 👶
+///
▶️ ✍ 👑 📃, `docs/ht/index.md`.
✋️ 👈 💼 ⏮️ 🤙 👎 ❌ 👈 💥 🏃♂ **🛠️**, 👆 🔜 💚 🔢 🦲 👈 🈚 **🔁** 🛠️, 🌘 👩❤👨 🕰...
-!!! tip
- ...👐 🚥 🎂 🈸 **💥 ⏪** ⚫️ 🎲 🚫 ⚒ 🔑 🚧 🔁 ⚫️ ♾. ✋️ 📚 💼, 👆 🔜 🎲 👀 ⚫️ ⏮️ 🛠️, ⚖️ 🌘 ▶️️ ⏮️ 🛠️.
+/// tip
- ➡️ 🎯 🔛 👑 💼, 🌐❔ ⚫️ 💪 💥 🍕 🎯 💼 **🔮**, & ⚫️ ⚒ 🔑 ⏏ ⚫️.
+...👐 🚥 🎂 🈸 **💥 ⏪** ⚫️ 🎲 🚫 ⚒ 🔑 🚧 🔁 ⚫️ ♾. ✋️ 📚 💼, 👆 🔜 🎲 👀 ⚫️ ⏮️ 🛠️, ⚖️ 🌘 ▶️️ ⏮️ 🛠️.
+
+➡️ 🎯 🔛 👑 💼, 🌐❔ ⚫️ 💪 💥 🍕 🎯 💼 **🔮**, & ⚫️ ⚒ 🔑 ⏏ ⚫️.
+
+///
👆 🔜 🎲 💚 ✔️ 👜 🈚 🔁 👆 🈸 **🔢 🦲**, ↩️ 👈 ☝, 🎏 🈸 ⏮️ Uvicorn & 🐍 ⏪ 💥, 📤 🕳 🎏 📟 🎏 📱 👈 💪 🕳 🔃 ⚫️.
* **☁ 🐕🦺** 👈 🍵 👉 👆
* ☁ 🐕🦺 🔜 🎲 **🍵 🧬 👆**. ⚫️ 🔜 🎲 ➡️ 👆 🔬 **🛠️ 🏃**, ⚖️ **📦 🖼** ⚙️, 🙆 💼, ⚫️ 🔜 🌅 🎲 **👁 Uvicorn 🛠️**, & ☁ 🐕🦺 🔜 🈚 🔁 ⚫️.
-!!! tip
- 🚫 😟 🚥 👫 🏬 🔃 **📦**, ☁, ⚖️ Kubernetes 🚫 ⚒ 📚 🔑.
+/// tip
+
+🚫 😟 🚥 👫 🏬 🔃 **📦**, ☁, ⚖️ Kubernetes 🚫 ⚒ 📚 🔑.
+
+👤 🔜 💬 👆 🌅 🔃 📦 🖼, ☁, Kubernetes, ♒️. 🔮 📃: [FastAPI 📦 - ☁](docker.md){.internal-link target=_blank}.
- 👤 🔜 💬 👆 🌅 🔃 📦 🖼, ☁, Kubernetes, ♒️. 🔮 📃: [FastAPI 📦 - ☁](docker.md){.internal-link target=_blank}.
+///
## ⏮️ 🔁 ⏭ ▶️
↗️, 📤 💼 🌐❔ 📤 🙅♂ ⚠ 🏃 ⏮️ 🔁 💗 🕰, 👈 💼, ⚫️ 📚 ⏩ 🍵.
-!!! tip
- , ✔️ 🤯 👈 ⚓️ 🔛 👆 🖥, 💼 👆 **5️⃣📆 🚫 💪 🙆 ⏮️ 🔁** ⏭ ▶️ 👆 🈸.
+/// tip
- 👈 💼, 👆 🚫🔜 ✔️ 😟 🔃 🙆 👉. 🤷
+, ✔️ 🤯 👈 ⚓️ 🔛 👆 🖥, 💼 👆 **5️⃣📆 🚫 💪 🙆 ⏮️ 🔁** ⏭ ▶️ 👆 🈸.
+
+👈 💼, 👆 🚫🔜 ✔️ 😟 🔃 🙆 👉. 🤷
+
+///
### 🖼 ⏮️ 🔁 🎛
* 🎉 ✍ 👈 🏃 ⏮️ 🔁 & ⤴️ ▶️ 👆 🈸
* 👆 🔜 💪 🌌 ▶️/⏏ *👈* 🎉 ✍, 🔍 ❌, ♒️.
-!!! tip
- 👤 🔜 🤝 👆 🌅 🧱 🖼 🔨 👉 ⏮️ 📦 🔮 📃: [FastAPI 📦 - ☁](docker.md){.internal-link target=_blank}.
+/// tip
+
+👤 🔜 🤝 👆 🌅 🧱 🖼 🔨 👉 ⏮️ 📦 🔮 📃: [FastAPI 📦 - ☁](docker.md){.internal-link target=_blank}.
+
+///
## ℹ 🛠️
⚙️ 💾 📦 ✔️ 📚 📈 ✅ **💂♂**, **🔬**, **🦁**, & 🎏.
-!!! tip
- 🏃 & ⏪ 💭 👉 💩 ❓ 🦘 [`Dockerfile` 🔛 👶](#fastapi).
+/// tip
+
+🏃 & ⏪ 💭 👉 💩 ❓ 🦘 [`Dockerfile` 🔛 👶](#fastapi).
+
+///
<details>
<summary>📁 🎮 👶</summary>
</div>
-!!! info
- 📤 🎏 📁 & 🧰 🔬 & ❎ 📦 🔗.
+/// info
+
+📤 🎏 📁 & 🧰 🔬 & ❎ 📦 🔗.
- 👤 🔜 🎦 👆 🖼 ⚙️ 🎶 ⏪ 📄 🔛. 👶
+👤 🔜 🎦 👆 🖼 ⚙️ 🎶 ⏪ 📄 🔛. 👶
+
+///
### ✍ **FastAPI** 📟
↩️ 📋 🔜 ▶️ `/code` & 🔘 ⚫️ 📁 `./app` ⏮️ 👆 📟, **Uvicorn** 🔜 💪 👀 & **🗄** `app` ⚪️➡️ `app.main`.
-!!! tip
- 📄 ⚫️❔ 🔠 ⏸ 🔨 🖊 🔠 🔢 💭 📟. 👶
+/// tip
+
+📄 ⚫️❔ 🔠 ⏸ 🔨 🖊 🔠 🔢 💭 📟. 👶
+
+///
👆 🔜 🔜 ✔️ 📁 📊 💖:
</div>
-!!! tip
- 👀 `.` 🔚, ⚫️ 🌓 `./`, ⚫️ 💬 ☁ 📁 ⚙️ 🏗 📦 🖼.
+/// tip
+
+👀 `.` 🔚, ⚫️ 🌓 `./`, ⚫️ 💬 ☁ 📁 ⚙️ 🏗 📦 🖼.
+
+👉 💼, ⚫️ 🎏 ⏮️ 📁 (`.`).
- 👉 💼, ⚫️ 🎏 ⏮️ 📁 (`.`).
+///
### ▶️ ☁ 📦
⚫️ 💪 ➕1️⃣ 📦, 🖼 ⏮️ <a href="https://traefik.io/" class="external-link" target="_blank">Traefik</a>, 🚚 **🇺🇸🔍** & **🏧** 🛠️ **📄**.
-!!! tip
- Traefik ✔️ 🛠️ ⏮️ ☁, Kubernetes, & 🎏, ⚫️ 📶 ⏩ ⚒ 🆙 & 🔗 🇺🇸🔍 👆 📦 ⏮️ ⚫️.
+/// tip
+
+Traefik ✔️ 🛠️ ⏮️ ☁, Kubernetes, & 🎏, ⚫️ 📶 ⏩ ⚒ 🆙 & 🔗 🇺🇸🔍 👆 📦 ⏮️ ⚫️.
+
+///
👐, 🇺🇸🔍 💪 🍵 ☁ 🐕🦺 1️⃣ 👫 🐕🦺 (⏪ 🏃 🈸 📦).
👉 🦲 🔜 ✊ **📐** 📨 & 📎 👈 👪 👨🏭 (🤞) **⚖** 🌌, ⚫️ 🛎 🤙 **📐 ⚙**.
-!!! tip
- 🎏 **🤝 ❎ 🗳** 🦲 ⚙️ 🇺🇸🔍 🔜 🎲 **📐 ⚙**.
+/// tip
+
+🎏 **🤝 ❎ 🗳** 🦲 ⚙️ 🇺🇸🔍 🔜 🎲 **📐 ⚙**.
+
+///
& 🕐❔ 👷 ⏮️ 📦, 🎏 ⚙️ 👆 ⚙️ ▶️ & 🛠️ 👫 🔜 ⏪ ✔️ 🔗 🧰 📶 **🕸 📻** (✅ 🇺🇸🔍 📨) ⚪️➡️ 👈 **📐 ⚙** (👈 💪 **🤝 ❎ 🗳**) 📦(Ⓜ) ⏮️ 👆 📱.
🚥 👆 ✔️ **💗 📦**, 🎲 🔠 1️⃣ 🏃 **👁 🛠️** (🖼, **Kubernetes** 🌑), ⤴️ 👆 🔜 🎲 💚 ✔️ **🎏 📦** 🔨 👷 **⏮️ 📶** 👁 📦, 🏃 👁 🛠️, **⏭** 🏃 🔁 👨🏭 📦.
-!!! info
- 🚥 👆 ⚙️ Kubernetes, 👉 🔜 🎲 <a href="https://kubernetes.io/docs/concepts/workloads/pods/init-containers/" class="external-link" target="_blank">🕑 📦</a>.
+/// info
+
+🚥 👆 ⚙️ Kubernetes, 👉 🔜 🎲 <a href="https://kubernetes.io/docs/concepts/workloads/pods/init-containers/" class="external-link" target="_blank">🕑 📦</a>.
+
+///
🚥 👆 ⚙️ 💼 📤 🙅♂ ⚠ 🏃♂ 👈 ⏮️ 📶 **💗 🕰 🔗** (🖼 🚥 👆 🚫 🏃 💽 🛠️, ✋️ ✅ 🚥 💽 🔜), ⤴️ 👆 💪 🚮 👫 🔠 📦 ▶️️ ⏭ ▶️ 👑 🛠️.
* <a href="https://github.com/tiangolo/uvicorn-gunicorn-fastapi-docker" class="external-link" target="_blank">tiangolo/uvicorn-🐁-fastapi</a>.
-!!! warning
- 📤 ↕ 🤞 👈 👆 **🚫** 💪 👉 🧢 🖼 ⚖️ 🙆 🎏 🎏 1️⃣, & 🔜 👻 📆 🏗 🖼 ⚪️➡️ 🖌 [🔬 🔛: 🏗 ☁ 🖼 FastAPI](#fastapi).
+/// warning
+
+📤 ↕ 🤞 👈 👆 **🚫** 💪 👉 🧢 🖼 ⚖️ 🙆 🎏 🎏 1️⃣, & 🔜 👻 📆 🏗 🖼 ⚪️➡️ 🖌 [🔬 🔛: 🏗 ☁ 🖼 FastAPI](#fastapi).
+
+///
👉 🖼 ✔️ **🚘-📳** 🛠️ 🔌 ⚒ **🔢 👨🏭 🛠️** ⚓️ 🔛 💽 🐚 💪.
⚫️ 🐕🦺 🏃 <a href="https://github.com/tiangolo/uvicorn-gunicorn-fastapi-docker#pre_start_path" class="external-link" target="_blank">**⏮️ 🔁 ⏭ ▶️**</a> ⏮️ ✍.
-!!! tip
- 👀 🌐 📳 & 🎛, 🚶 ☁ 🖼 📃: <a href="https://github.com/tiangolo/uvicorn-gunicorn-fastapi-docker" class="external-link" target="_blank">Tiangolo/uvicorn-🐁-fastapi</a>.
+/// tip
+
+👀 🌐 📳 & 🎛, 🚶 ☁ 🖼 📃: <a href="https://github.com/tiangolo/uvicorn-gunicorn-fastapi-docker" class="external-link" target="_blank">Tiangolo/uvicorn-🐁-fastapi</a>.
+
+///
### 🔢 🛠️ 🔛 🛂 ☁ 🖼
1️⃣1️⃣. 🏃 `uvicorn` 📋, 💬 ⚫️ ⚙️ `app` 🎚 🗄 ⚪️➡️ `app.main`.
-!!! tip
- 🖊 💭 🔢 👀 ⚫️❔ 🔠 ⏸ 🔨.
+/// tip
+
+🖊 💭 🔢 👀 ⚫️❔ 🔠 ⏸ 🔨.
+
+///
**☁ ▶️** 🍕 `Dockerfile` 👈 👷 **🍕 📦 🖼** 👈 🕴 ⚙️ 🏗 📁 ⚙️ ⏪.
✋️ ⚫️ 🌌 🌖 🏗 🌘 👈.
-!!! tip
- 🚥 👆 🏃 ⚖️ 🚫 💅, 😣 ⏮️ ⏭ 📄 🔁 🔁 👩🌾 ⚒ 🌐 🆙 ⏮️ 🎏 ⚒.
+/// tip
+
+🚥 👆 🏃 ⚖️ 🚫 💅, 😣 ⏮️ ⏭ 📄 🔁 🔁 👩🌾 ⚒ 🌐 🆙 ⏮️ 🎏 ⚒.
+
+///
**💡 🔰 🇺🇸🔍**, ⚪️➡️ 🏬 🤔, ✅ <a href="https://howhttps.works/" class="external-link" target="_blank">https://howhttps.works/</a>.
👆 🔜 🎲 👉 🕐, 🥇 🕰, 🕐❔ ⚒ 🌐 🆙.
-!!! tip
- 👉 🆔 📛 🍕 🌌 ⏭ 🇺🇸🔍, ✋️ 🌐 🪀 🔛 🆔 & 📢 📢, ⚫️ 💸 💬 ⚫️ 📥.
+/// tip
+
+👉 🆔 📛 🍕 🌌 ⏭ 🇺🇸🔍, ✋️ 🌐 🪀 🔛 🆔 & 📢 📢, ⚫️ 💸 💬 ⚫️ 📥.
+
+///
### 🏓
& 👈 ⚫️❔ **🇺🇸🔍** , ⚫️ ✅ **🇺🇸🔍** 🔘 **🔐 🤝 🔗** ↩️ 😁 (💽) 🕸 🔗.
-!!! tip
- 👀 👈 🔐 📻 🔨 **🕸 🎚**, 🚫 🇺🇸🔍 🎚.
+/// tip
+
+👀 👈 🔐 📻 🔨 **🕸 🎚**, 🚫 🇺🇸🔍 🎚.
+
+///
### 🇺🇸🔍 📨
👆 💪 ❎ 🔫 🔗 💽 ⏮️:
-=== "Uvicorn"
+//// tab | Uvicorn
- * <a href="https://www.uvicorn.org/" class="external-link" target="_blank">Uvicorn</a>, 🌩-⏩ 🔫 💽, 🏗 🔛 uvloop & httptool.
+* <a href="https://www.uvicorn.org/" class="external-link" target="_blank">Uvicorn</a>, 🌩-⏩ 🔫 💽, 🏗 🔛 uvloop & httptool.
- <div class="termy">
+<div class="termy">
+
+```console
+$ pip install "uvicorn[standard]"
- ```console
- $ pip install "uvicorn[standard]"
+---> 100%
+```
+
+</div>
- ---> 100%
- ```
+/// tip
- </div>
+❎ `standard`, Uvicorn 🔜 ❎ & ⚙️ 👍 ➕ 🔗.
- !!! tip
- ❎ `standard`, Uvicorn 🔜 ❎ & ⚙️ 👍 ➕ 🔗.
+👈 ✅ `uvloop`, ↕-🎭 💧-♻ `asyncio`, 👈 🚚 🦏 🛠️ 🎭 📈.
- 👈 ✅ `uvloop`, ↕-🎭 💧-♻ `asyncio`, 👈 🚚 🦏 🛠️ 🎭 📈.
+///
-=== "Hypercorn"
+////
- * <a href="https://github.com/pgjones/hypercorn" class="external-link" target="_blank">Hypercorn</a>, 🔫 💽 🔗 ⏮️ 🇺🇸🔍/2️⃣.
+//// tab | Hypercorn
- <div class="termy">
+* <a href="https://github.com/pgjones/hypercorn" class="external-link" target="_blank">Hypercorn</a>, 🔫 💽 🔗 ⏮️ 🇺🇸🔍/2️⃣.
- ```console
- $ pip install hypercorn
+<div class="termy">
+
+```console
+$ pip install hypercorn
+
+---> 100%
+```
- ---> 100%
- ```
+</div>
- </div>
+...⚖️ 🙆 🎏 🔫 💽.
- ...⚖️ 🙆 🎏 🔫 💽.
+////
## 🏃 💽 📋
👆 💪 ⤴️ 🏃 👆 🈸 🎏 🌌 👆 ✔️ ⌛ 🔰, ✋️ 🍵 `--reload` 🎛, ✅:
-=== "Uvicorn"
+//// tab | Uvicorn
- <div class="termy">
+<div class="termy">
- ```console
- $ uvicorn main:app --host 0.0.0.0 --port 80
+```console
+$ uvicorn main:app --host 0.0.0.0 --port 80
- <span style="color: green;">INFO</span>: Uvicorn running on http://0.0.0.0:80 (Press CTRL+C to quit)
- ```
+<span style="color: green;">INFO</span>: Uvicorn running on http://0.0.0.0:80 (Press CTRL+C to quit)
+```
- </div>
+</div>
+
+////
-=== "Hypercorn"
+//// tab | Hypercorn
- <div class="termy">
+<div class="termy">
+
+```console
+$ hypercorn main:app --bind 0.0.0.0:80
+
+Running on 0.0.0.0:8080 over http (CTRL + C to quit)
+```
+
+</div>
- ```console
- $ hypercorn main:app --bind 0.0.0.0:80
+////
- Running on 0.0.0.0:8080 over http (CTRL + C to quit)
- ```
+/// warning
- </div>
+💭 ❎ `--reload` 🎛 🚥 👆 ⚙️ ⚫️.
-!!! warning
- 💭 ❎ `--reload` 🎛 🚥 👆 ⚙️ ⚫️.
+ `--reload` 🎛 🍴 🌅 🌅 ℹ, 🌅 ⚠, ♒️.
- `--reload` 🎛 🍴 🌅 🌅 ℹ, 🌅 ⚠, ♒️.
+⚫️ ℹ 📚 ⏮️ **🛠️**, ✋️ 👆 **🚫🔜 🚫** ⚙️ ⚫️ **🏭**.
- ⚫️ ℹ 📚 ⏮️ **🛠️**, ✋️ 👆 **🚫🔜 🚫** ⚙️ ⚫️ **🏭**.
+///
## Hypercorn ⏮️ 🎻
📥 👤 🔜 🎦 👆 ❔ ⚙️ <a href="https://gunicorn.org/" class="external-link" target="_blank">**🐁**</a> ⏮️ **Uvicorn 👨🏭 🛠️**.
-!!! info
- 🚥 👆 ⚙️ 📦, 🖼 ⏮️ ☁ ⚖️ Kubernetes, 👤 🔜 💬 👆 🌅 🔃 👈 ⏭ 📃: [FastAPI 📦 - ☁](docker.md){.internal-link target=_blank}.
+/// info
- 🎯, 🕐❔ 🏃 🔛 **Kubernetes** 👆 🔜 🎲 **🚫** 💚 ⚙️ 🐁 & ↩️ 🏃 **👁 Uvicorn 🛠️ 📍 📦**, ✋️ 👤 🔜 💬 👆 🔃 ⚫️ ⏪ 👈 📃.
+🚥 👆 ⚙️ 📦, 🖼 ⏮️ ☁ ⚖️ Kubernetes, 👤 🔜 💬 👆 🌅 🔃 👈 ⏭ 📃: [FastAPI 📦 - ☁](docker.md){.internal-link target=_blank}.
+
+🎯, 🕐❔ 🏃 🔛 **Kubernetes** 👆 🔜 🎲 **🚫** 💚 ⚙️ 🐁 & ↩️ 🏃 **👁 Uvicorn 🛠️ 📍 📦**, ✋️ 👤 🔜 💬 👆 🔃 ⚫️ ⏪ 👈 📃.
+
+///
## 🐁 ⏮️ Uvicorn 👨🏭
FastAPI ⏩ 🏛 👈 🙆 "🐛" ⏬ 🔀 🐛 🔧 & 🚫-💔 🔀.
-!!! tip
- "🐛" 🏁 🔢, 🖼, `0.2.3`, 🐛 ⏬ `3`.
+/// tip
+
+"🐛" 🏁 🔢, 🖼, `0.2.3`, 🐛 ⏬ `3`.
+
+///
, 👆 🔜 💪 📌 ⏬ 💖:
💔 🔀 & 🆕 ⚒ 🚮 "🇺🇲" ⏬.
-!!! tip
- "🇺🇲" 🔢 🖕, 🖼, `0.2.3`, 🇺🇲 ⏬ `2`.
+/// tip
+
+"🇺🇲" 🔢 🖕, 🖼, `0.2.3`, 🇺🇲 ⏬ `2`.
+
+///
## ♻ FastAPI ⏬
📥 ❌ 📇 👫.
-!!! tip
- 🚥 👆 ✔️ 📄, 🏗, 🧰, ⚖️ 🕳 🔗 **FastAPI** 👈 🚫 📇 📥, ✍ <a href="https://github.com/fastapi/fastapi/edit/master/docs/en/data/external_links.yml" class="external-link" target="_blank">🚲 📨 ❎ ⚫️</a>.
+/// tip
+
+🚥 👆 ✔️ 📄, 🏗, 🧰, ⚖️ 🕳 🔗 **FastAPI** 👈 🚫 📇 📥, ✍ <a href="https://github.com/fastapi/fastapi/edit/master/docs/en/data/external_links.yml" class="external-link" target="_blank">🚲 📨 ❎ ⚫️</a>.
+
+///
## 📄
my_second_user: User = User(**second_user_data)
```
-!!! info
- `**second_user_data` ⛓:
+/// info
- 🚶♀️ 🔑 & 💲 `second_user_data` #️⃣ 🔗 🔑-💲 ❌, 🌓: `User(id=4, name="Mary", joined="2018-11-30")`
+`**second_user_data` ⛓:
+
+🚶♀️ 🔑 & 💲 `second_user_data` #️⃣ 🔗 🔑-💲 ❌, 🌓: `User(id=4, name="Mary", joined="2018-11-30")`
+
+///
### 👨🎨 🐕🦺
* ⤴️ **🏤** 💬 👈 👆 👈, 👈 ❔ 👤 🔜 💭 👆 🤙 ✅ ⚫️.
-!!! info
- 👐, 👤 💪 🚫 🎯 💙 🎸 👈 ✔️ 📚 ✔.
+/// info
- 📚 🕰 ⚫️ ✔️ 🔨 👈 📤 🎸 ⏮️ 3️⃣, 5️⃣ ⚖️ 🌅 ✔, 🎲 ↩️ 📛 😌, ✋️ 🕐❔ 👤 ✅ 🎸, 👫 🤙 💔, ✔️ 🐛, ⚖️ 🚫 ❎ ⚠ 👫 🛄 ❎. 👶
+👐, 👤 💪 🚫 🎯 💙 🎸 👈 ✔️ 📚 ✔.
- , ⚫️ 🤙 ⚠ 👈 👆 🤙 ✍ & 🏃 📟, & ➡️ 👤 💭 🏤 👈 👆. 👶
+📚 🕰 ⚫️ ✔️ 🔨 👈 📤 🎸 ⏮️ 3️⃣, 5️⃣ ⚖️ 🌅 ✔, 🎲 ↩️ 📛 😌, ✋️ 🕐❔ 👤 ✅ 🎸, 👫 🤙 💔, ✔️ 🐛, ⚖️ 🚫 ❎ ⚠ 👫 🛄 ❎. 👶
+
+, ⚫️ 🤙 ⚠ 👈 👆 🤙 ✍ & 🏃 📟, & ➡️ 👤 💭 🏤 👈 👆. 👶
+
+///
* 🚥 🇵🇷 💪 📉 🌌, 👆 💪 💭 👈, ✋️ 📤 🙅♂ 💪 💁♂️ 😟, 📤 5️⃣📆 📚 🤔 ☝ 🎑 (& 👤 🔜 ✔️ 👇 👍 👍 👶), ⚫️ 👻 🚥 👆 💪 🎯 🔛 ⚛ 👜.
🛑 👶 <a href="https://discord.gg/VQjSZaeJmf" class="external-link" target="_blank">😧 💬 💽</a> 👶 & 🤙 👅 ⏮️ 🎏 FastAPI 👪.
-!!! tip
- ❔, 💭 👫 <a href="https://github.com/fastapi/fastapi/discussions/new?category=questions" class="external-link" target="_blank">📂 💬</a>, 📤 🌅 👍 🤞 👆 🔜 📨 ℹ [FastAPI 🕴](fastapi-people.md#_2){.internal-link target=_blank}.
+/// tip
+
+❔, 💭 👫 <a href="https://github.com/fastapi/fastapi/discussions/new?category=questions" class="external-link" target="_blank">📂 💬</a>, 📤 🌅 👍 🤞 👆 🔜 📨 ℹ [FastAPI 🕴](fastapi-people.md#_2){.internal-link target=_blank}.
+
+⚙️ 💬 🕴 🎏 🏢 💬.
- ⚙️ 💬 🕴 🎏 🏢 💬.
+///
### 🚫 ⚙️ 💬 ❔
🖼, 🚥 👆 💚 ✍ ⚖️ 🔬 📨 💪 ⏭ ⚫️ 🛠️ 👆 🈸.
-!!! danger
- 👉 "🏧" ⚒.
+/// danger
- 🚥 👆 ▶️ ⏮️ **FastAPI** 👆 💪 💚 🚶 👉 📄.
+👉 "🏧" ⚒.
+
+🚥 👆 ▶️ ⏮️ **FastAPI** 👆 💪 💚 🚶 👉 📄.
+
+///
## ⚙️ 💼
### ✍ 🛃 `GzipRequest` 🎓
-!!! tip
- 👉 🧸 🖼 🎦 ❔ ⚫️ 👷, 🚥 👆 💪 🗜 🐕🦺, 👆 💪 ⚙️ 🚚 [`GzipMiddleware`](../advanced/middleware.md#gzipmiddleware){.internal-link target=_blank}.
+/// tip
+
+👉 🧸 🖼 🎦 ❔ ⚫️ 👷, 🚥 👆 💪 🗜 🐕🦺, 👆 💪 ⚙️ 🚚 [`GzipMiddleware`](../advanced/middleware.md#gzipmiddleware){.internal-link target=_blank}.
+
+///
🥇, 👥 ✍ `GzipRequest` 🎓, ❔ 🔜 📁 `Request.body()` 👩🔬 🗜 💪 🔍 ☑ 🎚.
{!../../../docs_src/custom_request_and_route/tutorial001.py!}
```
-!!! note "📡 ℹ"
- `Request` ✔️ `request.scope` 🔢, 👈 🐍 `dict` ⚗ 🗃 🔗 📨.
+/// note | "📡 ℹ"
- `Request` ✔️ `request.receive`, 👈 🔢 "📨" 💪 📨.
+`Request` ✔️ `request.scope` 🔢, 👈 🐍 `dict` ⚗ 🗃 🔗 📨.
- `scope` `dict` & `receive` 🔢 👯♂️ 🍕 🔫 🔧.
+ `Request` ✔️ `request.receive`, 👈 🔢 "📨" 💪 📨.
- & 👈 2️⃣ 👜, `scope` & `receive`, ⚫️❔ 💪 ✍ 🆕 `Request` 👐.
+ `scope` `dict` & `receive` 🔢 👯♂️ 🍕 🔫 🔧.
- 💡 🌅 🔃 `Request` ✅ <a href="https://www.starlette.io/requests/" class="external-link" target="_blank">💃 🩺 🔃 📨</a>.
+ & 👈 2️⃣ 👜, `scope` & `receive`, ⚫️❔ 💪 ✍ 🆕 `Request` 👐.
+
+💡 🌅 🔃 `Request` ✅ <a href="https://www.starlette.io/requests/" class="external-link" target="_blank">💃 🩺 🔃 📨</a>.
+
+///
🕴 👜 🔢 📨 `GzipRequest.get_route_handler` 🔨 🎏 🗜 `Request` `GzipRequest`.
## 🔐 📨 💪 ⚠ 🐕🦺
-!!! tip
- ❎ 👉 🎏 ⚠, ⚫️ 🎲 📚 ⏩ ⚙️ `body` 🛃 🐕🦺 `RequestValidationError` ([🚚 ❌](../tutorial/handling-errors.md#requestvalidationerror){.internal-link target=_blank}).
+/// tip
+
+❎ 👉 🎏 ⚠, ⚫️ 🎲 📚 ⏩ ⚙️ `body` 🛃 🐕🦺 `RequestValidationError` ([🚚 ❌](../tutorial/handling-errors.md#requestvalidationerror){.internal-link target=_blank}).
+
+✋️ 👉 🖼 ☑ & ⚫️ 🎦 ❔ 🔗 ⏮️ 🔗 🦲.
- ✋️ 👉 🖼 ☑ & ⚫️ 🎦 ❔ 🔗 ⏮️ 🔗 🦲.
+///
👥 💪 ⚙️ 👉 🎏 🎯 🔐 📨 💪 ⚠ 🐕🦺.
# ↔ 🗄
-!!! warning
- 👉 👍 🏧 ⚒. 👆 🎲 💪 🚶 ⚫️.
+/// warning
- 🚥 👆 📄 🔰 - 👩💻 🦮, 👆 💪 🎲 🚶 👉 📄.
+👉 👍 🏧 ⚒. 👆 🎲 💪 🚶 ⚫️.
- 🚥 👆 ⏪ 💭 👈 👆 💪 🔀 🏗 🗄 🔗, 😣 👂.
+🚥 👆 📄 🔰 - 👩💻 🦮, 👆 💪 🎲 🚶 👉 📄.
+
+🚥 👆 ⏪ 💭 👈 👆 💪 🔀 🏗 🗄 🔗, 😣 👂.
+
+///
📤 💼 🌐❔ 👆 💪 💪 🔀 🏗 🗄 🔗.
👆 💪 🌀 😐 FastAPI *➡ 🛠️* ⏮️ 🕹 🔛 🎏 🈸.
-!!! tip
- **🕹** ❎ 📶 🎯 ⚙️ 💼.
+/// tip
- ⚫️ ✔️ **📈** & **⚠** 🕐❔ 🔬 ⚠ **🕸 🔗**.
+**🕹** ❎ 📶 🎯 ⚙️ 💼.
- ⚒ 💭 👆 🔬 🚥 **💰** 👆 ⚙️ 💼 ⚖ **👐**. 👶
+⚫️ ✔️ **📈** & **⚠** 🕐❔ 🔬 ⚠ **🕸 🔗**.
+
+⚒ 💭 👆 🔬 🚥 **💰** 👆 ⚙️ 💼 ⚖ **👐**. 👶
+
+///
## 🕹 🗃
⚫️ 😢 ⚪️➡️ 💃, ✋️ 🚥 👆 ✔️ 📟 👈 ⚙️ ⚫️, 👆 💪 💪 **↔** <a href="https://github.com/ciscorn/starlette-graphene3" class="external-link" target="_blank">💃-Graphene3️⃣</a>, 👈 📔 🎏 ⚙️ 💼 & ✔️ **🌖 🌓 🔢**.
-!!! tip
- 🚥 👆 💪 🕹, 👤 🔜 👍 👆 ✅ 👅 <a href="https://strawberry.rocks/" class="external-link" target="_blank">🍓</a>, ⚫️ ⚓️ 🔛 🆎 ✍ ↩️ 🛃 🎓 & 🆎.
+/// tip
+
+🚥 👆 💪 🕹, 👤 🔜 👍 👆 ✅ 👅 <a href="https://strawberry.rocks/" class="external-link" target="_blank">🍓</a>, ⚫️ ⚓️ 🔛 🆎 ✍ ↩️ 🛃 🎓 & 🆎.
+
+///
## 💡 🌅
# 🗄 (🔗) 💽 ⏮️ 🏒
-!!! warning
- 🚥 👆 ▶️, 🔰 [🗄 (🔗) 💽](../tutorial/sql-databases.md){.internal-link target=_blank} 👈 ⚙️ 🇸🇲 🔜 🥃.
+/// warning
- 💭 🆓 🚶 👉.
+🚥 👆 ▶️, 🔰 [🗄 (🔗) 💽](../tutorial/sql-databases.md){.internal-link target=_blank} 👈 ⚙️ 🇸🇲 🔜 🥃.
+
+💭 🆓 🚶 👉.
+
+///
🚥 👆 ▶️ 🏗 ⚪️➡️ 🖌, 👆 🎲 👻 📆 ⏮️ 🇸🇲 🐜 ([🗄 (🔗) 💽](../tutorial/sql-databases.md){.internal-link target=_blank}), ⚖️ 🙆 🎏 🔁 🐜.
🚥 👆 ⏪ ✔️ 📟 🧢 👈 ⚙️ <a href="https://docs.peewee-orm.com/en/latest/" class="external-link" target="_blank">🏒 🐜</a>, 👆 💪 ✅ 📥 ❔ ⚙️ ⚫️ ⏮️ **FastAPI**.
-!!! warning "🐍 3️⃣.7️⃣ ➕ ✔"
- 👆 🔜 💪 🐍 3️⃣.7️⃣ ⚖️ 🔛 🔒 ⚙️ 🏒 ⏮️ FastAPI.
+/// warning | "🐍 3️⃣.7️⃣ ➕ ✔"
+
+👆 🔜 💪 🐍 3️⃣.7️⃣ ⚖️ 🔛 🔒 ⚙️ 🏒 ⏮️ FastAPI.
+
+///
## 🏒 🔁
👐, ⚫️ 💪 ⚫️, & 📥 👆 🔜 👀 ⚫️❔ ⚫️❔ 📟 👆 ✔️ 🚮 💪 ⚙️ 🏒 ⏮️ FastAPI.
-!!! note "📡 ℹ"
- 👆 💪 ✍ 🌅 🔃 🏒 🧍 🔃 🔁 🐍 <a href="https://docs.peewee-orm.com/en/latest/peewee/database.html#async-with-gevent" class="external-link" target="_blank">🩺</a>, <a href="https://github.com/coleifer/peewee/issues/263#issuecomment-517347032" class="external-link" target="_blank">❔</a>, <a href="https://github.com/coleifer/peewee/pull/2072#issuecomment-563215132" class="external-link" target="_blank">🇵🇷</a>.
+/// note | "📡 ℹ"
+
+👆 💪 ✍ 🌅 🔃 🏒 🧍 🔃 🔁 🐍 <a href="https://docs.peewee-orm.com/en/latest/peewee/database.html#async-with-gevent" class="external-link" target="_blank">🩺</a>, <a href="https://github.com/coleifer/peewee/issues/263#issuecomment-517347032" class="external-link" target="_blank">❔</a>, <a href="https://github.com/coleifer/peewee/pull/2072#issuecomment-563215132" class="external-link" target="_blank">🇵🇷</a>.
+
+///
## 🎏 📱
{!../../../docs_src/sql_databases_peewee/sql_app/database.py!}
```
-!!! tip
- ✔️ 🤯 👈 🚥 👆 💚 ⚙️ 🎏 💽, 💖 ✳, 👆 🚫 🚫 🔀 🎻. 👆 🔜 💪 ⚙️ 🎏 🏒 💽 🎓.
+/// tip
+
+✔️ 🤯 👈 🚥 👆 💚 ⚙️ 🎏 💽, 💖 ✳, 👆 🚫 🚫 🔀 🎻. 👆 🔜 💪 ⚙️ 🎏 🏒 💽 🎓.
+
+///
#### 🗒
...⚫️ 💪 🕴 `SQLite`.
-!!! info "📡 ℹ"
+/// info | "📡 ℹ"
- ⚫️❔ 🎏 📡 ℹ [🗄 (🔗) 💽](../tutorial/sql-databases.md#_7){.internal-link target=_blank} ✔.
+⚫️❔ 🎏 📡 ℹ [🗄 (🔗) 💽](../tutorial/sql-databases.md#_7){.internal-link target=_blank} ✔.
+
+///
### ⚒ 🏒 🔁-🔗 `PeeweeConnectionState`
& `threading.local` 🚫 🔗 ⏮️ 🆕 🔁 ⚒ 🏛 🐍.
-!!! note "📡 ℹ"
- `threading.local` ⚙️ ✔️ "🎱" 🔢 👈 ✔️ 🎏 💲 🔠 🧵.
+/// note | "📡 ℹ"
+
+`threading.local` ⚙️ ✔️ "🎱" 🔢 👈 ✔️ 🎏 💲 🔠 🧵.
- 👉 ⚠ 🗝 🛠️ 🏗 ✔️ 1️⃣ 👁 🧵 📍 📨, 🙅♂ 🌖, 🙅♂ 🌘.
+👉 ⚠ 🗝 🛠️ 🏗 ✔️ 1️⃣ 👁 🧵 📍 📨, 🙅♂ 🌖, 🙅♂ 🌘.
- ⚙️ 👉, 🔠 📨 🔜 ✔️ 🚮 👍 💽 🔗/🎉, ❔ ☑ 🏁 🥅.
+⚙️ 👉, 🔠 📨 🔜 ✔️ 🚮 👍 💽 🔗/🎉, ❔ ☑ 🏁 🥅.
- ✋️ FastAPI, ⚙️ 🆕 🔁 ⚒, 💪 🍵 🌅 🌘 1️⃣ 📨 🔛 🎏 🧵. & 🎏 🕰, 👁 📨, ⚫️ 💪 🏃 💗 👜 🎏 🧵 (🧵), ⚓️ 🔛 🚥 👆 ⚙️ `async def` ⚖️ 😐 `def`. 👉 ⚫️❔ 🤝 🌐 🎭 📈 FastAPI.
+✋️ FastAPI, ⚙️ 🆕 🔁 ⚒, 💪 🍵 🌅 🌘 1️⃣ 📨 🔛 🎏 🧵. & 🎏 🕰, 👁 📨, ⚫️ 💪 🏃 💗 👜 🎏 🧵 (🧵), ⚓️ 🔛 🚥 👆 ⚙️ `async def` ⚖️ 😐 `def`. 👉 ⚫️❔ 🤝 🌐 🎭 📈 FastAPI.
+
+///
✋️ 🐍 3️⃣.7️⃣ & 🔛 🚚 🌖 🏧 🎛 `threading.local`, 👈 💪 ⚙️ 🥉 🌐❔ `threading.local` 🔜 ⚙️, ✋️ 🔗 ⏮️ 🆕 🔁 ⚒.
, 👥 💪 ➕ 🎱 ⚒ ⚫️ 👷 🚥 ⚫️ ⚙️ `threading.local`. `__init__`, `__setattr__`, & `__getattr__` 🛠️ 🌐 ✔ 🎱 👉 ⚙️ 🏒 🍵 🤔 👈 ⚫️ 🔜 🔗 ⏮️ FastAPI.
-!!! tip
- 👉 🔜 ⚒ 🏒 🎭 ☑ 🕐❔ ⚙️ ⏮️ FastAPI. 🚫 🎲 📂 ⚖️ 📪 🔗 👈 ➖ ⚙️, 🏗 ❌, ♒️.
+/// tip
+
+👉 🔜 ⚒ 🏒 🎭 ☑ 🕐❔ ⚙️ ⏮️ FastAPI. 🚫 🎲 📂 ⚖️ 📪 🔗 👈 ➖ ⚙️, 🏗 ❌, ♒️.
- ✋️ ⚫️ 🚫 🤝 🏒 🔁 💎-🏋️. 👆 🔜 ⚙️ 😐 `def` 🔢 & 🚫 `async def`.
+✋️ ⚫️ 🚫 🤝 🏒 🔁 💎-🏋️. 👆 🔜 ⚙️ 😐 `def` 🔢 & 🚫 `async def`.
+
+///
### ⚙️ 🛃 `PeeweeConnectionState` 🎓
{!../../../docs_src/sql_databases_peewee/sql_app/database.py!}
```
-!!! tip
- ⚒ 💭 👆 📁 `db._state` *⏮️* 🏗 `db`.
+/// tip
+
+⚒ 💭 👆 📁 `db._state` *⏮️* 🏗 `db`.
+
+///
+
+/// tip
-!!! tip
- 👆 🔜 🎏 🙆 🎏 🏒 💽, 🔌 `PostgresqlDatabase`, `MySQLDatabase`, ♒️.
+👆 🔜 🎏 🙆 🎏 🏒 💽, 🔌 `PostgresqlDatabase`, `MySQLDatabase`, ♒️.
+
+///
## ✍ 💽 🏷
👉 🎏 👆 🔜 🚥 👆 ⏩ 🏒 🔰 & ℹ 🏷 ✔️ 🎏 💽 🇸🇲 🔰.
-!!! tip
- 🏒 ⚙️ ⚖ "**🏷**" 🔗 👉 🎓 & 👐 👈 🔗 ⏮️ 💽.
+/// tip
+
+🏒 ⚙️ ⚖ "**🏷**" 🔗 👉 🎓 & 👐 👈 🔗 ⏮️ 💽.
- ✋️ Pydantic ⚙️ ⚖ "**🏷**" 🔗 🕳 🎏, 💽 🔬, 🛠️, & 🧾 🎓 & 👐.
+✋️ Pydantic ⚙️ ⚖ "**🏷**" 🔗 🕳 🎏, 💽 🔬, 🛠️, & 🧾 🎓 & 👐.
+
+///
🗄 `db` ⚪️➡️ `database` (📁 `database.py` ⚪️➡️ 🔛) & ⚙️ ⚫️ 📥.
{!../../../docs_src/sql_databases_peewee/sql_app/models.py!}
```
-!!! tip
- 🏒 ✍ 📚 🎱 🔢.
+/// tip
+
+🏒 ✍ 📚 🎱 🔢.
- ⚫️ 🔜 🔁 🚮 `id` 🔢 🔢 👑 🔑.
+⚫️ 🔜 🔁 🚮 `id` 🔢 🔢 👑 🔑.
- ⚫️ 🔜 ⚒ 📛 🏓 ⚓️ 🔛 🎓 📛.
+⚫️ 🔜 ⚒ 📛 🏓 ⚓️ 🔛 🎓 📛.
- `Item`, ⚫️ 🔜 ✍ 🔢 `owner_id` ⏮️ 🔢 🆔 `User`. ✋️ 👥 🚫 📣 ⚫️ 🙆.
+ `Item`, ⚫️ 🔜 ✍ 🔢 `owner_id` ⏮️ 🔢 🆔 `User`. ✋️ 👥 🚫 📣 ⚫️ 🙆.
+
+///
## ✍ Pydantic 🏷
🔜 ➡️ ✅ 📁 `sql_app/schemas.py`.
-!!! tip
- ❎ 😨 🖖 🏒 *🏷* & Pydantic *🏷*, 👥 🔜 ✔️ 📁 `models.py` ⏮️ 🏒 🏷, & 📁 `schemas.py` ⏮️ Pydantic 🏷.
+/// tip
+
+❎ 😨 🖖 🏒 *🏷* & Pydantic *🏷*, 👥 🔜 ✔️ 📁 `models.py` ⏮️ 🏒 🏷, & 📁 `schemas.py` ⏮️ Pydantic 🏷.
- 👫 Pydantic 🏷 🔬 🌅 ⚖️ 🌘 "🔗" (☑ 📊 💠).
+👫 Pydantic 🏷 🔬 🌅 ⚖️ 🌘 "🔗" (☑ 📊 💠).
- 👉 🔜 ℹ 👥 ❎ 😨 ⏪ ⚙️ 👯♂️.
+👉 🔜 ℹ 👥 ❎ 😨 ⏪ ⚙️ 👯♂️.
+
+///
### ✍ Pydantic *🏷* / 🔗
{!../../../docs_src/sql_databases_peewee/sql_app/schemas.py!}
```
-!!! tip
- 📥 👥 🏗 🏷 ⏮️ `id`.
+/// tip
+
+📥 👥 🏗 🏷 ⏮️ `id`.
- 👥 🚫 🎯 ✔ `id` 🔢 🏒 🏷, ✋️ 🏒 🚮 1️⃣ 🔁.
+👥 🚫 🎯 ✔ `id` 🔢 🏒 🏷, ✋️ 🏒 🚮 1️⃣ 🔁.
- 👥 ❎ 🎱 `owner_id` 🔢 `Item`.
+👥 ❎ 🎱 `owner_id` 🔢 `Item`.
+
+///
### ✍ `PeeweeGetterDict` Pydantic *🏷* / 🔗
& ⤴️ 👥 ⚙️ ⚫️ Pydantic *🏷* / 🔗 👈 ⚙️ `orm_mode = True`, ⏮️ 📳 🔢 `getter_dict = PeeweeGetterDict`.
-!!! tip
- 👥 🕴 💪 ✍ 1️⃣ `PeeweeGetterDict` 🎓, & 👥 💪 ⚙️ ⚫️ 🌐 Pydantic *🏷* / 🔗.
+/// tip
+
+👥 🕴 💪 ✍ 1️⃣ `PeeweeGetterDict` 🎓, & 👥 💪 ⚙️ ⚫️ 🌐 Pydantic *🏷* / 🔗.
+
+///
## 💩 🇨🇻
**⏭ 📨**, 👥 🔜 ⏲ 👈 🔑 🔢 🔄 `async` 🔗 `reset_db_state()` & ⤴️ ✍ 🆕 🔗 `get_db()` 🔗, 👈 🆕 📨 🔜 ✔️ 🚮 👍 💽 🇵🇸 (🔗, 💵, ♒️).
-!!! tip
- FastAPI 🔁 🛠️, 1️⃣ 📨 💪 ▶️ ➖ 🛠️, & ⏭ 🏁, ➕1️⃣ 📨 💪 📨 & ▶️ 🏭 👍, & ⚫️ 🌐 💪 🛠️ 🎏 🧵.
+/// tip
+
+FastAPI 🔁 🛠️, 1️⃣ 📨 💪 ▶️ ➖ 🛠️, & ⏭ 🏁, ➕1️⃣ 📨 💪 📨 & ▶️ 🏭 👍, & ⚫️ 🌐 💪 🛠️ 🎏 🧵.
- ✋️ 🔑 🔢 🤔 👫 🔁 ⚒,, 🏒 💽 🇵🇸 ⚒ `async` 🔗 `reset_db_state()` 🔜 🚧 🚮 👍 💽 🎂 🎂 📨.
+✋️ 🔑 🔢 🤔 👫 🔁 ⚒,, 🏒 💽 🇵🇸 ⚒ `async` 🔗 `reset_db_state()` 🔜 🚧 🚮 👍 💽 🎂 🎂 📨.
- & 🎏 🕰, 🎏 🛠️ 📨 🔜 ✔️ 🚮 👍 💽 🇵🇸 👈 🔜 🔬 🎂 📨.
+ & 🎏 🕰, 🎏 🛠️ 📨 🔜 ✔️ 🚮 👍 💽 🇵🇸 👈 🔜 🔬 🎂 📨.
+
+///
#### 🏒 🗳
## 📡 ℹ
-!!! warning
- 👉 📶 📡 ℹ 👈 👆 🎲 🚫 💪.
+/// warning
+
+👉 📶 📡 ℹ 👈 👆 🎲 🚫 💪.
+
+///
### ⚠
✋️ 🚥 👆 🙅 ⚙️ **FastAPI**, 👆 🔜 💰 ⚪️➡️ 🏫 🍖 🔃 👫.
-!!! note
- 🚥 👆 🐍 🕴, & 👆 ⏪ 💭 🌐 🔃 🆎 🔑, 🚶 ⏭ 📃.
+/// note
+
+🚥 👆 🐍 🕴, & 👆 ⏪ 💭 🌐 🔃 🆎 🔑, 🚶 ⏭ 📃.
+
+///
## 🎯
🖼, ➡️ 🔬 🔢 `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` 🆎 ↩️.
+
+///
🔨 👈, 👆 👨🎨 💪 🚚 🐕🦺 ⏪ 🏭 🏬 ⚪️➡️ 📇:
👆 🔜 🎏 📣 `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!}
+```
+
+////
👉 ⛓:
🥈 🆎 🔢 💲 `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!}
- ```
+////
👉 ⛓:
🐍 3️⃣.1️⃣0️⃣ 📤 **🎛 ❕** 🌐❔ 👆 💪 🚮 💪 🆎 👽 <abbr title='also called "bitwise or operator", but that meaning is not relevant here'>⏸ ⏸ (`|`)</abbr>.
-=== "🐍 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`.
👉 ⛓ 👈 🐍 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`
👉 🆎 👈 ✊ 🆎 🔢 ⬜ 🗜 🤙 **💊 🆎** ⚖️ **💊**, 🖼:
-=== "🐍 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`, 👆 💪 ⚙️ <abbr title='also called "bitwise or operator", but that meaning is not relevant here'>⏸ ⏸ (`|`)</abbr> 📣 🇪🇺 🆎.
+* `Union`
+* `Optional` (🎏 ⏮️ 🐍 3️⃣.6️⃣)
+* ...& 🎏.
+
+🐍 3️⃣.1️⃣0️⃣, 🎛 ⚙️ 💊 `Union` & `Optional`, 👆 💪 ⚙️ <abbr title='also called "bitwise or operator", but that meaning is not relevant here'>⏸ ⏸ (`|`)</abbr> 📣 🇪🇺 🆎.
+
+////
### 🎓 🆎
🖼 ⚪️➡️ 🛂 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
- 💡 🌖 🔃 <a href="https://docs.pydantic.dev/" class="external-link" target="_blank">Pydantic, ✅ 🚮 🩺</a>.
+💡 🌖 🔃 <a href="https://docs.pydantic.dev/" class="external-link" target="_blank">Pydantic, ✅ 🚮 🩺</a>.
+
+///
**FastAPI** 🌐 ⚓️ 🔛 Pydantic.
👆 🔜 👀 📚 🌅 🌐 👉 💡 [🔰 - 👩💻 🦮](tutorial/index.md){.internal-link target=_blank}.
-!!! tip
- Pydantic ✔️ 🎁 🎭 🕐❔ 👆 ⚙️ `Optional` ⚖️ `Union[Something, None]` 🍵 🔢 💲, 👆 💪 ✍ 🌅 🔃 ⚫️ Pydantic 🩺 🔃 <a href="https://docs.pydantic.dev/latest/concepts/models/#required-optional-fields" class="external-link" target="_blank">✔ 📦 🏑</a>.
+/// tip
+
+Pydantic ✔️ 🎁 🎭 🕐❔ 👆 ⚙️ `Optional` ⚖️ `Union[Something, None]` 🍵 🔢 💲, 👆 💪 ✍ 🌅 🔃 ⚫️ Pydantic 🩺 🔃 <a href="https://docs.pydantic.dev/latest/concepts/models/#required-optional-fields" class="external-link" target="_blank">✔ 📦 🏑</a>.
+
+///
## 🆎 🔑 **FastAPI**
⚠ 👜 👈 ⚙️ 🐩 🐍 🆎, 👁 🥉 (↩️ ❎ 🌖 🎓, 👨🎨, ♒️), **FastAPI** 🔜 📚 👷 👆.
-!!! info
- 🚥 👆 ⏪ 🚶 🔘 🌐 🔰 & 👟 🔙 👀 🌅 🔃 🆎, 👍 ℹ <a href="https://mypy.readthedocs.io/en/latest/cheat_sheet_py3.html" class="external-link" target="_blank"> "🎮 🎼" ⚪️➡️ `mypy`</a>.
+/// info
+
+🚥 👆 ⏪ 🚶 🔘 🌐 🔰 & 👟 🔙 👀 🌅 🔃 🆎, 👍 ℹ <a href="https://mypy.readthedocs.io/en/latest/cheat_sheet_py3.html" class="external-link" target="_blank"> "🎮 🎼" ⚪️➡️ `mypy`</a>.
+
+///
**FastAPI** 💭 ⚫️❔ 🔠 💼 & ❔ 🏤-⚙️ 🎏 🎚, 👈 🌐 🖥 📋 🔗 👯♂️ & 🏃 🖥 ⏮️:
-=== "🐍 3️⃣.6️⃣ & 🔛"
+//// tab | 🐍 3️⃣.6️⃣ & 🔛
- ```Python hl_lines="13 15 22 25"
- {!> ../../../docs_src/background_tasks/tutorial002.py!}
- ```
+```Python hl_lines="13 15 22 25"
+{!> ../../../docs_src/background_tasks/tutorial002.py!}
+```
+
+////
-=== "🐍 3️⃣.1️⃣0️⃣ & 🔛"
+//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛
+
+```Python hl_lines="11 13 20 23"
+{!> ../../../docs_src/background_tasks/tutorial002_py310.py!}
+```
- ```Python hl_lines="11 13 20 23"
- {!> ../../../docs_src/background_tasks/tutorial002_py310.py!}
- ```
+////
👉 🖼, 📧 🔜 ✍ `log.txt` 📁 *⏮️* 📨 📨.
**FastAPI** 🚚 🏪 🧰 📊 👆 🈸 ⏪ 🚧 🌐 💪.
-!!! info
- 🚥 👆 👟 ⚪️➡️ 🏺, 👉 🔜 🌓 🏺 📗.
+/// info
+
+🚥 👆 👟 ⚪️➡️ 🏺, 👉 🔜 🌓 🏺 📗.
+
+///
## 🖼 📁 📊
│ └── 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`.
🌐 🎏 `parameters`, `responses`, `dependencies`, `tags`, ♒️.
-!!! tip
- 👉 🖼, 🔢 🤙 `router`, ✋️ 👆 💪 📛 ⚫️ 👐 👆 💚.
+/// tip
+
+👉 🖼, 🔢 🤙 `router`, ✋️ 👆 💪 📛 ⚫️ 👐 👆 💚.
+
+///
👥 🔜 🔌 👉 `APIRouter` 👑 `FastAPI` 📱, ✋️ 🥇, ➡️ ✅ 🔗 & ➕1️⃣ `APIRouter`.
{!../../../docs_src/bigger_applications/app/dependencies.py!}
```
-!!! tip
- 👥 ⚙️ 💭 🎚 📉 👉 🖼.
+/// tip
+
+👥 ⚙️ 💭 🎚 📉 👉 🖼.
+
+✋️ 🎰 💼 👆 🔜 🤚 👍 🏁 ⚙️ 🛠️ [💂♂ 🚙](security/index.md){.internal-link target=_blank}.
- ✋️ 🎰 💼 👆 🔜 🤚 👍 🏁 ⚙️ 🛠️ [💂♂ 🚙](security/index.md){.internal-link target=_blank}.
+///
## ➕1️⃣ 🕹 ⏮️ `APIRouter`
& 👥 💪 🚮 📇 `dependencies` 👈 🔜 🚮 🌐 *➡ 🛠️* 📻 & 🔜 🛠️/❎ 🔠 📨 ⚒ 👫.
-!!! tip
- 🗒 👈, 🌅 💖 [🔗 *➡ 🛠️ 👨🎨*](dependencies/dependencies-in-path-operation-decorators.md){.internal-link target=_blank}, 🙅♂ 💲 🔜 🚶♀️ 👆 *➡ 🛠️ 🔢*.
+/// tip
+
+🗒 👈, 🌅 💖 [🔗 *➡ 🛠️ 👨🎨*](dependencies/dependencies-in-path-operation-decorators.md){.internal-link target=_blank}, 🙅♂ 💲 🔜 🚶♀️ 👆 *➡ 🛠️ 🔢*.
+
+///
🔚 🏁 👈 🏬 ➡ 🔜:
* 📻 🔗 🛠️ 🥇, ⤴️ [`dependencies` 👨🎨](dependencies/dependencies-in-path-operation-decorators.md){.internal-link target=_blank}, & ⤴️ 😐 🔢 🔗.
* 👆 💪 🚮 [`Security` 🔗 ⏮️ `scopes`](../advanced/security/oauth2-scopes.md){.internal-link target=_blank}.
-!!! tip
- ✔️ `dependencies` `APIRouter` 💪 ⚙️, 🖼, 🚚 🤝 🎂 👪 *➡ 🛠️*. 🚥 🔗 🚫 🚮 📦 🔠 1️⃣ 👫.
+/// tip
+
+✔️ `dependencies` `APIRouter` 💪 ⚙️, 🖼, 🚚 🤝 🎂 👪 *➡ 🛠️*. 🚥 🔗 🚫 🚮 📦 🔠 1️⃣ 👫.
+
+///
+
+/// check
-!!! check
- `prefix`, `tags`, `responses`, & `dependencies` 🔢 (📚 🎏 💼) ⚒ ⚪️➡️ **FastAPI** ℹ 👆 ❎ 📟 ❎.
+`prefix`, `tags`, `responses`, & `dependencies` 🔢 (📚 🎏 💼) ⚒ ⚪️➡️ **FastAPI** ℹ 👆 ❎ 📟 ❎.
+
+///
### 🗄 🔗
#### ❔ ⚖ 🗄 👷
-!!! tip
- 🚥 👆 💭 👌 ❔ 🗄 👷, 😣 ⏭ 📄 🔛.
+/// tip
+
+🚥 👆 💭 👌 ❔ 🗄 👷, 😣 ⏭ 📄 🔛.
+
+///
👁 ❣ `.`, 💖:
{!../../../docs_src/bigger_applications/app/routers/items.py!}
```
-!!! tip
- 👉 🏁 ➡ 🛠️ 🔜 ✔️ 🌀 🔖: `["items", "custom"]`.
+/// tip
+
+👉 🏁 ➡ 🛠️ 🔜 ✔️ 🌀 🔖: `["items", "custom"]`.
- & ⚫️ 🔜 ✔️ 👯♂️ 📨 🧾, 1️⃣ `404` & 1️⃣ `403`.
+ & ⚫️ 🔜 ✔️ 👯♂️ 📨 🧾, 1️⃣ `404` & 1️⃣ `403`.
+
+///
## 👑 `FastAPI`
from app.routers import items, users
```
-!!! info
- 🥇 ⏬ "⚖ 🗄":
+/// info
+
+🥇 ⏬ "⚖ 🗄":
- ```Python
- from .routers import items, users
- ```
+```Python
+from .routers import items, users
+```
- 🥈 ⏬ "🎆 🗄":
+🥈 ⏬ "🎆 🗄":
+
+```Python
+from app.routers import items, users
+```
- ```Python
- from app.routers import items, users
- ```
+💡 🌅 🔃 🐍 📦 & 🕹, ✍ <a href="https://docs.python.org/3/tutorial/modules.html" class="external-link" target="_blank">🛂 🐍 🧾 🔃 🕹</a>.
- 💡 🌅 🔃 🐍 📦 & 🕹, ✍ <a href="https://docs.python.org/3/tutorial/modules.html" class="external-link" target="_blank">🛂 🐍 🧾 🔃 🕹</a>.
+///
### ❎ 📛 💥
{!../../../docs_src/bigger_applications/app/main.py!}
```
-!!! info
- `users.router` 🔌 `APIRouter` 🔘 📁 `app/routers/users.py`.
+/// info
- & `items.router` 🔌 `APIRouter` 🔘 📁 `app/routers/items.py`.
+`users.router` 🔌 `APIRouter` 🔘 📁 `app/routers/users.py`.
+
+ & `items.router` 🔌 `APIRouter` 🔘 📁 `app/routers/items.py`.
+
+///
⏮️ `app.include_router()` 👥 💪 🚮 🔠 `APIRouter` 👑 `FastAPI` 🈸.
⚫️ 🔜 🔌 🌐 🛣 ⚪️➡️ 👈 📻 🍕 ⚫️.
-!!! note "📡 ℹ"
- ⚫️ 🔜 🤙 🔘 ✍ *➡ 🛠️* 🔠 *➡ 🛠️* 👈 📣 `APIRouter`.
+/// note | "📡 ℹ"
+
+⚫️ 🔜 🤙 🔘 ✍ *➡ 🛠️* 🔠 *➡ 🛠️* 👈 📣 `APIRouter`.
+
+, ⛅ 🎑, ⚫️ 🔜 🤙 👷 🚥 🌐 🎏 👁 📱.
+
+///
- , ⛅ 🎑, ⚫️ 🔜 🤙 👷 🚥 🌐 🎏 👁 📱.
+/// check
-!!! check
- 👆 🚫 ✔️ 😟 🔃 🎭 🕐❔ ✅ 📻.
+👆 🚫 ✔️ 😟 🔃 🎭 🕐❔ ✅ 📻.
- 👉 🔜 ✊ ⏲ & 🔜 🕴 🔨 🕴.
+👉 🔜 ✊ ⏲ & 🔜 🕴 🔨 🕴.
- ⚫️ 🏆 🚫 📉 🎭. 👶
+⚫️ 🏆 🚫 📉 🎭. 👶
+
+///
### 🔌 `APIRouter` ⏮️ 🛃 `prefix`, `tags`, `responses`, & `dependencies`
& ⚫️ 🔜 👷 ☑, 👯♂️ ⏮️ 🌐 🎏 *➡ 🛠️* 🚮 ⏮️ `app.include_router()`.
-!!! info "📶 📡 ℹ"
- **🗒**: 👉 📶 📡 ℹ 👈 👆 🎲 💪 **🚶**.
+/// info | "📶 📡 ℹ"
+
+**🗒**: 👉 📶 📡 ℹ 👈 👆 🎲 💪 **🚶**.
+
+---
- ---
+ `APIRouter`Ⓜ 🚫 "🗻", 👫 🚫 👽 ⚪️➡️ 🎂 🈸.
- `APIRouter`Ⓜ 🚫 "🗻", 👫 🚫 👽 ⚪️➡️ 🎂 🈸.
+👉 ↩️ 👥 💚 🔌 👫 *➡ 🛠️* 🗄 🔗 & 👩💻 🔢.
- 👉 ↩️ 👥 💚 🔌 👫 *➡ 🛠️* 🗄 🔗 & 👩💻 🔢.
+👥 🚫🔜 ❎ 👫 & "🗻" 👫 ➡ 🎂, *➡ 🛠️* "🖖" (🏤-✍), 🚫 🔌 🔗.
- 👥 🚫🔜 ❎ 👫 & "🗻" 👫 ➡ 🎂, *➡ 🛠️* "🖖" (🏤-✍), 🚫 🔌 🔗.
+///
## ✅ 🏧 🛠️ 🩺
🥇, 👆 ✔️ 🗄 ⚫️:
-=== "🐍 3️⃣.6️⃣ & 🔛"
+//// tab | 🐍 3️⃣.6️⃣ & 🔛
- ```Python hl_lines="4"
- {!> ../../../docs_src/body_fields/tutorial001.py!}
- ```
+```Python hl_lines="4"
+{!> ../../../docs_src/body_fields/tutorial001.py!}
+```
-=== "🐍 3️⃣.1️⃣0️⃣ & 🔛"
+////
- ```Python hl_lines="2"
- {!> ../../../docs_src/body_fields/tutorial001_py310.py!}
- ```
+//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛
-!!! warning
- 👀 👈 `Field` 🗄 🔗 ⚪️➡️ `pydantic`, 🚫 ⚪️➡️ `fastapi` 🌐 🎂 (`Query`, `Path`, `Body`, ♒️).
+```Python hl_lines="2"
+{!> ../../../docs_src/body_fields/tutorial001_py310.py!}
+```
+
+////
+
+/// warning
+
+👀 👈 `Field` 🗄 🔗 ⚪️➡️ `pydantic`, 🚫 ⚪️➡️ `fastapi` 🌐 🎂 (`Query`, `Path`, `Body`, ♒️).
+
+///
## 📣 🏷 🔢
👆 💪 ⤴️ ⚙️ `Field` ⏮️ 🏷 🔢:
-=== "🐍 3️⃣.6️⃣ & 🔛"
+//// tab | 🐍 3️⃣.6️⃣ & 🔛
+
+```Python hl_lines="11-14"
+{!> ../../../docs_src/body_fields/tutorial001.py!}
+```
+
+////
- ```Python hl_lines="11-14"
- {!> ../../../docs_src/body_fields/tutorial001.py!}
- ```
+//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛
-=== "🐍 3️⃣.1️⃣0️⃣ & 🔛"
+```Python hl_lines="9-12"
+{!> ../../../docs_src/body_fields/tutorial001_py310.py!}
+```
- ```Python hl_lines="9-12"
- {!> ../../../docs_src/body_fields/tutorial001_py310.py!}
- ```
+////
`Field` 👷 🎏 🌌 `Query`, `Path` & `Body`, ⚫️ ✔️ 🌐 🎏 🔢, ♒️.
-!!! note "📡 ℹ"
- 🤙, `Query`, `Path` & 🎏 👆 🔜 👀 ⏭ ✍ 🎚 🏿 ⚠ `Param` 🎓, ❔ ⚫️ 🏿 Pydantic `FieldInfo` 🎓.
+/// note | "📡 ℹ"
- & Pydantic `Field` 📨 👐 `FieldInfo` 👍.
+🤙, `Query`, `Path` & 🎏 👆 🔜 👀 ⏭ ✍ 🎚 🏿 ⚠ `Param` 🎓, ❔ ⚫️ 🏿 Pydantic `FieldInfo` 🎓.
- `Body` 📨 🎚 🏿 `FieldInfo` 🔗. & 📤 🎏 👆 🔜 👀 ⏪ 👈 🏿 `Body` 🎓.
+ & Pydantic `Field` 📨 👐 `FieldInfo` 👍.
- 💭 👈 🕐❔ 👆 🗄 `Query`, `Path`, & 🎏 ⚪️➡️ `fastapi`, 👈 🤙 🔢 👈 📨 🎁 🎓.
+`Body` 📨 🎚 🏿 `FieldInfo` 🔗. & 📤 🎏 👆 🔜 👀 ⏪ 👈 🏿 `Body` 🎓.
-!!! tip
- 👀 ❔ 🔠 🏷 🔢 ⏮️ 🆎, 🔢 💲 & `Field` ✔️ 🎏 📊 *➡ 🛠️ 🔢* 🔢, ⏮️ `Field` ↩️ `Path`, `Query` & `Body`.
+💭 👈 🕐❔ 👆 🗄 `Query`, `Path`, & 🎏 ⚪️➡️ `fastapi`, 👈 🤙 🔢 👈 📨 🎁 🎓.
+
+///
+
+/// tip
+
+👀 ❔ 🔠 🏷 🔢 ⏮️ 🆎, 🔢 💲 & `Field` ✔️ 🎏 📊 *➡ 🛠️ 🔢* 🔢, ⏮️ `Field` ↩️ `Path`, `Query` & `Body`.
+
+///
## 🚮 ➕ ℹ
👆 🔜 💡 🌅 🔃 ❎ ➕ ℹ ⏪ 🩺, 🕐❔ 🏫 📣 🖼.
-!!! warning
- ➕ 🔑 🚶♀️ `Field` 🔜 🎁 📉 🗄 🔗 👆 🈸.
- 👫 🔑 5️⃣📆 🚫 🎯 🍕 🗄 🔧, 🗄 🧰, 🖼 [🗄 💳](https://validator.swagger.io/), 5️⃣📆 🚫 👷 ⏮️ 👆 🏗 🔗.
+/// warning
+
+➕ 🔑 🚶♀️ `Field` 🔜 🎁 📉 🗄 🔗 👆 🈸.
+👫 🔑 5️⃣📆 🚫 🎯 🍕 🗄 🔧, 🗄 🧰, 🖼 [🗄 💳](https://validator.swagger.io/), 5️⃣📆 🚫 👷 ⏮️ 👆 🏗 🔗.
+
+///
## 🌃
& 👆 💪 📣 💪 🔢 📦, ⚒ 🔢 `None`:
-=== "🐍 3️⃣.6️⃣ & 🔛"
+//// tab | 🐍 3️⃣.6️⃣ & 🔛
- ```Python hl_lines="19-21"
- {!> ../../../docs_src/body_multiple_params/tutorial001.py!}
- ```
+```Python hl_lines="19-21"
+{!> ../../../docs_src/body_multiple_params/tutorial001.py!}
+```
+
+////
-=== "🐍 3️⃣.1️⃣0️⃣ & 🔛"
+//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛
+
+```Python hl_lines="17-19"
+{!> ../../../docs_src/body_multiple_params/tutorial001_py310.py!}
+```
- ```Python hl_lines="17-19"
- {!> ../../../docs_src/body_multiple_params/tutorial001_py310.py!}
- ```
+////
-!!! note
- 👀 👈, 👉 💼, `item` 👈 🔜 ✊ ⚪️➡️ 💪 📦. ⚫️ ✔️ `None` 🔢 💲.
+/// note
+
+👀 👈, 👉 💼, `item` 👈 🔜 ✊ ⚪️➡️ 💪 📦. ⚫️ ✔️ `None` 🔢 💲.
+
+///
## 💗 💪 🔢
✋️ 👆 💪 📣 💗 💪 🔢, ✅ `item` & `user`:
-=== "🐍 3️⃣.6️⃣ & 🔛"
+//// tab | 🐍 3️⃣.6️⃣ & 🔛
- ```Python hl_lines="22"
- {!> ../../../docs_src/body_multiple_params/tutorial002.py!}
- ```
+```Python hl_lines="22"
+{!> ../../../docs_src/body_multiple_params/tutorial002.py!}
+```
-=== "🐍 3️⃣.1️⃣0️⃣ & 🔛"
+////
- ```Python hl_lines="20"
- {!> ../../../docs_src/body_multiple_params/tutorial002_py310.py!}
- ```
+//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛
+
+```Python hl_lines="20"
+{!> ../../../docs_src/body_multiple_params/tutorial002_py310.py!}
+```
+
+////
👉 💼, **FastAPI** 🔜 👀 👈 📤 🌅 🌘 1️⃣ 💪 🔢 🔢 (2️⃣ 🔢 👈 Pydantic 🏷).
}
```
-!!! note
- 👀 👈 ✋️ `item` 📣 🎏 🌌 ⏭, ⚫️ 🔜 ⌛ 🔘 💪 ⏮️ 🔑 `item`.
+/// note
+👀 👈 ✋️ `item` 📣 🎏 🌌 ⏭, ⚫️ 🔜 ⌛ 🔘 💪 ⏮️ 🔑 `item`.
+
+///
**FastAPI** 🔜 🏧 🛠️ ⚪️➡️ 📨, 👈 🔢 `item` 📨 ⚫️ 🎯 🎚 & 🎏 `user`.
✋️ 👆 💪 💡 **FastAPI** 😥 ⚫️ ➕1️⃣ 💪 🔑 ⚙️ `Body`:
-=== "🐍 3️⃣.6️⃣ & 🔛"
+//// tab | 🐍 3️⃣.6️⃣ & 🔛
- ```Python hl_lines="22"
- {!> ../../../docs_src/body_multiple_params/tutorial003.py!}
- ```
+```Python hl_lines="22"
+{!> ../../../docs_src/body_multiple_params/tutorial003.py!}
+```
-=== "🐍 3️⃣.1️⃣0️⃣ & 🔛"
+////
- ```Python hl_lines="20"
- {!> ../../../docs_src/body_multiple_params/tutorial003_py310.py!}
- ```
+//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛
+
+```Python hl_lines="20"
+{!> ../../../docs_src/body_multiple_params/tutorial003_py310.py!}
+```
+
+////
👉 💼, **FastAPI** 🔜 ⌛ 💪 💖:
🖼:
-=== "🐍 3️⃣.6️⃣ & 🔛"
+//// tab | 🐍 3️⃣.6️⃣ & 🔛
+
+```Python hl_lines="27"
+{!> ../../../docs_src/body_multiple_params/tutorial004.py!}
+```
+
+////
+
+//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛
- ```Python hl_lines="27"
- {!> ../../../docs_src/body_multiple_params/tutorial004.py!}
- ```
+```Python hl_lines="26"
+{!> ../../../docs_src/body_multiple_params/tutorial004_py310.py!}
+```
+
+////
-=== "🐍 3️⃣.1️⃣0️⃣ & 🔛"
+/// info
- ```Python hl_lines="26"
- {!> ../../../docs_src/body_multiple_params/tutorial004_py310.py!}
- ```
+`Body` ✔️ 🌐 🎏 ➕ 🔬 & 🗃 🔢 `Query`,`Path` & 🎏 👆 🔜 👀 ⏪.
-!!! info
- `Body` ✔️ 🌐 🎏 ➕ 🔬 & 🗃 🔢 `Query`,`Path` & 🎏 👆 🔜 👀 ⏪.
+///
## ⏯ 👁 💪 🔢
:
-=== "🐍 3️⃣.6️⃣ & 🔛"
+//// tab | 🐍 3️⃣.6️⃣ & 🔛
+
+```Python hl_lines="17"
+{!> ../../../docs_src/body_multiple_params/tutorial005.py!}
+```
+
+////
- ```Python hl_lines="17"
- {!> ../../../docs_src/body_multiple_params/tutorial005.py!}
- ```
+//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛
-=== "🐍 3️⃣.1️⃣0️⃣ & 🔛"
+```Python hl_lines="15"
+{!> ../../../docs_src/body_multiple_params/tutorial005_py310.py!}
+```
- ```Python hl_lines="15"
- {!> ../../../docs_src/body_multiple_params/tutorial005_py310.py!}
- ```
+////
👉 💼 **FastAPI** 🔜 ⌛ 💪 💖:
👆 💪 🔬 🔢 🏾. 🖼, 🐍 `list`:
-=== "🐍 3️⃣.6️⃣ & 🔛"
+//// tab | 🐍 3️⃣.6️⃣ & 🔛
- ```Python hl_lines="14"
- {!> ../../../docs_src/body_nested_models/tutorial001.py!}
- ```
+```Python hl_lines="14"
+{!> ../../../docs_src/body_nested_models/tutorial001.py!}
+```
+
+////
-=== "🐍 3️⃣.1️⃣0️⃣ & 🔛"
+//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛
+
+```Python hl_lines="12"
+{!> ../../../docs_src/body_nested_models/tutorial001_py310.py!}
+```
- ```Python hl_lines="12"
- {!> ../../../docs_src/body_nested_models/tutorial001_py310.py!}
- ```
+////
👉 🔜 ⚒ `tags` 📇, 👐 ⚫️ 🚫 📣 🆎 🔣 📇.
, 👆 🖼, 👥 💪 ⚒ `tags` 🎯 "📇 🎻":
-=== "🐍 3️⃣.6️⃣ & 🔛"
+//// tab | 🐍 3️⃣.6️⃣ & 🔛
+
+```Python hl_lines="14"
+{!> ../../../docs_src/body_nested_models/tutorial002.py!}
+```
+
+////
- ```Python hl_lines="14"
- {!> ../../../docs_src/body_nested_models/tutorial002.py!}
- ```
+//// tab | 🐍 3️⃣.9️⃣ & 🔛
-=== "🐍 3️⃣.9️⃣ & 🔛"
+```Python hl_lines="14"
+{!> ../../../docs_src/body_nested_models/tutorial002_py39.py!}
+```
+
+////
- ```Python hl_lines="14"
- {!> ../../../docs_src/body_nested_models/tutorial002_py39.py!}
- ```
+//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛
-=== "🐍 3️⃣.1️⃣0️⃣ & 🔛"
+```Python hl_lines="12"
+{!> ../../../docs_src/body_nested_models/tutorial002_py310.py!}
+```
- ```Python hl_lines="12"
- {!> ../../../docs_src/body_nested_models/tutorial002_py310.py!}
- ```
+////
## ⚒ 🆎
⤴️ 👥 💪 📣 `tags` ⚒ 🎻:
-=== "🐍 3️⃣.6️⃣ & 🔛"
+//// tab | 🐍 3️⃣.6️⃣ & 🔛
+
+```Python hl_lines="1 14"
+{!> ../../../docs_src/body_nested_models/tutorial003.py!}
+```
+
+////
- ```Python hl_lines="1 14"
- {!> ../../../docs_src/body_nested_models/tutorial003.py!}
- ```
+//// tab | 🐍 3️⃣.9️⃣ & 🔛
-=== "🐍 3️⃣.9️⃣ & 🔛"
+```Python hl_lines="14"
+{!> ../../../docs_src/body_nested_models/tutorial003_py39.py!}
+```
- ```Python hl_lines="14"
- {!> ../../../docs_src/body_nested_models/tutorial003_py39.py!}
- ```
+////
-=== "🐍 3️⃣.1️⃣0️⃣ & 🔛"
+//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛
- ```Python hl_lines="12"
- {!> ../../../docs_src/body_nested_models/tutorial003_py310.py!}
- ```
+```Python hl_lines="12"
+{!> ../../../docs_src/body_nested_models/tutorial003_py310.py!}
+```
+
+////
⏮️ 👉, 🚥 👆 📨 📨 ⏮️ ❎ 📊, ⚫️ 🔜 🗜 ⚒ 😍 🏬.
🖼, 👥 💪 🔬 `Image` 🏷:
-=== "🐍 3️⃣.6️⃣ & 🔛"
+//// tab | 🐍 3️⃣.6️⃣ & 🔛
+
+```Python hl_lines="9-11"
+{!> ../../../docs_src/body_nested_models/tutorial004.py!}
+```
+
+////
- ```Python hl_lines="9-11"
- {!> ../../../docs_src/body_nested_models/tutorial004.py!}
- ```
+//// tab | 🐍 3️⃣.9️⃣ & 🔛
-=== "🐍 3️⃣.9️⃣ & 🔛"
+```Python hl_lines="9-11"
+{!> ../../../docs_src/body_nested_models/tutorial004_py39.py!}
+```
+
+////
- ```Python hl_lines="9-11"
- {!> ../../../docs_src/body_nested_models/tutorial004_py39.py!}
- ```
+//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛
-=== "🐍 3️⃣.1️⃣0️⃣ & 🔛"
+```Python hl_lines="7-9"
+{!> ../../../docs_src/body_nested_models/tutorial004_py310.py!}
+```
- ```Python hl_lines="7-9"
- {!> ../../../docs_src/body_nested_models/tutorial004_py310.py!}
- ```
+////
### ⚙️ 📊 🆎
& ⤴️ 👥 💪 ⚙️ ⚫️ 🆎 🔢:
-=== "🐍 3️⃣.6️⃣ & 🔛"
+//// tab | 🐍 3️⃣.6️⃣ & 🔛
- ```Python hl_lines="20"
- {!> ../../../docs_src/body_nested_models/tutorial004.py!}
- ```
+```Python hl_lines="20"
+{!> ../../../docs_src/body_nested_models/tutorial004.py!}
+```
-=== "🐍 3️⃣.9️⃣ & 🔛"
+////
- ```Python hl_lines="20"
- {!> ../../../docs_src/body_nested_models/tutorial004_py39.py!}
- ```
+//// tab | 🐍 3️⃣.9️⃣ & 🔛
-=== "🐍 3️⃣.1️⃣0️⃣ & 🔛"
+```Python hl_lines="20"
+{!> ../../../docs_src/body_nested_models/tutorial004_py39.py!}
+```
+
+////
- ```Python hl_lines="18"
- {!> ../../../docs_src/body_nested_models/tutorial004_py310.py!}
- ```
+//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛
+
+```Python hl_lines="18"
+{!> ../../../docs_src/body_nested_models/tutorial004_py310.py!}
+```
+
+////
👉 🔜 ⛓ 👈 **FastAPI** 🔜 ⌛ 💪 🎏:
🖼, `Image` 🏷 👥 ✔️ `url` 🏑, 👥 💪 📣 ⚫️ ↩️ `str`, Pydantic `HttpUrl`:
-=== "🐍 3️⃣.6️⃣ & 🔛"
+//// tab | 🐍 3️⃣.6️⃣ & 🔛
- ```Python hl_lines="4 10"
- {!> ../../../docs_src/body_nested_models/tutorial005.py!}
- ```
+```Python hl_lines="4 10"
+{!> ../../../docs_src/body_nested_models/tutorial005.py!}
+```
-=== "🐍 3️⃣.9️⃣ & 🔛"
+////
- ```Python hl_lines="4 10"
- {!> ../../../docs_src/body_nested_models/tutorial005_py39.py!}
- ```
+//// tab | 🐍 3️⃣.9️⃣ & 🔛
-=== "🐍 3️⃣.1️⃣0️⃣ & 🔛"
+```Python hl_lines="4 10"
+{!> ../../../docs_src/body_nested_models/tutorial005_py39.py!}
+```
- ```Python hl_lines="2 8"
- {!> ../../../docs_src/body_nested_models/tutorial005_py310.py!}
- ```
+////
+
+//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛
+
+```Python hl_lines="2 8"
+{!> ../../../docs_src/body_nested_models/tutorial005_py310.py!}
+```
+
+////
🎻 🔜 ✅ ☑ 📛, & 📄 🎻 🔗 / 🗄 ✅.
👆 💪 ⚙️ Pydantic 🏷 🏾 `list`, `set`, ♒️:
-=== "🐍 3️⃣.6️⃣ & 🔛"
+//// tab | 🐍 3️⃣.6️⃣ & 🔛
- ```Python hl_lines="20"
- {!> ../../../docs_src/body_nested_models/tutorial006.py!}
- ```
+```Python hl_lines="20"
+{!> ../../../docs_src/body_nested_models/tutorial006.py!}
+```
+
+////
-=== "🐍 3️⃣.9️⃣ & 🔛"
+//// tab | 🐍 3️⃣.9️⃣ & 🔛
- ```Python hl_lines="20"
- {!> ../../../docs_src/body_nested_models/tutorial006_py39.py!}
- ```
+```Python hl_lines="20"
+{!> ../../../docs_src/body_nested_models/tutorial006_py39.py!}
+```
-=== "🐍 3️⃣.1️⃣0️⃣ & 🔛"
+////
- ```Python hl_lines="18"
- {!> ../../../docs_src/body_nested_models/tutorial006_py310.py!}
- ```
+//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛
+
+```Python hl_lines="18"
+{!> ../../../docs_src/body_nested_models/tutorial006_py310.py!}
+```
+
+////
👉 🔜 ⌛ (🗜, ✔, 📄, ♒️) 🎻 💪 💖:
}
```
-!!! info
- 👀 ❔ `images` 🔑 🔜 ✔️ 📇 🖼 🎚.
+/// info
+
+👀 ❔ `images` 🔑 🔜 ✔️ 📇 🖼 🎚.
+
+///
## 🙇 🐦 🏷
👆 💪 🔬 🎲 🙇 🐦 🏷:
-=== "🐍 3️⃣.6️⃣ & 🔛"
+//// tab | 🐍 3️⃣.6️⃣ & 🔛
+
+```Python hl_lines="9 14 20 23 27"
+{!> ../../../docs_src/body_nested_models/tutorial007.py!}
+```
+
+////
- ```Python hl_lines="9 14 20 23 27"
- {!> ../../../docs_src/body_nested_models/tutorial007.py!}
- ```
+//// tab | 🐍 3️⃣.9️⃣ & 🔛
-=== "🐍 3️⃣.9️⃣ & 🔛"
+```Python hl_lines="9 14 20 23 27"
+{!> ../../../docs_src/body_nested_models/tutorial007_py39.py!}
+```
+
+////
+
+//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛
+
+```Python hl_lines="7 12 18 21 25"
+{!> ../../../docs_src/body_nested_models/tutorial007_py310.py!}
+```
- ```Python hl_lines="9 14 20 23 27"
- {!> ../../../docs_src/body_nested_models/tutorial007_py39.py!}
- ```
+////
-=== "🐍 3️⃣.1️⃣0️⃣ & 🔛"
+/// info
- ```Python hl_lines="7 12 18 21 25"
- {!> ../../../docs_src/body_nested_models/tutorial007_py310.py!}
- ```
+👀 ❔ `Offer` ✔️ 📇 `Item`Ⓜ, ❔ 🔄 ✔️ 📦 📇 `Image`Ⓜ
-!!! info
- 👀 ❔ `Offer` ✔️ 📇 `Item`Ⓜ, ❔ 🔄 ✔️ 📦 📇 `Image`Ⓜ
+///
## 💪 😁 📇
:
-=== "🐍 3️⃣.6️⃣ & 🔛"
+//// tab | 🐍 3️⃣.6️⃣ & 🔛
+
+```Python hl_lines="15"
+{!> ../../../docs_src/body_nested_models/tutorial008.py!}
+```
- ```Python hl_lines="15"
- {!> ../../../docs_src/body_nested_models/tutorial008.py!}
- ```
+////
-=== "🐍 3️⃣.9️⃣ & 🔛"
+//// tab | 🐍 3️⃣.9️⃣ & 🔛
- ```Python hl_lines="13"
- {!> ../../../docs_src/body_nested_models/tutorial008_py39.py!}
- ```
+```Python hl_lines="13"
+{!> ../../../docs_src/body_nested_models/tutorial008_py39.py!}
+```
+
+////
## 👨🎨 🐕🦺 🌐
👉 💼, 👆 🔜 🚫 🙆 `dict` 📏 ⚫️ ✔️ `int` 🔑 ⏮️ `float` 💲:
-=== "🐍 3️⃣.6️⃣ & 🔛"
+//// tab | 🐍 3️⃣.6️⃣ & 🔛
+
+```Python hl_lines="9"
+{!> ../../../docs_src/body_nested_models/tutorial009.py!}
+```
+
+////
+
+//// tab | 🐍 3️⃣.9️⃣ & 🔛
+
+```Python hl_lines="7"
+{!> ../../../docs_src/body_nested_models/tutorial009_py39.py!}
+```
- ```Python hl_lines="9"
- {!> ../../../docs_src/body_nested_models/tutorial009.py!}
- ```
+////
-=== "🐍 3️⃣.9️⃣ & 🔛"
+/// tip
- ```Python hl_lines="7"
- {!> ../../../docs_src/body_nested_models/tutorial009_py39.py!}
- ```
+✔️ 🤯 👈 🎻 🕴 🐕🦺 `str` 🔑.
-!!! tip
- ✔️ 🤯 👈 🎻 🕴 🐕🦺 `str` 🔑.
+✋️ Pydantic ✔️ 🏧 💽 🛠️.
- ✋️ Pydantic ✔️ 🏧 💽 🛠️.
+👉 ⛓ 👈, ✋️ 👆 🛠️ 👩💻 💪 🕴 📨 🎻 🔑, 📏 👈 🎻 🔌 😁 🔢, Pydantic 🔜 🗜 👫 & ✔ 👫.
- 👉 ⛓ 👈, ✋️ 👆 🛠️ 👩💻 💪 🕴 📨 🎻 🔑, 📏 👈 🎻 🔌 😁 🔢, Pydantic 🔜 🗜 👫 & ✔ 👫.
+ & `dict` 👆 📨 `weights` 🔜 🤙 ✔️ `int` 🔑 & `float` 💲.
- & `dict` 👆 📨 `weights` 🔜 🤙 ✔️ `int` 🔑 & `float` 💲.
+///
## 🌃
👆 💪 ⚙️ `jsonable_encoder` 🗜 🔢 💽 📊 👈 💪 🏪 🎻 (✅ ⏮️ ☁ 💽). 🖼, 🏭 `datetime` `str`.
-=== "🐍 3️⃣.6️⃣ & 🔛"
+//// tab | 🐍 3️⃣.6️⃣ & 🔛
- ```Python hl_lines="30-35"
- {!> ../../../docs_src/body_updates/tutorial001.py!}
- ```
+```Python hl_lines="30-35"
+{!> ../../../docs_src/body_updates/tutorial001.py!}
+```
+
+////
+
+//// tab | 🐍 3️⃣.9️⃣ & 🔛
+
+```Python hl_lines="30-35"
+{!> ../../../docs_src/body_updates/tutorial001_py39.py!}
+```
-=== "🐍 3️⃣.9️⃣ & 🔛"
+////
- ```Python hl_lines="30-35"
- {!> ../../../docs_src/body_updates/tutorial001_py39.py!}
- ```
+//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛
-=== "🐍 3️⃣.1️⃣0️⃣ & 🔛"
+```Python hl_lines="28-33"
+{!> ../../../docs_src/body_updates/tutorial001_py310.py!}
+```
- ```Python hl_lines="28-33"
- {!> ../../../docs_src/body_updates/tutorial001_py310.py!}
- ```
+////
`PUT` ⚙️ 📨 💽 👈 🔜 ❎ ♻ 💽.
👉 ⛓ 👈 👆 💪 📨 🕴 💽 👈 👆 💚 ℹ, 🍂 🎂 🐣.
-!!! note
- `PATCH` 🌘 🛎 ⚙️ & 💭 🌘 `PUT`.
+/// note
+
+`PATCH` 🌘 🛎 ⚙️ & 💭 🌘 `PUT`.
+
+ & 📚 🏉 ⚙️ 🕴 `PUT`, 🍕 ℹ.
- & 📚 🏉 ⚙️ 🕴 `PUT`, 🍕 ℹ.
+👆 **🆓** ⚙️ 👫 👐 👆 💚, **FastAPI** 🚫 🚫 🙆 🚫.
- 👆 **🆓** ⚙️ 👫 👐 👆 💚, **FastAPI** 🚫 🚫 🙆 🚫.
+✋️ 👉 🦮 🎦 👆, 🌖 ⚖️ 🌘, ❔ 👫 🎯 ⚙️.
- ✋️ 👉 🦮 🎦 👆, 🌖 ⚖️ 🌘, ❔ 👫 🎯 ⚙️.
+///
### ⚙️ Pydantic `exclude_unset` 🔢
⤴️ 👆 💪 ⚙️ 👉 🏗 `dict` ⏮️ 🕴 💽 👈 ⚒ (📨 📨), 🚫 🔢 💲:
-=== "🐍 3️⃣.6️⃣ & 🔛"
+//// tab | 🐍 3️⃣.6️⃣ & 🔛
- ```Python hl_lines="34"
- {!> ../../../docs_src/body_updates/tutorial002.py!}
- ```
+```Python hl_lines="34"
+{!> ../../../docs_src/body_updates/tutorial002.py!}
+```
+
+////
-=== "🐍 3️⃣.9️⃣ & 🔛"
+//// tab | 🐍 3️⃣.9️⃣ & 🔛
- ```Python hl_lines="34"
- {!> ../../../docs_src/body_updates/tutorial002_py39.py!}
- ```
+```Python hl_lines="34"
+{!> ../../../docs_src/body_updates/tutorial002_py39.py!}
+```
-=== "🐍 3️⃣.1️⃣0️⃣ & 🔛"
+////
- ```Python hl_lines="32"
- {!> ../../../docs_src/body_updates/tutorial002_py310.py!}
- ```
+//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛
+
+```Python hl_lines="32"
+{!> ../../../docs_src/body_updates/tutorial002_py310.py!}
+```
+
+////
### ⚙️ Pydantic `update` 🔢
💖 `stored_item_model.copy(update=update_data)`:
-=== "🐍 3️⃣.6️⃣ & 🔛"
+//// tab | 🐍 3️⃣.6️⃣ & 🔛
+
+```Python hl_lines="35"
+{!> ../../../docs_src/body_updates/tutorial002.py!}
+```
+
+////
- ```Python hl_lines="35"
- {!> ../../../docs_src/body_updates/tutorial002.py!}
- ```
+//// tab | 🐍 3️⃣.9️⃣ & 🔛
+
+```Python hl_lines="35"
+{!> ../../../docs_src/body_updates/tutorial002_py39.py!}
+```
-=== "🐍 3️⃣.9️⃣ & 🔛"
+////
- ```Python hl_lines="35"
- {!> ../../../docs_src/body_updates/tutorial002_py39.py!}
- ```
+//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛
-=== "🐍 3️⃣.1️⃣0️⃣ & 🔛"
+```Python hl_lines="33"
+{!> ../../../docs_src/body_updates/tutorial002_py310.py!}
+```
- ```Python hl_lines="33"
- {!> ../../../docs_src/body_updates/tutorial002_py310.py!}
- ```
+////
### 🍕 ℹ 🌃
* 🖊 💽 👆 💽.
* 📨 ℹ 🏷.
-=== "🐍 3️⃣.6️⃣ & 🔛"
+//// tab | 🐍 3️⃣.6️⃣ & 🔛
+
+```Python hl_lines="30-37"
+{!> ../../../docs_src/body_updates/tutorial002.py!}
+```
+
+////
+
+//// tab | 🐍 3️⃣.9️⃣ & 🔛
+
+```Python hl_lines="30-37"
+{!> ../../../docs_src/body_updates/tutorial002_py39.py!}
+```
+
+////
+
+//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛
+
+```Python hl_lines="28-35"
+{!> ../../../docs_src/body_updates/tutorial002_py310.py!}
+```
- ```Python hl_lines="30-37"
- {!> ../../../docs_src/body_updates/tutorial002.py!}
- ```
+////
-=== "🐍 3️⃣.9️⃣ & 🔛"
+/// tip
- ```Python hl_lines="30-37"
- {!> ../../../docs_src/body_updates/tutorial002_py39.py!}
- ```
+👆 💪 🤙 ⚙️ 👉 🎏 ⚒ ⏮️ 🇺🇸🔍 `PUT` 🛠️.
-=== "🐍 3️⃣.1️⃣0️⃣ & 🔛"
+✋️ 🖼 📥 ⚙️ `PATCH` ↩️ ⚫️ ✍ 👫 ⚙️ 💼.
- ```Python hl_lines="28-35"
- {!> ../../../docs_src/body_updates/tutorial002_py310.py!}
- ```
+///
-!!! tip
- 👆 💪 🤙 ⚙️ 👉 🎏 ⚒ ⏮️ 🇺🇸🔍 `PUT` 🛠️.
+/// note
- ✋️ 🖼 📥 ⚙️ `PATCH` ↩️ ⚫️ ✍ 👫 ⚙️ 💼.
+👀 👈 🔢 🏷 ✔.
-!!! note
- 👀 👈 🔢 🏷 ✔.
+, 🚥 👆 💚 📨 🍕 ℹ 👈 💪 🚫 🌐 🔢, 👆 💪 ✔️ 🏷 ⏮️ 🌐 🔢 ™ 📦 (⏮️ 🔢 💲 ⚖️ `None`).
- , 🚥 👆 💚 📨 🍕 ℹ 👈 💪 🚫 🌐 🔢, 👆 💪 ✔️ 🏷 ⏮️ 🌐 🔢 ™ 📦 (⏮️ 🔢 💲 ⚖️ `None`).
+🔬 ⚪️➡️ 🏷 ⏮️ 🌐 📦 💲 **ℹ** & 🏷 ⏮️ ✔ 💲 **🏗**, 👆 💪 ⚙️ 💭 🔬 [➕ 🏷](extra-models.md){.internal-link target=_blank}.
- 🔬 ⚪️➡️ 🏷 ⏮️ 🌐 📦 💲 **ℹ** & 🏷 ⏮️ ✔ 💲 **🏗**, 👆 💪 ⚙️ 💭 🔬 [➕ 🏷](extra-models.md){.internal-link target=_blank}.
+///
📣 **📨** 💪, 👆 ⚙️ <a href="https://docs.pydantic.dev/" class="external-link" target="_blank">Pydantic</a> 🏷 ⏮️ 🌐 👫 🏋️ & 💰.
-!!! info
- 📨 💽, 👆 🔜 ⚙️ 1️⃣: `POST` (🌅 ⚠), `PUT`, `DELETE` ⚖️ `PATCH`.
+/// info
- 📨 💪 ⏮️ `GET` 📨 ✔️ ⚠ 🎭 🔧, 👐, ⚫️ 🐕🦺 FastAPI, 🕴 📶 🏗/😕 ⚙️ 💼.
+📨 💽, 👆 🔜 ⚙️ 1️⃣: `POST` (🌅 ⚠), `PUT`, `DELETE` ⚖️ `PATCH`.
- ⚫️ 🚫, 🎓 🩺 ⏮️ 🦁 🎚 🏆 🚫 🎦 🧾 💪 🕐❔ ⚙️ `GET`, & 🗳 🖕 💪 🚫 🐕🦺 ⚫️.
+📨 💪 ⏮️ `GET` 📨 ✔️ ⚠ 🎭 🔧, 👐, ⚫️ 🐕🦺 FastAPI, 🕴 📶 🏗/😕 ⚙️ 💼.
+
+⚫️ 🚫, 🎓 🩺 ⏮️ 🦁 🎚 🏆 🚫 🎦 🧾 💪 🕐❔ ⚙️ `GET`, & 🗳 🖕 💪 🚫 🐕🦺 ⚫️.
+
+///
## 🗄 Pydantic `BaseModel`
🥇, 👆 💪 🗄 `BaseModel` ⚪️➡️ `pydantic`:
-=== "🐍 3️⃣.6️⃣ & 🔛"
+//// tab | 🐍 3️⃣.6️⃣ & 🔛
+
+```Python hl_lines="4"
+{!> ../../../docs_src/body/tutorial001.py!}
+```
+
+////
- ```Python hl_lines="4"
- {!> ../../../docs_src/body/tutorial001.py!}
- ```
+//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛
-=== "🐍 3️⃣.1️⃣0️⃣ & 🔛"
+```Python hl_lines="2"
+{!> ../../../docs_src/body/tutorial001_py310.py!}
+```
- ```Python hl_lines="2"
- {!> ../../../docs_src/body/tutorial001_py310.py!}
- ```
+////
## ✍ 👆 💽 🏷
⚙️ 🐩 🐍 🆎 🌐 🔢:
-=== "🐍 3️⃣.6️⃣ & 🔛"
+//// tab | 🐍 3️⃣.6️⃣ & 🔛
- ```Python hl_lines="7-11"
- {!> ../../../docs_src/body/tutorial001.py!}
- ```
+```Python hl_lines="7-11"
+{!> ../../../docs_src/body/tutorial001.py!}
+```
-=== "🐍 3️⃣.1️⃣0️⃣ & 🔛"
+////
- ```Python hl_lines="5-9"
- {!> ../../../docs_src/body/tutorial001_py310.py!}
- ```
+//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛
+
+```Python hl_lines="5-9"
+{!> ../../../docs_src/body/tutorial001_py310.py!}
+```
+
+////
🎏 🕐❔ 📣 🔢 🔢, 🕐❔ 🏷 🔢 ✔️ 🔢 💲, ⚫️ 🚫 ✔. ⏪, ⚫️ ✔. ⚙️ `None` ⚒ ⚫️ 📦.
🚮 ⚫️ 👆 *➡ 🛠️*, 📣 ⚫️ 🎏 🌌 👆 📣 ➡ & 🔢 🔢:
-=== "🐍 3️⃣.6️⃣ & 🔛"
+//// tab | 🐍 3️⃣.6️⃣ & 🔛
- ```Python hl_lines="18"
- {!> ../../../docs_src/body/tutorial001.py!}
- ```
+```Python hl_lines="18"
+{!> ../../../docs_src/body/tutorial001.py!}
+```
-=== "🐍 3️⃣.1️⃣0️⃣ & 🔛"
+////
- ```Python hl_lines="16"
- {!> ../../../docs_src/body/tutorial001_py310.py!}
- ```
+//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛
+
+```Python hl_lines="16"
+{!> ../../../docs_src/body/tutorial001_py310.py!}
+```
+
+////
...& 📣 🚮 🆎 🏷 👆 ✍, `Item`.
<img src="/img/tutorial/body/image05.png">
-!!! tip
- 🚥 👆 ⚙️ <a href="https://www.jetbrains.com/pycharm/" class="external-link" target="_blank">🗒</a> 👆 👨🎨, 👆 💪 ⚙️ <a href="https://github.com/koxudaxi/pydantic-pycharm-plugin/" class="external-link" target="_blank">Pydantic 🗒 📁</a>.
+/// tip
+
+🚥 👆 ⚙️ <a href="https://www.jetbrains.com/pycharm/" class="external-link" target="_blank">🗒</a> 👆 👨🎨, 👆 💪 ⚙️ <a href="https://github.com/koxudaxi/pydantic-pycharm-plugin/" class="external-link" target="_blank">Pydantic 🗒 📁</a>.
- ⚫️ 📉 👨🎨 🐕🦺 Pydantic 🏷, ⏮️:
+⚫️ 📉 👨🎨 🐕🦺 Pydantic 🏷, ⏮️:
- * 🚘-🛠️
- * 🆎 ✅
- * 🛠️
- * 🔎
- * 🔬
+* 🚘-🛠️
+* 🆎 ✅
+* 🛠️
+* 🔎
+* 🔬
+
+///
## ⚙️ 🏷
🔘 🔢, 👆 💪 🔐 🌐 🔢 🏷 🎚 🔗:
-=== "🐍 3️⃣.6️⃣ & 🔛"
+//// tab | 🐍 3️⃣.6️⃣ & 🔛
+
+```Python hl_lines="21"
+{!> ../../../docs_src/body/tutorial002.py!}
+```
+
+////
- ```Python hl_lines="21"
- {!> ../../../docs_src/body/tutorial002.py!}
- ```
+//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛
-=== "🐍 3️⃣.1️⃣0️⃣ & 🔛"
+```Python hl_lines="19"
+{!> ../../../docs_src/body/tutorial002_py310.py!}
+```
- ```Python hl_lines="19"
- {!> ../../../docs_src/body/tutorial002_py310.py!}
- ```
+////
## 📨 💪 ➕ ➡ 🔢
**FastAPI** 🔜 🤔 👈 🔢 🔢 👈 🏏 ➡ 🔢 🔜 **✊ ⚪️➡️ ➡**, & 👈 🔢 🔢 👈 📣 Pydantic 🏷 🔜 **✊ ⚪️➡️ 📨 💪**.
-=== "🐍 3️⃣.6️⃣ & 🔛"
+//// tab | 🐍 3️⃣.6️⃣ & 🔛
+
+```Python hl_lines="17-18"
+{!> ../../../docs_src/body/tutorial003.py!}
+```
- ```Python hl_lines="17-18"
- {!> ../../../docs_src/body/tutorial003.py!}
- ```
+////
-=== "🐍 3️⃣.1️⃣0️⃣ & 🔛"
+//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛
- ```Python hl_lines="15-16"
- {!> ../../../docs_src/body/tutorial003_py310.py!}
- ```
+```Python hl_lines="15-16"
+{!> ../../../docs_src/body/tutorial003_py310.py!}
+```
+
+////
## 📨 💪 ➕ ➡ ➕ 🔢 🔢
**FastAPI** 🔜 🤔 🔠 👫 & ✊ 📊 ⚪️➡️ ☑ 🥉.
-=== "🐍 3️⃣.6️⃣ & 🔛"
+//// tab | 🐍 3️⃣.6️⃣ & 🔛
+
+```Python hl_lines="18"
+{!> ../../../docs_src/body/tutorial004.py!}
+```
- ```Python hl_lines="18"
- {!> ../../../docs_src/body/tutorial004.py!}
- ```
+////
-=== "🐍 3️⃣.1️⃣0️⃣ & 🔛"
+//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛
- ```Python hl_lines="16"
- {!> ../../../docs_src/body/tutorial004_py310.py!}
- ```
+```Python hl_lines="16"
+{!> ../../../docs_src/body/tutorial004_py310.py!}
+```
+
+////
🔢 🔢 🔜 🤔 ⏩:
* 🚥 🔢 **⭐ 🆎** (💖 `int`, `float`, `str`, `bool`, ♒️) ⚫️ 🔜 🔬 **🔢** 🔢.
* 🚥 🔢 📣 🆎 **Pydantic 🏷**, ⚫️ 🔜 🔬 📨 **💪**.
-!!! note
- FastAPI 🔜 💭 👈 💲 `q` 🚫 ✔ ↩️ 🔢 💲 `= None`.
+/// note
+
+FastAPI 🔜 💭 👈 💲 `q` 🚫 ✔ ↩️ 🔢 💲 `= None`.
+
+ `Union` `Union[str, None]` 🚫 ⚙️ FastAPI, ✋️ 🔜 ✔ 👆 👨🎨 🤝 👆 👍 🐕🦺 & 🔍 ❌.
- `Union` `Union[str, None]` 🚫 ⚙️ FastAPI, ✋️ 🔜 ✔ 👆 👨🎨 🤝 👆 👍 🐕🦺 & 🔍 ❌.
+///
## 🍵 Pydantic
🥇 🗄 `Cookie`:
-=== "🐍 3️⃣.6️⃣ & 🔛"
+//// tab | 🐍 3️⃣.6️⃣ & 🔛
- ```Python hl_lines="3"
- {!> ../../../docs_src/cookie_params/tutorial001.py!}
- ```
+```Python hl_lines="3"
+{!> ../../../docs_src/cookie_params/tutorial001.py!}
+```
-=== "🐍 3️⃣.1️⃣0️⃣ & 🔛"
+////
- ```Python hl_lines="1"
- {!> ../../../docs_src/cookie_params/tutorial001_py310.py!}
- ```
+//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛
+
+```Python hl_lines="1"
+{!> ../../../docs_src/cookie_params/tutorial001_py310.py!}
+```
+
+////
## 📣 `Cookie` 🔢
🥇 💲 🔢 💲, 👆 💪 🚶♀️ 🌐 ➕ 🔬 ⚖️ ✍ 🔢:
-=== "🐍 3️⃣.6️⃣ & 🔛"
+//// tab | 🐍 3️⃣.6️⃣ & 🔛
+
+```Python hl_lines="9"
+{!> ../../../docs_src/cookie_params/tutorial001.py!}
+```
+
+////
+
+//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛
+
+```Python hl_lines="7"
+{!> ../../../docs_src/cookie_params/tutorial001_py310.py!}
+```
+
+////
+
+/// note | "📡 ℹ"
- ```Python hl_lines="9"
- {!> ../../../docs_src/cookie_params/tutorial001.py!}
- ```
+`Cookie` "👭" 🎓 `Path` & `Query`. ⚫️ 😖 ⚪️➡️ 🎏 ⚠ `Param` 🎓.
-=== "🐍 3️⃣.1️⃣0️⃣ & 🔛"
+✋️ 💭 👈 🕐❔ 👆 🗄 `Query`, `Path`, `Cookie` & 🎏 ⚪️➡️ `fastapi`, 👈 🤙 🔢 👈 📨 🎁 🎓.
- ```Python hl_lines="7"
- {!> ../../../docs_src/cookie_params/tutorial001_py310.py!}
- ```
+///
-!!! note "📡 ℹ"
- `Cookie` "👭" 🎓 `Path` & `Query`. ⚫️ 😖 ⚪️➡️ 🎏 ⚠ `Param` 🎓.
+/// info
- ✋️ 💭 👈 🕐❔ 👆 🗄 `Query`, `Path`, `Cookie` & 🎏 ⚪️➡️ `fastapi`, 👈 🤙 🔢 👈 📨 🎁 🎓.
+📣 🍪, 👆 💪 ⚙️ `Cookie`, ↩️ ⏪ 🔢 🔜 🔬 🔢 🔢.
-!!! info
- 📣 🍪, 👆 💪 ⚙️ `Cookie`, ↩️ ⏪ 🔢 🔜 🔬 🔢 🔢.
+///
## 🌃
🌖 ℹ 🔃 <abbr title="Cross-Origin Resource Sharing">⚜</abbr>, ✅ <a href="https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS" class="external-link" target="_blank">🦎 ⚜ 🧾</a>.
-!!! note "📡 ℹ"
- 👆 💪 ⚙️ `from starlette.middleware.cors import CORSMiddleware`.
+/// note | "📡 ℹ"
- **FastAPI** 🚚 📚 🛠️ `fastapi.middleware` 🏪 👆, 👩💻. ✋️ 🌅 💪 🛠️ 👟 🔗 ⚪️➡️ 💃.
+👆 💪 ⚙️ `from starlette.middleware.cors import CORSMiddleware`.
+
+**FastAPI** 🚚 📚 🛠️ `fastapi.middleware` 🏪 👆, 👩💻. ✋️ 🌅 💪 🛠️ 👟 🔗 ⚪️➡️ 💃.
+
+///
🔜 🚫 🛠️.
-!!! info
- 🌅 ℹ, ✅ <a href="https://docs.python.org/3/library/__main__.html" class="external-link" target="_blank">🛂 🐍 🩺</a>.
+/// info
+
+🌅 ℹ, ✅ <a href="https://docs.python.org/3/library/__main__.html" class="external-link" target="_blank">🛂 🐍 🩺</a>.
+
+///
## 🏃 👆 📟 ⏮️ 👆 🕹
⏮️ 🖼, 👥 🛬 `dict` ⚪️➡️ 👆 🔗 ("☑"):
-=== "🐍 3️⃣.6️⃣ & 🔛"
+//// tab | 🐍 3️⃣.6️⃣ & 🔛
- ```Python hl_lines="9"
- {!> ../../../docs_src/dependencies/tutorial001.py!}
- ```
+```Python hl_lines="9"
+{!> ../../../docs_src/dependencies/tutorial001.py!}
+```
+
+////
-=== "🐍 3️⃣.1️⃣0️⃣ & 🔛"
+//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛
+
+```Python hl_lines="7"
+{!> ../../../docs_src/dependencies/tutorial001_py310.py!}
+```
- ```Python hl_lines="7"
- {!> ../../../docs_src/dependencies/tutorial001_py310.py!}
- ```
+////
✋️ ⤴️ 👥 🤚 `dict` 🔢 `commons` *➡ 🛠️ 🔢*.
⤴️, 👥 💪 🔀 🔗 "☑" `common_parameters` ⚪️➡️ 🔛 🎓 `CommonQueryParams`:
-=== "🐍 3️⃣.6️⃣ & 🔛"
+//// tab | 🐍 3️⃣.6️⃣ & 🔛
- ```Python hl_lines="11-15"
- {!> ../../../docs_src/dependencies/tutorial002.py!}
- ```
+```Python hl_lines="11-15"
+{!> ../../../docs_src/dependencies/tutorial002.py!}
+```
+
+////
-=== "🐍 3️⃣.1️⃣0️⃣ & 🔛"
+//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛
+
+```Python hl_lines="9-13"
+{!> ../../../docs_src/dependencies/tutorial002_py310.py!}
+```
- ```Python hl_lines="9-13"
- {!> ../../../docs_src/dependencies/tutorial002_py310.py!}
- ```
+////
💸 🙋 `__init__` 👩🔬 ⚙️ ✍ 👐 🎓:
-=== "🐍 3️⃣.6️⃣ & 🔛"
+//// tab | 🐍 3️⃣.6️⃣ & 🔛
- ```Python hl_lines="12"
- {!> ../../../docs_src/dependencies/tutorial002.py!}
- ```
+```Python hl_lines="12"
+{!> ../../../docs_src/dependencies/tutorial002.py!}
+```
+
+////
-=== "🐍 3️⃣.1️⃣0️⃣ & 🔛"
+//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛
+
+```Python hl_lines="10"
+{!> ../../../docs_src/dependencies/tutorial002_py310.py!}
+```
- ```Python hl_lines="10"
- {!> ../../../docs_src/dependencies/tutorial002_py310.py!}
- ```
+////
...⚫️ ✔️ 🎏 🔢 👆 ⏮️ `common_parameters`:
-=== "🐍 3️⃣.6️⃣ & 🔛"
+//// tab | 🐍 3️⃣.6️⃣ & 🔛
+
+```Python hl_lines="9"
+{!> ../../../docs_src/dependencies/tutorial001.py!}
+```
+
+////
- ```Python hl_lines="9"
- {!> ../../../docs_src/dependencies/tutorial001.py!}
- ```
+//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛
-=== "🐍 3️⃣.1️⃣0️⃣ & 🔛"
+```Python hl_lines="6"
+{!> ../../../docs_src/dependencies/tutorial001_py310.py!}
+```
- ```Python hl_lines="6"
- {!> ../../../docs_src/dependencies/tutorial001_py310.py!}
- ```
+////
📚 🔢 ⚫️❔ **FastAPI** 🔜 ⚙️ "❎" 🔗.
🔜 👆 💪 📣 👆 🔗 ⚙️ 👉 🎓.
-=== "🐍 3️⃣.6️⃣ & 🔛"
+//// tab | 🐍 3️⃣.6️⃣ & 🔛
+
+```Python hl_lines="19"
+{!> ../../../docs_src/dependencies/tutorial002.py!}
+```
+
+////
- ```Python hl_lines="19"
- {!> ../../../docs_src/dependencies/tutorial002.py!}
- ```
+//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛
-=== "🐍 3️⃣.1️⃣0️⃣ & 🔛"
+```Python hl_lines="17"
+{!> ../../../docs_src/dependencies/tutorial002_py310.py!}
+```
- ```Python hl_lines="17"
- {!> ../../../docs_src/dependencies/tutorial002_py310.py!}
- ```
+////
**FastAPI** 🤙 `CommonQueryParams` 🎓. 👉 ✍ "👐" 👈 🎓 & 👐 🔜 🚶♀️ 🔢 `commons` 👆 🔢.
...:
-=== "🐍 3️⃣.6️⃣ & 🔛"
+//// tab | 🐍 3️⃣.6️⃣ & 🔛
+
+```Python hl_lines="19"
+{!> ../../../docs_src/dependencies/tutorial003.py!}
+```
- ```Python hl_lines="19"
- {!> ../../../docs_src/dependencies/tutorial003.py!}
- ```
+////
-=== "🐍 3️⃣.1️⃣0️⃣ & 🔛"
+//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛
- ```Python hl_lines="17"
- {!> ../../../docs_src/dependencies/tutorial003_py310.py!}
- ```
+```Python hl_lines="17"
+{!> ../../../docs_src/dependencies/tutorial003_py310.py!}
+```
+
+////
✋️ 📣 🆎 💡 👈 🌌 👆 👨🎨 🔜 💭 ⚫️❔ 🔜 🚶♀️ 🔢 `commons`, & ⤴️ ⚫️ 💪 ℹ 👆 ⏮️ 📟 🛠️, 🆎 ✅, ♒️:
🎏 🖼 🔜 ⤴️ 👀 💖:
-=== "🐍 3️⃣.6️⃣ & 🔛"
+//// tab | 🐍 3️⃣.6️⃣ & 🔛
+
+```Python hl_lines="19"
+{!> ../../../docs_src/dependencies/tutorial004.py!}
+```
- ```Python hl_lines="19"
- {!> ../../../docs_src/dependencies/tutorial004.py!}
- ```
+////
-=== "🐍 3️⃣.1️⃣0️⃣ & 🔛"
+//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛
- ```Python hl_lines="17"
- {!> ../../../docs_src/dependencies/tutorial004_py310.py!}
- ```
+```Python hl_lines="17"
+{!> ../../../docs_src/dependencies/tutorial004_py310.py!}
+```
+
+////
...& **FastAPI** 🔜 💭 ⚫️❔.
-!!! tip
- 🚥 👈 😑 🌅 😨 🌘 👍, 🤷♂ ⚫️, 👆 🚫 *💪* ⚫️.
+/// tip
+
+🚥 👈 😑 🌅 😨 🌘 👍, 🤷♂ ⚫️, 👆 🚫 *💪* ⚫️.
+
+⚫️ ⌨. ↩️ **FastAPI** 💅 🔃 🤝 👆 📉 📟 🔁.
- ⚫️ ⌨. ↩️ **FastAPI** 💅 🔃 🤝 👆 📉 📟 🔁.
+///
👉 🔗 🔜 🛠️/❎ 🎏 🌌 😐 🔗. ✋️ 👫 💲 (🚥 👫 📨 🙆) 🏆 🚫 🚶♀️ 👆 *➡ 🛠️ 🔢*.
-!!! tip
- 👨🎨 ✅ ♻ 🔢 🔢, & 🎦 👫 ❌.
+/// tip
- ⚙️ 👉 `dependencies` *➡ 🛠️ 👨🎨* 👆 💪 ⚒ 💭 👫 🛠️ ⏪ ❎ 👨🎨/🏭 ❌.
+👨🎨 ✅ ♻ 🔢 🔢, & 🎦 👫 ❌.
- ⚫️ 💪 ℹ ❎ 😨 🆕 👩💻 👈 👀 ♻ 🔢 👆 📟 & 💪 💭 ⚫️ 🙃.
+⚙️ 👉 `dependencies` *➡ 🛠️ 👨🎨* 👆 💪 ⚒ 💭 👫 🛠️ ⏪ ❎ 👨🎨/🏭 ❌.
-!!! info
- 👉 🖼 👥 ⚙️ 💭 🛃 🎚 `X-Key` & `X-Token`.
+⚫️ 💪 ℹ ❎ 😨 🆕 👩💻 👈 👀 ♻ 🔢 👆 📟 & 💪 💭 ⚫️ 🙃.
- ✋️ 🎰 💼, 🕐❔ 🛠️ 💂♂, 👆 🔜 🤚 🌖 💰 ⚪️➡️ ⚙️ 🛠️ [💂♂ 🚙 (⏭ 📃)](../security/index.md){.internal-link target=_blank}.
+///
+
+/// info
+
+👉 🖼 👥 ⚙️ 💭 🛃 🎚 `X-Key` & `X-Token`.
+
+✋️ 🎰 💼, 🕐❔ 🛠️ 💂♂, 👆 🔜 🤚 🌖 💰 ⚪️➡️ ⚙️ 🛠️ [💂♂ 🚙 (⏭ 📃)](../security/index.md){.internal-link target=_blank}.
+
+///
## 🔗 ❌ & 📨 💲
👉, ⚙️ `yield` ↩️ `return`, & ✍ ➕ 🔁 ⏮️.
-!!! tip
- ⚒ 💭 ⚙️ `yield` 1️⃣ 👁 🕰.
+/// tip
-!!! note "📡 ℹ"
- 🙆 🔢 👈 ☑ ⚙️ ⏮️:
+⚒ 💭 ⚙️ `yield` 1️⃣ 👁 🕰.
- * <a href="https://docs.python.org/3/library/contextlib.html#contextlib.contextmanager" class="external-link" target="_blank">`@contextlib.contextmanager`</a> ⚖️
- * <a href="https://docs.python.org/3/library/contextlib.html#contextlib.asynccontextmanager" class="external-link" target="_blank">`@contextlib.asynccontextmanager`</a>
+///
- 🔜 ☑ ⚙️ **FastAPI** 🔗.
+/// note | "📡 ℹ"
- 👐, FastAPI ⚙️ 📚 2️⃣ 👨🎨 🔘.
+🙆 🔢 👈 ☑ ⚙️ ⏮️:
+
+* <a href="https://docs.python.org/3/library/contextlib.html#contextlib.contextmanager" class="external-link" target="_blank">`@contextlib.contextmanager`</a> ⚖️
+* <a href="https://docs.python.org/3/library/contextlib.html#contextlib.asynccontextmanager" class="external-link" target="_blank">`@contextlib.asynccontextmanager`</a>
+
+🔜 ☑ ⚙️ **FastAPI** 🔗.
+
+👐, FastAPI ⚙️ 📚 2️⃣ 👨🎨 🔘.
+
+///
## 💽 🔗 ⏮️ `yield`
{!../../../docs_src/dependencies/tutorial007.py!}
```
-!!! tip
- 👆 💪 ⚙️ `async` ⚖️ 😐 🔢.
+/// tip
+
+👆 💪 ⚙️ `async` ⚖️ 😐 🔢.
- **FastAPI** 🔜 ▶️️ 👜 ⏮️ 🔠, 🎏 ⏮️ 😐 🔗.
+**FastAPI** 🔜 ▶️️ 👜 ⏮️ 🔠, 🎏 ⏮️ 😐 🔗.
+
+///
## 🔗 ⏮️ `yield` & `try`
**FastAPI** 🔜 ⚒ 💭 🌐 🏃 ☑ ✔.
-!!! note "📡 ℹ"
- 👉 👷 👏 🐍 <a href="https://docs.python.org/3/library/contextlib.html" class="external-link" target="_blank">🔑 👨💼</a>.
+/// note | "📡 ℹ"
+
+👉 👷 👏 🐍 <a href="https://docs.python.org/3/library/contextlib.html" class="external-link" target="_blank">🔑 👨💼</a>.
- **FastAPI** ⚙️ 👫 🔘 🏆 👉.
+**FastAPI** ⚙️ 👫 🔘 🏆 👉.
+
+///
## 🔗 ⏮️ `yield` & `HTTPException`
🚥 👆 ✔️ 🛃 ⚠ 👈 👆 🔜 💖 🍵 *⏭* 🛬 📨 & 🎲 ❎ 📨, 🎲 🙋♀ `HTTPException`, ✍ [🛃 ⚠ 🐕🦺](../handling-errors.md#_4){.internal-link target=_blank}.
-!!! tip
- 👆 💪 🤚 ⚠ 🔌 `HTTPException` *⏭* `yield`. ✋️ 🚫 ⏮️.
+/// tip
+
+👆 💪 🤚 ⚠ 🔌 `HTTPException` *⏭* `yield`. ✋️ 🚫 ⏮️.
+
+///
🔁 🛠️ 🌅 ⚖️ 🌘 💖 👉 📊. 🕰 💧 ⚪️➡️ 🔝 🔝. & 🔠 🏓 1️⃣ 🍕 🔗 ⚖️ 🛠️ 📟.
end
```
-!!! info
- 🕴 **1️⃣ 📨** 🔜 📨 👩💻. ⚫️ 💪 1️⃣ ❌ 📨 ⚖️ ⚫️ 🔜 📨 ⚪️➡️ *➡ 🛠️*.
+/// info
+
+🕴 **1️⃣ 📨** 🔜 📨 👩💻. ⚫️ 💪 1️⃣ ❌ 📨 ⚖️ ⚫️ 🔜 📨 ⚪️➡️ *➡ 🛠️*.
+
+⏮️ 1️⃣ 📚 📨 📨, 🙅♂ 🎏 📨 💪 📨.
+
+///
+
+/// tip
- ⏮️ 1️⃣ 📚 📨 📨, 🙅♂ 🎏 📨 💪 📨.
+👉 📊 🎦 `HTTPException`, ✋️ 👆 💪 🤚 🙆 🎏 ⚠ ❔ 👆 ✍ [🛃 ⚠ 🐕🦺](../handling-errors.md#_4){.internal-link target=_blank}.
-!!! tip
- 👉 📊 🎦 `HTTPException`, ✋️ 👆 💪 🤚 🙆 🎏 ⚠ ❔ 👆 ✍ [🛃 ⚠ 🐕🦺](../handling-errors.md#_4){.internal-link target=_blank}.
+🚥 👆 🤚 🙆 ⚠, ⚫️ 🔜 🚶♀️ 🔗 ⏮️ 🌾, 🔌 `HTTPException`, & ⤴️ **🔄** ⚠ 🐕🦺. 🚥 📤 🙅♂ ⚠ 🐕🦺 👈 ⚠, ⚫️ 🔜 ⤴️ 🍵 🔢 🔗 `ServerErrorMiddleware`, 🛬 5️⃣0️⃣0️⃣ 🇺🇸🔍 👔 📟, ➡️ 👩💻 💭 👈 📤 ❌ 💽.
- 🚥 👆 🤚 🙆 ⚠, ⚫️ 🔜 🚶♀️ 🔗 ⏮️ 🌾, 🔌 `HTTPException`, & ⤴️ **🔄** ⚠ 🐕🦺. 🚥 📤 🙅♂ ⚠ 🐕🦺 👈 ⚠, ⚫️ 🔜 ⤴️ 🍵 🔢 🔗 `ServerErrorMiddleware`, 🛬 5️⃣0️⃣0️⃣ 🇺🇸🔍 👔 📟, ➡️ 👩💻 💭 👈 📤 ❌ 💽.
+///
## 🔑 👨💼
### ⚙️ 🔑 👨💼 🔗 ⏮️ `yield`
-!!! warning
- 👉, 🌅 ⚖️ 🌘, "🏧" 💭.
+/// warning
- 🚥 👆 ▶️ ⏮️ **FastAPI** 👆 💪 💚 🚶 ⚫️ 🔜.
+👉, 🌅 ⚖️ 🌘, "🏧" 💭.
+
+🚥 👆 ▶️ ⏮️ **FastAPI** 👆 💪 💚 🚶 ⚫️ 🔜.
+
+///
🐍, 👆 💪 ✍ 🔑 👨💼 <a href="https://docs.python.org/3/reference/datamodel.html#context-managers" class="external-link" target="_blank">🏗 🎓 ⏮️ 2️⃣ 👩🔬: `__enter__()` & `__exit__()`</a>.
{!../../../docs_src/dependencies/tutorial010.py!}
```
-!!! tip
- ➕1️⃣ 🌌 ✍ 🔑 👨💼 ⏮️:
+/// tip
+
+➕1️⃣ 🌌 ✍ 🔑 👨💼 ⏮️:
+
+* <a href="https://docs.python.org/3/library/contextlib.html#contextlib.contextmanager" class="external-link" target="_blank">`@contextlib.contextmanager`</a> ⚖️
+* <a href="https://docs.python.org/3/library/contextlib.html#contextlib.asynccontextmanager" class="external-link" target="_blank">`@contextlib.asynccontextmanager`</a>
- * <a href="https://docs.python.org/3/library/contextlib.html#contextlib.contextmanager" class="external-link" target="_blank">`@contextlib.contextmanager`</a> ⚖️
- * <a href="https://docs.python.org/3/library/contextlib.html#contextlib.asynccontextmanager" class="external-link" target="_blank">`@contextlib.asynccontextmanager`</a>
+⚙️ 👫 🎀 🔢 ⏮️ 👁 `yield`.
- ⚙️ 👫 🎀 🔢 ⏮️ 👁 `yield`.
+👈 ⚫️❔ **FastAPI** ⚙️ 🔘 🔗 ⏮️ `yield`.
- 👈 ⚫️❔ **FastAPI** ⚙️ 🔘 🔗 ⏮️ `yield`.
+✋️ 👆 🚫 ✔️ ⚙️ 👨🎨 FastAPI 🔗 (& 👆 🚫🔜 🚫).
- ✋️ 👆 🚫 ✔️ ⚙️ 👨🎨 FastAPI 🔗 (& 👆 🚫🔜 🚫).
+FastAPI 🔜 ⚫️ 👆 🔘.
- FastAPI 🔜 ⚫️ 👆 🔘.
+///
⚫️ 🔢 👈 💪 ✊ 🌐 🎏 🔢 👈 *➡ 🛠️ 🔢* 💪 ✊:
-=== "🐍 3️⃣.6️⃣ & 🔛"
+//// tab | 🐍 3️⃣.6️⃣ & 🔛
- ```Python hl_lines="8-11"
- {!> ../../../docs_src/dependencies/tutorial001.py!}
- ```
+```Python hl_lines="8-11"
+{!> ../../../docs_src/dependencies/tutorial001.py!}
+```
+
+////
-=== "🐍 3️⃣.1️⃣0️⃣ & 🔛"
+//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛
- ```Python hl_lines="6-7"
- {!> ../../../docs_src/dependencies/tutorial001_py310.py!}
- ```
+```Python hl_lines="6-7"
+{!> ../../../docs_src/dependencies/tutorial001_py310.py!}
+```
+
+////
👈 ⚫️.
### 🗄 `Depends`
-=== "🐍 3️⃣.6️⃣ & 🔛"
+//// tab | 🐍 3️⃣.6️⃣ & 🔛
- ```Python hl_lines="3"
- {!> ../../../docs_src/dependencies/tutorial001.py!}
- ```
+```Python hl_lines="3"
+{!> ../../../docs_src/dependencies/tutorial001.py!}
+```
-=== "🐍 3️⃣.1️⃣0️⃣ & 🔛"
+////
- ```Python hl_lines="1"
- {!> ../../../docs_src/dependencies/tutorial001_py310.py!}
- ```
+//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛
+
+```Python hl_lines="1"
+{!> ../../../docs_src/dependencies/tutorial001_py310.py!}
+```
+
+////
### 📣 🔗, "⚓️"
🎏 🌌 👆 ⚙️ `Body`, `Query`, ♒️. ⏮️ 👆 *➡ 🛠️ 🔢* 🔢, ⚙️ `Depends` ⏮️ 🆕 🔢:
-=== "🐍 3️⃣.6️⃣ & 🔛"
+//// tab | 🐍 3️⃣.6️⃣ & 🔛
+
+```Python hl_lines="15 20"
+{!> ../../../docs_src/dependencies/tutorial001.py!}
+```
+
+////
- ```Python hl_lines="15 20"
- {!> ../../../docs_src/dependencies/tutorial001.py!}
- ```
+//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛
-=== "🐍 3️⃣.1️⃣0️⃣ & 🔛"
+```Python hl_lines="11 16"
+{!> ../../../docs_src/dependencies/tutorial001_py310.py!}
+```
- ```Python hl_lines="11 16"
- {!> ../../../docs_src/dependencies/tutorial001_py310.py!}
- ```
+////
👐 👆 ⚙️ `Depends` 🔢 👆 🔢 🎏 🌌 👆 ⚙️ `Body`, `Query`, ♒️, `Depends` 👷 👄 🎏.
& 👈 🔢 ✊ 🔢 🎏 🌌 👈 *➡ 🛠️ 🔢* .
-!!! tip
- 👆 🔜 👀 ⚫️❔ 🎏 "👜", ↖️ ⚪️➡️ 🔢, 💪 ⚙️ 🔗 ⏭ 📃.
+/// tip
+
+👆 🔜 👀 ⚫️❔ 🎏 "👜", ↖️ ⚪️➡️ 🔢, 💪 ⚙️ 🔗 ⏭ 📃.
+
+///
🕐❔ 🆕 📨 🛬, **FastAPI** 🔜 ✊ 💅:
👉 🌌 👆 ✍ 🔗 📟 🕐 & **FastAPI** ✊ 💅 🤙 ⚫️ 👆 *➡ 🛠️*.
-!!! check
- 👀 👈 👆 🚫 ✔️ ✍ 🎁 🎓 & 🚶♀️ ⚫️ 👱 **FastAPI** "®" ⚫️ ⚖️ 🕳 🎏.
+/// check
- 👆 🚶♀️ ⚫️ `Depends` & **FastAPI** 💭 ❔ 🎂.
+👀 👈 👆 🚫 ✔️ ✍ 🎁 🎓 & 🚶♀️ ⚫️ 👱 **FastAPI** "®" ⚫️ ⚖️ 🕳 🎏.
+
+👆 🚶♀️ ⚫️ `Depends` & **FastAPI** 💭 ❔ 🎂.
+
+///
## `async` ⚖️ 🚫 `async`
⚫️ 🚫 🤔. **FastAPI** 🔜 💭 ⚫️❔.
-!!! note
- 🚥 👆 🚫 💭, ✅ [🔁: *"🏃 ❓" *](../../async.md){.internal-link target=_blank} 📄 🔃 `async` & `await` 🩺.
+/// note
+
+🚥 👆 🚫 💭, ✅ [🔁: *"🏃 ❓" *](../../async.md){.internal-link target=_blank} 📄 🔃 `async` & `await` 🩺.
+
+///
## 🛠️ ⏮️ 🗄
👆 💪 ✍ 🥇 🔗 ("☑") 💖:
-=== "🐍 3️⃣.6️⃣ & 🔛"
+//// tab | 🐍 3️⃣.6️⃣ & 🔛
- ```Python hl_lines="8-9"
- {!> ../../../docs_src/dependencies/tutorial005.py!}
- ```
+```Python hl_lines="8-9"
+{!> ../../../docs_src/dependencies/tutorial005.py!}
+```
+
+////
-=== "🐍 3️⃣.1️⃣0️⃣ & 🔛"
+//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛
+
+```Python hl_lines="6-7"
+{!> ../../../docs_src/dependencies/tutorial005_py310.py!}
+```
- ```Python hl_lines="6-7"
- {!> ../../../docs_src/dependencies/tutorial005_py310.py!}
- ```
+////
⚫️ 📣 📦 🔢 🔢 `q` `str`, & ⤴️ ⚫️ 📨 ⚫️.
⤴️ 👆 💪 ✍ ➕1️⃣ 🔗 🔢 ("☑") 👈 🎏 🕰 📣 🔗 🚮 👍 (⚫️ "⚓️" 💁♂️):
-=== "🐍 3️⃣.6️⃣ & 🔛"
+//// tab | 🐍 3️⃣.6️⃣ & 🔛
- ```Python hl_lines="13"
- {!> ../../../docs_src/dependencies/tutorial005.py!}
- ```
+```Python hl_lines="13"
+{!> ../../../docs_src/dependencies/tutorial005.py!}
+```
+
+////
-=== "🐍 3️⃣.1️⃣0️⃣ & 🔛"
+//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛
+
+```Python hl_lines="11"
+{!> ../../../docs_src/dependencies/tutorial005_py310.py!}
+```
- ```Python hl_lines="11"
- {!> ../../../docs_src/dependencies/tutorial005_py310.py!}
- ```
+////
➡️ 🎯 🔛 🔢 📣:
⤴️ 👥 💪 ⚙️ 🔗 ⏮️:
-=== "🐍 3️⃣.6️⃣ & 🔛"
+//// tab | 🐍 3️⃣.6️⃣ & 🔛
- ```Python hl_lines="22"
- {!> ../../../docs_src/dependencies/tutorial005.py!}
- ```
+```Python hl_lines="22"
+{!> ../../../docs_src/dependencies/tutorial005.py!}
+```
+
+////
+
+//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛
+
+```Python hl_lines="19"
+{!> ../../../docs_src/dependencies/tutorial005_py310.py!}
+```
+
+////
-=== "🐍 3️⃣.1️⃣0️⃣ & 🔛"
+/// info
- ```Python hl_lines="19"
- {!> ../../../docs_src/dependencies/tutorial005_py310.py!}
- ```
+👀 👈 👥 🕴 📣 1️⃣ 🔗 *➡ 🛠️ 🔢*, `query_or_cookie_extractor`.
-!!! info
- 👀 👈 👥 🕴 📣 1️⃣ 🔗 *➡ 🛠️ 🔢*, `query_or_cookie_extractor`.
+✋️ **FastAPI** 🔜 💭 👈 ⚫️ ✔️ ❎ `query_extractor` 🥇, 🚶♀️ 🏁 👈 `query_or_cookie_extractor` ⏪ 🤙 ⚫️.
- ✋️ **FastAPI** 🔜 💭 👈 ⚫️ ✔️ ❎ `query_extractor` 🥇, 🚶♀️ 🏁 👈 `query_or_cookie_extractor` ⏪ 🤙 ⚫️.
+///
```mermaid
graph TB
✋️, ⚫️ 📶 🏋️, & ✔ 👆 📣 🎲 🙇 🐦 🔗 "📊" (🌲).
-!!! tip
- 🌐 👉 💪 🚫 😑 ⚠ ⏮️ 👫 🙅 🖼.
+/// tip
+
+🌐 👉 💪 🚫 😑 ⚠ ⏮️ 👫 🙅 🖼.
+
+✋️ 👆 🔜 👀 ❔ ⚠ ⚫️ 📃 🔃 **💂♂**.
- ✋️ 👆 🔜 👀 ❔ ⚠ ⚫️ 📃 🔃 **💂♂**.
+ & 👆 🔜 👀 💸 📟 ⚫️ 🔜 🖊 👆.
- & 👆 🔜 👀 💸 📟 ⚫️ 🔜 🖊 👆.
+///
⚫️ 📨 🎚, 💖 Pydantic 🏷, & 📨 🎻 🔗 ⏬:
-=== "🐍 3️⃣.6️⃣ & 🔛"
+//// tab | 🐍 3️⃣.6️⃣ & 🔛
- ```Python hl_lines="5 22"
- {!> ../../../docs_src/encoder/tutorial001.py!}
- ```
+```Python hl_lines="5 22"
+{!> ../../../docs_src/encoder/tutorial001.py!}
+```
-=== "🐍 3️⃣.1️⃣0️⃣ & 🔛"
+////
- ```Python hl_lines="4 21"
- {!> ../../../docs_src/encoder/tutorial001_py310.py!}
- ```
+//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛
+
+```Python hl_lines="4 21"
+{!> ../../../docs_src/encoder/tutorial001_py310.py!}
+```
+
+////
👉 🖼, ⚫️ 🔜 🗜 Pydantic 🏷 `dict`, & `datetime` `str`.
⚫️ 🚫 📨 ⭕ `str` ⚗ 💽 🎻 📁 (🎻). ⚫️ 📨 🐍 🐩 💽 📊 (✅ `dict`) ⏮️ 💲 & 🎧-💲 👈 🌐 🔗 ⏮️ 🎻.
-!!! note
- `jsonable_encoder` 🤙 ⚙️ **FastAPI** 🔘 🗜 💽. ✋️ ⚫️ ⚠ 📚 🎏 😐.
+/// note
+
+`jsonable_encoder` 🤙 ⚙️ **FastAPI** 🔘 🗜 💽. ✋️ ⚫️ ⚠ 📚 🎏 😐.
+
+///
📥 🖼 *➡ 🛠️* ⏮️ 🔢 ⚙️ 🔛 🆎.
-=== "🐍 3️⃣.6️⃣ & 🔛"
+//// tab | 🐍 3️⃣.6️⃣ & 🔛
- ```Python hl_lines="1 3 12-16"
- {!> ../../../docs_src/extra_data_types/tutorial001.py!}
- ```
+```Python hl_lines="1 3 12-16"
+{!> ../../../docs_src/extra_data_types/tutorial001.py!}
+```
-=== "🐍 3️⃣.1️⃣0️⃣ & 🔛"
+////
- ```Python hl_lines="1 2 11-15"
- {!> ../../../docs_src/extra_data_types/tutorial001_py310.py!}
- ```
+//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛
+
+```Python hl_lines="1 2 11-15"
+{!> ../../../docs_src/extra_data_types/tutorial001_py310.py!}
+```
+
+////
🗒 👈 🔢 🔘 🔢 ✔️ 👫 🐠 💽 🆎, & 👆 💪, 🖼, 🎭 😐 📅 🎭, 💖:
-=== "🐍 3️⃣.6️⃣ & 🔛"
+//// tab | 🐍 3️⃣.6️⃣ & 🔛
+
+```Python hl_lines="18-19"
+{!> ../../../docs_src/extra_data_types/tutorial001.py!}
+```
+
+////
- ```Python hl_lines="18-19"
- {!> ../../../docs_src/extra_data_types/tutorial001.py!}
- ```
+//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛
-=== "🐍 3️⃣.1️⃣0️⃣ & 🔛"
+```Python hl_lines="17-18"
+{!> ../../../docs_src/extra_data_types/tutorial001_py310.py!}
+```
- ```Python hl_lines="17-18"
- {!> ../../../docs_src/extra_data_types/tutorial001_py310.py!}
- ```
+////
* **🔢 🏷** 🔜 🚫 ✔️ 🔐.
* **💽 🏷** 🔜 🎲 💪 ✔️ #️⃣ 🔐.
-!!! danger
- 🙅 🏪 👩💻 🔢 🔐. 🕧 🏪 "🔐 #️⃣" 👈 👆 💪 ⤴️ ✔.
+/// danger
- 🚥 👆 🚫 💭, 👆 🔜 💡 ⚫️❔ "🔐#️⃣" [💂♂ 📃](security/simple-oauth2.md#_4){.internal-link target=_blank}.
+🙅 🏪 👩💻 🔢 🔐. 🕧 🏪 "🔐 #️⃣" 👈 👆 💪 ⤴️ ✔.
+
+🚥 👆 🚫 💭, 👆 🔜 💡 ⚫️❔ "🔐#️⃣" [💂♂ 📃](security/simple-oauth2.md#_4){.internal-link target=_blank}.
+
+///
## 💗 🏷
📥 🏢 💭 ❔ 🏷 💪 👀 💖 ⏮️ 👫 🔐 🏑 & 🥉 🌐❔ 👫 ⚙️:
-=== "🐍 3️⃣.6️⃣ & 🔛"
+//// tab | 🐍 3️⃣.6️⃣ & 🔛
- ```Python hl_lines="9 11 16 22 24 29-30 33-35 40-41"
- {!> ../../../docs_src/extra_models/tutorial001.py!}
- ```
+```Python hl_lines="9 11 16 22 24 29-30 33-35 40-41"
+{!> ../../../docs_src/extra_models/tutorial001.py!}
+```
-=== "🐍 3️⃣.1️⃣0️⃣ & 🔛"
+////
- ```Python hl_lines="7 9 14 20 22 27-28 31-33 38-39"
- {!> ../../../docs_src/extra_models/tutorial001_py310.py!}
- ```
+//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛
+
+```Python hl_lines="7 9 14 20 22 27-28 31-33 38-39"
+{!> ../../../docs_src/extra_models/tutorial001_py310.py!}
+```
+
+////
### 🔃 `**user_in.dict()`
)
```
-!!! warning
- 🔗 🌖 🔢 🤖 💪 💧 💽, ✋️ 👫 ↗️ 🚫 🚚 🙆 🎰 💂♂.
+/// warning
+
+🔗 🌖 🔢 🤖 💪 💧 💽, ✋️ 👫 ↗️ 🚫 🚚 🙆 🎰 💂♂.
+
+///
## 📉 ❎
👈 🌌, 👥 💪 📣 🔺 🖖 🏷 (⏮️ 🔢 `password`, ⏮️ `hashed_password` & 🍵 🔐):
-=== "🐍 3️⃣.6️⃣ & 🔛"
+//// tab | 🐍 3️⃣.6️⃣ & 🔛
+
+```Python hl_lines="9 15-16 19-20 23-24"
+{!> ../../../docs_src/extra_models/tutorial002.py!}
+```
+
+////
- ```Python hl_lines="9 15-16 19-20 23-24"
- {!> ../../../docs_src/extra_models/tutorial002.py!}
- ```
+//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛
-=== "🐍 3️⃣.1️⃣0️⃣ & 🔛"
+```Python hl_lines="7 13-14 17-18 21-22"
+{!> ../../../docs_src/extra_models/tutorial002_py310.py!}
+```
- ```Python hl_lines="7 13-14 17-18 21-22"
- {!> ../../../docs_src/extra_models/tutorial002_py310.py!}
- ```
+////
## `Union` ⚖️ `anyOf`
👈, ⚙️ 🐩 🐍 🆎 🔑 <a href="https://docs.python.org/3/library/typing.html#typing.Union" class="external-link" target="_blank">`typing.Union`</a>:
-!!! note
- 🕐❔ ⚖ <a href="https://docs.pydantic.dev/latest/concepts/types/#unions" class="external-link" target="_blank">`Union`</a>, 🔌 🏆 🎯 🆎 🥇, ⏩ 🌘 🎯 🆎. 🖼 🔛, 🌖 🎯 `PlaneItem` 👟 ⏭ `CarItem` `Union[PlaneItem, CarItem]`.
+/// note
+
+🕐❔ ⚖ <a href="https://docs.pydantic.dev/latest/concepts/types/#unions" class="external-link" target="_blank">`Union`</a>, 🔌 🏆 🎯 🆎 🥇, ⏩ 🌘 🎯 🆎. 🖼 🔛, 🌖 🎯 `PlaneItem` 👟 ⏭ `CarItem` `Union[PlaneItem, CarItem]`.
-=== "🐍 3️⃣.6️⃣ & 🔛"
+///
- ```Python hl_lines="1 14-15 18-20 33"
- {!> ../../../docs_src/extra_models/tutorial003.py!}
- ```
+//// tab | 🐍 3️⃣.6️⃣ & 🔛
-=== "🐍 3️⃣.1️⃣0️⃣ & 🔛"
+```Python hl_lines="1 14-15 18-20 33"
+{!> ../../../docs_src/extra_models/tutorial003.py!}
+```
+
+////
- ```Python hl_lines="1 14-15 18-20 33"
- {!> ../../../docs_src/extra_models/tutorial003_py310.py!}
- ```
+//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛
+
+```Python hl_lines="1 14-15 18-20 33"
+{!> ../../../docs_src/extra_models/tutorial003_py310.py!}
+```
+
+////
### `Union` 🐍 3️⃣.1️⃣0️⃣
👈, ⚙️ 🐩 🐍 `typing.List` (⚖️ `list` 🐍 3️⃣.9️⃣ & 🔛):
-=== "🐍 3️⃣.6️⃣ & 🔛"
+//// tab | 🐍 3️⃣.6️⃣ & 🔛
- ```Python hl_lines="1 20"
- {!> ../../../docs_src/extra_models/tutorial004.py!}
- ```
+```Python hl_lines="1 20"
+{!> ../../../docs_src/extra_models/tutorial004.py!}
+```
-=== "🐍 3️⃣.9️⃣ & 🔛"
+////
- ```Python hl_lines="18"
- {!> ../../../docs_src/extra_models/tutorial004_py39.py!}
- ```
+//// tab | 🐍 3️⃣.9️⃣ & 🔛
+
+```Python hl_lines="18"
+{!> ../../../docs_src/extra_models/tutorial004_py39.py!}
+```
+
+////
## 📨 ⏮️ ❌ `dict`
👉 💼, 👆 💪 ⚙️ `typing.Dict` (⚖️ `dict` 🐍 3️⃣.9️⃣ & 🔛):
-=== "🐍 3️⃣.6️⃣ & 🔛"
+//// tab | 🐍 3️⃣.6️⃣ & 🔛
+
+```Python hl_lines="1 8"
+{!> ../../../docs_src/extra_models/tutorial005.py!}
+```
+
+////
- ```Python hl_lines="1 8"
- {!> ../../../docs_src/extra_models/tutorial005.py!}
- ```
+//// tab | 🐍 3️⃣.9️⃣ & 🔛
-=== "🐍 3️⃣.9️⃣ & 🔛"
+```Python hl_lines="6"
+{!> ../../../docs_src/extra_models/tutorial005_py39.py!}
+```
- ```Python hl_lines="6"
- {!> ../../../docs_src/extra_models/tutorial005_py39.py!}
- ```
+////
## 🌃
</div>
-!!! note
- 📋 `uvicorn main:app` 🔗:
+/// note
- * `main`: 📁 `main.py` (🐍 "🕹").
- * `app`: 🎚 ✍ 🔘 `main.py` ⏮️ ⏸ `app = FastAPI()`.
- * `--reload`: ⚒ 💽 ⏏ ⏮️ 📟 🔀. 🕴 ⚙️ 🛠️.
+📋 `uvicorn main:app` 🔗:
+
+* `main`: 📁 `main.py` (🐍 "🕹").
+* `app`: 🎚 ✍ 🔘 `main.py` ⏮️ ⏸ `app = FastAPI()`.
+* `--reload`: ⚒ 💽 ⏏ ⏮️ 📟 🔀. 🕴 ⚙️ 🛠️.
+
+///
🔢, 📤 ⏸ ⏮️ 🕳 💖:
`FastAPI` 🐍 🎓 👈 🚚 🌐 🛠️ 👆 🛠️.
-!!! note "📡 ℹ"
- `FastAPI` 🎓 👈 😖 🔗 ⚪️➡️ `Starlette`.
+/// note | "📡 ℹ"
+
+`FastAPI` 🎓 👈 😖 🔗 ⚪️➡️ `Starlette`.
- 👆 💪 ⚙️ 🌐 <a href="https://www.starlette.io/" class="external-link" target="_blank">💃</a> 🛠️ ⏮️ `FastAPI` 💁♂️.
+👆 💪 ⚙️ 🌐 <a href="https://www.starlette.io/" class="external-link" target="_blank">💃</a> 🛠️ ⏮️ `FastAPI` 💁♂️.
+
+///
### 🔁 2️⃣: ✍ `FastAPI` "👐"
/items/foo
```
-!!! info
- "➡" 🛎 🤙 "🔗" ⚖️ "🛣".
+/// info
+
+"➡" 🛎 🤙 "🔗" ⚖️ "🛣".
+
+///
⏪ 🏗 🛠️, "➡" 👑 🌌 🎏 "⚠" & "ℹ".
* ➡ `/`
* ⚙️ <abbr title="an HTTP GET method"><code>get</code> 🛠️</abbr>
-!!! info "`@decorator` ℹ"
- 👈 `@something` ❕ 🐍 🤙 "👨🎨".
+/// info | "`@decorator` ℹ"
- 👆 🚮 ⚫️ 🔛 🔝 🔢. 💖 📶 📔 👒 (👤 💭 👈 🌐❔ ⚖ 👟 ⚪️➡️).
+👈 `@something` ❕ 🐍 🤙 "👨🎨".
- "👨🎨" ✊ 🔢 🔛 & 🔨 🕳 ⏮️ ⚫️.
+👆 🚮 ⚫️ 🔛 🔝 🔢. 💖 📶 📔 👒 (👤 💭 👈 🌐❔ ⚖ 👟 ⚪️➡️).
- 👆 💼, 👉 👨🎨 💬 **FastAPI** 👈 🔢 🔛 🔗 **➡** `/` ⏮️ **🛠️** `get`.
+ "👨🎨" ✊ 🔢 🔛 & 🔨 🕳 ⏮️ ⚫️.
- ⚫️ "**➡ 🛠️ 👨🎨**".
+👆 💼, 👉 👨🎨 💬 **FastAPI** 👈 🔢 🔛 🔗 **➡** `/` ⏮️ **🛠️** `get`.
+
+⚫️ "**➡ 🛠️ 👨🎨**".
+
+///
👆 💪 ⚙️ 🎏 🛠️:
* `@app.patch()`
* `@app.trace()`
-!!! tip
- 👆 🆓 ⚙️ 🔠 🛠️ (🇺🇸🔍 👩🔬) 👆 🎋.
+/// tip
+
+👆 🆓 ⚙️ 🔠 🛠️ (🇺🇸🔍 👩🔬) 👆 🎋.
- **FastAPI** 🚫 🛠️ 🙆 🎯 🔑.
+**FastAPI** 🚫 🛠️ 🙆 🎯 🔑.
- ℹ 📥 🎁 📄, 🚫 📄.
+ℹ 📥 🎁 📄, 🚫 📄.
- 🖼, 🕐❔ ⚙️ 🕹 👆 🛎 🎭 🌐 🎯 ⚙️ 🕴 `POST` 🛠️.
+🖼, 🕐❔ ⚙️ 🕹 👆 🛎 🎭 🌐 🎯 ⚙️ 🕴 `POST` 🛠️.
+
+///
### 🔁 4️⃣: 🔬 **➡ 🛠️ 🔢**
{!../../../docs_src/first_steps/tutorial003.py!}
```
-!!! note
- 🚥 👆 🚫 💭 🔺, ✅ [🔁: *"🏃 ❓"*](../async.md#_2){.internal-link target=_blank}.
+/// note
+
+🚥 👆 🚫 💭 🔺, ✅ [🔁: *"🏃 ❓"*](../async.md#_2){.internal-link target=_blank}.
+
+///
### 🔁 5️⃣: 📨 🎚
}
```
-!!! tip
- 🕐❔ 🙋♀ `HTTPException`, 👆 💪 🚶♀️ 🙆 💲 👈 💪 🗜 🎻 🔢 `detail`, 🚫 🕴 `str`.
+/// tip
- 👆 💪 🚶♀️ `dict`, `list`, ♒️.
+🕐❔ 🙋♀ `HTTPException`, 👆 💪 🚶♀️ 🙆 💲 👈 💪 🗜 🎻 🔢 `detail`, 🚫 🕴 `str`.
- 👫 🍵 🔁 **FastAPI** & 🗜 🎻.
+👆 💪 🚶♀️ `dict`, `list`, ♒️.
+
+👫 🍵 🔁 **FastAPI** & 🗜 🎻.
+
+///
## 🚮 🛃 🎚
{"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`.
+///
## 🔐 🔢 ⚠ 🐕🦺
#### `RequestValidationError` 🆚 `ValidationError`
-!!! warning
- 👫 📡 ℹ 👈 👆 💪 🚶 🚥 ⚫️ 🚫 ⚠ 👆 🔜.
+/// warning
+
+👫 📡 ℹ 👈 👆 💪 🚶 🚥 ⚫️ 🚫 ⚠ 👆 🔜.
+
+///
`RequestValidationError` 🎧-🎓 Pydantic <a href="https://docs.pydantic.dev/latest/concepts/models/#error-handling" class="external-link" target="_blank">`ValidationError`</a>.
{!../../../docs_src/handling_errors/tutorial004.py!}
```
-!!! note "📡 ℹ"
- 👆 💪 ⚙️ `from starlette.responses import PlainTextResponse`.
+/// note | "📡 ℹ"
+
+👆 💪 ⚙️ `from starlette.responses import PlainTextResponse`.
+
+**FastAPI** 🚚 🎏 `starlette.responses` `fastapi.responses` 🏪 👆, 👩💻. ✋️ 🌅 💪 📨 👟 🔗 ⚪️➡️ 💃.
- **FastAPI** 🚚 🎏 `starlette.responses` `fastapi.responses` 🏪 👆, 👩💻. ✋️ 🌅 💪 📨 👟 🔗 ⚪️➡️ 💃.
+///
### ⚙️ `RequestValidationError` 💪
🥇 🗄 `Header`:
-=== "🐍 3️⃣.6️⃣ & 🔛"
+//// tab | 🐍 3️⃣.6️⃣ & 🔛
- ```Python hl_lines="3"
- {!> ../../../docs_src/header_params/tutorial001.py!}
- ```
+```Python hl_lines="3"
+{!> ../../../docs_src/header_params/tutorial001.py!}
+```
+
+////
+
+//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛
-=== "🐍 3️⃣.1️⃣0️⃣ & 🔛"
+```Python hl_lines="1"
+{!> ../../../docs_src/header_params/tutorial001_py310.py!}
+```
- ```Python hl_lines="1"
- {!> ../../../docs_src/header_params/tutorial001_py310.py!}
- ```
+////
## 📣 `Header` 🔢
🥇 💲 🔢 💲, 👆 💪 🚶♀️ 🌐 ➕ 🔬 ⚖️ ✍ 🔢:
-=== "🐍 3️⃣.6️⃣ & 🔛"
+//// tab | 🐍 3️⃣.6️⃣ & 🔛
+
+```Python hl_lines="9"
+{!> ../../../docs_src/header_params/tutorial001.py!}
+```
+
+////
+
+//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛
+
+```Python hl_lines="7"
+{!> ../../../docs_src/header_params/tutorial001_py310.py!}
+```
+
+////
+
+/// note | "📡 ℹ"
- ```Python hl_lines="9"
- {!> ../../../docs_src/header_params/tutorial001.py!}
- ```
+`Header` "👭" 🎓 `Path`, `Query` & `Cookie`. ⚫️ 😖 ⚪️➡️ 🎏 ⚠ `Param` 🎓.
-=== "🐍 3️⃣.1️⃣0️⃣ & 🔛"
+✋️ 💭 👈 🕐❔ 👆 🗄 `Query`, `Path`, `Header`, & 🎏 ⚪️➡️ `fastapi`, 👈 🤙 🔢 👈 📨 🎁 🎓.
- ```Python hl_lines="7"
- {!> ../../../docs_src/header_params/tutorial001_py310.py!}
- ```
+///
-!!! note "📡 ℹ"
- `Header` "👭" 🎓 `Path`, `Query` & `Cookie`. ⚫️ 😖 ⚪️➡️ 🎏 ⚠ `Param` 🎓.
+/// info
- ✋️ 💭 👈 🕐❔ 👆 🗄 `Query`, `Path`, `Header`, & 🎏 ⚪️➡️ `fastapi`, 👈 🤙 🔢 👈 📨 🎁 🎓.
+📣 🎚, 👆 💪 ⚙️ `Header`, ↩️ ⏪ 🔢 🔜 🔬 🔢 🔢.
-!!! info
- 📣 🎚, 👆 💪 ⚙️ `Header`, ↩️ ⏪ 🔢 🔜 🔬 🔢 🔢.
+///
## 🏧 🛠️
🚥 🤔 👆 💪 ❎ 🏧 🛠️ 🎦 🔠, ⚒ 🔢 `convert_underscores` `Header` `False`:
-=== "🐍 3️⃣.6️⃣ & 🔛"
+//// tab | 🐍 3️⃣.6️⃣ & 🔛
- ```Python hl_lines="10"
- {!> ../../../docs_src/header_params/tutorial002.py!}
- ```
+```Python hl_lines="10"
+{!> ../../../docs_src/header_params/tutorial002.py!}
+```
+
+////
+
+//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛
+
+```Python hl_lines="8"
+{!> ../../../docs_src/header_params/tutorial002_py310.py!}
+```
+
+////
-=== "🐍 3️⃣.1️⃣0️⃣ & 🔛"
+/// warning
- ```Python hl_lines="8"
- {!> ../../../docs_src/header_params/tutorial002_py310.py!}
- ```
+⏭ ⚒ `convert_underscores` `False`, 🐻 🤯 👈 🇺🇸🔍 🗳 & 💽 / ⚙️ 🎚 ⏮️ 🎦.
-!!! warning
- ⏭ ⚒ `convert_underscores` `False`, 🐻 🤯 👈 🇺🇸🔍 🗳 & 💽 / ⚙️ 🎚 ⏮️ 🎦.
+///
## ❎ 🎚
🖼, 📣 🎚 `X-Token` 👈 💪 😑 🌅 🌘 🕐, 👆 💪 ✍:
-=== "🐍 3️⃣.6️⃣ & 🔛"
+//// tab | 🐍 3️⃣.6️⃣ & 🔛
- ```Python hl_lines="9"
- {!> ../../../docs_src/header_params/tutorial003.py!}
- ```
+```Python hl_lines="9"
+{!> ../../../docs_src/header_params/tutorial003.py!}
+```
+
+////
+
+//// tab | 🐍 3️⃣.9️⃣ & 🔛
-=== "🐍 3️⃣.9️⃣ & 🔛"
+```Python hl_lines="9"
+{!> ../../../docs_src/header_params/tutorial003_py39.py!}
+```
+
+////
- ```Python hl_lines="9"
- {!> ../../../docs_src/header_params/tutorial003_py39.py!}
- ```
+//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛
-=== "🐍 3️⃣.1️⃣0️⃣ & 🔛"
+```Python hl_lines="7"
+{!> ../../../docs_src/header_params/tutorial003_py310.py!}
+```
- ```Python hl_lines="7"
- {!> ../../../docs_src/header_params/tutorial003_py310.py!}
- ```
+////
🚥 👆 🔗 ⏮️ 👈 *➡ 🛠️* 📨 2️⃣ 🇺🇸🔍 🎚 💖:
...👈 🔌 `uvicorn`, 👈 👆 💪 ⚙️ 💽 👈 🏃 👆 📟.
-!!! note
- 👆 💪 ❎ ⚫️ 🍕 🍕.
+/// note
- 👉 ⚫️❔ 👆 🔜 🎲 🕐 👆 💚 🛠️ 👆 🈸 🏭:
+👆 💪 ❎ ⚫️ 🍕 🍕.
- ```
- pip install "fastapi[standard]"
- ```
+👉 ⚫️❔ 👆 🔜 🎲 🕐 👆 💚 🛠️ 👆 🈸 🏭:
- ❎ `uvicorn` 👷 💽:
+```
+pip install "fastapi[standard]"
+```
+
+❎ `uvicorn` 👷 💽:
+
+```
+pip install "uvicorn[standard]"
+```
- ```
- pip install "uvicorn[standard]"
- ```
+ & 🎏 🔠 📦 🔗 👈 👆 💚 ⚙️.
- & 🎏 🔠 📦 🔗 👈 👆 💚 ⚙️.
+///
## 🏧 👩💻 🦮
{!../../../docs_src/metadata/tutorial001.py!}
```
-!!! tip
- 👆 💪 ✍ ✍ `description` 🏑 & ⚫️ 🔜 ✍ 🔢.
+/// tip
+
+👆 💪 ✍ ✍ `description` 🏑 & ⚫️ 🔜 ✍ 🔢.
+
+///
⏮️ 👉 📳, 🏧 🛠️ 🩺 🔜 👀 💖:
👀 👈 👆 💪 ⚙️ ✍ 🔘 📛, 🖼 "💳" 🔜 🎦 🦁 (**💳**) & "🎀" 🔜 🎦 ❕ (_🎀_).
-!!! tip
- 👆 🚫 ✔️ 🚮 🗃 🌐 🔖 👈 👆 ⚙️.
+/// tip
+
+👆 🚫 ✔️ 🚮 🗃 🌐 🔖 👈 👆 ⚙️.
+
+///
### ⚙️ 👆 🔖
{!../../../docs_src/metadata/tutorial004.py!}
```
-!!! info
- ✍ 🌅 🔃 🔖 [➡ 🛠️ 📳](path-operation-configuration.md#_3){.internal-link target=_blank}.
+/// info
+
+✍ 🌅 🔃 🔖 [➡ 🛠️ 📳](path-operation-configuration.md#_3){.internal-link target=_blank}.
+
+///
### ✅ 🩺
* ⚫️ 💪 🕳 👈 **📨** ⚖️ 🏃 🙆 💪 📟.
* ⤴️ ⚫️ 📨 **📨**.
-!!! note "📡 ℹ"
- 🚥 👆 ✔️ 🔗 ⏮️ `yield`, 🚪 📟 🔜 🏃 *⏮️* 🛠️.
+/// note | "📡 ℹ"
- 🚥 📤 🙆 🖥 📋 (📄 ⏪), 👫 🔜 🏃 *⏮️* 🌐 🛠️.
+🚥 👆 ✔️ 🔗 ⏮️ `yield`, 🚪 📟 🔜 🏃 *⏮️* 🛠️.
+
+🚥 📤 🙆 🖥 📋 (📄 ⏪), 👫 🔜 🏃 *⏮️* 🌐 🛠️.
+
+///
## ✍ 🛠️
{!../../../docs_src/middleware/tutorial001.py!}
```
-!!! tip
- ✔️ 🤯 👈 🛃 © 🎚 💪 🚮 <a href="https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers" class="external-link" target="_blank">⚙️ '✖-' 🔡</a>.
+/// tip
+
+✔️ 🤯 👈 🛃 © 🎚 💪 🚮 <a href="https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers" class="external-link" target="_blank">⚙️ '✖-' 🔡</a>.
+
+✋️ 🚥 👆 ✔️ 🛃 🎚 👈 👆 💚 👩💻 🖥 💪 👀, 👆 💪 🚮 👫 👆 ⚜ 📳 ([⚜ (✖️-🇨🇳 ℹ 🤝)](cors.md){.internal-link target=_blank}) ⚙️ 🔢 `expose_headers` 📄 <a href="https://www.starlette.io/middleware/#corsmiddleware" class="external-link" target="_blank">💃 ⚜ 🩺</a>.
+
+///
+
+/// note | "📡 ℹ"
- ✋️ 🚥 👆 ✔️ 🛃 🎚 👈 👆 💚 👩💻 🖥 💪 👀, 👆 💪 🚮 👫 👆 ⚜ 📳 ([⚜ (✖️-🇨🇳 ℹ 🤝)](cors.md){.internal-link target=_blank}) ⚙️ 🔢 `expose_headers` 📄 <a href="https://www.starlette.io/middleware/#corsmiddleware" class="external-link" target="_blank">💃 ⚜ 🩺</a>.
+👆 💪 ⚙️ `from starlette.requests import Request`.
-!!! note "📡 ℹ"
- 👆 💪 ⚙️ `from starlette.requests import Request`.
+**FastAPI** 🚚 ⚫️ 🏪 👆, 👩💻. ✋️ ⚫️ 👟 🔗 ⚪️➡️ 💃.
- **FastAPI** 🚚 ⚫️ 🏪 👆, 👩💻. ✋️ ⚫️ 👟 🔗 ⚪️➡️ 💃.
+///
### ⏭ & ⏮️ `response`
📤 📚 🔢 👈 👆 💪 🚶♀️ 👆 *➡ 🛠️ 👨🎨* 🔗 ⚫️.
-!!! warning
- 👀 👈 👫 🔢 🚶♀️ 🔗 *➡ 🛠️ 👨🎨*, 🚫 👆 *➡ 🛠️ 🔢*.
+/// warning
+
+👀 👈 👫 🔢 🚶♀️ 🔗 *➡ 🛠️ 👨🎨*, 🚫 👆 *➡ 🛠️ 🔢*.
+
+///
## 📨 👔 📟
✋️ 🚥 👆 🚫 💭 ⚫️❔ 🔠 🔢 📟, 👆 💪 ⚙️ ⌨ 📉 `status`:
-=== "🐍 3️⃣.6️⃣ & 🔛"
+//// tab | 🐍 3️⃣.6️⃣ & 🔛
+
+```Python hl_lines="3 17"
+{!> ../../../docs_src/path_operation_configuration/tutorial001.py!}
+```
+
+////
- ```Python hl_lines="3 17"
- {!> ../../../docs_src/path_operation_configuration/tutorial001.py!}
- ```
+//// tab | 🐍 3️⃣.9️⃣ & 🔛
-=== "🐍 3️⃣.9️⃣ & 🔛"
+```Python hl_lines="3 17"
+{!> ../../../docs_src/path_operation_configuration/tutorial001_py39.py!}
+```
+
+////
- ```Python hl_lines="3 17"
- {!> ../../../docs_src/path_operation_configuration/tutorial001_py39.py!}
- ```
+//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛
-=== "🐍 3️⃣.1️⃣0️⃣ & 🔛"
+```Python hl_lines="1 15"
+{!> ../../../docs_src/path_operation_configuration/tutorial001_py310.py!}
+```
- ```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️⃣ & 🔛"
+//// tab | 🐍 3️⃣.6️⃣ & 🔛
- ```Python hl_lines="17 22 27"
- {!> ../../../docs_src/path_operation_configuration/tutorial002.py!}
- ```
+```Python hl_lines="17 22 27"
+{!> ../../../docs_src/path_operation_configuration/tutorial002.py!}
+```
+
+////
-=== "🐍 3️⃣.9️⃣ & 🔛"
+//// tab | 🐍 3️⃣.9️⃣ & 🔛
- ```Python hl_lines="17 22 27"
- {!> ../../../docs_src/path_operation_configuration/tutorial002_py39.py!}
- ```
+```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!}
- ```
+//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛
+
+```Python hl_lines="15 20 25"
+{!> ../../../docs_src/path_operation_configuration/tutorial002_py310.py!}
+```
+
+////
👫 🔜 🚮 🗄 🔗 & ⚙️ 🏧 🧾 🔢:
👆 💪 🚮 `summary` & `description`:
-=== "🐍 3️⃣.6️⃣ & 🔛"
+//// tab | 🐍 3️⃣.6️⃣ & 🔛
+
+```Python hl_lines="20-21"
+{!> ../../../docs_src/path_operation_configuration/tutorial003.py!}
+```
+
+////
- ```Python hl_lines="20-21"
- {!> ../../../docs_src/path_operation_configuration/tutorial003.py!}
- ```
+//// tab | 🐍 3️⃣.9️⃣ & 🔛
-=== "🐍 3️⃣.9️⃣ & 🔛"
+```Python hl_lines="20-21"
+{!> ../../../docs_src/path_operation_configuration/tutorial003_py39.py!}
+```
+
+////
- ```Python hl_lines="20-21"
- {!> ../../../docs_src/path_operation_configuration/tutorial003_py39.py!}
- ```
+//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛
-=== "🐍 3️⃣.1️⃣0️⃣ & 🔛"
+```Python hl_lines="18-19"
+{!> ../../../docs_src/path_operation_configuration/tutorial003_py310.py!}
+```
- ```Python hl_lines="18-19"
- {!> ../../../docs_src/path_operation_configuration/tutorial003_py310.py!}
- ```
+////
## 📛 ⚪️➡️ #️⃣
👆 💪 ✍ <a href="https://en.wikipedia.org/wiki/Markdown" class="external-link" target="_blank">✍</a> #️⃣ , ⚫️ 🔜 🔬 & 🖥 ☑ (✊ 🔘 🏧 #️⃣ 📐).
-=== "🐍 3️⃣.6️⃣ & 🔛"
+//// tab | 🐍 3️⃣.6️⃣ & 🔛
+
+```Python hl_lines="19-27"
+{!> ../../../docs_src/path_operation_configuration/tutorial004.py!}
+```
+
+////
- ```Python hl_lines="19-27"
- {!> ../../../docs_src/path_operation_configuration/tutorial004.py!}
- ```
+//// tab | 🐍 3️⃣.9️⃣ & 🔛
-=== "🐍 3️⃣.9️⃣ & 🔛"
+```Python hl_lines="19-27"
+{!> ../../../docs_src/path_operation_configuration/tutorial004_py39.py!}
+```
- ```Python hl_lines="19-27"
- {!> ../../../docs_src/path_operation_configuration/tutorial004_py39.py!}
- ```
+////
-=== "🐍 3️⃣.1️⃣0️⃣ & 🔛"
+//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛
- ```Python hl_lines="17-25"
- {!> ../../../docs_src/path_operation_configuration/tutorial004_py310.py!}
- ```
+```Python hl_lines="17-25"
+{!> ../../../docs_src/path_operation_configuration/tutorial004_py310.py!}
+```
+
+////
⚫️ 🔜 ⚙️ 🎓 🩺:
👆 💪 ✔ 📨 📛 ⏮️ 🔢 `response_description`:
-=== "🐍 3️⃣.6️⃣ & 🔛"
+//// tab | 🐍 3️⃣.6️⃣ & 🔛
+
+```Python hl_lines="21"
+{!> ../../../docs_src/path_operation_configuration/tutorial005.py!}
+```
+
+////
+
+//// tab | 🐍 3️⃣.9️⃣ & 🔛
+
+```Python hl_lines="21"
+{!> ../../../docs_src/path_operation_configuration/tutorial005_py39.py!}
+```
+
+////
+
+//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛
+
+```Python hl_lines="19"
+{!> ../../../docs_src/path_operation_configuration/tutorial005_py310.py!}
+```
- ```Python hl_lines="21"
- {!> ../../../docs_src/path_operation_configuration/tutorial005.py!}
- ```
+////
-=== "🐍 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️⃣ "🏆 📨".
+///
<img src="/img/tutorial/path-operation-configuration/image03.png">
🥇, 🗄 `Path` ⚪️➡️ `fastapi`:
-=== "🐍 3️⃣.6️⃣ & 🔛"
+//// tab | 🐍 3️⃣.6️⃣ & 🔛
- ```Python hl_lines="3"
- {!> ../../../docs_src/path_params_numeric_validations/tutorial001.py!}
- ```
+```Python hl_lines="3"
+{!> ../../../docs_src/path_params_numeric_validations/tutorial001.py!}
+```
+
+////
-=== "🐍 3️⃣.1️⃣0️⃣ & 🔛"
+//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛
+
+```Python hl_lines="1"
+{!> ../../../docs_src/path_params_numeric_validations/tutorial001_py310.py!}
+```
- ```Python hl_lines="1"
- {!> ../../../docs_src/path_params_numeric_validations/tutorial001_py310.py!}
- ```
+////
## 📣 🗃
🖼, 📣 `title` 🗃 💲 ➡ 🔢 `item_id` 👆 💪 🆎:
-=== "🐍 3️⃣.6️⃣ & 🔛"
+//// tab | 🐍 3️⃣.6️⃣ & 🔛
- ```Python hl_lines="10"
- {!> ../../../docs_src/path_params_numeric_validations/tutorial001.py!}
- ```
+```Python hl_lines="10"
+{!> ../../../docs_src/path_params_numeric_validations/tutorial001.py!}
+```
+
+////
-=== "🐍 3️⃣.1️⃣0️⃣ & 🔛"
+//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛
- ```Python hl_lines="8"
- {!> ../../../docs_src/path_params_numeric_validations/tutorial001_py310.py!}
- ```
+```Python hl_lines="8"
+{!> ../../../docs_src/path_params_numeric_validations/tutorial001_py310.py!}
+```
-!!! note
- ➡ 🔢 🕧 ✔ ⚫️ ✔️ 🍕 ➡.
+////
- , 👆 🔜 📣 ⚫️ ⏮️ `...` ™ ⚫️ ✔.
+/// note
- 👐, 🚥 👆 📣 ⚫️ ⏮️ `None` ⚖️ ⚒ 🔢 💲, ⚫️ 🔜 🚫 📉 🕳, ⚫️ 🔜 🕧 🚚.
+➡ 🔢 🕧 ✔ ⚫️ ✔️ 🍕 ➡.
+
+, 👆 🔜 📣 ⚫️ ⏮️ `...` ™ ⚫️ ✔.
+
+👐, 🚥 👆 📣 ⚫️ ⏮️ `None` ⚖️ ⚒ 🔢 💲, ⚫️ 🔜 🚫 📉 🕳, ⚫️ 🔜 🕧 🚚.
+
+///
## ✔ 🔢 👆 💪
* `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`.
+👫 🔢 📤 (↩️ ⚙️ 🎓 🔗) 👈 👆 👨🎨 🚫 ™ ❌ 🔃 👫 🆎.
- 👫 🔢 📤 (↩️ ⚙️ 🎓 🔗) 👈 👆 👨🎨 🚫 ™ ❌ 🔃 👫 🆎.
+👈 🌌 👆 💪 ⚙️ 👆 😐 👨🎨 & 🛠️ 🧰 🍵 ✔️ 🚮 🛃 📳 🤷♂ 📚 ❌.
- 👈 🌌 👆 💪 ⚙️ 👆 😐 👨🎨 & 🛠️ 🧰 🍵 ✔️ 🚮 🛃 📳 🤷♂ 📚 ❌.
+///
👉 💼, `item_id` 📣 `int`.
-!!! check
- 👉 🔜 🤝 👆 👨🎨 🐕🦺 🔘 👆 🔢, ⏮️ ❌ ✅, 🛠️, ♒️.
+/// check
+
+👉 🔜 🤝 👆 👨🎨 🐕🦺 🔘 👆 🔢, ⏮️ ❌ ✅, 🛠️, ♒️.
+
+///
## 💽 <abbr title="also known as: serialization, parsing, marshalling">🛠️</abbr>
{"item_id":3}
```
-!!! check
- 👀 👈 💲 👆 🔢 📨 (& 📨) `3`, 🐍 `int`, 🚫 🎻 `"3"`.
+/// check
+
+👀 👈 💲 👆 🔢 📨 (& 📨) `3`, 🐍 `int`, 🚫 🎻 `"3"`.
+
+, ⏮️ 👈 🆎 📄, **FastAPI** 🤝 👆 🏧 📨 <abbr title="converting the string that comes from an HTTP request into Python data">"✍"</abbr>.
- , ⏮️ 👈 🆎 📄, **FastAPI** 🤝 👆 🏧 📨 <abbr title="converting the string that comes from an HTTP request into Python data">"✍"</abbr>.
+///
## 💽 🔬
🎏 ❌ 🔜 😑 🚥 👆 🚚 `float` ↩️ `int`,: <a href="http://127.0.0.1:8000/items/4.2" class="external-link" target="_blank">http://127.0.0.1:8000/items/4.2</a>
-!!! check
- , ⏮️ 🎏 🐍 🆎 📄, **FastAPI** 🤝 👆 💽 🔬.
+/// check
- 👀 👈 ❌ 🎯 🇵🇸 ⚫️❔ ☝ 🌐❔ 🔬 🚫 🚶♀️.
+, ⏮️ 🎏 🐍 🆎 📄, **FastAPI** 🤝 👆 💽 🔬.
- 👉 🙃 👍 ⏪ 🛠️ & 🛠️ 📟 👈 🔗 ⏮️ 👆 🛠️.
+👀 👈 ❌ 🎯 🇵🇸 ⚫️❔ ☝ 🌐❔ 🔬 🚫 🚶♀️.
+
+👉 🙃 👍 ⏪ 🛠️ & 🛠️ 📟 👈 🔗 ⏮️ 👆 🛠️.
+
+///
## 🧾
<img src="/img/tutorial/path-params/image01.png">
-!!! check
- 🔄, ⏮️ 👈 🎏 🐍 🆎 📄, **FastAPI** 🤝 👆 🏧, 🎓 🧾 (🛠️ 🦁 🎚).
+/// check
+
+🔄, ⏮️ 👈 🎏 🐍 🆎 📄, **FastAPI** 🤝 👆 🏧, 🎓 🧾 (🛠️ 🦁 🎚).
+
+👀 👈 ➡ 🔢 📣 🔢.
- 👀 👈 ➡ 🔢 📣 🔢.
+///
## 🐩-⚓️ 💰, 🎛 🧾
{!../../../docs_src/path_params/tutorial005.py!}
```
-!!! info
- <a href="https://docs.python.org/3/library/enum.html" class="external-link" target="_blank">🔢 (⚖️ 🔢) 💪 🐍</a> ↩️ ⏬ 3️⃣.4️⃣.
+/// info
-!!! tip
- 🚥 👆 💭, "📊", "🎓", & "🍏" 📛 🎰 🏫 <abbr title="Technically, Deep Learning model architectures">🏷</abbr>.
+<a href="https://docs.python.org/3/library/enum.html" class="external-link" target="_blank">🔢 (⚖️ 🔢) 💪 🐍</a> ↩️ ⏬ 3️⃣.4️⃣.
+
+///
+
+/// tip
+
+🚥 👆 💭, "📊", "🎓", & "🍏" 📛 🎰 🏫 <abbr title="Technically, Deep Learning model architectures">🏷</abbr>.
+
+///
### 📣 *➡ 🔢*
{!../../../docs_src/path_params/tutorial005.py!}
```
-!!! tip
- 👆 💪 🔐 💲 `"lenet"` ⏮️ `ModelName.lenet.value`.
+/// tip
+
+👆 💪 🔐 💲 `"lenet"` ⏮️ `ModelName.lenet.value`.
+
+///
#### 📨 *🔢 👨🎓*
{!../../../docs_src/path_params/tutorial004.py!}
```
-!!! tip
- 👆 💪 💪 🔢 🔌 `/home/johndoe/myfile.txt`, ⏮️ 🏁 🔪 (`/`).
+/// tip
+
+👆 💪 💪 🔢 🔌 `/home/johndoe/myfile.txt`, ⏮️ 🏁 🔪 (`/`).
+
+👈 💼, 📛 🔜: `/files//home/johndoe/myfile.txt`, ⏮️ 2️⃣✖️ 🔪 (`//`) 🖖 `files` & `home`.
- 👈 💼, 📛 🔜: `/files//home/johndoe/myfile.txt`, ⏮️ 2️⃣✖️ 🔪 (`//`) 🖖 `files` & `home`.
+///
## 🌃
➡️ ✊ 👉 🈸 🖼:
-=== "🐍 3️⃣.6️⃣ & 🔛"
+//// tab | 🐍 3️⃣.6️⃣ & 🔛
- ```Python hl_lines="9"
- {!> ../../../docs_src/query_params_str_validations/tutorial001.py!}
- ```
+```Python hl_lines="9"
+{!> ../../../docs_src/query_params_str_validations/tutorial001.py!}
+```
+
+////
+
+//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛
-=== "🐍 3️⃣.1️⃣0️⃣ & 🔛"
+```Python hl_lines="7"
+{!> ../../../docs_src/query_params_str_validations/tutorial001_py310.py!}
+```
- ```Python hl_lines="7"
- {!> ../../../docs_src/query_params_str_validations/tutorial001_py310.py!}
- ```
+////
🔢 🔢 `q` 🆎 `Union[str, None]` (⚖️ `str | None` 🐍 3️⃣.1️⃣0️⃣), 👈 ⛓ 👈 ⚫️ 🆎 `str` ✋️ 💪 `None`, & 👐, 🔢 💲 `None`, FastAPI 🔜 💭 ⚫️ 🚫 ✔.
-!!! note
- FastAPI 🔜 💭 👈 💲 `q` 🚫 ✔ ↩️ 🔢 💲 `= None`.
+/// note
+
+FastAPI 🔜 💭 👈 💲 `q` 🚫 ✔ ↩️ 🔢 💲 `= None`.
- `Union` `Union[str, None]` 🔜 ✔ 👆 👨🎨 🤝 👆 👍 🐕🦺 & 🔍 ❌.
+ `Union` `Union[str, None]` 🔜 ✔ 👆 👨🎨 🤝 👆 👍 🐕🦺 & 🔍 ❌.
+
+///
## 🌖 🔬
🏆 👈, 🥇 🗄 `Query` ⚪️➡️ `fastapi`:
-=== "🐍 3️⃣.6️⃣ & 🔛"
+//// tab | 🐍 3️⃣.6️⃣ & 🔛
+
+```Python hl_lines="3"
+{!> ../../../docs_src/query_params_str_validations/tutorial002.py!}
+```
- ```Python hl_lines="3"
- {!> ../../../docs_src/query_params_str_validations/tutorial002.py!}
- ```
+////
-=== "🐍 3️⃣.1️⃣0️⃣ & 🔛"
+//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛
+
+```Python hl_lines="1"
+{!> ../../../docs_src/query_params_str_validations/tutorial002_py310.py!}
+```
- ```Python hl_lines="1"
- {!> ../../../docs_src/query_params_str_validations/tutorial002_py310.py!}
- ```
+////
## ⚙️ `Query` 🔢 💲
& 🔜 ⚙️ ⚫️ 🔢 💲 👆 🔢, ⚒ 🔢 `max_length` 5️⃣0️⃣:
-=== "🐍 3️⃣.6️⃣ & 🔛"
+//// tab | 🐍 3️⃣.6️⃣ & 🔛
- ```Python hl_lines="9"
- {!> ../../../docs_src/query_params_str_validations/tutorial002.py!}
- ```
+```Python hl_lines="9"
+{!> ../../../docs_src/query_params_str_validations/tutorial002.py!}
+```
+
+////
+
+//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛
-=== "🐍 3️⃣.1️⃣0️⃣ & 🔛"
+```Python hl_lines="7"
+{!> ../../../docs_src/query_params_str_validations/tutorial002_py310.py!}
+```
- ```Python hl_lines="7"
- {!> ../../../docs_src/query_params_str_validations/tutorial002_py310.py!}
- ```
+////
👥 ✔️ ❎ 🔢 💲 `None` 🔢 ⏮️ `Query()`, 👥 💪 🔜 ⚒ 🔢 💲 ⏮️ 🔢 `Query(default=None)`, ⚫️ 🍦 🎏 🎯 ⚖ 👈 🔢 💲.
✋️ ⚫️ 📣 ⚫️ 🎯 💆♂ 🔢 🔢.
-!!! info
- ✔️ 🤯 👈 🌅 ⚠ 🍕 ⚒ 🔢 📦 🍕:
+/// info
- ```Python
- = None
- ```
+✔️ 🤯 👈 🌅 ⚠ 🍕 ⚒ 🔢 📦 🍕:
- ⚖️:
+```Python
+= None
+```
+
+⚖️:
+
+```Python
+= Query(default=None)
+```
- ```Python
- = Query(default=None)
- ```
+⚫️ 🔜 ⚙️ 👈 `None` 🔢 💲, & 👈 🌌 ⚒ 🔢 **🚫 ✔**.
- ⚫️ 🔜 ⚙️ 👈 `None` 🔢 💲, & 👈 🌌 ⚒ 🔢 **🚫 ✔**.
+ `Union[str, None]` 🍕 ✔ 👆 👨🎨 🚚 👻 🐕🦺, ✋️ ⚫️ 🚫 ⚫️❔ 💬 FastAPI 👈 👉 🔢 🚫 ✔.
- `Union[str, None]` 🍕 ✔ 👆 👨🎨 🚚 👻 🐕🦺, ✋️ ⚫️ 🚫 ⚫️❔ 💬 FastAPI 👈 👉 🔢 🚫 ✔.
+///
⤴️, 👥 💪 🚶♀️ 🌅 🔢 `Query`. 👉 💼, `max_length` 🔢 👈 ✔ 🎻:
👆 💪 🚮 🔢 `min_length`:
-=== "🐍 3️⃣.6️⃣ & 🔛"
+//// tab | 🐍 3️⃣.6️⃣ & 🔛
+
+```Python hl_lines="10"
+{!> ../../../docs_src/query_params_str_validations/tutorial003.py!}
+```
+
+////
- ```Python hl_lines="10"
- {!> ../../../docs_src/query_params_str_validations/tutorial003.py!}
- ```
+//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛
-=== "🐍 3️⃣.1️⃣0️⃣ & 🔛"
+```Python hl_lines="7"
+{!> ../../../docs_src/query_params_str_validations/tutorial003_py310.py!}
+```
- ```Python hl_lines="7"
- {!> ../../../docs_src/query_params_str_validations/tutorial003_py310.py!}
- ```
+////
## 🚮 🥔 🧬
👆 💪 🔬 <abbr title="A regular expression, regex or regexp is a sequence of characters that define a search pattern for strings.">🥔 🧬</abbr> 👈 🔢 🔜 🏏:
-=== "🐍 3️⃣.6️⃣ & 🔛"
+//// tab | 🐍 3️⃣.6️⃣ & 🔛
- ```Python hl_lines="11"
- {!> ../../../docs_src/query_params_str_validations/tutorial004.py!}
- ```
+```Python hl_lines="11"
+{!> ../../../docs_src/query_params_str_validations/tutorial004.py!}
+```
+
+////
-=== "🐍 3️⃣.1️⃣0️⃣ & 🔛"
+//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛
- ```Python hl_lines="9"
- {!> ../../../docs_src/query_params_str_validations/tutorial004_py310.py!}
- ```
+```Python hl_lines="9"
+{!> ../../../docs_src/query_params_str_validations/tutorial004_py310.py!}
+```
+
+////
👉 🎯 🥔 🧬 ✅ 👈 📨 🔢 💲:
{!../../../docs_src/query_params_str_validations/tutorial005.py!}
```
-!!! note
- ✔️ 🔢 💲 ⚒ 🔢 📦.
+/// note
+
+✔️ 🔢 💲 ⚒ 🔢 📦.
+
+///
## ⚒ ⚫️ ✔
{!../../../docs_src/query_params_str_validations/tutorial006b.py!}
```
-!!! info
- 🚥 👆 🚫 👀 👈 `...` ⏭: ⚫️ 🎁 👁 💲, ⚫️ <a href="https://docs.python.org/3/library/constants.html#Ellipsis" class="external-link" target="_blank">🍕 🐍 & 🤙 "❕"</a>.
+/// info
+
+🚥 👆 🚫 👀 👈 `...` ⏭: ⚫️ 🎁 👁 💲, ⚫️ <a href="https://docs.python.org/3/library/constants.html#Ellipsis" class="external-link" target="_blank">🍕 🐍 & 🤙 "❕"</a>.
+
+⚫️ ⚙️ Pydantic & FastAPI 🎯 📣 👈 💲 ✔.
- ⚫️ ⚙️ Pydantic & FastAPI 🎯 📣 👈 💲 ✔.
+///
👉 🔜 ➡️ **FastAPI** 💭 👈 👉 🔢 ✔.
👈, 👆 💪 📣 👈 `None` ☑ 🆎 ✋️ ⚙️ `default=...`:
-=== "🐍 3️⃣.6️⃣ & 🔛"
+//// tab | 🐍 3️⃣.6️⃣ & 🔛
+
+```Python hl_lines="9"
+{!> ../../../docs_src/query_params_str_validations/tutorial006c.py!}
+```
+
+////
+
+//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛
+
+```Python hl_lines="7"
+{!> ../../../docs_src/query_params_str_validations/tutorial006c_py310.py!}
+```
- ```Python hl_lines="9"
- {!> ../../../docs_src/query_params_str_validations/tutorial006c.py!}
- ```
+////
-=== "🐍 3️⃣.1️⃣0️⃣ & 🔛"
+/// tip
- ```Python hl_lines="7"
- {!> ../../../docs_src/query_params_str_validations/tutorial006c_py310.py!}
- ```
+Pydantic, ❔ ⚫️❔ 🏋️ 🌐 💽 🔬 & 🛠️ FastAPI, ✔️ 🎁 🎭 🕐❔ 👆 ⚙️ `Optional` ⚖️ `Union[Something, None]` 🍵 🔢 💲, 👆 💪 ✍ 🌅 🔃 ⚫️ Pydantic 🩺 🔃 <a href="https://docs.pydantic.dev/latest/concepts/models/#required-optional-fields" class="external-link" target="_blank">✔ 📦 🏑</a>.
-!!! tip
- Pydantic, ❔ ⚫️❔ 🏋️ 🌐 💽 🔬 & 🛠️ FastAPI, ✔️ 🎁 🎭 🕐❔ 👆 ⚙️ `Optional` ⚖️ `Union[Something, None]` 🍵 🔢 💲, 👆 💪 ✍ 🌅 🔃 ⚫️ Pydantic 🩺 🔃 <a href="https://docs.pydantic.dev/latest/concepts/models/#required-optional-fields" class="external-link" target="_blank">✔ 📦 🏑</a>.
+///
### ⚙️ Pydantic `Required` ↩️ ❕ (`...`)
{!../../../docs_src/query_params_str_validations/tutorial006d.py!}
```
-!!! tip
- 💭 👈 🌅 💼, 🕐❔ 🕳 🚚, 👆 💪 🎯 🚫 `default` 🔢, 👆 🛎 🚫 ✔️ ⚙️ `...` 🚫 `Required`.
+/// tip
+
+💭 👈 🌅 💼, 🕐❔ 🕳 🚚, 👆 💪 🎯 🚫 `default` 🔢, 👆 🛎 🚫 ✔️ ⚙️ `...` 🚫 `Required`.
+
+///
## 🔢 🔢 📇 / 💗 💲
🖼, 📣 🔢 🔢 `q` 👈 💪 😑 💗 🕰 📛, 👆 💪 ✍:
-=== "🐍 3️⃣.6️⃣ & 🔛"
+//// tab | 🐍 3️⃣.6️⃣ & 🔛
+
+```Python hl_lines="9"
+{!> ../../../docs_src/query_params_str_validations/tutorial011.py!}
+```
- ```Python hl_lines="9"
- {!> ../../../docs_src/query_params_str_validations/tutorial011.py!}
- ```
+////
-=== "🐍 3️⃣.9️⃣ & 🔛"
+//// tab | 🐍 3️⃣.9️⃣ & 🔛
- ```Python hl_lines="9"
- {!> ../../../docs_src/query_params_str_validations/tutorial011_py39.py!}
- ```
+```Python hl_lines="9"
+{!> ../../../docs_src/query_params_str_validations/tutorial011_py39.py!}
+```
-=== "🐍 3️⃣.1️⃣0️⃣ & 🔛"
+////
- ```Python hl_lines="7"
- {!> ../../../docs_src/query_params_str_validations/tutorial011_py310.py!}
- ```
+//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛
+
+```Python hl_lines="7"
+{!> ../../../docs_src/query_params_str_validations/tutorial011_py310.py!}
+```
+
+////
⤴️, ⏮️ 📛 💖:
}
```
-!!! tip
- 📣 🔢 🔢 ⏮️ 🆎 `list`, 💖 🖼 🔛, 👆 💪 🎯 ⚙️ `Query`, ⏪ ⚫️ 🔜 🔬 📨 💪.
+/// tip
+
+📣 🔢 🔢 ⏮️ 🆎 `list`, 💖 🖼 🔛, 👆 💪 🎯 ⚙️ `Query`, ⏪ ⚫️ 🔜 🔬 📨 💪.
+
+///
🎓 🛠️ 🩺 🔜 ℹ ➡️, ✔ 💗 💲:
& 👆 💪 🔬 🔢 `list` 💲 🚥 👌 🚚:
-=== "🐍 3️⃣.6️⃣ & 🔛"
+//// tab | 🐍 3️⃣.6️⃣ & 🔛
- ```Python hl_lines="9"
- {!> ../../../docs_src/query_params_str_validations/tutorial012.py!}
- ```
+```Python hl_lines="9"
+{!> ../../../docs_src/query_params_str_validations/tutorial012.py!}
+```
+
+////
+
+//// tab | 🐍 3️⃣.9️⃣ & 🔛
-=== "🐍 3️⃣.9️⃣ & 🔛"
+```Python hl_lines="7"
+{!> ../../../docs_src/query_params_str_validations/tutorial012_py39.py!}
+```
- ```Python hl_lines="7"
- {!> ../../../docs_src/query_params_str_validations/tutorial012_py39.py!}
- ```
+////
🚥 👆 🚶:
{!../../../docs_src/query_params_str_validations/tutorial013.py!}
```
-!!! note
- ✔️ 🤯 👈 👉 💼, FastAPI 🏆 🚫 ✅ 🎚 📇.
+/// note
- 🖼, `List[int]` 🔜 ✅ (& 📄) 👈 🎚 📇 🔢. ✋️ `list` 😞 🚫🔜.
+✔️ 🤯 👈 👉 💼, FastAPI 🏆 🚫 ✅ 🎚 📇.
+
+🖼, `List[int]` 🔜 ✅ (& 📄) 👈 🎚 📇 🔢. ✋️ `list` 😞 🚫🔜.
+
+///
## 📣 🌅 🗃
👈 ℹ 🔜 🔌 🏗 🗄 & ⚙️ 🧾 👩💻 🔢 & 🔢 🧰.
-!!! note
- ✔️ 🤯 👈 🎏 🧰 5️⃣📆 ✔️ 🎏 🎚 🗄 🐕🦺.
+/// note
+
+✔️ 🤯 👈 🎏 🧰 5️⃣📆 ✔️ 🎏 🎚 🗄 🐕🦺.
- 👫 💪 🚫 🎦 🌐 ➕ ℹ 📣, 👐 🌅 💼, ❌ ⚒ ⏪ 📄 🛠️.
+👫 💪 🚫 🎦 🌐 ➕ ℹ 📣, 👐 🌅 💼, ❌ ⚒ ⏪ 📄 🛠️.
+
+///
👆 💪 🚮 `title`:
-=== "🐍 3️⃣.6️⃣ & 🔛"
+//// tab | 🐍 3️⃣.6️⃣ & 🔛
- ```Python hl_lines="10"
- {!> ../../../docs_src/query_params_str_validations/tutorial007.py!}
- ```
+```Python hl_lines="10"
+{!> ../../../docs_src/query_params_str_validations/tutorial007.py!}
+```
-=== "🐍 3️⃣.1️⃣0️⃣ & 🔛"
+////
- ```Python hl_lines="8"
- {!> ../../../docs_src/query_params_str_validations/tutorial007_py310.py!}
- ```
+//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛
+
+```Python hl_lines="8"
+{!> ../../../docs_src/query_params_str_validations/tutorial007_py310.py!}
+```
+
+////
& `description`:
-=== "🐍 3️⃣.6️⃣ & 🔛"
+//// tab | 🐍 3️⃣.6️⃣ & 🔛
+
+```Python hl_lines="13"
+{!> ../../../docs_src/query_params_str_validations/tutorial008.py!}
+```
+
+////
- ```Python hl_lines="13"
- {!> ../../../docs_src/query_params_str_validations/tutorial008.py!}
- ```
+//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛
-=== "🐍 3️⃣.1️⃣0️⃣ & 🔛"
+```Python hl_lines="11"
+{!> ../../../docs_src/query_params_str_validations/tutorial008_py310.py!}
+```
- ```Python hl_lines="11"
- {!> ../../../docs_src/query_params_str_validations/tutorial008_py310.py!}
- ```
+////
## 📛 🔢
⤴️ 👆 💪 📣 `alias`, & 👈 📛 ⚫️❔ 🔜 ⚙️ 🔎 🔢 💲:
-=== "🐍 3️⃣.6️⃣ & 🔛"
+//// tab | 🐍 3️⃣.6️⃣ & 🔛
+
+```Python hl_lines="9"
+{!> ../../../docs_src/query_params_str_validations/tutorial009.py!}
+```
+
+////
- ```Python hl_lines="9"
- {!> ../../../docs_src/query_params_str_validations/tutorial009.py!}
- ```
+//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛
-=== "🐍 3️⃣.1️⃣0️⃣ & 🔛"
+```Python hl_lines="7"
+{!> ../../../docs_src/query_params_str_validations/tutorial009_py310.py!}
+```
- ```Python hl_lines="7"
- {!> ../../../docs_src/query_params_str_validations/tutorial009_py310.py!}
- ```
+////
## 😛 🔢
⤴️ 🚶♀️ 🔢 `deprecated=True` `Query`:
-=== "🐍 3️⃣.6️⃣ & 🔛"
+//// tab | 🐍 3️⃣.6️⃣ & 🔛
+
+```Python hl_lines="18"
+{!> ../../../docs_src/query_params_str_validations/tutorial010.py!}
+```
+
+////
- ```Python hl_lines="18"
- {!> ../../../docs_src/query_params_str_validations/tutorial010.py!}
- ```
+//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛
-=== "🐍 3️⃣.1️⃣0️⃣ & 🔛"
+```Python hl_lines="16"
+{!> ../../../docs_src/query_params_str_validations/tutorial010_py310.py!}
+```
- ```Python hl_lines="16"
- {!> ../../../docs_src/query_params_str_validations/tutorial010_py310.py!}
- ```
+////
🩺 🔜 🎦 ⚫️ 💖 👉:
🚫 🔢 🔢 ⚪️➡️ 🏗 🗄 🔗 (& ➡️, ⚪️➡️ 🏧 🧾 ⚙️), ⚒ 🔢 `include_in_schema` `Query` `False`:
-=== "🐍 3️⃣.6️⃣ & 🔛"
+//// tab | 🐍 3️⃣.6️⃣ & 🔛
+
+```Python hl_lines="10"
+{!> ../../../docs_src/query_params_str_validations/tutorial014.py!}
+```
- ```Python hl_lines="10"
- {!> ../../../docs_src/query_params_str_validations/tutorial014.py!}
- ```
+////
-=== "🐍 3️⃣.1️⃣0️⃣ & 🔛"
+//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛
+
+```Python hl_lines="8"
+{!> ../../../docs_src/query_params_str_validations/tutorial014_py310.py!}
+```
- ```Python hl_lines="8"
- {!> ../../../docs_src/query_params_str_validations/tutorial014_py310.py!}
- ```
+////
## 🌃
🎏 🌌, 👆 💪 📣 📦 🔢 🔢, ⚒ 👫 🔢 `None`:
-=== "🐍 3️⃣.6️⃣ & 🔛"
+//// tab | 🐍 3️⃣.6️⃣ & 🔛
- ```Python hl_lines="9"
- {!> ../../../docs_src/query_params/tutorial002.py!}
- ```
+```Python hl_lines="9"
+{!> ../../../docs_src/query_params/tutorial002.py!}
+```
+
+////
-=== "🐍 3️⃣.1️⃣0️⃣ & 🔛"
+//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛
- ```Python hl_lines="7"
- {!> ../../../docs_src/query_params/tutorial002_py310.py!}
- ```
+```Python hl_lines="7"
+{!> ../../../docs_src/query_params/tutorial002_py310.py!}
+```
+
+////
👉 💼, 🔢 🔢 `q` 🔜 📦, & 🔜 `None` 🔢.
-!!! check
- 👀 👈 **FastAPI** 🙃 🥃 👀 👈 ➡ 🔢 `item_id` ➡ 🔢 & `q` 🚫,, ⚫️ 🔢 🔢.
+/// check
+
+👀 👈 **FastAPI** 🙃 🥃 👀 👈 ➡ 🔢 `item_id` ➡ 🔢 & `q` 🚫,, ⚫️ 🔢 🔢.
+
+///
## 🔢 🔢 🆎 🛠️
👆 💪 📣 `bool` 🆎, & 👫 🔜 🗜:
-=== "🐍 3️⃣.6️⃣ & 🔛"
+//// tab | 🐍 3️⃣.6️⃣ & 🔛
+
+```Python hl_lines="9"
+{!> ../../../docs_src/query_params/tutorial003.py!}
+```
+
+////
- ```Python hl_lines="9"
- {!> ../../../docs_src/query_params/tutorial003.py!}
- ```
+//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛
-=== "🐍 3️⃣.1️⃣0️⃣ & 🔛"
+```Python hl_lines="7"
+{!> ../../../docs_src/query_params/tutorial003_py310.py!}
+```
- ```Python hl_lines="7"
- {!> ../../../docs_src/query_params/tutorial003_py310.py!}
- ```
+////
👉 💼, 🚥 👆 🚶:
👫 🔜 🔬 📛:
-=== "🐍 3️⃣.6️⃣ & 🔛"
+//// tab | 🐍 3️⃣.6️⃣ & 🔛
+
+```Python hl_lines="8 10"
+{!> ../../../docs_src/query_params/tutorial004.py!}
+```
+
+////
- ```Python hl_lines="8 10"
- {!> ../../../docs_src/query_params/tutorial004.py!}
- ```
+//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛
-=== "🐍 3️⃣.1️⃣0️⃣ & 🔛"
+```Python hl_lines="6 8"
+{!> ../../../docs_src/query_params/tutorial004_py310.py!}
+```
- ```Python hl_lines="6 8"
- {!> ../../../docs_src/query_params/tutorial004_py310.py!}
- ```
+////
## ✔ 🔢 🔢
& ↗️, 👆 💪 🔬 🔢 ✔, ✔️ 🔢 💲, & 🍕 📦:
-=== "🐍 3️⃣.6️⃣ & 🔛"
+//// tab | 🐍 3️⃣.6️⃣ & 🔛
- ```Python hl_lines="10"
- {!> ../../../docs_src/query_params/tutorial006.py!}
- ```
+```Python hl_lines="10"
+{!> ../../../docs_src/query_params/tutorial006.py!}
+```
-=== "🐍 3️⃣.1️⃣0️⃣ & 🔛"
+////
- ```Python hl_lines="8"
- {!> ../../../docs_src/query_params/tutorial006_py310.py!}
- ```
+//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛
+
+```Python hl_lines="8"
+{!> ../../../docs_src/query_params/tutorial006_py310.py!}
+```
+
+////
👉 💼, 📤 3️⃣ 🔢 🔢:
* `skip`, `int` ⏮️ 🔢 💲 `0`.
* `limit`, 📦 `int`.
-!!! tip
- 👆 💪 ⚙️ `Enum`Ⓜ 🎏 🌌 ⏮️ [➡ 🔢](path-params.md#_7){.internal-link target=_blank}.
+/// tip
+
+👆 💪 ⚙️ `Enum`Ⓜ 🎏 🌌 ⏮️ [➡ 🔢](path-params.md#_7){.internal-link target=_blank}.
+
+///
👆 💪 🔬 📁 📂 👩💻 ⚙️ `File`.
-!!! info
- 📨 📂 📁, 🥇 ❎ <a href="https://github.com/Kludex/python-multipart" class="external-link" target="_blank">`python-multipart`</a>.
+/// info
- 🤶 Ⓜ. `pip install python-multipart`.
+📨 📂 📁, 🥇 ❎ <a href="https://github.com/Kludex/python-multipart" class="external-link" target="_blank">`python-multipart`</a>.
- 👉 ↩️ 📂 📁 📨 "📨 💽".
+🤶 Ⓜ. `pip install python-multipart`.
+
+👉 ↩️ 📂 📁 📨 "📨 💽".
+
+///
## 🗄 `File`
{!../../../docs_src/request_files/tutorial001.py!}
```
-!!! info
- `File` 🎓 👈 😖 🔗 ⚪️➡️ `Form`.
+/// info
+
+`File` 🎓 👈 😖 🔗 ⚪️➡️ `Form`.
+
+✋️ 💭 👈 🕐❔ 👆 🗄 `Query`, `Path`, `File` & 🎏 ⚪️➡️ `fastapi`, 👈 🤙 🔢 👈 📨 🎁 🎓.
- ✋️ 💭 👈 🕐❔ 👆 🗄 `Query`, `Path`, `File` & 🎏 ⚪️➡️ `fastapi`, 👈 🤙 🔢 👈 📨 🎁 🎓.
+///
-!!! tip
- 📣 📁 💪, 👆 💪 ⚙️ `File`, ↩️ ⏪ 🔢 🔜 🔬 🔢 🔢 ⚖️ 💪 (🎻) 🔢.
+/// tip
+
+📣 📁 💪, 👆 💪 ⚙️ `File`, ↩️ ⏪ 🔢 🔜 🔬 🔢 🔢 ⚖️ 💪 (🎻) 🔢.
+
+///
📁 🔜 📂 "📨 💽".
contents = myfile.file.read()
```
-!!! note "`async` 📡 ℹ"
- 🕐❔ 👆 ⚙️ `async` 👩🔬, **FastAPI** 🏃 📁 👩🔬 🧵 & ⌛ 👫.
+/// note | "`async` 📡 ℹ"
+
+🕐❔ 👆 ⚙️ `async` 👩🔬, **FastAPI** 🏃 📁 👩🔬 🧵 & ⌛ 👫.
-!!! note "💃 📡 ℹ"
- **FastAPI**'Ⓜ `UploadFile` 😖 🔗 ⚪️➡️ **💃**'Ⓜ `UploadFile`, ✋️ 🚮 💪 🍕 ⚒ ⚫️ 🔗 ⏮️ **Pydantic** & 🎏 🍕 FastAPI.
+///
+
+/// note | "💃 📡 ℹ"
+
+**FastAPI**'Ⓜ `UploadFile` 😖 🔗 ⚪️➡️ **💃**'Ⓜ `UploadFile`, ✋️ 🚮 💪 🍕 ⚒ ⚫️ 🔗 ⏮️ **Pydantic** & 🎏 🍕 FastAPI.
+
+///
## ⚫️❔ "📨 💽"
**FastAPI** 🔜 ⚒ 💭 ✍ 👈 📊 ⚪️➡️ ▶️️ 🥉 ↩️ 🎻.
-!!! note "📡 ℹ"
- 📊 ⚪️➡️ 📨 🛎 🗜 ⚙️ "📻 🆎" `application/x-www-form-urlencoded` 🕐❔ ⚫️ 🚫 🔌 📁.
+/// note | "📡 ℹ"
+
+📊 ⚪️➡️ 📨 🛎 🗜 ⚙️ "📻 🆎" `application/x-www-form-urlencoded` 🕐❔ ⚫️ 🚫 🔌 📁.
+
+✋️ 🕐❔ 📨 🔌 📁, ⚫️ 🗜 `multipart/form-data`. 🚥 👆 ⚙️ `File`, **FastAPI** 🔜 💭 ⚫️ ✔️ 🤚 📁 ⚪️➡️ ☑ 🍕 💪.
+
+🚥 👆 💚 ✍ 🌖 🔃 👉 🔢 & 📨 🏑, 👳 <a href="https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods/POST" class="external-link" target="_blank"><abbr title="Mozilla Developer Network">🏇</abbr> 🕸 🩺 <code>POST</code></a>.
+
+///
- ✋️ 🕐❔ 📨 🔌 📁, ⚫️ 🗜 `multipart/form-data`. 🚥 👆 ⚙️ `File`, **FastAPI** 🔜 💭 ⚫️ ✔️ 🤚 📁 ⚪️➡️ ☑ 🍕 💪.
+/// warning
- 🚥 👆 💚 ✍ 🌖 🔃 👉 🔢 & 📨 🏑, 👳 <a href="https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods/POST" class="external-link" target="_blank"><abbr title="Mozilla Developer Network">🏇</abbr> 🕸 🩺 <code>POST</code></a>.
+👆 💪 📣 💗 `File` & `Form` 🔢 *➡ 🛠️*, ✋️ 👆 💪 🚫 📣 `Body` 🏑 👈 👆 ⌛ 📨 🎻, 📨 🔜 ✔️ 💪 🗜 ⚙️ `multipart/form-data` ↩️ `application/json`.
-!!! warning
- 👆 💪 📣 💗 `File` & `Form` 🔢 *➡ 🛠️*, ✋️ 👆 💪 🚫 📣 `Body` 🏑 👈 👆 ⌛ 📨 🎻, 📨 🔜 ✔️ 💪 🗜 ⚙️ `multipart/form-data` ↩️ `application/json`.
+👉 🚫 🚫 **FastAPI**, ⚫️ 🍕 🇺🇸🔍 🛠️.
- 👉 🚫 🚫 **FastAPI**, ⚫️ 🍕 🇺🇸🔍 🛠️.
+///
## 📦 📁 📂
👆 💪 ⚒ 📁 📦 ⚙️ 🐩 🆎 ✍ & ⚒ 🔢 💲 `None`:
-=== "🐍 3️⃣.6️⃣ & 🔛"
+//// tab | 🐍 3️⃣.6️⃣ & 🔛
- ```Python hl_lines="9 17"
- {!> ../../../docs_src/request_files/tutorial001_02.py!}
- ```
+```Python hl_lines="9 17"
+{!> ../../../docs_src/request_files/tutorial001_02.py!}
+```
+
+////
-=== "🐍 3️⃣.1️⃣0️⃣ & 🔛"
+//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛
+
+```Python hl_lines="7 14"
+{!> ../../../docs_src/request_files/tutorial001_02_py310.py!}
+```
- ```Python hl_lines="7 14"
- {!> ../../../docs_src/request_files/tutorial001_02_py310.py!}
- ```
+////
## `UploadFile` ⏮️ 🌖 🗃
⚙️ 👈, 📣 📇 `bytes` ⚖️ `UploadFile`:
-=== "🐍 3️⃣.6️⃣ & 🔛"
+//// tab | 🐍 3️⃣.6️⃣ & 🔛
+
+```Python hl_lines="10 15"
+{!> ../../../docs_src/request_files/tutorial002.py!}
+```
+
+////
- ```Python hl_lines="10 15"
- {!> ../../../docs_src/request_files/tutorial002.py!}
- ```
+//// tab | 🐍 3️⃣.9️⃣ & 🔛
-=== "🐍 3️⃣.9️⃣ & 🔛"
+```Python hl_lines="8 13"
+{!> ../../../docs_src/request_files/tutorial002_py39.py!}
+```
- ```Python hl_lines="8 13"
- {!> ../../../docs_src/request_files/tutorial002_py39.py!}
- ```
+////
👆 🔜 📨, 📣, `list` `bytes` ⚖️ `UploadFile`Ⓜ.
-!!! note "📡 ℹ"
- 👆 💪 ⚙️ `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️⃣ & 🔛"
+//// tab | 🐍 3️⃣.6️⃣ & 🔛
- ```Python hl_lines="18"
- {!> ../../../docs_src/request_files/tutorial003.py!}
- ```
+```Python hl_lines="18"
+{!> ../../../docs_src/request_files/tutorial003.py!}
+```
-=== "🐍 3️⃣.9️⃣ & 🔛"
+////
+
+//// tab | 🐍 3️⃣.9️⃣ & 🔛
+
+```Python hl_lines="16"
+{!> ../../../docs_src/request_files/tutorial003_py39.py!}
+```
- ```Python hl_lines="16"
- {!> ../../../docs_src/request_files/tutorial003_py39.py!}
- ```
+////
## 🌃
👆 💪 🔬 📁 & 📨 🏑 🎏 🕰 ⚙️ `File` & `Form`.
-!!! info
- 📨 📂 📁 & /⚖️ 📨 📊, 🥇 ❎ <a href="https://github.com/Kludex/python-multipart" class="external-link" target="_blank">`python-multipart`</a>.
+/// info
- 🤶 Ⓜ. `pip install python-multipart`.
+📨 📂 📁 & /⚖️ 📨 📊, 🥇 ❎ <a href="https://github.com/Kludex/python-multipart" class="external-link" target="_blank">`python-multipart`</a>.
+
+🤶 Ⓜ. `pip install python-multipart`.
+
+///
## 🗄 `File` & `Form`
& 👆 💪 📣 📁 `bytes` & `UploadFile`.
-!!! warning
- 👆 💪 📣 💗 `File` & `Form` 🔢 *➡ 🛠️*, ✋️ 👆 💪 🚫 📣 `Body` 🏑 👈 👆 ⌛ 📨 🎻, 📨 🔜 ✔️ 💪 🗜 ⚙️ `multipart/form-data` ↩️ `application/json`.
+/// warning
+
+👆 💪 📣 💗 `File` & `Form` 🔢 *➡ 🛠️*, ✋️ 👆 💪 🚫 📣 `Body` 🏑 👈 👆 ⌛ 📨 🎻, 📨 🔜 ✔️ 💪 🗜 ⚙️ `multipart/form-data` ↩️ `application/json`.
+
+👉 🚫 🚫 **FastAPI**, ⚫️ 🍕 🇺🇸🔍 🛠️.
- 👉 🚫 🚫 **FastAPI**, ⚫️ 🍕 🇺🇸🔍 🛠️.
+///
## 🌃
🕐❔ 👆 💪 📨 📨 🏑 ↩️ 🎻, 👆 💪 ⚙️ `Form`.
-!!! info
- ⚙️ 📨, 🥇 ❎ <a href="https://github.com/Kludex/python-multipart" class="external-link" target="_blank">`python-multipart`</a>.
+/// info
- 🤶 Ⓜ. `pip install python-multipart`.
+⚙️ 📨, 🥇 ❎ <a href="https://github.com/Kludex/python-multipart" class="external-link" target="_blank">`python-multipart`</a>.
+
+🤶 Ⓜ. `pip install python-multipart`.
+
+///
## 🗄 `Form`
⏮️ `Form` 👆 💪 📣 🎏 📳 ⏮️ `Body` (& `Query`, `Path`, `Cookie`), 🔌 🔬, 🖼, 📛 (✅ `user-name` ↩️ `username`), ♒️.
-!!! info
- `Form` 🎓 👈 😖 🔗 ⚪️➡️ `Body`.
+/// info
+
+`Form` 🎓 👈 😖 🔗 ⚪️➡️ `Body`.
+
+///
+
+/// tip
-!!! tip
- 📣 📨 💪, 👆 💪 ⚙️ `Form` 🎯, ↩️ 🍵 ⚫️ 🔢 🔜 🔬 🔢 🔢 ⚖️ 💪 (🎻) 🔢.
+📣 📨 💪, 👆 💪 ⚙️ `Form` 🎯, ↩️ 🍵 ⚫️ 🔢 🔜 🔬 🔢 🔢 ⚖️ 💪 (🎻) 🔢.
+
+///
## 🔃 "📨 🏑"
**FastAPI** 🔜 ⚒ 💭 ✍ 👈 📊 ⚪️➡️ ▶️️ 🥉 ↩️ 🎻.
-!!! note "📡 ℹ"
- 📊 ⚪️➡️ 📨 🛎 🗜 ⚙️ "📻 🆎" `application/x-www-form-urlencoded`.
+/// note | "📡 ℹ"
+
+📊 ⚪️➡️ 📨 🛎 🗜 ⚙️ "📻 🆎" `application/x-www-form-urlencoded`.
+
+✋️ 🕐❔ 📨 🔌 📁, ⚫️ 🗜 `multipart/form-data`. 👆 🔜 ✍ 🔃 🚚 📁 ⏭ 📃.
+
+🚥 👆 💚 ✍ 🌖 🔃 👉 🔢 & 📨 🏑, 👳 <a href="https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods/POST" class="external-link" target="_blank"><abbr title="Mozilla Developer Network">🏇</abbr> 🕸 🩺 <code>POST</code></a>.
+
+///
- ✋️ 🕐❔ 📨 🔌 📁, ⚫️ 🗜 `multipart/form-data`. 👆 🔜 ✍ 🔃 🚚 📁 ⏭ 📃.
+/// warning
- 🚥 👆 💚 ✍ 🌖 🔃 👉 🔢 & 📨 🏑, 👳 <a href="https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods/POST" class="external-link" target="_blank"><abbr title="Mozilla Developer Network">🏇</abbr> 🕸 🩺 <code>POST</code></a>.
+👆 💪 📣 💗 `Form` 🔢 *➡ 🛠️*, ✋️ 👆 💪 🚫 📣 `Body` 🏑 👈 👆 ⌛ 📨 🎻, 📨 🔜 ✔️ 💪 🗜 ⚙️ `application/x-www-form-urlencoded` ↩️ `application/json`.
-!!! warning
- 👆 💪 📣 💗 `Form` 🔢 *➡ 🛠️*, ✋️ 👆 💪 🚫 📣 `Body` 🏑 👈 👆 ⌛ 📨 🎻, 📨 🔜 ✔️ 💪 🗜 ⚙️ `application/x-www-form-urlencoded` ↩️ `application/json`.
+👉 🚫 🚫 **FastAPI**, ⚫️ 🍕 🇺🇸🔍 🛠️.
- 👉 🚫 🚫 **FastAPI**, ⚫️ 🍕 🇺🇸🔍 🛠️.
+///
## 🌃
👆 💪 ⚙️ **🆎 ✍** 🎏 🌌 👆 🔜 🔢 💽 🔢 **🔢**, 👆 💪 ⚙️ Pydantic 🏷, 📇, 📖, 📊 💲 💖 🔢, 🎻, ♒️.
-=== "🐍 3️⃣.6️⃣ & 🔛"
+//// tab | 🐍 3️⃣.6️⃣ & 🔛
- ```Python hl_lines="18 23"
- {!> ../../../docs_src/response_model/tutorial001_01.py!}
- ```
+```Python hl_lines="18 23"
+{!> ../../../docs_src/response_model/tutorial001_01.py!}
+```
+
+////
+
+//// tab | 🐍 3️⃣.9️⃣ & 🔛
-=== "🐍 3️⃣.9️⃣ & 🔛"
+```Python hl_lines="18 23"
+{!> ../../../docs_src/response_model/tutorial001_01_py39.py!}
+```
+
+////
- ```Python hl_lines="18 23"
- {!> ../../../docs_src/response_model/tutorial001_01_py39.py!}
- ```
+//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛
-=== "🐍 3️⃣.1️⃣0️⃣ & 🔛"
+```Python hl_lines="16 21"
+{!> ../../../docs_src/response_model/tutorial001_01_py310.py!}
+```
- ```Python hl_lines="16 21"
- {!> ../../../docs_src/response_model/tutorial001_01_py310.py!}
- ```
+////
FastAPI 🔜 ⚙️ 👉 📨 🆎:
* `@app.delete()`
* ♒️.
-=== "🐍 3️⃣.6️⃣ & 🔛"
+//// tab | 🐍 3️⃣.6️⃣ & 🔛
- ```Python hl_lines="17 22 24-27"
- {!> ../../../docs_src/response_model/tutorial001.py!}
- ```
+```Python hl_lines="17 22 24-27"
+{!> ../../../docs_src/response_model/tutorial001.py!}
+```
+
+////
-=== "🐍 3️⃣.9️⃣ & 🔛"
+//// tab | 🐍 3️⃣.9️⃣ & 🔛
- ```Python hl_lines="17 22 24-27"
- {!> ../../../docs_src/response_model/tutorial001_py39.py!}
- ```
+```Python hl_lines="17 22 24-27"
+{!> ../../../docs_src/response_model/tutorial001_py39.py!}
+```
-=== "🐍 3️⃣.1️⃣0️⃣ & 🔛"
+////
- ```Python hl_lines="17 22 24-27"
- {!> ../../../docs_src/response_model/tutorial001_py310.py!}
- ```
+//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛
+
+```Python hl_lines="17 22 24-27"
+{!> ../../../docs_src/response_model/tutorial001_py310.py!}
+```
-!!! note
- 👀 👈 `response_model` 🔢 "👨🎨" 👩🔬 (`get`, `post`, ♒️). 🚫 👆 *➡ 🛠️ 🔢*, 💖 🌐 🔢 & 💪.
+////
+
+/// 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` 📫
📥 👥 📣 `UserIn` 🏷, ⚫️ 🔜 🔌 🔢 🔐:
-=== "🐍 3️⃣.6️⃣ & 🔛"
+//// tab | 🐍 3️⃣.6️⃣ & 🔛
- ```Python hl_lines="9 11"
- {!> ../../../docs_src/response_model/tutorial002.py!}
- ```
+```Python hl_lines="9 11"
+{!> ../../../docs_src/response_model/tutorial002.py!}
+```
+
+////
+
+//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛
+
+```Python hl_lines="7 9"
+{!> ../../../docs_src/response_model/tutorial002_py310.py!}
+```
-=== "🐍 3️⃣.1️⃣0️⃣ & 🔛"
+////
- ```Python hl_lines="7 9"
- {!> ../../../docs_src/response_model/tutorial002_py310.py!}
- ```
+/// info
-!!! info
- ⚙️ `EmailStr`, 🥇 ❎ <a href="https://github.com/JoshData/python-email-validator" class="external-link" target="_blank">`email_validator`</a>.
+⚙️ `EmailStr`, 🥇 ❎ <a href="https://github.com/JoshData/python-email-validator" class="external-link" target="_blank">`email_validator`</a>.
- 🤶 Ⓜ. `pip install email-validator`
- ⚖️ `pip install pydantic[email]`.
+🤶 Ⓜ. `pip install email-validator`
+⚖️ `pip install pydantic[email]`.
+
+///
& 👥 ⚙️ 👉 🏷 📣 👆 🔢 & 🎏 🏷 📣 👆 🔢:
-=== "🐍 3️⃣.6️⃣ & 🔛"
+//// tab | 🐍 3️⃣.6️⃣ & 🔛
+
+```Python hl_lines="18"
+{!> ../../../docs_src/response_model/tutorial002.py!}
+```
- ```Python hl_lines="18"
- {!> ../../../docs_src/response_model/tutorial002.py!}
- ```
+////
-=== "🐍 3️⃣.1️⃣0️⃣ & 🔛"
+//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛
+
+```Python hl_lines="16"
+{!> ../../../docs_src/response_model/tutorial002_py310.py!}
+```
- ```Python hl_lines="16"
- {!> ../../../docs_src/response_model/tutorial002_py310.py!}
- ```
+////
🔜, 🕐❔ 🖥 🏗 👩💻 ⏮️ 🔐, 🛠️ 🔜 📨 🎏 🔐 📨.
✋️ 🚥 👥 ⚙️ 🎏 🏷 ➕1️⃣ *➡ 🛠️*, 👥 💪 📨 👆 👩💻 🔐 🔠 👩💻.
-!!! danger
- 🙅 🏪 ✅ 🔐 👩💻 ⚖️ 📨 ⚫️ 📨 💖 👉, 🚥 👆 💭 🌐 ⚠ & 👆 💭 ⚫️❔ 👆 🔨.
+/// danger
+
+🙅 🏪 ✅ 🔐 👩💻 ⚖️ 📨 ⚫️ 📨 💖 👉, 🚥 👆 💭 🌐 ⚠ & 👆 💭 ⚫️❔ 👆 🔨.
+
+///
## 🚮 🔢 🏷
👥 💪 ↩️ ✍ 🔢 🏷 ⏮️ 🔢 🔐 & 🔢 🏷 🍵 ⚫️:
-=== "🐍 3️⃣.6️⃣ & 🔛"
+//// tab | 🐍 3️⃣.6️⃣ & 🔛
+
+```Python hl_lines="9 11 16"
+{!> ../../../docs_src/response_model/tutorial003.py!}
+```
+
+////
- ```Python hl_lines="9 11 16"
- {!> ../../../docs_src/response_model/tutorial003.py!}
- ```
+//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛
-=== "🐍 3️⃣.1️⃣0️⃣ & 🔛"
+```Python hl_lines="9 11 16"
+{!> ../../../docs_src/response_model/tutorial003_py310.py!}
+```
- ```Python hl_lines="9 11 16"
- {!> ../../../docs_src/response_model/tutorial003_py310.py!}
- ```
+////
📥, ✋️ 👆 *➡ 🛠️ 🔢* 🛬 🎏 🔢 👩💻 👈 🔌 🔐:
-=== "🐍 3️⃣.6️⃣ & 🔛"
+//// tab | 🐍 3️⃣.6️⃣ & 🔛
+
+```Python hl_lines="24"
+{!> ../../../docs_src/response_model/tutorial003.py!}
+```
- ```Python hl_lines="24"
- {!> ../../../docs_src/response_model/tutorial003.py!}
- ```
+////
-=== "🐍 3️⃣.1️⃣0️⃣ & 🔛"
+//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛
+
+```Python hl_lines="24"
+{!> ../../../docs_src/response_model/tutorial003_py310.py!}
+```
- ```Python hl_lines="24"
- {!> ../../../docs_src/response_model/tutorial003_py310.py!}
- ```
+////
...👥 📣 `response_model` 👆 🏷 `UserOut`, 👈 🚫 🔌 🔐:
-=== "🐍 3️⃣.6️⃣ & 🔛"
+//// tab | 🐍 3️⃣.6️⃣ & 🔛
- ```Python hl_lines="22"
- {!> ../../../docs_src/response_model/tutorial003.py!}
- ```
+```Python hl_lines="22"
+{!> ../../../docs_src/response_model/tutorial003.py!}
+```
+
+////
-=== "🐍 3️⃣.1️⃣0️⃣ & 🔛"
+//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛
- ```Python hl_lines="22"
- {!> ../../../docs_src/response_model/tutorial003_py310.py!}
- ```
+```Python hl_lines="22"
+{!> ../../../docs_src/response_model/tutorial003_py310.py!}
+```
+
+////
, **FastAPI** 🔜 ✊ 💅 🖥 👅 🌐 💽 👈 🚫 📣 🔢 🏷 (⚙️ Pydantic).
& 👈 💼, 👥 💪 ⚙️ 🎓 & 🧬 ✊ 📈 🔢 **🆎 ✍** 🤚 👍 🐕🦺 👨🎨 & 🧰, & 🤚 FastAPI **💽 🖥**.
-=== "🐍 3️⃣.6️⃣ & 🔛"
+//// tab | 🐍 3️⃣.6️⃣ & 🔛
+
+```Python hl_lines="9-13 15-16 20"
+{!> ../../../docs_src/response_model/tutorial003_01.py!}
+```
+
+////
- ```Python hl_lines="9-13 15-16 20"
- {!> ../../../docs_src/response_model/tutorial003_01.py!}
- ```
+//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛
-=== "🐍 3️⃣.1️⃣0️⃣ & 🔛"
+```Python hl_lines="7-10 13-14 18"
+{!> ../../../docs_src/response_model/tutorial003_01_py310.py!}
+```
- ```Python hl_lines="7-10 13-14 18"
- {!> ../../../docs_src/response_model/tutorial003_01_py310.py!}
- ```
+////
⏮️ 👉, 👥 🤚 🏭 🐕🦺, ⚪️➡️ 👨🎨 & ✍ 👉 📟 ☑ ⚖ 🆎, ✋️ 👥 🤚 💽 🖥 ⚪️➡️ FastAPI.
🎏 🔜 🔨 🚥 👆 ✔️ 🕳 💖 <abbr title='A union between multiple types means "any of these types".'>🇪🇺</abbr> 🖖 🎏 🆎 🌐❔ 1️⃣ ⚖️ 🌅 👫 🚫 ☑ Pydantic 🆎, 🖼 👉 🔜 ❌ 👶:
-=== "🐍 3️⃣.6️⃣ & 🔛"
+//// tab | 🐍 3️⃣.6️⃣ & 🔛
- ```Python hl_lines="10"
- {!> ../../../docs_src/response_model/tutorial003_04.py!}
- ```
+```Python hl_lines="10"
+{!> ../../../docs_src/response_model/tutorial003_04.py!}
+```
+
+////
-=== "🐍 3️⃣.1️⃣0️⃣ & 🔛"
+//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛
- ```Python hl_lines="8"
- {!> ../../../docs_src/response_model/tutorial003_04_py310.py!}
- ```
+```Python hl_lines="8"
+{!> ../../../docs_src/response_model/tutorial003_04_py310.py!}
+```
+
+////
...👉 ❌ ↩️ 🆎 ✍ 🚫 Pydantic 🆎 & 🚫 👁 `Response` 🎓 ⚖️ 🏿, ⚫️ 🇪🇺 (🙆 2️⃣) 🖖 `Response` & `dict`.
👉 💼, 👆 💪 ❎ 📨 🏷 ⚡ ⚒ `response_model=None`:
-=== "🐍 3️⃣.6️⃣ & 🔛"
+//// tab | 🐍 3️⃣.6️⃣ & 🔛
+
+```Python hl_lines="9"
+{!> ../../../docs_src/response_model/tutorial003_05.py!}
+```
- ```Python hl_lines="9"
- {!> ../../../docs_src/response_model/tutorial003_05.py!}
- ```
+////
-=== "🐍 3️⃣.1️⃣0️⃣ & 🔛"
+//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛
+
+```Python hl_lines="7"
+{!> ../../../docs_src/response_model/tutorial003_05_py310.py!}
+```
- ```Python hl_lines="7"
- {!> ../../../docs_src/response_model/tutorial003_05_py310.py!}
- ```
+////
👉 🔜 ⚒ FastAPI 🚶 📨 🏷 ⚡ & 👈 🌌 👆 💪 ✔️ 🙆 📨 🆎 ✍ 👆 💪 🍵 ⚫️ 🤕 👆 FastAPI 🈸. 👶
👆 📨 🏷 💪 ✔️ 🔢 💲, 💖:
-=== "🐍 3️⃣.6️⃣ & 🔛"
+//// tab | 🐍 3️⃣.6️⃣ & 🔛
- ```Python hl_lines="11 13-14"
- {!> ../../../docs_src/response_model/tutorial004.py!}
- ```
+```Python hl_lines="11 13-14"
+{!> ../../../docs_src/response_model/tutorial004.py!}
+```
+
+////
+
+//// tab | 🐍 3️⃣.9️⃣ & 🔛
+
+```Python hl_lines="11 13-14"
+{!> ../../../docs_src/response_model/tutorial004_py39.py!}
+```
-=== "🐍 3️⃣.9️⃣ & 🔛"
+////
- ```Python hl_lines="11 13-14"
- {!> ../../../docs_src/response_model/tutorial004_py39.py!}
- ```
+//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛
-=== "🐍 3️⃣.1️⃣0️⃣ & 🔛"
+```Python hl_lines="9 11-12"
+{!> ../../../docs_src/response_model/tutorial004_py310.py!}
+```
- ```Python hl_lines="9 11-12"
- {!> ../../../docs_src/response_model/tutorial004_py310.py!}
- ```
+////
* `description: Union[str, None] = None` (⚖️ `str | None = None` 🐍 3️⃣.1️⃣0️⃣) ✔️ 🔢 `None`.
* `tax: float = 10.5` ✔️ 🔢 `10.5`.
👆 💪 ⚒ *➡ 🛠️ 👨🎨* 🔢 `response_model_exclude_unset=True`:
-=== "🐍 3️⃣.6️⃣ & 🔛"
+//// tab | 🐍 3️⃣.6️⃣ & 🔛
- ```Python hl_lines="24"
- {!> ../../../docs_src/response_model/tutorial004.py!}
- ```
+```Python hl_lines="24"
+{!> ../../../docs_src/response_model/tutorial004.py!}
+```
-=== "🐍 3️⃣.9️⃣ & 🔛"
+////
- ```Python hl_lines="24"
- {!> ../../../docs_src/response_model/tutorial004_py39.py!}
- ```
+//// tab | 🐍 3️⃣.9️⃣ & 🔛
-=== "🐍 3️⃣.1️⃣0️⃣ & 🔛"
+```Python hl_lines="24"
+{!> ../../../docs_src/response_model/tutorial004_py39.py!}
+```
- ```Python hl_lines="22"
- {!> ../../../docs_src/response_model/tutorial004_py310.py!}
- ```
+////
+
+//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛
+
+```Python hl_lines="22"
+{!> ../../../docs_src/response_model/tutorial004_py310.py!}
+```
+
+////
& 👈 🔢 💲 🏆 🚫 🔌 📨, 🕴 💲 🤙 ⚒.
}
```
-!!! info
- FastAPI ⚙️ Pydantic 🏷 `.dict()` ⏮️ <a href="https://docs.pydantic.dev/latest/concepts/serialization/#modeldict" class="external-link" target="_blank">🚮 `exclude_unset` 🔢</a> 🏆 👉.
+/// info
+
+FastAPI ⚙️ Pydantic 🏷 `.dict()` ⏮️ <a href="https://docs.pydantic.dev/latest/concepts/serialization/#modeldict" class="external-link" target="_blank">🚮 `exclude_unset` 🔢</a> 🏆 👉.
+
+///
+
+/// info
-!!! info
- 👆 💪 ⚙️:
+👆 💪 ⚙️:
- * `response_model_exclude_defaults=True`
- * `response_model_exclude_none=True`
+* `response_model_exclude_defaults=True`
+* `response_model_exclude_none=True`
- 🔬 <a href="https://docs.pydantic.dev/latest/concepts/serialization/#modeldict" class="external-link" target="_blank">Pydantic 🩺</a> `exclude_defaults` & `exclude_none`.
+🔬 <a href="https://docs.pydantic.dev/latest/concepts/serialization/#modeldict" class="external-link" target="_blank">Pydantic 🩺</a> `exclude_defaults` & `exclude_none`.
+
+///
#### 📊 ⏮️ 💲 🏑 ⏮️ 🔢
, 👫 🔜 🔌 🎻 📨.
-!!! tip
- 👀 👈 🔢 💲 💪 🕳, 🚫 🕴 `None`.
+/// tip
+
+👀 👈 🔢 💲 💪 🕳, 🚫 🕴 `None`.
+
+👫 💪 📇 (`[]`), `float` `10.5`, ♒️.
- 👫 💪 📇 (`[]`), `float` `10.5`, ♒️.
+///
### `response_model_include` & `response_model_exclude`
👉 💪 ⚙️ ⏩ ⌨ 🚥 👆 ✔️ 🕴 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️⃣ & 🔛"
+//// tab | 🐍 3️⃣.6️⃣ & 🔛
- ```Python hl_lines="31 37"
- {!> ../../../docs_src/response_model/tutorial005.py!}
- ```
+```Python hl_lines="31 37"
+{!> ../../../docs_src/response_model/tutorial005.py!}
+```
+
+////
+
+//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛
+
+```Python hl_lines="29 35"
+{!> ../../../docs_src/response_model/tutorial005_py310.py!}
+```
-=== "🐍 3️⃣.1️⃣0️⃣ & 🔛"
+////
- ```Python hl_lines="29 35"
- {!> ../../../docs_src/response_model/tutorial005_py310.py!}
- ```
+/// tip
-!!! tip
- ❕ `{"name", "description"}` ✍ `set` ⏮️ 📚 2️⃣ 💲.
+❕ `{"name", "description"}` ✍ `set` ⏮️ 📚 2️⃣ 💲.
- ⚫️ 🌓 `set(["name", "description"])`.
+⚫️ 🌓 `set(["name", "description"])`.
+
+///
#### ⚙️ `list`Ⓜ ↩️ `set`Ⓜ
🚥 👆 💭 ⚙️ `set` & ⚙️ `list` ⚖️ `tuple` ↩️, FastAPI 🔜 🗜 ⚫️ `set` & ⚫️ 🔜 👷 ☑:
-=== "🐍 3️⃣.6️⃣ & 🔛"
+//// tab | 🐍 3️⃣.6️⃣ & 🔛
+
+```Python hl_lines="31 37"
+{!> ../../../docs_src/response_model/tutorial006.py!}
+```
- ```Python hl_lines="31 37"
- {!> ../../../docs_src/response_model/tutorial006.py!}
- ```
+////
-=== "🐍 3️⃣.1️⃣0️⃣ & 🔛"
+//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛
+
+```Python hl_lines="29 35"
+{!> ../../../docs_src/response_model/tutorial006_py310.py!}
+```
- ```Python hl_lines="29 35"
- {!> ../../../docs_src/response_model/tutorial006_py310.py!}
- ```
+////
## 🌃
{!../../../docs_src/response_status_code/tutorial001.py!}
```
-!!! note
- 👀 👈 `status_code` 🔢 "👨🎨" 👩🔬 (`get`, `post`, ♒️). 🚫 👆 *➡ 🛠️ 🔢*, 💖 🌐 🔢 & 💪.
+/// note
+
+👀 👈 `status_code` 🔢 "👨🎨" 👩🔬 (`get`, `post`, ♒️). 🚫 👆 *➡ 🛠️ 🔢*, 💖 🌐 🔢 & 💪.
+
+///
`status_code` 🔢 📨 🔢 ⏮️ 🇺🇸🔍 👔 📟.
-!!! info
- `status_code` 💪 👐 📨 `IntEnum`, ✅ 🐍 <a href="https://docs.python.org/3/library/http.html#http.HTTPStatus" class="external-link" target="_blank">`http.HTTPStatus`</a>.
+/// info
+
+`status_code` 💪 👐 📨 `IntEnum`, ✅ 🐍 <a href="https://docs.python.org/3/library/http.html#http.HTTPStatus" class="external-link" target="_blank">`http.HTTPStatus`</a>.
+
+///
⚫️ 🔜:
<img src="/img/tutorial/response-status-code/image01.png">
-!!! note
- 📨 📟 (👀 ⏭ 📄) 🎦 👈 📨 🔨 🚫 ✔️ 💪.
+/// note
+
+📨 📟 (👀 ⏭ 📄) 🎦 👈 📨 🔨 🚫 ✔️ 💪.
+
+FastAPI 💭 👉, & 🔜 🏭 🗄 🩺 👈 🇵🇸 📤 🙅♂ 📨 💪.
- FastAPI 💭 👉, & 🔜 🏭 🗄 🩺 👈 🇵🇸 📤 🙅♂ 📨 💪.
+///
## 🔃 🇺🇸🔍 👔 📟
-!!! note
- 🚥 👆 ⏪ 💭 ⚫️❔ 🇺🇸🔍 👔 📟, 🚶 ⏭ 📄.
+/// note
+
+🚥 👆 ⏪ 💭 ⚫️❔ 🇺🇸🔍 👔 📟, 🚶 ⏭ 📄.
+
+///
🇺🇸🔍, 👆 📨 🔢 👔 📟 3️⃣ 9️⃣ 🍕 📨.
* 💊 ❌ ⚪️➡️ 👩💻, 👆 💪 ⚙️ `400`.
* `500` & 🔛 💽 ❌. 👆 🌖 🙅 ⚙️ 👫 🔗. 🕐❔ 🕳 🚶 ❌ 🍕 👆 🈸 📟, ⚖️ 💽, ⚫️ 🔜 🔁 📨 1️⃣ 👫 👔 📟.
-!!! tip
- 💭 🌅 🔃 🔠 👔 📟 & ❔ 📟 ⚫️❔, ✅ <a href="https://developer.mozilla.org/en-US/docs/Web/HTTP/Status" class="external-link" target="_blank"><abbr title="Mozilla Developer Network">🏇</abbr> 🧾 🔃 🇺🇸🔍 👔 📟</a>.
+/// tip
+
+💭 🌅 🔃 🔠 👔 📟 & ❔ 📟 ⚫️❔, ✅ <a href="https://developer.mozilla.org/en-US/docs/Web/HTTP/Status" class="external-link" target="_blank"><abbr title="Mozilla Developer Network">🏇</abbr> 🧾 🔃 🇺🇸🔍 👔 📟</a>.
+
+///
## ⌨ 💭 📛
<img src="/img/tutorial/response-status-code/image02.png">
-!!! note "📡 ℹ"
- 👆 💪 ⚙️ `from starlette import status`.
+/// note | "📡 ℹ"
+
+👆 💪 ⚙️ `from starlette import status`.
+
+**FastAPI** 🚚 🎏 `starlette.status` `fastapi.status` 🏪 👆, 👩💻. ✋️ ⚫️ 👟 🔗 ⚪️➡️ 💃.
- **FastAPI** 🚚 🎏 `starlette.status` `fastapi.status` 🏪 👆, 👩💻. ✋️ ⚫️ 👟 🔗 ⚪️➡️ 💃.
+///
## 🔀 🔢
👆 💪 📣 `example` Pydantic 🏷 ⚙️ `Config` & `schema_extra`, 🔬 <a href="https://docs.pydantic.dev/latest/concepts/json_schema/#customizing-json-schema" class="external-link" target="_blank">Pydantic 🩺: 🔗 🛃</a>:
-=== "🐍 3️⃣.6️⃣ & 🔛"
+//// tab | 🐍 3️⃣.6️⃣ & 🔛
- ```Python hl_lines="15-23"
- {!> ../../../docs_src/schema_extra_example/tutorial001.py!}
- ```
+```Python hl_lines="15-23"
+{!> ../../../docs_src/schema_extra_example/tutorial001.py!}
+```
-=== "🐍 3️⃣.1️⃣0️⃣ & 🔛"
+////
- ```Python hl_lines="13-21"
- {!> ../../../docs_src/schema_extra_example/tutorial001_py310.py!}
- ```
+//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛
+
+```Python hl_lines="13-21"
+{!> ../../../docs_src/schema_extra_example/tutorial001_py310.py!}
+```
+
+////
👈 ➕ ℹ 🔜 🚮-🔢 **🎻 🔗** 👈 🏷, & ⚫️ 🔜 ⚙️ 🛠️ 🩺.
-!!! tip
- 👆 💪 ⚙️ 🎏 ⚒ ↔ 🎻 🔗 & 🚮 👆 👍 🛃 ➕ ℹ.
+/// tip
+
+👆 💪 ⚙️ 🎏 ⚒ ↔ 🎻 🔗 & 🚮 👆 👍 🛃 ➕ ℹ.
+
+🖼 👆 💪 ⚙️ ⚫️ 🚮 🗃 🕸 👩💻 🔢, ♒️.
- 🖼 👆 💪 ⚙️ ⚫️ 🚮 🗃 🕸 👩💻 🔢, ♒️.
+///
## `Field` 🌖 ❌
👆 💪 ⚙️ 👉 🚮 `example` 🔠 🏑:
-=== "🐍 3️⃣.6️⃣ & 🔛"
+//// tab | 🐍 3️⃣.6️⃣ & 🔛
+
+```Python hl_lines="4 10-13"
+{!> ../../../docs_src/schema_extra_example/tutorial002.py!}
+```
+
+////
+
+//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛
- ```Python hl_lines="4 10-13"
- {!> ../../../docs_src/schema_extra_example/tutorial002.py!}
- ```
+```Python hl_lines="2 8-11"
+{!> ../../../docs_src/schema_extra_example/tutorial002_py310.py!}
+```
-=== "🐍 3️⃣.1️⃣0️⃣ & 🔛"
+////
- ```Python hl_lines="2 8-11"
- {!> ../../../docs_src/schema_extra_example/tutorial002_py310.py!}
- ```
+/// warning
-!!! warning
- 🚧 🤯 👈 📚 ➕ ❌ 🚶♀️ 🏆 🚫 🚮 🙆 🔬, 🕴 ➕ ℹ, 🧾 🎯.
+🚧 🤯 👈 📚 ➕ ❌ 🚶♀️ 🏆 🚫 🚮 🙆 🔬, 🕴 ➕ ℹ, 🧾 🎯.
+
+///
## `example` & `examples` 🗄
📥 👥 🚶♀️ `example` 📊 ⌛ `Body()`:
-=== "🐍 3️⃣.6️⃣ & 🔛"
+//// tab | 🐍 3️⃣.6️⃣ & 🔛
+
+```Python hl_lines="20-25"
+{!> ../../../docs_src/schema_extra_example/tutorial003.py!}
+```
- ```Python hl_lines="20-25"
- {!> ../../../docs_src/schema_extra_example/tutorial003.py!}
- ```
+////
-=== "🐍 3️⃣.1️⃣0️⃣ & 🔛"
+//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛
- ```Python hl_lines="18-23"
- {!> ../../../docs_src/schema_extra_example/tutorial003_py310.py!}
- ```
+```Python hl_lines="18-23"
+{!> ../../../docs_src/schema_extra_example/tutorial003_py310.py!}
+```
+
+////
### 🖼 🩺 🎚
* `value`: 👉 ☑ 🖼 🎦, ✅ `dict`.
* `externalValue`: 🎛 `value`, 📛 ☝ 🖼. 👐 👉 5️⃣📆 🚫 🐕🦺 📚 🧰 `value`.
-=== "🐍 3️⃣.6️⃣ & 🔛"
+//// tab | 🐍 3️⃣.6️⃣ & 🔛
+
+```Python hl_lines="21-47"
+{!> ../../../docs_src/schema_extra_example/tutorial004.py!}
+```
- ```Python hl_lines="21-47"
- {!> ../../../docs_src/schema_extra_example/tutorial004.py!}
- ```
+////
-=== "🐍 3️⃣.1️⃣0️⃣ & 🔛"
+//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛
- ```Python hl_lines="19-45"
- {!> ../../../docs_src/schema_extra_example/tutorial004_py310.py!}
- ```
+```Python hl_lines="19-45"
+{!> ../../../docs_src/schema_extra_example/tutorial004_py310.py!}
+```
+
+////
### 🖼 🩺 🎚
## 📡 ℹ
-!!! warning
- 👉 📶 📡 ℹ 🔃 🐩 **🎻 🔗** & **🗄**.
+/// warning
+
+👉 📶 📡 ℹ 🔃 🐩 **🎻 🔗** & **🗄**.
+
+🚥 💭 🔛 ⏪ 👷 👆, 👈 💪 🥃, & 👆 🎲 🚫 💪 👉 ℹ, 💭 🆓 🚶 👫.
- 🚥 💭 🔛 ⏪ 👷 👆, 👈 💪 🥃, & 👆 🎲 🚫 💪 👉 ℹ, 💭 🆓 🚶 👫.
+///
🕐❔ 👆 🚮 🖼 🔘 Pydantic 🏷, ⚙️ `schema_extra` ⚖️ `Field(example="something")` 👈 🖼 🚮 **🎻 🔗** 👈 Pydantic 🏷.
## 🏃 ⚫️
-!!! info
- 🥇 ❎ <a href="https://github.com/Kludex/python-multipart" class="external-link" target="_blank">`python-multipart`</a>.
+/// info
- 🤶 Ⓜ. `pip install python-multipart`.
+🥇 ❎ <a href="https://github.com/Kludex/python-multipart" class="external-link" target="_blank">`python-multipart`</a>.
- 👉 ↩️ **Oauth2️⃣** ⚙️ "📨 📊" 📨 `username` & `password`.
+🤶 Ⓜ. `pip install python-multipart`.
+
+👉 ↩️ **Oauth2️⃣** ⚙️ "📨 📊" 📨 `username` & `password`.
+
+///
🏃 🖼 ⏮️:
<img src="/img/tutorial/security/image01.png">
-!!! check "✔ 🔼 ❗"
- 👆 ⏪ ✔️ ✨ 🆕 "✔" 🔼.
+/// check | "✔ 🔼 ❗"
+
+👆 ⏪ ✔️ ✨ 🆕 "✔" 🔼.
+
+ & 👆 *➡ 🛠️* ✔️ 🐥 🔒 🔝-▶️️ ↩ 👈 👆 💪 🖊.
- & 👆 *➡ 🛠️* ✔️ 🐥 🔒 🔝-▶️️ ↩ 👈 👆 💪 🖊.
+///
& 🚥 👆 🖊 ⚫️, 👆 ✔️ 🐥 ✔ 📨 🆎 `username` & `password` (& 🎏 📦 🏑):
<img src="/img/tutorial/security/image02.png">
-!!! note
- ⚫️ 🚫 🤔 ⚫️❔ 👆 🆎 📨, ⚫️ 🏆 🚫 👷. ✋️ 👥 🔜 🤚 📤.
+/// note
+
+⚫️ 🚫 🤔 ⚫️❔ 👆 🆎 📨, ⚫️ 🏆 🚫 👷. ✋️ 👥 🔜 🤚 📤.
+
+///
👉 ↗️ 🚫 🕸 🏁 👩💻, ✋️ ⚫️ 👑 🏧 🧰 📄 🖥 🌐 👆 🛠️.
👉 🖼 👥 🔜 ⚙️ **Oauth2️⃣**, ⏮️ **🔐** 💧, ⚙️ **📨** 🤝. 👥 👈 ⚙️ `OAuth2PasswordBearer` 🎓.
-!!! info
- "📨" 🤝 🚫 🕴 🎛.
+/// info
+
+"📨" 🤝 🚫 🕴 🎛.
- ✋️ ⚫️ 🏆 1️⃣ 👆 ⚙️ 💼.
+✋️ ⚫️ 🏆 1️⃣ 👆 ⚙️ 💼.
- & ⚫️ 💪 🏆 🏆 ⚙️ 💼, 🚥 👆 Oauth2️⃣ 🕴 & 💭 ⚫️❔ ⚫️❔ 📤 ➕1️⃣ 🎛 👈 ♣ 👻 👆 💪.
+ & ⚫️ 💪 🏆 🏆 ⚙️ 💼, 🚥 👆 Oauth2️⃣ 🕴 & 💭 ⚫️❔ ⚫️❔ 📤 ➕1️⃣ 🎛 👈 ♣ 👻 👆 💪.
- 👈 💼, **FastAPI** 🚚 👆 ⏮️ 🧰 🏗 ⚫️.
+👈 💼, **FastAPI** 🚚 👆 ⏮️ 🧰 🏗 ⚫️.
+
+///
🕐❔ 👥 ✍ 👐 `OAuth2PasswordBearer` 🎓 👥 🚶♀️ `tokenUrl` 🔢. 👉 🔢 🔌 📛 👈 👩💻 (🕸 🏃 👩💻 🖥) 🔜 ⚙️ 📨 `username` & `password` ✔ 🤚 🤝.
{!../../../docs_src/security/tutorial001.py!}
```
-!!! tip
- 📥 `tokenUrl="token"` 🔗 ⚖ 📛 `token` 👈 👥 🚫 ✍. ⚫️ ⚖ 📛, ⚫️ 🌓 `./token`.
+/// tip
+
+📥 `tokenUrl="token"` 🔗 ⚖ 📛 `token` 👈 👥 🚫 ✍. ⚫️ ⚖ 📛, ⚫️ 🌓 `./token`.
- ↩️ 👥 ⚙️ ⚖ 📛, 🚥 👆 🛠️ 🔎 `https://example.com/`, ⤴️ ⚫️ 🔜 🔗 `https://example.com/token`. ✋️ 🚥 👆 🛠️ 🔎 `https://example.com/api/v1/`, ⤴️ ⚫️ 🔜 🔗 `https://example.com/api/v1/token`.
+↩️ 👥 ⚙️ ⚖ 📛, 🚥 👆 🛠️ 🔎 `https://example.com/`, ⤴️ ⚫️ 🔜 🔗 `https://example.com/token`. ✋️ 🚥 👆 🛠️ 🔎 `https://example.com/api/v1/`, ⤴️ ⚫️ 🔜 🔗 `https://example.com/api/v1/token`.
- ⚙️ ⚖ 📛 ⚠ ⚒ 💭 👆 🈸 🚧 👷 🏧 ⚙️ 💼 💖 [⛅ 🗳](../../advanced/behind-a-proxy.md){.internal-link target=_blank}.
+⚙️ ⚖ 📛 ⚠ ⚒ 💭 👆 🈸 🚧 👷 🏧 ⚙️ 💼 💖 [⛅ 🗳](../../advanced/behind-a-proxy.md){.internal-link target=_blank}.
+
+///
👉 🔢 🚫 ✍ 👈 🔗 / *➡ 🛠️*, ✋️ 📣 👈 📛 `/token` 🔜 1️⃣ 👈 👩💻 🔜 ⚙️ 🤚 🤝. 👈 ℹ ⚙️ 🗄, & ⤴️ 🎓 🛠️ 🧾 ⚙️.
👥 🔜 🔜 ✍ ☑ ➡ 🛠️.
-!!! info
- 🚥 👆 📶 ⚠ "✍" 👆 💪 👎 👗 🔢 📛 `tokenUrl` ↩️ `token_url`.
+/// info
+
+🚥 👆 📶 ⚠ "✍" 👆 💪 👎 👗 🔢 📛 `tokenUrl` ↩️ `token_url`.
- 👈 ↩️ ⚫️ ⚙️ 🎏 📛 🗄 🔌. 👈 🚥 👆 💪 🔬 🌅 🔃 🙆 👫 💂♂ ⚖ 👆 💪 📁 & 📋 ⚫️ 🔎 🌖 ℹ 🔃 ⚫️.
+👈 ↩️ ⚫️ ⚙️ 🎏 📛 🗄 🔌. 👈 🚥 👆 💪 🔬 🌅 🔃 🙆 👫 💂♂ ⚖ 👆 💪 📁 & 📋 ⚫️ 🔎 🌖 ℹ 🔃 ⚫️.
+
+///
`oauth2_scheme` 🔢 👐 `OAuth2PasswordBearer`, ✋️ ⚫️ "🇧🇲".
**FastAPI** 🔜 💭 👈 ⚫️ 💪 ⚙️ 👉 🔗 🔬 "💂♂ ⚖" 🗄 🔗 (& 🏧 🛠️ 🩺).
-!!! info "📡 ℹ"
- **FastAPI** 🔜 💭 👈 ⚫️ 💪 ⚙️ 🎓 `OAuth2PasswordBearer` (📣 🔗) 🔬 💂♂ ⚖ 🗄 ↩️ ⚫️ 😖 ⚪️➡️ `fastapi.security.oauth2.OAuth2`, ❔ 🔄 😖 ⚪️➡️ `fastapi.security.base.SecurityBase`.
+/// info | "📡 ℹ"
+
+**FastAPI** 🔜 💭 👈 ⚫️ 💪 ⚙️ 🎓 `OAuth2PasswordBearer` (📣 🔗) 🔬 💂♂ ⚖ 🗄 ↩️ ⚫️ 😖 ⚪️➡️ `fastapi.security.oauth2.OAuth2`, ❔ 🔄 😖 ⚪️➡️ `fastapi.security.base.SecurityBase`.
+
+🌐 💂♂ 🚙 👈 🛠️ ⏮️ 🗄 (& 🏧 🛠️ 🩺) 😖 ⚪️➡️ `SecurityBase`, 👈 ❔ **FastAPI** 💪 💭 ❔ 🛠️ 👫 🗄.
- 🌐 💂♂ 🚙 👈 🛠️ ⏮️ 🗄 (& 🏧 🛠️ 🩺) 😖 ⚪️➡️ `SecurityBase`, 👈 ❔ **FastAPI** 💪 💭 ❔ 🛠️ 👫 🗄.
+///
## ⚫️❔ ⚫️ 🔨
🎏 🌌 👥 ⚙️ Pydantic 📣 💪, 👥 💪 ⚙️ ⚫️ 🙆 🙆:
-=== "🐍 3️⃣.6️⃣ & 🔛"
+//// tab | 🐍 3️⃣.6️⃣ & 🔛
- ```Python hl_lines="5 12-16"
- {!> ../../../docs_src/security/tutorial002.py!}
- ```
+```Python hl_lines="5 12-16"
+{!> ../../../docs_src/security/tutorial002.py!}
+```
+
+////
+
+//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛
-=== "🐍 3️⃣.1️⃣0️⃣ & 🔛"
+```Python hl_lines="3 10-14"
+{!> ../../../docs_src/security/tutorial002_py310.py!}
+```
- ```Python hl_lines="3 10-14"
- {!> ../../../docs_src/security/tutorial002_py310.py!}
- ```
+////
## ✍ `get_current_user` 🔗
🎏 👥 🔨 ⏭ *➡ 🛠️* 🔗, 👆 🆕 🔗 `get_current_user` 🔜 📨 `token` `str` ⚪️➡️ 🎧-🔗 `oauth2_scheme`:
-=== "🐍 3️⃣.6️⃣ & 🔛"
+//// tab | 🐍 3️⃣.6️⃣ & 🔛
+
+```Python hl_lines="25"
+{!> ../../../docs_src/security/tutorial002.py!}
+```
+
+////
- ```Python hl_lines="25"
- {!> ../../../docs_src/security/tutorial002.py!}
- ```
+//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛
-=== "🐍 3️⃣.1️⃣0️⃣ & 🔛"
+```Python hl_lines="23"
+{!> ../../../docs_src/security/tutorial002_py310.py!}
+```
- ```Python hl_lines="23"
- {!> ../../../docs_src/security/tutorial002_py310.py!}
- ```
+////
## 🤚 👩💻
`get_current_user` 🔜 ⚙️ (❌) 🚙 🔢 👥 ✍, 👈 ✊ 🤝 `str` & 📨 👆 Pydantic `User` 🏷:
-=== "🐍 3️⃣.6️⃣ & 🔛"
+//// tab | 🐍 3️⃣.6️⃣ & 🔛
+
+```Python hl_lines="19-22 26-27"
+{!> ../../../docs_src/security/tutorial002.py!}
+```
+
+////
- ```Python hl_lines="19-22 26-27"
- {!> ../../../docs_src/security/tutorial002.py!}
- ```
+//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛
-=== "🐍 3️⃣.1️⃣0️⃣ & 🔛"
+```Python hl_lines="17-20 24-25"
+{!> ../../../docs_src/security/tutorial002_py310.py!}
+```
- ```Python hl_lines="17-20 24-25"
- {!> ../../../docs_src/security/tutorial002_py310.py!}
- ```
+////
## 💉 ⏮️ 👩💻
🔜 👥 💪 ⚙️ 🎏 `Depends` ⏮️ 👆 `get_current_user` *➡ 🛠️*:
-=== "🐍 3️⃣.6️⃣ & 🔛"
+//// tab | 🐍 3️⃣.6️⃣ & 🔛
- ```Python hl_lines="31"
- {!> ../../../docs_src/security/tutorial002.py!}
- ```
+```Python hl_lines="31"
+{!> ../../../docs_src/security/tutorial002.py!}
+```
+
+////
+
+//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛
-=== "🐍 3️⃣.1️⃣0️⃣ & 🔛"
+```Python hl_lines="29"
+{!> ../../../docs_src/security/tutorial002_py310.py!}
+```
- ```Python hl_lines="29"
- {!> ../../../docs_src/security/tutorial002_py310.py!}
- ```
+////
👀 👈 👥 📣 🆎 `current_user` Pydantic 🏷 `User`.
👉 🔜 ℹ 🇺🇲 🔘 🔢 ⏮️ 🌐 🛠️ & 🆎 ✅.
-!!! tip
- 👆 5️⃣📆 💭 👈 📨 💪 📣 ⏮️ Pydantic 🏷.
+/// tip
+
+👆 5️⃣📆 💭 👈 📨 💪 📣 ⏮️ Pydantic 🏷.
+
+📥 **FastAPI** 🏆 🚫 🤚 😨 ↩️ 👆 ⚙️ `Depends`.
- 📥 **FastAPI** 🏆 🚫 🤚 😨 ↩️ 👆 ⚙️ `Depends`.
+///
-!!! check
- 🌌 👉 🔗 ⚙️ 🏗 ✔ 👥 ✔️ 🎏 🔗 (🎏 "☑") 👈 🌐 📨 `User` 🏷.
+/// check
- 👥 🚫 🚫 ✔️ 🕴 1️⃣ 🔗 👈 💪 📨 👈 🆎 💽.
+🌌 👉 🔗 ⚙️ 🏗 ✔ 👥 ✔️ 🎏 🔗 (🎏 "☑") 👈 🌐 📨 `User` 🏷.
+
+👥 🚫 🚫 ✔️ 🕴 1️⃣ 🔗 👈 💪 📨 👈 🆎 💽.
+
+///
## 🎏 🏷
& 🌐 👉 💯 *➡ 🛠️* 💪 🤪 3️⃣ ⏸:
-=== "🐍 3️⃣.6️⃣ & 🔛"
+//// tab | 🐍 3️⃣.6️⃣ & 🔛
+
+```Python hl_lines="30-32"
+{!> ../../../docs_src/security/tutorial002.py!}
+```
+
+////
- ```Python hl_lines="30-32"
- {!> ../../../docs_src/security/tutorial002.py!}
- ```
+//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛
-=== "🐍 3️⃣.1️⃣0️⃣ & 🔛"
+```Python hl_lines="28-30"
+{!> ../../../docs_src/security/tutorial002_py310.py!}
+```
- ```Python hl_lines="28-30"
- {!> ../../../docs_src/security/tutorial002_py310.py!}
- ```
+////
## 🌃
Oauth2️⃣ 🚫 ✔ ❔ 🗜 📻, ⚫️ ⌛ 👆 ✔️ 👆 🈸 🍦 ⏮️ 🇺🇸🔍.
-!!! tip
- 📄 🔃 **🛠️** 👆 🔜 👀 ❔ ⚒ 🆙 🇺🇸🔍 🆓, ⚙️ Traefik & ➡️ 🗜.
+/// tip
+📄 🔃 **🛠️** 👆 🔜 👀 ❔ ⚒ 🆙 🇺🇸🔍 🆓, ⚙️ Traefik & ➡️ 🗜.
+
+///
## 👩💻 🔗
* 👉 🏧 🔍 ⚫️❔ 🔬 👩💻 🔗 🔧.
-!!! tip
- 🛠️ 🎏 🤝/✔ 🐕🦺 💖 🇺🇸🔍, 👱📔, 👱📔, 📂, ♒️. 💪 & 📶 ⏩.
+/// tip
+
+🛠️ 🎏 🤝/✔ 🐕🦺 💖 🇺🇸🔍, 👱📔, 👱📔, 📂, ♒️. 💪 & 📶 ⏩.
+
+🌅 🏗 ⚠ 🏗 🤝/✔ 🐕🦺 💖 👈, ✋️ **FastAPI** 🤝 👆 🧰 ⚫️ 💪, ⏪ 🔨 🏋️ 🏋♂ 👆.
- 🌅 🏗 ⚠ 🏗 🤝/✔ 🐕🦺 💖 👈, ✋️ **FastAPI** 🤝 👆 🧰 ⚫️ 💪, ⏪ 🔨 🏋️ 🏋♂ 👆.
+///
## **FastAPI** 🚙
📥 👥 ⚙️ 👍 1️⃣: <a href="https://cryptography.io/" class="external-link" target="_blank">)/⚛</a>.
-!!! tip
- 👉 🔰 ⏪ ⚙️ <a href="https://pyjwt.readthedocs.io/" class="external-link" target="_blank">PyJWT</a>.
+/// tip
- ✋️ ⚫️ ℹ ⚙️ 🐍-🇩🇬 ↩️ ⚫️ 🚚 🌐 ⚒ ⚪️➡️ PyJWT ➕ ➕ 👈 👆 💪 💪 ⏪ 🕐❔ 🏗 🛠️ ⏮️ 🎏 🧰.
+👉 🔰 ⏪ ⚙️ <a href="https://pyjwt.readthedocs.io/" class="external-link" target="_blank">PyJWT</a>.
+
+✋️ ⚫️ ℹ ⚙️ 🐍-🇩🇬 ↩️ ⚫️ 🚚 🌐 ⚒ ⚪️➡️ PyJWT ➕ ➕ 👈 👆 💪 💪 ⏪ 🕐❔ 🏗 🛠️ ⏮️ 🎏 🧰.
+
+///
## 🔐 🔁
</div>
-!!! tip
- ⏮️ `passlib`, 👆 💪 🔗 ⚫️ 💪 ✍ 🔐 ✍ **✳**, **🏺** 💂♂ 🔌-⚖️ 📚 🎏.
+/// tip
+
+⏮️ `passlib`, 👆 💪 🔗 ⚫️ 💪 ✍ 🔐 ✍ **✳**, **🏺** 💂♂ 🔌-⚖️ 📚 🎏.
+
+, 👆 🔜 💪, 🖼, 💰 🎏 📊 ⚪️➡️ ✳ 🈸 💽 ⏮️ FastAPI 🈸. ⚖️ 📉 ↔ ✳ 🈸 ⚙️ 🎏 💽.
- , 👆 🔜 💪, 🖼, 💰 🎏 📊 ⚪️➡️ ✳ 🈸 💽 ⏮️ FastAPI 🈸. ⚖️ 📉 ↔ ✳ 🈸 ⚙️ 🎏 💽.
+ & 👆 👩💻 🔜 💪 💳 ⚪️➡️ 👆 ✳ 📱 ⚖️ ⚪️➡️ 👆 **FastAPI** 📱, 🎏 🕰.
- & 👆 👩💻 🔜 💪 💳 ⚪️➡️ 👆 ✳ 📱 ⚖️ ⚪️➡️ 👆 **FastAPI** 📱, 🎏 🕰.
+///
## #️⃣ & ✔ 🔐
✍ 🇸🇲 "🔑". 👉 ⚫️❔ 🔜 ⚙️ #️⃣ & ✔ 🔐.
-!!! tip
- 🇸🇲 🔑 ✔️ 🛠️ ⚙️ 🎏 🔁 📊, 🔌 😢 🗝 🕐 🕴 ✔ ✔ 👫, ♒️.
+/// tip
- 🖼, 👆 💪 ⚙️ ⚫️ ✍ & ✔ 🔐 🏗 ➕1️⃣ ⚙️ (💖 ✳) ✋️ #️⃣ 🙆 🆕 🔐 ⏮️ 🎏 📊 💖 🐡.
+🇸🇲 🔑 ✔️ 🛠️ ⚙️ 🎏 🔁 📊, 🔌 😢 🗝 🕐 🕴 ✔ ✔ 👫, ♒️.
- & 🔗 ⏮️ 🌐 👫 🎏 🕰.
+🖼, 👆 💪 ⚙️ ⚫️ ✍ & ✔ 🔐 🏗 ➕1️⃣ ⚙️ (💖 ✳) ✋️ #️⃣ 🙆 🆕 🔐 ⏮️ 🎏 📊 💖 🐡.
+
+ & 🔗 ⏮️ 🌐 👫 🎏 🕰.
+
+///
✍ 🚙 🔢 #️⃣ 🔐 👟 ⚪️➡️ 👩💻.
& ➕1️⃣ 1️⃣ 🔓 & 📨 👩💻.
-=== "🐍 3️⃣.6️⃣ & 🔛"
+//// tab | 🐍 3️⃣.6️⃣ & 🔛
+
+```Python hl_lines="7 48 55-56 59-60 69-75"
+{!> ../../../docs_src/security/tutorial004.py!}
+```
+
+////
- ```Python hl_lines="7 48 55-56 59-60 69-75"
- {!> ../../../docs_src/security/tutorial004.py!}
- ```
+//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛
+
+```Python hl_lines="6 47 54-55 58-59 68-74"
+{!> ../../../docs_src/security/tutorial004_py310.py!}
+```
-=== "🐍 3️⃣.1️⃣0️⃣ & 🔛"
+////
- ```Python hl_lines="6 47 54-55 58-59 68-74"
- {!> ../../../docs_src/security/tutorial004_py310.py!}
- ```
+/// note
-!!! note
- 🚥 👆 ✅ 🆕 (❌) 💽 `fake_users_db`, 👆 🔜 👀 ❔ #️⃣ 🔐 👀 💖 🔜: `"$2b$12$EixZaYVK1fsbw1ZfbX3OXePaWxn96p36WQoeG6Lruj3vjPGga31lW"`.
+🚥 👆 ✅ 🆕 (❌) 💽 `fake_users_db`, 👆 🔜 👀 ❔ #️⃣ 🔐 👀 💖 🔜: `"$2b$12$EixZaYVK1fsbw1ZfbX3OXePaWxn96p36WQoeG6Lruj3vjPGga31lW"`.
+
+///
## 🍵 🥙 🤝
✍ 🚙 🔢 🏗 🆕 🔐 🤝.
-=== "🐍 3️⃣.6️⃣ & 🔛"
+//// tab | 🐍 3️⃣.6️⃣ & 🔛
+
+```Python hl_lines="6 12-14 28-30 78-86"
+{!> ../../../docs_src/security/tutorial004.py!}
+```
+
+////
- ```Python hl_lines="6 12-14 28-30 78-86"
- {!> ../../../docs_src/security/tutorial004.py!}
- ```
+//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛
-=== "🐍 3️⃣.1️⃣0️⃣ & 🔛"
+```Python hl_lines="5 11-13 27-29 77-85"
+{!> ../../../docs_src/security/tutorial004_py310.py!}
+```
- ```Python hl_lines="5 11-13 27-29 77-85"
- {!> ../../../docs_src/security/tutorial004_py310.py!}
- ```
+////
## ℹ 🔗
🚥 🤝 ❌, 📨 🇺🇸🔍 ❌ ▶️️ ↖️.
-=== "🐍 3️⃣.6️⃣ & 🔛"
+//// tab | 🐍 3️⃣.6️⃣ & 🔛
- ```Python hl_lines="89-106"
- {!> ../../../docs_src/security/tutorial004.py!}
- ```
+```Python hl_lines="89-106"
+{!> ../../../docs_src/security/tutorial004.py!}
+```
-=== "🐍 3️⃣.1️⃣0️⃣ & 🔛"
+////
- ```Python hl_lines="88-105"
- {!> ../../../docs_src/security/tutorial004_py310.py!}
- ```
+//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛
+
+```Python hl_lines="88-105"
+{!> ../../../docs_src/security/tutorial004_py310.py!}
+```
+
+////
## ℹ `/token` *➡ 🛠️*
✍ 🎰 🥙 🔐 🤝 & 📨 ⚫️.
-=== "🐍 3️⃣.6️⃣ & 🔛"
+//// tab | 🐍 3️⃣.6️⃣ & 🔛
+
+```Python hl_lines="115-130"
+{!> ../../../docs_src/security/tutorial004.py!}
+```
+
+////
- ```Python hl_lines="115-130"
- {!> ../../../docs_src/security/tutorial004.py!}
- ```
+//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛
-=== "🐍 3️⃣.1️⃣0️⃣ & 🔛"
+```Python hl_lines="114-129"
+{!> ../../../docs_src/security/tutorial004_py310.py!}
+```
- ```Python hl_lines="114-129"
- {!> ../../../docs_src/security/tutorial004_py310.py!}
- ```
+////
### 📡 ℹ 🔃 🥙 "📄" `sub`
🆔: `johndoe`
🔐: `secret`
-!!! check
- 👀 👈 🕳 📟 🔢 🔐 "`secret`", 👥 🕴 ✔️ #️⃣ ⏬.
+/// check
+
+👀 👈 🕳 📟 🔢 🔐 "`secret`", 👥 🕴 ✔️ #️⃣ ⏬.
+
+///
<img src="/img/tutorial/security/image08.png">
<img src="/img/tutorial/security/image10.png">
-!!! note
- 👀 🎚 `Authorization`, ⏮️ 💲 👈 ▶️ ⏮️ `Bearer `.
+/// note
+
+👀 🎚 `Authorization`, ⏮️ 💲 👈 ▶️ ⏮️ `Bearer `.
+
+///
## 🏧 ⚙️ ⏮️ `scopes`
* `instagram_basic` ⚙️ 👱📔 / 👱📔.
* `https://www.googleapis.com/auth/drive` ⚙️ 🇺🇸🔍.
-!!! info
- Oauth2️⃣ "↔" 🎻 👈 📣 🎯 ✔ ✔.
+/// info
- ⚫️ 🚫 🤔 🚥 ⚫️ ✔️ 🎏 🦹 💖 `:` ⚖️ 🚥 ⚫️ 📛.
+Oauth2️⃣ "↔" 🎻 👈 📣 🎯 ✔ ✔.
- 👈 ℹ 🛠️ 🎯.
+⚫️ 🚫 🤔 🚥 ⚫️ ✔️ 🎏 🦹 💖 `:` ⚖️ 🚥 ⚫️ 📛.
- Oauth2️⃣ 👫 🎻.
+👈 ℹ 🛠️ 🎯.
+
+Oauth2️⃣ 👫 🎻.
+
+///
## 📟 🤚 `username` & `password`
🥇, 🗄 `OAuth2PasswordRequestForm`, & ⚙️ ⚫️ 🔗 ⏮️ `Depends` *➡ 🛠️* `/token`:
-=== "🐍 3️⃣.6️⃣ & 🔛"
+//// tab | 🐍 3️⃣.6️⃣ & 🔛
- ```Python hl_lines="4 76"
- {!> ../../../docs_src/security/tutorial003.py!}
- ```
+```Python hl_lines="4 76"
+{!> ../../../docs_src/security/tutorial003.py!}
+```
-=== "🐍 3️⃣.1️⃣0️⃣ & 🔛"
+////
- ```Python hl_lines="2 74"
- {!> ../../../docs_src/security/tutorial003_py310.py!}
- ```
+//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛
+
+```Python hl_lines="2 74"
+{!> ../../../docs_src/security/tutorial003_py310.py!}
+```
+
+////
`OAuth2PasswordRequestForm` 🎓 🔗 👈 📣 📨 💪 ⏮️:
* 📦 `scope` 🏑 🦏 🎻, ✍ 🎻 🎏 🚀.
* 📦 `grant_type`.
-!!! tip
- Oauth2️⃣ 🔌 🤙 *🚚* 🏑 `grant_type` ⏮️ 🔧 💲 `password`, ✋️ `OAuth2PasswordRequestForm` 🚫 🛠️ ⚫️.
+/// tip
+
+Oauth2️⃣ 🔌 🤙 *🚚* 🏑 `grant_type` ⏮️ 🔧 💲 `password`, ✋️ `OAuth2PasswordRequestForm` 🚫 🛠️ ⚫️.
- 🚥 👆 💪 🛠️ ⚫️, ⚙️ `OAuth2PasswordRequestFormStrict` ↩️ `OAuth2PasswordRequestForm`.
+🚥 👆 💪 🛠️ ⚫️, ⚙️ `OAuth2PasswordRequestFormStrict` ↩️ `OAuth2PasswordRequestForm`.
+
+///
* 📦 `client_id` (👥 🚫 💪 ⚫️ 👆 🖼).
* 📦 `client_secret` (👥 🚫 💪 ⚫️ 👆 🖼).
-!!! info
- `OAuth2PasswordRequestForm` 🚫 🎁 🎓 **FastAPI** `OAuth2PasswordBearer`.
+/// info
+
+`OAuth2PasswordRequestForm` 🚫 🎁 🎓 **FastAPI** `OAuth2PasswordBearer`.
- `OAuth2PasswordBearer` ⚒ **FastAPI** 💭 👈 ⚫️ 💂♂ ⚖. ⚫️ 🚮 👈 🌌 🗄.
+`OAuth2PasswordBearer` ⚒ **FastAPI** 💭 👈 ⚫️ 💂♂ ⚖. ⚫️ 🚮 👈 🌌 🗄.
- ✋️ `OAuth2PasswordRequestForm` 🎓 🔗 👈 👆 💪 ✔️ ✍ 👆, ⚖️ 👆 💪 ✔️ 📣 `Form` 🔢 🔗.
+✋️ `OAuth2PasswordRequestForm` 🎓 🔗 👈 👆 💪 ✔️ ✍ 👆, ⚖️ 👆 💪 ✔️ 📣 `Form` 🔢 🔗.
- ✋️ ⚫️ ⚠ ⚙️ 💼, ⚫️ 🚚 **FastAPI** 🔗, ⚒ ⚫️ ⏩.
+✋️ ⚫️ ⚠ ⚙️ 💼, ⚫️ 🚚 **FastAPI** 🔗, ⚒ ⚫️ ⏩.
+
+///
### ⚙️ 📨 💽
-!!! tip
- 👐 🔗 🎓 `OAuth2PasswordRequestForm` 🏆 🚫 ✔️ 🔢 `scope` ⏮️ 📏 🎻 👽 🚀, ↩️, ⚫️ 🔜 ✔️ `scopes` 🔢 ⏮️ ☑ 📇 🎻 🔠 ↔ 📨.
+/// tip
+
+👐 🔗 🎓 `OAuth2PasswordRequestForm` 🏆 🚫 ✔️ 🔢 `scope` ⏮️ 📏 🎻 👽 🚀, ↩️, ⚫️ 🔜 ✔️ `scopes` 🔢 ⏮️ ☑ 📇 🎻 🔠 ↔ 📨.
+
+👥 🚫 ⚙️ `scopes` 👉 🖼, ✋️ 🛠️ 📤 🚥 👆 💪 ⚫️.
- 👥 🚫 ⚙️ `scopes` 👉 🖼, ✋️ 🛠️ 📤 🚥 👆 💪 ⚫️.
+///
🔜, 🤚 👩💻 📊 ⚪️➡️ (❌) 💽, ⚙️ `username` ⚪️➡️ 📨 🏑.
❌, 👥 ⚙️ ⚠ `HTTPException`:
-=== "🐍 3️⃣.6️⃣ & 🔛"
+//// tab | 🐍 3️⃣.6️⃣ & 🔛
- ```Python hl_lines="3 77-79"
- {!> ../../../docs_src/security/tutorial003.py!}
- ```
+```Python hl_lines="3 77-79"
+{!> ../../../docs_src/security/tutorial003.py!}
+```
-=== "🐍 3️⃣.1️⃣0️⃣ & 🔛"
+////
- ```Python hl_lines="1 75-77"
- {!> ../../../docs_src/security/tutorial003_py310.py!}
- ```
+//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛
+
+```Python hl_lines="1 75-77"
+{!> ../../../docs_src/security/tutorial003_py310.py!}
+```
+
+////
### ✅ 🔐
, 🧙♀ 🏆 🚫 💪 🔄 ⚙️ 👈 🎏 🔐 ➕1️⃣ ⚙️ (📚 👩💻 ⚙️ 🎏 🔐 🌐, 👉 🔜 ⚠).
-=== "🐍 3️⃣.6️⃣ & 🔛"
+//// tab | 🐍 3️⃣.6️⃣ & 🔛
+
+```Python hl_lines="80-83"
+{!> ../../../docs_src/security/tutorial003.py!}
+```
+
+////
- ```Python hl_lines="80-83"
- {!> ../../../docs_src/security/tutorial003.py!}
- ```
+//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛
-=== "🐍 3️⃣.1️⃣0️⃣ & 🔛"
+```Python hl_lines="78-81"
+{!> ../../../docs_src/security/tutorial003_py310.py!}
+```
- ```Python hl_lines="78-81"
- {!> ../../../docs_src/security/tutorial003_py310.py!}
- ```
+////
#### 🔃 `**user_dict`
)
```
-!!! info
- 🌅 🏁 🔑 `**👩💻_ #️⃣ ` ✅ 🔙 [🧾 **➕ 🏷**](../extra-models.md#user_indict){.internal-link target=_blank}.
+/// info
+
+🌅 🏁 🔑 `**👩💻_ #️⃣ ` ✅ 🔙 [🧾 **➕ 🏷**](../extra-models.md#user_indict){.internal-link target=_blank}.
+
+///
## 📨 🤝
👉 🙅 🖼, 👥 🔜 🍕 😟 & 📨 🎏 `username` 🤝.
-!!! tip
- ⏭ 📃, 👆 🔜 👀 🎰 🔐 🛠️, ⏮️ 🔐 #️⃣ & <abbr title="JSON Web Tokens">🥙</abbr> 🤝.
+/// tip
+
+⏭ 📃, 👆 🔜 👀 🎰 🔐 🛠️, ⏮️ 🔐 #️⃣ & <abbr title="JSON Web Tokens">🥙</abbr> 🤝.
+
+✋️ 🔜, ➡️ 🎯 🔛 🎯 ℹ 👥 💪.
+
+///
+
+//// tab | 🐍 3️⃣.6️⃣ & 🔛
+
+```Python hl_lines="85"
+{!> ../../../docs_src/security/tutorial003.py!}
+```
+
+////
- ✋️ 🔜, ➡️ 🎯 🔛 🎯 ℹ 👥 💪.
+//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛
-=== "🐍 3️⃣.6️⃣ & 🔛"
+```Python hl_lines="83"
+{!> ../../../docs_src/security/tutorial003_py310.py!}
+```
- ```Python hl_lines="85"
- {!> ../../../docs_src/security/tutorial003.py!}
- ```
+////
-=== "🐍 3️⃣.1️⃣0️⃣ & 🔛"
+/// tip
- ```Python hl_lines="83"
- {!> ../../../docs_src/security/tutorial003_py310.py!}
- ```
+🔌, 👆 🔜 📨 🎻 ⏮️ `access_token` & `token_type`, 🎏 👉 🖼.
-!!! tip
- 🔌, 👆 🔜 📨 🎻 ⏮️ `access_token` & `token_type`, 🎏 👉 🖼.
+👉 🕳 👈 👆 ✔️ 👆 👆 📟, & ⚒ 💭 👆 ⚙️ 📚 🎻 🔑.
- 👉 🕳 👈 👆 ✔️ 👆 👆 📟, & ⚒ 💭 👆 ⚙️ 📚 🎻 🔑.
+⚫️ 🌖 🕴 👜 👈 👆 ✔️ 💭 ☑ 👆, 🛠️ ⏮️ 🔧.
- ⚫️ 🌖 🕴 👜 👈 👆 ✔️ 💭 ☑ 👆, 🛠️ ⏮️ 🔧.
+🎂, **FastAPI** 🍵 ⚫️ 👆.
- 🎂, **FastAPI** 🍵 ⚫️ 👆.
+///
## ℹ 🔗
, 👆 🔗, 👥 🔜 🕴 🤚 👩💻 🚥 👩💻 🔀, ☑ 🔓, & 🦁:
-=== "🐍 3️⃣.6️⃣ & 🔛"
+//// tab | 🐍 3️⃣.6️⃣ & 🔛
+
+```Python hl_lines="58-66 69-72 90"
+{!> ../../../docs_src/security/tutorial003.py!}
+```
+
+////
+
+//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛
+
+```Python hl_lines="55-64 67-70 88"
+{!> ../../../docs_src/security/tutorial003_py310.py!}
+```
- ```Python hl_lines="58-66 69-72 90"
- {!> ../../../docs_src/security/tutorial003.py!}
- ```
+////
-=== "🐍 3️⃣.1️⃣0️⃣ & 🔛"
+/// info
- ```Python hl_lines="55-64 67-70 88"
- {!> ../../../docs_src/security/tutorial003_py310.py!}
- ```
+🌖 🎚 `WWW-Authenticate` ⏮️ 💲 `Bearer` 👥 🛬 📥 🍕 🔌.
-!!! info
- 🌖 🎚 `WWW-Authenticate` ⏮️ 💲 `Bearer` 👥 🛬 📥 🍕 🔌.
+🙆 🇺🇸🔍 (❌) 👔 📟 4️⃣0️⃣1️⃣ "⛔" 🤔 📨 `WWW-Authenticate` 🎚.
- 🙆 🇺🇸🔍 (❌) 👔 📟 4️⃣0️⃣1️⃣ "⛔" 🤔 📨 `WWW-Authenticate` 🎚.
+💼 📨 🤝 (👆 💼), 💲 👈 🎚 🔜 `Bearer`.
- 💼 📨 🤝 (👆 💼), 💲 👈 🎚 🔜 `Bearer`.
+👆 💪 🤙 🚶 👈 ➕ 🎚 & ⚫️ 🔜 👷.
- 👆 💪 🤙 🚶 👈 ➕ 🎚 & ⚫️ 🔜 👷.
+✋️ ⚫️ 🚚 📥 🛠️ ⏮️ 🔧.
- ✋️ ⚫️ 🚚 📥 🛠️ ⏮️ 🔧.
+, 📤 5️⃣📆 🧰 👈 ⌛ & ⚙️ ⚫️ (🔜 ⚖️ 🔮) & 👈 💪 ⚠ 👆 ⚖️ 👆 👩💻, 🔜 ⚖️ 🔮.
- , 📤 5️⃣📆 🧰 👈 ⌛ & ⚙️ ⚫️ (🔜 ⚖️ 🔮) & 👈 💪 ⚠ 👆 ⚖️ 👆 👩💻, 🔜 ⚖️ 🔮.
+👈 💰 🐩...
- 👈 💰 🐩...
+///
## 👀 ⚫️ 🎯
⏪, 👆 🏭 🈸, 👆 💪 💚 ⚙️ 💽 💽 💖 **✳**.
-!!! tip
- 📤 🛂 🏗 🚂 ⏮️ **FastAPI** & **✳**, 🌐 ⚓️ 🔛 **☁**, 🔌 🕸 & 🌖 🧰: <a href="https://github.com/tiangolo/full-stack-fastapi-postgresql" class="external-link" target="_blank">https://github.com/tiangolo/full-stack-fastapi-postgresql</a>
+/// tip
-!!! note
- 👀 👈 📚 📟 🐩 `SQLAlchemy` 📟 👆 🔜 ⚙️ ⏮️ 🙆 🛠️.
+📤 🛂 🏗 🚂 ⏮️ **FastAPI** & **✳**, 🌐 ⚓️ 🔛 **☁**, 🔌 🕸 & 🌖 🧰: <a href="https://github.com/tiangolo/full-stack-fastapi-postgresql" class="external-link" target="_blank">https://github.com/tiangolo/full-stack-fastapi-postgresql</a>
- **FastAPI** 🎯 📟 🤪 🕧.
+///
+
+/// note
+
+👀 👈 📚 📟 🐩 `SQLAlchemy` 📟 👆 🔜 ⚙️ ⏮️ 🙆 🛠️.
+
+ **FastAPI** 🎯 📟 🤪 🕧.
+
+///
## 🐜
🎏 🌌 👆 💪 ⚙️ 🙆 🎏 🐜.
-!!! tip
- 📤 🌓 📄 ⚙️ 🏒 📥 🩺.
+/// tip
+
+📤 🌓 📄 ⚙️ 🏒 📥 🩺.
+
+///
## 📁 📊
...& 🛠️ ⚫️ ⏮️ 👆 💽 📊 & 🎓 (📊 ✳, ✳ ⚖️ 🙆 🎏).
-!!! tip
+/// tip
- 👉 👑 ⏸ 👈 👆 🔜 ✔️ 🔀 🚥 👆 💚 ⚙️ 🎏 💽.
+👉 👑 ⏸ 👈 👆 🔜 ✔️ 🔀 🚥 👆 💚 ⚙️ 🎏 💽.
+
+///
### ✍ 🇸🇲 `engine`
...💪 🕴 `SQLite`. ⚫️ 🚫 💪 🎏 💽.
-!!! info "📡 ℹ"
+/// info | "📡 ℹ"
+
+🔢 🗄 🔜 🕴 ✔ 1️⃣ 🧵 🔗 ⏮️ ⚫️, 🤔 👈 🔠 🧵 🔜 🍵 🔬 📨.
- 🔢 🗄 🔜 🕴 ✔ 1️⃣ 🧵 🔗 ⏮️ ⚫️, 🤔 👈 🔠 🧵 🔜 🍵 🔬 📨.
+👉 ❎ 😫 🤝 🎏 🔗 🎏 👜 (🎏 📨).
- 👉 ❎ 😫 🤝 🎏 🔗 🎏 👜 (🎏 📨).
+✋️ FastAPI, ⚙️ 😐 🔢 (`def`) 🌅 🌘 1️⃣ 🧵 💪 🔗 ⏮️ 💽 🎏 📨, 👥 💪 ⚒ 🗄 💭 👈 ⚫️ 🔜 ✔ 👈 ⏮️ `connect_args={"check_same_thread": False}`.
- ✋️ FastAPI, ⚙️ 😐 🔢 (`def`) 🌅 🌘 1️⃣ 🧵 💪 🔗 ⏮️ 💽 🎏 📨, 👥 💪 ⚒ 🗄 💭 👈 ⚫️ 🔜 ✔ 👈 ⏮️ `connect_args={"check_same_thread": False}`.
+, 👥 🔜 ⚒ 💭 🔠 📨 🤚 🚮 👍 💽 🔗 🎉 🔗, 📤 🙅♂ 💪 👈 🔢 🛠️.
- , 👥 🔜 ⚒ 💭 🔠 📨 🤚 🚮 👍 💽 🔗 🎉 🔗, 📤 🙅♂ 💪 👈 🔢 🛠️.
+///
### ✍ `SessionLocal` 🎓
👥 🔜 ⚙️ 👉 `Base` 🎓 👥 ✍ ⏭ ✍ 🇸🇲 🏷.
-!!! tip
- 🇸🇲 ⚙️ ⚖ "**🏷**" 🔗 👉 🎓 & 👐 👈 🔗 ⏮️ 💽.
+/// tip
+
+🇸🇲 ⚙️ ⚖ "**🏷**" 🔗 👉 🎓 & 👐 👈 🔗 ⏮️ 💽.
- ✋️ Pydantic ⚙️ ⚖ "**🏷**" 🔗 🕳 🎏, 💽 🔬, 🛠️, & 🧾 🎓 & 👐.
+✋️ Pydantic ⚙️ ⚖ "**🏷**" 🔗 🕳 🎏, 💽 🔬, 🛠️, & 🧾 🎓 & 👐.
+
+///
🗄 `Base` ⚪️➡️ `database` (📁 `database.py` ⚪️➡️ 🔛).
🔜 ➡️ ✅ 📁 `sql_app/schemas.py`.
-!!! tip
- ❎ 😨 🖖 🇸🇲 *🏷* & Pydantic *🏷*, 👥 🔜 ✔️ 📁 `models.py` ⏮️ 🇸🇲 🏷, & 📁 `schemas.py` ⏮️ Pydantic 🏷.
+/// tip
+
+❎ 😨 🖖 🇸🇲 *🏷* & Pydantic *🏷*, 👥 🔜 ✔️ 📁 `models.py` ⏮️ 🇸🇲 🏷, & 📁 `schemas.py` ⏮️ Pydantic 🏷.
+
+👫 Pydantic 🏷 🔬 🌅 ⚖️ 🌘 "🔗" (☑ 📊 💠).
- 👫 Pydantic 🏷 🔬 🌅 ⚖️ 🌘 "🔗" (☑ 📊 💠).
+👉 🔜 ℹ 👥 ❎ 😨 ⏪ ⚙️ 👯♂️.
- 👉 🔜 ℹ 👥 ❎ 😨 ⏪ ⚙️ 👯♂️.
+///
### ✍ ▶️ Pydantic *🏷* / 🔗
✋️ 💂♂, `password` 🏆 🚫 🎏 Pydantic *🏷*, 🖼, ⚫️ 🏆 🚫 📨 ⚪️➡️ 🛠️ 🕐❔ 👂 👩💻.
-=== "🐍 3️⃣.6️⃣ & 🔛"
+//// tab | 🐍 3️⃣.6️⃣ & 🔛
- ```Python hl_lines="3 6-8 11-12 23-24 27-28"
- {!> ../../../docs_src/sql_databases/sql_app/schemas.py!}
- ```
+```Python hl_lines="3 6-8 11-12 23-24 27-28"
+{!> ../../../docs_src/sql_databases/sql_app/schemas.py!}
+```
+
+////
+
+//// tab | 🐍 3️⃣.9️⃣ & 🔛
-=== "🐍 3️⃣.9️⃣ & 🔛"
+```Python hl_lines="3 6-8 11-12 23-24 27-28"
+{!> ../../../docs_src/sql_databases/sql_app_py39/schemas.py!}
+```
+
+////
- ```Python hl_lines="3 6-8 11-12 23-24 27-28"
- {!> ../../../docs_src/sql_databases/sql_app_py39/schemas.py!}
- ```
+//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛
-=== "🐍 3️⃣.1️⃣0️⃣ & 🔛"
+```Python hl_lines="1 4-6 9-10 21-22 25-26"
+{!> ../../../docs_src/sql_databases/sql_app_py310/schemas.py!}
+```
- ```Python hl_lines="1 4-6 9-10 21-22 25-26"
- {!> ../../../docs_src/sql_databases/sql_app_py310/schemas.py!}
- ```
+////
#### 🇸🇲 👗 & Pydantic 👗
🚫 🕴 🆔 📚 🏬, ✋️ 🌐 💽 👈 👥 🔬 Pydantic *🏷* 👂 🏬: `Item`.
-=== "🐍 3️⃣.6️⃣ & 🔛"
+//// tab | 🐍 3️⃣.6️⃣ & 🔛
+
+```Python hl_lines="15-17 31-34"
+{!> ../../../docs_src/sql_databases/sql_app/schemas.py!}
+```
+
+////
+
+//// tab | 🐍 3️⃣.9️⃣ & 🔛
+
+```Python hl_lines="15-17 31-34"
+{!> ../../../docs_src/sql_databases/sql_app_py39/schemas.py!}
+```
+
+////
- ```Python hl_lines="15-17 31-34"
- {!> ../../../docs_src/sql_databases/sql_app/schemas.py!}
- ```
+//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛
-=== "🐍 3️⃣.9️⃣ & 🔛"
+```Python hl_lines="13-15 29-32"
+{!> ../../../docs_src/sql_databases/sql_app_py310/schemas.py!}
+```
- ```Python hl_lines="15-17 31-34"
- {!> ../../../docs_src/sql_databases/sql_app_py39/schemas.py!}
- ```
+////
-=== "🐍 3️⃣.1️⃣0️⃣ & 🔛"
+/// tip
- ```Python hl_lines="13-15 29-32"
- {!> ../../../docs_src/sql_databases/sql_app_py310/schemas.py!}
- ```
+👀 👈 `User`, Pydantic *🏷* 👈 🔜 ⚙️ 🕐❔ 👂 👩💻 (🛬 ⚫️ ⚪️➡️ 🛠️) 🚫 🔌 `password`.
-!!! tip
- 👀 👈 `User`, Pydantic *🏷* 👈 🔜 ⚙️ 🕐❔ 👂 👩💻 (🛬 ⚫️ ⚪️➡️ 🛠️) 🚫 🔌 `password`.
+///
### ⚙️ Pydantic `orm_mode`
`Config` 🎓, ⚒ 🔢 `orm_mode = True`.
-=== "🐍 3️⃣.6️⃣ & 🔛"
+//// tab | 🐍 3️⃣.6️⃣ & 🔛
+
+```Python hl_lines="15 19-20 31 36-37"
+{!> ../../../docs_src/sql_databases/sql_app/schemas.py!}
+```
+
+////
+
+//// tab | 🐍 3️⃣.9️⃣ & 🔛
- ```Python hl_lines="15 19-20 31 36-37"
- {!> ../../../docs_src/sql_databases/sql_app/schemas.py!}
- ```
+```Python hl_lines="15 19-20 31 36-37"
+{!> ../../../docs_src/sql_databases/sql_app_py39/schemas.py!}
+```
+
+////
+
+//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛
-=== "🐍 3️⃣.9️⃣ & 🔛"
+```Python hl_lines="13 17-18 29 34-35"
+{!> ../../../docs_src/sql_databases/sql_app_py310/schemas.py!}
+```
- ```Python hl_lines="15 19-20 31 36-37"
- {!> ../../../docs_src/sql_databases/sql_app_py39/schemas.py!}
- ```
+////
-=== "🐍 3️⃣.1️⃣0️⃣ & 🔛"
+/// tip
- ```Python hl_lines="13 17-18 29 34-35"
- {!> ../../../docs_src/sql_databases/sql_app_py310/schemas.py!}
- ```
+👀 ⚫️ ⚖ 💲 ⏮️ `=`, 💖:
-!!! tip
- 👀 ⚫️ ⚖ 💲 ⏮️ `=`, 💖:
+`orm_mode = True`
- `orm_mode = True`
+⚫️ 🚫 ⚙️ `:` 🆎 📄 ⏭.
- ⚫️ 🚫 ⚙️ `:` 🆎 📄 ⏭.
+👉 ⚒ 📁 💲, 🚫 📣 🆎.
- 👉 ⚒ 📁 💲, 🚫 📣 🆎.
+///
Pydantic `orm_mode` 🔜 💬 Pydantic *🏷* ✍ 💽 🚥 ⚫️ 🚫 `dict`, ✋️ 🐜 🏷 (⚖️ 🙆 🎏 ❌ 🎚 ⏮️ 🔢).
{!../../../docs_src/sql_databases/sql_app/crud.py!}
```
-!!! tip
- 🏗 🔢 👈 🕴 💡 🔗 ⏮️ 💽 (🤚 👩💻 ⚖️ 🏬) 🔬 👆 *➡ 🛠️ 🔢*, 👆 💪 🌖 💪 ♻ 👫 💗 🍕 & 🚮 <abbr title="Automated tests, written in code, that check if another piece of code is working correctly.">⚒ 💯</abbr> 👫.
+/// tip
+
+🏗 🔢 👈 🕴 💡 🔗 ⏮️ 💽 (🤚 👩💻 ⚖️ 🏬) 🔬 👆 *➡ 🛠️ 🔢*, 👆 💪 🌖 💪 ♻ 👫 💗 🍕 & 🚮 <abbr title="Automated tests, written in code, that check if another piece of code is working correctly.">⚒ 💯</abbr> 👫.
+
+///
### ✍ 💽
{!../../../docs_src/sql_databases/sql_app/crud.py!}
```
-!!! tip
- 🇸🇲 🏷 `User` 🔌 `hashed_password` 👈 🔜 🔌 🔐 #️⃣ ⏬ 🔐.
+/// tip
- ✋️ ⚫️❔ 🛠️ 👩💻 🚚 ⏮️ 🔐, 👆 💪 ⚗ ⚫️ & 🏗 #️⃣ 🔐 👆 🈸.
+🇸🇲 🏷 `User` 🔌 `hashed_password` 👈 🔜 🔌 🔐 #️⃣ ⏬ 🔐.
- & ⤴️ 🚶♀️ `hashed_password` ❌ ⏮️ 💲 🖊.
+✋️ ⚫️❔ 🛠️ 👩💻 🚚 ⏮️ 🔐, 👆 💪 ⚗ ⚫️ & 🏗 #️⃣ 🔐 👆 🈸.
-!!! warning
- 👉 🖼 🚫 🔐, 🔐 🚫#️⃣.
+ & ⤴️ 🚶♀️ `hashed_password` ❌ ⏮️ 💲 🖊.
- 🎰 👨❤👨 🈸 👆 🔜 💪 #️⃣ 🔐 & 🙅 🖊 👫 🔢.
+///
- 🌅 ℹ, 🚶 🔙 💂♂ 📄 🔰.
+/// warning
- 📥 👥 🎯 🕴 🔛 🧰 & 👨🔧 💽.
+👉 🖼 🚫 🔐, 🔐 🚫#️⃣.
-!!! tip
- ↩️ 🚶♀️ 🔠 🇨🇻 ❌ `Item` & 👂 🔠 1️⃣ 👫 ⚪️➡️ Pydantic *🏷*, 👥 🏭 `dict` ⏮️ Pydantic *🏷*'Ⓜ 📊 ⏮️:
+🎰 👨❤👨 🈸 👆 🔜 💪 #️⃣ 🔐 & 🙅 🖊 👫 🔢.
- `item.dict()`
+🌅 ℹ, 🚶 🔙 💂♂ 📄 🔰.
- & ⤴️ 👥 🚶♀️ `dict`'Ⓜ 🔑-💲 👫 🇨🇻 ❌ 🇸🇲 `Item`, ⏮️:
+📥 👥 🎯 🕴 🔛 🧰 & 👨🔧 💽.
- `Item(**item.dict())`
+///
- & ⤴️ 👥 🚶♀️ ➕ 🇨🇻 ❌ `owner_id` 👈 🚫 🚚 Pydantic *🏷*, ⏮️:
+/// tip
- `Item(**item.dict(), owner_id=user_id)`
+↩️ 🚶♀️ 🔠 🇨🇻 ❌ `Item` & 👂 🔠 1️⃣ 👫 ⚪️➡️ Pydantic *🏷*, 👥 🏭 `dict` ⏮️ Pydantic *🏷*'Ⓜ 📊 ⏮️:
+
+`item.dict()`
+
+ & ⤴️ 👥 🚶♀️ `dict`'Ⓜ 🔑-💲 👫 🇨🇻 ❌ 🇸🇲 `Item`, ⏮️:
+
+`Item(**item.dict())`
+
+ & ⤴️ 👥 🚶♀️ ➕ 🇨🇻 ❌ `owner_id` 👈 🚫 🚚 Pydantic *🏷*, ⏮️:
+
+`Item(**item.dict(), owner_id=user_id)`
+
+///
## 👑 **FastAPI** 📱
📶 🙃 🌌 ✍ 💽 🏓:
-=== "🐍 3️⃣.6️⃣ & 🔛"
+//// tab | 🐍 3️⃣.6️⃣ & 🔛
- ```Python hl_lines="9"
- {!> ../../../docs_src/sql_databases/sql_app/main.py!}
- ```
+```Python hl_lines="9"
+{!> ../../../docs_src/sql_databases/sql_app/main.py!}
+```
+
+////
+
+//// tab | 🐍 3️⃣.9️⃣ & 🔛
-=== "🐍 3️⃣.9️⃣ & 🔛"
+```Python hl_lines="7"
+{!> ../../../docs_src/sql_databases/sql_app_py39/main.py!}
+```
- ```Python hl_lines="7"
- {!> ../../../docs_src/sql_databases/sql_app_py39/main.py!}
- ```
+////
#### ⚗ 🗒
👆 🔗 🔜 ✍ 🆕 🇸🇲 `SessionLocal` 👈 🔜 ⚙️ 👁 📨, & ⤴️ 🔐 ⚫️ 🕐 📨 🏁.
-=== "🐍 3️⃣.6️⃣ & 🔛"
+//// tab | 🐍 3️⃣.6️⃣ & 🔛
+
+```Python hl_lines="15-20"
+{!> ../../../docs_src/sql_databases/sql_app/main.py!}
+```
+
+////
+
+//// tab | 🐍 3️⃣.9️⃣ & 🔛
+
+```Python hl_lines="13-18"
+{!> ../../../docs_src/sql_databases/sql_app_py39/main.py!}
+```
- ```Python hl_lines="15-20"
- {!> ../../../docs_src/sql_databases/sql_app/main.py!}
- ```
+////
-=== "🐍 3️⃣.9️⃣ & 🔛"
+/// info
- ```Python hl_lines="13-18"
- {!> ../../../docs_src/sql_databases/sql_app_py39/main.py!}
- ```
+👥 🚮 🏗 `SessionLocal()` & 🚚 📨 `try` 🍫.
-!!! info
- 👥 🚮 🏗 `SessionLocal()` & 🚚 📨 `try` 🍫.
+ & ⤴️ 👥 🔐 ⚫️ `finally` 🍫.
- & ⤴️ 👥 🔐 ⚫️ `finally` 🍫.
+👉 🌌 👥 ⚒ 💭 💽 🎉 🕧 📪 ⏮️ 📨. 🚥 📤 ⚠ ⏪ 🏭 📨.
- 👉 🌌 👥 ⚒ 💭 💽 🎉 🕧 📪 ⏮️ 📨. 🚥 📤 ⚠ ⏪ 🏭 📨.
+✋️ 👆 💪 🚫 🤚 ➕1️⃣ ⚠ ⚪️➡️ 🚪 📟 (⏮️ `yield`). 👀 🌖 [🔗 ⏮️ `yield` & `HTTPException`](dependencies/dependencies-with-yield.md#yield-httpexception){.internal-link target=_blank}
- ✋️ 👆 💪 🚫 🤚 ➕1️⃣ ⚠ ⚪️➡️ 🚪 📟 (⏮️ `yield`). 👀 🌖 [🔗 ⏮️ `yield` & `HTTPException`](dependencies/dependencies-with-yield.md#yield-httpexception){.internal-link target=_blank}
+///
& ⤴️, 🕐❔ ⚙️ 🔗 *➡ 🛠️ 🔢*, 👥 📣 ⚫️ ⏮️ 🆎 `Session` 👥 🗄 🔗 ⚪️➡️ 🇸🇲.
👉 🔜 ⤴️ 🤝 👥 👍 👨🎨 🐕🦺 🔘 *➡ 🛠️ 🔢*, ↩️ 👨🎨 🔜 💭 👈 `db` 🔢 🆎 `Session`:
-=== "🐍 3️⃣.6️⃣ & 🔛"
+//// tab | 🐍 3️⃣.6️⃣ & 🔛
+
+```Python hl_lines="24 32 38 47 53"
+{!> ../../../docs_src/sql_databases/sql_app/main.py!}
+```
+
+////
+
+//// tab | 🐍 3️⃣.9️⃣ & 🔛
+
+```Python hl_lines="22 30 36 45 51"
+{!> ../../../docs_src/sql_databases/sql_app_py39/main.py!}
+```
- ```Python hl_lines="24 32 38 47 53"
- {!> ../../../docs_src/sql_databases/sql_app/main.py!}
- ```
+////
-=== "🐍 3️⃣.9️⃣ & 🔛"
+/// info | "📡 ℹ"
- ```Python hl_lines="22 30 36 45 51"
- {!> ../../../docs_src/sql_databases/sql_app_py39/main.py!}
- ```
+🔢 `db` 🤙 🆎 `SessionLocal`, ✋️ 👉 🎓 (✍ ⏮️ `sessionmaker()`) "🗳" 🇸🇲 `Session`,, 👨🎨 🚫 🤙 💭 ⚫️❔ 👩🔬 🚚.
-!!! info "📡 ℹ"
- 🔢 `db` 🤙 🆎 `SessionLocal`, ✋️ 👉 🎓 (✍ ⏮️ `sessionmaker()`) "🗳" 🇸🇲 `Session`,, 👨🎨 🚫 🤙 💭 ⚫️❔ 👩🔬 🚚.
+✋️ 📣 🆎 `Session`, 👨🎨 🔜 💪 💭 💪 👩🔬 (`.add()`, `.query()`, `.commit()`, ♒️) & 💪 🚚 👍 🐕🦺 (💖 🛠️). 🆎 📄 🚫 📉 ☑ 🎚.
- ✋️ 📣 🆎 `Session`, 👨🎨 🔜 💪 💭 💪 👩🔬 (`.add()`, `.query()`, `.commit()`, ♒️) & 💪 🚚 👍 🐕🦺 (💖 🛠️). 🆎 📄 🚫 📉 ☑ 🎚.
+///
### ✍ 👆 **FastAPI** *➡ 🛠️*
🔜, 😒, 📥 🐩 **FastAPI** *➡ 🛠️* 📟.
-=== "🐍 3️⃣.6️⃣ & 🔛"
+//// tab | 🐍 3️⃣.6️⃣ & 🔛
+
+```Python hl_lines="23-28 31-34 37-42 45-49 52-55"
+{!> ../../../docs_src/sql_databases/sql_app/main.py!}
+```
+
+////
- ```Python hl_lines="23-28 31-34 37-42 45-49 52-55"
- {!> ../../../docs_src/sql_databases/sql_app/main.py!}
- ```
+//// tab | 🐍 3️⃣.9️⃣ & 🔛
-=== "🐍 3️⃣.9️⃣ & 🔛"
+```Python hl_lines="21-26 29-32 35-40 43-47 50-53"
+{!> ../../../docs_src/sql_databases/sql_app_py39/main.py!}
+```
- ```Python hl_lines="21-26 29-32 35-40 43-47 50-53"
- {!> ../../../docs_src/sql_databases/sql_app_py39/main.py!}
- ```
+////
👥 🏗 💽 🎉 ⏭ 🔠 📨 🔗 ⏮️ `yield`, & ⤴️ 📪 ⚫️ ⏮️.
⏮️ 👈, 👥 💪 🤙 `crud.get_user` 🔗 ⚪️➡️ 🔘 *➡ 🛠️ 🔢* & ⚙️ 👈 🎉.
-!!! tip
- 👀 👈 💲 👆 📨 🇸🇲 🏷, ⚖️ 📇 🇸🇲 🏷.
+/// tip
+
+👀 👈 💲 👆 📨 🇸🇲 🏷, ⚖️ 📇 🇸🇲 🏷.
+
+✋️ 🌐 *➡ 🛠️* ✔️ `response_model` ⏮️ Pydantic *🏷* / 🔗 ⚙️ `orm_mode`, 💽 📣 👆 Pydantic 🏷 🔜 ⚗ ⚪️➡️ 👫 & 📨 👩💻, ⏮️ 🌐 😐 ⛽ & 🔬.
+
+///
+
+/// tip
- ✋️ 🌐 *➡ 🛠️* ✔️ `response_model` ⏮️ Pydantic *🏷* / 🔗 ⚙️ `orm_mode`, 💽 📣 👆 Pydantic 🏷 🔜 ⚗ ⚪️➡️ 👫 & 📨 👩💻, ⏮️ 🌐 😐 ⛽ & 🔬.
+👀 👈 📤 `response_models` 👈 ✔️ 🐩 🐍 🆎 💖 `List[schemas.Item]`.
-!!! tip
- 👀 👈 📤 `response_models` 👈 ✔️ 🐩 🐍 🆎 💖 `List[schemas.Item]`.
+✋️ 🎚/🔢 👈 `List` Pydantic *🏷* ⏮️ `orm_mode`, 💽 🔜 🗃 & 📨 👩💻 🛎, 🍵 ⚠.
- ✋️ 🎚/🔢 👈 `List` Pydantic *🏷* ⏮️ `orm_mode`, 💽 🔜 🗃 & 📨 👩💻 🛎, 🍵 ⚠.
+///
### 🔃 `def` 🆚 `async def`
...
```
-!!! info
- 🚥 👆 💪 🔗 👆 🔗 💽 🔁, 👀 [🔁 🗄 (🔗) 💽](../advanced/async-sql-databases.md){.internal-link target=_blank}.
+/// info
-!!! note "📶 📡 ℹ"
- 🚥 👆 😟 & ✔️ ⏬ 📡 💡, 👆 💪 ✅ 📶 📡 ℹ ❔ 👉 `async def` 🆚 `def` 🍵 [🔁](../async.md#i_2){.internal-link target=_blank} 🩺.
+🚥 👆 💪 🔗 👆 🔗 💽 🔁, 👀 [🔁 🗄 (🔗) 💽](../advanced/async-sql-databases.md){.internal-link target=_blank}.
+
+///
+
+/// note | "📶 📡 ℹ"
+
+🚥 👆 😟 & ✔️ ⏬ 📡 💡, 👆 💪 ✅ 📶 📡 ℹ ❔ 👉 `async def` 🆚 `def` 🍵 [🔁](../async.md#i_2){.internal-link target=_blank} 🩺.
+
+///
## 🛠️
* `sql_app/schemas.py`:
-=== "🐍 3️⃣.6️⃣ & 🔛"
+//// tab | 🐍 3️⃣.6️⃣ & 🔛
+
+```Python
+{!> ../../../docs_src/sql_databases/sql_app/schemas.py!}
+```
+
+////
+
+//// tab | 🐍 3️⃣.9️⃣ & 🔛
- ```Python
- {!> ../../../docs_src/sql_databases/sql_app/schemas.py!}
- ```
+```Python
+{!> ../../../docs_src/sql_databases/sql_app_py39/schemas.py!}
+```
-=== "🐍 3️⃣.9️⃣ & 🔛"
+////
- ```Python
- {!> ../../../docs_src/sql_databases/sql_app_py39/schemas.py!}
- ```
+//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛
-=== "🐍 3️⃣.1️⃣0️⃣ & 🔛"
+```Python
+{!> ../../../docs_src/sql_databases/sql_app_py310/schemas.py!}
+```
- ```Python
- {!> ../../../docs_src/sql_databases/sql_app_py310/schemas.py!}
- ```
+////
* `sql_app/crud.py`:
* `sql_app/main.py`:
-=== "🐍 3️⃣.6️⃣ & 🔛"
+//// tab | 🐍 3️⃣.6️⃣ & 🔛
+
+```Python
+{!> ../../../docs_src/sql_databases/sql_app/main.py!}
+```
+
+////
- ```Python
- {!> ../../../docs_src/sql_databases/sql_app/main.py!}
- ```
+//// tab | 🐍 3️⃣.9️⃣ & 🔛
-=== "🐍 3️⃣.9️⃣ & 🔛"
+```Python
+{!> ../../../docs_src/sql_databases/sql_app_py39/main.py!}
+```
- ```Python
- {!> ../../../docs_src/sql_databases/sql_app_py39/main.py!}
- ```
+////
## ✅ ⚫️
👆 💪 📁 👉 📟 & ⚙️ ⚫️.
-!!! info
+/// info
+
+👐, 📟 🎦 📥 🍕 💯. 🌅 📟 👉 🩺.
- 👐, 📟 🎦 📥 🍕 💯. 🌅 📟 👉 🩺.
+///
⤴️ 👆 💪 🏃 ⚫️ ⏮️ Uvicorn:
🛠️ 👥 🔜 🚮 (🔢) 🔜 ✍ 🆕 🇸🇲 `SessionLocal` 🔠 📨, 🚮 ⚫️ 📨 & ⤴️ 🔐 ⚫️ 🕐 📨 🏁.
-=== "🐍 3️⃣.6️⃣ & 🔛"
+//// tab | 🐍 3️⃣.6️⃣ & 🔛
+
+```Python hl_lines="14-22"
+{!> ../../../docs_src/sql_databases/sql_app/alt_main.py!}
+```
+
+////
+
+//// tab | 🐍 3️⃣.9️⃣ & 🔛
- ```Python hl_lines="14-22"
- {!> ../../../docs_src/sql_databases/sql_app/alt_main.py!}
- ```
+```Python hl_lines="12-20"
+{!> ../../../docs_src/sql_databases/sql_app_py39/alt_main.py!}
+```
+
+////
-=== "🐍 3️⃣.9️⃣ & 🔛"
+/// info
- ```Python hl_lines="12-20"
- {!> ../../../docs_src/sql_databases/sql_app_py39/alt_main.py!}
- ```
+👥 🚮 🏗 `SessionLocal()` & 🚚 📨 `try` 🍫.
-!!! info
- 👥 🚮 🏗 `SessionLocal()` & 🚚 📨 `try` 🍫.
+ & ⤴️ 👥 🔐 ⚫️ `finally` 🍫.
- & ⤴️ 👥 🔐 ⚫️ `finally` 🍫.
+👉 🌌 👥 ⚒ 💭 💽 🎉 🕧 📪 ⏮️ 📨. 🚥 📤 ⚠ ⏪ 🏭 📨.
- 👉 🌌 👥 ⚒ 💭 💽 🎉 🕧 📪 ⏮️ 📨. 🚥 📤 ⚠ ⏪ 🏭 📨.
+///
### 🔃 `request.state`
* , 🔗 🔜 ✍ 🔠 📨.
* 🕐❔ *➡ 🛠️* 👈 🍵 👈 📨 🚫 💪 💽.
-!!! tip
- ⚫️ 🎲 👍 ⚙️ 🔗 ⏮️ `yield` 🕐❔ 👫 🥃 ⚙️ 💼.
+/// tip
+
+⚫️ 🎲 👍 ⚙️ 🔗 ⏮️ `yield` 🕐❔ 👫 🥃 ⚙️ 💼.
+
+///
+
+/// info
+
+🔗 ⏮️ `yield` 🚮 ⏳ **FastAPI**.
-!!! info
- 🔗 ⏮️ `yield` 🚮 ⏳ **FastAPI**.
+⏮️ ⏬ 👉 🔰 🕴 ✔️ 🖼 ⏮️ 🛠️ & 📤 🎲 📚 🈸 ⚙️ 🛠️ 💽 🎉 🧾.
- ⏮️ ⏬ 👉 🔰 🕴 ✔️ 🖼 ⏮️ 🛠️ & 📤 🎲 📚 🈸 ⚙️ 🛠️ 💽 🎉 🧾.
+///
{!../../../docs_src/static_files/tutorial001.py!}
```
-!!! note "📡 ℹ"
- 👆 💪 ⚙️ `from starlette.staticfiles import StaticFiles`.
+/// note | "📡 ℹ"
- **FastAPI** 🚚 🎏 `starlette.staticfiles` `fastapi.staticfiles` 🏪 👆, 👩💻. ✋️ ⚫️ 🤙 👟 🔗 ⚪️➡️ 💃.
+👆 💪 ⚙️ `from starlette.staticfiles import StaticFiles`.
+
+**FastAPI** 🚚 🎏 `starlette.staticfiles` `fastapi.staticfiles` 🏪 👆, 👩💻. ✋️ ⚫️ 🤙 👟 🔗 ⚪️➡️ 💃.
+
+///
### ⚫️❔ "🗜"
## ⚙️ `TestClient`
-!!! info
- ⚙️ `TestClient`, 🥇 ❎ <a href="https://www.python-httpx.org" class="external-link" target="_blank">`httpx`</a>.
+/// info
- 🤶 Ⓜ. `pip install httpx`.
+⚙️ `TestClient`, 🥇 ❎ <a href="https://www.python-httpx.org" class="external-link" target="_blank">`httpx`</a>.
+
+🤶 Ⓜ. `pip install httpx`.
+
+///
🗄 `TestClient`.
{!../../../docs_src/app_testing/tutorial001.py!}
```
-!!! tip
- 👀 👈 🔬 🔢 😐 `def`, 🚫 `async def`.
+/// tip
+
+👀 👈 🔬 🔢 😐 `def`, 🚫 `async def`.
+
+ & 🤙 👩💻 😐 🤙, 🚫 ⚙️ `await`.
+
+👉 ✔ 👆 ⚙️ `pytest` 🔗 🍵 🤢.
+
+///
+
+/// note | "📡 ℹ"
+
+👆 💪 ⚙️ `from starlette.testclient import TestClient`.
- & 🤙 👩💻 😐 🤙, 🚫 ⚙️ `await`.
+**FastAPI** 🚚 🎏 `starlette.testclient` `fastapi.testclient` 🏪 👆, 👩💻. ✋️ ⚫️ 👟 🔗 ⚪️➡️ 💃.
- 👉 ✔ 👆 ⚙️ `pytest` 🔗 🍵 🤢.
+///
-!!! note "📡 ℹ"
- 👆 💪 ⚙️ `from starlette.testclient import TestClient`.
+/// tip
- **FastAPI** 🚚 🎏 `starlette.testclient` `fastapi.testclient` 🏪 👆, 👩💻. ✋️ ⚫️ 👟 🔗 ⚪️➡️ 💃.
+🚥 👆 💚 🤙 `async` 🔢 👆 💯 ↖️ ⚪️➡️ 📨 📨 👆 FastAPI 🈸 (✅ 🔁 💽 🔢), ✔️ 👀 [🔁 💯](../advanced/async-tests.md){.internal-link target=_blank} 🏧 🔰.
-!!! tip
- 🚥 👆 💚 🤙 `async` 🔢 👆 💯 ↖️ ⚪️➡️ 📨 📨 👆 FastAPI 🈸 (✅ 🔁 💽 🔢), ✔️ 👀 [🔁 💯](../advanced/async-tests.md){.internal-link target=_blank} 🏧 🔰.
+///
## 🎏 💯
👯♂️ *➡ 🛠️* 🚚 `X-Token` 🎚.
-=== "🐍 3️⃣.6️⃣ & 🔛"
+//// tab | 🐍 3️⃣.6️⃣ & 🔛
- ```Python
- {!> ../../../docs_src/app_testing/app_b/main.py!}
- ```
+```Python
+{!> ../../../docs_src/app_testing/app_b/main.py!}
+```
+
+////
+
+//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛
-=== "🐍 3️⃣.1️⃣0️⃣ & 🔛"
+```Python
+{!> ../../../docs_src/app_testing/app_b_py310/main.py!}
+```
- ```Python
- {!> ../../../docs_src/app_testing/app_b_py310/main.py!}
- ```
+////
### ↔ 🔬 📁
🌖 ℹ 🔃 ❔ 🚶♀️ 💽 👩💻 (⚙️ `httpx` ⚖️ `TestClient`) ✅ <a href="https://www.python-httpx.org" class="external-link" target="_blank">🇸🇲 🧾</a>.
-!!! info
- 🗒 👈 `TestClient` 📨 💽 👈 💪 🗜 🎻, 🚫 Pydantic 🏷.
+/// info
+
+🗒 👈 `TestClient` 📨 💽 👈 💪 🗜 🎻, 🚫 Pydantic 🏷.
+
+🚥 👆 ✔️ Pydantic 🏷 👆 💯 & 👆 💚 📨 🚮 💽 🈸 ⏮️ 🔬, 👆 💪 ⚙️ `jsonable_encoder` 🔬 [🎻 🔗 🔢](encoder.md){.internal-link target=_blank}.
- 🚥 👆 ✔️ Pydantic 🏷 👆 💯 & 👆 💚 📨 🚮 💽 🈸 ⏮️ 🔬, 👆 💪 ⚙️ `jsonable_encoder` 🔬 [🎻 🔗 🔢](encoder.md){.internal-link target=_blank}.
+///
## 🏃 ⚫️
# Additional Responses in OpenAPI
-!!! warning
- This is a rather advanced topic.
+/// warning
- If you are starting with **FastAPI**, you might not need this.
+This is a rather advanced topic.
+
+If you are starting with **FastAPI**, you might not need this.
+
+///
You can declare additional responses, with additional status codes, media types, descriptions, etc.
{!../../../docs_src/additional_responses/tutorial001.py!}
```
-!!! note
- Keep in mind that you have to return the `JSONResponse` directly.
+/// note
+
+Keep in mind that you have to return the `JSONResponse` directly.
+
+///
+
+/// info
-!!! info
- The `model` key is not part of OpenAPI.
+The `model` key is not part of OpenAPI.
- **FastAPI** will take the Pydantic model from there, generate the `JSON Schema`, and put it in the correct place.
+**FastAPI** will take the Pydantic model from there, generate the `JSON Schema`, and put it in the correct place.
- The correct place is:
+The correct place is:
- * In the key `content`, that has as value another JSON object (`dict`) that contains:
- * A key with the media type, e.g. `application/json`, that contains as value another JSON object, that contains:
- * A key `schema`, that has as the value the JSON Schema from the model, here's the correct place.
- * **FastAPI** adds a reference here to the global JSON Schemas in another place in your OpenAPI instead of including it directly. This way, other applications and clients can use those JSON Schemas directly, provide better code generation tools, etc.
+* In the key `content`, that has as value another JSON object (`dict`) that contains:
+ * A key with the media type, e.g. `application/json`, that contains as value another JSON object, that contains:
+ * A key `schema`, that has as the value the JSON Schema from the model, here's the correct place.
+ * **FastAPI** adds a reference here to the global JSON Schemas in another place in your OpenAPI instead of including it directly. This way, other applications and clients can use those JSON Schemas directly, provide better code generation tools, etc.
+
+///
The generated responses in the OpenAPI for this *path operation* will be:
{!../../../docs_src/additional_responses/tutorial002.py!}
```
-!!! note
- Notice that you have to return the image using a `FileResponse` directly.
+/// note
+
+Notice that you have to return the image using a `FileResponse` directly.
+
+///
+
+/// info
+
+Unless you specify a different media type explicitly in your `responses` parameter, FastAPI will assume the response has the same media type as the main response class (default `application/json`).
-!!! info
- Unless you specify a different media type explicitly in your `responses` parameter, FastAPI will assume the response has the same media type as the main response class (default `application/json`).
+But if you have specified a custom response class with `None` as its media type, FastAPI will use `application/json` for any additional response that has an associated model.
- But if you have specified a custom response class with `None` as its media type, FastAPI will use `application/json` for any additional response that has an associated model.
+///
## Combining information
To achieve that, import `JSONResponse`, and return your content there directly, setting the `status_code` that you want:
-=== "Python 3.10+"
+//// tab | Python 3.10+
- ```Python hl_lines="4 25"
- {!> ../../../docs_src/additional_status_codes/tutorial001_an_py310.py!}
- ```
+```Python hl_lines="4 25"
+{!> ../../../docs_src/additional_status_codes/tutorial001_an_py310.py!}
+```
-=== "Python 3.9+"
+////
- ```Python hl_lines="4 25"
- {!> ../../../docs_src/additional_status_codes/tutorial001_an_py39.py!}
- ```
+//// tab | Python 3.9+
-=== "Python 3.8+"
+```Python hl_lines="4 25"
+{!> ../../../docs_src/additional_status_codes/tutorial001_an_py39.py!}
+```
- ```Python hl_lines="4 26"
- {!> ../../../docs_src/additional_status_codes/tutorial001_an.py!}
- ```
+////
-=== "Python 3.10+ non-Annotated"
+//// tab | Python 3.8+
- !!! tip
- Prefer to use the `Annotated` version if possible.
+```Python hl_lines="4 26"
+{!> ../../../docs_src/additional_status_codes/tutorial001_an.py!}
+```
- ```Python hl_lines="2 23"
- {!> ../../../docs_src/additional_status_codes/tutorial001_py310.py!}
- ```
+////
-=== "Python 3.8+ non-Annotated"
+//// tab | Python 3.10+ non-Annotated
- !!! tip
- Prefer to use the `Annotated` version if possible.
+/// tip
- ```Python hl_lines="4 25"
- {!> ../../../docs_src/additional_status_codes/tutorial001.py!}
- ```
+Prefer to use the `Annotated` version if possible.
-!!! warning
- When you return a `Response` directly, like in the example above, it will be returned directly.
+///
- It won't be serialized with a model, etc.
+```Python hl_lines="2 23"
+{!> ../../../docs_src/additional_status_codes/tutorial001_py310.py!}
+```
- Make sure it has the data you want it to have, and that the values are valid JSON (if you are using `JSONResponse`).
+////
-!!! note "Technical Details"
- You could also use `from starlette.responses import JSONResponse`.
+//// tab | Python 3.8+ non-Annotated
- **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 `status`.
+/// tip
+
+Prefer to use the `Annotated` version if possible.
+
+///
+
+```Python hl_lines="4 25"
+{!> ../../../docs_src/additional_status_codes/tutorial001.py!}
+```
+
+////
+
+/// warning
+
+When you return a `Response` directly, like in the example above, it will be returned directly.
+
+It won't be serialized with a model, etc.
+
+Make sure it has the data you want it to have, and that the values are valid JSON (if you are using `JSONResponse`).
+
+///
+
+/// note | "Technical Details"
+
+You could also use `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 `status`.
+
+///
## OpenAPI and API docs
To do that, we declare a method `__call__`:
-=== "Python 3.9+"
+//// tab | Python 3.9+
- ```Python hl_lines="12"
- {!> ../../../docs_src/dependencies/tutorial011_an_py39.py!}
- ```
+```Python hl_lines="12"
+{!> ../../../docs_src/dependencies/tutorial011_an_py39.py!}
+```
+
+////
+
+//// tab | Python 3.8+
+
+```Python hl_lines="11"
+{!> ../../../docs_src/dependencies/tutorial011_an.py!}
+```
-=== "Python 3.8+"
+////
- ```Python hl_lines="11"
- {!> ../../../docs_src/dependencies/tutorial011_an.py!}
- ```
+//// tab | Python 3.8+ non-Annotated
-=== "Python 3.8+ non-Annotated"
+/// tip
- !!! tip
- Prefer to use the `Annotated` version if possible.
+Prefer to use the `Annotated` version if possible.
- ```Python hl_lines="10"
- {!> ../../../docs_src/dependencies/tutorial011.py!}
- ```
+///
+
+```Python hl_lines="10"
+{!> ../../../docs_src/dependencies/tutorial011.py!}
+```
+
+////
In this case, this `__call__` is what **FastAPI** will use to check for additional parameters and sub-dependencies, and this is what will be called to pass a value to the parameter in your *path operation function* later.
And now, we can use `__init__` to declare the parameters of the instance that we can use to "parameterize" the dependency:
-=== "Python 3.9+"
+//// tab | Python 3.9+
- ```Python hl_lines="9"
- {!> ../../../docs_src/dependencies/tutorial011_an_py39.py!}
- ```
+```Python hl_lines="9"
+{!> ../../../docs_src/dependencies/tutorial011_an_py39.py!}
+```
-=== "Python 3.8+"
+////
- ```Python hl_lines="8"
- {!> ../../../docs_src/dependencies/tutorial011_an.py!}
- ```
+//// tab | Python 3.8+
-=== "Python 3.8+ non-Annotated"
+```Python hl_lines="8"
+{!> ../../../docs_src/dependencies/tutorial011_an.py!}
+```
+
+////
+
+//// tab | Python 3.8+ non-Annotated
+
+/// tip
- !!! tip
- Prefer to use the `Annotated` version if possible.
+Prefer to use the `Annotated` version if possible.
- ```Python hl_lines="7"
- {!> ../../../docs_src/dependencies/tutorial011.py!}
- ```
+///
+
+```Python hl_lines="7"
+{!> ../../../docs_src/dependencies/tutorial011.py!}
+```
+
+////
In this case, **FastAPI** won't ever touch or care about `__init__`, we will use it directly in our code.
We could create an instance of this class with:
-=== "Python 3.9+"
+//// tab | Python 3.9+
+
+```Python hl_lines="18"
+{!> ../../../docs_src/dependencies/tutorial011_an_py39.py!}
+```
+
+////
- ```Python hl_lines="18"
- {!> ../../../docs_src/dependencies/tutorial011_an_py39.py!}
- ```
+//// tab | Python 3.8+
-=== "Python 3.8+"
+```Python hl_lines="17"
+{!> ../../../docs_src/dependencies/tutorial011_an.py!}
+```
- ```Python hl_lines="17"
- {!> ../../../docs_src/dependencies/tutorial011_an.py!}
- ```
+////
-=== "Python 3.8+ non-Annotated"
+//// tab | Python 3.8+ non-Annotated
- !!! tip
- Prefer to use the `Annotated` version if possible.
+/// tip
- ```Python hl_lines="16"
- {!> ../../../docs_src/dependencies/tutorial011.py!}
- ```
+Prefer to use the `Annotated` version if possible.
+
+///
+
+```Python hl_lines="16"
+{!> ../../../docs_src/dependencies/tutorial011.py!}
+```
+
+////
And that way we are able to "parameterize" our dependency, that now has `"bar"` inside of it, as the attribute `checker.fixed_content`.
...and pass whatever that returns as the value of the dependency in our *path operation function* as the parameter `fixed_content_included`:
-=== "Python 3.9+"
+//// tab | Python 3.9+
+
+```Python hl_lines="22"
+{!> ../../../docs_src/dependencies/tutorial011_an_py39.py!}
+```
- ```Python hl_lines="22"
- {!> ../../../docs_src/dependencies/tutorial011_an_py39.py!}
- ```
+////
-=== "Python 3.8+"
+//// tab | Python 3.8+
- ```Python hl_lines="21"
- {!> ../../../docs_src/dependencies/tutorial011_an.py!}
- ```
+```Python hl_lines="21"
+{!> ../../../docs_src/dependencies/tutorial011_an.py!}
+```
+
+////
+
+//// tab | Python 3.8+ non-Annotated
+
+/// tip
+
+Prefer to use the `Annotated` version if possible.
+
+///
+
+```Python hl_lines="20"
+{!> ../../../docs_src/dependencies/tutorial011.py!}
+```
-=== "Python 3.8+ non-Annotated"
+////
- !!! tip
- Prefer to use the `Annotated` version if possible.
+/// tip
- ```Python hl_lines="20"
- {!> ../../../docs_src/dependencies/tutorial011.py!}
- ```
+All this might seem contrived. And it might not be very clear how is it useful yet.
-!!! tip
- All this might seem contrived. And it might not be very clear how is it useful yet.
+These examples are intentionally simple, but show how it all works.
- These examples are intentionally simple, but show how it all works.
+In the chapters about security, there are utility functions that are implemented in this same way.
- In the chapters about security, there are utility functions that are implemented in this same way.
+If you understood all this, you already know how those utility tools for security work underneath.
- If you understood all this, you already know how those utility tools for security work underneath.
+///
{!../../../docs_src/async_tests/test_main.py!}
```
-!!! tip
- Note that the test function is now `async def` instead of just `def` as before when using the `TestClient`.
+/// tip
+
+Note that the test function is now `async def` instead of just `def` as before when using the `TestClient`.
+
+///
Then we can create an `AsyncClient` with the app, and send async requests to it, using `await`.
...that we used to make our requests with the `TestClient`.
-!!! tip
- Note that we're using async/await with the new `AsyncClient` - the request is asynchronous.
+/// tip
+
+Note that we're using async/await with the new `AsyncClient` - the request is asynchronous.
+
+///
-!!! warning
- If your application relies on lifespan events, the `AsyncClient` won't trigger these events. To ensure they are triggered, use `LifespanManager` from <a href="https://github.com/florimondmanca/asgi-lifespan#usage" class="external-link" target="_blank">florimondmanca/asgi-lifespan</a>.
+/// warning
+
+If your application relies on lifespan events, the `AsyncClient` won't trigger these events. To ensure they are triggered, use `LifespanManager` from <a href="https://github.com/florimondmanca/asgi-lifespan#usage" class="external-link" target="_blank">florimondmanca/asgi-lifespan</a>.
+
+///
## Other Asynchronous Function Calls
As the testing function is now asynchronous, you can now also call (and `await`) other `async` functions apart from sending requests to your FastAPI application in your tests, exactly as you would call them anywhere else in your code.
-!!! tip
- If you encounter a `RuntimeError: Task attached to a different loop` when integrating asynchronous function calls in your tests (e.g. when using <a href="https://stackoverflow.com/questions/41584243/runtimeerror-task-attached-to-a-different-loop" class="external-link" target="_blank">MongoDB's MotorClient</a>) Remember to instantiate objects that need an event loop only within async functions, e.g. an `'@app.on_event("startup")` callback.
+/// tip
+
+If you encounter a `RuntimeError: Task attached to a different loop` when integrating asynchronous function calls in your tests (e.g. when using <a href="https://stackoverflow.com/questions/41584243/runtimeerror-task-attached-to-a-different-loop" class="external-link" target="_blank">MongoDB's MotorClient</a>) Remember to instantiate objects that need an event loop only within async functions, e.g. an `'@app.on_event("startup")` callback.
+
+///
proxy --> server
```
-!!! tip
- The IP `0.0.0.0` is commonly used to mean that the program listens on all the IPs available in that machine/server.
+/// tip
+
+The IP `0.0.0.0` is commonly used to mean that the program listens on all the IPs available in that machine/server.
+
+///
The docs UI would also need the OpenAPI schema to declare that this API `server` is located at `/api/v1` (behind the proxy). For example:
If you use Hypercorn, it also has the option `--root-path`.
-!!! note "Technical Details"
- The ASGI specification defines a `root_path` for this use case.
+/// note | "Technical Details"
+
+The ASGI specification defines a `root_path` for this use case.
+
+And the `--root-path` command line option provides that `root_path`.
- And the `--root-path` command line option provides that `root_path`.
+///
### Checking the current `root_path`
This tells Traefik to listen on port 9999 and to use another file `routes.toml`.
-!!! tip
- We are using port 9999 instead of the standard HTTP port 80 so that you don't have to run it with admin (`sudo`) privileges.
+/// tip
+
+We are using port 9999 instead of the standard HTTP port 80 so that you don't have to run it with admin (`sudo`) privileges.
+
+///
Now create that other file `routes.toml`:
}
```
-!!! tip
- Notice that even though you are accessing it at `http://127.0.0.1:8000/app` it shows the `root_path` of `/api/v1`, taken from the option `--root-path`.
+/// tip
+
+Notice that even though you are accessing it at `http://127.0.0.1:8000/app` it shows the `root_path` of `/api/v1`, taken from the option `--root-path`.
+
+///
And now open the URL with the port for Traefik, including the path prefix: <a href="http://127.0.0.1:9999/api/v1/app" class="external-link" target="_blank">http://127.0.0.1:9999/api/v1/app</a>.
## Additional servers
-!!! warning
- This is a more advanced use case. Feel free to skip it.
+/// warning
+
+This is a more advanced use case. Feel free to skip it.
+
+///
By default, **FastAPI** will create a `server` in the OpenAPI schema with the URL for the `root_path`.
}
```
-!!! tip
- Notice the auto-generated server with a `url` value of `/api/v1`, taken from the `root_path`.
+/// tip
+
+Notice the auto-generated server with a `url` value of `/api/v1`, taken from the `root_path`.
+
+///
In the docs UI at <a href="http://127.0.0.1:9999/api/v1/docs" class="external-link" target="_blank">http://127.0.0.1:9999/api/v1/docs</a> it would look like:
<img src="/img/tutorial/behind-a-proxy/image03.png">
-!!! tip
- The docs UI will interact with the server that you select.
+/// tip
+
+The docs UI will interact with the server that you select.
+
+///
### Disable automatic server from `root_path`
And if that `Response` has a JSON media type (`application/json`), like is the case with the `JSONResponse` and `UJSONResponse`, the data you return will be automatically converted (and filtered) with any Pydantic `response_model` that you declared in the *path operation decorator*.
-!!! note
- If you use a response class with no media type, FastAPI will expect your response to have no content, so it will not document the response format in its generated OpenAPI docs.
+/// note
+
+If you use a response class with no media type, FastAPI will expect your response to have no content, so it will not document the response format in its generated OpenAPI docs.
+
+///
## Use `ORJSONResponse`
{!../../../docs_src/custom_response/tutorial001b.py!}
```
-!!! info
- The parameter `response_class` will also be used to define the "media type" of the response.
+/// info
+
+The parameter `response_class` will also be used to define the "media type" of the response.
+
+In this case, the HTTP header `Content-Type` will be set to `application/json`.
- In this case, the HTTP header `Content-Type` will be set to `application/json`.
+And it will be documented as such in OpenAPI.
- And it will be documented as such in OpenAPI.
+///
-!!! tip
- The `ORJSONResponse` is only available in FastAPI, not in Starlette.
+/// tip
+
+The `ORJSONResponse` is only available in FastAPI, not in Starlette.
+
+///
## HTML Response
{!../../../docs_src/custom_response/tutorial002.py!}
```
-!!! info
- The parameter `response_class` will also be used to define the "media type" of the response.
+/// info
+
+The parameter `response_class` will also be used to define the "media type" of the response.
- In this case, the HTTP header `Content-Type` will be set to `text/html`.
+In this case, the HTTP header `Content-Type` will be set to `text/html`.
- And it will be documented as such in OpenAPI.
+And it will be documented as such in OpenAPI.
+
+///
### Return a `Response`
{!../../../docs_src/custom_response/tutorial003.py!}
```
-!!! warning
- A `Response` returned directly by your *path operation function* won't be documented in OpenAPI (for example, the `Content-Type` won't be documented) and won't be visible in the automatic interactive docs.
+/// warning
+
+A `Response` returned directly by your *path operation function* won't be documented in OpenAPI (for example, the `Content-Type` won't be documented) and won't be visible in the automatic interactive docs.
+
+///
-!!! info
- Of course, the actual `Content-Type` header, status code, etc, will come from the `Response` object you returned.
+/// info
+
+Of course, the actual `Content-Type` header, status code, etc, will come from the `Response` object you returned.
+
+///
### Document in OpenAPI and override `Response`
Keep in mind that you can use `Response` to return anything else, or even create a custom sub-class.
-!!! note "Technical Details"
- You could also use `from starlette.responses import HTMLResponse`.
+/// 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.
+
+///
### `Response`
A fast alternative JSON response using <a href="https://github.com/ijl/orjson" class="external-link" target="_blank">`orjson`</a>, as you read above.
-!!! info
- This requires installing `orjson` for example with `pip install orjson`.
+/// info
+
+This requires installing `orjson` for example with `pip install orjson`.
+
+///
### `UJSONResponse`
An alternative JSON response using <a href="https://github.com/ultrajson/ultrajson" class="external-link" target="_blank">`ujson`</a>.
-!!! info
- This requires installing `ujson` for example with `pip install ujson`.
+/// info
+
+This requires installing `ujson` for example with `pip install ujson`.
+
+///
+
+/// warning
+
+`ujson` is less careful than Python's built-in implementation in how it handles some edge-cases.
-!!! warning
- `ujson` is less careful than Python's built-in implementation in how it handles some edge-cases.
+///
```Python hl_lines="2 7"
{!../../../docs_src/custom_response/tutorial001.py!}
```
-!!! tip
- It's possible that `ORJSONResponse` might be a faster alternative.
+/// tip
+
+It's possible that `ORJSONResponse` might be a faster alternative.
+
+///
### `RedirectResponse`
By doing it this way, we can put it in a `with` block, and that way, ensure that it is closed after finishing.
-!!! tip
- Notice that here as we are using standard `open()` that doesn't support `async` and `await`, we declare the path operation with normal `def`.
+/// tip
+
+Notice that here as we are using standard `open()` that doesn't support `async` and `await`, we declare the path operation with normal `def`.
+
+///
### `FileResponse`
{!../../../docs_src/custom_response/tutorial010.py!}
```
-!!! tip
- You can still override `response_class` in *path operations* as before.
+/// tip
+
+You can still override `response_class` in *path operations* as before.
+
+///
## Additional documentation
This works the same way as with Pydantic models. And it is actually achieved in the same way underneath, using Pydantic.
-!!! info
- Keep in mind that dataclasses can't do everything Pydantic models can do.
+/// info
- So, you might still need to use Pydantic models.
+Keep in mind that dataclasses can't do everything Pydantic models can do.
- But if you have a bunch of dataclasses laying around, this is a nice trick to use them to power a web API using FastAPI. 🤓
+So, you might still need to use Pydantic models.
+
+But if you have a bunch of dataclasses laying around, this is a nice trick to use them to power a web API using FastAPI. 🤓
+
+///
## Dataclasses in `response_model`
And then, right after the `yield`, we unload the model. This code will be executed **after** the application **finishes handling requests**, right before the *shutdown*. This could, for example, release resources like memory or a GPU.
-!!! tip
- The `shutdown` would happen when you are **stopping** the application.
+/// tip
- Maybe you need to start a new version, or you just got tired of running it. 🤷
+The `shutdown` would happen when you are **stopping** the application.
+
+Maybe you need to start a new version, or you just got tired of running it. 🤷
+
+///
### Lifespan function
## Alternative Events (deprecated)
-!!! warning
- The recommended way to handle the *startup* and *shutdown* is using the `lifespan` parameter of the `FastAPI` app as described above. If you provide a `lifespan` parameter, `startup` and `shutdown` event handlers will no longer be called. It's all `lifespan` or all events, not both.
+/// warning
+
+The recommended way to handle the *startup* and *shutdown* is using the `lifespan` parameter of the `FastAPI` app as described above. If you provide a `lifespan` parameter, `startup` and `shutdown` event handlers will no longer be called. It's all `lifespan` or all events, not both.
- You can probably skip this part.
+You can probably skip this part.
+
+///
There's an alternative way to define this logic to be executed during *startup* and during *shutdown*.
Here, the `shutdown` event handler function will write a text line `"Application shutdown"` to a file `log.txt`.
-!!! info
- In the `open()` function, the `mode="a"` means "append", so, the line will be added after whatever is on that file, without overwriting the previous contents.
+/// info
+
+In the `open()` function, the `mode="a"` means "append", so, the line will be added after whatever is on that file, without overwriting the previous contents.
-!!! tip
- Notice that in this case we are using a standard Python `open()` function that interacts with a file.
+///
- So, it involves I/O (input/output), that requires "waiting" for things to be written to disk.
+/// tip
- But `open()` doesn't use `async` and `await`.
+Notice that in this case we are using a standard Python `open()` function that interacts with a file.
- So, we declare the event handler function with standard `def` instead of `async def`.
+So, it involves I/O (input/output), that requires "waiting" for things to be written to disk.
+
+But `open()` doesn't use `async` and `await`.
+
+So, we declare the event handler function with standard `def` instead of `async def`.
+
+///
### `startup` and `shutdown` together
Underneath, in the ASGI technical specification, this is part of the <a href="https://asgi.readthedocs.io/en/latest/specs/lifespan.html" class="external-link" target="_blank">Lifespan Protocol</a>, and it defines events called `startup` and `shutdown`.
-!!! info
- You can read more about the Starlette `lifespan` handlers in <a href="https://www.starlette.io/lifespan/" class="external-link" target="_blank">Starlette's Lifespan' docs</a>.
+/// info
+
+You can read more about the Starlette `lifespan` handlers in <a href="https://www.starlette.io/lifespan/" class="external-link" target="_blank">Starlette's Lifespan' docs</a>.
+
+Including how to handle lifespan state that can be used in other areas of your code.
- Including how to handle lifespan state that can be used in other areas of your code.
+///
## Sub Applications
Let's start with a simple FastAPI application:
-=== "Python 3.9+"
+//// tab | Python 3.9+
- ```Python hl_lines="7-9 12-13 16-17 21"
- {!> ../../../docs_src/generate_clients/tutorial001_py39.py!}
- ```
+```Python hl_lines="7-9 12-13 16-17 21"
+{!> ../../../docs_src/generate_clients/tutorial001_py39.py!}
+```
+
+////
-=== "Python 3.8+"
+//// tab | Python 3.8+
- ```Python hl_lines="9-11 14-15 18 19 23"
- {!> ../../../docs_src/generate_clients/tutorial001.py!}
- ```
+```Python hl_lines="9-11 14-15 18 19 23"
+{!> ../../../docs_src/generate_clients/tutorial001.py!}
+```
+
+////
Notice that the *path operations* define the models they use for request payload and response payload, using the models `Item` and `ResponseMessage`.
<img src="/img/tutorial/generate-clients/image03.png">
-!!! tip
- Notice the autocompletion for `name` and `price`, that was defined in the FastAPI application, in the `Item` model.
+/// tip
+
+Notice the autocompletion for `name` and `price`, that was defined in the FastAPI application, in the `Item` model.
+
+///
You will have inline errors for the data that you send:
For example, you could have a section for **items** and another section for **users**, and they could be separated by tags:
-=== "Python 3.9+"
+//// tab | Python 3.9+
+
+```Python hl_lines="21 26 34"
+{!> ../../../docs_src/generate_clients/tutorial002_py39.py!}
+```
+
+////
- ```Python hl_lines="21 26 34"
- {!> ../../../docs_src/generate_clients/tutorial002_py39.py!}
- ```
+//// tab | Python 3.8+
-=== "Python 3.8+"
+```Python hl_lines="23 28 36"
+{!> ../../../docs_src/generate_clients/tutorial002.py!}
+```
- ```Python hl_lines="23 28 36"
- {!> ../../../docs_src/generate_clients/tutorial002.py!}
- ```
+////
### Generate a TypeScript Client with Tags
You can then pass that custom function to **FastAPI** as the `generate_unique_id_function` parameter:
-=== "Python 3.9+"
+//// tab | Python 3.9+
+
+```Python hl_lines="6-7 10"
+{!> ../../../docs_src/generate_clients/tutorial003_py39.py!}
+```
- ```Python hl_lines="6-7 10"
- {!> ../../../docs_src/generate_clients/tutorial003_py39.py!}
- ```
+////
-=== "Python 3.8+"
+//// tab | Python 3.8+
+
+```Python hl_lines="8-9 12"
+{!> ../../../docs_src/generate_clients/tutorial003.py!}
+```
- ```Python hl_lines="8-9 12"
- {!> ../../../docs_src/generate_clients/tutorial003.py!}
- ```
+////
### Generate a TypeScript Client with Custom Operation IDs
We could download the OpenAPI JSON to a file `openapi.json` and then we could **remove that prefixed tag** with a script like this:
-=== "Python"
+//// tab | Python
- ```Python
- {!> ../../../docs_src/generate_clients/tutorial004.py!}
- ```
+```Python
+{!> ../../../docs_src/generate_clients/tutorial004.py!}
+```
+
+////
-=== "Node.js"
+//// tab | Node.js
+
+```Javascript
+{!> ../../../docs_src/generate_clients/tutorial004.js!}
+```
- ```Javascript
- {!> ../../../docs_src/generate_clients/tutorial004.js!}
- ```
+////
With that, the operation IDs would be renamed from things like `items-get_items` to just `get_items`, that way the client generator can generate simpler method names.
In the next sections you will see other options, configurations, and additional features.
-!!! tip
- The next sections are **not necessarily "advanced"**.
+/// tip
- And it's possible that for your use case, the solution is in one of them.
+The next sections are **not necessarily "advanced"**.
+
+And it's possible that for your use case, the solution is in one of them.
+
+///
## Read the Tutorial first
**FastAPI** includes several middlewares for common use cases, we'll see next how to use them.
-!!! note "Technical Details"
- For the next examples, you could also use `from starlette.middleware.something import SomethingMiddleware`.
+/// note | "Technical Details"
- **FastAPI** provides several middlewares in `fastapi.middleware` just as a convenience for you, the developer. But most of the available middlewares come directly from Starlette.
+For the next examples, you could also use `from starlette.middleware.something import SomethingMiddleware`.
+
+**FastAPI** provides several middlewares in `fastapi.middleware` just as a convenience for you, the developer. But most of the available middlewares come directly from Starlette.
+
+///
## `HTTPSRedirectMiddleware`
{!../../../docs_src/openapi_callbacks/tutorial001.py!}
```
-!!! tip
- The `callback_url` query parameter uses a Pydantic <a href="https://docs.pydantic.dev/latest/concepts/types/#urls" class="external-link" target="_blank">URL</a> type.
+/// tip
+
+The `callback_url` query parameter uses a Pydantic <a href="https://docs.pydantic.dev/latest/concepts/types/#urls" class="external-link" target="_blank">URL</a> type.
+
+///
The 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.
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 <a href="https://www.python-httpx.org" class="external-link" target="_blank">HTTPX</a> or <a href="https://requests.readthedocs.io/" class="external-link" target="_blank">Requests</a>.
+When implementing the callback yourself, you could use something like <a href="https://www.python-httpx.org" class="external-link" target="_blank">HTTPX</a> or <a href="https://requests.readthedocs.io/" class="external-link" target="_blank">Requests</a>.
+
+///
## Write the callback documentation code
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`
}
```
-!!! 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
{!../../../docs_src/openapi_callbacks/tutorial001.py!}
```
-!!! 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
This can make it a lot easier for your users to **implement their APIs** to receive your **webhook** requests, they might even be able to autogenerate some of their own API code.
-!!! info
- Webhooks are available in OpenAPI 3.1.0 and above, supported by FastAPI `0.99.0` and above.
+/// info
+
+Webhooks are available in OpenAPI 3.1.0 and above, supported by FastAPI `0.99.0` and above.
+
+///
## An app with webhooks
The webhooks that you define will end up in the **OpenAPI** schema and the automatic **docs UI**.
-!!! info
- The `app.webhooks` object is actually just an `APIRouter`, the same type you would use when structuring your app with multiple files.
+/// info
+
+The `app.webhooks` object is actually just an `APIRouter`, the same type you would use when structuring your app with multiple files.
+
+///
Notice that with webhooks you are actually not declaring a *path* (like `/items/`), the text you pass there is just an **identifier** of the webhook (the name of the event), for example in `@app.webhooks.post("new-subscription")`, the webhook name is `new-subscription`.
## OpenAPI operationId
-!!! warning
- If you are not an "expert" in OpenAPI, you probably don't need this.
+/// warning
+
+If you are not an "expert" in OpenAPI, you probably don't need this.
+
+///
You can set the OpenAPI `operationId` to be used in your *path operation* with the parameter `operation_id`.
{!../../../docs_src/path_operation_advanced_configuration/tutorial002.py!}
```
-!!! tip
- If you manually call `app.openapi()`, you should update the `operationId`s before that.
+/// tip
+
+If you manually call `app.openapi()`, you should update the `operationId`s before that.
+
+///
+
+/// warning
+
+If you do this, you have to make sure each one of your *path operation functions* has a unique name.
-!!! warning
- If you do this, you have to make sure each one of your *path operation functions* has a unique name.
+Even if they are in different modules (Python files).
- Even if they are in different modules (Python files).
+///
## Exclude from OpenAPI
When you declare a *path operation* in your application, **FastAPI** automatically generates the relevant metadata about that *path operation* to be included in the OpenAPI schema.
-!!! note "Technical details"
- In the OpenAPI specification it is called the <a href="https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.3.md#operation-object" class="external-link" target="_blank">Operation Object</a>.
+/// note | "Technical details"
+
+In the OpenAPI specification it is called the <a href="https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.3.md#operation-object" class="external-link" target="_blank">Operation Object</a>.
+
+///
It has all the information about the *path operation* and is used to generate the automatic documentation.
This *path operation*-specific OpenAPI schema is normally generated automatically by **FastAPI**, but you can also extend it.
-!!! tip
- This is a low level extension point.
+/// tip
+
+This is a low level extension point.
- If you only need to declare additional responses, a more convenient way to do it is with [Additional Responses in OpenAPI](additional-responses.md){.internal-link target=_blank}.
+If you only need to declare additional responses, a more convenient way to do it is with [Additional Responses in OpenAPI](additional-responses.md){.internal-link target=_blank}.
+
+///
You can extend the OpenAPI schema for a *path operation* using the parameter `openapi_extra`.
For example, in this application we don't use FastAPI's integrated functionality to extract the JSON Schema from Pydantic models nor the automatic validation for JSON. In fact, we are declaring the request content type as YAML, not JSON:
-=== "Pydantic v2"
+//// tab | Pydantic v2
+
+```Python hl_lines="17-22 24"
+{!> ../../../docs_src/path_operation_advanced_configuration/tutorial007.py!}
+```
+
+////
+
+//// tab | Pydantic v1
+
+```Python hl_lines="17-22 24"
+{!> ../../../docs_src/path_operation_advanced_configuration/tutorial007_pv1.py!}
+```
- ```Python hl_lines="17-22 24"
- {!> ../../../docs_src/path_operation_advanced_configuration/tutorial007.py!}
- ```
+////
-=== "Pydantic v1"
+/// info
- ```Python hl_lines="17-22 24"
- {!> ../../../docs_src/path_operation_advanced_configuration/tutorial007_pv1.py!}
- ```
+In Pydantic version 1 the method to get the JSON Schema for a model was called `Item.schema()`, in Pydantic version 2, the method is called `Item.model_json_schema()`.
-!!! info
- In Pydantic version 1 the method to get the JSON Schema for a model was called `Item.schema()`, in Pydantic version 2, the method is called `Item.model_json_schema()`.
+///
Nevertheless, although we are not using the default integrated functionality, we are still using a Pydantic model to manually generate the JSON Schema for the data that we want to receive in YAML.
And then in our code, we parse that YAML content directly, and then we are again using the same Pydantic model to validate the YAML content:
-=== "Pydantic v2"
+//// tab | Pydantic v2
+
+```Python hl_lines="26-33"
+{!> ../../../docs_src/path_operation_advanced_configuration/tutorial007.py!}
+```
+
+////
+
+//// tab | Pydantic v1
+
+```Python hl_lines="26-33"
+{!> ../../../docs_src/path_operation_advanced_configuration/tutorial007_pv1.py!}
+```
+
+////
+
+/// info
- ```Python hl_lines="26-33"
- {!> ../../../docs_src/path_operation_advanced_configuration/tutorial007.py!}
- ```
+In Pydantic version 1 the method to parse and validate an object was `Item.parse_obj()`, in Pydantic version 2, the method is called `Item.model_validate()`.
-=== "Pydantic v1"
+///
- ```Python hl_lines="26-33"
- {!> ../../../docs_src/path_operation_advanced_configuration/tutorial007_pv1.py!}
- ```
+/// tip
-!!! info
- In Pydantic version 1 the method to parse and validate an object was `Item.parse_obj()`, in Pydantic version 2, the method is called `Item.model_validate()`.
+Here we reuse the same Pydantic model.
-!!! tip
- Here we reuse the same Pydantic model.
+But the same way, we could have validated it in some other way.
- But the same way, we could have validated it in some other way.
+///
{!../../../docs_src/response_cookies/tutorial001.py!}
```
-!!! tip
- Keep in mind that if you return a response directly instead of using the `Response` parameter, FastAPI will return it directly.
+/// tip
- So, you will have to make sure your data is of the correct type. E.g. it is compatible with JSON, if you are returning a `JSONResponse`.
+Keep in mind that if you return a response directly instead of using the `Response` parameter, FastAPI will return it directly.
- And also that you are not sending any data that should have been filtered by a `response_model`.
+So, you will have to make sure your data is of the correct type. E.g. it is compatible with JSON, if you are returning a `JSONResponse`.
+
+And also that you are not sending any data that should have been filtered by a `response_model`.
+
+///
### More info
-!!! note "Technical Details"
- You could also use `from starlette.responses import Response` or `from starlette.responses import JSONResponse`.
+/// note | "Technical Details"
+
+You could also use `from starlette.responses import Response` or `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.
- **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.
+And as the `Response` can be used frequently to set headers and cookies, **FastAPI** also provides it at `fastapi.Response`.
- And as the `Response` can be used frequently to set headers and cookies, **FastAPI** also provides it at `fastapi.Response`.
+///
To see all the available parameters and options, check the <a href="https://www.starlette.io/responses/#set-cookie" class="external-link" target="_blank">documentation in Starlette</a>.
In fact, you can return any `Response` or any sub-class of it.
-!!! tip
- `JSONResponse` itself is a sub-class of `Response`.
+/// tip
+
+`JSONResponse` itself is a sub-class of `Response`.
+
+///
And when you return a `Response`, **FastAPI** will pass it directly.
{!../../../docs_src/response_directly/tutorial001.py!}
```
-!!! note "Technical Details"
- You could also use `from starlette.responses import JSONResponse`.
+/// note | "Technical Details"
+
+You could also use `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.
- **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.
+///
## Returning a custom `Response`
{!../../../docs_src/response_headers/tutorial001.py!}
```
-!!! note "Technical Details"
- You could also use `from starlette.responses import Response` or `from starlette.responses import JSONResponse`.
+/// note | "Technical Details"
- **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.
+You could also use `from starlette.responses import Response` or `from starlette.responses import JSONResponse`.
- And as the `Response` can be used frequently to set headers and cookies, **FastAPI** also provides it at `fastapi.Response`.
+**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.
+
+And as the `Response` can be used frequently to set headers and cookies, **FastAPI** also provides it at `fastapi.Response`.
+
+///
## Custom Headers
* It returns an object of type `HTTPBasicCredentials`:
* It contains the `username` and `password` sent.
-=== "Python 3.9+"
+//// tab | Python 3.9+
- ```Python hl_lines="4 8 12"
- {!> ../../../docs_src/security/tutorial006_an_py39.py!}
- ```
+```Python hl_lines="4 8 12"
+{!> ../../../docs_src/security/tutorial006_an_py39.py!}
+```
+
+////
+
+//// tab | Python 3.8+
+
+```Python hl_lines="2 7 11"
+{!> ../../../docs_src/security/tutorial006_an.py!}
+```
+
+////
-=== "Python 3.8+"
+//// tab | Python 3.8+ non-Annotated
- ```Python hl_lines="2 7 11"
- {!> ../../../docs_src/security/tutorial006_an.py!}
- ```
+/// tip
-=== "Python 3.8+ non-Annotated"
+Prefer to use the `Annotated` version if possible.
- !!! tip
- Prefer to use the `Annotated` version if possible.
+///
- ```Python hl_lines="2 6 10"
- {!> ../../../docs_src/security/tutorial006.py!}
- ```
+```Python hl_lines="2 6 10"
+{!> ../../../docs_src/security/tutorial006.py!}
+```
+
+////
When you try to open the URL for the first time (or click the "Execute" button in the docs) the browser will ask you for your username and password:
Then we can use `secrets.compare_digest()` to ensure that `credentials.username` is `"stanleyjobson"`, and that `credentials.password` is `"swordfish"`.
-=== "Python 3.9+"
+//// tab | Python 3.9+
+
+```Python hl_lines="1 12-24"
+{!> ../../../docs_src/security/tutorial007_an_py39.py!}
+```
+
+////
+
+//// tab | Python 3.8+
- ```Python hl_lines="1 12-24"
- {!> ../../../docs_src/security/tutorial007_an_py39.py!}
- ```
+```Python hl_lines="1 12-24"
+{!> ../../../docs_src/security/tutorial007_an.py!}
+```
+
+////
+
+//// tab | Python 3.8+ non-Annotated
-=== "Python 3.8+"
+/// tip
- ```Python hl_lines="1 12-24"
- {!> ../../../docs_src/security/tutorial007_an.py!}
- ```
+Prefer to use the `Annotated` version if possible.
-=== "Python 3.8+ non-Annotated"
+///
- !!! tip
- Prefer to use the `Annotated` version if possible.
+```Python hl_lines="1 11-21"
+{!> ../../../docs_src/security/tutorial007.py!}
+```
- ```Python hl_lines="1 11-21"
- {!> ../../../docs_src/security/tutorial007.py!}
- ```
+////
This would be similar to:
After detecting that the credentials are incorrect, return an `HTTPException` with a status code 401 (the same returned when no credentials are provided) and add the header `WWW-Authenticate` to make the browser show the login prompt again:
-=== "Python 3.9+"
+//// tab | Python 3.9+
+
+```Python hl_lines="26-30"
+{!> ../../../docs_src/security/tutorial007_an_py39.py!}
+```
+
+////
+
+//// tab | Python 3.8+
+
+```Python hl_lines="26-30"
+{!> ../../../docs_src/security/tutorial007_an.py!}
+```
+
+////
- ```Python hl_lines="26-30"
- {!> ../../../docs_src/security/tutorial007_an_py39.py!}
- ```
+//// tab | Python 3.8+ non-Annotated
-=== "Python 3.8+"
+/// tip
- ```Python hl_lines="26-30"
- {!> ../../../docs_src/security/tutorial007_an.py!}
- ```
+Prefer to use the `Annotated` version if possible.
-=== "Python 3.8+ non-Annotated"
+///
- !!! tip
- Prefer to use the `Annotated` version if possible.
+```Python hl_lines="23-27"
+{!> ../../../docs_src/security/tutorial007.py!}
+```
- ```Python hl_lines="23-27"
- {!> ../../../docs_src/security/tutorial007.py!}
- ```
+////
There are some extra features to handle security apart from the ones covered in the [Tutorial - User Guide: Security](../../tutorial/security/index.md){.internal-link target=_blank}.
-!!! tip
- The next sections are **not necessarily "advanced"**.
+/// tip
- And it's possible that for your use case, the solution is in one of them.
+The next sections are **not necessarily "advanced"**.
+
+And it's possible that for your use case, the solution is in one of them.
+
+///
## Read the Tutorial first
In this section you will see how to manage authentication and authorization with the same OAuth2 with scopes in your **FastAPI** application.
-!!! warning
- This is a more or less advanced section. If you are just starting, you can skip it.
+/// warning
- You don't necessarily need OAuth2 scopes, and you can handle authentication and authorization however you want.
+This is a more or less advanced section. If you are just starting, you can skip it.
- But OAuth2 with scopes can be nicely integrated into your API (with OpenAPI) and your API docs.
+You don't necessarily need OAuth2 scopes, and you can handle authentication and authorization however you want.
- Nevertheless, you still enforce those scopes, or any other security/authorization requirement, however you need, in your code.
+But OAuth2 with scopes can be nicely integrated into your API (with OpenAPI) and your API docs.
- In many cases, OAuth2 with scopes can be an overkill.
+Nevertheless, you still enforce those scopes, or any other security/authorization requirement, however you need, in your code.
- But if you know you need it, or you are curious, keep reading.
+In many cases, OAuth2 with scopes can be an overkill.
+
+But if you know you need it, or you are curious, keep reading.
+
+///
## OAuth2 scopes and OpenAPI
* `instagram_basic` is used by Facebook / Instagram.
* `https://www.googleapis.com/auth/drive` is used by Google.
-!!! info
- In OAuth2 a "scope" is just a string that declares a specific permission required.
+/// info
+
+In OAuth2 a "scope" is just a string that declares a specific permission required.
+
+It doesn't matter if it has other characters like `:` or if it is a URL.
- It doesn't matter if it has other characters like `:` or if it is a URL.
+Those details are implementation specific.
- Those details are implementation specific.
+For OAuth2 they are just strings.
- For OAuth2 they are just strings.
+///
## Global view
First, let's quickly see the parts that change from the examples in the main **Tutorial - User Guide** for [OAuth2 with Password (and hashing), Bearer with JWT tokens](../../tutorial/security/oauth2-jwt.md){.internal-link target=_blank}. Now using OAuth2 scopes:
-=== "Python 3.10+"
+//// tab | Python 3.10+
+
+```Python hl_lines="5 9 13 47 65 106 108-116 122-125 129-135 140 156"
+{!> ../../../docs_src/security/tutorial005_an_py310.py!}
+```
+
+////
+
+//// tab | Python 3.9+
+
+```Python hl_lines="2 5 9 13 47 65 106 108-116 122-125 129-135 140 156"
+{!> ../../../docs_src/security/tutorial005_an_py39.py!}
+```
+
+////
+
+//// tab | Python 3.8+
+
+```Python hl_lines="2 5 9 13 48 66 107 109-117 123-126 130-136 141 157"
+{!> ../../../docs_src/security/tutorial005_an.py!}
+```
+
+////
+
+//// tab | Python 3.10+ non-Annotated
+
+/// tip
- ```Python hl_lines="5 9 13 47 65 106 108-116 122-125 129-135 140 156"
- {!> ../../../docs_src/security/tutorial005_an_py310.py!}
- ```
+Prefer to use the `Annotated` version if possible.
-=== "Python 3.9+"
+///
- ```Python hl_lines="2 5 9 13 47 65 106 108-116 122-125 129-135 140 156"
- {!> ../../../docs_src/security/tutorial005_an_py39.py!}
- ```
+```Python hl_lines="4 8 12 46 64 105 107-115 121-124 128-134 139 155"
+{!> ../../../docs_src/security/tutorial005_py310.py!}
+```
-=== "Python 3.8+"
+////
- ```Python hl_lines="2 5 9 13 48 66 107 109-117 123-126 130-136 141 157"
- {!> ../../../docs_src/security/tutorial005_an.py!}
- ```
+//// tab | Python 3.9+ non-Annotated
-=== "Python 3.10+ non-Annotated"
+/// tip
- !!! tip
- Prefer to use the `Annotated` version if possible.
+Prefer to use the `Annotated` version if possible.
- ```Python hl_lines="4 8 12 46 64 105 107-115 121-124 128-134 139 155"
- {!> ../../../docs_src/security/tutorial005_py310.py!}
- ```
+///
-=== "Python 3.9+ non-Annotated"
+```Python hl_lines="2 5 9 13 47 65 106 108-116 122-125 129-135 140 156"
+{!> ../../../docs_src/security/tutorial005_py39.py!}
+```
- !!! tip
- Prefer to use the `Annotated` version if possible.
+////
- ```Python hl_lines="2 5 9 13 47 65 106 108-116 122-125 129-135 140 156"
- {!> ../../../docs_src/security/tutorial005_py39.py!}
- ```
+//// tab | Python 3.8+ non-Annotated
-=== "Python 3.8+ non-Annotated"
+/// tip
- !!! tip
- Prefer to use the `Annotated` version if possible.
+Prefer to use the `Annotated` version if possible.
- ```Python hl_lines="2 5 9 13 47 65 106 108-116 122-125 129-135 140 156"
- {!> ../../../docs_src/security/tutorial005.py!}
- ```
+///
+
+```Python hl_lines="2 5 9 13 47 65 106 108-116 122-125 129-135 140 156"
+{!> ../../../docs_src/security/tutorial005.py!}
+```
+
+////
Now let's review those changes step by step.
The `scopes` parameter receives a `dict` with each scope as a key and the description as the value:
-=== "Python 3.10+"
+//// tab | Python 3.10+
+
+```Python hl_lines="63-66"
+{!> ../../../docs_src/security/tutorial005_an_py310.py!}
+```
+
+////
+
+//// tab | Python 3.9+
+
+```Python hl_lines="63-66"
+{!> ../../../docs_src/security/tutorial005_an_py39.py!}
+```
+
+////
- ```Python hl_lines="63-66"
- {!> ../../../docs_src/security/tutorial005_an_py310.py!}
- ```
+//// tab | Python 3.8+
-=== "Python 3.9+"
+```Python hl_lines="64-67"
+{!> ../../../docs_src/security/tutorial005_an.py!}
+```
- ```Python hl_lines="63-66"
- {!> ../../../docs_src/security/tutorial005_an_py39.py!}
- ```
+////
-=== "Python 3.8+"
+//// tab | Python 3.10+ non-Annotated
- ```Python hl_lines="64-67"
- {!> ../../../docs_src/security/tutorial005_an.py!}
- ```
+/// tip
-=== "Python 3.10+ non-Annotated"
+Prefer to use the `Annotated` version if possible.
- !!! tip
- Prefer to use the `Annotated` version if possible.
+///
- ```Python hl_lines="62-65"
- {!> ../../../docs_src/security/tutorial005_py310.py!}
- ```
+```Python hl_lines="62-65"
+{!> ../../../docs_src/security/tutorial005_py310.py!}
+```
+////
-=== "Python 3.9+ non-Annotated"
+//// tab | Python 3.9+ non-Annotated
- !!! tip
- Prefer to use the `Annotated` version if possible.
+/// tip
- ```Python hl_lines="63-66"
- {!> ../../../docs_src/security/tutorial005_py39.py!}
- ```
+Prefer to use the `Annotated` version if possible.
-=== "Python 3.8+ non-Annotated"
+///
- !!! tip
- Prefer to use the `Annotated` version if possible.
+```Python hl_lines="63-66"
+{!> ../../../docs_src/security/tutorial005_py39.py!}
+```
- ```Python hl_lines="63-66"
- {!> ../../../docs_src/security/tutorial005.py!}
- ```
+////
+
+//// tab | Python 3.8+ non-Annotated
+
+/// tip
+
+Prefer to use the `Annotated` version if possible.
+
+///
+
+```Python hl_lines="63-66"
+{!> ../../../docs_src/security/tutorial005.py!}
+```
+
+////
Because we are now declaring those scopes, they will show up in the API docs when you log-in/authorize.
And we return the scopes as part of the JWT token.
-!!! danger
- For simplicity, here we are just adding the scopes received directly to the token.
+/// danger
+
+For simplicity, here we are just adding the scopes received directly to the token.
- But in your application, for security, you should make sure you only add the scopes that the user is actually able to have, or the ones you have predefined.
+But in your application, for security, you should make sure you only add the scopes that the user is actually able to have, or the ones you have predefined.
-=== "Python 3.10+"
+///
- ```Python hl_lines="156"
- {!> ../../../docs_src/security/tutorial005_an_py310.py!}
- ```
+//// tab | Python 3.10+
-=== "Python 3.9+"
+```Python hl_lines="156"
+{!> ../../../docs_src/security/tutorial005_an_py310.py!}
+```
- ```Python hl_lines="156"
- {!> ../../../docs_src/security/tutorial005_an_py39.py!}
- ```
+////
-=== "Python 3.8+"
+//// tab | Python 3.9+
- ```Python hl_lines="157"
- {!> ../../../docs_src/security/tutorial005_an.py!}
- ```
+```Python hl_lines="156"
+{!> ../../../docs_src/security/tutorial005_an_py39.py!}
+```
-=== "Python 3.10+ non-Annotated"
+////
- !!! tip
- Prefer to use the `Annotated` version if possible.
+//// tab | Python 3.8+
- ```Python hl_lines="155"
- {!> ../../../docs_src/security/tutorial005_py310.py!}
- ```
+```Python hl_lines="157"
+{!> ../../../docs_src/security/tutorial005_an.py!}
+```
-=== "Python 3.9+ non-Annotated"
+////
- !!! tip
- Prefer to use the `Annotated` version if possible.
+//// tab | Python 3.10+ non-Annotated
- ```Python hl_lines="156"
- {!> ../../../docs_src/security/tutorial005_py39.py!}
- ```
+/// tip
-=== "Python 3.8+ non-Annotated"
+Prefer to use the `Annotated` version if possible.
- !!! tip
- Prefer to use the `Annotated` version if possible.
+///
- ```Python hl_lines="156"
- {!> ../../../docs_src/security/tutorial005.py!}
- ```
+```Python hl_lines="155"
+{!> ../../../docs_src/security/tutorial005_py310.py!}
+```
+
+////
+
+//// tab | Python 3.9+ non-Annotated
+
+/// tip
+
+Prefer to use the `Annotated` version if possible.
+
+///
+
+```Python hl_lines="156"
+{!> ../../../docs_src/security/tutorial005_py39.py!}
+```
+
+////
+
+//// tab | Python 3.8+ non-Annotated
+
+/// tip
+
+Prefer to use the `Annotated` version if possible.
+
+///
+
+```Python hl_lines="156"
+{!> ../../../docs_src/security/tutorial005.py!}
+```
+
+////
## Declare scopes in *path operations* and dependencies
In this case, it requires the scope `me` (it could require more than one scope).
-!!! note
- You don't necessarily need to add different scopes in different places.
+/// note
+
+You don't necessarily need to add different scopes in different places.
+
+We are doing it here to demonstrate how **FastAPI** handles scopes declared at different levels.
+
+///
+
+//// tab | Python 3.10+
+
+```Python hl_lines="5 140 171"
+{!> ../../../docs_src/security/tutorial005_an_py310.py!}
+```
+
+////
+
+//// tab | Python 3.9+
+
+```Python hl_lines="5 140 171"
+{!> ../../../docs_src/security/tutorial005_an_py39.py!}
+```
+
+////
+
+//// tab | Python 3.8+
+
+```Python hl_lines="5 141 172"
+{!> ../../../docs_src/security/tutorial005_an.py!}
+```
+
+////
+
+//// tab | Python 3.10+ non-Annotated
+
+/// tip
- We are doing it here to demonstrate how **FastAPI** handles scopes declared at different levels.
+Prefer to use the `Annotated` version if possible.
-=== "Python 3.10+"
+///
- ```Python hl_lines="5 140 171"
- {!> ../../../docs_src/security/tutorial005_an_py310.py!}
- ```
+```Python hl_lines="4 139 168"
+{!> ../../../docs_src/security/tutorial005_py310.py!}
+```
-=== "Python 3.9+"
+////
- ```Python hl_lines="5 140 171"
- {!> ../../../docs_src/security/tutorial005_an_py39.py!}
- ```
+//// tab | Python 3.9+ non-Annotated
-=== "Python 3.8+"
+/// tip
- ```Python hl_lines="5 141 172"
- {!> ../../../docs_src/security/tutorial005_an.py!}
- ```
+Prefer to use the `Annotated` version if possible.
-=== "Python 3.10+ non-Annotated"
+///
- !!! tip
- Prefer to use the `Annotated` version if possible.
+```Python hl_lines="5 140 169"
+{!> ../../../docs_src/security/tutorial005_py39.py!}
+```
- ```Python hl_lines="4 139 168"
- {!> ../../../docs_src/security/tutorial005_py310.py!}
- ```
+////
-=== "Python 3.9+ non-Annotated"
+//// tab | Python 3.8+ non-Annotated
- !!! tip
- Prefer to use the `Annotated` version if possible.
+/// tip
- ```Python hl_lines="5 140 169"
- {!> ../../../docs_src/security/tutorial005_py39.py!}
- ```
+Prefer to use the `Annotated` version if possible.
-=== "Python 3.8+ non-Annotated"
+///
- !!! tip
- Prefer to use the `Annotated` version if possible.
+```Python hl_lines="5 140 169"
+{!> ../../../docs_src/security/tutorial005.py!}
+```
- ```Python hl_lines="5 140 169"
- {!> ../../../docs_src/security/tutorial005.py!}
- ```
+////
-!!! info "Technical Details"
- `Security` is actually a subclass of `Depends`, and it has just one extra parameter that we'll see later.
+/// info | "Technical Details"
- But by using `Security` instead of `Depends`, **FastAPI** will know that it can declare security scopes, use them internally, and document the API with OpenAPI.
+`Security` is actually a subclass of `Depends`, and it has just one extra parameter that we'll see later.
- But when you import `Query`, `Path`, `Depends`, `Security` and others from `fastapi`, those are actually functions that return special classes.
+But by using `Security` instead of `Depends`, **FastAPI** will know that it can declare security scopes, use them internally, and document the API with OpenAPI.
+
+But when you import `Query`, `Path`, `Depends`, `Security` and others from `fastapi`, those are actually functions that return special classes.
+
+///
## Use `SecurityScopes`
This `SecurityScopes` class is similar to `Request` (`Request` was used to get the request object directly).
-=== "Python 3.10+"
+//// tab | Python 3.10+
+
+```Python hl_lines="9 106"
+{!> ../../../docs_src/security/tutorial005_an_py310.py!}
+```
+
+////
+
+//// tab | Python 3.9+
+
+```Python hl_lines="9 106"
+{!> ../../../docs_src/security/tutorial005_an_py39.py!}
+```
+
+////
+
+//// tab | Python 3.8+
+
+```Python hl_lines="9 107"
+{!> ../../../docs_src/security/tutorial005_an.py!}
+```
+
+////
+
+//// tab | Python 3.10+ non-Annotated
+
+/// tip
+
+Prefer to use the `Annotated` version if possible.
+
+///
- ```Python hl_lines="9 106"
- {!> ../../../docs_src/security/tutorial005_an_py310.py!}
- ```
+```Python hl_lines="8 105"
+{!> ../../../docs_src/security/tutorial005_py310.py!}
+```
-=== "Python 3.9+"
+////
- ```Python hl_lines="9 106"
- {!> ../../../docs_src/security/tutorial005_an_py39.py!}
- ```
+//// tab | Python 3.9+ non-Annotated
-=== "Python 3.8+"
+/// tip
- ```Python hl_lines="9 107"
- {!> ../../../docs_src/security/tutorial005_an.py!}
- ```
+Prefer to use the `Annotated` version if possible.
-=== "Python 3.10+ non-Annotated"
+///
- !!! tip
- Prefer to use the `Annotated` version if possible.
+```Python hl_lines="9 106"
+{!> ../../../docs_src/security/tutorial005_py39.py!}
+```
- ```Python hl_lines="8 105"
- {!> ../../../docs_src/security/tutorial005_py310.py!}
- ```
+////
-=== "Python 3.9+ non-Annotated"
+//// tab | Python 3.8+ non-Annotated
- !!! tip
- Prefer to use the `Annotated` version if possible.
+/// tip
- ```Python hl_lines="9 106"
- {!> ../../../docs_src/security/tutorial005_py39.py!}
- ```
+Prefer to use the `Annotated` version if possible.
-=== "Python 3.8+ non-Annotated"
+///
- !!! tip
- Prefer to use the `Annotated` version if possible.
+```Python hl_lines="9 106"
+{!> ../../../docs_src/security/tutorial005.py!}
+```
- ```Python hl_lines="9 106"
- {!> ../../../docs_src/security/tutorial005.py!}
- ```
+////
## Use the `scopes`
In this exception, we include the scopes required (if any) as a string separated by spaces (using `scope_str`). We put that string containing the scopes in the `WWW-Authenticate` header (this is part of the spec).
-=== "Python 3.10+"
+//// tab | Python 3.10+
- ```Python hl_lines="106 108-116"
- {!> ../../../docs_src/security/tutorial005_an_py310.py!}
- ```
+```Python hl_lines="106 108-116"
+{!> ../../../docs_src/security/tutorial005_an_py310.py!}
+```
-=== "Python 3.9+"
+////
- ```Python hl_lines="106 108-116"
- {!> ../../../docs_src/security/tutorial005_an_py39.py!}
- ```
+//// tab | Python 3.9+
-=== "Python 3.8+"
+```Python hl_lines="106 108-116"
+{!> ../../../docs_src/security/tutorial005_an_py39.py!}
+```
- ```Python hl_lines="107 109-117"
- {!> ../../../docs_src/security/tutorial005_an.py!}
- ```
+////
-=== "Python 3.10+ non-Annotated"
+//// tab | Python 3.8+
- !!! tip
- Prefer to use the `Annotated` version if possible.
+```Python hl_lines="107 109-117"
+{!> ../../../docs_src/security/tutorial005_an.py!}
+```
- ```Python hl_lines="105 107-115"
- {!> ../../../docs_src/security/tutorial005_py310.py!}
- ```
+////
-=== "Python 3.9+ non-Annotated"
+//// tab | Python 3.10+ non-Annotated
- !!! tip
- Prefer to use the `Annotated` version if possible.
+/// tip
- ```Python hl_lines="106 108-116"
- {!> ../../../docs_src/security/tutorial005_py39.py!}
- ```
+Prefer to use the `Annotated` version if possible.
-=== "Python 3.8+ non-Annotated"
+///
- !!! tip
- Prefer to use the `Annotated` version if possible.
+```Python hl_lines="105 107-115"
+{!> ../../../docs_src/security/tutorial005_py310.py!}
+```
- ```Python hl_lines="106 108-116"
- {!> ../../../docs_src/security/tutorial005.py!}
- ```
+////
+
+//// tab | Python 3.9+ non-Annotated
+
+/// tip
+
+Prefer to use the `Annotated` version if possible.
+
+///
+
+```Python hl_lines="106 108-116"
+{!> ../../../docs_src/security/tutorial005_py39.py!}
+```
+
+////
+
+//// tab | Python 3.8+ non-Annotated
+
+/// tip
+
+Prefer to use the `Annotated` version if possible.
+
+///
+
+```Python hl_lines="106 108-116"
+{!> ../../../docs_src/security/tutorial005.py!}
+```
+
+////
## Verify the `username` and data shape
We also verify that we have a user with that username, and if not, we raise that same exception we created before.
-=== "Python 3.10+"
+//// tab | Python 3.10+
+
+```Python hl_lines="47 117-128"
+{!> ../../../docs_src/security/tutorial005_an_py310.py!}
+```
- ```Python hl_lines="47 117-128"
- {!> ../../../docs_src/security/tutorial005_an_py310.py!}
- ```
+////
-=== "Python 3.9+"
+//// tab | Python 3.9+
- ```Python hl_lines="47 117-128"
- {!> ../../../docs_src/security/tutorial005_an_py39.py!}
- ```
+```Python hl_lines="47 117-128"
+{!> ../../../docs_src/security/tutorial005_an_py39.py!}
+```
-=== "Python 3.8+"
+////
- ```Python hl_lines="48 118-129"
- {!> ../../../docs_src/security/tutorial005_an.py!}
- ```
+//// tab | Python 3.8+
-=== "Python 3.10+ non-Annotated"
+```Python hl_lines="48 118-129"
+{!> ../../../docs_src/security/tutorial005_an.py!}
+```
- !!! tip
- Prefer to use the `Annotated` version if possible.
+////
- ```Python hl_lines="46 116-127"
- {!> ../../../docs_src/security/tutorial005_py310.py!}
- ```
+//// tab | Python 3.10+ non-Annotated
-=== "Python 3.9+ non-Annotated"
+/// tip
- !!! tip
- Prefer to use the `Annotated` version if possible.
+Prefer to use the `Annotated` version if possible.
- ```Python hl_lines="47 117-128"
- {!> ../../../docs_src/security/tutorial005_py39.py!}
- ```
+///
-=== "Python 3.8+ non-Annotated"
+```Python hl_lines="46 116-127"
+{!> ../../../docs_src/security/tutorial005_py310.py!}
+```
- !!! tip
- Prefer to use the `Annotated` version if possible.
+////
- ```Python hl_lines="47 117-128"
- {!> ../../../docs_src/security/tutorial005.py!}
- ```
+//// tab | Python 3.9+ non-Annotated
+
+/// tip
+
+Prefer to use the `Annotated` version if possible.
+
+///
+
+```Python hl_lines="47 117-128"
+{!> ../../../docs_src/security/tutorial005_py39.py!}
+```
+
+////
+
+//// tab | Python 3.8+ non-Annotated
+
+/// tip
+
+Prefer to use the `Annotated` version if possible.
+
+///
+
+```Python hl_lines="47 117-128"
+{!> ../../../docs_src/security/tutorial005.py!}
+```
+
+////
## Verify the `scopes`
For this, we use `security_scopes.scopes`, that contains a `list` with all these scopes as `str`.
-=== "Python 3.10+"
+//// tab | Python 3.10+
+
+```Python hl_lines="129-135"
+{!> ../../../docs_src/security/tutorial005_an_py310.py!}
+```
+
+////
+
+//// tab | Python 3.9+
- ```Python hl_lines="129-135"
- {!> ../../../docs_src/security/tutorial005_an_py310.py!}
- ```
+```Python hl_lines="129-135"
+{!> ../../../docs_src/security/tutorial005_an_py39.py!}
+```
-=== "Python 3.9+"
+////
- ```Python hl_lines="129-135"
- {!> ../../../docs_src/security/tutorial005_an_py39.py!}
- ```
+//// tab | Python 3.8+
-=== "Python 3.8+"
+```Python hl_lines="130-136"
+{!> ../../../docs_src/security/tutorial005_an.py!}
+```
- ```Python hl_lines="130-136"
- {!> ../../../docs_src/security/tutorial005_an.py!}
- ```
+////
-=== "Python 3.10+ non-Annotated"
+//// tab | Python 3.10+ non-Annotated
- !!! tip
- Prefer to use the `Annotated` version if possible.
+/// tip
- ```Python hl_lines="128-134"
- {!> ../../../docs_src/security/tutorial005_py310.py!}
- ```
+Prefer to use the `Annotated` version if possible.
-=== "Python 3.9+ non-Annotated"
+///
- !!! tip
- Prefer to use the `Annotated` version if possible.
+```Python hl_lines="128-134"
+{!> ../../../docs_src/security/tutorial005_py310.py!}
+```
- ```Python hl_lines="129-135"
- {!> ../../../docs_src/security/tutorial005_py39.py!}
- ```
+////
-=== "Python 3.8+ non-Annotated"
+//// tab | Python 3.9+ non-Annotated
- !!! tip
- Prefer to use the `Annotated` version if possible.
+/// tip
- ```Python hl_lines="129-135"
- {!> ../../../docs_src/security/tutorial005.py!}
- ```
+Prefer to use the `Annotated` version if possible.
+
+///
+
+```Python hl_lines="129-135"
+{!> ../../../docs_src/security/tutorial005_py39.py!}
+```
+
+////
+
+//// tab | Python 3.8+ non-Annotated
+
+/// tip
+
+Prefer to use the `Annotated` version if possible.
+
+///
+
+```Python hl_lines="129-135"
+{!> ../../../docs_src/security/tutorial005.py!}
+```
+
+////
## Dependency tree and scopes
* `security_scopes.scopes` will contain `["me"]` for the *path operation* `read_users_me`, because it is declared in the dependency `get_current_active_user`.
* `security_scopes.scopes` will contain `[]` (nothing) for the *path operation* `read_system_status`, because it didn't declare any `Security` with `scopes`, and its dependency, `get_current_user`, doesn't declare any `scope` either.
-!!! tip
- The important and "magic" thing here is that `get_current_user` will have a different list of `scopes` to check for each *path operation*.
+/// tip
+
+The important and "magic" thing here is that `get_current_user` will have a different list of `scopes` to check for each *path operation*.
- All depending on the `scopes` declared in each *path operation* and each dependency in the dependency tree for that specific *path operation*.
+All depending on the `scopes` declared in each *path operation* and each dependency in the dependency tree for that specific *path operation*.
+
+///
## More details about `SecurityScopes`
The most secure is the code flow, but is more complex to implement as it requires more steps. As it is more complex, many providers end up suggesting the implicit flow.
-!!! note
- It's common that each authentication provider names their flows in a different way, to make it part of their brand.
+/// note
+
+It's common that each authentication provider names their flows in a different way, to make it part of their brand.
+
+But in the end, they are implementing the same OAuth2 standard.
- But in the end, they are implementing the same OAuth2 standard.
+///
**FastAPI** includes utilities for all these OAuth2 authentication flows in `fastapi.security.oauth2`.
## Environment Variables
-!!! tip
- If you already know what "environment variables" are and how to use them, feel free to skip to the next section below.
+/// tip
+
+If you already know what "environment variables" are and how to use them, feel free to skip to the next section below.
+
+///
An <a href="https://en.wikipedia.org/wiki/Environment_variable" class="external-link" target="_blank">environment variable</a> (also known as "env var") is a variable that lives outside of the Python code, in the operating system, and could be read by your Python code (or by other programs as well).
You can create and use environment variables in the shell, without needing Python:
-=== "Linux, macOS, Windows Bash"
+//// tab | Linux, macOS, Windows Bash
- <div class="termy">
+<div class="termy">
- ```console
- // You could create an env var MY_NAME with
- $ export MY_NAME="Wade Wilson"
+```console
+// You could create an env var MY_NAME with
+$ export MY_NAME="Wade Wilson"
- // Then you could use it with other programs, like
- $ echo "Hello $MY_NAME"
+// Then you could use it with other programs, like
+$ echo "Hello $MY_NAME"
+
+Hello Wade Wilson
+```
+
+</div>
- Hello Wade Wilson
- ```
+////
- </div>
+//// tab | Windows PowerShell
-=== "Windows PowerShell"
+<div class="termy">
- <div class="termy">
+```console
+// Create an env var MY_NAME
+$ $Env:MY_NAME = "Wade Wilson"
- ```console
- // Create an env var MY_NAME
- $ $Env:MY_NAME = "Wade Wilson"
+// Use it with other programs, like
+$ echo "Hello $Env:MY_NAME"
- // Use it with other programs, like
- $ echo "Hello $Env:MY_NAME"
+Hello Wade Wilson
+```
- Hello Wade Wilson
- ```
+</div>
- </div>
+////
### Read env vars in Python
print(f"Hello {name} from Python")
```
-!!! tip
- The second argument to <a href="https://docs.python.org/3.8/library/os.html#os.getenv" class="external-link" target="_blank">`os.getenv()`</a> is the default value to return.
+/// tip
+
+The second argument to <a href="https://docs.python.org/3.8/library/os.html#os.getenv" class="external-link" target="_blank">`os.getenv()`</a> is the default value to return.
- If not provided, it's `None` by default, here we provide `"World"` as the default value to use.
+If not provided, it's `None` by default, here we provide `"World"` as the default value to use.
+
+///
Then you could call that Python program:
</div>
-!!! tip
- You can read more about it at <a href="https://12factor.net/config" class="external-link" target="_blank">The Twelve-Factor App: Config</a>.
+/// tip
+
+You can read more about it at <a href="https://12factor.net/config" class="external-link" target="_blank">The Twelve-Factor App: Config</a>.
+
+///
### Types and validation
</div>
-!!! info
- In Pydantic v1 it came included with the main package. Now it is distributed as this independent package so that you can choose to install it or not if you don't need that functionality.
+/// info
+
+In Pydantic v1 it came included with the main package. Now it is distributed as this independent package so that you can choose to install it or not if you don't need that functionality.
+
+///
### Create the `Settings` object
You can use all the same validation features and tools you use for Pydantic models, like different data types and additional validations with `Field()`.
-=== "Pydantic v2"
+//// tab | Pydantic v2
+
+```Python hl_lines="2 5-8 11"
+{!> ../../../docs_src/settings/tutorial001.py!}
+```
+
+////
+
+//// tab | Pydantic v1
- ```Python hl_lines="2 5-8 11"
- {!> ../../../docs_src/settings/tutorial001.py!}
- ```
+/// info
+
+In Pydantic v1 you would import `BaseSettings` directly from `pydantic` instead of from `pydantic_settings`.
+
+///
+
+```Python hl_lines="2 5-8 11"
+{!> ../../../docs_src/settings/tutorial001_pv1.py!}
+```
-=== "Pydantic v1"
+////
- !!! info
- In Pydantic v1 you would import `BaseSettings` directly from `pydantic` instead of from `pydantic_settings`.
+/// tip
- ```Python hl_lines="2 5-8 11"
- {!> ../../../docs_src/settings/tutorial001_pv1.py!}
- ```
+If you want something quick to copy and paste, don't use this example, use the last one below.
-!!! tip
- If you want something quick to copy and paste, don't use this example, use the last one below.
+///
Then, when you create an instance of that `Settings` class (in this case, in the `settings` object), Pydantic will read the environment variables in a case-insensitive way, so, an upper-case variable `APP_NAME` will still be read for the attribute `app_name`.
</div>
-!!! tip
- To set multiple env vars for a single command just separate them with a space, and put them all before the command.
+/// tip
+
+To set multiple env vars for a single command just separate them with a space, and put them all before the command.
+
+///
And then the `admin_email` setting would be set to `"deadpool@example.com"`.
{!../../../docs_src/settings/app01/main.py!}
```
-!!! tip
- You would also need a file `__init__.py` as you saw in [Bigger Applications - Multiple Files](../tutorial/bigger-applications.md){.internal-link target=_blank}.
+/// tip
+
+You would also need a file `__init__.py` as you saw in [Bigger Applications - Multiple Files](../tutorial/bigger-applications.md){.internal-link target=_blank}.
+
+///
## Settings in a dependency
Now we create a dependency that returns a new `config.Settings()`.
-=== "Python 3.9+"
+//// tab | Python 3.9+
- ```Python hl_lines="6 12-13"
- {!> ../../../docs_src/settings/app02_an_py39/main.py!}
- ```
+```Python hl_lines="6 12-13"
+{!> ../../../docs_src/settings/app02_an_py39/main.py!}
+```
-=== "Python 3.8+"
+////
- ```Python hl_lines="6 12-13"
- {!> ../../../docs_src/settings/app02_an/main.py!}
- ```
+//// tab | Python 3.8+
-=== "Python 3.8+ non-Annotated"
+```Python hl_lines="6 12-13"
+{!> ../../../docs_src/settings/app02_an/main.py!}
+```
+
+////
- !!! tip
- Prefer to use the `Annotated` version if possible.
+//// tab | Python 3.8+ non-Annotated
- ```Python hl_lines="5 11-12"
- {!> ../../../docs_src/settings/app02/main.py!}
- ```
+/// tip
-!!! tip
- We'll discuss the `@lru_cache` in a bit.
+Prefer to use the `Annotated` version if possible.
- For now you can assume `get_settings()` is a normal function.
+///
+
+```Python hl_lines="5 11-12"
+{!> ../../../docs_src/settings/app02/main.py!}
+```
+
+////
+
+/// tip
+
+We'll discuss the `@lru_cache` in a bit.
+
+For now you can assume `get_settings()` is a normal function.
+
+///
And then we can require it from the *path operation function* as a dependency and use it anywhere we need it.
-=== "Python 3.9+"
+//// tab | Python 3.9+
+
+```Python hl_lines="17 19-21"
+{!> ../../../docs_src/settings/app02_an_py39/main.py!}
+```
+
+////
+
+//// tab | Python 3.8+
- ```Python hl_lines="17 19-21"
- {!> ../../../docs_src/settings/app02_an_py39/main.py!}
- ```
+```Python hl_lines="17 19-21"
+{!> ../../../docs_src/settings/app02_an/main.py!}
+```
+
+////
-=== "Python 3.8+"
+//// tab | Python 3.8+ non-Annotated
- ```Python hl_lines="17 19-21"
- {!> ../../../docs_src/settings/app02_an/main.py!}
- ```
+/// tip
-=== "Python 3.8+ non-Annotated"
+Prefer to use the `Annotated` version if possible.
- !!! tip
- Prefer to use the `Annotated` version if possible.
+///
- ```Python hl_lines="16 18-20"
- {!> ../../../docs_src/settings/app02/main.py!}
- ```
+```Python hl_lines="16 18-20"
+{!> ../../../docs_src/settings/app02/main.py!}
+```
+
+////
### Settings and testing
This practice is common enough that it has a name, these environment variables are commonly placed in a file `.env`, and the file is called a "dotenv".
-!!! tip
- A file starting with a dot (`.`) is a hidden file in Unix-like systems, like Linux and macOS.
+/// tip
+
+A file starting with a dot (`.`) is a hidden file in Unix-like systems, like Linux and macOS.
- But a dotenv file doesn't really have to have that exact filename.
+But a dotenv file doesn't really have to have that exact filename.
+
+///
Pydantic has support for reading from these types of files using an external library. You can read more at <a href="https://docs.pydantic.dev/latest/concepts/pydantic_settings/#dotenv-env-support" class="external-link" target="_blank">Pydantic Settings: Dotenv (.env) support</a>.
-!!! tip
- For this to work, you need to `pip install python-dotenv`.
+/// tip
+
+For this to work, you need to `pip install python-dotenv`.
+
+///
### The `.env` file
And then update your `config.py` with:
-=== "Pydantic v2"
+//// tab | Pydantic v2
- ```Python hl_lines="9"
- {!> ../../../docs_src/settings/app03_an/config.py!}
- ```
+```Python hl_lines="9"
+{!> ../../../docs_src/settings/app03_an/config.py!}
+```
- !!! tip
- The `model_config` attribute is used just for Pydantic configuration. You can read more at <a href="https://docs.pydantic.dev/latest/usage/model_config/" class="external-link" target="_blank">Pydantic Model Config</a>.
+/// tip
-=== "Pydantic v1"
+The `model_config` attribute is used just for Pydantic configuration. You can read more at <a href="https://docs.pydantic.dev/latest/usage/model_config/" class="external-link" target="_blank">Pydantic Model Config</a>.
- ```Python hl_lines="9-10"
- {!> ../../../docs_src/settings/app03_an/config_pv1.py!}
- ```
+///
- !!! tip
- The `Config` class is used just for Pydantic configuration. You can read more at <a href="https://docs.pydantic.dev/1.10/usage/model_config/" class="external-link" target="_blank">Pydantic Model Config</a>.
+////
-!!! info
- In Pydantic version 1 the configuration was done in an internal class `Config`, in Pydantic version 2 it's done in an attribute `model_config`. This attribute takes a `dict`, and to get autocompletion and inline errors you can import and use `SettingsConfigDict` to define that `dict`.
+//// tab | Pydantic v1
+
+```Python hl_lines="9-10"
+{!> ../../../docs_src/settings/app03_an/config_pv1.py!}
+```
+
+/// tip
+
+The `Config` class is used just for Pydantic configuration. You can read more at <a href="https://docs.pydantic.dev/1.10/usage/model_config/" class="external-link" target="_blank">Pydantic Model Config</a>.
+
+///
+
+////
+
+/// info
+
+In Pydantic version 1 the configuration was done in an internal class `Config`, in Pydantic version 2 it's done in an attribute `model_config`. This attribute takes a `dict`, and to get autocompletion and inline errors you can import and use `SettingsConfigDict` to define that `dict`.
+
+///
Here we define the config `env_file` inside of your Pydantic `Settings` class, and set the value to the filename with the dotenv file we want to use.
But as we are using the `@lru_cache` decorator on top, the `Settings` object will be created only once, the first time it's called. ✔️
-=== "Python 3.9+"
+//// tab | Python 3.9+
- ```Python hl_lines="1 11"
- {!> ../../../docs_src/settings/app03_an_py39/main.py!}
- ```
+```Python hl_lines="1 11"
+{!> ../../../docs_src/settings/app03_an_py39/main.py!}
+```
+
+////
+
+//// tab | Python 3.8+
+
+```Python hl_lines="1 11"
+{!> ../../../docs_src/settings/app03_an/main.py!}
+```
+
+////
-=== "Python 3.8+"
+//// tab | Python 3.8+ non-Annotated
- ```Python hl_lines="1 11"
- {!> ../../../docs_src/settings/app03_an/main.py!}
- ```
+/// tip
-=== "Python 3.8+ non-Annotated"
+Prefer to use the `Annotated` version if possible.
- !!! tip
- Prefer to use the `Annotated` version if possible.
+///
+
+```Python hl_lines="1 10"
+{!> ../../../docs_src/settings/app03/main.py!}
+```
- ```Python hl_lines="1 10"
- {!> ../../../docs_src/settings/app03/main.py!}
- ```
+////
Then for any subsequent calls of `get_settings()` in the dependencies for the next requests, instead of executing the internal code of `get_settings()` and creating a new `Settings` object, it will return the same object that was returned on the first call, again and again.
{!../../../docs_src/templates/tutorial001.py!}
```
-!!! note
- Before FastAPI 0.108.0, Starlette 0.29.0, the `name` was the first parameter.
+/// note
- Also, before that, in previous versions, the `request` object was passed as part of the key-value pairs in the context for Jinja2.
+Before FastAPI 0.108.0, Starlette 0.29.0, the `name` was the first parameter.
-!!! tip
- By declaring `response_class=HTMLResponse` the docs UI will be able to know that the response will be HTML.
+Also, before that, in previous versions, the `request` object was passed as part of the key-value pairs in the context for Jinja2.
-!!! note "Technical Details"
- You could also use `from starlette.templating import Jinja2Templates`.
+///
- **FastAPI** provides the same `starlette.templating` as `fastapi.templating` just as a convenience for you, the developer. But most of the available responses come directly from Starlette. The same with `Request` and `StaticFiles`.
+/// tip
+
+By declaring `response_class=HTMLResponse` the docs UI will be able to know that the response will be HTML.
+
+///
+
+/// note | "Technical Details"
+
+You could also use `from starlette.templating import Jinja2Templates`.
+
+**FastAPI** provides the same `starlette.templating` as `fastapi.templating` just as a convenience for you, the developer. But most of the available responses come directly from Starlette. The same with `Request` and `StaticFiles`.
+
+///
## Writing templates
# Testing a Database
-!!! info
- These docs are about to be updated. 🎉
+/// info
- The current version assumes Pydantic v1, and SQLAlchemy versions less than 2.0.
+These docs are about to be updated. 🎉
- The new docs will include Pydantic v2 and will use <a href="https://sqlmodel.tiangolo.com/" class="external-link" target="_blank">SQLModel</a> (which is also based on SQLAlchemy) once it is updated to use Pydantic v2 as well.
+The current version assumes Pydantic v1, and SQLAlchemy versions less than 2.0.
+
+The new docs will include Pydantic v2 and will use <a href="https://sqlmodel.tiangolo.com/" class="external-link" target="_blank">SQLModel</a> (which is also based on SQLAlchemy) once it is updated to use Pydantic v2 as well.
+
+///
You can use the same dependency overrides from [Testing Dependencies with Overrides](testing-dependencies.md){.internal-link target=_blank} to alter a database for testing.
{!../../../docs_src/sql_databases/sql_app/tests/test_sql_app.py!}
```
-!!! tip
- You could reduce duplication in that code by putting it in a function and using it from both `database.py` and `tests/test_sql_app.py`.
+/// tip
+
+You could reduce duplication in that code by putting it in a function and using it from both `database.py` and `tests/test_sql_app.py`.
- For simplicity and to focus on the specific testing code, we are just copying it.
+For simplicity and to focus on the specific testing code, we are just copying it.
+
+///
## Create the database
{!../../../docs_src/sql_databases/sql_app/tests/test_sql_app.py!}
```
-!!! tip
- The code for `override_get_db()` is almost exactly the same as for `get_db()`, but in `override_get_db()` we use the `TestingSessionLocal` for the testing database instead.
+/// tip
+
+The code for `override_get_db()` is almost exactly the same as for `get_db()`, but in `override_get_db()` we use the `TestingSessionLocal` for the testing database instead.
+
+///
## Test the app
And then **FastAPI** will call that override instead of the original dependency.
-=== "Python 3.10+"
+//// tab | Python 3.10+
- ```Python hl_lines="26-27 30"
- {!> ../../../docs_src/dependency_testing/tutorial001_an_py310.py!}
- ```
+```Python hl_lines="26-27 30"
+{!> ../../../docs_src/dependency_testing/tutorial001_an_py310.py!}
+```
+
+////
+
+//// tab | Python 3.9+
+
+```Python hl_lines="28-29 32"
+{!> ../../../docs_src/dependency_testing/tutorial001_an_py39.py!}
+```
+
+////
+
+//// tab | Python 3.8+
+
+```Python hl_lines="29-30 33"
+{!> ../../../docs_src/dependency_testing/tutorial001_an.py!}
+```
-=== "Python 3.9+"
+////
- ```Python hl_lines="28-29 32"
- {!> ../../../docs_src/dependency_testing/tutorial001_an_py39.py!}
- ```
+//// tab | Python 3.10+ non-Annotated
-=== "Python 3.8+"
+/// tip
- ```Python hl_lines="29-30 33"
- {!> ../../../docs_src/dependency_testing/tutorial001_an.py!}
- ```
+Prefer to use the `Annotated` version if possible.
-=== "Python 3.10+ non-Annotated"
+///
- !!! tip
- Prefer to use the `Annotated` version if possible.
+```Python hl_lines="24-25 28"
+{!> ../../../docs_src/dependency_testing/tutorial001_py310.py!}
+```
+
+////
+
+//// tab | Python 3.8+ non-Annotated
- ```Python hl_lines="24-25 28"
- {!> ../../../docs_src/dependency_testing/tutorial001_py310.py!}
- ```
+/// tip
-=== "Python 3.8+ non-Annotated"
+Prefer to use the `Annotated` version if possible.
- !!! tip
- Prefer to use the `Annotated` version if possible.
+///
+
+```Python hl_lines="28-29 32"
+{!> ../../../docs_src/dependency_testing/tutorial001.py!}
+```
- ```Python hl_lines="28-29 32"
- {!> ../../../docs_src/dependency_testing/tutorial001.py!}
- ```
+////
-!!! tip
- You can set a dependency override for a dependency used anywhere in your **FastAPI** application.
+/// tip
- The original dependency could be used in a *path operation function*, a *path operation decorator* (when you don't use the return value), a `.include_router()` call, etc.
+You can set a dependency override for a dependency used anywhere in your **FastAPI** application.
- FastAPI will still be able to override it.
+The original dependency could be used in a *path operation function*, a *path operation decorator* (when you don't use the return value), a `.include_router()` call, etc.
+
+FastAPI will still be able to override it.
+
+///
Then you can reset your overrides (remove them) by setting `app.dependency_overrides` to be an empty `dict`:
app.dependency_overrides = {}
```
-!!! tip
- If you want to override a dependency only during some tests, you can set the override at the beginning of the test (inside the test function) and reset it at the end (at the end of the test function).
+/// tip
+
+If you want to override a dependency only during some tests, you can set the override at the beginning of the test (inside the test function) and reset it at the end (at the end of the test function).
+
+///
{!../../../docs_src/app_testing/tutorial002.py!}
```
-!!! note
- For more details, check Starlette's documentation for <a href="https://www.starlette.io/testclient/#testing-websocket-sessions" class="external-link" target="_blank">testing WebSockets</a>.
+/// note
+
+For more details, check Starlette's documentation for <a href="https://www.starlette.io/testclient/#testing-websocket-sessions" class="external-link" target="_blank">testing WebSockets</a>.
+
+///
By declaring a *path operation function* parameter with the type being the `Request` **FastAPI** will know to pass the `Request` in that parameter.
-!!! tip
- Note that in this case, we are declaring a path parameter beside the request parameter.
+/// tip
- So, the path parameter will be extracted, validated, converted to the specified type and annotated with OpenAPI.
+Note that in this case, we are declaring a path parameter beside the request parameter.
- The same way, you can declare any other parameter as normally, and additionally, get the `Request` too.
+So, the path parameter will be extracted, validated, converted to the specified type and annotated with OpenAPI.
+
+The same way, you can declare any other parameter as normally, and additionally, get the `Request` too.
+
+///
## `Request` documentation
You can read more details about the <a href="https://www.starlette.io/requests/" class="external-link" target="_blank">`Request` object in the official Starlette documentation site</a>.
-!!! note "Technical Details"
- You could also use `from starlette.requests import Request`.
+/// note | "Technical Details"
+
+You could also use `from starlette.requests import Request`.
+
+**FastAPI** provides it directly just as a convenience for you, the developer. But it comes directly from Starlette.
- **FastAPI** provides it directly just as a convenience for you, the developer. But it comes directly from Starlette.
+///
{!../../../docs_src/websockets/tutorial001.py!}
```
-!!! note "Technical Details"
- You could also use `from starlette.websockets import WebSocket`.
+/// note | "Technical Details"
- **FastAPI** provides the same `WebSocket` directly just as a convenience for you, the developer. But it comes directly from Starlette.
+You could also use `from starlette.websockets import WebSocket`.
+
+**FastAPI** provides the same `WebSocket` directly just as a convenience for you, the developer. But it comes directly from Starlette.
+
+///
## Await for messages and send messages
They work the same way as for other FastAPI endpoints/*path operations*:
-=== "Python 3.10+"
+//// tab | Python 3.10+
+
+```Python hl_lines="68-69 82"
+{!> ../../../docs_src/websockets/tutorial002_an_py310.py!}
+```
+
+////
+
+//// tab | Python 3.9+
+
+```Python hl_lines="68-69 82"
+{!> ../../../docs_src/websockets/tutorial002_an_py39.py!}
+```
+
+////
+
+//// tab | Python 3.8+
+
+```Python hl_lines="69-70 83"
+{!> ../../../docs_src/websockets/tutorial002_an.py!}
+```
+
+////
- ```Python hl_lines="68-69 82"
- {!> ../../../docs_src/websockets/tutorial002_an_py310.py!}
- ```
+//// tab | Python 3.10+ non-Annotated
-=== "Python 3.9+"
+/// tip
- ```Python hl_lines="68-69 82"
- {!> ../../../docs_src/websockets/tutorial002_an_py39.py!}
- ```
+Prefer to use the `Annotated` version if possible.
-=== "Python 3.8+"
+///
- ```Python hl_lines="69-70 83"
- {!> ../../../docs_src/websockets/tutorial002_an.py!}
- ```
+```Python hl_lines="66-67 79"
+{!> ../../../docs_src/websockets/tutorial002_py310.py!}
+```
+
+////
-=== "Python 3.10+ non-Annotated"
+//// tab | Python 3.8+ non-Annotated
- !!! tip
- Prefer to use the `Annotated` version if possible.
+/// tip
- ```Python hl_lines="66-67 79"
- {!> ../../../docs_src/websockets/tutorial002_py310.py!}
- ```
+Prefer to use the `Annotated` version if possible.
-=== "Python 3.8+ non-Annotated"
+///
+
+```Python hl_lines="68-69 81"
+{!> ../../../docs_src/websockets/tutorial002.py!}
+```
- !!! tip
- Prefer to use the `Annotated` version if possible.
+////
- ```Python hl_lines="68-69 81"
- {!> ../../../docs_src/websockets/tutorial002.py!}
- ```
+/// info
-!!! info
- As this is a WebSocket it doesn't really make sense to raise an `HTTPException`, instead we raise a `WebSocketException`.
+As this is a WebSocket it doesn't really make sense to raise an `HTTPException`, instead we raise a `WebSocketException`.
- You can use a closing code from the <a href="https://tools.ietf.org/html/rfc6455#section-7.4.1" class="external-link" target="_blank">valid codes defined in the specification</a>.
+You can use a closing code from the <a href="https://tools.ietf.org/html/rfc6455#section-7.4.1" class="external-link" target="_blank">valid codes defined in the specification</a>.
+
+///
### Try the WebSockets with dependencies
* The "Item ID", used in the path.
* The "Token" used as a query parameter.
-!!! tip
- Notice that the query `token` will be handled by a dependency.
+/// tip
+
+Notice that the query `token` will be handled by a dependency.
+
+///
With that you can connect the WebSocket and then send and receive messages:
When a WebSocket connection is closed, the `await websocket.receive_text()` will raise a `WebSocketDisconnect` exception, which you can then catch and handle like in this example.
-=== "Python 3.9+"
+//// tab | Python 3.9+
- ```Python hl_lines="79-81"
- {!> ../../../docs_src/websockets/tutorial003_py39.py!}
- ```
+```Python hl_lines="79-81"
+{!> ../../../docs_src/websockets/tutorial003_py39.py!}
+```
+
+////
+
+//// tab | Python 3.8+
-=== "Python 3.8+"
+```Python hl_lines="81-83"
+{!> ../../../docs_src/websockets/tutorial003.py!}
+```
- ```Python hl_lines="81-83"
- {!> ../../../docs_src/websockets/tutorial003.py!}
- ```
+////
To try it out:
Client #1596980209979 left the chat
```
-!!! tip
- The app above is a minimal and simple example to demonstrate how to handle and broadcast messages to several WebSocket connections.
+/// tip
+
+The app above is a minimal and simple example to demonstrate how to handle and broadcast messages to several WebSocket connections.
+
+But keep in mind that, as everything is handled in memory, in a single list, it will only work while the process is running, and will only work with a single process.
- But keep in mind that, as everything is handled in memory, in a single list, it will only work while the process is running, and will only work with a single process.
+If you need something easy to integrate with FastAPI but that is more robust, supported by Redis, PostgreSQL or others, check <a href="https://github.com/encode/broadcaster" class="external-link" target="_blank">encode/broadcaster</a>.
- If you need something easy to integrate with FastAPI but that is more robust, supported by Redis, PostgreSQL or others, check <a href="https://github.com/encode/broadcaster" class="external-link" target="_blank">encode/broadcaster</a>.
+///
## More info
It was one of the first examples of **automatic API documentation**, and this was specifically one of the first ideas that inspired "the search for" **FastAPI**.
-!!! note
- Django REST Framework was created by Tom Christie. The same creator of Starlette and Uvicorn, on which **FastAPI** is based.
+/// note
+Django REST Framework was created by Tom Christie. The same creator of Starlette and Uvicorn, on which **FastAPI** is based.
-!!! check "Inspired **FastAPI** to"
- Have an automatic API documentation web user interface.
+///
+
+/// check | "Inspired **FastAPI** to"
+
+Have an automatic API documentation web user interface.
+
+///
### <a href="https://flask.palletsprojects.com" class="external-link" target="_blank">Flask</a>
Given the simplicity of Flask, it seemed like a good match for building APIs. The next thing to find was a "Django REST Framework" for Flask.
-!!! check "Inspired **FastAPI** to"
- Be a micro-framework. Making it easy to mix and match the tools and parts needed.
+/// check | "Inspired **FastAPI** to"
- Have a simple and easy to use routing system.
+Be a micro-framework. Making it easy to mix and match the tools and parts needed.
+Have a simple and easy to use routing system.
+
+///
### <a href="https://requests.readthedocs.io" class="external-link" target="_blank">Requests</a>
See the similarities in `requests.get(...)` and `@app.get(...)`.
-!!! check "Inspired **FastAPI** to"
- * Have a simple and intuitive API.
- * Use HTTP method names (operations) directly, in a straightforward and intuitive way.
- * Have sensible defaults, but powerful customizations.
+/// check | "Inspired **FastAPI** to"
+
+* Have a simple and intuitive API.
+* Use HTTP method names (operations) directly, in a straightforward and intuitive way.
+* Have sensible defaults, but powerful customizations.
+///
### <a href="https://swagger.io/" class="external-link" target="_blank">Swagger</a> / <a href="https://github.com/OAI/OpenAPI-Specification/" class="external-link" target="_blank">OpenAPI</a>
That's why when talking about version 2.0 it's common to say "Swagger", and for version 3+ "OpenAPI".
-!!! check "Inspired **FastAPI** to"
- Adopt and use an open standard for API specifications, instead of a custom schema.
+/// check | "Inspired **FastAPI** to"
+
+Adopt and use an open standard for API specifications, instead of a custom schema.
- And integrate standards-based user interface tools:
+And integrate standards-based user interface tools:
- * <a href="https://github.com/swagger-api/swagger-ui" class="external-link" target="_blank">Swagger UI</a>
- * <a href="https://github.com/Rebilly/ReDoc" class="external-link" target="_blank">ReDoc</a>
+* <a href="https://github.com/swagger-api/swagger-ui" class="external-link" target="_blank">Swagger UI</a>
+* <a href="https://github.com/Rebilly/ReDoc" class="external-link" target="_blank">ReDoc</a>
- These two were chosen for being fairly popular and stable, but doing a quick search, you could find dozens of alternative user interfaces for OpenAPI (that you can use with **FastAPI**).
+These two were chosen for being fairly popular and stable, but doing a quick search, you could find dozens of alternative user interfaces for OpenAPI (that you can use with **FastAPI**).
+
+///
### Flask REST frameworks
But it was created before there existed Python type hints. So, to define every <abbr title="the definition of how data should be formed">schema</abbr> you need to use specific utils and classes provided by Marshmallow.
-!!! check "Inspired **FastAPI** to"
- Use code to define "schemas" that provide data types and validation, automatically.
+/// check | "Inspired **FastAPI** to"
+
+Use code to define "schemas" that provide data types and validation, automatically.
+
+///
### <a href="https://webargs.readthedocs.io/en/latest/" class="external-link" target="_blank">Webargs</a>
It's a great tool and I have used it a lot too, before having **FastAPI**.
-!!! info
- Webargs was created by the same Marshmallow developers.
+/// info
+
+Webargs was created by the same Marshmallow developers.
+
+///
+
+/// check | "Inspired **FastAPI** to"
-!!! check "Inspired **FastAPI** to"
- Have automatic validation of incoming request data.
+Have automatic validation of incoming request data.
+
+///
### <a href="https://apispec.readthedocs.io/en/stable/" class="external-link" target="_blank">APISpec</a>
The editor can't help much with that. And if we modify parameters or Marshmallow schemas and forget to also modify that YAML docstring, the generated schema would be obsolete.
-!!! info
- APISpec was created by the same Marshmallow developers.
+/// info
+
+APISpec was created by the same Marshmallow developers.
+
+///
+/// check | "Inspired **FastAPI** to"
-!!! check "Inspired **FastAPI** to"
- Support the open standard for APIs, OpenAPI.
+Support the open standard for APIs, OpenAPI.
+
+///
### <a href="https://flask-apispec.readthedocs.io/en/latest/" class="external-link" target="_blank">Flask-apispec</a>
And these same full-stack generators were the base of the [**FastAPI** Project Generators](project-generation.md){.internal-link target=_blank}.
-!!! info
- Flask-apispec was created by the same Marshmallow developers.
+/// info
+
+Flask-apispec was created by the same Marshmallow developers.
+
+///
-!!! check "Inspired **FastAPI** to"
- Generate the OpenAPI schema automatically, from the same code that defines serialization and validation.
+/// check | "Inspired **FastAPI** to"
+
+Generate the OpenAPI schema automatically, from the same code that defines serialization and validation.
+
+///
### <a href="https://nestjs.com/" class="external-link" target="_blank">NestJS</a> (and <a href="https://angular.io/" class="external-link" target="_blank">Angular</a>)
It can't handle nested models very well. So, if the JSON body in the request is a JSON object that has inner fields that in turn are nested JSON objects, it cannot be properly documented and validated.
-!!! check "Inspired **FastAPI** to"
- Use Python types to have great editor support.
+/// check | "Inspired **FastAPI** to"
+
+Use Python types to have great editor support.
- Have a powerful dependency injection system. Find a way to minimize code repetition.
+Have a powerful dependency injection system. Find a way to minimize code repetition.
+
+///
### <a href="https://sanic.readthedocs.io/en/latest/" class="external-link" target="_blank">Sanic</a>
It was one of the first extremely fast Python frameworks based on `asyncio`. It was made to be very similar to Flask.
-!!! note "Technical Details"
- It used <a href="https://github.com/MagicStack/uvloop" class="external-link" target="_blank">`uvloop`</a> instead of the default Python `asyncio` loop. That's what made it so fast.
+/// note | "Technical Details"
+
+It used <a href="https://github.com/MagicStack/uvloop" class="external-link" target="_blank">`uvloop`</a> instead of the default Python `asyncio` loop. That's what made it so fast.
- It clearly inspired Uvicorn and Starlette, that are currently faster than Sanic in open benchmarks.
+It clearly inspired Uvicorn and Starlette, that are currently faster than Sanic in open benchmarks.
-!!! check "Inspired **FastAPI** to"
- Find a way to have a crazy performance.
+///
- That's why **FastAPI** is based on Starlette, as it is the fastest framework available (tested by third-party benchmarks).
+/// check | "Inspired **FastAPI** to"
+
+Find a way to have a crazy performance.
+
+That's why **FastAPI** is based on Starlette, as it is the fastest framework available (tested by third-party benchmarks).
+
+///
### <a href="https://falconframework.org/" class="external-link" target="_blank">Falcon</a>
So, data validation, serialization, and documentation, have to be done in code, not automatically. Or they have to be implemented as a framework on top of Falcon, like Hug. This same distinction happens in other frameworks that are inspired by Falcon's design, of having one request object and one response object as parameters.
-!!! check "Inspired **FastAPI** to"
- Find ways to get great performance.
+/// check | "Inspired **FastAPI** to"
- Along with Hug (as Hug is based on Falcon) inspired **FastAPI** to declare a `response` parameter in functions.
+Find ways to get great performance.
- Although in FastAPI it's optional, and is used mainly to set headers, cookies, and alternative status codes.
+Along with Hug (as Hug is based on Falcon) inspired **FastAPI** to declare a `response` parameter in functions.
+
+Although in FastAPI it's optional, and is used mainly to set headers, cookies, and alternative status codes.
+
+///
### <a href="https://moltenframework.com/" class="external-link" target="_blank">Molten</a>
Routes are declared in a single place, using functions declared in other places (instead of using decorators that can be placed right on top of the function that handles the endpoint). This is closer to how Django does it than to how Flask (and Starlette) does it. It separates in the code things that are relatively tightly coupled.
-!!! check "Inspired **FastAPI** to"
- Define extra validations for data types using the "default" value of model attributes. This improves editor support, and it was not available in Pydantic before.
+/// check | "Inspired **FastAPI** to"
+
+Define extra validations for data types using the "default" value of model attributes. This improves editor support, and it was not available in Pydantic before.
- This actually inspired updating parts of Pydantic, to support the same validation declaration style (all this functionality is now already available in Pydantic).
+This actually inspired updating parts of Pydantic, to support the same validation declaration style (all this functionality is now already available in Pydantic).
+
+///
### <a href="https://www.hug.rest/" class="external-link" target="_blank">Hug</a>
As it is based on the previous standard for synchronous Python web frameworks (WSGI), it can't handle Websockets and other things, although it still has high performance too.
-!!! info
- Hug was created by Timothy Crosley, the same creator of <a href="https://github.com/timothycrosley/isort" class="external-link" target="_blank">`isort`</a>, a great tool to automatically sort imports in Python files.
+/// info
+
+Hug was created by Timothy Crosley, the same creator of <a href="https://github.com/timothycrosley/isort" class="external-link" target="_blank">`isort`</a>, a great tool to automatically sort imports in Python files.
+
+///
-!!! check "Ideas inspiring **FastAPI**"
- Hug inspired parts of APIStar, and was one of the tools I found most promising, alongside APIStar.
+/// check | "Ideas inspiring **FastAPI**"
- Hug helped inspiring **FastAPI** to use Python type hints to declare parameters, and to generate a schema defining the API automatically.
+Hug inspired parts of APIStar, and was one of the tools I found most promising, alongside APIStar.
- Hug inspired **FastAPI** to declare a `response` parameter in functions to set headers and cookies.
+Hug helped inspiring **FastAPI** to use Python type hints to declare parameters, and to generate a schema defining the API automatically.
+
+Hug inspired **FastAPI** to declare a `response` parameter in functions to set headers and cookies.
+
+///
### <a href="https://github.com/encode/apistar" class="external-link" target="_blank">APIStar</a> (<= 0.5)
Now APIStar is a set of tools to validate OpenAPI specifications, not a web framework.
-!!! info
- APIStar was created by Tom Christie. The same guy that created:
+/// info
+
+APIStar was created by Tom Christie. The same guy that created:
- * Django REST Framework
- * Starlette (in which **FastAPI** is based)
- * Uvicorn (used by Starlette and **FastAPI**)
+* Django REST Framework
+* Starlette (in which **FastAPI** is based)
+* Uvicorn (used by Starlette and **FastAPI**)
-!!! check "Inspired **FastAPI** to"
- Exist.
+///
- The idea of declaring multiple things (data validation, serialization and documentation) with the same Python types, that at the same time provided great editor support, was something I considered a brilliant idea.
+/// check | "Inspired **FastAPI** to"
- And after searching for a long time for a similar framework and testing many different alternatives, APIStar was the best option available.
+Exist.
- Then APIStar stopped to exist as a server and Starlette was created, and was a new better foundation for such a system. That was the final inspiration to build **FastAPI**.
+The idea of declaring multiple things (data validation, serialization and documentation) with the same Python types, that at the same time provided great editor support, was something I considered a brilliant idea.
- I consider **FastAPI** a "spiritual successor" to APIStar, while improving and increasing the features, typing system, and other parts, based on the learnings from all these previous tools.
+And after searching for a long time for a similar framework and testing many different alternatives, APIStar was the best option available.
+
+Then APIStar stopped to exist as a server and Starlette was created, and was a new better foundation for such a system. That was the final inspiration to build **FastAPI**.
+
+I consider **FastAPI** a "spiritual successor" to APIStar, while improving and increasing the features, typing system, and other parts, based on the learnings from all these previous tools.
+
+///
## Used by **FastAPI**
It is comparable to Marshmallow. Although it's faster than Marshmallow in benchmarks. And as it is based on the same Python type hints, the editor support is great.
-!!! check "**FastAPI** uses it to"
- Handle all the data validation, data serialization and automatic model documentation (based on JSON Schema).
+/// check | "**FastAPI** uses it to"
- **FastAPI** then takes that JSON Schema data and puts it in OpenAPI, apart from all the other things it does.
+Handle all the data validation, data serialization and automatic model documentation (based on JSON Schema).
+
+**FastAPI** then takes that JSON Schema data and puts it in OpenAPI, apart from all the other things it does.
+
+///
### <a href="https://www.starlette.io/" class="external-link" target="_blank">Starlette</a>
That's one of the main things that **FastAPI** adds on top, all based on Python type hints (using Pydantic). That, plus the dependency injection system, security utilities, OpenAPI schema generation, etc.
-!!! note "Technical Details"
- ASGI is a new "standard" being developed by Django core team members. It is still not a "Python standard" (a PEP), although they are in the process of doing that.
+/// note | "Technical Details"
+
+ASGI is a new "standard" being developed by Django core team members. It is still not a "Python standard" (a PEP), although they are in the process of doing that.
- Nevertheless, it is already being used as a "standard" by several tools. This greatly improves interoperability, as you could switch Uvicorn for any other ASGI server (like Daphne or Hypercorn), or you could add ASGI compatible tools, like `python-socketio`.
+Nevertheless, it is already being used as a "standard" by several tools. This greatly improves interoperability, as you could switch Uvicorn for any other ASGI server (like Daphne or Hypercorn), or you could add ASGI compatible tools, like `python-socketio`.
-!!! check "**FastAPI** uses it to"
- Handle all the core web parts. Adding features on top.
+///
- The class `FastAPI` itself inherits directly from the class `Starlette`.
+/// check | "**FastAPI** uses it to"
- So, anything that you can do with Starlette, you can do it directly with **FastAPI**, as it is basically Starlette on steroids.
+Handle all the core web parts. Adding features on top.
+
+The class `FastAPI` itself inherits directly from the class `Starlette`.
+
+So, anything that you can do with Starlette, you can do it directly with **FastAPI**, as it is basically Starlette on steroids.
+
+///
### <a href="https://www.uvicorn.org/" class="external-link" target="_blank">Uvicorn</a>
It is the recommended server for Starlette and **FastAPI**.
-!!! check "**FastAPI** recommends it as"
- The main web server to run **FastAPI** applications.
+/// check | "**FastAPI** recommends it as"
+
+The main web server to run **FastAPI** applications.
+
+You can combine it with Gunicorn, to have an asynchronous multi-process server.
- You can combine it with Gunicorn, to have an asynchronous multi-process server.
+Check more details in the [Deployment](deployment/index.md){.internal-link target=_blank} section.
- Check more details in the [Deployment](deployment/index.md){.internal-link target=_blank} section.
+///
## Benchmarks and speed
return results
```
-!!! note
- You can only use `await` inside of functions created with `async def`.
+/// note
+
+You can only use `await` inside of functions created with `async def`.
+
+///
---
<img src="/img/async/concurrent-burgers/concurrent-burgers-07.png" class="illustration">
-!!! info
- Beautiful illustrations by <a href="https://www.instagram.com/ketrinadrawsalot" class="external-link" target="_blank">Ketrina Thompson</a>. 🎨
+/// info
+
+Beautiful illustrations by <a href="https://www.instagram.com/ketrinadrawsalot" class="external-link" target="_blank">Ketrina Thompson</a>. 🎨
+
+///
---
There was not much talk or flirting as most of the time was spent waiting 🕙 in front of the counter. 😞
-!!! info
- Beautiful illustrations by <a href="https://www.instagram.com/ketrinadrawsalot" class="external-link" target="_blank">Ketrina Thompson</a>. 🎨
+/// info
+
+Beautiful illustrations by <a href="https://www.instagram.com/ketrinadrawsalot" class="external-link" target="_blank">Ketrina Thompson</a>. 🎨
+
+///
---
## Very Technical Details
-!!! warning
- You can probably skip this.
+/// warning
+
+You can probably skip this.
+
+These are very technical details of how **FastAPI** works underneath.
- These are very technical details of how **FastAPI** works underneath.
+If you have quite some technical knowledge (coroutines, threads, blocking, etc.) and are curious about how FastAPI handles `async def` vs normal `def`, go ahead.
- If you have quite some technical knowledge (coroutines, threads, blocking, etc.) and are curious about how FastAPI handles `async def` vs normal `def`, go ahead.
+///
### Path operation functions
Activate the new environment with:
-=== "Linux, macOS"
+//// tab | Linux, macOS
- <div class="termy">
+<div class="termy">
- ```console
- $ source ./env/bin/activate
- ```
+```console
+$ source ./env/bin/activate
+```
- </div>
+</div>
-=== "Windows PowerShell"
+////
- <div class="termy">
+//// tab | Windows PowerShell
- ```console
- $ .\env\Scripts\Activate.ps1
- ```
+<div class="termy">
- </div>
+```console
+$ .\env\Scripts\Activate.ps1
+```
-=== "Windows Bash"
+</div>
+
+////
+
+//// tab | Windows Bash
- Or if you use Bash for Windows (e.g. <a href="https://gitforwindows.org/" class="external-link" target="_blank">Git Bash</a>):
+Or if you use Bash for Windows (e.g. <a href="https://gitforwindows.org/" class="external-link" target="_blank">Git Bash</a>):
- <div class="termy">
+<div class="termy">
+
+```console
+$ source ./env/Scripts/activate
+```
- ```console
- $ source ./env/Scripts/activate
- ```
+</div>
- </div>
+////
To check it worked, use:
-=== "Linux, macOS, Windows Bash"
+//// tab | Linux, macOS, Windows Bash
- <div class="termy">
+<div class="termy">
- ```console
- $ which pip
+```console
+$ which pip
- some/directory/fastapi/env/bin/pip
- ```
+some/directory/fastapi/env/bin/pip
+```
- </div>
+</div>
-=== "Windows PowerShell"
+////
- <div class="termy">
+//// tab | Windows PowerShell
- ```console
- $ Get-Command pip
+<div class="termy">
- some/directory/fastapi/env/bin/pip
- ```
+```console
+$ Get-Command pip
+
+some/directory/fastapi/env/bin/pip
+```
- </div>
+</div>
+
+////
If it shows the `pip` binary at `env/bin/pip` then it worked. 🎉
</div>
-!!! tip
- Every time you install a new package with `pip` under that environment, activate the environment again.
+/// tip
+
+Every time you install a new package with `pip` under that environment, activate the environment again.
- This makes sure that if you use a terminal program installed by that package, you use the one from your local environment and not any other that could be installed globally.
+This makes sure that if you use a terminal program installed by that package, you use the one from your local environment and not any other that could be installed globally.
+
+///
### Install requirements using pip
That way, you don't have to "install" your local version to be able to test every change.
-!!! note "Technical Details"
- This only happens when you install using this included `requirements.txt` instead of running `pip install fastapi` directly.
+/// note | "Technical Details"
+
+This only happens when you install using this included `requirements.txt` instead of running `pip install fastapi` directly.
- That is because inside the `requirements.txt` file, the local version of FastAPI is marked to be installed in "editable" mode, with the `-e` option.
+That is because inside the `requirements.txt` file, the local version of FastAPI is marked to be installed in "editable" mode, with the `-e` option.
+
+///
### Format the code
That way, you can edit the documentation/source files and see the changes live.
-!!! tip
- Alternatively, you can perform the same steps that scripts does manually.
+/// tip
- Go into the language directory, for the main docs in English it's at `docs/en/`:
+Alternatively, you can perform the same steps that scripts does manually.
- ```console
- $ cd docs/en/
- ```
+Go into the language directory, for the main docs in English it's at `docs/en/`:
- Then run `mkdocs` in that directory:
+```console
+$ cd docs/en/
+```
- ```console
- $ mkdocs serve --dev-addr 8008
- ```
+Then run `mkdocs` in that directory:
+
+```console
+$ mkdocs serve --dev-addr 8008
+```
+
+///
#### Typer CLI (optional)
And there are extra tools/scripts in place to handle translations in `./scripts/docs.py`.
-!!! tip
- You don't need to see the code in `./scripts/docs.py`, you just use it in the command line.
+/// tip
+
+You don't need to see the code in `./scripts/docs.py`, you just use it in the command line.
+
+///
All the documentation is in Markdown format in the directory `./docs/en/`.
* Review those pull requests, requesting changes or approving them. For the languages I don't speak, I'll wait for several others to review the translation before merging.
-!!! tip
- You can <a href="https://help.github.com/en/github/collaborating-with-issues-and-pull-requests/commenting-on-a-pull-request" class="external-link" target="_blank">add comments with change suggestions</a> to existing pull requests.
+/// tip
+
+You can <a href="https://help.github.com/en/github/collaborating-with-issues-and-pull-requests/commenting-on-a-pull-request" class="external-link" target="_blank">add comments with change suggestions</a> to existing pull requests.
+
+Check the docs about <a href="https://help.github.com/en/github/collaborating-with-issues-and-pull-requests/about-pull-request-reviews" class="external-link" target="_blank">adding a pull request review</a> to approve it or request changes.
- Check the docs about <a href="https://help.github.com/en/github/collaborating-with-issues-and-pull-requests/about-pull-request-reviews" class="external-link" target="_blank">adding a pull request review</a> to approve it or request changes.
+///
* Check if there's a <a href="https://github.com/fastapi/fastapi/discussions/categories/translations" class="external-link" target="_blank">GitHub Discussion</a> to coordinate translations for your language. You can subscribe to it, and when there's a new pull request to review, an automatic comment will be added to the discussion.
In the case of Spanish, the 2-letter code is `es`. So, the directory for Spanish translations is located at `docs/es/`.
-!!! tip
- The main ("official") language is English, located at `docs/en/`.
+/// tip
+
+The main ("official") language is English, located at `docs/en/`.
+
+///
Now run the live server for the docs in Spanish:
</div>
-!!! tip
- Alternatively, you can perform the same steps that scripts does manually.
+/// tip
+
+Alternatively, you can perform the same steps that scripts does manually.
- Go into the language directory, for the Spanish translations it's at `docs/es/`:
+Go into the language directory, for the Spanish translations it's at `docs/es/`:
+
+```console
+$ cd docs/es/
+```
- ```console
- $ cd docs/es/
- ```
+Then run `mkdocs` in that directory:
- Then run `mkdocs` in that directory:
+```console
+$ mkdocs serve --dev-addr 8008
+```
- ```console
- $ mkdocs serve --dev-addr 8008
- ```
+///
Now you can go to <a href="http://127.0.0.1:8008" class="external-link" target="_blank">http://127.0.0.1:8008</a> and see your changes live.
docs/es/docs/features.md
```
-!!! tip
- Notice that the only change in the path and file name is the language code, from `en` to `es`.
+/// tip
+
+Notice that the only change in the path and file name is the language code, from `en` to `es`.
+
+///
If you go to your browser you will see that now the docs show your new section (the info box at the top is gone). 🎉
INHERIT: ../en/mkdocs.yml
```
-!!! tip
- You could also simply create that file with those contents manually.
+/// tip
+
+You could also simply create that file with those contents manually.
+
+///
That command also created a dummy file `docs/ht/index.md` for the main page, you can start by translating that one.
But in those cases with really bad errors that crash the running **process**, you would want an external component that is in charge of **restarting** the process, at least a couple of times...
-!!! tip
- ...Although if the whole application is just **crashing immediately** it probably doesn't make sense to keep restarting it forever. But in those cases, you will probably notice it during development, or at least right after deployment.
+/// tip
- So let's focus on the main cases, where it could crash entirely in some particular cases **in the future**, and it still makes sense to restart it.
+...Although if the whole application is just **crashing immediately** it probably doesn't make sense to keep restarting it forever. But in those cases, you will probably notice it during development, or at least right after deployment.
+
+So let's focus on the main cases, where it could crash entirely in some particular cases **in the future**, and it still makes sense to restart it.
+
+///
You would probably want to have the thing in charge of restarting your application as an **external component**, because by that point, the same application with Uvicorn and Python already crashed, so there's nothing in the same code of the same app that could do anything about it.
* **Cloud services** that handle this for you
* The cloud service will probably **handle replication for you**. It would possibly let you define **a process to run**, or a **container image** to use, in any case, it would most probably be **a single Uvicorn process**, and the cloud service would be in charge of replicating it.
-!!! tip
- Don't worry if some of these items about **containers**, Docker, or Kubernetes don't make a lot of sense yet.
+/// tip
+
+Don't worry if some of these items about **containers**, Docker, or Kubernetes don't make a lot of sense yet.
+
+I'll tell you more about container images, Docker, Kubernetes, etc. in a future chapter: [FastAPI in Containers - Docker](docker.md){.internal-link target=_blank}.
- I'll tell you more about container images, Docker, Kubernetes, etc. in a future chapter: [FastAPI in Containers - Docker](docker.md){.internal-link target=_blank}.
+///
## Previous Steps Before Starting
Of course, there are some cases where there's no problem in running the previous steps multiple times, in that case, it's a lot easier to handle.
-!!! tip
- Also, keep in mind that depending on your setup, in some cases you **might not even need any previous steps** before starting your application.
+/// tip
- In that case, you wouldn't have to worry about any of this. 🤷
+Also, keep in mind that depending on your setup, in some cases you **might not even need any previous steps** before starting your application.
+
+In that case, you wouldn't have to worry about any of this. 🤷
+
+///
### Examples of Previous Steps Strategies
* A bash script that runs the previous steps and then starts your application
* You would still need a way to start/restart *that* bash script, detect errors, etc.
-!!! tip
- I'll give you more concrete examples for doing this with containers in a future chapter: [FastAPI in Containers - Docker](docker.md){.internal-link target=_blank}.
+/// tip
+
+I'll give you more concrete examples for doing this with containers in a future chapter: [FastAPI in Containers - Docker](docker.md){.internal-link target=_blank}.
+
+///
## Resource Utilization
Using Linux containers has several advantages including **security**, **replicability**, **simplicity**, and others.
-!!! tip
- In a hurry and already know this stuff? Jump to the [`Dockerfile` below 👇](#build-a-docker-image-for-fastapi).
+/// tip
+
+In a hurry and already know this stuff? Jump to the [`Dockerfile` below 👇](#build-a-docker-image-for-fastapi).
+
+///
<details>
<summary>Dockerfile Preview 👀</summary>
</div>
-!!! info
- There are other formats and tools to define and install package dependencies.
+/// info
+
+There are other formats and tools to define and install package dependencies.
+
+///
### Create the **FastAPI** Code
This command will be run from the **current working directory**, the same `/code` directory you set above with `WORKDIR /code`.
-!!! tip
- Review what each line does by clicking each number bubble in the code. 👆
+/// tip
+
+Review what each line does by clicking each number bubble in the code. 👆
+
+///
You should now have a directory structure like:
</div>
-!!! tip
- Notice the `.` at the end, it's equivalent to `./`, it tells Docker the directory to use to build the container image.
+/// tip
+
+Notice the `.` at the end, it's equivalent to `./`, it tells Docker the directory to use to build the container image.
+
+In this case, it's the same current directory (`.`).
- In this case, it's the same current directory (`.`).
+///
### Start the Docker Container
It could be another container, for example with <a href="https://traefik.io/" class="external-link" target="_blank">Traefik</a>, handling **HTTPS** and **automatic** acquisition of **certificates**.
-!!! tip
- Traefik has integrations with Docker, Kubernetes, and others, so it's very easy to set up and configure HTTPS for your containers with it.
+/// tip
+
+Traefik has integrations with Docker, Kubernetes, and others, so it's very easy to set up and configure HTTPS for your containers with it.
+
+///
Alternatively, HTTPS could be handled by a cloud provider as one of their services (while still running the application in a container).
As this component would take the **load** of requests and distribute that among the workers in a (hopefully) **balanced** way, it is also commonly called a **Load Balancer**.
-!!! tip
- The same **TLS Termination Proxy** component used for HTTPS would probably also be a **Load Balancer**.
+/// tip
+
+The same **TLS Termination Proxy** component used for HTTPS would probably also be a **Load Balancer**.
+
+///
And when working with containers, the same system you use to start and manage them would already have internal tools to transmit the **network communication** (e.g. HTTP requests) from that **load balancer** (that could also be a **TLS Termination Proxy**) to the container(s) with your app.
If you have **multiple containers**, probably each one running a **single process** (for example, in a **Kubernetes** cluster), then you would probably want to have a **separate container** doing the work of the **previous steps** in a single container, running a single process, **before** running the replicated worker containers.
-!!! info
- If you are using Kubernetes, this would probably be an <a href="https://kubernetes.io/docs/concepts/workloads/pods/init-containers/" class="external-link" target="_blank">Init Container</a>.
+/// info
+
+If you are using Kubernetes, this would probably be an <a href="https://kubernetes.io/docs/concepts/workloads/pods/init-containers/" class="external-link" target="_blank">Init Container</a>.
+
+///
If in your use case there's no problem in running those previous steps **multiple times in parallel** (for example if you are not running database migrations, but just checking if the database is ready yet), then you could also just put them in each container right before starting the main process.
* <a href="https://github.com/tiangolo/uvicorn-gunicorn-fastapi-docker" class="external-link" target="_blank">tiangolo/uvicorn-gunicorn-fastapi</a>.
-!!! warning
- There's a high chance that you **don't** need this base image or any other similar one, and would be better off by building the image from scratch as [described above in: Build a Docker Image for FastAPI](#build-a-docker-image-for-fastapi).
+/// warning
+
+There's a high chance that you **don't** need this base image or any other similar one, and would be better off by building the image from scratch as [described above in: Build a Docker Image for FastAPI](#build-a-docker-image-for-fastapi).
+
+///
This image has an **auto-tuning** mechanism included to set the **number of worker processes** based on the CPU cores available.
It also supports running <a href="https://github.com/tiangolo/uvicorn-gunicorn-fastapi-docker#pre_start_path" class="external-link" target="_blank">**previous steps before starting**</a> with a script.
-!!! tip
- To see all the configurations and options, go to the Docker image page: <a href="https://github.com/tiangolo/uvicorn-gunicorn-fastapi-docker" class="external-link" target="_blank">tiangolo/uvicorn-gunicorn-fastapi</a>.
+/// tip
+
+To see all the configurations and options, go to the Docker image page: <a href="https://github.com/tiangolo/uvicorn-gunicorn-fastapi-docker" class="external-link" target="_blank">tiangolo/uvicorn-gunicorn-fastapi</a>.
+
+///
### Number of Processes on the Official Docker Image
11. Use the `fastapi run` command to run your app.
-!!! tip
- Click the bubble numbers to see what each line does.
+/// tip
+
+Click the bubble numbers to see what each line does.
+
+///
A **Docker stage** is a part of a `Dockerfile` that works as a **temporary container image** that is only used to generate some files to be used later.
But it is way more complex than that.
-!!! tip
- If you are in a hurry or don't care, continue with the next sections for step by step instructions to set everything up with different techniques.
+/// tip
+
+If you are in a hurry or don't care, continue with the next sections for step by step instructions to set everything up with different techniques.
+
+///
To **learn the basics of HTTPS**, from a consumer perspective, check <a href="https://howhttps.works/" class="external-link" target="_blank">https://howhttps.works/</a>.
You would probably do this just once, the first time, when setting everything up.
-!!! tip
- This Domain Name part is way before HTTPS, but as everything depends on the domain and the IP address, it's worth mentioning it here.
+/// tip
+
+This Domain Name part is way before HTTPS, but as everything depends on the domain and the IP address, it's worth mentioning it here.
+
+///
### DNS
And that's what **HTTPS** is, it's just plain **HTTP** inside a **secure TLS connection** instead of a pure (unencrypted) TCP connection.
-!!! tip
- Notice that the encryption of the communication happens at the **TCP level**, not at the HTTP level.
+/// tip
+
+Notice that the encryption of the communication happens at the **TCP level**, not at the HTTP level.
+
+///
### HTTPS Request
But you can also install an ASGI server manually:
-=== "Uvicorn"
+//// tab | Uvicorn
- * <a href="https://www.uvicorn.org/" class="external-link" target="_blank">Uvicorn</a>, a lightning-fast ASGI server, built on uvloop and httptools.
+* <a href="https://www.uvicorn.org/" class="external-link" target="_blank">Uvicorn</a>, a lightning-fast ASGI server, built on uvloop and httptools.
- <div class="termy">
+<div class="termy">
- ```console
- $ pip install "uvicorn[standard]"
+```console
+$ pip install "uvicorn[standard]"
- ---> 100%
- ```
+---> 100%
+```
- </div>
+</div>
- !!! tip
- By adding the `standard`, Uvicorn will install and use some recommended extra dependencies.
+/// tip
- That including `uvloop`, the high-performance drop-in replacement for `asyncio`, that provides the big concurrency performance boost.
+By adding the `standard`, Uvicorn will install and use some recommended extra dependencies.
- When you install FastAPI with something like `pip install "fastapi[standard]"` you already get `uvicorn[standard]` as well.
+That including `uvloop`, the high-performance drop-in replacement for `asyncio`, that provides the big concurrency performance boost.
-=== "Hypercorn"
+When you install FastAPI with something like `pip install "fastapi[standard]"` you already get `uvicorn[standard]` as well.
- * <a href="https://github.com/pgjones/hypercorn" class="external-link" target="_blank">Hypercorn</a>, an ASGI server also compatible with HTTP/2.
+///
- <div class="termy">
+////
- ```console
- $ pip install hypercorn
+//// tab | Hypercorn
- ---> 100%
- ```
+* <a href="https://github.com/pgjones/hypercorn" class="external-link" target="_blank">Hypercorn</a>, an ASGI server also compatible with HTTP/2.
- </div>
+<div class="termy">
- ...or any other ASGI server.
+```console
+$ pip install hypercorn
+
+---> 100%
+```
+
+</div>
+
+...or any other ASGI server.
+
+////
## Run the Server Program
If you installed an ASGI server manually, you would normally need to pass an import string in a special format for it to import your FastAPI application:
-=== "Uvicorn"
+//// tab | Uvicorn
- <div class="termy">
+<div class="termy">
- ```console
- $ uvicorn main:app --host 0.0.0.0 --port 80
+```console
+$ uvicorn main:app --host 0.0.0.0 --port 80
+
+<span style="color: green;">INFO</span>: Uvicorn running on http://0.0.0.0:80 (Press CTRL+C to quit)
+```
+
+</div>
+
+////
+
+//// tab | Hypercorn
- <span style="color: green;">INFO</span>: Uvicorn running on http://0.0.0.0:80 (Press CTRL+C to quit)
- ```
+<div class="termy">
- </div>
+```console
+$ hypercorn main:app --bind 0.0.0.0:80
-=== "Hypercorn"
+Running on 0.0.0.0:8080 over http (CTRL + C to quit)
+```
- <div class="termy">
+</div>
- ```console
- $ hypercorn main:app --bind 0.0.0.0:80
+////
- Running on 0.0.0.0:8080 over http (CTRL + C to quit)
- ```
+/// note
- </div>
+The command `uvicorn main:app` refers to:
-!!! note
- The command `uvicorn main:app` refers to:
+* `main`: the file `main.py` (the Python "module").
+* `app`: the object created inside of `main.py` with the line `app = FastAPI()`.
+
+It is equivalent to:
+
+```Python
+from main import app
+```
- * `main`: the file `main.py` (the Python "module").
- * `app`: the object created inside of `main.py` with the line `app = FastAPI()`.
+///
- It is equivalent to:
+/// warning
- ```Python
- from main import app
- ```
+Uvicorn and others support a `--reload` option that is useful during development.
-!!! warning
- Uvicorn and others support a `--reload` option that is useful during development.
+The `--reload` option consumes much more resources, is more unstable, etc.
- The `--reload` option consumes much more resources, is more unstable, etc.
+It helps a lot during **development**, but you **shouldn't** use it in **production**.
- It helps a lot during **development**, but you **shouldn't** use it in **production**.
+///
## Hypercorn with Trio
Here I'll show you how to use <a href="https://gunicorn.org/" class="external-link" target="_blank">**Gunicorn**</a> with **Uvicorn worker processes**.
-!!! info
- If you are using containers, for example with Docker or Kubernetes, I'll tell you more about that in the next chapter: [FastAPI in Containers - Docker](docker.md){.internal-link target=_blank}.
+/// info
- In particular, when running on **Kubernetes** you will probably **not** want to use Gunicorn and instead run **a single Uvicorn process per container**, but I'll tell you about it later in that chapter.
+If you are using containers, for example with Docker or Kubernetes, I'll tell you more about that in the next chapter: [FastAPI in Containers - Docker](docker.md){.internal-link target=_blank}.
+
+In particular, when running on **Kubernetes** you will probably **not** want to use Gunicorn and instead run **a single Uvicorn process per container**, but I'll tell you about it later in that chapter.
+
+///
## Gunicorn with Uvicorn Workers
FastAPI also follows the convention that any "PATCH" version change is for bug fixes and non-breaking changes.
-!!! tip
- The "PATCH" is the last number, for example, in `0.2.3`, the PATCH version is `3`.
+/// tip
+
+The "PATCH" is the last number, for example, in `0.2.3`, the PATCH version is `3`.
+
+///
So, you should be able to pin to a version like:
Breaking changes and new features are added in "MINOR" versions.
-!!! tip
- The "MINOR" is the number in the middle, for example, in `0.2.3`, the MINOR version is `2`.
+/// tip
+
+The "MINOR" is the number in the middle, for example, in `0.2.3`, the MINOR version is `2`.
+
+///
## Upgrading the FastAPI versions
Here's an incomplete list of some of them.
-!!! tip
- If you have an article, project, tool, or anything related to **FastAPI** that is not yet listed here, create a <a href="https://github.com/fastapi/fastapi/edit/master/docs/en/data/external_links.yml" class="external-link" target="_blank">Pull Request adding it</a>.
+/// tip
+
+If you have an article, project, tool, or anything related to **FastAPI** that is not yet listed here, create a <a href="https://github.com/fastapi/fastapi/edit/master/docs/en/data/external_links.yml" class="external-link" target="_blank">Pull Request adding it</a>.
+
+///
{% for section_name, section_content in external_links.items() %}
In most cases you would (and should) have a "termination proxy" handling HTTPS for you on top, this will depend on how you deploy your application, your provider might do this for you, or you might need to set it up yourself.
-!!! tip
- You can learn more about it in the [deployment documentation](deployment/index.md){.internal-link target=_blank}.
+/// tip
+
+You can learn more about it in the [deployment documentation](deployment/index.md){.internal-link target=_blank}.
+
+///
They have proven to be **FastAPI Experts** by helping many others. ✨
-!!! tip
- You could become an official FastAPI Expert too!
+/// tip
- Just [help others with questions in GitHub](help-fastapi.md#help-others-with-questions-in-github){.internal-link target=_blank}. 🤓
+You could become an official FastAPI Expert too!
+
+Just [help others with questions in GitHub](help-fastapi.md#help-others-with-questions-in-github){.internal-link target=_blank}. 🤓
+
+///
You can see the **FastAPI Experts** for:
my_second_user: User = User(**second_user_data)
```
-!!! info
- `**second_user_data` means:
+/// info
- Pass the keys and values of the `second_user_data` dict directly as key-value arguments, equivalent to: `User(id=4, name="Mary", joined="2018-11-30")`
+`**second_user_data` means:
+
+Pass the keys and values of the `second_user_data` dict directly as key-value arguments, equivalent to: `User(id=4, name="Mary", joined="2018-11-30")`
+
+///
### Editor support
* Then **comment** saying that you did that, that's how I will know you really checked it.
-!!! info
- Unfortunately, I can't simply trust PRs that just have several approvals.
+/// info
- Several times it has happened that there are PRs with 3, 5 or more approvals, probably because the description is appealing, but when I check the PRs, they are actually broken, have a bug, or don't solve the problem they claim to solve. 😅
+Unfortunately, I can't simply trust PRs that just have several approvals.
- So, it's really important that you actually read and run the code, and let me know in the comments that you did. 🤓
+Several times it has happened that there are PRs with 3, 5 or more approvals, probably because the description is appealing, but when I check the PRs, they are actually broken, have a bug, or don't solve the problem they claim to solve. 😅
+
+So, it's really important that you actually read and run the code, and let me know in the comments that you did. 🤓
+
+///
* If the PR can be simplified in a way, you can ask for that, but there's no need to be too picky, there might be a lot of subjective points of view (and I will have my own as well 🙈), so it's better if you can focus on the fundamental things.
Join the 👥 <a href="https://discord.gg/VQjSZaeJmf" class="external-link" target="_blank">Discord chat server</a> 👥 and hang out with others in the FastAPI community.
-!!! tip
- For questions, ask them in <a href="https://github.com/fastapi/fastapi/discussions/new?category=questions" class="external-link" target="_blank">GitHub Discussions</a>, there's a much better chance you will receive help by the [FastAPI Experts](fastapi-people.md#fastapi-experts){.internal-link target=_blank}.
+/// tip
+
+For questions, ask them in <a href="https://github.com/fastapi/fastapi/discussions/new?category=questions" class="external-link" target="_blank">GitHub Discussions</a>, there's a much better chance you will receive help by the [FastAPI Experts](fastapi-people.md#fastapi-experts){.internal-link target=_blank}.
+
+Use the chat only for other general conversations.
- Use the chat only for other general conversations.
+///
### Don't use the chat for questions
# ~~Async SQL (Relational) Databases with Encode/Databases~~ (deprecated)
-!!! info
- These docs are about to be updated. 🎉
+/// info
- The current version assumes Pydantic v1.
+These docs are about to be updated. 🎉
- The new docs will include Pydantic v2 and will use <a href="https://sqlmodel.tiangolo.com/" class="external-link" target="_blank">SQLModel</a> once it is updated to use Pydantic v2 as well.
+The current version assumes Pydantic v1.
-!!! warning "Deprecated"
- This tutorial is deprecated and will be removed in a future version.
+The new docs will include Pydantic v2 and will use <a href="https://sqlmodel.tiangolo.com/" class="external-link" target="_blank">SQLModel</a> once it is updated to use Pydantic v2 as well.
+
+///
+
+/// warning | "Deprecated"
+
+This tutorial is deprecated and will be removed in a future version.
+
+///
You can also use <a href="https://github.com/encode/databases" class="external-link" target="_blank">`encode/databases`</a> with **FastAPI** to connect to databases using `async` and `await`.
Later, for your production application, you might want to use a database server like **PostgreSQL**.
-!!! tip
- You could adopt ideas from the section about SQLAlchemy ORM ([SQL (Relational) Databases](../tutorial/sql-databases.md){.internal-link target=_blank}), like using utility functions to perform operations in the database, independent of your **FastAPI** code.
+/// tip
- This section doesn't apply those ideas, to be equivalent to the counterpart in <a href="https://www.starlette.io/database/" class="external-link" target="_blank">Starlette</a>.
+You could adopt ideas from the section about SQLAlchemy ORM ([SQL (Relational) Databases](../tutorial/sql-databases.md){.internal-link target=_blank}), like using utility functions to perform operations in the database, independent of your **FastAPI** code.
+
+This section doesn't apply those ideas, to be equivalent to the counterpart in <a href="https://www.starlette.io/database/" class="external-link" target="_blank">Starlette</a>.
+
+///
## Import and set up `SQLAlchemy`
{!../../../docs_src/async_sql_databases/tutorial001.py!}
```
-!!! tip
- Notice that all this code is pure SQLAlchemy Core.
+/// tip
+
+Notice that all this code is pure SQLAlchemy Core.
+
+`databases` is not doing anything here yet.
- `databases` is not doing anything here yet.
+///
## Import and set up `databases`
{!../../../docs_src/async_sql_databases/tutorial001.py!}
```
-!!! tip
- If you were connecting to a different database (e.g. PostgreSQL), you would need to change the `DATABASE_URL`.
+/// tip
+
+If you were connecting to a different database (e.g. PostgreSQL), you would need to change the `DATABASE_URL`.
+
+///
## Create the tables
{!../../../docs_src/async_sql_databases/tutorial001.py!}
```
-!!! note
- Notice that as we communicate with the database using `await`, the *path operation function* is declared with `async`.
+/// note
+
+Notice that as we communicate with the database using `await`, the *path operation function* is declared with `async`.
+
+///
### Notice the `response_model=List[Note]`
{!../../../docs_src/async_sql_databases/tutorial001.py!}
```
-!!! info
- In Pydantic v1 the method was called `.dict()`, it was deprecated (but still supported) in Pydantic v2, and renamed to `.model_dump()`.
+/// info
+
+In Pydantic v1 the method was called `.dict()`, it was deprecated (but still supported) in Pydantic v2, and renamed to `.model_dump()`.
+
+The examples here use `.dict()` for compatibility with Pydantic v1, but you should use `.model_dump()` instead if you can use Pydantic v2.
+
+///
+
+/// note
- The examples here use `.dict()` for compatibility with Pydantic v1, but you should use `.model_dump()` instead if you can use Pydantic v2.
+Notice that as we communicate with the database using `await`, the *path operation function* is declared with `async`.
-!!! note
- Notice that as we communicate with the database using `await`, the *path operation function* is declared with `async`.
+///
### About `{**note.dict(), "id": last_record_id}`
{!../../../docs_src/custom_docs_ui/tutorial001.py!}
```
-!!! tip
- The *path operation* for `swagger_ui_redirect` is a helper for when you use OAuth2.
+/// tip
- If you integrate your API with an OAuth2 provider, you will be able to authenticate and come back to the API docs with the acquired credentials. And interact with it using the real OAuth2 authentication.
+The *path operation* for `swagger_ui_redirect` is a helper for when you use OAuth2.
- Swagger UI will handle it behind the scenes for you, but it needs this "redirect" helper.
+If you integrate your API with an OAuth2 provider, you will be able to authenticate and come back to the API docs with the acquired credentials. And interact with it using the real OAuth2 authentication.
+
+Swagger UI will handle it behind the scenes for you, but it needs this "redirect" helper.
+
+///
### Create a *path operation* to test it
{!../../../docs_src/custom_docs_ui/tutorial002.py!}
```
-!!! tip
- The *path operation* for `swagger_ui_redirect` is a helper for when you use OAuth2.
+/// tip
+
+The *path operation* for `swagger_ui_redirect` is a helper for when you use OAuth2.
+
+If you integrate your API with an OAuth2 provider, you will be able to authenticate and come back to the API docs with the acquired credentials. And interact with it using the real OAuth2 authentication.
- If you integrate your API with an OAuth2 provider, you will be able to authenticate and come back to the API docs with the acquired credentials. And interact with it using the real OAuth2 authentication.
+Swagger UI will handle it behind the scenes for you, but it needs this "redirect" helper.
- Swagger UI will handle it behind the scenes for you, but it needs this "redirect" helper.
+///
### Create a *path operation* to test static files
For example, if you want to read or manipulate the request body before it is processed by your application.
-!!! danger
- This is an "advanced" feature.
+/// danger
- If you are just starting with **FastAPI** you might want to skip this section.
+This is an "advanced" feature.
+
+If you are just starting with **FastAPI** you might want to skip this section.
+
+///
## Use cases
### Create a custom `GzipRequest` class
-!!! tip
- This is a toy example to demonstrate how it works, if you need Gzip support, you can use the provided [`GzipMiddleware`](../advanced/middleware.md#gzipmiddleware){.internal-link target=_blank}.
+/// tip
+
+This is a toy example to demonstrate how it works, if you need Gzip support, you can use the provided [`GzipMiddleware`](../advanced/middleware.md#gzipmiddleware){.internal-link target=_blank}.
+
+///
First, we create a `GzipRequest` class, which will overwrite the `Request.body()` method to decompress the body in the presence of an appropriate header.
{!../../../docs_src/custom_request_and_route/tutorial001.py!}
```
-!!! note "Technical Details"
- A `Request` has a `request.scope` attribute, that's just a Python `dict` containing the metadata related to the request.
+/// note | "Technical Details"
- A `Request` also has a `request.receive`, that's a function to "receive" the body of the request.
+A `Request` has a `request.scope` attribute, that's just a Python `dict` containing the metadata related to the request.
- The `scope` `dict` and `receive` function are both part of the ASGI specification.
+A `Request` also has a `request.receive`, that's a function to "receive" the body of the request.
- And those two things, `scope` and `receive`, are what is needed to create a new `Request` instance.
+The `scope` `dict` and `receive` function are both part of the ASGI specification.
- To learn more about the `Request` check <a href="https://www.starlette.io/requests/" class="external-link" target="_blank">Starlette's docs about Requests</a>.
+And those two things, `scope` and `receive`, are what is needed to create a new `Request` instance.
+
+To learn more about the `Request` check <a href="https://www.starlette.io/requests/" class="external-link" target="_blank">Starlette's docs about Requests</a>.
+
+///
The only thing the function returned by `GzipRequest.get_route_handler` does differently is convert the `Request` to a `GzipRequest`.
## Accessing the request body in an exception handler
-!!! tip
- To solve this same problem, it's probably a lot easier to use the `body` in a custom handler for `RequestValidationError` ([Handling Errors](../tutorial/handling-errors.md#use-the-requestvalidationerror-body){.internal-link target=_blank}).
+/// tip
+
+To solve this same problem, it's probably a lot easier to use the `body` in a custom handler for `RequestValidationError` ([Handling Errors](../tutorial/handling-errors.md#use-the-requestvalidationerror-body){.internal-link target=_blank}).
+
+But this example is still valid and it shows how to interact with the internal components.
- But this example is still valid and it shows how to interact with the internal components.
+///
We can also use this same approach to access the request body in an exception handler.
* `description`: The description of your API, this can include markdown and will be shown in the docs.
* `routes`: A list of routes, these are each of the registered *path operations*. They are taken from `app.routes`.
-!!! info
- The parameter `summary` is available in OpenAPI 3.1.0 and above, supported by FastAPI 0.99.0 and above.
+/// info
+
+The parameter `summary` is available in OpenAPI 3.1.0 and above, supported by FastAPI 0.99.0 and above.
+
+///
## Overriding the defaults
You can combine normal FastAPI *path operations* with GraphQL on the same application.
-!!! tip
- **GraphQL** solves some very specific use cases.
+/// tip
- It has **advantages** and **disadvantages** when compared to common **web APIs**.
+**GraphQL** solves some very specific use cases.
- Make sure you evaluate if the **benefits** for your use case compensate the **drawbacks**. 🤓
+It has **advantages** and **disadvantages** when compared to common **web APIs**.
+
+Make sure you evaluate if the **benefits** for your use case compensate the **drawbacks**. 🤓
+
+///
## GraphQL Libraries
It was deprecated from Starlette, but if you have code that used it, you can easily **migrate** to <a href="https://github.com/ciscorn/starlette-graphene3" class="external-link" target="_blank">starlette-graphene3</a>, that covers the same use case and has an **almost identical interface**.
-!!! tip
- If you need GraphQL, I still would recommend you check out <a href="https://strawberry.rocks/" class="external-link" target="_blank">Strawberry</a>, as it's based on type annotations instead of custom classes and types.
+/// tip
+
+If you need GraphQL, I still would recommend you check out <a href="https://strawberry.rocks/" class="external-link" target="_blank">Strawberry</a>, as it's based on type annotations instead of custom classes and types.
+
+///
## Learn More
If something seems interesting and useful to your project, go ahead and check it, but otherwise, you might probably just skip them.
-!!! tip
+/// tip
- If you want to **learn FastAPI** in a structured way (recommended), go and read the [Tutorial - User Guide](../tutorial/index.md){.internal-link target=_blank} chapter by chapter instead.
+If you want to **learn FastAPI** in a structured way (recommended), go and read the [Tutorial - User Guide](../tutorial/index.md){.internal-link target=_blank} chapter by chapter instead.
+
+///
# ~~NoSQL (Distributed / Big Data) Databases with Couchbase~~ (deprecated)
-!!! info
- These docs are about to be updated. 🎉
+/// info
- The current version assumes Pydantic v1.
+These docs are about to be updated. 🎉
- The new docs will hopefully use Pydantic v2 and will use <a href="https://art049.github.io/odmantic/" class="external-link" target="_blank">ODMantic</a> with MongoDB.
+The current version assumes Pydantic v1.
-!!! warning "Deprecated"
- This tutorial is deprecated and will be removed in a future version.
+The new docs will hopefully use Pydantic v2 and will use <a href="https://art049.github.io/odmantic/" class="external-link" target="_blank">ODMantic</a> with MongoDB.
+
+///
+
+/// warning | "Deprecated"
+
+This tutorial is deprecated and will be removed in a future version.
+
+///
**FastAPI** can also be integrated with any <abbr title="Distributed database (Big Data), also 'Not Only SQL'">NoSQL</abbr>.
* **ArangoDB**
* **ElasticSearch**, etc.
-!!! tip
- There is an official project generator with **FastAPI** and **Couchbase**, all based on **Docker**, including a frontend and more tools: <a href="https://github.com/tiangolo/full-stack-fastapi-couchbase" class="external-link" target="_blank">https://github.com/tiangolo/full-stack-fastapi-couchbase</a>
+/// tip
+
+There is an official project generator with **FastAPI** and **Couchbase**, all based on **Docker**, including a frontend and more tools: <a href="https://github.com/tiangolo/full-stack-fastapi-couchbase" class="external-link" target="_blank">https://github.com/tiangolo/full-stack-fastapi-couchbase</a>
+
+///
## Import Couchbase components
{!../../../docs_src/nosql_databases/tutorial001.py!}
```
-!!! note
- Notice that we have a `hashed_password` and a `type` field that will be stored in the database.
+/// note
+
+Notice that we have a `hashed_password` and a `type` field that will be stored in the database.
+
+But it is not part of the general `User` model (the one we will return in the *path operation*).
- But it is not part of the general `User` model (the one we will return in the *path operation*).
+///
## Get the user
Let's say you have a Pydantic model with default values, like this one:
-=== "Python 3.10+"
+//// tab | Python 3.10+
- ```Python hl_lines="7"
- {!> ../../../docs_src/separate_openapi_schemas/tutorial001_py310.py[ln:1-7]!}
+```Python hl_lines="7"
+{!> ../../../docs_src/separate_openapi_schemas/tutorial001_py310.py[ln:1-7]!}
- # Code below omitted 👇
- ```
+# Code below omitted 👇
+```
- <details>
- <summary>👀 Full file preview</summary>
+<details>
+<summary>👀 Full file preview</summary>
- ```Python
- {!> ../../../docs_src/separate_openapi_schemas/tutorial001_py310.py!}
- ```
+```Python
+{!> ../../../docs_src/separate_openapi_schemas/tutorial001_py310.py!}
+```
- </details>
+</details>
-=== "Python 3.9+"
+////
- ```Python hl_lines="9"
- {!> ../../../docs_src/separate_openapi_schemas/tutorial001_py39.py[ln:1-9]!}
+//// tab | Python 3.9+
- # Code below omitted 👇
- ```
+```Python hl_lines="9"
+{!> ../../../docs_src/separate_openapi_schemas/tutorial001_py39.py[ln:1-9]!}
- <details>
- <summary>👀 Full file preview</summary>
+# Code below omitted 👇
+```
- ```Python
- {!> ../../../docs_src/separate_openapi_schemas/tutorial001_py39.py!}
- ```
+<details>
+<summary>👀 Full file preview</summary>
- </details>
+```Python
+{!> ../../../docs_src/separate_openapi_schemas/tutorial001_py39.py!}
+```
-=== "Python 3.8+"
+</details>
- ```Python hl_lines="9"
- {!> ../../../docs_src/separate_openapi_schemas/tutorial001.py[ln:1-9]!}
+////
- # Code below omitted 👇
- ```
+//// tab | Python 3.8+
- <details>
- <summary>👀 Full file preview</summary>
+```Python hl_lines="9"
+{!> ../../../docs_src/separate_openapi_schemas/tutorial001.py[ln:1-9]!}
- ```Python
- {!> ../../../docs_src/separate_openapi_schemas/tutorial001.py!}
- ```
+# Code below omitted 👇
+```
- </details>
+<details>
+<summary>👀 Full file preview</summary>
+
+```Python
+{!> ../../../docs_src/separate_openapi_schemas/tutorial001.py!}
+```
+
+</details>
+
+////
### Model for Input
If you use this model as an input like here:
-=== "Python 3.10+"
+//// tab | Python 3.10+
+
+```Python hl_lines="14"
+{!> ../../../docs_src/separate_openapi_schemas/tutorial001_py310.py[ln:1-15]!}
- ```Python hl_lines="14"
- {!> ../../../docs_src/separate_openapi_schemas/tutorial001_py310.py[ln:1-15]!}
+# Code below omitted 👇
+```
- # Code below omitted 👇
- ```
+<details>
+<summary>👀 Full file preview</summary>
- <details>
- <summary>👀 Full file preview</summary>
+```Python
+{!> ../../../docs_src/separate_openapi_schemas/tutorial001_py310.py!}
+```
- ```Python
- {!> ../../../docs_src/separate_openapi_schemas/tutorial001_py310.py!}
- ```
+</details>
- </details>
+////
-=== "Python 3.9+"
+//// tab | Python 3.9+
- ```Python hl_lines="16"
- {!> ../../../docs_src/separate_openapi_schemas/tutorial001_py39.py[ln:1-17]!}
+```Python hl_lines="16"
+{!> ../../../docs_src/separate_openapi_schemas/tutorial001_py39.py[ln:1-17]!}
- # Code below omitted 👇
- ```
+# Code below omitted 👇
+```
- <details>
- <summary>👀 Full file preview</summary>
+<details>
+<summary>👀 Full file preview</summary>
- ```Python
- {!> ../../../docs_src/separate_openapi_schemas/tutorial001_py39.py!}
- ```
+```Python
+{!> ../../../docs_src/separate_openapi_schemas/tutorial001_py39.py!}
+```
- </details>
+</details>
-=== "Python 3.8+"
+////
- ```Python hl_lines="16"
- {!> ../../../docs_src/separate_openapi_schemas/tutorial001.py[ln:1-17]!}
+//// tab | Python 3.8+
- # Code below omitted 👇
- ```
+```Python hl_lines="16"
+{!> ../../../docs_src/separate_openapi_schemas/tutorial001.py[ln:1-17]!}
- <details>
- <summary>👀 Full file preview</summary>
+# Code below omitted 👇
+```
- ```Python
- {!> ../../../docs_src/separate_openapi_schemas/tutorial001.py!}
- ```
+<details>
+<summary>👀 Full file preview</summary>
- </details>
+```Python
+{!> ../../../docs_src/separate_openapi_schemas/tutorial001.py!}
+```
+
+</details>
+
+////
...then the `description` field will **not be required**. Because it has a default value of `None`.
But if you use the same model as an output, like here:
-=== "Python 3.10+"
+//// tab | Python 3.10+
+
+```Python hl_lines="19"
+{!> ../../../docs_src/separate_openapi_schemas/tutorial001_py310.py!}
+```
- ```Python hl_lines="19"
- {!> ../../../docs_src/separate_openapi_schemas/tutorial001_py310.py!}
- ```
+////
-=== "Python 3.9+"
+//// tab | Python 3.9+
- ```Python hl_lines="21"
- {!> ../../../docs_src/separate_openapi_schemas/tutorial001_py39.py!}
- ```
+```Python hl_lines="21"
+{!> ../../../docs_src/separate_openapi_schemas/tutorial001_py39.py!}
+```
-=== "Python 3.8+"
+////
- ```Python hl_lines="21"
- {!> ../../../docs_src/separate_openapi_schemas/tutorial001.py!}
- ```
+//// tab | Python 3.8+
+
+```Python hl_lines="21"
+{!> ../../../docs_src/separate_openapi_schemas/tutorial001.py!}
+```
+
+////
...then because `description` has a default value, if you **don't return anything** for that field, it will still have that **default value**.
In that case, you can disable this feature in **FastAPI**, with the parameter `separate_input_output_schemas=False`.
-!!! info
- Support for `separate_input_output_schemas` was added in FastAPI `0.102.0`. 🤓
+/// info
+
+Support for `separate_input_output_schemas` was added in FastAPI `0.102.0`. 🤓
+
+///
+
+//// tab | Python 3.10+
+
+```Python hl_lines="10"
+{!> ../../../docs_src/separate_openapi_schemas/tutorial002_py310.py!}
+```
+
+////
-=== "Python 3.10+"
+//// tab | Python 3.9+
- ```Python hl_lines="10"
- {!> ../../../docs_src/separate_openapi_schemas/tutorial002_py310.py!}
- ```
+```Python hl_lines="12"
+{!> ../../../docs_src/separate_openapi_schemas/tutorial002_py39.py!}
+```
-=== "Python 3.9+"
+////
- ```Python hl_lines="12"
- {!> ../../../docs_src/separate_openapi_schemas/tutorial002_py39.py!}
- ```
+//// tab | Python 3.8+
-=== "Python 3.8+"
+```Python hl_lines="12"
+{!> ../../../docs_src/separate_openapi_schemas/tutorial002.py!}
+```
- ```Python hl_lines="12"
- {!> ../../../docs_src/separate_openapi_schemas/tutorial002.py!}
- ```
+////
### Same Schema for Input and Output Models in Docs
# ~~SQL (Relational) Databases with Peewee~~ (deprecated)
-!!! warning "Deprecated"
- This tutorial is deprecated and will be removed in a future version.
+/// warning | "Deprecated"
-!!! warning
- If you are just starting, the tutorial [SQL (Relational) Databases](../tutorial/sql-databases.md){.internal-link target=_blank} that uses SQLAlchemy should be enough.
+This tutorial is deprecated and will be removed in a future version.
- Feel free to skip this.
+///
- Peewee is not recommended with FastAPI as it doesn't play well with anything async Python. There are several better alternatives.
+/// warning
-!!! info
- These docs assume Pydantic v1.
+If you are just starting, the tutorial [SQL (Relational) Databases](../tutorial/sql-databases.md){.internal-link target=_blank} that uses SQLAlchemy should be enough.
- Because Pewee doesn't play well with anything async and there are better alternatives, I won't update these docs for Pydantic v2, they are kept for now only for historical purposes.
+Feel free to skip this.
- The examples here are no longer tested in CI (as they were before).
+Peewee is not recommended with FastAPI as it doesn't play well with anything async Python. There are several better alternatives.
+
+///
+
+/// info
+
+These docs assume Pydantic v1.
+
+Because Pewee doesn't play well with anything async and there are better alternatives, I won't update these docs for Pydantic v2, they are kept for now only for historical purposes.
+
+The examples here are no longer tested in CI (as they were before).
+
+///
If you are starting a project from scratch, you are probably better off with SQLAlchemy ORM ([SQL (Relational) Databases](../tutorial/sql-databases.md){.internal-link target=_blank}), or any other async ORM.
If you already have a code base that uses <a href="https://docs.peewee-orm.com/en/latest/" class="external-link" target="_blank">Peewee ORM</a>, you can check here how to use it with **FastAPI**.
-!!! warning "Python 3.7+ required"
- You will need Python 3.7 or above to safely use Peewee with FastAPI.
+/// warning | "Python 3.7+ required"
+
+You will need Python 3.7 or above to safely use Peewee with FastAPI.
+
+///
## Peewee for async
Nevertheless, it's possible to do it, and here you'll see exactly what code you have to add to be able to use Peewee with FastAPI.
-!!! note "Technical Details"
- You can read more about Peewee's stand about async in Python <a href="https://docs.peewee-orm.com/en/latest/peewee/database.html#async-with-gevent" class="external-link" target="_blank">in the docs</a>, <a href="https://github.com/coleifer/peewee/issues/263#issuecomment-517347032" class="external-link" target="_blank">an issue</a>, <a href="https://github.com/coleifer/peewee/pull/2072#issuecomment-563215132" class="external-link" target="_blank">a PR</a>.
+/// note | "Technical Details"
+
+You can read more about Peewee's stand about async in Python <a href="https://docs.peewee-orm.com/en/latest/peewee/database.html#async-with-gevent" class="external-link" target="_blank">in the docs</a>, <a href="https://github.com/coleifer/peewee/issues/263#issuecomment-517347032" class="external-link" target="_blank">an issue</a>, <a href="https://github.com/coleifer/peewee/pull/2072#issuecomment-563215132" class="external-link" target="_blank">a PR</a>.
+
+///
## The same app
{!../../../docs_src/sql_databases_peewee/sql_app/database.py!}
```
-!!! tip
- Keep in mind that if you wanted to use a different database, like PostgreSQL, you couldn't just change the string. You would need to use a different Peewee database class.
+/// tip
+
+Keep in mind that if you wanted to use a different database, like PostgreSQL, you couldn't just change the string. You would need to use a different Peewee database class.
+
+///
#### Note
...it is needed only for `SQLite`.
-!!! info "Technical Details"
+/// info | "Technical Details"
- Exactly the same technical details as in [SQL (Relational) Databases](../tutorial/sql-databases.md#note){.internal-link target=_blank} apply.
+Exactly the same technical details as in [SQL (Relational) Databases](../tutorial/sql-databases.md#note){.internal-link target=_blank} apply.
+
+///
### Make Peewee async-compatible `PeeweeConnectionState`
And `threading.local` is not compatible with the new async features of modern Python.
-!!! note "Technical Details"
- `threading.local` is used to have a "magic" variable that has a different value for each thread.
+/// note | "Technical Details"
+
+`threading.local` is used to have a "magic" variable that has a different value for each thread.
- This was useful in older frameworks designed to have one single thread per request, no more, no less.
+This was useful in older frameworks designed to have one single thread per request, no more, no less.
- Using this, each request would have its own database connection/session, which is the actual final goal.
+Using this, each request would have its own database connection/session, which is the actual final goal.
- But FastAPI, using the new async features, could handle more than one request on the same thread. And at the same time, for a single request, it could run multiple things in different threads (in a threadpool), depending on if you use `async def` or normal `def`. This is what gives all the performance improvements to FastAPI.
+But FastAPI, using the new async features, could handle more than one request on the same thread. And at the same time, for a single request, it could run multiple things in different threads (in a threadpool), depending on if you use `async def` or normal `def`. This is what gives all the performance improvements to FastAPI.
+
+///
But Python 3.7 and above provide a more advanced alternative to `threading.local`, that can also be used in the places where `threading.local` would be used, but is compatible with the new async features.
So, we need to do some extra tricks to make it work as if it was just using `threading.local`. The `__init__`, `__setattr__`, and `__getattr__` implement all the required tricks for this to be used by Peewee without knowing that it is now compatible with FastAPI.
-!!! tip
- This will just make Peewee behave correctly when used with FastAPI. Not randomly opening or closing connections that are being used, creating errors, etc.
+/// tip
+
+This will just make Peewee behave correctly when used with FastAPI. Not randomly opening or closing connections that are being used, creating errors, etc.
- But it doesn't give Peewee async super-powers. You should still use normal `def` functions and not `async def`.
+But it doesn't give Peewee async super-powers. You should still use normal `def` functions and not `async def`.
+
+///
### Use the custom `PeeweeConnectionState` class
{!../../../docs_src/sql_databases_peewee/sql_app/database.py!}
```
-!!! tip
- Make sure you overwrite `db._state` *after* creating `db`.
+/// tip
+
+Make sure you overwrite `db._state` *after* creating `db`.
-!!! tip
- You would do the same for any other Peewee database, including `PostgresqlDatabase`, `MySQLDatabase`, etc.
+///
+
+/// tip
+
+You would do the same for any other Peewee database, including `PostgresqlDatabase`, `MySQLDatabase`, etc.
+
+///
## Create the database models
This is the same you would do if you followed the Peewee tutorial and updated the models to have the same data as in the SQLAlchemy tutorial.
-!!! tip
- Peewee also uses the term "**model**" to refer to these classes and instances that interact with the database.
+/// tip
+
+Peewee also uses the term "**model**" to refer to these classes and instances that interact with the database.
+
+But Pydantic also uses the term "**model**" to refer to something different, the data validation, conversion, and documentation classes and instances.
- But Pydantic also uses the term "**model**" to refer to something different, the data validation, conversion, and documentation classes and instances.
+///
Import `db` from `database` (the file `database.py` from above) and use it here.
{!../../../docs_src/sql_databases_peewee/sql_app/models.py!}
```
-!!! tip
- Peewee creates several magic attributes.
+/// tip
- It will automatically add an `id` attribute as an integer to be the primary key.
+Peewee creates several magic attributes.
- It will chose the name of the tables based on the class names.
+It will automatically add an `id` attribute as an integer to be the primary key.
- For the `Item`, it will create an attribute `owner_id` with the integer ID of the `User`. But we don't declare it anywhere.
+It will chose the name of the tables based on the class names.
+
+For the `Item`, it will create an attribute `owner_id` with the integer ID of the `User`. But we don't declare it anywhere.
+
+///
## Create the Pydantic models
Now let's check the file `sql_app/schemas.py`.
-!!! tip
- To avoid confusion between the Peewee *models* and the Pydantic *models*, we will have the file `models.py` with the Peewee models, and the file `schemas.py` with the Pydantic models.
+/// tip
+
+To avoid confusion between the Peewee *models* and the Pydantic *models*, we will have the file `models.py` with the Peewee models, and the file `schemas.py` with the Pydantic models.
+
+These Pydantic models define more or less a "schema" (a valid data shape).
- These Pydantic models define more or less a "schema" (a valid data shape).
+So this will help us avoiding confusion while using both.
- So this will help us avoiding confusion while using both.
+///
### Create the Pydantic *models* / schemas
{!../../../docs_src/sql_databases_peewee/sql_app/schemas.py!}
```
-!!! tip
- Here we are creating the models with an `id`.
+/// tip
- We didn't explicitly specify an `id` attribute in the Peewee models, but Peewee adds one automatically.
+Here we are creating the models with an `id`.
- We are also adding the magic `owner_id` attribute to `Item`.
+We didn't explicitly specify an `id` attribute in the Peewee models, but Peewee adds one automatically.
+
+We are also adding the magic `owner_id` attribute to `Item`.
+
+///
### Create a `PeeweeGetterDict` for the Pydantic *models* / schemas
And then we use it in the Pydantic *models* / schemas that use `orm_mode = True`, with the configuration variable `getter_dict = PeeweeGetterDict`.
-!!! tip
- We only need to create one `PeeweeGetterDict` class, and we can use it in all the Pydantic *models* / schemas.
+/// tip
+
+We only need to create one `PeeweeGetterDict` class, and we can use it in all the Pydantic *models* / schemas.
+
+///
## CRUD utils
For the **next request**, as we will reset that context variable again in the `async` dependency `reset_db_state()` and then create a new connection in the `get_db()` dependency, that new request will have its own database state (connection, transactions, etc).
-!!! tip
- As FastAPI is an async framework, one request could start being processed, and before finishing, another request could be received and start processing as well, and it all could be processed in the same thread.
+/// tip
- But context variables are aware of these async features, so, a Peewee database state set in the `async` dependency `reset_db_state()` will keep its own data throughout the entire request.
+As FastAPI is an async framework, one request could start being processed, and before finishing, another request could be received and start processing as well, and it all could be processed in the same thread.
- And at the same time, the other concurrent request will have its own database state that will be independent for the whole request.
+But context variables are aware of these async features, so, a Peewee database state set in the `async` dependency `reset_db_state()` will keep its own data throughout the entire request.
+
+And at the same time, the other concurrent request will have its own database state that will be independent for the whole request.
+
+///
#### Peewee Proxy
## Technical Details
-!!! warning
- These are very technical details that you probably don't need.
+/// warning
+
+These are very technical details that you probably don't need.
+
+///
### The problem
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
}
showRandomAnnouncement('announce-left', 5000)
showRandomAnnouncement('announce-right', 10000)
}
-
-main()
+document$.subscribe(() => {
+ main()
+})
These are the tasks that can be performed to manage the FastAPI repository by [team members](./fastapi-people.md#team){.internal-link target=_blank}.
-!!! tip
- This section is useful only to a handful of people, team members with permissions to manage the repository. You can probably skip it. 😉
+/// tip
+
+This section is useful only to a handful of people, team members with permissions to manage the repository. You can probably skip it. 😉
+
+///
...so, you are a [team member of FastAPI](./fastapi-people.md#team){.internal-link target=_blank}? Wow, you are so cool! 😎
* `internal`: Internal
* Use this for changes that only affect how the repo is managed. For example upgrades to internal dependencies, changes in GitHub Actions or scripts, etc.
-!!! tip
- Some tools like Dependabot, will add some labels, like `dependencies`, but have in mind that this label is not used by the `latest-changes` GitHub Action, so it won't be used in the release notes. Please make sure one of the labels above is added.
+/// tip
+
+Some tools like Dependabot, will add some labels, like `dependencies`, but have in mind that this label is not used by the `latest-changes` GitHub Action, so it won't be used in the release notes. Please make sure one of the labels above is added.
+
+///
## Add Labels to Translation PRs
* The "admonition" sections, like `tip`, `info`, etc. are not changed or translated. For example:
```
-!!! tip
- This is a tip.
+/// tip
+
+This is a tip.
+
+///
+
```
looks like this:
-!!! tip
- This is a tip.
+/// tip
+
+This is a tip.
+
+///
...it could be translated as:
```
-!!! tip
- Esto es un consejo.
+/// tip
+
+Esto es un consejo.
+
+///
+
```
...but needs to keep the exact `tip` keyword. If it was translated to `consejo`, like:
```
-!!! consejo
- Esto es un consejo.
+/// consejo
+
+Esto es un consejo.
+
+///
+
```
it would change the style to the default one, it would look like:
-!!! consejo
- Esto es un consejo.
+/// consejo
+
+Esto es un consejo.
+
+///
Those don't have to be translated, but if they are, they need to be written as:
```
-!!! tip "consejo"
- Esto es un consejo.
+/// tip | "consejo"
+
+Esto es un consejo.
+
+///
+
```
Which looks like:
-!!! tip "consejo"
- Esto es un consejo.
+/// tip | "consejo"
+
+Esto es un consejo.
+
+///
## First Translation PR
# FastAPI and friends newsletter
-<iframe data-w-type="embedded" frameborder="0" scrolling="no" marginheight="0" marginwidth="0" src="https://xr4n4.mjt.lu/wgt/xr4n4/hj5/form?c=40a44fa4" width="100%" style="height: 0;"></iframe>
+<iframe data-w-type="embedded" frameborder="0" scrolling="no" marginheight="0" marginwidth="0" src="https://xr4n4.mjt.lu/wgt/xr4n4/hj5/form?c=40a44fa4" width="100%" style="height: 800px;"></iframe>
<script type="text/javascript" src="https://app.mailjet.com/pas-nc-embedded-v1.js"></script>
But even if you never use **FastAPI**, you would benefit from learning a bit about them.
-!!! note
- If you are a Python expert, and you already know everything about type hints, skip to the next chapter.
+/// note
+
+If you are a Python expert, and you already know everything about type hints, skip to the next chapter.
+
+///
## Motivation
For example, let's define a variable to be a `list` of `str`.
-=== "Python 3.9+"
+//// tab | Python 3.9+
- Declare the variable, with the same colon (`:`) syntax.
+Declare the variable, with the same colon (`:`) syntax.
- As the type, put `list`.
+As the type, put `list`.
- As the list is a type that contains some internal types, you put them in square brackets:
+As the list is a type that contains some internal types, you put them in square brackets:
- ```Python hl_lines="1"
- {!> ../../../docs_src/python_types/tutorial006_py39.py!}
- ```
+```Python hl_lines="1"
+{!> ../../../docs_src/python_types/tutorial006_py39.py!}
+```
-=== "Python 3.8+"
+////
- From `typing`, import `List` (with a capital `L`):
+//// tab | Python 3.8+
- ```Python hl_lines="1"
- {!> ../../../docs_src/python_types/tutorial006.py!}
- ```
+From `typing`, import `List` (with a capital `L`):
- Declare the variable, with the same colon (`:`) syntax.
+```Python hl_lines="1"
+{!> ../../../docs_src/python_types/tutorial006.py!}
+```
+
+Declare the variable, with the same colon (`:`) syntax.
- As the type, put the `List` that you imported from `typing`.
+As the type, put the `List` that you imported from `typing`.
- As the list is a type that contains some internal types, you put them in square brackets:
+As the list is a type that contains some internal types, you put them in square brackets:
+
+```Python hl_lines="4"
+{!> ../../../docs_src/python_types/tutorial006.py!}
+```
- ```Python hl_lines="4"
- {!> ../../../docs_src/python_types/tutorial006.py!}
- ```
+////
-!!! info
- Those internal types in the square brackets are called "type parameters".
+/// info
- In this case, `str` is the type parameter passed to `List` (or `list` in Python 3.9 and above).
+Those internal types in the square brackets are called "type parameters".
+
+In this case, `str` is the type parameter passed to `List` (or `list` in Python 3.9 and above).
+
+///
That means: "the variable `items` is a `list`, and each of the items in this list is a `str`".
-!!! tip
- If you use Python 3.9 or above, you don't have to import `List` from `typing`, you can use the same regular `list` type instead.
+/// tip
+
+If you use Python 3.9 or above, you don't have to import `List` from `typing`, you can use the same regular `list` type instead.
+
+///
By doing that, your editor can provide support even while processing items from the list:
You would do the same to declare `tuple`s and `set`s:
-=== "Python 3.9+"
+//// tab | Python 3.9+
- ```Python hl_lines="1"
- {!> ../../../docs_src/python_types/tutorial007_py39.py!}
- ```
+```Python hl_lines="1"
+{!> ../../../docs_src/python_types/tutorial007_py39.py!}
+```
-=== "Python 3.8+"
+////
- ```Python hl_lines="1 4"
- {!> ../../../docs_src/python_types/tutorial007.py!}
- ```
+//// tab | Python 3.8+
+
+```Python hl_lines="1 4"
+{!> ../../../docs_src/python_types/tutorial007.py!}
+```
+
+////
This means:
The second type parameter is for the values of the `dict`:
-=== "Python 3.9+"
+//// tab | Python 3.9+
+
+```Python hl_lines="1"
+{!> ../../../docs_src/python_types/tutorial008_py39.py!}
+```
+
+////
- ```Python hl_lines="1"
- {!> ../../../docs_src/python_types/tutorial008_py39.py!}
- ```
+//// tab | Python 3.8+
-=== "Python 3.8+"
+```Python hl_lines="1 4"
+{!> ../../../docs_src/python_types/tutorial008.py!}
+```
- ```Python hl_lines="1 4"
- {!> ../../../docs_src/python_types/tutorial008.py!}
- ```
+////
This means:
In Python 3.10 there's also a **new syntax** where you can put the possible types separated by a <abbr title='also called "bitwise or operator", but that meaning is not relevant here'>vertical bar (`|`)</abbr>.
-=== "Python 3.10+"
+//// tab | Python 3.10+
- ```Python hl_lines="1"
- {!> ../../../docs_src/python_types/tutorial008b_py310.py!}
- ```
+```Python hl_lines="1"
+{!> ../../../docs_src/python_types/tutorial008b_py310.py!}
+```
+
+////
+
+//// tab | Python 3.8+
-=== "Python 3.8+"
+```Python hl_lines="1 4"
+{!> ../../../docs_src/python_types/tutorial008b.py!}
+```
- ```Python hl_lines="1 4"
- {!> ../../../docs_src/python_types/tutorial008b.py!}
- ```
+////
In both cases this means that `item` could be an `int` or a `str`.
This also means that in Python 3.10, you can use `Something | None`:
-=== "Python 3.10+"
+//// tab | Python 3.10+
+
+```Python hl_lines="1"
+{!> ../../../docs_src/python_types/tutorial009_py310.py!}
+```
+
+////
- ```Python hl_lines="1"
- {!> ../../../docs_src/python_types/tutorial009_py310.py!}
- ```
+//// tab | Python 3.8+
-=== "Python 3.8+"
+```Python hl_lines="1 4"
+{!> ../../../docs_src/python_types/tutorial009.py!}
+```
- ```Python hl_lines="1 4"
- {!> ../../../docs_src/python_types/tutorial009.py!}
- ```
+////
-=== "Python 3.8+ alternative"
+//// tab | Python 3.8+ alternative
- ```Python hl_lines="1 4"
- {!> ../../../docs_src/python_types/tutorial009b.py!}
- ```
+```Python hl_lines="1 4"
+{!> ../../../docs_src/python_types/tutorial009b.py!}
+```
+
+////
#### Using `Union` or `Optional`
These types that take type parameters in square brackets are called **Generic types** or **Generics**, for example:
-=== "Python 3.10+"
+//// tab | Python 3.10+
+
+You can use the same builtin types as generics (with square brackets and types inside):
+
+* `list`
+* `tuple`
+* `set`
+* `dict`
- You can use the same builtin types as generics (with square brackets and types inside):
+And the same as with Python 3.8, from the `typing` module:
- * `list`
- * `tuple`
- * `set`
- * `dict`
+* `Union`
+* `Optional` (the same as with Python 3.8)
+* ...and others.
- And the same as with Python 3.8, from the `typing` module:
+In Python 3.10, as an alternative to using the generics `Union` and `Optional`, you can use the <abbr title='also called "bitwise or operator", but that meaning is not relevant here'>vertical bar (`|`)</abbr> to declare unions of types, that's a lot better and simpler.
- * `Union`
- * `Optional` (the same as with Python 3.8)
- * ...and others.
+////
- In Python 3.10, as an alternative to using the generics `Union` and `Optional`, you can use the <abbr title='also called "bitwise or operator", but that meaning is not relevant here'>vertical bar (`|`)</abbr> to declare unions of types, that's a lot better and simpler.
+//// tab | Python 3.9+
-=== "Python 3.9+"
+You can use the same builtin types as generics (with square brackets and types inside):
- You can use the same builtin types as generics (with square brackets and types inside):
+* `list`
+* `tuple`
+* `set`
+* `dict`
- * `list`
- * `tuple`
- * `set`
- * `dict`
+And the same as with Python 3.8, from the `typing` module:
- And the same as with Python 3.8, from the `typing` module:
+* `Union`
+* `Optional`
+* ...and others.
- * `Union`
- * `Optional`
- * ...and others.
+////
-=== "Python 3.8+"
+//// tab | Python 3.8+
- * `List`
- * `Tuple`
- * `Set`
- * `Dict`
- * `Union`
- * `Optional`
- * ...and others.
+* `List`
+* `Tuple`
+* `Set`
+* `Dict`
+* `Union`
+* `Optional`
+* ...and others.
+
+////
### Classes as types
An example from the official Pydantic docs:
-=== "Python 3.10+"
+//// tab | Python 3.10+
+
+```Python
+{!> ../../../docs_src/python_types/tutorial011_py310.py!}
+```
- ```Python
- {!> ../../../docs_src/python_types/tutorial011_py310.py!}
- ```
+////
-=== "Python 3.9+"
+//// tab | Python 3.9+
- ```Python
- {!> ../../../docs_src/python_types/tutorial011_py39.py!}
- ```
+```Python
+{!> ../../../docs_src/python_types/tutorial011_py39.py!}
+```
-=== "Python 3.8+"
+////
- ```Python
- {!> ../../../docs_src/python_types/tutorial011.py!}
- ```
+//// tab | Python 3.8+
-!!! info
- To learn more about <a href="https://docs.pydantic.dev/" class="external-link" target="_blank">Pydantic, check its docs</a>.
+```Python
+{!> ../../../docs_src/python_types/tutorial011.py!}
+```
+
+////
+
+/// info
+
+To learn more about <a href="https://docs.pydantic.dev/" class="external-link" target="_blank">Pydantic, check its docs</a>.
+
+///
**FastAPI** is all based on Pydantic.
You will see a lot more of all this in practice in the [Tutorial - User Guide](tutorial/index.md){.internal-link target=_blank}.
-!!! tip
- Pydantic has a special behavior when you use `Optional` or `Union[Something, None]` without a default value, you can read more about it in the Pydantic docs about <a href="https://docs.pydantic.dev/latest/concepts/models/#required-optional-fields" class="external-link" target="_blank">Required Optional fields</a>.
+/// tip
+
+Pydantic has a special behavior when you use `Optional` or `Union[Something, None]` without a default value, you can read more about it in the Pydantic docs about <a href="https://docs.pydantic.dev/latest/concepts/models/#required-optional-fields" class="external-link" target="_blank">Required Optional fields</a>.
+
+///
## Type Hints with Metadata Annotations
Python also has a feature that allows putting **additional <abbr title="Data about the data, in this case, information about the type, e.g. a description.">metadata</abbr>** in these type hints using `Annotated`.
-=== "Python 3.9+"
+//// tab | Python 3.9+
+
+In Python 3.9, `Annotated` is part of the standard library, so you can import it from `typing`.
+
+```Python hl_lines="1 4"
+{!> ../../../docs_src/python_types/tutorial013_py39.py!}
+```
- In Python 3.9, `Annotated` is part of the standard library, so you can import it from `typing`.
+////
- ```Python hl_lines="1 4"
- {!> ../../../docs_src/python_types/tutorial013_py39.py!}
- ```
+//// tab | Python 3.8+
-=== "Python 3.8+"
+In versions below Python 3.9, you import `Annotated` from `typing_extensions`.
- In versions below Python 3.9, you import `Annotated` from `typing_extensions`.
+It will already be installed with **FastAPI**.
- It will already be installed with **FastAPI**.
+```Python hl_lines="1 4"
+{!> ../../../docs_src/python_types/tutorial013.py!}
+```
- ```Python hl_lines="1 4"
- {!> ../../../docs_src/python_types/tutorial013.py!}
- ```
+////
Python itself doesn't do anything with this `Annotated`. And for editors and other tools, the type is still `str`.
Later you will see how **powerful** it can be.
-!!! tip
- The fact that this is **standard Python** means that you will still get the **best possible developer experience** in your editor, with the tools you use to analyze and refactor your code, etc. ✨
+/// tip
- And also that your code will be very compatible with many other Python tools and libraries. 🚀
+The fact that this is **standard Python** means that you will still get the **best possible developer experience** in your editor, with the tools you use to analyze and refactor your code, etc. ✨
+
+And also that your code will be very compatible with many other Python tools and libraries. 🚀
+
+///
## Type hints in **FastAPI**
The important thing is that by using standard Python types, in a single place (instead of adding more classes, decorators, etc), **FastAPI** will do a lot of the work for you.
-!!! info
- If you already went through all the tutorial and came back to see more about types, a good resource is <a href="https://mypy.readthedocs.io/en/latest/cheat_sheet_py3.html" class="external-link" target="_blank">the "cheat sheet" from `mypy`</a>.
+/// info
+
+If you already went through all the tutorial and came back to see more about types, a good resource is <a href="https://mypy.readthedocs.io/en/latest/cheat_sheet_py3.html" class="external-link" target="_blank">the "cheat sheet" from `mypy`</a>.
+
+///
from fastapi import Request
```
-!!! tip
- When you want to define dependencies that should be compatible with both HTTP and WebSockets, you can define a parameter that takes an `HTTPConnection` instead of a `Request` or a `WebSocket`.
+/// tip
+
+When you want to define dependencies that should be compatible with both HTTP and WebSockets, you can define a parameter that takes an `HTTPConnection` instead of a `Request` or a `WebSocket`.
+
+///
::: fastapi.Request
from fastapi import WebSocket
```
-!!! tip
- When you want to define dependencies that should be compatible with both HTTP and WebSockets, you can define a parameter that takes an `HTTPConnection` instead of a `Request` or a `WebSocket`.
+/// tip
+
+When you want to define dependencies that should be compatible with both HTTP and WebSockets, you can define a parameter that takes an `HTTPConnection` instead of a `Request` or a `WebSocket`.
+
+///
::: fastapi.WebSocket
options:
**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+"
+//// tab | Python 3.10+
- ```Python hl_lines="13 15 22 25"
- {!> ../../../docs_src/background_tasks/tutorial002_an_py310.py!}
- ```
+```Python hl_lines="13 15 22 25"
+{!> ../../../docs_src/background_tasks/tutorial002_an_py310.py!}
+```
+
+////
+
+//// tab | Python 3.9+
+
+```Python hl_lines="13 15 22 25"
+{!> ../../../docs_src/background_tasks/tutorial002_an_py39.py!}
+```
+
+////
+
+//// tab | Python 3.8+
-=== "Python 3.9+"
+```Python hl_lines="14 16 23 26"
+{!> ../../../docs_src/background_tasks/tutorial002_an.py!}
+```
+
+////
- ```Python hl_lines="13 15 22 25"
- {!> ../../../docs_src/background_tasks/tutorial002_an_py39.py!}
- ```
+//// tab | Python 3.10+ non-Annotated
-=== "Python 3.8+"
+/// tip
- ```Python hl_lines="14 16 23 26"
- {!> ../../../docs_src/background_tasks/tutorial002_an.py!}
- ```
+Prefer to use the `Annotated` version if possible.
-=== "Python 3.10+ non-Annotated"
+///
+
+```Python hl_lines="11 13 20 23"
+{!> ../../../docs_src/background_tasks/tutorial002_py310.py!}
+```
- !!! tip
- Prefer to use the `Annotated` version if possible.
+////
- ```Python hl_lines="11 13 20 23"
- {!> ../../../docs_src/background_tasks/tutorial002_py310.py!}
- ```
+//// tab | Python 3.8+ non-Annotated
-=== "Python 3.8+ non-Annotated"
+/// tip
- !!! tip
- Prefer to use the `Annotated` version if possible.
+Prefer to use the `Annotated` version if possible.
+
+///
+
+```Python hl_lines="13 15 22 25"
+{!> ../../../docs_src/background_tasks/tutorial002.py!}
+```
- ```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.
**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
│ └── 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`.
All the same `parameters`, `responses`, `dependencies`, `tags`, etc.
-!!! tip
- In this example, the variable is called `router`, but you can name it however you want.
+/// tip
+
+In this example, the variable is called `router`, but you can name it however you want.
+
+///
We are going to include this `APIRouter` in the main `FastAPI` app, but first, let's check the dependencies and another `APIRouter`.
We will now use a simple dependency to read a custom `X-Token` header:
-=== "Python 3.9+"
+//// tab | Python 3.9+
+
+```Python hl_lines="3 6-8" title="app/dependencies.py"
+{!> ../../../docs_src/bigger_applications/app_an_py39/dependencies.py!}
+```
- ```Python hl_lines="3 6-8" title="app/dependencies.py"
- {!> ../../../docs_src/bigger_applications/app_an_py39/dependencies.py!}
- ```
+////
-=== "Python 3.8+"
+//// tab | Python 3.8+
- ```Python hl_lines="1 5-7" title="app/dependencies.py"
- {!> ../../../docs_src/bigger_applications/app_an/dependencies.py!}
- ```
+```Python hl_lines="1 5-7" title="app/dependencies.py"
+{!> ../../../docs_src/bigger_applications/app_an/dependencies.py!}
+```
-=== "Python 3.8+ non-Annotated"
+////
- !!! tip
- Prefer to use the `Annotated` version if possible.
+//// tab | Python 3.8+ non-Annotated
- ```Python hl_lines="1 4-6" title="app/dependencies.py"
- {!> ../../../docs_src/bigger_applications/app/dependencies.py!}
- ```
+/// tip
-!!! tip
- We are using an invented header to simplify this example.
+Prefer to use the `Annotated` version if possible.
- But in real cases you will get better results using the integrated [Security utilities](security/index.md){.internal-link target=_blank}.
+///
+
+```Python hl_lines="1 4-6" title="app/dependencies.py"
+{!> ../../../docs_src/bigger_applications/app/dependencies.py!}
+```
+
+////
+
+/// tip
+
+We are using an invented header to simplify this example.
+
+But in real cases you will get better results using the integrated [Security utilities](security/index.md){.internal-link target=_blank}.
+
+///
## Another module with `APIRouter`
And we can add a list of `dependencies` that will be added to all the *path operations* in the router and will be executed/solved for each request made to them.
-!!! tip
- Note that, much like [dependencies in *path operation decorators*](dependencies/dependencies-in-path-operation-decorators.md){.internal-link target=_blank}, no value will be passed to your *path operation function*.
+/// tip
+
+Note that, much like [dependencies in *path operation decorators*](dependencies/dependencies-in-path-operation-decorators.md){.internal-link target=_blank}, no value will be passed to your *path operation function*.
+
+///
The end result is that the item paths are now:
* The router dependencies are executed first, then the [`dependencies` in the decorator](dependencies/dependencies-in-path-operation-decorators.md){.internal-link target=_blank}, and then the normal parameter dependencies.
* You can also add [`Security` dependencies with `scopes`](../advanced/security/oauth2-scopes.md){.internal-link target=_blank}.
-!!! tip
- Having `dependencies` in the `APIRouter` can be used, for example, to require authentication for a whole group of *path operations*. Even if the dependencies are not added individually to each one of them.
+/// tip
+
+Having `dependencies` in the `APIRouter` can be used, for example, to require authentication for a whole group of *path operations*. Even if the dependencies are not added individually to each one of them.
+
+///
+
+/// check
-!!! check
- The `prefix`, `tags`, `responses`, and `dependencies` parameters are (as in many other cases) just a feature from **FastAPI** to help you avoid code duplication.
+The `prefix`, `tags`, `responses`, and `dependencies` parameters are (as in many other cases) just a feature from **FastAPI** to help you avoid code duplication.
+
+///
### Import the dependencies
#### How relative imports work
-!!! tip
- If you know perfectly how imports work, continue to the next section below.
+/// tip
+
+If you know perfectly how imports work, continue to the next section below.
+
+///
A single dot `.`, like in:
{!../../../docs_src/bigger_applications/app/routers/items.py!}
```
-!!! tip
- This last path operation will have the combination of tags: `["items", "custom"]`.
+/// tip
- And it will also have both responses in the documentation, one for `404` and one for `403`.
+This last path operation will have the combination of tags: `["items", "custom"]`.
+
+And it will also have both responses in the documentation, one for `404` and one for `403`.
+
+///
## The main `FastAPI`
from app.routers import items, users
```
-!!! info
- The first version is a "relative import":
+/// info
- ```Python
- from .routers import items, users
- ```
+The first version is a "relative import":
- The second version is an "absolute import":
+```Python
+from .routers import items, users
+```
+
+The second version is an "absolute import":
+
+```Python
+from app.routers import items, users
+```
- ```Python
- from app.routers import items, users
- ```
+To learn more about Python Packages and Modules, read <a href="https://docs.python.org/3/tutorial/modules.html" class="external-link" target="_blank">the official Python documentation about Modules</a>.
- To learn more about Python Packages and Modules, read <a href="https://docs.python.org/3/tutorial/modules.html" class="external-link" target="_blank">the official Python documentation about Modules</a>.
+///
### Avoid name collisions
{!../../../docs_src/bigger_applications/app/main.py!}
```
-!!! info
- `users.router` contains the `APIRouter` inside of the file `app/routers/users.py`.
+/// info
+
+`users.router` contains the `APIRouter` inside of the file `app/routers/users.py`.
- And `items.router` contains the `APIRouter` inside of the file `app/routers/items.py`.
+And `items.router` contains the `APIRouter` inside of the file `app/routers/items.py`.
+
+///
With `app.include_router()` we can add each `APIRouter` to the main `FastAPI` application.
It will include all the routes from that router as part of it.
-!!! note "Technical Details"
- It will actually internally create a *path operation* for each *path operation* that was declared in the `APIRouter`.
+/// note | "Technical Details"
+
+It will actually internally create a *path operation* for each *path operation* that was declared in the `APIRouter`.
+
+So, behind the scenes, it will actually work as if everything was the same single app.
- So, behind the scenes, it will actually work as if everything was the same single app.
+///
-!!! check
- You don't have to worry about performance when including routers.
+/// check
- This will take microseconds and will only happen at startup.
+You don't have to worry about performance when including routers.
- So it won't affect performance. ⚡
+This will take microseconds and will only happen at startup.
+
+So it won't affect performance. ⚡
+
+///
### Include an `APIRouter` with a custom `prefix`, `tags`, `responses`, and `dependencies`
and it will work correctly, together with all the other *path operations* added with `app.include_router()`.
-!!! info "Very Technical Details"
- **Note**: this is a very technical detail that you probably can **just skip**.
+/// info | "Very Technical Details"
+
+**Note**: this is a very technical detail that you probably can **just skip**.
+
+---
- ---
+The `APIRouter`s are not "mounted", they are not isolated from the rest of the application.
- The `APIRouter`s are not "mounted", they are not isolated from the rest of the application.
+This is because we want to include their *path operations* in the OpenAPI schema and the user interfaces.
- This is because we want to include their *path operations* in the OpenAPI schema and the user interfaces.
+As we cannot just isolate them and "mount" them independently of the rest, the *path operations* are "cloned" (re-created), not included directly.
- As we cannot just isolate them and "mount" them independently of the rest, the *path operations* are "cloned" (re-created), not included directly.
+///
## Check the automatic API docs
First, you have to import it:
-=== "Python 3.10+"
+//// tab | Python 3.10+
- ```Python hl_lines="4"
- {!> ../../../docs_src/body_fields/tutorial001_an_py310.py!}
- ```
+```Python hl_lines="4"
+{!> ../../../docs_src/body_fields/tutorial001_an_py310.py!}
+```
-=== "Python 3.9+"
+////
- ```Python hl_lines="4"
- {!> ../../../docs_src/body_fields/tutorial001_an_py39.py!}
- ```
+//// tab | Python 3.9+
-=== "Python 3.8+"
+```Python hl_lines="4"
+{!> ../../../docs_src/body_fields/tutorial001_an_py39.py!}
+```
- ```Python hl_lines="4"
- {!> ../../../docs_src/body_fields/tutorial001_an.py!}
- ```
+////
-=== "Python 3.10+ non-Annotated"
+//// tab | Python 3.8+
- !!! tip
- Prefer to use the `Annotated` version if possible.
+```Python hl_lines="4"
+{!> ../../../docs_src/body_fields/tutorial001_an.py!}
+```
- ```Python hl_lines="2"
- {!> ../../../docs_src/body_fields/tutorial001_py310.py!}
- ```
+////
-=== "Python 3.8+ non-Annotated"
+//// tab | Python 3.10+ non-Annotated
- !!! tip
- Prefer to use the `Annotated` version if possible.
+/// tip
- ```Python hl_lines="4"
- {!> ../../../docs_src/body_fields/tutorial001.py!}
- ```
+Prefer to use the `Annotated` version if possible.
-!!! warning
- Notice that `Field` is imported directly from `pydantic`, not from `fastapi` as are all the rest (`Query`, `Path`, `Body`, etc).
+///
+
+```Python hl_lines="2"
+{!> ../../../docs_src/body_fields/tutorial001_py310.py!}
+```
+
+////
+
+//// tab | Python 3.8+ non-Annotated
+
+/// tip
+
+Prefer to use the `Annotated` version if possible.
+
+///
+
+```Python hl_lines="4"
+{!> ../../../docs_src/body_fields/tutorial001.py!}
+```
+
+////
+
+/// warning
+
+Notice that `Field` is imported directly from `pydantic`, not from `fastapi` as are all the rest (`Query`, `Path`, `Body`, etc).
+
+///
## Declare model attributes
You can then use `Field` with model attributes:
-=== "Python 3.10+"
+//// tab | Python 3.10+
+
+```Python hl_lines="11-14"
+{!> ../../../docs_src/body_fields/tutorial001_an_py310.py!}
+```
+
+////
- ```Python hl_lines="11-14"
- {!> ../../../docs_src/body_fields/tutorial001_an_py310.py!}
- ```
+//// tab | Python 3.9+
-=== "Python 3.9+"
+```Python hl_lines="11-14"
+{!> ../../../docs_src/body_fields/tutorial001_an_py39.py!}
+```
- ```Python hl_lines="11-14"
- {!> ../../../docs_src/body_fields/tutorial001_an_py39.py!}
- ```
+////
-=== "Python 3.8+"
+//// tab | Python 3.8+
- ```Python hl_lines="12-15"
- {!> ../../../docs_src/body_fields/tutorial001_an.py!}
- ```
+```Python hl_lines="12-15"
+{!> ../../../docs_src/body_fields/tutorial001_an.py!}
+```
-=== "Python 3.10+ non-Annotated"
+////
- !!! tip
- Prefer to use the `Annotated` version if possible.
+//// tab | Python 3.10+ non-Annotated
- ```Python hl_lines="9-12"
- {!> ../../../docs_src/body_fields/tutorial001_py310.py!}
- ```
+/// tip
-=== "Python 3.8+ non-Annotated"
+Prefer to use the `Annotated` version if possible.
- !!! tip
- Prefer to use the `Annotated` version if possible.
+///
- ```Python hl_lines="11-14"
- {!> ../../../docs_src/body_fields/tutorial001.py!}
- ```
+```Python hl_lines="9-12"
+{!> ../../../docs_src/body_fields/tutorial001_py310.py!}
+```
+
+////
+
+//// tab | Python 3.8+ non-Annotated
+
+/// tip
+
+Prefer to use the `Annotated` version if possible.
+
+///
+
+```Python hl_lines="11-14"
+{!> ../../../docs_src/body_fields/tutorial001.py!}
+```
+
+////
`Field` works the same way as `Query`, `Path` and `Body`, it has all the same parameters, etc.
-!!! note "Technical Details"
- Actually, `Query`, `Path` and others you'll see next create objects of subclasses of a common `Param` class, which is itself a subclass of Pydantic's `FieldInfo` class.
+/// note | "Technical Details"
- And Pydantic's `Field` returns an instance of `FieldInfo` as well.
+Actually, `Query`, `Path` and others you'll see next create objects of subclasses of a common `Param` class, which is itself a subclass of Pydantic's `FieldInfo` class.
- `Body` also returns objects of a subclass of `FieldInfo` directly. And there are others you will see later that are subclasses of the `Body` class.
+And Pydantic's `Field` returns an instance of `FieldInfo` as well.
- Remember that when you import `Query`, `Path`, and others from `fastapi`, those are actually functions that return special classes.
+`Body` also returns objects of a subclass of `FieldInfo` directly. And there are others you will see later that are subclasses of the `Body` class.
-!!! tip
- Notice how each model's attribute with a type, default value and `Field` has the same structure as a *path operation function's* parameter, with `Field` instead of `Path`, `Query` and `Body`.
+Remember that when you import `Query`, `Path`, and others from `fastapi`, those are actually functions that return special classes.
+
+///
+
+/// tip
+
+Notice how each model's attribute with a type, default value and `Field` has the same structure as a *path operation function's* parameter, with `Field` instead of `Path`, `Query` and `Body`.
+
+///
## Add extra information
You will learn more about adding extra information later in the docs, when learning to declare examples.
-!!! warning
- Extra keys passed to `Field` will also be present in the resulting OpenAPI schema for your application.
- As these keys may not necessarily be part of the OpenAPI specification, some OpenAPI tools, for example [the OpenAPI validator](https://validator.swagger.io/), may not work with your generated schema.
+/// warning
+
+Extra keys passed to `Field` will also be present in the resulting OpenAPI schema for your application.
+As these keys may not necessarily be part of the OpenAPI specification, some OpenAPI tools, for example [the OpenAPI validator](https://validator.swagger.io/), may not work with your generated schema.
+
+///
## Recap
And you can also declare body parameters as optional, by setting the default to `None`:
-=== "Python 3.10+"
+//// tab | Python 3.10+
- ```Python hl_lines="18-20"
- {!> ../../../docs_src/body_multiple_params/tutorial001_an_py310.py!}
- ```
+```Python hl_lines="18-20"
+{!> ../../../docs_src/body_multiple_params/tutorial001_an_py310.py!}
+```
+
+////
-=== "Python 3.9+"
+//// tab | Python 3.9+
- ```Python hl_lines="18-20"
- {!> ../../../docs_src/body_multiple_params/tutorial001_an_py39.py!}
- ```
+```Python hl_lines="18-20"
+{!> ../../../docs_src/body_multiple_params/tutorial001_an_py39.py!}
+```
-=== "Python 3.8+"
+////
- ```Python hl_lines="19-21"
- {!> ../../../docs_src/body_multiple_params/tutorial001_an.py!}
- ```
+//// tab | Python 3.8+
+
+```Python hl_lines="19-21"
+{!> ../../../docs_src/body_multiple_params/tutorial001_an.py!}
+```
-=== "Python 3.10+ non-Annotated"
+////
- !!! tip
- Prefer to use the `Annotated` version if possible.
+//// tab | Python 3.10+ non-Annotated
- ```Python hl_lines="17-19"
- {!> ../../../docs_src/body_multiple_params/tutorial001_py310.py!}
- ```
+/// tip
+
+Prefer to use the `Annotated` version if possible.
+
+///
+
+```Python hl_lines="17-19"
+{!> ../../../docs_src/body_multiple_params/tutorial001_py310.py!}
+```
-=== "Python 3.8+ non-Annotated"
+////
- !!! tip
- Prefer to use the `Annotated` version if possible.
+//// tab | Python 3.8+ non-Annotated
- ```Python hl_lines="19-21"
- {!> ../../../docs_src/body_multiple_params/tutorial001.py!}
- ```
+/// tip
-!!! note
- Notice that, in this case, the `item` that would be taken from the body is optional. As it has a `None` default value.
+Prefer to use the `Annotated` version if possible.
+
+///
+
+```Python hl_lines="19-21"
+{!> ../../../docs_src/body_multiple_params/tutorial001.py!}
+```
+
+////
+
+/// note
+
+Notice that, in this case, the `item` that would be taken from the body is optional. As it has a `None` default value.
+
+///
## Multiple body parameters
But you can also declare multiple body parameters, e.g. `item` and `user`:
-=== "Python 3.10+"
+//// tab | Python 3.10+
- ```Python hl_lines="20"
- {!> ../../../docs_src/body_multiple_params/tutorial002_py310.py!}
- ```
+```Python hl_lines="20"
+{!> ../../../docs_src/body_multiple_params/tutorial002_py310.py!}
+```
-=== "Python 3.8+"
+////
- ```Python hl_lines="22"
- {!> ../../../docs_src/body_multiple_params/tutorial002.py!}
- ```
+//// tab | Python 3.8+
+
+```Python hl_lines="22"
+{!> ../../../docs_src/body_multiple_params/tutorial002.py!}
+```
+
+////
In this case, **FastAPI** will notice that there are more than one body parameters in the function (two parameters that are Pydantic models).
}
```
-!!! note
- Notice that even though the `item` was declared the same way as before, it is now expected to be inside of the body with a key `item`.
+/// note
+
+Notice that even though the `item` was declared the same way as before, it is now expected to be inside of the body with a key `item`.
+///
**FastAPI** will do the automatic conversion from the request, so that the parameter `item` receives its specific content and the same for `user`.
But you can instruct **FastAPI** to treat it as another body key using `Body`:
-=== "Python 3.10+"
+//// tab | Python 3.10+
+
+```Python hl_lines="23"
+{!> ../../../docs_src/body_multiple_params/tutorial003_an_py310.py!}
+```
+
+////
+
+//// tab | Python 3.9+
- ```Python hl_lines="23"
- {!> ../../../docs_src/body_multiple_params/tutorial003_an_py310.py!}
- ```
+```Python hl_lines="23"
+{!> ../../../docs_src/body_multiple_params/tutorial003_an_py39.py!}
+```
+
+////
+
+//// tab | Python 3.8+
+
+```Python hl_lines="24"
+{!> ../../../docs_src/body_multiple_params/tutorial003_an.py!}
+```
+
+////
-=== "Python 3.9+"
+//// tab | Python 3.10+ non-Annotated
- ```Python hl_lines="23"
- {!> ../../../docs_src/body_multiple_params/tutorial003_an_py39.py!}
- ```
+/// tip
-=== "Python 3.8+"
+Prefer to use the `Annotated` version if possible.
- ```Python hl_lines="24"
- {!> ../../../docs_src/body_multiple_params/tutorial003_an.py!}
- ```
+///
-=== "Python 3.10+ non-Annotated"
+```Python hl_lines="20"
+{!> ../../../docs_src/body_multiple_params/tutorial003_py310.py!}
+```
- !!! tip
- Prefer to use the `Annotated` version if possible.
+////
- ```Python hl_lines="20"
- {!> ../../../docs_src/body_multiple_params/tutorial003_py310.py!}
- ```
+//// tab | Python 3.8+ non-Annotated
-=== "Python 3.8+ non-Annotated"
+/// tip
- !!! tip
- Prefer to use the `Annotated` version if possible.
+Prefer to use the `Annotated` version if possible.
- ```Python hl_lines="22"
- {!> ../../../docs_src/body_multiple_params/tutorial003.py!}
- ```
+///
+
+```Python hl_lines="22"
+{!> ../../../docs_src/body_multiple_params/tutorial003.py!}
+```
+
+////
In this case, **FastAPI** will expect a body like:
For example:
-=== "Python 3.10+"
+//// tab | Python 3.10+
+
+```Python hl_lines="27"
+{!> ../../../docs_src/body_multiple_params/tutorial004_an_py310.py!}
+```
+
+////
+
+//// tab | Python 3.9+
+
+```Python hl_lines="27"
+{!> ../../../docs_src/body_multiple_params/tutorial004_an_py39.py!}
+```
+
+////
+
+//// tab | Python 3.8+
+
+```Python hl_lines="28"
+{!> ../../../docs_src/body_multiple_params/tutorial004_an.py!}
+```
+
+////
+
+//// tab | Python 3.10+ non-Annotated
+
+/// tip
+
+Prefer to use the `Annotated` version if possible.
- ```Python hl_lines="27"
- {!> ../../../docs_src/body_multiple_params/tutorial004_an_py310.py!}
- ```
+///
-=== "Python 3.9+"
+```Python hl_lines="25"
+{!> ../../../docs_src/body_multiple_params/tutorial004_py310.py!}
+```
- ```Python hl_lines="27"
- {!> ../../../docs_src/body_multiple_params/tutorial004_an_py39.py!}
- ```
+////
-=== "Python 3.8+"
+//// tab | Python 3.8+ non-Annotated
- ```Python hl_lines="28"
- {!> ../../../docs_src/body_multiple_params/tutorial004_an.py!}
- ```
+/// tip
-=== "Python 3.10+ non-Annotated"
+Prefer to use the `Annotated` version if possible.
- !!! tip
- Prefer to use the `Annotated` version if possible.
+///
- ```Python hl_lines="25"
- {!> ../../../docs_src/body_multiple_params/tutorial004_py310.py!}
- ```
+```Python hl_lines="27"
+{!> ../../../docs_src/body_multiple_params/tutorial004.py!}
+```
-=== "Python 3.8+ non-Annotated"
+////
- !!! tip
- Prefer to use the `Annotated` version if possible.
+/// info
- ```Python hl_lines="27"
- {!> ../../../docs_src/body_multiple_params/tutorial004.py!}
- ```
+`Body` also has all the same extra validation and metadata parameters as `Query`,`Path` and others you will see later.
-!!! info
- `Body` also has all the same extra validation and metadata parameters as `Query`,`Path` and others you will see later.
+///
## Embed a single body parameter
as in:
-=== "Python 3.10+"
+//// tab | Python 3.10+
+
+```Python hl_lines="17"
+{!> ../../../docs_src/body_multiple_params/tutorial005_an_py310.py!}
+```
+
+////
+
+//// tab | Python 3.9+
+
+```Python hl_lines="17"
+{!> ../../../docs_src/body_multiple_params/tutorial005_an_py39.py!}
+```
+
+////
+
+//// tab | Python 3.8+
+
+```Python hl_lines="18"
+{!> ../../../docs_src/body_multiple_params/tutorial005_an.py!}
+```
+
+////
+
+//// tab | Python 3.10+ non-Annotated
- ```Python hl_lines="17"
- {!> ../../../docs_src/body_multiple_params/tutorial005_an_py310.py!}
- ```
+/// tip
-=== "Python 3.9+"
+Prefer to use the `Annotated` version if possible.
- ```Python hl_lines="17"
- {!> ../../../docs_src/body_multiple_params/tutorial005_an_py39.py!}
- ```
+///
-=== "Python 3.8+"
+```Python hl_lines="15"
+{!> ../../../docs_src/body_multiple_params/tutorial005_py310.py!}
+```
- ```Python hl_lines="18"
- {!> ../../../docs_src/body_multiple_params/tutorial005_an.py!}
- ```
+////
-=== "Python 3.10+ non-Annotated"
+//// tab | Python 3.8+ non-Annotated
- !!! tip
- Prefer to use the `Annotated` version if possible.
+/// tip
- ```Python hl_lines="15"
- {!> ../../../docs_src/body_multiple_params/tutorial005_py310.py!}
- ```
+Prefer to use the `Annotated` version if possible.
-=== "Python 3.8+ non-Annotated"
+///
- !!! tip
- Prefer to use the `Annotated` version if possible.
+```Python hl_lines="17"
+{!> ../../../docs_src/body_multiple_params/tutorial005.py!}
+```
- ```Python hl_lines="17"
- {!> ../../../docs_src/body_multiple_params/tutorial005.py!}
- ```
+////
In this case **FastAPI** will expect a body like:
You can define an attribute to be a subtype. For example, a Python `list`:
-=== "Python 3.10+"
+//// tab | Python 3.10+
- ```Python hl_lines="12"
- {!> ../../../docs_src/body_nested_models/tutorial001_py310.py!}
- ```
+```Python hl_lines="12"
+{!> ../../../docs_src/body_nested_models/tutorial001_py310.py!}
+```
+
+////
-=== "Python 3.8+"
+//// tab | Python 3.8+
+
+```Python hl_lines="14"
+{!> ../../../docs_src/body_nested_models/tutorial001.py!}
+```
- ```Python hl_lines="14"
- {!> ../../../docs_src/body_nested_models/tutorial001.py!}
- ```
+////
This will make `tags` be a list, although it doesn't declare the type of the elements of the list.
So, in our example, we can make `tags` be specifically a "list of strings":
-=== "Python 3.10+"
+//// tab | Python 3.10+
+
+```Python hl_lines="12"
+{!> ../../../docs_src/body_nested_models/tutorial002_py310.py!}
+```
+
+////
+
+//// tab | Python 3.9+
- ```Python hl_lines="12"
- {!> ../../../docs_src/body_nested_models/tutorial002_py310.py!}
- ```
+```Python hl_lines="14"
+{!> ../../../docs_src/body_nested_models/tutorial002_py39.py!}
+```
-=== "Python 3.9+"
+////
- ```Python hl_lines="14"
- {!> ../../../docs_src/body_nested_models/tutorial002_py39.py!}
- ```
+//// tab | Python 3.8+
-=== "Python 3.8+"
+```Python hl_lines="14"
+{!> ../../../docs_src/body_nested_models/tutorial002.py!}
+```
- ```Python hl_lines="14"
- {!> ../../../docs_src/body_nested_models/tutorial002.py!}
- ```
+////
## Set types
Then we can declare `tags` as a set of strings:
-=== "Python 3.10+"
+//// tab | Python 3.10+
+
+```Python hl_lines="12"
+{!> ../../../docs_src/body_nested_models/tutorial003_py310.py!}
+```
+
+////
- ```Python hl_lines="12"
- {!> ../../../docs_src/body_nested_models/tutorial003_py310.py!}
- ```
+//// tab | Python 3.9+
-=== "Python 3.9+"
+```Python hl_lines="14"
+{!> ../../../docs_src/body_nested_models/tutorial003_py39.py!}
+```
- ```Python hl_lines="14"
- {!> ../../../docs_src/body_nested_models/tutorial003_py39.py!}
- ```
+////
-=== "Python 3.8+"
+//// tab | Python 3.8+
- ```Python hl_lines="1 14"
- {!> ../../../docs_src/body_nested_models/tutorial003.py!}
- ```
+```Python hl_lines="1 14"
+{!> ../../../docs_src/body_nested_models/tutorial003.py!}
+```
+
+////
With this, even if you receive a request with duplicate data, it will be converted to a set of unique items.
For example, we can define an `Image` model:
-=== "Python 3.10+"
+//// tab | Python 3.10+
+
+```Python hl_lines="7-9"
+{!> ../../../docs_src/body_nested_models/tutorial004_py310.py!}
+```
+
+////
- ```Python hl_lines="7-9"
- {!> ../../../docs_src/body_nested_models/tutorial004_py310.py!}
- ```
+//// tab | Python 3.9+
-=== "Python 3.9+"
+```Python hl_lines="9-11"
+{!> ../../../docs_src/body_nested_models/tutorial004_py39.py!}
+```
+
+////
- ```Python hl_lines="9-11"
- {!> ../../../docs_src/body_nested_models/tutorial004_py39.py!}
- ```
+//// tab | Python 3.8+
-=== "Python 3.8+"
+```Python hl_lines="9-11"
+{!> ../../../docs_src/body_nested_models/tutorial004.py!}
+```
- ```Python hl_lines="9-11"
- {!> ../../../docs_src/body_nested_models/tutorial004.py!}
- ```
+////
### Use the submodel as a type
And then we can use it as the type of an attribute:
-=== "Python 3.10+"
+//// tab | Python 3.10+
- ```Python hl_lines="18"
- {!> ../../../docs_src/body_nested_models/tutorial004_py310.py!}
- ```
+```Python hl_lines="18"
+{!> ../../../docs_src/body_nested_models/tutorial004_py310.py!}
+```
-=== "Python 3.9+"
+////
- ```Python hl_lines="20"
- {!> ../../../docs_src/body_nested_models/tutorial004_py39.py!}
- ```
+//// tab | Python 3.9+
-=== "Python 3.8+"
+```Python hl_lines="20"
+{!> ../../../docs_src/body_nested_models/tutorial004_py39.py!}
+```
+
+////
- ```Python hl_lines="20"
- {!> ../../../docs_src/body_nested_models/tutorial004.py!}
- ```
+//// tab | Python 3.8+
+
+```Python hl_lines="20"
+{!> ../../../docs_src/body_nested_models/tutorial004.py!}
+```
+
+////
This would mean that **FastAPI** would expect a body similar to:
For example, as in the `Image` model we have a `url` field, we can declare it to be an instance of Pydantic's `HttpUrl` instead of a `str`:
-=== "Python 3.10+"
+//// tab | Python 3.10+
- ```Python hl_lines="2 8"
- {!> ../../../docs_src/body_nested_models/tutorial005_py310.py!}
- ```
+```Python hl_lines="2 8"
+{!> ../../../docs_src/body_nested_models/tutorial005_py310.py!}
+```
-=== "Python 3.9+"
+////
- ```Python hl_lines="4 10"
- {!> ../../../docs_src/body_nested_models/tutorial005_py39.py!}
- ```
+//// tab | Python 3.9+
-=== "Python 3.8+"
+```Python hl_lines="4 10"
+{!> ../../../docs_src/body_nested_models/tutorial005_py39.py!}
+```
- ```Python hl_lines="4 10"
- {!> ../../../docs_src/body_nested_models/tutorial005.py!}
- ```
+////
+
+//// tab | Python 3.8+
+
+```Python hl_lines="4 10"
+{!> ../../../docs_src/body_nested_models/tutorial005.py!}
+```
+
+////
The string will be checked to be a valid URL, and documented in JSON Schema / OpenAPI as such.
You can also use Pydantic models as subtypes of `list`, `set`, etc.:
-=== "Python 3.10+"
+//// tab | Python 3.10+
- ```Python hl_lines="18"
- {!> ../../../docs_src/body_nested_models/tutorial006_py310.py!}
- ```
+```Python hl_lines="18"
+{!> ../../../docs_src/body_nested_models/tutorial006_py310.py!}
+```
+
+////
-=== "Python 3.9+"
+//// tab | Python 3.9+
- ```Python hl_lines="20"
- {!> ../../../docs_src/body_nested_models/tutorial006_py39.py!}
- ```
+```Python hl_lines="20"
+{!> ../../../docs_src/body_nested_models/tutorial006_py39.py!}
+```
-=== "Python 3.8+"
+////
- ```Python hl_lines="20"
- {!> ../../../docs_src/body_nested_models/tutorial006.py!}
- ```
+//// tab | Python 3.8+
+
+```Python hl_lines="20"
+{!> ../../../docs_src/body_nested_models/tutorial006.py!}
+```
+
+////
This will expect (convert, validate, document, etc.) a JSON body like:
}
```
-!!! info
- Notice how the `images` key now has a list of image objects.
+/// info
+
+Notice how the `images` key now has a list of image objects.
+
+///
## Deeply nested models
You can define arbitrarily deeply nested models:
-=== "Python 3.10+"
+//// tab | Python 3.10+
+
+```Python hl_lines="7 12 18 21 25"
+{!> ../../../docs_src/body_nested_models/tutorial007_py310.py!}
+```
+
+////
- ```Python hl_lines="7 12 18 21 25"
- {!> ../../../docs_src/body_nested_models/tutorial007_py310.py!}
- ```
+//// tab | Python 3.9+
-=== "Python 3.9+"
+```Python hl_lines="9 14 20 23 27"
+{!> ../../../docs_src/body_nested_models/tutorial007_py39.py!}
+```
+
+////
+
+//// tab | Python 3.8+
+
+```Python hl_lines="9 14 20 23 27"
+{!> ../../../docs_src/body_nested_models/tutorial007.py!}
+```
- ```Python hl_lines="9 14 20 23 27"
- {!> ../../../docs_src/body_nested_models/tutorial007_py39.py!}
- ```
+////
-=== "Python 3.8+"
+/// info
- ```Python hl_lines="9 14 20 23 27"
- {!> ../../../docs_src/body_nested_models/tutorial007.py!}
- ```
+Notice how `Offer` has a list of `Item`s, which in turn have an optional list of `Image`s
-!!! info
- Notice how `Offer` has a list of `Item`s, which in turn have an optional list of `Image`s
+///
## Bodies of pure lists
as in:
-=== "Python 3.9+"
+//// tab | Python 3.9+
+
+```Python hl_lines="13"
+{!> ../../../docs_src/body_nested_models/tutorial008_py39.py!}
+```
- ```Python hl_lines="13"
- {!> ../../../docs_src/body_nested_models/tutorial008_py39.py!}
- ```
+////
-=== "Python 3.8+"
+//// tab | Python 3.8+
- ```Python hl_lines="15"
- {!> ../../../docs_src/body_nested_models/tutorial008.py!}
- ```
+```Python hl_lines="15"
+{!> ../../../docs_src/body_nested_models/tutorial008.py!}
+```
+
+////
## Editor support everywhere
In this case, you would accept any `dict` as long as it has `int` keys with `float` values:
-=== "Python 3.9+"
+//// tab | Python 3.9+
+
+```Python hl_lines="7"
+{!> ../../../docs_src/body_nested_models/tutorial009_py39.py!}
+```
+
+////
+
+//// tab | Python 3.8+
+
+```Python hl_lines="9"
+{!> ../../../docs_src/body_nested_models/tutorial009.py!}
+```
- ```Python hl_lines="7"
- {!> ../../../docs_src/body_nested_models/tutorial009_py39.py!}
- ```
+////
-=== "Python 3.8+"
+/// tip
- ```Python hl_lines="9"
- {!> ../../../docs_src/body_nested_models/tutorial009.py!}
- ```
+Keep in mind that JSON only supports `str` as keys.
-!!! tip
- Keep in mind that JSON only supports `str` as keys.
+But Pydantic has automatic data conversion.
- But Pydantic has automatic data conversion.
+This means that, even though your API clients can only send strings as keys, as long as those strings contain pure integers, Pydantic will convert them and validate them.
- This means that, even though your API clients can only send strings as keys, as long as those strings contain pure integers, Pydantic will convert them and validate them.
+And the `dict` you receive as `weights` will actually have `int` keys and `float` values.
- And the `dict` you receive as `weights` will actually have `int` keys and `float` values.
+///
## Recap
You can use the `jsonable_encoder` to convert the input data to data that can be stored as JSON (e.g. with a NoSQL database). For example, converting `datetime` to `str`.
-=== "Python 3.10+"
+//// tab | Python 3.10+
- ```Python hl_lines="28-33"
- {!> ../../../docs_src/body_updates/tutorial001_py310.py!}
- ```
+```Python hl_lines="28-33"
+{!> ../../../docs_src/body_updates/tutorial001_py310.py!}
+```
+
+////
-=== "Python 3.9+"
+//// tab | Python 3.9+
- ```Python hl_lines="30-35"
- {!> ../../../docs_src/body_updates/tutorial001_py39.py!}
- ```
+```Python hl_lines="30-35"
+{!> ../../../docs_src/body_updates/tutorial001_py39.py!}
+```
-=== "Python 3.8+"
+////
- ```Python hl_lines="30-35"
- {!> ../../../docs_src/body_updates/tutorial001.py!}
- ```
+//// tab | Python 3.8+
+
+```Python hl_lines="30-35"
+{!> ../../../docs_src/body_updates/tutorial001.py!}
+```
+
+////
`PUT` is used to receive data that should replace the existing data.
This means that you can send only the data that you want to update, leaving the rest intact.
-!!! note
- `PATCH` is less commonly used and known than `PUT`.
+/// note
+
+`PATCH` is less commonly used and known than `PUT`.
- And many teams use only `PUT`, even for partial updates.
+And many teams use only `PUT`, even for partial updates.
- You are **free** to use them however you want, **FastAPI** doesn't impose any restrictions.
+You are **free** to use them however you want, **FastAPI** doesn't impose any restrictions.
- But this guide shows you, more or less, how they are intended to be used.
+But this guide shows you, more or less, how they are intended to be used.
+
+///
### Using Pydantic's `exclude_unset` parameter
Like `item.model_dump(exclude_unset=True)`.
-!!! info
- In Pydantic v1 the method was called `.dict()`, it was deprecated (but still supported) in Pydantic v2, and renamed to `.model_dump()`.
+/// 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.
+The examples here use `.dict()` for compatibility with Pydantic v1, but you should use `.model_dump()` instead if you can use Pydantic v2.
+
+///
That would generate a `dict` with only the data that was set when creating the `item` model, excluding default values.
Then you can use this to generate a `dict` with only the data that was set (sent in the request), omitting default values:
-=== "Python 3.10+"
+//// tab | Python 3.10+
+
+```Python hl_lines="32"
+{!> ../../../docs_src/body_updates/tutorial002_py310.py!}
+```
+
+////
- ```Python hl_lines="32"
- {!> ../../../docs_src/body_updates/tutorial002_py310.py!}
- ```
+//// tab | Python 3.9+
-=== "Python 3.9+"
+```Python hl_lines="34"
+{!> ../../../docs_src/body_updates/tutorial002_py39.py!}
+```
+
+////
- ```Python hl_lines="34"
- {!> ../../../docs_src/body_updates/tutorial002_py39.py!}
- ```
+//// tab | Python 3.8+
-=== "Python 3.8+"
+```Python hl_lines="34"
+{!> ../../../docs_src/body_updates/tutorial002.py!}
+```
- ```Python hl_lines="34"
- {!> ../../../docs_src/body_updates/tutorial002.py!}
- ```
+////
### Using Pydantic's `update` parameter
Now, you can create a copy of the existing model using `.model_copy()`, and pass the `update` parameter with a `dict` containing the data to update.
-!!! info
- In Pydantic v1 the method was called `.copy()`, it was deprecated (but still supported) in Pydantic v2, and renamed to `.model_copy()`.
+/// info
+
+In Pydantic v1 the method was called `.copy()`, it was deprecated (but still supported) in Pydantic v2, and renamed to `.model_copy()`.
- The examples here use `.copy()` for compatibility with Pydantic v1, but you should use `.model_copy()` instead if you can use Pydantic v2.
+The examples here use `.copy()` for compatibility with Pydantic v1, but you should use `.model_copy()` instead if you can use Pydantic v2.
+
+///
Like `stored_item_model.model_copy(update=update_data)`:
-=== "Python 3.10+"
+//// tab | Python 3.10+
- ```Python hl_lines="33"
- {!> ../../../docs_src/body_updates/tutorial002_py310.py!}
- ```
+```Python hl_lines="33"
+{!> ../../../docs_src/body_updates/tutorial002_py310.py!}
+```
-=== "Python 3.9+"
+////
- ```Python hl_lines="35"
- {!> ../../../docs_src/body_updates/tutorial002_py39.py!}
- ```
+//// tab | Python 3.9+
-=== "Python 3.8+"
+```Python hl_lines="35"
+{!> ../../../docs_src/body_updates/tutorial002_py39.py!}
+```
- ```Python hl_lines="35"
- {!> ../../../docs_src/body_updates/tutorial002.py!}
- ```
+////
+
+//// tab | Python 3.8+
+
+```Python hl_lines="35"
+{!> ../../../docs_src/body_updates/tutorial002.py!}
+```
+
+////
### Partial updates recap
* Save the data to your DB.
* Return the updated model.
-=== "Python 3.10+"
+//// tab | Python 3.10+
+
+```Python hl_lines="28-35"
+{!> ../../../docs_src/body_updates/tutorial002_py310.py!}
+```
+
+////
+
+//// tab | Python 3.9+
+
+```Python hl_lines="30-37"
+{!> ../../../docs_src/body_updates/tutorial002_py39.py!}
+```
+
+////
+
+//// tab | Python 3.8+
+
+```Python hl_lines="30-37"
+{!> ../../../docs_src/body_updates/tutorial002.py!}
+```
- ```Python hl_lines="28-35"
- {!> ../../../docs_src/body_updates/tutorial002_py310.py!}
- ```
+////
-=== "Python 3.9+"
+/// tip
- ```Python hl_lines="30-37"
- {!> ../../../docs_src/body_updates/tutorial002_py39.py!}
- ```
+You can actually use this same technique with an HTTP `PUT` operation.
-=== "Python 3.8+"
+But the example here uses `PATCH` because it was created for these use cases.
- ```Python hl_lines="30-37"
- {!> ../../../docs_src/body_updates/tutorial002.py!}
- ```
+///
-!!! tip
- You can actually use this same technique with an HTTP `PUT` operation.
+/// note
- But the example here uses `PATCH` because it was created for these use cases.
+Notice that the input model is still validated.
-!!! note
- Notice that the input model is still validated.
+So, if you want to receive partial updates that can omit all the attributes, you need to have a model with all the attributes marked as optional (with default values or `None`).
- So, if you want to receive partial updates that can omit all the attributes, you need to have a model with all the attributes marked as optional (with default values or `None`).
+To distinguish from the models with all optional values for **updates** and models with required values for **creation**, you can use the ideas described in [Extra Models](extra-models.md){.internal-link target=_blank}.
- To distinguish from the models with all optional values for **updates** and models with required values for **creation**, you can use the ideas described in [Extra Models](extra-models.md){.internal-link target=_blank}.
+///
To declare a **request** body, you use <a href="https://docs.pydantic.dev/" class="external-link" target="_blank">Pydantic</a> models with all their power and benefits.
-!!! info
- To send data, you should use one of: `POST` (the more common), `PUT`, `DELETE` or `PATCH`.
+/// info
- Sending a body with a `GET` request has an undefined behavior in the specifications, nevertheless, it is supported by FastAPI, only for very complex/extreme use cases.
+To send data, you should use one of: `POST` (the more common), `PUT`, `DELETE` or `PATCH`.
- As it is discouraged, the interactive docs with Swagger UI won't show the documentation for the body when using `GET`, and proxies in the middle might not support it.
+Sending a body with a `GET` request has an undefined behavior in the specifications, nevertheless, it is supported by FastAPI, only for very complex/extreme use cases.
+
+As it is discouraged, the interactive docs with Swagger UI won't show the documentation for the body when using `GET`, and proxies in the middle might not support it.
+
+///
## Import Pydantic's `BaseModel`
First, you need to import `BaseModel` from `pydantic`:
-=== "Python 3.10+"
+//// tab | Python 3.10+
+
+```Python hl_lines="2"
+{!> ../../../docs_src/body/tutorial001_py310.py!}
+```
+
+////
- ```Python hl_lines="2"
- {!> ../../../docs_src/body/tutorial001_py310.py!}
- ```
+//// tab | Python 3.8+
-=== "Python 3.8+"
+```Python hl_lines="4"
+{!> ../../../docs_src/body/tutorial001.py!}
+```
- ```Python hl_lines="4"
- {!> ../../../docs_src/body/tutorial001.py!}
- ```
+////
## Create your data model
Use standard Python types for all the attributes:
-=== "Python 3.10+"
+//// tab | Python 3.10+
- ```Python hl_lines="5-9"
- {!> ../../../docs_src/body/tutorial001_py310.py!}
- ```
+```Python hl_lines="5-9"
+{!> ../../../docs_src/body/tutorial001_py310.py!}
+```
-=== "Python 3.8+"
+////
- ```Python hl_lines="7-11"
- {!> ../../../docs_src/body/tutorial001.py!}
- ```
+//// tab | Python 3.8+
+
+```Python hl_lines="7-11"
+{!> ../../../docs_src/body/tutorial001.py!}
+```
+
+////
The same as when declaring query parameters, when a model attribute has a default value, it is not required. Otherwise, it is required. Use `None` to make it just optional.
To add it to your *path operation*, declare it the same way you declared path and query parameters:
-=== "Python 3.10+"
+//// tab | Python 3.10+
- ```Python hl_lines="16"
- {!> ../../../docs_src/body/tutorial001_py310.py!}
- ```
+```Python hl_lines="16"
+{!> ../../../docs_src/body/tutorial001_py310.py!}
+```
-=== "Python 3.8+"
+////
- ```Python hl_lines="18"
- {!> ../../../docs_src/body/tutorial001.py!}
- ```
+//// tab | Python 3.8+
+
+```Python hl_lines="18"
+{!> ../../../docs_src/body/tutorial001.py!}
+```
+
+////
...and declare its type as the model you created, `Item`.
<img src="/img/tutorial/body/image05.png">
-!!! tip
- If you use <a href="https://www.jetbrains.com/pycharm/" class="external-link" target="_blank">PyCharm</a> as your editor, you can use the <a href="https://github.com/koxudaxi/pydantic-pycharm-plugin/" class="external-link" target="_blank">Pydantic PyCharm Plugin</a>.
+/// tip
+
+If you use <a href="https://www.jetbrains.com/pycharm/" class="external-link" target="_blank">PyCharm</a> as your editor, you can use the <a href="https://github.com/koxudaxi/pydantic-pycharm-plugin/" class="external-link" target="_blank">Pydantic PyCharm Plugin</a>.
- It improves editor support for Pydantic models, with:
+It improves editor support for Pydantic models, with:
- * auto-completion
- * type checks
- * refactoring
- * searching
- * inspections
+* auto-completion
+* type checks
+* refactoring
+* searching
+* inspections
+
+///
## Use the model
Inside of the function, you can access all the attributes of the model object directly:
-=== "Python 3.10+"
+//// tab | Python 3.10+
+
+```Python hl_lines="19"
+{!> ../../../docs_src/body/tutorial002_py310.py!}
+```
+
+////
- ```Python hl_lines="19"
- {!> ../../../docs_src/body/tutorial002_py310.py!}
- ```
+//// tab | Python 3.8+
-=== "Python 3.8+"
+```Python hl_lines="21"
+{!> ../../../docs_src/body/tutorial002.py!}
+```
- ```Python hl_lines="21"
- {!> ../../../docs_src/body/tutorial002.py!}
- ```
+////
## Request body + path parameters
**FastAPI** will recognize that the function parameters that match path parameters should be **taken from the path**, and that function parameters that are declared to be Pydantic models should be **taken from the request body**.
-=== "Python 3.10+"
+//// tab | Python 3.10+
+
+```Python hl_lines="15-16"
+{!> ../../../docs_src/body/tutorial003_py310.py!}
+```
- ```Python hl_lines="15-16"
- {!> ../../../docs_src/body/tutorial003_py310.py!}
- ```
+////
-=== "Python 3.8+"
+//// tab | Python 3.8+
- ```Python hl_lines="17-18"
- {!> ../../../docs_src/body/tutorial003.py!}
- ```
+```Python hl_lines="17-18"
+{!> ../../../docs_src/body/tutorial003.py!}
+```
+
+////
## Request body + path + query parameters
**FastAPI** will recognize each of them and take the data from the correct place.
-=== "Python 3.10+"
+//// tab | Python 3.10+
+
+```Python hl_lines="16"
+{!> ../../../docs_src/body/tutorial004_py310.py!}
+```
- ```Python hl_lines="16"
- {!> ../../../docs_src/body/tutorial004_py310.py!}
- ```
+////
-=== "Python 3.8+"
+//// tab | Python 3.8+
- ```Python hl_lines="18"
- {!> ../../../docs_src/body/tutorial004.py!}
- ```
+```Python hl_lines="18"
+{!> ../../../docs_src/body/tutorial004.py!}
+```
+
+////
The function parameters will be recognized as follows:
* If the parameter is of a **singular type** (like `int`, `float`, `str`, `bool`, etc) it will be interpreted as a **query** parameter.
* If the parameter is declared to be of the type of a **Pydantic model**, it will be interpreted as a request **body**.
-!!! note
- FastAPI will know that the value of `q` is not required because of the default value `= None`.
+/// note
+
+FastAPI will know that the value of `q` is not required because of the default value `= None`.
+
+The `Union` in `Union[str, None]` is not used by FastAPI, but will allow your editor to give you better support and detect errors.
- The `Union` in `Union[str, None]` is not used by FastAPI, but will allow your editor to give you better support and detect errors.
+///
## Without Pydantic
First import `Cookie`:
-=== "Python 3.10+"
+//// tab | Python 3.10+
- ```Python hl_lines="3"
- {!> ../../../docs_src/cookie_params/tutorial001_an_py310.py!}
- ```
+```Python hl_lines="3"
+{!> ../../../docs_src/cookie_params/tutorial001_an_py310.py!}
+```
-=== "Python 3.9+"
+////
- ```Python hl_lines="3"
- {!> ../../../docs_src/cookie_params/tutorial001_an_py39.py!}
- ```
+//// tab | Python 3.9+
-=== "Python 3.8+"
+```Python hl_lines="3"
+{!> ../../../docs_src/cookie_params/tutorial001_an_py39.py!}
+```
- ```Python hl_lines="3"
- {!> ../../../docs_src/cookie_params/tutorial001_an.py!}
- ```
+////
-=== "Python 3.10+ non-Annotated"
+//// tab | Python 3.8+
- !!! tip
- Prefer to use the `Annotated` version if possible.
+```Python hl_lines="3"
+{!> ../../../docs_src/cookie_params/tutorial001_an.py!}
+```
- ```Python hl_lines="1"
- {!> ../../../docs_src/cookie_params/tutorial001_py310.py!}
- ```
+////
-=== "Python 3.8+ non-Annotated"
+//// tab | Python 3.10+ non-Annotated
- !!! tip
- Prefer to use the `Annotated` version if possible.
+/// tip
- ```Python hl_lines="3"
- {!> ../../../docs_src/cookie_params/tutorial001.py!}
- ```
+Prefer to use the `Annotated` version if possible.
+
+///
+
+```Python hl_lines="1"
+{!> ../../../docs_src/cookie_params/tutorial001_py310.py!}
+```
+
+////
+
+//// tab | Python 3.8+ non-Annotated
+
+/// tip
+
+Prefer to use the `Annotated` version if possible.
+
+///
+
+```Python hl_lines="3"
+{!> ../../../docs_src/cookie_params/tutorial001.py!}
+```
+
+////
## Declare `Cookie` parameters
The first value is the default value, you can pass all the extra validation or annotation parameters:
-=== "Python 3.10+"
+//// tab | Python 3.10+
+
+```Python hl_lines="9"
+{!> ../../../docs_src/cookie_params/tutorial001_an_py310.py!}
+```
+
+////
+
+//// tab | Python 3.9+
+
+```Python hl_lines="9"
+{!> ../../../docs_src/cookie_params/tutorial001_an_py39.py!}
+```
+
+////
+
+//// tab | Python 3.8+
+
+```Python hl_lines="10"
+{!> ../../../docs_src/cookie_params/tutorial001_an.py!}
+```
+
+////
+
+//// tab | Python 3.10+ non-Annotated
+
+/// tip
+
+Prefer to use the `Annotated` version if possible.
+
+///
+
+```Python hl_lines="7"
+{!> ../../../docs_src/cookie_params/tutorial001_py310.py!}
+```
- ```Python hl_lines="9"
- {!> ../../../docs_src/cookie_params/tutorial001_an_py310.py!}
- ```
+////
-=== "Python 3.9+"
+//// tab | Python 3.8+ non-Annotated
- ```Python hl_lines="9"
- {!> ../../../docs_src/cookie_params/tutorial001_an_py39.py!}
- ```
+/// tip
-=== "Python 3.8+"
+Prefer to use the `Annotated` version if possible.
- ```Python hl_lines="10"
- {!> ../../../docs_src/cookie_params/tutorial001_an.py!}
- ```
+///
-=== "Python 3.10+ non-Annotated"
+```Python hl_lines="9"
+{!> ../../../docs_src/cookie_params/tutorial001.py!}
+```
- !!! tip
- Prefer to use the `Annotated` version if possible.
+////
- ```Python hl_lines="7"
- {!> ../../../docs_src/cookie_params/tutorial001_py310.py!}
- ```
+/// note | "Technical Details"
-=== "Python 3.8+ non-Annotated"
+`Cookie` is a "sister" class of `Path` and `Query`. It also inherits from the same common `Param` class.
- !!! tip
- Prefer to use the `Annotated` version if possible.
+But remember that when you import `Query`, `Path`, `Cookie` and others from `fastapi`, those are actually functions that return special classes.
- ```Python hl_lines="9"
- {!> ../../../docs_src/cookie_params/tutorial001.py!}
- ```
+///
-!!! note "Technical Details"
- `Cookie` is a "sister" class of `Path` and `Query`. It also inherits from the same common `Param` class.
+/// info
- But remember that when you import `Query`, `Path`, `Cookie` and others from `fastapi`, those are actually functions that return special classes.
+To declare cookies, you need to use `Cookie`, because otherwise the parameters would be interpreted as query parameters.
-!!! info
- To declare cookies, you need to use `Cookie`, because otherwise the parameters would be interpreted as query parameters.
+///
## Recap
For more info about <abbr title="Cross-Origin Resource Sharing">CORS</abbr>, check the <a href="https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS" class="external-link" target="_blank">Mozilla CORS documentation</a>.
-!!! note "Technical Details"
- You could also use `from starlette.middleware.cors import CORSMiddleware`.
+/// note | "Technical Details"
- **FastAPI** provides several middlewares in `fastapi.middleware` just as a convenience for you, the developer. But most of the available middlewares come directly from Starlette.
+You could also use `from starlette.middleware.cors import CORSMiddleware`.
+
+**FastAPI** provides several middlewares in `fastapi.middleware` just as a convenience for you, the developer. But most of the available middlewares come directly from Starlette.
+
+///
will not be executed.
-!!! info
- For more information, check <a href="https://docs.python.org/3/library/__main__.html" class="external-link" target="_blank">the official Python docs</a>.
+/// info
+
+For more information, check <a href="https://docs.python.org/3/library/__main__.html" class="external-link" target="_blank">the official Python docs</a>.
+
+///
## Run your code with your debugger
In the previous example, we were returning a `dict` from our dependency ("dependable"):
-=== "Python 3.10+"
+//// tab | Python 3.10+
- ```Python hl_lines="9"
- {!> ../../../docs_src/dependencies/tutorial001_an_py310.py!}
- ```
+```Python hl_lines="9"
+{!> ../../../docs_src/dependencies/tutorial001_an_py310.py!}
+```
+
+////
+
+//// tab | Python 3.9+
+
+```Python hl_lines="11"
+{!> ../../../docs_src/dependencies/tutorial001_an_py39.py!}
+```
-=== "Python 3.9+"
+////
- ```Python hl_lines="11"
- {!> ../../../docs_src/dependencies/tutorial001_an_py39.py!}
- ```
+//// tab | Python 3.8+
-=== "Python 3.8+"
+```Python hl_lines="12"
+{!> ../../../docs_src/dependencies/tutorial001_an.py!}
+```
+
+////
+
+//// tab | Python 3.10+ non-Annotated
- ```Python hl_lines="12"
- {!> ../../../docs_src/dependencies/tutorial001_an.py!}
- ```
+/// tip
-=== "Python 3.10+ non-Annotated"
+Prefer to use the `Annotated` version if possible.
- !!! tip
- Prefer to use the `Annotated` version if possible.
+///
+
+```Python hl_lines="7"
+{!> ../../../docs_src/dependencies/tutorial001_py310.py!}
+```
- ```Python hl_lines="7"
- {!> ../../../docs_src/dependencies/tutorial001_py310.py!}
- ```
+////
-=== "Python 3.8+ non-Annotated"
+//// tab | Python 3.8+ non-Annotated
- !!! tip
- Prefer to use the `Annotated` version if possible.
+/// tip
- ```Python hl_lines="11"
- {!> ../../../docs_src/dependencies/tutorial001.py!}
- ```
+Prefer to use the `Annotated` version if possible.
+
+///
+
+```Python hl_lines="11"
+{!> ../../../docs_src/dependencies/tutorial001.py!}
+```
+
+////
But then we get a `dict` in the parameter `commons` of the *path operation function*.
Then, we can change the dependency "dependable" `common_parameters` from above to the class `CommonQueryParams`:
-=== "Python 3.10+"
+//// tab | Python 3.10+
- ```Python hl_lines="11-15"
- {!> ../../../docs_src/dependencies/tutorial002_an_py310.py!}
- ```
+```Python hl_lines="11-15"
+{!> ../../../docs_src/dependencies/tutorial002_an_py310.py!}
+```
-=== "Python 3.9+"
+////
- ```Python hl_lines="11-15"
- {!> ../../../docs_src/dependencies/tutorial002_an_py39.py!}
- ```
+//// tab | Python 3.9+
-=== "Python 3.8+"
+```Python hl_lines="11-15"
+{!> ../../../docs_src/dependencies/tutorial002_an_py39.py!}
+```
+
+////
- ```Python hl_lines="12-16"
- {!> ../../../docs_src/dependencies/tutorial002_an.py!}
- ```
+//// tab | Python 3.8+
-=== "Python 3.10+ non-Annotated"
+```Python hl_lines="12-16"
+{!> ../../../docs_src/dependencies/tutorial002_an.py!}
+```
- !!! tip
- Prefer to use the `Annotated` version if possible.
+////
- ```Python hl_lines="9-13"
- {!> ../../../docs_src/dependencies/tutorial002_py310.py!}
- ```
+//// tab | Python 3.10+ non-Annotated
-=== "Python 3.8+ non-Annotated"
+/// tip
- !!! tip
- Prefer to use the `Annotated` version if possible.
+Prefer to use the `Annotated` version if possible.
- ```Python hl_lines="11-15"
- {!> ../../../docs_src/dependencies/tutorial002.py!}
- ```
+///
+
+```Python hl_lines="9-13"
+{!> ../../../docs_src/dependencies/tutorial002_py310.py!}
+```
+
+////
+
+//// tab | Python 3.8+ non-Annotated
+
+/// tip
+
+Prefer to use the `Annotated` version if possible.
+
+///
+
+```Python hl_lines="11-15"
+{!> ../../../docs_src/dependencies/tutorial002.py!}
+```
+
+////
Pay attention to the `__init__` method used to create the instance of the class:
-=== "Python 3.10+"
+//// tab | Python 3.10+
+
+```Python hl_lines="12"
+{!> ../../../docs_src/dependencies/tutorial002_an_py310.py!}
+```
+
+////
+
+//// tab | Python 3.9+
+
+```Python hl_lines="12"
+{!> ../../../docs_src/dependencies/tutorial002_an_py39.py!}
+```
+
+////
+
+//// tab | Python 3.8+
+
+```Python hl_lines="13"
+{!> ../../../docs_src/dependencies/tutorial002_an.py!}
+```
+
+////
- ```Python hl_lines="12"
- {!> ../../../docs_src/dependencies/tutorial002_an_py310.py!}
- ```
+//// tab | Python 3.10+ non-Annotated
-=== "Python 3.9+"
+/// tip
- ```Python hl_lines="12"
- {!> ../../../docs_src/dependencies/tutorial002_an_py39.py!}
- ```
+Prefer to use the `Annotated` version if possible.
-=== "Python 3.8+"
+///
- ```Python hl_lines="13"
- {!> ../../../docs_src/dependencies/tutorial002_an.py!}
- ```
+```Python hl_lines="10"
+{!> ../../../docs_src/dependencies/tutorial002_py310.py!}
+```
-=== "Python 3.10+ non-Annotated"
+////
- !!! tip
- Prefer to use the `Annotated` version if possible.
+//// tab | Python 3.8+ non-Annotated
- ```Python hl_lines="10"
- {!> ../../../docs_src/dependencies/tutorial002_py310.py!}
- ```
+/// tip
-=== "Python 3.8+ non-Annotated"
+Prefer to use the `Annotated` version if possible.
- !!! tip
- Prefer to use the `Annotated` version if possible.
+///
+
+```Python hl_lines="12"
+{!> ../../../docs_src/dependencies/tutorial002.py!}
+```
- ```Python hl_lines="12"
- {!> ../../../docs_src/dependencies/tutorial002.py!}
- ```
+////
...it has the same parameters as our previous `common_parameters`:
-=== "Python 3.10+"
+//// tab | Python 3.10+
- ```Python hl_lines="8"
- {!> ../../../docs_src/dependencies/tutorial001_an_py310.py!}
- ```
+```Python hl_lines="8"
+{!> ../../../docs_src/dependencies/tutorial001_an_py310.py!}
+```
+
+////
-=== "Python 3.9+"
+//// tab | Python 3.9+
- ```Python hl_lines="9"
- {!> ../../../docs_src/dependencies/tutorial001_an_py39.py!}
- ```
+```Python hl_lines="9"
+{!> ../../../docs_src/dependencies/tutorial001_an_py39.py!}
+```
-=== "Python 3.8+"
+////
- ```Python hl_lines="10"
- {!> ../../../docs_src/dependencies/tutorial001_an.py!}
- ```
+//// tab | Python 3.8+
+
+```Python hl_lines="10"
+{!> ../../../docs_src/dependencies/tutorial001_an.py!}
+```
-=== "Python 3.10+ non-Annotated"
+////
- !!! tip
- Prefer to use the `Annotated` version if possible.
+//// tab | Python 3.10+ non-Annotated
- ```Python hl_lines="6"
- {!> ../../../docs_src/dependencies/tutorial001_py310.py!}
- ```
+/// tip
-=== "Python 3.8+ non-Annotated"
+Prefer to use the `Annotated` version if possible.
- !!! tip
- Prefer to use the `Annotated` version if possible.
+///
+
+```Python hl_lines="6"
+{!> ../../../docs_src/dependencies/tutorial001_py310.py!}
+```
+
+////
+
+//// tab | Python 3.8+ non-Annotated
+
+/// tip
+
+Prefer to use the `Annotated` version if possible.
+
+///
+
+```Python hl_lines="9"
+{!> ../../../docs_src/dependencies/tutorial001.py!}
+```
- ```Python hl_lines="9"
- {!> ../../../docs_src/dependencies/tutorial001.py!}
- ```
+////
Those parameters are what **FastAPI** will use to "solve" the dependency.
Now you can declare your dependency using this class.
-=== "Python 3.10+"
+//// tab | Python 3.10+
- ```Python hl_lines="19"
- {!> ../../../docs_src/dependencies/tutorial002_an_py310.py!}
- ```
+```Python hl_lines="19"
+{!> ../../../docs_src/dependencies/tutorial002_an_py310.py!}
+```
+
+////
+
+//// tab | Python 3.9+
+
+```Python hl_lines="19"
+{!> ../../../docs_src/dependencies/tutorial002_an_py39.py!}
+```
+
+////
+
+//// tab | Python 3.8+
+
+```Python hl_lines="20"
+{!> ../../../docs_src/dependencies/tutorial002_an.py!}
+```
-=== "Python 3.9+"
+////
- ```Python hl_lines="19"
- {!> ../../../docs_src/dependencies/tutorial002_an_py39.py!}
- ```
+//// tab | Python 3.10+ non-Annotated
-=== "Python 3.8+"
+/// tip
- ```Python hl_lines="20"
- {!> ../../../docs_src/dependencies/tutorial002_an.py!}
- ```
+Prefer to use the `Annotated` version if possible.
-=== "Python 3.10+ non-Annotated"
+///
- !!! tip
- Prefer to use the `Annotated` version if possible.
+```Python hl_lines="17"
+{!> ../../../docs_src/dependencies/tutorial002_py310.py!}
+```
+
+////
+
+//// tab | Python 3.8+ non-Annotated
- ```Python hl_lines="17"
- {!> ../../../docs_src/dependencies/tutorial002_py310.py!}
- ```
+/// tip
-=== "Python 3.8+ non-Annotated"
+Prefer to use the `Annotated` version if possible.
- !!! tip
- Prefer to use the `Annotated` version if possible.
+///
+
+```Python hl_lines="19"
+{!> ../../../docs_src/dependencies/tutorial002.py!}
+```
- ```Python hl_lines="19"
- {!> ../../../docs_src/dependencies/tutorial002.py!}
- ```
+////
**FastAPI** calls the `CommonQueryParams` class. This creates an "instance" of that class and the instance will be passed as the parameter `commons` to your function.
Notice how we write `CommonQueryParams` twice in the above code:
-=== "Python 3.8+"
+//// tab | Python 3.8+
+
+```Python
+commons: Annotated[CommonQueryParams, Depends(CommonQueryParams)]
+```
+
+////
- ```Python
- commons: Annotated[CommonQueryParams, Depends(CommonQueryParams)]
- ```
+//// tab | Python 3.8+ non-Annotated
-=== "Python 3.8+ non-Annotated"
+/// tip
- !!! tip
- Prefer to use the `Annotated` version if possible.
+Prefer to use the `Annotated` version if possible.
- ```Python
- commons: CommonQueryParams = Depends(CommonQueryParams)
- ```
+///
+
+```Python
+commons: CommonQueryParams = Depends(CommonQueryParams)
+```
+
+////
The last `CommonQueryParams`, in:
In this case, the first `CommonQueryParams`, in:
-=== "Python 3.8+"
+//// tab | Python 3.8+
+
+```Python
+commons: Annotated[CommonQueryParams, ...
+```
+
+////
- ```Python
- commons: Annotated[CommonQueryParams, ...
- ```
+//// tab | Python 3.8+ non-Annotated
-=== "Python 3.8+ non-Annotated"
+/// tip
- !!! tip
- Prefer to use the `Annotated` version if possible.
+Prefer to use the `Annotated` version if possible.
- ```Python
- commons: CommonQueryParams ...
- ```
+///
+
+```Python
+commons: CommonQueryParams ...
+```
+
+////
...doesn't have any special meaning for **FastAPI**. FastAPI won't use it for data conversion, validation, etc. (as it is using the `Depends(CommonQueryParams)` for that).
You could actually write just:
-=== "Python 3.8+"
+//// tab | Python 3.8+
+
+```Python
+commons: Annotated[Any, Depends(CommonQueryParams)]
+```
- ```Python
- commons: Annotated[Any, Depends(CommonQueryParams)]
- ```
+////
-=== "Python 3.8+ non-Annotated"
+//// tab | Python 3.8+ non-Annotated
- !!! tip
- Prefer to use the `Annotated` version if possible.
+/// tip
- ```Python
- commons = Depends(CommonQueryParams)
- ```
+Prefer to use the `Annotated` version if possible.
+
+///
+
+```Python
+commons = Depends(CommonQueryParams)
+```
+
+////
...as in:
-=== "Python 3.10+"
+//// tab | Python 3.10+
+
+```Python hl_lines="19"
+{!> ../../../docs_src/dependencies/tutorial003_an_py310.py!}
+```
+
+////
+
+//// tab | Python 3.9+
+
+```Python hl_lines="19"
+{!> ../../../docs_src/dependencies/tutorial003_an_py39.py!}
+```
+
+////
+
+//// tab | Python 3.8+
- ```Python hl_lines="19"
- {!> ../../../docs_src/dependencies/tutorial003_an_py310.py!}
- ```
+```Python hl_lines="20"
+{!> ../../../docs_src/dependencies/tutorial003_an.py!}
+```
+
+////
-=== "Python 3.9+"
+//// tab | Python 3.10+ non-Annotated
- ```Python hl_lines="19"
- {!> ../../../docs_src/dependencies/tutorial003_an_py39.py!}
- ```
+/// tip
-=== "Python 3.8+"
+Prefer to use the `Annotated` version if possible.
- ```Python hl_lines="20"
- {!> ../../../docs_src/dependencies/tutorial003_an.py!}
- ```
+///
-=== "Python 3.10+ non-Annotated"
+```Python hl_lines="17"
+{!> ../../../docs_src/dependencies/tutorial003_py310.py!}
+```
- !!! tip
- Prefer to use the `Annotated` version if possible.
+////
- ```Python hl_lines="17"
- {!> ../../../docs_src/dependencies/tutorial003_py310.py!}
- ```
+//// tab | Python 3.8+ non-Annotated
-=== "Python 3.8+ non-Annotated"
+/// tip
- !!! tip
- Prefer to use the `Annotated` version if possible.
+Prefer to use the `Annotated` version if possible.
- ```Python hl_lines="19"
- {!> ../../../docs_src/dependencies/tutorial003.py!}
- ```
+///
+
+```Python hl_lines="19"
+{!> ../../../docs_src/dependencies/tutorial003.py!}
+```
+
+////
But declaring the type is encouraged as that way your editor will know what will be passed as the parameter `commons`, and then it can help you with code completion, type checks, etc:
But you see that we are having some code repetition here, writing `CommonQueryParams` twice:
-=== "Python 3.8+"
+//// tab | Python 3.8+
+
+```Python
+commons: Annotated[CommonQueryParams, Depends(CommonQueryParams)]
+```
+
+////
+
+//// tab | Python 3.8+ non-Annotated
+
+/// tip
- ```Python
- commons: Annotated[CommonQueryParams, Depends(CommonQueryParams)]
- ```
+Prefer to use the `Annotated` version if possible.
-=== "Python 3.8+ non-Annotated"
+///
- !!! tip
- Prefer to use the `Annotated` version if possible.
+```Python
+commons: CommonQueryParams = Depends(CommonQueryParams)
+```
- ```Python
- commons: CommonQueryParams = Depends(CommonQueryParams)
- ```
+////
**FastAPI** provides a shortcut for these cases, in where the dependency is *specifically* a class that **FastAPI** will "call" to create an instance of the class itself.
Instead of writing:
-=== "Python 3.8+"
+//// tab | Python 3.8+
- ```Python
- commons: Annotated[CommonQueryParams, Depends(CommonQueryParams)]
- ```
+```Python
+commons: Annotated[CommonQueryParams, Depends(CommonQueryParams)]
+```
+
+////
-=== "Python 3.8+ non-Annotated"
+//// tab | Python 3.8+ non-Annotated
- !!! tip
- Prefer to use the `Annotated` version if possible.
+/// tip
- ```Python
- commons: CommonQueryParams = Depends(CommonQueryParams)
- ```
+Prefer to use the `Annotated` version if possible.
+
+///
+
+```Python
+commons: CommonQueryParams = Depends(CommonQueryParams)
+```
+
+////
...you write:
-=== "Python 3.8+"
+//// tab | Python 3.8+
- ```Python
- commons: Annotated[CommonQueryParams, Depends()]
- ```
+```Python
+commons: Annotated[CommonQueryParams, Depends()]
+```
-=== "Python 3.8 non-Annotated"
+////
- !!! tip
- Prefer to use the `Annotated` version if possible.
+//// tab | Python 3.8 non-Annotated
- ```Python
- commons: CommonQueryParams = Depends()
- ```
+/// tip
+
+Prefer to use the `Annotated` version if possible.
+
+///
+
+```Python
+commons: CommonQueryParams = Depends()
+```
+
+////
You declare the dependency as the type of the parameter, and you use `Depends()` without any parameter, instead of having to write the full class *again* inside of `Depends(CommonQueryParams)`.
The same example would then look like:
-=== "Python 3.10+"
+//// tab | Python 3.10+
+
+```Python hl_lines="19"
+{!> ../../../docs_src/dependencies/tutorial004_an_py310.py!}
+```
+
+////
+
+//// tab | Python 3.9+
+
+```Python hl_lines="19"
+{!> ../../../docs_src/dependencies/tutorial004_an_py39.py!}
+```
+
+////
- ```Python hl_lines="19"
- {!> ../../../docs_src/dependencies/tutorial004_an_py310.py!}
- ```
+//// tab | Python 3.8+
-=== "Python 3.9+"
+```Python hl_lines="20"
+{!> ../../../docs_src/dependencies/tutorial004_an.py!}
+```
+
+////
- ```Python hl_lines="19"
- {!> ../../../docs_src/dependencies/tutorial004_an_py39.py!}
- ```
+//// tab | Python 3.10+ non-Annotated
-=== "Python 3.8+"
+/// tip
- ```Python hl_lines="20"
- {!> ../../../docs_src/dependencies/tutorial004_an.py!}
- ```
+Prefer to use the `Annotated` version if possible.
-=== "Python 3.10+ non-Annotated"
+///
- !!! tip
- Prefer to use the `Annotated` version if possible.
+```Python hl_lines="17"
+{!> ../../../docs_src/dependencies/tutorial004_py310.py!}
+```
- ```Python hl_lines="17"
- {!> ../../../docs_src/dependencies/tutorial004_py310.py!}
- ```
+////
-=== "Python 3.8+ non-Annotated"
+//// tab | Python 3.8+ non-Annotated
- !!! tip
- Prefer to use the `Annotated` version if possible.
+/// tip
- ```Python hl_lines="19"
- {!> ../../../docs_src/dependencies/tutorial004.py!}
- ```
+Prefer to use the `Annotated` version if possible.
+
+///
+
+```Python hl_lines="19"
+{!> ../../../docs_src/dependencies/tutorial004.py!}
+```
+
+////
...and **FastAPI** will know what to do.
-!!! tip
- If that seems more confusing than helpful, disregard it, you don't *need* it.
+/// tip
+
+If that seems more confusing than helpful, disregard it, you don't *need* it.
+
+It is just a shortcut. Because **FastAPI** cares about helping you minimize code repetition.
- It is just a shortcut. Because **FastAPI** cares about helping you minimize code repetition.
+///
It should be a `list` of `Depends()`:
-=== "Python 3.9+"
+//// tab | Python 3.9+
- ```Python hl_lines="19"
- {!> ../../../docs_src/dependencies/tutorial006_an_py39.py!}
- ```
+```Python hl_lines="19"
+{!> ../../../docs_src/dependencies/tutorial006_an_py39.py!}
+```
-=== "Python 3.8+"
+////
- ```Python hl_lines="18"
- {!> ../../../docs_src/dependencies/tutorial006_an.py!}
- ```
+//// tab | Python 3.8+
-=== "Python 3.8 non-Annotated"
+```Python hl_lines="18"
+{!> ../../../docs_src/dependencies/tutorial006_an.py!}
+```
- !!! tip
- Prefer to use the `Annotated` version if possible.
+////
- ```Python hl_lines="17"
- {!> ../../../docs_src/dependencies/tutorial006.py!}
- ```
+//// tab | Python 3.8 non-Annotated
+
+/// tip
+
+Prefer to use the `Annotated` version if possible.
+
+///
+
+```Python hl_lines="17"
+{!> ../../../docs_src/dependencies/tutorial006.py!}
+```
+
+////
These dependencies will be executed/solved the same way as normal dependencies. But their value (if they return any) won't be passed to your *path operation function*.
-!!! tip
- Some editors check for unused function parameters, and show them as errors.
+/// tip
+
+Some editors check for unused function parameters, and show them as errors.
- Using these `dependencies` in the *path operation decorator* you can make sure they are executed while avoiding editor/tooling errors.
+Using these `dependencies` in the *path operation decorator* you can make sure they are executed while avoiding editor/tooling errors.
- It might also help avoid confusion for new developers that see an unused parameter in your code and could think it's unnecessary.
+It might also help avoid confusion for new developers that see an unused parameter in your code and could think it's unnecessary.
-!!! info
- In this example we use invented custom headers `X-Key` and `X-Token`.
+///
- But in real cases, when implementing security, you would get more benefits from using the integrated [Security utilities (the next chapter)](../security/index.md){.internal-link target=_blank}.
+/// info
+
+In this example we use invented custom headers `X-Key` and `X-Token`.
+
+But in real cases, when implementing security, you would get more benefits from using the integrated [Security utilities (the next chapter)](../security/index.md){.internal-link target=_blank}.
+
+///
## Dependencies errors and return values
They can declare request requirements (like headers) or other sub-dependencies:
-=== "Python 3.9+"
+//// tab | Python 3.9+
+
+```Python hl_lines="8 13"
+{!> ../../../docs_src/dependencies/tutorial006_an_py39.py!}
+```
+
+////
+
+//// tab | Python 3.8+
- ```Python hl_lines="8 13"
- {!> ../../../docs_src/dependencies/tutorial006_an_py39.py!}
- ```
+```Python hl_lines="7 12"
+{!> ../../../docs_src/dependencies/tutorial006_an.py!}
+```
-=== "Python 3.8+"
+////
- ```Python hl_lines="7 12"
- {!> ../../../docs_src/dependencies/tutorial006_an.py!}
- ```
+//// tab | Python 3.8 non-Annotated
-=== "Python 3.8 non-Annotated"
+/// tip
- !!! tip
- Prefer to use the `Annotated` version if possible.
+Prefer to use the `Annotated` version if possible.
- ```Python hl_lines="6 11"
- {!> ../../../docs_src/dependencies/tutorial006.py!}
- ```
+///
+
+```Python hl_lines="6 11"
+{!> ../../../docs_src/dependencies/tutorial006.py!}
+```
+
+////
### Raise exceptions
These dependencies can `raise` exceptions, the same as normal dependencies:
-=== "Python 3.9+"
+//// tab | Python 3.9+
+
+```Python hl_lines="10 15"
+{!> ../../../docs_src/dependencies/tutorial006_an_py39.py!}
+```
+
+////
+
+//// tab | Python 3.8+
+
+```Python hl_lines="9 14"
+{!> ../../../docs_src/dependencies/tutorial006_an.py!}
+```
- ```Python hl_lines="10 15"
- {!> ../../../docs_src/dependencies/tutorial006_an_py39.py!}
- ```
+////
-=== "Python 3.8+"
+//// tab | Python 3.8 non-Annotated
- ```Python hl_lines="9 14"
- {!> ../../../docs_src/dependencies/tutorial006_an.py!}
- ```
+/// tip
-=== "Python 3.8 non-Annotated"
+Prefer to use the `Annotated` version if possible.
- !!! tip
- Prefer to use the `Annotated` version if possible.
+///
- ```Python hl_lines="8 13"
- {!> ../../../docs_src/dependencies/tutorial006.py!}
- ```
+```Python hl_lines="8 13"
+{!> ../../../docs_src/dependencies/tutorial006.py!}
+```
+
+////
### Return values
So, you can reuse a normal dependency (that returns a value) you already use somewhere else, and even though the value won't be used, the dependency will be executed:
-=== "Python 3.9+"
+//// tab | Python 3.9+
+
+```Python hl_lines="11 16"
+{!> ../../../docs_src/dependencies/tutorial006_an_py39.py!}
+```
+
+////
+
+//// tab | Python 3.8+
+
+```Python hl_lines="10 15"
+{!> ../../../docs_src/dependencies/tutorial006_an.py!}
+```
+
+////
- ```Python hl_lines="11 16"
- {!> ../../../docs_src/dependencies/tutorial006_an_py39.py!}
- ```
+//// tab | Python 3.8 non-Annotated
-=== "Python 3.8+"
+/// tip
- ```Python hl_lines="10 15"
- {!> ../../../docs_src/dependencies/tutorial006_an.py!}
- ```
+Prefer to use the `Annotated` version if possible.
-=== "Python 3.8 non-Annotated"
+///
- !!! tip
- Prefer to use the `Annotated` version if possible.
+```Python hl_lines="9 14"
+{!> ../../../docs_src/dependencies/tutorial006.py!}
+```
- ```Python hl_lines="9 14"
- {!> ../../../docs_src/dependencies/tutorial006.py!}
- ```
+////
## Dependencies for a group of *path operations*
To do this, use `yield` instead of `return`, and write the extra steps (code) after.
-!!! tip
- Make sure to use `yield` one single time.
+/// tip
-!!! note "Technical Details"
- Any function that is valid to use with:
+Make sure to use `yield` one single time.
- * <a href="https://docs.python.org/3/library/contextlib.html#contextlib.contextmanager" class="external-link" target="_blank">`@contextlib.contextmanager`</a> or
- * <a href="https://docs.python.org/3/library/contextlib.html#contextlib.asynccontextmanager" class="external-link" target="_blank">`@contextlib.asynccontextmanager`</a>
+///
- would be valid to use as a **FastAPI** dependency.
+/// note | "Technical Details"
- In fact, FastAPI uses those two decorators internally.
+Any function that is valid to use with:
+
+* <a href="https://docs.python.org/3/library/contextlib.html#contextlib.contextmanager" class="external-link" target="_blank">`@contextlib.contextmanager`</a> or
+* <a href="https://docs.python.org/3/library/contextlib.html#contextlib.asynccontextmanager" class="external-link" target="_blank">`@contextlib.asynccontextmanager`</a>
+
+would be valid to use as a **FastAPI** dependency.
+
+In fact, FastAPI uses those two decorators internally.
+
+///
## A database dependency with `yield`
{!../../../docs_src/dependencies/tutorial007.py!}
```
-!!! tip
- You can use `async` or regular functions.
+/// tip
- **FastAPI** will do the right thing with each, the same as with normal dependencies.
+You can use `async` or regular functions.
+
+**FastAPI** will do the right thing with each, the same as with normal dependencies.
+
+///
## A dependency with `yield` and `try`
For example, `dependency_c` can have a dependency on `dependency_b`, and `dependency_b` on `dependency_a`:
-=== "Python 3.9+"
+//// tab | Python 3.9+
- ```Python hl_lines="6 14 22"
- {!> ../../../docs_src/dependencies/tutorial008_an_py39.py!}
- ```
+```Python hl_lines="6 14 22"
+{!> ../../../docs_src/dependencies/tutorial008_an_py39.py!}
+```
-=== "Python 3.8+"
+////
- ```Python hl_lines="5 13 21"
- {!> ../../../docs_src/dependencies/tutorial008_an.py!}
- ```
+//// tab | Python 3.8+
-=== "Python 3.8+ non-Annotated"
+```Python hl_lines="5 13 21"
+{!> ../../../docs_src/dependencies/tutorial008_an.py!}
+```
- !!! tip
- Prefer to use the `Annotated` version if possible.
+////
- ```Python hl_lines="4 12 20"
- {!> ../../../docs_src/dependencies/tutorial008.py!}
- ```
+//// tab | Python 3.8+ non-Annotated
+
+/// tip
+
+Prefer to use the `Annotated` version if possible.
+
+///
+
+```Python hl_lines="4 12 20"
+{!> ../../../docs_src/dependencies/tutorial008.py!}
+```
+
+////
And all of them can use `yield`.
And, in turn, `dependency_b` needs the value from `dependency_a` (here named `dep_a`) to be available for its exit code.
-=== "Python 3.9+"
+//// tab | Python 3.9+
+
+```Python hl_lines="18-19 26-27"
+{!> ../../../docs_src/dependencies/tutorial008_an_py39.py!}
+```
+
+////
+
+//// tab | Python 3.8+
+
+```Python hl_lines="17-18 25-26"
+{!> ../../../docs_src/dependencies/tutorial008_an.py!}
+```
+
+////
- ```Python hl_lines="18-19 26-27"
- {!> ../../../docs_src/dependencies/tutorial008_an_py39.py!}
- ```
+//// tab | Python 3.8+ non-Annotated
-=== "Python 3.8+"
+/// tip
- ```Python hl_lines="17-18 25-26"
- {!> ../../../docs_src/dependencies/tutorial008_an.py!}
- ```
+Prefer to use the `Annotated` version if possible.
-=== "Python 3.8+ non-Annotated"
+///
- !!! tip
- Prefer to use the `Annotated` version if possible.
+```Python hl_lines="16-17 24-25"
+{!> ../../../docs_src/dependencies/tutorial008.py!}
+```
- ```Python hl_lines="16-17 24-25"
- {!> ../../../docs_src/dependencies/tutorial008.py!}
- ```
+////
The same way, you could have some dependencies with `yield` and some other dependencies with `return`, and have some of those depend on some of the others.
**FastAPI** will make sure everything is run in the correct order.
-!!! note "Technical Details"
- This works thanks to Python's <a href="https://docs.python.org/3/library/contextlib.html" class="external-link" target="_blank">Context Managers</a>.
+/// note | "Technical Details"
+
+This works thanks to Python's <a href="https://docs.python.org/3/library/contextlib.html" class="external-link" target="_blank">Context Managers</a>.
- **FastAPI** uses them internally to achieve this.
+**FastAPI** uses them internally to achieve this.
+
+///
## Dependencies with `yield` and `HTTPException`
The same way, you could raise an `HTTPException` or similar in the exit code, after the `yield`.
-!!! tip
+/// tip
+
+This is a somewhat advanced technique, and in most of the cases you won't really need it, as you can raise exceptions (including `HTTPException`) from inside of the rest of your application code, for example, in the *path operation function*.
- This is a somewhat advanced technique, and in most of the cases you won't really need it, as you can raise exceptions (including `HTTPException`) from inside of the rest of your application code, for example, in the *path operation function*.
+But it's there for you if you need it. 🤓
- But it's there for you if you need it. 🤓
+///
-=== "Python 3.9+"
+//// tab | Python 3.9+
+
+```Python hl_lines="18-22 31"
+{!> ../../../docs_src/dependencies/tutorial008b_an_py39.py!}
+```
- ```Python hl_lines="18-22 31"
- {!> ../../../docs_src/dependencies/tutorial008b_an_py39.py!}
- ```
+////
+
+//// tab | Python 3.8+
+
+```Python hl_lines="17-21 30"
+{!> ../../../docs_src/dependencies/tutorial008b_an.py!}
+```
-=== "Python 3.8+"
+////
- ```Python hl_lines="17-21 30"
- {!> ../../../docs_src/dependencies/tutorial008b_an.py!}
- ```
+//// tab | Python 3.8+ non-Annotated
-=== "Python 3.8+ non-Annotated"
+/// tip
- !!! tip
- Prefer to use the `Annotated` version if possible.
+Prefer to use the `Annotated` version if possible.
- ```Python hl_lines="16-20 29"
- {!> ../../../docs_src/dependencies/tutorial008b.py!}
- ```
+///
+
+```Python hl_lines="16-20 29"
+{!> ../../../docs_src/dependencies/tutorial008b.py!}
+```
+
+////
An alternative you could use to catch exceptions (and possibly also raise another `HTTPException`) is to create a [Custom Exception Handler](../handling-errors.md#install-custom-exception-handlers){.internal-link target=_blank}.
If you catch an exception using `except` in a dependency with `yield` and you don't raise it again (or raise a new exception), FastAPI won't be able to notice there was an exception, the same way that would happen with regular Python:
-=== "Python 3.9+"
+//// tab | Python 3.9+
+
+```Python hl_lines="15-16"
+{!> ../../../docs_src/dependencies/tutorial008c_an_py39.py!}
+```
+
+////
- ```Python hl_lines="15-16"
- {!> ../../../docs_src/dependencies/tutorial008c_an_py39.py!}
- ```
+//// tab | Python 3.8+
+
+```Python hl_lines="14-15"
+{!> ../../../docs_src/dependencies/tutorial008c_an.py!}
+```
-=== "Python 3.8+"
+////
- ```Python hl_lines="14-15"
- {!> ../../../docs_src/dependencies/tutorial008c_an.py!}
- ```
+//// tab | Python 3.8+ non-Annotated
-=== "Python 3.8+ non-Annotated"
+/// tip
- !!! tip
- Prefer to use the `Annotated` version if possible.
+Prefer to use the `Annotated` version if possible.
- ```Python hl_lines="13-14"
- {!> ../../../docs_src/dependencies/tutorial008c.py!}
- ```
+///
+
+```Python hl_lines="13-14"
+{!> ../../../docs_src/dependencies/tutorial008c.py!}
+```
+
+////
In this case, the client will see an *HTTP 500 Internal Server Error* response as it should, given that we are not raising an `HTTPException` or similar, but the server will **not have any logs** or any other indication of what was the error. 😱
You can re-raise the same exception using `raise`:
-=== "Python 3.9+"
+//// tab | Python 3.9+
- ```Python hl_lines="17"
- {!> ../../../docs_src/dependencies/tutorial008d_an_py39.py!}
- ```
+```Python hl_lines="17"
+{!> ../../../docs_src/dependencies/tutorial008d_an_py39.py!}
+```
-=== "Python 3.8+"
+////
+
+//// tab | Python 3.8+
+
+```Python hl_lines="16"
+{!> ../../../docs_src/dependencies/tutorial008d_an.py!}
+```
- ```Python hl_lines="16"
- {!> ../../../docs_src/dependencies/tutorial008d_an.py!}
- ```
+////
+//// tab | Python 3.8+ non-Annotated
-=== "Python 3.8+ non-Annotated"
+/// tip
- !!! tip
- Prefer to use the `Annotated` version if possible.
+Prefer to use the `Annotated` version if possible.
- ```Python hl_lines="15"
- {!> ../../../docs_src/dependencies/tutorial008d.py!}
- ```
+///
+
+```Python hl_lines="15"
+{!> ../../../docs_src/dependencies/tutorial008d.py!}
+```
+
+////
Now the client will get the same *HTTP 500 Internal Server Error* response, but the server will have our custom `InternalError` in the logs. 😎
end
```
-!!! info
- Only **one response** will be sent to the client. It might be one of the error responses or it will be the response from the *path operation*.
+/// info
+
+Only **one response** will be sent to the client. It might be one of the error responses or it will be the response from the *path operation*.
+
+After one of those responses is sent, no other response can be sent.
+
+///
+
+/// tip
- After one of those responses is sent, no other response can be sent.
+This diagram shows `HTTPException`, but you could also raise any other exception that you catch in a dependency with `yield` or with a [Custom Exception Handler](../handling-errors.md#install-custom-exception-handlers){.internal-link target=_blank}.
-!!! tip
- This diagram shows `HTTPException`, but you could also raise any other exception that you catch in a dependency with `yield` or with a [Custom Exception Handler](../handling-errors.md#install-custom-exception-handlers){.internal-link target=_blank}.
+If you raise any exception, it will be passed to the dependencies with yield, including `HTTPException`. In most cases you will want to re-raise that same exception or a new one from the dependency with `yield` to make sure it's properly handled.
- If you raise any exception, it will be passed to the dependencies with yield, including `HTTPException`. In most cases you will want to re-raise that same exception or a new one from the dependency with `yield` to make sure it's properly handled.
+///
## Dependencies with `yield`, `HTTPException`, `except` and Background Tasks
-!!! warning
- You most probably don't need these technical details, you can skip this section and continue below.
+/// warning
- These details are useful mainly if you were using a version of FastAPI prior to 0.106.0 and used resources from dependencies with `yield` in background tasks.
+You most probably don't need these technical details, you can skip this section and continue below.
+
+These details are useful mainly if you were using a version of FastAPI prior to 0.106.0 and used resources from dependencies with `yield` in background tasks.
+
+///
### Dependencies with `yield` and `except`, Technical Details
Nevertheless, as this would mean waiting for the response to travel through the network while unnecessarily holding a resource in a dependency with yield (for example a database connection), this was changed in FastAPI 0.106.0.
-!!! tip
+/// tip
- Additionally, a background task is normally an independent set of logic that should be handled separately, with its own resources (e.g. its own database connection).
+Additionally, a background task is normally an independent set of logic that should be handled separately, with its own resources (e.g. its own database connection).
- So, this way you will probably have cleaner code.
+So, this way you will probably have cleaner code.
+
+///
If you used to rely on this behavior, now you should create the resources for background tasks inside the background task itself, and use internally only data that doesn't depend on the resources of dependencies with `yield`.
### Using context managers in dependencies with `yield`
-!!! warning
- This is, more or less, an "advanced" idea.
+/// warning
+
+This is, more or less, an "advanced" idea.
- If you are just starting with **FastAPI** you might want to skip it for now.
+If you are just starting with **FastAPI** you might want to skip it for now.
+
+///
In Python, you can create Context Managers by <a href="https://docs.python.org/3/reference/datamodel.html#context-managers" class="external-link" target="_blank">creating a class with two methods: `__enter__()` and `__exit__()`</a>.
{!../../../docs_src/dependencies/tutorial010.py!}
```
-!!! tip
- Another way to create a context manager is with:
+/// tip
+
+Another way to create a context manager is with:
+
+* <a href="https://docs.python.org/3/library/contextlib.html#contextlib.contextmanager" class="external-link" target="_blank">`@contextlib.contextmanager`</a> or
+* <a href="https://docs.python.org/3/library/contextlib.html#contextlib.asynccontextmanager" class="external-link" target="_blank">`@contextlib.asynccontextmanager`</a>
- * <a href="https://docs.python.org/3/library/contextlib.html#contextlib.contextmanager" class="external-link" target="_blank">`@contextlib.contextmanager`</a> or
- * <a href="https://docs.python.org/3/library/contextlib.html#contextlib.asynccontextmanager" class="external-link" target="_blank">`@contextlib.asynccontextmanager`</a>
+using them to decorate a function with a single `yield`.
- using them to decorate a function with a single `yield`.
+That's what **FastAPI** uses internally for dependencies with `yield`.
- That's what **FastAPI** uses internally for dependencies with `yield`.
+But you don't have to use the decorators for FastAPI dependencies (and you shouldn't).
- But you don't have to use the decorators for FastAPI dependencies (and you shouldn't).
+FastAPI will do it for you internally.
- FastAPI will do it for you internally.
+///
In that case, they will be applied to all the *path operations* in the application:
-=== "Python 3.9+"
+//// tab | Python 3.9+
- ```Python hl_lines="16"
- {!> ../../../docs_src/dependencies/tutorial012_an_py39.py!}
- ```
+```Python hl_lines="16"
+{!> ../../../docs_src/dependencies/tutorial012_an_py39.py!}
+```
-=== "Python 3.8+"
+////
- ```Python hl_lines="16"
- {!> ../../../docs_src/dependencies/tutorial012_an.py!}
- ```
+//// tab | Python 3.8+
-=== "Python 3.8 non-Annotated"
+```Python hl_lines="16"
+{!> ../../../docs_src/dependencies/tutorial012_an.py!}
+```
- !!! tip
- Prefer to use the `Annotated` version if possible.
+////
- ```Python hl_lines="15"
- {!> ../../../docs_src/dependencies/tutorial012.py!}
- ```
+//// tab | Python 3.8 non-Annotated
+
+/// tip
+
+Prefer to use the `Annotated` version if possible.
+
+///
+
+```Python hl_lines="15"
+{!> ../../../docs_src/dependencies/tutorial012.py!}
+```
+
+////
And all the ideas in the section about [adding `dependencies` to the *path operation decorators*](dependencies-in-path-operation-decorators.md){.internal-link target=_blank} still apply, but in this case, to all of the *path operations* in the app.
It is just a function that can take all the same parameters that a *path operation function* can take:
-=== "Python 3.10+"
+//// tab | Python 3.10+
- ```Python hl_lines="8-9"
- {!> ../../../docs_src/dependencies/tutorial001_an_py310.py!}
- ```
+```Python hl_lines="8-9"
+{!> ../../../docs_src/dependencies/tutorial001_an_py310.py!}
+```
+
+////
+
+//// tab | Python 3.9+
+
+```Python hl_lines="8-11"
+{!> ../../../docs_src/dependencies/tutorial001_an_py39.py!}
+```
+
+////
-=== "Python 3.9+"
+//// tab | Python 3.8+
- ```Python hl_lines="8-11"
- {!> ../../../docs_src/dependencies/tutorial001_an_py39.py!}
- ```
+```Python hl_lines="9-12"
+{!> ../../../docs_src/dependencies/tutorial001_an.py!}
+```
-=== "Python 3.8+"
+////
- ```Python hl_lines="9-12"
- {!> ../../../docs_src/dependencies/tutorial001_an.py!}
- ```
+//// tab | Python 3.10+ non-Annotated
-=== "Python 3.10+ non-Annotated"
+/// tip
- !!! tip
- Prefer to use the `Annotated` version if possible.
+Prefer to use the `Annotated` version if possible.
- ```Python hl_lines="6-7"
- {!> ../../../docs_src/dependencies/tutorial001_py310.py!}
- ```
+///
-=== "Python 3.8+ non-Annotated"
+```Python hl_lines="6-7"
+{!> ../../../docs_src/dependencies/tutorial001_py310.py!}
+```
- !!! tip
- Prefer to use the `Annotated` version if possible.
+////
- ```Python hl_lines="8-11"
- {!> ../../../docs_src/dependencies/tutorial001.py!}
- ```
+//// tab | Python 3.8+ non-Annotated
+
+/// tip
+
+Prefer to use the `Annotated` version if possible.
+
+///
+
+```Python hl_lines="8-11"
+{!> ../../../docs_src/dependencies/tutorial001.py!}
+```
+
+////
That's it.
And then it just returns a `dict` containing those values.
-!!! info
- FastAPI added support for `Annotated` (and started recommending it) in version 0.95.0.
+/// info
+
+FastAPI added support for `Annotated` (and started recommending it) in version 0.95.0.
- If you have an older version, you would get errors when trying to use `Annotated`.
+If you have an older version, you would get errors when trying to use `Annotated`.
- Make sure you [Upgrade the FastAPI version](../../deployment/versions.md#upgrading-the-fastapi-versions){.internal-link target=_blank} to at least 0.95.1 before using `Annotated`.
+Make sure you [Upgrade the FastAPI version](../../deployment/versions.md#upgrading-the-fastapi-versions){.internal-link target=_blank} to at least 0.95.1 before using `Annotated`.
+
+///
### Import `Depends`
-=== "Python 3.10+"
+//// tab | Python 3.10+
+
+```Python hl_lines="3"
+{!> ../../../docs_src/dependencies/tutorial001_an_py310.py!}
+```
+
+////
+
+//// tab | Python 3.9+
+
+```Python hl_lines="3"
+{!> ../../../docs_src/dependencies/tutorial001_an_py39.py!}
+```
+
+////
+
+//// tab | Python 3.8+
+
+```Python hl_lines="3"
+{!> ../../../docs_src/dependencies/tutorial001_an.py!}
+```
- ```Python hl_lines="3"
- {!> ../../../docs_src/dependencies/tutorial001_an_py310.py!}
- ```
+////
-=== "Python 3.9+"
+//// tab | Python 3.10+ non-Annotated
- ```Python hl_lines="3"
- {!> ../../../docs_src/dependencies/tutorial001_an_py39.py!}
- ```
+/// tip
-=== "Python 3.8+"
+Prefer to use the `Annotated` version if possible.
+
+///
+
+```Python hl_lines="1"
+{!> ../../../docs_src/dependencies/tutorial001_py310.py!}
+```
- ```Python hl_lines="3"
- {!> ../../../docs_src/dependencies/tutorial001_an.py!}
- ```
+////
-=== "Python 3.10+ non-Annotated"
+//// tab | Python 3.8+ non-Annotated
- !!! tip
- Prefer to use the `Annotated` version if possible.
+/// tip
- ```Python hl_lines="1"
- {!> ../../../docs_src/dependencies/tutorial001_py310.py!}
- ```
+Prefer to use the `Annotated` version if possible.
-=== "Python 3.8+ non-Annotated"
+///
- !!! tip
- Prefer to use the `Annotated` version if possible.
+```Python hl_lines="3"
+{!> ../../../docs_src/dependencies/tutorial001.py!}
+```
- ```Python hl_lines="3"
- {!> ../../../docs_src/dependencies/tutorial001.py!}
- ```
+////
### Declare the dependency, in the "dependant"
The same way you use `Body`, `Query`, etc. with your *path operation function* parameters, use `Depends` with a new parameter:
-=== "Python 3.10+"
+//// tab | Python 3.10+
+
+```Python hl_lines="13 18"
+{!> ../../../docs_src/dependencies/tutorial001_an_py310.py!}
+```
+
+////
- ```Python hl_lines="13 18"
- {!> ../../../docs_src/dependencies/tutorial001_an_py310.py!}
- ```
+//// tab | Python 3.9+
-=== "Python 3.9+"
+```Python hl_lines="15 20"
+{!> ../../../docs_src/dependencies/tutorial001_an_py39.py!}
+```
+
+////
- ```Python hl_lines="15 20"
- {!> ../../../docs_src/dependencies/tutorial001_an_py39.py!}
- ```
+//// tab | Python 3.8+
-=== "Python 3.8+"
+```Python hl_lines="16 21"
+{!> ../../../docs_src/dependencies/tutorial001_an.py!}
+```
- ```Python hl_lines="16 21"
- {!> ../../../docs_src/dependencies/tutorial001_an.py!}
- ```
+////
-=== "Python 3.10+ non-Annotated"
+//// tab | Python 3.10+ non-Annotated
- !!! tip
- Prefer to use the `Annotated` version if possible.
+/// tip
- ```Python hl_lines="11 16"
- {!> ../../../docs_src/dependencies/tutorial001_py310.py!}
- ```
+Prefer to use the `Annotated` version if possible.
-=== "Python 3.8+ non-Annotated"
+///
- !!! tip
- Prefer to use the `Annotated` version if possible.
+```Python hl_lines="11 16"
+{!> ../../../docs_src/dependencies/tutorial001_py310.py!}
+```
+
+////
+
+//// tab | Python 3.8+ non-Annotated
+
+/// tip
+
+Prefer to use the `Annotated` version if possible.
+
+///
+
+```Python hl_lines="15 20"
+{!> ../../../docs_src/dependencies/tutorial001.py!}
+```
- ```Python hl_lines="15 20"
- {!> ../../../docs_src/dependencies/tutorial001.py!}
- ```
+////
Although you use `Depends` in the parameters of your function the same way you use `Body`, `Query`, etc, `Depends` works a bit differently.
And that function takes parameters in the same way that *path operation functions* do.
-!!! tip
- You'll see what other "things", apart from functions, can be used as dependencies in the next chapter.
+/// tip
+
+You'll see what other "things", apart from functions, can be used as dependencies in the next chapter.
+
+///
Whenever a new request arrives, **FastAPI** will take care of:
This way you write shared code once and **FastAPI** takes care of calling it for your *path operations*.
-!!! check
- Notice that you don't have to create a special class and pass it somewhere to **FastAPI** to "register" it or anything similar.
+/// check
+
+Notice that you don't have to create a special class and pass it somewhere to **FastAPI** to "register" it or anything similar.
+
+You just pass it to `Depends` and **FastAPI** knows how to do the rest.
- You just pass it to `Depends` and **FastAPI** knows how to do the rest.
+///
## Share `Annotated` dependencies
But because we are using `Annotated`, we can store that `Annotated` value in a variable and use it in multiple places:
-=== "Python 3.10+"
+//// tab | Python 3.10+
+
+```Python hl_lines="12 16 21"
+{!> ../../../docs_src/dependencies/tutorial001_02_an_py310.py!}
+```
+
+////
- ```Python hl_lines="12 16 21"
- {!> ../../../docs_src/dependencies/tutorial001_02_an_py310.py!}
- ```
+//// tab | Python 3.9+
-=== "Python 3.9+"
+```Python hl_lines="14 18 23"
+{!> ../../../docs_src/dependencies/tutorial001_02_an_py39.py!}
+```
+
+////
- ```Python hl_lines="14 18 23"
- {!> ../../../docs_src/dependencies/tutorial001_02_an_py39.py!}
- ```
+//// tab | Python 3.8+
+
+```Python hl_lines="15 19 24"
+{!> ../../../docs_src/dependencies/tutorial001_02_an.py!}
+```
-=== "Python 3.8+"
+////
- ```Python hl_lines="15 19 24"
- {!> ../../../docs_src/dependencies/tutorial001_02_an.py!}
- ```
+/// tip
-!!! tip
- This is just standard Python, it's called a "type alias", it's actually not specific to **FastAPI**.
+This is just standard Python, it's called a "type alias", it's actually not specific to **FastAPI**.
- But because **FastAPI** is based on the Python standards, including `Annotated`, you can use this trick in your code. 😎
+But because **FastAPI** is based on the Python standards, including `Annotated`, you can use this trick in your code. 😎
+
+///
The dependencies will keep working as expected, and the **best part** is that the **type information will be preserved**, which means that your editor will be able to keep providing you with **autocompletion**, **inline errors**, etc. The same for other tools like `mypy`.
It doesn't matter. **FastAPI** will know what to do.
-!!! note
- If you don't know, check the [Async: *"In a hurry?"*](../../async.md#in-a-hurry){.internal-link target=_blank} section about `async` and `await` in the docs.
+/// note
+
+If you don't know, check the [Async: *"In a hurry?"*](../../async.md#in-a-hurry){.internal-link target=_blank} section about `async` and `await` in the docs.
+
+///
## Integrated with OpenAPI
You could create a first dependency ("dependable") like:
-=== "Python 3.10+"
+//// tab | Python 3.10+
- ```Python hl_lines="8-9"
- {!> ../../../docs_src/dependencies/tutorial005_an_py310.py!}
- ```
+```Python hl_lines="8-9"
+{!> ../../../docs_src/dependencies/tutorial005_an_py310.py!}
+```
+
+////
-=== "Python 3.9+"
+//// tab | Python 3.9+
+
+```Python hl_lines="8-9"
+{!> ../../../docs_src/dependencies/tutorial005_an_py39.py!}
+```
- ```Python hl_lines="8-9"
- {!> ../../../docs_src/dependencies/tutorial005_an_py39.py!}
- ```
+////
+
+//// tab | Python 3.8+
+
+```Python hl_lines="9-10"
+{!> ../../../docs_src/dependencies/tutorial005_an.py!}
+```
-=== "Python 3.8+"
+////
+
+//// tab | Python 3.10 non-Annotated
+
+/// tip
+
+Prefer to use the `Annotated` version if possible.
+
+///
+
+```Python hl_lines="6-7"
+{!> ../../../docs_src/dependencies/tutorial005_py310.py!}
+```
- ```Python hl_lines="9-10"
- {!> ../../../docs_src/dependencies/tutorial005_an.py!}
- ```
+////
-=== "Python 3.10 non-Annotated"
+//// tab | Python 3.8 non-Annotated
- !!! tip
- Prefer to use the `Annotated` version if possible.
+/// tip
- ```Python hl_lines="6-7"
- {!> ../../../docs_src/dependencies/tutorial005_py310.py!}
- ```
+Prefer to use the `Annotated` version if possible.
-=== "Python 3.8 non-Annotated"
+///
- !!! tip
- Prefer to use the `Annotated` version if possible.
+```Python hl_lines="8-9"
+{!> ../../../docs_src/dependencies/tutorial005.py!}
+```
- ```Python hl_lines="8-9"
- {!> ../../../docs_src/dependencies/tutorial005.py!}
- ```
+////
It declares an optional query parameter `q` as a `str`, and then it just returns it.
Then you can create another dependency function (a "dependable") that at the same time declares a dependency of its own (so it is a "dependant" too):
-=== "Python 3.10+"
+//// tab | Python 3.10+
+
+```Python hl_lines="13"
+{!> ../../../docs_src/dependencies/tutorial005_an_py310.py!}
+```
+
+////
+
+//// tab | Python 3.9+
+
+```Python hl_lines="13"
+{!> ../../../docs_src/dependencies/tutorial005_an_py39.py!}
+```
+
+////
+
+//// tab | Python 3.8+
+
+```Python hl_lines="14"
+{!> ../../../docs_src/dependencies/tutorial005_an.py!}
+```
+
+////
+
+//// tab | Python 3.10 non-Annotated
- ```Python hl_lines="13"
- {!> ../../../docs_src/dependencies/tutorial005_an_py310.py!}
- ```
+/// tip
-=== "Python 3.9+"
+Prefer to use the `Annotated` version if possible.
- ```Python hl_lines="13"
- {!> ../../../docs_src/dependencies/tutorial005_an_py39.py!}
- ```
+///
-=== "Python 3.8+"
+```Python hl_lines="11"
+{!> ../../../docs_src/dependencies/tutorial005_py310.py!}
+```
- ```Python hl_lines="14"
- {!> ../../../docs_src/dependencies/tutorial005_an.py!}
- ```
+////
-=== "Python 3.10 non-Annotated"
+//// tab | Python 3.8 non-Annotated
- !!! tip
- Prefer to use the `Annotated` version if possible.
+/// tip
- ```Python hl_lines="11"
- {!> ../../../docs_src/dependencies/tutorial005_py310.py!}
- ```
+Prefer to use the `Annotated` version if possible.
-=== "Python 3.8 non-Annotated"
+///
- !!! tip
- Prefer to use the `Annotated` version if possible.
+```Python hl_lines="13"
+{!> ../../../docs_src/dependencies/tutorial005.py!}
+```
- ```Python hl_lines="13"
- {!> ../../../docs_src/dependencies/tutorial005.py!}
- ```
+////
Let's focus on the parameters declared:
Then we can use the dependency with:
-=== "Python 3.10+"
+//// tab | Python 3.10+
+
+```Python hl_lines="23"
+{!> ../../../docs_src/dependencies/tutorial005_an_py310.py!}
+```
+
+////
+
+//// tab | Python 3.9+
+
+```Python hl_lines="23"
+{!> ../../../docs_src/dependencies/tutorial005_an_py39.py!}
+```
+
+////
+
+//// tab | Python 3.8+
+
+```Python hl_lines="24"
+{!> ../../../docs_src/dependencies/tutorial005_an.py!}
+```
+
+////
- ```Python hl_lines="23"
- {!> ../../../docs_src/dependencies/tutorial005_an_py310.py!}
- ```
+//// tab | Python 3.10 non-Annotated
-=== "Python 3.9+"
+/// tip
- ```Python hl_lines="23"
- {!> ../../../docs_src/dependencies/tutorial005_an_py39.py!}
- ```
+Prefer to use the `Annotated` version if possible.
-=== "Python 3.8+"
+///
- ```Python hl_lines="24"
- {!> ../../../docs_src/dependencies/tutorial005_an.py!}
- ```
+```Python hl_lines="19"
+{!> ../../../docs_src/dependencies/tutorial005_py310.py!}
+```
+
+////
-=== "Python 3.10 non-Annotated"
+//// tab | Python 3.8 non-Annotated
- !!! tip
- Prefer to use the `Annotated` version if possible.
+/// tip
- ```Python hl_lines="19"
- {!> ../../../docs_src/dependencies/tutorial005_py310.py!}
- ```
+Prefer to use the `Annotated` version if possible.
-=== "Python 3.8 non-Annotated"
+///
+
+```Python hl_lines="22"
+{!> ../../../docs_src/dependencies/tutorial005.py!}
+```
- !!! tip
- Prefer to use the `Annotated` version if possible.
+////
- ```Python hl_lines="22"
- {!> ../../../docs_src/dependencies/tutorial005.py!}
- ```
+/// info
-!!! info
- Notice that we are only declaring one dependency in the *path operation function*, the `query_or_cookie_extractor`.
+Notice that we are only declaring one dependency in the *path operation function*, the `query_or_cookie_extractor`.
- But **FastAPI** will know that it has to solve `query_extractor` first, to pass the results of that to `query_or_cookie_extractor` while calling it.
+But **FastAPI** will know that it has to solve `query_extractor` first, to pass the results of that to `query_or_cookie_extractor` while calling it.
+
+///
```mermaid
graph TB
In an advanced scenario where you know you need the dependency to be called at every step (possibly multiple times) in the same request instead of using the "cached" value, you can set the parameter `use_cache=False` when using `Depends`:
-=== "Python 3.8+"
+//// tab | Python 3.8+
+
+```Python hl_lines="1"
+async def needy_dependency(fresh_value: Annotated[str, Depends(get_value, use_cache=False)]):
+ return {"fresh_value": fresh_value}
+```
- ```Python hl_lines="1"
- async def needy_dependency(fresh_value: Annotated[str, Depends(get_value, use_cache=False)]):
- return {"fresh_value": fresh_value}
- ```
+////
-=== "Python 3.8+ non-Annotated"
+//// tab | Python 3.8+ non-Annotated
- !!! tip
- Prefer to use the `Annotated` version if possible.
+/// tip
- ```Python hl_lines="1"
- async def needy_dependency(fresh_value: str = Depends(get_value, use_cache=False)):
- return {"fresh_value": fresh_value}
- ```
+Prefer to use the `Annotated` version if possible.
+
+///
+
+```Python hl_lines="1"
+async def needy_dependency(fresh_value: str = Depends(get_value, use_cache=False)):
+ return {"fresh_value": fresh_value}
+```
+
+////
## Recap
But still, it is very powerful, and allows you to declare arbitrarily deeply nested dependency "graphs" (trees).
-!!! tip
- All this might not seem as useful with these simple examples.
+/// tip
+
+All this might not seem as useful with these simple examples.
+
+But you will see how useful it is in the chapters about **security**.
- But you will see how useful it is in the chapters about **security**.
+And you will also see the amounts of code it will save you.
- And you will also see the amounts of code it will save you.
+///
It receives an object, like a Pydantic model, and returns a JSON compatible version:
-=== "Python 3.10+"
+//// tab | Python 3.10+
- ```Python hl_lines="4 21"
- {!> ../../../docs_src/encoder/tutorial001_py310.py!}
- ```
+```Python hl_lines="4 21"
+{!> ../../../docs_src/encoder/tutorial001_py310.py!}
+```
-=== "Python 3.8+"
+////
- ```Python hl_lines="5 22"
- {!> ../../../docs_src/encoder/tutorial001.py!}
- ```
+//// tab | Python 3.8+
+
+```Python hl_lines="5 22"
+{!> ../../../docs_src/encoder/tutorial001.py!}
+```
+
+////
In this example, it would convert the Pydantic model to a `dict`, and the `datetime` to a `str`.
It doesn't return a large `str` containing the data in JSON format (as a string). It returns a Python standard data structure (e.g. a `dict`) with values and sub-values that are all compatible with JSON.
-!!! note
- `jsonable_encoder` is actually used by **FastAPI** internally to convert data. But it is useful in many other scenarios.
+/// note
+
+`jsonable_encoder` is actually used by **FastAPI** internally to convert data. But it is useful in many other scenarios.
+
+///
Here's an example *path operation* with parameters using some of the above types.
-=== "Python 3.10+"
+//// tab | Python 3.10+
- ```Python hl_lines="1 3 12-16"
- {!> ../../../docs_src/extra_data_types/tutorial001_an_py310.py!}
- ```
+```Python hl_lines="1 3 12-16"
+{!> ../../../docs_src/extra_data_types/tutorial001_an_py310.py!}
+```
-=== "Python 3.9+"
+////
- ```Python hl_lines="1 3 12-16"
- {!> ../../../docs_src/extra_data_types/tutorial001_an_py39.py!}
- ```
+//// tab | Python 3.9+
-=== "Python 3.8+"
+```Python hl_lines="1 3 12-16"
+{!> ../../../docs_src/extra_data_types/tutorial001_an_py39.py!}
+```
- ```Python hl_lines="1 3 13-17"
- {!> ../../../docs_src/extra_data_types/tutorial001_an.py!}
- ```
+////
-=== "Python 3.10+ non-Annotated"
+//// tab | Python 3.8+
- !!! tip
- Prefer to use the `Annotated` version if possible.
+```Python hl_lines="1 3 13-17"
+{!> ../../../docs_src/extra_data_types/tutorial001_an.py!}
+```
- ```Python hl_lines="1 2 11-15"
- {!> ../../../docs_src/extra_data_types/tutorial001_py310.py!}
- ```
+////
-=== "Python 3.8+ non-Annotated"
+//// tab | Python 3.10+ non-Annotated
- !!! tip
- Prefer to use the `Annotated` version if possible.
+/// tip
- ```Python hl_lines="1 2 12-16"
- {!> ../../../docs_src/extra_data_types/tutorial001.py!}
- ```
+Prefer to use the `Annotated` version if possible.
+
+///
+
+```Python hl_lines="1 2 11-15"
+{!> ../../../docs_src/extra_data_types/tutorial001_py310.py!}
+```
+
+////
+
+//// tab | Python 3.8+ non-Annotated
+
+/// tip
+
+Prefer to use the `Annotated` version if possible.
+
+///
+
+```Python hl_lines="1 2 12-16"
+{!> ../../../docs_src/extra_data_types/tutorial001.py!}
+```
+
+////
Note that the parameters inside the function have their natural data type, and you can, for example, perform normal date manipulations, like:
-=== "Python 3.10+"
+//// tab | Python 3.10+
+
+```Python hl_lines="18-19"
+{!> ../../../docs_src/extra_data_types/tutorial001_an_py310.py!}
+```
+
+////
+
+//// tab | Python 3.9+
+
+```Python hl_lines="18-19"
+{!> ../../../docs_src/extra_data_types/tutorial001_an_py39.py!}
+```
+
+////
+
+//// tab | Python 3.8+
+
+```Python hl_lines="19-20"
+{!> ../../../docs_src/extra_data_types/tutorial001_an.py!}
+```
+
+////
+
+//// tab | Python 3.10+ non-Annotated
- ```Python hl_lines="18-19"
- {!> ../../../docs_src/extra_data_types/tutorial001_an_py310.py!}
- ```
+/// tip
-=== "Python 3.9+"
+Prefer to use the `Annotated` version if possible.
- ```Python hl_lines="18-19"
- {!> ../../../docs_src/extra_data_types/tutorial001_an_py39.py!}
- ```
+///
-=== "Python 3.8+"
+```Python hl_lines="17-18"
+{!> ../../../docs_src/extra_data_types/tutorial001_py310.py!}
+```
- ```Python hl_lines="19-20"
- {!> ../../../docs_src/extra_data_types/tutorial001_an.py!}
- ```
+////
-=== "Python 3.10+ non-Annotated"
+//// tab | Python 3.8+ non-Annotated
- !!! tip
- Prefer to use the `Annotated` version if possible.
+/// tip
- ```Python hl_lines="17-18"
- {!> ../../../docs_src/extra_data_types/tutorial001_py310.py!}
- ```
+Prefer to use the `Annotated` version if possible.
-=== "Python 3.8+ non-Annotated"
+///
- !!! tip
- Prefer to use the `Annotated` version if possible.
+```Python hl_lines="18-19"
+{!> ../../../docs_src/extra_data_types/tutorial001.py!}
+```
- ```Python hl_lines="18-19"
- {!> ../../../docs_src/extra_data_types/tutorial001.py!}
- ```
+////
* The **output model** should not have a password.
* The **database model** would probably need to have a hashed password.
-!!! danger
- Never store user's plaintext passwords. Always store a "secure hash" that you can then verify.
+/// danger
- If you don't know, you will learn what a "password hash" is in the [security chapters](security/simple-oauth2.md#password-hashing){.internal-link target=_blank}.
+Never store user's plaintext passwords. Always store a "secure hash" that you can then verify.
+
+If you don't know, you will learn what a "password hash" is in the [security chapters](security/simple-oauth2.md#password-hashing){.internal-link target=_blank}.
+
+///
## Multiple models
Here's a general idea of how the models could look like with their password fields and the places where they are used:
-=== "Python 3.10+"
+//// tab | Python 3.10+
+
+```Python hl_lines="7 9 14 20 22 27-28 31-33 38-39"
+{!> ../../../docs_src/extra_models/tutorial001_py310.py!}
+```
+
+////
+
+//// tab | Python 3.8+
+
+```Python hl_lines="9 11 16 22 24 29-30 33-35 40-41"
+{!> ../../../docs_src/extra_models/tutorial001.py!}
+```
- ```Python hl_lines="7 9 14 20 22 27-28 31-33 38-39"
- {!> ../../../docs_src/extra_models/tutorial001_py310.py!}
- ```
+////
-=== "Python 3.8+"
+/// info
- ```Python hl_lines="9 11 16 22 24 29-30 33-35 40-41"
- {!> ../../../docs_src/extra_models/tutorial001.py!}
- ```
+In Pydantic v1 the method was called `.dict()`, it was deprecated (but still supported) in Pydantic v2, and renamed to `.model_dump()`.
-!!! 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.
- The examples here use `.dict()` for compatibility with Pydantic v1, but you should use `.model_dump()` instead if you can use Pydantic v2.
+///
### About `**user_in.dict()`
)
```
-!!! warning
- The supporting additional functions are just to demo a possible flow of the data, but they of course are not providing any real security.
+/// warning
+
+The supporting additional functions are just to demo a possible flow of the data, but they of course are not providing any real security.
+
+///
## Reduce duplication
That way, we can declare just the differences between the models (with plaintext `password`, with `hashed_password` and without password):
-=== "Python 3.10+"
+//// tab | Python 3.10+
- ```Python hl_lines="7 13-14 17-18 21-22"
- {!> ../../../docs_src/extra_models/tutorial002_py310.py!}
- ```
+```Python hl_lines="7 13-14 17-18 21-22"
+{!> ../../../docs_src/extra_models/tutorial002_py310.py!}
+```
-=== "Python 3.8+"
+////
+
+//// tab | Python 3.8+
+
+```Python hl_lines="9 15-16 19-20 23-24"
+{!> ../../../docs_src/extra_models/tutorial002.py!}
+```
- ```Python hl_lines="9 15-16 19-20 23-24"
- {!> ../../../docs_src/extra_models/tutorial002.py!}
- ```
+////
## `Union` or `anyOf`
To do that, use the standard Python type hint <a href="https://docs.python.org/3/library/typing.html#typing.Union" class="external-link" target="_blank">`typing.Union`</a>:
-!!! note
- When defining a <a href="https://docs.pydantic.dev/latest/concepts/types/#unions" class="external-link" target="_blank">`Union`</a>, include the most specific type first, followed by the less specific type. In the example below, the more specific `PlaneItem` comes before `CarItem` in `Union[PlaneItem, CarItem]`.
+/// note
-=== "Python 3.10+"
+When defining a <a href="https://docs.pydantic.dev/latest/concepts/types/#unions" class="external-link" target="_blank">`Union`</a>, include the most specific type first, followed by the less specific type. In the example below, the more specific `PlaneItem` comes before `CarItem` in `Union[PlaneItem, CarItem]`.
- ```Python hl_lines="1 14-15 18-20 33"
- {!> ../../../docs_src/extra_models/tutorial003_py310.py!}
- ```
+///
-=== "Python 3.8+"
+//// tab | Python 3.10+
- ```Python hl_lines="1 14-15 18-20 33"
- {!> ../../../docs_src/extra_models/tutorial003.py!}
- ```
+```Python hl_lines="1 14-15 18-20 33"
+{!> ../../../docs_src/extra_models/tutorial003_py310.py!}
+```
+
+////
+
+//// tab | Python 3.8+
+
+```Python hl_lines="1 14-15 18-20 33"
+{!> ../../../docs_src/extra_models/tutorial003.py!}
+```
+
+////
### `Union` in Python 3.10
For that, use the standard Python `typing.List` (or just `list` in Python 3.9 and above):
-=== "Python 3.9+"
+//// tab | Python 3.9+
+
+```Python hl_lines="18"
+{!> ../../../docs_src/extra_models/tutorial004_py39.py!}
+```
+
+////
- ```Python hl_lines="18"
- {!> ../../../docs_src/extra_models/tutorial004_py39.py!}
- ```
+//// tab | Python 3.8+
-=== "Python 3.8+"
+```Python hl_lines="1 20"
+{!> ../../../docs_src/extra_models/tutorial004.py!}
+```
- ```Python hl_lines="1 20"
- {!> ../../../docs_src/extra_models/tutorial004.py!}
- ```
+////
## Response with arbitrary `dict`
In this case, you can use `typing.Dict` (or just `dict` in Python 3.9 and above):
-=== "Python 3.9+"
+//// tab | Python 3.9+
- ```Python hl_lines="6"
- {!> ../../../docs_src/extra_models/tutorial005_py39.py!}
- ```
+```Python hl_lines="6"
+{!> ../../../docs_src/extra_models/tutorial005_py39.py!}
+```
-=== "Python 3.8+"
+////
+
+//// tab | Python 3.8+
+
+```Python hl_lines="1 8"
+{!> ../../../docs_src/extra_models/tutorial005.py!}
+```
- ```Python hl_lines="1 8"
- {!> ../../../docs_src/extra_models/tutorial005.py!}
- ```
+////
## Recap
`FastAPI` is a Python class that provides all the functionality for your API.
-!!! note "Technical Details"
- `FastAPI` is a class that inherits directly from `Starlette`.
+/// note | "Technical Details"
- You can use all the <a href="https://www.starlette.io/" class="external-link" target="_blank">Starlette</a> functionality with `FastAPI` too.
+`FastAPI` is a class that inherits directly from `Starlette`.
+
+You can use all the <a href="https://www.starlette.io/" class="external-link" target="_blank">Starlette</a> functionality with `FastAPI` too.
+
+///
### Step 2: create a `FastAPI` "instance"
/items/foo
```
-!!! info
- A "path" is also commonly called an "endpoint" or a "route".
+/// info
+
+A "path" is also commonly called an "endpoint" or a "route".
+
+///
While building an API, the "path" is the main way to separate "concerns" and "resources".
* the path `/`
* using a <abbr title="an HTTP GET method"><code>get</code> operation</abbr>
-!!! info "`@decorator` Info"
- That `@something` syntax in Python is called a "decorator".
+/// info | "`@decorator` Info"
+
+That `@something` syntax in Python is called a "decorator".
- You put it on top of a function. Like a pretty decorative hat (I guess that's where the term came from).
+You put it on top of a function. Like a pretty decorative hat (I guess that's where the term came from).
- A "decorator" takes the function below and does something with it.
+A "decorator" takes the function below and does something with it.
- In our case, this decorator tells **FastAPI** that the function below corresponds to the **path** `/` with an **operation** `get`.
+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**".
+It is the "**path operation decorator**".
+
+///
You can also use the other operations:
* `@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**
{!../../../docs_src/first_steps/tutorial003.py!}
```
-!!! 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
}
```
-!!! tip
- When raising an `HTTPException`, you can pass any value that can be converted to JSON as the parameter `detail`, not only `str`.
+/// tip
- You could pass a `dict`, a `list`, etc.
+When raising an `HTTPException`, you can pass any value that can be converted to JSON as the parameter `detail`, not only `str`.
- They are handled automatically by **FastAPI** and converted to JSON.
+You could pass a `dict`, a `list`, etc.
+
+They are handled automatically by **FastAPI** and converted to JSON.
+
+///
## Add custom headers
{"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
#### `RequestValidationError` vs `ValidationError`
-!!! warning
- These are technical details that you might skip if it's not important for you now.
+/// warning
+
+These are technical details that you might skip if it's not important for you now.
+
+///
`RequestValidationError` is a sub-class of Pydantic's <a href="https://docs.pydantic.dev/latest/concepts/models/#error-handling" class="external-link" target="_blank">`ValidationError`</a>.
{!../../../docs_src/handling_errors/tutorial004.py!}
```
-!!! note "Technical Details"
- You could also use `from starlette.responses import PlainTextResponse`.
+/// note | "Technical Details"
+
+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
First import `Header`:
-=== "Python 3.10+"
+//// tab | Python 3.10+
- ```Python hl_lines="3"
- {!> ../../../docs_src/header_params/tutorial001_an_py310.py!}
- ```
+```Python hl_lines="3"
+{!> ../../../docs_src/header_params/tutorial001_an_py310.py!}
+```
+
+////
-=== "Python 3.9+"
+//// tab | Python 3.9+
- ```Python hl_lines="3"
- {!> ../../../docs_src/header_params/tutorial001_an_py39.py!}
- ```
+```Python hl_lines="3"
+{!> ../../../docs_src/header_params/tutorial001_an_py39.py!}
+```
-=== "Python 3.8+"
+////
- ```Python hl_lines="3"
- {!> ../../../docs_src/header_params/tutorial001_an.py!}
- ```
+//// tab | Python 3.8+
+
+```Python hl_lines="3"
+{!> ../../../docs_src/header_params/tutorial001_an.py!}
+```
-=== "Python 3.10+ non-Annotated"
+////
- !!! tip
- Prefer to use the `Annotated` version if possible.
+//// tab | Python 3.10+ non-Annotated
- ```Python hl_lines="1"
- {!> ../../../docs_src/header_params/tutorial001_py310.py!}
- ```
+/// tip
+
+Prefer to use the `Annotated` version if possible.
+
+///
+
+```Python hl_lines="1"
+{!> ../../../docs_src/header_params/tutorial001_py310.py!}
+```
-=== "Python 3.8+ non-Annotated"
+////
- !!! tip
- Prefer to use the `Annotated` version if possible.
+//// tab | Python 3.8+ non-Annotated
- ```Python hl_lines="3"
- {!> ../../../docs_src/header_params/tutorial001.py!}
- ```
+/// tip
+
+Prefer to use the `Annotated` version if possible.
+
+///
+
+```Python hl_lines="3"
+{!> ../../../docs_src/header_params/tutorial001.py!}
+```
+
+////
## Declare `Header` parameters
The first value is the default value, you can pass all the extra validation or annotation parameters:
-=== "Python 3.10+"
+//// tab | Python 3.10+
- ```Python hl_lines="9"
- {!> ../../../docs_src/header_params/tutorial001_an_py310.py!}
- ```
+```Python hl_lines="9"
+{!> ../../../docs_src/header_params/tutorial001_an_py310.py!}
+```
-=== "Python 3.9+"
+////
- ```Python hl_lines="9"
- {!> ../../../docs_src/header_params/tutorial001_an_py39.py!}
- ```
+//// tab | Python 3.9+
-=== "Python 3.8+"
+```Python hl_lines="9"
+{!> ../../../docs_src/header_params/tutorial001_an_py39.py!}
+```
- ```Python hl_lines="10"
- {!> ../../../docs_src/header_params/tutorial001_an.py!}
- ```
+////
-=== "Python 3.10+ non-Annotated"
+//// tab | Python 3.8+
- !!! tip
- Prefer to use the `Annotated` version if possible.
+```Python hl_lines="10"
+{!> ../../../docs_src/header_params/tutorial001_an.py!}
+```
- ```Python hl_lines="7"
- {!> ../../../docs_src/header_params/tutorial001_py310.py!}
- ```
+////
-=== "Python 3.8+ non-Annotated"
+//// tab | Python 3.10+ non-Annotated
- !!! tip
- Prefer to use the `Annotated` version if possible.
+/// tip
- ```Python hl_lines="9"
- {!> ../../../docs_src/header_params/tutorial001.py!}
- ```
+Prefer to use the `Annotated` version if possible.
-!!! note "Technical Details"
- `Header` is a "sister" class of `Path`, `Query` and `Cookie`. It also inherits from the same common `Param` class.
+///
- But remember that when you import `Query`, `Path`, `Header`, and others from `fastapi`, those are actually functions that return special classes.
+```Python hl_lines="7"
+{!> ../../../docs_src/header_params/tutorial001_py310.py!}
+```
+
+////
+
+//// tab | Python 3.8+ non-Annotated
+
+/// tip
+
+Prefer to use the `Annotated` version if possible.
+
+///
+
+```Python hl_lines="9"
+{!> ../../../docs_src/header_params/tutorial001.py!}
+```
-!!! info
- To declare headers, you need to use `Header`, because otherwise the parameters would be interpreted as query parameters.
+////
+
+/// note | "Technical Details"
+
+`Header` is a "sister" class of `Path`, `Query` and `Cookie`. It also inherits from the same common `Param` class.
+
+But remember that when you import `Query`, `Path`, `Header`, and others from `fastapi`, those are actually functions that return special classes.
+
+///
+
+/// info
+
+To declare headers, you need to use `Header`, because otherwise the parameters would be interpreted as query parameters.
+
+///
## Automatic conversion
If for some reason you need to disable automatic conversion of underscores to hyphens, set the parameter `convert_underscores` of `Header` to `False`:
-=== "Python 3.10+"
+//// tab | Python 3.10+
+
+```Python hl_lines="10"
+{!> ../../../docs_src/header_params/tutorial002_an_py310.py!}
+```
+
+////
- ```Python hl_lines="10"
- {!> ../../../docs_src/header_params/tutorial002_an_py310.py!}
- ```
+//// tab | Python 3.9+
-=== "Python 3.9+"
+```Python hl_lines="11"
+{!> ../../../docs_src/header_params/tutorial002_an_py39.py!}
+```
- ```Python hl_lines="11"
- {!> ../../../docs_src/header_params/tutorial002_an_py39.py!}
- ```
+////
-=== "Python 3.8+"
+//// tab | Python 3.8+
+
+```Python hl_lines="12"
+{!> ../../../docs_src/header_params/tutorial002_an.py!}
+```
- ```Python hl_lines="12"
- {!> ../../../docs_src/header_params/tutorial002_an.py!}
- ```
+////
-=== "Python 3.10+ non-Annotated"
+//// tab | Python 3.10+ non-Annotated
- !!! tip
- Prefer to use the `Annotated` version if possible.
+/// tip
+
+Prefer to use the `Annotated` version if possible.
+
+///
+
+```Python hl_lines="8"
+{!> ../../../docs_src/header_params/tutorial002_py310.py!}
+```
- ```Python hl_lines="8"
- {!> ../../../docs_src/header_params/tutorial002_py310.py!}
- ```
+////
-=== "Python 3.8+ non-Annotated"
+//// tab | Python 3.8+ non-Annotated
- !!! tip
- Prefer to use the `Annotated` version if possible.
+/// tip
- ```Python hl_lines="10"
- {!> ../../../docs_src/header_params/tutorial002.py!}
- ```
+Prefer to use the `Annotated` version if possible.
-!!! warning
- Before setting `convert_underscores` to `False`, bear in mind that some HTTP proxies and servers disallow the usage of headers with underscores.
+///
+
+```Python hl_lines="10"
+{!> ../../../docs_src/header_params/tutorial002.py!}
+```
+
+////
+
+/// warning
+
+Before setting `convert_underscores` to `False`, bear in mind that some HTTP proxies and servers disallow the usage of headers with underscores.
+
+///
## Duplicate headers
For example, to declare a header of `X-Token` that can appear more than once, you can write:
-=== "Python 3.10+"
+//// tab | Python 3.10+
- ```Python hl_lines="9"
- {!> ../../../docs_src/header_params/tutorial003_an_py310.py!}
- ```
+```Python hl_lines="9"
+{!> ../../../docs_src/header_params/tutorial003_an_py310.py!}
+```
-=== "Python 3.9+"
+////
- ```Python hl_lines="9"
- {!> ../../../docs_src/header_params/tutorial003_an_py39.py!}
- ```
+//// tab | Python 3.9+
-=== "Python 3.8+"
+```Python hl_lines="9"
+{!> ../../../docs_src/header_params/tutorial003_an_py39.py!}
+```
- ```Python hl_lines="10"
- {!> ../../../docs_src/header_params/tutorial003_an.py!}
- ```
+////
-=== "Python 3.10+ non-Annotated"
+//// tab | Python 3.8+
- !!! tip
- Prefer to use the `Annotated` version if possible.
+```Python hl_lines="10"
+{!> ../../../docs_src/header_params/tutorial003_an.py!}
+```
+
+////
+
+//// tab | Python 3.10+ non-Annotated
+
+/// tip
+
+Prefer to use the `Annotated` version if possible.
+
+///
+
+```Python hl_lines="7"
+{!> ../../../docs_src/header_params/tutorial003_py310.py!}
+```
- ```Python hl_lines="7"
- {!> ../../../docs_src/header_params/tutorial003_py310.py!}
- ```
+////
-=== "Python 3.9+ non-Annotated"
+//// tab | Python 3.9+ non-Annotated
- !!! tip
- Prefer to use the `Annotated` version if possible.
+/// tip
- ```Python hl_lines="9"
- {!> ../../../docs_src/header_params/tutorial003_py39.py!}
- ```
+Prefer to use the `Annotated` version if possible.
-=== "Python 3.8+ non-Annotated"
+///
- !!! tip
- Prefer to use the `Annotated` version if possible.
+```Python hl_lines="9"
+{!> ../../../docs_src/header_params/tutorial003_py39.py!}
+```
+
+////
+
+//// tab | Python 3.8+ non-Annotated
+
+/// tip
+
+Prefer to use the `Annotated` version if possible.
+
+///
+
+```Python hl_lines="9"
+{!> ../../../docs_src/header_params/tutorial003.py!}
+```
- ```Python hl_lines="9"
- {!> ../../../docs_src/header_params/tutorial003.py!}
- ```
+////
If you communicate with that *path operation* sending two HTTP headers like:
</div>
-!!! note
- When you install with `pip install "fastapi[standard]"` it comes with some default optional standard dependencies.
+/// note
- If you don't want to have those optional dependencies, you can instead install `pip install fastapi`.
+When you install with `pip install "fastapi[standard]"` it comes with some default optional standard dependencies.
+
+If you don't want to have those optional dependencies, you can instead install `pip install fastapi`.
+
+///
## Advanced User Guide
{!../../../docs_src/metadata/tutorial001.py!}
```
-!!! tip
- You can write Markdown in the `description` field and it will be rendered in the output.
+/// tip
+
+You can write Markdown in the `description` field and it will be rendered in the output.
+
+///
With this configuration, the automatic API docs would look like:
Notice that you can use Markdown inside of the descriptions, for example "login" will be shown in bold (**login**) and "fancy" will be shown in italics (_fancy_).
-!!! tip
- You don't have to add metadata for all the tags that you use.
+/// tip
+
+You don't have to add metadata for all the tags that you use.
+
+///
### Use your tags
{!../../../docs_src/metadata/tutorial004.py!}
```
-!!! info
- Read more about tags in [Path Operation Configuration](path-operation-configuration.md#tags){.internal-link target=_blank}.
+/// info
+
+Read more about tags in [Path Operation Configuration](path-operation-configuration.md#tags){.internal-link target=_blank}.
+
+///
### Check the docs
* It can do something to that **response** or run any needed code.
* Then it returns the **response**.
-!!! note "Technical Details"
- If you have dependencies with `yield`, the exit code will run *after* the middleware.
+/// note | "Technical Details"
- If there were any background tasks (documented later), they will run *after* all the middleware.
+If you have dependencies with `yield`, the exit code will run *after* the middleware.
+
+If there were any background tasks (documented later), they will run *after* all the middleware.
+
+///
## Create a middleware
{!../../../docs_src/middleware/tutorial001.py!}
```
-!!! tip
- Keep in mind that custom proprietary headers can be added <a href="https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers" class="external-link" target="_blank">using the 'X-' prefix</a>.
+/// tip
+
+Keep in mind that custom proprietary headers can be added <a href="https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers" class="external-link" target="_blank">using the 'X-' prefix</a>.
+
+But if you have custom headers that you want a client in a browser to be able to see, you need to add them to your CORS configurations ([CORS (Cross-Origin Resource Sharing)](cors.md){.internal-link target=_blank}) using the parameter `expose_headers` documented in <a href="https://www.starlette.io/middleware/#corsmiddleware" class="external-link" target="_blank">Starlette's CORS docs</a>.
+
+///
+
+/// note | "Technical Details"
- But if you have custom headers that you want a client in a browser to be able to see, you need to add them to your CORS configurations ([CORS (Cross-Origin Resource Sharing)](cors.md){.internal-link target=_blank}) using the parameter `expose_headers` documented in <a href="https://www.starlette.io/middleware/#corsmiddleware" class="external-link" target="_blank">Starlette's CORS docs</a>.
+You could also use `from starlette.requests import Request`.
-!!! note "Technical Details"
- You could also use `from starlette.requests import Request`.
+**FastAPI** provides it as a convenience for you, the developer. But it comes directly from Starlette.
- **FastAPI** provides it as a convenience for you, the developer. But it comes directly from Starlette.
+///
### Before and after the `response`
There are several parameters that you can pass to your *path operation decorator* to configure it.
-!!! warning
- Notice that these parameters are passed directly to the *path operation decorator*, not to your *path operation function*.
+/// warning
+
+Notice that these parameters are passed directly to the *path operation decorator*, not to your *path operation function*.
+
+///
## Response Status Code
But if you don't remember what each number code is for, you can use the shortcut constants in `status`:
-=== "Python 3.10+"
+//// tab | Python 3.10+
+
+```Python hl_lines="1 15"
+{!> ../../../docs_src/path_operation_configuration/tutorial001_py310.py!}
+```
+
+////
- ```Python hl_lines="1 15"
- {!> ../../../docs_src/path_operation_configuration/tutorial001_py310.py!}
- ```
+//// tab | Python 3.9+
-=== "Python 3.9+"
+```Python hl_lines="3 17"
+{!> ../../../docs_src/path_operation_configuration/tutorial001_py39.py!}
+```
+
+////
- ```Python hl_lines="3 17"
- {!> ../../../docs_src/path_operation_configuration/tutorial001_py39.py!}
- ```
+//// tab | Python 3.8+
-=== "Python 3.8+"
+```Python hl_lines="3 17"
+{!> ../../../docs_src/path_operation_configuration/tutorial001.py!}
+```
- ```Python hl_lines="3 17"
- {!> ../../../docs_src/path_operation_configuration/tutorial001.py!}
- ```
+////
That status code will be used in the response and will be added to the OpenAPI schema.
-!!! note "Technical Details"
- You could also use `from starlette import status`.
+/// note | "Technical Details"
+
+You could also use `from starlette import status`.
+
+**FastAPI** provides the same `starlette.status` as `fastapi.status` just as a convenience for you, the developer. But it comes directly from Starlette.
- **FastAPI** provides the same `starlette.status` as `fastapi.status` just as a convenience for you, the developer. But it comes directly from Starlette.
+///
## Tags
You can add tags to your *path operation*, pass the parameter `tags` with a `list` of `str` (commonly just one `str`):
-=== "Python 3.10+"
+//// tab | Python 3.10+
- ```Python hl_lines="15 20 25"
- {!> ../../../docs_src/path_operation_configuration/tutorial002_py310.py!}
- ```
+```Python hl_lines="15 20 25"
+{!> ../../../docs_src/path_operation_configuration/tutorial002_py310.py!}
+```
+
+////
-=== "Python 3.9+"
+//// tab | Python 3.9+
- ```Python hl_lines="17 22 27"
- {!> ../../../docs_src/path_operation_configuration/tutorial002_py39.py!}
- ```
+```Python hl_lines="17 22 27"
+{!> ../../../docs_src/path_operation_configuration/tutorial002_py39.py!}
+```
-=== "Python 3.8+"
+////
- ```Python hl_lines="17 22 27"
- {!> ../../../docs_src/path_operation_configuration/tutorial002.py!}
- ```
+//// tab | Python 3.8+
+
+```Python hl_lines="17 22 27"
+{!> ../../../docs_src/path_operation_configuration/tutorial002.py!}
+```
+
+////
They will be added to the OpenAPI schema and used by the automatic documentation interfaces:
You can add a `summary` and `description`:
-=== "Python 3.10+"
+//// tab | Python 3.10+
+
+```Python hl_lines="18-19"
+{!> ../../../docs_src/path_operation_configuration/tutorial003_py310.py!}
+```
+
+////
- ```Python hl_lines="18-19"
- {!> ../../../docs_src/path_operation_configuration/tutorial003_py310.py!}
- ```
+//// tab | Python 3.9+
-=== "Python 3.9+"
+```Python hl_lines="20-21"
+{!> ../../../docs_src/path_operation_configuration/tutorial003_py39.py!}
+```
+
+////
- ```Python hl_lines="20-21"
- {!> ../../../docs_src/path_operation_configuration/tutorial003_py39.py!}
- ```
+//// tab | Python 3.8+
-=== "Python 3.8+"
+```Python hl_lines="20-21"
+{!> ../../../docs_src/path_operation_configuration/tutorial003.py!}
+```
- ```Python hl_lines="20-21"
- {!> ../../../docs_src/path_operation_configuration/tutorial003.py!}
- ```
+////
## Description from docstring
You can write <a href="https://en.wikipedia.org/wiki/Markdown" class="external-link" target="_blank">Markdown</a> in the docstring, it will be interpreted and displayed correctly (taking into account docstring indentation).
-=== "Python 3.10+"
+//// tab | Python 3.10+
+
+```Python hl_lines="17-25"
+{!> ../../../docs_src/path_operation_configuration/tutorial004_py310.py!}
+```
+
+////
- ```Python hl_lines="17-25"
- {!> ../../../docs_src/path_operation_configuration/tutorial004_py310.py!}
- ```
+//// tab | Python 3.9+
-=== "Python 3.9+"
+```Python hl_lines="19-27"
+{!> ../../../docs_src/path_operation_configuration/tutorial004_py39.py!}
+```
- ```Python hl_lines="19-27"
- {!> ../../../docs_src/path_operation_configuration/tutorial004_py39.py!}
- ```
+////
-=== "Python 3.8+"
+//// tab | Python 3.8+
- ```Python hl_lines="19-27"
- {!> ../../../docs_src/path_operation_configuration/tutorial004.py!}
- ```
+```Python hl_lines="19-27"
+{!> ../../../docs_src/path_operation_configuration/tutorial004.py!}
+```
+
+////
It will be used in the interactive docs:
You can specify the response description with the parameter `response_description`:
-=== "Python 3.10+"
+//// tab | Python 3.10+
+
+```Python hl_lines="19"
+{!> ../../../docs_src/path_operation_configuration/tutorial005_py310.py!}
+```
+
+////
+
+//// tab | Python 3.9+
+
+```Python hl_lines="21"
+{!> ../../../docs_src/path_operation_configuration/tutorial005_py39.py!}
+```
+
+////
+
+//// tab | Python 3.8+
+
+```Python hl_lines="21"
+{!> ../../../docs_src/path_operation_configuration/tutorial005.py!}
+```
- ```Python hl_lines="19"
- {!> ../../../docs_src/path_operation_configuration/tutorial005_py310.py!}
- ```
+////
-=== "Python 3.9+"
+/// info
- ```Python hl_lines="21"
- {!> ../../../docs_src/path_operation_configuration/tutorial005_py39.py!}
- ```
+Notice that `response_description` refers specifically to the response, the `description` refers to the *path operation* in general.
-=== "Python 3.8+"
+///
- ```Python hl_lines="21"
- {!> ../../../docs_src/path_operation_configuration/tutorial005.py!}
- ```
+/// check
-!!! info
- Notice that `response_description` refers specifically to the response, the `description` refers to the *path operation* in general.
+OpenAPI specifies that each *path operation* requires a response description.
-!!! check
- OpenAPI specifies that each *path operation* requires a response description.
+So, if you don't provide one, **FastAPI** will automatically generate one of "Successful response".
- So, if you don't provide one, **FastAPI** will automatically generate one of "Successful response".
+///
<img src="/img/tutorial/path-operation-configuration/image03.png">
First, import `Path` from `fastapi`, and import `Annotated`:
-=== "Python 3.10+"
+//// tab | Python 3.10+
- ```Python hl_lines="1 3"
- {!> ../../../docs_src/path_params_numeric_validations/tutorial001_an_py310.py!}
- ```
+```Python hl_lines="1 3"
+{!> ../../../docs_src/path_params_numeric_validations/tutorial001_an_py310.py!}
+```
+
+////
+
+//// tab | Python 3.9+
+
+```Python hl_lines="1 3"
+{!> ../../../docs_src/path_params_numeric_validations/tutorial001_an_py39.py!}
+```
+
+////
+
+//// tab | Python 3.8+
+
+```Python hl_lines="3-4"
+{!> ../../../docs_src/path_params_numeric_validations/tutorial001_an.py!}
+```
+
+////
-=== "Python 3.9+"
+//// tab | Python 3.10+ non-Annotated
- ```Python hl_lines="1 3"
- {!> ../../../docs_src/path_params_numeric_validations/tutorial001_an_py39.py!}
- ```
+/// tip
-=== "Python 3.8+"
+Prefer to use the `Annotated` version if possible.
- ```Python hl_lines="3-4"
- {!> ../../../docs_src/path_params_numeric_validations/tutorial001_an.py!}
- ```
+///
-=== "Python 3.10+ non-Annotated"
+```Python hl_lines="1"
+{!> ../../../docs_src/path_params_numeric_validations/tutorial001_py310.py!}
+```
+
+////
+
+//// tab | Python 3.8+ non-Annotated
+
+/// tip
+
+Prefer to use the `Annotated` version if possible.
- !!! tip
- Prefer to use the `Annotated` version if possible.
+///
- ```Python hl_lines="1"
- {!> ../../../docs_src/path_params_numeric_validations/tutorial001_py310.py!}
- ```
+```Python hl_lines="3"
+{!> ../../../docs_src/path_params_numeric_validations/tutorial001.py!}
+```
-=== "Python 3.8+ non-Annotated"
+////
- !!! tip
- Prefer to use the `Annotated` version if possible.
+/// info
- ```Python hl_lines="3"
- {!> ../../../docs_src/path_params_numeric_validations/tutorial001.py!}
- ```
+FastAPI added support for `Annotated` (and started recommending it) in version 0.95.0.
-!!! info
- FastAPI added support for `Annotated` (and started recommending it) in version 0.95.0.
+If you have an older version, you would get errors when trying to use `Annotated`.
- If you have an older version, you would get errors when trying to use `Annotated`.
+Make sure you [Upgrade the FastAPI version](../deployment/versions.md#upgrading-the-fastapi-versions){.internal-link target=_blank} to at least 0.95.1 before using `Annotated`.
- Make sure you [Upgrade the FastAPI version](../deployment/versions.md#upgrading-the-fastapi-versions){.internal-link target=_blank} to at least 0.95.1 before using `Annotated`.
+///
## Declare metadata
For example, to declare a `title` metadata value for the path parameter `item_id` you can type:
-=== "Python 3.10+"
+//// tab | Python 3.10+
- ```Python hl_lines="10"
- {!> ../../../docs_src/path_params_numeric_validations/tutorial001_an_py310.py!}
- ```
+```Python hl_lines="10"
+{!> ../../../docs_src/path_params_numeric_validations/tutorial001_an_py310.py!}
+```
-=== "Python 3.9+"
+////
- ```Python hl_lines="10"
- {!> ../../../docs_src/path_params_numeric_validations/tutorial001_an_py39.py!}
- ```
+//// tab | Python 3.9+
-=== "Python 3.8+"
+```Python hl_lines="10"
+{!> ../../../docs_src/path_params_numeric_validations/tutorial001_an_py39.py!}
+```
- ```Python hl_lines="11"
- {!> ../../../docs_src/path_params_numeric_validations/tutorial001_an.py!}
- ```
+////
-=== "Python 3.10+ non-Annotated"
+//// tab | Python 3.8+
- !!! tip
- Prefer to use the `Annotated` version if possible.
+```Python hl_lines="11"
+{!> ../../../docs_src/path_params_numeric_validations/tutorial001_an.py!}
+```
- ```Python hl_lines="8"
- {!> ../../../docs_src/path_params_numeric_validations/tutorial001_py310.py!}
- ```
+////
-=== "Python 3.8+ non-Annotated"
+//// tab | Python 3.10+ non-Annotated
- !!! tip
- Prefer to use the `Annotated` version if possible.
+/// tip
- ```Python hl_lines="10"
- {!> ../../../docs_src/path_params_numeric_validations/tutorial001.py!}
- ```
+Prefer to use the `Annotated` version if possible.
-!!! note
- A path parameter is always required as it has to be part of the path. Even if you declared it with `None` or set a default value, it would not affect anything, it would still be always required.
+///
+
+```Python hl_lines="8"
+{!> ../../../docs_src/path_params_numeric_validations/tutorial001_py310.py!}
+```
+
+////
+
+//// tab | Python 3.8+ non-Annotated
+
+/// tip
+
+Prefer to use the `Annotated` version if possible.
+
+///
+
+```Python hl_lines="10"
+{!> ../../../docs_src/path_params_numeric_validations/tutorial001.py!}
+```
+
+////
+
+/// note
+
+A path parameter is always required as it has to be part of the path. Even if you declared it with `None` or set a default value, it would not affect anything, it would still be always required.
+
+///
## Order the parameters as you need
-!!! tip
- This is probably not as important or necessary if you use `Annotated`.
+/// tip
+
+This is probably not as important or necessary if you use `Annotated`.
+
+///
Let's say that you want to declare the query parameter `q` as a required `str`.
So, you can declare your function as:
-=== "Python 3.8 non-Annotated"
+//// tab | Python 3.8 non-Annotated
+
+/// tip
- !!! tip
- Prefer to use the `Annotated` version if possible.
+Prefer to use the `Annotated` version if possible.
+
+///
+
+```Python hl_lines="7"
+{!> ../../../docs_src/path_params_numeric_validations/tutorial002.py!}
+```
- ```Python hl_lines="7"
- {!> ../../../docs_src/path_params_numeric_validations/tutorial002.py!}
- ```
+////
But keep in mind that if you use `Annotated`, you won't have this problem, it won't matter as you're not using the function parameter default values for `Query()` or `Path()`.
-=== "Python 3.9+"
+//// tab | Python 3.9+
- ```Python hl_lines="10"
- {!> ../../../docs_src/path_params_numeric_validations/tutorial002_an_py39.py!}
- ```
+```Python hl_lines="10"
+{!> ../../../docs_src/path_params_numeric_validations/tutorial002_an_py39.py!}
+```
+
+////
-=== "Python 3.8+"
+//// tab | Python 3.8+
- ```Python hl_lines="9"
- {!> ../../../docs_src/path_params_numeric_validations/tutorial002_an.py!}
- ```
+```Python hl_lines="9"
+{!> ../../../docs_src/path_params_numeric_validations/tutorial002_an.py!}
+```
+
+////
## Order the parameters as you need, tricks
-!!! tip
- This is probably not as important or necessary if you use `Annotated`.
+/// tip
+
+This is probably not as important or necessary if you use `Annotated`.
+
+///
Here's a **small trick** that can be handy, but you won't need it often.
Keep in mind that if you use `Annotated`, as you are not using function parameter default values, you won't have this problem, and you probably won't need to use `*`.
-=== "Python 3.9+"
+//// tab | Python 3.9+
+
+```Python hl_lines="10"
+{!> ../../../docs_src/path_params_numeric_validations/tutorial003_an_py39.py!}
+```
- ```Python hl_lines="10"
- {!> ../../../docs_src/path_params_numeric_validations/tutorial003_an_py39.py!}
- ```
+////
-=== "Python 3.8+"
+//// tab | Python 3.8+
+
+```Python hl_lines="9"
+{!> ../../../docs_src/path_params_numeric_validations/tutorial003_an.py!}
+```
- ```Python hl_lines="9"
- {!> ../../../docs_src/path_params_numeric_validations/tutorial003_an.py!}
- ```
+////
## Number validations: greater than or equal
Here, with `ge=1`, `item_id` will need to be an integer number "`g`reater than or `e`qual" to `1`.
-=== "Python 3.9+"
+//// tab | Python 3.9+
- ```Python hl_lines="10"
- {!> ../../../docs_src/path_params_numeric_validations/tutorial004_an_py39.py!}
- ```
+```Python hl_lines="10"
+{!> ../../../docs_src/path_params_numeric_validations/tutorial004_an_py39.py!}
+```
+
+////
+
+//// tab | Python 3.8+
+
+```Python hl_lines="9"
+{!> ../../../docs_src/path_params_numeric_validations/tutorial004_an.py!}
+```
-=== "Python 3.8+"
+////
- ```Python hl_lines="9"
- {!> ../../../docs_src/path_params_numeric_validations/tutorial004_an.py!}
- ```
+//// tab | Python 3.8+ non-Annotated
-=== "Python 3.8+ non-Annotated"
+/// tip
- !!! tip
- Prefer to use the `Annotated` version if possible.
+Prefer to use the `Annotated` version if possible.
- ```Python hl_lines="8"
- {!> ../../../docs_src/path_params_numeric_validations/tutorial004.py!}
- ```
+///
+
+```Python hl_lines="8"
+{!> ../../../docs_src/path_params_numeric_validations/tutorial004.py!}
+```
+
+////
## Number validations: greater than and less than or equal
* `gt`: `g`reater `t`han
* `le`: `l`ess than or `e`qual
-=== "Python 3.9+"
+//// tab | Python 3.9+
+
+```Python hl_lines="10"
+{!> ../../../docs_src/path_params_numeric_validations/tutorial005_an_py39.py!}
+```
+
+////
+
+//// tab | Python 3.8+
+
+```Python hl_lines="9"
+{!> ../../../docs_src/path_params_numeric_validations/tutorial005_an.py!}
+```
- ```Python hl_lines="10"
- {!> ../../../docs_src/path_params_numeric_validations/tutorial005_an_py39.py!}
- ```
+////
-=== "Python 3.8+"
+//// tab | Python 3.8+ non-Annotated
- ```Python hl_lines="9"
- {!> ../../../docs_src/path_params_numeric_validations/tutorial005_an.py!}
- ```
+/// tip
-=== "Python 3.8+ non-Annotated"
+Prefer to use the `Annotated` version if possible.
- !!! tip
- Prefer to use the `Annotated` version if possible.
+///
- ```Python hl_lines="9"
- {!> ../../../docs_src/path_params_numeric_validations/tutorial005.py!}
- ```
+```Python hl_lines="9"
+{!> ../../../docs_src/path_params_numeric_validations/tutorial005.py!}
+```
+
+////
## Number validations: floats, greater than and less than
And the same for <abbr title="less than"><code>lt</code></abbr>.
-=== "Python 3.9+"
+//// tab | Python 3.9+
- ```Python hl_lines="13"
- {!> ../../../docs_src/path_params_numeric_validations/tutorial006_an_py39.py!}
- ```
+```Python hl_lines="13"
+{!> ../../../docs_src/path_params_numeric_validations/tutorial006_an_py39.py!}
+```
-=== "Python 3.8+"
+////
- ```Python hl_lines="12"
- {!> ../../../docs_src/path_params_numeric_validations/tutorial006_an.py!}
- ```
+//// tab | Python 3.8+
+
+```Python hl_lines="12"
+{!> ../../../docs_src/path_params_numeric_validations/tutorial006_an.py!}
+```
-=== "Python 3.8+ non-Annotated"
+////
- !!! tip
- Prefer to use the `Annotated` version if possible.
+//// tab | Python 3.8+ non-Annotated
- ```Python hl_lines="11"
- {!> ../../../docs_src/path_params_numeric_validations/tutorial006.py!}
- ```
+/// tip
+
+Prefer to use the `Annotated` version if possible.
+
+///
+
+```Python hl_lines="11"
+{!> ../../../docs_src/path_params_numeric_validations/tutorial006.py!}
+```
+
+////
## Recap
* `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.
+///
In this case, `item_id` is declared to be an `int`.
-!!! check
- This will give you editor support inside of your function, with error checks, completion, etc.
+/// check
+
+This will give you editor support inside of your function, with error checks, completion, etc.
+
+///
## Data <abbr title="also known as: serialization, parsing, marshalling">conversion</abbr>
{"item_id":3}
```
-!!! check
- Notice that the value your function received (and returned) is `3`, as a Python `int`, not a string `"3"`.
+/// check
+
+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 <abbr title="converting the string that comes from an HTTP request into Python data">"parsing"</abbr>.
- So, with that type declaration, **FastAPI** gives you automatic request <abbr title="converting the string that comes from an HTTP request into Python data">"parsing"</abbr>.
+///
## Data validation
The same error would appear if you provided a `float` instead of an `int`, as in: <a href="http://127.0.0.1:8000/items/4.2" class="external-link" target="_blank">http://127.0.0.1:8000/items/4.2</a>
-!!! check
- So, with the same Python type declaration, **FastAPI** gives you data validation.
+/// check
- Notice that the error also clearly states exactly the point where the validation didn't pass.
+So, with the same Python type declaration, **FastAPI** gives you data validation.
- This is incredibly helpful while developing and debugging code that interacts with your API.
+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.
+
+///
## Documentation
<img src="/img/tutorial/path-params/image01.png">
-!!! 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
{!../../../docs_src/path_params/tutorial005.py!}
```
-!!! info
- <a href="https://docs.python.org/3/library/enum.html" class="external-link" target="_blank">Enumerations (or enums) are available in Python</a> since version 3.4.
+/// info
-!!! tip
- If you are wondering, "AlexNet", "ResNet", and "LeNet" are just names of Machine Learning <abbr title="Technically, Deep Learning model architectures">models</abbr>.
+<a href="https://docs.python.org/3/library/enum.html" class="external-link" target="_blank">Enumerations (or enums) are available in Python</a> since version 3.4.
+
+///
+
+/// tip
+
+If you are wondering, "AlexNet", "ResNet", and "LeNet" are just names of Machine Learning <abbr title="Technically, Deep Learning model architectures">models</abbr>.
+
+///
### Declare a *path parameter*
{!../../../docs_src/path_params/tutorial005.py!}
```
-!!! 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*
{!../../../docs_src/path_params/tutorial004.py!}
```
-!!! 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
Let's take this application as example:
-=== "Python 3.10+"
+//// tab | Python 3.10+
- ```Python hl_lines="7"
- {!> ../../../docs_src/query_params_str_validations/tutorial001_py310.py!}
- ```
+```Python hl_lines="7"
+{!> ../../../docs_src/query_params_str_validations/tutorial001_py310.py!}
+```
+
+////
-=== "Python 3.8+"
+//// tab | Python 3.8+
+
+```Python hl_lines="9"
+{!> ../../../docs_src/query_params_str_validations/tutorial001.py!}
+```
- ```Python hl_lines="9"
- {!> ../../../docs_src/query_params_str_validations/tutorial001.py!}
- ```
+////
The query parameter `q` is of type `Union[str, None]` (or `str | None` in Python 3.10), that means that it's of type `str` but could also be `None`, and indeed, the default value is `None`, so FastAPI will know it's not required.
-!!! note
- FastAPI will know that the value of `q` is not required because of the default value `= None`.
+/// note
- The `Union` in `Union[str, None]` will allow your editor to give you better support and detect errors.
+FastAPI will know that the value of `q` is not required because of the default value `= None`.
+
+The `Union` in `Union[str, None]` will allow your editor to give you better support and detect errors.
+
+///
## Additional validation
* `Query` from `fastapi`
* `Annotated` from `typing` (or from `typing_extensions` in Python below 3.9)
-=== "Python 3.10+"
+//// tab | Python 3.10+
+
+In Python 3.9 or above, `Annotated` is part of the standard library, so you can import it from `typing`.
+
+```Python hl_lines="1 3"
+{!> ../../../docs_src/query_params_str_validations/tutorial002_an_py310.py!}
+```
+
+////
- In Python 3.9 or above, `Annotated` is part of the standard library, so you can import it from `typing`.
+//// tab | Python 3.8+
- ```Python hl_lines="1 3"
- {!> ../../../docs_src/query_params_str_validations/tutorial002_an_py310.py!}
- ```
+In versions of Python below Python 3.9 you import `Annotated` from `typing_extensions`.
-=== "Python 3.8+"
+It will already be installed with FastAPI.
+
+```Python hl_lines="3-4"
+{!> ../../../docs_src/query_params_str_validations/tutorial002_an.py!}
+```
- In versions of Python below Python 3.9 you import `Annotated` from `typing_extensions`.
+////
- It will already be installed with FastAPI.
+/// info
- ```Python hl_lines="3-4"
- {!> ../../../docs_src/query_params_str_validations/tutorial002_an.py!}
- ```
+FastAPI added support for `Annotated` (and started recommending it) in version 0.95.0.
-!!! info
- FastAPI added support for `Annotated` (and started recommending it) in version 0.95.0.
+If you have an older version, you would get errors when trying to use `Annotated`.
- If you have an older version, you would get errors when trying to use `Annotated`.
+Make sure you [Upgrade the FastAPI version](../deployment/versions.md#upgrading-the-fastapi-versions){.internal-link target=_blank} to at least 0.95.1 before using `Annotated`.
- Make sure you [Upgrade the FastAPI version](../deployment/versions.md#upgrading-the-fastapi-versions){.internal-link target=_blank} to at least 0.95.1 before using `Annotated`.
+///
## Use `Annotated` in the type for the `q` parameter
We had this type annotation:
-=== "Python 3.10+"
+//// tab | Python 3.10+
- ```Python
- q: str | None = None
- ```
+```Python
+q: str | None = None
+```
-=== "Python 3.8+"
+////
- ```Python
- q: Union[str, None] = None
- ```
+//// tab | Python 3.8+
+
+```Python
+q: Union[str, None] = None
+```
+
+////
What we will do is wrap that with `Annotated`, so it becomes:
-=== "Python 3.10+"
+//// tab | Python 3.10+
- ```Python
- q: Annotated[str | None] = None
- ```
+```Python
+q: Annotated[str | None] = None
+```
-=== "Python 3.8+"
+////
- ```Python
- q: Annotated[Union[str, None]] = None
- ```
+//// tab | Python 3.8+
+
+```Python
+q: Annotated[Union[str, None]] = None
+```
+
+////
Both of those versions mean the same thing, `q` is a parameter that can be a `str` or `None`, and by default, it is `None`.
Now that we have this `Annotated` where we can put more information (in this case some additional validation), add `Query` inside of `Annotated`, and set the parameter `max_length` to `50`:
-=== "Python 3.10+"
+//// tab | Python 3.10+
- ```Python hl_lines="9"
- {!> ../../../docs_src/query_params_str_validations/tutorial002_an_py310.py!}
- ```
+```Python hl_lines="9"
+{!> ../../../docs_src/query_params_str_validations/tutorial002_an_py310.py!}
+```
-=== "Python 3.8+"
+////
- ```Python hl_lines="10"
- {!> ../../../docs_src/query_params_str_validations/tutorial002_an.py!}
- ```
+//// tab | Python 3.8+
+
+```Python hl_lines="10"
+{!> ../../../docs_src/query_params_str_validations/tutorial002_an.py!}
+```
+
+////
Notice that the default value is still `None`, so the parameter is still optional.
But now, having `Query(max_length=50)` inside of `Annotated`, we are telling FastAPI that we want it to have **additional validation** for this value, we want it to have maximum 50 characters. 😎
-!!! tip
+/// tip
+
+Here we are using `Query()` because this is a **query parameter**. Later we will see others like `Path()`, `Body()`, `Header()`, and `Cookie()`, that also accept the same arguments as `Query()`.
- Here we are using `Query()` because this is a **query parameter**. Later we will see others like `Path()`, `Body()`, `Header()`, and `Cookie()`, that also accept the same arguments as `Query()`.
+///
FastAPI will now:
Previous versions of FastAPI (before <abbr title="before 2023-03">0.95.0</abbr>) required you to use `Query` as the default value of your parameter, instead of putting it in `Annotated`, there's a high chance that you will see code using it around, so I'll explain it to you.
-!!! tip
- For new code and whenever possible, use `Annotated` as explained above. There are multiple advantages (explained below) and no disadvantages. 🍰
+/// tip
+
+For new code and whenever possible, use `Annotated` as explained above. There are multiple advantages (explained below) and no disadvantages. 🍰
+
+///
This is how you would use `Query()` as the default value of your function parameter, setting the parameter `max_length` to 50:
-=== "Python 3.10+"
+//// tab | Python 3.10+
+
+```Python hl_lines="7"
+{!> ../../../docs_src/query_params_str_validations/tutorial002_py310.py!}
+```
+
+////
- ```Python hl_lines="7"
- {!> ../../../docs_src/query_params_str_validations/tutorial002_py310.py!}
- ```
+//// tab | Python 3.8+
-=== "Python 3.8+"
+```Python hl_lines="9"
+{!> ../../../docs_src/query_params_str_validations/tutorial002.py!}
+```
- ```Python hl_lines="9"
- {!> ../../../docs_src/query_params_str_validations/tutorial002.py!}
- ```
+////
As in this case (without using `Annotated`) we have to replace the default value `None` in the function with `Query()`, we now need to set the default value with the parameter `Query(default=None)`, it serves the same purpose of defining that default value (at least for FastAPI).
But it declares it explicitly as being a query parameter.
-!!! info
- Keep in mind that the most important part to make a parameter optional is the part:
+/// info
- ```Python
- = None
- ```
+Keep in mind that the most important part to make a parameter optional is the part:
- or the:
+```Python
+= None
+```
- ```Python
- = Query(default=None)
- ```
+or the:
- as it will use that `None` as the default value, and that way make the parameter **not required**.
+```Python
+= Query(default=None)
+```
+
+as it will use that `None` as the default value, and that way make the parameter **not required**.
+
+The `Union[str, None]` part allows your editor to provide better support, but it is not what tells FastAPI that this parameter is not required.
- The `Union[str, None]` part allows your editor to provide better support, but it is not what tells FastAPI that this parameter is not required.
+///
Then, we can pass more parameters to `Query`. In this case, the `max_length` parameter that applies to strings:
You can also add a parameter `min_length`:
-=== "Python 3.10+"
+//// tab | Python 3.10+
+
+```Python hl_lines="10"
+{!> ../../../docs_src/query_params_str_validations/tutorial003_an_py310.py!}
+```
+
+////
- ```Python hl_lines="10"
- {!> ../../../docs_src/query_params_str_validations/tutorial003_an_py310.py!}
- ```
+//// tab | Python 3.9+
-=== "Python 3.9+"
+```Python hl_lines="10"
+{!> ../../../docs_src/query_params_str_validations/tutorial003_an_py39.py!}
+```
+
+////
+
+//// tab | Python 3.8+
+
+```Python hl_lines="11"
+{!> ../../../docs_src/query_params_str_validations/tutorial003_an.py!}
+```
+
+////
- ```Python hl_lines="10"
- {!> ../../../docs_src/query_params_str_validations/tutorial003_an_py39.py!}
- ```
+//// tab | Python 3.10+ non-Annotated
-=== "Python 3.8+"
+/// tip
- ```Python hl_lines="11"
- {!> ../../../docs_src/query_params_str_validations/tutorial003_an.py!}
- ```
+Prefer to use the `Annotated` version if possible.
-=== "Python 3.10+ non-Annotated"
+///
+
+```Python hl_lines="7"
+{!> ../../../docs_src/query_params_str_validations/tutorial003_py310.py!}
+```
- !!! tip
- Prefer to use the `Annotated` version if possible.
+////
- ```Python hl_lines="7"
- {!> ../../../docs_src/query_params_str_validations/tutorial003_py310.py!}
- ```
+//// tab | Python 3.8+ non-Annotated
-=== "Python 3.8+ non-Annotated"
+/// tip
- !!! tip
- Prefer to use the `Annotated` version if possible.
+Prefer to use the `Annotated` version if possible.
- ```Python hl_lines="10"
- {!> ../../../docs_src/query_params_str_validations/tutorial003.py!}
- ```
+///
+
+```Python hl_lines="10"
+{!> ../../../docs_src/query_params_str_validations/tutorial003.py!}
+```
+
+////
## Add regular expressions
You can define a <abbr title="A regular expression, regex or regexp is a sequence of characters that define a search pattern for strings.">regular expression</abbr> `pattern` that the parameter should match:
-=== "Python 3.10+"
+//// tab | Python 3.10+
- ```Python hl_lines="11"
- {!> ../../../docs_src/query_params_str_validations/tutorial004_an_py310.py!}
- ```
+```Python hl_lines="11"
+{!> ../../../docs_src/query_params_str_validations/tutorial004_an_py310.py!}
+```
-=== "Python 3.9+"
+////
- ```Python hl_lines="11"
- {!> ../../../docs_src/query_params_str_validations/tutorial004_an_py39.py!}
- ```
+//// tab | Python 3.9+
-=== "Python 3.8+"
+```Python hl_lines="11"
+{!> ../../../docs_src/query_params_str_validations/tutorial004_an_py39.py!}
+```
+
+////
- ```Python hl_lines="12"
- {!> ../../../docs_src/query_params_str_validations/tutorial004_an.py!}
- ```
+//// tab | Python 3.8+
-=== "Python 3.10+ non-Annotated"
+```Python hl_lines="12"
+{!> ../../../docs_src/query_params_str_validations/tutorial004_an.py!}
+```
- !!! tip
- Prefer to use the `Annotated` version if possible.
+////
- ```Python hl_lines="9"
- {!> ../../../docs_src/query_params_str_validations/tutorial004_py310.py!}
- ```
+//// tab | Python 3.10+ non-Annotated
-=== "Python 3.8+ non-Annotated"
+/// tip
- !!! tip
- Prefer to use the `Annotated` version if possible.
+Prefer to use the `Annotated` version if possible.
- ```Python hl_lines="11"
- {!> ../../../docs_src/query_params_str_validations/tutorial004.py!}
- ```
+///
+
+```Python hl_lines="9"
+{!> ../../../docs_src/query_params_str_validations/tutorial004_py310.py!}
+```
+
+////
+
+//// tab | Python 3.8+ non-Annotated
+
+/// tip
+
+Prefer to use the `Annotated` version if possible.
+
+///
+
+```Python hl_lines="11"
+{!> ../../../docs_src/query_params_str_validations/tutorial004.py!}
+```
+
+////
This specific regular expression pattern checks that the received parameter value:
You could still see some code using it:
-=== "Python 3.10+ Pydantic v1"
+//// tab | Python 3.10+ Pydantic v1
+
+```Python hl_lines="11"
+{!> ../../../docs_src/query_params_str_validations/tutorial004_an_py310_regex.py!}
+```
- ```Python hl_lines="11"
- {!> ../../../docs_src/query_params_str_validations/tutorial004_an_py310_regex.py!}
- ```
+////
But know that this is deprecated and it should be updated to use the new parameter `pattern`. 🤓
Let's say that you want to declare the `q` query parameter to have a `min_length` of `3`, and to have a default value of `"fixedquery"`:
-=== "Python 3.9+"
+//// tab | Python 3.9+
+
+```Python hl_lines="9"
+{!> ../../../docs_src/query_params_str_validations/tutorial005_an_py39.py!}
+```
+
+////
- ```Python hl_lines="9"
- {!> ../../../docs_src/query_params_str_validations/tutorial005_an_py39.py!}
- ```
+//// tab | Python 3.8+
-=== "Python 3.8+"
+```Python hl_lines="8"
+{!> ../../../docs_src/query_params_str_validations/tutorial005_an.py!}
+```
+
+////
+
+//// tab | Python 3.8+ non-Annotated
+
+/// tip
- ```Python hl_lines="8"
- {!> ../../../docs_src/query_params_str_validations/tutorial005_an.py!}
- ```
+Prefer to use the `Annotated` version if possible.
-=== "Python 3.8+ non-Annotated"
+///
- !!! tip
- Prefer to use the `Annotated` version if possible.
+```Python hl_lines="7"
+{!> ../../../docs_src/query_params_str_validations/tutorial005.py!}
+```
+
+////
- ```Python hl_lines="7"
- {!> ../../../docs_src/query_params_str_validations/tutorial005.py!}
- ```
+/// note
-!!! note
- Having a default value of any type, including `None`, makes the parameter optional (not required).
+Having a default value of any type, including `None`, makes the parameter optional (not required).
+
+///
## Make it required
But we are now declaring it with `Query`, for example like:
-=== "Annotated"
+//// tab | Annotated
- ```Python
- q: Annotated[Union[str, None], Query(min_length=3)] = None
- ```
+```Python
+q: Annotated[Union[str, None], Query(min_length=3)] = None
+```
+
+////
-=== "non-Annotated"
+//// tab | non-Annotated
- ```Python
- q: Union[str, None] = Query(default=None, min_length=3)
- ```
+```Python
+q: Union[str, None] = Query(default=None, min_length=3)
+```
+
+////
So, when you need to declare a value as required while using `Query`, you can simply not declare a default value:
-=== "Python 3.9+"
+//// tab | Python 3.9+
+
+```Python hl_lines="9"
+{!> ../../../docs_src/query_params_str_validations/tutorial006_an_py39.py!}
+```
+
+////
+
+//// tab | Python 3.8+
+
+```Python hl_lines="8"
+{!> ../../../docs_src/query_params_str_validations/tutorial006_an.py!}
+```
+
+////
+
+//// tab | Python 3.8+ non-Annotated
- ```Python hl_lines="9"
- {!> ../../../docs_src/query_params_str_validations/tutorial006_an_py39.py!}
- ```
+/// tip
-=== "Python 3.8+"
+Prefer to use the `Annotated` version if possible.
- ```Python hl_lines="8"
- {!> ../../../docs_src/query_params_str_validations/tutorial006_an.py!}
- ```
+///
+
+```Python hl_lines="7"
+{!> ../../../docs_src/query_params_str_validations/tutorial006.py!}
+```
-=== "Python 3.8+ non-Annotated"
+/// tip
- !!! tip
- Prefer to use the `Annotated` version if possible.
+Notice that, even though in this case the `Query()` is used as the function parameter default value, we don't pass the `default=None` to `Query()`.
- ```Python hl_lines="7"
- {!> ../../../docs_src/query_params_str_validations/tutorial006.py!}
- ```
+Still, probably better to use the `Annotated` version. 😉
- !!! tip
- Notice that, even though in this case the `Query()` is used as the function parameter default value, we don't pass the `default=None` to `Query()`.
+///
- Still, probably better to use the `Annotated` version. 😉
+////
### Required with Ellipsis (`...`)
There's an alternative way to explicitly declare that a value is required. You can set the default to the literal value `...`:
-=== "Python 3.9+"
+//// tab | Python 3.9+
+
+```Python hl_lines="9"
+{!> ../../../docs_src/query_params_str_validations/tutorial006b_an_py39.py!}
+```
+
+////
+
+//// tab | Python 3.8+
+
+```Python hl_lines="8"
+{!> ../../../docs_src/query_params_str_validations/tutorial006b_an.py!}
+```
+
+////
- ```Python hl_lines="9"
- {!> ../../../docs_src/query_params_str_validations/tutorial006b_an_py39.py!}
- ```
+//// tab | Python 3.8+ non-Annotated
-=== "Python 3.8+"
+/// tip
- ```Python hl_lines="8"
- {!> ../../../docs_src/query_params_str_validations/tutorial006b_an.py!}
- ```
+Prefer to use the `Annotated` version if possible.
-=== "Python 3.8+ non-Annotated"
+///
- !!! tip
- Prefer to use the `Annotated` version if possible.
+```Python hl_lines="7"
+{!> ../../../docs_src/query_params_str_validations/tutorial006b.py!}
+```
+
+////
- ```Python hl_lines="7"
- {!> ../../../docs_src/query_params_str_validations/tutorial006b.py!}
- ```
+/// info
-!!! info
- If you hadn't seen that `...` before: it is a special single value, it is <a href="https://docs.python.org/3/library/constants.html#Ellipsis" class="external-link" target="_blank">part of Python and is called "Ellipsis"</a>.
+If you hadn't seen that `...` before: it is a special single value, it is <a href="https://docs.python.org/3/library/constants.html#Ellipsis" class="external-link" target="_blank">part of Python and is called "Ellipsis"</a>.
- It is used by Pydantic and FastAPI to explicitly declare that a value is required.
+It is used by Pydantic and FastAPI to explicitly declare that a value is required.
+
+///
This will let **FastAPI** know that this parameter is required.
To do that, you can declare that `None` is a valid type but still use `...` as the default:
-=== "Python 3.10+"
+//// tab | Python 3.10+
+
+```Python hl_lines="9"
+{!> ../../../docs_src/query_params_str_validations/tutorial006c_an_py310.py!}
+```
- ```Python hl_lines="9"
- {!> ../../../docs_src/query_params_str_validations/tutorial006c_an_py310.py!}
- ```
+////
-=== "Python 3.9+"
+//// tab | Python 3.9+
- ```Python hl_lines="9"
- {!> ../../../docs_src/query_params_str_validations/tutorial006c_an_py39.py!}
- ```
+```Python hl_lines="9"
+{!> ../../../docs_src/query_params_str_validations/tutorial006c_an_py39.py!}
+```
-=== "Python 3.8+"
+////
- ```Python hl_lines="10"
- {!> ../../../docs_src/query_params_str_validations/tutorial006c_an.py!}
- ```
+//// tab | Python 3.8+
-=== "Python 3.10+ non-Annotated"
+```Python hl_lines="10"
+{!> ../../../docs_src/query_params_str_validations/tutorial006c_an.py!}
+```
- !!! tip
- Prefer to use the `Annotated` version if possible.
+////
- ```Python hl_lines="7"
- {!> ../../../docs_src/query_params_str_validations/tutorial006c_py310.py!}
- ```
+//// tab | Python 3.10+ non-Annotated
-=== "Python 3.8+ non-Annotated"
+/// tip
- !!! tip
- Prefer to use the `Annotated` version if possible.
+Prefer to use the `Annotated` version if possible.
- ```Python hl_lines="9"
- {!> ../../../docs_src/query_params_str_validations/tutorial006c.py!}
- ```
+///
-!!! tip
- Pydantic, which is what powers all the data validation and serialization in FastAPI, has a special behavior when you use `Optional` or `Union[Something, None]` without a default value, you can read more about it in the Pydantic docs about <a href="https://docs.pydantic.dev/latest/concepts/models/#required-optional-fields" class="external-link" target="_blank">Required Optional fields</a>.
+```Python hl_lines="7"
+{!> ../../../docs_src/query_params_str_validations/tutorial006c_py310.py!}
+```
+
+////
+
+//// tab | Python 3.8+ non-Annotated
+
+/// tip
+
+Prefer to use the `Annotated` version if possible.
+
+///
+
+```Python hl_lines="9"
+{!> ../../../docs_src/query_params_str_validations/tutorial006c.py!}
+```
-!!! tip
- Remember that in most of the cases, when something is required, you can simply omit the default, so you normally don't have to use `...`.
+////
+
+/// tip
+
+Pydantic, which is what powers all the data validation and serialization in FastAPI, has a special behavior when you use `Optional` or `Union[Something, None]` without a default value, you can read more about it in the Pydantic docs about <a href="https://docs.pydantic.dev/latest/concepts/models/#required-optional-fields" class="external-link" target="_blank">Required Optional fields</a>.
+
+///
+
+/// tip
+
+Remember that in most of the cases, when something is required, you can simply omit the default, so you normally don't have to use `...`.
+
+///
## Query parameter list / multiple values
For example, to declare a query parameter `q` that can appear multiple times in the URL, you can write:
-=== "Python 3.10+"
+//// tab | Python 3.10+
+
+```Python hl_lines="9"
+{!> ../../../docs_src/query_params_str_validations/tutorial011_an_py310.py!}
+```
+
+////
+
+//// tab | Python 3.9+
+
+```Python hl_lines="9"
+{!> ../../../docs_src/query_params_str_validations/tutorial011_an_py39.py!}
+```
+
+////
+
+//// tab | Python 3.8+
+
+```Python hl_lines="10"
+{!> ../../../docs_src/query_params_str_validations/tutorial011_an.py!}
+```
+
+////
+
+//// tab | Python 3.10+ non-Annotated
+
+/// tip
- ```Python hl_lines="9"
- {!> ../../../docs_src/query_params_str_validations/tutorial011_an_py310.py!}
- ```
+Prefer to use the `Annotated` version if possible.
-=== "Python 3.9+"
+///
- ```Python hl_lines="9"
- {!> ../../../docs_src/query_params_str_validations/tutorial011_an_py39.py!}
- ```
+```Python hl_lines="7"
+{!> ../../../docs_src/query_params_str_validations/tutorial011_py310.py!}
+```
+
+////
-=== "Python 3.8+"
+//// tab | Python 3.9+ non-Annotated
- ```Python hl_lines="10"
- {!> ../../../docs_src/query_params_str_validations/tutorial011_an.py!}
- ```
+/// tip
-=== "Python 3.10+ non-Annotated"
+Prefer to use the `Annotated` version if possible.
- !!! tip
- Prefer to use the `Annotated` version if possible.
+///
- ```Python hl_lines="7"
- {!> ../../../docs_src/query_params_str_validations/tutorial011_py310.py!}
- ```
+```Python hl_lines="9"
+{!> ../../../docs_src/query_params_str_validations/tutorial011_py39.py!}
+```
-=== "Python 3.9+ non-Annotated"
+////
- !!! tip
- Prefer to use the `Annotated` version if possible.
+//// tab | Python 3.8+ non-Annotated
- ```Python hl_lines="9"
- {!> ../../../docs_src/query_params_str_validations/tutorial011_py39.py!}
- ```
+/// tip
-=== "Python 3.8+ non-Annotated"
+Prefer to use the `Annotated` version if possible.
- !!! tip
- Prefer to use the `Annotated` version if possible.
+///
- ```Python hl_lines="9"
- {!> ../../../docs_src/query_params_str_validations/tutorial011.py!}
- ```
+```Python hl_lines="9"
+{!> ../../../docs_src/query_params_str_validations/tutorial011.py!}
+```
+
+////
Then, with a URL like:
}
```
-!!! tip
- To declare a query parameter with a type of `list`, like in the example above, you need to explicitly use `Query`, otherwise it would be interpreted as a request body.
+/// tip
+
+To declare a query parameter with a type of `list`, like in the example above, you need to explicitly use `Query`, otherwise it would be interpreted as a request body.
+
+///
The interactive API docs will update accordingly, to allow multiple values:
And you can also define a default `list` of values if none are provided:
-=== "Python 3.9+"
+//// tab | Python 3.9+
+
+```Python hl_lines="9"
+{!> ../../../docs_src/query_params_str_validations/tutorial012_an_py39.py!}
+```
+
+////
+
+//// tab | Python 3.8+
- ```Python hl_lines="9"
- {!> ../../../docs_src/query_params_str_validations/tutorial012_an_py39.py!}
- ```
+```Python hl_lines="10"
+{!> ../../../docs_src/query_params_str_validations/tutorial012_an.py!}
+```
+
+////
+
+//// tab | Python 3.9+ non-Annotated
+
+/// tip
-=== "Python 3.8+"
+Prefer to use the `Annotated` version if possible.
- ```Python hl_lines="10"
- {!> ../../../docs_src/query_params_str_validations/tutorial012_an.py!}
- ```
+///
-=== "Python 3.9+ non-Annotated"
+```Python hl_lines="7"
+{!> ../../../docs_src/query_params_str_validations/tutorial012_py39.py!}
+```
+
+////
- !!! tip
- Prefer to use the `Annotated` version if possible.
+//// tab | Python 3.8+ non-Annotated
- ```Python hl_lines="7"
- {!> ../../../docs_src/query_params_str_validations/tutorial012_py39.py!}
- ```
+/// tip
-=== "Python 3.8+ non-Annotated"
+Prefer to use the `Annotated` version if possible.
- !!! tip
- Prefer to use the `Annotated` version if possible.
+///
+
+```Python hl_lines="9"
+{!> ../../../docs_src/query_params_str_validations/tutorial012.py!}
+```
- ```Python hl_lines="9"
- {!> ../../../docs_src/query_params_str_validations/tutorial012.py!}
- ```
+////
If you go to:
You can also use `list` directly instead of `List[str]` (or `list[str]` in Python 3.9+):
-=== "Python 3.9+"
+//// tab | Python 3.9+
+
+```Python hl_lines="9"
+{!> ../../../docs_src/query_params_str_validations/tutorial013_an_py39.py!}
+```
+
+////
+
+//// tab | Python 3.8+
+
+```Python hl_lines="8"
+{!> ../../../docs_src/query_params_str_validations/tutorial013_an.py!}
+```
+
+////
- ```Python hl_lines="9"
- {!> ../../../docs_src/query_params_str_validations/tutorial013_an_py39.py!}
- ```
+//// tab | Python 3.8+ non-Annotated
-=== "Python 3.8+"
+/// tip
- ```Python hl_lines="8"
- {!> ../../../docs_src/query_params_str_validations/tutorial013_an.py!}
- ```
+Prefer to use the `Annotated` version if possible.
-=== "Python 3.8+ non-Annotated"
+///
- !!! tip
- Prefer to use the `Annotated` version if possible.
+```Python hl_lines="7"
+{!> ../../../docs_src/query_params_str_validations/tutorial013.py!}
+```
+
+////
- ```Python hl_lines="7"
- {!> ../../../docs_src/query_params_str_validations/tutorial013.py!}
- ```
+/// note
-!!! note
- Keep in mind that in this case, FastAPI won't check the contents of the list.
+Keep in mind that in this case, FastAPI won't check the contents of the list.
- For example, `List[int]` would check (and document) that the contents of the list are integers. But `list` alone wouldn't.
+For example, `List[int]` would check (and document) that the contents of the list are integers. But `list` alone wouldn't.
+
+///
## Declare more metadata
That information will be included in the generated OpenAPI and used by the documentation user interfaces and external tools.
-!!! note
- Keep in mind that different tools might have different levels of OpenAPI support.
+/// note
+
+Keep in mind that different tools might have different levels of OpenAPI support.
- Some of them might not show all the extra information declared yet, although in most of the cases, the missing feature is already planned for development.
+Some of them might not show all the extra information declared yet, although in most of the cases, the missing feature is already planned for development.
+
+///
You can add a `title`:
-=== "Python 3.10+"
+//// tab | Python 3.10+
+
+```Python hl_lines="10"
+{!> ../../../docs_src/query_params_str_validations/tutorial007_an_py310.py!}
+```
+
+////
+
+//// tab | Python 3.9+
+
+```Python hl_lines="10"
+{!> ../../../docs_src/query_params_str_validations/tutorial007_an_py39.py!}
+```
+
+////
+
+//// tab | Python 3.8+
+
+```Python hl_lines="11"
+{!> ../../../docs_src/query_params_str_validations/tutorial007_an.py!}
+```
+
+////
+
+//// tab | Python 3.10+ non-Annotated
- ```Python hl_lines="10"
- {!> ../../../docs_src/query_params_str_validations/tutorial007_an_py310.py!}
- ```
+/// tip
-=== "Python 3.9+"
+Prefer to use the `Annotated` version if possible.
- ```Python hl_lines="10"
- {!> ../../../docs_src/query_params_str_validations/tutorial007_an_py39.py!}
- ```
+///
-=== "Python 3.8+"
+```Python hl_lines="8"
+{!> ../../../docs_src/query_params_str_validations/tutorial007_py310.py!}
+```
- ```Python hl_lines="11"
- {!> ../../../docs_src/query_params_str_validations/tutorial007_an.py!}
- ```
+////
-=== "Python 3.10+ non-Annotated"
+//// tab | Python 3.8+ non-Annotated
- !!! tip
- Prefer to use the `Annotated` version if possible.
+/// tip
- ```Python hl_lines="8"
- {!> ../../../docs_src/query_params_str_validations/tutorial007_py310.py!}
- ```
+Prefer to use the `Annotated` version if possible.
-=== "Python 3.8+ non-Annotated"
+///
- !!! tip
- Prefer to use the `Annotated` version if possible.
+```Python hl_lines="10"
+{!> ../../../docs_src/query_params_str_validations/tutorial007.py!}
+```
- ```Python hl_lines="10"
- {!> ../../../docs_src/query_params_str_validations/tutorial007.py!}
- ```
+////
And a `description`:
-=== "Python 3.10+"
+//// tab | Python 3.10+
+
+```Python hl_lines="14"
+{!> ../../../docs_src/query_params_str_validations/tutorial008_an_py310.py!}
+```
+
+////
+
+//// tab | Python 3.9+
+
+```Python hl_lines="14"
+{!> ../../../docs_src/query_params_str_validations/tutorial008_an_py39.py!}
+```
+
+////
+
+//// tab | Python 3.8+
+
+```Python hl_lines="15"
+{!> ../../../docs_src/query_params_str_validations/tutorial008_an.py!}
+```
+
+////
- ```Python hl_lines="14"
- {!> ../../../docs_src/query_params_str_validations/tutorial008_an_py310.py!}
- ```
+//// tab | Python 3.10+ non-Annotated
-=== "Python 3.9+"
+/// tip
- ```Python hl_lines="14"
- {!> ../../../docs_src/query_params_str_validations/tutorial008_an_py39.py!}
- ```
+Prefer to use the `Annotated` version if possible.
-=== "Python 3.8+"
+///
- ```Python hl_lines="15"
- {!> ../../../docs_src/query_params_str_validations/tutorial008_an.py!}
- ```
+```Python hl_lines="11"
+{!> ../../../docs_src/query_params_str_validations/tutorial008_py310.py!}
+```
+
+////
-=== "Python 3.10+ non-Annotated"
+//// tab | Python 3.8+ non-Annotated
- !!! tip
- Prefer to use the `Annotated` version if possible.
+/// tip
- ```Python hl_lines="11"
- {!> ../../../docs_src/query_params_str_validations/tutorial008_py310.py!}
- ```
+Prefer to use the `Annotated` version if possible.
-=== "Python 3.8+ non-Annotated"
+///
- !!! tip
- Prefer to use the `Annotated` version if possible.
+```Python hl_lines="13"
+{!> ../../../docs_src/query_params_str_validations/tutorial008.py!}
+```
- ```Python hl_lines="13"
- {!> ../../../docs_src/query_params_str_validations/tutorial008.py!}
- ```
+////
## Alias parameters
Then you can declare an `alias`, and that alias is what will be used to find the parameter value:
-=== "Python 3.10+"
+//// tab | Python 3.10+
+
+```Python hl_lines="9"
+{!> ../../../docs_src/query_params_str_validations/tutorial009_an_py310.py!}
+```
+
+////
+
+//// tab | Python 3.9+
+
+```Python hl_lines="9"
+{!> ../../../docs_src/query_params_str_validations/tutorial009_an_py39.py!}
+```
+
+////
+
+//// tab | Python 3.8+
+
+```Python hl_lines="10"
+{!> ../../../docs_src/query_params_str_validations/tutorial009_an.py!}
+```
+
+////
+
+//// tab | Python 3.10+ non-Annotated
- ```Python hl_lines="9"
- {!> ../../../docs_src/query_params_str_validations/tutorial009_an_py310.py!}
- ```
+/// tip
-=== "Python 3.9+"
+Prefer to use the `Annotated` version if possible.
- ```Python hl_lines="9"
- {!> ../../../docs_src/query_params_str_validations/tutorial009_an_py39.py!}
- ```
+///
-=== "Python 3.8+"
+```Python hl_lines="7"
+{!> ../../../docs_src/query_params_str_validations/tutorial009_py310.py!}
+```
- ```Python hl_lines="10"
- {!> ../../../docs_src/query_params_str_validations/tutorial009_an.py!}
- ```
+////
-=== "Python 3.10+ non-Annotated"
+//// tab | Python 3.8+ non-Annotated
- !!! tip
- Prefer to use the `Annotated` version if possible.
+/// tip
- ```Python hl_lines="7"
- {!> ../../../docs_src/query_params_str_validations/tutorial009_py310.py!}
- ```
+Prefer to use the `Annotated` version if possible.
-=== "Python 3.8+ non-Annotated"
+///
- !!! tip
- Prefer to use the `Annotated` version if possible.
+```Python hl_lines="9"
+{!> ../../../docs_src/query_params_str_validations/tutorial009.py!}
+```
- ```Python hl_lines="9"
- {!> ../../../docs_src/query_params_str_validations/tutorial009.py!}
- ```
+////
## Deprecating parameters
Then pass the parameter `deprecated=True` to `Query`:
-=== "Python 3.10+"
+//// tab | Python 3.10+
+
+```Python hl_lines="19"
+{!> ../../../docs_src/query_params_str_validations/tutorial010_an_py310.py!}
+```
+
+////
+
+//// tab | Python 3.9+
- ```Python hl_lines="19"
- {!> ../../../docs_src/query_params_str_validations/tutorial010_an_py310.py!}
- ```
+```Python hl_lines="19"
+{!> ../../../docs_src/query_params_str_validations/tutorial010_an_py39.py!}
+```
-=== "Python 3.9+"
+////
- ```Python hl_lines="19"
- {!> ../../../docs_src/query_params_str_validations/tutorial010_an_py39.py!}
- ```
+//// tab | Python 3.8+
-=== "Python 3.8+"
+```Python hl_lines="20"
+{!> ../../../docs_src/query_params_str_validations/tutorial010_an.py!}
+```
+
+////
+
+//// tab | Python 3.10+ non-Annotated
+
+/// tip
+
+Prefer to use the `Annotated` version if possible.
+
+///
+
+```Python hl_lines="16"
+{!> ../../../docs_src/query_params_str_validations/tutorial010_py310.py!}
+```
- ```Python hl_lines="20"
- {!> ../../../docs_src/query_params_str_validations/tutorial010_an.py!}
- ```
+////
-=== "Python 3.10+ non-Annotated"
+//// tab | Python 3.8+ non-Annotated
- !!! tip
- Prefer to use the `Annotated` version if possible.
+/// tip
- ```Python hl_lines="16"
- {!> ../../../docs_src/query_params_str_validations/tutorial010_py310.py!}
- ```
+Prefer to use the `Annotated` version if possible.
-=== "Python 3.8+ non-Annotated"
+///
- !!! tip
- Prefer to use the `Annotated` version if possible.
+```Python hl_lines="18"
+{!> ../../../docs_src/query_params_str_validations/tutorial010.py!}
+```
- ```Python hl_lines="18"
- {!> ../../../docs_src/query_params_str_validations/tutorial010.py!}
- ```
+////
The docs will show it like this:
To exclude a query parameter from the generated OpenAPI schema (and thus, from the automatic documentation systems), set the parameter `include_in_schema` of `Query` to `False`:
-=== "Python 3.10+"
+//// tab | Python 3.10+
+
+```Python hl_lines="10"
+{!> ../../../docs_src/query_params_str_validations/tutorial014_an_py310.py!}
+```
+
+////
- ```Python hl_lines="10"
- {!> ../../../docs_src/query_params_str_validations/tutorial014_an_py310.py!}
- ```
+//// tab | Python 3.9+
-=== "Python 3.9+"
+```Python hl_lines="10"
+{!> ../../../docs_src/query_params_str_validations/tutorial014_an_py39.py!}
+```
+
+////
- ```Python hl_lines="10"
- {!> ../../../docs_src/query_params_str_validations/tutorial014_an_py39.py!}
- ```
+//// tab | Python 3.8+
-=== "Python 3.8+"
+```Python hl_lines="11"
+{!> ../../../docs_src/query_params_str_validations/tutorial014_an.py!}
+```
- ```Python hl_lines="11"
- {!> ../../../docs_src/query_params_str_validations/tutorial014_an.py!}
- ```
+////
-=== "Python 3.10+ non-Annotated"
+//// tab | Python 3.10+ non-Annotated
- !!! tip
- Prefer to use the `Annotated` version if possible.
+/// tip
- ```Python hl_lines="8"
- {!> ../../../docs_src/query_params_str_validations/tutorial014_py310.py!}
- ```
+Prefer to use the `Annotated` version if possible.
-=== "Python 3.8+ non-Annotated"
+///
- !!! tip
- Prefer to use the `Annotated` version if possible.
+```Python hl_lines="8"
+{!> ../../../docs_src/query_params_str_validations/tutorial014_py310.py!}
+```
+
+////
+
+//// tab | Python 3.8+ non-Annotated
+
+/// tip
+
+Prefer to use the `Annotated` version if possible.
+
+///
+
+```Python hl_lines="10"
+{!> ../../../docs_src/query_params_str_validations/tutorial014.py!}
+```
- ```Python hl_lines="10"
- {!> ../../../docs_src/query_params_str_validations/tutorial014.py!}
- ```
+////
## Recap
The same way, you can declare optional query parameters, by setting their default to `None`:
-=== "Python 3.10+"
+//// tab | Python 3.10+
- ```Python hl_lines="7"
- {!> ../../../docs_src/query_params/tutorial002_py310.py!}
- ```
+```Python hl_lines="7"
+{!> ../../../docs_src/query_params/tutorial002_py310.py!}
+```
+
+////
+
+//// tab | Python 3.8+
-=== "Python 3.8+"
+```Python hl_lines="9"
+{!> ../../../docs_src/query_params/tutorial002.py!}
+```
- ```Python hl_lines="9"
- {!> ../../../docs_src/query_params/tutorial002.py!}
- ```
+////
In this case, the function parameter `q` will be optional, and will be `None` by default.
-!!! check
- Also notice that **FastAPI** is smart enough to notice that the path parameter `item_id` is a path parameter and `q` is not, so, it's a query parameter.
+/// check
+
+Also notice that **FastAPI** is smart enough to notice that the path parameter `item_id` is a path parameter and `q` is not, so, it's a query parameter.
+
+///
## Query parameter type conversion
You can also declare `bool` types, and they will be converted:
-=== "Python 3.10+"
+//// tab | Python 3.10+
+
+```Python hl_lines="7"
+{!> ../../../docs_src/query_params/tutorial003_py310.py!}
+```
- ```Python hl_lines="7"
- {!> ../../../docs_src/query_params/tutorial003_py310.py!}
- ```
+////
-=== "Python 3.8+"
+//// tab | Python 3.8+
+
+```Python hl_lines="9"
+{!> ../../../docs_src/query_params/tutorial003.py!}
+```
- ```Python hl_lines="9"
- {!> ../../../docs_src/query_params/tutorial003.py!}
- ```
+////
In this case, if you go to:
They will be detected by name:
-=== "Python 3.10+"
+//// tab | Python 3.10+
+
+```Python hl_lines="6 8"
+{!> ../../../docs_src/query_params/tutorial004_py310.py!}
+```
+
+////
- ```Python hl_lines="6 8"
- {!> ../../../docs_src/query_params/tutorial004_py310.py!}
- ```
+//// tab | Python 3.8+
-=== "Python 3.8+"
+```Python hl_lines="8 10"
+{!> ../../../docs_src/query_params/tutorial004.py!}
+```
- ```Python hl_lines="8 10"
- {!> ../../../docs_src/query_params/tutorial004.py!}
- ```
+////
## Required query parameters
And of course, you can define some parameters as required, some as having a default value, and some entirely optional:
-=== "Python 3.10+"
+//// tab | Python 3.10+
- ```Python hl_lines="8"
- {!> ../../../docs_src/query_params/tutorial006_py310.py!}
- ```
+```Python hl_lines="8"
+{!> ../../../docs_src/query_params/tutorial006_py310.py!}
+```
-=== "Python 3.8+"
+////
- ```Python hl_lines="10"
- {!> ../../../docs_src/query_params/tutorial006.py!}
- ```
+//// tab | Python 3.8+
+
+```Python hl_lines="10"
+{!> ../../../docs_src/query_params/tutorial006.py!}
+```
+
+////
In this case, there are 3 query parameters:
* `skip`, an `int` with a default value of `0`.
* `limit`, an optional `int`.
-!!! tip
- You could also use `Enum`s the same way as with [Path Parameters](path-params.md#predefined-values){.internal-link target=_blank}.
+/// tip
+
+You could also use `Enum`s the same way as with [Path Parameters](path-params.md#predefined-values){.internal-link target=_blank}.
+
+///
You can define files to be uploaded by the client using `File`.
-!!! info
- To receive uploaded files, first install <a href="https://github.com/Kludex/python-multipart" class="external-link" target="_blank">`python-multipart`</a>.
+/// info
- E.g. `pip install python-multipart`.
+To receive uploaded files, first install <a href="https://github.com/Kludex/python-multipart" class="external-link" target="_blank">`python-multipart`</a>.
- This is because uploaded files are sent as "form data".
+E.g. `pip install python-multipart`.
+
+This is because uploaded files are sent as "form data".
+
+///
## Import `File`
Import `File` and `UploadFile` from `fastapi`:
-=== "Python 3.9+"
+//// tab | Python 3.9+
+
+```Python hl_lines="3"
+{!> ../../../docs_src/request_files/tutorial001_an_py39.py!}
+```
+
+////
- ```Python hl_lines="3"
- {!> ../../../docs_src/request_files/tutorial001_an_py39.py!}
- ```
+//// tab | Python 3.8+
-=== "Python 3.8+"
+```Python hl_lines="1"
+{!> ../../../docs_src/request_files/tutorial001_an.py!}
+```
- ```Python hl_lines="1"
- {!> ../../../docs_src/request_files/tutorial001_an.py!}
- ```
+////
-=== "Python 3.8+ non-Annotated"
+//// tab | Python 3.8+ non-Annotated
- !!! tip
- Prefer to use the `Annotated` version if possible.
+/// tip
- ```Python hl_lines="1"
- {!> ../../../docs_src/request_files/tutorial001.py!}
- ```
+Prefer to use the `Annotated` version if possible.
+
+///
+
+```Python hl_lines="1"
+{!> ../../../docs_src/request_files/tutorial001.py!}
+```
+
+////
## Define `File` Parameters
Create file parameters the same way you would for `Body` or `Form`:
-=== "Python 3.9+"
+//// tab | Python 3.9+
+
+```Python hl_lines="9"
+{!> ../../../docs_src/request_files/tutorial001_an_py39.py!}
+```
+
+////
+
+//// tab | Python 3.8+
+
+```Python hl_lines="8"
+{!> ../../../docs_src/request_files/tutorial001_an.py!}
+```
+
+////
- ```Python hl_lines="9"
- {!> ../../../docs_src/request_files/tutorial001_an_py39.py!}
- ```
+//// tab | Python 3.8+ non-Annotated
+
+/// tip
+
+Prefer to use the `Annotated` version if possible.
+
+///
+
+```Python hl_lines="7"
+{!> ../../../docs_src/request_files/tutorial001.py!}
+```
-=== "Python 3.8+"
+////
- ```Python hl_lines="8"
- {!> ../../../docs_src/request_files/tutorial001_an.py!}
- ```
+/// info
-=== "Python 3.8+ non-Annotated"
+`File` is a class that inherits directly from `Form`.
- !!! tip
- Prefer to use the `Annotated` version if possible.
+But remember that when you import `Query`, `Path`, `File` and others from `fastapi`, those are actually functions that return special classes.
- ```Python hl_lines="7"
- {!> ../../../docs_src/request_files/tutorial001.py!}
- ```
+///
-!!! info
- `File` is a class that inherits directly from `Form`.
+/// tip
- But remember that when you import `Query`, `Path`, `File` and others from `fastapi`, those are actually functions that return special classes.
+To declare File bodies, you need to use `File`, because otherwise the parameters would be interpreted as query parameters or body (JSON) parameters.
-!!! tip
- To declare File bodies, you need to use `File`, because otherwise the parameters would be interpreted as query parameters or body (JSON) parameters.
+///
The files will be uploaded as "form data".
Define a file parameter with a type of `UploadFile`:
-=== "Python 3.9+"
+//// tab | Python 3.9+
- ```Python hl_lines="14"
- {!> ../../../docs_src/request_files/tutorial001_an_py39.py!}
- ```
+```Python hl_lines="14"
+{!> ../../../docs_src/request_files/tutorial001_an_py39.py!}
+```
+
+////
+
+//// tab | Python 3.8+
-=== "Python 3.8+"
+```Python hl_lines="13"
+{!> ../../../docs_src/request_files/tutorial001_an.py!}
+```
+
+////
- ```Python hl_lines="13"
- {!> ../../../docs_src/request_files/tutorial001_an.py!}
- ```
+//// tab | Python 3.8+ non-Annotated
-=== "Python 3.8+ non-Annotated"
+/// tip
- !!! tip
- Prefer to use the `Annotated` version if possible.
+Prefer to use the `Annotated` version if possible.
- ```Python hl_lines="12"
- {!> ../../../docs_src/request_files/tutorial001.py!}
- ```
+///
+
+```Python hl_lines="12"
+{!> ../../../docs_src/request_files/tutorial001.py!}
+```
+
+////
Using `UploadFile` has several advantages over `bytes`:
contents = myfile.file.read()
```
-!!! note "`async` Technical Details"
- When you use the `async` methods, **FastAPI** runs the file methods in a threadpool and awaits for them.
+/// note | "`async` Technical Details"
+
+When you use the `async` methods, **FastAPI** runs the file methods in a threadpool and awaits for them.
+
+///
+
+/// note | "Starlette Technical Details"
-!!! note "Starlette Technical Details"
- **FastAPI**'s `UploadFile` inherits directly from **Starlette**'s `UploadFile`, but adds some necessary parts to make it compatible with **Pydantic** and the other parts of FastAPI.
+**FastAPI**'s `UploadFile` inherits directly from **Starlette**'s `UploadFile`, but adds some necessary parts to make it compatible with **Pydantic** and the other parts of FastAPI.
+
+///
## What is "Form Data"
**FastAPI** will make sure to read that data from the right place instead of JSON.
-!!! note "Technical Details"
- Data from forms is normally encoded using the "media type" `application/x-www-form-urlencoded` when it doesn't include files.
+/// note | "Technical Details"
+
+Data from forms is normally encoded using the "media type" `application/x-www-form-urlencoded` when it doesn't include files.
+
+But when the form includes files, it is encoded as `multipart/form-data`. If you use `File`, **FastAPI** will know it has to get the files from the correct part of the body.
+
+If you want to read more about these encodings and form fields, head to the <a href="https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods/POST" class="external-link" target="_blank"><abbr title="Mozilla Developer Network">MDN</abbr> web docs for <code>POST</code></a>.
+
+///
- 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.
+/// warning
- If you want to read more about these encodings and form fields, head to the <a href="https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods/POST" class="external-link" target="_blank"><abbr title="Mozilla Developer Network">MDN</abbr> web docs for <code>POST</code></a>.
+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`.
-!!! 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.
- This is not a limitation of **FastAPI**, it's part of the HTTP protocol.
+///
## Optional File Upload
You can make a file optional by using standard type annotations and setting a default value of `None`:
-=== "Python 3.10+"
+//// tab | Python 3.10+
+
+```Python hl_lines="9 17"
+{!> ../../../docs_src/request_files/tutorial001_02_an_py310.py!}
+```
+
+////
+
+//// tab | Python 3.9+
+
+```Python hl_lines="9 17"
+{!> ../../../docs_src/request_files/tutorial001_02_an_py39.py!}
+```
+
+////
+
+//// tab | Python 3.8+
- ```Python hl_lines="9 17"
- {!> ../../../docs_src/request_files/tutorial001_02_an_py310.py!}
- ```
+```Python hl_lines="10 18"
+{!> ../../../docs_src/request_files/tutorial001_02_an.py!}
+```
+
+////
-=== "Python 3.9+"
+//// tab | Python 3.10+ non-Annotated
- ```Python hl_lines="9 17"
- {!> ../../../docs_src/request_files/tutorial001_02_an_py39.py!}
- ```
+/// tip
-=== "Python 3.8+"
+Prefer to use the `Annotated` version if possible.
- ```Python hl_lines="10 18"
- {!> ../../../docs_src/request_files/tutorial001_02_an.py!}
- ```
+///
-=== "Python 3.10+ non-Annotated"
+```Python hl_lines="7 15"
+{!> ../../../docs_src/request_files/tutorial001_02_py310.py!}
+```
- !!! tip
- Prefer to use the `Annotated` version if possible.
+////
- ```Python hl_lines="7 15"
- {!> ../../../docs_src/request_files/tutorial001_02_py310.py!}
- ```
+//// tab | Python 3.8+ non-Annotated
-=== "Python 3.8+ non-Annotated"
+/// tip
- !!! tip
- Prefer to use the `Annotated` version if possible.
+Prefer to use the `Annotated` version if possible.
- ```Python hl_lines="9 17"
- {!> ../../../docs_src/request_files/tutorial001_02.py!}
- ```
+///
+
+```Python hl_lines="9 17"
+{!> ../../../docs_src/request_files/tutorial001_02.py!}
+```
+
+////
## `UploadFile` with Additional Metadata
You can also use `File()` with `UploadFile`, for example, to set additional metadata:
-=== "Python 3.9+"
+//// tab | Python 3.9+
+
+```Python hl_lines="9 15"
+{!> ../../../docs_src/request_files/tutorial001_03_an_py39.py!}
+```
+
+////
+
+//// tab | Python 3.8+
+
+```Python hl_lines="8 14"
+{!> ../../../docs_src/request_files/tutorial001_03_an.py!}
+```
+
+////
- ```Python hl_lines="9 15"
- {!> ../../../docs_src/request_files/tutorial001_03_an_py39.py!}
- ```
+//// tab | Python 3.8+ non-Annotated
-=== "Python 3.8+"
+/// tip
- ```Python hl_lines="8 14"
- {!> ../../../docs_src/request_files/tutorial001_03_an.py!}
- ```
+Prefer to use the `Annotated` version if possible.
-=== "Python 3.8+ non-Annotated"
+///
- !!! tip
- Prefer to use the `Annotated` version if possible.
+```Python hl_lines="7 13"
+{!> ../../../docs_src/request_files/tutorial001_03.py!}
+```
- ```Python hl_lines="7 13"
- {!> ../../../docs_src/request_files/tutorial001_03.py!}
- ```
+////
## Multiple File Uploads
To use that, declare a list of `bytes` or `UploadFile`:
-=== "Python 3.9+"
+//// tab | Python 3.9+
- ```Python hl_lines="10 15"
- {!> ../../../docs_src/request_files/tutorial002_an_py39.py!}
- ```
+```Python hl_lines="10 15"
+{!> ../../../docs_src/request_files/tutorial002_an_py39.py!}
+```
+
+////
-=== "Python 3.8+"
+//// tab | Python 3.8+
- ```Python hl_lines="11 16"
- {!> ../../../docs_src/request_files/tutorial002_an.py!}
- ```
+```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.
+//// tab | Python 3.9+ non-Annotated
- ```Python hl_lines="8 13"
- {!> ../../../docs_src/request_files/tutorial002_py39.py!}
- ```
+/// tip
-=== "Python 3.8+ non-Annotated"
+Prefer to use the `Annotated` version if possible.
- !!! tip
- Prefer to use the `Annotated` version if possible.
+///
+
+```Python hl_lines="8 13"
+{!> ../../../docs_src/request_files/tutorial002_py39.py!}
+```
- ```Python hl_lines="10 15"
- {!> ../../../docs_src/request_files/tutorial002.py!}
- ```
+////
+
+//// tab | Python 3.8+ non-Annotated
+
+/// tip
+
+Prefer to use the `Annotated` version if possible.
+
+///
+
+```Python hl_lines="10 15"
+{!> ../../../docs_src/request_files/tutorial002.py!}
+```
+
+////
You will receive, as declared, a `list` of `bytes` or `UploadFile`s.
-!!! note "Technical Details"
- 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+"
+//// tab | Python 3.9+
- ```Python hl_lines="11 18-20"
- {!> ../../../docs_src/request_files/tutorial003_an_py39.py!}
- ```
+```Python hl_lines="11 18-20"
+{!> ../../../docs_src/request_files/tutorial003_an_py39.py!}
+```
-=== "Python 3.8+"
+////
- ```Python hl_lines="12 19-21"
- {!> ../../../docs_src/request_files/tutorial003_an.py!}
- ```
+//// tab | Python 3.8+
-=== "Python 3.9+ non-Annotated"
+```Python hl_lines="12 19-21"
+{!> ../../../docs_src/request_files/tutorial003_an.py!}
+```
- !!! tip
- Prefer to use the `Annotated` version if possible.
+////
- ```Python hl_lines="9 16"
- {!> ../../../docs_src/request_files/tutorial003_py39.py!}
- ```
+//// tab | Python 3.9+ non-Annotated
-=== "Python 3.8+ non-Annotated"
+/// tip
- !!! tip
- Prefer to use the `Annotated` version if possible.
+Prefer to use the `Annotated` version if possible.
+
+///
+
+```Python hl_lines="9 16"
+{!> ../../../docs_src/request_files/tutorial003_py39.py!}
+```
+
+////
+
+//// tab | Python 3.8+ non-Annotated
+
+/// tip
+
+Prefer to use the `Annotated` version if possible.
+
+///
+
+```Python hl_lines="11 18"
+{!> ../../../docs_src/request_files/tutorial003.py!}
+```
- ```Python hl_lines="11 18"
- {!> ../../../docs_src/request_files/tutorial003.py!}
- ```
+////
## Recap
You can define files and form fields at the same time using `File` and `Form`.
-!!! info
- To receive uploaded files and/or form data, first install <a href="https://github.com/Kludex/python-multipart" class="external-link" target="_blank">`python-multipart`</a>.
+/// info
- E.g. `pip install python-multipart`.
+To receive uploaded files and/or form data, first install <a href="https://github.com/Kludex/python-multipart" class="external-link" target="_blank">`python-multipart`</a>.
+
+E.g. `pip install python-multipart`.
+
+///
## Import `File` and `Form`
-=== "Python 3.9+"
+//// tab | Python 3.9+
+
+```Python hl_lines="3"
+{!> ../../../docs_src/request_forms_and_files/tutorial001_an_py39.py!}
+```
+
+////
+
+//// tab | Python 3.8+
+
+```Python hl_lines="1"
+{!> ../../../docs_src/request_forms_and_files/tutorial001_an.py!}
+```
+
+////
- ```Python hl_lines="3"
- {!> ../../../docs_src/request_forms_and_files/tutorial001_an_py39.py!}
- ```
+//// tab | Python 3.8+ non-Annotated
-=== "Python 3.8+"
+/// tip
- ```Python hl_lines="1"
- {!> ../../../docs_src/request_forms_and_files/tutorial001_an.py!}
- ```
+Prefer to use the `Annotated` version if possible.
-=== "Python 3.8+ non-Annotated"
+///
- !!! tip
- Prefer to use the `Annotated` version if possible.
+```Python hl_lines="1"
+{!> ../../../docs_src/request_forms_and_files/tutorial001.py!}
+```
- ```Python hl_lines="1"
- {!> ../../../docs_src/request_forms_and_files/tutorial001.py!}
- ```
+////
## Define `File` and `Form` parameters
Create file and form parameters the same way you would for `Body` or `Query`:
-=== "Python 3.9+"
+//// tab | Python 3.9+
- ```Python hl_lines="10-12"
- {!> ../../../docs_src/request_forms_and_files/tutorial001_an_py39.py!}
- ```
+```Python hl_lines="10-12"
+{!> ../../../docs_src/request_forms_and_files/tutorial001_an_py39.py!}
+```
-=== "Python 3.8+"
+////
- ```Python hl_lines="9-11"
- {!> ../../../docs_src/request_forms_and_files/tutorial001_an.py!}
- ```
+//// tab | Python 3.8+
-=== "Python 3.8+ non-Annotated"
+```Python hl_lines="9-11"
+{!> ../../../docs_src/request_forms_and_files/tutorial001_an.py!}
+```
- !!! tip
- Prefer to use the `Annotated` version if possible.
+////
- ```Python hl_lines="8"
- {!> ../../../docs_src/request_forms_and_files/tutorial001.py!}
- ```
+//// tab | Python 3.8+ non-Annotated
+
+/// tip
+
+Prefer to use the `Annotated` version if possible.
+
+///
+
+```Python hl_lines="8"
+{!> ../../../docs_src/request_forms_and_files/tutorial001.py!}
+```
+
+////
The files and form fields will be uploaded as form data and you will receive the files and form fields.
And you can declare some of the files as `bytes` and some as `UploadFile`.
-!!! 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`.
+/// 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.
- This is not a limitation of **FastAPI**, it's part of the HTTP protocol.
+///
## Recap
When you need to receive form fields instead of JSON, you can use `Form`.
-!!! info
- To use forms, first install <a href="https://github.com/Kludex/python-multipart" class="external-link" target="_blank">`python-multipart`</a>.
+/// info
- E.g. `pip install python-multipart`.
+To use forms, first install <a href="https://github.com/Kludex/python-multipart" class="external-link" target="_blank">`python-multipart`</a>.
+
+E.g. `pip install python-multipart`.
+
+///
## Import `Form`
Import `Form` from `fastapi`:
-=== "Python 3.9+"
+//// tab | Python 3.9+
+
+```Python hl_lines="3"
+{!> ../../../docs_src/request_forms/tutorial001_an_py39.py!}
+```
+
+////
+
+//// tab | Python 3.8+
- ```Python hl_lines="3"
- {!> ../../../docs_src/request_forms/tutorial001_an_py39.py!}
- ```
+```Python hl_lines="1"
+{!> ../../../docs_src/request_forms/tutorial001_an.py!}
+```
-=== "Python 3.8+"
+////
- ```Python hl_lines="1"
- {!> ../../../docs_src/request_forms/tutorial001_an.py!}
- ```
+//// tab | Python 3.8+ non-Annotated
-=== "Python 3.8+ non-Annotated"
+/// tip
- !!! tip
- Prefer to use the `Annotated` version if possible.
+Prefer to use the `Annotated` version if possible.
- ```Python hl_lines="1"
- {!> ../../../docs_src/request_forms/tutorial001.py!}
- ```
+///
+
+```Python hl_lines="1"
+{!> ../../../docs_src/request_forms/tutorial001.py!}
+```
+
+////
## Define `Form` parameters
Create form parameters the same way you would for `Body` or `Query`:
-=== "Python 3.9+"
+//// tab | Python 3.9+
+
+```Python hl_lines="9"
+{!> ../../../docs_src/request_forms/tutorial001_an_py39.py!}
+```
+
+////
+
+//// tab | Python 3.8+
- ```Python hl_lines="9"
- {!> ../../../docs_src/request_forms/tutorial001_an_py39.py!}
- ```
+```Python hl_lines="8"
+{!> ../../../docs_src/request_forms/tutorial001_an.py!}
+```
-=== "Python 3.8+"
+////
- ```Python hl_lines="8"
- {!> ../../../docs_src/request_forms/tutorial001_an.py!}
- ```
+//// tab | Python 3.8+ non-Annotated
-=== "Python 3.8+ non-Annotated"
+/// tip
- !!! tip
- Prefer to use the `Annotated` version if possible.
+Prefer to use the `Annotated` version if possible.
- ```Python hl_lines="7"
- {!> ../../../docs_src/request_forms/tutorial001.py!}
- ```
+///
+
+```Python hl_lines="7"
+{!> ../../../docs_src/request_forms/tutorial001.py!}
+```
+
+////
For example, in one of the ways the OAuth2 specification can be used (called "password flow") it is required to send a `username` and `password` as form fields.
With `Form` you can declare the same configurations as with `Body` (and `Query`, `Path`, `Cookie`), including validation, examples, an alias (e.g. `user-name` instead of `username`), etc.
-!!! info
- `Form` is a class that inherits directly from `Body`.
+/// info
+
+`Form` is a class that inherits directly from `Body`.
+
+///
+
+/// tip
-!!! tip
- To declare form bodies, you need to use `Form` explicitly, because without it the parameters would be interpreted as query parameters or body (JSON) parameters.
+To declare form bodies, you need to use `Form` explicitly, because without it the parameters would be interpreted as query parameters or body (JSON) parameters.
+
+///
## About "Form Fields"
**FastAPI** will make sure to read that data from the right place instead of JSON.
-!!! note "Technical Details"
- Data from forms is normally encoded using the "media type" `application/x-www-form-urlencoded`.
+/// note | "Technical Details"
+
+Data from forms is normally encoded using the "media type" `application/x-www-form-urlencoded`.
+
+But when the form includes files, it is encoded as `multipart/form-data`. You'll read about handling files in the next chapter.
+
+If you want to read more about these encodings and form fields, head to the <a href="https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods/POST" class="external-link" target="_blank"><abbr title="Mozilla Developer Network">MDN</abbr> web docs for <code>POST</code></a>.
+
+///
- 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 <a href="https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods/POST" class="external-link" target="_blank"><abbr title="Mozilla Developer Network">MDN</abbr> web docs for <code>POST</code></a>.
+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
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+"
+//// tab | Python 3.10+
- ```Python hl_lines="16 21"
- {!> ../../../docs_src/response_model/tutorial001_01_py310.py!}
- ```
+```Python hl_lines="16 21"
+{!> ../../../docs_src/response_model/tutorial001_01_py310.py!}
+```
+
+////
+
+//// tab | Python 3.9+
-=== "Python 3.9+"
+```Python hl_lines="18 23"
+{!> ../../../docs_src/response_model/tutorial001_01_py39.py!}
+```
+
+////
- ```Python hl_lines="18 23"
- {!> ../../../docs_src/response_model/tutorial001_01_py39.py!}
- ```
+//// tab | Python 3.8+
-=== "Python 3.8+"
+```Python hl_lines="18 23"
+{!> ../../../docs_src/response_model/tutorial001_01.py!}
+```
- ```Python hl_lines="18 23"
- {!> ../../../docs_src/response_model/tutorial001_01.py!}
- ```
+////
FastAPI will use this return type to:
* `@app.delete()`
* etc.
-=== "Python 3.10+"
+//// tab | Python 3.10+
- ```Python hl_lines="17 22 24-27"
- {!> ../../../docs_src/response_model/tutorial001_py310.py!}
- ```
+```Python hl_lines="17 22 24-27"
+{!> ../../../docs_src/response_model/tutorial001_py310.py!}
+```
+
+////
-=== "Python 3.9+"
+//// tab | Python 3.9+
- ```Python hl_lines="17 22 24-27"
- {!> ../../../docs_src/response_model/tutorial001_py39.py!}
- ```
+```Python hl_lines="17 22 24-27"
+{!> ../../../docs_src/response_model/tutorial001_py39.py!}
+```
-=== "Python 3.8+"
+////
- ```Python hl_lines="17 22 24-27"
- {!> ../../../docs_src/response_model/tutorial001.py!}
- ```
+//// tab | Python 3.8+
+
+```Python hl_lines="17 22 24-27"
+{!> ../../../docs_src/response_model/tutorial001.py!}
+```
-!!! note
- Notice that `response_model` is a parameter of the "decorator" method (`get`, `post`, etc). Not of your *path operation function*, like all the parameters and body.
+////
+
+/// 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
+
+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`.
- 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
Here we are declaring a `UserIn` model, it will contain a plaintext password:
-=== "Python 3.10+"
+//// tab | Python 3.10+
+
+```Python hl_lines="7 9"
+{!> ../../../docs_src/response_model/tutorial002_py310.py!}
+```
+
+////
+
+//// tab | Python 3.8+
+
+```Python hl_lines="9 11"
+{!> ../../../docs_src/response_model/tutorial002.py!}
+```
- ```Python hl_lines="7 9"
- {!> ../../../docs_src/response_model/tutorial002_py310.py!}
- ```
+////
-=== "Python 3.8+"
+/// info
- ```Python hl_lines="9 11"
- {!> ../../../docs_src/response_model/tutorial002.py!}
- ```
+To use `EmailStr`, first install <a href="https://github.com/JoshData/python-email-validator" class="external-link" target="_blank">`email_validator`</a>.
-!!! info
- To use `EmailStr`, first install <a href="https://github.com/JoshData/python-email-validator" class="external-link" target="_blank">`email_validator`</a>.
+E.g. `pip install email-validator`
+or `pip install pydantic[email]`.
- E.g. `pip install email-validator`
- or `pip install pydantic[email]`.
+///
And we are using this model to declare our input and the same model to declare our output:
-=== "Python 3.10+"
+//// tab | Python 3.10+
+
+```Python hl_lines="16"
+{!> ../../../docs_src/response_model/tutorial002_py310.py!}
+```
+
+////
- ```Python hl_lines="16"
- {!> ../../../docs_src/response_model/tutorial002_py310.py!}
- ```
+//// tab | Python 3.8+
-=== "Python 3.8+"
+```Python hl_lines="18"
+{!> ../../../docs_src/response_model/tutorial002.py!}
+```
- ```Python hl_lines="18"
- {!> ../../../docs_src/response_model/tutorial002.py!}
- ```
+////
Now, whenever a browser is creating a user with a password, the API will return the same password in the response.
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
+
+Never store the plain password of a user or send it in a response like this, unless you know all the caveats and you know what you are doing.
+
+///
## Add an output model
We can instead create an input model with the plaintext password and an output model without it:
-=== "Python 3.10+"
+//// tab | Python 3.10+
+
+```Python hl_lines="9 11 16"
+{!> ../../../docs_src/response_model/tutorial003_py310.py!}
+```
- ```Python hl_lines="9 11 16"
- {!> ../../../docs_src/response_model/tutorial003_py310.py!}
- ```
+////
-=== "Python 3.8+"
+//// tab | Python 3.8+
+
+```Python hl_lines="9 11 16"
+{!> ../../../docs_src/response_model/tutorial003.py!}
+```
- ```Python hl_lines="9 11 16"
- {!> ../../../docs_src/response_model/tutorial003.py!}
- ```
+////
Here, even though our *path operation function* is returning the same input user that contains the password:
-=== "Python 3.10+"
+//// tab | Python 3.10+
- ```Python hl_lines="24"
- {!> ../../../docs_src/response_model/tutorial003_py310.py!}
- ```
+```Python hl_lines="24"
+{!> ../../../docs_src/response_model/tutorial003_py310.py!}
+```
+
+////
-=== "Python 3.8+"
+//// tab | Python 3.8+
- ```Python hl_lines="24"
- {!> ../../../docs_src/response_model/tutorial003.py!}
- ```
+```Python hl_lines="24"
+{!> ../../../docs_src/response_model/tutorial003.py!}
+```
+
+////
...we declared the `response_model` to be our model `UserOut`, that doesn't include the password:
-=== "Python 3.10+"
+//// tab | Python 3.10+
+
+```Python hl_lines="22"
+{!> ../../../docs_src/response_model/tutorial003_py310.py!}
+```
+
+////
- ```Python hl_lines="22"
- {!> ../../../docs_src/response_model/tutorial003_py310.py!}
- ```
+//// tab | Python 3.8+
-=== "Python 3.8+"
+```Python hl_lines="22"
+{!> ../../../docs_src/response_model/tutorial003.py!}
+```
- ```Python hl_lines="22"
- {!> ../../../docs_src/response_model/tutorial003.py!}
- ```
+////
So, **FastAPI** will take care of filtering out all the data that is not declared in the output model (using Pydantic).
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+"
+//// tab | Python 3.10+
+
+```Python hl_lines="7-10 13-14 18"
+{!> ../../../docs_src/response_model/tutorial003_01_py310.py!}
+```
+
+////
- ```Python hl_lines="7-10 13-14 18"
- {!> ../../../docs_src/response_model/tutorial003_01_py310.py!}
- ```
+//// tab | Python 3.8+
-=== "Python 3.8+"
+```Python hl_lines="9-13 15-16 20"
+{!> ../../../docs_src/response_model/tutorial003_01.py!}
+```
- ```Python hl_lines="9-13 15-16 20"
- {!> ../../../docs_src/response_model/tutorial003_01.py!}
- ```
+////
With this, we get tooling support, from editors and mypy as this code is correct in terms of types, but we also get the data filtering from FastAPI.
The same would happen if you had something like a <abbr title='A union between multiple types means "any of these types".'>union</abbr> between different types where one or more of them are not valid Pydantic types, for example this would fail 💥:
-=== "Python 3.10+"
+//// tab | Python 3.10+
+
+```Python hl_lines="8"
+{!> ../../../docs_src/response_model/tutorial003_04_py310.py!}
+```
+
+////
- ```Python hl_lines="8"
- {!> ../../../docs_src/response_model/tutorial003_04_py310.py!}
- ```
+//// tab | Python 3.8+
-=== "Python 3.8+"
+```Python hl_lines="10"
+{!> ../../../docs_src/response_model/tutorial003_04.py!}
+```
- ```Python hl_lines="10"
- {!> ../../../docs_src/response_model/tutorial003_04.py!}
- ```
+////
...this fails because the type annotation is not a Pydantic type and is not just a single `Response` class or subclass, it's a union (any of the two) between a `Response` and a `dict`.
In this case, you can disable the response model generation by setting `response_model=None`:
-=== "Python 3.10+"
+//// tab | Python 3.10+
- ```Python hl_lines="7"
- {!> ../../../docs_src/response_model/tutorial003_05_py310.py!}
- ```
+```Python hl_lines="7"
+{!> ../../../docs_src/response_model/tutorial003_05_py310.py!}
+```
+
+////
-=== "Python 3.8+"
+//// tab | Python 3.8+
- ```Python hl_lines="9"
- {!> ../../../docs_src/response_model/tutorial003_05.py!}
- ```
+```Python hl_lines="9"
+{!> ../../../docs_src/response_model/tutorial003_05.py!}
+```
+
+////
This will make FastAPI skip the response model generation and that way you can have any return type annotations you need without it affecting your FastAPI application. 🤓
Your response model could have default values, like:
-=== "Python 3.10+"
+//// tab | Python 3.10+
- ```Python hl_lines="9 11-12"
- {!> ../../../docs_src/response_model/tutorial004_py310.py!}
- ```
+```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!}
- ```
+//// tab | Python 3.9+
-=== "Python 3.8+"
+```Python hl_lines="11 13-14"
+{!> ../../../docs_src/response_model/tutorial004_py39.py!}
+```
+
+////
+
+//// tab | Python 3.8+
+
+```Python hl_lines="11 13-14"
+{!> ../../../docs_src/response_model/tutorial004.py!}
+```
- ```Python hl_lines="11 13-14"
- {!> ../../../docs_src/response_model/tutorial004.py!}
- ```
+////
* `description: Union[str, None] = None` (or `str | None = None` in Python 3.10) has a default of `None`.
* `tax: float = 10.5` has a default of `10.5`.
You can set the *path operation decorator* parameter `response_model_exclude_unset=True`:
-=== "Python 3.10+"
+//// tab | Python 3.10+
- ```Python hl_lines="22"
- {!> ../../../docs_src/response_model/tutorial004_py310.py!}
- ```
+```Python hl_lines="22"
+{!> ../../../docs_src/response_model/tutorial004_py310.py!}
+```
+
+////
+
+//// tab | Python 3.9+
+
+```Python hl_lines="24"
+{!> ../../../docs_src/response_model/tutorial004_py39.py!}
+```
-=== "Python 3.9+"
+////
- ```Python hl_lines="24"
- {!> ../../../docs_src/response_model/tutorial004_py39.py!}
- ```
+//// tab | Python 3.8+
-=== "Python 3.8+"
+```Python hl_lines="24"
+{!> ../../../docs_src/response_model/tutorial004.py!}
+```
- ```Python hl_lines="24"
- {!> ../../../docs_src/response_model/tutorial004.py!}
- ```
+////
and those default values won't be included in the response, only the values actually set.
}
```
-!!! info
- In Pydantic v1 the method was called `.dict()`, it was deprecated (but still supported) in Pydantic v2, and renamed to `.model_dump()`.
+/// 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 <a href="https://docs.pydantic.dev/latest/concepts/serialization/#modeldict" class="external-link" target="_blank">its `exclude_unset` parameter</a> to achieve this.
- 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 <a href="https://docs.pydantic.dev/latest/concepts/serialization/#modeldict" class="external-link" target="_blank">its `exclude_unset` parameter</a> 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 <a href="https://docs.pydantic.dev/latest/concepts/serialization/#modeldict" class="external-link" target="_blank">the Pydantic docs</a> for `exclude_defaults` and `exclude_none`.
+as described in <a href="https://docs.pydantic.dev/latest/concepts/serialization/#modeldict" class="external-link" target="_blank">the Pydantic docs</a> for `exclude_defaults` and `exclude_none`.
+
+///
#### Data with values for fields with defaults
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`
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
- 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.
+But it is still recommended to use the ideas above, using multiple classes, instead of these parameters.
- This also applies to `response_model_by_alias` that works similarly.
+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.
-=== "Python 3.10+"
+This also applies to `response_model_by_alias` that works similarly.
- ```Python hl_lines="29 35"
- {!> ../../../docs_src/response_model/tutorial005_py310.py!}
- ```
+///
-=== "Python 3.8+"
+//// tab | Python 3.10+
- ```Python hl_lines="31 37"
- {!> ../../../docs_src/response_model/tutorial005.py!}
- ```
+```Python hl_lines="29 35"
+{!> ../../../docs_src/response_model/tutorial005_py310.py!}
+```
-!!! tip
- The syntax `{"name", "description"}` creates a `set` with those two values.
+////
- It is equivalent to `set(["name", "description"])`.
+//// tab | Python 3.8+
+
+```Python hl_lines="31 37"
+{!> ../../../docs_src/response_model/tutorial005.py!}
+```
+
+////
+
+/// tip
+
+The syntax `{"name", "description"}` creates a `set` with those two values.
+
+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+"
+//// tab | Python 3.10+
+
+```Python hl_lines="29 35"
+{!> ../../../docs_src/response_model/tutorial006_py310.py!}
+```
- ```Python hl_lines="29 35"
- {!> ../../../docs_src/response_model/tutorial006_py310.py!}
- ```
+////
-=== "Python 3.8+"
+//// tab | Python 3.8+
+
+```Python hl_lines="31 37"
+{!> ../../../docs_src/response_model/tutorial006.py!}
+```
- ```Python hl_lines="31 37"
- {!> ../../../docs_src/response_model/tutorial006.py!}
- ```
+////
## Recap
{!../../../docs_src/response_status_code/tutorial001.py!}
```
-!!! 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 <a href="https://docs.python.org/3/library/http.html#http.HTTPStatus" class="external-link" target="_blank">`http.HTTPStatus`</a>.
+/// info
+
+`status_code` can alternatively also receive an `IntEnum`, such as Python's <a href="https://docs.python.org/3/library/http.html#http.HTTPStatus" class="external-link" target="_blank">`http.HTTPStatus`</a>.
+
+///
It will:
<img src="/img/tutorial/response-status-code/image01.png">
-!!! note
- Some response codes (see the next section) indicate that the response does not have a body.
+/// note
+
+Some response codes (see the next section) indicate that the response does not have a body.
+
+FastAPI knows this, and will produce OpenAPI docs that state there is no response body.
- FastAPI knows this, and will produce OpenAPI docs that state there is no response body.
+///
## About HTTP status codes
-!!! note
- If you already know what HTTP status codes are, skip to the next section.
+/// note
+
+If you already know what HTTP status codes are, skip to the next section.
+
+///
In HTTP, you send a numeric status code of 3 digits as part of the response.
* For generic errors from the client, you can just use `400`.
* `500` and above are for server errors. You almost never use them directly. When something goes wrong at some part in your application code, or server, it will automatically return one of these status codes.
-!!! tip
- To know more about each status code and which code is for what, check the <a href="https://developer.mozilla.org/en-US/docs/Web/HTTP/Status" class="external-link" target="_blank"><abbr title="Mozilla Developer Network">MDN</abbr> documentation about HTTP status codes</a>.
+/// tip
+
+To know more about each status code and which code is for what, check the <a href="https://developer.mozilla.org/en-US/docs/Web/HTTP/Status" class="external-link" target="_blank"><abbr title="Mozilla Developer Network">MDN</abbr> documentation about HTTP status codes</a>.
+
+///
## Shortcut to remember the names
<img src="/img/tutorial/response-status-code/image02.png">
-!!! note "Technical Details"
- You could also use `from starlette import status`.
+/// note | "Technical Details"
+
+You could also use `from starlette import status`.
+
+**FastAPI** provides the same `starlette.status` as `fastapi.status` just as a convenience for you, the developer. But it comes directly from Starlette.
- **FastAPI** provides the same `starlette.status` as `fastapi.status` just as a convenience for you, the developer. But it comes directly from Starlette.
+///
## Changing the default
You can declare `examples` for a Pydantic model that will be added to the generated JSON Schema.
-=== "Python 3.10+ Pydantic v2"
+//// tab | Python 3.10+ Pydantic v2
- ```Python hl_lines="13-24"
- {!> ../../../docs_src/schema_extra_example/tutorial001_py310.py!}
- ```
+```Python hl_lines="13-24"
+{!> ../../../docs_src/schema_extra_example/tutorial001_py310.py!}
+```
-=== "Python 3.10+ Pydantic v1"
+////
- ```Python hl_lines="13-23"
- {!> ../../../docs_src/schema_extra_example/tutorial001_py310_pv1.py!}
- ```
+//// tab | Python 3.10+ Pydantic v1
-=== "Python 3.8+ Pydantic v2"
+```Python hl_lines="13-23"
+{!> ../../../docs_src/schema_extra_example/tutorial001_py310_pv1.py!}
+```
- ```Python hl_lines="15-26"
- {!> ../../../docs_src/schema_extra_example/tutorial001.py!}
- ```
+////
-=== "Python 3.8+ Pydantic v1"
+//// tab | Python 3.8+ Pydantic v2
- ```Python hl_lines="15-25"
- {!> ../../../docs_src/schema_extra_example/tutorial001_pv1.py!}
- ```
+```Python hl_lines="15-26"
+{!> ../../../docs_src/schema_extra_example/tutorial001.py!}
+```
+
+////
+
+//// tab | Python 3.8+ Pydantic v1
+
+```Python hl_lines="15-25"
+{!> ../../../docs_src/schema_extra_example/tutorial001_pv1.py!}
+```
+
+////
That extra info will be added as-is to the output **JSON Schema** for that model, and it will be used in the API docs.
-=== "Pydantic v2"
+//// tab | Pydantic v2
+
+In Pydantic version 2, you would use the attribute `model_config`, that takes a `dict` as described in <a href="https://docs.pydantic.dev/latest/usage/model_config/" class="external-link" target="_blank">Pydantic's docs: Model Config</a>.
+
+You can set `"json_schema_extra"` with a `dict` containing any additional data you would like to show up in the generated JSON Schema, including `examples`.
- In Pydantic version 2, you would use the attribute `model_config`, that takes a `dict` as described in <a href="https://docs.pydantic.dev/latest/usage/model_config/" class="external-link" target="_blank">Pydantic's docs: Model Config</a>.
+////
- You can set `"json_schema_extra"` with a `dict` containing any additional data you would like to show up in the generated JSON Schema, including `examples`.
+//// tab | Pydantic v1
-=== "Pydantic v1"
+In Pydantic version 1, you would use an internal class `Config` and `schema_extra`, as described in <a href="https://docs.pydantic.dev/1.10/usage/schema/#schema-customization" class="external-link" target="_blank">Pydantic's docs: Schema customization</a>.
- In Pydantic version 1, you would use an internal class `Config` and `schema_extra`, as described in <a href="https://docs.pydantic.dev/1.10/usage/schema/#schema-customization" class="external-link" target="_blank">Pydantic's docs: Schema customization</a>.
+You can set `schema_extra` with a `dict` containing any additional data you would like to show up in the generated JSON Schema, including `examples`.
- You can set `schema_extra` with a `dict` containing any additional data you would like to show up in the generated JSON Schema, including `examples`.
+////
-!!! tip
- You could use the same technique to extend the JSON Schema and add your own custom extra info.
+/// tip
- For example you could use it to add metadata for a frontend user interface, etc.
+You could use the same technique to extend the JSON Schema and add your own custom extra info.
-!!! info
- OpenAPI 3.1.0 (used since FastAPI 0.99.0) added support for `examples`, which is part of the **JSON Schema** standard.
+For example you could use it to add metadata for a frontend user interface, etc.
- Before that, it only supported the keyword `example` with a single example. That is still supported by OpenAPI 3.1.0, but is deprecated and is not part of the JSON Schema standard. So you are encouraged to migrate `example` to `examples`. 🤓
+///
- You can read more at the end of this page.
+/// info
+
+OpenAPI 3.1.0 (used since FastAPI 0.99.0) added support for `examples`, which is part of the **JSON Schema** standard.
+
+Before that, it only supported the keyword `example` with a single example. That is still supported by OpenAPI 3.1.0, but is deprecated and is not part of the JSON Schema standard. So you are encouraged to migrate `example` to `examples`. 🤓
+
+You can read more at the end of this page.
+
+///
## `Field` additional arguments
When using `Field()` with Pydantic models, you can also declare additional `examples`:
-=== "Python 3.10+"
+//// tab | Python 3.10+
+
+```Python hl_lines="2 8-11"
+{!> ../../../docs_src/schema_extra_example/tutorial002_py310.py!}
+```
+
+////
- ```Python hl_lines="2 8-11"
- {!> ../../../docs_src/schema_extra_example/tutorial002_py310.py!}
- ```
+//// tab | Python 3.8+
-=== "Python 3.8+"
+```Python hl_lines="4 10-13"
+{!> ../../../docs_src/schema_extra_example/tutorial002.py!}
+```
- ```Python hl_lines="4 10-13"
- {!> ../../../docs_src/schema_extra_example/tutorial002.py!}
- ```
+////
## `examples` in JSON Schema - OpenAPI
Here we pass `examples` containing one example of the data expected in `Body()`:
-=== "Python 3.10+"
+//// tab | Python 3.10+
- ```Python hl_lines="22-29"
- {!> ../../../docs_src/schema_extra_example/tutorial003_an_py310.py!}
- ```
+```Python hl_lines="22-29"
+{!> ../../../docs_src/schema_extra_example/tutorial003_an_py310.py!}
+```
-=== "Python 3.9+"
+////
- ```Python hl_lines="22-29"
- {!> ../../../docs_src/schema_extra_example/tutorial003_an_py39.py!}
- ```
+//// tab | Python 3.9+
-=== "Python 3.8+"
+```Python hl_lines="22-29"
+{!> ../../../docs_src/schema_extra_example/tutorial003_an_py39.py!}
+```
- ```Python hl_lines="23-30"
- {!> ../../../docs_src/schema_extra_example/tutorial003_an.py!}
- ```
+////
-=== "Python 3.10+ non-Annotated"
+//// tab | Python 3.8+
- !!! tip
- Prefer to use the `Annotated` version if possible.
+```Python hl_lines="23-30"
+{!> ../../../docs_src/schema_extra_example/tutorial003_an.py!}
+```
- ```Python hl_lines="18-25"
- {!> ../../../docs_src/schema_extra_example/tutorial003_py310.py!}
- ```
+////
-=== "Python 3.8+ non-Annotated"
+//// tab | Python 3.10+ non-Annotated
- !!! tip
- Prefer to use the `Annotated` version if possible.
+/// tip
- ```Python hl_lines="20-27"
- {!> ../../../docs_src/schema_extra_example/tutorial003.py!}
- ```
+Prefer to use the `Annotated` version if possible.
+
+///
+
+```Python hl_lines="18-25"
+{!> ../../../docs_src/schema_extra_example/tutorial003_py310.py!}
+```
+
+////
+
+//// tab | Python 3.8+ non-Annotated
+
+/// tip
+
+Prefer to use the `Annotated` version if possible.
+
+///
+
+```Python hl_lines="20-27"
+{!> ../../../docs_src/schema_extra_example/tutorial003.py!}
+```
+
+////
### Example in the docs UI
You can of course also pass multiple `examples`:
-=== "Python 3.10+"
+//// tab | Python 3.10+
+
+```Python hl_lines="23-38"
+{!> ../../../docs_src/schema_extra_example/tutorial004_an_py310.py!}
+```
+
+////
+
+//// tab | Python 3.9+
- ```Python hl_lines="23-38"
- {!> ../../../docs_src/schema_extra_example/tutorial004_an_py310.py!}
- ```
+```Python hl_lines="23-38"
+{!> ../../../docs_src/schema_extra_example/tutorial004_an_py39.py!}
+```
-=== "Python 3.9+"
+////
- ```Python hl_lines="23-38"
- {!> ../../../docs_src/schema_extra_example/tutorial004_an_py39.py!}
- ```
+//// tab | Python 3.8+
-=== "Python 3.8+"
+```Python hl_lines="24-39"
+{!> ../../../docs_src/schema_extra_example/tutorial004_an.py!}
+```
- ```Python hl_lines="24-39"
- {!> ../../../docs_src/schema_extra_example/tutorial004_an.py!}
- ```
+////
-=== "Python 3.10+ non-Annotated"
+//// tab | Python 3.10+ non-Annotated
- !!! tip
- Prefer to use the `Annotated` version if possible.
+/// tip
- ```Python hl_lines="19-34"
- {!> ../../../docs_src/schema_extra_example/tutorial004_py310.py!}
- ```
+Prefer to use the `Annotated` version if possible.
-=== "Python 3.8+ non-Annotated"
+///
- !!! tip
- Prefer to use the `Annotated` version if possible.
+```Python hl_lines="19-34"
+{!> ../../../docs_src/schema_extra_example/tutorial004_py310.py!}
+```
- ```Python hl_lines="21-36"
- {!> ../../../docs_src/schema_extra_example/tutorial004.py!}
- ```
+////
+
+//// tab | Python 3.8+ non-Annotated
+
+/// tip
+
+Prefer to use the `Annotated` version if possible.
+
+///
+
+```Python hl_lines="21-36"
+{!> ../../../docs_src/schema_extra_example/tutorial004.py!}
+```
+
+////
When you do this, the examples will be part of the internal **JSON Schema** for that body data.
You can use it like this:
-=== "Python 3.10+"
+//// tab | Python 3.10+
+
+```Python hl_lines="23-49"
+{!> ../../../docs_src/schema_extra_example/tutorial005_an_py310.py!}
+```
+
+////
+
+//// tab | Python 3.9+
+
+```Python hl_lines="23-49"
+{!> ../../../docs_src/schema_extra_example/tutorial005_an_py39.py!}
+```
+
+////
+
+//// tab | Python 3.8+
- ```Python hl_lines="23-49"
- {!> ../../../docs_src/schema_extra_example/tutorial005_an_py310.py!}
- ```
+```Python hl_lines="24-50"
+{!> ../../../docs_src/schema_extra_example/tutorial005_an.py!}
+```
-=== "Python 3.9+"
+////
- ```Python hl_lines="23-49"
- {!> ../../../docs_src/schema_extra_example/tutorial005_an_py39.py!}
- ```
+//// tab | Python 3.10+ non-Annotated
-=== "Python 3.8+"
+/// tip
- ```Python hl_lines="24-50"
- {!> ../../../docs_src/schema_extra_example/tutorial005_an.py!}
- ```
+Prefer to use the `Annotated` version if possible.
-=== "Python 3.10+ non-Annotated"
+///
- !!! tip
- Prefer to use the `Annotated` version if possible.
+```Python hl_lines="19-45"
+{!> ../../../docs_src/schema_extra_example/tutorial005_py310.py!}
+```
- ```Python hl_lines="19-45"
- {!> ../../../docs_src/schema_extra_example/tutorial005_py310.py!}
- ```
+////
-=== "Python 3.8+ non-Annotated"
+//// tab | Python 3.8+ non-Annotated
- !!! tip
- Prefer to use the `Annotated` version if possible.
+/// tip
- ```Python hl_lines="21-47"
- {!> ../../../docs_src/schema_extra_example/tutorial005.py!}
- ```
+Prefer to use the `Annotated` version if possible.
+
+///
+
+```Python hl_lines="21-47"
+{!> ../../../docs_src/schema_extra_example/tutorial005.py!}
+```
+
+////
### OpenAPI Examples in the Docs UI
## Technical Details
-!!! tip
- If you are already using **FastAPI** version **0.99.0 or above**, you can probably **skip** these details.
+/// tip
+
+If you are already using **FastAPI** version **0.99.0 or above**, you can probably **skip** these details.
+
+They are more relevant for older versions, before OpenAPI 3.1.0 was available.
+
+You can consider this a brief OpenAPI and JSON Schema **history lesson**. 🤓
- They are more relevant for older versions, before OpenAPI 3.1.0 was available.
+///
- You can consider this a brief OpenAPI and JSON Schema **history lesson**. 🤓
+/// warning
-!!! warning
- These are very technical details about the standards **JSON Schema** and **OpenAPI**.
+These are very technical details about the standards **JSON Schema** and **OpenAPI**.
- If the ideas above already work for you, that might be enough, and you probably don't need these details, feel free to skip them.
+If the ideas above already work for you, that might be enough, and you probably don't need these details, feel free to skip them.
+
+///
Before OpenAPI 3.1.0, OpenAPI used an older and modified version of **JSON Schema**.
* `File()`
* `Form()`
-!!! info
- This old OpenAPI-specific `examples` parameter is now `openapi_examples` since FastAPI `0.103.0`.
+/// info
+
+This old OpenAPI-specific `examples` parameter is now `openapi_examples` since FastAPI `0.103.0`.
+
+///
### JSON Schema's `examples` field
This new `examples` field in JSON Schema is **just a `list`** of examples, not a dict with extra metadata as in the other places in OpenAPI (described above).
-!!! info
- Even after OpenAPI 3.1.0 was released with this new simpler integration with JSON Schema, for a while, Swagger UI, the tool that provides the automatic docs, didn't support OpenAPI 3.1.0 (it does since version 5.0.0 🎉).
+/// info
+
+Even after OpenAPI 3.1.0 was released with this new simpler integration with JSON Schema, for a while, Swagger UI, the tool that provides the automatic docs, didn't support OpenAPI 3.1.0 (it does since version 5.0.0 🎉).
+
+Because of that, versions of FastAPI previous to 0.99.0 still used versions of OpenAPI lower than 3.1.0.
- Because of that, versions of FastAPI previous to 0.99.0 still used versions of OpenAPI lower than 3.1.0.
+///
### Pydantic and FastAPI `examples`
Copy the example in a file `main.py`:
-=== "Python 3.9+"
+//// tab | Python 3.9+
- ```Python
- {!> ../../../docs_src/security/tutorial001_an_py39.py!}
- ```
+```Python
+{!> ../../../docs_src/security/tutorial001_an_py39.py!}
+```
+
+////
+
+//// tab | Python 3.8+
+
+```Python
+{!> ../../../docs_src/security/tutorial001_an.py!}
+```
+
+////
-=== "Python 3.8+"
+//// tab | Python 3.8+ non-Annotated
- ```Python
- {!> ../../../docs_src/security/tutorial001_an.py!}
- ```
+/// tip
-=== "Python 3.8+ non-Annotated"
+Prefer to use the `Annotated` version if possible.
- !!! tip
- Prefer to use the `Annotated` version if possible.
+///
- ```Python
- {!> ../../../docs_src/security/tutorial001.py!}
- ```
+```Python
+{!> ../../../docs_src/security/tutorial001.py!}
+```
+////
## Run it
-!!! info
- The <a href="https://github.com/Kludex/python-multipart" class="external-link" target="_blank">`python-multipart`</a> package is automatically installed with **FastAPI** when you run the `pip install "fastapi[standard]"` command.
+/// info
- However, if you use the `pip install fastapi` command, the `python-multipart` package is not included by default. To install it manually, use the following command:
+The <a href="https://github.com/Kludex/python-multipart" class="external-link" target="_blank">`python-multipart`</a> package is automatically installed with **FastAPI** when you run the `pip install "fastapi[standard]"` command.
- `pip install python-multipart`
+However, if you use the `pip install fastapi` command, the `python-multipart` package is not included by default. To install it manually, use the following command:
- This is because **OAuth2** uses "form data" for sending the `username` and `password`.
+`pip install python-multipart`
+
+This is because **OAuth2** uses "form data" for sending the `username` and `password`.
+
+///
Run the example with:
<img src="/img/tutorial/security/image01.png">
-!!! check "Authorize button!"
- You already have a shiny new "Authorize" button.
+/// check | "Authorize button!"
+
+You already have a shiny new "Authorize" button.
- And your *path operation* has a little lock in the top-right corner that you can click.
+And your *path operation* has a little lock in the top-right corner that you can click.
+
+///
And if you click it, you have a little authorization form to type a `username` and `password` (and other optional fields):
<img src="/img/tutorial/security/image02.png">
-!!! note
- It doesn't matter what you type in the form, it won't work yet. But we'll get there.
+/// note
+
+It doesn't matter what you type in the form, it won't work yet. But we'll get there.
+
+///
This is of course not the frontend for the final users, but it's a great automatic tool to document interactively all your API.
In this example we are going to use **OAuth2**, with the **Password** flow, using a **Bearer** token. We do that using the `OAuth2PasswordBearer` class.
-!!! info
- A "bearer" token is not the only option.
+/// info
+
+A "bearer" token is not the only option.
+
+But it's the best one for our use case.
- But it's the best one for our use case.
+And it might be the best for most use cases, unless you are an OAuth2 expert and know exactly why there's another option that suits better your needs.
- And it might be the best for most use cases, unless you are an OAuth2 expert and know exactly why there's another option that suits better your needs.
+In that case, **FastAPI** also provides you with the tools to build it.
- In that case, **FastAPI** also provides you with the tools to build it.
+///
When we create an instance of the `OAuth2PasswordBearer` class we pass in the `tokenUrl` parameter. This parameter contains the URL that the client (the frontend running in the user's browser) will use to send the `username` and `password` in order to get a token.
-=== "Python 3.9+"
+//// tab | Python 3.9+
+
+```Python hl_lines="8"
+{!> ../../../docs_src/security/tutorial001_an_py39.py!}
+```
+
+////
+
+//// tab | Python 3.8+
+
+```Python hl_lines="7"
+{!> ../../../docs_src/security/tutorial001_an.py!}
+```
+
+////
- ```Python hl_lines="8"
- {!> ../../../docs_src/security/tutorial001_an_py39.py!}
- ```
+//// tab | Python 3.8+ non-Annotated
-=== "Python 3.8+"
+/// tip
- ```Python hl_lines="7"
- {!> ../../../docs_src/security/tutorial001_an.py!}
- ```
+Prefer to use the `Annotated` version if possible.
-=== "Python 3.8+ non-Annotated"
+///
- !!! tip
- Prefer to use the `Annotated` version if possible.
+```Python hl_lines="6"
+{!> ../../../docs_src/security/tutorial001.py!}
+```
+
+////
+
+/// tip
- ```Python hl_lines="6"
- {!> ../../../docs_src/security/tutorial001.py!}
- ```
+Here `tokenUrl="token"` refers to a relative URL `token` that we haven't created yet. As it's a relative URL, it's equivalent to `./token`.
-!!! tip
- Here `tokenUrl="token"` refers to a relative URL `token` that we haven't created yet. As it's a relative URL, it's equivalent to `./token`.
+Because we are using a relative URL, if your API was located at `https://example.com/`, then it would refer to `https://example.com/token`. But if your API was located at `https://example.com/api/v1/`, then it would refer to `https://example.com/api/v1/token`.
- Because we are using a relative URL, if your API was located at `https://example.com/`, then it would refer to `https://example.com/token`. But if your API was located at `https://example.com/api/v1/`, then it would refer to `https://example.com/api/v1/token`.
+Using a relative URL is important to make sure your application keeps working even in an advanced use case like [Behind a Proxy](../../advanced/behind-a-proxy.md){.internal-link target=_blank}.
- Using a relative URL is important to make sure your application keeps working even in an advanced use case like [Behind a Proxy](../../advanced/behind-a-proxy.md){.internal-link target=_blank}.
+///
This parameter doesn't create that endpoint / *path operation*, but declares that the URL `/token` will be the one that the client should use to get the token. That information is used in OpenAPI, and then in the interactive API documentation systems.
We will soon also create the actual path operation.
-!!! info
- If you are a very strict "Pythonista" you might dislike the style of the parameter name `tokenUrl` instead of `token_url`.
+/// info
+
+If you are a very strict "Pythonista" you might dislike the style of the parameter name `tokenUrl` instead of `token_url`.
+
+That's because it is using the same name as in the OpenAPI spec. So that if you need to investigate more about any of these security schemes you can just copy and paste it to find more information about it.
- That's because it is using the same name as in the OpenAPI spec. So that if you need to investigate more about any of these security schemes you can just copy and paste it to find more information about it.
+///
The `oauth2_scheme` variable is an instance of `OAuth2PasswordBearer`, but it is also a "callable".
Now you can pass that `oauth2_scheme` in a dependency with `Depends`.
-=== "Python 3.9+"
+//// tab | Python 3.9+
- ```Python hl_lines="12"
- {!> ../../../docs_src/security/tutorial001_an_py39.py!}
- ```
+```Python hl_lines="12"
+{!> ../../../docs_src/security/tutorial001_an_py39.py!}
+```
+
+////
+
+//// tab | Python 3.8+
+
+```Python hl_lines="11"
+{!> ../../../docs_src/security/tutorial001_an.py!}
+```
-=== "Python 3.8+"
+////
- ```Python hl_lines="11"
- {!> ../../../docs_src/security/tutorial001_an.py!}
- ```
+//// tab | Python 3.8+ non-Annotated
-=== "Python 3.8+ non-Annotated"
+/// tip
- !!! tip
- Prefer to use the `Annotated` version if possible.
+Prefer to use the `Annotated` version if possible.
- ```Python hl_lines="10"
- {!> ../../../docs_src/security/tutorial001.py!}
- ```
+///
+
+```Python hl_lines="10"
+{!> ../../../docs_src/security/tutorial001.py!}
+```
+
+////
This dependency will provide a `str` that is assigned to the parameter `token` of the *path operation function*.
**FastAPI** will know that it can use this dependency to define a "security scheme" in the OpenAPI schema (and the automatic API docs).
-!!! info "Technical Details"
- **FastAPI** will know that it can use the class `OAuth2PasswordBearer` (declared in a dependency) to define the security scheme in OpenAPI because it inherits from `fastapi.security.oauth2.OAuth2`, which in turn inherits from `fastapi.security.base.SecurityBase`.
+/// info | "Technical Details"
+
+**FastAPI** will know that it can use the class `OAuth2PasswordBearer` (declared in a dependency) to define the security scheme in OpenAPI because it inherits from `fastapi.security.oauth2.OAuth2`, which in turn inherits from `fastapi.security.base.SecurityBase`.
+
+All the security utilities that integrate with OpenAPI (and the automatic API docs) inherit from `SecurityBase`, that's how **FastAPI** can know how to integrate them in OpenAPI.
- All the security utilities that integrate with OpenAPI (and the automatic API docs) inherit from `SecurityBase`, that's how **FastAPI** can know how to integrate them in OpenAPI.
+///
## What it does
In the previous chapter the security system (which is based on the dependency injection system) was giving the *path operation function* a `token` as a `str`:
-=== "Python 3.9+"
+//// tab | Python 3.9+
- ```Python hl_lines="12"
- {!> ../../../docs_src/security/tutorial001_an_py39.py!}
- ```
+```Python hl_lines="12"
+{!> ../../../docs_src/security/tutorial001_an_py39.py!}
+```
-=== "Python 3.8+"
+////
- ```Python hl_lines="11"
- {!> ../../../docs_src/security/tutorial001_an.py!}
- ```
+//// tab | Python 3.8+
-=== "Python 3.8+ non-Annotated"
+```Python hl_lines="11"
+{!> ../../../docs_src/security/tutorial001_an.py!}
+```
- !!! tip
- Prefer to use the `Annotated` version if possible.
+////
- ```Python hl_lines="10"
- {!> ../../../docs_src/security/tutorial001.py!}
- ```
+//// tab | Python 3.8+ non-Annotated
+
+/// tip
+
+Prefer to use the `Annotated` version if possible.
+
+///
+
+```Python hl_lines="10"
+{!> ../../../docs_src/security/tutorial001.py!}
+```
+
+////
But that is still not that useful.
The same way we use Pydantic to declare bodies, we can use it anywhere else:
-=== "Python 3.10+"
+//// tab | Python 3.10+
+
+```Python hl_lines="5 12-16"
+{!> ../../../docs_src/security/tutorial002_an_py310.py!}
+```
+
+////
+
+//// tab | Python 3.9+
+
+```Python hl_lines="5 12-16"
+{!> ../../../docs_src/security/tutorial002_an_py39.py!}
+```
+
+////
+
+//// tab | Python 3.8+
+
+```Python hl_lines="5 13-17"
+{!> ../../../docs_src/security/tutorial002_an.py!}
+```
+
+////
+
+//// tab | Python 3.10+ non-Annotated
- ```Python hl_lines="5 12-16"
- {!> ../../../docs_src/security/tutorial002_an_py310.py!}
- ```
+/// tip
-=== "Python 3.9+"
+Prefer to use the `Annotated` version if possible.
- ```Python hl_lines="5 12-16"
- {!> ../../../docs_src/security/tutorial002_an_py39.py!}
- ```
+///
-=== "Python 3.8+"
+```Python hl_lines="3 10-14"
+{!> ../../../docs_src/security/tutorial002_py310.py!}
+```
- ```Python hl_lines="5 13-17"
- {!> ../../../docs_src/security/tutorial002_an.py!}
- ```
+////
-=== "Python 3.10+ non-Annotated"
+//// tab | Python 3.8+ non-Annotated
- !!! tip
- Prefer to use the `Annotated` version if possible.
+/// tip
- ```Python hl_lines="3 10-14"
- {!> ../../../docs_src/security/tutorial002_py310.py!}
- ```
+Prefer to use the `Annotated` version if possible.
-=== "Python 3.8+ non-Annotated"
+///
- !!! tip
- Prefer to use the `Annotated` version if possible.
+```Python hl_lines="5 12-16"
+{!> ../../../docs_src/security/tutorial002.py!}
+```
- ```Python hl_lines="5 12-16"
- {!> ../../../docs_src/security/tutorial002.py!}
- ```
+////
## Create a `get_current_user` dependency
The same as we were doing before in the *path operation* directly, our new dependency `get_current_user` will receive a `token` as a `str` from the sub-dependency `oauth2_scheme`:
-=== "Python 3.10+"
+//// tab | Python 3.10+
- ```Python hl_lines="25"
- {!> ../../../docs_src/security/tutorial002_an_py310.py!}
- ```
+```Python hl_lines="25"
+{!> ../../../docs_src/security/tutorial002_an_py310.py!}
+```
-=== "Python 3.9+"
+////
- ```Python hl_lines="25"
- {!> ../../../docs_src/security/tutorial002_an_py39.py!}
- ```
+//// tab | Python 3.9+
-=== "Python 3.8+"
+```Python hl_lines="25"
+{!> ../../../docs_src/security/tutorial002_an_py39.py!}
+```
- ```Python hl_lines="26"
- {!> ../../../docs_src/security/tutorial002_an.py!}
- ```
+////
-=== "Python 3.10+ non-Annotated"
+//// tab | Python 3.8+
- !!! tip
- Prefer to use the `Annotated` version if possible.
+```Python hl_lines="26"
+{!> ../../../docs_src/security/tutorial002_an.py!}
+```
- ```Python hl_lines="23"
- {!> ../../../docs_src/security/tutorial002_py310.py!}
- ```
+////
-=== "Python 3.8+ non-Annotated"
+//// tab | Python 3.10+ non-Annotated
- !!! tip
- Prefer to use the `Annotated` version if possible.
+/// tip
- ```Python hl_lines="25"
- {!> ../../../docs_src/security/tutorial002.py!}
- ```
+Prefer to use the `Annotated` version if possible.
+
+///
+
+```Python hl_lines="23"
+{!> ../../../docs_src/security/tutorial002_py310.py!}
+```
+
+////
+
+//// tab | Python 3.8+ non-Annotated
+
+/// tip
+
+Prefer to use the `Annotated` version if possible.
+
+///
+
+```Python hl_lines="25"
+{!> ../../../docs_src/security/tutorial002.py!}
+```
+
+////
## Get the user
`get_current_user` will use a (fake) utility function we created, that takes a token as a `str` and returns our Pydantic `User` model:
-=== "Python 3.10+"
+//// tab | Python 3.10+
+
+```Python hl_lines="19-22 26-27"
+{!> ../../../docs_src/security/tutorial002_an_py310.py!}
+```
+
+////
+
+//// tab | Python 3.9+
+
+```Python hl_lines="19-22 26-27"
+{!> ../../../docs_src/security/tutorial002_an_py39.py!}
+```
- ```Python hl_lines="19-22 26-27"
- {!> ../../../docs_src/security/tutorial002_an_py310.py!}
- ```
+////
-=== "Python 3.9+"
+//// tab | Python 3.8+
- ```Python hl_lines="19-22 26-27"
- {!> ../../../docs_src/security/tutorial002_an_py39.py!}
- ```
+```Python hl_lines="20-23 27-28"
+{!> ../../../docs_src/security/tutorial002_an.py!}
+```
-=== "Python 3.8+"
+////
- ```Python hl_lines="20-23 27-28"
- {!> ../../../docs_src/security/tutorial002_an.py!}
- ```
+//// tab | Python 3.10+ non-Annotated
-=== "Python 3.10+ non-Annotated"
+/// tip
- !!! tip
- Prefer to use the `Annotated` version if possible.
+Prefer to use the `Annotated` version if possible.
- ```Python hl_lines="17-20 24-25"
- {!> ../../../docs_src/security/tutorial002_py310.py!}
- ```
+///
-=== "Python 3.8+ non-Annotated"
+```Python hl_lines="17-20 24-25"
+{!> ../../../docs_src/security/tutorial002_py310.py!}
+```
- !!! tip
- Prefer to use the `Annotated` version if possible.
+////
- ```Python hl_lines="19-22 26-27"
- {!> ../../../docs_src/security/tutorial002.py!}
- ```
+//// tab | Python 3.8+ non-Annotated
+
+/// tip
+
+Prefer to use the `Annotated` version if possible.
+
+///
+
+```Python hl_lines="19-22 26-27"
+{!> ../../../docs_src/security/tutorial002.py!}
+```
+
+////
## Inject the current user
So now we can use the same `Depends` with our `get_current_user` in the *path operation*:
-=== "Python 3.10+"
+//// tab | Python 3.10+
+
+```Python hl_lines="31"
+{!> ../../../docs_src/security/tutorial002_an_py310.py!}
+```
+
+////
+
+//// tab | Python 3.9+
+
+```Python hl_lines="31"
+{!> ../../../docs_src/security/tutorial002_an_py39.py!}
+```
+
+////
+
+//// tab | Python 3.8+
+
+```Python hl_lines="32"
+{!> ../../../docs_src/security/tutorial002_an.py!}
+```
+
+////
+
+//// tab | Python 3.10+ non-Annotated
- ```Python hl_lines="31"
- {!> ../../../docs_src/security/tutorial002_an_py310.py!}
- ```
+/// tip
-=== "Python 3.9+"
+Prefer to use the `Annotated` version if possible.
- ```Python hl_lines="31"
- {!> ../../../docs_src/security/tutorial002_an_py39.py!}
- ```
+///
-=== "Python 3.8+"
+```Python hl_lines="29"
+{!> ../../../docs_src/security/tutorial002_py310.py!}
+```
- ```Python hl_lines="32"
- {!> ../../../docs_src/security/tutorial002_an.py!}
- ```
+////
-=== "Python 3.10+ non-Annotated"
+//// tab | Python 3.8+ non-Annotated
- !!! tip
- Prefer to use the `Annotated` version if possible.
+/// tip
- ```Python hl_lines="29"
- {!> ../../../docs_src/security/tutorial002_py310.py!}
- ```
+Prefer to use the `Annotated` version if possible.
-=== "Python 3.8+ non-Annotated"
+///
- !!! tip
- Prefer to use the `Annotated` version if possible.
+```Python hl_lines="31"
+{!> ../../../docs_src/security/tutorial002.py!}
+```
- ```Python hl_lines="31"
- {!> ../../../docs_src/security/tutorial002.py!}
- ```
+////
Notice that we declare the type of `current_user` as the Pydantic model `User`.
This will help us inside of the function with all the completion and type checks.
-!!! tip
- You might remember that request bodies are also declared with Pydantic models.
+/// tip
- Here **FastAPI** won't get confused because you are using `Depends`.
+You might remember that request bodies are also declared with Pydantic models.
-!!! check
- The way this dependency system is designed allows us to have different dependencies (different "dependables") that all return a `User` model.
+Here **FastAPI** won't get confused because you are using `Depends`.
- We are not restricted to having only one dependency that can return that type of data.
+///
+
+/// check
+
+The way this dependency system is designed allows us to have different dependencies (different "dependables") that all return a `User` model.
+
+We are not restricted to having only one dependency that can return that type of data.
+
+///
## Other models
And all these thousands of *path operations* can be as small as 3 lines:
-=== "Python 3.10+"
+//// tab | Python 3.10+
+
+```Python hl_lines="30-32"
+{!> ../../../docs_src/security/tutorial002_an_py310.py!}
+```
+
+////
+
+//// tab | Python 3.9+
+
+```Python hl_lines="30-32"
+{!> ../../../docs_src/security/tutorial002_an_py39.py!}
+```
+
+////
+
+//// tab | Python 3.8+
+
+```Python hl_lines="31-33"
+{!> ../../../docs_src/security/tutorial002_an.py!}
+```
+
+////
+
+//// tab | Python 3.10+ non-Annotated
- ```Python hl_lines="30-32"
- {!> ../../../docs_src/security/tutorial002_an_py310.py!}
- ```
+/// tip
-=== "Python 3.9+"
+Prefer to use the `Annotated` version if possible.
- ```Python hl_lines="30-32"
- {!> ../../../docs_src/security/tutorial002_an_py39.py!}
- ```
+///
-=== "Python 3.8+"
+```Python hl_lines="28-30"
+{!> ../../../docs_src/security/tutorial002_py310.py!}
+```
- ```Python hl_lines="31-33"
- {!> ../../../docs_src/security/tutorial002_an.py!}
- ```
+////
-=== "Python 3.10+ non-Annotated"
+//// tab | Python 3.8+ non-Annotated
- !!! tip
- Prefer to use the `Annotated` version if possible.
+/// tip
- ```Python hl_lines="28-30"
- {!> ../../../docs_src/security/tutorial002_py310.py!}
- ```
+Prefer to use the `Annotated` version if possible.
-=== "Python 3.8+ non-Annotated"
+///
- !!! tip
- Prefer to use the `Annotated` version if possible.
+```Python hl_lines="30-32"
+{!> ../../../docs_src/security/tutorial002.py!}
+```
- ```Python hl_lines="30-32"
- {!> ../../../docs_src/security/tutorial002.py!}
- ```
+////
## Recap
OAuth2 doesn't specify how to encrypt the communication, it expects you to have your application served with HTTPS.
-!!! tip
- In the section about **deployment** you will see how to set up HTTPS for free, using Traefik and Let's Encrypt.
+/// tip
+In the section about **deployment** you will see how to set up HTTPS for free, using Traefik and Let's Encrypt.
+
+///
## OpenID Connect
* This automatic discovery is what is defined in the OpenID Connect specification.
-!!! tip
- Integrating other authentication/authorization providers like Google, Facebook, Twitter, GitHub, etc. is also possible and relatively easy.
+/// tip
+
+Integrating other authentication/authorization providers like Google, Facebook, Twitter, GitHub, etc. is also possible and relatively easy.
+
+The most complex problem is building an authentication/authorization provider like those, but **FastAPI** gives you the tools to do it easily, while doing the heavy lifting for you.
- The most complex problem is building an authentication/authorization provider like those, but **FastAPI** gives you the tools to do it easily, while doing the heavy lifting for you.
+///
## **FastAPI** utilities
</div>
-!!! info
- If you are planning to use digital signature algorithms like RSA or ECDSA, you should install the cryptography library dependency `pyjwt[crypto]`.
+/// info
- You can read more about it in the <a href="https://pyjwt.readthedocs.io/en/latest/installation.html" class="external-link" target="_blank">PyJWT Installation docs</a>.
+If you are planning to use digital signature algorithms like RSA or ECDSA, you should install the cryptography library dependency `pyjwt[crypto]`.
+
+You can read more about it in the <a href="https://pyjwt.readthedocs.io/en/latest/installation.html" class="external-link" target="_blank">PyJWT Installation docs</a>.
+
+///
## Password hashing
</div>
-!!! tip
- With `passlib`, you could even configure it to be able to read passwords created by **Django**, a **Flask** security plug-in or many others.
+/// tip
+
+With `passlib`, you could even configure it to be able to read passwords created by **Django**, a **Flask** security plug-in or many others.
- So, you would be able to, for example, share the same data from a Django application in a database with a FastAPI application. Or gradually migrate a Django application using the same database.
+So, you would be able to, for example, share the same data from a Django application in a database with a FastAPI application. Or gradually migrate a Django application using the same database.
- And your users would be able to login from your Django app or from your **FastAPI** app, at the same time.
+And your users would be able to login from your Django app or from your **FastAPI** app, at the same time.
+
+///
## Hash and verify the passwords
Create a PassLib "context". This is what will be used to hash and verify passwords.
-!!! tip
- The PassLib context also has functionality to use different hashing algorithms, including deprecated old ones only to allow verifying them, etc.
+/// tip
+
+The PassLib context also has functionality to use different hashing algorithms, including deprecated old ones only to allow verifying them, etc.
- For example, you could use it to read and verify passwords generated by another system (like Django) but hash any new passwords with a different algorithm like Bcrypt.
+For example, you could use it to read and verify passwords generated by another system (like Django) but hash any new passwords with a different algorithm like Bcrypt.
- And be compatible with all of them at the same time.
+And be compatible with all of them at the same time.
+
+///
Create a utility function to hash a password coming from the user.
And another one to authenticate and return a user.
-=== "Python 3.10+"
+//// tab | Python 3.10+
+
+```Python hl_lines="8 49 56-57 60-61 70-76"
+{!> ../../../docs_src/security/tutorial004_an_py310.py!}
+```
+
+////
+
+//// tab | Python 3.9+
+
+```Python hl_lines="8 49 56-57 60-61 70-76"
+{!> ../../../docs_src/security/tutorial004_an_py39.py!}
+```
+
+////
+
+//// tab | Python 3.8+
+
+```Python hl_lines="8 50 57-58 61-62 71-77"
+{!> ../../../docs_src/security/tutorial004_an.py!}
+```
+
+////
- ```Python hl_lines="8 49 56-57 60-61 70-76"
- {!> ../../../docs_src/security/tutorial004_an_py310.py!}
- ```
+//// tab | Python 3.10+ non-Annotated
-=== "Python 3.9+"
+/// tip
- ```Python hl_lines="8 49 56-57 60-61 70-76"
- {!> ../../../docs_src/security/tutorial004_an_py39.py!}
- ```
+Prefer to use the `Annotated` version if possible.
-=== "Python 3.8+"
+///
- ```Python hl_lines="8 50 57-58 61-62 71-77"
- {!> ../../../docs_src/security/tutorial004_an.py!}
- ```
+```Python hl_lines="7 48 55-56 59-60 69-75"
+{!> ../../../docs_src/security/tutorial004_py310.py!}
+```
+
+////
+
+//// tab | Python 3.8+ non-Annotated
-=== "Python 3.10+ non-Annotated"
+/// tip
- !!! tip
- Prefer to use the `Annotated` version if possible.
+Prefer to use the `Annotated` version if possible.
- ```Python hl_lines="7 48 55-56 59-60 69-75"
- {!> ../../../docs_src/security/tutorial004_py310.py!}
- ```
+///
+
+```Python hl_lines="8 49 56-57 60-61 70-76"
+{!> ../../../docs_src/security/tutorial004.py!}
+```
-=== "Python 3.8+ non-Annotated"
+////
- !!! tip
- Prefer to use the `Annotated` version if possible.
+/// note
- ```Python hl_lines="8 49 56-57 60-61 70-76"
- {!> ../../../docs_src/security/tutorial004.py!}
- ```
+If you check the new (fake) database `fake_users_db`, you will see how the hashed password looks like now: `"$2b$12$EixZaYVK1fsbw1ZfbX3OXePaWxn96p36WQoeG6Lruj3vjPGga31lW"`.
-!!! note
- If you check the new (fake) database `fake_users_db`, you will see how the hashed password looks like now: `"$2b$12$EixZaYVK1fsbw1ZfbX3OXePaWxn96p36WQoeG6Lruj3vjPGga31lW"`.
+///
## Handle JWT tokens
Create a utility function to generate a new access token.
-=== "Python 3.10+"
+//// tab | Python 3.10+
+
+```Python hl_lines="4 7 13-15 29-31 79-87"
+{!> ../../../docs_src/security/tutorial004_an_py310.py!}
+```
+
+////
+
+//// tab | Python 3.9+
+
+```Python hl_lines="4 7 13-15 29-31 79-87"
+{!> ../../../docs_src/security/tutorial004_an_py39.py!}
+```
+
+////
+
+//// tab | Python 3.8+
+
+```Python hl_lines="4 7 14-16 30-32 80-88"
+{!> ../../../docs_src/security/tutorial004_an.py!}
+```
+
+////
+
+//// tab | Python 3.10+ non-Annotated
- ```Python hl_lines="4 7 13-15 29-31 79-87"
- {!> ../../../docs_src/security/tutorial004_an_py310.py!}
- ```
+/// tip
-=== "Python 3.9+"
+Prefer to use the `Annotated` version if possible.
- ```Python hl_lines="4 7 13-15 29-31 79-87"
- {!> ../../../docs_src/security/tutorial004_an_py39.py!}
- ```
+///
-=== "Python 3.8+"
+```Python hl_lines="3 6 12-14 28-30 78-86"
+{!> ../../../docs_src/security/tutorial004_py310.py!}
+```
- ```Python hl_lines="4 7 14-16 30-32 80-88"
- {!> ../../../docs_src/security/tutorial004_an.py!}
- ```
+////
-=== "Python 3.10+ non-Annotated"
+//// tab | Python 3.8+ non-Annotated
- !!! tip
- Prefer to use the `Annotated` version if possible.
+/// tip
- ```Python hl_lines="3 6 12-14 28-30 78-86"
- {!> ../../../docs_src/security/tutorial004_py310.py!}
- ```
+Prefer to use the `Annotated` version if possible.
-=== "Python 3.8+ non-Annotated"
+///
- !!! tip
- Prefer to use the `Annotated` version if possible.
+```Python hl_lines="4 7 13-15 29-31 79-87"
+{!> ../../../docs_src/security/tutorial004.py!}
+```
- ```Python hl_lines="4 7 13-15 29-31 79-87"
- {!> ../../../docs_src/security/tutorial004.py!}
- ```
+////
## Update the dependencies
If the token is invalid, return an HTTP error right away.
-=== "Python 3.10+"
+//// tab | Python 3.10+
- ```Python hl_lines="90-107"
- {!> ../../../docs_src/security/tutorial004_an_py310.py!}
- ```
+```Python hl_lines="90-107"
+{!> ../../../docs_src/security/tutorial004_an_py310.py!}
+```
-=== "Python 3.9+"
+////
- ```Python hl_lines="90-107"
- {!> ../../../docs_src/security/tutorial004_an_py39.py!}
- ```
+//// tab | Python 3.9+
-=== "Python 3.8+"
+```Python hl_lines="90-107"
+{!> ../../../docs_src/security/tutorial004_an_py39.py!}
+```
- ```Python hl_lines="91-108"
- {!> ../../../docs_src/security/tutorial004_an.py!}
- ```
+////
-=== "Python 3.10+ non-Annotated"
+//// tab | Python 3.8+
- !!! tip
- Prefer to use the `Annotated` version if possible.
+```Python hl_lines="91-108"
+{!> ../../../docs_src/security/tutorial004_an.py!}
+```
- ```Python hl_lines="89-106"
- {!> ../../../docs_src/security/tutorial004_py310.py!}
- ```
+////
-=== "Python 3.8+ non-Annotated"
+//// tab | Python 3.10+ non-Annotated
- !!! tip
- Prefer to use the `Annotated` version if possible.
+/// tip
+
+Prefer to use the `Annotated` version if possible.
+
+///
+
+```Python hl_lines="89-106"
+{!> ../../../docs_src/security/tutorial004_py310.py!}
+```
- ```Python hl_lines="90-107"
- {!> ../../../docs_src/security/tutorial004.py!}
- ```
+////
+
+//// tab | Python 3.8+ non-Annotated
+
+/// tip
+
+Prefer to use the `Annotated` version if possible.
+
+///
+
+```Python hl_lines="90-107"
+{!> ../../../docs_src/security/tutorial004.py!}
+```
+
+////
## Update the `/token` *path operation*
Create a real JWT access token and return it.
-=== "Python 3.10+"
+//// tab | Python 3.10+
+
+```Python hl_lines="118-133"
+{!> ../../../docs_src/security/tutorial004_an_py310.py!}
+```
+
+////
- ```Python hl_lines="118-133"
- {!> ../../../docs_src/security/tutorial004_an_py310.py!}
- ```
+//// tab | Python 3.9+
-=== "Python 3.9+"
+```Python hl_lines="118-133"
+{!> ../../../docs_src/security/tutorial004_an_py39.py!}
+```
- ```Python hl_lines="118-133"
- {!> ../../../docs_src/security/tutorial004_an_py39.py!}
- ```
+////
-=== "Python 3.8+"
+//// tab | Python 3.8+
+
+```Python hl_lines="119-134"
+{!> ../../../docs_src/security/tutorial004_an.py!}
+```
- ```Python hl_lines="119-134"
- {!> ../../../docs_src/security/tutorial004_an.py!}
- ```
+////
-=== "Python 3.10+ non-Annotated"
+//// tab | Python 3.10+ non-Annotated
- !!! tip
- Prefer to use the `Annotated` version if possible.
+/// tip
+
+Prefer to use the `Annotated` version if possible.
+
+///
+
+```Python hl_lines="115-130"
+{!> ../../../docs_src/security/tutorial004_py310.py!}
+```
- ```Python hl_lines="115-130"
- {!> ../../../docs_src/security/tutorial004_py310.py!}
- ```
+////
-=== "Python 3.8+ non-Annotated"
+//// tab | Python 3.8+ non-Annotated
- !!! tip
- Prefer to use the `Annotated` version if possible.
+/// tip
- ```Python hl_lines="116-131"
- {!> ../../../docs_src/security/tutorial004.py!}
- ```
+Prefer to use the `Annotated` version if possible.
+
+///
+
+```Python hl_lines="116-131"
+{!> ../../../docs_src/security/tutorial004.py!}
+```
+
+////
### Technical details about the JWT "subject" `sub`
Username: `johndoe`
Password: `secret`
-!!! check
- Notice that nowhere in the code is the plaintext password "`secret`", we only have the hashed version.
+/// check
+
+Notice that nowhere in the code is the plaintext password "`secret`", we only have the hashed version.
+
+///
<img src="/img/tutorial/security/image08.png">
<img src="/img/tutorial/security/image10.png">
-!!! note
- Notice the header `Authorization`, with a value that starts with `Bearer `.
+/// note
+
+Notice the header `Authorization`, with a value that starts with `Bearer `.
+
+///
## Advanced usage with `scopes`
* `instagram_basic` is used by Facebook / Instagram.
* `https://www.googleapis.com/auth/drive` is used by Google.
-!!! info
- In OAuth2 a "scope" is just a string that declares a specific permission required.
+/// info
- It doesn't matter if it has other characters like `:` or if it is a URL.
+In OAuth2 a "scope" is just a string that declares a specific permission required.
- Those details are implementation specific.
+It doesn't matter if it has other characters like `:` or if it is a URL.
- For OAuth2 they are just strings.
+Those details are implementation specific.
+
+For OAuth2 they are just strings.
+
+///
## Code to get the `username` and `password`
First, import `OAuth2PasswordRequestForm`, and use it as a dependency with `Depends` in the *path operation* for `/token`:
-=== "Python 3.10+"
+//// tab | Python 3.10+
+
+```Python hl_lines="4 78"
+{!> ../../../docs_src/security/tutorial003_an_py310.py!}
+```
+
+////
+
+//// tab | Python 3.9+
+
+```Python hl_lines="4 78"
+{!> ../../../docs_src/security/tutorial003_an_py39.py!}
+```
+
+////
+
+//// tab | Python 3.8+
+
+```Python hl_lines="4 79"
+{!> ../../../docs_src/security/tutorial003_an.py!}
+```
+
+////
+
+//// tab | Python 3.10+ non-Annotated
- ```Python hl_lines="4 78"
- {!> ../../../docs_src/security/tutorial003_an_py310.py!}
- ```
+/// tip
-=== "Python 3.9+"
+Prefer to use the `Annotated` version if possible.
- ```Python hl_lines="4 78"
- {!> ../../../docs_src/security/tutorial003_an_py39.py!}
- ```
+///
-=== "Python 3.8+"
+```Python hl_lines="2 74"
+{!> ../../../docs_src/security/tutorial003_py310.py!}
+```
- ```Python hl_lines="4 79"
- {!> ../../../docs_src/security/tutorial003_an.py!}
- ```
+////
-=== "Python 3.10+ non-Annotated"
+//// tab | Python 3.8+ non-Annotated
- !!! tip
- Prefer to use the `Annotated` version if possible.
+/// tip
- ```Python hl_lines="2 74"
- {!> ../../../docs_src/security/tutorial003_py310.py!}
- ```
+Prefer to use the `Annotated` version if possible.
-=== "Python 3.8+ non-Annotated"
+///
- !!! tip
- Prefer to use the `Annotated` version if possible.
+```Python hl_lines="4 76"
+{!> ../../../docs_src/security/tutorial003.py!}
+```
- ```Python hl_lines="4 76"
- {!> ../../../docs_src/security/tutorial003.py!}
- ```
+////
`OAuth2PasswordRequestForm` is a class dependency that declares a form body with:
* An optional `scope` field as a big string, composed of strings separated by spaces.
* An optional `grant_type`.
-!!! tip
- The OAuth2 spec actually *requires* a field `grant_type` with a fixed value of `password`, but `OAuth2PasswordRequestForm` doesn't enforce it.
+/// tip
+
+The OAuth2 spec actually *requires* a field `grant_type` with a fixed value of `password`, but `OAuth2PasswordRequestForm` doesn't enforce it.
- If you need to enforce it, use `OAuth2PasswordRequestFormStrict` instead of `OAuth2PasswordRequestForm`.
+If you need to enforce it, use `OAuth2PasswordRequestFormStrict` instead of `OAuth2PasswordRequestForm`.
+
+///
* An optional `client_id` (we don't need it for our example).
* An optional `client_secret` (we don't need it for our example).
-!!! info
- The `OAuth2PasswordRequestForm` is not a special class for **FastAPI** as is `OAuth2PasswordBearer`.
+/// info
+
+The `OAuth2PasswordRequestForm` is not a special class for **FastAPI** as is `OAuth2PasswordBearer`.
+
+`OAuth2PasswordBearer` makes **FastAPI** know that it is a security scheme. So it is added that way to OpenAPI.
- `OAuth2PasswordBearer` makes **FastAPI** know that it is a security scheme. So it is added that way to OpenAPI.
+But `OAuth2PasswordRequestForm` is just a class dependency that you could have written yourself, or you could have declared `Form` parameters directly.
- But `OAuth2PasswordRequestForm` is just a class dependency that you could have written yourself, or you could have declared `Form` parameters directly.
+But as it's a common use case, it is provided by **FastAPI** directly, just to make it easier.
- But as it's a common use case, it is provided by **FastAPI** directly, just to make it easier.
+///
### Use the form data
-!!! tip
- The instance of the dependency class `OAuth2PasswordRequestForm` won't have an attribute `scope` with the long string separated by spaces, instead, it will have a `scopes` attribute with the actual list of strings for each scope sent.
+/// tip
+
+The instance of the dependency class `OAuth2PasswordRequestForm` won't have an attribute `scope` with the long string separated by spaces, instead, it will have a `scopes` attribute with the actual list of strings for each scope sent.
+
+We are not using `scopes` in this example, but the functionality is there if you need it.
- We are not using `scopes` in this example, but the functionality is there if you need it.
+///
Now, get the user data from the (fake) database, using the `username` from the form field.
For the error, we use the exception `HTTPException`:
-=== "Python 3.10+"
+//// tab | Python 3.10+
- ```Python hl_lines="3 79-81"
- {!> ../../../docs_src/security/tutorial003_an_py310.py!}
- ```
+```Python hl_lines="3 79-81"
+{!> ../../../docs_src/security/tutorial003_an_py310.py!}
+```
+
+////
+
+//// tab | Python 3.9+
-=== "Python 3.9+"
+```Python hl_lines="3 79-81"
+{!> ../../../docs_src/security/tutorial003_an_py39.py!}
+```
+
+////
- ```Python hl_lines="3 79-81"
- {!> ../../../docs_src/security/tutorial003_an_py39.py!}
- ```
+//// tab | Python 3.8+
-=== "Python 3.8+"
+```Python hl_lines="3 80-82"
+{!> ../../../docs_src/security/tutorial003_an.py!}
+```
- ```Python hl_lines="3 80-82"
- {!> ../../../docs_src/security/tutorial003_an.py!}
- ```
+////
-=== "Python 3.10+ non-Annotated"
+//// tab | Python 3.10+ non-Annotated
+
+/// tip
+
+Prefer to use the `Annotated` version if possible.
+
+///
+
+```Python hl_lines="1 75-77"
+{!> ../../../docs_src/security/tutorial003_py310.py!}
+```
- !!! tip
- Prefer to use the `Annotated` version if possible.
+////
- ```Python hl_lines="1 75-77"
- {!> ../../../docs_src/security/tutorial003_py310.py!}
- ```
+//// tab | Python 3.8+ non-Annotated
-=== "Python 3.8+ non-Annotated"
+/// tip
- !!! tip
- Prefer to use the `Annotated` version if possible.
+Prefer to use the `Annotated` version if possible.
- ```Python hl_lines="3 77-79"
- {!> ../../../docs_src/security/tutorial003.py!}
- ```
+///
+
+```Python hl_lines="3 77-79"
+{!> ../../../docs_src/security/tutorial003.py!}
+```
+
+////
### Check the password
So, the thief won't be able to try to use those same passwords in another system (as many users use the same password everywhere, this would be dangerous).
-=== "Python 3.10+"
+//// tab | Python 3.10+
+
+```Python hl_lines="82-85"
+{!> ../../../docs_src/security/tutorial003_an_py310.py!}
+```
+
+////
+
+//// tab | Python 3.9+
+
+```Python hl_lines="82-85"
+{!> ../../../docs_src/security/tutorial003_an_py39.py!}
+```
+
+////
- ```Python hl_lines="82-85"
- {!> ../../../docs_src/security/tutorial003_an_py310.py!}
- ```
+//// tab | Python 3.8+
-=== "Python 3.9+"
+```Python hl_lines="83-86"
+{!> ../../../docs_src/security/tutorial003_an.py!}
+```
+
+////
+
+//// tab | Python 3.10+ non-Annotated
- ```Python hl_lines="82-85"
- {!> ../../../docs_src/security/tutorial003_an_py39.py!}
- ```
+/// tip
-=== "Python 3.8+"
+Prefer to use the `Annotated` version if possible.
- ```Python hl_lines="83-86"
- {!> ../../../docs_src/security/tutorial003_an.py!}
- ```
+///
-=== "Python 3.10+ non-Annotated"
+```Python hl_lines="78-81"
+{!> ../../../docs_src/security/tutorial003_py310.py!}
+```
+
+////
- !!! tip
- Prefer to use the `Annotated` version if possible.
+//// tab | Python 3.8+ non-Annotated
- ```Python hl_lines="78-81"
- {!> ../../../docs_src/security/tutorial003_py310.py!}
- ```
+/// tip
-=== "Python 3.8+ non-Annotated"
+Prefer to use the `Annotated` version if possible.
- !!! tip
- Prefer to use the `Annotated` version if possible.
+///
- ```Python hl_lines="80-83"
- {!> ../../../docs_src/security/tutorial003.py!}
- ```
+```Python hl_lines="80-83"
+{!> ../../../docs_src/security/tutorial003.py!}
+```
+
+////
#### About `**user_dict`
)
```
-!!! info
- For a more complete explanation of `**user_dict` check back in [the documentation for **Extra Models**](../extra-models.md#about-user_indict){.internal-link target=_blank}.
+/// info
+
+For a more complete explanation of `**user_dict` check back in [the documentation for **Extra Models**](../extra-models.md#about-user_indict){.internal-link target=_blank}.
+
+///
## Return the token
For this simple example, we are going to just be completely insecure and return the same `username` as the token.
-!!! tip
- In the next chapter, you will see a real secure implementation, with password hashing and <abbr title="JSON Web Tokens">JWT</abbr> tokens.
+/// tip
+
+In the next chapter, you will see a real secure implementation, with password hashing and <abbr title="JSON Web Tokens">JWT</abbr> tokens.
+
+But for now, let's focus on the specific details we need.
- But for now, let's focus on the specific details we need.
+///
-=== "Python 3.10+"
+//// tab | Python 3.10+
- ```Python hl_lines="87"
- {!> ../../../docs_src/security/tutorial003_an_py310.py!}
- ```
+```Python hl_lines="87"
+{!> ../../../docs_src/security/tutorial003_an_py310.py!}
+```
+
+////
+
+//// tab | Python 3.9+
-=== "Python 3.9+"
+```Python hl_lines="87"
+{!> ../../../docs_src/security/tutorial003_an_py39.py!}
+```
- ```Python hl_lines="87"
- {!> ../../../docs_src/security/tutorial003_an_py39.py!}
- ```
+////
-=== "Python 3.8+"
+//// tab | Python 3.8+
- ```Python hl_lines="88"
- {!> ../../../docs_src/security/tutorial003_an.py!}
- ```
+```Python hl_lines="88"
+{!> ../../../docs_src/security/tutorial003_an.py!}
+```
-=== "Python 3.10+ non-Annotated"
+////
- !!! tip
- Prefer to use the `Annotated` version if possible.
+//// tab | Python 3.10+ non-Annotated
- ```Python hl_lines="83"
- {!> ../../../docs_src/security/tutorial003_py310.py!}
- ```
+/// tip
-=== "Python 3.8+ non-Annotated"
+Prefer to use the `Annotated` version if possible.
- !!! tip
- Prefer to use the `Annotated` version if possible.
+///
- ```Python hl_lines="85"
- {!> ../../../docs_src/security/tutorial003.py!}
- ```
+```Python hl_lines="83"
+{!> ../../../docs_src/security/tutorial003_py310.py!}
+```
-!!! tip
- By the spec, you should return a JSON with an `access_token` and a `token_type`, the same as in this example.
+////
- This is something that you have to do yourself in your code, and make sure you use those JSON keys.
+//// tab | Python 3.8+ non-Annotated
+
+/// tip
+
+Prefer to use the `Annotated` version if possible.
+
+///
+
+```Python hl_lines="85"
+{!> ../../../docs_src/security/tutorial003.py!}
+```
- It's almost the only thing that you have to remember to do correctly yourself, to be compliant with the specifications.
+////
- For the rest, **FastAPI** handles it for you.
+/// tip
+
+By the spec, you should return a JSON with an `access_token` and a `token_type`, the same as in this example.
+
+This is something that you have to do yourself in your code, and make sure you use those JSON keys.
+
+It's almost the only thing that you have to remember to do correctly yourself, to be compliant with the specifications.
+
+For the rest, **FastAPI** handles it for you.
+
+///
## Update the dependencies
So, in our endpoint, we will only get a user if the user exists, was correctly authenticated, and is active:
-=== "Python 3.10+"
+//// tab | Python 3.10+
- ```Python hl_lines="58-66 69-74 94"
- {!> ../../../docs_src/security/tutorial003_an_py310.py!}
- ```
+```Python hl_lines="58-66 69-74 94"
+{!> ../../../docs_src/security/tutorial003_an_py310.py!}
+```
-=== "Python 3.9+"
+////
- ```Python hl_lines="58-66 69-74 94"
- {!> ../../../docs_src/security/tutorial003_an_py39.py!}
- ```
+//// tab | Python 3.9+
-=== "Python 3.8+"
+```Python hl_lines="58-66 69-74 94"
+{!> ../../../docs_src/security/tutorial003_an_py39.py!}
+```
+
+////
+
+//// tab | Python 3.8+
+
+```Python hl_lines="59-67 70-75 95"
+{!> ../../../docs_src/security/tutorial003_an.py!}
+```
- ```Python hl_lines="59-67 70-75 95"
- {!> ../../../docs_src/security/tutorial003_an.py!}
- ```
+////
-=== "Python 3.10+ non-Annotated"
+//// tab | Python 3.10+ non-Annotated
- !!! tip
- Prefer to use the `Annotated` version if possible.
+/// tip
- ```Python hl_lines="56-64 67-70 88"
- {!> ../../../docs_src/security/tutorial003_py310.py!}
- ```
+Prefer to use the `Annotated` version if possible.
+
+///
+
+```Python hl_lines="56-64 67-70 88"
+{!> ../../../docs_src/security/tutorial003_py310.py!}
+```
+
+////
+
+//// tab | Python 3.8+ non-Annotated
+
+/// tip
+
+Prefer to use the `Annotated` version if possible.
+
+///
+
+```Python hl_lines="58-66 69-72 90"
+{!> ../../../docs_src/security/tutorial003.py!}
+```
-=== "Python 3.8+ non-Annotated"
+////
- !!! tip
- Prefer to use the `Annotated` version if possible.
+/// info
- ```Python hl_lines="58-66 69-72 90"
- {!> ../../../docs_src/security/tutorial003.py!}
- ```
+The additional header `WWW-Authenticate` with value `Bearer` we are returning here is also part of the spec.
-!!! info
- The additional header `WWW-Authenticate` with value `Bearer` we are returning here is also part of the spec.
+Any HTTP (error) status code 401 "UNAUTHORIZED" is supposed to also return a `WWW-Authenticate` header.
- Any HTTP (error) status code 401 "UNAUTHORIZED" is supposed to also return a `WWW-Authenticate` header.
+In the case of bearer tokens (our case), the value of that header should be `Bearer`.
- In the case of bearer tokens (our case), the value of that header should be `Bearer`.
+You can actually skip that extra header and it would still work.
- You can actually skip that extra header and it would still work.
+But it's provided here to be compliant with the specifications.
- But it's provided here to be compliant with the specifications.
+Also, there might be tools that expect and use it (now or in the future) and that might be useful for you or your users, now or in the future.
- Also, there might be tools that expect and use it (now or in the future) and that might be useful for you or your users, now or in the future.
+That's the benefit of standards...
- That's the benefit of standards...
+///
## See it in action
# SQL (Relational) Databases
-!!! info
- These docs are about to be updated. 🎉
+/// info
- The current version assumes Pydantic v1, and SQLAlchemy versions less than 2.0.
+These docs are about to be updated. 🎉
- The new docs will include Pydantic v2 and will use <a href="https://sqlmodel.tiangolo.com/" class="external-link" target="_blank">SQLModel</a> (which is also based on SQLAlchemy) once it is updated to use Pydantic v2 as well.
+The current version assumes Pydantic v1, and SQLAlchemy versions less than 2.0.
+
+The new docs will include Pydantic v2 and will use <a href="https://sqlmodel.tiangolo.com/" class="external-link" target="_blank">SQLModel</a> (which is also based on SQLAlchemy) once it is updated to use Pydantic v2 as well.
+
+///
**FastAPI** doesn't require you to use a SQL (relational) database.
Later, for your production application, you might want to use a database server like **PostgreSQL**.
-!!! tip
- There is an official project generator with **FastAPI** and **PostgreSQL**, all based on **Docker**, including a frontend and more tools: <a href="https://github.com/tiangolo/full-stack-fastapi-postgresql" class="external-link" target="_blank">https://github.com/tiangolo/full-stack-fastapi-postgresql</a>
+/// tip
+
+There is an official project generator with **FastAPI** and **PostgreSQL**, all based on **Docker**, including a frontend and more tools: <a href="https://github.com/tiangolo/full-stack-fastapi-postgresql" class="external-link" target="_blank">https://github.com/tiangolo/full-stack-fastapi-postgresql</a>
+
+///
-!!! note
- Notice that most of the code is the standard `SQLAlchemy` code you would use with any framework.
+/// note
- The **FastAPI** specific code is as small as always.
+Notice that most of the code is the standard `SQLAlchemy` code you would use with any framework.
+
+The **FastAPI** specific code is as small as always.
+
+///
## ORMs
In a similar way you could use any other ORM.
-!!! tip
- There's an equivalent article using Peewee here in the docs.
+/// tip
+
+There's an equivalent article using Peewee here in the docs.
+
+///
## File structure
...and adapt it with your database data and credentials (equivalently for MySQL, MariaDB or any other).
-!!! tip
+/// tip
+
+This is the main line that you would have to modify if you wanted to use a different database.
- This is the main line that you would have to modify if you wanted to use a different database.
+///
### Create the SQLAlchemy `engine`
...is needed only for `SQLite`. It's not needed for other databases.
-!!! info "Technical Details"
+/// info | "Technical Details"
+
+By default SQLite will only allow one thread to communicate with it, assuming that each thread would handle an independent request.
- By default SQLite will only allow one thread to communicate with it, assuming that each thread would handle an independent request.
+This is to prevent accidentally sharing the same connection for different things (for different requests).
- This is to prevent accidentally sharing the same connection for different things (for different requests).
+But in FastAPI, using normal functions (`def`) more than one thread could interact with the database for the same request, so we need to make SQLite know that it should allow that with `connect_args={"check_same_thread": False}`.
- But in FastAPI, using normal functions (`def`) more than one thread could interact with the database for the same request, so we need to make SQLite know that it should allow that with `connect_args={"check_same_thread": False}`.
+Also, we will make sure each request gets its own database connection session in a dependency, so there's no need for that default mechanism.
- Also, we will make sure each request gets its own database connection session in a dependency, so there's no need for that default mechanism.
+///
### Create a `SessionLocal` class
We will use this `Base` class we created before to create the SQLAlchemy models.
-!!! tip
- SQLAlchemy uses the term "**model**" to refer to these classes and instances that interact with the database.
+/// tip
- But Pydantic also uses the term "**model**" to refer to something different, the data validation, conversion, and documentation classes and instances.
+SQLAlchemy uses the term "**model**" to refer to these classes and instances that interact with the database.
+
+But Pydantic also uses the term "**model**" to refer to something different, the data validation, conversion, and documentation classes and instances.
+
+///
Import `Base` from `database` (the file `database.py` from above).
Now let's check the file `sql_app/schemas.py`.
-!!! tip
- To avoid confusion between the SQLAlchemy *models* and the Pydantic *models*, we will have the file `models.py` with the SQLAlchemy models, and the file `schemas.py` with the Pydantic models.
+/// tip
+
+To avoid confusion between the SQLAlchemy *models* and the Pydantic *models*, we will have the file `models.py` with the SQLAlchemy models, and the file `schemas.py` with the Pydantic models.
- These Pydantic models define more or less a "schema" (a valid data shape).
+These Pydantic models define more or less a "schema" (a valid data shape).
- So this will help us avoiding confusion while using both.
+So this will help us avoiding confusion while using both.
+
+///
### Create initial Pydantic *models* / schemas
But for security, the `password` won't be in other Pydantic *models*, for example, it won't be sent from the API when reading a user.
-=== "Python 3.10+"
+//// tab | Python 3.10+
+
+```Python hl_lines="1 4-6 9-10 21-22 25-26"
+{!> ../../../docs_src/sql_databases/sql_app_py310/schemas.py!}
+```
+
+////
+
+//// tab | Python 3.9+
- ```Python hl_lines="1 4-6 9-10 21-22 25-26"
- {!> ../../../docs_src/sql_databases/sql_app_py310/schemas.py!}
- ```
+```Python hl_lines="3 6-8 11-12 23-24 27-28"
+{!> ../../../docs_src/sql_databases/sql_app_py39/schemas.py!}
+```
-=== "Python 3.9+"
+////
- ```Python hl_lines="3 6-8 11-12 23-24 27-28"
- {!> ../../../docs_src/sql_databases/sql_app_py39/schemas.py!}
- ```
+//// tab | Python 3.8+
-=== "Python 3.8+"
+```Python hl_lines="3 6-8 11-12 23-24 27-28"
+{!> ../../../docs_src/sql_databases/sql_app/schemas.py!}
+```
- ```Python hl_lines="3 6-8 11-12 23-24 27-28"
- {!> ../../../docs_src/sql_databases/sql_app/schemas.py!}
- ```
+////
#### SQLAlchemy style and Pydantic style
Not only the IDs of those items, but all the data that we defined in the Pydantic *model* for reading items: `Item`.
-=== "Python 3.10+"
+//// tab | Python 3.10+
+
+```Python hl_lines="13-15 29-32"
+{!> ../../../docs_src/sql_databases/sql_app_py310/schemas.py!}
+```
+
+////
+
+//// tab | Python 3.9+
+
+```Python hl_lines="15-17 31-34"
+{!> ../../../docs_src/sql_databases/sql_app_py39/schemas.py!}
+```
+
+////
- ```Python hl_lines="13-15 29-32"
- {!> ../../../docs_src/sql_databases/sql_app_py310/schemas.py!}
- ```
+//// tab | Python 3.8+
-=== "Python 3.9+"
+```Python hl_lines="15-17 31-34"
+{!> ../../../docs_src/sql_databases/sql_app/schemas.py!}
+```
- ```Python hl_lines="15-17 31-34"
- {!> ../../../docs_src/sql_databases/sql_app_py39/schemas.py!}
- ```
+////
-=== "Python 3.8+"
+/// tip
- ```Python hl_lines="15-17 31-34"
- {!> ../../../docs_src/sql_databases/sql_app/schemas.py!}
- ```
+Notice that the `User`, the Pydantic *model* that will be used when reading a user (returning it from the API) doesn't include the `password`.
-!!! tip
- Notice that the `User`, the Pydantic *model* that will be used when reading a user (returning it from the API) doesn't include the `password`.
+///
### Use Pydantic's `orm_mode`
In the `Config` class, set the attribute `orm_mode = True`.
-=== "Python 3.10+"
+//// tab | Python 3.10+
- ```Python hl_lines="13 17-18 29 34-35"
- {!> ../../../docs_src/sql_databases/sql_app_py310/schemas.py!}
- ```
+```Python hl_lines="13 17-18 29 34-35"
+{!> ../../../docs_src/sql_databases/sql_app_py310/schemas.py!}
+```
-=== "Python 3.9+"
+////
- ```Python hl_lines="15 19-20 31 36-37"
- {!> ../../../docs_src/sql_databases/sql_app_py39/schemas.py!}
- ```
+//// tab | Python 3.9+
-=== "Python 3.8+"
+```Python hl_lines="15 19-20 31 36-37"
+{!> ../../../docs_src/sql_databases/sql_app_py39/schemas.py!}
+```
+
+////
- ```Python hl_lines="15 19-20 31 36-37"
- {!> ../../../docs_src/sql_databases/sql_app/schemas.py!}
- ```
+//// tab | Python 3.8+
-!!! tip
- Notice it's assigning a value with `=`, like:
+```Python hl_lines="15 19-20 31 36-37"
+{!> ../../../docs_src/sql_databases/sql_app/schemas.py!}
+```
- `orm_mode = True`
+////
- It doesn't use `:` as for the type declarations before.
+/// tip
- This is setting a config value, not declaring a type.
+Notice it's assigning a value with `=`, like:
+
+`orm_mode = True`
+
+It doesn't use `:` as for the type declarations before.
+
+This is setting a config value, not declaring a type.
+
+///
Pydantic's `orm_mode` will tell the Pydantic *model* to read the data even if it is not a `dict`, but an ORM model (or any other arbitrary object with attributes).
{!../../../docs_src/sql_databases/sql_app/crud.py!}
```
-!!! tip
- By creating functions that are only dedicated to interacting with the database (get a user or an item) independent of your *path operation function*, you can more easily reuse them in multiple parts and also add <abbr title="Automated tests, written in code, that check if another piece of code is working correctly.">unit tests</abbr> for them.
+/// tip
+
+By creating functions that are only dedicated to interacting with the database (get a user or an item) independent of your *path operation function*, you can more easily reuse them in multiple parts and also add <abbr title="Automated tests, written in code, that check if another piece of code is working correctly.">unit tests</abbr> for them.
+
+///
### Create data
{!../../../docs_src/sql_databases/sql_app/crud.py!}
```
-!!! info
- In Pydantic v1 the method was called `.dict()`, it was deprecated (but still supported) in Pydantic v2, and renamed to `.model_dump()`.
+/// info
- The examples here use `.dict()` for compatibility with Pydantic v1, but you should use `.model_dump()` instead if you can use Pydantic v2.
+In Pydantic v1 the method was called `.dict()`, it was deprecated (but still supported) in Pydantic v2, and renamed to `.model_dump()`.
-!!! tip
- The SQLAlchemy model for `User` contains a `hashed_password` that should contain a secure hashed version of the password.
+The examples here use `.dict()` for compatibility with Pydantic v1, but you should use `.model_dump()` instead if you can use Pydantic v2.
- But as what the API client provides is the original password, you need to extract it and generate the hashed password in your application.
+///
- And then pass the `hashed_password` argument with the value to save.
+/// tip
-!!! warning
- This example is not secure, the password is not hashed.
+The SQLAlchemy model for `User` contains a `hashed_password` that should contain a secure hashed version of the password.
- In a real life application you would need to hash the password and never save them in plaintext.
+But as what the API client provides is the original password, you need to extract it and generate the hashed password in your application.
- For more details, go back to the Security section in the tutorial.
+And then pass the `hashed_password` argument with the value to save.
- Here we are focusing only on the tools and mechanics of databases.
+///
-!!! tip
- Instead of passing each of the keyword arguments to `Item` and reading each one of them from the Pydantic *model*, we are generating a `dict` with the Pydantic *model*'s data with:
+/// warning
- `item.dict()`
+This example is not secure, the password is not hashed.
- and then we are passing the `dict`'s key-value pairs as the keyword arguments to the SQLAlchemy `Item`, with:
+In a real life application you would need to hash the password and never save them in plaintext.
- `Item(**item.dict())`
+For more details, go back to the Security section in the tutorial.
- And then we pass the extra keyword argument `owner_id` that is not provided by the Pydantic *model*, with:
+Here we are focusing only on the tools and mechanics of databases.
- `Item(**item.dict(), owner_id=user_id)`
+///
+
+/// tip
+
+Instead of passing each of the keyword arguments to `Item` and reading each one of them from the Pydantic *model*, we are generating a `dict` with the Pydantic *model*'s data with:
+
+`item.dict()`
+
+and then we are passing the `dict`'s key-value pairs as the keyword arguments to the SQLAlchemy `Item`, with:
+
+`Item(**item.dict())`
+
+And then we pass the extra keyword argument `owner_id` that is not provided by the Pydantic *model*, with:
+
+`Item(**item.dict(), owner_id=user_id)`
+
+///
## Main **FastAPI** app
In a very simplistic way create the database tables:
-=== "Python 3.9+"
+//// tab | Python 3.9+
+
+```Python hl_lines="7"
+{!> ../../../docs_src/sql_databases/sql_app_py39/main.py!}
+```
+
+////
- ```Python hl_lines="7"
- {!> ../../../docs_src/sql_databases/sql_app_py39/main.py!}
- ```
+//// tab | Python 3.8+
-=== "Python 3.8+"
+```Python hl_lines="9"
+{!> ../../../docs_src/sql_databases/sql_app/main.py!}
+```
- ```Python hl_lines="9"
- {!> ../../../docs_src/sql_databases/sql_app/main.py!}
- ```
+////
#### Alembic Note
Our dependency will create a new SQLAlchemy `SessionLocal` that will be used in a single request, and then close it once the request is finished.
-=== "Python 3.9+"
+//// tab | Python 3.9+
- ```Python hl_lines="13-18"
- {!> ../../../docs_src/sql_databases/sql_app_py39/main.py!}
- ```
+```Python hl_lines="13-18"
+{!> ../../../docs_src/sql_databases/sql_app_py39/main.py!}
+```
+
+////
-=== "Python 3.8+"
+//// tab | Python 3.8+
+
+```Python hl_lines="15-20"
+{!> ../../../docs_src/sql_databases/sql_app/main.py!}
+```
- ```Python hl_lines="15-20"
- {!> ../../../docs_src/sql_databases/sql_app/main.py!}
- ```
+////
-!!! info
- We put the creation of the `SessionLocal()` and handling of the requests in a `try` block.
+/// info
- And then we close it in the `finally` block.
+We put the creation of the `SessionLocal()` and handling of the requests in a `try` block.
- This way we make sure the database session is always closed after the request. Even if there was an exception while processing the request.
+And then we close it in the `finally` block.
- But you can't raise another exception from the exit code (after `yield`). See more in [Dependencies with `yield` and `HTTPException`](dependencies/dependencies-with-yield.md#dependencies-with-yield-and-httpexception){.internal-link target=_blank}
+This way we make sure the database session is always closed after the request. Even if there was an exception while processing the request.
+
+But you can't raise another exception from the exit code (after `yield`). See more in [Dependencies with `yield` and `HTTPException`](dependencies/dependencies-with-yield.md#dependencies-with-yield-and-httpexception){.internal-link target=_blank}
+
+///
And then, when using the dependency in a *path operation function*, we declare it with the type `Session` we imported directly from SQLAlchemy.
This will then give us better editor support inside the *path operation function*, because the editor will know that the `db` parameter is of type `Session`:
-=== "Python 3.9+"
+//// tab | Python 3.9+
- ```Python hl_lines="22 30 36 45 51"
- {!> ../../../docs_src/sql_databases/sql_app_py39/main.py!}
- ```
+```Python hl_lines="22 30 36 45 51"
+{!> ../../../docs_src/sql_databases/sql_app_py39/main.py!}
+```
-=== "Python 3.8+"
+////
- ```Python hl_lines="24 32 38 47 53"
- {!> ../../../docs_src/sql_databases/sql_app/main.py!}
- ```
+//// tab | Python 3.8+
-!!! info "Technical Details"
- The parameter `db` is actually of type `SessionLocal`, but this class (created with `sessionmaker()`) is a "proxy" of a SQLAlchemy `Session`, so, the editor doesn't really know what methods are provided.
+```Python hl_lines="24 32 38 47 53"
+{!> ../../../docs_src/sql_databases/sql_app/main.py!}
+```
+
+////
+
+/// info | "Technical Details"
- But by declaring the type as `Session`, the editor now can know the available methods (`.add()`, `.query()`, `.commit()`, etc) and can provide better support (like completion). The type declaration doesn't affect the actual object.
+The parameter `db` is actually of type `SessionLocal`, but this class (created with `sessionmaker()`) is a "proxy" of a SQLAlchemy `Session`, so, the editor doesn't really know what methods are provided.
+
+But by declaring the type as `Session`, the editor now can know the available methods (`.add()`, `.query()`, `.commit()`, etc) and can provide better support (like completion). The type declaration doesn't affect the actual object.
+
+///
### Create your **FastAPI** *path operations*
Now, finally, here's the standard **FastAPI** *path operations* code.
-=== "Python 3.9+"
+//// tab | Python 3.9+
- ```Python hl_lines="21-26 29-32 35-40 43-47 50-53"
- {!> ../../../docs_src/sql_databases/sql_app_py39/main.py!}
- ```
+```Python hl_lines="21-26 29-32 35-40 43-47 50-53"
+{!> ../../../docs_src/sql_databases/sql_app_py39/main.py!}
+```
-=== "Python 3.8+"
+////
- ```Python hl_lines="23-28 31-34 37-42 45-49 52-55"
- {!> ../../../docs_src/sql_databases/sql_app/main.py!}
- ```
+//// tab | Python 3.8+
+
+```Python hl_lines="23-28 31-34 37-42 45-49 52-55"
+{!> ../../../docs_src/sql_databases/sql_app/main.py!}
+```
+
+////
We are creating the database session before each request in the dependency with `yield`, and then closing it afterwards.
With that, we can just call `crud.get_user` directly from inside of the *path operation function* and use that session.
-!!! tip
- Notice that the values you return are SQLAlchemy models, or lists of SQLAlchemy models.
+/// tip
+
+Notice that the values you return are SQLAlchemy models, or lists of SQLAlchemy models.
+
+But as all the *path operations* have a `response_model` with Pydantic *models* / schemas using `orm_mode`, the data declared in your Pydantic models will be extracted from them and returned to the client, with all the normal filtering and validation.
+
+///
- But as all the *path operations* have a `response_model` with Pydantic *models* / schemas using `orm_mode`, the data declared in your Pydantic models will be extracted from them and returned to the client, with all the normal filtering and validation.
+/// tip
-!!! tip
- Also notice that there are `response_models` that have standard Python types like `List[schemas.Item]`.
+Also notice that there are `response_models` that have standard Python types like `List[schemas.Item]`.
- But as the content/parameter of that `List` is a Pydantic *model* with `orm_mode`, the data will be retrieved and returned to the client as normally, without problems.
+But as the content/parameter of that `List` is a Pydantic *model* with `orm_mode`, the data will be retrieved and returned to the client as normally, without problems.
+
+///
### About `def` vs `async def`
...
```
-!!! info
- If you need to connect to your relational database asynchronously, see [Async SQL (Relational) Databases](../how-to/async-sql-encode-databases.md){.internal-link target=_blank}.
+/// info
+
+If you need to connect to your relational database asynchronously, see [Async SQL (Relational) Databases](../how-to/async-sql-encode-databases.md){.internal-link target=_blank}.
+
+///
-!!! note "Very Technical Details"
- If you are curious and have a deep technical knowledge, you can check the very technical details of how this `async def` vs `def` is handled in the [Async](../async.md#very-technical-details){.internal-link target=_blank} docs.
+/// note | "Very Technical Details"
+
+If you are curious and have a deep technical knowledge, you can check the very technical details of how this `async def` vs `def` is handled in the [Async](../async.md#very-technical-details){.internal-link target=_blank} docs.
+
+///
## Migrations
* `sql_app/schemas.py`:
-=== "Python 3.10+"
+//// tab | Python 3.10+
+
+```Python
+{!> ../../../docs_src/sql_databases/sql_app_py310/schemas.py!}
+```
- ```Python
- {!> ../../../docs_src/sql_databases/sql_app_py310/schemas.py!}
- ```
+////
-=== "Python 3.9+"
+//// tab | Python 3.9+
- ```Python
- {!> ../../../docs_src/sql_databases/sql_app_py39/schemas.py!}
- ```
+```Python
+{!> ../../../docs_src/sql_databases/sql_app_py39/schemas.py!}
+```
-=== "Python 3.8+"
+////
- ```Python
- {!> ../../../docs_src/sql_databases/sql_app/schemas.py!}
- ```
+//// tab | Python 3.8+
+
+```Python
+{!> ../../../docs_src/sql_databases/sql_app/schemas.py!}
+```
+
+////
* `sql_app/crud.py`:
* `sql_app/main.py`:
-=== "Python 3.9+"
+//// tab | Python 3.9+
+
+```Python
+{!> ../../../docs_src/sql_databases/sql_app_py39/main.py!}
+```
- ```Python
- {!> ../../../docs_src/sql_databases/sql_app_py39/main.py!}
- ```
+////
-=== "Python 3.8+"
+//// tab | Python 3.8+
- ```Python
- {!> ../../../docs_src/sql_databases/sql_app/main.py!}
- ```
+```Python
+{!> ../../../docs_src/sql_databases/sql_app/main.py!}
+```
+
+////
## Check it
You can copy this code and use it as is.
-!!! info
+/// info
+
+In fact, the code shown here is part of the tests. As most of the code in these docs.
- In fact, the code shown here is part of the tests. As most of the code in these docs.
+///
Then you can run it with Uvicorn:
The middleware we'll add (just a function) will create a new SQLAlchemy `SessionLocal` for each request, add it to the request and then close it once the request is finished.
-=== "Python 3.9+"
+//// tab | Python 3.9+
+
+```Python hl_lines="12-20"
+{!> ../../../docs_src/sql_databases/sql_app_py39/alt_main.py!}
+```
+
+////
+
+//// tab | Python 3.8+
- ```Python hl_lines="12-20"
- {!> ../../../docs_src/sql_databases/sql_app_py39/alt_main.py!}
- ```
+```Python hl_lines="14-22"
+{!> ../../../docs_src/sql_databases/sql_app/alt_main.py!}
+```
+
+////
-=== "Python 3.8+"
+/// info
- ```Python hl_lines="14-22"
- {!> ../../../docs_src/sql_databases/sql_app/alt_main.py!}
- ```
+We put the creation of the `SessionLocal()` and handling of the requests in a `try` block.
-!!! info
- We put the creation of the `SessionLocal()` and handling of the requests in a `try` block.
+And then we close it in the `finally` block.
- And then we close it in the `finally` block.
+This way we make sure the database session is always closed after the request. Even if there was an exception while processing the request.
- This way we make sure the database session is always closed after the request. Even if there was an exception while processing the request.
+///
### About `request.state`
* So, a connection will be created for every request.
* Even when the *path operation* that handles that request didn't need the DB.
-!!! tip
- It's probably better to use dependencies with `yield` when they are enough for the use case.
+/// tip
+
+It's probably better to use dependencies with `yield` when they are enough for the use case.
+
+///
+
+/// info
+
+Dependencies with `yield` were added recently to **FastAPI**.
-!!! info
- Dependencies with `yield` were added recently to **FastAPI**.
+A previous version of this tutorial only had the examples with a middleware and there are probably several applications using the middleware for database session management.
- A previous version of this tutorial only had the examples with a middleware and there are probably several applications using the middleware for database session management.
+///
{!../../../docs_src/static_files/tutorial001.py!}
```
-!!! note "Technical Details"
- You could also use `from starlette.staticfiles import StaticFiles`.
+/// note | "Technical Details"
- **FastAPI** provides the same `starlette.staticfiles` as `fastapi.staticfiles` just as a convenience for you, the developer. But it actually comes directly from Starlette.
+You could also use `from starlette.staticfiles import StaticFiles`.
+
+**FastAPI** provides the same `starlette.staticfiles` as `fastapi.staticfiles` just as a convenience for you, the developer. But it actually comes directly from Starlette.
+
+///
### What is "Mounting"
## Using `TestClient`
-!!! info
- To use `TestClient`, first install <a href="https://www.python-httpx.org" class="external-link" target="_blank">`httpx`</a>.
+/// info
- E.g. `pip install httpx`.
+To use `TestClient`, first install <a href="https://www.python-httpx.org" class="external-link" target="_blank">`httpx`</a>.
+
+E.g. `pip install httpx`.
+
+///
Import `TestClient`.
{!../../../docs_src/app_testing/tutorial001.py!}
```
-!!! tip
- Notice that the testing functions are normal `def`, not `async def`.
+/// tip
+
+Notice that the testing functions are normal `def`, not `async def`.
+
+And the calls to the client are also normal calls, not using `await`.
+
+This allows you to use `pytest` directly without complications.
+
+///
+
+/// note | "Technical Details"
+
+You could also use `from starlette.testclient import TestClient`.
- And the calls to the client are also normal calls, not using `await`.
+**FastAPI** provides the same `starlette.testclient` as `fastapi.testclient` just as a convenience for you, the developer. But it comes directly from Starlette.
- This allows you to use `pytest` directly without complications.
+///
-!!! note "Technical Details"
- You could also use `from starlette.testclient import TestClient`.
+/// tip
- **FastAPI** provides the same `starlette.testclient` as `fastapi.testclient` just as a convenience for you, the developer. But it comes directly from Starlette.
+If you want to call `async` functions in your tests apart from sending requests to your FastAPI application (e.g. asynchronous database functions), have a look at the [Async Tests](../advanced/async-tests.md){.internal-link target=_blank} in the advanced tutorial.
-!!! tip
- If you want to call `async` functions in your tests apart from sending requests to your FastAPI application (e.g. asynchronous database functions), have a look at the [Async Tests](../advanced/async-tests.md){.internal-link target=_blank} in the advanced tutorial.
+///
## Separating tests
Both *path operations* require an `X-Token` header.
-=== "Python 3.10+"
+//// tab | Python 3.10+
- ```Python
- {!> ../../../docs_src/app_testing/app_b_an_py310/main.py!}
- ```
+```Python
+{!> ../../../docs_src/app_testing/app_b_an_py310/main.py!}
+```
-=== "Python 3.9+"
+////
- ```Python
- {!> ../../../docs_src/app_testing/app_b_an_py39/main.py!}
- ```
+//// tab | Python 3.9+
-=== "Python 3.8+"
+```Python
+{!> ../../../docs_src/app_testing/app_b_an_py39/main.py!}
+```
- ```Python
- {!> ../../../docs_src/app_testing/app_b_an/main.py!}
- ```
+////
-=== "Python 3.10+ non-Annotated"
+//// tab | Python 3.8+
+
+```Python
+{!> ../../../docs_src/app_testing/app_b_an/main.py!}
+```
- !!! tip
- Prefer to use the `Annotated` version if possible.
+////
- ```Python
- {!> ../../../docs_src/app_testing/app_b_py310/main.py!}
- ```
+//// tab | Python 3.10+ non-Annotated
-=== "Python 3.8+ non-Annotated"
+/// tip
- !!! tip
- Prefer to use the `Annotated` version if possible.
+Prefer to use the `Annotated` version if possible.
- ```Python
- {!> ../../../docs_src/app_testing/app_b/main.py!}
- ```
+///
+
+```Python
+{!> ../../../docs_src/app_testing/app_b_py310/main.py!}
+```
+
+////
+
+//// tab | Python 3.8+ non-Annotated
+
+/// tip
+
+Prefer to use the `Annotated` version if possible.
+
+///
+
+```Python
+{!> ../../../docs_src/app_testing/app_b/main.py!}
+```
+
+////
### Extended testing file
For more information about how to pass data to the backend (using `httpx` or the `TestClient`) check the <a href="https://www.python-httpx.org" class="external-link" target="_blank">HTTPX documentation</a>.
-!!! info
- Note that the `TestClient` receives data that can be converted to JSON, not Pydantic models.
+/// info
+
+Note that the `TestClient` receives data that can be converted to JSON, not Pydantic models.
+
+If you have a Pydantic model in your test and you want to send its data to the application during testing, you can use the `jsonable_encoder` described in [JSON Compatible Encoder](encoder.md){.internal-link target=_blank}.
- If you have a Pydantic model in your test and you want to send its data to the application during testing, you can use the `jsonable_encoder` described in [JSON Compatible Encoder](encoder.md){.internal-link target=_blank}.
+///
## Run it
cards_layout_options:
logo: ../en/docs/img/icon-white.svg
typeset:
+markdown_extensions:
+ material.extensions.preview:
+ targets:
+ include:
+ - ./*
name: material
custom_dir: ../en/overrides
palette:
+ - media: "(prefers-color-scheme)"
+ toggle:
+ icon: material/lightbulb-auto
+ name: Switch to light mode
- media: '(prefers-color-scheme: light)'
scheme: default
primary: teal
accent: amber
toggle:
icon: material/lightbulb-outline
- name: Switch to light mode
+ name: Switch to system preference
features:
- - search.suggest
- - search.highlight
+ - content.code.annotate
+ - content.code.copy
+ # - content.code.select
+ - content.footnote.tooltips
- content.tabs.link
- - navigation.indexes
- content.tooltips
+ - navigation.footer
+ - navigation.indexes
+ - navigation.instant
+ - navigation.instant.prefetch
+ - navigation.instant.preview
+ - navigation.instant.progress
- navigation.path
- - content.code.annotate
- - content.code.copy
- - content.code.select
- navigation.tabs
+ - navigation.tabs.sticky
+ - navigation.top
+ - navigation.tracking
+ - search.highlight
+ - search.share
+ - search.suggest
+ - toc.follow
+
icon:
repo: fontawesome/brands/github-alt
logo: img/icon-white.svg
language: en
repo_name: fastapi/fastapi
repo_url: https://github.com/fastapi/fastapi
-edit_uri: ''
plugins:
- search: null
+ # Material for MkDocs
+ search:
+ social:
+ # Other plugins
macros:
include_yaml:
- external_links: ../en/data/external_links.yml
signature_crossrefs: true
show_symbol_type_heading: true
show_symbol_type_toc: true
+
nav:
- FastAPI:
- index.md
- benchmarks.md
- management.md
- release-notes.md
+
markdown_extensions:
+ # Python Markdown
+ abbr:
+ attr_list:
+ footnotes:
+ md_in_html:
+ tables:
toc:
permalink: true
- markdown.extensions.codehilite:
- guess_lang: false
- mdx_include:
- base_path: docs
- admonition: null
- codehilite: null
- extra: null
+
+ # Python Markdown Extensions
+ pymdownx.betterem:
+ smart_enable: all
+ pymdownx.caret:
+ pymdownx.highlight:
+ line_spans: __span
+ pymdownx.inlinehilite:
+ pymdownx.keys:
+ pymdownx.mark:
pymdownx.superfences:
custom_fences:
- name: mermaid
class: mermaid
- format: !!python/name:pymdownx.superfences.fence_code_format ''
- pymdownx.tabbed:
- alternate_style: true
- pymdownx.tilde: null
- attr_list: null
- md_in_html: null
+ format: !!python/name:pymdownx.superfences.fence_code_format
+ pymdownx.tilde:
+
+ # pymdownx blocks
+ pymdownx.blocks.admonition:
+ types:
+ - note
+ - attention
+ - caution
+ - danger
+ - error
+ - tip
+ - hint
+ - warning
+ # Custom types
+ - info
+ - check
+ pymdownx.blocks.details:
+ pymdownx.blocks.tab:
+ alternate_style: True
+
+ # Other extensions
+ mdx_include:
+ base_path: docs
+
extra:
analytics:
provider: google
property: G-YNEVN69SC3
+ feedback:
+ title: Was this page helpful?
+ ratings:
+ - icon: material/emoticon-happy-outline
+ name: This page was helpful
+ data: 1
+ note: >-
+ Thanks for your feedback!
+ - icon: material/emoticon-sad-outline
+ name: This page could be improved
+ data: 0
+ note: >-
+ Thanks for your feedback!
social:
- icon: fontawesome/brands/github-alt
link: https://github.com/fastapi/fastapi
link: https://medium.com/@tiangolo
- icon: fontawesome/solid/globe
link: https://tiangolo.com
+
alternate:
- link: /
name: en - English
name: zh-hant - 繁體中文
- link: /em/
name: 😉
+
extra_css:
- css/termynal.css
- css/custom.css
+
extra_javascript:
- js/termynal.js
- js/custom.js
+
hooks:
- ../../scripts/mkdocs_hooks.py
{!../../../docs_src/additional_status_codes/tutorial001.py!}
```
-!!! warning "Advertencia"
- Cuando devuelves directamente una `Response`, como en los ejemplos anteriores, será devuelta directamente.
+/// warning | "Advertencia"
- No será serializado con el modelo, etc.
+Cuando devuelves directamente una `Response`, como en los ejemplos anteriores, será devuelta directamente.
- Asegúrate de que la respuesta tenga los datos que quieras, y que los valores sean JSON válidos (si estás usando `JSONResponse`).
+No será serializado con el modelo, etc.
-!!! note "Detalles Técnicos"
- También podrías utilizar `from starlette.responses import JSONResponse`.
+Asegúrate de que la respuesta tenga los datos que quieras, y que los valores sean JSON válidos (si estás usando `JSONResponse`).
- **FastAPI** provee las mismas `starlette.responses` que `fastapi.responses` simplemente como una convención para ti, el desarrollador. Pero la mayoría de las respuestas disponibles vienen directamente de Starlette. Lo mismo con `status`.
+///
+
+/// note | "Detalles Técnicos"
+
+También podrías utilizar `from starlette.responses import JSONResponse`.
+
+**FastAPI** provee las mismas `starlette.responses` que `fastapi.responses` simplemente como una convención para ti, el desarrollador. Pero la mayoría de las respuestas disponibles vienen directamente de Starlette. Lo mismo con `status`.
+
+///
## OpenAPI y documentación de API
En las secciones siguientes verás otras opciones, configuraciones, y características adicionales.
-!!! tip
- Las próximas secciones **no son necesariamente "avanzadas"**.
+/// tip
- Y es posible que para tu caso, la solución se encuentre en una de estas.
+Las próximas secciones **no son necesariamente "avanzadas"**.
+
+Y es posible que para tu caso, la solución se encuentre en una de estas.
+
+///
## Lee primero el Tutorial
## OpenAPI operationId
-!!! warning "Advertencia"
- Si no eres una persona "experta" en OpenAPI, probablemente no necesitas leer esto.
+/// warning | "Advertencia"
+
+Si no eres una persona "experta" en OpenAPI, probablemente no necesitas leer esto.
+
+///
Puedes asignar el `operationId` de OpenAPI para ser usado en tu *operación de path* con el parámetro `operation_id`.
{!../../../docs_src/path_operation_advanced_configuration/tutorial002.py!}
```
-!!! tip "Consejo"
- Si llamas manualmente a `app.openapi()`, debes actualizar el `operationId`s antes de hacerlo.
+/// tip | "Consejo"
+
+Si llamas manualmente a `app.openapi()`, debes actualizar el `operationId`s antes de hacerlo.
+
+///
+
+/// warning | "Advertencia"
+
+Si haces esto, debes asegurarte de que cada una de tus *funciones de las operaciones de path* tenga un nombre único.
-!!! warning "Advertencia"
- Si haces esto, debes asegurarte de que cada una de tus *funciones de las operaciones de path* tenga un nombre único.
+Incluso si están en diferentes módulos (archivos Python).
- Incluso si están en diferentes módulos (archivos Python).
+///
## Excluir de OpenAPI
De hecho, puedes devolver cualquier `Response` o cualquier subclase de la misma.
-!!! tip "Consejo"
- `JSONResponse` en sí misma es una subclase de `Response`.
+/// tip | "Consejo"
+
+`JSONResponse` en sí misma es una subclase de `Response`.
+
+///
Y cuando devuelves una `Response`, **FastAPI** la pasará directamente.
{!../../../docs_src/response_directly/tutorial001.py!}
```
-!!! note "Detalles Técnicos"
- También puedes usar `from starlette.responses import JSONResponse`.
+/// note | "Detalles Técnicos"
+
+También puedes usar `from starlette.responses import JSONResponse`.
+
+**FastAPI** provee `starlette.responses` como `fastapi.responses`, simplemente como una conveniencia para ti, el desarrollador. Pero la mayoría de las respuestas disponibles vienen directamente de Starlette.
- **FastAPI** provee `starlette.responses` como `fastapi.responses`, simplemente como una conveniencia para ti, el desarrollador. Pero la mayoría de las respuestas disponibles vienen directamente de Starlette.
+///
## Devolviendo una `Response` personalizada
{!../../../docs_src/response_headers/tutorial001.py!}
```
-!!! note "Detalles Técnicos"
- También podrías utilizar `from starlette.responses import Response` o `from starlette.responses import JSONResponse`.
+/// note | "Detalles Técnicos"
- **FastAPI** proporciona las mismas `starlette.responses` en `fastapi.responses` sólo que de una manera más conveniente para ti, el desarrollador. En otras palabras, muchas de las responses disponibles provienen directamente de Starlette.
+También podrías utilizar `from starlette.responses import Response` o `from starlette.responses import JSONResponse`.
+**FastAPI** proporciona las mismas `starlette.responses` en `fastapi.responses` sólo que de una manera más conveniente para ti, el desarrollador. En otras palabras, muchas de las responses disponibles provienen directamente de Starlette.
- Y como la `Response` puede ser usada frecuentemente para configurar headers y cookies, **FastAPI** también la provee en `fastapi.Response`.
+
+Y como la `Response` puede ser usada frecuentemente para configurar headers y cookies, **FastAPI** también la provee en `fastapi.Response`.
+
+///
## Headers Personalizados
Hay algunas características adicionales para manejar la seguridad además de las que se tratan en el [Tutorial - Guía de Usuario: Seguridad](../../tutorial/security/index.md){.internal-link target=_blank}.
-!!! tip
- Las siguientes secciones **no necesariamente son "avanzadas"**.
+/// tip
- Y es posible que para tu caso de uso, la solución esté en alguna de ellas.
+Las siguientes secciones **no necesariamente son "avanzadas"**.
+
+Y es posible que para tu caso de uso, la solución esté en alguna de ellas.
+
+///
## Leer primero el Tutorial
return results
```
-!!! note "Nota"
- Solo puedes usar `await` dentro de funciones creadas con `async def`.
+/// note | "Nota"
+
+Solo puedes usar `await` dentro de funciones creadas con `async def`.
+
+///
---
<img src="https://fastapi.tiangolo.com/img/async/concurrent-burgers/concurrent-burgers-07.png" alt="illustration">
-!!! info
- Las ilustraciones fueron creados por <a href="https://www.instagram.com/ketrinadrawsalot" class="external-link" target="_blank">Ketrina Thompson</a>. 🎨
+/// info
+
+Las ilustraciones fueron creados por <a href="https://www.instagram.com/ketrinadrawsalot" class="external-link" target="_blank">Ketrina Thompson</a>. 🎨
+
+///
---
No has hablado ni coqueteado mucho, ya que has pasado la mayor parte del tiempo esperando 🕙 frente al mostrador 😞.
-!!! info
- Las ilustraciones fueron creados por <a href="https://www.instagram.com/ketrinadrawsalot" class="external-link" target="_blank">Ketrina Thompson</a>. 🎨
+/// info
+
+Las ilustraciones fueron creados por <a href="https://www.instagram.com/ketrinadrawsalot" class="external-link" target="_blank">Ketrina Thompson</a>. 🎨
+
+///
---
## Detalles muy técnicos
-!!! warning "Advertencia"
- Probablemente puedas saltarte esto.
+/// warning | "Advertencia"
+
+Probablemente puedas saltarte esto.
+
+Estos son detalles muy técnicos de cómo **FastAPI** funciona a muy bajo nivel.
- Estos son detalles muy técnicos de cómo **FastAPI** funciona a muy bajo nivel.
+Si tienes bastante conocimiento técnico (coroutines, threads, bloqueos, etc.) y tienes curiosidad acerca de cómo FastAPI gestiona `async def` vs `def` normal, continúa.
- Si tienes bastante conocimiento técnico (coroutines, threads, bloqueos, etc.) y tienes curiosidad acerca de cómo FastAPI gestiona `async def` vs `def` normal, continúa.
+///
### Path operation functions
FastAPI también sigue la convención de que cualquier cambio hecho en una <abbr title="versiones de parche">"PATCH" version</abbr> es para solucionar errores y <abbr title="cambios que no rompan funcionalidades o compatibilidad">*non-breaking changes*</abbr>.
-!!! tip
- El <abbr title="parche">"PATCH"</abbr> es el último número, por ejemplo, en `0.2.3`, la <abbr title="versiones de parche">PATCH version</abbr> es `3`.
+/// tip
+
+El <abbr title="parche">"PATCH"</abbr> es el último número, por ejemplo, en `0.2.3`, la <abbr title="versiones de parche">PATCH version</abbr> es `3`.
+
+///
Entonces, deberías fijar la versión así:
En versiones <abbr title="versiones menores">"MINOR"</abbr> son añadidas nuevas características y posibles <abbr title="Cambios que rompen posibles funcionalidades o compatibilidad">breaking changes</abbr>.
-!!! tip
- La versión "MINOR" es el número en el medio, por ejemplo, en `0.2.3`, la <abbr title="versión menor">"MINOR" version</abbr> es `2`.
+/// tip
+
+La versión "MINOR" es el número en el medio, por ejemplo, en `0.2.3`, la <abbr title="versión menor">"MINOR" version</abbr> es `2`.
+
+///
## Actualizando las versiones de FastAPI
Aquí hay una lista incompleta de algunos de ellos.
-!!! tip "Consejo"
- Si tienes un artículo, proyecto, herramienta o cualquier cosa relacionada con **FastAPI** que aún no aparece aquí, crea un <a href="https://github.com/fastapi/fastapi/edit/master/docs/en/data/external_links.yml" class="external-link" target="_blank">Pull Request agregándolo</a>.
+/// tip | "Consejo"
+
+Si tienes un artículo, proyecto, herramienta o cualquier cosa relacionada con **FastAPI** que aún no aparece aquí, crea un <a href="https://github.com/fastapi/fastapi/edit/master/docs/en/data/external_links.yml" class="external-link" target="_blank">Pull Request agregándolo</a>.
+
+///
{% for section_name, section_content in external_links.items() %}
my_second_user: User = User(**second_user_data)
```
-!!! info
- `**second_user_data` significa:
+/// info
- Pasa las <abbr title="en español key se refiere a la guía de un diccionario">keys</abbr> y los valores del dict `second_user_data` directamente como argumentos de key-value, equivalente a: `User(id=4, name="Mary", joined="2018-11-30")`
+`**second_user_data` significa:
+
+Pasa las <abbr title="en español key se refiere a la guía de un diccionario">keys</abbr> y los valores del dict `second_user_data` directamente como argumentos de key-value, equivalente a: `User(id=4, name="Mary", joined="2018-11-30")`
+
+///
### Soporte del editor
Puedes combinar *operaciones de path* regulares de la library de FastAPI con GraphQL en la misma aplicación.
-!!! tip
- **GraphQL** resuelve algunos casos de uso específicos.
+/// tip
- Tiene **ventajas** y **desventajas** cuando lo comparas con **APIs web** comunes.
+**GraphQL** resuelve algunos casos de uso específicos.
- Asegúrate de evaluar si los **beneficios** para tu caso de uso compensan las **desventajas.** 🤓
+Tiene **ventajas** y **desventajas** cuando lo comparas con **APIs web** comunes.
+
+Asegúrate de evaluar si los **beneficios** para tu caso de uso compensan las **desventajas.** 🤓
+
+///
## Librerías GraphQL
Esto fue marcado como obsoleto en Starlette, pero si aún tienes código que lo usa, puedes fácilmente **migrar** a <a href="https://github.com/ciscorn/starlette-graphene3" class="external-link" target="_blank">starlette-graphene3</a>, la cual cubre el mismo caso de uso y tiene una **interfaz casi idéntica.**
-!!! tip
- Si necesitas GraphQL, te recomendaría revisar <a href="https://strawberry.rocks/" class="external-link" target="_blank">Strawberry</a>, que es basada en anotaciones de tipo en vez de clases y tipos personalizados.
+/// tip
+
+Si necesitas GraphQL, te recomendaría revisar <a href="https://strawberry.rocks/" class="external-link" target="_blank">Strawberry</a>, que es basada en anotaciones de tipo en vez de clases y tipos personalizados.
+
+///
## Aprende más
Pero, así nunca uses **FastAPI** te beneficiarás de aprender un poco sobre los type hints.
-!!! 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 lo sabes todo sobre los type hints, salta al siguiente capítulo.
+
+///
## Motivación
{!../../../docs_src/python_types/tutorial010.py!}
```
-!!! info "Información"
- Para aprender más sobre <a href="https://docs.pydantic.dev/" class="external-link" target="_blank">Pydantic mira su documentación</a>.
+/// info | "Información"
+
+Para aprender más sobre <a href="https://docs.pydantic.dev/" class="external-link" target="_blank">Pydantic mira su documentación</a>.
+
+///
**FastAPI** está todo basado en Pydantic.
Lo importante es que usando los tipos de Python estándar en un único lugar (en vez de añadir más clases, decorator, etc.) **FastAPI** hará mucho del trabajo por ti.
-!!! info "Información"
- Si ya pasaste por todo el tutorial y volviste a la sección de los tipos, una buena referencia es <a href="https://mypy.readthedocs.io/en/latest/cheat_sheet_py3.html" class="external-link" target="_blank">la "cheat sheet" de `mypy`</a>.
+/// info | "Información"
+
+Si ya pasaste por todo el tutorial y volviste a la sección de los tipos, una buena referencia es <a href="https://mypy.readthedocs.io/en/latest/cheat_sheet_py3.html" class="external-link" target="_blank">la "cheat sheet" de `mypy`</a>.
+
+///
Primero importa `Cookie`:
-=== "Python 3.10+"
+//// tab | Python 3.10+
- ```Python hl_lines="3"
- {!> ../../../docs_src/cookie_params/tutorial001_an_py310.py!}
- ```
+```Python hl_lines="3"
+{!> ../../../docs_src/cookie_params/tutorial001_an_py310.py!}
+```
-=== "Python 3.9+"
+////
- ```Python hl_lines="3"
- {!> ../../../docs_src/cookie_params/tutorial001_an_py39.py!}
- ```
+//// tab | Python 3.9+
-=== "Python 3.8+"
+```Python hl_lines="3"
+{!> ../../../docs_src/cookie_params/tutorial001_an_py39.py!}
+```
- ```Python hl_lines="3"
- {!> ../../../docs_src/cookie_params/tutorial001_an.py!}
- ```
+////
-=== "Python 3.10+ non-Annotated"
+//// tab | Python 3.8+
- !!! tip
- Prefer to use the `Annotated` version if possible.
+```Python hl_lines="3"
+{!> ../../../docs_src/cookie_params/tutorial001_an.py!}
+```
- ```Python hl_lines="1"
- {!> ../../../docs_src/cookie_params/tutorial001_py310.py!}
- ```
+////
-=== "Python 3.8+ non-Annotated"
+//// tab | Python 3.10+ non-Annotated
- !!! tip
- Prefer to use the `Annotated` version if possible.
+/// tip
- ```Python hl_lines="3"
- {!> ../../../docs_src/cookie_params/tutorial001.py!}
- ```
+Prefer to use the `Annotated` version if possible.
+
+///
+
+```Python hl_lines="1"
+{!> ../../../docs_src/cookie_params/tutorial001_py310.py!}
+```
+
+////
+
+//// tab | Python 3.8+ non-Annotated
+
+/// tip
+
+Prefer to use the `Annotated` version if possible.
+
+///
+
+```Python hl_lines="3"
+{!> ../../../docs_src/cookie_params/tutorial001.py!}
+```
+
+////
## Declarar parámetros de `Cookie`
El primer valor es el valor por defecto, puedes pasar todos los parámetros adicionales de validación o anotación:
-=== "Python 3.10+"
+//// tab | Python 3.10+
+
+```Python hl_lines="9"
+{!> ../../../docs_src/cookie_params/tutorial001_an_py310.py!}
+```
+
+////
+
+//// tab | Python 3.9+
+
+```Python hl_lines="9"
+{!> ../../../docs_src/cookie_params/tutorial001_an_py39.py!}
+```
+
+////
+
+//// tab | Python 3.8+
+
+```Python hl_lines="10"
+{!> ../../../docs_src/cookie_params/tutorial001_an.py!}
+```
+
+////
+
+//// tab | Python 3.10+ non-Annotated
+
+/// tip
+
+Prefer to use the `Annotated` version if possible.
+
+///
+
+```Python hl_lines="7"
+{!> ../../../docs_src/cookie_params/tutorial001_py310.py!}
+```
- ```Python hl_lines="9"
- {!> ../../../docs_src/cookie_params/tutorial001_an_py310.py!}
- ```
+////
-=== "Python 3.9+"
+//// tab | Python 3.8+ non-Annotated
- ```Python hl_lines="9"
- {!> ../../../docs_src/cookie_params/tutorial001_an_py39.py!}
- ```
+/// tip
-=== "Python 3.8+"
+Prefer to use the `Annotated` version if possible.
- ```Python hl_lines="10"
- {!> ../../../docs_src/cookie_params/tutorial001_an.py!}
- ```
+///
-=== "Python 3.10+ non-Annotated"
+```Python hl_lines="9"
+{!> ../../../docs_src/cookie_params/tutorial001.py!}
+```
- !!! tip
- Prefer to use the `Annotated` version if possible.
+////
- ```Python hl_lines="7"
- {!> ../../../docs_src/cookie_params/tutorial001_py310.py!}
- ```
+/// note | "Detalles Técnicos"
-=== "Python 3.8+ non-Annotated"
+`Cookie` es una clase "hermana" de `Path` y `Query`. También hereda de la misma clase común `Param`.
- !!! tip
- Prefer to use the `Annotated` version if possible.
+Pero recuerda que cuando importas `Query`, `Path`, `Cookie` y otros de `fastapi`, en realidad son funciones que devuelven clases especiales.
- ```Python hl_lines="9"
- {!> ../../../docs_src/cookie_params/tutorial001.py!}
- ```
+///
-!!! note "Detalles Técnicos"
- `Cookie` es una clase "hermana" de `Path` y `Query`. También hereda de la misma clase común `Param`.
+/// info
- Pero recuerda que cuando importas `Query`, `Path`, `Cookie` y otros de `fastapi`, en realidad son funciones que devuelven clases especiales.
+Para declarar cookies, necesitas usar `Cookie`, porque de lo contrario los parámetros serían interpretados como parámetros de query.
-!!! info
- Para declarar cookies, necesitas usar `Cookie`, porque de lo contrario los parámetros serían interpretados como parámetros de query.
+///
## Resumen
</div>
-!!! note "Nota"
- El comando `uvicorn main:app` se refiere a:
+/// note | "Nota"
- * `main`: el archivo `main.py` (el "módulo" de Python).
- * `app`: el objeto creado dentro de `main.py` con la línea `app = FastAPI()`.
- * `--reload`: hace que el servidor se reinicie cada vez que cambia el código. Úsalo únicamente para desarrollo.
+El comando `uvicorn main:app` se refiere a:
+
+* `main`: el archivo `main.py` (el "módulo" de Python).
+* `app`: el objeto creado dentro de `main.py` con la línea `app = FastAPI()`.
+* `--reload`: hace que el servidor se reinicie cada vez que cambia el código. Úsalo únicamente para desarrollo.
+
+///
En el output, hay una línea que dice más o menos:
`FastAPI` es una clase de Python que provee toda la funcionalidad para tu API.
-!!! note "Detalles Técnicos"
- `FastAPI` es una clase que hereda directamente de `Starlette`.
+/// note | "Detalles Técnicos"
+
+`FastAPI` es una clase que hereda directamente de `Starlette`.
- También puedes usar toda la funcionalidad de <a href="https://www.starlette.io/" class="external-link" target="_blank">Starlette</a>.
+También puedes usar toda la funcionalidad de <a href="https://www.starlette.io/" class="external-link" target="_blank">Starlette</a>.
+
+///
### Paso 2: crea un "instance" de `FastAPI`
/items/foo
```
-!!! info "Información"
- Un "path" también se conoce habitualmente como "endpoint", "route" o "ruta".
+/// info | "Información"
+
+Un "path" también se conoce habitualmente como "endpoint", "route" o "ruta".
+
+///
Cuando construyes una API, el "path" es la manera principal de separar los <abbr title="en inglés: separation of concerns">"intereses"</abbr> y los "recursos".
* el path `/`
* usando una <abbr title="an HTTP GET method">operación <code>get</code></abbr>
-!!! 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` se llama un "decorador" en Python.
- Un "decorador" toma la función que tiene debajo y hace algo con ella.
+Lo pones encima de una función. Es como un lindo sombrero decorado (creo que de ahí salió el concepto).
- 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 que tiene debajo 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 que está debajo corresponde al **path** `/` con una **operación** `get`.
+
+Es el "**decorador de operaciones de path**".
+
+///
También puedes usar las otras operaciones:
* `@app.patch()`
* `@app.trace()`
-!!! tip "Consejo"
- Tienes la libertad de usar cada operación (método de HTTP) como quieras.
+/// tip | "Consejo"
+
+Tienes la libertad de usar cada operación (método de HTTP) como quieras.
- **FastAPI** no impone ningún significado específico.
+**FastAPI** no impone ningún significado específico.
- La información que está presentada aquí es una guía, no un requerimiento.
+La información que está presentada aquí es una guía, no un requerimiento.
- 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 únicamente operaciones `POST`.
+
+///
### Paso 4: define la **función de la operación de path**
{!../../../docs_src/first_steps/tutorial003.py!}
```
-!!! note "Nota"
- Si no sabes la diferencia, revisa el [Async: *"¿Tienes prisa?"*](../async.md#tienes-prisa){.internal-link target=_blank}.
+/// note | "Nota"
+
+Si no sabes la diferencia, revisa el [Async: *"¿Tienes prisa?"*](../async.md#tienes-prisa){.internal-link target=_blank}.
+
+///
### Paso 5: devuelve el contenido
...eso también incluye `uvicorn` que puedes usar como el servidor que ejecuta tu código.
-!!! note "Nota"
- También puedes instalarlo parte por parte.
+/// note | "Nota"
- Esto es lo que probablemente harías una vez que desees implementar tu aplicación en producción:
+También puedes instalarlo parte por parte.
- ```
- pip install fastapi
- ```
+Esto es lo que probablemente harías una vez que desees implementar tu aplicación en producción:
- También debes instalar `uvicorn` para que funcione como tu servidor:
+```
+pip install fastapi
+```
+
+También debes instalar `uvicorn` para que funcione como tu servidor:
+
+```
+pip install "uvicorn[standard]"
+```
- ```
- pip install "uvicorn[standard]"
- ```
+Y lo mismo para cada una de las dependencias opcionales que quieras utilizar.
- Y lo mismo para cada una de las dependencias opcionales que quieras utilizar.
+///
## Guía Avanzada de Usuario
En este caso, `item_id` es declarado como un `int`.
-!!! check "Revisa"
- Esto te dará soporte en el editor dentro de tu función, con chequeo de errores, auto-completado, etc.
+/// check | "Revisa"
+
+Esto te dará soporte en el editor dentro de tu función, con chequeo de errores, auto-completado, etc.
+
+///
## <abbr title="también conocido en inglés como: serialization, parsing, marshalling">Conversión</abbr> de datos
{"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"
+
+Observa que el valor que recibió (y devolvió) tu función es `3`, como un Python `int`, y no un string `"3"`.
+
+Entonces, con esa declaración de tipos **FastAPI** te da <abbr title="convertir el string que viene de un HTTP request a datos de Python">"parsing"</abbr> automático del request.
- Entonces, con esa declaración de tipos **FastAPI** te da <abbr title="convertir el string que viene de un HTTP request a datos de Python">"parsing"</abbr> automático del request.
+///
## Validación de datos
El mismo error aparecería si pasaras un `float` en vez de un `int` como en: <a href="http://127.0.0.1:8000/items/4.2" class="external-link" target="_blank">http://127.0.0.1:8000/items/4.2</a>
-!!! check "Revisa"
- Así, con la misma declaración de tipo de Python, **FastAPI** te da validación de datos.
+/// check | "Revisa"
- Observa que el error también muestra claramente el punto exacto en el que no pasó la validación.
+Así, con la misma declaración de tipo de Python, **FastAPI** te da validación de datos.
- Esto es increíblemente útil cuando estás desarrollando y debugging código que interactúa con tu API.
+Observa que el error también muestra claramente el punto exacto en el que no pasó la validación.
+
+Esto es increíblemente útil cuando estás desarrollando y debugging código que interactúa con tu API.
+
+///
## Documentación
<img src="/img/tutorial/path-params/image01.png">
-!!! check "Revisa"
- Nuevamente, con la misma declaración de tipo de Python, **FastAPI** te da documentación automática e interactiva (integrándose con Swagger UI)
+/// check | "Revisa"
+
+Nuevamente, con la misma declaración de tipo de Python, **FastAPI** te da documentación automática e interactiva (integrándose con Swagger UI)
+
+Observa que el parámetro de path está declarado como un integer.
- Observa que el parámetro de path está declarado como un integer.
+///
## Beneficios basados en estándares, documentación alternativa
{!../../../docs_src/path_params/tutorial005.py!}
```
-!!! info "Información"
- Las <a href="https://docs.python.org/3/library/enum.html" class="external-link" target="_blank">Enumerations (o enums) están disponibles en Python</a> desde la versión 3.4.
+/// info | "Información"
-!!! tip "Consejo"
- Si lo estás dudando, "AlexNet", "ResNet", y "LeNet" son solo nombres de <abbr title="Técnicamente, arquitecturas de modelos de Deep Learning">modelos</abbr> de Machine Learning.
+Las <a href="https://docs.python.org/3/library/enum.html" class="external-link" target="_blank">Enumerations (o enums) están disponibles en Python</a> desde la versión 3.4.
+
+///
+
+/// tip | "Consejo"
+
+Si lo estás dudando, "AlexNet", "ResNet", y "LeNet" son solo nombres de <abbr title="Técnicamente, arquitecturas de modelos de Deep Learning">modelos</abbr> de Machine Learning.
+
+///
### Declara un *parámetro de path*
{!../../../docs_src/path_params/tutorial005.py!}
```
-!!! tip "Consejo"
- También podrías obtener el valor `"lenet"` con `ModelName.lenet.value`.
+/// tip | "Consejo"
+
+También podrías obtener el valor `"lenet"` con `ModelName.lenet.value`.
+
+///
#### Devuelve *enumeration members*
{!../../../docs_src/path_params/tutorial004.py!}
```
-!!! tip "Consejo"
- Podrías necesitar que el parámetro contenga `/home/johndoe/myfile.txt` con un slash inicial (`/`).
+/// tip | "Consejo"
+
+Podrías necesitar que el parámetro contenga `/home/johndoe/myfile.txt` con un slash inicial (`/`).
+
+En este caso la URL sería `/files//home/johndoe/myfile.txt` con un slash doble (`//`) entre `files` y `home`.
- En este caso la URL sería `/files//home/johndoe/myfile.txt` con un slash doble (`//`) entre `files` y `home`.
+///
## Repaso
En este caso el parámetro de la función `q` será opcional y será `None` por defecto.
-!!! check "Revisa"
- También puedes notar que **FastAPI** es lo suficientemente inteligente para darse cuenta de que el parámetro de path `item_id` es un parámetro de path y que `q` no lo es, y por lo tanto es un parámetro de query.
+/// check | "Revisa"
-!!! note "Nota"
- FastAPI sabrá que `q` es opcional por el `= None`.
+También puedes notar que **FastAPI** es lo suficientemente inteligente para darse cuenta de que el parámetro de path `item_id` es un parámetro de path y que `q` no lo es, y por lo tanto es un parámetro de query.
- El `Union` en `Union[str, None]` no es usado por FastAPI (FastAPI solo usará la parte `str`), pero el `Union[str, None]` le permitirá a tu editor ayudarte a encontrar errores en tu código.
+///
+
+/// note | "Nota"
+
+FastAPI sabrá que `q` es opcional por el `= None`.
+
+El `Union` en `Union[str, None]` no es usado por FastAPI (FastAPI solo usará la parte `str`), pero el `Union[str, None]` le permitirá a tu editor ayudarte a encontrar errores en tu código.
+
+///
## Conversión de tipos de parámetros de query
* `skip`, un `int` con un valor por defecto de `0`.
* `limit`, un `int` opcional.
-!!! tip "Consejo"
- También podrías usar los `Enum`s de la misma manera que con los [Parámetros de path](path-params.md#valores-predefinidos){.internal-link target=_blank}.
+/// tip | "Consejo"
+
+También podrías usar los `Enum`s de la misma manera que con los [Parámetros de path](path-params.md#valores-predefinidos){.internal-link target=_blank}.
+
+///
my_second_user: User = User(**second_user_data)
```
-!!! info
- `**second_user_data` یعنی:
+/// info
- کلید ها و مقادیر دیکشنری `second_user_data` را مستقیما به عنوان ارگومان های key-value بفرست، که معادل است با : `User(id=4, name="Mary", joined="2018-11-30")`
+`**second_user_data` یعنی:
+
+کلید ها و مقادیر دیکشنری `second_user_data` را مستقیما به عنوان ارگومان های key-value بفرست، که معادل است با : `User(id=4, name="Mary", joined="2018-11-30")`
+
+///
### پشتیبانی ویرایشگر
* می تواند کاری با **پاسخ** انجام دهید یا هر کد مورد نیازتان را اجرا کند.
* سپس **پاسخ** را برمی گرداند.
-!!! توجه "جزئیات فنی"
- در صورت وجود وابستگی هایی با `yield`، کد خروجی **پس از** اجرای میانافزار اجرا خواهد شد.
+/// توجه | "جزئیات فنی"
- در صورت وجود هر گونه وظایف پس زمینه (که در ادامه توضیح داده میشوند)، تمام میانافزارها *پس از آن* اجرا خواهند شد.
+در صورت وجود وابستگی هایی با `yield`، کد خروجی **پس از** اجرای میانافزار اجرا خواهد شد.
+
+در صورت وجود هر گونه وظایف پس زمینه (که در ادامه توضیح داده میشوند)، تمام میانافزارها *پس از آن* اجرا خواهند شد.
+
+///
## ساخت یک میان افزار
{!../../../docs_src/middleware/tutorial001.py!}
```
-!!! نکته به خاطر داشته باشید که هدرهای اختصاصی سفارشی را می توان با استفاده از پیشوند "X-" اضافه کرد.
+/// نکته | به خاطر داشته باشید که هدرهای اختصاصی سفارشی را می توان با استفاده از پیشوند "X-" اضافه کرد.
+
+اما اگر هدرهای سفارشی دارید که میخواهید مرورگر کاربر بتواند آنها را ببیند، باید آنها را با استفاده از پارامتر `expose_headers` که در مستندات <a href="https://www.starlette.io/middleware/#corsmiddleware" class="external-link" target="_blank">CORS از Starlette</a> توضیح داده شده است، به پیکربندی CORS خود اضافه کنید.
+
+///
+
+/// توجه | "جزئیات فنی"
- اما اگر هدرهای سفارشی دارید که میخواهید مرورگر کاربر بتواند آنها را ببیند، باید آنها را با استفاده از پارامتر `expose_headers` که در مستندات <a href="https://www.starlette.io/middleware/#corsmiddleware" class="external-link" target="_blank">CORS از Starlette</a> توضیح داده شده است، به پیکربندی CORS خود اضافه کنید.
+شما همچنین میتوانید از `from starlette.requests import Request` استفاده کنید.
-!!! توجه "جزئیات فنی"
- شما همچنین میتوانید از `from starlette.requests import Request` استفاده کنید.
+**FastAPI** این را به عنوان یک سهولت برای شما به عنوان برنامهنویس فراهم میکند. اما این مستقیما از Starlette به دست میآید.
- **FastAPI** این را به عنوان یک سهولت برای شما به عنوان برنامهنویس فراهم میکند. اما این مستقیما از Starlette به دست میآید.
+///
### قبل و بعد از `پاسخ`
پروتکل استاندارد OAuth2 روش رمزگذاری ارتباط را مشخص نمی کند، بلکه انتظار دارد که برنامه شما با HTTPS سرویس دهی شود.
-!!! نکته
- در بخش در مورد **استقرار** ، شما یاد خواهید گرفت که چگونه با استفاده از Traefik و Let's Encrypt رایگان HTTPS را راه اندازی کنید.
+/// نکته
+
+در بخش در مورد **استقرار** ، شما یاد خواهید گرفت که چگونه با استفاده از Traefik و Let's Encrypt رایگان HTTPS را راه اندازی کنید.
+
+///
## استاندارد OpenID Connect
* شیوه `openIdConnect`: یک روش برای تعریف نحوه کشف دادههای احراز هویت OAuth2 به صورت خودکار.
* کشف خودکار این موضوع را که در مشخصه OpenID Connect تعریف شده است، مشخص میکند.
-!!! نکته
- ادغام سایر ارائهدهندگان احراز هویت/اجازهدهی مانند گوگل، فیسبوک، توییتر، گیتهاب و غیره نیز امکانپذیر و نسبتاً آسان است.
+/// نکته
+
+ادغام سایر ارائهدهندگان احراز هویت/اجازهدهی مانند گوگل، فیسبوک، توییتر، گیتهاب و غیره نیز امکانپذیر و نسبتاً آسان است.
+
+مشکل پیچیدهترین مسئله، ساخت یک ارائهدهنده احراز هویت/اجازهدهی مانند آنها است، اما **FastAPI** ابزارهای لازم برای انجام این کار را با سهولت به شما میدهد و همه کارهای سنگین را برای شما انجام میدهد.
- مشکل پیچیدهترین مسئله، ساخت یک ارائهدهنده احراز هویت/اجازهدهی مانند آنها است، اما **FastAPI** ابزارهای لازم برای انجام این کار را با سهولت به شما میدهد و همه کارهای سنگین را برای شما انجام میدهد.
+///
## ابزارهای **FastAPI**
# Réponses supplémentaires dans OpenAPI
-!!! warning "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.
{!../../../docs_src/additional_responses/tutorial001.py!}
```
-!!! note "Remarque"
- Gardez à l'esprit que vous devez renvoyer directement `JSONResponse`.
+/// note | "Remarque"
+
+Gardez à l'esprit que vous devez renvoyer directement `JSONResponse`.
+
+///
+
+/// info
-!!! info
- La clé `model` ne fait pas partie d'OpenAPI.
+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 :
{!../../../docs_src/additional_responses/tutorial002.py!}
```
-!!! note "Remarque"
- Notez que vous devez retourner l'image en utilisant directement un `FileResponse`.
+/// note | "Remarque"
+
+Notez que vous devez retourner l'image en utilisant directement un `FileResponse`.
+
+///
+
+/// 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`).
-!!! 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`).
+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
{!../../../docs_src/additional_status_codes/tutorial001.py!}
```
-!!! warning "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
Dans les sections suivantes, vous verrez des options, configurations et fonctionnalités supplémentaires.
-!!! note "Remarque"
- 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
## ID d'opération OpenAPI
-!!! warning "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`.
{!../../../docs_src/path_operation_advanced_configuration/tutorial002.py!}
```
-!!! tip "Astuce"
- Si vous appelez manuellement `app.openapi()`, vous devez mettre à jour les `operationId` avant.
+/// tip | "Astuce"
+
+Si vous appelez manuellement `app.openapi()`, vous devez mettre à jour les `operationId` avant.
+
+///
+
+/// warning | "Attention"
+
+Pour faire cela, vous devez vous assurer que chacun de vos *chemin* ait un nom unique.
-!!! 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).
- Même s'ils se trouvent dans des modules différents (fichiers Python).
+///
## Exclusion d'OpenAPI
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étadonnées des <a href="https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.3.md#operation-object" class="external-link" target="_blank">Objets d'opération</a>.
+/// note | "Détails techniques"
+
+La spécification OpenAPI appelle ces métadonnées des <a href="https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.3.md#operation-object" class="external-link" target="_blank">Objets d'opération</a>.
+
+///
Il contient toutes les informations sur le *chemin* et est utilisé pour générer automatiquement la documentation.
Ce schéma OpenAPI spécifique aux *operations* est normalement généré automatiquement par **FastAPI**, mais vous pouvez également l'étendre.
-!!! 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}.
+/// 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`.
{!../../../docs_src/path_operation_advanced_configuration/tutorial007.py!}
```
-!!! tip "Astuce"
- Ici, nous réutilisons le même modèle Pydantic.
+/// tip | "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.
+///
En fait, vous pouvez retourner n'importe quelle `Response` ou n'importe quelle sous-classe de celle-ci.
-!!! note "Remarque"
- `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.
{!../../../docs_src/response_directly/tutorial001.py!}
```
-!!! 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
Il s'agissait de l'un des premiers exemples de **documentation automatique pour API**, et c'est précisément l'une des
premières idées qui a inspiré "la recherche de" **FastAPI**.
-!!! note
+/// note
+
Django REST framework a été créé par Tom Christie. Le créateur de Starlette et Uvicorn, sur lesquels **FastAPI** est basé.
-!!! check "A inspiré **FastAPI** à"
+///
+
+/// check | "A inspiré **FastAPI** à"
+
Avoir une interface de documentation automatique de l'API.
+///
+
### <a href="https://flask.palletsprojects.com" class="external-link" target="_blank">Flask</a>
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.
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.
+///
+
### <a href="https://requests.readthedocs.io" class="external-link" target="_blank">Requests</a>
**FastAPI** n'est pas réellement une alternative à **Requests**. Leur cadre est très différent.
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.
+
+///
### <a href="https://swagger.io/" class="external-link" target="_blank">Swagger</a> / <a href="https://github.com/OAI/OpenAPI-Specification/" class="external-link" target="_blank">OpenAPI</a>
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 :
- * <a href="https://github.com/swagger-api/swagger-ui" class="external-link" target="_blank">Swagger UI</a>
- * <a href="https://github.com/Rebilly/ReDoc" class="external-link" target="_blank">ReDoc</a>
+* <a href="https://github.com/swagger-api/swagger-ui" class="external-link" target="_blank">Swagger UI</a>
+* <a href="https://github.com/Rebilly/ReDoc" class="external-link" target="_blank">ReDoc</a>
- 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
Mais elle a été créée avant que les type hints n'existent en Python. Ainsi, pour définir chaque <abbr title="la définition de
la façon dont les données doivent être formées">schéma</abbr>, 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.
+///
+
### <a href="https://webargs.readthedocs.io/en/latest/" class="external-link" target="_blank">Webargs</a>
Une autre grande fonctionnalité requise par les API est le <abbr title="la lecture et la conversion en données
C'est un outil formidable et je l'ai beaucoup utilisé aussi, avant d'avoir **FastAPI**.
-!!! info
+/// info
+
Webargs a été créé par les développeurs de Marshmallow.
-!!! check "A inspiré **FastAPI** à"
+///
+
+/// check | "A inspiré **FastAPI** à"
+
Disposer d'une validation automatique des données des requêtes entrantes.
+///
+
### <a href="https://apispec.readthedocs.io/en/stable/" class="external-link" target="_blank">APISpec</a>
Marshmallow et Webargs fournissent la validation, l'analyse et la sérialisation en tant que plug-ins.
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.
+///
+
### <a href="https://flask-apispec.readthedocs.io/en/latest/" class="external-link" target="_blank">Flask-apispec</a>
C'est un plug-in pour Flask, qui relie Webargs, Marshmallow et APISpec.
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.
+///
+
### <a href="https://nestjs.com/" class="external-link" target="_blank">NestJS</a> (et <a href="https://angular.io/" class="external-link" target="_blank">Angular</a>)
Ce n'est même pas du Python, NestJS est un framework JavaScript (TypeScript) NodeJS inspiré d'Angular.
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.
+
+///
### <a href="https://sanic.readthedocs.io/en/latest/" class="external-link" target="_blank">Sanic</a>
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 <a href="https://github.com/MagicStack/uvloop" class="external-link" target="_blank">`uvloop`</a> 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).
+
+///
### <a href="https://falconframework.org/" class="external-link" target="_blank">Falcon</a>
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.
+///
### <a href="https://moltenframework.com/" class="external-link" target="_blank">Molten</a>
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).
+
+///
### <a href="https://www.hug.rest/" class="external-link" target="_blank">Hug</a>
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 <a href="https://github.com/timothycrosley/isort" class="external-link" target="_blank">`isort`</a>, 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.
+///
### <a href="https://github.com/encode/apistar" class="external-link" target="_blank">APIStar</a> (<= 0.5)
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**
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.
+
+///
### <a href="https://www.starlette.io/" class="external-link" target="_blank">Starlette</a>
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.
+
+///
### <a href="https://www.uvicorn.org/" class="external-link" target="_blank">Uvicorn</a>
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
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`.
+
+///
---
<img src="/img/async/concurrent-burgers/concurrent-burgers-07.png" class="illustration">
-!!! info
- Illustrations proposées par <a href="https://www.instagram.com/ketrinadrawsalot" class="external-link" target="_blank">Ketrina Thompson</a>. 🎨
+/// info
+
+Illustrations proposées par <a href="https://www.instagram.com/ketrinadrawsalot" class="external-link" target="_blank">Ketrina Thompson</a>. 🎨
+
+///
---
Durant tout ce processus, il n'y a presque pas eu de discussions ou de flirts car la plupart de votre temps à été passé à attendre 🕙 devant le comptoir 😞.
-!!! info
- Illustrations proposées par <a href="https://www.instagram.com/ketrinadrawsalot" class="external-link" target="_blank">Ketrina Thompson</a>. 🎨
+/// info
+
+Illustrations proposées par <a href="https://www.instagram.com/ketrinadrawsalot" class="external-link" target="_blank">Ketrina Thompson</a>. 🎨
+
+///
---
## Détails très techniques
-!!! warning "Attention !"
- Vous pouvez probablement ignorer cela.
+/// warning | "Attention !"
+
+Vous pouvez probablement ignorer cela.
+
+Ce sont des détails très poussés sur comment **FastAPI** fonctionne en arrière-plan.
- Ce sont des détails très poussés sur comment **FastAPI** fonctionne en arrière-plan.
+Si vous avez de bonnes connaissances techniques (coroutines, threads, code bloquant, etc.) et êtes curieux de comment **FastAPI** gère `async def` versus le `def` classique, cette partie est faite pour vous.
- Si vous avez de bonnes connaissances techniques (coroutines, threads, code bloquant, etc.) et êtes curieux de comment **FastAPI** gère `async def` versus le `def` classique, cette partie est faite pour vous.
+///
### Fonctions de chemin
Activez le nouvel environnement avec :
-=== "Linux, macOS"
+//// tab | Linux, macOS
- <div class="termy">
+<div class="termy">
- ```console
- $ source ./env/bin/activate
- ```
+```console
+$ source ./env/bin/activate
+```
- </div>
+</div>
-=== "Windows PowerShell"
+////
- <div class="termy">
+//// tab | Windows PowerShell
- ```console
- $ .\env\Scripts\Activate.ps1
- ```
+<div class="termy">
- </div>
+```console
+$ .\env\Scripts\Activate.ps1
+```
-=== "Windows Bash"
+</div>
+
+////
- Ou si vous utilisez Bash pour Windows (par exemple <a href="https://gitforwindows.org/" class="external-link" target="_blank">Git Bash</a>):
+//// tab | Windows Bash
- <div class="termy">
+Ou si vous utilisez Bash pour Windows (par exemple <a href="https://gitforwindows.org/" class="external-link" target="_blank">Git Bash</a>):
- ```console
- $ source ./env/Scripts/activate
- ```
+<div class="termy">
- </div>
+```console
+$ source ./env/Scripts/activate
+```
+
+</div>
+
+////
Pour vérifier que cela a fonctionné, utilisez :
-=== "Linux, macOS, Windows Bash"
+//// tab | Linux, macOS, Windows Bash
+
+<div class="termy">
+
+```console
+$ which pip
- <div class="termy">
+some/directory/fastapi/env/bin/pip
+```
- ```console
- $ which pip
+</div>
- some/directory/fastapi/env/bin/pip
- ```
+////
- </div>
+//// tab | Windows PowerShell
-=== "Windows PowerShell"
+<div class="termy">
- <div class="termy">
+```console
+$ Get-Command pip
- ```console
- $ Get-Command pip
+some/directory/fastapi/env/bin/pip
+```
- some/directory/fastapi/env/bin/pip
- ```
+</div>
- </div>
+////
Si celui-ci montre le binaire `pip` à `env/bin/pip`, alors ça a fonctionné. 🎉
-!!! tip
- Chaque fois que vous installez un nouveau paquet avec `pip` sous cet environnement, activez à nouveau l'environnement.
+/// tip
- Cela permet de s'assurer que si vous utilisez un programme terminal installé par ce paquet (comme `flit`), vous utilisez celui de votre environnement local et pas un autre qui pourrait être installé globalement.
+Chaque fois que vous installez un nouveau paquet avec `pip` sous cet environnement, activez à nouveau l'environnement.
+
+Cela permet de s'assurer que si vous utilisez un programme terminal installé par ce paquet (comme `flit`), vous utilisez celui de votre environnement local et pas un autre qui pourrait être installé globalement.
+
+///
### Flit
Et maintenant, utilisez `flit` pour installer les dépendances de développement :
-=== "Linux, macOS"
+//// tab | Linux, macOS
+
+<div class="termy">
+
+```console
+$ flit install --deps develop --symlink
- <div class="termy">
+---> 100%
+```
- ```console
- $ flit install --deps develop --symlink
+</div>
- ---> 100%
- ```
+////
- </div>
+//// tab | Windows
-=== "Windows"
+Si vous êtes sous Windows, utilisez `--pth-file` au lieu de `--symlink` :
- Si vous êtes sous Windows, utilisez `--pth-file` au lieu de `--symlink` :
+<div class="termy">
- <div class="termy">
+```console
+$ flit install --deps develop --pth-file
- ```console
- $ flit install --deps develop --pth-file
+---> 100%
+```
- ---> 100%
- ```
+</div>
- </div>
+////
Il installera toutes les dépendances et votre FastAPI local dans votre environnement local.
Et il y a des outils/scripts supplémentaires en place pour gérer les traductions dans `./scripts/docs.py`.
-!!! tip
- Vous n'avez pas besoin de voir le code dans `./scripts/docs.py`, vous l'utilisez simplement dans la ligne de commande.
+/// tip
+
+Vous n'avez pas besoin de voir le code dans `./scripts/docs.py`, vous l'utilisez simplement dans la ligne de commande.
+
+///
Toute la documentation est au format Markdown dans le répertoire `./docs/fr/`.
* Vérifiez les <a href="https://github.com/fastapi/fastapi/pulls" class="external-link" target="_blank">pull requests existantes</a> pour votre langue et ajouter des reviews demandant des changements ou les approuvant.
-!!! tip
- Vous pouvez <a href="https://help.github.com/en/github/collaborating-with-issues-and-pull-requests/commenting-on-a-pull-request" class="external-link" target="_blank">ajouter des commentaires avec des suggestions de changement</a> aux pull requests existantes.
+/// tip
+
+Vous pouvez <a href="https://help.github.com/en/github/collaborating-with-issues-and-pull-requests/commenting-on-a-pull-request" class="external-link" target="_blank">ajouter des commentaires avec des suggestions de changement</a> aux pull requests existantes.
+
+Consultez les documents concernant <a href="https://help.github.com/en/github/collaborating-with-issues-and-pull-requests/about-pull-request-reviews" class="external-link" target="_blank">l'ajout d'un review de pull request</a> pour l'approuver ou demander des modifications.
- Consultez les documents concernant <a href="https://help.github.com/en/github/collaborating-with-issues-and-pull-requests/about-pull-request-reviews" class="external-link" target="_blank">l'ajout d'un review de pull request</a> pour l'approuver ou demander des modifications.
+///
* Vérifiez dans <a href="https://github.com/fastapi/fastapi/issues" class="external-link" target="_blank">issues</a> pour voir s'il y a une personne qui coordonne les traductions pour votre langue.
Dans le cas de l'espagnol, le code à deux lettres est `es`. Ainsi, le répertoire des traductions espagnoles se trouve à l'adresse `docs/es/`.
-!!! tip
- La langue principale ("officielle") est l'anglais, qui se trouve à l'adresse "docs/en/".
+/// tip
+
+La langue principale ("officielle") est l'anglais, qui se trouve à l'adresse "docs/en/".
+
+///
Maintenant, lancez le serveur en live pour les documents en espagnol :
docs/es/docs/features.md
```
-!!! tip
- Notez que le seul changement dans le chemin et le nom du fichier est le code de langue, qui passe de `en` à `es`.
+/// tip
+
+Notez que le seul changement dans le chemin et le nom du fichier est le code de langue, qui passe de `en` à `es`.
+
+///
* Ouvrez maintenant le fichier de configuration de MkDocs pour l'anglais à
Vous pouvez maintenant vérifier dans votre éditeur de code le répertoire nouvellement créé `docs/ht/`.
-!!! tip
- Créez une première demande d'extraction à l'aide de cette fonction, afin de configurer la nouvelle langue avant d'ajouter des traductions.
+/// tip
+
+Créez une première demande d'extraction à l'aide de cette fonction, afin de configurer la nouvelle langue avant d'ajouter des traductions.
+
+Ainsi, d'autres personnes peuvent vous aider à rédiger d'autres pages pendant que vous travaillez sur la première. 🚀
- Ainsi, d'autres personnes peuvent vous aider à rédiger d'autres pages pendant que vous travaillez sur la première. 🚀
+///
Commencez par traduire la page principale, `docs/ht/index.md`.
Mais vous pouvez toujours changer et mettre à jour toutes les configurations avec des variables d'environnement ou des fichiers de configuration.
-!!! tip "Astuce"
- Pour voir toutes les configurations et options, rendez-vous sur la page de l'image Docker : <a href="https://github.com/tiangolo/uvicorn-gunicorn-fastapi-docker" class="external-link" target="_blank">tiangolo/uvicorn-gunicorn-fastapi</a>.
+/// tip | "Astuce"
+
+Pour voir toutes les configurations et options, rendez-vous sur la page de l'image Docker : <a href="https://github.com/tiangolo/uvicorn-gunicorn-fastapi-docker" class="external-link" target="_blank">tiangolo/uvicorn-gunicorn-fastapi</a>.
+
+///
## Créer un `Dockerfile`
Mais c'est beaucoup plus complexe que cela.
-!!! tip
- Si vous êtes pressé ou si cela ne vous intéresse pas, passez aux sections suivantes pour obtenir des instructions étape par étape afin de tout configurer avec différentes techniques.
+/// tip
+
+Si vous êtes pressé ou si cela ne vous intéresse pas, passez aux sections suivantes pour obtenir des instructions étape par étape afin de tout configurer avec différentes techniques.
+
+///
Pour apprendre les bases du HTTPS, du point de vue d'un utilisateur, consultez <a href="https://howhttps.works/"
class="external-link" target="_blank">https://howhttps.works/</a>.
Vous pouvez installer un serveur compatible ASGI avec :
-=== "Uvicorn"
+//// tab | Uvicorn
- * <a href="https://www.uvicorn.org/" class="external-link" target="_blank">Uvicorn</a>, un serveur ASGI rapide comme l'éclair, basé sur uvloop et httptools.
+* <a href="https://www.uvicorn.org/" class="external-link" target="_blank">Uvicorn</a>, un serveur ASGI rapide comme l'éclair, basé sur uvloop et httptools.
- <div class="termy">
+<div class="termy">
+
+```console
+$ pip install "uvicorn[standard]"
- ```console
- $ pip install "uvicorn[standard]"
+---> 100%
+```
+
+</div>
- ---> 100%
- ```
+/// tip | "Astuce"
- </div>
+En ajoutant `standard`, Uvicorn va installer et utiliser quelques dépendances supplémentaires recommandées.
- !!! tip "Astuce"
- En ajoutant `standard`, Uvicorn va installer et utiliser quelques dépendances supplémentaires recommandées.
+Cela inclut `uvloop`, le remplaçant performant de `asyncio`, qui fournit le gros gain de performance en matière de concurrence.
- Cela inclut `uvloop`, le remplaçant performant de `asyncio`, qui fournit le gros gain de performance en matière de concurrence.
+///
-=== "Hypercorn"
+////
- * <a href="https://github.com/pgjones/hypercorn" class="external-link" target="_blank">Hypercorn</a>, un serveur ASGI également compatible avec HTTP/2.
+//// tab | Hypercorn
- <div class="termy">
+* <a href="https://github.com/pgjones/hypercorn" class="external-link" target="_blank">Hypercorn</a>, un serveur ASGI également compatible avec HTTP/2.
- ```console
- $ pip install hypercorn
+<div class="termy">
+
+```console
+$ pip install hypercorn
+
+---> 100%
+```
- ---> 100%
- ```
+</div>
- </div>
+...ou tout autre serveur ASGI.
- ...ou tout autre serveur ASGI.
+////
## Exécutez le programme serveur
Vous pouvez ensuite exécuter votre application de la même manière que vous l'avez fait dans les tutoriels, mais sans l'option `--reload`, par exemple :
-=== "Uvicorn"
+//// tab | Uvicorn
- <div class="termy">
+<div class="termy">
- ```console
- $ uvicorn main:app --host 0.0.0.0 --port 80
+```console
+$ uvicorn main:app --host 0.0.0.0 --port 80
- <span style="color: green;">INFO</span>: Uvicorn running on http://0.0.0.0:80 (Press CTRL+C to quit)
- ```
+<span style="color: green;">INFO</span>: Uvicorn running on http://0.0.0.0:80 (Press CTRL+C to quit)
+```
- </div>
+</div>
+
+////
-=== "Hypercorn"
+//// tab | Hypercorn
- <div class="termy">
+<div class="termy">
+
+```console
+$ hypercorn main:app --bind 0.0.0.0:80
+
+Running on 0.0.0.0:8080 over http (CTRL + C to quit)
+```
+
+</div>
- ```console
- $ hypercorn main:app --bind 0.0.0.0:80
+////
- Running on 0.0.0.0:8080 over http (CTRL + C to quit)
- ```
+/// warning
- </div>
+N'oubliez pas de supprimer l'option `--reload` si vous l'utilisiez.
-!!! warning
- N'oubliez pas de supprimer l'option `--reload` si vous l'utilisiez.
+ L'option `--reload` consomme beaucoup plus de ressources, est plus instable, etc.
- L'option `--reload` consomme beaucoup plus de ressources, est plus instable, etc.
+ Cela aide beaucoup pendant le **développement**, mais vous **ne devriez pas** l'utiliser en **production**.
- Cela aide beaucoup pendant le **développement**, mais vous **ne devriez pas** l'utiliser en **production**.
+///
## Hypercorn avec Trio
FastAPI suit également la convention que tout changement de version "PATCH" est pour des corrections de bogues et
des changements rétrocompatibles.
-!!! tip "Astuce"
- Le "PATCH" est le dernier chiffre, par exemple, dans `0.2.3`, la version PATCH est `3`.
+/// tip | "Astuce"
+
+Le "PATCH" est le dernier chiffre, par exemple, dans `0.2.3`, la version PATCH est `3`.
+
+///
Donc, vous devriez être capable d'épingler une version comme suit :
Les changements non rétrocompatibles et les nouvelles fonctionnalités sont ajoutés dans les versions "MINOR".
-!!! tip "Astuce"
- Le "MINOR" est le numéro au milieu, par exemple, dans `0.2.3`, la version MINOR est `2`.
+/// tip | "Astuce"
+
+Le "MINOR" est le numéro au milieu, par exemple, dans `0.2.3`, la version MINOR est `2`.
+
+///
## Mise à jour des versions FastAPI
Voici une liste incomplète de certains d'entre eux.
-!!! tip "Astuce"
- Si vous avez un article, projet, outil, ou quoi que ce soit lié à **FastAPI** qui n'est actuellement pas listé ici, créez une <a href="https://github.com/fastapi/fastapi/edit/master/docs/en/data/external_links.yml" class="external-link" target="_blank">Pull Request l'ajoutant</a>.
+/// tip | "Astuce"
+
+Si vous avez un article, projet, outil, ou quoi que ce soit lié à **FastAPI** qui n'est actuellement pas listé ici, créez une <a href="https://github.com/fastapi/fastapi/edit/master/docs/en/data/external_links.yml" class="external-link" target="_blank">Pull Request l'ajoutant</a>.
+
+///
{% for section_name, section_content in external_links.items() %}
my_second_user: User = User(**second_user_data)
```
-!!! info
- `**second_user_data` signifie:
+/// info
- Utilise les clés et valeurs du dictionnaire `second_user_data` directement comme des arguments clé-valeur. C'est équivalent à: `User(id=4, name="Mary", joined="2018-11-30")`
+`**second_user_data` signifie:
+
+Utilise les clés et valeurs du dictionnaire `second_user_data` directement comme des arguments clé-valeur. C'est équivalent à: `User(id=4, name="Mary", joined="2018-11-30")`
+
+///
### Support d'éditeurs
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
{!../../../docs_src/python_types/tutorial006.py!}
```
-!!! tip "Astuce"
- Ces types internes entre crochets sont appelés des "paramètres de type".
+/// tip | "Astuce"
+
+Ces types internes entre crochets sont appelés des "paramètres de type".
+
+Ici, `str` est un paramètre de type passé à `List`.
- Ici, `str` est un paramètre de type passé à `List`.
+///
Ce qui signifie : "la variable `items` est une `list`, et chacun de ses éléments a pour type `str`.
{!../../../docs_src/python_types/tutorial011.py!}
```
-!!! info
- Pour en savoir plus à propos de <a href="https://docs.pydantic.dev/" class="external-link" target="_blank">Pydantic, allez jeter un coup d'oeil à sa documentation</a>.
+/// info
+
+Pour en savoir plus à propos de <a href="https://docs.pydantic.dev/" class="external-link" target="_blank">Pydantic, allez jeter un coup d'oeil à sa documentation</a>.
+
+///
**FastAPI** est basé entièrement sur **Pydantic**.
Ce qu'il faut retenir c'est qu'en utilisant les types standard de Python, à un seul endroit (plutôt que d'ajouter plus de classes, de décorateurs, etc.), **FastAPI** fera une grande partie du travail pour vous.
-!!! info
- Si vous avez déjà lu le tutoriel et êtes revenus ici pour voir plus sur les types, une bonne ressource est la <a href="https://mypy.readthedocs.io/en/latest/cheat_sheet_py3.html" class="external-link" target="_blank">"cheat sheet" de `mypy`</a>.
+/// info
+
+Si vous avez déjà lu le tutoriel et êtes revenus ici pour voir plus sur les types, une bonne ressource est la <a href="https://mypy.readthedocs.io/en/latest/cheat_sheet_py3.html" class="external-link" target="_blank">"cheat sheet" de `mypy`</a>.
+
+///
Vous pouvez également déclarer des paramètres body comme étant optionnels, en leur assignant une valeur par défaut à `None` :
-=== "Python 3.10+"
+//// tab | Python 3.10+
- ```Python hl_lines="18-20"
- {!> ../../../docs_src/body_multiple_params/tutorial001_an_py310.py!}
- ```
+```Python hl_lines="18-20"
+{!> ../../../docs_src/body_multiple_params/tutorial001_an_py310.py!}
+```
+
+////
-=== "Python 3.9+"
+//// tab | Python 3.9+
- ```Python hl_lines="18-20"
- {!> ../../../docs_src/body_multiple_params/tutorial001_an_py39.py!}
- ```
+```Python hl_lines="18-20"
+{!> ../../../docs_src/body_multiple_params/tutorial001_an_py39.py!}
+```
-=== "Python 3.8+"
+////
- ```Python hl_lines="19-21"
- {!> ../../../docs_src/body_multiple_params/tutorial001_an.py!}
- ```
+//// tab | Python 3.8+
+
+```Python hl_lines="19-21"
+{!> ../../../docs_src/body_multiple_params/tutorial001_an.py!}
+```
-=== "Python 3.10+ non-Annotated"
+////
- !!! tip
- Préférez utiliser la version `Annotated` si possible.
+//// tab | Python 3.10+ non-Annotated
- ```Python hl_lines="17-19"
- {!> ../../../docs_src/body_multiple_params/tutorial001_py310.py!}
- ```
+/// tip
+
+Préférez utiliser la version `Annotated` si possible.
+
+///
+
+```Python hl_lines="17-19"
+{!> ../../../docs_src/body_multiple_params/tutorial001_py310.py!}
+```
-=== "Python 3.8+ non-Annotated"
+////
- !!! tip
- Préférez utiliser la version `Annotated` si possible.
+//// tab | Python 3.8+ non-Annotated
- ```Python hl_lines="19-21"
- {!> ../../../docs_src/body_multiple_params/tutorial001.py!}
- ```
+/// tip
-!!! note
- Notez que, dans ce cas, le paramètre `item` provenant du `Body` est optionnel (sa valeur par défaut est `None`).
+Préférez utiliser la version `Annotated` si possible.
+
+///
+
+```Python hl_lines="19-21"
+{!> ../../../docs_src/body_multiple_params/tutorial001.py!}
+```
+
+////
+
+/// note
+
+Notez que, dans ce cas, le paramètre `item` provenant du `Body` est optionnel (sa valeur par défaut est `None`).
+
+///
## Paramètres multiples du body
Mais vous pouvez également déclarer plusieurs paramètres provenant de body, par exemple `item` et `user` simultanément :
-=== "Python 3.10+"
+//// tab | Python 3.10+
- ```Python hl_lines="20"
- {!> ../../../docs_src/body_multiple_params/tutorial002_py310.py!}
- ```
+```Python hl_lines="20"
+{!> ../../../docs_src/body_multiple_params/tutorial002_py310.py!}
+```
-=== "Python 3.8+"
+////
- ```Python hl_lines="22"
- {!> ../../../docs_src/body_multiple_params/tutorial002.py!}
- ```
+//// tab | Python 3.8+
+
+```Python hl_lines="22"
+{!> ../../../docs_src/body_multiple_params/tutorial002.py!}
+```
+
+////
Dans ce cas, **FastAPI** détectera qu'il y a plus d'un paramètre dans le body (chacun correspondant à un modèle Pydantic).
}
```
-!!! note
- "Notez que, bien que nous ayons déclaré le paramètre `item` de la même manière que précédemment, il est maintenant associé à la clé `item` dans le corps de la requête."`.
+/// note
+
+"Notez que, bien que nous ayons déclaré le paramètre `item` de la même manière que précédemment, il est maintenant associé à la clé `item` dans le corps de la requête."`.
+
+///
**FastAPI** effectue la conversion de la requête de façon transparente, de sorte que les objets `item` et `user` se trouvent correctement définis.
Si vous le déclarez tel quel, comme c'est une valeur [scalaire](https://docs.github.com/fr/graphql/reference/scalars), **FastAPI** supposera qu'il s'agit d'un paramètre de requête (`Query`).
Mais vous pouvez indiquer à **FastAPI** de la traiter comme une variable de body en utilisant `Body` :
-=== "Python 3.10+"
+//// tab | Python 3.10+
+
+```Python hl_lines="23"
+{!> ../../../docs_src/body_multiple_params/tutorial003_an_py310.py!}
+```
+
+////
+
+//// tab | Python 3.9+
+
+```Python hl_lines="23"
+{!> ../../../docs_src/body_multiple_params/tutorial003_an_py39.py!}
+```
+
+////
+
+//// tab | Python 3.8+
+
+```Python hl_lines="24"
+{!> ../../../docs_src/body_multiple_params/tutorial003_an.py!}
+```
+
+////
- ```Python hl_lines="23"
- {!> ../../../docs_src/body_multiple_params/tutorial003_an_py310.py!}
- ```
+//// tab | Python 3.10+ non-Annotated
-=== "Python 3.9+"
+/// tip
- ```Python hl_lines="23"
- {!> ../../../docs_src/body_multiple_params/tutorial003_an_py39.py!}
- ```
+Préférez utiliser la version `Annotated` si possible.
-=== "Python 3.8+"
+///
- ```Python hl_lines="24"
- {!> ../../../docs_src/body_multiple_params/tutorial003_an.py!}
- ```
+```Python hl_lines="20"
+{!> ../../../docs_src/body_multiple_params/tutorial003_py310.py!}
+```
+
+////
-=== "Python 3.10+ non-Annotated"
+//// tab | Python 3.8+ non-Annotated
- !!! tip
- Préférez utiliser la version `Annotated` si possible.
+/// tip
- ```Python hl_lines="20"
- {!> ../../../docs_src/body_multiple_params/tutorial003_py310.py!}
- ```
+Préférez utiliser la version `Annotated` si possible.
-=== "Python 3.8+ non-Annotated"
+///
- !!! tip
- Préférez utiliser la version `Annotated` si possible.
+```Python hl_lines="22"
+{!> ../../../docs_src/body_multiple_params/tutorial003.py!}
+```
- ```Python hl_lines="22"
- {!> ../../../docs_src/body_multiple_params/tutorial003.py!}
- ```
+////
Dans ce cas, **FastAPI** s'attendra à un body semblable à :
Par exemple :
-=== "Python 3.10+"
+//// tab | Python 3.10+
- ```Python hl_lines="27"
- {!> ../../../docs_src/body_multiple_params/tutorial004_an_py310.py!}
- ```
+```Python hl_lines="27"
+{!> ../../../docs_src/body_multiple_params/tutorial004_an_py310.py!}
+```
-=== "Python 3.9+"
+////
- ```Python hl_lines="27"
- {!> ../../../docs_src/body_multiple_params/tutorial004_an_py39.py!}
- ```
+//// tab | Python 3.9+
-=== "Python 3.8+"
+```Python hl_lines="27"
+{!> ../../../docs_src/body_multiple_params/tutorial004_an_py39.py!}
+```
+
+////
+
+//// tab | Python 3.8+
+
+```Python hl_lines="28"
+{!> ../../../docs_src/body_multiple_params/tutorial004_an.py!}
+```
- ```Python hl_lines="28"
- {!> ../../../docs_src/body_multiple_params/tutorial004_an.py!}
- ```
+////
-=== "Python 3.10+ non-Annotated"
+//// tab | Python 3.10+ non-Annotated
- !!! tip
- Préférez utiliser la version `Annotated` si possible.
+/// tip
- ```Python hl_lines="25"
- {!> ../../../docs_src/body_multiple_params/tutorial004_py310.py!}
- ```
+Préférez utiliser la version `Annotated` si possible.
-=== "Python 3.8+ non-Annotated"
+///
- !!! tip
- Préférez utiliser la version `Annotated` si possible.
+```Python hl_lines="25"
+{!> ../../../docs_src/body_multiple_params/tutorial004_py310.py!}
+```
+
+////
+
+//// tab | Python 3.8+ non-Annotated
+
+/// tip
+
+Préférez utiliser la version `Annotated` si possible.
+
+///
+
+```Python hl_lines="27"
+{!> ../../../docs_src/body_multiple_params/tutorial004.py!}
+```
- ```Python hl_lines="27"
- {!> ../../../docs_src/body_multiple_params/tutorial004.py!}
- ```
+////
-!!! info
- `Body` possède les mêmes paramètres de validation additionnels et de gestion des métadonnées que `Query` et `Path`, ainsi que d'autres que nous verrons plus tard.
+/// info
+
+`Body` possède les mêmes paramètres de validation additionnels et de gestion des métadonnées que `Query` et `Path`, ainsi que d'autres que nous verrons plus tard.
+
+///
## Inclure un paramètre imbriqué dans le body
Voici un exemple complet :
-=== "Python 3.10+"
+//// tab | Python 3.10+
+
+```Python hl_lines="17"
+{!> ../../../docs_src/body_multiple_params/tutorial005_an_py310.py!}
+```
+
+////
+
+//// tab | Python 3.9+
+
+```Python hl_lines="17"
+{!> ../../../docs_src/body_multiple_params/tutorial005_an_py39.py!}
+```
+
+////
+
+//// tab | Python 3.8+
+
+```Python hl_lines="18"
+{!> ../../../docs_src/body_multiple_params/tutorial005_an.py!}
+```
+
+////
+
+//// tab | Python 3.10+ non-Annotated
- ```Python hl_lines="17"
- {!> ../../../docs_src/body_multiple_params/tutorial005_an_py310.py!}
- ```
+/// tip
-=== "Python 3.9+"
+Préférez utiliser la version `Annotated` si possible.
- ```Python hl_lines="17"
- {!> ../../../docs_src/body_multiple_params/tutorial005_an_py39.py!}
- ```
+///
-=== "Python 3.8+"
+```Python hl_lines="15"
+{!> ../../../docs_src/body_multiple_params/tutorial005_py310.py!}
+```
- ```Python hl_lines="18"
- {!> ../../../docs_src/body_multiple_params/tutorial005_an.py!}
- ```
+////
-=== "Python 3.10+ non-Annotated"
+//// tab | Python 3.8+ non-Annotated
- !!! tip
- Préférez utiliser la version `Annotated` si possible.
+/// tip
- ```Python hl_lines="15"
- {!> ../../../docs_src/body_multiple_params/tutorial005_py310.py!}
- ```
+Préférez utiliser la version `Annotated` si possible.
-=== "Python 3.8+ non-Annotated"
+///
- !!! tip
- Préférez utiliser la version `Annotated` si possible.
+```Python hl_lines="17"
+{!> ../../../docs_src/body_multiple_params/tutorial005.py!}
+```
- ```Python hl_lines="17"
- {!> ../../../docs_src/body_multiple_params/tutorial005.py!}
- ```
+////
Dans ce cas **FastAPI** attendra un body semblable à :
Pour déclarer un corps de **requête**, on utilise les modèles de <a href="https://docs.pydantic.dev/" class="external-link" target="_blank">Pydantic</a> en profitant de tous leurs avantages et fonctionnalités.
-!!! info
- Pour envoyer de la donnée, vous devriez utiliser : `POST` (le plus populaire), `PUT`, `DELETE` ou `PATCH`.
+/// info
- Envoyer un corps dans une requête `GET` a un comportement non défini dans les spécifications, cela est néanmoins supporté par **FastAPI**, seulement pour des cas d'utilisation très complexes/extrêmes.
+Pour envoyer de la donnée, vous devriez utiliser : `POST` (le plus populaire), `PUT`, `DELETE` ou `PATCH`.
- Ceci étant découragé, la documentation interactive générée par Swagger UI ne montrera pas de documentation pour le corps d'une requête `GET`, et les proxys intermédiaires risquent de ne pas le supporter.
+Envoyer un corps dans une requête `GET` a un comportement non défini dans les spécifications, cela est néanmoins supporté par **FastAPI**, seulement pour des cas d'utilisation très complexes/extrêmes.
+
+Ceci étant découragé, la documentation interactive générée par Swagger UI ne montrera pas de documentation pour le corps d'une requête `GET`, et les proxys intermédiaires risquent de ne pas le supporter.
+
+///
## Importez le `BaseModel` de Pydantic
<img src="/img/tutorial/body/image05.png">
-!!! tip "Astuce"
- Si vous utilisez <a href="https://www.jetbrains.com/pycharm/" class="external-link" target="_blank">PyCharm</a> comme éditeur, vous pouvez utiliser le Plugin <a href="https://github.com/koxudaxi/pydantic-pycharm-plugin/" class="external-link" target="_blank">Pydantic PyCharm Plugin</a>.
+/// tip | "Astuce"
+
+Si vous utilisez <a href="https://www.jetbrains.com/pycharm/" class="external-link" target="_blank">PyCharm</a> comme éditeur, vous pouvez utiliser le Plugin <a href="https://github.com/koxudaxi/pydantic-pycharm-plugin/" class="external-link" target="_blank">Pydantic PyCharm Plugin</a>.
- Ce qui améliore le support pour les modèles Pydantic avec :
+Ce qui améliore le support pour les modèles Pydantic avec :
- * de l'auto-complétion
- * des vérifications de type
- * du "refactoring" (ou remaniement de code)
- * de la recherche
- * de l'inspection
+* de l'auto-complétion
+* des vérifications de type
+* du "refactoring" (ou remaniement de code)
+* de la recherche
+* de l'inspection
+
+///
## Utilisez le modèle
* Si le paramètre est d'un **type singulier** (comme `int`, `float`, `str`, `bool`, etc.), il sera interprété comme un paramètre de **requête**.
* Si le paramètre est déclaré comme ayant pour type un **modèle Pydantic**, il sera interprété comme faisant partie du **corps** de la requête.
-!!! note
- **FastAPI** saura que la valeur de `q` n'est pas requise grâce à la valeur par défaut `=None`.
+/// note
+
+**FastAPI** saura que la valeur de `q` n'est pas requise grâce à la valeur par défaut `=None`.
+
+Le type `Optional` dans `Optional[str]` n'est pas utilisé par **FastAPI**, mais sera utile à votre éditeur pour améliorer le support offert par ce dernier et détecter plus facilement des erreurs de type.
- Le type `Optional` dans `Optional[str]` n'est pas utilisé par **FastAPI**, mais sera utile à votre éditeur pour améliorer le support offert par ce dernier et détecter plus facilement des erreurs de type.
+///
## Sans Pydantic
ne sera pas exécutée.
-!!! info
+/// info
+
Pour plus d'informations, consultez <a href="https://docs.python.org/3/library/__main__.html" class="external-link" target="_blank">la documentation officielle de Python</a>.
+///
+
## Exécutez votre code avec votre <abbr title="En anglais: debugger">débogueur</abbr>
Parce que vous exécutez le serveur Uvicorn directement depuis votre code, vous pouvez appeler votre programme Python (votre application FastAPI) directement depuis le <abbr title="En anglais: debugger">débogueur</abbr>.
</div>
-!!! note
- La commande `uvicorn main:app` fait référence à :
+/// note
- * `main` : le fichier `main.py` (le module Python).
- * `app` : l'objet créé dans `main.py` via la ligne `app = FastAPI()`.
- * `--reload` : l'option disant à uvicorn de redémarrer le serveur à chaque changement du code. À ne pas utiliser en production !
+La commande `uvicorn main:app` fait référence à :
+
+* `main` : le fichier `main.py` (le module Python).
+* `app` : l'objet créé dans `main.py` via la ligne `app = FastAPI()`.
+* `--reload` : l'option disant à uvicorn de redémarrer le serveur à chaque changement du code. À ne pas utiliser en production !
+
+///
Vous devriez voir dans la console, une ligne semblable à la suivante :
`FastAPI` est une classe Python qui fournit toutes les fonctionnalités nécessaires au lancement de votre API.
-!!! note "Détails techniques"
- `FastAPI` est une classe héritant directement de `Starlette`.
+/// note | "Détails techniques"
+
+`FastAPI` est une classe héritant directement de `Starlette`.
- Vous pouvez donc aussi utiliser toutes les fonctionnalités de <a href="https://www.starlette.io/" class="external-link" target="_blank">Starlette</a> depuis `FastAPI`.
+Vous pouvez donc aussi utiliser toutes les fonctionnalités de <a href="https://www.starlette.io/" class="external-link" target="_blank">Starlette</a> depuis `FastAPI`.
+
+///
### Étape 2 : créer une "instance" `FastAPI`
/items/foo
```
-!!! info
- Un chemin, ou "path" est aussi souvent appelé route ou "endpoint".
+/// info
+
+Un chemin, ou "path" est aussi souvent appelé route ou "endpoint".
+///
#### Opération
* le chemin `/`
* en utilisant une <abbr title="une méthode GET HTTP">opération <code>get</code></abbr>
-!!! info "`@décorateur` Info"
- Cette syntaxe `@something` en Python est appelée un "décorateur".
+/// info | "`@décorateur` Info"
+
+Cette syntaxe `@something` en Python est appelée un "décorateur".
- Vous la mettez au dessus d'une fonction. Comme un joli chapeau décoratif (j'imagine que ce terme vient de là 🤷🏻♂).
+Vous la mettez au dessus d'une fonction. Comme un joli chapeau décoratif (j'imagine que ce terme vient de là 🤷🏻♂).
- Un "décorateur" prend la fonction en dessous et en fait quelque chose.
+Un "décorateur" prend la fonction en dessous et en fait quelque chose.
- Dans notre cas, ce décorateur dit à **FastAPI** que la fonction en dessous correspond au **chemin** `/` avec l'**opération** `get`.
+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**".
+C'est le "**décorateur d'opération de chemin**".
+
+///
Vous pouvez aussi utiliser les autres opérations :
* `@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**.
{!../../../docs_src/first_steps/tutorial003.py!}
```
-!!! 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}.
+/// 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}.
+
+///
### Étape 5 : retourner le contenu
... qui comprend également `uvicorn`, que vous pouvez utiliser comme serveur pour exécuter votre code.
-!!! note
- Vous pouvez également l'installer pièce par pièce.
+/// note
- C'est ce que vous feriez probablement une fois que vous voudrez déployer votre application en production :
+Vous pouvez également l'installer pièce par pièce.
- ```
- pip install fastapi
- ```
+C'est ce que vous feriez probablement une fois que vous voudrez déployer votre application en production :
- Installez également `uvicorn` pour qu'il fonctionne comme serveur :
+```
+pip install fastapi
+```
+
+Installez également `uvicorn` pour qu'il fonctionne comme serveur :
+
+```
+pip install uvicorn
+```
- ```
- pip install uvicorn
- ```
+Et la même chose pour chacune des dépendances facultatives que vous voulez utiliser.
- Et la même chose pour chacune des dépendances facultatives que vous voulez utiliser.
+///
## Guide utilisateur avancé
Tout d'abord, importez `Path` de `fastapi`, et importez `Annotated` :
-=== "Python 3.10+"
+//// tab | Python 3.10+
- ```Python hl_lines="1 3"
- {!> ../../../docs_src/path_params_numeric_validations/tutorial001_an_py310.py!}
- ```
+```Python hl_lines="1 3"
+{!> ../../../docs_src/path_params_numeric_validations/tutorial001_an_py310.py!}
+```
+
+////
+
+//// tab | Python 3.9+
+
+```Python hl_lines="1 3"
+{!> ../../../docs_src/path_params_numeric_validations/tutorial001_an_py39.py!}
+```
+
+////
+
+//// tab | Python 3.8+
+
+```Python hl_lines="3-4"
+{!> ../../../docs_src/path_params_numeric_validations/tutorial001_an.py!}
+```
+
+////
+
+//// tab | Python 3.10+ non-Annotated
-=== "Python 3.9+"
+/// tip
- ```Python hl_lines="1 3"
- {!> ../../../docs_src/path_params_numeric_validations/tutorial001_an_py39.py!}
- ```
+Préférez utiliser la version `Annotated` si possible.
-=== "Python 3.8+"
+///
- ```Python hl_lines="3-4"
- {!> ../../../docs_src/path_params_numeric_validations/tutorial001_an.py!}
- ```
+```Python hl_lines="1"
+{!> ../../../docs_src/path_params_numeric_validations/tutorial001_py310.py!}
+```
+
+////
+
+//// tab | Python 3.8+ non-Annotated
-=== "Python 3.10+ non-Annotated"
+/// tip
- !!! tip
- Préférez utiliser la version `Annotated` si possible.
+Préférez utiliser la version `Annotated` si possible.
- ```Python hl_lines="1"
- {!> ../../../docs_src/path_params_numeric_validations/tutorial001_py310.py!}
- ```
+///
-=== "Python 3.8+ non-Annotated"
+```Python hl_lines="3"
+{!> ../../../docs_src/path_params_numeric_validations/tutorial001.py!}
+```
+
+////
- !!! tip
- Préférez utiliser la version `Annotated` si possible.
+/// info
- ```Python hl_lines="3"
- {!> ../../../docs_src/path_params_numeric_validations/tutorial001.py!}
- ```
+FastAPI a ajouté le support pour `Annotated` (et a commencé à le recommander) dans la version 0.95.0.
-!!! info
- FastAPI a ajouté le support pour `Annotated` (et a commencé à le recommander) dans la version 0.95.0.
+Si vous avez une version plus ancienne, vous obtiendrez des erreurs en essayant d'utiliser `Annotated`.
- Si vous avez une version plus ancienne, vous obtiendrez des erreurs en essayant d'utiliser `Annotated`.
+Assurez-vous de [Mettre à jour la version de FastAPI](../deployment/versions.md#upgrading-the-fastapi-versions){.internal-link target=_blank} à la version 0.95.1 à minima avant d'utiliser `Annotated`.
- Assurez-vous de [Mettre à jour la version de FastAPI](../deployment/versions.md#upgrading-the-fastapi-versions){.internal-link target=_blank} à la version 0.95.1 à minima avant d'utiliser `Annotated`.
+///
## Déclarer des métadonnées
Par exemple, pour déclarer une valeur de métadonnée `title` pour le paramètre de chemin `item_id`, vous pouvez écrire :
-=== "Python 3.10+"
+//// tab | Python 3.10+
- ```Python hl_lines="10"
- {!> ../../../docs_src/path_params_numeric_validations/tutorial001_an_py310.py!}
- ```
+```Python hl_lines="10"
+{!> ../../../docs_src/path_params_numeric_validations/tutorial001_an_py310.py!}
+```
-=== "Python 3.9+"
+////
- ```Python hl_lines="10"
- {!> ../../../docs_src/path_params_numeric_validations/tutorial001_an_py39.py!}
- ```
+//// tab | Python 3.9+
-=== "Python 3.8+"
+```Python hl_lines="10"
+{!> ../../../docs_src/path_params_numeric_validations/tutorial001_an_py39.py!}
+```
+
+////
- ```Python hl_lines="11"
- {!> ../../../docs_src/path_params_numeric_validations/tutorial001_an.py!}
- ```
+//// tab | Python 3.8+
-=== "Python 3.10+ non-Annotated"
+```Python hl_lines="11"
+{!> ../../../docs_src/path_params_numeric_validations/tutorial001_an.py!}
+```
- !!! tip
- Préférez utiliser la version `Annotated` si possible.
+////
- ```Python hl_lines="8"
- {!> ../../../docs_src/path_params_numeric_validations/tutorial001_py310.py!}
- ```
+//// tab | Python 3.10+ non-Annotated
-=== "Python 3.8+ non-Annotated"
+/// tip
- !!! tip
- Préférez utiliser la version `Annotated` si possible.
+Préférez utiliser la version `Annotated` si possible.
- ```Python hl_lines="10"
- {!> ../../../docs_src/path_params_numeric_validations/tutorial001.py!}
- ```
+///
+
+```Python hl_lines="8"
+{!> ../../../docs_src/path_params_numeric_validations/tutorial001_py310.py!}
+```
-!!! note
- Un paramètre de chemin est toujours requis car il doit faire partie du chemin. Même si vous l'avez déclaré avec `None` ou défini une valeur par défaut, cela ne changerait rien, il serait toujours requis.
+////
+
+//// tab | Python 3.8+ non-Annotated
+
+/// tip
+
+Préférez utiliser la version `Annotated` si possible.
+
+///
+
+```Python hl_lines="10"
+{!> ../../../docs_src/path_params_numeric_validations/tutorial001.py!}
+```
+
+////
+
+/// note
+
+Un paramètre de chemin est toujours requis car il doit faire partie du chemin. Même si vous l'avez déclaré avec `None` ou défini une valeur par défaut, cela ne changerait rien, il serait toujours requis.
+
+///
## Ordonnez les paramètres comme vous le souhaitez
-!!! tip
- Ce n'est probablement pas aussi important ou nécessaire si vous utilisez `Annotated`.
+/// tip
+
+Ce n'est probablement pas aussi important ou nécessaire si vous utilisez `Annotated`.
+
+///
Disons que vous voulez déclarer le paramètre de requête `q` comme un `str` requis.
Ainsi, vous pouvez déclarer votre fonction comme suit :
-=== "Python 3.8 non-Annotated"
+//// tab | Python 3.8 non-Annotated
+
+/// tip
+
+Préférez utiliser la version `Annotated` si possible.
- !!! tip
- Préférez utiliser la version `Annotated` si possible.
+///
+
+```Python hl_lines="7"
+{!> ../../../docs_src/path_params_numeric_validations/tutorial002.py!}
+```
- ```Python hl_lines="7"
- {!> ../../../docs_src/path_params_numeric_validations/tutorial002.py!}
- ```
+////
Mais gardez à l'esprit que si vous utilisez `Annotated`, vous n'aurez pas ce problème, cela n'aura pas d'importance car vous n'utilisez pas les valeurs par défaut des paramètres de fonction pour `Query()` ou `Path()`.
-=== "Python 3.9+"
+//// tab | Python 3.9+
+
+```Python hl_lines="10"
+{!> ../../../docs_src/path_params_numeric_validations/tutorial002_an_py39.py!}
+```
- ```Python hl_lines="10"
- {!> ../../../docs_src/path_params_numeric_validations/tutorial002_an_py39.py!}
- ```
+////
-=== "Python 3.8+"
+//// tab | Python 3.8+
+
+```Python hl_lines="9"
+{!> ../../../docs_src/path_params_numeric_validations/tutorial002_an.py!}
+```
- ```Python hl_lines="9"
- {!> ../../../docs_src/path_params_numeric_validations/tutorial002_an.py!}
- ```
+////
## Ordonnez les paramètres comme vous le souhaitez (astuces)
-!!! tip
- Ce n'est probablement pas aussi important ou nécessaire si vous utilisez `Annotated`.
+/// tip
+
+Ce n'est probablement pas aussi important ou nécessaire si vous utilisez `Annotated`.
+
+///
Voici une **petite astuce** qui peut être pratique, mais vous n'en aurez pas souvent besoin.
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 `*`.
-=== "Python 3.9+"
+//// tab | Python 3.9+
+
+```Python hl_lines="10"
+{!> ../../../docs_src/path_params_numeric_validations/tutorial003_an_py39.py!}
+```
+
+////
- ```Python hl_lines="10"
- {!> ../../../docs_src/path_params_numeric_validations/tutorial003_an_py39.py!}
- ```
+//// tab | Python 3.8+
-=== "Python 3.8+"
+```Python hl_lines="9"
+{!> ../../../docs_src/path_params_numeric_validations/tutorial003_an.py!}
+```
- ```Python hl_lines="9"
- {!> ../../../docs_src/path_params_numeric_validations/tutorial003_an.py!}
- ```
+////
## Validations numériques : supérieur ou égal
Ici, avec `ge=1`, `item_id` devra être un nombre entier "`g`reater than or `e`qual" à `1`.
-=== "Python 3.9+"
+//// tab | Python 3.9+
- ```Python hl_lines="10"
- {!> ../../../docs_src/path_params_numeric_validations/tutorial004_an_py39.py!}
- ```
+```Python hl_lines="10"
+{!> ../../../docs_src/path_params_numeric_validations/tutorial004_an_py39.py!}
+```
+
+////
+
+//// tab | Python 3.8+
+
+```Python hl_lines="9"
+{!> ../../../docs_src/path_params_numeric_validations/tutorial004_an.py!}
+```
-=== "Python 3.8+"
+////
- ```Python hl_lines="9"
- {!> ../../../docs_src/path_params_numeric_validations/tutorial004_an.py!}
- ```
+//// tab | Python 3.8+ non-Annotated
-=== "Python 3.8+ non-Annotated"
+/// tip
- !!! tip
- Prefer to use the `Annotated` version if possible.
+Prefer to use the `Annotated` version if possible.
- ```Python hl_lines="8"
- {!> ../../../docs_src/path_params_numeric_validations/tutorial004.py!}
- ```
+///
+
+```Python hl_lines="8"
+{!> ../../../docs_src/path_params_numeric_validations/tutorial004.py!}
+```
+
+////
## Validations numériques : supérieur ou égal et inférieur ou égal
* `gt` : `g`reater `t`han
* `le` : `l`ess than or `e`qual
-=== "Python 3.9+"
+//// tab | Python 3.9+
+
+```Python hl_lines="10"
+{!> ../../../docs_src/path_params_numeric_validations/tutorial004_an_py39.py!}
+```
+
+////
+
+//// tab | Python 3.8+
+
+```Python hl_lines="9"
+{!> ../../../docs_src/path_params_numeric_validations/tutorial004_an.py!}
+```
+
+////
- ```Python hl_lines="10"
- {!> ../../../docs_src/path_params_numeric_validations/tutorial004_an_py39.py!}
- ```
+//// tab | Python 3.8+ non-Annotated
-=== "Python 3.8+"
+/// tip
- ```Python hl_lines="9"
- {!> ../../../docs_src/path_params_numeric_validations/tutorial004_an.py!}
- ```
+Préférez utiliser la version `Annotated` si possible.
-=== "Python 3.8+ non-Annotated"
+///
- !!! tip
- Préférez utiliser la version `Annotated` si possible.
+```Python hl_lines="8"
+{!> ../../../docs_src/path_params_numeric_validations/tutorial004.py!}
+```
- ```Python hl_lines="8"
- {!> ../../../docs_src/path_params_numeric_validations/tutorial004.py!}
- ```
+////
## Validations numériques : supérieur et inférieur ou égal
* `gt` : `g`reater `t`han
* `le` : `l`ess than or `e`qual
-=== "Python 3.9+"
+//// tab | Python 3.9+
+
+```Python hl_lines="10"
+{!> ../../../docs_src/path_params_numeric_validations/tutorial005_an_py39.py!}
+```
+
+////
+
+//// tab | Python 3.8+
- ```Python hl_lines="10"
- {!> ../../../docs_src/path_params_numeric_validations/tutorial005_an_py39.py!}
- ```
+```Python hl_lines="9"
+{!> ../../../docs_src/path_params_numeric_validations/tutorial005_an.py!}
+```
-=== "Python 3.8+"
+////
- ```Python hl_lines="9"
- {!> ../../../docs_src/path_params_numeric_validations/tutorial005_an.py!}
- ```
+//// tab | Python 3.8+ non-Annotated
-=== "Python 3.8+ non-Annotated"
+/// tip
- !!! tip
- Préférez utiliser la version `Annotated` si possible.
+Préférez utiliser la version `Annotated` si possible.
- ```Python hl_lines="9"
- {!> ../../../docs_src/path_params_numeric_validations/tutorial005.py!}
- ```
+///
+
+```Python hl_lines="9"
+{!> ../../../docs_src/path_params_numeric_validations/tutorial005.py!}
+```
+
+////
## Validations numériques : flottants, supérieur et inférieur
Et la même chose pour <abbr title="less than"><code>lt</code></abbr>.
-=== "Python 3.9+"
+//// tab | Python 3.9+
- ```Python hl_lines="13"
- {!> ../../../docs_src/path_params_numeric_validations/tutorial006_an_py39.py!}
- ```
+```Python hl_lines="13"
+{!> ../../../docs_src/path_params_numeric_validations/tutorial006_an_py39.py!}
+```
-=== "Python 3.8+"
+////
- ```Python hl_lines="12"
- {!> ../../../docs_src/path_params_numeric_validations/tutorial006_an.py!}
- ```
+//// tab | Python 3.8+
-=== "Python 3.8+ non-Annotated"
+```Python hl_lines="12"
+{!> ../../../docs_src/path_params_numeric_validations/tutorial006_an.py!}
+```
- !!! tip
- Préférez utiliser la version `Annotated` si possible.
+////
- ```Python hl_lines="11"
- {!> ../../../docs_src/path_params_numeric_validations/tutorial006.py!}
- ```
+//// tab | Python 3.8+ non-Annotated
+
+/// tip
+
+Préférez utiliser la version `Annotated` si possible.
+
+///
+
+```Python hl_lines="11"
+{!> ../../../docs_src/path_params_numeric_validations/tutorial006.py!}
+```
+
+////
## Pour résumer
* `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`.
+/// 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"
- Tous partagent les mêmes paramètres pour des validations supplémentaires et des métadonnées que vous avez vu précédemment.
+Lorsque vous importez `Query`, `Path` et d'autres de `fastapi`, ce sont en fait des fonctions.
-!!! 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.
- 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`.
- 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.
- 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.
- 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.
+///
Ici, `item_id` est déclaré comme `int`.
-!!! 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.
+/// 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.
+
+///
## <abbr title="aussi appelé sérialisation, ou parfois parsing ou marshalling en anglais">Conversion</abbr> de données
{"item_id":3}
```
-!!! check "vérifier"
- 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"`.
+/// check | "vérifier"
+
+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
+<abbr title="conversion de la chaîne de caractères venant de la requête HTTP en données Python">"parsing"</abbr> automatique.
- Grâce aux déclarations de types, **FastAPI** fournit du
- <abbr title="conversion de la chaîne de caractères venant de la requête HTTP en données Python">"parsing"</abbr> automatique.
+///
## Validation de données
<a href="http://127.0.0.1:8000/items/4.2" class="external-link" target="_blank">http://127.0.0.1:8000/items/4.2</a>.
-!!! check "vérifier"
- Donc, avec ces mêmes déclarations de type Python, **FastAPI** vous fournit de la validation de données.
+/// check | "vérifier"
- Notez que l'erreur mentionne le point exact où la validation n'a pas réussi.
+Donc, avec ces mêmes déclarations de type Python, **FastAPI** vous fournit de la validation de données.
- Ce qui est incroyablement utile au moment de développer et débugger du code qui interagit avec votre API.
+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.
+
+///
## Documentation
<img src="/img/tutorial/path-params/image01.png">
-!!! info
- À nouveau, en utilisant uniquement les déclarations de type Python, **FastAPI** vous fournit automatiquement une documentation interactive (via Swagger UI).
+/// info
+
+À nouveau, en utilisant uniquement les déclarations de type Python, **FastAPI** vous fournit automatiquement une documentation interactive (via Swagger UI).
+
+On voit bien dans la documentation que `item_id` est déclaré comme entier.
- On voit bien dans la documentation que `item_id` est déclaré comme entier.
+///
## Les avantages d'avoir une documentation basée sur une norme, et la documentation alternative.
{!../../../docs_src/path_params/tutorial005.py!}
```
-!!! info
- <a href="https://docs.python.org/3/library/enum.html" class="external-link" target="_blank">Les énumérations (ou enums) sont disponibles en Python</a> depuis la version 3.4.
+/// info
-!!! tip "Astuce"
- Pour ceux qui se demandent, "AlexNet", "ResNet", et "LeNet" sont juste des noms de <abbr title="Techniquement, des architectures de modèles">modèles</abbr> de Machine Learning.
+<a href="https://docs.python.org/3/library/enum.html" class="external-link" target="_blank">Les énumérations (ou enums) sont disponibles en Python</a> depuis la version 3.4.
+
+///
+
+/// tip | "Astuce"
+
+Pour ceux qui se demandent, "AlexNet", "ResNet", et "LeNet" sont juste des noms de <abbr title="Techniquement, des architectures de modèles">modèles</abbr> de Machine Learning.
+
+///
### Déclarer un paramètre de chemin
{!../../../docs_src/path_params/tutorial005.py!}
```
-!!! tip "Astuce"
- Vous pouvez aussi accéder la valeur `"lenet"` avec `ModelName.lenet.value`.
+/// tip | "Astuce"
+
+Vous pouvez aussi accéder la valeur `"lenet"` avec `ModelName.lenet.value`.
+
+///
#### Retourner des *membres d'énumération*
{!../../../docs_src/path_params/tutorial004.py!}
```
-!!! tip "Astuce"
- Vous pourriez avoir besoin que le paramètre contienne `/home/johndoe/myfile.txt`, avec un slash au début (`/`).
+/// tip | "Astuce"
+
+Vous pourriez avoir besoin que le paramètre contienne `/home/johndoe/myfile.txt`, avec un slash au début (`/`).
+
+Dans ce cas, l'URL serait : `/files//home/johndoe/myfile.txt`, avec un double slash (`//`) entre `files` et `home`.
- Dans ce cas, l'URL serait : `/files//home/johndoe/myfile.txt`, avec un double slash (`//`) entre `files` et `home`.
+///
## Récapitulatif
Le paramètre de requête `q` a pour type `Union[str, None]` (ou `str | None` en Python 3.10), signifiant qu'il est de type `str` mais pourrait aussi être égal à `None`, et bien sûr, la valeur par défaut est `None`, donc **FastAPI** saura qu'il n'est pas requis.
-!!! note
- **FastAPI** saura que la valeur de `q` n'est pas requise grâce à la valeur par défaut `= None`.
+/// note
- Le `Union` dans `Union[str, None]` permettra à votre éditeur de vous offrir un meilleur support et de détecter les erreurs.
+**FastAPI** saura que la valeur de `q` n'est pas requise grâce à la valeur par défaut `= None`.
+
+Le `Union` dans `Union[str, None]` permettra à votre éditeur de vous offrir un meilleur support et de détecter les erreurs.
+
+///
## Validation additionnelle
Mais déclare explicitement `q` comme étant un paramètre de requête.
-!!! info
- Gardez à l'esprit que la partie la plus importante pour rendre un paramètre optionnel est :
+/// info
- ```Python
- = None
- ```
+Gardez à l'esprit que la partie la plus importante pour rendre un paramètre optionnel est :
- ou :
+```Python
+= None
+```
- ```Python
- = Query(None)
- ```
+ou :
- et utilisera ce `None` pour détecter que ce paramètre de requête **n'est pas requis**.
+```Python
+= Query(None)
+```
+
+et utilisera ce `None` pour détecter que ce paramètre de requête **n'est pas requis**.
- Le `Union[str, None]` est uniquement là pour permettre à votre éditeur un meilleur support.
+Le `Union[str, None]` est uniquement là pour permettre à votre éditeur un meilleur support.
+
+///
Ensuite, nous pouvons passer d'autres paramètres à `Query`. Dans cet exemple, le paramètre `max_length` qui s'applique aux chaînes de caractères :
{!../../../docs_src/query_params_str_validations/tutorial005.py!}
```
-!!! note "Rappel"
- Avoir une valeur par défaut rend le paramètre optionnel.
+/// note | "Rappel"
+
+Avoir une valeur par défaut rend le paramètre optionnel.
+
+///
## Rendre ce paramètre requis
{!../../../docs_src/query_params_str_validations/tutorial006.py!}
```
-!!! info
- Si vous n'avez jamais vu ce `...` auparavant : c'est une des constantes natives de Python <a href="https://docs.python.org/fr/3/library/constants.html#Ellipsis" class="external-link" target="_blank">appelée "Ellipsis"</a>.
+/// info
+
+Si vous n'avez jamais vu ce `...` auparavant : c'est une des constantes natives de Python <a href="https://docs.python.org/fr/3/library/constants.html#Ellipsis" class="external-link" target="_blank">appelée "Ellipsis"</a>.
+
+///
Cela indiquera à **FastAPI** que la présence de ce paramètre est obligatoire.
}
```
-!!! tip "Astuce"
- Pour déclarer un paramètre de requête de type `list`, comme dans l'exemple ci-dessus, il faut explicitement utiliser `Query`, sinon cela sera interprété comme faisant partie du corps de la requête.
+/// tip | "Astuce"
+
+Pour déclarer un paramètre de requête de type `list`, comme dans l'exemple ci-dessus, il faut explicitement utiliser `Query`, sinon cela sera interprété comme faisant partie du corps de la requête.
+
+///
La documentation sera donc mise à jour automatiquement pour autoriser plusieurs valeurs :
{!../../../docs_src/query_params_str_validations/tutorial013.py!}
```
-!!! note
- Dans ce cas-là, **FastAPI** ne vérifiera pas le contenu de la liste.
+/// note
- Par exemple, `List[int]` vérifiera (et documentera) que la liste est bien entièrement composée d'entiers. Alors qu'un simple `list` ne ferait pas cette vérification.
+Dans ce cas-là, **FastAPI** ne vérifiera pas le contenu de la liste.
+
+Par exemple, `List[int]` vérifiera (et documentera) que la liste est bien entièrement composée d'entiers. Alors qu'un simple `list` ne ferait pas cette vérification.
+
+///
## Déclarer des métadonnées supplémentaires
Ces informations seront incluses dans le schéma `OpenAPI` généré et utilisées par la documentation interactive ou les outils externes utilisés.
-!!! note
- Gardez en tête que les outils externes utilisés ne supportent pas forcément tous parfaitement OpenAPI.
+/// note
+
+Gardez en tête que les outils externes utilisés ne supportent pas forcément tous parfaitement OpenAPI.
+
+Il se peut donc que certains d'entre eux n'utilisent pas toutes les métadonnées que vous avez déclarées pour le moment, bien que dans la plupart des cas, les fonctionnalités manquantes ont prévu d'être implémentées.
- Il se peut donc que certains d'entre eux n'utilisent pas toutes les métadonnées que vous avez déclarées pour le moment, bien que dans la plupart des cas, les fonctionnalités manquantes ont prévu d'être implémentées.
+///
Vous pouvez ajouter un `title` :
Ici, le paramètre `q` sera optionnel, et aura `None` comme valeur par défaut.
-!!! check "Remarque"
- On peut voir que **FastAPI** est capable de détecter que le paramètre de chemin `item_id` est un paramètre de chemin et que `q` n'en est pas un, c'est donc un paramètre de requête.
+/// check | "Remarque"
-!!! note
- **FastAPI** saura que `q` est optionnel grâce au `=None`.
+On peut voir que **FastAPI** est capable de détecter que le paramètre de chemin `item_id` est un paramètre de chemin et que `q` n'en est pas un, c'est donc un paramètre de requête.
- Le `Optional` dans `Optional[str]` n'est pas utilisé par **FastAPI** (**FastAPI** n'en utilisera que la partie `str`), mais il servira tout de même à votre éditeur de texte pour détecter des erreurs dans votre code.
+///
+/// note
+
+**FastAPI** saura que `q` est optionnel grâce au `=None`.
+
+Le `Optional` dans `Optional[str]` n'est pas utilisé par **FastAPI** (**FastAPI** n'en utilisera que la partie `str`), mais il servira tout de même à votre éditeur de texte pour détecter des erreurs dans votre code.
+
+///
## Conversion des types des paramètres de requête
* `skip`, un `int` avec comme valeur par défaut `0`.
* `limit`, un `int` optionnel.
-!!! tip "Astuce"
- Vous pouvez utiliser les `Enum`s de la même façon qu'avec les [Paramètres de chemin](path-params.md#valeurs-predefinies){.internal-link target=_blank}.
+/// tip | "Astuce"
+
+Vous pouvez utiliser les `Enum`s de la même façon qu'avec les [Paramètres de chemin](path-params.md#valeurs-predefinies){.internal-link target=_blank}.
+
+///
* Validálja hogy van egy `item_id` mező a `GET` és `PUT` kérésekben.
* Validálja hogy az `item_id` `int` típusú a `GET` és `PUT` kérésekben.
* Ha nem akkor látni fogunk egy tiszta hibát ezzel kapcsolatban.
-* ellenőrzi hogyha van egy opcionális query paraméter `q` névvel (azaz `http://127.0.0.1:8000/items/foo?q=somequery`) `GET` \1ckérések esetén.
+* ellenőrzi hogyha van egy opcionális query paraméter `q` névvel (azaz `http://127.0.0.1:8000/items/foo?q=somequery`) `GET` kérések esetén.
* Mivel a `q` paraméter `= None`-al van deklarálva, ezért opcionális.
* `None` nélkül ez a mező kötelező lenne (mint például a body `PUT` kérések esetén).
* a `/items/{item_id}` címre érkező `PUT` kérések esetén, a JSON-t a következőképpen olvassa be:
...yang juga termasuk `uvicorn`, yang dapat kamu gunakan sebagai server yang menjalankan kodemu.
-!!! note "Catatan"
- Kamu juga dapat meng-installnya bagian demi bagian.
+/// note | "Catatan"
- Hal ini mungkin yang akan kamu lakukan ketika kamu hendak menyebarkan (men-deploy) aplikasimu ke tahap produksi:
+Kamu juga dapat meng-installnya bagian demi bagian.
- ```
- pip install fastapi
- ```
+Hal ini mungkin yang akan kamu lakukan ketika kamu hendak menyebarkan (men-deploy) aplikasimu ke tahap produksi:
- Juga install `uvicorn` untuk menjalankan server"
+```
+pip install fastapi
+```
+
+Juga install `uvicorn` untuk menjalankan server"
+
+```
+pip install "uvicorn[standard]"
+```
- ```
- pip install "uvicorn[standard]"
- ```
+Dan demikian juga untuk pilihan dependensi yang hendak kamu gunakan.
- Dan demikian juga untuk pilihan dependensi yang hendak kamu gunakan.
+///
## Pedoman Pengguna Lanjutan
-
{!../../../docs/missing-translation.md!}
{!../../../docs_src/additional_status_codes/tutorial001.py!}
```
-!!! 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ドキュメント
そしてもし、`Response` が、`JSONResponse` や `UJSONResponse` の場合のようにJSONメディアタイプ (`application/json`) ならば、データは *path operationデコレータ* に宣言したPydantic `response_model` により自動的に変換 (もしくはフィルタ) されます。
-!!! note "備考"
- メディアタイプを指定せずにレスポンスクラスを利用すると、FastAPIは何もコンテンツがないことを期待します。そのため、生成されるOpenAPIドキュメントにレスポンスフォーマットが記載されません。
+/// note | "備考"
+
+メディアタイプを指定せずにレスポンスクラスを利用すると、FastAPIは何もコンテンツがないことを期待します。そのため、生成されるOpenAPIドキュメントにレスポンスフォーマットが記載されません。
+
+///
## `ORJSONResponse` を使う
{!../../../docs_src/custom_response/tutorial001b.py!}
```
-!!! info "情報"
- パラメータ `response_class` は、レスポンスの「メディアタイプ」を定義するために利用することもできます。
+/// info | "情報"
+
+パラメータ `response_class` は、レスポンスの「メディアタイプ」を定義するために利用することもできます。
+
+この場合、HTTPヘッダー `Content-Type` には `application/json` がセットされます。
+
+そして、OpenAPIにはそのようにドキュメントされます。
+
+///
- この場合、HTTPヘッダー `Content-Type` には `application/json` がセットされます。
+/// tip | "豆知識"
- そして、OpenAPIにはそのようにドキュメントされます。
+`ORJSONResponse` は、現在はFastAPIのみで利用可能で、Starletteでは利用できません。
-!!! tip "豆知識"
- `ORJSONResponse` は、現在はFastAPIのみで利用可能で、Starletteでは利用できません。
+///
## HTMLレスポンス
{!../../../docs_src/custom_response/tutorial002.py!}
```
-!!! info "情報"
- パラメータ `response_class` は、レスポンスの「メディアタイプ」を定義するために利用されます。
+/// info | "情報"
- この場合、HTTPヘッダー `Content-Type` には `text/html` がセットされます。
+パラメータ `response_class` は、レスポンスの「メディアタイプ」を定義するために利用されます。
- そして、OpenAPIにはそのようにドキュメント化されます。
+この場合、HTTPヘッダー `Content-Type` には `text/html` がセットされます。
+
+そして、OpenAPIにはそのようにドキュメント化されます。
+
+///
### `Response` を返す
{!../../../docs_src/custom_response/tutorial003.py!}
```
-!!! warning "注意"
- *path operation関数* から直接返される `Response` は、OpenAPIにドキュメントされず (例えば、 `Content-Type` がドキュメントされない) 、自動的な対話的ドキュメントからも閲覧できません。
+/// warning | "注意"
+
+*path operation関数* から直接返される `Response` は、OpenAPIにドキュメントされず (例えば、 `Content-Type` がドキュメントされない) 、自動的な対話的ドキュメントからも閲覧できません。
+
+///
+
+/// info | "情報"
-!!! info "情報"
- もちろん、実際の `Content-Type` ヘッダーやステータスコードなどは、返された `Response` オブジェクトに由来しています。
+もちろん、実際の `Content-Type` ヘッダーやステータスコードなどは、返された `Response` オブジェクトに由来しています。
+
+///
### OpenAPIドキュメントと `Response` のオーバーライド
`Response` を使って他の何かを返せますし、カスタムのサブクラスも作れることを覚えておいてください。
-!!! note "技術詳細"
- `from starlette.responses import HTMLResponse` も利用できます。
+/// note | "技術詳細"
+
+`from starlette.responses import HTMLResponse` も利用できます。
+
+**FastAPI** は開発者の利便性のために `fastapi.responses` として `starlette.responses` と同じものを提供しています。しかし、利用可能なレスポンスのほとんどはStarletteから直接提供されます。
- **FastAPI** は開発者の利便性のために `fastapi.responses` として `starlette.responses` と同じものを提供しています。しかし、利用可能なレスポンスのほとんどはStarletteから直接提供されます。
+///
### `Response`
<a href="https://github.com/ultrajson/ultrajson" class="external-link" target="_blank">`ujson`</a>を使った、代替のJSONレスポンスです。
-!!! warning "注意"
- `ujson` は、いくつかのエッジケースの取り扱いについて、Pythonにビルトインされた実装よりも作りこまれていません。
+/// warning | "注意"
+
+`ujson` は、いくつかのエッジケースの取り扱いについて、Pythonにビルトインされた実装よりも作りこまれていません。
+
+///
```Python hl_lines="2 7"
{!../../../docs_src/custom_response/tutorial001.py!}
```
-!!! tip "豆知識"
- `ORJSONResponse` のほうが高速な代替かもしれません。
+/// tip | "豆知識"
+
+`ORJSONResponse` のほうが高速な代替かもしれません。
+
+///
### `RedirectResponse`
{!../../../docs_src/custom_response/tutorial008.py!}
```
-!!! tip "豆知識"
- ここでは `async` や `await` をサポートしていない標準の `open()` を使っているので、通常の `def` でpath operationを宣言していることに注意してください。
+/// tip | "豆知識"
+
+ここでは `async` や `await` をサポートしていない標準の `open()` を使っているので、通常の `def` でpath operationを宣言していることに注意してください。
+
+///
### `FileResponse`
{!../../../docs_src/custom_response/tutorial010.py!}
```
-!!! tip "豆知識"
- 前に見たように、 *path operation* の中で `response_class` をオーバーライドできます。
+/// tip | "豆知識"
+
+前に見たように、 *path operation* の中で `response_class` をオーバーライドできます。
+
+///
## その他のドキュメント
以降のセクションでは、チュートリアルでは説明しきれなかったオプションや設定、および機能について説明します。
-!!! tip "豆知識"
- 以降のセクションは、 **必ずしも"応用編"ではありません**。
+/// tip | "豆知識"
- ユースケースによっては、その中から解決策を見つけられるかもしれません。
+以降のセクションは、 **必ずしも"応用編"ではありません**。
+
+ユースケースによっては、その中から解決策を見つけられるかもしれません。
+
+///
## 先にチュートリアルを読む
## OpenAPI operationId
-!!! warning "注意"
- あなたがOpenAPIの「エキスパート」でなければ、これは必要ないかもしれません。
+/// warning | "注意"
+
+あなたがOpenAPIの「エキスパート」でなければ、これは必要ないかもしれません。
+
+///
*path operation* で `operation_id` パラメータを利用することで、OpenAPIの `operationId` を設定できます。
{!../../../docs_src/path_operation_advanced_configuration/tutorial002.py!}
```
-!!! tip "豆知識"
- `app.openapi()` を手動でコールする場合、その前に`operationId`を更新する必要があります。
+/// tip | "豆知識"
+
+`app.openapi()` を手動でコールする場合、その前に`operationId`を更新する必要があります。
+
+///
+
+/// warning | "注意"
+
+この方法をとる場合、各 *path operation関数* が一意な名前である必要があります。
-!!! warning "注意"
- この方法をとる場合、各 *path operation関数* が一意な名前である必要があります。
+それらが異なるモジュール (Pythonファイル) にあるとしてもです。
- それらが異なるモジュール (Pythonファイル) にあるとしてもです。
+///
## OpenAPIから除外する
実際は、`Response` やそのサブクラスを返すことができます。
-!!! tip "豆知識"
- `JSONResponse` それ自体は、 `Response` のサブクラスです。
+/// tip | "豆知識"
+
+`JSONResponse` それ自体は、 `Response` のサブクラスです。
+
+///
`Response` を返した場合は、**FastAPI** は直接それを返します。
{!../../../docs_src/response_directly/tutorial001.py!}
```
-!!! 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` を返す
{!../../../docs_src/websockets/tutorial001.py!}
```
-!!! note "技術詳細"
- `from starlette.websockets import WebSocket` を使用しても構いません.
+/// note | "技術詳細"
- **FastAPI** は開発者の利便性のために、同じ `WebSocket` を提供します。しかし、こちらはStarletteから直接提供されるものです。
+`from starlette.websockets import WebSocket` を使用しても構いません.
+
+**FastAPI** は開発者の利便性のために、同じ `WebSocket` を提供します。しかし、こちらはStarletteから直接提供されるものです。
+
+///
## メッセージの送受信
{!../../../docs_src/websockets/tutorial002.py!}
```
-!!! info "情報"
- WebSocket で `HTTPException` を発生させることはあまり意味がありません。したがって、WebSocketの接続を直接閉じる方がよいでしょう。
+/// info | "情報"
+
+WebSocket で `HTTPException` を発生させることはあまり意味がありません。したがって、WebSocketの接続を直接閉じる方がよいでしょう。
+
+クロージングコードは、<a href="https://tools.ietf.org/html/rfc6455#section-7.4.1" class="external-link" target="_blank">仕様で定義された有効なコード</a>の中から使用することができます。
- クロージングコードは、<a href="https://tools.ietf.org/html/rfc6455#section-7.4.1" class="external-link" target="_blank">仕様で定義された有効なコード</a>の中から使用することができます。
+将来的には、どこからでも `raise` できる `WebSocketException` が用意され、専用の例外ハンドラを追加できるようになる予定です。これは、Starlette の <a href="https://github.com/encode/starlette/pull/527" class="external-link" target="_blank">PR #527</a> に依存するものです。
- 将来的には、どこからでも `raise` できる `WebSocketException` が用意され、専用の例外ハンドラを追加できるようになる予定です。これは、Starlette の <a href="https://github.com/encode/starlette/pull/527" class="external-link" target="_blank">PR #527</a> に依存するものです。
+///
### 依存関係を用いてWebSocketsを試してみる
* パスで使用される「Item ID」
* クエリパラメータとして使用される「Token」
-!!! tip "豆知識"
- クエリ `token` は依存パッケージによって処理されることに注意してください。
+/// tip | "豆知識"
+
+クエリ `token` は依存パッケージによって処理されることに注意してください。
+
+///
これにより、WebSocketに接続してメッセージを送受信できます。
Client #1596980209979 left the chat
```
-!!! tip "豆知識"
- 上記のアプリは、複数の WebSocket 接続に対してメッセージを処理し、ブロードキャストする方法を示すための最小限のシンプルな例です。
+/// tip | "豆知識"
+
+上記のアプリは、複数の WebSocket 接続に対してメッセージを処理し、ブロードキャストする方法を示すための最小限のシンプルな例です。
+
+しかし、すべての接続がメモリ内の単一のリストで処理されるため、プロセスの実行中にのみ機能し、単一のプロセスでのみ機能することに注意してください。
- しかし、すべての接続がメモリ内の単一のリストで処理されるため、プロセスの実行中にのみ機能し、単一のプロセスでのみ機能することに注意してください。
+もしFastAPIと簡単に統合できて、RedisやPostgreSQLなどでサポートされている、より堅牢なものが必要なら、<a href="https://github.com/encode/broadcaster" class="external-link" target="_blank">encode/broadcaster</a> を確認してください。
- もしFastAPIと簡単に統合できて、RedisやPostgreSQLなどでサポートされている、より堅牢なものが必要なら、<a href="https://github.com/encode/broadcaster" class="external-link" target="_blank">encode/broadcaster</a> を確認してください。
+///
## その他のドキュメント
これは**自動的な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ユーザーインターフェースを持っている点。
+
+///
### <a href="http://flask.pocoo.org/" class="external-link" target="_blank">Flask</a>
Flaskのシンプルさを考えると、APIを構築するのに適しているように思えました。次に見つけるべきは、Flask 用の「Django REST Framework」でした。
-!!! check "**FastAPI**へ与えたインスピレーション"
- マイクロフレームワークであること。ツールやパーツを目的に合うように簡単に組み合わせられる点。
+/// check | "**FastAPI**へ与えたインスピレーション"
+
+マイクロフレームワークであること。ツールやパーツを目的に合うように簡単に組み合わせられる点。
- シンプルで簡単なルーティングの仕組みを持っている点。
+シンプルで簡単なルーティングの仕組みを持っている点。
+///
### <a href="http://docs.python-requests.org" class="external-link" target="_blank">Requests</a>
`requests.get(...)` と`@app.get(...)` には類似点が見受けられます。
-!!! check "**FastAPI**へ与えたインスピレーション"
- * シンプルで直感的なAPIを持っている点。
- * HTTPメソッド名を直接利用し、単純で直感的である。
- * 適切なデフォルト値を持ちつつ、強力なカスタマイズ性を持っている。
+/// check | "**FastAPI**へ与えたインスピレーション"
+
+* シンプルで直感的なAPIを持っている点。
+* HTTPメソッド名を直接利用し、単純で直感的である。
+* 適切なデフォルト値を持ちつつ、強力なカスタマイズ性を持っている。
+///
### <a href="https://swagger.io/" class="external-link" target="_blank">Swagger</a> / <a href="https://github.com/OAI/OpenAPI-Specification/" class="external-link" target="_blank">OpenAPI</a>
そのため、バージョン2.0では「Swagger」、バージョン3以上では「OpenAPI」と表記するのが一般的です。
-!!! check "**FastAPI**へ与えたインスピレーション"
- 独自のスキーマの代わりに、API仕様のオープンな標準を採用しました。
+/// check | "**FastAPI**へ与えたインスピレーション"
- そして、標準に基づくユーザーインターフェースツールを統合しています。
+独自のスキーマの代わりに、API仕様のオープンな標準を採用しました。
- * <a href="https://github.com/swagger-api/swagger-ui" class="external-link" target="_blank">Swagger UI</a>
- * <a href="https://github.com/Rebilly/ReDoc" class="external-link" target="_blank">ReDoc</a>
+そして、標準に基づくユーザーインターフェースツールを統合しています。
- この二つは人気で安定したものとして選択されましたが、少し検索してみると、 (**FastAPI**と同時に使用できる) OpenAPIのための多くの代替となるツールを見つけることができます。
+* <a href="https://github.com/swagger-api/swagger-ui" class="external-link" target="_blank">Swagger UI</a>
+* <a href="https://github.com/Rebilly/ReDoc" class="external-link" target="_blank">ReDoc</a>
+
+この二つは人気で安定したものとして選択されましたが、少し検索してみると、 (**FastAPI**と同時に使用できる) OpenAPIのための多くの代替となるツールを見つけることができます。
+
+///
### Flask REST フレームワーク
しかし、それはPythonの型ヒントが存在する前に作られたものです。そのため、すべての<abbr title="データがどのように形成されるべきかの定義">スキーマ</abbr>を定義するためには、Marshmallowが提供する特定のユーティリティやクラスを使用する必要があります。
-!!! check "**FastAPI**へ与えたインスピレーション"
- コードで「スキーマ」を定義し、データの型やバリデーションを自動で提供する点。
+/// check | "**FastAPI**へ与えたインスピレーション"
+
+コードで「スキーマ」を定義し、データの型やバリデーションを自動で提供する点。
+
+///
### <a href="https://webargs.readthedocs.io/en/latest/" class="external-link" target="_blank">Webargs</a>
素晴らしいツールで、私も**FastAPI**を持つ前はよく使っていました。
-!!! info "情報"
- Webargsは、Marshmallowと同じ開発者により作られました。
+/// info | "情報"
+
+Webargsは、Marshmallowと同じ開発者により作られました。
+
+///
-!!! check "**FastAPI**へ与えたインスピレーション"
- 受信したデータに対する自動的なバリデーションを持っている点。
+/// check | "**FastAPI**へ与えたインスピレーション"
+
+受信したデータに対する自動的なバリデーションを持っている点。
+
+///
### <a href="https://apispec.readthedocs.io/en/stable/" class="external-link" target="_blank">APISpec</a>
エディタでは、この問題を解決することはできません。また、パラメータやMarshmallowスキーマを変更したときに、YAMLのdocstringを変更するのを忘れてしまうと、生成されたスキーマが古くなってしまいます。
-!!! info "情報"
- APISpecは、Marshmallowと同じ開発者により作成されました。
+/// info | "情報"
+
+APISpecは、Marshmallowと同じ開発者により作成されました。
+
+///
+
+/// check | "**FastAPI**へ与えたインスピレーション"
+
+OpenAPIという、APIについてのオープンな標準をサポートしている点。
-!!! check "**FastAPI**へ与えたインスピレーション"
- OpenAPIという、APIについてのオープンな標準をサポートしている点。
+///
### <a href="https://flask-apispec.readthedocs.io/en/latest/" class="external-link" target="_blank">Flask-apispec</a>
そして、これらのフルスタックジェネレーターは、[**FastAPI** Project Generators](project-generation.md){.internal-link target=_blank}の元となっていました。
-!!! info "情報"
- Flask-apispecはMarshmallowと同じ開発者により作成されました。
+/// info | "情報"
-!!! check "**FastAPI**へ与えたインスピレーション"
- シリアライゼーションとバリデーションを定義したコードから、OpenAPIスキーマを自動的に生成する点。
+Flask-apispecはMarshmallowと同じ開発者により作成されました。
+
+///
+
+/// check | "**FastAPI**へ与えたインスピレーション"
+
+シリアライゼーションとバリデーションを定義したコードから、OpenAPIスキーマを自動的に生成する点。
+
+///
### <a href="https://nestjs.com/" class="external-link" target="_blank">NestJS</a> (と<a href="https://angular.io/" class="external-link" target="_blank">Angular</a>)
入れ子になったモデルをうまく扱えません。そのため、リクエストのJSONボディが内部フィールドを持つJSONオブジェクトで、それが順番にネストされたJSONオブジェクトになっている場合、適切にドキュメント化やバリデーションをすることができません。
-!!! check "**FastAPI**へ与えたインスピレーション"
- 素晴らしいエディターの補助を得るために、Pythonの型ヒントを利用している点。
+/// check | "**FastAPI**へ与えたインスピレーション"
+
+素晴らしいエディターの補助を得るために、Pythonの型ヒントを利用している点。
+
+強力な依存性注入の仕組みを持ち、コードの繰り返しを最小化する方法を見つけた点。
- 強力な依存性注入の仕組みを持ち、コードの繰り返しを最小化する方法を見つけた点。
+///
### <a href="https://sanic.readthedocs.io/en/latest/" class="external-link" target="_blank">Sanic</a>
`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に基づいている理由です。
+
+///
### <a href="https://falconframework.org/" class="external-link" target="_blank">Falcon</a>
そのため、データのバリデーション、シリアライゼーション、ドキュメント化は、自動的にできずコードの中で行わなければなりません。あるいは、HugのようにFalconの上にフレームワークとして実装されなければなりません。このような分断は、パラメータとして1つのリクエストオブジェクトと1つのレスポンスオブジェクトを持つというFalconのデザインにインスピレーションを受けた他のフレームワークでも起こります。
-!!! check "**FastAPI**へ与えたインスピレーション"
- 素晴らしい性能を得るための方法を見つけた点。
+/// check | "**FastAPI**へ与えたインスピレーション"
+
+素晴らしい性能を得るための方法を見つけた点。
+
+Hug (HugはFalconをベースにしています) と一緒に、**FastAPI**が`response`引数を関数に持つことにインスピレーションを与えました。
- Hug (HugはFalconをベースにしています) と一緒に、**FastAPI**が`response`引数を関数に持つことにインスピレーションを与えました。
+**FastAPI**では任意ですが、ヘッダーやCookieやステータスコードを設定するために利用されています。
- **FastAPI**では任意ですが、ヘッダーやCookieやステータスコードを設定するために利用されています。
+///
### <a href="https://moltenframework.com/" class="external-link" target="_blank">Molten</a>
ルーティングは一つの場所で宣言され、他の場所で宣言された関数を使用します (エンドポイントを扱う関数のすぐ上に配置できるデコレータを使用するのではなく) 。これはFlask (やStarlette) よりも、Djangoに近いです。これは、比較的緊密に結合されているものをコードの中で分離しています。
-!!! check "**FastAPI**へ与えたインスピレーション"
- モデルの属性の「デフォルト」値を使用したデータ型の追加バリデーションを定義します。これはエディタの補助を改善するもので、以前はPydanticでは利用できませんでした。
+/// check | "**FastAPI**へ与えたインスピレーション"
- 同様の方法でのバリデーションの宣言をサポートするよう、Pydanticを部分的にアップデートするインスピーレションを与えました。(現在はこれらの機能は全てPydanticで可能となっています。)
+モデルの属性の「デフォルト」値を使用したデータ型の追加バリデーションを定義します。これはエディタの補助を改善するもので、以前はPydanticでは利用できませんでした。
+
+同様の方法でのバリデーションの宣言をサポートするよう、Pydanticを部分的にアップデートするインスピーレションを与えました。(現在はこれらの機能は全てPydanticで可能となっています。)
+
+///
### <a href="http://www.hug.rest/" class="external-link" target="_blank">Hug</a>
以前のPythonの同期型Webフレームワーク標準 (WSGI) をベースにしているため、Websocketなどは扱えませんが、それでも高性能です。
-!!! info "情報"
- HugはTimothy Crosleyにより作成されました。彼は<a href="https://github.com/timothycrosley/isort" class="external-link" target="_blank">`isort`</a>など、Pythonのファイル内のインポートの並び替えを自動的におこうなう素晴らしいツールの開発者です。
+/// info | "情報"
+
+HugはTimothy Crosleyにより作成されました。彼は<a href="https://github.com/timothycrosley/isort" class="external-link" target="_blank">`isort`</a>など、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`引数を宣言することにインスピレーションを与えました。
+///
### <a href="https://github.com/encode/apistar" class="external-link" target="_blank">APIStar</a> (<= 0.5)
今では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**が利用しているもの
Marshmallowに匹敵しますが、ベンチマークではMarshmallowよりも高速です。また、Pythonの型ヒントを元にしているので、エディタの補助が素晴らしいです。
-!!! check "**FastAPI**での使用用途"
- データのバリデーション、データのシリアライゼーション、自動的なモデルの (JSON Schemaに基づいた) ドキュメント化の全てを扱えます。
+/// check | "**FastAPI**での使用用途"
+
+データのバリデーション、データのシリアライゼーション、自動的なモデルの (JSON Schemaに基づいた) ドキュメント化の全てを扱えます。
+
+**FastAPI**はJSON SchemaのデータをOpenAPIに利用します。
- **FastAPI**はJSON SchemaのデータをOpenAPIに利用します。
+///
### <a href="https://www.starlette.io/" class="external-link" target="_blank">Starlette</a>
これは **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**で直接可能です。
+
+///
### <a href="https://www.uvicorn.org/" class="external-link" target="_blank">Uvicorn</a>
Starletteや**FastAPI**のサーバーとして推奨されています。
-!!! check "**FastAPI**が推奨する理由"
- **FastAPI**アプリケーションを実行するメインのウェブサーバーである点。
+/// check | "**FastAPI**が推奨する理由"
+
+**FastAPI**アプリケーションを実行するメインのウェブサーバーである点。
+
+Gunicornと組み合わせることで、非同期でマルチプロセスなサーバーを持つことがきます。
- Gunicornと組み合わせることで、非同期でマルチプロセスなサーバーを持つことがきます。
+詳細は[デプロイ](deployment/index.md){.internal-link target=_blank}の項目で確認してください。
- 詳細は[デプロイ](deployment/index.md){.internal-link target=_blank}の項目で確認してください。
+///
## ベンチマーク と スピード
return results
```
-!!! note "備考"
- `async def` を使用して作成された関数の内部でしか `await` は使用できません。
+/// note | "備考"
+
+`async def` を使用して作成された関数の内部でしか `await` は使用できません。
+
+///
---
## 非常に発展的な技術的詳細
-!!! warning "注意"
- 恐らくスキップしても良いでしょう。
+/// warning | "注意"
+
+恐らくスキップしても良いでしょう。
+
+この部分は**FastAPI**の仕組みに関する非常に技術的な詳細です。
- この部分は**FastAPI**の仕組みに関する非常に技術的な詳細です。
+かなりの技術知識 (コルーチン、スレッド、ブロッキングなど) があり、FastAPIが `async def` と通常の `def` をどのように処理するか知りたい場合は、先に進んでください。
- かなりの技術知識 (コルーチン、スレッド、ブロッキングなど) があり、FastAPIが `async def` と通常の `def` をどのように処理するか知りたい場合は、先に進んでください。
+///
### Path operation 関数
新しい環境を有効化するには:
-=== "Linux, macOS"
+//// tab | Linux, macOS
- <div class="termy">
+<div class="termy">
- ```console
- $ source ./env/bin/activate
- ```
+```console
+$ source ./env/bin/activate
+```
- </div>
+</div>
-=== "Windows PowerShell"
+////
- <div class="termy">
+//// tab | Windows PowerShell
- ```console
- $ .\env\Scripts\Activate.ps1
- ```
+<div class="termy">
- </div>
+```console
+$ .\env\Scripts\Activate.ps1
+```
-=== "Windows Bash"
+</div>
- もしwindows用のBash (例えば、<a href="https://gitforwindows.org/" class="external-link" target="_blank">Git Bash</a>)を使っているなら:
+////
- <div class="termy">
+//// tab | Windows Bash
- ```console
- $ source ./env/Scripts/activate
- ```
+もしwindows用のBash (例えば、<a href="https://gitforwindows.org/" class="external-link" target="_blank">Git Bash</a>)を使っているなら:
- </div>
+<div class="termy">
+
+```console
+$ source ./env/Scripts/activate
+```
+
+</div>
+
+////
動作の確認には、下記を実行します:
-=== "Linux, macOS, Windows Bash"
+//// tab | Linux, macOS, Windows Bash
- <div class="termy">
+<div class="termy">
- ```console
- $ which pip
+```console
+$ which pip
- some/directory/fastapi/env/bin/pip
- ```
+some/directory/fastapi/env/bin/pip
+```
- </div>
+</div>
-=== "Windows PowerShell"
+////
- <div class="termy">
+//// tab | Windows PowerShell
- ```console
- $ Get-Command pip
+<div class="termy">
- some/directory/fastapi/env/bin/pip
- ```
+```console
+$ Get-Command pip
- </div>
+some/directory/fastapi/env/bin/pip
+```
+
+</div>
+
+////
`env/bin/pip`に`pip`バイナリが表示される場合は、正常に機能しています。🎉
-!!! tip "豆知識"
- この環境で`pip`を使って新しいパッケージをインストールするたびに、仮想環境を再度有効化します。
+/// tip | "豆知識"
+
+この環境で`pip`を使って新しいパッケージをインストールするたびに、仮想環境を再度有効化します。
- これにより、そのパッケージによってインストールされたターミナルのプログラム を使用する場合、ローカル環境のものを使用し、グローバルにインストールされたものは使用されなくなります。
+これにより、そのパッケージによってインストールされたターミナルのプログラム を使用する場合、ローカル環境のものを使用し、グローバルにインストールされたものは使用されなくなります。
+
+///
### pip
そして、翻訳を処理するためのツール/スクリプトが、`./scripts/docs.py`に用意されています。
-!!! tip "豆知識"
- `./scripts/docs.py`のコードを見る必要はなく、コマンドラインからただ使うだけです。
+/// tip | "豆知識"
+
+`./scripts/docs.py`のコードを見る必要はなく、コマンドラインからただ使うだけです。
+
+///
すべてのドキュメントが、Markdown形式で`./docs/en/`ディレクトリにあります。
* あなたの言語の<a href="https://github.com/fastapi/fastapi/pulls" class="external-link" target="_blank">今あるプルリクエスト</a>を確認し、変更や承認をするレビューを追加します。
-!!! tip "豆知識"
- すでにあるプルリクエストに<a href="https://help.github.com/en/github/collaborating-with-issues-and-pull-requests/commenting-on-a-pull-request" class="external-link" target="_blank">修正提案つきのコメントを追加</a>できます。
+/// tip | "豆知識"
+
+すでにあるプルリクエストに<a href="https://help.github.com/en/github/collaborating-with-issues-and-pull-requests/commenting-on-a-pull-request" class="external-link" target="_blank">修正提案つきのコメントを追加</a>できます。
+
+修正提案の承認のために<a href="https://help.github.com/en/github/collaborating-with-issues-and-pull-requests/about-pull-request-reviews" class="external-link" target="_blank">プルリクエストのレビューの追加</a>のドキュメントを確認してください。
- 修正提案の承認のために<a href="https://help.github.com/en/github/collaborating-with-issues-and-pull-requests/about-pull-request-reviews" class="external-link" target="_blank">プルリクエストのレビューの追加</a>のドキュメントを確認してください。
+///
* <a href="https://github.com/fastapi/fastapi/issues" class="external-link" target="_blank">issues</a>をチェックして、あなたの言語に対応する翻訳があるかどうかを確認してください。
スペイン語の場合、2文字のコードは`es`です。したがって、スペイン語のディレクトリは`docs/es/`です。
-!!! tip "豆知識"
- メイン (「公式」) 言語は英語で、`docs/en/`にあります。
+/// tip | "豆知識"
+
+メイン (「公式」) 言語は英語で、`docs/en/`にあります。
+
+///
次に、ドキュメントのライブサーバーをスペイン語で実行します:
docs/es/docs/features.md
```
-!!! tip "豆知識"
- パスとファイル名の変更は、`en`から`es`への言語コードだけであることに注意してください。
+/// tip | "豆知識"
+
+パスとファイル名の変更は、`en`から`es`への言語コードだけであることに注意してください。
+
+///
* ここで、英語のMkDocs構成ファイルを開きます:
これで、新しく作成された`docs/ht/`ディレクトリをコードエディターから確認できます。
-!!! tip "豆知識"
- 翻訳を追加する前に、これだけで最初のプルリクエストを作成し、新しい言語の設定をセットアップします。
+/// tip | "豆知識"
+
+翻訳を追加する前に、これだけで最初のプルリクエストを作成し、新しい言語の設定をセットアップします。
+
+そうすることで、最初のページで作業している間、誰かの他のページの作業を助けることができます。 🚀
- そうすることで、最初のページで作業している間、誰かの他のページの作業を助けることができます。 🚀
+///
まず、メインページの`docs/ht/index.md`を翻訳します。
しかし、実行中の**プロセス**をクラッシュさせるような本当にひどいエラーの場合、少なくとも2〜3回ほどプロセスを**再起動**させる外部コンポーネントが必要でしょう。
-!!! tip
- ...とはいえ、アプリケーション全体が**すぐにクラッシュする**のであれば、いつまでも再起動し続けるのは意味がないでしょう。しかし、その場合はおそらく開発中か少なくともデプロイ直後に気づくと思われます。
+/// tip
- そこで、**将来**クラッシュする可能性があり、それでも再スタートさせることに意味があるような、主なケースに焦点を当ててみます。
+...とはいえ、アプリケーション全体が**すぐにクラッシュする**のであれば、いつまでも再起動し続けるのは意味がないでしょう。しかし、その場合はおそらく開発中か少なくともデプロイ直後に気づくと思われます。
+
+そこで、**将来**クラッシュする可能性があり、それでも再スタートさせることに意味があるような、主なケースに焦点を当ててみます。
+
+///
あなたはおそらく**外部コンポーネント**がアプリケーションの再起動を担当することを望むと考えます。 なぜなら、その時点でUvicornとPythonを使った同じアプリケーションはすでにクラッシュしており、同じアプリケーションの同じコードに対して何もできないためです。
* **クラウド・サービス**によるレプリケーション
* クラウド・サービスはおそらく**あなたのためにレプリケーションを処理**します。**実行するプロセス**や使用する**コンテナイメージ**を定義できるかもしれませんが、いずれにせよ、それはおそらく**単一のUvicornプロセス**であり、クラウドサービスはそのレプリケーションを担当するでしょう。
-!!! tip
- これらの**コンテナ**やDockerそしてKubernetesに関する項目が、まだあまり意味をなしていなくても心配しないでください。
- <!-- NOTE: the current version of docker.md is outdated compared to English one. -->
+/// tip
+
+これらの**コンテナ**やDockerそしてKubernetesに関する項目が、まだあまり意味をなしていなくても心配しないでください。
+<!-- NOTE: the current version of docker.md is outdated compared to English one. -->
+
+コンテナ・イメージ、Docker、Kubernetesなどについては、次の章で詳しく説明します: [コンテナ内のFastAPI - Docker](docker.md){.internal-link target=_blank}.
- コンテナ・イメージ、Docker、Kubernetesなどについては、次の章で詳しく説明します: [コンテナ内のFastAPI - Docker](docker.md){.internal-link target=_blank}.
+///
## 開始前の事前のステップ
もちろん、事前のステップを何度も実行しても問題がない場合もあり、その際は対処がかなり楽になります。
-!!! tip
- また、セットアップによっては、アプリケーションを開始する前の**事前のステップ**が必要ない場合もあることを覚えておいてください。
+/// tip
- その場合は、このようなことを心配する必要はないです。🤷
+また、セットアップによっては、アプリケーションを開始する前の**事前のステップ**が必要ない場合もあることを覚えておいてください。
+
+その場合は、このようなことを心配する必要はないです。🤷
+
+///
### 事前ステップの戦略例
* 事前のステップを実行し、アプリケーションを起動するbashスクリプト
* 利用するbashスクリプトを起動/再起動したり、エラーを検出したりする方法は以前として必要になるでしょう。
-!!! tip
- <!-- NOTE: the current version of docker.md is outdated compared to English one. -->
- コンテナを使った具体的な例については、次の章で紹介します: [コンテナ内のFastAPI - Docker](docker.md){.internal-link target=_blank}.
+/// tip
+
+<!-- NOTE: the current version of docker.md is outdated compared to English one. -->
+コンテナを使った具体的な例については、次の章で紹介します: [コンテナ内のFastAPI - Docker](docker.md){.internal-link target=_blank}.
+
+///
## リソースの利用
Linuxコンテナの使用には、**セキュリティ**、**反復可能性(レプリカビリティ)**、**シンプリシティ**など、いくつかの利点があります。
-!!! tip
- TODO: なぜか遷移できない
- お急ぎで、すでにこれらの情報をご存じですか? [以下の`Dockerfile`の箇所👇](#build-a-docker-image-for-fastapi)へジャンプしてください。
+/// tip
+
+TODO: なぜか遷移できない
+お急ぎで、すでにこれらの情報をご存じですか? [以下の`Dockerfile`の箇所👇](#build-a-docker-image-for-fastapi)へジャンプしてください。
+
+///
<details>
<summary>Dockerfile プレビュー 👀</summary>
</div>
-!!! info
- パッケージの依存関係を定義しインストールするためのフォーマットやツールは他にもあります。
+/// info
+
+パッケージの依存関係を定義しインストールするためのフォーマットやツールは他にもあります。
- Poetryを使った例は、後述するセクションでご紹介します。👇
+Poetryを使った例は、後述するセクションでご紹介します。👇
+
+///
### **FastAPI**コードを作成する
そのためプログラムは `/code` で開始しその中にあなたのコードがある `./app` ディレクトリがあるので、**Uvicorn** は `app.main` から `app` を参照し、**インポート** することができます。
-!!! tip
- コード内の"+"の吹き出しをクリックして、各行が何をするのかをレビューしてください。👆
+/// tip
+
+コード内の"+"の吹き出しをクリックして、各行が何をするのかをレビューしてください。👆
+
+///
これで、次のようなディレクトリ構造になるはずです:
</div>
-!!! tip
- 末尾の `.` に注目してほしいです。これは `./` と同じ意味です。 これはDockerにコンテナイメージのビルドに使用するディレクトリを指示します。
+/// tip
+
+末尾の `.` に注目してほしいです。これは `./` と同じ意味です。 これはDockerにコンテナイメージのビルドに使用するディレクトリを指示します。
+
+この場合、同じカレント・ディレクトリ(`.`)です。
- この場合、同じカレント・ディレクトリ(`.`)です。
+///
### Dockerコンテナの起動する
例えば<a href="https://traefik.io/" class="external-link" target="_blank">Traefik</a>のように、**HTTPS**と**証明書**の**自動**取得を扱う別のコンテナである可能性もあります。
-!!! tip
- TraefikはDockerやKubernetesなどと統合されているので、コンテナ用のHTTPSの設定や構成はとても簡単です。
+/// tip
+
+TraefikはDockerやKubernetesなどと統合されているので、コンテナ用のHTTPSの設定や構成はとても簡単です。
+
+///
あるいは、(コンテナ内でアプリケーションを実行しながら)クラウド・プロバイダーがサービスの1つとしてHTTPSを処理することもできます。
このコンポーネントはリクエストの **負荷** を受け、 (うまくいけば) その負荷を**バランスよく** ワーカーに分配するので、一般に **ロードバランサ** とも呼ばれます。
-!!! tip
- HTTPSに使われるものと同じ**TLS Termination Proxy**コンポーネントは、おそらく**ロードバランサー**にもなるでしょう。
+/// tip
+
+HTTPSに使われるものと同じ**TLS Termination Proxy**コンポーネントは、おそらく**ロードバランサー**にもなるでしょう。
+
+///
そしてコンテナで作業する場合、コンテナの起動と管理に使用する同じシステムには、**ロードバランサー**(**TLS Termination Proxy**の可能性もある)から**ネットワーク通信**(HTTPリクエストなど)をアプリのあるコンテナ(複数可)に送信するための内部ツールが既にあるはずです。
複数の**コンテナ**があり、おそらくそれぞれが**単一のプロセス**を実行している場合(**Kubernetes**クラスタなど)、レプリケートされたワーカーコンテナを実行する**前に**、単一のコンテナで**事前のステップ**の作業を行う**別のコンテナ**を持ちたいと思うでしょう。
-!!! info
- もしKubernetesを使用している場合, これはおそらく<a href="https://kubernetes.io/docs/concepts/workloads/pods/init-containers/" class="external-link" target="_blank">Init コンテナ</a>でしょう。
+/// info
+
+もしKubernetesを使用している場合, これはおそらく<a href="https://kubernetes.io/docs/concepts/workloads/pods/init-containers/" class="external-link" target="_blank">Init コンテナ</a>でしょう。
+
+///
ユースケースが事前のステップを**並列で複数回**実行するのに問題がない場合(例:データベースの準備チェック)、メインプロセスを開始する前に、それらのステップを各コンテナに入れることが可能です。
* <a href="https://github.com/tiangolo/uvicorn-gunicorn-fastapi-docker" class="external-link" target="_blank">tiangolo/uvicorn-gunicorn-fastapi</a>.
-!!! warning
- このベースイメージや類似のイメージは**必要ない**可能性が高いので、[上記の: FastAPI用のDockerイメージをビルドする(Build a Docker Image for FastAPI)](#build-a-docker-image-for-fastapi)のようにゼロからイメージをビルドする方が良いでしょう。
+/// warning
+
+このベースイメージや類似のイメージは**必要ない**可能性が高いので、[上記の: FastAPI用のDockerイメージをビルドする(Build a Docker Image for FastAPI)](#build-a-docker-image-for-fastapi)のようにゼロからイメージをビルドする方が良いでしょう。
+
+///
このイメージには、利用可能なCPUコアに基づいて**ワーカー・プロセスの数**を設定する**オートチューニング**メカニズムが含まれています。
また、スクリプトで<a href="https://github.com/tiangolo/uvicorn-gunicorn-fastapi-docker#pre_start_path" class="external-link" target="_blank">**開始前の事前ステップ**</a>を実行することもサポートしている。
-!!! tip
- すべての設定とオプションを見るには、Dockerイメージのページをご覧ください: <a href="https://github.com/tiangolo/uvicorn-gunicorn-fastapi-docker" class="external-link" target="_blank">tiangolo/uvicorn-gunicorn-fastapi</a>
+/// tip
+
+すべての設定とオプションを見るには、Dockerイメージのページをご覧ください: <a href="https://github.com/tiangolo/uvicorn-gunicorn-fastapi-docker" class="external-link" target="_blank">tiangolo/uvicorn-gunicorn-fastapi</a>
+
+///
### 公式Dockerイメージのプロセス数
9. 生成された `requirements.txt` ファイルにあるパッケージの依存関係をインストールします
10. app` ディレクトリを `/code` ディレクトリにコピーします
11. uvicorn` コマンドを実行して、`app.main` からインポートした `app` オブジェクトを使用するように指示します
-!!! tip
- "+"の吹き出しをクリックすると、それぞれの行が何をするのかを見ることができます
+/// tip
+
+"+"の吹き出しをクリックすると、それぞれの行が何をするのかを見ることができます
+
+///
**Dockerステージ**は`Dockerfile`の一部で、**一時的なコンテナイメージ**として動作します。
しかし、それよりもはるかに複雑です。
-!!! tip
- もし急いでいたり、HTTPSの仕組みについて気にしないのであれば、次のセクションに進み、さまざまなテクニックを使ってすべてをセットアップするステップ・バイ・ステップの手順をご覧ください。
+/// tip
+
+もし急いでいたり、HTTPSの仕組みについて気にしないのであれば、次のセクションに進み、さまざまなテクニックを使ってすべてをセットアップするステップ・バイ・ステップの手順をご覧ください。
+
+///
利用者の視点から **HTTPS の基本を学ぶ**に当たっては、次のリソースをオススメします: <a href="https://howhttps.works/" class="external-link" target="_blank">https://howhttps.works/</a>.
これはおそらく、最初の1回だけあり、すべてをセットアップするときに行うでしょう。
-!!! tip
- ドメイン名の話はHTTPSに関する話のはるか前にありますが、すべてがドメインとIPアドレスに依存するため、ここで言及する価値があります。
+/// tip
+
+ドメイン名の話はHTTPSに関する話のはるか前にありますが、すべてがドメインとIPアドレスに依存するため、ここで言及する価値があります。
+
+///
### DNS
これが**HTTPS**であり、純粋な(暗号化されていない)TCP接続ではなく、**セキュアなTLS接続**の中に**HTTP**があるだけです。
-!!! tip
- 通信の暗号化は、HTTPレベルではなく、**TCPレベル**で行われることに注意してください。
+/// tip
+
+通信の暗号化は、HTTPレベルではなく、**TCPレベル**で行われることに注意してください。
+
+///
### HTTPS リクエスト
以下の様なASGI対応のサーバをインストールする必要があります:
-=== "Uvicorn"
+//// tab | Uvicorn
- * <a href="https://www.uvicorn.org/" class="external-link" target="_blank">Uvicorn</a>, uvloopとhttptoolsを基にした高速なASGIサーバ。
+* <a href="https://www.uvicorn.org/" class="external-link" target="_blank">Uvicorn</a>, uvloopとhttptoolsを基にした高速なASGIサーバ。
- <div class="termy">
+<div class="termy">
- ```console
- $ pip install "uvicorn[standard]"
+```console
+$ pip install "uvicorn[standard]"
- ---> 100%
- ```
+---> 100%
+```
- </div>
+</div>
-!!! tip "豆知識"
- `standard` を加えることで、Uvicornがインストールされ、いくつかの推奨される依存関係を利用するようになります。
+////
- これには、`asyncio` の高性能な完全互換品である `uvloop` が含まれ、並行処理のパフォーマンスが大幅に向上します。
+/// tip | "豆知識"
-=== "Hypercorn"
+`standard` を加えることで、Uvicornがインストールされ、いくつかの推奨される依存関係を利用するようになります。
- * <a href="https://github.com/pgjones/hypercorn" class="external-link" target="_blank">Hypercorn</a>, HTTP/2にも対応しているASGIサーバ。
+これには、`asyncio` の高性能な完全互換品である `uvloop` が含まれ、並行処理のパフォーマンスが大幅に向上します。
- <div class="termy">
+///
- ```console
- $ pip install hypercorn
+//// tab | Hypercorn
- ---> 100%
- ```
+* <a href="https://github.com/pgjones/hypercorn" class="external-link" target="_blank">Hypercorn</a>, HTTP/2にも対応しているASGIサーバ。
- </div>
+<div class="termy">
- ...または、これら以外のASGIサーバ。
+```console
+$ pip install hypercorn
+
+---> 100%
+```
+
+</div>
+
+...または、これら以外のASGIサーバ。
+
+////
そして、チュートリアルと同様な方法でアプリケーションを起動して下さい。ただし、以下の様に`--reload` オプションは使用しないで下さい:
-=== "Uvicorn"
+//// tab | Uvicorn
+
+<div class="termy">
+
+```console
+$ uvicorn main:app --host 0.0.0.0 --port 80
- <div class="termy">
+<span style="color: green;">INFO</span>: Uvicorn running on http://0.0.0.0:80 (Press CTRL+C to quit)
+```
- ```console
- $ uvicorn main:app --host 0.0.0.0 --port 80
+</div>
- <span style="color: green;">INFO</span>: Uvicorn running on http://0.0.0.0:80 (Press CTRL+C to quit)
- ```
+////
- </div>
+//// tab | Hypercorn
-=== "Hypercorn"
+<div class="termy">
- <div class="termy">
+```console
+$ hypercorn main:app --bind 0.0.0.0:80
- ```console
- $ hypercorn main:app --bind 0.0.0.0:80
+Running on 0.0.0.0:8080 over http (CTRL + C to quit)
+```
- Running on 0.0.0.0:8080 over http (CTRL + C to quit)
- ```
+</div>
- </div>
+////
停止した場合に自動的に再起動させるツールを設定したいかもしれません。
ここでは<a href="https://gunicorn.org/" class="external-link" target="_blank">**Gunicorn**</a>が**Uvicornのワーカー・プロセス**を管理する場合の使い方について紹介していきます。
-!!! info
- <!-- NOTE: the current version of docker.md is outdated compared to English one. -->
- DockerやKubernetesなどのコンテナを使用している場合は、次の章で詳しく説明します: [コンテナ内のFastAPI - Docker](docker.md){.internal-link target=_blank}
+/// info
- 特に**Kubernetes**上で実行する場合は、おそらく**Gunicornを使用せず**、**コンテナごとに単一のUvicornプロセス**を実行することになりますが、それについてはこの章の後半で説明します。
+<!-- NOTE: the current version of docker.md is outdated compared to English one. -->
+DockerやKubernetesなどのコンテナを使用している場合は、次の章で詳しく説明します: [コンテナ内のFastAPI - Docker](docker.md){.internal-link target=_blank}
+
+特に**Kubernetes**上で実行する場合は、おそらく**Gunicornを使用せず**、**コンテナごとに単一のUvicornプロセス**を実行することになりますが、それについてはこの章の後半で説明します。
+
+///
## GunicornによるUvicornのワーカー・プロセスの管理
FastAPIでは「パッチ」バージョンはバグ修正と非破壊的な変更に留めるという規約に従っています。
-!!! tip "豆知識"
- 「パッチ」は最後の数字を指します。例えば、`0.2.3` ではパッチバージョンは `3` です。
+/// tip | "豆知識"
+
+「パッチ」は最後の数字を指します。例えば、`0.2.3` ではパッチバージョンは `3` です。
+
+///
従って、以下の様なバージョンの固定が望ましいです:
破壊的な変更と新機能実装は「マイナー」バージョンで加えられます。
-!!! tip "豆知識"
- 「マイナー」は真ん中の数字です。例えば、`0.2.3` ではマイナーバージョンは `2` です。
+/// tip | "豆知識"
+
+「マイナー」は真ん中の数字です。例えば、`0.2.3` ではマイナーバージョンは `2` です。
+
+///
## FastAPIのバージョンのアップグレード
それらの不完全なリストを以下に示します。
-!!! tip "豆知識"
- ここにまだ載っていない**FastAPI**に関連する記事、プロジェクト、ツールなどがある場合は、 <a href="https://github.com/fastapi/fastapi/edit/master/docs/en/data/external_links.yml" class="external-link" target="_blank">プルリクエストして下さい</a>。
+/// tip | "豆知識"
+
+ここにまだ載っていない**FastAPI**に関連する記事、プロジェクト、ツールなどがある場合は、 <a href="https://github.com/fastapi/fastapi/edit/master/docs/en/data/external_links.yml" class="external-link" target="_blank">プルリクエストして下さい</a>。
+
+///
{% for section_name, section_content in external_links.items() %}
my_second_user: User = User(**second_user_data)
```
-!!! info "情報"
- `**second_user_data` は以下を意味します:
+/// info | "情報"
- `second_user_data`辞書のキーと値を直接、キーと値の引数として渡します。これは、`User(id=4, name="Mary", joined="2018-11-30")`と同等です。
+`**second_user_data` は以下を意味します:
+
+`second_user_data`辞書のキーと値を直接、キーと値の引数として渡します。これは、`User(id=4, name="Mary", joined="2018-11-30")`と同等です。
+
+///
### エディタのサポート
しかしたとえまったく **FastAPI** を使用しない場合でも、それらについて少し学ぶことで利点を得ることができるでしょう。
-!!! note "備考"
- もしあなたがPythonの専門家で、すでに型ヒントについてすべて知っているのであれば、次の章まで読み飛ばしてください。
+/// note | "備考"
+
+もしあなたがPythonの専門家で、すでに型ヒントについてすべて知っているのであれば、次の章まで読み飛ばしてください。
+
+///
## 動機
{!../../../docs_src/python_types/tutorial006.py!}
```
-!!! tip "豆知識"
- 角括弧内の内部の型は「型パラメータ」と呼ばれています。
+/// tip | "豆知識"
+
+角括弧内の内部の型は「型パラメータ」と呼ばれています。
+
+この場合、`str`は`List`に渡される型パラメータです。
- この場合、`str`は`List`に渡される型パラメータです。
+///
つまり: 変数`items`は`list`であり、このリストの各項目は`str`です。
{!../../../docs_src/python_types/tutorial011.py!}
```
-!!! info "情報"
- Pydanticについてより学びたい方は<a href="https://docs.pydantic.dev/" class="external-link" target="_blank">ドキュメントを参照してください</a>.
+/// info | "情報"
+
+Pydanticについてより学びたい方は<a href="https://docs.pydantic.dev/" class="external-link" target="_blank">ドキュメントを参照してください</a>.
+
+///
**FastAPI** はすべてPydanticをベースにしています。
重要なのは、Pythonの標準的な型を使うことで、(クラスやデコレータなどを追加するのではなく)1つの場所で **FastAPI** が多くの作業を代わりにやってくれているということです。
-!!! info "情報"
- すでにすべてのチュートリアルを終えて、型についての詳細を見るためにこのページに戻ってきた場合は、<a href="https://mypy.readthedocs.io/en/latest/cheat_sheet_py3.html" class="external-link" target="_blank">`mypy`のチートシートを参照してください</a>
+/// info | "情報"
+
+すでにすべてのチュートリアルを終えて、型についての詳細を見るためにこのページに戻ってきた場合は、<a href="https://mypy.readthedocs.io/en/latest/cheat_sheet_py3.html" class="external-link" target="_blank">`mypy`のチートシートを参照してください</a>
+
+///
{!../../../docs_src/body_fields/tutorial001.py!}
```
-!!! warning "注意"
- `Field`は他の全てのもの(`Query`、`Path`、`Body`など)とは違い、`fastapi`からではなく、`pydantic`から直接インポートされていることに注意してください。
+/// warning | "注意"
+
+`Field`は他の全てのもの(`Query`、`Path`、`Body`など)とは違い、`fastapi`からではなく、`pydantic`から直接インポートされていることに注意してください。
+
+///
## モデルの属性の宣言
`Field`は`Query`や`Path`、`Body`と同じように動作し、全く同様のパラメータなどを持ちます。
-!!! note "技術詳細"
- 実際には次に見る`Query`や`Path`などは、共通の`Param`クラスのサブクラスのオブジェクトを作成しますが、それ自体はPydanticの`FieldInfo`クラスのサブクラスです。
+/// note | "技術詳細"
+
+実際には次に見る`Query`や`Path`などは、共通の`Param`クラスのサブクラスのオブジェクトを作成しますが、それ自体はPydanticの`FieldInfo`クラスのサブクラスです。
+
+また、Pydanticの`Field`は`FieldInfo`のインスタンスも返します。
+
+`Body`は`FieldInfo`のサブクラスのオブジェクトを直接返すこともできます。そして、他にも`Body`クラスのサブクラスであるものがあります。
+
+`fastapi`から`Query`や`Path`などをインポートする場合、これらは実際には特殊なクラスを返す関数であることに注意してください。
- また、Pydanticの`Field`は`FieldInfo`のインスタンスも返します。
+///
- `Body`は`FieldInfo`のサブクラスのオブジェクトを直接返すこともできます。そして、他にも`Body`クラスのサブクラスであるものがあります。
+/// tip | "豆知識"
- `fastapi`から`Query`や`Path`などをインポートする場合、これらは実際には特殊なクラスを返す関数であることに注意してください。
+型、デフォルト値、`Field`を持つ各モデルの属性が、`Path`や`Query`、`Body`の代わりに`Field`を持つ、*path operation 関数の*パラメータと同じ構造になっていることに注目してください。
-!!! tip "豆知識"
- 型、デフォルト値、`Field`を持つ各モデルの属性が、`Path`や`Query`、`Body`の代わりに`Field`を持つ、*path operation 関数の*パラメータと同じ構造になっていることに注目してください。
+///
## 追加情報の追加
{!../../../docs_src/body_multiple_params/tutorial001.py!}
```
-!!! note "備考"
- この場合、ボディから取得する`item`はオプションであることに注意してください。デフォルト値は`None`です。
+/// note | "備考"
+
+この場合、ボディから取得する`item`はオプションであることに注意してください。デフォルト値は`None`です。
+
+///
## 複数のボディパラメータ
}
```
-!!! note "備考"
- 以前と同じように`item`が宣言されていたにもかかわらず、`item`はキー`item`を持つボディの内部にあることが期待されていることに注意してください。
+/// note | "備考"
+
+以前と同じように`item`が宣言されていたにもかかわらず、`item`はキー`item`を持つボディの内部にあることが期待されていることに注意してください。
+
+///
**FastAPI** はリクエストから自動で変換を行い、パラメータ`item`が特定の内容を受け取り、`user`も同じように特定の内容を受け取ります。
{!../../../docs_src/body_multiple_params/tutorial004.py!}
```
-!!! info "情報"
- `Body`もまた、後述する `Query` や `Path` などと同様に、すべての検証パラメータとメタデータパラメータを持っています。
+/// info | "情報"
+
+`Body`もまた、後述する `Query` や `Path` などと同様に、すべての検証パラメータとメタデータパラメータを持っています。
+///
## 単一のボディパラメータの埋め込み
}
```
-!!! info "情報"
- `images`キーが画像オブジェクトのリストを持つようになったことに注目してください。
+/// info | "情報"
+
+`images`キーが画像オブジェクトのリストを持つようになったことに注目してください。
+
+///
## 深くネストされたモデル
{!../../../docs_src/body_nested_models/tutorial007.py!}
```
-!!! info "情報"
- `Offer`は`Item`のリストであり、オプションの`Image`のリストを持っていることに注目してください。
+/// info | "情報"
+
+`Offer`は`Item`のリストであり、オプションの`Image`のリストを持っていることに注目してください。
+
+///
## 純粋なリストのボディ
{!../../../docs_src/body_nested_models/tutorial009.py!}
```
-!!! tip "豆知識"
- JSONはキーとして`str`しかサポートしていないことに注意してください。
+/// tip | "豆知識"
+
+JSONはキーとして`str`しかサポートしていないことに注意してください。
+
+しかしPydanticには自動データ変換機能があります。
- しかしPydanticには自動データ変換機能があります。
+これは、APIクライアントがキーとして文字列しか送信できなくても、それらの文字列に純粋な整数が含まれている限り、Pydanticが変換して検証することを意味します。
- これは、APIクライアントがキーとして文字列しか送信できなくても、それらの文字列に純粋な整数が含まれている限り、Pydanticが変換して検証することを意味します。
+そして、`weights`として受け取る`dict`は、実際には`int`のキーと`float`の値を持つことになります。
- そして、`weights`として受け取る`dict`は、実際には`int`のキーと`float`の値を持つことになります。
+///
## まとめ
つまり、更新したいデータだけを送信して、残りはそのままにしておくことができます。
-!!! note "備考"
- `PATCH`は`PUT`よりもあまり使われておらず、知られていません。
+/// note | "備考"
- また、多くのチームは部分的な更新であっても`PUT`だけを使用しています。
+`PATCH`は`PUT`よりもあまり使われておらず、知られていません。
- **FastAPI** はどんな制限も課けていないので、それらを使うのは **自由** です。
+また、多くのチームは部分的な更新であっても`PUT`だけを使用しています。
- しかし、このガイドでは、それらがどのように使用されることを意図しているかを多かれ少なかれ、示しています。
+**FastAPI** はどんな制限も課けていないので、それらを使うのは **自由** です。
+
+しかし、このガイドでは、それらがどのように使用されることを意図しているかを多かれ少なかれ、示しています。
+
+///
### Pydanticの`exclude_unset`パラメータの使用
{!../../../docs_src/body_updates/tutorial002.py!}
```
-!!! tip "豆知識"
- 実際には、HTTPの`PUT`操作でも同じテクニックを使用することができます。
+/// tip | "豆知識"
+
+実際には、HTTPの`PUT`操作でも同じテクニックを使用することができます。
+
+しかし、これらのユースケースのために作成されたので、ここでの例では`PATCH`を使用しています。
+
+///
+
+/// note | "備考"
- しかし、これらのユースケースのために作成されたので、ここでの例では`PATCH`を使用しています。
+入力モデルがまだ検証されていることに注目してください。
-!!! note "備考"
- 入力モデルがまだ検証されていることに注目してください。
+そのため、すべての属性を省略できる部分的な変更を受け取りたい場合は、すべての属性をオプションとしてマークしたモデルを用意する必要があります(デフォルト値または`None`を使用して)。
- そのため、すべての属性を省略できる部分的な変更を受け取りたい場合は、すべての属性をオプションとしてマークしたモデルを用意する必要があります(デフォルト値または`None`を使用して)。
+**更新** のためのオプション値がすべて設定されているモデルと、**作成** のための必須値が設定されているモデルを区別するには、[追加モデル](extra-models.md){.internal-link target=_blank}で説明されている考え方を利用することができます。
- **更新** のためのオプション値がすべて設定されているモデルと、**作成** のための必須値が設定されているモデルを区別するには、[追加モデル](extra-models.md){.internal-link target=_blank}で説明されている考え方を利用することができます。
+///
**リクエスト** ボディを宣言するために <a href="https://docs.pydantic.dev/" class="external-link" target="_blank">Pydantic</a> モデルを使用します。そして、その全てのパワーとメリットを利用します。
-!!! info "情報"
- データを送るには、`POST` (もっともよく使われる)、`PUT`、`DELETE` または `PATCH` を使うべきです。
+/// info | "情報"
- GET リクエストでボディを送信することは、仕様では未定義の動作ですが、FastAPI でサポートされており、非常に複雑な(極端な)ユースケースにのみ対応しています。
+データを送るには、`POST` (もっともよく使われる)、`PUT`、`DELETE` または `PATCH` を使うべきです。
- 非推奨なので、Swagger UIを使った対話型のドキュメントにはGETのボディ情報は表示されません。さらに、中継するプロキシが対応していない可能性があります。
+GET リクエストでボディを送信することは、仕様では未定義の動作ですが、FastAPI でサポートされており、非常に複雑な(極端な)ユースケースにのみ対応しています。
+
+非推奨なので、Swagger UIを使った対話型のドキュメントにはGETのボディ情報は表示されません。さらに、中継するプロキシが対応していない可能性があります。
+
+///
## Pydanticの `BaseModel` をインポート
<img src="/img/tutorial/body/image05.png">
-!!! tip "豆知識"
- <a href="https://www.jetbrains.com/pycharm/" class="external-link" target="_blank">PyCharm</a>エディタを使用している場合は、<a href="https://github.com/koxudaxi/pydantic-pycharm-plugin/" class="external-link" target="_blank">Pydantic PyCharm Plugin</a>が使用可能です。
+/// tip | "豆知識"
+
+<a href="https://www.jetbrains.com/pycharm/" class="external-link" target="_blank">PyCharm</a>エディタを使用している場合は、<a href="https://github.com/koxudaxi/pydantic-pycharm-plugin/" class="external-link" target="_blank">Pydantic PyCharm Plugin</a>が使用可能です。
- 以下のエディターサポートが強化されます:
+以下のエディターサポートが強化されます:
- * 自動補完
- * 型チェック
- * リファクタリング
- * 検索
- * インスペクション
+* 自動補完
+* 型チェック
+* リファクタリング
+* 検索
+* インスペクション
+
+///
## モデルの使用
* パラメータが**単数型** (`int`、`float`、`str`、`bool` など)の場合は**クエリ**パラメータとして解釈されます。
* パラメータが **Pydantic モデル**型で宣言された場合、リクエスト**ボディ**として解釈されます。
-!!! note "備考"
- FastAPIは、`= None`があるおかげで、`q`がオプショナルだとわかります。
+/// note | "備考"
+
+FastAPIは、`= None`があるおかげで、`q`がオプショナルだとわかります。
+
+`Optional[str]` の`Optional` はFastAPIでは使用されていません(FastAPIは`str`の部分のみ使用します)。しかし、`Optional[str]` はエディタがコードのエラーを見つけるのを助けてくれます。
- `Optional[str]` の`Optional` はFastAPIでは使用されていません(FastAPIは`str`の部分のみ使用します)。しかし、`Optional[str]` はエディタがコードのエラーを見つけるのを助けてくれます。
+///
## Pydanticを使わない方法
{!../../../docs_src/cookie_params/tutorial001.py!}
```
-!!! note "技術詳細"
- `Cookie`は`Path`と`Query`の「姉妹」クラスです。また、同じ共通の`Param`クラスを継承しています。
+/// note | "技術詳細"
- しかし、`fastapi`から`Query`や`Path`、`Cookie`などをインポートする場合、それらは実際には特殊なクラスを返す関数であることを覚えておいてください。
+`Cookie`は`Path`と`Query`の「姉妹」クラスです。また、同じ共通の`Param`クラスを継承しています。
-!!! info "情報"
- クッキーを宣言するには、`Cookie`を使う必要があります。なぜなら、そうしないとパラメータがクエリのパラメータとして解釈されてしまうからです。
+しかし、`fastapi`から`Query`や`Path`、`Cookie`などをインポートする場合、それらは実際には特殊なクラスを返す関数であることを覚えておいてください。
+
+///
+
+/// info | "情報"
+
+クッキーを宣言するには、`Cookie`を使う必要があります。なぜなら、そうしないとパラメータがクエリのパラメータとして解釈されてしまうからです。
+
+///
## まとめ
<abbr title="Cross-Origin Resource Sharing (オリジン間リソース共有)">CORS</abbr>についてより詳しい情報は、<a href="https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS" class="external-link" target="_blank">Mozilla CORS documentation</a> を参照して下さい。
-!!! note "技術詳細"
- `from starlette.middleware.cors import CORSMiddleware` も使用できます。
+/// note | "技術詳細"
- **FastAPI** は、開発者の利便性を高めるために、`fastapi.middleware` でいくつかのミドルウェアを提供します。利用可能なミドルウェアのほとんどは、Starletteから直接提供されています。
+`from starlette.middleware.cors import CORSMiddleware` も使用できます。
+
+**FastAPI** は、開発者の利便性を高めるために、`fastapi.middleware` でいくつかのミドルウェアを提供します。利用可能なミドルウェアのほとんどは、Starletteから直接提供されています。
+
+///
は実行されません。
-!!! info "情報"
- より詳しい情報は、<a href="https://docs.python.org/3/library/__main__.html" class="external-link" target="_blank">公式Pythonドキュメント</a>を参照してください。
+/// info | "情報"
+
+より詳しい情報は、<a href="https://docs.python.org/3/library/__main__.html" class="external-link" target="_blank">公式Pythonドキュメント</a>を参照してください。
+
+///
## デバッガーでコードを実行
...そして **FastAPI** は何をすべきか知っています。
-!!! tip "豆知識"
- 役に立つというよりも、混乱するようであれば無視してください。それをする*必要*はありません。
+/// tip | "豆知識"
- それは単なるショートカットです。なぜなら **FastAPI** はコードの繰り返しを最小限に抑えることに気を使っているからです。
+役に立つというよりも、混乱するようであれば無視してください。それをする*必要*はありません。
+
+それは単なるショートカットです。なぜなら **FastAPI** はコードの繰り返しを最小限に抑えることに気を使っているからです。
+
+///
これらの依存関係は、通常の依存関係と同様に実行・解決されます。しかし、それらの値(何かを返す場合)は*path operation関数*には渡されません。
-!!! tip "豆知識"
- エディタによっては、未使用の関数パラメータをチェックしてエラーとして表示するものもあります。
+/// tip | "豆知識"
- `dependencies`を`path operationデコレータ`で使用することで、エディタやツールのエラーを回避しながら確実に実行することができます。
+エディタによっては、未使用の関数パラメータをチェックしてエラーとして表示するものもあります。
- また、コードの未使用のパラメータがあるのを見て、それが不要だと思ってしまうような新しい開発者の混乱を避けるのにも役立つかもしれません。
+`dependencies`を`path operationデコレータ`で使用することで、エディタやツールのエラーを回避しながら確実に実行することができます。
+
+また、コードの未使用のパラメータがあるのを見て、それが不要だと思ってしまうような新しい開発者の混乱を避けるのにも役立つかもしれません。
+
+///
## 依存関係のエラーと戻り値
これを行うには、`return`の代わりに`yield`を使い、その後に追加のステップを書きます。
-!!! tip "豆知識"
- `yield`は必ず一度だけ使用するようにしてください。
+/// tip | "豆知識"
-!!! info "情報"
- これを動作させるには、**Python 3.7** 以上を使用するか、**Python 3.6** では"backports"をインストールする必要があります:
+`yield`は必ず一度だけ使用するようにしてください。
- ```
- pip install async-exit-stack async-generator
- ```
+///
- これにより<a href="https://github.com/sorcio/async_exit_stack" class="external-link" target="_blank">async-exit-stack</a>と<a href="https://github.com/python-trio/async_generator" class="external-link" target="_blank">async-generator</a>がインストールされます。
+/// info | "情報"
-!!! note "技術詳細"
- 以下と一緒に使用できる関数なら何でも有効です:
+これを動作させるには、**Python 3.7** 以上を使用するか、**Python 3.6** では"backports"をインストールする必要があります:
- * <a href="https://docs.python.org/3/library/contextlib.html#contextlib.contextmanager" class="external-link" target="_blank">`@contextlib.contextmanager`</a>または
- * <a href="https://docs.python.org/3/library/contextlib.html#contextlib.asynccontextmanager" class="external-link" target="_blank">`@contextlib.asynccontextmanager`</a>
+```
+pip install async-exit-stack async-generator
+```
+
+これにより<a href="https://github.com/sorcio/async_exit_stack" class="external-link" target="_blank">async-exit-stack</a>と<a href="https://github.com/python-trio/async_generator" class="external-link" target="_blank">async-generator</a>がインストールされます。
+
+///
+
+/// note | "技術詳細"
+
+以下と一緒に使用できる関数なら何でも有効です:
- これらは **FastAPI** の依存関係として使用するのに有効です。
+* <a href="https://docs.python.org/3/library/contextlib.html#contextlib.contextmanager" class="external-link" target="_blank">`@contextlib.contextmanager`</a>または
+* <a href="https://docs.python.org/3/library/contextlib.html#contextlib.asynccontextmanager" class="external-link" target="_blank">`@contextlib.asynccontextmanager`</a>
- 実際、FastAPIは内部的にこれら2つのデコレータを使用しています。
+これらは **FastAPI** の依存関係として使用するのに有効です。
+
+実際、FastAPIは内部的にこれら2つのデコレータを使用しています。
+
+///
## `yield`を持つデータベースの依存関係
{!../../../docs_src/dependencies/tutorial007.py!}
```
-!!! tip "豆知識"
- `async`や通常の関数を使用することができます。
+/// tip | "豆知識"
+
+`async`や通常の関数を使用することができます。
- **FastAPI** は、通常の依存関係と同じように、それぞれで正しいことを行います。
+**FastAPI** は、通常の依存関係と同じように、それぞれで正しいことを行います。
+
+///
## `yield`と`try`を持つ依存関係
**FastAPI** は、全てが正しい順序で実行されていることを確認します。
-!!! note "技術詳細"
- これはPythonの<a href="https://docs.python.org/3/library/contextlib.html" class="external-link" target="_blank">Context Managers</a>のおかげで動作します。
+/// note | "技術詳細"
+
+これはPythonの<a href="https://docs.python.org/3/library/contextlib.html" class="external-link" target="_blank">Context Managers</a>のおかげで動作します。
- **FastAPI** はこれを実現するために内部的に使用しています。
+**FastAPI** はこれを実現するために内部的に使用しています。
+
+///
## `yield`と`HTTPException`を持つ依存関係
レスポンスを返したり、レスポンスを変更したり、`HTTPException`を発生させたりする*前に*処理したいカスタム例外がある場合は、[カスタム例外ハンドラ](../handling-errors.md#_4){.internal-link target=_blank}を作成してください。
-!!! tip "豆知識"
- `HTTPException`を含む例外は、`yield`の*前*でも発生させることができます。ただし、後ではできません。
+/// tip | "豆知識"
+
+`HTTPException`を含む例外は、`yield`の*前*でも発生させることができます。ただし、後ではできません。
+
+///
実行の順序は多かれ少なかれ以下の図のようになります。時間は上から下へと流れていきます。そして、各列はコードを相互作用させたり、実行したりしている部分の一つです。
end
```
-!!! info "情報"
- **1つのレスポンス** だけがクライアントに送信されます。それはエラーレスポンスの一つかもしれませんし、*path operation*からのレスポンスかもしれません。
+/// info | "情報"
+
+**1つのレスポンス** だけがクライアントに送信されます。それはエラーレスポンスの一つかもしれませんし、*path operation*からのレスポンスかもしれません。
+
+いずれかのレスポンスが送信された後、他のレスポンスを送信することはできません。
+
+///
- いずれかのレスポンスが送信された後、他のレスポンスを送信することはできません。
+/// tip | "豆知識"
-!!! tip "豆知識"
- この図は`HTTPException`を示していますが、[カスタム例外ハンドラ](../handling-errors.md#_4){.internal-link target=_blank}を作成することで、他の例外を発生させることもできます。そして、その例外は依存関係の終了コードではなく、そのカスタム例外ハンドラによって処理されます。
+この図は`HTTPException`を示していますが、[カスタム例外ハンドラ](../handling-errors.md#_4){.internal-link target=_blank}を作成することで、他の例外を発生させることもできます。そして、その例外は依存関係の終了コードではなく、そのカスタム例外ハンドラによって処理されます。
- しかし例外ハンドラで処理されない例外を発生させた場合は、依存関係の終了コードで処理されます。
+しかし例外ハンドラで処理されない例外を発生させた場合は、依存関係の終了コードで処理されます。
+
+///
## コンテキストマネージャ
### `yield`を持つ依存関係でのコンテキストマネージャの使用
-!!! warning "注意"
- これは多かれ少なかれ、「高度な」発想です。
+/// warning | "注意"
+
+これは多かれ少なかれ、「高度な」発想です。
+
+**FastAPI** を使い始めたばかりの方は、とりあえずスキップした方がよいかもしれません。
- **FastAPI** を使い始めたばかりの方は、とりあえずスキップした方がよいかもしれません。
+///
Pythonでは、<a href="https://docs.python.org/3/reference/datamodel.html#context-managers" class="external-link" target="_blank">以下の2つのメソッドを持つクラスを作成する: `__enter__()`と`__exit__()`</a>ことでコンテキストマネージャを作成することができます。
{!../../../docs_src/dependencies/tutorial010.py!}
```
-!!! tip "豆知識"
- コンテキストマネージャを作成するもう一つの方法はwithです:
+/// tip | "豆知識"
+
+コンテキストマネージャを作成するもう一つの方法はwithです:
+
+* <a href="https://docs.python.org/3/library/contextlib.html#contextlib.contextmanager" class="external-link" target="_blank">`@contextlib.contextmanager`</a> または
+* <a href="https://docs.python.org/3/library/contextlib.html#contextlib.asynccontextmanager" class="external-link" target="_blank">`@contextlib.asynccontextmanager`</a>
- * <a href="https://docs.python.org/3/library/contextlib.html#contextlib.contextmanager" class="external-link" target="_blank">`@contextlib.contextmanager`</a> または
- * <a href="https://docs.python.org/3/library/contextlib.html#contextlib.asynccontextmanager" class="external-link" target="_blank">`@contextlib.asynccontextmanager`</a>
+これらを使って、関数を単一の`yield`でデコレートすることができます。
- これらを使って、関数を単一の`yield`でデコレートすることができます。
+これは **FastAPI** が内部的に`yield`を持つ依存関係のために使用しているものです。
- これは **FastAPI** が内部的に`yield`を持つ依存関係のために使用しているものです。
+しかし、FastAPIの依存関係にデコレータを使う必要はありません(そして使うべきではありません)。
- しかし、FastAPIの依存関係にデコレータを使う必要はありません(そして使うべきではありません)。
+FastAPIが内部的にやってくれます。
- FastAPIが内部的にやってくれます。
+///
そして、その関数は、*path operation関数*が行うのと同じ方法でパラメータを取ります。
-!!! tip "豆知識"
- 次の章では、関数以外の「もの」が依存関係として使用できるものを見ていきます。
+/// tip | "豆知識"
+
+次の章では、関数以外の「もの」が依存関係として使用できるものを見ていきます。
+
+///
新しいリクエストが到着するたびに、**FastAPI** が以下のような処理を行います:
この方法では、共有されるコードを一度書き、**FastAPI** が*path operations*のための呼び出しを行います。
-!!! check "確認"
- 特別なクラスを作成してどこかで **FastAPI** に渡して「登録」する必要はないことに注意してください。
+/// check | "確認"
+
+特別なクラスを作成してどこかで **FastAPI** に渡して「登録」する必要はないことに注意してください。
- `Depends`を渡すだけで、**FastAPI** が残りの処理をしてくれます。
+`Depends`を渡すだけで、**FastAPI** が残りの処理をしてくれます。
+
+///
## `async`にするかどうか
それは重要ではありません。**FastAPI** は何をすべきかを知っています。
-!!! note "備考"
- わからない場合は、ドキュメントの[Async: *"In a hurry?"*](../../async.md){.internal-link target=_blank}の中の`async`と`await`についてのセクションを確認してください。
+/// note | "備考"
+
+わからない場合は、ドキュメントの[Async: *"In a hurry?"*](../../async.md){.internal-link target=_blank}の中の`async`と`await`についてのセクションを確認してください。
+
+///
## OpenAPIとの統合
{!../../../docs_src/dependencies/tutorial005.py!}
```
-!!! info "情報"
- *path operation関数*の中で宣言している依存関係は`query_or_cookie_extractor`の1つだけであることに注意してください。
+/// info | "情報"
- しかし、**FastAPI** は`query_extractor`を最初に解決し、その結果を`query_or_cookie_extractor`を呼び出す時に渡す必要があることを知っています。
+*path operation関数*の中で宣言している依存関係は`query_or_cookie_extractor`の1つだけであることに注意してください。
+
+しかし、**FastAPI** は`query_extractor`を最初に解決し、その結果を`query_or_cookie_extractor`を呼び出す時に渡す必要があることを知っています。
+
+///
```mermaid
graph TB
しかし、それでも非常に強力で、任意の深くネストされた依存関係「グラフ」(ツリー)を宣言することができます。
-!!! tip "豆知識"
- これらの単純な例では、全てが役に立つとは言えないかもしれません。
+/// tip | "豆知識"
+
+これらの単純な例では、全てが役に立つとは言えないかもしれません。
+
+しかし、**security** についての章で、それがどれほど有用であるかがわかるでしょう。
- しかし、**security** についての章で、それがどれほど有用であるかがわかるでしょう。
+そして、あなたを救うコードの量もみることになるでしょう。
- そして、あなたを救うコードの量もみることになるでしょう。
+///
これはJSON形式のデータを含む大きな`str`を(文字列として)返しません。JSONと互換性のある値とサブの値を持つPython標準のデータ構造(例:`dict`)を返します。
-!!! note "備考"
- `jsonable_encoder`は実際には **FastAPI** が内部的にデータを変換するために使用します。しかしこれは他の多くのシナリオで有用です。
+/// note | "備考"
+
+`jsonable_encoder`は実際には **FastAPI** が内部的にデータを変換するために使用します。しかしこれは他の多くのシナリオで有用です。
+
+///
* **出力モデル**はパスワードをもつべきではありません。
* **データベースモデル**はおそらくハッシュ化されたパスワードが必要になるでしょう。
-!!! danger "危険"
- ユーザーの平文のパスワードは絶対に保存しないでください。常に認証に利用可能な「安全なハッシュ」を保存してください。
+/// danger | "危険"
- 知らない方は、[セキュリティの章](security/simple-oauth2.md#password-hashing){.internal-link target=_blank}で「パスワードハッシュ」とは何かを学ぶことができます。
+ユーザーの平文のパスワードは絶対に保存しないでください。常に認証に利用可能な「安全なハッシュ」を保存してください。
+
+知らない方は、[セキュリティの章](security/simple-oauth2.md#password-hashing){.internal-link target=_blank}で「パスワードハッシュ」とは何かを学ぶことができます。
+
+///
## 複数のモデル
)
```
-!!! warning "注意"
- サポートしている追加機能は、データの可能な流れをデモするだけであり、もちろん本当のセキュリティを提供しているわけではありません。
+/// warning | "注意"
+
+サポートしている追加機能は、データの可能な流れをデモするだけであり、もちろん本当のセキュリティを提供しているわけではありません。
+
+///
## 重複の削減
</div>
-!!! note "備考"
- `uvicorn main:app`は以下を示します:
+/// note | "備考"
- * `main`: `main.py`ファイル (Python "module")。
- * `app`: `main.py`内部で作られるobject(`app = FastAPI()`のように記述される)。
- * `--reload`: コードの変更時にサーバーを再起動させる。開発用。
+`uvicorn main:app`は以下を示します:
+
+* `main`: `main.py`ファイル (Python "module")。
+* `app`: `main.py`内部で作られるobject(`app = FastAPI()`のように記述される)。
+* `--reload`: コードの変更時にサーバーを再起動させる。開発用。
+
+///
出力には次のような行があります:
`FastAPI`は、APIのすべての機能を提供するPythonクラスです。
-!!! note "技術詳細"
- `FastAPI`は`Starlette`を直接継承するクラスです。
+/// note | "技術詳細"
+
+`FastAPI`は`Starlette`を直接継承するクラスです。
- `FastAPI`でも<a href="https://www.starlette.io/" class="external-link" target="_blank">Starlette</a>のすべての機能を利用可能です。
+`FastAPI`でも<a href="https://www.starlette.io/" class="external-link" target="_blank">Starlette</a>のすべての機能を利用可能です。
+
+///
### Step 2: `FastAPI`の「インスタンス」を生成
/items/foo
```
-!!! info "情報"
- 「パス」は一般に「エンドポイント」または「ルート」とも呼ばれます。
+/// info | "情報"
+
+「パス」は一般に「エンドポイント」または「ルート」とも呼ばれます。
+
+///
APIを構築する際、「パス」は「関心事」と「リソース」を分離するための主要な方法です。
* パス `/`
* <abbr title="an HTTP GET method"><code>get</code> オペレーション</abbr>
-!!! info "`@decorator` について"
- Pythonにおける`@something`シンタックスはデコレータと呼ばれます。
+/// info | "`@decorator` について"
- 「デコレータ」は関数の上に置きます。かわいらしい装飾的な帽子のようです(この用語の由来はそこにあると思います)。
+Pythonにおける`@something`シンタックスはデコレータと呼ばれます。
- 「デコレータ」は直下の関数を受け取り、それを使って何かを行います。
+「デコレータ」は関数の上に置きます。かわいらしい装飾的な帽子のようです(この用語の由来はそこにあると思います)。
- 私たちの場合、このデコレーターは直下の関数が**オペレーション** `get`を使用した**パス**` / `に対応することを**FastAPI** に通知します。
+「デコレータ」は直下の関数を受け取り、それを使って何かを行います。
- これが「*パスオペレーションデコレータ*」です。
+私たちの場合、このデコレーターは直下の関数が**オペレーション** `get`を使用した**パス**` / `に対応することを**FastAPI** に通知します。
+
+これが「*パスオペレーションデコレータ*」です。
+
+///
他のオペレーションも使用できます:
* `@app.patch()`
* `@app.trace()`
-!!! tip "豆知識"
- 各オペレーション (HTTPメソッド)は自由に使用できます。
+/// tip | "豆知識"
+
+各オペレーション (HTTPメソッド)は自由に使用できます。
- **FastAPI**は特定の意味づけを強制しません。
+**FastAPI**は特定の意味づけを強制しません。
- ここでの情報は、要件ではなくガイドラインとして提示されます。
+ここでの情報は、要件ではなくガイドラインとして提示されます。
- 例えば、GraphQLを使用する場合、通常は`POST`オペレーションのみを使用してすべてのアクションを実行します。
+例えば、GraphQLを使用する場合、通常は`POST`オペレーションのみを使用してすべてのアクションを実行します。
+
+///
### Step 4: **パスオペレーション**を定義
{!../../../docs_src/first_steps/tutorial003.py!}
```
-!!! note "備考"
- 違いが分からない場合は、[Async: *"急いでいますか?"*](../async.md#_1){.internal-link target=_blank}を確認してください。
+/// note | "備考"
+
+違いが分からない場合は、[Async: *"急いでいますか?"*](../async.md#_1){.internal-link target=_blank}を確認してください。
+
+///
### Step 5: コンテンツの返信
}
```
-!!! tip "豆知識"
- `HTTPException`を発生させる際には、`str`だけでなく、JSONに変換できる任意の値を`detail`パラメータとして渡すことができます。
+/// tip | "豆知識"
- `dist`や`list`などを渡すことができます。
+`HTTPException`を発生させる際には、`str`だけでなく、JSONに変換できる任意の値を`detail`パラメータとして渡すことができます。
- これらは **FastAPI** によって自動的に処理され、JSONに変換されます。
+`dist`や`list`などを渡すことができます。
+
+これらは **FastAPI** によって自動的に処理され、JSONに変換されます。
+
+///
## カスタムヘッダーの追加
{"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** は開発者の利便性を考慮して、`fastapi.responses`と同じ`starlette.responses`を提供しています。しかし、利用可能なレスポンスのほとんどはStarletteから直接提供されます。これは`Request`と同じです。
- **FastAPI** は開発者の利便性を考慮して、`fastapi.responses`と同じ`starlette.responses`を提供しています。しかし、利用可能なレスポンスのほとんどはStarletteから直接提供されます。これは`Request`と同じです。
+///
## デフォルトの例外ハンドラのオーバーライド
#### `RequestValidationError`と`ValidationError`
-!!! warning "注意"
- これらは今のあなたにとって重要でない場合は省略しても良い技術的な詳細です。
+/// warning | "注意"
+
+これらは今のあなたにとって重要でない場合は省略しても良い技術的な詳細です。
+
+///
`RequestValidationError`はPydanticの<a href="https://docs.pydantic.dev/latest/concepts/models/#error-handling" class="external-link" target="_blank">`ValidationError`</a>のサブクラスです。
{!../../../docs_src/handling_errors/tutorial004.py!}
```
-!!! note "技術詳細"
- また、`from starlette.responses import PlainTextResponse`を使用することもできます。
+/// note | "技術詳細"
+
+また、`from starlette.responses import PlainTextResponse`を使用することもできます。
+
+**FastAPI** は開発者の利便性を考慮して、`fastapi.responses`と同じ`starlette.responses`を提供しています。しかし、利用可能なレスポンスのほとんどはStarletteから直接提供されます。
- **FastAPI** は開発者の利便性を考慮して、`fastapi.responses`と同じ`starlette.responses`を提供しています。しかし、利用可能なレスポンスのほとんどはStarletteから直接提供されます。
+///
### `RequestValidationError`のボディの使用
{!../../../docs_src/header_params/tutorial001.py!}
```
-!!! note "技術詳細"
- `Header`は`Path`や`Query`、`Cookie`の「姉妹」クラスです。また、同じ共通の`Param`クラスを継承しています。
+/// note | "技術詳細"
- しかし、`fastapi`から`Query`や`Path`、`Header`などをインポートする場合、それらは実際には特殊なクラスを返す関数であることを覚えておいてください。
+`Header`は`Path`や`Query`、`Cookie`の「姉妹」クラスです。また、同じ共通の`Param`クラスを継承しています。
-!!! info "情報"
- ヘッダーを宣言するには、`Header`を使う必要があります。なぜなら、そうしないと、パラメータがクエリのパラメータとして解釈されてしまうからです。
+しかし、`fastapi`から`Query`や`Path`、`Header`などをインポートする場合、それらは実際には特殊なクラスを返す関数であることを覚えておいてください。
+
+///
+
+/// info | "情報"
+
+ヘッダーを宣言するには、`Header`を使う必要があります。なぜなら、そうしないと、パラメータがクエリのパラメータとして解釈されてしまうからです。
+
+///
## 自動変換
{!../../../docs_src/header_params/tutorial002.py!}
```
-!!! warning "注意"
- `convert_underscores`を`False`に設定する前に、HTTPプロキシやサーバの中にはアンダースコアを含むヘッダーの使用を許可していないものがあることに注意してください。
+/// warning | "注意"
+
+`convert_underscores`を`False`に設定する前に、HTTPプロキシやサーバの中にはアンダースコアを含むヘッダーの使用を許可していないものがあることに注意してください。
+///
## ヘッダーの重複
...これには、コードを実行するサーバーとして使用できる `uvicorn`も含まれます。
-!!! note "備考"
- パーツ毎にインストールすることも可能です。
+/// note | "備考"
- 以下は、アプリケーションを本番環境にデプロイする際に行うであろうものです:
+パーツ毎にインストールすることも可能です。
- ```
- pip install fastapi
- ```
+以下は、アプリケーションを本番環境にデプロイする際に行うであろうものです:
- また、サーバーとして動作するように`uvicorn` をインストールします:
+```
+pip install fastapi
+```
+
+また、サーバーとして動作するように`uvicorn` をインストールします:
+
+```
+pip install "uvicorn[standard]"
+```
- ```
- pip install "uvicorn[standard]"
- ```
+そして、使用したい依存関係をそれぞれ同様にインストールします。
- そして、使用したい依存関係をそれぞれ同様にインストールします。
+///
## 高度なユーザーガイド
説明文 (description) の中で Markdown を使用できることに注意してください。たとえば、「login」は太字 (**login**) で表示され、「fancy」は斜体 (_fancy_) で表示されます。
-!!! tip "豆知識"
- 使用するすべてのタグにメタデータを追加する必要はありません。
+/// tip | "豆知識"
+
+使用するすべてのタグにメタデータを追加する必要はありません。
+
+///
### 自作タグの使用
{!../../../docs_src/metadata/tutorial004.py!}
```
-!!! info "情報"
- タグのより詳しい説明を知りたい場合は [Path Operation Configuration](path-operation-configuration.md#tags){.internal-link target=_blank} を参照して下さい。
+/// info | "情報"
+
+タグのより詳しい説明を知りたい場合は [Path Operation Configuration](path-operation-configuration.md#tags){.internal-link target=_blank} を参照して下さい。
+
+///
### ドキュメントの確認
* その**レスポンス**に対して何かを実行したり、必要なコードを実行したりできます。
* そして、**レスポンス**を返します。
-!!! note "技術詳細"
- `yield` を使った依存関係をもつ場合は、終了コードはミドルウェアの *後に* 実行されます。
+/// note | "技術詳細"
- バックグラウンドタスク (後述) がある場合は、それらは全てのミドルウェアの *後に* 実行されます。
+`yield` を使った依存関係をもつ場合は、終了コードはミドルウェアの *後に* 実行されます。
+
+バックグラウンドタスク (後述) がある場合は、それらは全てのミドルウェアの *後に* 実行されます。
+
+///
## ミドルウェアの作成
{!../../../docs_src/middleware/tutorial001.py!}
```
-!!! tip "豆知識"
- <a href="https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers" class="external-link" target="_blank">'X-'プレフィックスを使用</a>してカスタムの独自ヘッダーを追加できます。
+/// tip | "豆知識"
+
+<a href="https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers" class="external-link" target="_blank">'X-'プレフィックスを使用</a>してカスタムの独自ヘッダーを追加できます。
+
+ただし、ブラウザのクライアントに表示させたいカスタムヘッダーがある場合は、<a href="https://www.starlette.io/middleware/#corsmiddleware" class="external-link" target="_blank">StarletteのCORSドキュメント</a>に記載されているパラメータ `expose_headers` を使用して、それらをCORS設定に追加する必要があります ([CORS (オリジン間リソース共有)](cors.md){.internal-link target=_blank})
+
+///
+
+/// note | "技術詳細"
- ただし、ブラウザのクライアントに表示させたいカスタムヘッダーがある場合は、<a href="https://www.starlette.io/middleware/#corsmiddleware" class="external-link" target="_blank">StarletteのCORSドキュメント</a>に記載されているパラメータ `expose_headers` を使用して、それらをCORS設定に追加する必要があります ([CORS (オリジン間リソース共有)](cors.md){.internal-link target=_blank})
+`from starlette.requests import Request` を使用することもできます。
-!!! note "技術詳細"
- `from starlette.requests import Request` を使用することもできます。
+**FastAPI**は、開発者の便利のためにこれを提供していますが、Starletteから直接きています。
- **FastAPI**は、開発者の便利のためにこれを提供していますが、Starletteから直接きています。
+///
### `response` の前後
*path operationデコレータ*を設定するためのパラメータがいくつかあります。
-!!! warning "注意"
- これらのパラメータは*path operation関数*ではなく、*path operationデコレータ*に直接渡されることに注意してください。
+/// warning | "注意"
+
+これらのパラメータは*path operation関数*ではなく、*path operationデコレータ*に直接渡されることに注意してください。
+
+///
## レスポンスステータスコード
そのステータスコードはレスポンスで使用され、OpenAPIスキーマに追加されます。
-!!! note "技術詳細"
- また、`from starlette import status`を使用することもできます。
+/// note | "技術詳細"
+
+また、`from starlette import status`を使用することもできます。
+
+**FastAPI** は開発者の利便性を考慮して、`fastapi.status`と同じ`starlette.status`を提供しています。しかし、これはStarletteから直接提供されています。
- **FastAPI** は開発者の利便性を考慮して、`fastapi.status`と同じ`starlette.status`を提供しています。しかし、これはStarletteから直接提供されています。
+///
## タグ
{!../../../docs_src/path_operation_configuration/tutorial005.py!}
```
-!!! info "情報"
- `respnse_description`は具体的にレスポンスを参照し、`description`は*path operation*全般を参照していることに注意してください。
+/// info | "情報"
+
+`respnse_description`は具体的にレスポンスを参照し、`description`は*path operation*全般を参照していることに注意してください。
+
+///
+
+/// check | "確認"
+
+OpenAPIは*path operation*ごとにレスポンスの説明を必要としています。
-!!! check "確認"
- OpenAPIは*path operation*ごとにレスポンスの説明を必要としています。
+そのため、それを提供しない場合は、**FastAPI** が自動的に「成功のレスポンス」を生成します。
- そのため、それを提供しない場合は、**FastAPI** が自動的に「成功のレスポンス」を生成します。
+///
<img src="https://fastapi.tiangolo.com/img/tutorial/path-operation-configuration/image03.png">
{!../../../docs_src/path_params_numeric_validations/tutorial001.py!}
```
-!!! note "備考"
- パスの一部でなければならないので、パスパラメータは常に必須です。
+/// note | "備考"
- そのため、`...`を使用して必須と示す必要があります。
+パスの一部でなければならないので、パスパラメータは常に必須です。
- それでも、`None`で宣言しても、デフォルト値を設定しても、何の影響もなく、常に必要とされていることに変わりはありません。
+そのため、`...`を使用して必須と示す必要があります。
+
+それでも、`None`で宣言しても、デフォルト値を設定しても、何の影響もなく、常に必要とされていることに変わりはありません。
+
+///
## 必要に応じてパラメータを並び替える
* `lt`: より小さい(`l`ess `t`han)
* `le`: 以下(`l`ess than or `e`qual)
-!!! info "情報"
- `Query`、`Path`などは後に共通の`Param`クラスのサブクラスを見ることになります。(使う必要はありません)
+/// info | "情報"
+
+`Query`、`Path`などは後に共通の`Param`クラスのサブクラスを見ることになります。(使う必要はありません)
+
+そして、それらすべては、これまで見てきた追加のバリデーションとメタデータと同じパラメータを共有しています。
+
+///
+
+/// note | "技術詳細"
- そして、それらすべては、これまで見てきた追加のバリデーションとメタデータと同じパラメータを共有しています。
+`fastapi`から\b`Query`、`Path`などをインポートすると、これらは実際には関数です。
-!!! note "技術詳細"
- `fastapi`から\b`Query`、`Path`などをインポートすると、これらは実際には関数です。
+呼び出されると、同じ名前のクラスのインスタンスを返します。
- 呼び出されると、同じ名前のクラスのインスタンスを返します。
+そのため、関数である`Query`をインポートし、それを呼び出すと、`Query`という名前のクラスのインスタンスが返されます。
- そのため、関数である`Query`をインポートし、それを呼び出すと、`Query`という名前のクラスのインスタンスが返されます。
+これらの関数は(クラスを直接使うのではなく)エディタが型についてエラーとしないようにするために存在します。
- これらの関数は(クラスを直接使うのではなく)エディタが型についてエラーとしないようにするために存在します。
+この方法によって、これらのエラーを無視するための設定を追加することなく、通常のエディタやコーディングツールを使用することができます。
- この方法によって、これらのエラーを無視するための設定を追加することなく、通常のエディタやコーディングツールを使用することができます。
+///
ここでは、 `item_id` は `int` として宣言されています。
-!!! check "確認"
- これにより、関数内でのエディターサポート (エラーチェックや補完など) が提供されます。
+/// check | "確認"
+
+これにより、関数内でのエディターサポート (エラーチェックや補完など) が提供されます。
+
+///
## データ<abbr title="別名: serialization, parsing, marshalling">変換</abbr>
{"item_id":3}
```
-!!! check "確認"
- 関数が受け取った(および返した)値は、文字列の `"3"` ではなく、Pythonの `int` としての `3` であることに注意してください。
+/// check | "確認"
+
+関数が受け取った(および返した)値は、文字列の `"3"` ではなく、Pythonの `int` としての `3` であることに注意してください。
+
+したがって、型宣言を使用すると、**FastAPI**は自動リクエスト <abbr title="HTTPリクエストで受け取った文字列をPythonデータへ変換する">"解析"</abbr> を行います。
- したがって、型宣言を使用すると、**FastAPI**は自動リクエスト <abbr title="HTTPリクエストで受け取った文字列をPythonデータへ変換する">"解析"</abbr> を行います。
+///
## データバリデーション
<a href="http://127.0.0.1:8000/items/4.2" class="external-link" target="_blank">http://127.0.0.1:8000/items/4.2</a> で見られるように、intのかわりに `float` が与えられた場合にも同様なエラーが表示されます。
-!!! check "確認"
- したがって、Pythonの型宣言を使用することで、**FastAPI**はデータのバリデーションを行います。
+/// check | "確認"
- 表示されたエラーには問題のある箇所が明確に指摘されていることに注意してください。
+したがって、Pythonの型宣言を使用することで、**FastAPI**はデータのバリデーションを行います。
- これは、APIに関連するコードの開発およびデバッグに非常に役立ちます。
+表示されたエラーには問題のある箇所が明確に指摘されていることに注意してください。
+
+これは、APIに関連するコードの開発およびデバッグに非常に役立ちます。
+
+///
## ドキュメント
<img src="/img/tutorial/path-params/image01.png">
-!!! check "確認"
- 繰り返しになりますが、Python型宣言を使用するだけで、**FastAPI**は対話的なAPIドキュメントを自動的に生成します(Swagger UIを統合)。
+/// check | "確認"
+
+繰り返しになりますが、Python型宣言を使用するだけで、**FastAPI**は対話的なAPIドキュメントを自動的に生成します(Swagger UIを統合)。
+
+パスパラメータが整数として宣言されていることに注意してください。
- パスパラメータが整数として宣言されていることに注意してください。
+///
## 標準であることのメリット、ドキュメンテーションの代替物
{!../../../docs_src/path_params/tutorial005.py!}
```
-!!! info "情報"
- <a href="https://docs.python.org/3/library/enum.html" class="external-link" target="_blank">Enumerations (もしくは、enums)はPython 3.4以降で利用できます</a>。
+/// info | "情報"
-!!! tip "豆知識"
- "AlexNet"、"ResNet"そして"LeNet"は機械学習<abbr title="Technically, Deep Learning model architectures">モデル</abbr>の名前です。
+<a href="https://docs.python.org/3/library/enum.html" class="external-link" target="_blank">Enumerations (もしくは、enums)はPython 3.4以降で利用できます</a>。
+
+///
+
+/// tip | "豆知識"
+
+"AlexNet"、"ResNet"そして"LeNet"は機械学習<abbr title="Technically, Deep Learning model architectures">モデル</abbr>の名前です。
+
+///
### *パスパラメータ*の宣言
{!../../../docs_src/path_params/tutorial005.py!}
```
-!!! tip "豆知識"
- `ModelName.lenet.value` でも `"lenet"` 値にアクセスできます。
+/// tip | "豆知識"
+
+`ModelName.lenet.value` でも `"lenet"` 値にアクセスできます。
+
+///
#### *列挙型メンバ*の返却
{!../../../docs_src/path_params/tutorial004.py!}
```
-!!! tip "豆知識"
- 最初のスラッシュ (`/`)が付いている `/home/johndoe/myfile.txt` をパラメータが含んでいる必要があります。
+/// tip | "豆知識"
+
+最初のスラッシュ (`/`)が付いている `/home/johndoe/myfile.txt` をパラメータが含んでいる必要があります。
+
+この場合、URLは `files` と `home` の間にダブルスラッシュ (`//`) のある、 `/files//home/johndoe/myfile.txt` になります。
- この場合、URLは `files` と `home` の間にダブルスラッシュ (`//`) のある、 `/files//home/johndoe/myfile.txt` になります。
+///
## まとめ
クエリパラメータ `q` は `Optional[str]` 型で、`None` を許容する `str` 型を意味しており、デフォルトは `None` です。そのため、FastAPIはそれが必須ではないと理解します。
-!!! note "備考"
- FastAPIは、 `q` はデフォルト値が `=None` であるため、必須ではないと理解します。
+/// note | "備考"
+
+FastAPIは、 `q` はデフォルト値が `=None` であるため、必須ではないと理解します。
+
+`Optional[str]` における `Optional` はFastAPIには利用されませんが、エディターによるより良いサポートとエラー検出を可能にします。
+
+///
- `Optional[str]` における `Optional` はFastAPIには利用されませんが、エディターによるより良いサポートとエラー検出を可能にします。
## バリデーションの追加
`q`はオプショナルですが、もし値が渡されてきた場合には、**50文字を超えないこと**を強制してみましょう。
しかし、これはクエリパラメータとして明示的に宣言しています。
-!!! info "情報"
- FastAPIは以下の部分を気にすることを覚えておいてください:
+/// info | "情報"
+
+FastAPIは以下の部分を気にすることを覚えておいてください:
+
+```Python
+= None
+```
- ```Python
- = None
- ```
+もしくは:
- もしくは:
+```Python
+= Query(default=None)
+```
- ```Python
- = Query(default=None)
- ```
+そして、 `None` を利用することでクエリパラメータが必須ではないと検知します。
- そして、 `None` を利用することでクエリパラメータが必須ではないと検知します。
+`Optional` の部分は、エディターによるより良いサポートを可能にします。
- `Optional` の部分は、エディターによるより良いサポートを可能にします。
+///
そして、さらに多くのパラメータを`Query`に渡すことができます。この場合、文字列に適用される、`max_length`パラメータを指定します。
{!../../../docs_src/query_params_str_validations/tutorial005.py!}
```
-!!! note "備考"
- デフォルト値を指定すると、パラメータは任意になります。
+/// note | "備考"
+
+デフォルト値を指定すると、パラメータは任意になります。
+
+///
## 必須にする
{!../../../docs_src/query_params_str_validations/tutorial006.py!}
```
-!!! info "情報"
- これまで`...`を見たことがない方へ: これは特殊な単一値です。<a href="https://docs.python.org/3/library/constants.html#Ellipsis" class="external-link" target="_blank">Pythonの一部であり、"Ellipsis"と呼ばれています</a>。
+/// info | "情報"
+
+これまで`...`を見たことがない方へ: これは特殊な単一値です。<a href="https://docs.python.org/3/library/constants.html#Ellipsis" class="external-link" target="_blank">Pythonの一部であり、"Ellipsis"と呼ばれています</a>。
+
+///
これは **FastAPI** にこのパラメータが必須であることを知らせます。
}
```
-!!! tip "豆知識"
- 上述の例のように、`list`型のクエリパラメータを宣言するには明示的に`Query`を使用する必要があります。そうしない場合、リクエストボディと解釈されます。
+/// tip | "豆知識"
+
+上述の例のように、`list`型のクエリパラメータを宣言するには明示的に`Query`を使用する必要があります。そうしない場合、リクエストボディと解釈されます。
+
+///
対話的APIドキュメントは複数の値を許可するために自動的に更新されます。
{!../../../docs_src/query_params_str_validations/tutorial013.py!}
```
-!!! note "備考"
- この場合、FastAPIはリストの内容をチェックしないことを覚えておいてください。
+/// note | "備考"
- 例えば`List[int]`はリストの内容が整数であるかどうかをチェックします(そして、文書化します)。しかし`list`だけではそうしません。
+この場合、FastAPIはリストの内容をチェックしないことを覚えておいてください。
+
+例えば`List[int]`はリストの内容が整数であるかどうかをチェックします(そして、文書化します)。しかし`list`だけではそうしません。
+
+///
## より多くのメタデータを宣言する
その情報は、生成されたOpenAPIに含まれ、ドキュメントのユーザーインターフェースや外部のツールで使用されます。
-!!! note "備考"
- ツールによってOpenAPIのサポートのレベルが異なる可能性があることを覚えておいてください。
+/// note | "備考"
+
+ツールによってOpenAPIのサポートのレベルが異なる可能性があることを覚えておいてください。
+
+その中には、宣言されたすべての追加情報が表示されていないものもあるかもしれませんが、ほとんどの場合、不足している機能はすでに開発の計画がされています。
- その中には、宣言されたすべての追加情報が表示されていないものもあるかもしれませんが、ほとんどの場合、不足している機能はすでに開発の計画がされています。
+///
`title`を追加できます:
-
# クエリパラメータ
パスパラメータではない関数パラメータを宣言すると、それらは自動的に "クエリ" パラメータとして解釈されます。
この場合、関数パラメータ `q` はオプショナルとなり、デフォルトでは `None` になります。
-!!! check "確認"
- パスパラメータ `item_id` はパスパラメータであり、`q` はそれとは違ってクエリパラメータであると判別できるほど**FastAPI** が賢いということにも注意してください。
+/// check | "確認"
+
+パスパラメータ `item_id` はパスパラメータであり、`q` はそれとは違ってクエリパラメータであると判別できるほど**FastAPI** が賢いということにも注意してください。
+
+///
## クエリパラメータの型変換
* `skip`、デフォルト値を `0` とする `int` 。
* `limit`、オプショナルな `int` 。
-!!! tip "豆知識"
+/// tip | "豆知識"
+
+[パスパラメータ](path-params.md#_8){.internal-link target=_blank}と同様に `Enum` を使用できます。
- [パスパラメータ](path-params.md#_8){.internal-link target=_blank}と同様に `Enum` を使用できます。
+///
`File`と`Form`を同時に使うことでファイルとフォームフィールドを定義することができます。
-!!! info "情報"
- アップロードされたファイルやフォームデータを受信するには、まず<a href="https://andrew-d.github.io/python-multipart/" class="external-link" target="_blank">`python-multipart`</a>をインストールします。
+/// info | "情報"
- 例えば、`pip install python-multipart`のように。
+アップロードされたファイルやフォームデータを受信するには、まず<a href="https://andrew-d.github.io/python-multipart/" class="external-link" target="_blank">`python-multipart`</a>をインストールします。
+
+例えば、`pip install python-multipart`のように。
+
+///
## `File`と`Form`のインポート
また、いくつかのファイルを`bytes`として、いくつかのファイルを`UploadFile`として宣言することができます。
-!!! warning "注意"
- *path operation*で複数の`File`と`Form`パラメータを宣言することができますが、JSONとして受け取ることを期待している`Body`フィールドを宣言することはできません。なぜなら、リクエストのボディは`application/json`の代わりに`multipart/form-data`を使ってエンコードされているからです。
+/// warning | "注意"
+
+*path operation*で複数の`File`と`Form`パラメータを宣言することができますが、JSONとして受け取ることを期待している`Body`フィールドを宣言することはできません。なぜなら、リクエストのボディは`application/json`の代わりに`multipart/form-data`を使ってエンコードされているからです。
+
+これは **FastAPI** の制限ではなく、HTTPプロトコルの一部です。
- これは **FastAPI** の制限ではなく、HTTPプロトコルの一部です。
+///
## まとめ
JSONの代わりにフィールドを受け取る場合は、`Form`を使用します。
-!!! info "情報"
- フォームを使うためには、まず<a href="https://github.com/Kludex/python-multipart" class="external-link" target="_blank">`python-multipart`</a>をインストールします。
+/// info | "情報"
- たとえば、`pip install python-multipart`のように。
+フォームを使うためには、まず<a href="https://github.com/Kludex/python-multipart" class="external-link" target="_blank">`python-multipart`</a>をインストールします。
+
+たとえば、`pip install python-multipart`のように。
+
+///
## `Form`のインポート
`Form`では`Body`(および`Query`や`Path`、`Cookie`)と同じメタデータとバリデーションを宣言することができます。
-!!! info "情報"
- `Form`は`Body`を直接継承するクラスです。
+/// info | "情報"
+
+`Form`は`Body`を直接継承するクラスです。
+
+///
+
+/// tip | "豆知識"
-!!! tip "豆知識"
- フォームのボディを宣言するには、明示的に`Form`を使用する必要があります。なぜなら、これを使わないと、パラメータはクエリパラメータやボディ(JSON)パラメータとして解釈されるからです。
+フォームのボディを宣言するには、明示的に`Form`を使用する必要があります。なぜなら、これを使わないと、パラメータはクエリパラメータやボディ(JSON)パラメータとして解釈されるからです。
+
+///
## 「フォームフィールド」について
**FastAPI** は、JSONの代わりにそのデータを適切な場所から読み込むようにします。
-!!! note "技術詳細"
- フォームからのデータは通常、`application/x-www-form-urlencoded`の「media type」を使用してエンコードされます。
+/// note | "技術詳細"
+
+フォームからのデータは通常、`application/x-www-form-urlencoded`の「media type」を使用してエンコードされます。
+
+しかし、フォームがファイルを含む場合は、`multipart/form-data`としてエンコードされます。ファイルの扱いについては次の章で説明します。
+
+これらのエンコーディングやフォームフィールドの詳細については、<a href="https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods/POST" class="external-link" target="_blank"><abbr title="Mozilla Developer Network">MDN</abbr>の<code>POST</code></a>のウェブドキュメントを参照してください。
+
+///
- しかし、フォームがファイルを含む場合は、`multipart/form-data`としてエンコードされます。ファイルの扱いについては次の章で説明します。
+/// warning | "注意"
- これらのエンコーディングやフォームフィールドの詳細については、<a href="https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods/POST" class="external-link" target="_blank"><abbr title="Mozilla Developer Network">MDN</abbr>の<code>POST</code></a>のウェブドキュメントを参照してください。
+*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プロトコルの一部です。
+///
## まとめ
{!../../../docs_src/response_model/tutorial001.py!}
```
-!!! note "備考"
- `response_model`は「デコレータ」メソッド(`get`、`post`など)のパラメータであることに注意してください。すべてのパラメータやボディのように、*path operation関数* のパラメータではありません。
+/// note | "備考"
+
+`response_model`は「デコレータ」メソッド(`get`、`post`など)のパラメータであることに注意してください。すべてのパラメータやボディのように、*path operation関数* のパラメータではありません。
+
+///
Pydanticモデルの属性に対して宣言するのと同じ型を受け取るので、Pydanticモデルになることもできますが、例えば、`List[Item]`のようなPydanticモデルの`list`になることもできます。
* 出力データをモデルのデータに限定します。これがどのように重要なのか以下で見ていきましょう。
-!!! note "技術詳細"
- レスポンスモデルは、関数の戻り値のアノテーションではなく、このパラメータで宣言されています。なぜなら、パス関数は実際にはそのレスポンスモデルを返すのではなく、`dict`やデータベースオブジェクト、あるいは他のモデルを返し、`response_model`を使用してフィールドの制限やシリアライズを行うからです。
+/// note | "技術詳細"
+
+レスポンスモデルは、関数の戻り値のアノテーションではなく、このパラメータで宣言されています。なぜなら、パス関数は実際にはそのレスポンスモデルを返すのではなく、`dict`やデータベースオブジェクト、あるいは他のモデルを返し、`response_model`を使用してフィールドの制限やシリアライズを行うからです。
+
+///
## 同じ入力データの返却
しかし、同じモデルを別の*path operation*に使用すると、すべてのクライアントにユーザーのパスワードを送信してしまうことになります。
-!!! danger "危険"
- ユーザーの平文のパスワードを保存したり、レスポンスで送信したりすることは絶対にしないでください。
+/// danger | "危険"
+
+ユーザーの平文のパスワードを保存したり、レスポンスで送信したりすることは絶対にしないでください。
+
+///
## 出力モデルの追加
}
```
-!!! info "情報"
- FastAPIはこれをするために、Pydanticモデルの`.dict()`を<a href="https://docs.pydantic.dev/latest/concepts/serialization/#modeldict" class="external-link" target="_blank">その`exclude_unset`パラメータ</a>で使用しています。
+/// info | "情報"
+
+FastAPIはこれをするために、Pydanticモデルの`.dict()`を<a href="https://docs.pydantic.dev/latest/concepts/serialization/#modeldict" class="external-link" target="_blank">その`exclude_unset`パラメータ</a>で使用しています。
+
+///
-!!! info "情報"
- 以下も使用することができます:
+/// info | "情報"
- * `response_model_exclude_defaults=True`
- * `response_model_exclude_none=True`
+以下も使用することができます:
- `exclude_defaults`と`exclude_none`については、<a href="https://docs.pydantic.dev/latest/concepts/serialization/#modeldict" class="external-link" target="_blank">Pydanticのドキュメント</a>で説明されている通りです。
+* `response_model_exclude_defaults=True`
+* `response_model_exclude_none=True`
+
+`exclude_defaults`と`exclude_none`については、<a href="https://docs.pydantic.dev/latest/concepts/serialization/#modeldict" class="external-link" target="_blank">Pydanticのドキュメント</a>で説明されている通りです。
+
+///
#### デフォルト値を持つフィールドの値を持つデータ
そのため、それらはJSONレスポンスに含まれることになります。
-!!! tip "豆知識"
- デフォルト値は`None`だけでなく、なんでも良いことに注意してください。
- 例えば、リスト(`[]`)や`10.5`の`float`などです。
+/// tip | "豆知識"
+
+デフォルト値は`None`だけでなく、なんでも良いことに注意してください。
+例えば、リスト(`[]`)や`10.5`の`float`などです。
+
+///
### `response_model_include`と`response_model_exclude`
これは、Pydanticモデルが1つしかなく、出力からいくつかのデータを削除したい場合のクイックショートカットとして使用することができます。
-!!! tip "豆知識"
- それでも、これらのパラメータではなく、複数のクラスを使用して、上記のようなアイデアを使うことをおすすめします。
+/// tip | "豆知識"
- これは`response_model_include`や`response_mode_exclude`を使用していくつかの属性を省略しても、アプリケーションのOpenAPI(とドキュメント)で生成されたJSON Schemaが完全なモデルになるからです。
+それでも、これらのパラメータではなく、複数のクラスを使用して、上記のようなアイデアを使うことをおすすめします。
- 同様に動作する`response_model_by_alias`にも当てはまります。
+これは`response_model_include`や`response_mode_exclude`を使用していくつかの属性を省略しても、アプリケーションのOpenAPI(とドキュメント)で生成されたJSON Schemaが完全なモデルになるからです。
+
+同様に動作する`response_model_by_alias`にも当てはまります。
+
+///
```Python hl_lines="31 37"
{!../../../docs_src/response_model/tutorial005.py!}
```
-!!! tip "豆知識"
- `{"name", "description"}`の構文はこれら2つの値をもつ`set`を作成します。
+/// tip | "豆知識"
+
+`{"name", "description"}`の構文はこれら2つの値をもつ`set`を作成します。
+
+これは`set(["name", "description"])`と同等です。
- これは`set(["name", "description"])`と同等です。
+///
#### `set`の代わりに`list`を使用する
{!../../../docs_src/response_status_code/tutorial001.py!}
```
-!!! note "備考"
- `status_code`は「デコレータ」メソッド(`get`、`post`など)のパラメータであることに注意してください。すべてのパラメータやボディのように、*path operation関数*のものではありません。
+/// note | "備考"
+
+`status_code`は「デコレータ」メソッド(`get`、`post`など)のパラメータであることに注意してください。すべてのパラメータやボディのように、*path operation関数*のものではありません。
+
+///
`status_code`パラメータはHTTPステータスコードを含む数値を受け取ります。
-!!! info "情報"
- `status_code`は代わりに、Pythonの<a href="https://docs.python.org/3/library/http.html#http.HTTPStatus" class="external-link" target="_blank">`http.HTTPStatus`</a>のように、`IntEnum`を受け取ることもできます。
+/// info | "情報"
+
+`status_code`は代わりに、Pythonの<a href="https://docs.python.org/3/library/http.html#http.HTTPStatus" class="external-link" target="_blank">`http.HTTPStatus`</a>のように、`IntEnum`を受け取ることもできます。
+
+///
これは:
<img src="https://fastapi.tiangolo.com/img/tutorial/response-status-code/image01.png">
-!!! note "備考"
- いくつかのレスポンスコード(次のセクションを参照)は、レスポンスにボディがないことを示しています。
+/// note | "備考"
+
+いくつかのレスポンスコード(次のセクションを参照)は、レスポンスにボディがないことを示しています。
+
+FastAPIはこれを知っていて、レスポンスボディがないというOpenAPIドキュメントを生成します。
- FastAPIはこれを知っていて、レスポンスボディがないというOpenAPIドキュメントを生成します。
+///
## HTTPステータスコードについて
-!!! note "備考"
- すでにHTTPステータスコードが何であるかを知っている場合は、次のセクションにスキップしてください。
+/// note | "備考"
+
+すでにHTTPステータスコードが何であるかを知っている場合は、次のセクションにスキップしてください。
+
+///
HTTPでは、レスポンスの一部として3桁の数字のステータスコードを送信します。
* クライアントからの一般的なエラーについては、`400`を使用することができます。
* `500`以上はサーバーエラーのためのものです。これらを直接使うことはほとんどありません。アプリケーションコードやサーバーのどこかで何か問題が発生した場合、これらのステータスコードのいずれかが自動的に返されます。
-!!! tip "豆知識"
- それぞれのステータスコードとどのコードが何のためのコードなのかについて詳細は<a href="https://developer.mozilla.org/en-US/docs/Web/HTTP/Status" class="external-link" target="_blank"><abbr title="Mozilla Developer Network">MDN</abbr> HTTP レスポンスステータスコードについてのドキュメント</a>を参照してください。
+/// tip | "豆知識"
+
+それぞれのステータスコードとどのコードが何のためのコードなのかについて詳細は<a href="https://developer.mozilla.org/en-US/docs/Web/HTTP/Status" class="external-link" target="_blank"><abbr title="Mozilla Developer Network">MDN</abbr> HTTP レスポンスステータスコードについてのドキュメント</a>を参照してください。
+
+///
## 名前を覚えるための近道
<img src="https://fastapi.tiangolo.com/img/tutorial/response-status-code/image02.png">
-!!! note "技術詳細"
- また、`from starlette import status`を使うこともできます。
+/// note | "技術詳細"
+
+また、`from starlette import status`を使うこともできます。
+
+**FastAPI** は、`開発者の利便性を考慮して、fastapi.status`と同じ`starlette.status`を提供しています。しかし、これはStarletteから直接提供されています。
- **FastAPI** は、`開発者の利便性を考慮して、fastapi.status`と同じ`starlette.status`を提供しています。しかし、これはStarletteから直接提供されています。
+///
## デフォルトの変更
{!../../../docs_src/schema_extra_example/tutorial002.py!}
```
-!!! warning "注意"
- これらの追加引数が渡されても、文書化のためのバリデーションは追加されず、注釈だけが追加されることを覚えておいてください。
+/// warning | "注意"
+
+これらの追加引数が渡されても、文書化のためのバリデーションは追加されず、注釈だけが追加されることを覚えておいてください。
+
+///
## `Body`の追加引数
## 実行
-!!! info "情報"
- まず<a href="https://github.com/Kludex/python-multipart" class="external-link" target="_blank">`python-multipart`</a>をインストールします。
+/// info | "情報"
- 例えば、`pip install python-multipart`。
+まず<a href="https://github.com/Kludex/python-multipart" class="external-link" target="_blank">`python-multipart`</a>をインストールします。
- これは、**OAuth2**が `ユーザー名` や `パスワード` を送信するために、「フォームデータ」を使うからです。
+例えば、`pip install python-multipart`。
+
+これは、**OAuth2**が `ユーザー名` や `パスワード` を送信するために、「フォームデータ」を使うからです。
+
+///
例を実行します:
<img src="/img/tutorial/security/image01.png">
-!!! check "Authorizeボタン!"
- すでにピカピカの新しい「Authorize」ボタンがあります。
+/// check | "Authorizeボタン!"
+
+すでにピカピカの新しい「Authorize」ボタンがあります。
+
+そして、あなたの*path operation*には、右上にクリックできる小さな鍵アイコンがあります。
- そして、あなたの*path operation*には、右上にクリックできる小さな鍵アイコンがあります。
+///
それをクリックすると、`ユーザー名`と`パスワード` (およびその他のオプションフィールド) を入力する小さな認証フォームが表示されます:
<img src="/img/tutorial/security/image02.png">
-!!! note "備考"
- フォームに何を入力しても、まだうまくいきません。ですが、これから動くようになります。
+/// note | "備考"
+
+フォームに何を入力しても、まだうまくいきません。ですが、これから動くようになります。
+
+///
もちろんエンドユーザーのためのフロントエンドではありません。しかし、すべてのAPIをインタラクティブにドキュメント化するための素晴らしい自動ツールです。
この例では、**Bearer**トークンを使用して**OAuth2**を**パスワード**フローで使用します。これには`OAuth2PasswordBearer`クラスを使用します。
-!!! info "情報"
- 「bearer」トークンが、唯一の選択肢ではありません。
+/// info | "情報"
+
+「bearer」トークンが、唯一の選択肢ではありません。
- しかし、私たちのユースケースには最適です。
+しかし、私たちのユースケースには最適です。
- あなたがOAuth2の専門家で、あなたのニーズに適した別のオプションがある理由を正確に知っている場合を除き、ほとんどのユースケースに最適かもしれません。
+あなたがOAuth2の専門家で、あなたのニーズに適した別のオプションがある理由を正確に知っている場合を除き、ほとんどのユースケースに最適かもしれません。
- その場合、**FastAPI**はそれを構築するためのツールも提供します。
+その場合、**FastAPI**はそれを構築するためのツールも提供します。
+
+///
`OAuth2PasswordBearer` クラスのインスタンスを作成する時に、パラメーター`tokenUrl`を渡します。このパラメーターには、クライアント (ユーザーのブラウザで動作するフロントエンド) がトークンを取得するために`ユーザー名`と`パスワード`を送信するURLを指定します。
{!../../../docs_src/security/tutorial001.py!}
```
-!!! tip "豆知識"
- ここで、`tokenUrl="token"`は、まだ作成していない相対URL`token`を指します。相対URLなので、`./token`と同じです。
+/// tip | "豆知識"
+
+ここで、`tokenUrl="token"`は、まだ作成していない相対URL`token`を指します。相対URLなので、`./token`と同じです。
- 相対URLを使っているので、APIが`https://example.com/`にある場合、`https://example.com/token`を参照します。しかし、APIが`https://example.com/api/v1/`にある場合は`https://example.com/api/v1/token`を参照することになります。
+相対URLを使っているので、APIが`https://example.com/`にある場合、`https://example.com/token`を参照します。しかし、APIが`https://example.com/api/v1/`にある場合は`https://example.com/api/v1/token`を参照することになります。
- 相対 URL を使うことは、[プロキシと接続](../../advanced/behind-a-proxy.md){.internal-link target=_blank}のような高度なユースケースでもアプリケーションを動作させ続けるために重要です。
+相対 URL を使うことは、[プロキシと接続](../../advanced/behind-a-proxy.md){.internal-link target=_blank}のような高度なユースケースでもアプリケーションを動作させ続けるために重要です。
+
+///
このパラメーターはエンドポイント/ *path operation*を作成しません。しかし、URL`/token`はクライアントがトークンを取得するために使用するものであると宣言します。この情報は OpenAPI やインタラクティブな API ドキュメントシステムで使われます。
実際のpath operationもすぐに作ります。
-!!! info "情報"
- 非常に厳格な「Pythonista」であれば、パラメーター名のスタイルが`token_url`ではなく`tokenUrl`であることを気に入らないかもしれません。
+/// info | "情報"
+
+非常に厳格な「Pythonista」であれば、パラメーター名のスタイルが`token_url`ではなく`tokenUrl`であることを気に入らないかもしれません。
- それはOpenAPI仕様と同じ名前を使用しているからです。そのため、これらのセキュリティスキームについてもっと調べる必要がある場合は、それをコピーして貼り付ければ、それについての詳細な情報を見つけることができます。
+それはOpenAPI仕様と同じ名前を使用しているからです。そのため、これらのセキュリティスキームについてもっと調べる必要がある場合は、それをコピーして貼り付ければ、それについての詳細な情報を見つけることができます。
+
+///
変数`oauth2_scheme`は`OAuth2PasswordBearer`のインスタンスですが、「呼び出し可能」です。
**FastAPI**は、この依存関係を使用してOpenAPIスキーマ (および自動APIドキュメント) で「セキュリティスキーム」を定義できることを知っています。
-!!! info "技術詳細"
- **FastAPI**は、`OAuth2PasswordBearer` クラス (依存関係で宣言されている) を使用してOpenAPIのセキュリティスキームを定義できることを知っています。これは`fastapi.security.oauth2.OAuth2`、`fastapi.security.base.SecurityBase`を継承しているからです。
+/// info | "技術詳細"
+
+**FastAPI**は、`OAuth2PasswordBearer` クラス (依存関係で宣言されている) を使用してOpenAPIのセキュリティスキームを定義できることを知っています。これは`fastapi.security.oauth2.OAuth2`、`fastapi.security.base.SecurityBase`を継承しているからです。
+
+OpenAPIと統合するセキュリティユーティリティ (および自動APIドキュメント) はすべて`SecurityBase`を継承しています。それにより、**FastAPI**はそれらをOpenAPIに統合する方法を知ることができます。
- OpenAPIと統合するセキュリティユーティリティ (および自動APIドキュメント) はすべて`SecurityBase`を継承しています。それにより、**FastAPI**はそれらをOpenAPIに統合する方法を知ることができます。
+///
## どのように動作するか
その関数の中ですべての入力補完や型チェックを行う際に役に立ちます。
-!!! tip "豆知識"
- リクエストボディはPydanticモデルでも宣言できることを覚えているかもしれません。
+/// tip | "豆知識"
- ここでは `Depends` を使っているおかげで、 **FastAPI** が混乱することはありません。
+リクエストボディはPydanticモデルでも宣言できることを覚えているかもしれません。
+ここでは `Depends` を使っているおかげで、 **FastAPI** が混乱することはありません。
-!!! check "確認"
- 依存関係システムがこのように設計されているおかげで、 `User` モデルを返却する別の依存関係(別の"dependables")を持つことができます。
+///
- 同じデータ型を返却する依存関係は一つだけしか持てない、という制約が入ることはないのです。
+/// check | "確認"
+依存関係システムがこのように設計されているおかげで、 `User` モデルを返却する別の依存関係(別の"dependables")を持つことができます。
+
+同じデータ型を返却する依存関係は一つだけしか持てない、という制約が入ることはないのです。
+
+///
## 別のモデル
OAuth2は、通信を暗号化する方法を指定せず、アプリケーションがHTTPSで提供されることを想定しています。
-!!! tip "豆知識"
- **デプロイ**のセクションでは、TraefikとLet's Encryptを使用して、無料でHTTPSを設定する方法が紹介されています。
+/// tip | "豆知識"
+**デプロイ**のセクションでは、TraefikとLet's Encryptを使用して、無料でHTTPSを設定する方法が紹介されています。
+
+///
## OpenID Connect
* この自動検出メカニズムは、OpenID Connectの仕様で定義されているものです。
-!!! tip "豆知識"
- Google、Facebook、Twitter、GitHubなど、他の認証/認可プロバイダを統合することも可能で、比較的簡単です。
+/// tip | "豆知識"
+
+Google、Facebook、Twitter、GitHubなど、他の認証/認可プロバイダを統合することも可能で、比較的簡単です。
+
+最も複雑な問題は、それらのような認証/認可プロバイダを構築することですが、**FastAPI**は、あなたのために重い仕事をこなしながら、それを簡単に行うためのツールを提供します。
- 最も複雑な問題は、それらのような認証/認可プロバイダを構築することですが、**FastAPI**は、あなたのために重い仕事をこなしながら、それを簡単に行うためのツールを提供します。
+///
## **FastAPI** ユーティリティ
ここでは、推奨されているものを使用します:<a href="https://cryptography.io/" class="external-link" target="_blank">pyca/cryptography</a>。
-!!! tip "豆知識"
- このチュートリアルでは以前、<a href="https://pyjwt.readthedocs.io/" class="external-link" target="_blank">PyJWT</a>を使用していました。
+/// tip | "豆知識"
- しかし、Python-joseは、PyJWTのすべての機能に加えて、後に他のツールと統合して構築する際におそらく必要となる可能性のあるいくつかの追加機能を提供しています。そのため、代わりにPython-joseを使用するように更新されました。
+このチュートリアルでは以前、<a href="https://pyjwt.readthedocs.io/" class="external-link" target="_blank">PyJWT</a>を使用していました。
+
+しかし、Python-joseは、PyJWTのすべての機能に加えて、後に他のツールと統合して構築する際におそらく必要となる可能性のあるいくつかの追加機能を提供しています。そのため、代わりにPython-joseを使用するように更新されました。
+
+///
## パスワードのハッシュ化
</div>
-!!! tip "豆知識"
- `passlib`を使用すると、**Django**や**Flask**のセキュリティプラグインなどで作成されたパスワードを読み取れるように設定できます。
+/// tip | "豆知識"
+
+`passlib`を使用すると、**Django**や**Flask**のセキュリティプラグインなどで作成されたパスワードを読み取れるように設定できます。
- 例えば、Djangoアプリケーションからデータベース内の同じデータをFastAPIアプリケーションと共有できるだけではなく、同じデータベースを使用してDjangoアプリケーションを徐々に移行することもできます。
+例えば、Djangoアプリケーションからデータベース内の同じデータをFastAPIアプリケーションと共有できるだけではなく、同じデータベースを使用してDjangoアプリケーションを徐々に移行することもできます。
- また、ユーザーはDjangoアプリまたは**FastAPI**アプリからも、同時にログインできるようになります。
+また、ユーザーはDjangoアプリまたは**FastAPI**アプリからも、同時にログインできるようになります。
+///
## パスワードのハッシュ化と検証
PassLib の「context」を作成します。これは、パスワードのハッシュ化と検証に使用されるものです。
-!!! tip "豆知識"
- PassLibのcontextには、検証だけが許された非推奨の古いハッシュアルゴリズムを含む、様々なハッシュアルゴリズムを使用した検証機能もあります。
+/// tip | "豆知識"
- 例えば、この機能を使用して、別のシステム(Djangoなど)によって生成されたパスワードを読み取って検証し、Bcryptなどの別のアルゴリズムを使用して新しいパスワードをハッシュするといったことができます。
+PassLibのcontextには、検証だけが許された非推奨の古いハッシュアルゴリズムを含む、様々なハッシュアルゴリズムを使用した検証機能もあります。
- そして、同時にそれらはすべてに互換性があります。
+例えば、この機能を使用して、別のシステム(Djangoなど)によって生成されたパスワードを読み取って検証し、Bcryptなどの別のアルゴリズムを使用して新しいパスワードをハッシュするといったことができます。
+
+そして、同時にそれらはすべてに互換性があります。
+
+///
ユーザーから送られてきたパスワードをハッシュ化するユーティリティー関数を作成します。
{!../../../docs_src/security/tutorial004.py!}
```
-!!! note "備考"
- 新しい(偽の)データベース`fake_users_db`を確認すると、ハッシュ化されたパスワードが次のようになっていることがわかります:`"$2b$12$EixZaYVK1fsbw1ZfbX3OXePaWxn96p36WQoeG6Lruj3vjPGga31lW"`
+/// note | "備考"
+
+新しい(偽の)データベース`fake_users_db`を確認すると、ハッシュ化されたパスワードが次のようになっていることがわかります:`"$2b$12$EixZaYVK1fsbw1ZfbX3OXePaWxn96p36WQoeG6Lruj3vjPGga31lW"`
+
+///
## JWTトークンの取り扱い
Username: `johndoe`
Password: `secret`
-!!! check "確認"
- コードのどこにも平文のパスワード"`secret`"はなく、ハッシュ化されたものしかないことを確認してください。
+/// check | "確認"
+
+コードのどこにも平文のパスワード"`secret`"はなく、ハッシュ化されたものしかないことを確認してください。
+
+///
<img src="/img/tutorial/security/image08.png">
<img src="/img/tutorial/security/image10.png">
-!!! note "備考"
- ヘッダーの`Authorization`には、`Bearer`で始まる値があります。
+/// note | "備考"
+
+ヘッダーの`Authorization`には、`Bearer`で始まる値があります。
+
+///
## `scopes` を使った高度なユースケース
{!../../../docs_src/static_files/tutorial001.py!}
```
-!!! note "技術詳細"
- `from starlette.staticfiles import StaticFiles` も使用できます。
+/// note | "技術詳細"
- **FastAPI**は、開発者の利便性のために、`starlette.staticfiles` と同じ `fastapi.staticfiles` を提供します。しかし、実際にはStarletteから直接渡されています。
+`from starlette.staticfiles import StaticFiles` も使用できます。
+
+**FastAPI**は、開発者の利便性のために、`starlette.staticfiles` と同じ `fastapi.staticfiles` を提供します。しかし、実際にはStarletteから直接渡されています。
+
+///
### 「マウント」とは
{!../../../docs_src/app_testing/tutorial001.py!}
```
-!!! tip "豆知識"
- テスト関数は `async def` ではなく、通常の `def` であることに注意してください。
+/// tip | "豆知識"
- また、クライアントへの呼び出しも通常の呼び出しであり、`await` を使用しません。
+テスト関数は `async def` ではなく、通常の `def` であることに注意してください。
- これにより、煩雑にならずに、`pytest` を直接使用できます。
+また、クライアントへの呼び出しも通常の呼び出しであり、`await` を使用しません。
-!!! note "技術詳細"
- `from starlette.testclient import TestClient` も使用できます。
+これにより、煩雑にならずに、`pytest` を直接使用できます。
- **FastAPI** は開発者の利便性のために `fastapi.testclient` と同じ `starlette.testclient` を提供します。しかし、実際にはStarletteから直接渡されています。
+///
-!!! tip "豆知識"
- FastAPIアプリケーションへのリクエストの送信とは別に、テストで `async` 関数 (非同期データベース関数など) を呼び出したい場合は、高度なチュートリアルの[Async Tests](../advanced/async-tests.md){.internal-link target=_blank} を参照してください。
+/// note | "技術詳細"
+
+`from starlette.testclient import TestClient` も使用できます。
+
+**FastAPI** は開発者の利便性のために `fastapi.testclient` と同じ `starlette.testclient` を提供します。しかし、実際にはStarletteから直接渡されています。
+
+///
+
+/// tip | "豆知識"
+
+FastAPIアプリケーションへのリクエストの送信とは別に、テストで `async` 関数 (非同期データベース関数など) を呼び出したい場合は、高度なチュートリアルの[Async Tests](../advanced/async-tests.md){.internal-link target=_blank} を参照してください。
+
+///
## テストの分離
これらの *path operation* には `X-Token` ヘッダーが必要です。
-=== "Python 3.10+"
+//// tab | Python 3.10+
+
+```Python
+{!> ../../../docs_src/app_testing/app_b_py310/main.py!}
+```
- ```Python
- {!> ../../../docs_src/app_testing/app_b_py310/main.py!}
- ```
+////
-=== "Python 3.6+"
+//// tab | Python 3.6+
- ```Python
- {!> ../../../docs_src/app_testing/app_b/main.py!}
- ```
+```Python
+{!> ../../../docs_src/app_testing/app_b/main.py!}
+```
+
+////
### 拡張版テストファイル
(`httpx` または `TestClient` を使用して) バックエンドにデータを渡す方法の詳細は、<a href="https://www.python-httpx.org" class="external-link" target="_blank">HTTPXのドキュメント</a>を確認してください。
-!!! info "情報"
- `TestClient` は、Pydanticモデルではなく、JSONに変換できるデータを受け取ることに注意してください。
+/// info | "情報"
+
+`TestClient` は、Pydanticモデルではなく、JSONに変換できるデータを受け取ることに注意してください。
+
+テストにPydanticモデルがあり、テスト中にそのデータをアプリケーションに送信したい場合は、[JSON互換エンコーダ](encoder.md){.internal-link target=_blank} で説明されている `jsonable_encoder` が利用できます。
- テストにPydanticモデルがあり、テスト中にそのデータをアプリケーションに送信したい場合は、[JSON互換エンコーダ](encoder.md){.internal-link target=_blank} で説明されている `jsonable_encoder` が利用できます。
+///
## 実行
이 함수들은 `async def` 또는 평범하게 `def`으로 선언할 수 있습니다.
-!!! warning "경고"
- 이벤트 핸들러는 주 응용 프로그램에서만 작동합니다. [하위 응용 프로그램 - 마운트](./sub-applications.md){.internal-link target=_blank}에서는 작동하지 않습니다.
+/// warning | "경고"
+
+이벤트 핸들러는 주 응용 프로그램에서만 작동합니다. [하위 응용 프로그램 - 마운트](./sub-applications.md){.internal-link target=_blank}에서는 작동하지 않습니다.
+
+///
## `startup` 이벤트
이 예제에서 `shutdown` 이벤트 핸들러 함수는 `"Application shutdown"`이라는 텍스트가 적힌 `log.txt` 파일을 추가할 것입니다.
-!!! info "정보"
- `open()` 함수에서 `mode="a"`는 "추가"를 의미합니다. 따라서 이미 존재하는 파일의 내용을 덮어쓰지 않고 새로운 줄을 추가합니다.
+/// info | "정보"
+
+`open()` 함수에서 `mode="a"`는 "추가"를 의미합니다. 따라서 이미 존재하는 파일의 내용을 덮어쓰지 않고 새로운 줄을 추가합니다.
+
+///
+
+/// tip | "팁"
+
+이 예제에서는 파일과 상호작용 하기 위해 파이썬 표준 함수인 `open()`을 사용하고 있습니다.
+
+따라서 디스크에 데이터를 쓰기 위해 "대기"가 필요한 I/O (입력/출력) 작업을 수행합니다.
+
+그러나 `open()`은 `async`와 `await`을 사용하지 않기 때문에 이벤트 핸들러 함수는 `async def`가 아닌 표준 `def`로 선언하고 있습니다.
-!!! tip "팁"
- 이 예제에서는 파일과 상호작용 하기 위해 파이썬 표준 함수인 `open()`을 사용하고 있습니다.
+///
- 따라서 디스크에 데이터를 쓰기 위해 "대기"가 필요한 I/O (입력/출력) 작업을 수행합니다.
+/// info | "정보"
- 그러나 `open()`은 `async`와 `await`을 사용하지 않기 때문에 이벤트 핸들러 함수는 `async def`가 아닌 표준 `def`로 선언하고 있습니다.
+이벤트 핸들러에 관한 내용은 <a href="https://www.starlette.io/events/" class="external-link" target="_blank">Starlette 이벤트 문서</a>에서 추가로 확인할 수 있습니다.
-!!! info "정보"
- 이벤트 핸들러에 관한 내용은 <a href="https://www.starlette.io/events/" class="external-link" target="_blank">Starlette 이벤트 문서</a>에서 추가로 확인할 수 있습니다.
+///
이어지는 장에서는 여러분이 다른 옵션, 구성 및 추가 기능을 보실 수 있습니다.
-!!! tip "팁"
- 다음 장들이 **반드시 "심화"**인 것은 아닙니다.
+/// tip | "팁"
- 그리고 여러분의 사용 사례에 대한 해결책이 그중 하나에 있을 수 있습니다.
+다음 장들이 **반드시 "심화"**인 것은 아닙니다.
+
+그리고 여러분의 사용 사례에 대한 해결책이 그중 하나에 있을 수 있습니다.
+
+///
## 자습서를 먼저 읽으십시오
return results
```
-!!! note "참고"
- `async def`로 생성된 함수 내부에서만 `await`를 사용할 수 있습니다.
+/// note | "참고"
+
+`async def`로 생성된 함수 내부에서만 `await`를 사용할 수 있습니다.
+
+///
---
## 매우 세부적인 기술적 사항
-!!! warning "경고"
- 이 부분은 넘어가도 됩니다.
+/// warning | "경고"
+
+이 부분은 넘어가도 됩니다.
+
+이것들은 **FastAPI**가 내부적으로 어떻게 동작하는지에 대한 매우 세부적인 기술사항입니다.
- ì\9d´ê²\83ë\93¤ì\9d\80 **FastAPI**ê°\80 ë\82´ë¶\80ì \81ì\9c¼ë¡\9c ì\96´ë\96»ê²\8c ë\8f\99ì\9e\91í\95\98ë\8a\94ì§\80ì\97\90 ë\8c\80í\95\9c 매ì\9a° ì\84¸ë¶\80ì \81ì\9d¸ 기ì\88 ì\82¬í\95ì\9e\85ë\8b\88ë\8b¤.
+ë§\8cì\95½ 기ì\88 ì \81 ì§\80ì\8b\9d(ì½\94루í\8b´, ì\8a¤ë \88ë\93\9c, ë¸\94ë¡\9dí\82¹ ë\93±)ì\9d´ ì\9e\88ê³ FastAPIê°\80 ì\96´ë\96»ê²\8c `async def` vs `def`를 ë\8b¤ë£¨ë\8a\94ì§\80 ê¶\81ê¸\88í\95\98ë\8b¤ë©´, ê³\84ì\86\8dí\95\98ì\8bì\8b\9cì\98¤.
- 만약 기술적 지식(코루틴, 스레드, 블록킹 등)이 있고 FastAPI가 어떻게 `async def` vs `def`를 다루는지 궁금하다면, 계속하십시오.
+///
### 경로 작동 함수
리눅스 컨테이너를 사용하는 데에는 **보안**, **반복 가능성**, **단순함** 등의 장점이 있습니다.
-!!! tip "팁"
- 시간에 쫓기고 있고 이미 이런것들을 알고 있다면 [`Dockerfile`👇](#build-a-docker-image-for-fastapi)로 점프할 수 있습니다.
+/// tip | "팁"
+
+시간에 쫓기고 있고 이미 이런것들을 알고 있다면 [`Dockerfile`👇](#build-a-docker-image-for-fastapi)로 점프할 수 있습니다.
+
+///
<details>
<summary>도커파일 미리보기 👀</summary>
</div>
-!!! info "정보"
- 패키지 종속성을 정의하고 설치하기 위한 방법과 도구는 다양합니다.
+/// info | "정보"
+
+패키지 종속성을 정의하고 설치하기 위한 방법과 도구는 다양합니다.
- 나중에 아래 세션에서 Poetry를 사용한 예시를 보이겠습니다. 👇
+나중에 아래 세션에서 Poetry를 사용한 예시를 보이겠습니다. 👇
+
+///
### **FastAPI** 코드 생성하기
프로그램이 `/code`에서 시작하고 그 속에 `./app` 디렉터리가 여러분의 코드와 함께 들어있기 때문에, **Uvicorn**은 이를 보고 `app`을 `app.main`으로부터 **불러 올** 것입니다.
-!!! tip "팁"
- 각 코드 라인을 코드의 숫자 버블을 클릭하여 리뷰할 수 있습니다. 👆
+/// tip | "팁"
+
+각 코드 라인을 코드의 숫자 버블을 클릭하여 리뷰할 수 있습니다. 👆
+
+///
이제 여러분은 다음과 같은 디렉터리 구조를 가지고 있을 것입니다:
</div>
-!!! tip "팁"
- 맨 끝에 있는 `.` 에 주목합시다. 이는 `./`와 동등하며, 도커에게 컨테이너 이미지를 빌드하기 위한 디렉터리를 알려줍니다.
+/// tip | "팁"
+
+맨 끝에 있는 `.` 에 주목합시다. 이는 `./`와 동등하며, 도커에게 컨테이너 이미지를 빌드하기 위한 디렉터리를 알려줍니다.
+
+이 경우에는 현재 디렉터리(`.`)와 같습니다.
- 이 경우에는 현재 디렉터리(`.`)와 같습니다.
+///
### 도커 컨테이너 시작하기
**HTTPS**와 **인증서**의 **자동** 취득을 다루는 것은 다른 컨테이너가 될 수 있는데, 예를 들어 <a href="https://traefik.io/" class="external-link" target="_blank">Traefik</a>을 사용하는 것입니다.
-!!! tip "팁"
- Traefik은 도커, 쿠버네티스, 그리고 다른 도구와 통합되어 있어 여러분의 컨테이너를 포함하는 HTTPS를 셋업하고 설정하는 것이 매우 쉽습니다.
+/// tip | "팁"
+
+Traefik은 도커, 쿠버네티스, 그리고 다른 도구와 통합되어 있어 여러분의 컨테이너를 포함하는 HTTPS를 셋업하고 설정하는 것이 매우 쉽습니다.
+
+///
대안적으로, HTTPS는 클라우드 제공자에 의해 서비스의 일환으로 다루어질 수도 있습니다 (이때도 어플리케이션은 여전히 컨테이너에서 실행될 것입니다).
이 요소가 요청들의 **로드**를 읽어들이고 각 워커에게 (바라건대) **균형적으로** 분배한다면, 이 요소는 일반적으로 **로드 밸런서**라고 불립니다.
-!!! tip "팁"
- HTTPS를 위해 사용된 **TLS 종료 프록시** 요소 또한 **로드 밸런서**가 될 수 있습니다.
+/// tip | "팁"
+
+HTTPS를 위해 사용된 **TLS 종료 프록시** 요소 또한 **로드 밸런서**가 될 수 있습니다.
+
+///
또한 컨테이너로 작업할 때, 컨테이너를 시작하고 관리하기 위해 사용한 것과 동일한 시스템은 이미 해당 **로드 밸런서**로 부터 여러분의 앱에 해당하는 컨테이너로 **네트워크 통신**(예를 들어, HTTP 요청)을 전송하는 내부적인 도구를 가지고 있을 것입니다 (여기서도 로드 밸런서는 **TLS 종료 프록시**일 수 있습니다).
만약 여러분이 **여러개의 컨테이너**를 가지고 있다면, 아마도 각각의 컨테이너는 **하나의 프로세스**를 가지고 있을 것입니다(예를 들어, **쿠버네티스** 클러스터에서). 그러면 여러분은 복제된 워커 컨테이너를 실행하기 **이전에**, 하나의 컨테이너에 있는 **이전의 단계들을** 수행하는 단일 프로세스를 가지는 **별도의 컨테이너들**을 가지고 싶을 것입니다.
-!!! info "정보"
- 만약 여러분이 쿠버네티스를 사용하고 있다면, 아마도 이는 <a href="https://kubernetes.io/docs/concepts/workloads/pods/init-containers/" class="external-link" target="_blank">Init Container</a>일 것입니다.
+/// info | "정보"
+
+만약 여러분이 쿠버네티스를 사용하고 있다면, 아마도 이는 <a href="https://kubernetes.io/docs/concepts/workloads/pods/init-containers/" class="external-link" target="_blank">Init Container</a>일 것입니다.
+
+///
만약 여러분의 이용 사례에서 이전 단계들을 **병렬적으로 여러번** 수행하는데에 문제가 없다면 (예를 들어 데이터베이스 이전을 실행하지 않고 데이터베이스가 준비되었는지 확인만 하는 경우), 메인 프로세스를 시작하기 전에 이 단계들을 각 컨테이너에 넣을 수 있습니다.
* <a href="https://github.com/tiangolo/uvicorn-gunicorn-fastapi-docker" class="external-link" target="_blank">tiangolo/uvicorn-gunicorn-fastapi</a>.
-!!! warning "경고"
- 여러분이 이 베이스 이미지 또는 다른 유사한 이미지를 필요로 하지 **않을** 높은 가능성이 있으며, [위에서 설명된 것처럼: FastAPI를 위한 도커 이미지 빌드하기](#build-a-docker-image-for-fastapi) 처음부터 이미지를 빌드하는 것이 더 나을 수 있습니다.
+/// warning | "경고"
+
+여러분이 이 베이스 이미지 또는 다른 유사한 이미지를 필요로 하지 **않을** 높은 가능성이 있으며, [위에서 설명된 것처럼: FastAPI를 위한 도커 이미지 빌드하기](#build-a-docker-image-for-fastapi) 처음부터 이미지를 빌드하는 것이 더 나을 수 있습니다.
+
+///
이 이미지는 가능한 CPU 코어에 기반한 **몇개의 워커 프로세스**를 설정하는 **자동-튜닝** 메커니즘을 포함하고 있습니다.
또한 스크립트를 통해 <a href="https://github.com/tiangolo/uvicorn-gunicorn-fastapi-docker#pre_start_path" class="external-link" target="_blank">**시작하기 전 사전 단계**</a>를 실행하는 것을 지원합니다.
-!!! tip "팁"
- 모든 설정과 옵션을 보려면, 도커 이미지 페이지로 이동합니다: <a href="https://github.com/tiangolo/uvicorn-gunicorn-fastapi-docker" class="external-link" target="_blank">tiangolo/uvicorn-gunicorn-fastapi</a>.
+/// tip | "팁"
+
+모든 설정과 옵션을 보려면, 도커 이미지 페이지로 이동합니다: <a href="https://github.com/tiangolo/uvicorn-gunicorn-fastapi-docker" class="external-link" target="_blank">tiangolo/uvicorn-gunicorn-fastapi</a>.
+
+///
### 공식 도커 이미지에 있는 프로세스 개수
11. `uvicorn` 커맨드를 실행하여, `app.main`에서 불러온 `app` 객체를 사용하도록 합니다.
-!!! tip "팁"
- 버블 숫자를 클릭해 각 줄이 하는 일을 알아볼 수 있습니다.
+/// tip | "팁"
+
+버블 숫자를 클릭해 각 줄이 하는 일을 알아볼 수 있습니다.
+
+///
**도커 스테이지**란 `Dockefile`의 일부로서 나중에 사용하기 위한 파일들을 생성하기 위한 **일시적인 컨테이너 이미지**로 작동합니다.
지금부터 <a href="https://gunicorn.org/" class="external-link" target="_blank">**구니콘**</a>을 **유비콘 워커 프로세스**와 함께 사용하는 방법을 알려드리겠습니다.
-!!! info "정보"
- 만약 도커와 쿠버네티스 같은 컨테이너를 사용하고 있다면 다음 챕터 [FastAPI와 컨테이너 - 도커](docker.md){.internal-link target=_blank}에서 더 많은 정보를 얻을 수 있습니다.
+/// info | "정보"
- 특히, 쿠버네티스에서 실행할 때는 구니콘을 사용하지 않고 대신 컨테이너당 하나의 유비콘 프로세스를 실행하는 것이 좋습니다. 이 장의 뒷부분에서 설명하겠습니다.
+만약 도커와 쿠버네티스 같은 컨테이너를 사용하고 있다면 다음 챕터 [FastAPI와 컨테이너 - 도커](docker.md){.internal-link target=_blank}에서 더 많은 정보를 얻을 수 있습니다.
+
+특히, 쿠버네티스에서 실행할 때는 구니콘을 사용하지 않고 대신 컨테이너당 하나의 유비콘 프로세스를 실행하는 것이 좋습니다. 이 장의 뒷부분에서 설명하겠습니다.
+
+///
## 구니콘과 유비콘 워커
FastAPI는 오류를 수정하고, 일반적인 변경사항을 위해 "패치"버전의 관습을 따릅니다.
-!!! tip "팁"
- 여기서 말하는 "패치"란 버전의 마지막 숫자로, 예를 들어 `0.2.3` 버전에서 "패치"는 `3`을 의미합니다.
+/// tip | "팁"
+
+여기서 말하는 "패치"란 버전의 마지막 숫자로, 예를 들어 `0.2.3` 버전에서 "패치"는 `3`을 의미합니다.
+
+///
따라서 다음과 같이 버전을 표시할 수 있습니다:
수정된 사항과 새로운 요소들이 "마이너" 버전에 추가되었습니다.
-!!! tip "팁"
- "마이너"란 버전 넘버의 가운데 숫자로, 예를 들어서 `0.2.3`의 "마이너" 버전은 `2`입니다.
+/// tip | "팁"
+
+"마이너"란 버전 넘버의 가운데 숫자로, 예를 들어서 `0.2.3`의 "마이너" 버전은 `2`입니다.
+
+///
## FastAPI 버전의 업그레이드
my_second_user: User = User(**second_user_data)
```
-!!! info "정보"
- `**second_user_data`가 뜻하는 것:
+/// info | "정보"
- `second_user_data` 딕셔너리의 키와 값을 키-값 인자로서 바로 넘겨줍니다. 다음과 동일합니다: `User(id=4, name="Mary", joined="2018-11-30")`
+`**second_user_data`가 뜻하는 것:
+
+`second_user_data` 딕셔너리의 키와 값을 키-값 인자로서 바로 넘겨줍니다. 다음과 동일합니다: `User(id=4, name="Mary", joined="2018-11-30")`
+
+///
### 편집기 지원
비록 **FastAPI**를 쓰지 않는다고 하더라도, 조금이라도 알아두면 도움이 될 것입니다.
-!!! note "참고"
- 파이썬에 능숙하셔서 타입 힌트에 대해 모두 아신다면, 다음 챕터로 건너뛰세요.
+/// note | "참고"
+
+파이썬에 능숙하셔서 타입 힌트에 대해 모두 아신다면, 다음 챕터로 건너뛰세요.
+
+///
## 동기 부여
{!../../../docs_src/python_types/tutorial006.py!}
```
-!!! tip "팁"
- 대괄호 안의 내부 타입은 "타입 매개변수(type paramters)"라고 합니다.
+/// tip | "팁"
+
+대괄호 안의 내부 타입은 "타입 매개변수(type paramters)"라고 합니다.
+
+이번 예제에서는 `str`이 `List`에 들어간 타입 매개변수 입니다.
- 이번 예제에서는 `str`이 `List`에 들어간 타입 매개변수 입니다.
+///
이는 "`items`은 `list`인데, 배열에 들어있는 아이템 각각은 `str`이다"라는 뜻입니다.
{!../../../docs_src/python_types/tutorial011.py!}
```
-!!! info "정보"
- Pydantic<에 대해 더 배우고 싶다면 <a href="https://docs.pydantic.dev/" class="external-link" target="_blank">공식 문서</a>를 참고하세요.</a>
+/// info | "정보"
+Pydantic<에 대해 더 배우고 싶다면 <a href="https://docs.pydantic.dev/" class="external-link" target="_blank">공식 문서</a>를 참고하세요.</a>
+
+///
**FastAPI**는 모두 Pydantic을 기반으로 되어 있습니다.
가장 중요한 건, 표준 파이썬 타입을 한 곳에서(클래스를 더하거나, 데코레이터 사용하는 대신) 사용함으로써 **FastAPI**가 당신을 위해 많은 일을 해준다는 사실이죠.
-!!! info "정보"
- 만약 모든 자습서를 다 보았음에도 타입에 대해서 더 보고자 방문한 경우에는 <a href="https://mypy.readthedocs.io/en/latest/cheat_sheet_py3.html" class="external-link" target="_blank">`mypy`에서 제공하는 "cheat sheet"</a>이 좋은 자료가 될 겁니다.
+/// info | "정보"
+
+만약 모든 자습서를 다 보았음에도 타입에 대해서 더 보고자 방문한 경우에는 <a href="https://mypy.readthedocs.io/en/latest/cheat_sheet_py3.html" class="external-link" target="_blank">`mypy`에서 제공하는 "cheat sheet"</a>이 좋은 자료가 될 겁니다.
+
+///
**FastAPI**는 각 경우에 수행할 작업과 동일한 개체를 내부적으로 재사용하기에, 모든 백그라운드 작업이 함께 병합되고 나중에 백그라운드에서 실행됩니다.
-=== "Python 3.6 and above"
+//// tab | Python 3.6 and above
- ```Python hl_lines="13 15 22 25"
- {!> ../../../docs_src/background_tasks/tutorial002.py!}
- ```
+```Python hl_lines="13 15 22 25"
+{!> ../../../docs_src/background_tasks/tutorial002.py!}
+```
+
+////
-=== "Python 3.10 and above"
+//// tab | Python 3.10 and above
+
+```Python hl_lines="11 13 20 23"
+{!> ../../../docs_src/background_tasks/tutorial002_py310.py!}
+```
- ```Python hl_lines="11 13 20 23"
- {!> ../../../docs_src/background_tasks/tutorial002_py310.py!}
- ```
+////
이 예제에서는 응답이 반환된 후에 `log.txt` 파일에 메시지가 기록됩니다.
먼저 이를 임포트해야 합니다:
-=== "Python 3.10+"
+//// tab | Python 3.10+
- ```Python hl_lines="4"
- {!> ../../../docs_src/body_fields/tutorial001_an_py310.py!}
- ```
+```Python hl_lines="4"
+{!> ../../../docs_src/body_fields/tutorial001_an_py310.py!}
+```
-=== "Python 3.9+"
+////
- ```Python hl_lines="4"
- {!> ../../../docs_src/body_fields/tutorial001_an_py39.py!}
- ```
+//// tab | Python 3.9+
-=== "Python 3.8+"
+```Python hl_lines="4"
+{!> ../../../docs_src/body_fields/tutorial001_an_py39.py!}
+```
- ```Python hl_lines="4"
- {!> ../../../docs_src/body_fields/tutorial001_an.py!}
- ```
+////
-=== "Python 3.10+ Annotated가 없는 경우"
+//// tab | Python 3.8+
- !!! tip "팁"
- 가능하다면 `Annotated`가 달린 버전을 권장합니다.
+```Python hl_lines="4"
+{!> ../../../docs_src/body_fields/tutorial001_an.py!}
+```
- ```Python hl_lines="2"
- {!> ../../../docs_src/body_fields/tutorial001_py310.py!}
- ```
+////
-=== "Python 3.8+ Annotated가 없는 경우"
+//// tab | Python 3.10+ Annotated가 없는 경우
- !!! tip "팁"
- 가능하다면 `Annotated`가 달린 버전을 권장합니다.
+/// tip | "팁"
- ```Python hl_lines="4"
- {!> ../../../docs_src/body_fields/tutorial001.py!}
- ```
+가능하다면 `Annotated`가 달린 버전을 권장합니다.
-!!! warning "경고"
- `Field`는 다른 것들처럼 (`Query`, `Path`, `Body` 등) `fastapi`에서가 아닌 `pydantic`에서 바로 임포트 되는 점에 주의하세요.
+///
+
+```Python hl_lines="2"
+{!> ../../../docs_src/body_fields/tutorial001_py310.py!}
+```
+
+////
+
+//// tab | Python 3.8+ Annotated가 없는 경우
+
+/// tip | "팁"
+
+가능하다면 `Annotated`가 달린 버전을 권장합니다.
+
+///
+
+```Python hl_lines="4"
+{!> ../../../docs_src/body_fields/tutorial001.py!}
+```
+
+////
+
+/// warning | "경고"
+
+`Field`는 다른 것들처럼 (`Query`, `Path`, `Body` 등) `fastapi`에서가 아닌 `pydantic`에서 바로 임포트 되는 점에 주의하세요.
+
+///
## 모델 어트리뷰트 선언
그 다음 모델 어트리뷰트와 함께 `Field`를 사용할 수 있습니다:
-=== "Python 3.10+"
+//// tab | Python 3.10+
+
+```Python hl_lines="11-14"
+{!> ../../../docs_src/body_fields/tutorial001_an_py310.py!}
+```
+
+////
- ```Python hl_lines="11-14"
- {!> ../../../docs_src/body_fields/tutorial001_an_py310.py!}
- ```
+//// tab | Python 3.9+
-=== "Python 3.9+"
+```Python hl_lines="11-14"
+{!> ../../../docs_src/body_fields/tutorial001_an_py39.py!}
+```
- ```Python hl_lines="11-14"
- {!> ../../../docs_src/body_fields/tutorial001_an_py39.py!}
- ```
+////
-=== "Python 3.8+"
+//// tab | Python 3.8+
- ```Python hl_lines="12-15"
- {!> ../../../docs_src/body_fields/tutorial001_an.py!}
- ```
+```Python hl_lines="12-15"
+{!> ../../../docs_src/body_fields/tutorial001_an.py!}
+```
-=== "Python 3.10+ Annotated가 없는 경우"
+////
- !!! tip "팁"
- 가능하다면 `Annotated`가 달린 버전을 권장합니다.
+//// tab | Python 3.10+ Annotated가 없는 경우
- ```Python hl_lines="9-12"
- {!> ../../../docs_src/body_fields/tutorial001_py310.py!}
- ```
+/// tip | "팁"
-=== "Python 3.8+ Annotated가 없는 경우"
+가능하다면 `Annotated`가 달린 버전을 권장합니다.
- !!! tip "팁"
- 가능하다면 `Annotated`가 달린 버전을 권장합니다.
+///
- ```Python hl_lines="11-14"
- {!> ../../../docs_src/body_fields/tutorial001.py!}
- ```
+```Python hl_lines="9-12"
+{!> ../../../docs_src/body_fields/tutorial001_py310.py!}
+```
+
+////
+
+//// tab | Python 3.8+ Annotated가 없는 경우
+
+/// tip | "팁"
+
+가능하다면 `Annotated`가 달린 버전을 권장합니다.
+
+///
+
+```Python hl_lines="11-14"
+{!> ../../../docs_src/body_fields/tutorial001.py!}
+```
+
+////
`Field`는 `Query`, `Path`와 `Body`와 같은 방식으로 동작하며, 모두 같은 매개변수들 등을 가집니다.
-!!! note "기술적 세부사항"
- 실제로 `Query`, `Path`등, 여러분이 앞으로 볼 다른 것들은 공통 클래스인 `Param` 클래스의 서브클래스 객체를 만드는데, 그 자체로 Pydantic의 `FieldInfo` 클래스의 서브클래스입니다.
+/// note | "기술적 세부사항"
- 그리고 Pydantic의 `Field` 또한 `FieldInfo`의 인스턴스를 반환합니다.
+실제로 `Query`, `Path`등, 여러분이 앞으로 볼 다른 것들은 공통 클래스인 `Param` 클래스의 서브클래스 객체를 만드는데, 그 자체로 Pydantic의 `FieldInfo` 클래스의 서브클래스입니다.
- `Body` 또한 `FieldInfo`의 서브클래스 객체를 직접적으로 반환합니다. 그리고 `Body` 클래스의 서브클래스인 것들도 여러분이 나중에 보게될 것입니다.
+그리고 Pydantic의 `Field` 또한 `FieldInfo`의 인스턴스를 반환합니다.
- `Query`, `Path`와 그 외 것들을 `fastapi`에서 임포트할 때, 이는 실제로 특별한 클래스를 반환하는 함수인 것을 기억해 주세요.
+`Body` 또한 `FieldInfo`의 서브클래스 객체를 직접적으로 반환합니다. 그리고 `Body` 클래스의 서브클래스인 것들도 여러분이 나중에 보게될 것입니다.
-!!! tip "팁"
- 주목할 점은 타입, 기본 값 및 `Field`로 이루어진 각 모델 어트리뷰트가 `Path`, `Query`와 `Body`대신 `Field`를 사용하는 *경로 작동 함수*의 매개변수와 같은 구조를 가진다는 점 입니다.
+ `Query`, `Path`와 그 외 것들을 `fastapi`에서 임포트할 때, 이는 실제로 특별한 클래스를 반환하는 함수인 것을 기억해 주세요.
+
+///
+
+/// tip | "팁"
+
+주목할 점은 타입, 기본 값 및 `Field`로 이루어진 각 모델 어트리뷰트가 `Path`, `Query`와 `Body`대신 `Field`를 사용하는 *경로 작동 함수*의 매개변수와 같은 구조를 가진다는 점 입니다.
+
+///
## 별도 정보 추가
여러분이 예제를 선언할 때 나중에 이 공식 문서에서 별도 정보를 추가하는 방법을 배울 것입니다.
-!!! warning "경고"
- 별도 키가 전달된 `Field` 또한 여러분의 어플리케이션의 OpenAPI 스키마에 나타날 것입니다.
- 이런 키가 OpenAPI 명세서, [the OpenAPI validator](https://validator.swagger.io/)같은 몇몇 OpenAPI 도구들에 포함되지 못할 수 있으며, 여러분이 생성한 스키마와 호환되지 않을 수 있습니다.
+/// warning | "경고"
+
+별도 키가 전달된 `Field` 또한 여러분의 어플리케이션의 OpenAPI 스키마에 나타날 것입니다.
+이런 키가 OpenAPI 명세서, [the OpenAPI validator](https://validator.swagger.io/)같은 몇몇 OpenAPI 도구들에 포함되지 못할 수 있으며, 여러분이 생성한 스키마와 호환되지 않을 수 있습니다.
+
+///
## 요약
{!../../../docs_src/body_multiple_params/tutorial001.py!}
```
-!!! note "참고"
- 이 경우에는 본문으로 부터 가져온 ` item`은 기본값이 `None`이기 때문에, 선택사항이라는 점을 유의해야 합니다.
+/// note | "참고"
+
+이 경우에는 본문으로 부터 가져온 ` item`은 기본값이 `None`이기 때문에, 선택사항이라는 점을 유의해야 합니다.
+
+///
## 다중 본문 매개변수
}
```
-!!! note "참고"
- 이전과 같이 `item`이 선언 되었더라도, 본문 내의 `item` 키가 있을 것이라고 예측합니다.
+/// note | "참고"
+
+이전과 같이 `item`이 선언 되었더라도, 본문 내의 `item` 키가 있을 것이라고 예측합니다.
+
+///
FastAPI는 요청을 자동으로 변환해, 매개변수의 `item`과 `user`를 특별한 내용으로 받도록 할 것입니다.
q: Optional[str] = None
```
-!!! info "정보"
- `Body` 또한 `Query`, `Path` 그리고 이후에 볼 다른 것들처럼 동일한 추가 검증과 메타데이터 매개변수를 갖고 있습니다.
+/// info | "정보"
+
+`Body` 또한 `Query`, `Path` 그리고 이후에 볼 다른 것들처럼 동일한 추가 검증과 메타데이터 매개변수를 갖고 있습니다.
+
+///
## 단일 본문 매개변수 삽입하기
}
```
-!!! info "정보"
- `images` 키가 어떻게 이미지 객체 리스트를 갖는지 주목하세요.
+/// info | "정보"
+
+`images` 키가 어떻게 이미지 객체 리스트를 갖는지 주목하세요.
+
+///
## 깊게 중첩된 모델
{!../../../docs_src/body_nested_models/tutorial007.py!}
```
-!!! info "정보"
- `Offer`가 선택사항 `Image` 리스트를 차례로 갖는 `Item` 리스트를 어떻게 가지고 있는지 주목하세요
+/// info | "정보"
+
+`Offer`가 선택사항 `Image` 리스트를 차례로 갖는 `Item` 리스트를 어떻게 가지고 있는지 주목하세요
+
+///
## 순수 리스트의 본문
{!../../../docs_src/body_nested_models/tutorial009.py!}
```
-!!! tip "팁"
- JSON은 오직 `str`형 키만 지원한다는 것을 염두에 두세요.
+/// tip | "팁"
+
+JSON은 오직 `str`형 키만 지원한다는 것을 염두에 두세요.
+
+하지만 Pydantic은 자동 데이터 변환이 있습니다.
- 하지만 Pydantic은 자동 데이터 변환이 있습니다.
+즉, API 클라이언트가 문자열을 키로 보내더라도 해당 문자열이 순수한 정수를 포함하는한 Pydantic은 이를 변환하고 검증합니다.
- 즉, API 클라이언트가 문자열을 키로 보내더라도 해당 문자열이 순수한 정수를 포함하는한 Pydantic은 이를 변환하고 검증합니다.
+그러므로 `weights`로 받은 `dict`는 실제로 `int` 키와 `float` 값을 가집니다.
- 그러므로 `weights`로 받은 `dict`는 실제로 `int` 키와 `float` 값을 가집니다.
+///
## 요약
**요청** 본문을 선언하기 위해서 모든 강력함과 이점을 갖춘 <a href="https://docs.pydantic.dev/" class="external-link" target="_blank">Pydantic</a> 모델을 사용합니다.
-!!! info "정보"
- 데이터를 보내기 위해, (좀 더 보편적인) `POST`, `PUT`, `DELETE` 혹은 `PATCH` 중에 하나를 사용하는 것이 좋습니다.
+/// info | "정보"
- `GET` 요청에 본문을 담아 보내는 것은 명세서에 정의되지 않은 행동입니다. 그럼에도 불구하고, 이 방식은 아주 복잡한/극한의 사용 상황에서만 FastAPI에 의해 지원됩니다.
+데이터를 보내기 위해, (좀 더 보편적인) `POST`, `PUT`, `DELETE` 혹은 `PATCH` 중에 하나를 사용하는 것이 좋습니다.
- `GET` 요청에 본문을 담는 것은 권장되지 않기에, Swagger UI같은 대화형 문서에서는 `GET` 사용시 담기는 본문에 대한 문서를 표시하지 않으며, 중간에 있는 프록시는 이를 지원하지 않을 수도 있습니다.
+`GET` 요청에 본문을 담아 보내는 것은 명세서에 정의되지 않은 행동입니다. 그럼에도 불구하고, 이 방식은 아주 복잡한/극한의 사용 상황에서만 FastAPI에 의해 지원됩니다.
+
+`GET` 요청에 본문을 담는 것은 권장되지 않기에, Swagger UI같은 대화형 문서에서는 `GET` 사용시 담기는 본문에 대한 문서를 표시하지 않으며, 중간에 있는 프록시는 이를 지원하지 않을 수도 있습니다.
+
+///
## Pydantic의 `BaseModel` 임포트
먼저 `pydantic`에서 `BaseModel`를 임포트해야 합니다:
-=== "Python 3.10+"
+//// tab | Python 3.10+
+
+```Python hl_lines="2"
+{!> ../../../docs_src/body/tutorial001_py310.py!}
+```
+
+////
- ```Python hl_lines="2"
- {!> ../../../docs_src/body/tutorial001_py310.py!}
- ```
+//// tab | Python 3.8+
-=== "Python 3.8+"
+```Python hl_lines="4"
+{!> ../../../docs_src/body/tutorial001.py!}
+```
- ```Python hl_lines="4"
- {!> ../../../docs_src/body/tutorial001.py!}
- ```
+////
## 여러분의 데이터 모델 만들기
모든 어트리뷰트에 대해 표준 파이썬 타입을 사용합니다:
-=== "Python 3.10+"
+//// tab | Python 3.10+
- ```Python hl_lines="5-9"
- {!> ../../../docs_src/body/tutorial001_py310.py!}
- ```
+```Python hl_lines="5-9"
+{!> ../../../docs_src/body/tutorial001_py310.py!}
+```
-=== "Python 3.8+"
+////
- ```Python hl_lines="7-11"
- {!> ../../../docs_src/body/tutorial001.py!}
- ```
+//// tab | Python 3.8+
+
+```Python hl_lines="7-11"
+{!> ../../../docs_src/body/tutorial001.py!}
+```
+
+////
쿼리 매개변수를 선언할 때와 같이, 모델 어트리뷰트가 기본 값을 가지고 있어도 이는 필수가 아닙니다. 그외에는 필수입니다. 그저 `None`을 사용하여 선택적으로 만들 수 있습니다.
여러분의 *경로 작동*에 추가하기 위해, 경로 매개변수 그리고 쿼리 매개변수에서 선언했던 것과 같은 방식으로 선언하면 됩니다.
-=== "Python 3.10+"
+//// tab | Python 3.10+
- ```Python hl_lines="16"
- {!> ../../../docs_src/body/tutorial001_py310.py!}
- ```
+```Python hl_lines="16"
+{!> ../../../docs_src/body/tutorial001_py310.py!}
+```
-=== "Python 3.8+"
+////
- ```Python hl_lines="18"
- {!> ../../../docs_src/body/tutorial001.py!}
- ```
+//// tab | Python 3.8+
+
+```Python hl_lines="18"
+{!> ../../../docs_src/body/tutorial001.py!}
+```
+
+////
...그리고 만들어낸 모델인 `Item`으로 타입을 선언합니다.
<img src="/img/tutorial/body/image05.png">
-!!! tip "팁"
- 만약 <a href="https://www.jetbrains.com/pycharm/" class="external-link" target="_blank">PyCharm</a>를 편집기로 사용한다면, <a href="https://github.com/koxudaxi/pydantic-pycharm-plugin/" class="external-link" target="_blank">Pydantic PyCharm Plugin</a>을 사용할 수 있습니다.
+/// tip | "팁"
+
+만약 <a href="https://www.jetbrains.com/pycharm/" class="external-link" target="_blank">PyCharm</a>를 편집기로 사용한다면, <a href="https://github.com/koxudaxi/pydantic-pycharm-plugin/" class="external-link" target="_blank">Pydantic PyCharm Plugin</a>을 사용할 수 있습니다.
- 다음 사항을 포함해 Pydantic 모델에 대한 편집기 지원을 향상시킵니다:
+다음 사항을 포함해 Pydantic 모델에 대한 편집기 지원을 향상시킵니다:
- * 자동 완성
- * 타입 확인
- * 리팩토링
- * 검색
- * 점검
+* 자동 완성
+* 타입 확인
+* 리팩토링
+* 검색
+* 점검
+
+///
## 모델 사용하기
함수 안에서 모델 객체의 모든 어트리뷰트에 직접 접근 가능합니다:
-=== "Python 3.10+"
+//// tab | Python 3.10+
+
+```Python hl_lines="19"
+{!> ../../../docs_src/body/tutorial002_py310.py!}
+```
+
+////
- ```Python hl_lines="19"
- {!> ../../../docs_src/body/tutorial002_py310.py!}
- ```
+//// tab | Python 3.8+
-=== "Python 3.8+"
+```Python hl_lines="21"
+{!> ../../../docs_src/body/tutorial002.py!}
+```
- ```Python hl_lines="21"
- {!> ../../../docs_src/body/tutorial002.py!}
- ```
+////
## 요청 본문 + 경로 매개변수
**FastAPI**는 경로 매개변수와 일치하는 함수 매개변수가 **경로에서 가져와야 한다**는 것을 인지하며, Pydantic 모델로 선언된 그 함수 매개변수는 **요청 본문에서 가져와야 한다**는 것을 인지할 것입니다.
-=== "Python 3.10+"
+//// tab | Python 3.10+
+
+```Python hl_lines="15-16"
+{!> ../../../docs_src/body/tutorial003_py310.py!}
+```
- ```Python hl_lines="15-16"
- {!> ../../../docs_src/body/tutorial003_py310.py!}
- ```
+////
-=== "Python 3.8+"
+//// tab | Python 3.8+
- ```Python hl_lines="17-18"
- {!> ../../../docs_src/body/tutorial003.py!}
- ```
+```Python hl_lines="17-18"
+{!> ../../../docs_src/body/tutorial003.py!}
+```
+
+////
## 요청 본문 + 경로 + 쿼리 매개변수
**FastAPI**는 각각을 인지하고 데이터를 옳바른 위치에 가져올 것입니다.
-=== "Python 3.10+"
+//// tab | Python 3.10+
+
+```Python hl_lines="16"
+{!> ../../../docs_src/body/tutorial004_py310.py!}
+```
- ```Python hl_lines="16"
- {!> ../../../docs_src/body/tutorial004_py310.py!}
- ```
+////
-=== "Python 3.8+"
+//// tab | Python 3.8+
- ```Python hl_lines="18"
- {!> ../../../docs_src/body/tutorial004.py!}
- ```
+```Python hl_lines="18"
+{!> ../../../docs_src/body/tutorial004.py!}
+```
+
+////
함수 매개변수는 다음을 따라서 인지하게 됩니다:
* 만약 매개변수가 (`int`, `float`, `str`, `bool` 등과 같은) **유일한 타입**으로 되어있으면, **쿼리** 매개변수로 해석될 것입니다.
* 만약 매개변수가 **Pydantic 모델** 타입으로 선언되어 있으면, 요청 **본문**으로 해석될 것입니다.
-!!! note "참고"
- FastAPI는 `q`의 값이 필요없음을 알게 될 것입니다. 기본 값이 `= None`이기 때문입니다.
+/// note | "참고"
+
+FastAPI는 `q`의 값이 필요없음을 알게 될 것입니다. 기본 값이 `= None`이기 때문입니다.
+
+`Union[str, None]`에 있는 `Union`은 FastAPI에 의해 사용된 것이 아니지만, 편집기로 하여금 더 나은 지원과 에러 탐지를 지원할 것입니다.
- `Union[str, None]`에 있는 `Union`은 FastAPI에 의해 사용된 것이 아니지만, 편집기로 하여금 더 나은 지원과 에러 탐지를 지원할 것입니다.
+///
## Pydantic없이
먼저 `Cookie`를 임포트합니다:
-=== "Python 3.10+"
+//// tab | Python 3.10+
- ```Python hl_lines="3"
- {!> ../../../docs_src/cookie_params/tutorial001_an_py310.py!}
- ```
+```Python hl_lines="3"
+{!> ../../../docs_src/cookie_params/tutorial001_an_py310.py!}
+```
-=== "Python 3.9+"
+////
- ```Python hl_lines="3"
- {!> ../../../docs_src/cookie_params/tutorial001_an_py39.py!}
- ```
+//// tab | Python 3.9+
-=== "Python 3.8+"
+```Python hl_lines="3"
+{!> ../../../docs_src/cookie_params/tutorial001_an_py39.py!}
+```
- ```Python hl_lines="3"
- {!> ../../../docs_src/cookie_params/tutorial001_an.py!}
- ```
+////
-=== "Python 3.10+ Annotated가 없는 경우"
+//// tab | Python 3.8+
- !!! tip "팁"
- 가능하다면 `Annotated`가 달린 버전을 권장합니다.
+```Python hl_lines="3"
+{!> ../../../docs_src/cookie_params/tutorial001_an.py!}
+```
- ```Python hl_lines="1"
- {!> ../../../docs_src/cookie_params/tutorial001_py310.py!}
- ```
+////
-=== "Python 3.8+ Annotated가 없는 경우"
+//// tab | Python 3.10+ Annotated가 없는 경우
- !!! tip "팁"
- 가능하다면 `Annotated`가 달린 버전을 권장합니다.
+/// tip | "팁"
- ```Python hl_lines="3"
- {!> ../../../docs_src/cookie_params/tutorial001.py!}
- ```
+가능하다면 `Annotated`가 달린 버전을 권장합니다.
+
+///
+
+```Python hl_lines="1"
+{!> ../../../docs_src/cookie_params/tutorial001_py310.py!}
+```
+
+////
+
+//// tab | Python 3.8+ Annotated가 없는 경우
+
+/// tip | "팁"
+
+가능하다면 `Annotated`가 달린 버전을 권장합니다.
+
+///
+
+```Python hl_lines="3"
+{!> ../../../docs_src/cookie_params/tutorial001.py!}
+```
+
+////
## `Cookie` 매개변수 선언
첫 번째 값은 기본값이며, 추가 검증이나 어노테이션 매개변수 모두 전달할 수 있습니다:
-=== "Python 3.10+"
+//// tab | Python 3.10+
+
+```Python hl_lines="9"
+{!> ../../../docs_src/cookie_params/tutorial001_an_py310.py!}
+```
+
+////
+
+//// tab | Python 3.9+
+
+```Python hl_lines="9"
+{!> ../../../docs_src/cookie_params/tutorial001_an_py39.py!}
+```
+
+////
+
+//// tab | Python 3.8+
+
+```Python hl_lines="10"
+{!> ../../../docs_src/cookie_params/tutorial001_an.py!}
+```
+
+////
+
+//// tab | Python 3.10+ Annotated가 없는 경우
+
+/// tip | "팁"
+
+가능하다면 `Annotated`가 달린 버전을 권장합니다.
+
+///
+
+```Python hl_lines="7"
+{!> ../../../docs_src/cookie_params/tutorial001_py310.py!}
+```
- ```Python hl_lines="9"
- {!> ../../../docs_src/cookie_params/tutorial001_an_py310.py!}
- ```
+////
-=== "Python 3.9+"
+//// tab | Python 3.8+ Annotated가 없는 경우
- ```Python hl_lines="9"
- {!> ../../../docs_src/cookie_params/tutorial001_an_py39.py!}
- ```
+/// tip | "팁"
-=== "Python 3.8+"
+가능하다면 `Annotated`가 달린 버전을 권장합니다.
- ```Python hl_lines="10"
- {!> ../../../docs_src/cookie_params/tutorial001_an.py!}
- ```
+///
-=== "Python 3.10+ Annotated가 없는 경우"
+```Python hl_lines="9"
+{!> ../../../docs_src/cookie_params/tutorial001.py!}
+```
- !!! tip "팁"
- 가능하다면 `Annotated`가 달린 버전을 권장합니다.
+////
- ```Python hl_lines="7"
- {!> ../../../docs_src/cookie_params/tutorial001_py310.py!}
- ```
+/// note | "기술 세부사항"
-=== "Python 3.8+ Annotated가 없는 경우"
+`Cookie`는 `Path` 및 `Query`의 "자매"클래스입니다. 이 역시 동일한 공통 `Param` 클래스를 상속합니다.
- !!! tip "팁"
- 가능하다면 `Annotated`가 달린 버전을 권장합니다.
+`Query`, `Path`, `Cookie` 그리고 다른 것들은 `fastapi`에서 임포트 할 때, 실제로는 특별한 클래스를 반환하는 함수임을 기억하세요.
- ```Python hl_lines="9"
- {!> ../../../docs_src/cookie_params/tutorial001.py!}
- ```
+///
-!!! note "기술 세부사항"
- `Cookie`는 `Path` 및 `Query`의 "자매"클래스입니다. 이 역시 동일한 공통 `Param` 클래스를 상속합니다.
+/// info | "정보"
- `Query`, `Path`, `Cookie` 그리고 다른 것들은 `fastapi`에서 임포트 할 때, 실제로는 특별한 클래스를 반환하는 함수임을 기억하세요.
+쿠키를 선언하기 위해서는 `Cookie`를 사용해야 합니다. 그렇지 않으면 해당 매개변수를 쿼리 매개변수로 해석하기 때문입니다.
-!!! info "정보"
- 쿠키를 선언하기 위해서는 `Cookie`를 사용해야 합니다. 그렇지 않으면 해당 매개변수를 쿼리 매개변수로 해석하기 때문입니다.
+///
## 요약
<abbr title="교차-출처 리소스 공유">CORS</abbr>에 대한 더 많은 정보를 알고싶다면, <a href="https://developer.mozilla.org/ko/docs/Web/HTTP/CORS" class="external-link" target="_blank">Mozilla CORS 문서</a>를 참고하기 바랍니다.
-!!! note "기술적 세부 사항"
- `from starlette.middleware.cors import CORSMiddleware` 역시 사용할 수 있습니다.
+/// note | "기술적 세부 사항"
- **FastAPI**는 개발자인 당신의 편의를 위해 `fastapi.middleware` 에서 몇가지의 미들웨어를 제공합니다. 하지만 대부분의 미들웨어가 Stralette으로부터 직접 제공됩니다.
+`from starlette.middleware.cors import CORSMiddleware` 역시 사용할 수 있습니다.
+
+**FastAPI**는 개발자인 당신의 편의를 위해 `fastapi.middleware` 에서 몇가지의 미들웨어를 제공합니다. 하지만 대부분의 미들웨어가 Stralette으로부터 직접 제공됩니다.
+
+///
은 실행되지 않습니다.
-!!! info "정보"
- 자세한 내용은 <a href="https://docs.python.org/3/library/__main__.html" class="external-link" target="_blank">공식 Python 문서</a>를 확인하세요
+/// info | "정보"
+
+자세한 내용은 <a href="https://docs.python.org/3/library/__main__.html" class="external-link" target="_blank">공식 Python 문서</a>를 확인하세요
+
+///
## 디버거로 코드 실행
이전 예제에서, 우리는 의존성(의존 가능한) 함수에서 `딕셔너리`객체를 반환하고 있었습니다:
-=== "파이썬 3.6 이상"
+//// tab | 파이썬 3.6 이상
- ```Python hl_lines="9"
- {!> ../../../docs_src/dependencies/tutorial001.py!}
- ```
+```Python hl_lines="9"
+{!> ../../../docs_src/dependencies/tutorial001.py!}
+```
+
+////
-=== "파이썬 3.10 이상"
+//// tab | 파이썬 3.10 이상
+
+```Python hl_lines="7"
+{!> ../../../docs_src/dependencies/tutorial001_py310.py!}
+```
- ```Python hl_lines="7"
- {!> ../../../docs_src/dependencies/tutorial001_py310.py!}
- ```
+////
우리는 *경로 작동 함수*의 매개변수 `commons`에서 `딕셔너리` 객체를 얻습니다.
그래서, 우리는 위 예제에서의 `common_paramenters` 의존성을 클래스 `CommonQueryParams`로 바꿀 수 있습니다.
-=== "파이썬 3.6 이상"
+//// tab | 파이썬 3.6 이상
- ```Python hl_lines="11-15"
- {!> ../../../docs_src/dependencies/tutorial002.py!}
- ```
+```Python hl_lines="11-15"
+{!> ../../../docs_src/dependencies/tutorial002.py!}
+```
+
+////
-=== "파이썬 3.10 이상"
+//// tab | 파이썬 3.10 이상
+
+```Python hl_lines="9-13"
+{!> ../../../docs_src/dependencies/tutorial002_py310.py!}
+```
- ```Python hl_lines="9-13"
- {!> ../../../docs_src/dependencies/tutorial002_py310.py!}
- ```
+////
클래스의 인스턴스를 생성하는 데 사용되는 `__init__` 메서드에 주목하기 바랍니다:
-=== "파이썬 3.6 이상"
+//// tab | 파이썬 3.6 이상
- ```Python hl_lines="12"
- {!> ../../../docs_src/dependencies/tutorial002.py!}
- ```
+```Python hl_lines="12"
+{!> ../../../docs_src/dependencies/tutorial002.py!}
+```
+
+////
-=== "파이썬 3.10 이상"
+//// tab | 파이썬 3.10 이상
+
+```Python hl_lines="10"
+{!> ../../../docs_src/dependencies/tutorial002_py310.py!}
+```
- ```Python hl_lines="10"
- {!> ../../../docs_src/dependencies/tutorial002_py310.py!}
- ```
+////
...이전 `common_parameters`와 동일한 매개변수를 가집니다:
-=== "파이썬 3.6 이상"
+//// tab | 파이썬 3.6 이상
+
+```Python hl_lines="9"
+{!> ../../../docs_src/dependencies/tutorial001.py!}
+```
+
+////
- ```Python hl_lines="9"
- {!> ../../../docs_src/dependencies/tutorial001.py!}
- ```
+//// tab | 파이썬 3.10 이상
-=== "파이썬 3.10 이상"
+```Python hl_lines="6"
+{!> ../../../docs_src/dependencies/tutorial001_py310.py!}
+```
- ```Python hl_lines="6"
- {!> ../../../docs_src/dependencies/tutorial001_py310.py!}
- ```
+////
이 매개변수들은 **FastAPI**가 의존성을 "해결"하기 위해 사용할 것입니다
이제 아래의 클래스를 이용해서 의존성을 정의할 수 있습니다.
-=== "파이썬 3.6 이상"
+//// tab | 파이썬 3.6 이상
+
+```Python hl_lines="19"
+{!> ../../../docs_src/dependencies/tutorial002.py!}
+```
+
+////
- ```Python hl_lines="19"
- {!> ../../../docs_src/dependencies/tutorial002.py!}
- ```
+//// tab | 파이썬 3.10 이상
-=== "파이썬 3.10 이상"
+```Python hl_lines="17"
+{!> ../../../docs_src/dependencies/tutorial002_py310.py!}
+```
- ```Python hl_lines="17"
- {!> ../../../docs_src/dependencies/tutorial002_py310.py!}
- ```
+////
**FastAPI**는 `CommonQueryParams` 클래스를 호출합니다. 이것은 해당 클래스의 "인스턴스"를 생성하고 그 인스턴스는 함수의 매개변수 `commons`로 전달됩니다.
..전체적인 코드는 아래와 같습니다:
-=== "파이썬 3.6 이상"
+//// tab | 파이썬 3.6 이상
+
+```Python hl_lines="19"
+{!> ../../../docs_src/dependencies/tutorial003.py!}
+```
- ```Python hl_lines="19"
- {!> ../../../docs_src/dependencies/tutorial003.py!}
- ```
+////
-=== "파이썬 3.10 이상"
+//// tab | 파이썬 3.10 이상
- ```Python hl_lines="17"
- {!> ../../../docs_src/dependencies/tutorial003_py310.py!}
- ```
+```Python hl_lines="17"
+{!> ../../../docs_src/dependencies/tutorial003_py310.py!}
+```
+
+////
그러나 자료형을 선언하면 에디터가 매개변수 `commons`로 전달될 것이 무엇인지 알게 되고, 이를 통해 코드 완성, 자료형 확인 등에 도움이 될 수 있으므로 권장됩니다.
아래에 같은 예제가 있습니다:
-=== "파이썬 3.6 이상"
+//// tab | 파이썬 3.6 이상
+
+```Python hl_lines="19"
+{!> ../../../docs_src/dependencies/tutorial004.py!}
+```
- ```Python hl_lines="19"
- {!> ../../../docs_src/dependencies/tutorial004.py!}
- ```
+////
-=== "파이썬 3.10 이상"
+//// tab | 파이썬 3.10 이상
- ```Python hl_lines="17"
- {!> ../../../docs_src/dependencies/tutorial004_py310.py!}
- ```
+```Python hl_lines="17"
+{!> ../../../docs_src/dependencies/tutorial004_py310.py!}
+```
+
+////
...이렇게 코드를 단축하여도 **FastAPI**는 무엇을 해야하는지 알고 있습니다.
-!!! tip "팁"
- 만약 이것이 도움이 되기보다 더 헷갈리게 만든다면, 잊어버리십시오. 이것이 반드시 필요한 것은 아닙니다.
+/// tip | "팁"
+
+만약 이것이 도움이 되기보다 더 헷갈리게 만든다면, 잊어버리십시오. 이것이 반드시 필요한 것은 아닙니다.
+
+이것은 단지 손쉬운 방법일 뿐입니다. 왜냐하면 **FastAPI**는 코드 반복을 최소화할 수 있는 방법을 고민하기 때문입니다.
- 이것은 단지 손쉬운 방법일 뿐입니다. 왜냐하면 **FastAPI**는 코드 반복을 최소화할 수 있는 방법을 고민하기 때문입니다.
+///
`Depends()`로 된 `list`이어야합니다:
-=== "Python 3.9+"
+//// tab | Python 3.9+
- ```Python hl_lines="19"
- {!> ../../../docs_src/dependencies/tutorial006_an_py39.py!}
- ```
+```Python hl_lines="19"
+{!> ../../../docs_src/dependencies/tutorial006_an_py39.py!}
+```
-=== "Python 3.8+"
+////
- ```Python hl_lines="18"
- {!> ../../../docs_src/dependencies/tutorial006_an.py!}
- ```
+//// tab | Python 3.8+
-=== "Python 3.8 Annotated가 없는 경우"
+```Python hl_lines="18"
+{!> ../../../docs_src/dependencies/tutorial006_an.py!}
+```
- !!! tip "팁"
- 가능하다면 `Annotated`가 달린 버전을 권장합니다.
+////
- ```Python hl_lines="17"
- {!> ../../../docs_src/dependencies/tutorial006.py!}
- ```
+//// tab | Python 3.8 Annotated가 없는 경우
+
+/// tip | "팁"
+
+가능하다면 `Annotated`가 달린 버전을 권장합니다.
+
+///
+
+```Python hl_lines="17"
+{!> ../../../docs_src/dependencies/tutorial006.py!}
+```
+
+////
이러한 의존성들은 기존 의존성들과 같은 방식으로 실행/해결됩니다. 그러나 값은 (무엇이든 반환한다면) *경로 작동 함수*에 제공되지 않습니다.
-!!! tip "팁"
- 일부 편집기에서는 사용되지 않는 함수 매개변수를 검사하고 오류로 표시합니다.
+/// tip | "팁"
+
+일부 편집기에서는 사용되지 않는 함수 매개변수를 검사하고 오류로 표시합니다.
- *경로 작동 데코레이터*에서 `dependencies`를 사용하면 편집기/도구 오류를 피하며 실행되도록 할 수 있습니다.
+*경로 작동 데코레이터*에서 `dependencies`를 사용하면 편집기/도구 오류를 피하며 실행되도록 할 수 있습니다.
- 또한 코드에서 사용되지 않는 매개변수를 보고 불필요하다고 생각할 수 있는 새로운 개발자의 혼란을 방지하는데 도움이 될 수 있습니다.
+또한 코드에서 사용되지 않는 매개변수를 보고 불필요하다고 생각할 수 있는 새로운 개발자의 혼란을 방지하는데 도움이 될 수 있습니다.
-!!! info "정보"
- 이 예시에서 `X-Key`와 `X-Token`이라는 커스텀 헤더를 만들어 사용했습니다.
+///
- 그러나 실제로 보안을 구현할 때는 통합된 [보안 유틸리티 (다음 챕터)](../security/index.md){.internal-link target=_blank}를 사용하는 것이 더 많은 이점을 얻을 수 있습니다.
+/// info | "정보"
+
+이 예시에서 `X-Key`와 `X-Token`이라는 커스텀 헤더를 만들어 사용했습니다.
+
+그러나 실제로 보안을 구현할 때는 통합된 [보안 유틸리티 (다음 챕터)](../security/index.md){.internal-link target=_blank}를 사용하는 것이 더 많은 이점을 얻을 수 있습니다.
+
+///
## 의존성 오류와 값 반환하기
(헤더같은) 요청 요구사항이나 하위-의존성을 선언할 수 있습니다:
-=== "Python 3.9+"
+//// tab | Python 3.9+
+
+```Python hl_lines="8 13"
+{!> ../../../docs_src/dependencies/tutorial006_an_py39.py!}
+```
+
+////
+
+//// tab | Python 3.8+
- ```Python hl_lines="8 13"
- {!> ../../../docs_src/dependencies/tutorial006_an_py39.py!}
- ```
+```Python hl_lines="7 12"
+{!> ../../../docs_src/dependencies/tutorial006_an.py!}
+```
-=== "Python 3.8+"
+////
- ```Python hl_lines="7 12"
- {!> ../../../docs_src/dependencies/tutorial006_an.py!}
- ```
+//// tab | Python 3.8 Annotated가 없는 경우
-=== "Python 3.8 Annotated가 없는 경우"
+/// tip | "팁"
- !!! tip "팁"
- 가능하다면 `Annotated`가 달린 버전을 권장합니다.
+가능하다면 `Annotated`가 달린 버전을 권장합니다.
- ```Python hl_lines="6 11"
- {!> ../../../docs_src/dependencies/tutorial006.py!}
- ```
+///
+
+```Python hl_lines="6 11"
+{!> ../../../docs_src/dependencies/tutorial006.py!}
+```
+
+////
### 오류 발생시키기
다음 의존성은 기존 의존성과 동일하게 예외를 `raise`를 일으킬 수 있습니다:
-=== "Python 3.9+"
+//// tab | Python 3.9+
+
+```Python hl_lines="10 15"
+{!> ../../../docs_src/dependencies/tutorial006_an_py39.py!}
+```
+
+////
+
+//// tab | Python 3.8+
+
+```Python hl_lines="9 14"
+{!> ../../../docs_src/dependencies/tutorial006_an.py!}
+```
- ```Python hl_lines="10 15"
- {!> ../../../docs_src/dependencies/tutorial006_an_py39.py!}
- ```
+////
-=== "Python 3.8+"
+//// tab | Python 3.8 Annotated가 없는 경우
- ```Python hl_lines="9 14"
- {!> ../../../docs_src/dependencies/tutorial006_an.py!}
- ```
+/// tip | "팁"
-=== "Python 3.8 Annotated가 없는 경우"
+가능하다면 `Annotated`가 달린 버전을 권장합니다.
- !!! tip "팁"
- 가능하다면 `Annotated`가 달린 버전을 권장합니다.
+///
- ```Python hl_lines="8 13"
- {!> ../../../docs_src/dependencies/tutorial006.py!}
- ```
+```Python hl_lines="8 13"
+{!> ../../../docs_src/dependencies/tutorial006.py!}
+```
+
+////
### 값 반환하기
그래서 이미 다른 곳에서 사용된 (값을 반환하는) 일반적인 의존성을 재사용할 수 있고, 비록 값은 사용되지 않지만 의존성은 실행될 것입니다:
-=== "Python 3.9+"
+//// tab | Python 3.9+
+
+```Python hl_lines="11 16"
+{!> ../../../docs_src/dependencies/tutorial006_an_py39.py!}
+```
+
+////
+
+//// tab | Python 3.8+
+
+```Python hl_lines="10 15"
+{!> ../../../docs_src/dependencies/tutorial006_an.py!}
+```
+
+////
- ```Python hl_lines="11 16"
- {!> ../../../docs_src/dependencies/tutorial006_an_py39.py!}
- ```
+//// tab | Python 3.8 Annotated가 없는 경우
-=== "Python 3.8+"
+/// tip | "팁"
- ```Python hl_lines="10 15"
- {!> ../../../docs_src/dependencies/tutorial006_an.py!}
- ```
+가능하다면 `Annotated`가 달린 버전을 권장합니다.
-=== "Python 3.8 Annotated가 없는 경우"
+///
- !!! tip "팁"
- 가능하다면 `Annotated`가 달린 버전을 권장합니다.
+```Python hl_lines="9 14"
+{!> ../../../docs_src/dependencies/tutorial006.py!}
+```
- ```Python hl_lines="9 14"
- {!> ../../../docs_src/dependencies/tutorial006.py!}
- ```
+////
## *경로 작동* 모음에 대한 의존성
그런 경우에, 애플리케이션의 모든 *경로 작동*에 적용될 것입니다:
-=== "Python 3.9+"
+//// tab | Python 3.9+
- ```Python hl_lines="16"
- {!> ../../../docs_src/dependencies/tutorial012_an_py39.py!}
- ```
+```Python hl_lines="16"
+{!> ../../../docs_src/dependencies/tutorial012_an_py39.py!}
+```
-=== "Python 3.8+"
+////
- ```Python hl_lines="16"
- {!> ../../../docs_src/dependencies/tutorial012_an.py!}
- ```
+//// tab | Python 3.8+
-=== "Python 3.8 Annotated가 없는 경우"
+```Python hl_lines="16"
+{!> ../../../docs_src/dependencies/tutorial012_an.py!}
+```
- !!! tip "팁"
- 가능하다면 `Annotated`가 달린 버전을 권장합니다.
+////
- ```Python hl_lines="15"
- {!> ../../../docs_src/dependencies/tutorial012.py!}
- ```
+//// tab | Python 3.8 Annotated가 없는 경우
+
+/// tip | "팁"
+
+가능하다면 `Annotated`가 달린 버전을 권장합니다.
+
+///
+
+```Python hl_lines="15"
+{!> ../../../docs_src/dependencies/tutorial012.py!}
+```
+
+////
그리고 [*경로 작동 데코레이터*에 `dependencies` 추가하기](dependencies-in-path-operation-decorators.md){.internal-link target=_blank}에 대한 아이디어는 여전히 적용되지만 여기에서는 앱에 있는 모든 *경로 작동*에 적용됩니다.
*경로 작동 함수*가 가질 수 있는 모든 매개변수를 갖는 단순한 함수입니다:
-=== "Python 3.10+"
+//// tab | Python 3.10+
- ```Python hl_lines="8-9"
- {!> ../../../docs_src/dependencies/tutorial001_an_py310.py!}
- ```
+```Python hl_lines="8-9"
+{!> ../../../docs_src/dependencies/tutorial001_an_py310.py!}
+```
+
+////
+
+//// tab | Python 3.9+
+
+```Python hl_lines="8-11"
+{!> ../../../docs_src/dependencies/tutorial001_an_py39.py!}
+```
+
+////
-=== "Python 3.9+"
+//// tab | Python 3.8+
- ```Python hl_lines="8-11"
- {!> ../../../docs_src/dependencies/tutorial001_an_py39.py!}
- ```
+```Python hl_lines="9-12"
+{!> ../../../docs_src/dependencies/tutorial001_an.py!}
+```
-=== "Python 3.8+"
+////
- ```Python hl_lines="9-12"
- {!> ../../../docs_src/dependencies/tutorial001_an.py!}
- ```
+//// tab | Python 3.10+ Annotated가 없는 경우
-=== "Python 3.10+ Annotated가 없는 경우"
+/// tip | "팁"
- !!! tip "팁"
- 가능하다면 `Annotated`가 달린 버전을 권장합니다.
+가능하다면 `Annotated`가 달린 버전을 권장합니다.
- ```Python hl_lines="6-7"
- {!> ../../../docs_src/dependencies/tutorial001_py310.py!}
- ```
+///
-=== "Python 3.8+ Annotated가 없는 경우"
+```Python hl_lines="6-7"
+{!> ../../../docs_src/dependencies/tutorial001_py310.py!}
+```
- !!! tip "팁"
- 가능하다면 `Annotated`가 달린 버전을 권장합니다.
+////
- ```Python hl_lines="8-11"
- {!> ../../../docs_src/dependencies/tutorial001.py!}
- ```
+//// tab | Python 3.8+ Annotated가 없는 경우
+
+/// tip | "팁"
+
+가능하다면 `Annotated`가 달린 버전을 권장합니다.
+
+///
+
+```Python hl_lines="8-11"
+{!> ../../../docs_src/dependencies/tutorial001.py!}
+```
+
+////
이게 다입니다.
그 후 위의 값을 포함한 `dict` 자료형으로 반환할 뿐입니다.
-!!! info "정보"
- FastAPI는 0.95.0 버전부터 `Annotated`에 대한 지원을 (그리고 이를 사용하기 권장합니다) 추가했습니다.
+/// info | "정보"
+
+FastAPI는 0.95.0 버전부터 `Annotated`에 대한 지원을 (그리고 이를 사용하기 권장합니다) 추가했습니다.
- 옛날 버전을 가지고 있는 경우, `Annotated`를 사용하려 하면 에러를 맞이하게 될 것입니다.
+옛날 버전을 가지고 있는 경우, `Annotated`를 사용하려 하면 에러를 맞이하게 될 것입니다.
- `Annotated`를 사용하기 전에 최소 0.95.1로 [FastAPI 버전 업그레이드](../../deployment/versions.md#fastapi_2){.internal-link target=_blank}를 확실하게 하세요.
+`Annotated`를 사용하기 전에 최소 0.95.1로 [FastAPI 버전 업그레이드](../../deployment/versions.md#fastapi_2){.internal-link target=_blank}를 확실하게 하세요.
+
+///
### `Depends` 불러오기
-=== "Python 3.10+"
+//// tab | Python 3.10+
+
+```Python hl_lines="3"
+{!> ../../../docs_src/dependencies/tutorial001_an_py310.py!}
+```
+
+////
+
+//// tab | Python 3.9+
+
+```Python hl_lines="3"
+{!> ../../../docs_src/dependencies/tutorial001_an_py39.py!}
+```
+
+////
+
+//// tab | Python 3.8+
+
+```Python hl_lines="3"
+{!> ../../../docs_src/dependencies/tutorial001_an.py!}
+```
- ```Python hl_lines="3"
- {!> ../../../docs_src/dependencies/tutorial001_an_py310.py!}
- ```
+////
-=== "Python 3.9+"
+//// tab | Python 3.10+ Annotated가 없는 경우
- ```Python hl_lines="3"
- {!> ../../../docs_src/dependencies/tutorial001_an_py39.py!}
- ```
+/// tip | "팁"
-=== "Python 3.8+"
+가능하다면 `Annotated`가 달린 버전을 권장합니다.
+
+///
+
+```Python hl_lines="1"
+{!> ../../../docs_src/dependencies/tutorial001_py310.py!}
+```
- ```Python hl_lines="3"
- {!> ../../../docs_src/dependencies/tutorial001_an.py!}
- ```
+////
-=== "Python 3.10+ Annotated가 없는 경우"
+//// tab | Python 3.8+ Annotated가 없는 경우
- !!! tip "팁"
- 가능하다면 `Annotated`가 달린 버전을 권장합니다.
+/// tip | "팁"
- ```Python hl_lines="1"
- {!> ../../../docs_src/dependencies/tutorial001_py310.py!}
- ```
+가능하다면 `Annotated`가 달린 버전을 권장합니다.
-=== "Python 3.8+ Annotated가 없는 경우"
+///
- !!! tip "팁"
- 가능하다면 `Annotated`가 달린 버전을 권장합니다.
+```Python hl_lines="3"
+{!> ../../../docs_src/dependencies/tutorial001.py!}
+```
- ```Python hl_lines="3"
- {!> ../../../docs_src/dependencies/tutorial001.py!}
- ```
+////
### "의존자"에 의존성 명시하기
*경로 작동 함수*의 매개변수로 `Body`, `Query` 등을 사용하는 방식과 같이 새로운 매개변수로 `Depends`를 사용합니다:
-=== "Python 3.10+"
+//// tab | Python 3.10+
+
+```Python hl_lines="13 18"
+{!> ../../../docs_src/dependencies/tutorial001_an_py310.py!}
+```
+
+////
- ```Python hl_lines="13 18"
- {!> ../../../docs_src/dependencies/tutorial001_an_py310.py!}
- ```
+//// tab | Python 3.9+
-=== "Python 3.9+"
+```Python hl_lines="15 20"
+{!> ../../../docs_src/dependencies/tutorial001_an_py39.py!}
+```
+
+////
- ```Python hl_lines="15 20"
- {!> ../../../docs_src/dependencies/tutorial001_an_py39.py!}
- ```
+//// tab | Python 3.8+
-=== "Python 3.8+"
+```Python hl_lines="16 21"
+{!> ../../../docs_src/dependencies/tutorial001_an.py!}
+```
- ```Python hl_lines="16 21"
- {!> ../../../docs_src/dependencies/tutorial001_an.py!}
- ```
+////
-=== "Python 3.10+ Annotated가 없는 경우"
+//// tab | Python 3.10+ Annotated가 없는 경우
- !!! tip "팁"
- 가능하다면 `Annotated`가 달린 버전을 권장합니다.
+/// tip | "팁"
- ```Python hl_lines="11 16"
- {!> ../../../docs_src/dependencies/tutorial001_py310.py!}
- ```
+가능하다면 `Annotated`가 달린 버전을 권장합니다.
-=== "Python 3.8+ Annotated가 없는 경우"
+///
- !!! tip "팁"
- 가능하다면 `Annotated`가 달린 버전을 권장합니다.
+```Python hl_lines="11 16"
+{!> ../../../docs_src/dependencies/tutorial001_py310.py!}
+```
+
+////
+
+//// tab | Python 3.8+ Annotated가 없는 경우
+
+/// tip | "팁"
+
+가능하다면 `Annotated`가 달린 버전을 권장합니다.
+
+///
+
+```Python hl_lines="15 20"
+{!> ../../../docs_src/dependencies/tutorial001.py!}
+```
- ```Python hl_lines="15 20"
- {!> ../../../docs_src/dependencies/tutorial001.py!}
- ```
+////
비록 `Body`, `Query` 등을 사용하는 것과 같은 방식으로 여러분의 함수의 매개변수에 있는 `Depends`를 사용하지만, `Depends`는 약간 다르게 작동합니다.
그리고 그 함수는 *경로 작동 함수*가 작동하는 것과 같은 방식으로 매개변수를 받습니다.
-!!! tip "팁"
- 여러분은 다음 장에서 함수를 제외하고서, "다른 것들"이 어떻게 의존성으로 사용되는지 알게 될 것입니다.
+/// tip | "팁"
+
+여러분은 다음 장에서 함수를 제외하고서, "다른 것들"이 어떻게 의존성으로 사용되는지 알게 될 것입니다.
+
+///
새로운 요청이 도착할 때마다, **FastAPI**는 다음을 처리합니다:
이렇게 하면 공용 코드를 한번만 적어도 되며, **FastAPI**는 *경로 작동*을 위해 이에 대한 호출을 처리합니다.
-!!! check "확인"
- 특별한 클래스를 만들지 않아도 되며, 이러한 것 혹은 비슷한 종류를 **FastAPI**에 "등록"하기 위해 어떤 곳에 넘겨주지 않아도 됩니다.
+/// check | "확인"
+
+특별한 클래스를 만들지 않아도 되며, 이러한 것 혹은 비슷한 종류를 **FastAPI**에 "등록"하기 위해 어떤 곳에 넘겨주지 않아도 됩니다.
+
+단순히 `Depends`에 넘겨주기만 하면 되며, **FastAPI**는 나머지를 어찌할지 알고 있습니다.
- 단순히 `Depends`에 넘겨주기만 하면 되며, **FastAPI**는 나머지를 어찌할지 알고 있습니다.
+///
## `Annotated`인 의존성 공유하기
하지만 `Annotated`를 사용하고 있기에, `Annotated` 값을 변수에 저장하고 여러 장소에서 사용할 수 있습니다:
-=== "Python 3.10+"
+//// tab | Python 3.10+
+
+```Python hl_lines="12 16 21"
+{!> ../../../docs_src/dependencies/tutorial001_02_an_py310.py!}
+```
+
+////
- ```Python hl_lines="12 16 21"
- {!> ../../../docs_src/dependencies/tutorial001_02_an_py310.py!}
- ```
+//// tab | Python 3.9+
-=== "Python 3.9+"
+```Python hl_lines="14 18 23"
+{!> ../../../docs_src/dependencies/tutorial001_02_an_py39.py!}
+```
+
+////
- ```Python hl_lines="14 18 23"
- {!> ../../../docs_src/dependencies/tutorial001_02_an_py39.py!}
- ```
+//// tab | Python 3.8+
+
+```Python hl_lines="15 19 24"
+{!> ../../../docs_src/dependencies/tutorial001_02_an.py!}
+```
-=== "Python 3.8+"
+////
- ```Python hl_lines="15 19 24"
- {!> ../../../docs_src/dependencies/tutorial001_02_an.py!}
- ```
+/// tip | "팁"
-!!! tip "팁"
- 이는 그저 표준 파이썬이고 "type alias"라고 부르며 사실 **FastAPI**에 국한되는 것은 아닙니다.
+이는 그저 표준 파이썬이고 "type alias"라고 부르며 사실 **FastAPI**에 국한되는 것은 아닙니다.
- 하지만, `Annotated`를 포함하여, **FastAPI**가 파이썬 표준을 기반으로 하고 있기에, 이를 여러분의 코드 트릭으로 사용할 수 있습니다. 😎
+하지만, `Annotated`를 포함하여, **FastAPI**가 파이썬 표준을 기반으로 하고 있기에, 이를 여러분의 코드 트릭으로 사용할 수 있습니다. 😎
+
+///
이 의존성은 계속해서 예상한대로 작동할 것이며, **제일 좋은 부분**은 **타입 정보가 보존된다는 것입니다**. 즉 여러분의 편집기가 **자동 완성**, **인라인 에러** 등을 계속해서 제공할 수 있다는 것입니다. `mypy`같은 다른 도구도 마찬가지입니다.
아무 문제 없습니다. **FastAPI**는 무엇을 할지 알고 있습니다.
-!!! note "참고"
- 잘 모르시겠다면, [Async: *"In a hurry?"*](../../async.md){.internal-link target=_blank} 문서에서 `async`와 `await`에 대해 확인할 수 있습니다.
+/// note | "참고"
+
+잘 모르시겠다면, [Async: *"In a hurry?"*](../../async.md){.internal-link target=_blank} 문서에서 `async`와 `await`에 대해 확인할 수 있습니다.
+
+///
## OpenAPI와 통합
길이가 긴 문자열 형태의 JSON 형식(문자열)의 데이터가 들어있는 상황에서는 `str`로 반환하지 않습니다. JSON과 모두 호환되는 값과 하위 값이 있는 Python 표준 데이터 구조 (예: `dict`)를 반환합니다.
-!!! note "참고"
- 실제로 `jsonable_encoder`는 **FastAPI** 에서 내부적으로 데이터를 변환하는 데 사용하지만, 다른 많은 곳에서도 이는 유용합니다.
+/// note | "참고"
+
+실제로 `jsonable_encoder`는 **FastAPI** 에서 내부적으로 데이터를 변환하는 데 사용하지만, 다른 많은 곳에서도 이는 유용합니다.
+
+///
위의 몇몇 자료형을 매개변수로 사용하는 *경로 작동* 예시입니다.
-=== "Python 3.10+"
+//// tab | Python 3.10+
- ```Python hl_lines="1 3 12-16"
- {!> ../../../docs_src/extra_data_types/tutorial001_an_py310.py!}
- ```
+```Python hl_lines="1 3 12-16"
+{!> ../../../docs_src/extra_data_types/tutorial001_an_py310.py!}
+```
-=== "Python 3.9+"
+////
- ```Python hl_lines="1 3 12-16"
- {!> ../../../docs_src/extra_data_types/tutorial001_an_py39.py!}
- ```
+//// tab | Python 3.9+
-=== "Python 3.8+"
+```Python hl_lines="1 3 12-16"
+{!> ../../../docs_src/extra_data_types/tutorial001_an_py39.py!}
+```
- ```Python hl_lines="1 3 13-17"
- {!> ../../../docs_src/extra_data_types/tutorial001_an.py!}
- ```
+////
-=== "Python 3.10+ non-Annotated"
+//// tab | Python 3.8+
- !!! tip
- Prefer to use the `Annotated` version if possible.
+```Python hl_lines="1 3 13-17"
+{!> ../../../docs_src/extra_data_types/tutorial001_an.py!}
+```
- ```Python hl_lines="1 2 11-15"
- {!> ../../../docs_src/extra_data_types/tutorial001_py310.py!}
- ```
+////
-=== "Python 3.8+ non-Annotated"
+//// tab | Python 3.10+ non-Annotated
- !!! tip
- Prefer to use the `Annotated` version if possible.
+/// tip
- ```Python hl_lines="1 2 12-16"
- {!> ../../../docs_src/extra_data_types/tutorial001.py!}
- ```
+Prefer to use the `Annotated` version if possible.
+
+///
+
+```Python hl_lines="1 2 11-15"
+{!> ../../../docs_src/extra_data_types/tutorial001_py310.py!}
+```
+
+////
+
+//// tab | Python 3.8+ non-Annotated
+
+/// tip
+
+Prefer to use the `Annotated` version if possible.
+
+///
+
+```Python hl_lines="1 2 12-16"
+{!> ../../../docs_src/extra_data_types/tutorial001.py!}
+```
+
+////
함수 안의 매개변수가 그들만의 데이터 자료형을 가지고 있으며, 예를 들어, 다음과 같이 날짜를 조작할 수 있음을 참고하십시오:
-=== "Python 3.10+"
+//// tab | Python 3.10+
+
+```Python hl_lines="18-19"
+{!> ../../../docs_src/extra_data_types/tutorial001_an_py310.py!}
+```
+
+////
+
+//// tab | Python 3.9+
+
+```Python hl_lines="18-19"
+{!> ../../../docs_src/extra_data_types/tutorial001_an_py39.py!}
+```
+
+////
+
+//// tab | Python 3.8+
+
+```Python hl_lines="19-20"
+{!> ../../../docs_src/extra_data_types/tutorial001_an.py!}
+```
+
+////
+
+//// tab | Python 3.10+ non-Annotated
- ```Python hl_lines="18-19"
- {!> ../../../docs_src/extra_data_types/tutorial001_an_py310.py!}
- ```
+/// tip
-=== "Python 3.9+"
+Prefer to use the `Annotated` version if possible.
- ```Python hl_lines="18-19"
- {!> ../../../docs_src/extra_data_types/tutorial001_an_py39.py!}
- ```
+///
-=== "Python 3.8+"
+```Python hl_lines="17-18"
+{!> ../../../docs_src/extra_data_types/tutorial001_py310.py!}
+```
- ```Python hl_lines="19-20"
- {!> ../../../docs_src/extra_data_types/tutorial001_an.py!}
- ```
+////
-=== "Python 3.10+ non-Annotated"
+//// tab | Python 3.8+ non-Annotated
- !!! tip
- Prefer to use the `Annotated` version if possible.
+/// tip
- ```Python hl_lines="17-18"
- {!> ../../../docs_src/extra_data_types/tutorial001_py310.py!}
- ```
+Prefer to use the `Annotated` version if possible.
-=== "Python 3.8+ non-Annotated"
+///
- !!! tip
- Prefer to use the `Annotated` version if possible.
+```Python hl_lines="18-19"
+{!> ../../../docs_src/extra_data_types/tutorial001.py!}
+```
- ```Python hl_lines="18-19"
- {!> ../../../docs_src/extra_data_types/tutorial001.py!}
- ```
+////
</div>
-!!! note "참고"
- `uvicorn main:app` 명령은 다음을 의미합니다:
+/// note | "참고"
- * `main`: 파일 `main.py` (파이썬 "모듈").
- * `app`: `main.py` 내부의 `app = FastAPI()` 줄에서 생성한 오브젝트.
- * `--reload`: 코드 변경 시 자동으로 서버 재시작. 개발 시에만 사용.
+`uvicorn main:app` 명령은 다음을 의미합니다:
+
+* `main`: 파일 `main.py` (파이썬 "모듈").
+* `app`: `main.py` 내부의 `app = FastAPI()` 줄에서 생성한 오브젝트.
+* `--reload`: 코드 변경 시 자동으로 서버 재시작. 개발 시에만 사용.
+
+///
출력되는 줄들 중에는 아래와 같은 내용이 있습니다:
`FastAPI`는 당신의 API를 위한 모든 기능을 제공하는 파이썬 클래스입니다.
-!!! note "기술 세부사항"
- `FastAPI`는 `Starlette`를 직접 상속하는 클래스입니다.
+/// note | "기술 세부사항"
+
+`FastAPI`는 `Starlette`를 직접 상속하는 클래스입니다.
- `FastAPI`로 <a href="https://www.starlette.io/" class="external-link" target="_blank">Starlette</a>의 모든 기능을 사용할 수 있습니다.
+`FastAPI`로 <a href="https://www.starlette.io/" class="external-link" target="_blank">Starlette</a>의 모든 기능을 사용할 수 있습니다.
+
+///
### 2 단계: `FastAPI` "인스턴스" 생성
/items/foo
```
-!!! info "정보"
- "경로"는 일반적으로 "엔드포인트" 또는 "라우트"라고도 불립니다.
+/// info | "정보"
+
+"경로"는 일반적으로 "엔드포인트" 또는 "라우트"라고도 불립니다.
+
+///
API를 설계할 때 "경로"는 "관심사"와 "리소스"를 분리하기 위한 주요한 방법입니다.
* 경로 `/`
* <abbr title="HTTP GET 메소드"><code>get</code> 작동</abbr> 사용
-!!! info "`@decorator` 정보"
- 이 `@something` 문법은 파이썬에서 "데코레이터"라 부릅니다.
+/// info | "`@decorator` 정보"
- 마치 예쁜 장식용(Decorative) 모자처럼(개인적으로 이 용어가 여기서 유래한 것 같습니다) 함수 맨 위에 놓습니다.
+이 `@something` 문법은 파이썬에서 "데코레이터"라 부릅니다.
- "데코레이터"는 아래 있는 함수를 받아 그것으로 무언가를 합니다.
+마치 예쁜 장식용(Decorative) 모자처럼(개인적으로 이 용어가 여기서 유래한 것 같습니다) 함수 맨 위에 놓습니다.
- 우리의 경우, 이 데코레이터는 **FastAPI**에게 아래 함수가 **경로** `/`의 `get` **작동**에 해당한다고 알려줍니다.
+"데코레이터"는 아래 있는 함수를 받아 그것으로 무언가를 합니다.
- 이것이 "**경로 작동 데코레이터**"입니다.
+우리의 경우, 이 데코레이터는 **FastAPI**에게 아래 함수가 **경로** `/`의 `get` **작동**에 해당한다고 알려줍니다.
+
+이것이 "**경로 작동 데코레이터**"입니다.
+
+///
다른 작동도 사용할 수 있습니다:
* `@app.patch()`
* `@app.trace()`
-!!! tip "팁"
- 각 작동(HTTP 메소드)을 원하는 대로 사용해도 됩니다.
+/// tip | "팁"
+
+각 작동(HTTP 메소드)을 원하는 대로 사용해도 됩니다.
- **FastAPI**는 특정 의미를 강제하지 않습니다.
+**FastAPI**는 특정 의미를 강제하지 않습니다.
- 여기서 정보는 지침서일뿐 강제사항이 아닙니다.
+여기서 정보는 지침서일뿐 강제사항이 아닙니다.
- 예를 들어 GraphQL을 사용하는 경우, 일반적으로 `POST` 작동만 사용하여 모든 행동을 수행합니다.
+예를 들어 GraphQL을 사용하는 경우, 일반적으로 `POST` 작동만 사용하여 모든 행동을 수행합니다.
+
+///
### 4 단계: **경로 작동 함수** 정의
{!../../../docs_src/first_steps/tutorial003.py!}
```
-!!! note "참고"
- 차이점을 모르겠다면 [Async: *"바쁘신 경우"*](../async.md#_1){.internal-link target=_blank}을 확인하세요.
+/// note | "참고"
+
+차이점을 모르겠다면 [Async: *"바쁘신 경우"*](../async.md#_1){.internal-link target=_blank}을 확인하세요.
+
+///
### 5 단계: 콘텐츠 반환
{!../../../docs_src/header_params/tutorial001.py!}
```
-!!! note "기술 세부사항"
- `Header`는 `Path`, `Query` 및 `Cookie`의 "자매"클래스입니다. 이 역시 동일한 공통 `Param` 클래스를 상속합니다.
+/// note | "기술 세부사항"
- `Query`, `Path`, `Header` 그리고 다른 것들을 `fastapi`에서 임포트 할 때, 이들은 실제로 특별한 클래스를 반환하는 함수임을 기억하세요.
+`Header`는 `Path`, `Query` 및 `Cookie`의 "자매"클래스입니다. 이 역시 동일한 공통 `Param` 클래스를 상속합니다.
-!!! info "정보"
- 헤더를 선언하기 위해서 `Header`를 사용해야 합니다. 그렇지 않으면 해당 매개변수를 쿼리 매개변수로 해석하기 때문입니다.
+`Query`, `Path`, `Header` 그리고 다른 것들을 `fastapi`에서 임포트 할 때, 이들은 실제로 특별한 클래스를 반환하는 함수임을 기억하세요.
+
+///
+
+/// info | "정보"
+
+헤더를 선언하기 위해서 `Header`를 사용해야 합니다. 그렇지 않으면 해당 매개변수를 쿼리 매개변수로 해석하기 때문입니다.
+
+///
## 자동 변환
{!../../../docs_src/header_params/tutorial002.py!}
```
-!!! warning "경고"
- `convert_underscore`를 `False`로 설정하기 전에, 어떤 HTTP 프록시들과 서버들은 언더스코어가 포함된 헤더 사용을 허락하지 않는다는 것을 명심하십시오.
+/// warning | "경고"
+
+`convert_underscore`를 `False`로 설정하기 전에, 어떤 HTTP 프록시들과 서버들은 언더스코어가 포함된 헤더 사용을 허락하지 않는다는 것을 명심하십시오.
+
+///
## 중복 헤더
...이는 코드를 실행하는 서버로 사용할 수 있는 `uvicorn` 또한 포함하고 있습니다.
-!!! note "참고"
- 부분적으로 설치할 수도 있습니다.
+/// note | "참고"
- 애플리케이션을 운영 환경에 배포하려는 경우 다음과 같이 합니다:
+부분적으로 설치할 수도 있습니다.
- ```
- pip install fastapi
- ```
+애플리케이션을 운영 환경에 배포하려는 경우 다음과 같이 합니다:
- 추가로 서버 역할을 하는 `uvicorn`을 설치합니다:
+```
+pip install fastapi
+```
+
+추가로 서버 역할을 하는 `uvicorn`을 설치합니다:
+
+```
+pip install uvicorn
+```
- ```
- pip install uvicorn
- ```
+사용하려는 각 선택적인 의존성에 대해서도 동일합니다.
- 사용하려는 각 선택적인 의존성에 대해서도 동일합니다.
+///
## 고급 사용자 안내서
* **응답** 또는 다른 필요한 코드를 실행시키는 동작을 할 수 있습니다.
* **응답**를 반환합니다.
-!!! note "기술 세부사항"
- 만약 `yield`를 사용한 의존성을 가지고 있다면, 미들웨어가 실행되고 난 후에 exit이 실행됩니다.
+/// note | "기술 세부사항"
- 만약 (나중에 문서에서 다룰) 백그라운드 작업이 있다면, 모든 미들웨어가 실행되고 *난 후에* 실행됩니다.
+만약 `yield`를 사용한 의존성을 가지고 있다면, 미들웨어가 실행되고 난 후에 exit이 실행됩니다.
+
+만약 (나중에 문서에서 다룰) 백그라운드 작업이 있다면, 모든 미들웨어가 실행되고 *난 후에* 실행됩니다.
+
+///
## 미들웨어 만들기
{!../../../docs_src/middleware/tutorial001.py!}
```
-!!! tip "팁"
- 사용자 정의 헤더는 <a href="https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers" class="external-link" target="_blank">'X-' 접두사를 사용</a>하여 추가할 수 있습니다.
+/// tip | "팁"
+
+사용자 정의 헤더는 <a href="https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers" class="external-link" target="_blank">'X-' 접두사를 사용</a>하여 추가할 수 있습니다.
+
+그러나 만약 클라이언트의 브라우저에서 볼 수 있는 사용자 정의 헤더를 가지고 있다면, 그것들을 CORS 설정([CORS (Cross-Origin Resource Sharing)](cors.md){.internal-link target=_blank})에 <a href="https://www.starlette.io/middleware/#corsmiddleware" class="external-link" target="_blank">Starlette CORS 문서</a>에 명시된 `expose_headers` 매개변수를 이용하여 헤더들을 추가하여야합니다.
+
+///
+
+/// note | "기술적 세부사항"
- 그러나 만약 클라이언트의 브라우저에서 볼 수 있는 사용자 정의 헤더를 가지고 있다면, 그것들을 CORS 설정([CORS (Cross-Origin Resource Sharing)](cors.md){.internal-link target=_blank})에 <a href="https://www.starlette.io/middleware/#corsmiddleware" class="external-link" target="_blank">Starlette CORS 문서</a>에 명시된 `expose_headers` 매개변수를 이용하여 헤더들을 추가하여야합니다.
+`from starlette.requests import request`를 사용할 수도 있습니다.
-!!! note "기술적 세부사항"
- `from starlette.requests import request`를 사용할 수도 있습니다.
+**FastAPI**는 개발자에게 편의를 위해 이를 제공합니다. 그러나 Starlette에서 직접 파생되었습니다.
- **FastAPI**는 개발자에게 편의를 위해 이를 제공합니다. 그러나 Starlette에서 직접 파생되었습니다.
+///
### `response`의 전과 후
*경로 작동 데코레이터*를 설정하기 위해서 전달할수 있는 몇 가지 매개변수가 있습니다.
-!!! warning "경고"
- 아래 매개변수들은 *경로 작동 함수*가 아닌 *경로 작동 데코레이터*에 직접 전달된다는 사실을 기억하십시오.
+/// warning | "경고"
+
+아래 매개변수들은 *경로 작동 함수*가 아닌 *경로 작동 데코레이터*에 직접 전달된다는 사실을 기억하십시오.
+
+///
## 응답 상태 코드
각 상태 코드들은 응답에 사용되며, OpenAPI 스키마에 추가됩니다.
-!!! note "기술적 세부사항"
- 다음과 같이 임포트하셔도 좋습니다. `from starlette import status`.
+/// note | "기술적 세부사항"
+
+다음과 같이 임포트하셔도 좋습니다. `from starlette import status`.
+
+**FastAPI**는 개발자 여러분의 편의를 위해서 `starlette.status`와 동일한 `fastapi.status`를 제공합니다. 하지만 Starlette에서 직접 온 것입니다.
- **FastAPI**는 개발자 여러분의 편의를 위해서 `starlette.status`와 동일한 `fastapi.status`를 제공합니다. 하지만 Starlette에서 직접 온 것입니다.
+///
## 태그
{!../../../docs_src/path_operation_configuration/tutorial005.py!}
```
-!!! info "정보"
- `response_description`은 구체적으로 응답을 지칭하며, `description`은 일반적인 *경로 작동*을 지칭합니다.
+/// info | "정보"
+
+`response_description`은 구체적으로 응답을 지칭하며, `description`은 일반적인 *경로 작동*을 지칭합니다.
+
+///
+
+/// check | "확인"
+
+OpenAPI는 각 *경로 작동*이 응답에 관한 설명을 요구할 것을 명시합니다.
-!!! check "확인"
- OpenAPI는 각 *경로 작동*이 응답에 관한 설명을 요구할 것을 명시합니다.
+따라서, 응답에 관한 설명이 없을경우, **FastAPI**가 자동으로 "성공 응답" 중 하나를 생성합니다.
- 따라서, 응답에 관한 설명이 없을경우, **FastAPI**가 자동으로 "성공 응답" 중 하나를 생성합니다.
+///
<img src="/img/tutorial/path-operation-configuration/image03.png">
{!../../../docs_src/path_params_numeric_validations/tutorial001.py!}
```
-!!! note "참고"
- 경로 매개변수는 경로의 일부여야 하므로 언제나 필수적입니다.
+/// note | "참고"
- 즉, `...`로 선언해서 필수임을 나타내는게 좋습니다.
+경로 매개변수는 경로의 일부여야 하므로 언제나 필수적입니다.
- 그럼에도 `None`으로 선언하거나 기본값을 지정할지라도 아무 영향을 끼치지 않으며 언제나 필수입니다.
+즉, `...`로 선언해서 필수임을 나타내는게 좋습니다.
+
+그럼에도 `None`으로 선언하거나 기본값을 지정할지라도 아무 영향을 끼치지 않으며 언제나 필수입니다.
+
+///
## 필요한 경우 매개변수 정렬하기
* `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`라는 이름을 가진 클래스의 인스턴스를 반환합니다.
+편집기에서 타입에 대한 오류를 표시하지 않도록 하기 위해 (클래스를 직접 사용하는 대신) 이러한 함수들이 있습니다.
- 편집기에서 타입에 대한 오류를 표시하지 않도록 하기 위해 (클래스를 직접 사용하는 대신) 이러한 함수들이 있습니다.
+이렇게 하면 오류를 무시하기 위한 사용자 설정을 추가하지 않고도 일반 편집기와 코딩 도구를 사용할 수 있습니다.
- 이렇게 하면 오류를 무시하기 위한 사용자 설정을 추가하지 않고도 일반 편집기와 코딩 도구를 사용할 수 있습니다.
+///
위의 예시에서, `item_id`는 `int`로 선언되었습니다.
-!!! check "확인"
- 이 기능은 함수 내에서 오류 검사, 자동완성 등의 편집기 기능을 활용할 수 있게 해줍니다.
+/// check | "확인"
+
+이 기능은 함수 내에서 오류 검사, 자동완성 등의 편집기 기능을 활용할 수 있게 해줍니다.
+
+///
## 데이터 <abbr title="다음으로도 알려져 있습니다: 직렬화, 파싱, 마샬링">변환</abbr>
{"item_id":3}
```
-!!! check "확인"
- 함수가 받은(반환도 하는) 값은 문자열 `"3"`이 아니라 파이썬 `int` 형인 `3`입니다.
+/// check | "확인"
+
+함수가 받은(반환도 하는) 값은 문자열 `"3"`이 아니라 파이썬 `int` 형인 `3`입니다.
+
+즉, 타입 선언을 하면 **FastAPI**는 자동으로 요청을 <abbr title="HTTP 요청에서 전달되는 문자열을 파이썬 데이터로 변환">"파싱"</abbr>합니다.
- 즉, 타입 선언을 하면 **FastAPI**는 자동으로 요청을 <abbr title="HTTP 요청에서 전달되는 문자열을 파이썬 데이터로 변환">"파싱"</abbr>합니다.
+///
## 데이터 검증
`int`가 아닌 `float`을 전달하는 경우에도 동일한 오류가 나타납니다: <a href="http://127.0.0.1:8000/items/4.2" class="external-link" target="_blank">http://127.0.0.1:8000/items/4.2</a>
-!!! check "확인"
- 즉, 파이썬 타입 선언을 하면 **FastAPI**는 데이터 검증을 합니다.
+/// check | "확인"
- ì\98¤ë¥\98ì\97\90ë\8a\94 ì \95í\99\95í\9e\88 ì\96´ë\8a\90 ì§\80ì \90ì\97\90ì\84\9c ê²\80ì¦\9dì\9d\84 í\86µê³¼í\95\98ì§\80 못í\96\88ë\8a\94ì§\80 ëª\85ì\8b\9cë\90©ë\8b\88ë\8b¤.
+ì¦\89, í\8c\8cì\9d´ì\8d¬ í\83\80ì\9e\85 ì\84 ì\96¸ì\9d\84 í\95\98ë©´ **FastAPI**ë\8a\94 ë\8d°ì\9d´í\84° ê²\80ì¦\9dì\9d\84 í\95©ë\8b\88ë\8b¤.
- 이는 API와 상호 작용하는 코드를 개발하고 디버깅하는 데 매우 유용합니다.
+오류에는 정확히 어느 지점에서 검증을 통과하지 못했는지 명시됩니다.
+
+이는 API와 상호 작용하는 코드를 개발하고 디버깅하는 데 매우 유용합니다.
+
+///
## 문서화
<img src="/img/tutorial/path-params/image01.png">
-!!! check "확인"
- 그저 파이썬 타입 선언을 하기만 하면 **FastAPI**는 자동 대화형 API 문서(Swagger UI)를 제공합니다.
+/// check | "확인"
+
+그저 파이썬 타입 선언을 하기만 하면 **FastAPI**는 자동 대화형 API 문서(Swagger UI)를 제공합니다.
+
+경로 매개변수가 정수형으로 명시된 것을 확인할 수 있습니다.
- 경로 매개변수가 정수형으로 명시된 것을 확인할 수 있습니다.
+///
## 표준 기반의 이점, 대체 문서
{!../../../docs_src/path_params/tutorial005.py!}
```
-!!! info "정보"
- <a href="https://docs.python.org/3/library/enum.html" class="external-link" target="_blank">열거형(또는 enums)</a>은 파이썬 버전 3.4 이후로 사용 가능합니다.
+/// info | "정보"
-!!! tip "팁"
- 혹시 궁금하다면, "AlexNet", "ResNet", 그리고 "LeNet"은 그저 기계 학습 <abbr title="기술적으로 정확히는 딥 러닝 모델 구조">모델</abbr>들의 이름입니다.
+<a href="https://docs.python.org/3/library/enum.html" class="external-link" target="_blank">열거형(또는 enums)</a>은 파이썬 버전 3.4 이후로 사용 가능합니다.
+
+///
+
+/// tip | "팁"
+
+혹시 궁금하다면, "AlexNet", "ResNet", 그리고 "LeNet"은 그저 기계 학습 <abbr title="기술적으로 정확히는 딥 러닝 모델 구조">모델</abbr>들의 이름입니다.
+
+///
### *경로 매개변수* 선언
{!../../../docs_src/path_params/tutorial005.py!}
```
-!!! tip "팁"
- `ModelName.lenet.value`로도 값 `"lenet"`에 접근할 수 있습니다.
+/// tip | "팁"
+
+`ModelName.lenet.value`로도 값 `"lenet"`에 접근할 수 있습니다.
+
+///
#### *열거형 멤버* 반환
{!../../../docs_src/path_params/tutorial004.py!}
```
-!!! tip "팁"
- 매개변수가 가져야 하는 값이 `/home/johndoe/myfile.txt`와 같이 슬래시로 시작(`/`)해야 할 수 있습니다.
+/// tip | "팁"
+
+매개변수가 가져야 하는 값이 `/home/johndoe/myfile.txt`와 같이 슬래시로 시작(`/`)해야 할 수 있습니다.
+
+이 경우 URL은: `/files//home/johndoe/myfile.txt`이며 `files`과 `home` 사이에 이중 슬래시(`//`)가 생깁니다.
- 이 경우 URL은: `/files//home/johndoe/myfile.txt`이며 `files`과 `home` 사이에 이중 슬래시(`//`)가 생깁니다.
+///
## 요약
쿼리 매개변수 `q`는 `Optional[str]` 자료형입니다. 즉, `str` 자료형이지만 `None` 역시 될 수 있음을 뜻하고, 실제로 기본값은 `None`이기 때문에 FastAPI는 이 매개변수가 필수가 아니라는 것을 압니다.
-!!! note "참고"
- FastAPI는 `q`의 기본값이 `= None`이기 때문에 필수가 아님을 압니다.
+/// note | "참고"
- `Optional[str]`에 있는 `Optional`은 FastAPI가 사용하는게 아니지만, 편집기에게 더 나은 지원과 오류 탐지를 제공하게 해줍니다.
+FastAPI는 `q`의 기본값이 `= None`이기 때문에 필수가 아님을 압니다.
+
+`Optional[str]`에 있는 `Optional`은 FastAPI가 사용하는게 아니지만, 편집기에게 더 나은 지원과 오류 탐지를 제공하게 해줍니다.
+
+///
## 추가 검증
하지만 명시적으로 쿼리 매개변수를 선언합니다.
-!!! info "정보"
- FastAPI는 다음 부분에 관심이 있습니다:
+/// info | "정보"
- ```Python
- = None
- ```
+FastAPI는 다음 부분에 관심이 있습니다:
- 또는:
+```Python
+= None
+```
- ```Python
- = Query(None)
- ```
+또는:
- 그리고 `None`을 사용하여 쿼라 매개변수가 필수적이지 않다는 것을 파악합니다.
+```Python
+= Query(None)
+```
+
+그리고 `None`을 사용하여 쿼라 매개변수가 필수적이지 않다는 것을 파악합니다.
- `Optional` 부분은 편집기에게 더 나은 지원을 제공하기 위해서만 사용됩니다.
+`Optional` 부분은 편집기에게 더 나은 지원을 제공하기 위해서만 사용됩니다.
+
+///
또한 `Query`로 더 많은 매개변수를 전달할 수 있습니다. 지금의 경우 문자열에 적용되는 `max_length` 매개변수입니다:
{!../../../docs_src/query_params_str_validations/tutorial005.py!}
```
-!!! note "참고"
- 기본값을 갖는 것만으로 매개변수는 선택적이 됩니다.
+/// note | "참고"
+
+기본값을 갖는 것만으로 매개변수는 선택적이 됩니다.
+
+///
## 필수로 만들기
{!../../../docs_src/query_params_str_validations/tutorial006.py!}
```
-!!! info "정보"
- 이전에 `...`를 본적이 없다면: 특별한 단일값으로, <a href="https://docs.python.org/3/library/constants.html#Ellipsis" class="external-link" target="_blank">파이썬의 일부이며 "Ellipsis"라 부릅니다</a>.
+/// info | "정보"
+
+이전에 `...`를 본적이 없다면: 특별한 단일값으로, <a href="https://docs.python.org/3/library/constants.html#Ellipsis" class="external-link" target="_blank">파이썬의 일부이며 "Ellipsis"라 부릅니다</a>.
+
+///
이렇게 하면 **FastAPI**가 이 매개변수는 필수임을 알 수 있습니다.
}
```
-!!! tip "팁"
- 위의 예와 같이 `list` 자료형으로 쿼리 매개변수를 선언하려면 `Query`를 명시적으로 사용해야 합니다. 그렇지 않으면 요청 본문으로 해석됩니다.
+/// tip | "팁"
+
+위의 예와 같이 `list` 자료형으로 쿼리 매개변수를 선언하려면 `Query`를 명시적으로 사용해야 합니다. 그렇지 않으면 요청 본문으로 해석됩니다.
+
+///
대화형 API 문서는 여러 값을 허용하도록 수정 됩니다:
{!../../../docs_src/query_params_str_validations/tutorial013.py!}
```
-!!! note "참고"
- 이 경우 FastAPI는 리스트의 내용을 검사하지 않음을 명심하기 바랍니다.
+/// note | "참고"
- 예를 들어, `List[int]`는 리스트 내용이 정수인지 검사(및 문서화)합니다. 하지만 `list` 단독일 경우는 아닙니다.
+이 경우 FastAPI는 리스트의 내용을 검사하지 않음을 명심하기 바랍니다.
+
+예를 들어, `List[int]`는 리스트 내용이 정수인지 검사(및 문서화)합니다. 하지만 `list` 단독일 경우는 아닙니다.
+
+///
## 더 많은 메타데이터 선언
해당 정보는 생성된 OpenAPI에 포함되고 문서 사용자 인터페이스 및 외부 도구에서 사용됩니다.
-!!! note "참고"
- 도구에 따라 OpenAPI 지원 수준이 다를 수 있음을 명심하기 바랍니다.
+/// note | "참고"
+
+도구에 따라 OpenAPI 지원 수준이 다를 수 있음을 명심하기 바랍니다.
+
+일부는 아직 선언된 추가 정보를 모두 표시하지 않을 수 있지만, 대부분의 경우 누락된 기능은 이미 개발 계획이 있습니다.
- 일부는 아직 선언된 추가 정보를 모두 표시하지 않을 수 있지만, 대부분의 경우 누락된 기능은 이미 개발 계획이 있습니다.
+///
`title`을 추가할 수 있습니다:
이 경우 함수 매개변수 `q`는 선택적이며 기본값으로 `None` 값이 됩니다.
-!!! check "확인"
- **FastAPI**는 `item_id`가 경로 매개변수이고 `q`는 경로 매개변수가 아닌 쿼리 매개변수라는 것을 알 정도로 충분히 똑똑합니다.
+/// check | "확인"
-!!! note "참고"
- FastAPI는 `q`가 `= None`이므로 선택적이라는 것을 인지합니다.
+**FastAPI**는 `item_id`가 경로 매개변수이고 `q`는 경로 매개변수가 아닌 쿼리 매개변수라는 것을 알 정도로 충분히 똑똑합니다.
- `Union[str, None]`에 있는 `Union`은 FastAPI(FastAPI는 `str` 부분만 사용합니다)가 사용하는게 아니지만, `Union[str, None]`은 편집기에게 코드에서 오류를 찾아낼 수 있게 도와줍니다.
+///
+
+/// note | "참고"
+
+FastAPI는 `q`가 `= None`이므로 선택적이라는 것을 인지합니다.
+
+`Union[str, None]`에 있는 `Union`은 FastAPI(FastAPI는 `str` 부분만 사용합니다)가 사용하는게 아니지만, `Union[str, None]`은 편집기에게 코드에서 오류를 찾아낼 수 있게 도와줍니다.
+
+///
## 쿼리 매개변수 형변환
* `skip`, 기본값이 `0`인 `int`.
* `limit`, 선택적인 `int`.
-!!! tip "팁"
- [경로 매개변수](path-params.md#_8){.internal-link target=_blank}와 마찬가지로 `Enum`을 사용할 수 있습니다.
+/// tip | "팁"
+
+[경로 매개변수](path-params.md#_8){.internal-link target=_blank}와 마찬가지로 `Enum`을 사용할 수 있습니다.
+
+///
`File`을 사용하여 클라이언트가 업로드할 파일들을 정의할 수 있습니다.
-!!! info "정보"
- 업로드된 파일을 전달받기 위해 먼저 <a href="https://github.com/Kludex/python-multipart" class="external-link" target="_blank">`python-multipart`</a>를 설치해야합니다.
+/// info | "정보"
- 예시) `pip install python-multipart`.
+업로드된 파일을 전달받기 위해 먼저 <a href="https://github.com/Kludex/python-multipart" class="external-link" target="_blank">`python-multipart`</a>를 설치해야합니다.
- 업로드된 파일들은 "폼 데이터"의 형태로 전송되기 때문에 이 작업이 필요합니다.
+예시) `pip install python-multipart`.
+
+업로드된 파일들은 "폼 데이터"의 형태로 전송되기 때문에 이 작업이 필요합니다.
+
+///
## `File` 임포트
{!../../../docs_src/request_files/tutorial001.py!}
```
-!!! info "정보"
- `File` 은 `Form` 으로부터 직접 상속된 클래스입니다.
+/// info | "정보"
+
+`File` 은 `Form` 으로부터 직접 상속된 클래스입니다.
+
+하지만 `fastapi`로부터 `Query`, `Path`, `File` 등을 임포트 할 때, 이것들은 특별한 클래스들을 반환하는 함수라는 것을 기억하기 바랍니다.
+
+///
- 하지만 `fastapi`로부터 `Query`, `Path`, `File` 등을 임포트 할 때, 이것들은 특별한 클래스들을 반환하는 함수라는 것을 기억하기 바랍니다.
+/// tip | "팁"
-!!! tip "팁"
- File의 본문을 선언할 때, 매개변수가 쿼리 매개변수 또는 본문(JSON) 매개변수로 해석되는 것을 방지하기 위해 `File` 을 사용해야합니다.
+File의 본문을 선언할 때, 매개변수가 쿼리 매개변수 또는 본문(JSON) 매개변수로 해석되는 것을 방지하기 위해 `File` 을 사용해야합니다.
+
+///
파일들은 "폼 데이터"의 형태로 업로드 됩니다.
contents = myfile.file.read()
```
-!!! note "`async` 기술적 세부사항"
- `async` 메소드들을 사용할 때 **FastAPI**는 스레드풀에서 파일 메소드들을 실행하고 그들을 기다립니다.
+/// note | "`async` 기술적 세부사항"
+
+`async` 메소드들을 사용할 때 **FastAPI**는 스레드풀에서 파일 메소드들을 실행하고 그들을 기다립니다.
+
+///
+
+/// note | "Starlette 기술적 세부사항"
-!!! note "Starlette 기술적 세부사항"
- **FastAPI**의 `UploadFile` 은 **Starlette**의 `UploadFile` 을 직접적으로 상속받지만, **Pydantic** 및 FastAPI의 다른 부분들과의 호환성을 위해 필요한 부분들이 추가되었습니다.
+**FastAPI**의 `UploadFile` 은 **Starlette**의 `UploadFile` 을 직접적으로 상속받지만, **Pydantic** 및 FastAPI의 다른 부분들과의 호환성을 위해 필요한 부분들이 추가되었습니다.
+
+///
## "폼 데이터"란
**FastAPI**는 JSON 대신 올바른 위치에서 데이터를 읽을 수 있도록 합니다.
-!!! note "기술적 세부사항"
- 폼의 데이터는 파일이 포함되지 않은 경우 일반적으로 "미디어 유형" `application/x-www-form-urlencoded` 을 사용해 인코딩 됩니다.
+/// note | "기술적 세부사항"
+
+폼의 데이터는 파일이 포함되지 않은 경우 일반적으로 "미디어 유형" `application/x-www-form-urlencoded` 을 사용해 인코딩 됩니다.
+
+하지만 파일이 포함된 경우, `multipart/form-data`로 인코딩됩니다. `File`을 사용하였다면, **FastAPI**는 본문의 적합한 부분에서 파일을 가져와야 한다는 것을 인지합니다.
+
+인코딩과 폼 필드에 대해 더 알고싶다면, <a href="https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods/POST" class="external-link" target="_blank"><code>POST</code>에 관한<abbr title="Mozilla Developer Network">MDN</abbr>웹 문서</a> 를 참고하기 바랍니다,.
+
+///
- 하지만 파일이 포함된 경우, `multipart/form-data`로 인코딩됩니다. `File`을 사용하였다면, **FastAPI**는 본문의 적합한 부분에서 파일을 가져와야 한다는 것을 인지합니다.
+/// warning | "경고"
- 인코딩과 폼 필드에 대해 더 알고싶다면, <a href="https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods/POST" class="external-link" target="_blank"><code>POST</code>에 관한<abbr title="Mozilla Developer Network">MDN</abbr>웹 문서</a> 를 참고하기 바랍니다,.
+다수의 `File` 과 `Form` 매개변수를 한 *경로 작동*에 선언하는 것이 가능하지만, 요청의 본문이 `application/json` 가 아닌 `multipart/form-data` 로 인코딩 되기 때문에 JSON으로 받아야하는 `Body` 필드를 함께 선언할 수는 없습니다.
-!!! warning "경고"
- 다수의 `File` 과 `Form` 매개변수를 한 *경로 작동*에 선언하는 것이 가능하지만, 요청의 본문이 `application/json` 가 아닌 `multipart/form-data` 로 인코딩 되기 때문에 JSON으로 받아야하는 `Body` 필드를 함께 선언할 수는 없습니다.
+이는 **FastAPI**의 한계가 아니라, HTTP 프로토콜에 의한 것입니다.
- 이는 **FastAPI**의 한계가 아니라, HTTP 프로토콜에 의한 것입니다.
+///
## 다중 파일 업로드
선언한대로, `bytes` 의 `list` 또는 `UploadFile` 들을 전송받을 것입니다.
-!!! note "참고"
- 2019년 4월 14일부터 Swagger UI가 하나의 폼 필드로 다수의 파일을 업로드하는 것을 지원하지 않습니다. 더 많은 정보를 원하면, <a href="https://github.com/swagger-api/swagger-ui/issues/4276" class="external-link" target="_blank">#4276</a>과 <a href="https://github.com/swagger-api/swagger-ui/issues/3641" class="external-link" target="_blank">#3641</a>을 참고하세요.
+/// note | "참고"
+
+2019년 4월 14일부터 Swagger UI가 하나의 폼 필드로 다수의 파일을 업로드하는 것을 지원하지 않습니다. 더 많은 정보를 원하면, <a href="https://github.com/swagger-api/swagger-ui/issues/4276" class="external-link" target="_blank">#4276</a>과 <a href="https://github.com/swagger-api/swagger-ui/issues/3641" class="external-link" target="_blank">#3641</a>을 참고하세요.
+
+그럼에도, **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로부터 직접 제공됩니다.
+///
## 요약
`File` 과 `Form` 을 사용하여 파일과 폼을 함께 정의할 수 있습니다.
-!!! info "정보"
- 파일과 폼 데이터를 함께, 또는 각각 업로드하기 위해 먼저 <a href="https://github.com/Kludex/python-multipart" class="external-link" target="_blank">`python-multipart`</a>를 설치해야합니다.
+/// info | "정보"
- 예 ) `pip install python-multipart`.
+파일과 폼 데이터를 함께, 또는 각각 업로드하기 위해 먼저 <a href="https://github.com/Kludex/python-multipart" class="external-link" target="_blank">`python-multipart`</a>를 설치해야합니다.
+
+예 ) `pip install python-multipart`.
+
+///
## `File` 및 `Form` 업로드
어떤 파일들은 `bytes`로, 또 어떤 파일들은 `UploadFile`로 선언할 수 있습니다.
-!!! warning "경고"
- 다수의 `File`과 `Form` 매개변수를 한 *경로 작동*에 선언하는 것이 가능하지만, 요청의 본문이 `application/json`가 아닌 `multipart/form-data`로 인코딩 되기 때문에 JSON으로 받아야하는 `Body` 필드를 함께 선언할 수는 없습니다.
+/// warning | "경고"
+
+다수의 `File`과 `Form` 매개변수를 한 *경로 작동*에 선언하는 것이 가능하지만, 요청의 본문이 `application/json`가 아닌 `multipart/form-data`로 인코딩 되기 때문에 JSON으로 받아야하는 `Body` 필드를 함께 선언할 수는 없습니다.
+
+이는 **FastAPI**의 한계가 아니라, HTTP 프로토콜에 의한 것입니다.
- 이는 **FastAPI**의 한계가 아니라, HTTP 프로토콜에 의한 것입니다.
+///
## 요약
{!../../../docs_src/response_model/tutorial001.py!}
```
-!!! note "참고"
- `response_model`은 "데코레이터" 메소드(`get`, `post`, 등)의 매개변수입니다. 모든 매개변수들과 본문(body)처럼 *경로 작동 함수*가 아닙니다.
+/// note | "참고"
+
+`response_model`은 "데코레이터" 메소드(`get`, `post`, 등)의 매개변수입니다. 모든 매개변수들과 본문(body)처럼 *경로 작동 함수*가 아닙니다.
+
+///
Pydantic 모델 어트리뷰트를 선언한 것과 동일한 타입을 수신하므로 Pydantic 모델이 될 수 있지만, `List[Item]`과 같이 Pydantic 모델들의 `list`일 수도 있습니다.
* 해당 모델의 출력 데이터 제한. 이것이 얼마나 중요한지 아래에서 볼 것입니다.
-!!! note "기술 세부사항"
- 응답 모델은 함수의 타입 어노테이션 대신 이 매개변수로 선언하는데, 경로 함수가 실제 응답 모델을 반환하지 않고 `dict`, 데이터베이스 객체나 기타 다른 모델을 `response_model`을 사용하여 필드 제한과 직렬화를 수행하고 반환할 수 있기 때문입니다
+/// note | "기술 세부사항"
+
+응답 모델은 함수의 타입 어노테이션 대신 이 매개변수로 선언하는데, 경로 함수가 실제 응답 모델을 반환하지 않고 `dict`, 데이터베이스 객체나 기타 다른 모델을 `response_model`을 사용하여 필드 제한과 직렬화를 수행하고 반환할 수 있기 때문입니다
+
+///
## 동일한 입력 데이터 반환
그러나 동일한 모델을 다른 *경로 작동*에서 사용할 경우, 모든 클라이언트에게 사용자의 비밀번호를 발신할 수 있습니다.
-!!! danger "위험"
- 절대로 사용자의 평문 비밀번호를 저장하거나 응답으로 발신하지 마십시오.
+/// danger | "위험"
+
+절대로 사용자의 평문 비밀번호를 저장하거나 응답으로 발신하지 마십시오.
+
+///
## 출력 모델 추가
}
```
-!!! info "정보"
- FastAPI는 이를 위해 Pydantic 모델의 `.dict()`의 <a href="https://docs.pydantic.dev/latest/concepts/serialization/#modeldict" class="external-link" target="_blank"> `exclude_unset` 매개변수</a>를 사용합니다.
+/// info | "정보"
+
+FastAPI는 이를 위해 Pydantic 모델의 `.dict()`의 <a href="https://docs.pydantic.dev/latest/concepts/serialization/#modeldict" class="external-link" target="_blank"> `exclude_unset` 매개변수</a>를 사용합니다.
+
+///
-!!! info "정보"
- 아래 또한 사용할 수 있습니다:
+/// info | "정보"
- * `response_model_exclude_defaults=True`
- * `response_model_exclude_none=True`
+아래 또한 사용할 수 있습니다:
- <a href="https://docs.pydantic.dev/latest/concepts/serialization/#modeldict" class="external-link" target="_blank">Pydantic 문서</a>에서 `exclude_defaults` 및 `exclude_none`에 대해 설명한 대로 사용할 수 있습니다.
+* `response_model_exclude_defaults=True`
+* `response_model_exclude_none=True`
+
+<a href="https://docs.pydantic.dev/latest/concepts/serialization/#modeldict" class="external-link" target="_blank">Pydantic 문서</a>에서 `exclude_defaults` 및 `exclude_none`에 대해 설명한 대로 사용할 수 있습니다.
+
+///
#### 기본값이 있는 필드를 갖는 값의 데이터
따라서 JSON 스키마에 포함됩니다.
-!!! tip "팁"
- `None` 뿐만 아니라 다른 어떤 것도 기본값이 될 수 있습니다.
+/// tip | "팁"
+
+`None` 뿐만 아니라 다른 어떤 것도 기본값이 될 수 있습니다.
+
+리스트(`[]`), `float`인 `10.5` 등이 될 수 있습니다.
- 리스트(`[]`), `float`인 `10.5` 등이 될 수 있습니다.
+///
### `response_model_include` 및 `response_model_exclude`
Pydantic 모델이 하나만 있고 출력에서 일부 데이터를 제거하려는 경우 빠른 지름길로 사용할 수 있습니다.
-!!! tip "팁"
- 하지만 이러한 매개변수 대신 여러 클래스를 사용하여 위 아이디어를 사용하는 것을 추천합니다.
+/// tip | "팁"
- 이는 일부 어트리뷰트를 생략하기 위해 `response_model_include` 또는 `response_model_exclude`를 사용하더라도 앱의 OpenAPI(및 문서)가 생성한 JSON 스키마가 여전히 전체 모델에 대한 스키마이기 때문입니다.
+하지만 이러한 매개변수 대신 여러 클래스를 사용하여 위 아이디어를 사용하는 것을 추천합니다.
- 비슷하게 작동하는 `response_model_by_alias` 역시 마찬가지로 적용됩니다.
+이는 일부 어트리뷰트를 생략하기 위해 `response_model_include` 또는 `response_model_exclude`를 사용하더라도 앱의 OpenAPI(및 문서)가 생성한 JSON 스키마가 여전히 전체 모델에 대한 스키마이기 때문입니다.
+
+비슷하게 작동하는 `response_model_by_alias` 역시 마찬가지로 적용됩니다.
+
+///
```Python hl_lines="31 37"
{!../../../docs_src/response_model/tutorial005.py!}
```
-!!! tip "팁"
- 문법 `{"name", "description"}`은 두 값을 갖는 `set`을 만듭니다.
+/// tip | "팁"
+
+문법 `{"name", "description"}`은 두 값을 갖는 `set`을 만듭니다.
+
+이는 `set(["name", "description"])`과 동일합니다.
- 이는 `set(["name", "description"])`과 동일합니다.
+///
#### `set` 대신 `list` 사용하기
{!../../../docs_src/response_status_code/tutorial001.py!}
```
-!!! note "참고"
- `status_code` 는 "데코레이터" 메소드(`get`, `post` 등)의 매개변수입니다. 모든 매개변수들과 본문처럼 *경로 작동 함수*가 아닙니다.
+/// note | "참고"
+
+`status_code` 는 "데코레이터" 메소드(`get`, `post` 등)의 매개변수입니다. 모든 매개변수들과 본문처럼 *경로 작동 함수*가 아닙니다.
+
+///
`status_code` 매개변수는 HTTP 상태 코드를 숫자로 입력받습니다.
-!!! info "정보"
- `status_code` 는 파이썬의 `http.HTTPStatus` 와 같은 `IntEnum` 을 입력받을 수도 있습니다.
+/// info | "정보"
+
+`status_code` 는 파이썬의 `http.HTTPStatus` 와 같은 `IntEnum` 을 입력받을 수도 있습니다.
+
+///
`status_code` 매개변수는:
<img src="https://fastapi.tiangolo.com/img/tutorial/response-status-code/image01.png">
-!!! note "참고"
- 어떤 응답 코드들은 해당 응답에 본문이 없다는 것을 의미하기도 합니다 (다음 항목 참고).
+/// note | "참고"
+
+어떤 응답 코드들은 해당 응답에 본문이 없다는 것을 의미하기도 합니다 (다음 항목 참고).
+
+이에 따라 FastAPI는 응답 본문이 없음을 명시하는 OpenAPI를 생성합니다.
- 이에 따라 FastAPI는 응답 본문이 없음을 명시하는 OpenAPI를 생성합니다.
+///
## HTTP 상태 코드에 대하여
-!!! note "참고"
- 만약 HTTP 상태 코드에 대하여 이미 알고있다면, 다음 항목으로 넘어가십시오.
+/// note | "참고"
+
+만약 HTTP 상태 코드에 대하여 이미 알고있다면, 다음 항목으로 넘어가십시오.
+
+///
HTTP는 세자리의 숫자 상태 코드를 응답의 일부로 전송합니다.
* 일반적인 클라이언트 오류의 경우 `400` 을 사용할 수 있습니다.
* `5xx` 상태 코드는 서버 오류에 사용됩니다. 이것들을 직접 사용할 일은 거의 없습니다. 응용 프로그램 코드나 서버의 일부에서 문제가 발생하면 자동으로 이들 상태 코드 중 하나를 반환합니다.
-!!! tip "팁"
- 각각의 상태 코드와 이들이 의미하는 내용에 대해 더 알고싶다면 <a href="https://developer.mozilla.org/en-US/docs/Web/HTTP/Status" class="external-link" target="_blank"><abbr title="Mozilla Developer Network">MDN</abbr> HTTP 상태 코드에 관한 문서</a> 를 확인하십시오.
+/// tip | "팁"
+
+각각의 상태 코드와 이들이 의미하는 내용에 대해 더 알고싶다면 <a href="https://developer.mozilla.org/en-US/docs/Web/HTTP/Status" class="external-link" target="_blank"><abbr title="Mozilla Developer Network">MDN</abbr> HTTP 상태 코드에 관한 문서</a> 를 확인하십시오.
+
+///
## 이름을 기억하는 쉬운 방법
<img src="https://fastapi.tiangolo.com/img/tutorial/response-status-code/image02.png">
-!!! note "기술적 세부사항"
- `from starlette import status` 역시 사용할 수 있습니다.
+/// note | "기술적 세부사항"
+
+`from starlette import status` 역시 사용할 수 있습니다.
+
+**FastAPI**는 개발자인 여러분의 편의를 위해 `fastapi.status` 와 동일한 `starlette.status` 도 제공합니다. 하지만 이것은 Starlette로부터 직접 제공됩니다.
- **FastAPI**는 개발자인 여러분의 편의를 위해 `fastapi.status` 와 동일한 `starlette.status` 도 제공합니다. 하지만 이것은 Starlette로부터 직접 제공됩니다.
+///
## 기본값 변경
생성된 JSON 스키마에 추가될 Pydantic 모델을 위한 `examples`을 선언할 수 있습니다.
-=== "Python 3.10+ Pydantic v2"
+//// tab | Python 3.10+ Pydantic v2
- ```Python hl_lines="13-24"
- {!> ../../../docs_src/schema_extra_example/tutorial001_py310.py!}
- ```
+```Python hl_lines="13-24"
+{!> ../../../docs_src/schema_extra_example/tutorial001_py310.py!}
+```
-=== "Python 3.10+ Pydantic v1"
+////
- ```Python hl_lines="13-23"
- {!> ../../../docs_src/schema_extra_example/tutorial001_py310_pv1.py!}
- ```
+//// tab | Python 3.10+ Pydantic v1
-=== "Python 3.8+ Pydantic v2"
+```Python hl_lines="13-23"
+{!> ../../../docs_src/schema_extra_example/tutorial001_py310_pv1.py!}
+```
- ```Python hl_lines="15-26"
- {!> ../../../docs_src/schema_extra_example/tutorial001.py!}
- ```
+////
-=== "Python 3.8+ Pydantic v1"
+//// tab | Python 3.8+ Pydantic v2
- ```Python hl_lines="15-25"
- {!> ../../../docs_src/schema_extra_example/tutorial001_pv1.py!}
- ```
+```Python hl_lines="15-26"
+{!> ../../../docs_src/schema_extra_example/tutorial001.py!}
+```
+
+////
+
+//// tab | Python 3.8+ Pydantic v1
+
+```Python hl_lines="15-25"
+{!> ../../../docs_src/schema_extra_example/tutorial001_pv1.py!}
+```
+
+////
추가 정보는 있는 그대로 해당 모델의 **JSON 스키마** 결과에 추가되고, API 문서에서 사용합니다.
-=== "Pydantic v2"
+//// tab | Pydantic v2
+
+Pydantic 버전 2에서 <a href="https://docs.pydantic.dev/latest/usage/model_config/" class="external-link" target="_blank">Pydantic 공식 문서: Model Config</a>에 나와 있는 것처럼 `dict`를 받는 `model_config` 어트리뷰트를 사용할 것입니다.
+
+`"json_schema_extra"`를 생성된 JSON 스키마에서 보여주고 싶은 별도의 데이터와 `examples`를 포함하는 `dict`으로 설정할 수 있습니다.
- Pydantic 버전 2에서 <a href="https://docs.pydantic.dev/latest/usage/model_config/" class="external-link" target="_blank">Pydantic 공식 문서: Model Config</a>에 나와 있는 것처럼 `dict`를 받는 `model_config` 어트리뷰트를 사용할 것입니다.
+////
- `"json_schema_extra"`를 생성된 JSON 스키마에서 보여주고 싶은 별도의 데이터와 `examples`를 포함하는 `dict`으로 설정할 수 있습니다.
+//// tab | Pydantic v1
-=== "Pydantic v1"
+Pydantic v1에서 <a href="https://docs.pydantic.dev/1.10/usage/schema/#schema-customization" class="external-link" target="_blank">Pydantic 공식 문서: Schema customization</a>에서 설명하는 것처럼, 내부 클래스인 `Config`와 `schema_extra`를 사용할 것입니다.
- Pydantic v1에서 <a href="https://docs.pydantic.dev/1.10/usage/schema/#schema-customization" class="external-link" target="_blank">Pydantic 공식 문서: Schema customization</a>에서 설명하는 것처럼, 내부 클래스인 `Config`와 `schema_extra`를 사용할 것입니다.
+`schema_extra`를 생성된 JSON 스키마에서 보여주고 싶은 별도의 데이터와 `examples`를 포함하는 `dict`으로 설정할 수 있습니다.
- `schema_extra`를 생성된 JSON 스키마에서 보여주고 싶은 별도의 데이터와 `examples`를 포함하는 `dict`으로 설정할 수 있습니다.
+////
-!!! tip "팁"
- JSON 스키마를 확장하고 여러분의 별도의 자체 데이터를 추가하기 위해 같은 기술을 사용할 수 있습니다.
+/// tip | "팁"
- 예를 들면, 프론트엔드 사용자 인터페이스에 메타데이터를 추가하는 등에 사용할 수 있습니다.
+JSON 스키마를 확장하고 여러분의 별도의 자체 데이터를 추가하기 위해 같은 기술을 사용할 수 있습니다.
-!!! info "정보"
- (FastAPI 0.99.0부터 쓰이기 시작한) OpenAPI 3.1.0은 **JSON 스키마** 표준의 일부인 `examples`에 대한 지원을 추가했습니다.
+예를 들면, 프론트엔드 사용자 인터페이스에 메타데이터를 추가하는 등에 사용할 수 있습니다.
- 그 전에는, 하나의 예제만 가능한 `example` 키워드만 지원했습니다. 이는 아직 OpenAPI 3.1.0에서 지원하지만, 지원이 종료될 것이며 JSON 스키마 표준에 포함되지 않습니다. 그렇기에 `example`을 `examples`으로 이전하는 것을 추천합니다. 🤓
+///
- 이 문서 끝에 더 많은 읽을거리가 있습니다.
+/// info | "정보"
+
+(FastAPI 0.99.0부터 쓰이기 시작한) OpenAPI 3.1.0은 **JSON 스키마** 표준의 일부인 `examples`에 대한 지원을 추가했습니다.
+
+그 전에는, 하나의 예제만 가능한 `example` 키워드만 지원했습니다. 이는 아직 OpenAPI 3.1.0에서 지원하지만, 지원이 종료될 것이며 JSON 스키마 표준에 포함되지 않습니다. 그렇기에 `example`을 `examples`으로 이전하는 것을 추천합니다. 🤓
+
+이 문서 끝에 더 많은 읽을거리가 있습니다.
+
+///
## `Field` 추가 인자
Pydantic 모델과 같이 `Field()`를 사용할 때 추가적인 `examples`를 선언할 수 있습니다:
-=== "Python 3.10+"
+//// tab | Python 3.10+
+
+```Python hl_lines="2 8-11"
+{!> ../../../docs_src/schema_extra_example/tutorial002_py310.py!}
+```
+
+////
- ```Python hl_lines="2 8-11"
- {!> ../../../docs_src/schema_extra_example/tutorial002_py310.py!}
- ```
+//// tab | Python 3.8+
-=== "Python 3.8+"
+```Python hl_lines="4 10-13"
+{!> ../../../docs_src/schema_extra_example/tutorial002.py!}
+```
- ```Python hl_lines="4 10-13"
- {!> ../../../docs_src/schema_extra_example/tutorial002.py!}
- ```
+////
## JSON Schema에서의 `examples` - OpenAPI
여기, `Body()`에 예상되는 예제 데이터 하나를 포함한 `examples`를 넘겼습니다:
-=== "Python 3.10+"
+//// tab | Python 3.10+
- ```Python hl_lines="22-29"
- {!> ../../../docs_src/schema_extra_example/tutorial003_an_py310.py!}
- ```
+```Python hl_lines="22-29"
+{!> ../../../docs_src/schema_extra_example/tutorial003_an_py310.py!}
+```
-=== "Python 3.9+"
+////
- ```Python hl_lines="22-29"
- {!> ../../../docs_src/schema_extra_example/tutorial003_an_py39.py!}
- ```
+//// tab | Python 3.9+
-=== "Python 3.8+"
+```Python hl_lines="22-29"
+{!> ../../../docs_src/schema_extra_example/tutorial003_an_py39.py!}
+```
- ```Python hl_lines="23-30"
- {!> ../../../docs_src/schema_extra_example/tutorial003_an.py!}
- ```
+////
-=== "Python 3.10+ Annotated가 없는 경우"
+//// tab | Python 3.8+
- !!! tip "팁"
- 가능하다면 `Annotated`가 달린 버전을 권장합니다.
+```Python hl_lines="23-30"
+{!> ../../../docs_src/schema_extra_example/tutorial003_an.py!}
+```
- ```Python hl_lines="18-25"
- {!> ../../../docs_src/schema_extra_example/tutorial003_py310.py!}
- ```
+////
-=== "Python 3.8+ Annotated가 없는 경우"
+//// tab | Python 3.10+ Annotated가 없는 경우
- !!! tip "팁"
- 가능하다면 `Annotated`가 달린 버전을 권장합니다.
+/// tip | "팁"
- ```Python hl_lines="20-27"
- {!> ../../../docs_src/schema_extra_example/tutorial003.py!}
- ```
+가능하다면 `Annotated`가 달린 버전을 권장합니다.
+
+///
+
+```Python hl_lines="18-25"
+{!> ../../../docs_src/schema_extra_example/tutorial003_py310.py!}
+```
+
+////
+
+//// tab | Python 3.8+ Annotated가 없는 경우
+
+/// tip | "팁"
+
+가능하다면 `Annotated`가 달린 버전을 권장합니다.
+
+///
+
+```Python hl_lines="20-27"
+{!> ../../../docs_src/schema_extra_example/tutorial003.py!}
+```
+
+////
### 문서 UI 예시
물론 여러 `examples`를 넘길 수 있습니다:
-=== "Python 3.10+"
+//// tab | Python 3.10+
+
+```Python hl_lines="23-38"
+{!> ../../../docs_src/schema_extra_example/tutorial004_an_py310.py!}
+```
+
+////
+
+//// tab | Python 3.9+
- ```Python hl_lines="23-38"
- {!> ../../../docs_src/schema_extra_example/tutorial004_an_py310.py!}
- ```
+```Python hl_lines="23-38"
+{!> ../../../docs_src/schema_extra_example/tutorial004_an_py39.py!}
+```
-=== "Python 3.9+"
+////
- ```Python hl_lines="23-38"
- {!> ../../../docs_src/schema_extra_example/tutorial004_an_py39.py!}
- ```
+//// tab | Python 3.8+
-=== "Python 3.8+"
+```Python hl_lines="24-39"
+{!> ../../../docs_src/schema_extra_example/tutorial004_an.py!}
+```
- ```Python hl_lines="24-39"
- {!> ../../../docs_src/schema_extra_example/tutorial004_an.py!}
- ```
+////
-=== "Python 3.10+ Annotated가 없는 경우"
+//// tab | Python 3.10+ Annotated가 없는 경우
- !!! tip "팁"
- 가능하다면 `Annotated`가 달린 버전을 권장합니다.
+/// tip | "팁"
- ```Python hl_lines="19-34"
- {!> ../../../docs_src/schema_extra_example/tutorial004_py310.py!}
- ```
+가능하다면 `Annotated`가 달린 버전을 권장합니다.
-=== "Python 3.8+ Annotated가 없는 경우"
+///
- !!! tip "팁"
- 가능하다면 `Annotated`가 달린 버전을 권장합니다.
+```Python hl_lines="19-34"
+{!> ../../../docs_src/schema_extra_example/tutorial004_py310.py!}
+```
- ```Python hl_lines="21-36"
- {!> ../../../docs_src/schema_extra_example/tutorial004.py!}
- ```
+////
+
+//// tab | Python 3.8+ Annotated가 없는 경우
+
+/// tip | "팁"
+
+가능하다면 `Annotated`가 달린 버전을 권장합니다.
+
+///
+
+```Python hl_lines="21-36"
+{!> ../../../docs_src/schema_extra_example/tutorial004.py!}
+```
+
+////
이와 같이 하면 이 예제는 그 본문 데이터를 위한 내부 **JSON 스키마**의 일부가 될 것입니다.
이를 다음과 같이 사용할 수 있습니다:
-=== "Python 3.10+"
+//// tab | Python 3.10+
+
+```Python hl_lines="23-49"
+{!> ../../../docs_src/schema_extra_example/tutorial005_an_py310.py!}
+```
+
+////
+
+//// tab | Python 3.9+
+
+```Python hl_lines="23-49"
+{!> ../../../docs_src/schema_extra_example/tutorial005_an_py39.py!}
+```
+
+////
+
+//// tab | Python 3.8+
- ```Python hl_lines="23-49"
- {!> ../../../docs_src/schema_extra_example/tutorial005_an_py310.py!}
- ```
+```Python hl_lines="24-50"
+{!> ../../../docs_src/schema_extra_example/tutorial005_an.py!}
+```
-=== "Python 3.9+"
+////
- ```Python hl_lines="23-49"
- {!> ../../../docs_src/schema_extra_example/tutorial005_an_py39.py!}
- ```
+//// tab | Python 3.10+ Annotated가 없는 경우
-=== "Python 3.8+"
+/// tip | "팁"
- ```Python hl_lines="24-50"
- {!> ../../../docs_src/schema_extra_example/tutorial005_an.py!}
- ```
+가능하다면 `Annotated`가 달린 버전을 권장합니다.
-=== "Python 3.10+ Annotated가 없는 경우"
+///
- !!! tip "팁"
- 가능하다면 `Annotated`가 달린 버전을 권장합니다.
+```Python hl_lines="19-45"
+{!> ../../../docs_src/schema_extra_example/tutorial005_py310.py!}
+```
- ```Python hl_lines="19-45"
- {!> ../../../docs_src/schema_extra_example/tutorial005_py310.py!}
- ```
+////
-=== "Python 3.8+ Annotated가 없는 경우"
+//// tab | Python 3.8+ Annotated가 없는 경우
- !!! tip "팁"
- 가능하다면 `Annotated`가 달린 버전을 권장합니다.
+/// tip | "팁"
- ```Python hl_lines="21-47"
- {!> ../../../docs_src/schema_extra_example/tutorial005.py!}
- ```
+가능하다면 `Annotated`가 달린 버전을 권장합니다.
+
+///
+
+```Python hl_lines="21-47"
+{!> ../../../docs_src/schema_extra_example/tutorial005.py!}
+```
+
+////
### 문서 UI에서의 OpenAPI 예시
## 기술적 세부 사항
-!!! tip "팁"
- 이미 **FastAPI**의 **0.99.0 혹은 그 이상** 버전을 사용하고 있다면, 이 세부 사항을 **스킵**해도 상관 없을 것입니다.
+/// tip | "팁"
+
+이미 **FastAPI**의 **0.99.0 혹은 그 이상** 버전을 사용하고 있다면, 이 세부 사항을 **스킵**해도 상관 없을 것입니다.
+
+세부 사항은 OpenAPI 3.1.0이 사용가능하기 전, 예전 버전과 더 관련있습니다.
+
+간략한 OpenAPI와 JSON 스키마 **역사 강의**로 생각할 수 있습니다. 🤓
- 세부 사항은 OpenAPI 3.1.0이 사용가능하기 전, 예전 버전과 더 관련있습니다.
+///
- 간략한 OpenAPI와 JSON 스키마 **역사 강의**로 생각할 수 있습니다. 🤓
+/// warning | "경고"
-!!! warning "경고"
- 표준 **JSON 스키마**와 **OpenAPI**에 대한 아주 기술적인 세부사항입니다.
+표준 **JSON 스키마**와 **OpenAPI**에 대한 아주 기술적인 세부사항입니다.
- 만약 위의 생각이 작동한다면, 그것으로 충분하며 이 세부 사항은 필요없을 것이니, 마음 편하게 스킵하셔도 됩니다.
+만약 위의 생각이 작동한다면, 그것으로 충분하며 이 세부 사항은 필요없을 것이니, 마음 편하게 스킵하셔도 됩니다.
+
+///
OpenAPI 3.1.0 전에 OpenAPI는 오래된 **JSON 스키마**의 수정된 버전을 사용했습니다.
* `File()`
* `Form()`
-!!! info "정보"
- 이 예전 OpenAPI-특화 `examples` 매개변수는 이제 FastAPI `0.103.0`부터 `openapi_examples`입니다.
+/// info | "정보"
+
+이 예전 OpenAPI-특화 `examples` 매개변수는 이제 FastAPI `0.103.0`부터 `openapi_examples`입니다.
+
+///
### JSON 스키마의 `examples` 필드
JSON 스키마의 새로운 `examples` 필드는 예제 속 **단순한 `list`**이며, (위에서 상술한 것처럼) OpenAPI의 다른 곳에 존재하는 dict으로 된 추가적인 메타데이터가 아닙니다.
-!!! info "정보"
- 더 쉽고 새로운 JSON 스키마와의 통합과 함께 OpenAPI 3.1.0가 배포되었지만, 잠시동안 자동 문서 생성을 제공하는 도구인 Swagger UI는 OpenAPI 3.1.0을 지원하지 않았습니다 (5.0.0 버전부터 지원합니다 🎉).
+/// info | "정보"
+
+더 쉽고 새로운 JSON 스키마와의 통합과 함께 OpenAPI 3.1.0가 배포되었지만, 잠시동안 자동 문서 생성을 제공하는 도구인 Swagger UI는 OpenAPI 3.1.0을 지원하지 않았습니다 (5.0.0 버전부터 지원합니다 🎉).
+
+이로인해, FastAPI 0.99.0 이전 버전은 아직 OpenAPI 3.1.0 보다 낮은 버전을 사용했습니다.
- 이로인해, FastAPI 0.99.0 이전 버전은 아직 OpenAPI 3.1.0 보다 낮은 버전을 사용했습니다.
+///
### Pydantic과 FastAPI `examples`
Pydantic을 사용하여 본문을 선언하는 것과 같은 방식으로 다른 곳에서 사용할 수 있습니다.
-=== "파이썬 3.7 이상"
+//// tab | 파이썬 3.7 이상
- ```Python hl_lines="5 12-16"
- {!> ../../../docs_src/security/tutorial002.py!}
- ```
+```Python hl_lines="5 12-16"
+{!> ../../../docs_src/security/tutorial002.py!}
+```
+
+////
+
+//// tab | 파이썬 3.10 이상
-=== "파이썬 3.10 이상"
+```Python hl_lines="3 10-14"
+{!> ../../../docs_src/security/tutorial002_py310.py!}
+```
- ```Python hl_lines="3 10-14"
- {!> ../../../docs_src/security/tutorial002_py310.py!}
- ```
+////
## `get_current_user` 의존성 생성하기
이전에 *경로 작동*에서 직접 수행했던 것과 동일하게 새 종속성 `get_current_user`는 하위 종속성 `oauth2_scheme`에서 `str`로 `token`을 수신합니다.
-=== "파이썬 3.7 이상"
+//// tab | 파이썬 3.7 이상
+
+```Python hl_lines="25"
+{!> ../../../docs_src/security/tutorial002.py!}
+```
+
+////
- ```Python hl_lines="25"
- {!> ../../../docs_src/security/tutorial002.py!}
- ```
+//// tab | 파이썬 3.10 이상
-=== "파이썬 3.10 이상"
+```Python hl_lines="23"
+{!> ../../../docs_src/security/tutorial002_py310.py!}
+```
- ```Python hl_lines="23"
- {!> ../../../docs_src/security/tutorial002_py310.py!}
- ```
+////
## 유저 가져오기
`get_current_user`는 토큰을 `str`로 취하고 Pydantic `User` 모델을 반환하는 우리가 만든 (가짜) 유틸리티 함수를 사용합니다.
-=== "파이썬 3.7 이상"
+//// tab | 파이썬 3.7 이상
+
+```Python hl_lines="19-22 26-27"
+{!> ../../../docs_src/security/tutorial002.py!}
+```
+
+////
- ```Python hl_lines="19-22 26-27"
- {!> ../../../docs_src/security/tutorial002.py!}
- ```
+//// tab | 파이썬 3.10 이상
-=== "파이썬 3.10 이상"
+```Python hl_lines="17-20 24-25"
+{!> ../../../docs_src/security/tutorial002_py310.py!}
+```
- ```Python hl_lines="17-20 24-25"
- {!> ../../../docs_src/security/tutorial002_py310.py!}
- ```
+////
## 현재 유저 주입하기
이제 *경로 작동*에서 `get_current_user`와 동일한 `Depends`를 사용할 수 있습니다.
-=== "파이썬 3.7 이상"
+//// tab | 파이썬 3.7 이상
- ```Python hl_lines="31"
- {!> ../../../docs_src/security/tutorial002.py!}
- ```
+```Python hl_lines="31"
+{!> ../../../docs_src/security/tutorial002.py!}
+```
+
+////
+
+//// tab | 파이썬 3.10 이상
-=== "파이썬 3.10 이상"
+```Python hl_lines="29"
+{!> ../../../docs_src/security/tutorial002_py310.py!}
+```
- ```Python hl_lines="29"
- {!> ../../../docs_src/security/tutorial002_py310.py!}
- ```
+////
Pydantic 모델인 `User`로 `current_user`의 타입을 선언하는 것을 알아야 합니다.
이것은 모든 완료 및 타입 검사를 통해 함수 내부에서 우리를 도울 것입니다.
-!!! tip "팁"
- 요청 본문도 Pydantic 모델로 선언된다는 것을 기억할 것입니다.
+/// tip | "팁"
+
+요청 본문도 Pydantic 모델로 선언된다는 것을 기억할 것입니다.
+
+여기서 **FastAPI**는 `Depends`를 사용하고 있기 때문에 혼동되지 않습니다.
- 여기서 **FastAPI**는 `Depends`를 사용하고 있기 때문에 혼동되지 않습니다.
+///
-!!! check "확인"
- 이 의존성 시스템이 설계된 방식은 모두 `User` 모델을 반환하는 다양한 의존성(다른 "의존적인")을 가질 수 있도록 합니다.
+/// check | "확인"
- 해당 타입의 데이터를 반환할 수 있는 의존성이 하나만 있는 것으로 제한되지 않습니다.
+이 의존성 시스템이 설계된 방식은 모두 `User` 모델을 반환하는 다양한 의존성(다른 "의존적인")을 가질 수 있도록 합니다.
+
+해당 타입의 데이터를 반환할 수 있는 의존성이 하나만 있는 것으로 제한되지 않습니다.
+
+///
## 다른 모델
그리고 이 수천 개의 *경로 작동*은 모두 3줄 정도로 줄일 수 있습니다.
-=== "파이썬 3.7 이상"
+//// tab | 파이썬 3.7 이상
+
+```Python hl_lines="30-32"
+{!> ../../../docs_src/security/tutorial002.py!}
+```
+
+////
- ```Python hl_lines="30-32"
- {!> ../../../docs_src/security/tutorial002.py!}
- ```
+//// tab | 파이썬 3.10 이상
-=== "파이썬 3.10 이상"
+```Python hl_lines="28-30"
+{!> ../../../docs_src/security/tutorial002_py310.py!}
+```
- ```Python hl_lines="28-30"
- {!> ../../../docs_src/security/tutorial002_py310.py!}
- ```
+////
## 요약
* `instagram_basic`은 페이스북/인스타그램에서 사용합니다.
* `https://www.googleapis.com/auth/drive`는 Google에서 사용합니다.
-!!! 정보
- OAuth2에서 "범위"는 필요한 특정 권한을 선언하는 문자열입니다.
+/// 정보
- `:`과 같은 다른 문자가 있는지 또는 URL인지는 중요하지 않습니다.
+OAuth2에서 "범위"는 필요한 특정 권한을 선언하는 문자열입니다.
- 이러한 세부 사항은 구현에 따라 다릅니다.
+`:`과 같은 다른 문자가 있는지 또는 URL인지는 중요하지 않습니다.
- OAuth2의 경우 문자열일 뿐입니다.
+이러한 세부 사항은 구현에 따라 다릅니다.
+
+OAuth2의 경우 문자열일 뿐입니다.
+
+///
## `username`과 `password`를 가져오는 코드
먼저 `OAuth2PasswordRequestForm`을 가져와 `/token`에 대한 *경로 작동*에서 `Depends`의 의존성으로 사용합니다.
-=== "파이썬 3.7 이상"
+//// tab | 파이썬 3.7 이상
- ```Python hl_lines="4 76"
- {!> ../../../docs_src/security/tutorial003.py!}
- ```
+```Python hl_lines="4 76"
+{!> ../../../docs_src/security/tutorial003.py!}
+```
-=== "파이썬 3.10 이상"
+////
- ```Python hl_lines="2 74"
- {!> ../../../docs_src/security/tutorial003_py310.py!}
- ```
+//// tab | 파이썬 3.10 이상
+
+```Python hl_lines="2 74"
+{!> ../../../docs_src/security/tutorial003_py310.py!}
+```
+
+////
`OAuth2PasswordRequestForm`은 다음을 사용하여 폼 본문을 선언하는 클래스 의존성입니다:
* `scope`는 선택적인 필드로 공백으로 구분된 문자열로 구성된 큰 문자열입니다.
* `grant_type`(선택적으로 사용).
-!!! 팁
- OAuth2 사양은 실제로 `password`라는 고정 값이 있는 `grant_type` 필드를 *요구*하지만 `OAuth2PasswordRequestForm`은 이를 강요하지 않습니다.
+/// 팁
+
+OAuth2 사양은 실제로 `password`라는 고정 값이 있는 `grant_type` 필드를 *요구*하지만 `OAuth2PasswordRequestForm`은 이를 강요하지 않습니다.
- 사용해야 한다면 `OAuth2PasswordRequestForm` 대신 `OAuth2PasswordRequestFormStrict`를 사용하면 됩니다.
+사용해야 한다면 `OAuth2PasswordRequestForm` 대신 `OAuth2PasswordRequestFormStrict`를 사용하면 됩니다.
+
+///
* `client_id`(선택적으로 사용) (예제에서는 필요하지 않습니다).
* `client_secret`(선택적으로 사용) (예제에서는 필요하지 않습니다).
-!!! 정보
- `OAuth2PasswordRequestForm`은 `OAuth2PasswordBearer`와 같이 **FastAPI**에 대한 특수 클래스가 아닙니다.
+/// 정보
+
+`OAuth2PasswordRequestForm`은 `OAuth2PasswordBearer`와 같이 **FastAPI**에 대한 특수 클래스가 아닙니다.
- `OAuth2PasswordBearer`는 **FastAPI**가 보안 체계임을 알도록 합니다. 그래서 OpenAPI에 그렇게 추가됩니다.
+`OAuth2PasswordBearer`는 **FastAPI**가 보안 체계임을 알도록 합니다. 그래서 OpenAPI에 그렇게 추가됩니다.
- 그러나 `OAuth2PasswordRequestForm`은 직접 작성하거나 `Form` 매개변수를 직접 선언할 수 있는 클래스 의존성일 뿐입니다.
+그러나 `OAuth2PasswordRequestForm`은 직접 작성하거나 `Form` 매개변수를 직접 선언할 수 있는 클래스 의존성일 뿐입니다.
- 그러나 일반적인 사용 사례이므로 더 쉽게 하기 위해 **FastAPI**에서 직접 제공합니다.
+그러나 일반적인 사용 사례이므로 더 쉽게 하기 위해 **FastAPI**에서 직접 제공합니다.
+
+///
### 폼 데이터 사용하기
-!!! 팁
- 종속성 클래스 `OAuth2PasswordRequestForm`의 인스턴스에는 공백으로 구분된 긴 문자열이 있는 `scope` 속성이 없고 대신 전송된 각 범위에 대한 실제 문자열 목록이 있는 `scopes` 속성이 있습니다.
+/// 팁
+
+종속성 클래스 `OAuth2PasswordRequestForm`의 인스턴스에는 공백으로 구분된 긴 문자열이 있는 `scope` 속성이 없고 대신 전송된 각 범위에 대한 실제 문자열 목록이 있는 `scopes` 속성이 있습니다.
+
+이 예제에서는 `scopes`를 사용하지 않지만 필요한 경우, 기능이 있습니다.
- 이 예제에서는 `scopes`를 사용하지 않지만 필요한 경우, 기능이 있습니다.
+///
이제 폼 필드의 `username`을 사용하여 (가짜) 데이터베이스에서 유저 데이터를 가져옵니다.
오류의 경우 `HTTPException` 예외를 사용합니다:
-=== "파이썬 3.7 이상"
+//// tab | 파이썬 3.7 이상
- ```Python hl_lines="3 77-79"
- {!> ../../../docs_src/security/tutorial003.py!}
- ```
+```Python hl_lines="3 77-79"
+{!> ../../../docs_src/security/tutorial003.py!}
+```
-=== "파이썬 3.10 이상"
+////
- ```Python hl_lines="1 75-77"
- {!> ../../../docs_src/security/tutorial003_py310.py!}
- ```
+//// tab | 파이썬 3.10 이상
+
+```Python hl_lines="1 75-77"
+{!> ../../../docs_src/security/tutorial003_py310.py!}
+```
+
+////
### 패스워드 확인하기
따라서 해커는 다른 시스템에서 동일한 암호를 사용하려고 시도할 수 없습니다(많은 사용자가 모든 곳에서 동일한 암호를 사용하므로 이는 위험할 수 있습니다).
-=== "P파이썬 3.7 이상"
+//// tab | P파이썬 3.7 이상
+
+```Python hl_lines="80-83"
+{!> ../../../docs_src/security/tutorial003.py!}
+```
+
+////
- ```Python hl_lines="80-83"
- {!> ../../../docs_src/security/tutorial003.py!}
- ```
+//// tab | 파이썬 3.10 이상
-=== "파이썬 3.10 이상"
+```Python hl_lines="78-81"
+{!> ../../../docs_src/security/tutorial003_py310.py!}
+```
- ```Python hl_lines="78-81"
- {!> ../../../docs_src/security/tutorial003_py310.py!}
- ```
+////
#### `**user_dict`에 대해
)
```
-!!! 정보
- `**user_dict`에 대한 자세한 설명은 [**추가 모델** 문서](../extra-models.md#about-user_indict){.internal-link target=_blank}를 다시 읽어봅시다.
+/// 정보
+
+`**user_dict`에 대한 자세한 설명은 [**추가 모델** 문서](../extra-models.md#about-user_indict){.internal-link target=_blank}를 다시 읽어봅시다.
+
+///
## 토큰 반환하기
이 간단한 예제에서는 완전히 안전하지 않고, 동일한 `username`을 토큰으로 반환합니다.
-!!! 팁
- 다음 장에서는 패스워드 해싱 및 <abbr title="JSON Web Tokens">JWT</abbr> 토큰을 사용하여 실제 보안 구현을 볼 수 있습니다.
+/// 팁
+
+다음 장에서는 패스워드 해싱 및 <abbr title="JSON Web Tokens">JWT</abbr> 토큰을 사용하여 실제 보안 구현을 볼 수 있습니다.
+
+하지만 지금은 필요한 세부 정보에 집중하겠습니다.
+
+///
+
+//// tab | 파이썬 3.7 이상
+
+```Python hl_lines="85"
+{!> ../../../docs_src/security/tutorial003.py!}
+```
+
+////
- 하지만 지금은 필요한 세부 정보에 집중하겠습니다.
+//// tab | 파이썬 3.10 이상
-=== "파이썬 3.7 이상"
+```Python hl_lines="83"
+{!> ../../../docs_src/security/tutorial003_py310.py!}
+```
- ```Python hl_lines="85"
- {!> ../../../docs_src/security/tutorial003.py!}
- ```
+////
-=== "파이썬 3.10 이상"
+/// 팁
- ```Python hl_lines="83"
- {!> ../../../docs_src/security/tutorial003_py310.py!}
- ```
+사양에 따라 이 예제와 동일하게 `access_token` 및 `token_type`이 포함된 JSON을 반환해야 합니다.
-!!! 팁
- 사양에 따라 이 예제와 동일하게 `access_token` 및 `token_type`이 포함된 JSON을 반환해야 합니다.
+이는 코드에서 직접 수행해야 하며 해당 JSON 키를 사용해야 합니다.
- 이는 코드에서 직접 수행해야 하며 해당 JSON 키를 사용해야 합니다.
+사양을 준수하기 위해 스스로 올바르게 수행하기 위해 거의 유일하게 기억해야 하는 것입니다.
- 사양을 준수하기 위해 스스로 올바르게 수행하기 위해 거의 유일하게 기억해야 하는 것입니다.
+나머지는 **FastAPI**가 처리합니다.
- 나머지는 **FastAPI**가 처리합니다.
+///
## 의존성 업데이트하기
따라서 엔드포인트에서는 사용자가 존재하고 올바르게 인증되었으며 활성 상태인 경우에만 사용자를 얻습니다:
-=== "파이썬 3.7 이상"
+//// tab | 파이썬 3.7 이상
+
+```Python hl_lines="58-66 69-72 90"
+{!> ../../../docs_src/security/tutorial003.py!}
+```
+
+////
+
+//// tab | 파이썬 3.10 이상
+
+```Python hl_lines="55-64 67-70 88"
+{!> ../../../docs_src/security/tutorial003_py310.py!}
+```
- ```Python hl_lines="58-66 69-72 90"
- {!> ../../../docs_src/security/tutorial003.py!}
- ```
+////
-=== "파이썬 3.10 이상"
+/// 정보
- ```Python hl_lines="55-64 67-70 88"
- {!> ../../../docs_src/security/tutorial003_py310.py!}
- ```
+여기서 반환하는 값이 `Bearer`인 추가 헤더 `WWW-Authenticate`도 사양의 일부입니다.
-!!! 정보
- 여기서 반환하는 값이 `Bearer`인 추가 헤더 `WWW-Authenticate`도 사양의 일부입니다.
+모든 HTTP(오류) 상태 코드 401 "UNAUTHORIZED"는 `WWW-Authenticate` 헤더도 반환해야 합니다.
- 모든 HTTP(오류) 상태 코드 401 "UNAUTHORIZED"는 `WWW-Authenticate` 헤더도 반환해야 합니다.
+베어러 토큰의 경우(지금의 경우) 해당 헤더의 값은 `Bearer`여야 합니다.
- 베어러 토큰의 경우(지금의 경우) 해당 헤더의 값은 `Bearer`여야 합니다.
+실제로 추가 헤더를 건너뛸 수 있으며 여전히 작동합니다.
- ì\8b¤ì \9cë¡\9c ì¶\94ê°\80 í\97¤ë\8d\94를 ê±´ë\84\88ë\9b¸ ì\88\98 ì\9e\88ì\9c¼ë©° ì\97¬ì \84í\9e\88 ì\9e\91ë\8f\99í\95©ë\8b\88ë\8b¤.
+ê·¸ë\9f¬ë\82\98 ì\97¬ê¸°ì\97\90ì\84\9cë\8a\94 ì\82¬ì\96\91ì\9d\84 ì¤\80ì\88\98í\95\98ë\8f\84ë¡\9d ì \9cê³µë\90©ë\8b\88ë\8b¤.
- 그러나 여기에서는 사양을 준수하도록 제공됩니다.
+또한 이를 예상하고 (현재 또는 미래에) 사용하는 도구가 있을 수 있으며, 현재 또는 미래에 자신 혹은 자신의 유저들에게 유용할 것입니다.
- 또한 이를 예상하고 (현재 또는 미래에) 사용하는 도구가 있을 수 있으며, 현재 또는 미래에 자신 혹은 자신의 유저들에게 유용할 것입니다.
+그것이 표준의 이점입니다 ...
- 그것이 표준의 이점입니다 ...
+///
## 확인하기
{!../../../docs_src/static_files/tutorial001.py!}
```
-!!! note "기술적 세부사항"
- `from starlette.staticfiles import StaticFiles` 를 사용할 수도 있습니다\1c.
+/// note | "기술적 세부사항"
- **FastAPI**는 단지 개발자인, 당신에게 편의를 제공하기 위해 `fastapi.static files` 와 동일한 `starlett.static files`를 제공합니다. 하지만 사실 이것은 Starlett에서 직접 온 것입니다.
+`from starlette.staticfiles import StaticFiles` 를 사용할 수도 있습니다.
+
+**FastAPI**는 단지 개발자인, 당신에게 편의를 제공하기 위해 `fastapi.static files` 와 동일한 `starlett.static files`를 제공합니다. 하지만 사실 이것은 Starlett에서 직접 온 것입니다.
+
+///
### "마운팅" 이란
-!!! warning
- The current page still doesn't have a translation for this language.
+/// warning
- But you can help translating it: [Contributing](https://fastapi.tiangolo.com/contributing/){.internal-link target=_blank}.
+The current page still doesn't have a translation for this language.
+
+But you can help translating it: [Contributing](https://fastapi.tiangolo.com/contributing/){.internal-link target=_blank}.
+
+///
my_second_user: User = User(**second_user_data)
```
-!!! info
- `**second_user_data` oznacza:
+/// info
- Przekaż klucze i wartości słownika `second_user_data` bezpośrednio jako argumenty klucz-wartość, co jest równoznaczne z: `User(id=4, name="Mary", joined="2018-11-30")`
+`**second_user_data` oznacza:
+
+Przekaż klucze i wartości słownika `second_user_data` bezpośrednio jako argumenty klucz-wartość, co jest równoznaczne z: `User(id=4, name="Mary", joined="2018-11-30")`
+
+///
### Wsparcie edytora
* Następnie dodaj **komentarz** z informacją o tym, że sprawdziłeś kod, dzięki temu będę miał pewność, że faktycznie go sprawdziłeś.
-!!! info
- Niestety, nie mogę ślepo ufać PR-om, nawet jeśli mają kilka zatwierdzeń.
+/// info
- Kilka razy zdarzyło się, że PR-y miały 3, 5 lub więcej zatwierdzeń (prawdopodobnie dlatego, że opis obiecuje rozwiązanie ważnego problemu), ale gdy sam sprawdziłem danego PR-a, okazał się być zbugowany lub nie rozwiązywał problemu, który rzekomo miał rozwiązywać. 😅
+Niestety, nie mogę ślepo ufać PR-om, nawet jeśli mają kilka zatwierdzeń.
- Dlatego tak ważne jest, abyś faktycznie przeczytał i uruchomił kod oraz napisał w komentarzu, że to zrobiłeś. 🤓
+Kilka razy zdarzyło się, że PR-y miały 3, 5 lub więcej zatwierdzeń (prawdopodobnie dlatego, że opis obiecuje rozwiązanie ważnego problemu), ale gdy sam sprawdziłem danego PR-a, okazał się być zbugowany lub nie rozwiązywał problemu, który rzekomo miał rozwiązywać. 😅
+
+Dlatego tak ważne jest, abyś faktycznie przeczytał i uruchomił kod oraz napisał w komentarzu, że to zrobiłeś. 🤓
+
+///
* Jeśli PR można uprościć w jakiś sposób, możesz o to poprosić, ale nie ma potrzeby być zbyt wybrednym, może być wiele subiektywnych punktów widzenia (a ja też będę miał swój 🙈), więc lepiej żebyś skupił się na kluczowych rzeczach.
Dołącz do 👥 <a href="https://discord.gg/VQjSZaeJmf" class="external-link" target="_blank">serwera czatu na Discordzie</a> 👥 i spędzaj czas z innymi w społeczności FastAPI.
-!!! tip "Wskazówka"
- Jeśli masz pytania, zadaj je w <a href="https://github.com/fastapi/fastapi/discussions/new?category=questions" class="external-link" target="_blank">Dyskusjach na GitHubie</a>, jest dużo większa szansa, że otrzymasz pomoc od [Ekspertów FastAPI](fastapi-people.md#fastapi-experts){.internal-link target=_blank}.
+/// tip | "Wskazówka"
+
+Jeśli masz pytania, zadaj je w <a href="https://github.com/fastapi/fastapi/discussions/new?category=questions" class="external-link" target="_blank">Dyskusjach na GitHubie</a>, jest dużo większa szansa, że otrzymasz pomoc od [Ekspertów FastAPI](fastapi-people.md#fastapi-experts){.internal-link target=_blank}.
+
+Używaj czatu tylko do innych ogólnych rozmów.
- Używaj czatu tylko do innych ogólnych rozmów.
+///
### Nie zadawaj pytań na czacie
</div>
-!!! note
- Polecenie `uvicorn main:app` odnosi się do:
+/// note
- * `main`: plik `main.py` ("moduł" Python).
- * `app`: obiekt utworzony w pliku `main.py` w lini `app = FastAPI()`.
- * `--reload`: sprawia, że serwer uruchamia się ponownie po zmianie kodu. Używany tylko w trakcie tworzenia oprogramowania.
+Polecenie `uvicorn main:app` odnosi się do:
+
+* `main`: plik `main.py` ("moduł" Python).
+* `app`: obiekt utworzony w pliku `main.py` w lini `app = FastAPI()`.
+* `--reload`: sprawia, że serwer uruchamia się ponownie po zmianie kodu. Używany tylko w trakcie tworzenia oprogramowania.
+
+///
Na wyjściu znajduje się linia z czymś w rodzaju:
`FastAPI` jest klasą, która zapewnia wszystkie funkcjonalności Twojego API.
-!!! note "Szczegóły techniczne"
- `FastAPI` jest klasą, która dziedziczy bezpośrednio z `Starlette`.
+/// note | "Szczegóły techniczne"
+
+`FastAPI` jest klasą, która dziedziczy bezpośrednio z `Starlette`.
- Oznacza to, że możesz korzystać ze wszystkich funkcjonalności <a href="https://www.starlette.io/" class="external-link" target="_blank">Starlette</a> również w `FastAPI`.
+Oznacza to, że możesz korzystać ze wszystkich funkcjonalności <a href="https://www.starlette.io/" class="external-link" target="_blank">Starlette</a> również w `FastAPI`.
+///
### Krok 2: utwórz instancję `FastAPI`
/items/foo
```
-!!! info
- "Ścieżka" jest zazwyczaj nazywana "path", "endpoint" lub "route'.
+/// info
+
+"Ścieżka" jest zazwyczaj nazywana "path", "endpoint" lub "route'.
+
+///
Podczas budowania API, "ścieżka" jest głównym sposobem na oddzielenie "odpowiedzialności" i „zasobów”.
* ścieżki `/`
* używając <abbr title="metoda HTTP GET">operacji <code>get</code></abbr>
-!!! info "`@decorator` Info"
- Składnia `@something` jest w Pythonie nazywana "dekoratorem".
+/// info | "`@decorator` Info"
+
+Składnia `@something` jest w Pythonie nazywana "dekoratorem".
- Umieszczasz to na szczycie funkcji. Jak ładną ozdobną czapkę (chyba stąd wzięła się nazwa).
+Umieszczasz to na szczycie funkcji. Jak ładną ozdobną czapkę (chyba stąd wzięła się nazwa).
- "Dekorator" przyjmuje funkcję znajdującą się poniżej jego i coś z nią robi.
+"Dekorator" przyjmuje funkcję znajdującą się poniżej jego i coś z nią robi.
- W naszym przypadku dekorator mówi **FastAPI**, że poniższa funkcja odpowiada **ścieżce** `/` z **operacją** `get`.
+W naszym przypadku dekorator mówi **FastAPI**, że poniższa funkcja odpowiada **ścieżce** `/` z **operacją** `get`.
- Jest to "**dekorator operacji na ścieżce**".
+Jest to "**dekorator operacji na ścieżce**".
+
+///
Możesz również użyć innej operacji:
* `@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ę**
{!../../../docs_src/first_steps/tutorial003.py!}
```
-!!! note
- Jeśli nie znasz różnicy, sprawdź [Async: *"In a hurry?"*](../async.md#in-a-hurry){.internal-link target=_blank}.
+/// note
+
+Jeśli nie znasz różnicy, sprawdź [Async: *"In a hurry?"*](../async.md#in-a-hurry){.internal-link target=_blank}.
+
+///
### Krok 5: zwróć zawartość
...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
# Retornos Adicionais no OpenAPI
-!!! warning "Aviso"
- Este é um tema bem avançado.
+/// warning | "Aviso"
- Se você está começando com o **FastAPI**, provavelmente você não precisa disso.
+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.
{!../../../docs_src/additional_responses/tutorial001.py!}
```
-!!! note "Nota"
- Lembre-se que você deve retornar o `JSONResponse` diretamente.
+/// note | "Nota"
+
+Lembre-se que você deve retornar o `JSONResponse` diretamente.
+
+///
+
+/// info | "Informação"
-!!! info "Informação"
- A chave `model` não é parte do OpenAPI.
+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 **FastAPI** pegará o modelo do Pydantic, gerará o `JSON Schema`, e adicionará no local correto.
- O 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.
+* 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á:
{!../../../docs_src/additional_responses/tutorial002.py!}
```
-!!! note "Nota"
- Note que você deve retornar a imagem utilizando um `FileResponse` diretamente.
+/// 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`).
-!!! 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.
- 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
Para conseguir isso, importe `JSONResponse` e retorne o seu conteúdo diretamente, definindo o `status_code` que você deseja:
-=== "Python 3.10+"
+//// tab | Python 3.10+
- ```Python hl_lines="4 25"
- {!> ../../../docs_src/additional_status_codes/tutorial001_an_py310.py!}
- ```
+```Python hl_lines="4 25"
+{!> ../../../docs_src/additional_status_codes/tutorial001_an_py310.py!}
+```
-=== "Python 3.9+"
+////
- ```Python hl_lines="4 25"
- {!> ../../../docs_src/additional_status_codes/tutorial001_an_py39.py!}
- ```
+//// tab | Python 3.9+
-=== "Python 3.8+"
+```Python hl_lines="4 25"
+{!> ../../../docs_src/additional_status_codes/tutorial001_an_py39.py!}
+```
- ```Python hl_lines="4 26"
- {!> ../../../docs_src/additional_status_codes/tutorial001_an.py!}
- ```
+////
-=== "Python 3.10+ non-Annotated"
+//// tab | Python 3.8+
- !!! tip "Dica"
- Faça uso da versão `Annotated` quando possível.
+```Python hl_lines="4 26"
+{!> ../../../docs_src/additional_status_codes/tutorial001_an.py!}
+```
- ```Python hl_lines="2 23"
- {!> ../../../docs_src/additional_status_codes/tutorial001_py310.py!}
- ```
+////
-=== "Python 3.8+ non-Annotated"
+//// tab | Python 3.10+ non-Annotated
- !!! tip "Dica"
- Faça uso da versão `Annotated` quando possível.
+/// tip | "Dica"
- ```Python hl_lines="4 25"
- {!> ../../../docs_src/additional_status_codes/tutorial001.py!}
- ```
+Faça uso da versão `Annotated` quando possível.
-!!! warning "Aviso"
- Quando você retorna um `Response` diretamente, como no exemplo acima, ele será retornado diretamente.
+///
- Ele não será serializado com um modelo, etc.
+```Python hl_lines="2 23"
+{!> ../../../docs_src/additional_status_codes/tutorial001_py310.py!}
+```
- Garanta que ele tenha toda informação que você deseja, e que os valores sejam um JSON válido (caso você esteja usando `JSONResponse`).
+////
-!!! note "Detalhes técnicos"
- Você também pode utilizar `from starlette.responses import JSONResponse`.
+//// tab | Python 3.8+ non-Annotated
- O **FastAPI** disponibiliza o `starlette.responses` como `fastapi.responses` apenas por conveniência para você, o programador. Porém a maioria dos retornos disponíveis vem diretamente do Starlette. O mesmo com `status`.
+/// tip | "Dica"
+
+Faça uso da versão `Annotated` quando possível.
+
+///
+
+```Python hl_lines="4 25"
+{!> ../../../docs_src/additional_status_codes/tutorial001.py!}
+```
+
+////
+
+/// warning | "Aviso"
+
+Quando você retorna um `Response` diretamente, como no exemplo acima, ele será retornado diretamente.
+
+Ele não será serializado com um modelo, etc.
+
+Garanta que ele tenha toda informação que você deseja, e que os valores sejam um JSON válido (caso você esteja usando `JSONResponse`).
+
+///
+
+/// note | "Detalhes técnicos"
+
+Você também pode utilizar `from starlette.responses import JSONResponse`.
+
+O **FastAPI** disponibiliza o `starlette.responses` como `fastapi.responses` apenas por conveniência para você, o programador. Porém a maioria dos retornos disponíveis vem diretamente do Starlette. O mesmo com `status`.
+
+///
## OpenAPI e documentação da API
Para fazer isso, nós declaramos o método `__call__`:
-=== "Python 3.9+"
+//// tab | Python 3.9+
- ```Python hl_lines="12"
- {!> ../../../docs_src/dependencies/tutorial011_an_py39.py!}
- ```
+```Python hl_lines="12"
+{!> ../../../docs_src/dependencies/tutorial011_an_py39.py!}
+```
+
+////
+
+//// tab | Python 3.8+
+
+```Python hl_lines="11"
+{!> ../../../docs_src/dependencies/tutorial011_an.py!}
+```
-=== "Python 3.8+"
+////
- ```Python hl_lines="11"
- {!> ../../../docs_src/dependencies/tutorial011_an.py!}
- ```
+//// tab | Python 3.8+ non-Annotated
-=== "Python 3.8+ non-Annotated"
+/// tip | "Dica"
- !!! tip "Dica"
- Prefira utilizar a versão `Annotated` se possível.
+Prefira utilizar a versão `Annotated` se possível.
- ```Python hl_lines="10"
- {!> ../../../docs_src/dependencies/tutorial011.py!}
- ```
+///
+
+```Python hl_lines="10"
+{!> ../../../docs_src/dependencies/tutorial011.py!}
+```
+
+////
Neste caso, o `__call__` é o que o **FastAPI** utilizará para verificar parâmetros adicionais e sub dependências, e isso é o que será chamado para passar o valor ao parâmetro na sua *função de operação de rota* posteriormente.
E agora, nós podemos utilizar o `__init__` para declarar os parâmetros da instância que podemos utilizar para "parametrizar" a dependência:
-=== "Python 3.9+"
+//// tab | Python 3.9+
- ```Python hl_lines="9"
- {!> ../../../docs_src/dependencies/tutorial011_an_py39.py!}
- ```
+```Python hl_lines="9"
+{!> ../../../docs_src/dependencies/tutorial011_an_py39.py!}
+```
-=== "Python 3.8+"
+////
- ```Python hl_lines="8"
- {!> ../../../docs_src/dependencies/tutorial011_an.py!}
- ```
+//// tab | Python 3.8+
-=== "Python 3.8+ non-Annotated"
+```Python hl_lines="8"
+{!> ../../../docs_src/dependencies/tutorial011_an.py!}
+```
+
+////
+
+//// tab | Python 3.8+ non-Annotated
+
+/// tip | "Dica"
- !!! tip "Dica"
- Prefira utilizar a versão `Annotated` se possível.
+Prefira utilizar a versão `Annotated` se possível.
- ```Python hl_lines="7"
- {!> ../../../docs_src/dependencies/tutorial011.py!}
- ```
+///
+
+```Python hl_lines="7"
+{!> ../../../docs_src/dependencies/tutorial011.py!}
+```
+
+////
Neste caso, o **FastAPI** nunca tocará ou se importará com o `__init__`, nós vamos utilizar diretamente em nosso código.
Nós poderíamos criar uma instância desta classe com:
-=== "Python 3.9+"
+//// tab | Python 3.9+
+
+```Python hl_lines="18"
+{!> ../../../docs_src/dependencies/tutorial011_an_py39.py!}
+```
+
+////
- ```Python hl_lines="18"
- {!> ../../../docs_src/dependencies/tutorial011_an_py39.py!}
- ```
+//// tab | Python 3.8+
-=== "Python 3.8+"
+```Python hl_lines="17"
+{!> ../../../docs_src/dependencies/tutorial011_an.py!}
+```
- ```Python hl_lines="17"
- {!> ../../../docs_src/dependencies/tutorial011_an.py!}
- ```
+////
-=== "Python 3.8+ non-Annotated"
+//// tab | Python 3.8+ non-Annotated
- !!! tip "Dica"
- Prefira utilizar a versão `Annotated` se possível.
+/// tip | "Dica"
- ```Python hl_lines="16"
- {!> ../../../docs_src/dependencies/tutorial011.py!}
- ```
+Prefira utilizar a versão `Annotated` se possível.
+
+///
+
+```Python hl_lines="16"
+{!> ../../../docs_src/dependencies/tutorial011.py!}
+```
+
+////
E deste modo nós podemos "parametrizar" a nossa dependência, que agora possui `"bar"` dentro dele, como o atributo `checker.fixed_content`.
...e passar o que quer que isso retorne como valor da dependência em nossa *função de operação de rota* como o parâmetro `fixed_content_included`:
-=== "Python 3.9+"
+//// tab | Python 3.9+
+
+```Python hl_lines="22"
+{!> ../../../docs_src/dependencies/tutorial011_an_py39.py!}
+```
- ```Python hl_lines="22"
- {!> ../../../docs_src/dependencies/tutorial011_an_py39.py!}
- ```
+////
-=== "Python 3.8+"
+//// tab | Python 3.8+
- ```Python hl_lines="21"
- {!> ../../../docs_src/dependencies/tutorial011_an.py!}
- ```
+```Python hl_lines="21"
+{!> ../../../docs_src/dependencies/tutorial011_an.py!}
+```
+
+////
+
+//// tab | Python 3.8+ non-Annotated
+
+/// tip | "Dica"
+
+Prefira utilizar a versão `Annotated` se possível.
+
+///
+
+```Python hl_lines="20"
+{!> ../../../docs_src/dependencies/tutorial011.py!}
+```
-=== "Python 3.8+ non-Annotated"
+////
- !!! tip "Dica"
- Prefira utilizar a versão `Annotated` se possível.
+/// tip | "Dica"
- ```Python hl_lines="20"
- {!> ../../../docs_src/dependencies/tutorial011.py!}
- ```
+Tudo isso parece não ser natural. E pode não estar muito claro ou aparentar ser útil ainda.
-!!! tip "Dica"
- Tudo isso parece não ser natural. E pode não estar muito claro ou aparentar ser útil ainda.
+Estes exemplos são intencionalmente simples, porém mostram como tudo funciona.
- Estes exemplos são intencionalmente simples, porém mostram como tudo funciona.
+Nos capítulos sobre segurança, existem funções utilitárias que são implementadas desta maneira.
- Nos capítulos sobre segurança, existem funções utilitárias que são implementadas desta maneira.
+Se você entendeu tudo isso, você já sabe como essas funções utilitárias para segurança funcionam por debaixo dos panos.
- Se você entendeu tudo isso, você já sabe como essas funções utilitárias para segurança funcionam por debaixo dos panos.
+///
{!../../../docs_src/async_tests/test_main.py!}
```
-!!! tip "Dica"
- Note que a função de teste é `async def` agora, no lugar de apenas `def` como quando estávamos utilizando o `TestClient` anteriormente.
+/// tip | "Dica"
+
+Note que a função de teste é `async def` agora, no lugar de apenas `def` como quando estávamos utilizando o `TestClient` anteriormente.
+
+///
Então podemos criar um `AsyncClient` com a aplicação, e enviar requisições assíncronas para ela utilizando `await`.
...que nós utilizamos para fazer as nossas requisições utilizando o `TestClient`.
-!!! tip "Dica"
- Note que nós estamos utilizando async/await com o novo `AsyncClient` - a requisição é assíncrona.
+/// tip | "Dica"
+
+Note que nós estamos utilizando async/await com o novo `AsyncClient` - a requisição é assíncrona.
+
+///
-!!! warning "Aviso"
- Se a sua aplicação depende dos eventos de vida útil (*lifespan*), o `AsyncClient` não acionará estes eventos. Para garantir que eles são acionados, utilize o `LifespanManager` do <a href="https://github.com/florimondmanca/asgi-lifespan#usage" class="external-link" target="_blank">florimondmanca/asgi-lifespan</a>.
+/// warning | "Aviso"
+
+Se a sua aplicação depende dos eventos de vida útil (*lifespan*), o `AsyncClient` não acionará estes eventos. Para garantir que eles são acionados, utilize o `LifespanManager` do <a href="https://github.com/florimondmanca/asgi-lifespan#usage" class="external-link" target="_blank">florimondmanca/asgi-lifespan</a>.
+
+///
## Outras Chamadas de Funções Assíncronas
Como a função de teste agora é assíncrona, você pode chamar (e `esperar`) outras funções `async` além de enviar requisições para a sua aplicação FastAPI em seus testes, exatamente como você as chamaria em qualquer outro lugar do seu código.
-!!! tip "Dica"
- Se você se deparar com um `RuntimeError: Task attached to a different loop` ao integrar funções assíncronas em seus testes (e.g. ao utilizar o <a href="https://stackoverflow.com/questions/41584243/runtimeerror-task-attached-to-a-different-loop" class="external-link" target="_blank">MotorClient do MongoDB</a>) Lembre-se de instanciar objetos que precisam de um loop de eventos (*event loop*) apenas em funções assíncronas, e.g. um *"callback"* `'@app.on_event("startup")`.
+/// tip | "Dica"
+
+Se você se deparar com um `RuntimeError: Task attached to a different loop` ao integrar funções assíncronas em seus testes (e.g. ao utilizar o <a href="https://stackoverflow.com/questions/41584243/runtimeerror-task-attached-to-a-different-loop" class="external-link" target="_blank">MotorClient do MongoDB</a>) Lembre-se de instanciar objetos que precisam de um loop de eventos (*event loop*) apenas em funções assíncronas, e.g. um *"callback"* `'@app.on_event("startup")`.
+
+///
proxy --> server
```
-!!! tip "Dica"
- O IP `0.0.0.0` é comumente usado para significar que o programa escuta em todos os IPs disponíveis naquela máquina/servidor.
+/// tip | "Dica"
+
+O IP `0.0.0.0` é comumente usado para significar que o programa escuta em todos os IPs disponíveis naquela máquina/servidor.
+
+///
A interface de documentação também precisaria do OpenAPI schema para declarar que API `server` está localizado em `/api/v1` (atrás do proxy). Por exemplo:
Se você usar Hypercorn, ele também tem a opção `--root-path`.
-!!! note "Detalhes Técnicos"
- A especificação ASGI define um `root_path` para esse caso de uso.
+/// note | "Detalhes Técnicos"
+
+A especificação ASGI define um `root_path` para esse caso de uso.
+
+E a opção de linha de comando `--root-path` fornece esse `root_path`.
- E a opção de linha de comando `--root-path` fornece esse `root_path`.
+///
### Verificando o `root_path` atual
Isso diz ao Traefik para escutar na porta 9999 e usar outro arquivo `routes.toml`.
-!!! tip "Dica"
- Estamos usando a porta 9999 em vez da porta padrão HTTP 80 para que você não precise executá-lo com privilégios de administrador (`sudo`).
+/// tip | "Dica"
+
+Estamos usando a porta 9999 em vez da porta padrão HTTP 80 para que você não precise executá-lo com privilégios de administrador (`sudo`).
+
+///
Agora crie esse outro arquivo `routes.toml`:
}
```
-!!! tip "Dica"
- Perceba que, mesmo acessando em `http://127.0.0.1:8000/app`, ele mostra o `root_path` de `/api/v1`, retirado da opção `--root-path`.
+/// tip | "Dica"
+
+Perceba que, mesmo acessando em `http://127.0.0.1:8000/app`, ele mostra o `root_path` de `/api/v1`, retirado da opção `--root-path`.
+
+///
E agora abra o URL com a porta para o Traefik, incluindo o prefixo de caminho: <a href="http://127.0.0.1:9999/api/v1/app" class="external-link" target="_blank">http://127.0.0.1:9999/api/v1/app</a>.
## Servidores adicionais
-!!! warning "Aviso"
- Este é um caso de uso mais avançado. Sinta-se à vontade para pular.
+/// warning | "Aviso"
+
+Este é um caso de uso mais avançado. Sinta-se à vontade para pular.
+
+///
Por padrão, o **FastAPI** criará um `server` no OpenAPI schema com o URL para o `root_path`.
}
```
-!!! tip "Dica"
- Perceba o servidor gerado automaticamente com um valor `url` de `/api/v1`, retirado do `root_path`.
+/// tip | "Dica"
+
+Perceba o servidor gerado automaticamente com um valor `url` de `/api/v1`, retirado do `root_path`.
+
+///
Na interface de documentação em <a href="http://127.0.0.1:9999/api/v1/docs" class="external-link" target="_blank">http://127.0.0.1:9999/api/v1/docs</a> parecerá:
<img src="/img/tutorial/behind-a-proxy/image03.png">
-!!! tip "Dica"
- A interface de documentação interagirá com o servidor que você selecionar.
+/// tip | "Dica"
+
+A interface de documentação interagirá com o servidor que você selecionar.
+
+///
### Desabilitar servidor automático de `root_path`
E então, logo após o `yield`, descarregaremos o modelo. Esse código será executado **após** a aplicação **terminar de lidar com as requisições**, pouco antes do *encerramento*. Isso poderia, por exemplo, liberar recursos como memória ou GPU.
-!!! tip "Dica"
- O `shutdown` aconteceria quando você estivesse **encerrando** a aplicação.
+/// tip | "Dica"
- Talvez você precise inicializar uma nova versão, ou apenas cansou de executá-la. 🤷
+O `shutdown` aconteceria quando você estivesse **encerrando** a aplicação.
+
+Talvez você precise inicializar uma nova versão, ou apenas cansou de executá-la. 🤷
+
+///
### Função _lifespan_
## Eventos alternativos (deprecados)
-!!! warning "Aviso"
- A maneira recomendada para lidar com a *inicialização* e o *encerramento* é usando o parâmetro `lifespan` da aplicação `FastAPI` como descrito acima.
+/// warning | "Aviso"
+
+A maneira recomendada para lidar com a *inicialização* e o *encerramento* é usando o parâmetro `lifespan` da aplicação `FastAPI` como descrito acima.
- Você provavelmente pode pular essa parte.
+Você provavelmente pode pular essa parte.
+
+///
Existe uma forma alternativa para definir a execução dessa lógica durante *inicialização* e durante *encerramento*.
Aqui, a função de manipulação de evento `shutdown` irá escrever uma linha de texto `"Application shutdown"` no arquivo `log.txt`.
-!!! info "Informação"
- Na função `open()`, o `mode="a"` significa "acrescentar", então, a linha irá ser adicionada depois de qualquer coisa que esteja naquele arquivo, sem sobrescrever o conteúdo anterior.
+/// info | "Informação"
+
+Na função `open()`, o `mode="a"` significa "acrescentar", então, a linha irá ser adicionada depois de qualquer coisa que esteja naquele arquivo, sem sobrescrever o conteúdo anterior.
-!!! tip "Dica"
- Perceba que nesse caso nós estamos usando a função padrão do Python `open()` que interage com um arquivo.
+///
- Então, isso envolve I/O (input/output), que exige "esperar" que coisas sejam escritas em disco.
+/// tip | "Dica"
- Mas `open()` não usa `async` e `await`.
+Perceba que nesse caso nós estamos usando a função padrão do Python `open()` que interage com um arquivo.
- Então, nós declaramos uma função de manipulação de evento com o padrão `def` ao invés de `async def`.
+Então, isso envolve I/O (input/output), que exige "esperar" que coisas sejam escritas em disco.
+
+Mas `open()` não usa `async` e `await`.
+
+Então, nós declaramos uma função de manipulação de evento com o padrão `def` ao invés de `async def`.
+
+///
### `startup` e `shutdown` juntos
Por baixo, na especificação técnica ASGI, essa é a parte do <a href="https://asgi.readthedocs.io/en/latest/specs/lifespan.html" class="external-link" target="_blank">Protocolo Lifespan</a>, e define eventos chamados `startup` e `shutdown`.
-!!! info "Informação"
- Você pode ler mais sobre o manipulador `lifespan` do Starlette na <a href="https://www.starlette.io/lifespan/" class="external-link" target="_blank">Documentação do Lifespan Starlette</a>.
+/// info | "Informação"
+
+Você pode ler mais sobre o manipulador `lifespan` do Starlette na <a href="https://www.starlette.io/lifespan/" class="external-link" target="_blank">Documentação do Lifespan Starlette</a>.
+
+Incluindo como manipular estado do lifespan que pode ser usado em outras áreas do seu código.
- Incluindo como manipular estado do lifespan que pode ser usado em outras áreas do seu código.
+///
## Sub Aplicações
Na próxima seção você verá outras opções, configurações, e recursos adicionais.
-!!! tip "Dica"
- As próximas seções **não são necessáriamente "avançadas"**
+/// tip | "Dica"
- E é possível que para seu caso de uso, a solução esteja em uma delas.
+As próximas seções **não são necessáriamente "avançadas"**
+
+E é possível que para seu caso de uso, a solução esteja em uma delas.
+
+///
## Leia o Tutorial primeiro
Isto pode facilitar bastante para os seus usuários **implementarem as APIs deles** para receber as requisições dos seus **webhooks**, eles podem inclusive ser capazes de gerar parte do código da API deles.
-!!! info "Informação"
- Webhooks estão disponíveis a partir do OpenAPI 3.1.0, e possui suporte do FastAPI a partir da versão `0.99.0`.
+/// info | "Informação"
+
+Webhooks estão disponíveis a partir do OpenAPI 3.1.0, e possui suporte do FastAPI a partir da versão `0.99.0`.
+
+///
## Uma aplicação com webhooks
Os webhooks que você define aparecerão no esquema do **OpenAPI** e na **página de documentação** gerada automaticamente.
-!!! info "Informação"
- O objeto `app.webhooks` é na verdade apenas um `APIRouter`, o mesmo tipo que você utilizaria ao estruturar a sua aplicação com diversos arquivos.
+/// info | "Informação"
+
+O objeto `app.webhooks` é na verdade apenas um `APIRouter`, o mesmo tipo que você utilizaria ao estruturar a sua aplicação com diversos arquivos.
+
+///
Note que utilizando webhooks você não está de fato declarando uma **rota** (como `/items/`), o texto que informa é apenas um **identificador** do webhook (o nome do evento), por exemplo em `@app.webhooks.post("new-subscription")`, o nome do webhook é `new-subscription`.
## Variáveis de Ambiente
-!!! dica
- Se você já sabe o que são variáveis de ambiente e como utilizá-las, sinta-se livre para avançar para o próximo tópico.
+/// dica
+
+Se você já sabe o que são variáveis de ambiente e como utilizá-las, sinta-se livre para avançar para o próximo tópico.
+
+///
Uma <a href="https://pt.wikipedia.org/wiki/Variável_de_ambiente" class="external-link" target="_blank">variável de ambiente</a> (abreviada em inglês para "env var") é uma variável definida fora do código Python, no sistema operacional, e pode ser lida pelo seu código Python (ou por outros programas).
Você pode criar e utilizar variáveis de ambiente no terminal, sem precisar utilizar Python:
-=== "Linux, macOS, Windows Bash"
+//// tab | Linux, macOS, Windows Bash
- <div class="termy">
+<div class="termy">
- ```console
- // Você pode criar uma env var MY_NAME usando
- $ export MY_NAME="Wade Wilson"
+```console
+// Você pode criar uma env var MY_NAME usando
+$ export MY_NAME="Wade Wilson"
- // E utilizá-la em outros programas, como
- $ echo "Hello $MY_NAME"
+// E utilizá-la em outros programas, como
+$ echo "Hello $MY_NAME"
+
+Hello Wade Wilson
+```
+
+</div>
- Hello Wade Wilson
- ```
+////
- </div>
+//// tab | Windows PowerShell
-=== "Windows PowerShell"
+<div class="termy">
- <div class="termy">
+```console
+// Criando env var MY_NAME
+$ $Env:MY_NAME = "Wade Wilson"
- ```console
- // Criando env var MY_NAME
- $ $Env:MY_NAME = "Wade Wilson"
+// Usando em outros programas, como
+$ echo "Hello $Env:MY_NAME"
- // Usando em outros programas, como
- $ echo "Hello $Env:MY_NAME"
+Hello Wade Wilson
+```
- Hello Wade Wilson
- ```
+</div>
- </div>
+////
### Lendo variáveis de ambiente com Python
print(f"Hello {name} from Python")
```
-!!! dica
- O segundo parâmetro em <a href="https://docs.python.org/3.8/library/os.html#os.getenv" class="external-link" target="_blank">`os.getenv()`</a> é o valor padrão para o retorno.
+/// dica
+
+O segundo parâmetro em <a href="https://docs.python.org/3.8/library/os.html#os.getenv" class="external-link" target="_blank">`os.getenv()`</a> é o valor padrão para o retorno.
- Se nenhum valor for informado, `None` é utilizado por padrão, aqui definimos `"World"` como o valor padrão a ser utilizado.
+Se nenhum valor for informado, `None` é utilizado por padrão, aqui definimos `"World"` como o valor padrão a ser utilizado.
+
+///
E depois você pode executar esse arquivo:
</div>
-!!! dica
- Você pode ler mais sobre isso em: <a href="https://12factor.net/pt_br/config" class="external-link" target="_blank">The Twelve-Factor App: Configurações</a>.
+/// dica
+
+Você pode ler mais sobre isso em: <a href="https://12factor.net/pt_br/config" class="external-link" target="_blank">The Twelve-Factor App: Configurações</a>.
+
+///
### Tipagem e Validação
</div>
-!!! info
- Na v1 do Pydantic ele estava incluído no pacote principal. Agora ele está distribuido como um pacote independente para que você possa optar por instalar ou não caso você não precise dessa funcionalidade.
+/// info
+
+Na v1 do Pydantic ele estava incluído no pacote principal. Agora ele está distribuido como um pacote independente para que você possa optar por instalar ou não caso você não precise dessa funcionalidade.
+
+///
### Criando o objeto `Settings`
Você pode utilizar todas as ferramentas e funcionalidades de validação que são utilizadas nos modelos do Pydantic, como tipos de dados diferentes e validações adicionei com `Field()`.
-=== "Pydantic v2"
+//// tab | Pydantic v2
+
+```Python hl_lines="2 5-8 11"
+{!> ../../../docs_src/settings/tutorial001.py!}
+```
+
+////
+
+//// tab | Pydantic v1
- ```Python hl_lines="2 5-8 11"
- {!> ../../../docs_src/settings/tutorial001.py!}
- ```
+/// info
+
+Na versão 1 do Pydantic você importaria `BaseSettings` diretamente do módulo `pydantic` em vez do módulo `pydantic_settings`.
+
+///
+
+```Python hl_lines="2 5-8 11"
+{!> ../../../docs_src/settings/tutorial001_pv1.py!}
+```
-=== "Pydantic v1"
+////
- !!! Info
- Na versão 1 do Pydantic você importaria `BaseSettings` diretamente do módulo `pydantic` em vez do módulo `pydantic_settings`.
+/// dica
- ```Python hl_lines="2 5-8 11"
- {!> ../../../docs_src/settings/tutorial001_pv1.py!}
- ```
+Se você quiser algo pronto para copiar e colar na sua aplicação, não use esse exemplo, mas sim o exemplo abaixo.
-!!! dica
- Se você quiser algo pronto para copiar e colar na sua aplicação, não use esse exemplo, mas sim o exemplo abaixo.
+///
Portanto, quando você cria uma instância da classe `Settings` (nesse caso, o objeto `settings`), o Pydantic lê as variáveis de ambiente sem diferenciar maiúsculas e minúsculas, por isso, uma variável maiúscula `APP_NAME` será usada para o atributo `app_name`.
</div>
-!!! dica
- Para definir múltiplas variáveis de ambiente para um único comando basta separá-las utilizando espaços, e incluir todas elas antes do comando.
+/// dica
+
+Para definir múltiplas variáveis de ambiente para um único comando basta separá-las utilizando espaços, e incluir todas elas antes do comando.
+
+///
Assim, o atributo `admin_email` seria definido como `"deadpool@example.com"`.
{!../../../docs_src/settings/app01/main.py!}
```
-!!! dica
- Você também precisa incluir um arquivo `__init__.py` como visto em [Bigger Applications - Multiple Files](../tutorial/bigger-applications.md){.internal-link target=\_blank}.
+/// dica
+
+Você também precisa incluir um arquivo `__init__.py` como visto em [Bigger Applications - Multiple Files](../tutorial/bigger-applications.md){.internal-link target=\_blank}.
+
+///
## Configurações em uma dependência
Agora criamos a dependência que retorna um novo objeto `config.Settings()`.
-=== "Python 3.9+"
+//// tab | Python 3.9+
- ```Python hl_lines="6 12-13"
- {!> ../../../docs_src/settings/app02_an_py39/main.py!}
- ```
+```Python hl_lines="6 12-13"
+{!> ../../../docs_src/settings/app02_an_py39/main.py!}
+```
-=== "Python 3.8+"
+////
- ```Python hl_lines="6 12-13"
- {!> ../../../docs_src/settings/app02_an/main.py!}
- ```
+//// tab | Python 3.8+
-=== "Python 3.8+ non-Annotated"
+```Python hl_lines="6 12-13"
+{!> ../../../docs_src/settings/app02_an/main.py!}
+```
+
+////
- !!! dica
- Utilize a versão com `Annotated` se possível.
+//// tab | Python 3.8+ non-Annotated
- ```Python hl_lines="5 11-12"
- {!> ../../../docs_src/settings/app02/main.py!}
- ```
+/// dica
-!!! dica
- Vamos discutir sobre `@lru_cache` logo mais.
+Utilize a versão com `Annotated` se possível.
- Por enquanto, você pode considerar `get_settings()` como uma função normal.
+///
+
+```Python hl_lines="5 11-12"
+{!> ../../../docs_src/settings/app02/main.py!}
+```
+
+////
+
+/// dica
+
+Vamos discutir sobre `@lru_cache` logo mais.
+
+Por enquanto, você pode considerar `get_settings()` como uma função normal.
+
+///
E então podemos declarar essas configurações como uma dependência na função de operação da rota e utilizar onde for necessário.
-=== "Python 3.9+"
+//// tab | Python 3.9+
+
+```Python hl_lines="17 19-21"
+{!> ../../../docs_src/settings/app02_an_py39/main.py!}
+```
+
+////
+
+//// tab | Python 3.8+
- ```Python hl_lines="17 19-21"
- {!> ../../../docs_src/settings/app02_an_py39/main.py!}
- ```
+```Python hl_lines="17 19-21"
+{!> ../../../docs_src/settings/app02_an/main.py!}
+```
+
+////
-=== "Python 3.8+"
+//// tab | Python 3.8+ non-Annotated
- ```Python hl_lines="17 19-21"
- {!> ../../../docs_src/settings/app02_an/main.py!}
- ```
+/// dica
-=== "Python 3.8+ non-Annotated"
+Utilize a versão com `Annotated` se possível.
- !!! dica
- Utilize a versão com `Annotated` se possível.
+///
- ```Python hl_lines="16 18-20"
- {!> ../../../docs_src/settings/app02/main.py!}
- ```
+```Python hl_lines="16 18-20"
+{!> ../../../docs_src/settings/app02/main.py!}
+```
+
+////
### Configurações e testes
Essa prática é tão comum que possui um nome, essas variáveis de ambiente normalmente são colocadas em um arquivo `.env`, e esse arquivo é chamado de "dotenv".
-!!! dica
- Um arquivo iniciando com um ponto final (`.`) é um arquivo oculto em sistemas baseados em Unix, como Linux e MacOS.
+/// dica
+
+Um arquivo iniciando com um ponto final (`.`) é um arquivo oculto em sistemas baseados em Unix, como Linux e MacOS.
- Mas um arquivo dotenv não precisa ter esse nome exato.
+Mas um arquivo dotenv não precisa ter esse nome exato.
+
+///
Pydantic suporta a leitura desses tipos de arquivos utilizando uma biblioteca externa. Você pode ler mais em <a href="https://docs.pydantic.dev/latest/concepts/pydantic_settings/#dotenv-env-support" class="external-link" target="_blank">Pydantic Settings: Dotenv (.env) support</a>.
-!!! dica
- Para que isso funcione você precisa executar `pip install python-dotenv`.
+/// dica
+
+Para que isso funcione você precisa executar `pip install python-dotenv`.
+
+///
### O arquivo `.env`
E então adicionar o seguinte código em `config.py`:
-=== "Pydantic v2"
+//// tab | Pydantic v2
- ```Python hl_lines="9"
- {!> ../../../docs_src/settings/app03_an/config.py!}
- ```
+```Python hl_lines="9"
+{!> ../../../docs_src/settings/app03_an/config.py!}
+```
- !!! dica
- O atributo `model_config` é usado apenas para configuração do Pydantic. Você pode ler mais em <a href="https://docs.pydantic.dev/latest/usage/model_config/" class="external-link" target="_blank">Pydantic Model Config</a>.
+/// dica
-=== "Pydantic v1"
+O atributo `model_config` é usado apenas para configuração do Pydantic. Você pode ler mais em <a href="https://docs.pydantic.dev/latest/usage/model_config/" class="external-link" target="_blank">Pydantic Model Config</a>.
- ```Python hl_lines="9-10"
- {!> ../../../docs_src/settings/app03_an/config_pv1.py!}
- ```
+///
- !!! dica
- A classe `Config` é usada apenas para configuração do Pydantic. Você pode ler mais em <a href="https://docs.pydantic.dev/1.10/usage/model_config/" class="external-link" target="_blank">Pydantic Model Config</a>.
+////
-!!! info
- Na versão 1 do Pydantic a configuração é realizada por uma classe interna `Config`, na versão 2 do Pydantic isso é feito com o atributo `model_config`. Esse atributo recebe um `dict`, para utilizar o autocomplete e checagem de erros do seu editor de texto você pode importar e utilizar `SettingsConfigDict` para definir esse `dict`.
+//// tab | Pydantic v1
+
+```Python hl_lines="9-10"
+{!> ../../../docs_src/settings/app03_an/config_pv1.py!}
+```
+
+/// dica
+
+A classe `Config` é usada apenas para configuração do Pydantic. Você pode ler mais em <a href="https://docs.pydantic.dev/1.10/usage/model_config/" class="external-link" target="_blank">Pydantic Model Config</a>.
+
+///
+
+////
+
+/// info
+
+Na versão 1 do Pydantic a configuração é realizada por uma classe interna `Config`, na versão 2 do Pydantic isso é feito com o atributo `model_config`. Esse atributo recebe um `dict`, para utilizar o autocomplete e checagem de erros do seu editor de texto você pode importar e utilizar `SettingsConfigDict` para definir esse `dict`.
+
+///
Aqui definimos a configuração `env_file` dentro da classe `Settings` do Pydantic, e definimos o valor como o nome do arquivo dotenv que queremos utilizar.
Mas como estamos utilizando o decorador `@lru_cache` acima, o objeto `Settings` é criado apenas uma vez, na primeira vez que a função é chamada. ✔️
-=== "Python 3.9+"
+//// tab | Python 3.9+
- ```Python hl_lines="1 11"
- {!> ../../../docs_src/settings/app03_an_py39/main.py!}
- ```
+```Python hl_lines="1 11"
+{!> ../../../docs_src/settings/app03_an_py39/main.py!}
+```
+
+////
+
+//// tab | Python 3.8+
+
+```Python hl_lines="1 11"
+{!> ../../../docs_src/settings/app03_an/main.py!}
+```
+
+////
-=== "Python 3.8+"
+//// tab | Python 3.8+ non-Annotated
- ```Python hl_lines="1 11"
- {!> ../../../docs_src/settings/app03_an/main.py!}
- ```
+/// dica
-=== "Python 3.8+ non-Annotated"
+Utilize a versão com `Annotated` se possível.
- !!! dica
- Utilize a versão com `Annotated` se possível.
+///
+
+```Python hl_lines="1 10"
+{!> ../../../docs_src/settings/app03/main.py!}
+```
- ```Python hl_lines="1 10"
- {!> ../../../docs_src/settings/app03/main.py!}
- ```
+////
Dessa forma, todas as chamadas da função `get_settings()` nas dependências das próximas requisições, em vez de executar o código interno de `get_settings()` e instanciar um novo objeto `Settings`, irão retornar o mesmo objeto que foi retornado na primeira chamada, de novo e de novo.
{!../../../docs_src/templates/tutorial001.py!}
```
-!!! note
- Antes do FastAPI 0.108.0, Starlette 0.29.0, `name` era o primeiro parâmetro.
+/// note
- Além disso, em versões anteriores, o objeto `request` era passado como parte dos pares chave-valor no "context" dict para o Jinja2.
+Antes do FastAPI 0.108.0, Starlette 0.29.0, `name` era o primeiro parâmetro.
+Além disso, em versões anteriores, o objeto `request` era passado como parte dos pares chave-valor no "context" dict para o Jinja2.
-!!! tip "Dica"
- Ao declarar `response_class=HTMLResponse`, a documentação entenderá que a resposta será HTML.
+///
+/// tip | "Dica"
-!!! note "Detalhes Técnicos"
- Você também poderia usar `from starlette.templating import Jinja2Templates`.
+Ao declarar `response_class=HTMLResponse`, a documentação entenderá que a resposta será HTML.
- **FastAPI** fornece o mesmo `starlette.templating` como `fastapi.templating` apenas como uma conveniência para você, o desenvolvedor. Mas a maioria das respostas disponíveis vêm diretamente do Starlette. O mesmo acontece com `Request` e `StaticFiles`.
+///
+
+/// note | "Detalhes Técnicos"
+
+Você também poderia usar `from starlette.templating import Jinja2Templates`.
+
+**FastAPI** fornece o mesmo `starlette.templating` como `fastapi.templating` apenas como uma conveniência para você, o desenvolvedor. Mas a maioria das respostas disponíveis vêm diretamente do Starlette. O mesmo acontece com `Request` e `StaticFiles`.
+
+///
## Escrevendo Templates
Ele foi um dos primeiros exemplos de **documentação automática de API**, e essa foi especificamente uma das primeiras idéias que inspirou "a busca por" **FastAPI**.
-!!! note "Nota"
- Django REST Framework foi criado por Tom Christie. O mesmo criador de Starlette e Uvicorn, nos quais **FastAPI** é baseado.
+/// note | "Nota"
-!!! check "**FastAPI** inspirado para"
- Ter uma documentação automática da API em interface web.
+Django REST Framework foi criado por Tom Christie. O mesmo criador de Starlette e Uvicorn, nos quais **FastAPI** é baseado.
+
+///
+
+/// check | "**FastAPI** inspirado para"
+
+Ter uma documentação automática da API em interface web.
+
+///
### <a href="https://flask.palletsprojects.com" class="external-link" target="_blank">Flask</a>
Dada a simplicidade do Flask, parecia uma ótima opção para construção de APIs. A próxima coisa a procurar era um "Django REST Framework" para Flask.
-!!! check "**FastAPI** inspirado para"
- Ser um microframework. Fazer ele fácil para misturar e combinar com ferramentas e partes necessárias.
+/// check | "**FastAPI** inspirado para"
- Ser simples e com sistema de roteamento fácil de usar.
+Ser um microframework. Fazer ele fácil para misturar e combinar com ferramentas e partes necessárias.
+
+Ser simples e com sistema de roteamento fácil de usar.
+
+///
### <a href="https://requests.readthedocs.io" class="external-link" target="_blank">Requests</a>
Veja as similaridades em `requests.get(...)` e `@app.get(...)`.
-!!! check "**FastAPI** inspirado para"
- * Ter uma API simples e intuitiva.
- * Utilizar nomes de métodos HTTP (operações) diretamente, de um jeito direto e intuitivo.
- * Ter padrões sensíveis, mas customizações poderosas.
+/// check | "**FastAPI** inspirado para"
+
+* Ter uma API simples e intuitiva.
+* Utilizar nomes de métodos HTTP (operações) diretamente, de um jeito direto e intuitivo.
+* Ter padrões sensíveis, mas customizações poderosas.
+
+///
### <a href="https://swagger.io/" class="external-link" target="_blank">Swagger</a> / <a href="https://github.com/OAI/OpenAPI-Specification/" class="external-link" target="_blank">OpenAPI</a>
Isso acontece porquê quando alguém fala sobre a versão 2.0 é comum dizer "Swagger", e para a versão 3+, "OpenAPI".
-!!! check "**FastAPI** inspirado para"
- Adotar e usar um padrão aberto para especificações API, ao invés de algum esquema customizado.
+/// check | "**FastAPI** inspirado para"
+
+Adotar e usar um padrão aberto para especificações API, ao invés de algum esquema customizado.
+
+E integrar ferramentas de interface para usuários baseado nos padrões:
- E integrar ferramentas de interface para usuários baseado nos padrões:
+* <a href="https://github.com/swagger-api/swagger-ui" class="external-link" target="_blank">Swagger UI</a>
+* <a href="https://github.com/Rebilly/ReDoc" class="external-link" target="_blank">ReDoc</a>
- * <a href="https://github.com/swagger-api/swagger-ui" class="external-link" target="_blank">Swagger UI</a>
- * <a href="https://github.com/Rebilly/ReDoc" class="external-link" target="_blank">ReDoc</a>
+Esses dois foram escolhidos por serem bem populares e estáveis, mas fazendo uma pesquisa rápida, você pode encontrar dúzias de interfaces alternativas adicionais para OpenAPI (assim você poderá utilizar com **FastAPI**).
- Esses dois foram escolhidos por serem bem populares e estáveis, mas fazendo uma pesquisa rápida, você pode encontrar dúzias de interfaces alternativas adicionais para OpenAPI (assim você poderá utilizar com **FastAPI**).
+///
### Flask REST frameworks
Mas ele foi criado antes da existência do _type hints_ do Python. Então, para definir todo o <abbr title="definição de como os dados devem ser formados">_schema_</abbr> você precisa utilizar específicas ferramentas e classes fornecidas pelo Marshmallow.
-!!! check "**FastAPI** inspirado para"
- Usar código para definir "schemas" que forneçam, automaticamente, tipos de dados e validação.
+/// check | "**FastAPI** inspirado para"
+
+Usar código para definir "schemas" que forneçam, automaticamente, tipos de dados e validação.
+
+///
### <a href="https://webargs.readthedocs.io/en/latest/" class="external-link" target="_blank">Webargs</a>
Ele é uma grande ferramenta e eu também a utilizei muito, antes de ter o **FastAPI**.
-!!! info
- Webargs foi criado pelos mesmos desenvolvedores do Marshmallow.
+/// info
+
+Webargs foi criado pelos mesmos desenvolvedores do Marshmallow.
-!!! check "**FastAPI** inspirado para"
- Ter validação automática de dados vindos de requisições.
+///
+
+/// check | "**FastAPI** inspirado para"
+
+Ter validação automática de dados vindos de requisições.
+
+///
### <a href="https://apispec.readthedocs.io/en/stable/" class="external-link" target="_blank">APISpec</a>
O editor não poderá ajudar muito com isso. E se nós modificarmos os parâmetros dos _schemas_ do Marshmallow e esquecer de modificar também aquela _docstring_ YAML, o _schema_ gerado pode ficar obsoleto.
-!!! info
- APISpec foi criado pelos mesmos desenvolvedores do Marshmallow.
+/// info
+
+APISpec foi criado pelos mesmos desenvolvedores do Marshmallow.
+
+///
+
+/// check | "**FastAPI** inspirado para"
-!!! check "**FastAPI** inspirado para"
- Dar suporte a padrões abertos para APIs, OpenAPI.
+Dar suporte a padrões abertos para APIs, OpenAPI.
+
+///
### <a href="https://flask-apispec.readthedocs.io/en/latest/" class="external-link" target="_blank">Flask-apispec</a>
E esses mesmos geradores _full-stack_ foram a base dos [Geradores de Projetos **FastAPI**](project-generation.md){.internal-link target=_blank}.
-!!! info
- Flask-apispec foi criado pelos mesmos desenvolvedores do Marshmallow.
+/// info
+
+Flask-apispec foi criado pelos mesmos desenvolvedores do Marshmallow.
+
+///
-!!! check "**FastAPI** inspirado para"
- Gerar _schema_ OpenAPI automaticamente, a partir do mesmo código que define serialização e validação.
+/// check | "**FastAPI** inspirado para"
+
+Gerar _schema_ OpenAPI automaticamente, a partir do mesmo código que define serialização e validação.
+
+///
### <a href="https://nestjs.com/" class="external-link" target="_blank">NestJS</a> (and <a href="https://angular.io/" class="external-link" target="_blank">Angular</a>)
Ele também não controla modelos aninhados muito bem. Então, se o corpo JSON na requisição for um objeto JSON que contém campos internos que contém objetos JSON aninhados, ele não consegue ser validado e documentado apropriadamente.
-!!! check "**FastAPI** inspirado para"
- Usar tipos Python para ter um ótimo suporte do editor.
+/// check | "**FastAPI** inspirado para"
+
+Usar tipos Python para ter um ótimo suporte do editor.
- Ter um sistema de injeção de dependência poderoso. Achar um jeito de minimizar repetição de código.
+Ter um sistema de injeção de dependência poderoso. Achar um jeito de minimizar repetição de código.
+
+///
### <a href="https://sanic.readthedocs.io/en/latest/" class="external-link" target="_blank">Sanic</a>
Ele foi um dos primeiros frameworks Python extremamente rápido baseado em `asyncio`. Ele foi feito para ser muito similar ao Flask.
-!!! note "Detalhes técnicos"
- Ele utiliza <a href="https://github.com/MagicStack/uvloop" class="external-link" target="_blank">`uvloop`</a> ao invés do '_loop_' `asyncio` padrão do Python. É isso que deixa ele tão rápido.
+/// note | "Detalhes técnicos"
+
+Ele utiliza <a href="https://github.com/MagicStack/uvloop" class="external-link" target="_blank">`uvloop`</a> ao invés do '_loop_' `asyncio` padrão do Python. É isso que deixa ele tão rápido.
+
+Ele claramente inspirou Uvicorn e Starlette, que são atualmente mais rápidos que o Sanic em testes de performance abertos.
+
+///
- Ele claramente inspirou Uvicorn e Starlette, que são atualmente mais rápidos que o Sanic em testes de performance abertos.
+/// check | "**FastAPI** inspirado para"
-!!! check "**FastAPI** inspirado para"
- Achar um jeito de ter uma performance insana.
+Achar um jeito de ter uma performance insana.
- É por isso que o **FastAPI** é baseado em Starlette, para que ele seja o framework mais rápido disponível (performance testada por terceiros).
+É por isso que o **FastAPI** é baseado em Starlette, para que ele seja o framework mais rápido disponível (performance testada por terceiros).
+
+///
### <a href="https://falconframework.org/" class="external-link" target="_blank">Falcon</a>
Então, validação de dados, serialização e documentação tem que ser feitos no código, não automaticamente. Ou eles terão que ser implementados como um framework acima do Falcon, como o Hug. Essa mesma distinção acontece em outros frameworks que são inspirados pelo design do Falcon, tendo um objeto de requisição e um objeto de resposta como parâmetros.
-!!! check "**FastAPI** inspirado para"
- Achar jeitos de conseguir melhor performance.
+/// check | "**FastAPI** inspirado para"
+
+Achar jeitos de conseguir melhor performance.
+
+Juntamente com Hug (como Hug é baseado no Falcon) inspirou **FastAPI** para declarar um parâmetro de `resposta` nas funções.
- Juntamente com Hug (como Hug é baseado no Falcon) inspirou **FastAPI** para declarar um parâmetro de `resposta` nas funções.
+Embora no FastAPI seja opcional, é utilizado principalmente para configurar cabeçalhos, cookies e códigos de status alternativos.
- Embora no FastAPI seja opcional, é utilizado principalmente para configurar cabeçalhos, cookies e códigos de status alternativos.
+///
### <a href="https://moltenframework.com/" class="external-link" target="_blank">Molten</a>
Rotas são declaradas em um único lugar, usando funções declaradas em outros lugares (ao invés de usar decoradores que possam ser colocados diretamente acima da função que controla o _endpoint_). Isso é mais perto de como o Django faz isso do que como Flask (e Starlette) faz. Ele separa no código coisas que são relativamente amarradas.
-!!! check "**FastAPI** inspirado para"
- Definir validações extras para tipos de dados usando valores "padrão" de atributos dos modelos. Isso melhora o suporte do editor, e não estava disponível no Pydantic antes.
+/// check | "**FastAPI** inspirado para"
- Isso na verdade inspirou a atualização de partes do Pydantic, para dar suporte ao mesmo estilo de declaração da validação (toda essa funcionalidade já está disponível no Pydantic).
+Definir validações extras para tipos de dados usando valores "padrão" de atributos dos modelos. Isso melhora o suporte do editor, e não estava disponível no Pydantic antes.
+
+Isso na verdade inspirou a atualização de partes do Pydantic, para dar suporte ao mesmo estilo de declaração da validação (toda essa funcionalidade já está disponível no Pydantic).
+
+///
### <a href="https://www.hug.rest/" class="external-link" target="_blank">Hug</a>
Como é baseado nos padrões anteriores de frameworks web síncronos (WSGI), ele não pode controlar _Websockets_ e outras coisas, embora ele ainda tenha uma alta performance também.
-!!! info
- Hug foi criado por Timothy Crosley, o mesmo criador do <a href="https://github.com/timothycrosley/isort" class="external-link" target="_blank">`isort`</a>, uma grande ferramenta para ordenação automática de _imports_ em arquivos Python.
+/// info
+
+Hug foi criado por Timothy Crosley, o mesmo criador do <a href="https://github.com/timothycrosley/isort" class="external-link" target="_blank">`isort`</a>, uma grande ferramenta para ordenação automática de _imports_ em arquivos Python.
+
+///
+
+/// check | "Idéias inspiradas para o **FastAPI**"
+
+Hug inspirou partes do APIStar, e foi uma das ferramentas que eu achei mais promissora, ao lado do APIStar.
-!!! check "Idéias inspiradas para o **FastAPI**"
- Hug inspirou partes do APIStar, e foi uma das ferramentas que eu achei mais promissora, ao lado do APIStar.
+Hug ajudou a inspirar o **FastAPI** a usar _type hints_ do Python para declarar parâmetros, e para gerar um _schema_ definindo a API automaticamente.
- Hug ajudou a inspirar o **FastAPI** a usar _type hints_ do Python para declarar parâmetros, e para gerar um _schema_ definindo a API automaticamente.
+Hug inspirou **FastAPI** a declarar um parâmetro de `resposta` em funções para definir cabeçalhos e cookies.
- Hug inspirou **FastAPI** a declarar um parâmetro de `resposta` em funções para definir cabeçalhos e cookies.
+///
### <a href="https://github.com/encode/apistar" class="external-link" target="_blank">APIStar</a> (<= 0.5)
Agora APIStar é um conjunto de ferramentas para validar especificações OpenAPI, não um framework web.
-!!! info
- APIStar foi criado por Tom Christie. O mesmo cara que criou:
+/// info
- * Django REST Framework
- * Starlette (no qual **FastAPI** é baseado)
- * Uvicorn (usado por Starlette e **FastAPI**)
+APIStar foi criado por Tom Christie. O mesmo cara que criou:
-!!! check "**FastAPI** inspirado para"
- Existir.
+* Django REST Framework
+* Starlette (no qual **FastAPI** é baseado)
+* Uvicorn (usado por Starlette e **FastAPI**)
- A idéia de declarar múltiplas coisas (validação de dados, serialização e documentação) com os mesmos tipos Python, que ao mesmo tempo fornecesse grande suporte ao editor, era algo que eu considerava uma brilhante idéia.
+///
- E após procurar por um logo tempo por um framework similar e testar muitas alternativas diferentes, APIStar foi a melhor opção disponível.
+/// check | "**FastAPI** inspirado para"
- Então APIStar parou de existir como um servidor e Starlette foi criado, e foi uma nova melhor fundação para tal sistema. Essa foi a inspiração final para construir **FastAPI**.
+Existir.
- Eu considero **FastAPI** um "sucessor espiritual" para o APIStar, evoluindo e melhorando os recursos, sistema de tipagem e outras partes, baseado na aprendizagem de todas essas ferramentas acima.
+A idéia de declarar múltiplas coisas (validação de dados, serialização e documentação) com os mesmos tipos Python, que ao mesmo tempo fornecesse grande suporte ao editor, era algo que eu considerava uma brilhante idéia.
+
+E após procurar por um logo tempo por um framework similar e testar muitas alternativas diferentes, APIStar foi a melhor opção disponível.
+
+Então APIStar parou de existir como um servidor e Starlette foi criado, e foi uma nova melhor fundação para tal sistema. Essa foi a inspiração final para construir **FastAPI**.
+
+Eu considero **FastAPI** um "sucessor espiritual" para o APIStar, evoluindo e melhorando os recursos, sistema de tipagem e outras partes, baseado na aprendizagem de todas essas ferramentas acima.
+
+///
## Usados por **FastAPI**
Ele é comparável ao Marshmallow. Embora ele seja mais rápido que Marshmallow em testes de performance. E ele é baseado nos mesmos Python _type hints_, o suporte ao editor é ótimo.
-!!! check "**FastAPI** usa isso para"
- Controlar toda a validação de dados, serialização de dados e modelo de documentação automática (baseado no JSON Schema).
+/// check | "**FastAPI** usa isso para"
+
+Controlar toda a validação de dados, serialização de dados e modelo de documentação automática (baseado no JSON Schema).
+
+**FastAPI** então pega dados do JSON Schema e coloca eles no OpenAPI, à parte de todas as outras coisas que ele faz.
- **FastAPI** então pega dados do JSON Schema e coloca eles no OpenAPI, à parte de todas as outras coisas que ele faz.
+///
### <a href="https://www.starlette.io/" class="external-link" target="_blank">Starlette</a>
Essa é uma das principais coisas que **FastAPI** adiciona no topo, tudo baseado em Python _type hints_ (usando Pydantic). Isso, mais o sistema de injeção de dependência, utilidades de segurança, geração de _schema_ OpenAPI, etc.
-!!! note "Detalhes Técnicos"
- ASGI é um novo "padrão" sendo desenvolvido pelos membros do time central do Django. Ele ainda não está como "Padrão Python" (PEP), embora eles estejam em processo de fazer isso.
+/// note | "Detalhes Técnicos"
- No entanto, ele já está sendo utilizado como "padrão" por diversas ferramentas. Isso melhora enormemente a interoperabilidade, como você poderia trocar Uvicorn por qualquer outro servidor ASGI (como Daphne ou Hypercorn), ou você poderia adicionar ferramentas compatíveis com ASGI, como `python-socketio`.
+ASGI é um novo "padrão" sendo desenvolvido pelos membros do time central do Django. Ele ainda não está como "Padrão Python" (PEP), embora eles estejam em processo de fazer isso.
-!!! check "**FastAPI** usa isso para"
- Controlar todas as partes web centrais. Adiciona recursos no topo.
+No entanto, ele já está sendo utilizado como "padrão" por diversas ferramentas. Isso melhora enormemente a interoperabilidade, como você poderia trocar Uvicorn por qualquer outro servidor ASGI (como Daphne ou Hypercorn), ou você poderia adicionar ferramentas compatíveis com ASGI, como `python-socketio`.
- A classe `FastAPI` em si herda `Starlette`.
+///
- Então, qualquer coisa que você faz com Starlette, você pode fazer diretamente com **FastAPI**, pois ele é basicamente um Starlette com esteróides.
+/// check | "**FastAPI** usa isso para"
+
+Controlar todas as partes web centrais. Adiciona recursos no topo.
+
+A classe `FastAPI` em si herda `Starlette`.
+
+Então, qualquer coisa que você faz com Starlette, você pode fazer diretamente com **FastAPI**, pois ele é basicamente um Starlette com esteróides.
+
+///
### <a href="https://www.uvicorn.org/" class="external-link" target="_blank">Uvicorn</a>
Ele é o servidor recomendado para Starlette e **FastAPI**.
-!!! check "**FastAPI** recomenda isso para"
- O principal servidor web para rodar aplicações **FastAPI**.
+/// check | "**FastAPI** recomenda isso para"
+
+O principal servidor web para rodar aplicações **FastAPI**.
+
+Você pode combinar ele com o Gunicorn, para ter um servidor multi-processos assíncrono.
- Você pode combinar ele com o Gunicorn, para ter um servidor multi-processos assíncrono.
+Verifique mais detalhes na seção [Deployment](deployment/index.md){.internal-link target=_blank}.
- Verifique mais detalhes na seção [Deployment](deployment/index.md){.internal-link target=_blank}.
+///
## Performance e velocidade
return results
```
-!!! note
- Você só pode usar `await` dentro de funções criadas com `async def`.
+/// note
+
+Você só pode usar `await` dentro de funções criadas com `async def`.
+
+///
---
## Detalhes muito técnicos
-!!! warning
- Você pode provavelmente pular isso.
+/// warning
+
+Você pode provavelmente pular isso.
+
+Esses são detalhes muito técnicos de como **FastAPI** funciona por baixo do capô.
- Esses são detalhes muito técnicos de como **FastAPI** funciona por baixo do capô.
+Se você tem algum conhecimento técnico (corrotinas, threads, blocking etc) e está curioso sobre como o FastAPI controla o `async def` vs normal `def`, vá em frente.
- Se você tem algum conhecimento técnico (corrotinas, threads, blocking etc) e está curioso sobre como o FastAPI controla o `async def` vs normal `def`, vá em frente.
+///
### Funções de operação de rota
Ative o novo ambiente com:
-=== "Linux, macOS"
+//// tab | Linux, macOS
- <div class="termy">
+<div class="termy">
- ```console
- $ source ./env/bin/activate
- ```
+```console
+$ source ./env/bin/activate
+```
- </div>
+</div>
-=== "Windows PowerShell"
+////
- <div class="termy">
+//// tab | Windows PowerShell
- ```console
- $ .\env\Scripts\Activate.ps1
- ```
+<div class="termy">
- </div>
+```console
+$ .\env\Scripts\Activate.ps1
+```
-=== "Windows Bash"
+</div>
- Ou se você usa Bash para Windows (por exemplo <a href="https://gitforwindows.org/" class="external-link" target="_blank">Git Bash</a>):
+////
- <div class="termy">
+//// tab | Windows Bash
- ```console
- $ source ./env/Scripts/activate
- ```
+Ou se você usa Bash para Windows (por exemplo <a href="https://gitforwindows.org/" class="external-link" target="_blank">Git Bash</a>):
- </div>
+<div class="termy">
+
+```console
+$ source ./env/Scripts/activate
+```
+
+</div>
+
+////
Para verificar se funcionou, use:
-=== "Linux, macOS, Windows Bash"
+//// tab | Linux, macOS, Windows Bash
- <div class="termy">
+<div class="termy">
- ```console
- $ which pip
+```console
+$ which pip
- some/directory/fastapi/env/bin/pip
- ```
+some/directory/fastapi/env/bin/pip
+```
- </div>
+</div>
-=== "Windows PowerShell"
+////
- <div class="termy">
+//// tab | Windows PowerShell
- ```console
- $ Get-Command pip
+<div class="termy">
- some/directory/fastapi/env/bin/pip
- ```
+```console
+$ Get-Command pip
- </div>
+some/directory/fastapi/env/bin/pip
+```
+
+</div>
+
+////
Se ele exibir o binário `pip` em `env/bin/pip` então funcionou. 🎉
-!!! tip
- Toda vez que você instalar um novo pacote com `pip` nesse ambiente, ative o ambiente novamente.
+/// tip
+
+Toda vez que você instalar um novo pacote com `pip` nesse ambiente, ative o ambiente novamente.
- Isso garante que se você usar um programa instalado por aquele pacote, você utilizará aquele de seu ambiente local e não outro que possa estar instalado globalmente.
+Isso garante que se você usar um programa instalado por aquele pacote, você utilizará aquele de seu ambiente local e não outro que possa estar instalado globalmente.
+
+///
### pip
E existem ferramentas/_scripts_ extras para controlar as traduções em `./scripts/docs.py`.
-!!! tip
- Você não precisa ver o código em `./scripts/docs.py`, você apenas o utiliza na linha de comando.
+/// tip
+
+Você não precisa ver o código em `./scripts/docs.py`, você apenas o utiliza na linha de comando.
+
+///
Toda a documentação está no formato Markdown no diretório `./docs/pt/`.
* Verifique sempre os <a href="https://github.com/fastapi/fastapi/pulls" class="external-link" target="_blank">_pull requests_ existentes</a> para a sua linguagem e faça revisões das alterações e aprove elas.
-!!! tip
- Você pode <a href="https://help.github.com/en/github/collaborating-with-issues-and-pull-requests/commenting-on-a-pull-request" class="external-link" target="_blank">adicionar comentários com sugestões de alterações</a> para _pull requests_ existentes.
+/// tip
+
+Você pode <a href="https://help.github.com/en/github/collaborating-with-issues-and-pull-requests/commenting-on-a-pull-request" class="external-link" target="_blank">adicionar comentários com sugestões de alterações</a> para _pull requests_ existentes.
+
+Verifique as documentações sobre <a href="https://help.github.com/en/github/collaborating-with-issues-and-pull-requests/about-pull-request-reviews" class="external-link" target="_blank">adicionar revisão ao _pull request_</a> para aprovação ou solicitação de alterações.
- Verifique as documentações sobre <a href="https://help.github.com/en/github/collaborating-with-issues-and-pull-requests/about-pull-request-reviews" class="external-link" target="_blank">adicionar revisão ao _pull request_</a> para aprovação ou solicitação de alterações.
+///
* Verifique em <a href="https://github.com/fastapi/fastapi/issues" class="external-link" target="_blank">_issues_</a> para ver se existe alguém coordenando traduções para a sua linguagem.
No caso do Espanhol, o código de duas letras é `es`. Então, o diretório para traduções em Espanhol está localizada em `docs/es/`.
-!!! tip
- A principal ("oficial") linguagem é o Inglês, localizado em `docs/en/`.
+/// tip
+
+A principal ("oficial") linguagem é o Inglês, localizado em `docs/en/`.
+
+///
Agora rode o _servidor ao vivo_ para as documentações em Espanhol:
docs/es/docs/features.md
```
-!!! tip
- Observe que a única mudança na rota é o código da linguagem, de `en` para `es`.
+/// tip
+
+Observe que a única mudança na rota é o código da linguagem, de `en` para `es`.
+
+///
* Agora abra o arquivo de configuração MkDocs para Inglês em:
Agora você pode verificar em seu editor de código o mais novo diretório criado `docs/ht/`.
-!!! tip
- Crie um primeiro _pull request_ com apenas isso, para iniciar a configuração da nova linguagem, antes de adicionar traduções.
+/// tip
+
+Crie um primeiro _pull request_ com apenas isso, para iniciar a configuração da nova linguagem, antes de adicionar traduções.
+
+Desse modo outros poderão ajudar com outras páginas enquanto você trabalha na primeira. 🚀
- Desse modo outros poderão ajudar com outras páginas enquanto você trabalha na primeira. 🚀
+///
Inicie traduzindo a página principal, `docs/ht/index.md`.
FastAPI também segue a convenção que qualquer versão de _"PATCH"_ seja para ajustes de _bugs_ e mudanças que não quebrem a aplicação.
-!!! tip
- O _"PATCH"_ é o último número, por exemplo, em `0.2.3`, a versão do _PATCH_ é `3`.
+/// tip
+
+O _"PATCH"_ é o último número, por exemplo, em `0.2.3`, a versão do _PATCH_ é `3`.
+
+///
Então, você poderia ser capaz de fixar para uma versão como:
Mudanças que quebram e novos recursos são adicionados em versões _"MINOR"_.
-!!! tip
- O _"MINOR"_ é o número do meio, por exemplo, em `0.2.3`, a versão _MINOR_ é `2`.
+/// tip
+
+O _"MINOR"_ é o número do meio, por exemplo, em `0.2.3`, a versão _MINOR_ é `2`.
+
+///
### Atualizando as versões FastAPI
Mas você pode ainda mudar e atualizar todas as configurações com variáveis de ambiente ou arquivos de configuração.
-!!! tip
- Para ver todas as configurações e opções, vá para a página da imagem do Docker: <a href="https://github.com/tiangolo/uvicorn-gunicorn-fastapi-docker" class="external-link" target="_blank">tiangolo/uvicorn-gunicorn-fastapi</a>.
+/// tip
+
+Para ver todas as configurações e opções, vá para a página da imagem do Docker: <a href="https://github.com/tiangolo/uvicorn-gunicorn-fastapi-docker" class="external-link" target="_blank">tiangolo/uvicorn-gunicorn-fastapi</a>.
+
+///
### Crie um `Dockerfile`
Mas ele é um pouquinho mais complexo do que isso.
-!!! tip
- Se você está com pressa ou não se importa, continue na próxima seção com instruções passo a passo para configurar tudo.
+/// tip
+
+Se você está com pressa ou não se importa, continue na próxima seção com instruções passo a passo para configurar tudo.
+
+///
Para aprender o básico de HTTPS, pela perspectiva de um consumidor, verifique <a href="https://howhttps.works/" class="external-link" target="_blank">https://howhttps.works/</a>.
Você apenas precisa instalar um servidor ASGI compatível como:
-=== "Uvicorn"
+//// tab | Uvicorn
- * <a href="https://www.uvicorn.org/" class="external-link" target="_blank">Uvicorn</a>, um servidor ASGI peso leve, construído sobre uvloop e httptools.
+* <a href="https://www.uvicorn.org/" class="external-link" target="_blank">Uvicorn</a>, um servidor ASGI peso leve, construído sobre uvloop e httptools.
- <div class="termy">
+<div class="termy">
+
+```console
+$ pip install "uvicorn[standard]"
- ```console
- $ pip install "uvicorn[standard]"
+---> 100%
+```
+
+</div>
- ---> 100%
- ```
+////
- </div>
+//// tab | Hypercorn
-=== "Hypercorn"
+* <a href="https://github.com/pgjones/hypercorn" class="external-link" target="_blank">Hypercorn</a>, um servidor ASGI também compatível com HTTP/2.
- * <a href="https://github.com/pgjones/hypercorn" class="external-link" target="_blank">Hypercorn</a>, um servidor ASGI também compatível com HTTP/2.
+<div class="termy">
- <div class="termy">
+```console
+$ pip install hypercorn
- ```console
- $ pip install hypercorn
+---> 100%
+```
- ---> 100%
- ```
+</div>
- </div>
+...ou qualquer outro servidor ASGI.
- ...ou qualquer outro servidor ASGI.
+////
E rode sua applicação do mesmo modo que você tem feito nos tutoriais, mas sem a opção `--reload`, por exemplo:
-=== "Uvicorn"
+//// tab | Uvicorn
- <div class="termy">
+<div class="termy">
- ```console
- $ uvicorn main:app --host 0.0.0.0 --port 80
+```console
+$ uvicorn main:app --host 0.0.0.0 --port 80
- <span style="color: green;">INFO</span>: Uvicorn running on http://0.0.0.0:80 (Press CTRL+C to quit)
- ```
+<span style="color: green;">INFO</span>: Uvicorn running on http://0.0.0.0:80 (Press CTRL+C to quit)
+```
- </div>
+</div>
+
+////
-=== "Hypercorn"
+//// tab | Hypercorn
- <div class="termy">
+<div class="termy">
- ```console
- $ hypercorn main:app --bind 0.0.0.0:80
+```console
+$ hypercorn main:app --bind 0.0.0.0:80
- Running on 0.0.0.0:8080 over http (CTRL + C to quit)
- ```
+Running on 0.0.0.0:8080 over http (CTRL + C to quit)
+```
+
+</div>
- </div>
+////
Você deve querer configurar mais algumas ferramentas para ter certeza que ele seja reinicializado automaticamante se ele parar.
Usando contêineres Linux você tem diversas vantagens incluindo **segurança**, **replicabilidade**, **simplicidade**, entre outras.
-!!! tip "Dica"
- Está com pressa e já sabe dessas coisas? Pode ir direto para [`Dockerfile` abaixo 👇](#construindo-uma-imagem-docker-para-fastapi).
+/// tip | "Dica"
+Está com pressa e já sabe dessas coisas? Pode ir direto para [`Dockerfile` abaixo 👇](#construindo-uma-imagem-docker-para-fastapi).
+
+///
<details>
<summary>Visualização do Dockerfile 👀</summary>
</div>
-!!! info
- Há outros formatos e ferramentas para definir e instalar dependências de pacote.
+/// info
+
+Há outros formatos e ferramentas para definir e instalar dependências de pacote.
+
+Eu vou mostrar um exemplo depois usando Poetry em uma seção abaixo. 👇
- Eu vou mostrar um exemplo depois usando Poetry em uma seção abaixo. 👇
+///
### Criando o Código do **FastAPI**
Porque o programa será iniciado em `/code` e dentro dele está o diretório `./app` com seu código, o **Uvicorn** será capaz de ver e **importar** `app` de `app.main`.
-!!! tip
- Revise o que cada linha faz clicando em cada bolha com o número no código. 👆
+/// tip
+
+Revise o que cada linha faz clicando em cada bolha com o número no código. 👆
+
+///
Agora você deve ter uma estrutura de diretório como:
</div>
-!!! tip
- Note o `.` no final, é equivalente a `./`, ele diz ao Docker o diretório a ser usado para construir a imagem do contêiner.
+/// tip
- Nesse caso, é o mesmo diretório atual (`.`).
+Note o `.` no final, é equivalente a `./`, ele diz ao Docker o diretório a ser usado para construir a imagem do contêiner.
+
+Nesse caso, é o mesmo diretório atual (`.`).
+
+///
### Inicie o contêiner Docker
Isso poderia ser outro contêiner, por exemplo, com <a href="https://traefik.io/" class="external-link" target="_blank">Traefik</a>, lidando com **HTTPS** e aquisição **automática** de **certificados**.
-!!! tip
- Traefik tem integrações com Docker, Kubernetes e outros, portanto, é muito fácil configurar e configurar o HTTPS para seus contêineres com ele.
+/// tip
+
+Traefik tem integrações com Docker, Kubernetes e outros, portanto, é muito fácil configurar e configurar o HTTPS para seus contêineres com ele.
+
+///
Alternativamente, o HTTPS poderia ser tratado por um provedor de nuvem como um de seus serviços (enquanto ainda executasse o aplicativo em um contêiner).
Como esse componente assumiria a **carga** de solicitações e distribuiria isso entre os trabalhadores de uma maneira (esperançosamente) **balanceada**, ele também é comumente chamado de **Balanceador de Carga**.
-!!! tip
- O mesmo componente **Proxy de Terminação TLS** usado para HTTPS provavelmente também seria um **Balanceador de Carga**.
+/// tip
+
+O mesmo componente **Proxy de Terminação TLS** usado para HTTPS provavelmente também seria um **Balanceador de Carga**.
+
+///
E quando trabalhar com contêineres, o mesmo sistema que você usa para iniciar e gerenciá-los já terá ferramentas internas para transmitir a **comunicação de rede** (por exemplo, solicitações HTTP) do **balanceador de carga** (que também pode ser um **Proxy de Terminação TLS**) para o(s) contêiner(es) com seu aplicativo.
Se você tiver **múltiplos contêineres**, provavelmente cada um executando um **único processo** (por exemplo, em um cluster do **Kubernetes**), então provavelmente você gostaria de ter um **contêiner separado** fazendo o trabalho dos **passos anteriores** em um único contêiner, executando um único processo, **antes** de executar os contêineres trabalhadores replicados.
-!!! info
- Se você estiver usando o Kubernetes, provavelmente será um <a href="https://kubernetes.io/docs/concepts/workloads/pods/init-containers/" class="external-link" target="_blank">Init Container</a>.
+/// info
+
+Se você estiver usando o Kubernetes, provavelmente será um <a href="https://kubernetes.io/docs/concepts/workloads/pods/init-containers/" class="external-link" target="_blank">Init Container</a>.
+
+///
Se no seu caso de uso não houver problema em executar esses passos anteriores **em paralelo várias vezes** (por exemplo, se você não estiver executando migrações de banco de dados, mas apenas verificando se o banco de dados está pronto), então você também pode colocá-los em cada contêiner logo antes de iniciar o processo principal.
* <a href="https://github.com/tiangolo/uvicorn-gunicorn-fastapi-docker" class="external-link" target="_blank">tiangolo/uvicorn-gunicorn-fastapi</a>.
-!!! warning
- Existe uma grande chance de que você **não** precise dessa imagem base ou de qualquer outra semelhante, e seria melhor construir a imagem do zero, como [descrito acima em: Construa uma Imagem Docker para o FastAPI](#construindo-uma-imagem-docker-para-fastapi).
+/// warning
+
+Existe uma grande chance de que você **não** precise dessa imagem base ou de qualquer outra semelhante, e seria melhor construir a imagem do zero, como [descrito acima em: Construa uma Imagem Docker para o FastAPI](#construindo-uma-imagem-docker-para-fastapi).
+
+///
Essa imagem tem um mecanismo de **auto-ajuste** incluído para definir o **número de processos trabalhadores** com base nos núcleos de CPU disponíveis.
Há também suporte para executar <a href="https://github.com/tiangolo/uvicorn-gunicorn-fastapi-docker#pre_start_path" class="external-link" target="_blank">**passos anteriores antes de iniciar**</a> com um script.
-!!! tip
- Para ver todas as configurações e opções, vá para a página da imagem Docker: <a href="https://github.com/tiangolo/uvicorn-gunicorn-fastapi-docker" class="external-link" target="_blank">tiangolo/uvicorn-gunicorn-fastapi</a>.
+/// tip
+
+Para ver todas as configurações e opções, vá para a página da imagem Docker: <a href="https://github.com/tiangolo/uvicorn-gunicorn-fastapi-docker" class="external-link" target="_blank">tiangolo/uvicorn-gunicorn-fastapi</a>.
+
+///
### Número de Processos na Imagem Oficial do Docker
11. Execute o comando `uvicorn`, informando-o para usar o objeto `app` importado de `app.main`.
-!!! tip
- Clique nos números das bolhas para ver o que cada linha faz.
+/// tip
+
+Clique nos números das bolhas para ver o que cada linha faz.
+
+///
Um **estágio do Docker** é uma parte de um `Dockerfile` que funciona como uma **imagem temporária do contêiner** que só é usada para gerar alguns arquivos para serem usados posteriormente.
Mas é bem mais complexo do que isso.
-!!! tip "Dica"
- Se você está com pressa ou não se importa, continue com as seções seguintes para instruções passo a passo para configurar tudo com diferentes técnicas.
+/// tip | "Dica"
+
+Se você está com pressa ou não se importa, continue com as seções seguintes para instruções passo a passo para configurar tudo com diferentes técnicas.
+
+///
Para aprender o básico de HTTPS de uma perspectiva do usuário, verifique <a href="https://howhttps.works/pt-br/" class="external-link" target="_blank">https://howhttps.works/pt-br/</a>.
FastAPI também segue a convenção de que qualquer alteração de versão "PATCH" é para correção de bugs e alterações não significativas.
-!!! tip "Dica"
- O "PATCH" é o último número, por exemplo, em `0.2.3`, a versão PATCH é `3`.
+/// tip | "Dica"
+
+O "PATCH" é o último número, por exemplo, em `0.2.3`, a versão PATCH é `3`.
+
+///
Logo, você deveria conseguir fixar a versão, como:
Mudanças significativas e novos recursos são adicionados em versões "MINOR".
-!!! tip "Dica"
- O "MINOR" é o número que está no meio, por exemplo, em `0.2.3`, a versão MINOR é `2`.
+/// tip | "Dica"
+
+O "MINOR" é o número que está no meio, por exemplo, em `0.2.3`, a versão MINOR é `2`.
+
+///
## Atualizando as versões do FastAPI
Aqui tem uma lista, incompleta, de algumas delas.
-!!! tip "Dica"
- Se você tem um artigo, projeto, ferramenta ou qualquer coisa relacionada ao **FastAPI** que ainda não está listada aqui, crie um <a href="https://github.com/fastapi/fastapi/edit/master/docs/external-links.md" class="external-link" target="_blank">_Pull Request_ adicionando ele</a>.
+/// tip | "Dica"
+
+Se você tem um artigo, projeto, ferramenta ou qualquer coisa relacionada ao **FastAPI** que ainda não está listada aqui, crie um <a href="https://github.com/fastapi/fastapi/edit/master/docs/external-links.md" class="external-link" target="_blank">_Pull Request_ adicionando ele</a>.
+
+///
{% for section_name, section_content in external_links.items() %}
Em muitos casos você pode ter (e deveria ter) um "proxy de saída" tratando HTTPS no topo, isso dependerá de como você fará o deploy da sua aplicação, seu provedor pode fazer isso pra você ou talvez seja necessário fazer você mesmo.
-!!! tip
- Você pode aprender mais sobre em [documentação de deployment](deployment/index.md){.internal-link target=_blank}.
+/// tip
+
+Você pode aprender mais sobre em [documentação de deployment](deployment/index.md){.internal-link target=_blank}.
+
+///
my_second_user: User = User(**second_user_data)
```
-!!! info
- `**second_user_data` quer dizer:
+/// info
- Passe as chaves e valores do dicionário `second_user_data` diretamente como argumentos chave-valor, equivalente a: `User(id=4, name="Mary", joined="2018-11-30")`
+`**second_user_data` quer dizer:
+
+Passe as chaves e valores do dicionário `second_user_data` diretamente como argumentos chave-valor, equivalente a: `User(id=4, name="Mary", joined="2018-11-30")`
+
+///
### Suporte de editores
Entre no 👥 <a href="https://discord.gg/VQjSZaeJmf" class="external-link" target="_blank">server de conversa do Discord</a> 👥 e conheça novas pessoas da comunidade
do FastAPI.
-!!! tip "Dica"
- Para perguntas, pergunte nas <a href="https://github.com/fastapi/fastapi/issues/new/choose" class="external-link" target="_blank">questões do GitHub</a>, lá tem um chance maior de você ser ajudado sobre o FastAPI [FastAPI Experts](fastapi-people.md#especialistas){.internal-link target=_blank}.
+/// tip | "Dica"
- Use o chat apenas para outro tipo de assunto.
+Para perguntas, pergunte nas <a href="https://github.com/fastapi/fastapi/issues/new/choose" class="external-link" target="_blank">questões do GitHub</a>, lá tem um chance maior de você ser ajudado sobre o FastAPI [FastAPI Experts](fastapi-people.md#especialistas){.internal-link target=_blank}.
+
+Use o chat apenas para outro tipo de assunto.
+
+///
### Não faça perguntas no chat
Se algo parecer interessante e útil para o seu projeto, vá em frente e dê uma olhada. Caso contrário, você pode simplesmente ignorá-lo.
-!!! tip
+/// tip
- Se você deseja **aprender FastAPI** de forma estruturada (recomendado), leia capítulo por capítulo [Tutorial - Guia de Usuário](../tutorial/index.md){.internal-link target=_blank} em vez disso.
+Se você deseja **aprender FastAPI** de forma estruturada (recomendado), leia capítulo por capítulo [Tutorial - Guia de Usuário](../tutorial/index.md){.internal-link target=_blank} em vez disso.
+
+///
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
{!../../../docs_src/python_types/tutorial006.py!}
```
-!!! tip "Dica"
- Esses tipos internos entre colchetes são chamados de "parâmetros de tipo".
+/// tip | "Dica"
+
+Esses tipos internos entre colchetes são chamados de "parâmetros de tipo".
- Nesse caso, `str` é o parâmetro de tipo passado para `List`.
+Nesse caso, `str` é o parâmetro de tipo passado para `List`.
+
+///
Isso significa que: "a variável `items` é uma `list`, e cada um dos itens desta lista é uma `str`".
{!../../../docs_src/python_types/tutorial011.py!}
```
-!!! info "Informação"
- Para saber mais sobre o <a href="https://docs.pydantic.dev/" class="external-link" target="_blank"> Pydantic, verifique seus documentos </a>.
+/// info | "Informação"
+
+Para saber mais sobre o <a href="https://docs.pydantic.dev/" class="external-link" target="_blank"> Pydantic, verifique seus documentos </a>.
+
+///
**FastAPI** é todo baseado em Pydantic.
O importante é que, usando tipos padrão de Python, em um único local (em vez de adicionar mais classes, decoradores, etc.), o **FastAPI** fará muito trabalho para você.
-!!! info "Informação"
- Se você já passou por todo o tutorial e voltou para ver mais sobre os tipos, um bom recurso é <a href = "https://mypy.readthedocs.io/en/latest/cheat_sheet_py3.html" class = "external-link "target =" _ blank "> a "cheat sheet" do `mypy` </a>.
+/// info | "Informação"
+
+Se você já passou por todo o tutorial e voltou para ver mais sobre os tipos, um bom recurso é <a href = "https://mypy.readthedocs.io/en/latest/cheat_sheet_py3.html" class = "external-link "target =" _ blank "> a "cheat sheet" do `mypy` </a>.
+
+///
{!../../../docs_src/body_fields/tutorial001.py!}
```
-!!! warning "Aviso"
- Note que `Field` é importado diretamente do `pydantic`, não do `fastapi` como todo o resto (`Query`, `Path`, `Body`, etc).
+/// warning | "Aviso"
+
+Note que `Field` é importado diretamente do `pydantic`, não do `fastapi` como todo o resto (`Query`, `Path`, `Body`, etc).
+
+///
## Declare atributos do modelo
`Field` funciona da mesma forma que `Query`, `Path` e `Body`, ele possui todos os mesmos parâmetros, etc.
-!!! note "Detalhes técnicos"
- Na realidade, `Query`, `Path` e outros que você verá em seguida, criam objetos de subclasses de uma classe `Param` comum, que é ela mesma uma subclasse da classe `FieldInfo` do Pydantic.
+/// note | "Detalhes técnicos"
+
+Na realidade, `Query`, `Path` e outros que você verá em seguida, criam objetos de subclasses de uma classe `Param` comum, que é ela mesma uma subclasse da classe `FieldInfo` do Pydantic.
+
+E `Field` do Pydantic retorna uma instância de `FieldInfo` também.
+
+`Body` também retorna objetos de uma subclasse de `FieldInfo` diretamente. E tem outras que você verá mais tarde que são subclasses da classe `Body`.
+
+Lembre-se que quando você importa `Query`, `Path`, e outros de `fastapi`, esse são na realidade funções que retornam classes especiais.
- E `Field` do Pydantic retorna uma instância de `FieldInfo` também.
+///
- `Body` também retorna objetos de uma subclasse de `FieldInfo` diretamente. E tem outras que você verá mais tarde que são subclasses da classe `Body`.
+/// tip | "Dica"
- Lembre-se que quando você importa `Query`, `Path`, e outros de `fastapi`, esse são na realidade funções que retornam classes especiais.
+Note como cada atributo do modelo com um tipo, valor padrão e `Field` possuem a mesma estrutura que parâmetros de *funções de operações de rota*, com `Field` ao invés de `Path`, `Query` e `Body`.
-!!! tip "Dica"
- Note como cada atributo do modelo com um tipo, valor padrão e `Field` possuem a mesma estrutura que parâmetros de *funções de operações de rota*, com `Field` ao invés de `Path`, `Query` e `Body`.
+///
## Adicione informações extras
E você também pode declarar parâmetros de corpo como opcionais, definindo o valor padrão com `None`:
-=== "Python 3.10+"
+//// tab | Python 3.10+
- ```Python hl_lines="17-19"
- {!> ../../../docs_src/body_multiple_params/tutorial001_py310.py!}
- ```
+```Python hl_lines="17-19"
+{!> ../../../docs_src/body_multiple_params/tutorial001_py310.py!}
+```
+
+////
-=== "Python 3.8+"
+//// tab | Python 3.8+
+
+```Python hl_lines="19-21"
+{!> ../../../docs_src/body_multiple_params/tutorial001.py!}
+```
- ```Python hl_lines="19-21"
- {!> ../../../docs_src/body_multiple_params/tutorial001.py!}
- ```
+////
-!!! note "Nota"
- Repare que, neste caso, o `item` que seria capturado a partir do corpo é opcional. Visto que ele possui `None` como valor padrão.
+/// note | "Nota"
+
+Repare que, neste caso, o `item` que seria capturado a partir do corpo é opcional. Visto que ele possui `None` como valor padrão.
+
+///
## Múltiplos parâmetros de corpo
Mas você pode também declarar múltiplos parâmetros de corpo, por exemplo, `item` e `user`:
-=== "Python 3.10+"
+//// tab | Python 3.10+
- ```Python hl_lines="20"
- {!> ../../../docs_src/body_multiple_params/tutorial002_py310.py!}
- ```
+```Python hl_lines="20"
+{!> ../../../docs_src/body_multiple_params/tutorial002_py310.py!}
+```
-=== "Python 3.8+"
+////
- ```Python hl_lines="22"
- {!> ../../../docs_src/body_multiple_params/tutorial002.py!}
- ```
+//// tab | Python 3.8+
+
+```Python hl_lines="22"
+{!> ../../../docs_src/body_multiple_params/tutorial002.py!}
+```
+
+////
Neste caso, o **FastAPI** perceberá que existe mais de um parâmetro de corpo na função (dois parâmetros que são modelos Pydantic).
}
```
-!!! note "Nota"
- Repare que mesmo que o `item` esteja declarado da mesma maneira que antes, agora é esperado que ele esteja dentro do corpo com uma chave `item`.
+/// note | "Nota"
+Repare que mesmo que o `item` esteja declarado da mesma maneira que antes, agora é esperado que ele esteja dentro do corpo com uma chave `item`.
+
+///
O **FastAPI** fará a conversão automática a partir da requisição, assim esse parâmetro `item` receberá seu respectivo conteúdo e o mesmo ocorrerá com `user`.
Mas você pode instruir o **FastAPI** para tratá-lo como outra chave do corpo usando `Body`:
-=== "Python 3.8+"
+//// tab | Python 3.8+
- ```Python hl_lines="22"
- {!> ../../../docs_src/body_multiple_params/tutorial003.py!}
- ```
+```Python hl_lines="22"
+{!> ../../../docs_src/body_multiple_params/tutorial003.py!}
+```
-=== "Python 3.10+"
+////
- ```Python hl_lines="20"
- {!> ../../../docs_src/body_multiple_params/tutorial003_py310.py!}
- ```
+//// tab | Python 3.10+
+
+```Python hl_lines="20"
+{!> ../../../docs_src/body_multiple_params/tutorial003_py310.py!}
+```
+
+////
Neste caso, o **FastAPI** esperará um corpo como:
Por exemplo:
-=== "Python 3.10+"
+//// tab | Python 3.10+
+
+```Python hl_lines="26"
+{!> ../../../docs_src/body_multiple_params/tutorial004_py310.py!}
+```
+
+////
+
+//// tab | Python 3.8+
- ```Python hl_lines="26"
- {!> ../../../docs_src/body_multiple_params/tutorial004_py310.py!}
- ```
+```Python hl_lines="27"
+{!> ../../../docs_src/body_multiple_params/tutorial004.py!}
+```
+
+////
-=== "Python 3.8+"
+/// info | "Informação"
- ```Python hl_lines="27"
- {!> ../../../docs_src/body_multiple_params/tutorial004.py!}
- ```
+`Body` também possui todas as validações adicionais e metadados de parâmetros como em `Query`,`Path` e outras que você verá depois.
-!!! info "Informação"
- `Body` também possui todas as validações adicionais e metadados de parâmetros como em `Query`,`Path` e outras que você verá depois.
+///
## Declare um único parâmetro de corpo indicando sua chave
como em:
-=== "Python 3.10+"
+//// tab | Python 3.10+
+
+```Python hl_lines="15"
+{!> ../../../docs_src/body_multiple_params/tutorial005_py310.py!}
+```
+
+////
- ```Python hl_lines="15"
- {!> ../../../docs_src/body_multiple_params/tutorial005_py310.py!}
- ```
+//// tab | Python 3.8+
-=== "Python 3.8+"
+```Python hl_lines="17"
+{!> ../../../docs_src/body_multiple_params/tutorial005.py!}
+```
- ```Python hl_lines="17"
- {!> ../../../docs_src/body_multiple_params/tutorial005.py!}
- ```
+////
Neste caso o **FastAPI** esperará um corpo como:
}
```
-!!! info "informação"
- Note como o campo `images` agora tem uma lista de objetos de image.
+/// info | "informação"
+
+Note como o campo `images` agora tem uma lista de objetos de image.
+
+///
## Modelos profundamente aninhados
{!../../../docs_src/body_nested_models/tutorial007.py!}
```
-!!! info "informação"
- Note como `Offer` tem uma lista de `Item`s, que por sua vez possui opcionalmente uma lista `Image`s
+/// info | "informação"
+
+Note como `Offer` tem uma lista de `Item`s, que por sua vez possui opcionalmente uma lista `Image`s
+
+///
## Corpos de listas puras
{!../../../docs_src/body_nested_models/tutorial009.py!}
```
-!!! tip "Dica"
- Leve em condideração que o JSON só suporta `str` como chaves.
+/// tip | "Dica"
+
+Leve em condideração que o JSON só suporta `str` como chaves.
+
+Mas o Pydantic tem conversão automática de dados.
- Mas o Pydantic tem conversão automática de dados.
+Isso significa que, embora os clientes da API só possam enviar strings como chaves, desde que essas strings contenham inteiros puros, o Pydantic irá convertê-los e validá-los.
- Isso significa que, embora os clientes da API só possam enviar strings como chaves, desde que essas strings contenham inteiros puros, o Pydantic irá convertê-los e validá-los.
+E o `dict` que você recebe como `weights` terá, na verdade, chaves `int` e valores` float`.
- E o `dict` que você recebe como `weights` terá, na verdade, chaves `int` e valores` float`.
+///
## Recapitulação
Para declarar um corpo da **requisição**, você utiliza os modelos do <a href="https://docs.pydantic.dev/" class="external-link" target="_blank">Pydantic</a> com todos os seus poderes e benefícios.
-!!! info "Informação"
- Para enviar dados, você deve usar utilizar um dos métodos: `POST` (Mais comum), `PUT`, `DELETE` ou `PATCH`.
+/// info | "Informação"
- Enviar um corpo em uma requisição `GET` não tem um comportamento definido nas especificações, porém é suportado pelo FastAPI, apenas para casos de uso bem complexos/extremos.
+Para enviar dados, você deve usar utilizar um dos métodos: `POST` (Mais comum), `PUT`, `DELETE` ou `PATCH`.
- Como é desencorajado, a documentação interativa com Swagger UI não irá mostrar a documentação para o corpo da requisição para um `GET`, e proxies que intermediarem podem não suportar o corpo da requisição.
+Enviar um corpo em uma requisição `GET` não tem um comportamento definido nas especificações, porém é suportado pelo FastAPI, apenas para casos de uso bem complexos/extremos.
+
+Como é desencorajado, a documentação interativa com Swagger UI não irá mostrar a documentação para o corpo da requisição para um `GET`, e proxies que intermediarem podem não suportar o corpo da requisição.
+
+///
## Importe o `BaseModel` do Pydantic
<img src="/img/tutorial/body/image05.png">
-!!! tip "Dica"
- Se você utiliza o <a href="https://www.jetbrains.com/pycharm/" class="external-link" target="_blank">PyCharm</a> como editor, você pode utilizar o <a href="https://github.com/koxudaxi/pydantic-pycharm-plugin/" class="external-link" target="_blank">Plugin do Pydantic para o PyCharm </a>.
+/// tip | "Dica"
+
+Se você utiliza o <a href="https://www.jetbrains.com/pycharm/" class="external-link" target="_blank">PyCharm</a> como editor, você pode utilizar o <a href="https://github.com/koxudaxi/pydantic-pycharm-plugin/" class="external-link" target="_blank">Plugin do Pydantic para o PyCharm </a>.
- Melhora o suporte do editor para seus modelos Pydantic com::
+Melhora o suporte do editor para seus modelos Pydantic com::
- * completação automática
- * verificação de tipos
- * refatoração
- * buscas
- * inspeções
+* completação automática
+* verificação de tipos
+* refatoração
+* buscas
+* inspeções
+
+///
## Use o modelo
* Se o parâmetro é de um **tipo único** (como `int`, `float`, `str`, `bool`, etc) será interpretado como um parâmetro de **consulta**.
* Se o parâmetro é declarado como um **modelo Pydantic**, será interpretado como o **corpo** da requisição.
-!!! note "Observação"
- O FastAPI saberá que o valor de `q` não é obrigatório por causa do valor padrão `= None`.
+/// note | "Observação"
+
+O FastAPI saberá que o valor de `q` não é obrigatório por causa do valor padrão `= None`.
+
+O `Union` em `Union[str, None]` não é utilizado pelo FastAPI, mas permite ao seu editor de texto lhe dar um suporte melhor e detectar erros.
- O `Union` em `Union[str, None]` não é utilizado pelo FastAPI, mas permite ao seu editor de texto lhe dar um suporte melhor e detectar erros.
+///
## Sem o Pydantic
{!../../../docs_src/cookie_params/tutorial001.py!}
```
-!!! note "Detalhes Técnicos"
- `Cookie` é uma classe "irmã" de `Path` e `Query`. Ela também herda da mesma classe em comum `Param`.
+/// note | "Detalhes Técnicos"
- Mas lembre-se que quando você importa `Query`, `Path`, `Cookie` e outras de `fastapi`, elas são na verdade funções que retornam classes especiais.
+`Cookie` é uma classe "irmã" de `Path` e `Query`. Ela também herda da mesma classe em comum `Param`.
-!!! info "Informação"
- Para declarar cookies, você precisa usar `Cookie`, caso contrário, os parâmetros seriam interpretados como parâmetros de consulta.
+Mas lembre-se que quando você importa `Query`, `Path`, `Cookie` e outras de `fastapi`, elas são na verdade funções que retornam classes especiais.
+
+///
+
+/// info | "Informação"
+
+Para declarar cookies, você precisa usar `Cookie`, caso contrário, os parâmetros seriam interpretados como parâmetros de consulta.
+
+///
## Recapitulando
Para mais informações <abbr title="Cross-Origin Resource Sharing">CORS</abbr>, acesse <a href="https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS" class="external-link" target="_blank">Mozilla CORS documentation</a>.
-!!! note "Detalhes técnicos"
- Você também pode usar `from starlette.middleware.cors import CORSMiddleware`.
+/// note | "Detalhes técnicos"
- **FastAPI** fornece vários middlewares em `fastapi.middleware` apenas como uma conveniência para você, o desenvolvedor. Mas a maioria dos middlewares disponíveis vêm diretamente da Starlette.
+Você também pode usar `from starlette.middleware.cors import CORSMiddleware`.
+
+**FastAPI** fornece vários middlewares em `fastapi.middleware` apenas como uma conveniência para você, o desenvolvedor. Mas a maioria dos middlewares disponíveis vêm diretamente da Starlette.
+
+///
No exemplo anterior, nós retornávamos um `dict` da nossa dependência ("injetável"):
-=== "Python 3.10+"
+//// tab | Python 3.10+
- ```Python hl_lines="9"
- {!> ../../../docs_src/dependencies/tutorial001_an_py310.py!}
- ```
+```Python hl_lines="9"
+{!> ../../../docs_src/dependencies/tutorial001_an_py310.py!}
+```
+
+////
-=== "Python 3.9+"
+//// tab | Python 3.9+
- ```Python hl_lines="11"
- {!> ../../../docs_src/dependencies/tutorial001_an_py39.py!}
- ```
+```Python hl_lines="11"
+{!> ../../../docs_src/dependencies/tutorial001_an_py39.py!}
+```
-=== "Python 3.8+"
+////
- ```Python hl_lines="12"
- {!> ../../../docs_src/dependencies/tutorial001_an.py!}
- ```
+//// tab | Python 3.8+
+
+```Python hl_lines="12"
+{!> ../../../docs_src/dependencies/tutorial001_an.py!}
+```
-=== "Python 3.10+ non-Annotated"
+////
- !!! tip "Dica"
- Utilize a versão com `Annotated` se possível.
+//// tab | Python 3.10+ non-Annotated
- ```Python hl_lines="7"
- {!> ../../../docs_src/dependencies/tutorial001_py310.py!}
- ```
+/// tip | "Dica"
+
+Utilize a versão com `Annotated` se possível.
+
+///
+
+```Python hl_lines="7"
+{!> ../../../docs_src/dependencies/tutorial001_py310.py!}
+```
-=== "Python 3.8+ non-Annotated"
+////
- !!! tip "Dica"
- Utilize a versão com `Annotated` se possível.
+//// tab | Python 3.8+ non-Annotated
- ```Python hl_lines="11"
- {!> ../../../docs_src/dependencies/tutorial001.py!}
- ```
+/// tip | "Dica"
+
+Utilize a versão com `Annotated` se possível.
+
+///
+
+```Python hl_lines="11"
+{!> ../../../docs_src/dependencies/tutorial001.py!}
+```
+
+////
Mas assim obtemos um `dict` como valor do parâmetro `commons` na *função de operação de rota*.
Então, podemos mudar o "injetável" na dependência `common_parameters` acima para a classe `CommonQueryParams`:
-=== "Python 3.10+"
+//// tab | Python 3.10+
- ```Python hl_lines="11-15"
- {!> ../../../docs_src/dependencies/tutorial002_an_py310.py!}
- ```
+```Python hl_lines="11-15"
+{!> ../../../docs_src/dependencies/tutorial002_an_py310.py!}
+```
-=== "Python 3.9+"
+////
- ```Python hl_lines="11-15"
- {!> ../../../docs_src/dependencies/tutorial002_an_py39.py!}
- ```
+//// tab | Python 3.9+
-=== "Python 3.8+"
+```Python hl_lines="11-15"
+{!> ../../../docs_src/dependencies/tutorial002_an_py39.py!}
+```
- ```Python hl_lines="12-16"
- {!> ../../../docs_src/dependencies/tutorial002_an.py!}
- ```
+////
-=== "Python 3.10+ non-Annotated"
+//// tab | Python 3.8+
- !!! tip "Dica"
- Utilize a versão com `Annotated` se possível.
+```Python hl_lines="12-16"
+{!> ../../../docs_src/dependencies/tutorial002_an.py!}
+```
+////
- ```Python hl_lines="9-13"
- {!> ../../../docs_src/dependencies/tutorial002_py310.py!}
- ```
+//// tab | Python 3.10+ non-Annotated
-=== "Python 3.8+ non-Annotated"
+/// tip | "Dica"
- !!! tip "Dica"
- Utilize a versão com `Annotated` se possível.
+Utilize a versão com `Annotated` se possível.
+///
- ```Python hl_lines="11-15"
- {!> ../../../docs_src/dependencies/tutorial002.py!}
- ```
+```Python hl_lines="9-13"
+{!> ../../../docs_src/dependencies/tutorial002_py310.py!}
+```
+
+////
+
+//// tab | Python 3.8+ non-Annotated
+
+/// tip | "Dica"
+
+Utilize a versão com `Annotated` se possível.
+
+///
+
+```Python hl_lines="11-15"
+{!> ../../../docs_src/dependencies/tutorial002.py!}
+```
+
+////
Observe o método `__init__` usado para criar uma instância da classe:
-=== "Python 3.10+"
+//// tab | Python 3.10+
+
+```Python hl_lines="12"
+{!> ../../../docs_src/dependencies/tutorial002_an_py310.py!}
+```
+
+////
+
+//// tab | Python 3.9+
+
+```Python hl_lines="12"
+{!> ../../../docs_src/dependencies/tutorial002_an_py39.py!}
+```
+
+////
- ```Python hl_lines="12"
- {!> ../../../docs_src/dependencies/tutorial002_an_py310.py!}
- ```
+//// tab | Python 3.8+
-=== "Python 3.9+"
+```Python hl_lines="13"
+{!> ../../../docs_src/dependencies/tutorial002_an.py!}
+```
+
+////
- ```Python hl_lines="12"
- {!> ../../../docs_src/dependencies/tutorial002_an_py39.py!}
- ```
+//// tab | Python 3.10+ non-Annotated
-=== "Python 3.8+"
+/// tip | "Dica"
- ```Python hl_lines="13"
- {!> ../../../docs_src/dependencies/tutorial002_an.py!}
- ```
+Utilize a versão com `Annotated` se possível.
-=== "Python 3.10+ non-Annotated"
+///
- !!! tip "Dica"
- Utilize a versão com `Annotated` se possível.
+```Python hl_lines="10"
+{!> ../../../docs_src/dependencies/tutorial002_py310.py!}
+```
+////
- ```Python hl_lines="10"
- {!> ../../../docs_src/dependencies/tutorial002_py310.py!}
- ```
+//// tab | Python 3.8+ non-Annotated
-=== "Python 3.8+ non-Annotated"
+/// tip | "Dica"
- !!! tip "Dica"
- Utilize a versão com `Annotated` se possível.
+Utilize a versão com `Annotated` se possível.
+///
+
+```Python hl_lines="12"
+{!> ../../../docs_src/dependencies/tutorial002.py!}
+```
- ```Python hl_lines="12"
- {!> ../../../docs_src/dependencies/tutorial002.py!}
- ```
+////
...ele possui os mesmos parâmetros que nosso `common_parameters` anterior:
-=== "Python 3.10+"
+//// tab | Python 3.10+
- ```Python hl_lines="8"
- {!> ../../../docs_src/dependencies/tutorial001_an_py310.py!}
- ```
+```Python hl_lines="8"
+{!> ../../../docs_src/dependencies/tutorial001_an_py310.py!}
+```
+
+////
-=== "Python 3.9+"
+//// tab | Python 3.9+
- ```Python hl_lines="9"
- {!> ../../../docs_src/dependencies/tutorial001_an_py39.py!}
- ```
+```Python hl_lines="9"
+{!> ../../../docs_src/dependencies/tutorial001_an_py39.py!}
+```
-=== "Python 3.8+"
+////
- ```Python hl_lines="10"
- {!> ../../../docs_src/dependencies/tutorial001_an.py!}
- ```
+//// tab | Python 3.8+
-=== "Python 3.10+ non-Annotated"
+```Python hl_lines="10"
+{!> ../../../docs_src/dependencies/tutorial001_an.py!}
+```
- !!! tip "Dica"
- Utilize a versão com `Annotated` se possível.
+////
+//// tab | Python 3.10+ non-Annotated
- ```Python hl_lines="6"
- {!> ../../../docs_src/dependencies/tutorial001_py310.py!}
- ```
+/// tip | "Dica"
-=== "Python 3.8+ non-Annotated"
+Utilize a versão com `Annotated` se possível.
- !!! tip "Dica"
- Utilize a versão com `Annotated` se possível.
+///
+```Python hl_lines="6"
+{!> ../../../docs_src/dependencies/tutorial001_py310.py!}
+```
+
+////
+
+//// tab | Python 3.8+ non-Annotated
+
+/// tip | "Dica"
+
+Utilize a versão com `Annotated` se possível.
+
+///
+
+```Python hl_lines="9"
+{!> ../../../docs_src/dependencies/tutorial001.py!}
+```
- ```Python hl_lines="9"
- {!> ../../../docs_src/dependencies/tutorial001.py!}
- ```
+////
Esses parâmetros são utilizados pelo **FastAPI** para "definir" a dependência.
Agora você pode declarar sua dependência utilizando essa classe.
-=== "Python 3.10+"
+//// tab | Python 3.10+
- ```Python hl_lines="19"
- {!> ../../../docs_src/dependencies/tutorial002_an_py310.py!}
- ```
+```Python hl_lines="19"
+{!> ../../../docs_src/dependencies/tutorial002_an_py310.py!}
+```
+
+////
+
+//// tab | Python 3.9+
+
+```Python hl_lines="19"
+{!> ../../../docs_src/dependencies/tutorial002_an_py39.py!}
+```
+
+////
+
+//// tab | Python 3.8+
+
+```Python hl_lines="20"
+{!> ../../../docs_src/dependencies/tutorial002_an.py!}
+```
+
+////
-=== "Python 3.9+"
+//// tab | Python 3.10+ non-Annotated
- ```Python hl_lines="19"
- {!> ../../../docs_src/dependencies/tutorial002_an_py39.py!}
- ```
+/// tip | "Dica"
-=== "Python 3.8+"
+Utilize a versão com `Annotated` se possível.
- ```Python hl_lines="20"
- {!> ../../../docs_src/dependencies/tutorial002_an.py!}
- ```
+///
-=== "Python 3.10+ non-Annotated"
+```Python hl_lines="17"
+{!> ../../../docs_src/dependencies/tutorial002_py310.py!}
+```
- !!! tip "Dica"
- Utilize a versão com `Annotated` se possível.
+////
+//// tab | Python 3.8+ non-Annotated
- ```Python hl_lines="17"
- {!> ../../../docs_src/dependencies/tutorial002_py310.py!}
- ```
+/// tip | "Dica"
-=== "Python 3.8+ non-Annotated"
+Utilize a versão com `Annotated` se possível.
- !!! tip "Dica"
- Utilize a versão com `Annotated` se possível.
+///
+```Python hl_lines="19"
+{!> ../../../docs_src/dependencies/tutorial002.py!}
+```
- ```Python hl_lines="19"
- {!> ../../../docs_src/dependencies/tutorial002.py!}
- ```
+////
O **FastAPI** chama a classe `CommonQueryParams`. Isso cria uma "instância" dessa classe e é a instância que será passada para o parâmetro `commons` na sua função.
Perceba como escrevemos `CommonQueryParams` duas vezes no código abaixo:
-=== "Python 3.8+"
+//// tab | Python 3.8+
+
+```Python
+commons: Annotated[CommonQueryParams, Depends(CommonQueryParams)]
+```
+
+////
- ```Python
- commons: Annotated[CommonQueryParams, Depends(CommonQueryParams)]
- ```
+//// tab | Python 3.8+ non-Annotated
-=== "Python 3.8+ non-Annotated"
+/// tip | "Dica"
- !!! tip "Dica"
- Utilize a versão com `Annotated` se possível.
+Utilize a versão com `Annotated` se possível.
+///
- ```Python
- commons: CommonQueryParams = Depends(CommonQueryParams)
- ```
+```Python
+commons: CommonQueryParams = Depends(CommonQueryParams)
+```
+
+////
O último `CommonQueryParams`, em:
Nesse caso, o primeiro `CommonQueryParams`, em:
-=== "Python 3.8+"
+//// tab | Python 3.8+
- ```Python
- commons: Annotated[CommonQueryParams, ...
- ```
+```Python
+commons: Annotated[CommonQueryParams, ...
+```
-=== "Python 3.8+ non-Annotated"
+////
- !!! tip "Dica"
- Utilize a versão com `Annotated` se possível.
+//// tab | Python 3.8+ non-Annotated
+/// tip | "Dica"
- ```Python
- commons: CommonQueryParams ...
- ```
+Utilize a versão com `Annotated` se possível.
+
+///
+
+```Python
+commons: CommonQueryParams ...
+```
+
+////
...não tem nenhum signficado especial para o **FastAPI**. O FastAPI não irá utilizá-lo para conversão dos dados, validação, etc (já que ele utiliza `Depends(CommonQueryParams)` para isso).
Na verdade você poderia escrever apenas:
-=== "Python 3.8+"
+//// tab | Python 3.8+
+
+```Python
+commons: Annotated[Any, Depends(CommonQueryParams)]
+```
+
+////
+
+//// tab | Python 3.8+ non-Annotated
- ```Python
- commons: Annotated[Any, Depends(CommonQueryParams)]
- ```
+/// tip | "Dica"
-=== "Python 3.8+ non-Annotated"
+Utilize a versão com `Annotated` se possível.
- !!! tip "Dica"
- Utilize a versão com `Annotated` se possível.
+///
+```Python
+commons = Depends(CommonQueryParams)
+```
- ```Python
- commons = Depends(CommonQueryParams)
- ```
+////
...como em:
-=== "Python 3.10+"
+//// tab | Python 3.10+
- ```Python hl_lines="19"
- {!> ../../../docs_src/dependencies/tutorial003_an_py310.py!}
- ```
+```Python hl_lines="19"
+{!> ../../../docs_src/dependencies/tutorial003_an_py310.py!}
+```
+
+////
+
+//// tab | Python 3.9+
+
+```Python hl_lines="19"
+{!> ../../../docs_src/dependencies/tutorial003_an_py39.py!}
+```
+
+////
+
+//// tab | Python 3.8+
+
+```Python hl_lines="20"
+{!> ../../../docs_src/dependencies/tutorial003_an.py!}
+```
+
+////
-=== "Python 3.9+"
+//// tab | Python 3.10+ non-Annotated
- ```Python hl_lines="19"
- {!> ../../../docs_src/dependencies/tutorial003_an_py39.py!}
- ```
+/// tip | "Dica"
-=== "Python 3.8+"
+Utilize a versão com `Annotated` se possível.
- ```Python hl_lines="20"
- {!> ../../../docs_src/dependencies/tutorial003_an.py!}
- ```
+///
-=== "Python 3.10+ non-Annotated"
+```Python hl_lines="17"
+{!> ../../../docs_src/dependencies/tutorial003_py310.py!}
+```
- !!! tip "Dica"
- Utilize a versão com `Annotated` se possível.
+////
+//// tab | Python 3.8+ non-Annotated
- ```Python hl_lines="17"
- {!> ../../../docs_src/dependencies/tutorial003_py310.py!}
- ```
+/// tip | "Dica"
-=== "Python 3.8+ non-Annotated"
+Utilize a versão com `Annotated` se possível.
- !!! tip "Dica"
- Utilize a versão com `Annotated` se possível.
+///
+```Python hl_lines="19"
+{!> ../../../docs_src/dependencies/tutorial003.py!}
+```
- ```Python hl_lines="19"
- {!> ../../../docs_src/dependencies/tutorial003.py!}
- ```
+////
Mas declarar o tipo é encorajado por que é a forma que o seu editor de texto sabe o que será passado como valor do parâmetro `commons`.
Mas você pode ver que temos uma repetição do código neste exemplo, escrevendo `CommonQueryParams` duas vezes:
-=== "Python 3.8+"
+//// tab | Python 3.8+
+
+```Python
+commons: Annotated[CommonQueryParams, Depends(CommonQueryParams)]
+```
+
+////
- ```Python
- commons: Annotated[CommonQueryParams, Depends(CommonQueryParams)]
- ```
+//// tab | Python 3.8+ non-Annotated
-=== "Python 3.8+ non-Annotated"
+/// tip | "Dica"
- !!! tip "Dica"
- Utilize a versão com `Annotated` se possível.
+Utilize a versão com `Annotated` se possível.
- ```Python
- commons: CommonQueryParams = Depends(CommonQueryParams)
- ```
+///
+
+```Python
+commons: CommonQueryParams = Depends(CommonQueryParams)
+```
+
+////
O **FastAPI** nos fornece um atalho para esses casos, onde a dependência é *especificamente* uma classe que o **FastAPI** irá "chamar" para criar uma instância da própria classe.
Em vez de escrever:
-=== "Python 3.8+"
+//// tab | Python 3.8+
- ```Python
- commons: Annotated[CommonQueryParams, Depends(CommonQueryParams)]
- ```
+```Python
+commons: Annotated[CommonQueryParams, Depends(CommonQueryParams)]
+```
+
+////
-=== "Python 3.8+ non-Annotated"
+//// tab | Python 3.8+ non-Annotated
- !!! tip "Dica"
- Utilize a versão com `Annotated` se possível.
+/// tip | "Dica"
- ```Python
- commons: CommonQueryParams = Depends(CommonQueryParams)
- ```
+Utilize a versão com `Annotated` se possível.
+
+///
+
+```Python
+commons: CommonQueryParams = Depends(CommonQueryParams)
+```
+
+////
...escreva:
-=== "Python 3.8+"
+//// tab | Python 3.8+
+
+```Python
+commons: Annotated[CommonQueryParams, Depends()]
+```
- ```Python
- commons: Annotated[CommonQueryParams, Depends()]
- ```
+////
-=== "Python 3.8 non-Annotated"
+//// tab | Python 3.8 non-Annotated
- !!! tip "Dica"
- Utilize a versão com `Annotated` se possível.
+/// tip | "Dica"
+Utilize a versão com `Annotated` se possível.
- ```Python
- commons: CommonQueryParams = Depends()
- ```
+///
+
+```Python
+commons: CommonQueryParams = Depends()
+```
+
+////
Você declara a dependência como o tipo do parâmetro, e utiliza `Depends()` sem nenhum parâmetro, em vez de ter que escrever a classe *novamente* dentro de `Depends(CommonQueryParams)`.
O mesmo exemplo ficaria então dessa forma:
-=== "Python 3.10+"
+//// tab | Python 3.10+
+
+```Python hl_lines="19"
+{!> ../../../docs_src/dependencies/tutorial004_an_py310.py!}
+```
+
+////
+
+//// tab | Python 3.9+
+
+```Python hl_lines="19"
+{!> ../../../docs_src/dependencies/tutorial004_an_py39.py!}
+```
+
+////
+
+//// tab | Python 3.8+
+
+```Python hl_lines="20"
+{!> ../../../docs_src/dependencies/tutorial004_an.py!}
+```
- ```Python hl_lines="19"
- {!> ../../../docs_src/dependencies/tutorial004_an_py310.py!}
- ```
+////
-=== "Python 3.9+"
+//// tab | Python 3.10+ non-Annotated
- ```Python hl_lines="19"
- {!> ../../../docs_src/dependencies/tutorial004_an_py39.py!}
- ```
+/// tip | "Dica"
-=== "Python 3.8+"
+Utilize a versão com `Annotated` se possível.
- ```Python hl_lines="20"
- {!> ../../../docs_src/dependencies/tutorial004_an.py!}
- ```
+///
-=== "Python 3.10+ non-Annotated"
+```Python hl_lines="17"
+{!> ../../../docs_src/dependencies/tutorial004_py310.py!}
+```
- !!! tip "Dica"
- Utilize a versão com `Annotated` se possível.
+////
+//// tab | Python 3.8+ non-Annotated
- ```Python hl_lines="17"
- {!> ../../../docs_src/dependencies/tutorial004_py310.py!}
- ```
+/// tip | "Dica"
-=== "Python 3.8+ non-Annotated"
+Utilize a versão com `Annotated` se possível.
- !!! tip "Dica"
- Utilize a versão com `Annotated` se possível.
+///
+```Python hl_lines="19"
+{!> ../../../docs_src/dependencies/tutorial004.py!}
+```
- ```Python hl_lines="19"
- {!> ../../../docs_src/dependencies/tutorial004.py!}
- ```
+////
...e o **FastAPI** saberá o que fazer.
-!!! tip "Dica"
- Se isso parece mais confuso do que útil, não utilize, você não *precisa* disso.
+/// tip | "Dica"
+
+Se isso parece mais confuso do que útil, não utilize, você não *precisa* disso.
+
+É apenas um atalho. Por que o **FastAPI** se preocupa em ajudar a minimizar a repetição de código.
- É apenas um atalho. Por que o **FastAPI** se preocupa em ajudar a minimizar a repetição de código.
+///
Ele deve ser uma lista de `Depends()`:
-=== "Python 3.9+"
+//// tab | Python 3.9+
- ```Python hl_lines="19"
- {!> ../../../docs_src/dependencies/tutorial006_an_py39.py!}
- ```
+```Python hl_lines="19"
+{!> ../../../docs_src/dependencies/tutorial006_an_py39.py!}
+```
-=== "Python 3.8+"
+////
- ```Python hl_lines="18"
- {!> ../../../docs_src/dependencies/tutorial006_an.py!}
- ```
+//// tab | Python 3.8+
-=== "Python 3.8 non-Annotated"
+```Python hl_lines="18"
+{!> ../../../docs_src/dependencies/tutorial006_an.py!}
+```
- !!! tip "Dica"
- Utilize a versão com `Annotated` se possível
+////
+
+//// tab | Python 3.8 non-Annotated
+
+/// tip | "Dica"
+
+Utilize a versão com `Annotated` se possível
+
+///
+
+```Python hl_lines="17"
+{!> ../../../docs_src/dependencies/tutorial006.py!}
+```
+
+////
- ```Python hl_lines="17"
- {!> ../../../docs_src/dependencies/tutorial006.py!}
- ```
Essas dependências serão executadas/resolvidas da mesma forma que dependências comuns. Mas o valor delas (se existir algum) não será passado para a sua *função de operação de rota*.
-!!! tip "Dica"
- Alguns editores de texto checam parâmetros de funções não utilizados, e os mostram como erros.
+/// tip | "Dica"
+
+Alguns editores de texto checam parâmetros de funções não utilizados, e os mostram como erros.
- Utilizando `dependencies` no *decorador da operação de rota* você pode garantir que elas serão executadas enquanto evita errors de editores/ferramentas.
+Utilizando `dependencies` no *decorador da operação de rota* você pode garantir que elas serão executadas enquanto evita errors de editores/ferramentas.
- Isso também pode ser útil para evitar confundir novos desenvolvedores que ao ver um parâmetro não usado no seu código podem pensar que ele é desnecessário.
+Isso também pode ser útil para evitar confundir novos desenvolvedores que ao ver um parâmetro não usado no seu código podem pensar que ele é desnecessário.
-!!! info "Informação"
- Neste exemplo utilizamos cabeçalhos personalizados inventados `X-Keys` e `X-Token`.
+///
- Mas em situações reais, como implementações de segurança, você pode obter mais vantagens em usar as [Ferramentas de segurança integradas (o próximo capítulo)](../security/index.md){.internal-link target=_blank}.
+/// info | "Informação"
+
+Neste exemplo utilizamos cabeçalhos personalizados inventados `X-Keys` e `X-Token`.
+
+Mas em situações reais, como implementações de segurança, você pode obter mais vantagens em usar as [Ferramentas de segurança integradas (o próximo capítulo)](../security/index.md){.internal-link target=_blank}.
+
+///
## Erros das dependências e valores de retorno
Dependências podem declarar requisitos de requisições (como cabeçalhos) ou outras subdependências:
-=== "Python 3.9+"
+//// tab | Python 3.9+
+
+```Python hl_lines="8 13"
+{!> ../../../docs_src/dependencies/tutorial006_an_py39.py!}
+```
+
+////
+
+//// tab | Python 3.8+
+
+```Python hl_lines="7 12"
+{!> ../../../docs_src/dependencies/tutorial006_an.py!}
+```
- ```Python hl_lines="8 13"
- {!> ../../../docs_src/dependencies/tutorial006_an_py39.py!}
- ```
+////
-=== "Python 3.8+"
+//// tab | Python 3.8 non-Annotated
- ```Python hl_lines="7 12"
- {!> ../../../docs_src/dependencies/tutorial006_an.py!}
- ```
+/// tip | "Dica"
-=== "Python 3.8 non-Annotated"
+Utilize a versão com `Annotated` se possível
- !!! tip "Dica"
- Utilize a versão com `Annotated` se possível
+///
- ```Python hl_lines="6 11"
- {!> ../../../docs_src/dependencies/tutorial006.py!}
- ```
+```Python hl_lines="6 11"
+{!> ../../../docs_src/dependencies/tutorial006.py!}
+```
+
+////
### Levantando exceções
Essas dependências podem levantar exceções, da mesma forma que dependências comuns:
-=== "Python 3.9+"
+//// tab | Python 3.9+
+
+```Python hl_lines="10 15"
+{!> ../../../docs_src/dependencies/tutorial006_an_py39.py!}
+```
+
+////
+
+//// tab | Python 3.8+
- ```Python hl_lines="10 15"
- {!> ../../../docs_src/dependencies/tutorial006_an_py39.py!}
- ```
+```Python hl_lines="9 14"
+{!> ../../../docs_src/dependencies/tutorial006_an.py!}
+```
-=== "Python 3.8+"
+////
- ```Python hl_lines="9 14"
- {!> ../../../docs_src/dependencies/tutorial006_an.py!}
- ```
+//// tab | Python 3.8 non-Annotated
-=== "Python 3.8 non-Annotated"
+/// tip | "Dica"
- !!! tip "Dica"
- Utilize a versão com `Annotated` se possível
+Utilize a versão com `Annotated` se possível
- ```Python hl_lines="8 13"
- {!> ../../../docs_src/dependencies/tutorial006.py!}
- ```
+///
+
+```Python hl_lines="8 13"
+{!> ../../../docs_src/dependencies/tutorial006.py!}
+```
+
+////
### Valores de retorno
Então, você pode reutilizar uma dependência comum (que retorna um valor) que já seja utilizada em outro lugar, e mesmo que o valor não seja utilizado, a dependência será executada:
-=== "Python 3.9+"
+//// tab | Python 3.9+
+
+```Python hl_lines="11 16"
+{!> ../../../docs_src/dependencies/tutorial006_an_py39.py!}
+```
+
+////
+
+//// tab | Python 3.8+
+
+```Python hl_lines="10 15"
+{!> ../../../docs_src/dependencies/tutorial006_an.py!}
+```
+
+////
+
+//// tab | Python 3.8 non-Annotated
+
+/// tip | "Dica"
- ```Python hl_lines="11 16"
- {!> ../../../docs_src/dependencies/tutorial006_an_py39.py!}
- ```
-=== "Python 3.8+"
- ```Python hl_lines="10 15"
- {!> ../../../docs_src/dependencies/tutorial006_an.py!}
- ```
+///
-=== "Python 3.8 non-Annotated"
+ Utilize a versão com `Annotated` se possível
- !!! tip "Dica"
- Utilize a versão com `Annotated` se possível
+```Python hl_lines="9 14"
+{!> ../../../docs_src/dependencies/tutorial006.py!}
+```
- ```Python hl_lines="9 14"
- {!> ../../../docs_src/dependencies/tutorial006.py!}
- ```
+////
## Dependências para um grupo de *operações de rota*
Para fazer isso, utilize `yield` em vez de `return`, e escreva os passos extras (código) depois.
-!!! tip "Dica"
- Garanta que `yield` é utilizado apenas uma vez.
+/// tip | "Dica"
-!!! note "Detalhes Técnicos"
- Qualquer função que possa ser utilizada com:
+Garanta que `yield` é utilizado apenas uma vez.
- * <a href="https://docs.python.org/3/library/contextlib.html#contextlib.contextmanager" class="external-link" target="_blank">`@contextlib.contextmanager`</a> ou
- * <a href="https://docs.python.org/3/library/contextlib.html#contextlib.asynccontextmanager" class="external-link" target="_blank">`@contextlib.asynccontextmanager`</a>
+///
- pode ser utilizada como uma dependência do **FastAPI**.
+/// note | "Detalhes Técnicos"
- Na realidade, o FastAPI utiliza esses dois decoradores internamente.
+Qualquer função que possa ser utilizada com:
+
+* <a href="https://docs.python.org/3/library/contextlib.html#contextlib.contextmanager" class="external-link" target="_blank">`@contextlib.contextmanager`</a> ou
+* <a href="https://docs.python.org/3/library/contextlib.html#contextlib.asynccontextmanager" class="external-link" target="_blank">`@contextlib.asynccontextmanager`</a>
+
+pode ser utilizada como uma dependência do **FastAPI**.
+
+Na realidade, o FastAPI utiliza esses dois decoradores internamente.
+
+///
## Uma dependência de banco de dados com `yield`
{!../../../docs_src/dependencies/tutorial007.py!}
```
-!!! tip "Dica"
- Você pode usar funções assíncronas (`async`) ou funções comuns.
+/// tip | "Dica"
- O **FastAPI** saberá o que fazer com cada uma, da mesma forma que as dependências comuns.
+Você pode usar funções assíncronas (`async`) ou funções comuns.
+
+O **FastAPI** saberá o que fazer com cada uma, da mesma forma que as dependências comuns.
+
+///
## Uma dependência com `yield` e `try`
Por exemplo, `dependency_c` pode depender de `dependency_b`, e `dependency_b` depender de `dependency_a`:
-=== "python 3.9+"
+//// tab | python 3.9+
- ```python hl_lines="6 14 22"
- {!> ../../../docs_src/dependencies/tutorial008_an_py39.py!}
- ```
+```python hl_lines="6 14 22"
+{!> ../../../docs_src/dependencies/tutorial008_an_py39.py!}
+```
-=== "python 3.8+"
+////
- ```python hl_lines="5 13 21"
- {!> ../../../docs_src/dependencies/tutorial008_an.py!}
- ```
+//// tab | python 3.8+
-=== "python 3.8+ non-annotated"
+```python hl_lines="5 13 21"
+{!> ../../../docs_src/dependencies/tutorial008_an.py!}
+```
- !!! tip "Dica"
- Utilize a versão com `Annotated` se possível.
+////
- ```python hl_lines="4 12 20"
- {!> ../../../docs_src/dependencies/tutorial008.py!}
- ```
+//// tab | python 3.8+ non-annotated
+
+/// tip | "Dica"
+
+Utilize a versão com `Annotated` se possível.
+
+///
+
+```python hl_lines="4 12 20"
+{!> ../../../docs_src/dependencies/tutorial008.py!}
+```
+
+////
E todas elas podem utilizar `yield`.
E, por outro lado, `dependency_b` precisa que o valor de `dependency_a` (nomeada de `dep_a`) continue disponível para executar seu código de saída.
-=== "python 3.9+"
+//// tab | python 3.9+
+
+```python hl_lines="18-19 26-27"
+{!> ../../../docs_src/dependencies/tutorial008_an_py39.py!}
+```
+
+////
+
+//// tab | python 3.8+
+
+```python hl_lines="17-18 25-26"
+{!> ../../../docs_src/dependencies/tutorial008_an.py!}
+```
+
+////
- ```python hl_lines="18-19 26-27"
- {!> ../../../docs_src/dependencies/tutorial008_an_py39.py!}
- ```
+//// tab | python 3.8+ non-annotated
-=== "python 3.8+"
+/// tip | "Dica"
- ```python hl_lines="17-18 25-26"
- {!> ../../../docs_src/dependencies/tutorial008_an.py!}
- ```
+Utilize a versão com `Annotated` se possível.
-=== "python 3.8+ non-annotated"
+///
- !!! tip "Dica"
- Utilize a versão com `Annotated` se possível.
+```python hl_lines="16-17 24-25"
+{!> ../../../docs_src/dependencies/tutorial008.py!}
+```
- ```python hl_lines="16-17 24-25"
- {!> ../../../docs_src/dependencies/tutorial008.py!}
- ```
+////
Da mesma forma, você pode ter algumas dependências com `yield` e outras com `return` e ter uma relação de dependência entre algumas dos dois tipos.
O **FastAPI** se encarrega de executá-las na ordem certa.
-!!! note "Detalhes Técnicos"
- Tudo isso funciona graças aos <a href="https://docs.python.org/3/library/contextlib.html" class="external-link" target="_blank">gerenciadores de contexto</a> do Python.
+/// note | "Detalhes Técnicos"
+
+Tudo isso funciona graças aos <a href="https://docs.python.org/3/library/contextlib.html" class="external-link" target="_blank">gerenciadores de contexto</a> do Python.
- O **FastAPI** utiliza eles internamente para alcançar isso.
+O **FastAPI** utiliza eles internamente para alcançar isso.
+
+///
## Dependências com `yield` e `httpexception`
Da mesma forma, você pode lançar uma `httpexception` ou algo parecido no código de saída, após o `yield`
-!!! tip "Dica"
+/// tip | "Dica"
+
+Essa é uma técnica relativamente avançada, e na maioria dos casos você não precisa dela totalmente, já que você pode lançar exceções (incluindo `httpexception`) dentro do resto do código da sua aplicação, por exemplo, em uma *função de operação de rota*.
+
+Mas ela existe para ser utilizada caso você precise. 🤓
+
+///
+
+//// tab | python 3.9+
+
+```python hl_lines="18-22 31"
+{!> ../../../docs_src/dependencies/tutorial008b_an_py39.py!}
+```
+
+////
- Essa é uma técnica relativamente avançada, e na maioria dos casos você não precisa dela totalmente, já que você pode lançar exceções (incluindo `httpexception`) dentro do resto do código da sua aplicação, por exemplo, em uma *função de operação de rota*.
+//// tab | python 3.8+
- Mas ela existe para ser utilizada caso você precise. 🤓
+```python hl_lines="17-21 30"
+{!> ../../../docs_src/dependencies/tutorial008b_an.py!}
+```
-=== "python 3.9+"
+////
- ```python hl_lines="18-22 31"
- {!> ../../../docs_src/dependencies/tutorial008b_an_py39.py!}
- ```
+//// tab | python 3.8+ non-annotated
-=== "python 3.8+"
+/// tip | "Dica"
- ```python hl_lines="17-21 30"
- {!> ../../../docs_src/dependencies/tutorial008b_an.py!}
- ```
+Utilize a versão com `Annotated` se possível.
-=== "python 3.8+ non-annotated"
+///
- !!! tip "Dica"
- Utilize a versão com `Annotated` se possível.
+```python hl_lines="16-20 29"
+{!> ../../../docs_src/dependencies/tutorial008b.py!}
+```
- ```python hl_lines="16-20 29"
- {!> ../../../docs_src/dependencies/tutorial008b.py!}
- ```
+////
Uma alternativa que você pode utilizar para capturar exceções (e possivelmente lançar outra HTTPException) é criar um [Manipulador de Exceções Customizado](../handling-errors.md#instalando-manipuladores-de-excecoes-customizados){.internal-link target=_blank}.
Se você capturar uma exceção com `except` em uma dependência que utilize `yield` e ela não for levantada novamente (ou uma nova exceção for levantada), o FastAPI não será capaz de identifcar que houve uma exceção, da mesma forma que aconteceria com Python puro:
-=== "Python 3.9+"
+//// tab | Python 3.9+
+
+```Python hl_lines="15-16"
+{!> ../../../docs_src/dependencies/tutorial008c_an_py39.py!}
+```
+
+////
- ```Python hl_lines="15-16"
- {!> ../../../docs_src/dependencies/tutorial008c_an_py39.py!}
- ```
+//// tab | Python 3.8+
+
+```Python hl_lines="14-15"
+{!> ../../../docs_src/dependencies/tutorial008c_an.py!}
+```
-=== "Python 3.8+"
+////
- ```Python hl_lines="14-15"
- {!> ../../../docs_src/dependencies/tutorial008c_an.py!}
- ```
+//// tab | Python 3.8+ non-annotated
-=== "Python 3.8+ non-annotated"
+/// tip | "dica"
- !!! tip "dica"
- utilize a versão com `Annotated` se possível.
+utilize a versão com `Annotated` se possível.
- ```Python hl_lines="13-14"
- {!> ../../../docs_src/dependencies/tutorial008c.py!}
- ```
+///
+
+```Python hl_lines="13-14"
+{!> ../../../docs_src/dependencies/tutorial008c.py!}
+```
+
+////
Neste caso, o cliente irá ver uma resposta *HTTP 500 Internal Server Error* como deveria acontecer, já que não estamos levantando nenhuma `HTTPException` ou coisa parecida, mas o servidor **não terá nenhum log** ou qualquer outra indicação de qual foi o erro. 😱
Você pode relançar a mesma exceção utilizando `raise`:
-=== "Python 3.9+"
+//// tab | Python 3.9+
+
+```Python hl_lines="17"
+{!> ../../../docs_src/dependencies/tutorial008d_an_py39.py!}
+```
+
+////
+
+//// tab | Python 3.8+
- ```Python hl_lines="17"
- {!> ../../../docs_src/dependencies/tutorial008d_an_py39.py!}
- ```
+```Python hl_lines="16"
+{!> ../../../docs_src/dependencies/tutorial008d_an.py!}
+```
+
+////
-=== "Python 3.8+"
+//// tab | python 3.8+ non-annotated
- ```Python hl_lines="16"
- {!> ../../../docs_src/dependencies/tutorial008d_an.py!}
- ```
+/// tip | "Dica"
-=== "python 3.8+ non-annotated"
+Utilize a versão com `Annotated` se possível.
- !!! tip "Dica"
- Utilize a versão com `Annotated` se possível.
+///
+
+```Python hl_lines="15"
+{!> ../../../docs_src/dependencies/tutorial008d.py!}
+```
- ```Python hl_lines="15"
- {!> ../../../docs_src/dependencies/tutorial008d.py!}
- ```
+////
Agora o cliente irá receber a mesma resposta *HTTP 500 Internal Server Error*, mas o servidor terá nosso `InternalError` personalizado nos logs. 😎
end
```
-!!! info "Informação"
- Apenas **uma resposta** será enviada para o cliente. Ela pode ser uma das respostas de erro, ou então a resposta da *operação de rota*.
+/// info | "Informação"
+
+Apenas **uma resposta** será enviada para o cliente. Ela pode ser uma das respostas de erro, ou então a resposta da *operação de rota*.
+
+Após uma dessas respostas ser enviada, nenhuma outra resposta pode ser enviada
+
+///
+
+/// tip | "Dica"
- Após uma dessas respostas ser enviada, nenhuma outra resposta pode ser enviada
+Esse diagrama mostra `HttpException`, mas você pode levantar qualquer outra exceção que você capture em uma dependência com `yield` ou um [Manipulador de exceções personalizado](../handling-errors.md#instalando-manipuladores-de-excecoes-customizados){.internal-link target=_blank}.
-!!! tip "Dica"
- Esse diagrama mostra `HttpException`, mas você pode levantar qualquer outra exceção que você capture em uma dependência com `yield` ou um [Manipulador de exceções personalizado](../handling-errors.md#instalando-manipuladores-de-excecoes-customizados){.internal-link target=_blank}.
+Se você lançar qualquer exceção, ela será passada para as dependências com yield, inlcuindo a `HTTPException`. Na maioria dos casos você vai querer relançar essa mesma exceção ou uma nova a partir da dependência com `yield` para garantir que ela seja tratada adequadamente.
- Se você lançar qualquer exceção, ela será passada para as dependências com yield, inlcuindo a `HTTPException`. Na maioria dos casos você vai querer relançar essa mesma exceção ou uma nova a partir da dependência com `yield` para garantir que ela seja tratada adequadamente.
+///
## Dependências com `yield`, `HTTPException`, `except` e Tarefas de Background
-!!! warning "Aviso"
- Você provavelmente não precisa desses detalhes técnicos, você pode pular essa seção e continuar na próxima seção abaixo.
+/// warning | "Aviso"
- Esses detalhes são úteis principalmente se você estiver usando uma versão do FastAPI anterior à 0.106.0 e utilizando recursos de dependências com `yield` em tarefas de background.
+Você provavelmente não precisa desses detalhes técnicos, você pode pular essa seção e continuar na próxima seção abaixo.
+
+Esses detalhes são úteis principalmente se você estiver usando uma versão do FastAPI anterior à 0.106.0 e utilizando recursos de dependências com `yield` em tarefas de background.
+
+///
### Dependências com `yield` e `except`, Detalhes Técnicos
Ainda assim, como isso exigiria esperar que a resposta navegasse pela rede enquanto mantia ativo um recurso desnecessário na dependência com yield (por exemplo, uma conexão com banco de dados), isso mudou na versão 0.106.0 do FastAPI.
-!!! tip "Dica"
+/// tip | "Dica"
- Adicionalmente, uma tarefa de background é, normalmente, um conjunto de lógicas independentes que devem ser manipuladas separadamente, com seus próprios recursos (e.g. sua própria conexão com banco de dados).
+Adicionalmente, uma tarefa de background é, normalmente, um conjunto de lógicas independentes que devem ser manipuladas separadamente, com seus próprios recursos (e.g. sua própria conexão com banco de dados).
- Então, dessa forma você provavelmente terá um código mais limpo.
+Então, dessa forma você provavelmente terá um código mais limpo.
+
+///
Se você costumava depender desse comportamento, agora você precisa criar os recursos para uma tarefa de background dentro dela mesma, e usar internamente apenas dados que não dependam de recursos de dependências com `yield`.
### Utilizando gerenciadores de contexto em dependências com `yield`
-!!! warning "Aviso"
- Isso é uma ideia mais ou menos "avançada".
+/// warning | "Aviso"
+
+Isso é uma ideia mais ou menos "avançada".
- Se você está apenas iniciando com o **FastAPI** você pode querer pular isso por enquanto.
+Se você está apenas iniciando com o **FastAPI** você pode querer pular isso por enquanto.
+
+///
Em python, você pode criar Gerenciadores de Contexto ao <a href="https://docs.python.org/3/reference/datamodel.html#context-managers" class="external-link" target="_blank"> criar uma classe com dois métodos: `__enter__()` e `__exit__()`</a>.
{!../../../docs_src/dependencies/tutorial010.py!}
```
-!!! tip "Dica"
- Outra forma de criar um gerenciador de contexto é utilizando:
+/// tip | "Dica"
+
+Outra forma de criar um gerenciador de contexto é utilizando:
+
+* <a href="https://docs.python.org/3/library/contextlib.html#contextlib.contextmanager" class="external-link" target="_blank">`@contextlib.contextmanager`</a> ou
- * <a href="https://docs.python.org/3/library/contextlib.html#contextlib.contextmanager" class="external-link" target="_blank">`@contextlib.contextmanager`</a> ou
+* <a href="https://docs.python.org/3/library/contextlib.html#contextlib.asynccontextmanager" class="external-link" target="_blank">`@contextlib.asynccontextmanager`</a>
- * <a href="https://docs.python.org/3/library/contextlib.html#contextlib.asynccontextmanager" class="external-link" target="_blank">`@contextlib.asynccontextmanager`</a>
+Para decorar uma função com um único `yield`.
- Para decorar uma função com um único `yield`.
+Isso é o que o **FastAPI** usa internamente para dependências com `yield`.
- Isso é o que o **FastAPI** usa internamente para dependências com `yield`.
+Mas você não precisa usar esses decoradores para as dependências do FastAPI (e você não deveria).
- Mas você não precisa usar esses decoradores para as dependências do FastAPI (e você não deveria).
+O FastAPI irá fazer isso para você internamente.
- O FastAPI irá fazer isso para você internamente.
+///
Nesse caso, elas serão aplicadas a todas as *operações de rota* da aplicação:
-=== "Python 3.9+"
+//// tab | Python 3.9+
- ```Python hl_lines="16"
- {!> ../../../docs_src/dependencies/tutorial012_an_py39.py!}
- ```
+```Python hl_lines="16"
+{!> ../../../docs_src/dependencies/tutorial012_an_py39.py!}
+```
-=== "Python 3.8+"
+////
- ```Python hl_lines="16"
- {!> ../../../docs_src/dependencies/tutorial012_an.py!}
- ```
+//// tab | Python 3.8+
-=== "Python 3.8 non-Annotated"
+```Python hl_lines="16"
+{!> ../../../docs_src/dependencies/tutorial012_an.py!}
+```
- !!! tip "Dica"
- Utilize a versão com `Annotated` se possível.
+////
- ```Python hl_lines="15"
- {!> ../../../docs_src/dependencies/tutorial012.py!}
- ```
+//// tab | Python 3.8 non-Annotated
+
+/// tip | "Dica"
+
+Utilize a versão com `Annotated` se possível.
+
+///
+
+```Python hl_lines="15"
+{!> ../../../docs_src/dependencies/tutorial012.py!}
+```
+
+////
E todos os conceitos apresentados na sessão sobre [adicionar dependências em *decoradores de operação de rota*](dependencies-in-path-operation-decorators.md){.internal-link target=_blank} ainda se aplicam, mas nesse caso, para todas as *operações de rota* da aplicação.
Ela é apenas uma função que pode receber os mesmos parâmetros de uma *função de operação de rota*:
-=== "Python 3.10+"
+//// tab | Python 3.10+
- ```Python hl_lines="8-9"
- {!> ../../../docs_src/dependencies/tutorial001_an_py310.py!}
- ```
+```Python hl_lines="8-9"
+{!> ../../../docs_src/dependencies/tutorial001_an_py310.py!}
+```
+
+////
+
+//// tab | Python 3.9+
+
+```Python hl_lines="8-11"
+{!> ../../../docs_src/dependencies/tutorial001_an_py39.py!}
+```
+
+////
-=== "Python 3.9+"
+//// tab | Python 3.8+
- ```Python hl_lines="8-11"
- {!> ../../../docs_src/dependencies/tutorial001_an_py39.py!}
- ```
+```Python hl_lines="9-12"
+{!> ../../../docs_src/dependencies/tutorial001_an.py!}
+```
-=== "Python 3.8+"
+////
- ```Python hl_lines="9-12"
- {!> ../../../docs_src/dependencies/tutorial001_an.py!}
- ```
+//// tab | Python 3.10+ non-Annotated
-=== "Python 3.10+ non-Annotated"
+/// tip | "Dica"
- !!! tip "Dica"
- Utilize a versão com `Annotated` se possível.
+Utilize a versão com `Annotated` se possível.
- ```Python hl_lines="6-7"
- {!> ../../../docs_src/dependencies/tutorial001_py310.py!}
- ```
+///
-=== "Python 3.8+ non-Annotated"
+```Python hl_lines="6-7"
+{!> ../../../docs_src/dependencies/tutorial001_py310.py!}
+```
- !!! tip "Dica"
- Utilize a versão com `Annotated` se possível.
+////
- ```Python hl_lines="8-11"
- {!> ../../../docs_src/dependencies/tutorial001.py!}
- ```
+//// tab | Python 3.8+ non-Annotated
+
+/// tip | "Dica"
+
+Utilize a versão com `Annotated` se possível.
+
+///
+
+```Python hl_lines="8-11"
+{!> ../../../docs_src/dependencies/tutorial001.py!}
+```
+
+////
E pronto.
E então retorna um `dict` contendo esses valores.
-!!! info "Informação"
- FastAPI passou a suportar a notação `Annotated` (e começou a recomendá-la) na versão 0.95.0.
+/// info | "Informação"
+
+FastAPI passou a suportar a notação `Annotated` (e começou a recomendá-la) na versão 0.95.0.
- Se você utiliza uma versão anterior, ocorrerão erros ao tentar utilizar `Annotated`.
+Se você utiliza uma versão anterior, ocorrerão erros ao tentar utilizar `Annotated`.
- Certifique-se de [Atualizar a versão do FastAPI](../../deployment/versions.md#atualizando-as-versoes-do-fastapi){.internal-link target=_blank} para pelo menos 0.95.1 antes de usar `Annotated`.
+Certifique-se de [Atualizar a versão do FastAPI](../../deployment/versions.md#atualizando-as-versoes-do-fastapi){.internal-link target=_blank} para pelo menos 0.95.1 antes de usar `Annotated`.
+
+///
### Importando `Depends`
-=== "Python 3.10+"
+//// tab | Python 3.10+
+
+```Python hl_lines="3"
+{!> ../../../docs_src/dependencies/tutorial001_an_py310.py!}
+```
+
+////
+
+//// tab | Python 3.9+
+
+```Python hl_lines="3"
+{!> ../../../docs_src/dependencies/tutorial001_an_py39.py!}
+```
+
+////
+
+//// tab | Python 3.8+
+
+```Python hl_lines="3"
+{!> ../../../docs_src/dependencies/tutorial001_an.py!}
+```
- ```Python hl_lines="3"
- {!> ../../../docs_src/dependencies/tutorial001_an_py310.py!}
- ```
+////
-=== "Python 3.9+"
+//// tab | Python 3.10+ non-Annotated
- ```Python hl_lines="3"
- {!> ../../../docs_src/dependencies/tutorial001_an_py39.py!}
- ```
+/// tip | "Dica"
-=== "Python 3.8+"
+Utilize a versão com `Annotated` se possível.
+
+///
+
+```Python hl_lines="1"
+{!> ../../../docs_src/dependencies/tutorial001_py310.py!}
+```
- ```Python hl_lines="3"
- {!> ../../../docs_src/dependencies/tutorial001_an.py!}
- ```
+////
-=== "Python 3.10+ non-Annotated"
+//// tab | Python 3.8+ non-Annotated
- !!! tip "Dica"
- Utilize a versão com `Annotated` se possível.
+/// tip | "Dica"
- ```Python hl_lines="1"
- {!> ../../../docs_src/dependencies/tutorial001_py310.py!}
- ```
+Utilize a versão com `Annotated` se possível.
-=== "Python 3.8+ non-Annotated"
+///
- !!! tip "Dica"
- Utilize a versão com `Annotated` se possível.
+```Python hl_lines="3"
+{!> ../../../docs_src/dependencies/tutorial001.py!}
+```
- ```Python hl_lines="3"
- {!> ../../../docs_src/dependencies/tutorial001.py!}
- ```
+////
### Declarando a dependência, no "dependente"
Da mesma forma que você utiliza `Body`, `Query`, etc. Como parâmetros de sua *função de operação de rota*, utilize `Depends` com um novo parâmetro:
-=== "Python 3.10+"
+//// tab | Python 3.10+
+
+```Python hl_lines="13 18"
+{!> ../../../docs_src/dependencies/tutorial001_an_py310.py!}
+```
+
+////
- ```Python hl_lines="13 18"
- {!> ../../../docs_src/dependencies/tutorial001_an_py310.py!}
- ```
+//// tab | Python 3.9+
-=== "Python 3.9+"
+```Python hl_lines="15 20"
+{!> ../../../docs_src/dependencies/tutorial001_an_py39.py!}
+```
+
+////
- ```Python hl_lines="15 20"
- {!> ../../../docs_src/dependencies/tutorial001_an_py39.py!}
- ```
+//// tab | Python 3.8+
-=== "Python 3.8+"
+```Python hl_lines="16 21"
+{!> ../../../docs_src/dependencies/tutorial001_an.py!}
+```
- ```Python hl_lines="16 21"
- {!> ../../../docs_src/dependencies/tutorial001_an.py!}
- ```
+////
-=== "Python 3.10+ non-Annotated"
+//// tab | Python 3.10+ non-Annotated
- !!! tip "Dica"
- Utilize a versão com `Annotated` se possível.
+/// tip | "Dica"
- ```Python hl_lines="11 16"
- {!> ../../../docs_src/dependencies/tutorial001_py310.py!}
- ```
+Utilize a versão com `Annotated` se possível.
-=== "Python 3.8+ non-Annotated"
+///
- !!! tip "Dica"
- Utilize a versão com `Annotated` se possível.
+```Python hl_lines="11 16"
+{!> ../../../docs_src/dependencies/tutorial001_py310.py!}
+```
+
+////
+
+//// tab | Python 3.8+ non-Annotated
+
+/// tip | "Dica"
+
+Utilize a versão com `Annotated` se possível.
+
+///
+
+```Python hl_lines="15 20"
+{!> ../../../docs_src/dependencies/tutorial001.py!}
+```
- ```Python hl_lines="15 20"
- {!> ../../../docs_src/dependencies/tutorial001.py!}
- ```
+////
Ainda que `Depends` seja utilizado nos parâmetros da função da mesma forma que `Body`, `Query`, etc, `Depends` funciona de uma forma um pouco diferente.
E essa função vai receber os parâmetros da mesma forma que uma *função de operação de rota*.
-!!! tip "Dica"
- Você verá quais outras "coisas", além de funções, podem ser usadas como dependências no próximo capítulo.
+/// tip | "Dica"
+
+Você verá quais outras "coisas", além de funções, podem ser usadas como dependências no próximo capítulo.
+
+///
Sempre que uma nova requisição for realizada, o **FastAPI** se encarrega de:
Assim, você escreve um código compartilhado apenas uma vez e o **FastAPI** se encarrega de chamá-lo em suas *operações de rota*.
-!!! check "Checando"
- Perceba que você não precisa criar uma classe especial e enviar a dependência para algum outro lugar em que o **FastAPI** a "registre" ou realize qualquer operação similar.
+/// check | "Checando"
+
+Perceba que você não precisa criar uma classe especial e enviar a dependência para algum outro lugar em que o **FastAPI** a "registre" ou realize qualquer operação similar.
+
+Você apenas envia para `Depends` e o **FastAPI** sabe como fazer o resto.
- Você apenas envia para `Depends` e o **FastAPI** sabe como fazer o resto.
+///
## Compartilhando dependências `Annotated`
Mas como estamos utilizando `Annotated`, podemos guardar esse valor `Annotated` em uma variável e utilizá-la em múltiplos locais:
-=== "Python 3.10+"
+//// tab | Python 3.10+
+
+```Python hl_lines="12 16 21"
+{!> ../../../docs_src/dependencies/tutorial001_02_an_py310.py!}
+```
+
+////
- ```Python hl_lines="12 16 21"
- {!> ../../../docs_src/dependencies/tutorial001_02_an_py310.py!}
- ```
+//// tab | Python 3.9+
-=== "Python 3.9+"
+```Python hl_lines="14 18 23"
+{!> ../../../docs_src/dependencies/tutorial001_02_an_py39.py!}
+```
+
+////
- ```Python hl_lines="14 18 23"
- {!> ../../../docs_src/dependencies/tutorial001_02_an_py39.py!}
- ```
+//// tab | Python 3.8+
+
+```Python hl_lines="15 19 24"
+{!> ../../../docs_src/dependencies/tutorial001_02_an.py!}
+```
-=== "Python 3.8+"
+////
- ```Python hl_lines="15 19 24"
- {!> ../../../docs_src/dependencies/tutorial001_02_an.py!}
- ```
+/// tip | "Dica"
-!!! tip "Dica"
- Isso é apenas Python padrão, essa funcionalidade é chamada de "type alias", e na verdade não é específica ao **FastAPI**.
+Isso é apenas Python padrão, essa funcionalidade é chamada de "type alias", e na verdade não é específica ao **FastAPI**.
- Mas como o **FastAPI** se baseia em convenções do Python, incluindo `Annotated`, você pode incluir esse truque no seu código. 😎
+Mas como o **FastAPI** se baseia em convenções do Python, incluindo `Annotated`, você pode incluir esse truque no seu código. 😎
+
+///
As dependências continuarão funcionando como esperado, e a **melhor parte** é que a **informação sobre o tipo é preservada**, o que signfica que seu editor de texto ainda irá incluir **preenchimento automático**, **visualização de erros**, etc. O mesmo vale para ferramentas como `mypy`.
Não faz diferença. O **FastAPI** sabe o que fazer.
-!!! note "Nota"
- Caso você não conheça, veja em [Async: *"Com Pressa?"*](../../async.md#com-pressa){.internal-link target=_blank} a sessão acerca de `async` e `await` na documentação.
+/// note | "Nota"
+
+Caso você não conheça, veja em [Async: *"Com Pressa?"*](../../async.md#com-pressa){.internal-link target=_blank} a sessão acerca de `async` e `await` na documentação.
+
+///
## Integrando com OpenAPI
Você pode criar uma primeira dependência (injetável) dessa forma:
-=== "Python 3.10+"
+//// tab | Python 3.10+
- ```Python hl_lines="8-9"
- {!> ../../../docs_src/dependencies/tutorial005_an_py310.py!}
- ```
+```Python hl_lines="8-9"
+{!> ../../../docs_src/dependencies/tutorial005_an_py310.py!}
+```
+
+////
-=== "Python 3.9+"
+//// tab | Python 3.9+
+
+```Python hl_lines="8-9"
+{!> ../../../docs_src/dependencies/tutorial005_an_py39.py!}
+```
- ```Python hl_lines="8-9"
- {!> ../../../docs_src/dependencies/tutorial005_an_py39.py!}
- ```
+////
+
+//// tab | Python 3.8+
+
+```Python hl_lines="9-10"
+{!> ../../../docs_src/dependencies/tutorial005_an.py!}
+```
-=== "Python 3.8+"
+////
+
+//// tab | Python 3.10 non-Annotated
+
+/// tip | "Dica"
+
+Utilize a versão com `Annotated` se possível.
+
+///
+
+```Python hl_lines="6-7"
+{!> ../../../docs_src/dependencies/tutorial005_py310.py!}
+```
- ```Python hl_lines="9-10"
- {!> ../../../docs_src/dependencies/tutorial005_an.py!}
- ```
+////
-=== "Python 3.10 non-Annotated"
+//// tab | Python 3.8 non-Annotated
- !!! tip "Dica"
- Utilize a versão com `Annotated` se possível.
+/// tip | "Dica"
- ```Python hl_lines="6-7"
- {!> ../../../docs_src/dependencies/tutorial005_py310.py!}
- ```
+Utilize a versão com `Annotated` se possível.
-=== "Python 3.8 non-Annotated"
+///
- !!! tip "Dica"
- Utilize a versão com `Annotated` se possível.
+```Python hl_lines="8-9"
+{!> ../../../docs_src/dependencies/tutorial005.py!}
+```
- ```Python hl_lines="8-9"
- {!> ../../../docs_src/dependencies/tutorial005.py!}
- ```
+////
Esse código declara um parâmetro de consulta opcional, `q`, com o tipo `str`, e então retorna esse parâmetro.
Então, você pode criar uma outra função para uma dependência (um "injetável") que ao mesmo tempo declara sua própria dependência (o que faz dela um "dependente" também):
-=== "Python 3.10+"
+//// tab | Python 3.10+
+
+```Python hl_lines="13"
+{!> ../../../docs_src/dependencies/tutorial005_an_py310.py!}
+```
+
+////
+
+//// tab | Python 3.9+
+
+```Python hl_lines="13"
+{!> ../../../docs_src/dependencies/tutorial005_an_py39.py!}
+```
+
+////
+
+//// tab | Python 3.8+
+
+```Python hl_lines="14"
+{!> ../../../docs_src/dependencies/tutorial005_an.py!}
+```
+
+////
+
+//// tab | Python 3.10 non-Annotated
- ```Python hl_lines="13"
- {!> ../../../docs_src/dependencies/tutorial005_an_py310.py!}
- ```
+/// tip | "Dica"
-=== "Python 3.9+"
+Utilize a versão com `Annotated` se possível.
- ```Python hl_lines="13"
- {!> ../../../docs_src/dependencies/tutorial005_an_py39.py!}
- ```
+///
-=== "Python 3.8+"
+```Python hl_lines="11"
+{!> ../../../docs_src/dependencies/tutorial005_py310.py!}
+```
- ```Python hl_lines="14"
- {!> ../../../docs_src/dependencies/tutorial005_an.py!}
- ```
+////
-=== "Python 3.10 non-Annotated"
+//// tab | Python 3.8 non-Annotated
- !!! tip "Dica"
- Utilize a versão com `Annotated` se possível.
+/// tip | "Dica"
- ```Python hl_lines="11"
- {!> ../../../docs_src/dependencies/tutorial005_py310.py!}
- ```
+Utilize a versão com `Annotated` se possível.
-=== "Python 3.8 non-Annotated"
+///
- !!! tip "Dica"
- Utilize a versão com `Annotated` se possível.
+```Python hl_lines="13"
+{!> ../../../docs_src/dependencies/tutorial005.py!}
+```
- ```Python hl_lines="13"
- {!> ../../../docs_src/dependencies/tutorial005.py!}
- ```
+////
Vamos focar nos parâmetros declarados:
Então podemos utilizar a dependência com:
-=== "Python 3.10+"
+//// tab | Python 3.10+
+
+```Python hl_lines="23"
+{!> ../../../docs_src/dependencies/tutorial005_an_py310.py!}
+```
+
+////
+
+//// tab | Python 3.9+
+
+```Python hl_lines="23"
+{!> ../../../docs_src/dependencies/tutorial005_an_py39.py!}
+```
+
+////
+
+//// tab | Python 3.8+
+
+```Python hl_lines="24"
+{!> ../../../docs_src/dependencies/tutorial005_an.py!}
+```
+
+////
- ```Python hl_lines="23"
- {!> ../../../docs_src/dependencies/tutorial005_an_py310.py!}
- ```
+//// tab | Python 3.10 non-Annotated
-=== "Python 3.9+"
+/// tip | "Dica"
- ```Python hl_lines="23"
- {!> ../../../docs_src/dependencies/tutorial005_an_py39.py!}
- ```
+Utilize a versão com `Annotated` se possível.
-=== "Python 3.8+"
+///
- ```Python hl_lines="24"
- {!> ../../../docs_src/dependencies/tutorial005_an.py!}
- ```
+```Python hl_lines="19"
+{!> ../../../docs_src/dependencies/tutorial005_py310.py!}
+```
+
+////
-=== "Python 3.10 non-Annotated"
+//// tab | Python 3.8 non-Annotated
- !!! tip "Dica"
- Utilize a versão com `Annotated` se possível.
+/// tip | "Dica"
- ```Python hl_lines="19"
- {!> ../../../docs_src/dependencies/tutorial005_py310.py!}
- ```
+Utilize a versão com `Annotated` se possível.
-=== "Python 3.8 non-Annotated"
+///
+
+```Python hl_lines="22"
+{!> ../../../docs_src/dependencies/tutorial005.py!}
+```
- !!! tip "Dica"
- Utilize a versão com `Annotated` se possível.
+////
- ```Python hl_lines="22"
- {!> ../../../docs_src/dependencies/tutorial005.py!}
- ```
+/// info | "Informação"
-!!! info "Informação"
- Perceba que nós estamos declarando apenas uma dependência na *função de operação de rota*, em `query_or_cookie_extractor`.
+Perceba que nós estamos declarando apenas uma dependência na *função de operação de rota*, em `query_or_cookie_extractor`.
- Mas o **FastAPI** saberá que precisa solucionar `query_extractor` primeiro, para passar o resultado para `query_or_cookie_extractor` enquanto chama a função.
+Mas o **FastAPI** saberá que precisa solucionar `query_extractor` primeiro, para passar o resultado para `query_or_cookie_extractor` enquanto chama a função.
+
+///
```mermaid
graph TB
Em um cenário avançado onde você precise que a dependência seja calculada em cada passo (possivelmente várias vezes) de uma requisição em vez de utilizar o valor em "cache", você pode definir o parâmetro `use_cache=False` em `Depends`:
-=== "Python 3.8+"
+//// tab | Python 3.8+
+
+```Python hl_lines="1"
+async def needy_dependency(fresh_value: Annotated[str, Depends(get_value, use_cache=False)]):
+ return {"fresh_value": fresh_value}
+```
- ```Python hl_lines="1"
- async def needy_dependency(fresh_value: Annotated[str, Depends(get_value, use_cache=False)]):
- return {"fresh_value": fresh_value}
- ```
+////
-=== "Python 3.8+ non-Annotated"
+//// tab | Python 3.8+ non-Annotated
- !!! tip "Dica"
- Utilize a versão com `Annotated` se possível.
+/// tip | "Dica"
- ```Python hl_lines="1"
- async def needy_dependency(fresh_value: str = Depends(get_value, use_cache=False)):
- return {"fresh_value": fresh_value}
- ```
+Utilize a versão com `Annotated` se possível.
+
+///
+
+```Python hl_lines="1"
+async def needy_dependency(fresh_value: str = Depends(get_value, use_cache=False)):
+ return {"fresh_value": fresh_value}
+```
+
+////
## Recapitulando
Mas ainda assim, é bastante poderoso, e permite que você declare grafos (árvores) de dependências com uma profundidade arbitrária.
-!!! tip "Dica"
- Tudo isso pode não parecer muito útil com esses exemplos.
+/// tip | "Dica"
+
+Tudo isso pode não parecer muito útil com esses exemplos.
+
+Mas você verá o quão útil isso é nos capítulos sobre **segurança**.
- Mas você verá o quão útil isso é nos capítulos sobre **segurança**.
+E você também verá a quantidade de código que você não precisara escrever.
- E você também verá a quantidade de código que você não precisara escrever.
+///
A função recebe um objeto, como um modelo Pydantic e retorna uma versão compatível com JSON:
-=== "Python 3.10+"
+//// tab | Python 3.10+
- ```Python hl_lines="4 21"
- {!> ../../../docs_src/encoder/tutorial001_py310.py!}
- ```
+```Python hl_lines="4 21"
+{!> ../../../docs_src/encoder/tutorial001_py310.py!}
+```
-=== "Python 3.8+"
+////
- ```Python hl_lines="5 22"
- {!> ../../../docs_src/encoder/tutorial001.py!}
- ```
+//// tab | Python 3.8+
+
+```Python hl_lines="5 22"
+{!> ../../../docs_src/encoder/tutorial001.py!}
+```
+
+////
Neste exemplo, ele converteria o modelo Pydantic em um `dict`, e o `datetime` em um `str`.
A função não retorna um grande `str` contendo os dados no formato JSON (como uma string). Mas sim, retorna uma estrutura de dados padrão do Python (por exemplo, um `dict`) com valores e subvalores compatíveis com JSON.
-!!! note "Nota"
- `jsonable_encoder` é realmente usado pelo **FastAPI** internamente para converter dados. Mas também é útil em muitos outros cenários.
+/// note | "Nota"
+
+`jsonable_encoder` é realmente usado pelo **FastAPI** internamente para converter dados. Mas também é útil em muitos outros cenários.
+
+///
* O **modelo de saída** não deve ter uma senha.
* O **modelo de banco de dados** provavelmente precisaria ter uma senha criptografada.
-!!! danger
- Nunca armazene senhas em texto simples dos usuários. Sempre armazene uma "hash segura" que você pode verificar depois.
+/// danger
- Se não souber, você aprenderá o que é uma "senha hash" nos [capítulos de segurança](security/simple-oauth2.md#password-hashing){.internal-link target=_blank}.
+Nunca armazene senhas em texto simples dos usuários. Sempre armazene uma "hash segura" que você pode verificar depois.
+
+Se não souber, você aprenderá o que é uma "senha hash" nos [capítulos de segurança](security/simple-oauth2.md#password-hashing){.internal-link target=_blank}.
+
+///
## Múltiplos modelos
Aqui está uma ideia geral de como os modelos poderiam parecer com seus campos de senha e os lugares onde são usados:
-=== "Python 3.8 and above"
+//// tab | Python 3.8 and above
- ```Python hl_lines="9 11 16 22 24 29-30 33-35 40-41"
- {!> ../../../docs_src/extra_models/tutorial001.py!}
- ```
+```Python hl_lines="9 11 16 22 24 29-30 33-35 40-41"
+{!> ../../../docs_src/extra_models/tutorial001.py!}
+```
-=== "Python 3.10 and above"
+////
- ```Python hl_lines="7 9 14 20 22 27-28 31-33 38-39"
- {!> ../../../docs_src/extra_models/tutorial001_py310.py!}
- ```
+//// tab | Python 3.10 and above
+
+```Python hl_lines="7 9 14 20 22 27-28 31-33 38-39"
+{!> ../../../docs_src/extra_models/tutorial001_py310.py!}
+```
+
+////
### Sobre `**user_in.dict()`
)
```
-!!! warning
- As funções adicionais de suporte são apenas para demonstração de um fluxo possível dos dados, mas é claro que elas não fornecem segurança real.
+/// warning
+
+As funções adicionais de suporte são apenas para demonstração de um fluxo possível dos dados, mas é claro que elas não fornecem segurança real.
+
+///
## Reduzir duplicação
Dessa forma, podemos declarar apenas as diferenças entre os modelos (com `password` em texto claro, com `hashed_password` e sem senha):
-=== "Python 3.8 and above"
+//// tab | Python 3.8 and above
+
+```Python hl_lines="9 15-16 19-20 23-24"
+{!> ../../../docs_src/extra_models/tutorial002.py!}
+```
+
+////
- ```Python hl_lines="9 15-16 19-20 23-24"
- {!> ../../../docs_src/extra_models/tutorial002.py!}
- ```
+//// tab | Python 3.10 and above
-=== "Python 3.10 and above"
+```Python hl_lines="7 13-14 17-18 21-22"
+{!> ../../../docs_src/extra_models/tutorial002_py310.py!}
+```
- ```Python hl_lines="7 13-14 17-18 21-22"
- {!> ../../../docs_src/extra_models/tutorial002_py310.py!}
- ```
+////
## `Union` ou `anyOf`
Para fazer isso, use a dica de tipo padrão do Python <a href="https://docs.python.org/3/library/typing.html#typing.Union" class="external-link" target="_blank">`typing.Union`</a>:
-!!! note
- Ao definir um <a href="https://docs.pydantic.dev/latest/concepts/types/#unions" class="external-link" target="_blank">`Union`</a>, inclua o tipo mais específico primeiro, seguido pelo tipo menos específico. No exemplo abaixo, o tipo mais específico `PlaneItem` vem antes de `CarItem` em `Union[PlaneItem, CarItem]`.
+/// note
+
+Ao definir um <a href="https://docs.pydantic.dev/latest/concepts/types/#unions" class="external-link" target="_blank">`Union`</a>, inclua o tipo mais específico primeiro, seguido pelo tipo menos específico. No exemplo abaixo, o tipo mais específico `PlaneItem` vem antes de `CarItem` em `Union[PlaneItem, CarItem]`.
-=== "Python 3.8 and above"
+///
- ```Python hl_lines="1 14-15 18-20 33"
- {!> ../../../docs_src/extra_models/tutorial003.py!}
- ```
+//// tab | Python 3.8 and above
-=== "Python 3.10 and above"
+```Python hl_lines="1 14-15 18-20 33"
+{!> ../../../docs_src/extra_models/tutorial003.py!}
+```
+
+////
- ```Python hl_lines="1 14-15 18-20 33"
- {!> ../../../docs_src/extra_models/tutorial003_py310.py!}
- ```
+//// tab | Python 3.10 and above
+
+```Python hl_lines="1 14-15 18-20 33"
+{!> ../../../docs_src/extra_models/tutorial003_py310.py!}
+```
+
+////
### `Union` no Python 3.10
Para isso, use o padrão Python `typing.List` (ou simplesmente `list` no Python 3.9 e superior):
-=== "Python 3.8 and above"
+//// tab | Python 3.8 and above
- ```Python hl_lines="1 20"
- {!> ../../../docs_src/extra_models/tutorial004.py!}
- ```
+```Python hl_lines="1 20"
+{!> ../../../docs_src/extra_models/tutorial004.py!}
+```
-=== "Python 3.9 and above"
+////
- ```Python hl_lines="18"
- {!> ../../../docs_src/extra_models/tutorial004_py39.py!}
- ```
+//// tab | Python 3.9 and above
+
+```Python hl_lines="18"
+{!> ../../../docs_src/extra_models/tutorial004_py39.py!}
+```
+
+////
## Resposta com `dict` arbitrário
Neste caso, você pode usar `typing.Dict` (ou simplesmente dict no Python 3.9 e superior):
-=== "Python 3.8 and above"
+//// tab | Python 3.8 and above
+
+```Python hl_lines="1 8"
+{!> ../../../docs_src/extra_models/tutorial005.py!}
+```
+
+////
- ```Python hl_lines="1 8"
- {!> ../../../docs_src/extra_models/tutorial005.py!}
- ```
+//// tab | Python 3.9 and above
-=== "Python 3.9 and above"
+```Python hl_lines="6"
+{!> ../../../docs_src/extra_models/tutorial005_py39.py!}
+```
- ```Python hl_lines="6"
- {!> ../../../docs_src/extra_models/tutorial005_py39.py!}
- ```
+////
## Em resumo
</div>
-!!! note "Nota"
- O comando `uvicorn main:app` se refere a:
+/// note | "Nota"
- * `main`: o arquivo `main.py` (o "módulo" Python).
- * `app`: o objeto criado no arquivo `main.py` com a linha `app = FastAPI()`.
- * `--reload`: faz o servidor reiniciar após mudanças de código. Use apenas para desenvolvimento.
+O comando `uvicorn main:app` se refere a:
+
+* `main`: o arquivo `main.py` (o "módulo" Python).
+* `app`: o objeto criado no arquivo `main.py` com a linha `app = FastAPI()`.
+* `--reload`: faz o servidor reiniciar após mudanças de código. Use apenas para desenvolvimento.
+
+///
Na saída, temos:
`FastAPI` é uma classe Python que fornece todas as funcionalidades para sua API.
-!!! note "Detalhes técnicos"
- `FastAPI` é uma classe que herda diretamente de `Starlette`.
+/// note | "Detalhes técnicos"
+
+`FastAPI` é uma classe que herda diretamente de `Starlette`.
- Você pode usar todas as funcionalidades do <a href="https://www.starlette.io/" class="external-link" target="_blank">Starlette</a> com `FastAPI` também.
+Você pode usar todas as funcionalidades do <a href="https://www.starlette.io/" class="external-link" target="_blank">Starlette</a> com `FastAPI` também.
+
+///
### Passo 2: crie uma "instância" de `FastAPI`
/items/foo
```
-!!! info "Informação"
- Uma "rota" também é comumente chamada de "endpoint".
+/// info | "Informação"
+
+Uma "rota" também é comumente chamada de "endpoint".
+
+///
Ao construir uma API, a "rota" é a principal forma de separar "preocupações" e "recursos".
* a rota `/`
* usando o <abbr title="o método HTTP GET">operador <code>get</code></abbr>
-!!! 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:
* `@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**
{!../../../docs_src/first_steps/tutorial003.py!}
```
-!!! note "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
}
```
-!!! 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
{"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
### `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 <a href="https://docs.pydantic.dev/latest/#error-handling" class="external-link" target="_blank">`ValidationError`</a> existente no Pydantic.
{!../../../docs_src/handling_errors/tutorial004.py!}
```
-!!! note "Detalhes Técnicos"
- Você pode usar `from starlette.responses import PlainTextResponse`.
+/// note | "Detalhes Técnicos"
+
+Você pode usar `from starlette.responses import PlainTextResponse`.
- **FastAPI** disponibiliza o mesmo `starlette.responses` como `fastapi.responses`, como conveniência a você, desenvolvedor. Contudo, a maior parte das respostas disponíveis vem diretamente do Starlette.
+**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`.
Primeiro importe `Header`:
-=== "Python 3.10+"
+//// tab | Python 3.10+
- ```Python hl_lines="1"
- {!> ../../../docs_src/header_params/tutorial001_py310.py!}
- ```
+```Python hl_lines="1"
+{!> ../../../docs_src/header_params/tutorial001_py310.py!}
+```
+
+////
+
+//// tab | Python 3.8+
-=== "Python 3.8+"
+```Python hl_lines="3"
+{!> ../../../docs_src/header_params/tutorial001.py!}
+```
- ```Python hl_lines="3"
- {!> ../../../docs_src/header_params/tutorial001.py!}
- ```
+////
## Declare parâmetros de `Header`
O primeiro valor é o valor padrão, você pode passar todas as validações adicionais ou parâmetros de anotação:
-=== "Python 3.10+"
+//// tab | Python 3.10+
+
+```Python hl_lines="7"
+{!> ../../../docs_src/header_params/tutorial001_py310.py!}
+```
+
+////
+
+//// tab | Python 3.8+
+
+```Python hl_lines="9"
+{!> ../../../docs_src/header_params/tutorial001.py!}
+```
+
+////
+
+/// note | "Detalhes Técnicos"
- ```Python hl_lines="7"
- {!> ../../../docs_src/header_params/tutorial001_py310.py!}
- ```
+`Header` é uma classe "irmã" de `Path`, `Query` e `Cookie`. Ela também herda da mesma classe em comum `Param`.
-=== "Python 3.8+"
+Mas lembre-se que quando você importa `Query`, `Path`, `Header`, e outras de `fastapi`, elas são na verdade funções que retornam classes especiais.
- ```Python hl_lines="9"
- {!> ../../../docs_src/header_params/tutorial001.py!}
- ```
+///
-!!! note "Detalhes Técnicos"
- `Header` é uma classe "irmã" de `Path`, `Query` e `Cookie`. Ela também herda da mesma classe em comum `Param`.
+/// info
- Mas lembre-se que quando você importa `Query`, `Path`, `Header`, e outras de `fastapi`, elas são na verdade funções que retornam classes especiais.
+Para declarar headers, você precisa usar `Header`, caso contrário, os parâmetros seriam interpretados como parâmetros de consulta.
-!!! info
- Para declarar headers, você precisa usar `Header`, caso contrário, os parâmetros seriam interpretados como parâmetros de consulta.
+///
## Conversão automática
Se por algum motivo você precisar desabilitar a conversão automática de sublinhados para hífens, defina o parâmetro `convert_underscores` de `Header` para `False`:
-=== "Python 3.10+"
+//// tab | Python 3.10+
- ```Python hl_lines="8"
- {!> ../../../docs_src/header_params/tutorial002_py310.py!}
- ```
+```Python hl_lines="8"
+{!> ../../../docs_src/header_params/tutorial002_py310.py!}
+```
+
+////
+
+//// tab | Python 3.8+
+
+```Python hl_lines="10"
+{!> ../../../docs_src/header_params/tutorial002.py!}
+```
+
+////
-=== "Python 3.8+"
+/// warning | "Aviso"
- ```Python hl_lines="10"
- {!> ../../../docs_src/header_params/tutorial002.py!}
- ```
+Antes de definir `convert_underscores` como `False`, lembre-se de que alguns proxies e servidores HTTP não permitem o uso de cabeçalhos com sublinhados.
-!!! warning "Aviso"
- Antes de definir `convert_underscores` como `False`, lembre-se de que alguns proxies e servidores HTTP não permitem o uso de cabeçalhos com sublinhados.
+///
## Cabeçalhos duplicados
Por exemplo, para declarar um cabeçalho de `X-Token` que pode aparecer mais de uma vez, você pode escrever:
-=== "Python 3.10+"
+//// tab | Python 3.10+
- ```Python hl_lines="7"
- {!> ../../../docs_src/header_params/tutorial003_py310.py!}
- ```
+```Python hl_lines="7"
+{!> ../../../docs_src/header_params/tutorial003_py310.py!}
+```
+
+////
+
+//// tab | Python 3.9+
-=== "Python 3.9+"
+```Python hl_lines="9"
+{!> ../../../docs_src/header_params/tutorial003_py39.py!}
+```
+
+////
- ```Python hl_lines="9"
- {!> ../../../docs_src/header_params/tutorial003_py39.py!}
- ```
+//// tab | Python 3.8+
-=== "Python 3.8+"
+```Python hl_lines="9"
+{!> ../../../docs_src/header_params/tutorial003.py!}
+```
- ```Python hl_lines="9"
- {!> ../../../docs_src/header_params/tutorial003.py!}
- ```
+////
Se você se comunicar com essa *operação de caminho* enviando dois cabeçalhos HTTP como:
...isso também inclui o `uvicorn`, que você pode usar como o servidor que rodará seu código.
-!!! note "Nota"
- Você também pode instalar parte por parte.
+/// note | "Nota"
- Isso é provavelmente o que você faria quando você quisesse lançar sua aplicação em produção:
+Você também pode instalar parte por parte.
- ```
- pip install fastapi
- ```
+Isso é provavelmente o que você faria quando você quisesse lançar sua aplicação em produção:
- Também instale o `uvicorn` para funcionar como servidor:
+```
+pip install fastapi
+```
+
+Também instale o `uvicorn` para funcionar como servidor:
+
+```
+pip install "uvicorn[standard]"
+```
- ```
- pip install "uvicorn[standard]"
- ```
+E o mesmo para cada dependência opcional que você quiser usar.
- E o mesmo para cada dependência opcional que você quiser usar.
+///
## Guia Avançado de Usuário
* Ele pode fazer algo com essa **resposta** ou executar qualquer código necessário.
* Então ele retorna a **resposta**.
-!!! note "Detalhes técnicos"
- Se você tiver dependências com `yield`, o código de saída será executado *depois* do middleware.
+/// note | "Detalhes técnicos"
- Se houver alguma tarefa em segundo plano (documentada posteriormente), ela será executada *depois* de todo o middleware.
+Se você tiver dependências com `yield`, o código de saída será executado *depois* do middleware.
+
+Se houver alguma tarefa em segundo plano (documentada posteriormente), ela será executada *depois* de todo o middleware.
+
+///
## Criar um middleware
{!../../../docs_src/middleware/tutorial001.py!}
```
-!!! tip "Dica"
- Tenha em mente que cabeçalhos proprietários personalizados podem ser adicionados <a href="https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers" class="external-link" target="_blank">usando o prefixo 'X-'</a>.
+/// tip | "Dica"
+
+Tenha em mente que cabeçalhos proprietários personalizados podem ser adicionados <a href="https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers" class="external-link" target="_blank">usando o prefixo 'X-'</a>.
+
+Mas se você tiver cabeçalhos personalizados desejando que um cliente em um navegador esteja apto a ver, você precisa adicioná-los às suas configurações CORS ([CORS (Cross-Origin Resource Sharing)](cors.md){.internal-link target=_blank}) usando o parâmetro `expose_headers` documentado em <a href="https://www.starlette.io/middleware/#corsmiddleware" class="external-link" target="_blank">Documentos CORS da Starlette</a>.
+
+///
+
+/// note | "Detalhes técnicos"
- Mas se você tiver cabeçalhos personalizados desejando que um cliente em um navegador esteja apto a ver, você precisa adicioná-los às suas configurações CORS ([CORS (Cross-Origin Resource Sharing)](cors.md){.internal-link target=_blank}) usando o parâmetro `expose_headers` documentado em <a href="https://www.starlette.io/middleware/#corsmiddleware" class="external-link" target="_blank">Documentos CORS da Starlette</a>.
+Você também pode usar `from starlette.requests import Request`.
-!!! note "Detalhes técnicos"
- Você também pode usar `from starlette.requests import Request`.
+**FastAPI** fornece isso como uma conveniência para você, o desenvolvedor. Mas vem diretamente da Starlette.
- **FastAPI** fornece isso como uma conveniência para você, o desenvolvedor. Mas vem diretamente da Starlette.
+///
### Antes e depois da `response`
Existem vários parâmetros que você pode passar para o seu *decorador de operação de rota* para configurá-lo.
-!!! warning "Aviso"
- Observe que esses parâmetros são passados diretamente para o *decorador de operação de rota*, não para a sua *função de operação de rota*.
+/// warning | "Aviso"
+
+Observe que esses parâmetros são passados diretamente para o *decorador de operação de rota*, não para a sua *função de operação de rota*.
+
+///
## Código de Status da Resposta
Mas se você não se lembrar o que cada código numérico significa, pode usar as constantes de atalho em `status`:
-=== "Python 3.8 and above"
+//// tab | Python 3.8 and above
+
+```Python hl_lines="3 17"
+{!> ../../../docs_src/path_operation_configuration/tutorial001.py!}
+```
+
+////
- ```Python hl_lines="3 17"
- {!> ../../../docs_src/path_operation_configuration/tutorial001.py!}
- ```
+//// tab | Python 3.9 and above
-=== "Python 3.9 and above"
+```Python hl_lines="3 17"
+{!> ../../../docs_src/path_operation_configuration/tutorial001_py39.py!}
+```
+
+////
- ```Python hl_lines="3 17"
- {!> ../../../docs_src/path_operation_configuration/tutorial001_py39.py!}
- ```
+//// tab | Python 3.10 and above
-=== "Python 3.10 and above"
+```Python hl_lines="1 15"
+{!> ../../../docs_src/path_operation_configuration/tutorial001_py310.py!}
+```
- ```Python hl_lines="1 15"
- {!> ../../../docs_src/path_operation_configuration/tutorial001_py310.py!}
- ```
+////
Esse código de status será usado na resposta e será adicionado ao esquema OpenAPI.
-!!! note "Detalhes Técnicos"
- Você também poderia usar `from starlette import status`.
+/// note | "Detalhes Técnicos"
+
+Você também poderia usar `from starlette import status`.
+
+**FastAPI** fornece o mesmo `starlette.status` como `fastapi.status` apenas como uma conveniência para você, o desenvolvedor. Mas vem diretamente do Starlette.
- **FastAPI** fornece o mesmo `starlette.status` como `fastapi.status` apenas como uma conveniência para você, o desenvolvedor. Mas vem diretamente do Starlette.
+///
## Tags
Você pode adicionar tags para sua *operação de rota*, passe o parâmetro `tags` com uma `list` de `str` (comumente apenas um `str`):
-=== "Python 3.8 and above"
+//// tab | Python 3.8 and above
- ```Python hl_lines="17 22 27"
- {!> ../../../docs_src/path_operation_configuration/tutorial002.py!}
- ```
+```Python hl_lines="17 22 27"
+{!> ../../../docs_src/path_operation_configuration/tutorial002.py!}
+```
+
+////
-=== "Python 3.9 and above"
+//// tab | Python 3.9 and above
- ```Python hl_lines="17 22 27"
- {!> ../../../docs_src/path_operation_configuration/tutorial002_py39.py!}
- ```
+```Python hl_lines="17 22 27"
+{!> ../../../docs_src/path_operation_configuration/tutorial002_py39.py!}
+```
-=== "Python 3.10 and above"
+////
- ```Python hl_lines="15 20 25"
- {!> ../../../docs_src/path_operation_configuration/tutorial002_py310.py!}
- ```
+//// tab | Python 3.10 and above
+
+```Python hl_lines="15 20 25"
+{!> ../../../docs_src/path_operation_configuration/tutorial002_py310.py!}
+```
+
+////
Eles serão adicionados ao esquema OpenAPI e usados pelas interfaces de documentação automática:
Você pode adicionar um `summary` e uma `description`:
-=== "Python 3.8 and above"
+//// tab | Python 3.8 and above
+
+```Python hl_lines="20-21"
+{!> ../../../docs_src/path_operation_configuration/tutorial003.py!}
+```
+
+////
- ```Python hl_lines="20-21"
- {!> ../../../docs_src/path_operation_configuration/tutorial003.py!}
- ```
+//// tab | Python 3.9 and above
-=== "Python 3.9 and above"
+```Python hl_lines="20-21"
+{!> ../../../docs_src/path_operation_configuration/tutorial003_py39.py!}
+```
+
+////
- ```Python hl_lines="20-21"
- {!> ../../../docs_src/path_operation_configuration/tutorial003_py39.py!}
- ```
+//// tab | Python 3.10 and above
-=== "Python 3.10 and above"
+```Python hl_lines="18-19"
+{!> ../../../docs_src/path_operation_configuration/tutorial003_py310.py!}
+```
- ```Python hl_lines="18-19"
- {!> ../../../docs_src/path_operation_configuration/tutorial003_py310.py!}
- ```
+////
## Descrição do docstring
Você pode escrever <a href="https://en.wikipedia.org/wiki/Markdown" class="external-link" target="_blank">Markdown</a> na docstring, ele será interpretado e exibido corretamente (levando em conta a indentação da docstring).
-=== "Python 3.8 and above"
+//// tab | Python 3.8 and above
+
+```Python hl_lines="19-27"
+{!> ../../../docs_src/path_operation_configuration/tutorial004.py!}
+```
+
+////
- ```Python hl_lines="19-27"
- {!> ../../../docs_src/path_operation_configuration/tutorial004.py!}
- ```
+//// tab | Python 3.9 and above
-=== "Python 3.9 and above"
+```Python hl_lines="19-27"
+{!> ../../../docs_src/path_operation_configuration/tutorial004_py39.py!}
+```
- ```Python hl_lines="19-27"
- {!> ../../../docs_src/path_operation_configuration/tutorial004_py39.py!}
- ```
+////
-=== "Python 3.10 and above"
+//// tab | Python 3.10 and above
- ```Python hl_lines="17-25"
- {!> ../../../docs_src/path_operation_configuration/tutorial004_py310.py!}
- ```
+```Python hl_lines="17-25"
+{!> ../../../docs_src/path_operation_configuration/tutorial004_py310.py!}
+```
+
+////
Ela será usada nas documentações interativas:
Você pode especificar a descrição da resposta com o parâmetro `response_description`:
-=== "Python 3.8 and above"
+//// tab | Python 3.8 and above
+
+```Python hl_lines="21"
+{!> ../../../docs_src/path_operation_configuration/tutorial005.py!}
+```
+
+////
+
+//// tab | Python 3.9 and above
+
+```Python hl_lines="21"
+{!> ../../../docs_src/path_operation_configuration/tutorial005_py39.py!}
+```
+
+////
+
+//// tab | Python 3.10 and above
+
+```Python hl_lines="19"
+{!> ../../../docs_src/path_operation_configuration/tutorial005_py310.py!}
+```
- ```Python hl_lines="21"
- {!> ../../../docs_src/path_operation_configuration/tutorial005.py!}
- ```
+////
-=== "Python 3.9 and above"
+/// info | "Informação"
- ```Python hl_lines="21"
- {!> ../../../docs_src/path_operation_configuration/tutorial005_py39.py!}
- ```
+Note que `response_description` se refere especificamente à resposta, a `description` se refere à *operação de rota* em geral.
-=== "Python 3.10 and above"
+///
- ```Python hl_lines="19"
- {!> ../../../docs_src/path_operation_configuration/tutorial005_py310.py!}
- ```
+/// check
-!!! info "Informação"
- Note que `response_description` se refere especificamente à resposta, a `description` se refere à *operação de rota* em geral.
+OpenAPI especifica que cada *operação de rota* requer uma descrição de resposta.
-!!! check
- OpenAPI especifica que cada *operação de rota* requer uma descrição de resposta.
+Então, se você não fornecer uma, o **FastAPI** irá gerar automaticamente uma de "Resposta bem-sucedida".
- Então, se você não fornecer uma, o **FastAPI** irá gerar automaticamente uma de "Resposta bem-sucedida".
+///
<img src="/img/tutorial/path-operation-configuration/image03.png">
Primeiro, importe `Path` de `fastapi`:
-=== "Python 3.10+"
+//// tab | Python 3.10+
- ```Python hl_lines="1"
- {!> ../../../docs_src/path_params_numeric_validations/tutorial001_py310.py!}
- ```
+```Python hl_lines="1"
+{!> ../../../docs_src/path_params_numeric_validations/tutorial001_py310.py!}
+```
+
+////
-=== "Python 3.8+"
+//// tab | Python 3.8+
+
+```Python hl_lines="3"
+{!> ../../../docs_src/path_params_numeric_validations/tutorial001.py!}
+```
- ```Python hl_lines="3"
- {!> ../../../docs_src/path_params_numeric_validations/tutorial001.py!}
- ```
+////
## Declare metadados
Por exemplo para declarar um valor de metadado `title` para o parâmetro de rota `item_id` você pode digitar:
-=== "Python 3.10+"
+//// tab | Python 3.10+
- ```Python hl_lines="8"
- {!> ../../../docs_src/path_params_numeric_validations/tutorial001_py310.py!}
- ```
+```Python hl_lines="8"
+{!> ../../../docs_src/path_params_numeric_validations/tutorial001_py310.py!}
+```
-=== "Python 3.8+"
+////
- ```Python hl_lines="10"
- {!> ../../../docs_src/path_params_numeric_validations/tutorial001.py!}
- ```
+//// tab | Python 3.8+
+
+```Python hl_lines="10"
+{!> ../../../docs_src/path_params_numeric_validations/tutorial001.py!}
+```
-!!! note "Nota"
- Um parâmetro de rota é sempre obrigatório, como se fizesse parte da rota.
+////
- Então, você deve declará-lo com `...` para marcá-lo como obrigatório.
+/// note | "Nota"
- Mesmo que você declare-o como `None` ou defina um valor padrão, isso não teria efeito algum, o parâmetro ainda seria obrigatório.
+Um parâmetro de rota é sempre obrigatório, como se fizesse parte da rota.
+
+Então, você deve declará-lo com `...` para marcá-lo como obrigatório.
+
+Mesmo que você declare-o como `None` ou defina um valor padrão, isso não teria efeito algum, o parâmetro ainda seria obrigatório.
+
+///
## Ordene os parâmetros de acordo com sua necessidade
* `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.
+///
Nesse caso, `item_id` está sendo declarado como um `int`.
-!!! check "Verifique"
+/// check | "Verifique"
+
+
+
+///
+
Isso vai dar à você suporte do seu editor dentro das funções, com verificações de erros, autocompletar, etc.
## Conversão de <abbr title="também conhecido como: serialização, parsing, marshalling">dados</abbr>
{"item_id":3}
```
-!!! check "Verifique"
+/// check | "Verifique"
+
+
+
+///
+
Observe que o valor recebido pela função (e também retornado por ela) é `3`, como um Python `int`, não como uma string `"3"`.
Então, com essa declaração de tipo, o **FastAPI** dá pra você um <abbr title="convertendo a string que veio do request HTTP em um dado Python">"parsing"</abbr> automático no request .
O mesmo erro apareceria se você tivesse fornecido um `float` ao invés de um `int`, como em: <a href="http://127.0.0.1:8000/items/4.2" class="external-link" target="_blank">http://127.0.0.1:8000/items/4.2</a>
-!!! check "Verifique"
+/// check | "Verifique"
+
+
+
+///
+
Então, com a mesma declaração de tipo do Python, o **FastAPI** dá pra você validação de dados.
Observe que o erro também mostra claramente o ponto exato onde a validação não passou.
<img src="/img/tutorial/path-params/image01.png">
-!!! check "Verifique"
+/// check | "Verifique"
+
+
+
+///
+
Novamente, apenas com a mesma declaração de tipo do Python, o **FastAPI** te dá de forma automática e interativa a documentação (integrada com o Swagger UI).
Veja que o parâmetro de rota está declarado como sendo um inteiro (int).
{!../../../docs_src/path_params/tutorial005.py!}
```
-!!! info "informação"
- <a href="https://docs.python.org/3/library/enum.html" class="external-link" target="_blank">Enumerations (ou enums) estão disponíveis no Python</a> desde a versão 3.4.
+/// info | "informação"
+
+<a href="https://docs.python.org/3/library/enum.html" class="external-link" target="_blank">Enumerations (ou enums) estão disponíveis no Python</a> desde a versão 3.4.
+
+///
+
+/// tip | "Dica"
+
+
+
+///
-!!! tip "Dica"
Se você está se perguntando, "AlexNet", "ResNet", e "LeNet" são apenas nomes de <abbr title="técnicamente, modelos de arquitetura de Deep Learning">modelos</abbr> de Machine Learning (aprendizado de máquina).
### Declare um *parâmetro de rota*
{!../../../docs_src/path_params/tutorial005.py!}
```
-!!! tip "Dica"
+/// tip | "Dica"
+
+
+
+///
+
Você também poderia acessar o valor `"lenet"` com `ModelName.lenet.value`
#### Retorne *membros de enumeration*
{!../../../docs_src/path_params/tutorial004.py!}
```
-!!! tip "Dica"
+/// tip | "Dica"
+
+
+
+///
+
Você poderia precisar que o parâmetro contivesse `/home/johndoe/myfile.txt`, com uma barra no inicio (`/`).
Neste caso, a URL deveria ser: `/files//home/johndoe/myfile.txt`, com barra dupla (`//`) entre `files` e `home`.
O parâmetro de consulta `q` é do tipo `Union[str, None]`, o que significa que é do tipo `str` mas que também pode ser `None`, e de fato, o valor padrão é `None`, então o FastAPI saberá que não é obrigatório.
-!!! note "Observação"
- O FastAPI saberá que o valor de `q` não é obrigatório por causa do valor padrão `= None`.
+/// note | "Observação"
- O `Union` em `Union[str, None]` não é usado pelo FastAPI, mas permitirá que seu editor lhe dê um melhor suporte e detecte erros.
+O FastAPI saberá que o valor de `q` não é obrigatório por causa do valor padrão `= None`.
+
+O `Union` em `Union[str, None]` não é usado pelo FastAPI, mas permitirá que seu editor lhe dê um melhor suporte e detecte erros.
+
+///
## Validação adicional
Mas o declara explicitamente como um parâmetro de consulta.
-!!! info "Informação"
- Tenha em mente que o FastAPI se preocupa com a parte:
+/// info | "Informação"
- ```Python
- = None
- ```
+Tenha em mente que o FastAPI se preocupa com a parte:
- Ou com:
+```Python
+= None
+```
- ```Python
- = Query(default=None)
- ```
+Ou com:
- E irá utilizar o `None` para detectar que o parâmetro de consulta não é obrigatório.
+```Python
+= Query(default=None)
+```
+
+E irá utilizar o `None` para detectar que o parâmetro de consulta não é obrigatório.
- O `Union` é apenas para permitir que seu editor de texto lhe dê um melhor suporte.
+O `Union` é apenas para permitir que seu editor de texto lhe dê um melhor suporte.
+
+///
Então, podemos passar mais parâmetros para `Query`. Neste caso, o parâmetro `max_length` que se aplica a textos:
{!../../../docs_src/query_params_str_validations/tutorial005.py!}
```
-!!! note "Observação"
- O parâmetro torna-se opcional quando possui um valor padrão.
+/// note | "Observação"
+
+O parâmetro torna-se opcional quando possui um valor padrão.
+
+///
## Torne-o obrigatório
{!../../../docs_src/query_params_str_validations/tutorial006.py!}
```
-!!! info "Informação"
- Se você nunca viu os `...` antes: é um valor único especial, faz <a href="https://docs.python.org/3/library/constants.html#Ellipsis" class="external-link" target="_blank">parte do Python e é chamado "Ellipsis"</a>.
+/// info | "Informação"
+
+Se você nunca viu os `...` antes: é um valor único especial, faz <a href="https://docs.python.org/3/library/constants.html#Ellipsis" class="external-link" target="_blank">parte do Python e é chamado "Ellipsis"</a>.
+
+///
Dessa forma o **FastAPI** saberá que o parâmetro é obrigatório.
}
```
-!!! tip "Dica"
- Para declarar um parâmetro de consulta com o tipo `list`, como no exemplo acima, você precisa usar explicitamente o `Query`, caso contrário será interpretado como um corpo da requisição.
+/// tip | "Dica"
+
+Para declarar um parâmetro de consulta com o tipo `list`, como no exemplo acima, você precisa usar explicitamente o `Query`, caso contrário será interpretado como um corpo da requisição.
+
+///
A documentação interativa da API irá atualizar de acordo, permitindo múltiplos valores:
{!../../../docs_src/query_params_str_validations/tutorial013.py!}
```
-!!! note "Observação"
- Tenha em mente que neste caso, o FastAPI não irá validar os conteúdos da lista.
+/// note | "Observação"
- Por exemplo, um `List[int]` iria validar (e documentar) que os contéudos da lista são números inteiros. Mas apenas `list` não.
+Tenha em mente que neste caso, o FastAPI não irá validar os conteúdos da lista.
+
+Por exemplo, um `List[int]` iria validar (e documentar) que os contéudos da lista são números inteiros. Mas apenas `list` não.
+
+///
## Declarando mais metadados
Essa informações serão inclusas no esquema do OpenAPI e utilizado pela documentação interativa e ferramentas externas.
-!!! note "Observação"
- Tenha em mente que cada ferramenta oferece diferentes níveis de suporte ao OpenAPI.
+/// note | "Observação"
+
+Tenha em mente que cada ferramenta oferece diferentes níveis de suporte ao OpenAPI.
+
+Algumas delas não exibem todas as informações extras que declaramos, ainda que na maioria dos casos, esses recursos estão planejados para desenvolvimento.
- Algumas delas não exibem todas as informações extras que declaramos, ainda que na maioria dos casos, esses recursos estão planejados para desenvolvimento.
+///
Você pode adicionar um `title`:
Da mesma forma, você pode declarar parâmetros de consulta opcionais, definindo o valor padrão para `None`:
-=== "Python 3.10+"
+//// tab | Python 3.10+
- ```Python hl_lines="7"
- {!> ../../../docs_src/query_params/tutorial002_py310.py!}
- ```
+```Python hl_lines="7"
+{!> ../../../docs_src/query_params/tutorial002_py310.py!}
+```
+
+////
+
+//// tab | Python 3.8+
-=== "Python 3.8+"
+```Python hl_lines="9"
+{!> ../../../docs_src/query_params/tutorial002.py!}
+```
- ```Python hl_lines="9"
- {!> ../../../docs_src/query_params/tutorial002.py!}
- ```
+////
Nesse caso, o parâmetro da função `q` será opcional, e `None` será o padrão.
-!!! check "Verificar"
- Você também pode notar que o **FastAPI** é esperto o suficiente para perceber que o parâmetro da rota `item_id` é um parâmetro da rota, e `q` não é, portanto, `q` é o parâmetro de consulta.
+/// check | "Verificar"
+
+Você também pode notar que o **FastAPI** é esperto o suficiente para perceber que o parâmetro da rota `item_id` é um parâmetro da rota, e `q` não é, portanto, `q` é o parâmetro de consulta.
+///
## Conversão dos tipos de parâmetros de consulta
Você também pode declarar tipos `bool`, e eles serão convertidos:
-=== "Python 3.10+"
+//// tab | Python 3.10+
- ```Python hl_lines="7"
- {!> ../../../docs_src/query_params/tutorial003_py310.py!}
- ```
+```Python hl_lines="7"
+{!> ../../../docs_src/query_params/tutorial003_py310.py!}
+```
+
+////
+
+//// tab | Python 3.8+
-=== "Python 3.8+"
+```Python hl_lines="9"
+{!> ../../../docs_src/query_params/tutorial003.py!}
+```
- ```Python hl_lines="9"
- {!> ../../../docs_src/query_params/tutorial003.py!}
- ```
+////
Nesse caso, se você for para:
Eles serão detectados pelo nome:
-=== "Python 3.10+"
+//// tab | Python 3.10+
- ```Python hl_lines="6 8"
- {!> ../../../docs_src/query_params/tutorial004_py310.py!}
- ```
+```Python hl_lines="6 8"
+{!> ../../../docs_src/query_params/tutorial004_py310.py!}
+```
+
+////
-=== "Python 3.8+"
+//// tab | Python 3.8+
- ```Python hl_lines="8 10"
- {!> ../../../docs_src/query_params/tutorial004.py!}
- ```
+```Python hl_lines="8 10"
+{!> ../../../docs_src/query_params/tutorial004.py!}
+```
+
+////
## Parâmetros de consulta obrigatórios
E claro, você pode definir alguns parâmetros como obrigatórios, alguns possuindo um valor padrão, e outros sendo totalmente opcionais:
-=== "Python 3.10+"
+//// tab | Python 3.10+
+
+```Python hl_lines="8"
+{!> ../../../docs_src/query_params/tutorial006_py310.py!}
+```
+
+////
- ```Python hl_lines="8"
- {!> ../../../docs_src/query_params/tutorial006_py310.py!}
- ```
+//// tab | Python 3.8+
-=== "Python 3.8+"
+```Python hl_lines="10"
+{!> ../../../docs_src/query_params/tutorial006.py!}
+```
- ```Python hl_lines="10"
- {!> ../../../docs_src/query_params/tutorial006.py!}
- ```
+////
Nesse caso, existem 3 parâmetros de consulta:
* `skip`, um `int` com o valor padrão `0`.
* `limit`, um `int` opcional.
-!!! tip "Dica"
- Você também poderia usar `Enum` da mesma forma que com [Path Parameters](path-params.md#valores-predefinidos){.internal-link target=_blank}.
+/// tip | "Dica"
+
+Você também poderia usar `Enum` da mesma forma que com [Path Parameters](path-params.md#valores-predefinidos){.internal-link target=_blank}.
+
+///
Você pode definir arquivos e campos de formulário ao mesmo tempo usando `File` e `Form`.
-!!! info "Informação"
- Para receber arquivos carregados e/ou dados de formulário, primeiro instale <a href="https://github.com/Kludex/python-multipart" class="external-link" target="_blank">`python-multipart`</a>.
+/// info | "Informação"
- Por exemplo: `pip install python-multipart`.
+Para receber arquivos carregados e/ou dados de formulário, primeiro instale <a href="https://github.com/Kludex/python-multipart" class="external-link" target="_blank">`python-multipart`</a>.
+Por exemplo: `pip install python-multipart`.
+
+///
## Importe `File` e `Form`
E você pode declarar alguns dos arquivos como `bytes` e alguns como `UploadFile`.
-!!! warning "Aviso"
- Você pode declarar vários parâmetros `File` e `Form` em uma *operação de caminho*, mas não é possível declarar campos `Body` para receber como JSON, pois a requisição terá o corpo codificado usando `multipart/form-data` ao invés de `application/json`.
+/// warning | "Aviso"
+
+Você pode declarar vários parâmetros `File` e `Form` em uma *operação de caminho*, mas não é possível declarar campos `Body` para 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.
- Isso não é uma limitação do **FastAPI** , é parte do protocolo HTTP.
+///
## Recapitulando
Quando você precisar receber campos de formulário ao invés de JSON, você pode usar `Form`.
-!!! info "Informação"
- Para usar formulários, primeiro instale <a href="https://github.com/Kludex/python-multipart" class="external-link" target="_blank">`python-multipart`</a>.
+/// info | "Informação"
- Ex: `pip install python-multipart`.
+Para usar formulários, primeiro instale <a href="https://github.com/Kludex/python-multipart" class="external-link" target="_blank">`python-multipart`</a>.
+
+Ex: `pip install python-multipart`.
+
+///
## Importe `Form`
Com `Form` você pode declarar os mesmos metadados e validação que com `Body` (e `Query`, `Path`, `Cookie`).
-!!! info "Informação"
- `Form` é uma classe que herda diretamente de `Body`.
+/// info | "Informação"
+
+`Form` é uma classe que herda diretamente de `Body`.
+
+///
+
+/// tip | "Dica"
-!!! tip "Dica"
- Para declarar corpos de formulário, você precisa usar `Form` explicitamente, porque sem ele os parâmetros seriam interpretados como parâmetros de consulta ou parâmetros de corpo (JSON).
+Para declarar corpos de formulário, você precisa usar `Form` explicitamente, porque sem ele os parâmetros seriam interpretados como parâmetros de consulta ou parâmetros de corpo (JSON).
+
+///
## Sobre "Campos de formulário"
O **FastAPI** fará a leitura desses dados no lugar certo em vez de JSON.
-!!! note "Detalhes técnicos"
- Os dados dos formulários são normalmente codificados usando o "tipo de mídia" `application/x-www-form-urlencoded`.
+/// note | "Detalhes técnicos"
+
+Os dados dos formulários são normalmente codificados usando o "tipo de mídia" `application/x-www-form-urlencoded`.
+
+ 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.
+
+Se você quiser ler mais sobre essas codificações e campos de formulário, vá para o <a href="https://developer.mozilla.org/pt-BR/docs/Web/HTTP/Methods/POST" class="external-link" target="_blank"><abbr title="Mozilla Developer Network">MDN</abbr> web docs para <code>POST</code></a>.
+
+///
- 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 <a href="https://developer.mozilla.org/pt-BR/docs/Web/HTTP/Methods/POST" class="external-link" target="_blank"><abbr title="Mozilla Developer Network">MDN</abbr> web docs para <code>POST</code></a>.
+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
{!../../../docs_src/response_status_code/tutorial001.py!}
```
-!!! note "Nota"
- Observe que `status_code` é um parâmetro do método "decorador" (get, post, etc). Não da sua função de *operação de caminho*, como todos os parâmetros e corpo.
+/// note | "Nota"
+
+Observe que `status_code` é um parâmetro do método "decorador" (get, post, etc). Não da sua função de *operação de caminho*, como todos os parâmetros e corpo.
+
+///
O parâmetro `status_code` recebe um número com o código de status HTTP.
-!!! info "Informação"
- `status_code` também pode receber um `IntEnum`, como o do Python <a href="https://docs.python.org/3/library/http.html#http.HTTPStatus" class="external-link" target="_blank">`http.HTTPStatus`</a>.
+/// info | "Informação"
+
+`status_code` também pode receber um `IntEnum`, como o do Python <a href="https://docs.python.org/3/library/http.html#http.HTTPStatus" class="external-link" target="_blank">`http.HTTPStatus`</a>.
+
+///
Dessa forma:
<img src="/img/tutorial/response-status-code/image01.png">
-!!! note "Nota"
- Alguns códigos de resposta (consulte a próxima seção) indicam que a resposta não possui um corpo.
+/// note | "Nota"
+
+Alguns códigos de resposta (consulte a próxima seção) indicam que a resposta não possui um corpo.
+
+O FastAPI sabe disso e produzirá documentos OpenAPI informando que não há corpo de resposta.
- O FastAPI sabe disso e produzirá documentos OpenAPI informando que não há corpo de resposta.
+///
## Sobre os códigos de status HTTP
-!!! note "Nota"
- Se você já sabe o que são códigos de status HTTP, pule para a próxima seção.
+/// note | "Nota"
+
+Se você já sabe o que são códigos de status HTTP, pule para a próxima seção.
+
+///
Em HTTP, você envia um código de status numérico de 3 dígitos como parte da resposta.
* Para erros genéricos do cliente, você pode usar apenas `400`.
* `500` e acima são para erros do servidor. Você quase nunca os usa diretamente. Quando algo der errado em alguma parte do código do seu aplicativo ou servidor, ele retornará automaticamente um desses códigos de status.
-!!! tip "Dica"
- Para saber mais sobre cada código de status e qual código serve para quê, verifique o <a href="https://developer.mozilla.org/pt-BR/docs/Web/HTTP/Status" class="external-link" target="_blank"><abbr title="Mozilla Developer Network">MDN</abbr> documentação sobre códigos de status HTTP</a>.
+/// tip | "Dica"
+
+Para saber mais sobre cada código de status e qual código serve para quê, verifique o <a href="https://developer.mozilla.org/pt-BR/docs/Web/HTTP/Status" class="external-link" target="_blank"><abbr title="Mozilla Developer Network">MDN</abbr> documentação sobre códigos de status HTTP</a>.
+
+///
## Atalho para lembrar os nomes
<img src="/img/tutorial/response-status-code/image02.png">
-!!! note "Detalhes técnicos"
- Você também pode usar `from starlette import status`.
+/// note | "Detalhes técnicos"
+
+Você também pode usar `from starlette import status`.
- **FastAPI** fornece o mesmo `starlette.status` como `fastapi.status` apenas como uma conveniência para você, o desenvolvedor. Mas vem diretamente da Starlette.
+**FastAPI** fornece o mesmo `starlette.status` como `fastapi.status` apenas como uma conveniência para você, o desenvolvedor. Mas vem diretamente da Starlette.
+///
## Alterando o padrão
Essas informações extras serão adicionadas como se encontram no **JSON Schema** de resposta desse modelo e serão usadas na documentação da API.
-!!! tip "Dica"
- Você pode usar a mesma técnica para estender o JSON Schema e adicionar suas próprias informações extras de forma personalizada.
+/// tip | "Dica"
- Por exemplo, você pode usar isso para adicionar metadados para uma interface de usuário de front-end, etc.
+Você pode usar a mesma técnica para estender o JSON Schema e adicionar suas próprias informações extras de forma personalizada.
+
+Por exemplo, você pode usar isso para adicionar metadados para uma interface de usuário de front-end, etc.
+
+///
## `Field` de argumentos adicionais
{!../../../docs_src/schema_extra_example/tutorial002.py!}
```
-!!! warning "Atenção"
- Lembre-se de que esses argumentos extras passados não adicionarão nenhuma validação, apenas informações extras, para fins de documentação.
+/// warning | "Atenção"
+
+Lembre-se de que esses argumentos extras passados não adicionarão nenhuma validação, apenas informações extras, para fins de documentação.
+
+///
## `example` e `examples` no OpenAPI
## Detalhes técnicos
-!!! warning "Atenção"
- Esses são detalhes muito técnicos sobre os padrões **JSON Schema** e **OpenAPI**.
+/// warning | "Atenção"
+
+Esses são detalhes muito técnicos sobre os padrões **JSON Schema** e **OpenAPI**.
+
+Se as ideias explicadas acima já funcionam para você, isso pode ser o suficiente, e você provavelmente não precisa desses detalhes, fique à vontade para pular.
- Se as ideias explicadas acima já funcionam para você, isso pode ser o suficiente, e você provavelmente não precisa desses detalhes, fique à vontade para pular.
+///
Quando você adiciona um exemplo dentro de um modelo Pydantic, usando `schema_extra` ou` Field(example="something") `esse exemplo é adicionado ao **JSON Schema** para esse modelo Pydantic.
## Execute-o
-!!! info "informação"
+/// info | "informação"
+
+
+
+///
+
Primeiro, instale <a href="https://github.com/Kludex/python-multipart" class="external-link" target="_blank">`python-multipart`</a>.
Ex: `pip install python-multipart`.
<img src="/img/tutorial/security/image01.png">
-!!! check "Botão de Autorizar!"
+/// check | "Botão de Autorizar!"
+
+
+
+///
+
Você já tem um novo "botão de autorizar!".
E seu *path operation* tem um pequeno cadeado no canto superior direito que você pode clicar.
<img src="/img/tutorial/security/image02.png">
-!!! note "Nota"
+/// note | "Nota"
+
+
+
+///
+
Não importa o que você digita no formulário, não vai funcionar ainda. Mas nós vamos chegar lá.
Claro que este não é o frontend para os usuários finais, mas é uma ótima ferramenta automática para documentar interativamente toda sua API.
Neste exemplo, nós vamos usar o **OAuth2** com o fluxo de **Senha**, usando um token **Bearer**. Fazemos isso usando a classe `OAuth2PasswordBearer`.
-!!! info "informação"
+/// info | "informação"
+
+
+
+///
+
Um token "bearer" não é a única opção.
Mas é a melhor no nosso caso.
{!../../../docs_src/security/tutorial001.py!}
```
-!!! tip "Dica"
+/// tip | "Dica"
+
+
+
+///
+
Esse `tokenUrl="token"` se refere a uma URL relativa que nós não criamos ainda. Como é uma URL relativa, é equivalente a `./token`.
Porque estamos usando uma URL relativa, se sua API estava localizada em `https://example.com/`, então irá referir-se à `https://example.com/token`. Mas se sua API estava localizada em `https://example.com/api/v1/`, então irá referir-se à `https://example.com/api/v1/token`.
Em breve também criaremos o atual path operation.
-!!! info "informação"
+/// info | "informação"
+
+
+
+///
+
Se você é um "Pythonista" muito rigoroso, você pode não gostar do estilo do nome do parâmetro `tokenUrl` em vez de `token_url`.
Isso ocorre porque está utilizando o mesmo nome que está nas especificações do OpenAPI. Então, se você precisa investigar mais sobre qualquer um desses esquemas de segurança, você pode simplesmente copiar e colar para encontrar mais informações sobre isso.
A **FastAPI** saberá que pode usar essa dependência para definir um "esquema de segurança" no esquema da OpenAPI (e na documentação da API automática).
-!!! info "Detalhes técnicos"
+/// info | "Detalhes técnicos"
+
+
+
+///
+
**FastAPI** saberá que pode usar a classe `OAuth2PasswordBearer` (declarada na dependência) para definir o esquema de segurança na OpenAPI porque herda de `fastapi.security.oauth2.OAuth2`, que por sua vez herda de `fastapi.security.base.Securitybase`.
Todos os utilitários de segurança que se integram com OpenAPI (e na documentação da API automática) herdam de `SecurityBase`, é assim que **FastAPI** pode saber como integrá-los no OpenAPI.
OAuth2 não especifica como criptografar a comunicação, ele espera que você tenha sua aplicação em um servidor HTTPS.
-!!! tip "Dica"
- Na seção sobre **deployment** você irá ver como configurar HTTPS de modo gratuito, usando Traefik e Let’s Encrypt.
+/// tip | "Dica"
+Na seção sobre **deployment** você irá ver como configurar HTTPS de modo gratuito, usando Traefik e Let’s Encrypt.
+
+///
## OpenID Connect
* Essa descoberta automática é o que é definido na especificação OpenID Connect.
-!!! tip "Dica"
- Integração com outros provedores de autenticação/autorização como Google, Facebook, Twitter, GitHub, etc. é bem possível e relativamente fácil.
+/// tip | "Dica"
+
+Integração com outros provedores de autenticação/autorização como Google, Facebook, Twitter, GitHub, etc. é bem possível e relativamente fácil.
+
+O problema mais complexo é criar um provedor de autenticação/autorização como eles, mas o FastAPI dá a você ferramentas para fazer isso facilmente, enquanto faz o trabalho pesado para você.
- O problema mais complexo é criar um provedor de autenticação/autorização como eles, mas o FastAPI dá a você ferramentas para fazer isso facilmente, enquanto faz o trabalho pesado para você.
+///
## **FastAPI** utilitários
{!../../../docs_src/static_files/tutorial001.py!}
```
-!!! note "Detalhes técnicos"
- Você também pode usar `from starlette.staticfiles import StaticFiles`.
+/// note | "Detalhes técnicos"
- O **FastAPI** fornece o mesmo que `starlette.staticfiles` como `fastapi.staticfiles` apenas como uma conveniência para você, o desenvolvedor. Mas na verdade vem diretamente da Starlette.
+Você também pode usar `from starlette.staticfiles import StaticFiles`.
+
+O **FastAPI** fornece o mesmo que `starlette.staticfiles` como `fastapi.staticfiles` apenas como uma conveniência para você, o desenvolvedor. Mas na verdade vem diretamente da Starlette.
+
+///
### O que é "Montagem"
Это был один из первых примеров **автоматического документирования API** и это была одна из первых идей, вдохновивших на создание **FastAPI**.
-!!! note "Заметка"
- Django REST Framework был создан Tom Christie.
- Он же создал Starlette и Uvicorn, на которых основан **FastAPI**.
+/// note | "Заметка"
-!!! check "Идея для **FastAPI**"
- Должно быть автоматическое создание документации API с пользовательским веб-интерфейсом.
+Django REST Framework был создан Tom Christie.
+Он же создал Starlette и Uvicorn, на которых основан **FastAPI**.
+
+///
+
+/// check | "Идея для **FastAPI**"
+
+Должно быть автоматическое создание документации API с пользовательским веб-интерфейсом.
+
+///
### <a href="https://flask.palletsprojects.com" class="external-link" target="_blank">Flask</a>
Простота Flask, показалась мне подходящей для создания API.
Но ещё нужно было найти "Django REST Framework" для Flask.
-!!! check "Идеи для **FastAPI**"
- Это будет микрофреймворк. К нему легко будет добавить необходимые инструменты и части.
+/// check | "Идеи для **FastAPI**"
+
+Это будет микрофреймворк. К нему легко будет добавить необходимые инструменты и части.
- Должна быть простая и лёгкая в использовании система маршрутизации запросов.
+Должна быть простая и лёгкая в использовании система маршрутизации запросов.
+///
### <a href="https://requests.readthedocs.io" class="external-link" target="_blank">Requests</a>
Глядите, как похоже `requests.get(...)` и `@app.get(...)`.
-!!! check "Идеи для **FastAPI**"
- * Должен быть простой и понятный API.
- * Нужно использовать названия HTTP-методов (операций) для упрощения понимания происходящего.
- * Должны быть разумные настройки по умолчанию и широкие возможности их кастомизации.
+/// check | "Идеи для **FastAPI**"
+
+* Должен быть простой и понятный API.
+* Нужно использовать названия HTTP-методов (операций) для упрощения понимания происходящего.
+* Должны быть разумные настройки по умолчанию и широкие возможности их кастомизации.
+///
### <a href="https://swagger.io/" class="external-link" target="_blank">Swagger</a> / <a href="https://github.com/OAI/OpenAPI-Specification/" class="external-link" target="_blank">OpenAPI</a>
Вот почему, когда говорят о версии 2.0, обычно говорят "Swagger", а для версии 3+ "OpenAPI".
-!!! check "Идеи для **FastAPI**"
- Использовать открытые стандарты для спецификаций API вместо самодельных схем.
+/// check | "Идеи для **FastAPI**"
- Совместимость с основанными на стандартах пользовательскими интерфейсами:
+Использовать открытые стандарты для спецификаций API вместо самодельных схем.
- * <a href="https://github.com/swagger-api/swagger-ui" class="external-link" target="_blank">Swagger UI</a>
- * <a href="https://github.com/Rebilly/ReDoc" class="external-link" target="_blank">ReDoc</a>
+Совместимость с основанными на стандартах пользовательскими интерфейсами:
- Они были выбраны за популярность и стабильность.
- Но сделав беглый поиск, Вы можете найти десятки альтернативных пользовательских интерфейсов для OpenAPI, которые Вы можете использовать с **FastAPI**.
+* <a href="https://github.com/swagger-api/swagger-ui" class="external-link" target="_blank">Swagger UI</a>
+* <a href="https://github.com/Rebilly/ReDoc" class="external-link" target="_blank">ReDoc</a>
+
+Они были выбраны за популярность и стабильность.
+Но сделав беглый поиск, Вы можете найти десятки альтернативных пользовательских интерфейсов для OpenAPI, которые Вы можете использовать с **FastAPI**.
+
+///
### REST фреймворки для Flask
Итак, чтобы определить каждую <abbr title="Формат данных">схему</abbr>,
Вам нужно использовать определенные утилиты и классы, предоставляемые Marshmallow.
-!!! check "Идея для **FastAPI**"
- Использовать код программы для автоматического создания "схем", определяющих типы данных и их проверку.
+/// check | "Идея для **FastAPI**"
+
+Использовать код программы для автоматического создания "схем", определяющих типы данных и их проверку.
+
+///
### <a href="https://webargs.readthedocs.io/en/latest/" class="external-link" target="_blank">Webargs</a>
Это превосходный инструмент и я тоже часто пользовался им до **FastAPI**.
-!!! info "Информация"
- Webargs бы создан разработчиками Marshmallow.
+/// info | "Информация"
+
+Webargs бы создан разработчиками Marshmallow.
+
+///
-!!! check "Идея для **FastAPI**"
- Должна быть автоматическая проверка входных данных.
+/// check | "Идея для **FastAPI**"
+
+Должна быть автоматическая проверка входных данных.
+
+///
### <a href="https://apispec.readthedocs.io/en/stable/" class="external-link" target="_blank">APISpec</a>
Редактор кода не особо может помочь в такой парадигме.
А изменив какие-то параметры или схемы для Marshmallow можно забыть отредактировать докстринг с YAML и сгенерированная схема становится недействительной.
-!!! info "Информация"
- APISpec тоже был создан авторами Marshmallow.
+/// info | "Информация"
+
+APISpec тоже был создан авторами Marshmallow.
+
+///
+
+/// check | "Идея для **FastAPI**"
+
+Необходима поддержка открытого стандарта для API - OpenAPI.
-!!! check "Идея для **FastAPI**"
- Необходима поддержка открытого стандарта для API - OpenAPI.
+///
### <a href="https://flask-apispec.readthedocs.io/en/latest/" class="external-link" target="_blank">Flask-apispec</a>
Эти генераторы проектов также стали основой для [Генераторов проектов с **FastAPI**](project-generation.md){.internal-link target=_blank}.
-!!! info "Информация"
- Как ни странно, но Flask-apispec тоже создан авторами Marshmallow.
+/// info | "Информация"
-!!! check "Идея для **FastAPI**"
- Схема OpenAPI должна создаваться автоматически и использовать тот же код, который осуществляет сериализацию и проверку данных.
+Как ни странно, но Flask-apispec тоже создан авторами Marshmallow.
+
+///
+
+/// check | "Идея для **FastAPI**"
+
+Схема OpenAPI должна создаваться автоматически и использовать тот же код, который осуществляет сериализацию и проверку данных.
+
+///
### <a href="https://nestjs.com/" class="external-link" target="_blank">NestJS</a> (и <a href="https://angular.io/" class="external-link" target="_blank">Angular</a>)
Кроме того, он не очень хорошо справляется с вложенными моделями.
Если в запросе имеется объект JSON, внутренние поля которого, в свою очередь, являются вложенными объектами JSON, это не может быть должным образом задокументировано и проверено.
-!!! check "Идеи для **FastAPI** "
- Нужно использовать подсказки типов, чтоб воспользоваться поддержкой редактора кода.
+/// check | "Идеи для **FastAPI** "
+
+Нужно использовать подсказки типов, чтоб воспользоваться поддержкой редактора кода.
+
+Нужна мощная система внедрения зависимостей. Необходим способ для уменьшения повторов кода.
- Нужна мощная система внедрения зависимостей. Необходим способ для уменьшения повторов кода.
+///
### <a href="https://sanic.readthedocs.io/en/latest/" class="external-link" target="_blank">Sanic</a>
Sanic был одним из первых чрезвычайно быстрых Python-фреймворков основанных на `asyncio`.
Он был сделан очень похожим на Flask.
-!!! note "Технические детали"
- В нём использован <a href="https://github.com/MagicStack/uvloop" class="external-link" target="_blank">`uvloop`</a> вместо стандартного цикла событий `asyncio`, что и сделало его таким быстрым.
+/// note | "Технические детали"
- Он явно вдохновил создателей Uvicorn и Starlette, которые в настоящее время быстрее Sanic в открытых бенчмарках.
+В нём использован <a href="https://github.com/MagicStack/uvloop" class="external-link" target="_blank">`uvloop`</a> вместо стандартного цикла событий `asyncio`, что и сделало его таким быстрым.
-!!! check "Идеи для **FastAPI**"
- Должна быть сумасшедшая производительность.
+Он явно вдохновил создателей Uvicorn и Starlette, которые в настоящее время быстрее Sanic в открытых бенчмарках.
- Для этого **FastAPI** основан на Starlette, самом быстром из доступных фреймворков (по замерам незаинтересованных лиц).
+///
+
+/// check | "Идеи для **FastAPI**"
+
+Должна быть сумасшедшая производительность.
+
+Для этого **FastAPI** основан на Starlette, самом быстром из доступных фреймворков (по замерам незаинтересованных лиц).
+
+///
### <a href="https://falconframework.org/" class="external-link" target="_blank">Falcon</a>
Либо эти функции должны быть встроены во фреймворк, сконструированный поверх Falcon, как в Hug.
Такая же особенность присутствует и в других фреймворках, вдохновлённых идеей Falcon, использовать только один объект запроса и один объект ответа.
-!!! check "Идея для **FastAPI**"
- Найдите способы добиться отличной производительности.
+/// check | "Идея для **FastAPI**"
+
+Найдите способы добиться отличной производительности.
+
+Объявлять параметры `ответа сервера` в функциях, как в Hug.
- Объявлять параметры `ответа сервера` в функциях, как в Hug.
+Хотя в FastAPI это необязательно и используется в основном для установки заголовков, куки и альтернативных кодов состояния.
- Хотя в FastAPI это необязательно и используется в основном для установки заголовков, куки и альтернативных кодов состояния.
+///
### <a href="https://moltenframework.com/" class="external-link" target="_blank">Molten</a>
Это больше похоже на Django, чем на Flask и Starlette.
Он разделяет в коде вещи, которые довольно тесно связаны.
-!!! check "Идея для **FastAPI**"
- Определить дополнительные проверки типов данных, используя значения атрибутов модели "по умолчанию".
- Это улучшает помощь редактора и раньше это не было доступно в Pydantic.
+/// check | "Идея для **FastAPI**"
- Фактически это подтолкнуло на обновление Pydantic для поддержки одинакового стиля проверок (теперь этот функционал уже доступен в Pydantic).
+Определить дополнительные проверки типов данных, используя значения атрибутов модели "по умолчанию".
+Это улучшает помощь редактора и раньше это не было доступно в Pydantic.
+
+Фактически это подтолкнуло на обновление Pydantic для поддержки одинакового стиля проверок (теперь этот функционал уже доступен в Pydantic).
+
+///
### <a href="https://www.hug.rest/" class="external-link" target="_blank">Hug</a>
Поскольку он основан на WSGI, старом стандарте для синхронных веб-фреймворков, он не может работать с веб-сокетами и другими модными штуками, но всё равно обладает высокой производительностью.
-!!! info "Информация"
- Hug создан Timothy Crosley, автором <a href="https://github.com/timothycrosley/isort" class="external-link" target="_blank">`isort`</a>, отличного инструмента для автоматической сортировки импортов в Python-файлах.
+/// info | "Информация"
+
+Hug создан Timothy Crosley, автором <a href="https://github.com/timothycrosley/isort" class="external-link" target="_blank">`isort`</a>, отличного инструмента для автоматической сортировки импортов в Python-файлах.
+
+///
+
+/// check | "Идеи для **FastAPI**"
+
+Hug повлиял на создание некоторых частей APIStar и был одним из инструментов, которые я счел наиболее многообещающими, наряду с APIStar.
-!!! check "Идеи для **FastAPI**"
- Hug повлиял на создание некоторых частей APIStar и был одним из инструментов, которые я счел наиболее многообещающими, наряду с APIStar.
+Hug натолкнул на мысли использовать в **FastAPI** подсказки типов Python для автоматического создания схемы, определяющей API и его параметры.
- Hug натолкнул на мысли использовать в **FastAPI** подсказки типов Python для автоматического создания схемы, определяющей API и его параметры.
+Hug вдохновил **FastAPI** объявить параметр `ответа` в функциях для установки заголовков и куки.
- Hug вдохновил **FastAPI** объявить параметр `ответа` в функциях для установки заголовков и куки.
+///
### <a href="https://github.com/encode/apistar" class="external-link" target="_blank">APIStar</a> (<= 0.5)
Ныне 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**
Его можно сравнить с Marshmallow, хотя в бенчмарках Pydantic быстрее, чем Marshmallow.
И он основан на тех же подсказках типов, которые отлично поддерживаются редакторами кода.
-!!! check "**FastAPI** использует Pydantic"
- Для проверки данных, сериализации данных и автоматической документации моделей (на основе JSON Schema).
+/// check | "**FastAPI** использует Pydantic"
+
+Для проверки данных, сериализации данных и автоматической документации моделей (на основе JSON Schema).
+
+Затем **FastAPI** берёт эти схемы JSON и помещает их в схему OpenAPI, не касаясь других вещей, которые он делает.
- Затем **FastAPI** берёт эти схемы JSON и помещает их в схему OpenAPI, не касаясь других вещей, которые он делает.
+///
### <a href="https://www.starlette.io/" class="external-link" target="_blank">Starlette</a>
**FastAPI** добавляет эти функции используя подсказки типов Python и Pydantic.
Ещё **FastAPI** добавляет систему внедрения зависимостей, утилиты безопасности, генерацию схемы OpenAPI и т.д.
-!!! note "Технические детали"
- ASGI - это новый "стандарт" разработанный участниками команды Django.
- Он пока что не является "стандартом в Python" (то есть принятым PEP), но процесс принятия запущен.
+/// note | "Технические детали"
- Тем не менее он уже используется в качестве "стандарта" несколькими инструментами.
- Это значительно улучшает совместимость, поскольку Вы можете переключиться с Uvicorn на любой другой ASGI-сервер (например, Daphne или Hypercorn) или Вы можете добавить ASGI-совместимые инструменты, такие как `python-socketio`.
+ASGI - это новый "стандарт" разработанный участниками команды Django.
+Он пока что не является "стандартом в Python" (то есть принятым PEP), но процесс принятия запущен.
-!!! check "**FastAPI** использует Starlette"
- В качестве ядра веб-сервиса для обработки запросов, добавив некоторые функции сверху.
+Тем не менее он уже используется в качестве "стандарта" несколькими инструментами.
+Это значительно улучшает совместимость, поскольку Вы можете переключиться с Uvicorn на любой другой ASGI-сервер (например, Daphne или Hypercorn) или Вы можете добавить ASGI-совместимые инструменты, такие как `python-socketio`.
- Класс `FastAPI` наследуется напрямую от класса `Starlette`.
+///
- Таким образом, всё что Вы могли делать со Starlette, Вы можете делать с **FastAPI**, по сути это прокачанный Starlette.
+/// check | "**FastAPI** использует Starlette"
+
+В качестве ядра веб-сервиса для обработки запросов, добавив некоторые функции сверху.
+
+Класс `FastAPI` наследуется напрямую от класса `Starlette`.
+
+Таким образом, всё что Вы могли делать со Starlette, Вы можете делать с **FastAPI**, по сути это прокачанный Starlette.
+
+///
### <a href="https://www.uvicorn.org/" class="external-link" target="_blank">Uvicorn</a>
Он рекомендуется в качестве сервера для Starlette и **FastAPI**.
-!!! check "**FastAPI** рекомендует его"
- Как основной сервер для запуска приложения **FastAPI**.
+/// check | "**FastAPI** рекомендует его"
+
+Как основной сервер для запуска приложения **FastAPI**.
+
+Вы можете объединить его с Gunicorn, чтобы иметь асинхронный многопроцессный сервер.
- Вы можете объединить его с Gunicorn, чтобы иметь асинхронный многопроцессный сервер.
+Узнать больше деталей можно в разделе [Развёртывание](deployment/index.md){.internal-link target=_blank}.
- Узнать больше деталей можно в разделе [Развёртывание](deployment/index.md){.internal-link target=_blank}.
+///
## Тестовые замеры и скорость
return results
```
-!!! note
- `await` можно использовать только внутри функций, объявленных с использованием `async def`.
+/// note
+
+`await` можно использовать только внутри функций, объявленных с использованием `async def`.
+
+///
---
## Очень технические подробности
-!!! warning
- Этот раздел читать не обязательно.
+/// warning
+
+Этот раздел читать не обязательно.
+
+Здесь приводятся подробности внутреннего устройства **FastAPI**.
- Здесь приводятся подробности внутреннего устройства **FastAPI**.
+Но если вы обладаете техническими знаниями (корутины, потоки, блокировка и т. д.)
+и вам интересно, как FastAPI обрабатывает `async def` в отличие от обычных `def`,
+читайте дальше.
- Но если вы обладаете техническими знаниями (корутины, потоки, блокировка и т. д.)
- и вам интересно, как FastAPI обрабатывает `async def` в отличие от обычных `def`,
- читайте дальше.
+///
### Функции обработки пути
Активируйте виртуально окружение командой:
-=== "Linux, macOS"
+//// tab | Linux, macOS
- <div class="termy">
+<div class="termy">
- ```console
- $ source ./env/bin/activate
- ```
+```console
+$ source ./env/bin/activate
+```
+
+</div>
- </div>
+////
-=== "Windows PowerShell"
+//// tab | Windows PowerShell
+
+<div class="termy">
+
+```console
+$ .\env\Scripts\Activate.ps1
+```
- <div class="termy">
+</div>
- ```console
- $ .\env\Scripts\Activate.ps1
- ```
+////
- </div>
+//// tab | Windows Bash
-=== "Windows Bash"
+Если Вы пользуетесь Bash для Windows (например: <a href="https://gitforwindows.org/" class="external-link" target="_blank">Git Bash</a>):
- Если Вы пользуетесь Bash для Windows (например: <a href="https://gitforwindows.org/" class="external-link" target="_blank">Git Bash</a>):
+<div class="termy">
- <div class="termy">
+```console
+$ source ./env/Scripts/activate
+```
- ```console
- $ source ./env/Scripts/activate
- ```
+</div>
- </div>
+////
Проверьте, что всё сработало:
-=== "Linux, macOS, Windows Bash"
+//// tab | Linux, macOS, Windows Bash
+
+<div class="termy">
+
+```console
+$ which pip
- <div class="termy">
+some/directory/fastapi/env/bin/pip
+```
- ```console
- $ which pip
+</div>
- some/directory/fastapi/env/bin/pip
- ```
+////
- </div>
+//// tab | Windows PowerShell
-=== "Windows PowerShell"
+<div class="termy">
- <div class="termy">
+```console
+$ Get-Command pip
- ```console
- $ Get-Command pip
+some/directory/fastapi/env/bin/pip
+```
- some/directory/fastapi/env/bin/pip
- ```
+</div>
- </div>
+////
Если в терминале появится ответ, что бинарник `pip` расположен по пути `.../env/bin/pip`, значит всё в порядке. 🎉
</div>
-!!! tip "Подсказка"
- Каждый раз, перед установкой новой библиотеки в виртуальное окружение при помощи `pip`, не забудьте активировать это виртуальное окружение.
+/// tip | "Подсказка"
+
+Каждый раз, перед установкой новой библиотеки в виртуальное окружение при помощи `pip`, не забудьте активировать это виртуальное окружение.
+
+Это гарантирует, что если Вы используете библиотеку, установленную этим пакетом, то Вы используете библиотеку из Вашего локального окружения, а не любую другую, которая может быть установлена глобально.
- Это гарантирует, что если Вы используете библиотеку, установленную этим пакетом, то Вы используете библиотеку из Вашего локального окружения, а не любую другую, которая может быть установлена глобально.
+///
### pip
Также существуют дополнительные инструменты/скрипты для работы с переводами в `./scripts/docs.py`.
-!!! tip "Подсказка"
+/// tip | "Подсказка"
- Нет необходимости заглядывать в `./scripts/docs.py`, просто используйте это в командной строке.
+Нет необходимости заглядывать в `./scripts/docs.py`, просто используйте это в командной строке.
+
+///
Вся документация имеет формат Markdown и расположена в директории `./docs/en/`.
* Проверьте <a href="https://github.com/fastapi/fastapi/pulls" class="external-link" target="_blank">существующие пул-реквесты</a> для Вашего языка. Добавьте отзывы с просьбой внести изменения, если они необходимы, или одобрите их.
-!!! tip "Подсказка"
- Вы можете <a href="https://help.github.com/en/github/collaborating-with-issues-and-pull-requests/commenting-on-a-pull-request" class="external-link" target="_blank">добавлять комментарии с предложениями по изменению</a> в существующие пул-реквесты.
+/// tip | "Подсказка"
+
+Вы можете <a href="https://help.github.com/en/github/collaborating-with-issues-and-pull-requests/commenting-on-a-pull-request" class="external-link" target="_blank">добавлять комментарии с предложениями по изменению</a> в существующие пул-реквесты.
+
+Ознакомьтесь с документацией о <a href="https://help.github.com/en/github/collaborating-with-issues-and-pull-requests/about-pull-request-reviews" class="external-link" target="_blank">добавлении отзыва к пул-реквесту</a>, чтобы утвердить его или запросить изменения.
- Ознакомьтесь с документацией о <a href="https://help.github.com/en/github/collaborating-with-issues-and-pull-requests/about-pull-request-reviews" class="external-link" target="_blank">добавлении отзыва к пул-реквесту</a>, чтобы утвердить его или запросить изменения.
+///
* Проверьте <a href="https://github.com/fastapi/fastapi/issues" class="external-link" target="_blank">проблемы и вопросы</a>, чтобы узнать, есть ли кто-то, координирующий переводы для Вашего языка.
Кодом испанского языка является `es`. А значит директория для переводов на испанский язык: `docs/es/`.
-!!! tip "Подсказка"
- Главный ("официальный") язык - английский, директория для него `docs/en/`.
+/// tip | "Подсказка"
+
+Главный ("официальный") язык - английский, директория для него `docs/en/`.
+
+///
Вы можете запустить сервер документации на испанском:
docs/es/docs/features.md
```
-!!! tip "Подсказка"
- Заметьте, что в пути файла мы изменили только код языка с `en` на `es`.
+/// tip | "Подсказка"
+
+Заметьте, что в пути файла мы изменили только код языка с `en` на `es`.
+
+///
* Теперь откройте файл конфигурации MkDocs для английского языка, расположенный тут:
После чего Вы можете проверить в своем редакторе кода, что появился новый каталог `docs/ht/`.
-!!! tip "Подсказка"
- Создайте первый пул-реквест, который будет содержать только пустую директорию для нового языка, прежде чем добавлять переводы.
+/// tip | "Подсказка"
+
+Создайте первый пул-реквест, который будет содержать только пустую директорию для нового языка, прежде чем добавлять переводы.
+
+Таким образом, другие участники могут переводить другие страницы, пока Вы работаете над одной. 🚀
- Таким образом, другие участники могут переводить другие страницы, пока Вы работаете над одной. 🚀
+///
Начните перевод с главной страницы `docs/ht/index.md`.
Для случаев, когда ошибки приводят к сбою в запущенном **процессе**, Вам понадобится добавить компонент, который **перезапустит** процесс хотя бы пару раз...
-!!! tip "Заметка"
- ... Если приложение падает сразу же после запуска, вероятно бесполезно его бесконечно перезапускать. Но полагаю, вы заметите такое поведение во время разработки или, по крайней мере, сразу после развёртывания.
+/// tip | "Заметка"
- Так что давайте сосредоточимся на конкретных случаях, когда приложение может полностью выйти из строя, но всё ещё есть смысл его запустить заново.
+... Если приложение падает сразу же после запуска, вероятно бесполезно его бесконечно перезапускать. Но полагаю, вы заметите такое поведение во время разработки или, по крайней мере, сразу после развёртывания.
+
+Так что давайте сосредоточимся на конкретных случаях, когда приложение может полностью выйти из строя, но всё ещё есть смысл его запустить заново.
+
+///
Возможно вы захотите, чтоб был некий **внешний компонент**, ответственный за перезапуск вашего приложения даже если уже не работает Uvicorn или Python. То есть ничего из того, что написано в вашем коде внутри приложения, не может быть выполнено в принципе.
* **Облачные сервисы**, которые позаботятся обо всём за Вас
* Возможно, что облачный сервис умеет **управлять запуском дополнительных экземпляров приложения**. Вероятно, он потребует, чтоб вы указали - какой **процесс** или **образ** следует клонировать. Скорее всего, вы укажете **один процесс Uvicorn** и облачный сервис будет запускать его копии при необходимости.
-!!! tip "Заметка"
- Если вы не знаете, что такое **контейнеры**, Docker или Kubernetes, не переживайте.
+/// tip | "Заметка"
+
+Если вы не знаете, что такое **контейнеры**, Docker или Kubernetes, не переживайте.
+
+Я поведаю Вам о контейнерах, образах, Docker, Kubernetes и т.п. в главе: [FastAPI внутри контейнеров - Docker](docker.md){.internal-link target=_blank}.
- Я поведаю Вам о контейнерах, образах, Docker, Kubernetes и т.п. в главе: [FastAPI внутри контейнеров - Docker](docker.md){.internal-link target=_blank}.
+///
## Шаги, предшествующие запуску
Безусловно, возможны случаи, когда нет проблем при выполнении предварительной подготовки параллельно или несколько раз. Тогда Вам повезло, работать с ними намного проще.
-!!! tip "Заметка"
- Имейте в виду, что в некоторых случаях запуск вашего приложения **может не требовать каких-либо предварительных шагов вовсе**.
+/// tip | "Заметка"
- Что ж, тогда Вам не нужно беспокоиться об этом. 🤷
+Имейте в виду, что в некоторых случаях запуск вашего приложения **может не требовать каких-либо предварительных шагов вовсе**.
+
+Что ж, тогда Вам не нужно беспокоиться об этом. 🤷
+
+///
### Примеры стратегий запуска предварительных шагов
* Bash-скрипт, выполняющий предварительные шаги, а затем запускающий приложение.
* При этом Вам всё ещё нужно найти способ - как запускать/перезапускать *такой* bash-скрипт, обнаруживать ошибки и т.п.
-!!! tip "Заметка"
- Я приведу Вам больше конкретных примеров работы с контейнерами в главе: [FastAPI внутри контейнеров - Docker](docker.md){.internal-link target=_blank}.
+/// tip | "Заметка"
+
+Я приведу Вам больше конкретных примеров работы с контейнерами в главе: [FastAPI внутри контейнеров - Docker](docker.md){.internal-link target=_blank}.
+
+///
## Утилизация ресурсов
Использование контейнеров на основе Linux имеет ряд преимуществ, включая **безопасность**, **воспроизводимость**, **простоту** и прочие.
-!!! tip "Подсказка"
- Торопитесь или уже знакомы с этой технологией? Перепрыгните на раздел [Создать Docker-образ для FastAPI 👇](#docker-fastapi)
+/// tip | "Подсказка"
+
+Торопитесь или уже знакомы с этой технологией? Перепрыгните на раздел [Создать Docker-образ для FastAPI 👇](#docker-fastapi)
+
+///
<details>
<summary>Развернуть Dockerfile 👀</summary>
</div>
-!!! info "Информация"
- Существуют и другие инструменты управления зависимостями.
+/// info | "Информация"
+
+Существуют и другие инструменты управления зависимостями.
- В этом же разделе, но позже, я покажу вам пример использования Poetry. 👇
+В этом же разделе, но позже, я покажу вам пример использования Poetry. 👇
+
+///
### Создать приложение **FastAPI**
Так как команда выполняется внутри директории `/code`, в которую мы поместили папку `./app` с приложением, то **Uvicorn** сможет найти и **импортировать** объект `app` из файла `app.main`.
-!!! tip "Подсказка"
- Если ткнёте на кружок с плюсом, то увидите пояснения. 👆
+/// tip | "Подсказка"
+
+Если ткнёте на кружок с плюсом, то увидите пояснения. 👆
+
+///
На данном этапе структура проекта должны выглядеть так:
</div>
-!!! tip "Подсказка"
- Обратите внимание, что в конце написана точка - `.`, это то же самое что и `./`, тем самым мы указываем Docker директорию, из которой нужно выполнять сборку образа контейнера.
+/// tip | "Подсказка"
+
+Обратите внимание, что в конце написана точка - `.`, это то же самое что и `./`, тем самым мы указываем Docker директорию, из которой нужно выполнять сборку образа контейнера.
+
+В данном случае это та же самая директория (`.`).
- В данном случае это та же самая директория (`.`).
+///
### Запуск Docker-контейнера
Это может быть другой контейнер, в котором есть, например, <a href="https://traefik.io/" class="external-link" target="_blank">Traefik</a>, работающий с **HTTPS** и **самостоятельно** обновляющий **сертификаты**.
-!!! tip "Подсказка"
- Traefik совместим с Docker, Kubernetes и им подобными инструментами. Он очень прост в установке и настройке использования HTTPS для Ваших контейнеров.
+/// tip | "Подсказка"
+
+Traefik совместим с Docker, Kubernetes и им подобными инструментами. Он очень прост в установке и настройке использования HTTPS для Ваших контейнеров.
+
+///
В качестве альтернативы, работу с HTTPS можно доверить облачному провайдеру, если он предоставляет такую услугу.
Поскольку этот компонент **принимает запросы** и равномерно **распределяет** их между компонентами, его также называют **балансировщиком нагрузки**.
-!!! tip "Подсказка"
- **Прокси-сервер завершения работы TLS** одновременно может быть **балансировщиком нагрузки**.
+/// tip | "Подсказка"
+
+**Прокси-сервер завершения работы TLS** одновременно может быть **балансировщиком нагрузки**.
+
+///
Система оркестрации, которую вы используете для запуска и управления контейнерами, имеет встроенный инструмент **сетевого взаимодействия** (например, для передачи HTTP-запросов) между контейнерами с Вашими приложениями и **балансировщиком нагрузки** (который также может быть **прокси-сервером**).
Когда вы запускаете **множество контейнеров**, в каждом из которых работает **только один процесс** (например, в кластере **Kubernetes**), может возникнуть необходимость иметь **отдельный контейнер**, который осуществит **предварительные шаги перед запуском** остальных контейнеров (например, применяет миграции к базе данных).
-!!! info "Информация"
- При использовании Kubernetes, это может быть <a href="https://kubernetes.io/docs/concepts/workloads/pods/init-containers/" class="external-link" target="_blank">Инициализирующий контейнер</a>.
+/// info | "Информация"
+
+При использовании Kubernetes, это может быть <a href="https://kubernetes.io/docs/concepts/workloads/pods/init-containers/" class="external-link" target="_blank">Инициализирующий контейнер</a>.
+
+///
При отсутствии такой необходимости (допустим, не нужно применять миграции к базе данных, а только проверить, что она готова принимать соединения), вы можете проводить такую проверку в каждом контейнере перед запуском его основного процесса и запускать все контейнеры **одновременно**.
* <a href="https://github.com/tiangolo/uvicorn-gunicorn-fastapi-docker" class="external-link" target="_blank">tiangolo/uvicorn-gunicorn-fastapi</a>.
-!!! warning "Предупреждение"
- Скорее всего у вас **нет необходимости** в использовании этого образа или подобного ему и лучше создать свой образ с нуля как описано тут: [Создать Docker-образ для FastAPI](#docker-fastapi).
+/// warning | "Предупреждение"
+
+Скорее всего у вас **нет необходимости** в использовании этого образа или подобного ему и лучше создать свой образ с нуля как описано тут: [Создать Docker-образ для FastAPI](#docker-fastapi).
+
+///
В этом образе есть **автоматический** механизм подстройки для запуска **необходимого количества процессов** в соответствии с доступным количеством ядер процессора.
Он также поддерживает прохождение <a href="https://github.com/tiangolo/uvicorn-gunicorn-fastapi-docker#pre_start_path" class="external-link" target="_blank">**Подготовительных шагов при запуске контейнеров**</a> при помощи скрипта.
-!!! tip "Подсказка"
- Для просмотра всех возможных настроек перейдите на страницу этого Docker-образа: <a href="https://github.com/tiangolo/uvicorn-gunicorn-fastapi-docker" class="external-link" target="_blank">tiangolo/uvicorn-gunicorn-fastapi</a>.
+/// tip | "Подсказка"
+
+Для просмотра всех возможных настроек перейдите на страницу этого Docker-образа: <a href="https://github.com/tiangolo/uvicorn-gunicorn-fastapi-docker" class="external-link" target="_blank">tiangolo/uvicorn-gunicorn-fastapi</a>.
+
+///
### Количество процессов в официальном Docker-образе
11. Запустите `uvicorn`, указав ему использовать объект `app`, расположенный в `app.main`.
-!!! tip "Подсказка"
- Если ткнёте на кружок с плюсом, то увидите объяснения, что происходит в этой строке.
+/// tip | "Подсказка"
+
+Если ткнёте на кружок с плюсом, то увидите объяснения, что происходит в этой строке.
+
+///
**Этапы сборки Docker-образа** являются частью `Dockerfile` и работают как **временные образы контейнеров**. Они нужны только для создания файлов, используемых в дальнейших этапах.
Но всё несколько сложнее.
-!!! tip "Заметка"
- Если вы торопитесь или вам не интересно, можете перейти на следующую страницу этого пошагового руководства по размещению приложений на серверах с использованием различных технологий.
+/// tip | "Заметка"
+
+Если вы торопитесь или вам не интересно, можете перейти на следующую страницу этого пошагового руководства по размещению приложений на серверах с использованием различных технологий.
+
+///
Чтобы **изучить основы HTTPS** для клиента, перейдите по ссылке <a href="https://howhttps.works/" class="external-link" target="_blank">https://howhttps.works/</a>.
Обычно эту запись достаточно указать один раз, при первоначальной настройке всего сервера.
-!!! tip "Заметка"
- Уровни протоколов, работающих с именами доменов, намного ниже HTTPS, но об этом следует упомянуть здесь, так как всё зависит от доменов и IP-адресов.
+/// tip | "Заметка"
+
+Уровни протоколов, работающих с именами доменов, намного ниже HTTPS, но об этом следует упомянуть здесь, так как всё зависит от доменов и IP-адресов.
+
+///
### DNS
Таким образом, **HTTPS** это тот же **HTTP**, но внутри **безопасного TLS-соединения** вместо чистого (незашифрованного) TCP-соединения.
-!!! tip "Заметка"
- Обратите внимание, что шифрование происходит на **уровне TCP**, а не на более высоком уровне HTTP.
+/// tip | "Заметка"
+
+Обратите внимание, что шифрование происходит на **уровне TCP**, а не на более высоком уровне HTTP.
+
+///
### HTTPS-запрос
Вы можете установить сервер, совместимый с протоколом ASGI, так:
-=== "Uvicorn"
+//// tab | Uvicorn
- * <a href="https://www.uvicorn.org/" class="external-link" target="_blank">Uvicorn</a>, очень быстрый ASGI сервер, основанный на библиотеках uvloop и httptools.
+* <a href="https://www.uvicorn.org/" class="external-link" target="_blank">Uvicorn</a>, очень быстрый ASGI сервер, основанный на библиотеках uvloop и httptools.
- <div class="termy">
+<div class="termy">
- ```console
- $ pip install "uvicorn[standard]"
+```console
+$ pip install "uvicorn[standard]"
- ---> 100%
- ```
+---> 100%
+```
- </div>
+</div>
+
+/// tip | "Подсказка"
- !!! tip "Подсказка"
- С опцией `standard`, Uvicorn будет устанавливаться и использоваться с некоторыми дополнительными рекомендованными зависимостями.
+С опцией `standard`, Uvicorn будет устанавливаться и использоваться с некоторыми дополнительными рекомендованными зависимостями.
- В них входит `uvloop`, высокопроизводительная замена `asyncio`, которая значительно ускоряет работу асинхронных программ.
+В них входит `uvloop`, высокопроизводительная замена `asyncio`, которая значительно ускоряет работу асинхронных программ.
-=== "Hypercorn"
+///
- * <a href="https://github.com/pgjones/hypercorn" class="external-link" target="_blank">Hypercorn</a>, ASGI сервер, поддерживающий протокол HTTP/2.
+////
- <div class="termy">
+//// tab | Hypercorn
- ```console
- $ pip install hypercorn
+* <a href="https://github.com/pgjones/hypercorn" class="external-link" target="_blank">Hypercorn</a>, ASGI сервер, поддерживающий протокол HTTP/2.
- ---> 100%
- ```
+<div class="termy">
- </div>
+```console
+$ pip install hypercorn
+
+---> 100%
+```
+
+</div>
- ...или какой-либо другой ASGI сервер.
+...или какой-либо другой ASGI сервер.
+
+////
## Запуск серверной программы
Затем запустите ваше приложение так же, как было указано в руководстве ранее, но без опции `--reload`:
-=== "Uvicorn"
+//// tab | Uvicorn
+
+<div class="termy">
+
+```console
+$ uvicorn main:app --host 0.0.0.0 --port 80
+
+<span style="color: green;">INFO</span>: Uvicorn running on http://0.0.0.0:80 (Press CTRL+C to quit)
+```
- <div class="termy">
+</div>
- ```console
- $ uvicorn main:app --host 0.0.0.0 --port 80
+////
- <span style="color: green;">INFO</span>: Uvicorn running on http://0.0.0.0:80 (Press CTRL+C to quit)
- ```
+//// tab | Hypercorn
- </div>
+<div class="termy">
-=== "Hypercorn"
+```console
+$ hypercorn main:app --bind 0.0.0.0:80
- <div class="termy">
+Running on 0.0.0.0:8080 over http (CTRL + C to quit)
+```
- ```console
- $ hypercorn main:app --bind 0.0.0.0:80
+</div>
- Running on 0.0.0.0:8080 over http (CTRL + C to quit)
- ```
+////
- </div>
+/// warning | "Предупреждение"
-!!! warning "Предупреждение"
+Не забудьте удалить опцию `--reload`, если ранее пользовались ею.
- Не забудьте удалить опцию `--reload`, если ранее пользовались ею.
+Включение опции `--reload` требует дополнительных ресурсов, влияет на стабильность работы приложения и может повлечь прочие неприятности.
- Включение опции `--reload` требует дополнительных ресурсов, влияет на стабильность работы приложения и может повлечь прочие неприятности.
+Она сильно помогает во время **разработки**, но **не следует** использовать её при **реальной работе** приложения.
- Она сильно помогает во время **разработки**, но **не следует** использовать её при **реальной работе** приложения.
+///
## Hypercorn с Trio
FastAPI следует соглашению в том, что любые изменения "ПАТЧ"-версии предназначены для исправления багов и внесения обратно совместимых изменений.
-!!! tip "Подсказка"
- "ПАТЧ" - это последнее число. Например, в `0.2.3`, ПАТЧ-версия - это `3`.
+/// tip | "Подсказка"
+
+"ПАТЧ" - это последнее число. Например, в `0.2.3`, ПАТЧ-версия - это `3`.
+
+///
Итак, вы можете закрепить версию следующим образом:
Обратно несовместимые изменения и новые функции добавляются в "МИНОРНЫЕ" версии.
-!!! tip "Подсказка"
- "МИНОРНАЯ" версия - это число в середине. Например, в `0.2.3` МИНОРНАЯ версия - это `2`.
+/// tip | "Подсказка"
+
+"МИНОРНАЯ" версия - это число в середине. Например, в `0.2.3` МИНОРНАЯ версия - это `2`.
+
+///
## Обновление версий FastAPI
Вот неполный список некоторых из них.
-!!! tip
- Если у вас есть статья, проект, инструмент или что-либо, связанное с **FastAPI**, что еще не перечислено здесь, создайте <a href="https://github.com/fastapi/fastapi/edit/master/docs/en/data/external_links.yml" class="external-link" target="_blank">Pull Request</a>.
+/// tip
+
+Если у вас есть статья, проект, инструмент или что-либо, связанное с **FastAPI**, что еще не перечислено здесь, создайте <a href="https://github.com/fastapi/fastapi/edit/master/docs/en/data/external_links.yml" class="external-link" target="_blank">Pull Request</a>.
+
+///
{% for section_name, section_content in external_links.items() %}
my_second_user: User = User(**second_user_data)
```
-!!! info "Информация"
- `**second_user_data` означает:
+/// info | "Информация"
- Передать ключи и значения словаря `second_user_data`, в качестве аргументов типа "ключ-значение", это эквивалентно: `User(id=4, name="Mary", joined="2018-11-30")` .
+`**second_user_data` означает:
+
+Передать ключи и значения словаря `second_user_data`, в качестве аргументов типа "ключ-значение", это эквивалентно: `User(id=4, name="Mary", joined="2018-11-30")` .
+
+///
### Поддержка редакторов (IDE)
* Затем, используя **комментарий**, сообщите, что Вы сделали проверку, тогда я буду знать, что Вы действительно проверили код.
-!!! info "Информация"
- К сожалению, я не могу так просто доверять пул-реквестам, у которых уже есть несколько одобрений.
+/// info | "Информация"
- Бывали случаи, что пул-реквесты имели 3, 5 или больше одобрений, вероятно из-за привлекательного описания, но когда я проверял эти пул-реквесты, они оказывались сломаны, содержали ошибки или вовсе не решали проблему, которую, как они утверждали, должны были решить. 😅
+К сожалению, я не могу так просто доверять пул-реквестам, у которых уже есть несколько одобрений.
- Потому это действительно важно - проверять и запускать код, и комментарием уведомлять меня, что Вы проделали эти действия. 🤓
+Бывали случаи, что пул-реквесты имели 3, 5 или больше одобрений, вероятно из-за привлекательного описания, но когда я проверял эти пул-реквесты, они оказывались сломаны, содержали ошибки или вовсе не решали проблему, которую, как они утверждали, должны были решить. 😅
+
+Потому это действительно важно - проверять и запускать код, и комментарием уведомлять меня, что Вы проделали эти действия. 🤓
+
+///
* Если Вы считаете, что пул-реквест можно упростить, то можете попросить об этом, но не нужно быть слишком придирчивым, может быть много субъективных точек зрения (и у меня тоже будет своя 🙈), поэтому будет лучше, если Вы сосредоточитесь на фундаментальных вещах.
Подключайтесь к 👥 <a href="https://discord.gg/VQjSZaeJmf" class="external-link" target="_blank"> чату в Discord</a> 👥 и общайтесь с другими участниками сообщества FastAPI.
-!!! tip "Подсказка"
- Вопросы по проблемам с фреймворком лучше задавать в <a href="https://github.com/fastapi/fastapi/issues/new/choose" class="external-link" target="_blank">GitHub issues</a>, так больше шансов, что Вы получите помощь от [Экспертов FastAPI](fastapi-people.md#_3){.internal-link target=_blank}.
+/// tip | "Подсказка"
+
+Вопросы по проблемам с фреймворком лучше задавать в <a href="https://github.com/fastapi/fastapi/issues/new/choose" class="external-link" target="_blank">GitHub issues</a>, так больше шансов, что Вы получите помощь от [Экспертов FastAPI](fastapi-people.md#_3){.internal-link target=_blank}.
+
+Используйте этот чат только для бесед на отвлечённые темы.
- Используйте этот чат только для бесед на отвлечённые темы.
+///
### Не использовать чаты для вопросов
Но даже если вы никогда не используете **FastAPI**, вам будет полезно немного узнать о них.
-!!! note
- Если вы являетесь экспертом в Python и уже знаете всё об аннотациях типов, переходите к следующему разделу.
+/// note
+
+Если вы являетесь экспертом в Python и уже знаете всё об аннотациях типов, переходите к следующему разделу.
+
+///
## Мотивация
{!../../../docs_src/python_types/tutorial006.py!}
```
-!!! tip
- Эти внутренние типы в квадратных скобках называются «параметрами типов».
+/// tip
+
+Эти внутренние типы в квадратных скобках называются «параметрами типов».
+
+В этом случае `str` является параметром типа, передаваемым в `List`.
- В этом случае `str` является параметром типа, передаваемым в `List`.
+///
Это означает: "переменная `items` является `list`, и каждый из элементов этого списка является `str`".
{!../../../docs_src/python_types/tutorial011.py!}
```
-!!! info
- Чтобы узнать больше о <a href="https://docs.pydantic.dev/" class="external-link" target="_blank">Pydantic, читайте его документацию</a>.
+/// info
+
+Чтобы узнать больше о <a href="https://docs.pydantic.dev/" class="external-link" target="_blank">Pydantic, читайте его документацию</a>.
+
+///
**FastAPI** целиком основан на Pydantic.
Важно то, что при использовании стандартных типов Python в одном месте (вместо добавления дополнительных классов, декораторов и т.д.) **FastAPI** сделает за вас большую часть работы.
-!!! info
- Если вы уже прошли всё руководство и вернулись, чтобы узнать больше о типах, хорошим ресурсом является <a href="https://mypy.readthedocs.io/en/latest/cheat_sheet_py3.html" class="external-link" target="_blank">«шпаргалка» от `mypy`</a>.
+/// info
+
+Если вы уже прошли всё руководство и вернулись, чтобы узнать больше о типах, хорошим ресурсом является <a href="https://mypy.readthedocs.io/en/latest/cheat_sheet_py3.html" class="external-link" target="_blank">«шпаргалка» от `mypy`</a>.
+
+///
**FastAPI** знает, что нужно сделать в каждом случае и как переиспользовать тот же объект `BackgroundTasks`, так чтобы все фоновые задачи собрались и запустились вместе в фоне:
-=== "Python 3.10+"
+//// tab | Python 3.10+
- ```Python hl_lines="11 13 20 23"
- {!> ../../../docs_src/background_tasks/tutorial002_py310.py!}
- ```
+```Python hl_lines="11 13 20 23"
+{!> ../../../docs_src/background_tasks/tutorial002_py310.py!}
+```
+
+////
-=== "Python 3.8+"
+//// tab | Python 3.8+
+
+```Python hl_lines="13 15 22 25"
+{!> ../../../docs_src/background_tasks/tutorial002.py!}
+```
- ```Python hl_lines="13 15 22 25"
- {!> ../../../docs_src/background_tasks/tutorial002.py!}
- ```
+////
В этом примере сообщения будут записаны в `log.txt` *после* того, как ответ сервера был отправлен.
Сначала вы должны импортировать его:
-=== "Python 3.10+"
+//// tab | Python 3.10+
- ```Python hl_lines="2"
- {!> ../../../docs_src/body_fields/tutorial001_py310.py!}
- ```
+```Python hl_lines="2"
+{!> ../../../docs_src/body_fields/tutorial001_py310.py!}
+```
-=== "Python 3.8+"
+////
- ```Python hl_lines="4"
- {!> ../../../docs_src/body_fields/tutorial001.py!}
- ```
+//// tab | Python 3.8+
-!!! warning "Внимание"
- Обратите внимание, что функция `Field` импортируется непосредственно из `pydantic`, а не из `fastapi`, как все остальные функции (`Query`, `Path`, `Body` и т.д.).
+```Python hl_lines="4"
+{!> ../../../docs_src/body_fields/tutorial001.py!}
+```
+
+////
+
+/// warning | "Внимание"
+
+Обратите внимание, что функция `Field` импортируется непосредственно из `pydantic`, а не из `fastapi`, как все остальные функции (`Query`, `Path`, `Body` и т.д.).
+
+///
## Объявление атрибутов модели
Вы можете использовать функцию `Field` с атрибутами модели:
-=== "Python 3.10+"
+//// tab | Python 3.10+
+
+```Python hl_lines="9-12"
+{!> ../../../docs_src/body_fields/tutorial001_py310.py!}
+```
+
+////
- ```Python hl_lines="9-12"
- {!> ../../../docs_src/body_fields/tutorial001_py310.py!}
- ```
+//// tab | Python 3.8+
-=== "Python 3.8+"
+```Python hl_lines="11-14"
+{!> ../../../docs_src/body_fields/tutorial001.py!}
+```
- ```Python hl_lines="11-14"
- {!> ../../../docs_src/body_fields/tutorial001.py!}
- ```
+////
Функция `Field` работает так же, как `Query`, `Path` и `Body`, у неё такие же параметры и т.д.
-!!! note "Технические детали"
- На самом деле, `Query`, `Path` и другие функции, которые вы увидите в дальнейшем, создают объекты подклассов общего класса `Param`, который сам по себе является подклассом `FieldInfo` из Pydantic.
+/// note | "Технические детали"
- И `Field` (из Pydantic), и `Body`, оба возвращают объекты подкласса `FieldInfo`.
+На самом деле, `Query`, `Path` и другие функции, которые вы увидите в дальнейшем, создают объекты подклассов общего класса `Param`, который сам по себе является подклассом `FieldInfo` из Pydantic.
- У класса `Body` есть и другие подклассы, с которыми вы ознакомитесь позже.
+И `Field` (из Pydantic), и `Body`, оба возвращают объекты подкласса `FieldInfo`.
- Помните, что когда вы импортируете `Query`, `Path` и другое из `fastapi`, это фактически функции, которые возвращают специальные классы.
+У класса `Body` есть и другие подклассы, с которыми вы ознакомитесь позже.
-!!! tip "Подсказка"
- Обратите внимание, что каждый атрибут модели с типом, значением по умолчанию и `Field` имеет ту же структуру, что и параметр *функции обработки пути* с `Field` вместо `Path`, `Query` и `Body`.
+Помните, что когда вы импортируете `Query`, `Path` и другое из `fastapi`, это фактически функции, которые возвращают специальные классы.
+
+///
+
+/// tip | "Подсказка"
+
+Обратите внимание, что каждый атрибут модели с типом, значением по умолчанию и `Field` имеет ту же структуру, что и параметр *функции обработки пути* с `Field` вместо `Path`, `Query` и `Body`.
+
+///
## Добавление дополнительной информации
Вы узнаете больше о добавлении дополнительной информации позже в документации, когда будете изучать, как задавать примеры принимаемых данных.
-!!! warning "Внимание"
- Дополнительные ключи, переданные в функцию `Field`, также будут присутствовать в сгенерированной OpenAPI схеме вашего приложения.
- Поскольку эти ключи не являются обязательной частью спецификации OpenAPI, некоторые инструменты OpenAPI, например, [валидатор OpenAPI](https://validator.swagger.io/), могут не работать с вашей сгенерированной схемой.
+/// warning | "Внимание"
+
+Дополнительные ключи, переданные в функцию `Field`, также будут присутствовать в сгенерированной OpenAPI схеме вашего приложения.
+Поскольку эти ключи не являются обязательной частью спецификации OpenAPI, некоторые инструменты OpenAPI, например, [валидатор OpenAPI](https://validator.swagger.io/), могут не работать с вашей сгенерированной схемой.
+
+///
## Резюме
Вы также можете объявить параметры тела запроса как необязательные, установив значение по умолчанию, равное `None`:
-=== "Python 3.10+"
+//// tab | Python 3.10+
- ```Python hl_lines="18-20"
- {!> ../../../docs_src/body_multiple_params/tutorial001_an_py310.py!}
- ```
+```Python hl_lines="18-20"
+{!> ../../../docs_src/body_multiple_params/tutorial001_an_py310.py!}
+```
+
+////
-=== "Python 3.9+"
+//// tab | Python 3.9+
- ```Python hl_lines="18-20"
- {!> ../../../docs_src/body_multiple_params/tutorial001_an_py39.py!}
- ```
+```Python hl_lines="18-20"
+{!> ../../../docs_src/body_multiple_params/tutorial001_an_py39.py!}
+```
-=== "Python 3.8+"
+////
- ```Python hl_lines="19-21"
- {!> ../../../docs_src/body_multiple_params/tutorial001_an.py!}
- ```
+//// tab | Python 3.8+
+
+```Python hl_lines="19-21"
+{!> ../../../docs_src/body_multiple_params/tutorial001_an.py!}
+```
-=== "Python 3.10+ non-Annotated"
+////
- !!! tip "Заметка"
- Рекомендуется использовать `Annotated` версию, если это возможно.
+//// tab | Python 3.10+ non-Annotated
- ```Python hl_lines="17-19"
- {!> ../../../docs_src/body_multiple_params/tutorial001_py310.py!}
- ```
+/// tip | "Заметка"
+
+Рекомендуется использовать `Annotated` версию, если это возможно.
+
+///
+
+```Python hl_lines="17-19"
+{!> ../../../docs_src/body_multiple_params/tutorial001_py310.py!}
+```
-=== "Python 3.8+ non-Annotated"
+////
- !!! tip "Заметка"
- Рекомендуется использовать версию с `Annotated`, если это возможно.
+//// tab | Python 3.8+ non-Annotated
- ```Python hl_lines="19-21"
- {!> ../../../docs_src/body_multiple_params/tutorial001.py!}
- ```
+/// tip | "Заметка"
-!!! note "Заметка"
- Заметьте, что в данном случае параметр `item`, который будет взят из тела запроса, необязателен. Так как было установлено значение `None` по умолчанию.
+Рекомендуется использовать версию с `Annotated`, если это возможно.
+
+///
+
+```Python hl_lines="19-21"
+{!> ../../../docs_src/body_multiple_params/tutorial001.py!}
+```
+
+////
+
+/// note | "Заметка"
+
+Заметьте, что в данном случае параметр `item`, который будет взят из тела запроса, необязателен. Так как было установлено значение `None` по умолчанию.
+
+///
## Несколько параметров тела запроса
Но вы также можете объявить множество параметров тела запроса, например `item` и `user`:
-=== "Python 3.10+"
+//// tab | Python 3.10+
- ```Python hl_lines="20"
- {!> ../../../docs_src/body_multiple_params/tutorial002_py310.py!}
- ```
+```Python hl_lines="20"
+{!> ../../../docs_src/body_multiple_params/tutorial002_py310.py!}
+```
-=== "Python 3.8+"
+////
- ```Python hl_lines="22"
- {!> ../../../docs_src/body_multiple_params/tutorial002.py!}
- ```
+//// tab | Python 3.8+
+
+```Python hl_lines="22"
+{!> ../../../docs_src/body_multiple_params/tutorial002.py!}
+```
+
+////
В этом случае **FastAPI** заметит, что в функции есть более одного параметра тела (два параметра, которые являются моделями Pydantic).
}
```
-!!! note "Внимание"
- Обратите внимание, что хотя параметр `item` был объявлен таким же способом, как и раньше, теперь предпологается, что он находится внутри тела с ключом `item`.
+/// note | "Внимание"
+
+Обратите внимание, что хотя параметр `item` был объявлен таким же способом, как и раньше, теперь предпологается, что он находится внутри тела с ключом `item`.
+///
**FastAPI** сделает автоматические преобразование из запроса, так что параметр `item` получит своё конкретное содержимое, и то же самое происходит с пользователем `user`.
Но вы можете указать **FastAPI** обрабатывать его, как ещё один ключ тела запроса, используя `Body`:
-=== "Python 3.10+"
+//// tab | Python 3.10+
+
+```Python hl_lines="23"
+{!> ../../../docs_src/body_multiple_params/tutorial003_an_py310.py!}
+```
+
+////
+
+//// tab | Python 3.9+
- ```Python hl_lines="23"
- {!> ../../../docs_src/body_multiple_params/tutorial003_an_py310.py!}
- ```
+```Python hl_lines="23"
+{!> ../../../docs_src/body_multiple_params/tutorial003_an_py39.py!}
+```
+
+////
+
+//// tab | Python 3.8+
+
+```Python hl_lines="24"
+{!> ../../../docs_src/body_multiple_params/tutorial003_an.py!}
+```
+
+////
-=== "Python 3.9+"
+//// tab | Python 3.10+ non-Annotated
- ```Python hl_lines="23"
- {!> ../../../docs_src/body_multiple_params/tutorial003_an_py39.py!}
- ```
+/// tip | "Заметка"
-=== "Python 3.8+"
+Рекомендуется использовать `Annotated` версию, если это возможно.
- ```Python hl_lines="24"
- {!> ../../../docs_src/body_multiple_params/tutorial003_an.py!}
- ```
+///
-=== "Python 3.10+ non-Annotated"
+```Python hl_lines="20"
+{!> ../../../docs_src/body_multiple_params/tutorial003_py310.py!}
+```
- !!! tip "Заметка"
- Рекомендуется использовать `Annotated` версию, если это возможно.
+////
- ```Python hl_lines="20"
- {!> ../../../docs_src/body_multiple_params/tutorial003_py310.py!}
- ```
+//// tab | Python 3.8+ non-Annotated
-=== "Python 3.8+ non-Annotated"
+/// tip | "Заметка"
- !!! tip "Заметка"
- Рекомендуется использовать `Annotated` версию, если это возможно.
+Рекомендуется использовать `Annotated` версию, если это возможно.
- ```Python hl_lines="22"
- {!> ../../../docs_src/body_multiple_params/tutorial003.py!}
- ```
+///
+
+```Python hl_lines="22"
+{!> ../../../docs_src/body_multiple_params/tutorial003.py!}
+```
+
+////
В этом случае, **FastAPI** будет ожидать тело запроса в формате:
Например:
-=== "Python 3.10+"
+//// tab | Python 3.10+
+
+```Python hl_lines="27"
+{!> ../../../docs_src/body_multiple_params/tutorial004_an_py310.py!}
+```
+
+////
+
+//// tab | Python 3.9+
+
+```Python hl_lines="27"
+{!> ../../../docs_src/body_multiple_params/tutorial004_an_py39.py!}
+```
+
+////
+
+//// tab | Python 3.8+
+
+```Python hl_lines="28"
+{!> ../../../docs_src/body_multiple_params/tutorial004_an.py!}
+```
+
+////
+
+//// tab | Python 3.10+ non-Annotated
+
+/// tip | "Заметка"
+
+Рекомендуется использовать `Annotated` версию, если это возможно.
- ```Python hl_lines="27"
- {!> ../../../docs_src/body_multiple_params/tutorial004_an_py310.py!}
- ```
+///
-=== "Python 3.9+"
+```Python hl_lines="25"
+{!> ../../../docs_src/body_multiple_params/tutorial004_py310.py!}
+```
- ```Python hl_lines="27"
- {!> ../../../docs_src/body_multiple_params/tutorial004_an_py39.py!}
- ```
+////
-=== "Python 3.8+"
+//// tab | Python 3.8+ non-Annotated
- ```Python hl_lines="28"
- {!> ../../../docs_src/body_multiple_params/tutorial004_an.py!}
- ```
+/// tip | "Заметка"
-=== "Python 3.10+ non-Annotated"
+Рекомендуется использовать `Annotated` версию, если это возможно.
- !!! tip "Заметка"
- Рекомендуется использовать `Annotated` версию, если это возможно.
+///
- ```Python hl_lines="25"
- {!> ../../../docs_src/body_multiple_params/tutorial004_py310.py!}
- ```
+```Python hl_lines="27"
+{!> ../../../docs_src/body_multiple_params/tutorial004.py!}
+```
-=== "Python 3.8+ non-Annotated"
+////
- !!! tip "Заметка"
- Рекомендуется использовать `Annotated` версию, если это возможно.
+/// info | "Информация"
- ```Python hl_lines="27"
- {!> ../../../docs_src/body_multiple_params/tutorial004.py!}
- ```
+`Body` также имеет все те же дополнительные параметры валидации и метаданных, как у `Query`,`Path` и других, которые вы увидите позже.
-!!! info "Информация"
- `Body` также имеет все те же дополнительные параметры валидации и метаданных, как у `Query`,`Path` и других, которые вы увидите позже.
+///
## Добавление одного body-параметра
так же, как в этом примере:
-=== "Python 3.10+"
+//// tab | Python 3.10+
+
+```Python hl_lines="17"
+{!> ../../../docs_src/body_multiple_params/tutorial005_an_py310.py!}
+```
+
+////
+
+//// tab | Python 3.9+
+
+```Python hl_lines="17"
+{!> ../../../docs_src/body_multiple_params/tutorial005_an_py39.py!}
+```
+
+////
+
+//// tab | Python 3.8+
+
+```Python hl_lines="18"
+{!> ../../../docs_src/body_multiple_params/tutorial005_an.py!}
+```
+
+////
+
+//// tab | Python 3.10+ non-Annotated
- ```Python hl_lines="17"
- {!> ../../../docs_src/body_multiple_params/tutorial005_an_py310.py!}
- ```
+/// tip | "Заметка"
-=== "Python 3.9+"
+Рекомендуется использовать `Annotated` версию, если это возможно.
- ```Python hl_lines="17"
- {!> ../../../docs_src/body_multiple_params/tutorial005_an_py39.py!}
- ```
+///
-=== "Python 3.8+"
+```Python hl_lines="15"
+{!> ../../../docs_src/body_multiple_params/tutorial005_py310.py!}
+```
- ```Python hl_lines="18"
- {!> ../../../docs_src/body_multiple_params/tutorial005_an.py!}
- ```
+////
-=== "Python 3.10+ non-Annotated"
+//// tab | Python 3.8+ non-Annotated
- !!! tip "Заметка"
- Рекомендуется использовать `Annotated` версию, если это возможно.
+/// tip | "Заметка"
- ```Python hl_lines="15"
- {!> ../../../docs_src/body_multiple_params/tutorial005_py310.py!}
- ```
+Рекомендуется использовать `Annotated` версию, если это возможно.
-=== "Python 3.8+ non-Annotated"
+///
- !!! tip "Заметка"
- Рекомендуется использовать `Annotated` версию, если это возможно.
+```Python hl_lines="17"
+{!> ../../../docs_src/body_multiple_params/tutorial005.py!}
+```
- ```Python hl_lines="17"
- {!> ../../../docs_src/body_multiple_params/tutorial005.py!}
- ```
+////
В этом случае **FastAPI** будет ожидать тело запроса в формате:
Вы можете определять атрибут как подтип. Например, тип `list` в Python:
-=== "Python 3.10+"
+//// tab | Python 3.10+
- ```Python hl_lines="12"
- {!> ../../../docs_src/body_nested_models/tutorial001_py310.py!}
- ```
+```Python hl_lines="12"
+{!> ../../../docs_src/body_nested_models/tutorial001_py310.py!}
+```
+
+////
-=== "Python 3.8+"
+//// tab | Python 3.8+
+
+```Python hl_lines="14"
+{!> ../../../docs_src/body_nested_models/tutorial001.py!}
+```
- ```Python hl_lines="14"
- {!> ../../../docs_src/body_nested_models/tutorial001.py!}
- ```
+////
Это приведёт к тому, что обьект `tags` преобразуется в список, несмотря на то что тип его элементов не объявлен.
Таким образом, в нашем примере мы можем явно указать тип данных для поля `tags` как "список строк":
-=== "Python 3.10+"
+//// tab | Python 3.10+
+
+```Python hl_lines="12"
+{!> ../../../docs_src/body_nested_models/tutorial002_py310.py!}
+```
+
+////
+
+//// tab | Python 3.9+
- ```Python hl_lines="12"
- {!> ../../../docs_src/body_nested_models/tutorial002_py310.py!}
- ```
+```Python hl_lines="14"
+{!> ../../../docs_src/body_nested_models/tutorial002_py39.py!}
+```
-=== "Python 3.9+"
+////
- ```Python hl_lines="14"
- {!> ../../../docs_src/body_nested_models/tutorial002_py39.py!}
- ```
+//// tab | Python 3.8+
-=== "Python 3.8+"
+```Python hl_lines="14"
+{!> ../../../docs_src/body_nested_models/tutorial002.py!}
+```
- ```Python hl_lines="14"
- {!> ../../../docs_src/body_nested_models/tutorial002.py!}
- ```
+////
## Типы множеств
Тогда мы можем обьявить поле `tags` как множество строк:
-=== "Python 3.10+"
+//// tab | Python 3.10+
+
+```Python hl_lines="12"
+{!> ../../../docs_src/body_nested_models/tutorial003_py310.py!}
+```
+
+////
- ```Python hl_lines="12"
- {!> ../../../docs_src/body_nested_models/tutorial003_py310.py!}
- ```
+//// tab | Python 3.9+
-=== "Python 3.9+"
+```Python hl_lines="14"
+{!> ../../../docs_src/body_nested_models/tutorial003_py39.py!}
+```
- ```Python hl_lines="14"
- {!> ../../../docs_src/body_nested_models/tutorial003_py39.py!}
- ```
+////
-=== "Python 3.8+"
+//// tab | Python 3.8+
- ```Python hl_lines="1 14"
- {!> ../../../docs_src/body_nested_models/tutorial003.py!}
- ```
+```Python hl_lines="1 14"
+{!> ../../../docs_src/body_nested_models/tutorial003.py!}
+```
+
+////
С помощью этого, даже если вы получите запрос с повторяющимися данными, они будут преобразованы в множество уникальных элементов.
Например, мы можем определить модель `Image`:
-=== "Python 3.10+"
+//// tab | Python 3.10+
+
+```Python hl_lines="7-9"
+{!> ../../../docs_src/body_nested_models/tutorial004_py310.py!}
+```
+
+////
- ```Python hl_lines="7-9"
- {!> ../../../docs_src/body_nested_models/tutorial004_py310.py!}
- ```
+//// tab | Python 3.9+
-=== "Python 3.9+"
+```Python hl_lines="9-11"
+{!> ../../../docs_src/body_nested_models/tutorial004_py39.py!}
+```
+
+////
- ```Python hl_lines="9-11"
- {!> ../../../docs_src/body_nested_models/tutorial004_py39.py!}
- ```
+//// tab | Python 3.8+
-=== "Python 3.8+"
+```Python hl_lines="9-11"
+{!> ../../../docs_src/body_nested_models/tutorial004.py!}
+```
- ```Python hl_lines="9-11"
- {!> ../../../docs_src/body_nested_models/tutorial004.py!}
- ```
+////
### Использование вложенной модели в качестве типа
Также мы можем использовать эту модель как тип атрибута:
-=== "Python 3.10+"
+//// tab | Python 3.10+
- ```Python hl_lines="18"
- {!> ../../../docs_src/body_nested_models/tutorial004_py310.py!}
- ```
+```Python hl_lines="18"
+{!> ../../../docs_src/body_nested_models/tutorial004_py310.py!}
+```
-=== "Python 3.9+"
+////
- ```Python hl_lines="20"
- {!> ../../../docs_src/body_nested_models/tutorial004_py39.py!}
- ```
+//// tab | Python 3.9+
-=== "Python 3.8+"
+```Python hl_lines="20"
+{!> ../../../docs_src/body_nested_models/tutorial004_py39.py!}
+```
+
+////
- ```Python hl_lines="20"
- {!> ../../../docs_src/body_nested_models/tutorial004.py!}
- ```
+//// tab | Python 3.8+
+
+```Python hl_lines="20"
+{!> ../../../docs_src/body_nested_models/tutorial004.py!}
+```
+
+////
Это означает, что **FastAPI** будет ожидать тело запроса, аналогичное этому:
Например, так как в модели `Image` у нас есть поле `url`, то мы можем объявить его как тип `HttpUrl` из модуля Pydantic вместо типа `str`:
-=== "Python 3.10+"
+//// tab | Python 3.10+
- ```Python hl_lines="2 8"
- {!> ../../../docs_src/body_nested_models/tutorial005_py310.py!}
- ```
+```Python hl_lines="2 8"
+{!> ../../../docs_src/body_nested_models/tutorial005_py310.py!}
+```
-=== "Python 3.9+"
+////
- ```Python hl_lines="4 10"
- {!> ../../../docs_src/body_nested_models/tutorial005_py39.py!}
- ```
+//// tab | Python 3.9+
-=== "Python 3.8+"
+```Python hl_lines="4 10"
+{!> ../../../docs_src/body_nested_models/tutorial005_py39.py!}
+```
- ```Python hl_lines="4 10"
- {!> ../../../docs_src/body_nested_models/tutorial005.py!}
- ```
+////
+
+//// tab | Python 3.8+
+
+```Python hl_lines="4 10"
+{!> ../../../docs_src/body_nested_models/tutorial005.py!}
+```
+
+////
Строка будет проверена на соответствие допустимому URL-адресу и задокументирована в JSON схему / OpenAPI.
Вы также можете использовать модели Pydantic в качестве типов вложенных в `list`, `set` и т.д:
-=== "Python 3.10+"
+//// tab | Python 3.10+
- ```Python hl_lines="18"
- {!> ../../../docs_src/body_nested_models/tutorial006_py310.py!}
- ```
+```Python hl_lines="18"
+{!> ../../../docs_src/body_nested_models/tutorial006_py310.py!}
+```
+
+////
-=== "Python 3.9+"
+//// tab | Python 3.9+
- ```Python hl_lines="20"
- {!> ../../../docs_src/body_nested_models/tutorial006_py39.py!}
- ```
+```Python hl_lines="20"
+{!> ../../../docs_src/body_nested_models/tutorial006_py39.py!}
+```
-=== "Python 3.8+"
+////
- ```Python hl_lines="20"
- {!> ../../../docs_src/body_nested_models/tutorial006.py!}
- ```
+//// tab | Python 3.8+
+
+```Python hl_lines="20"
+{!> ../../../docs_src/body_nested_models/tutorial006.py!}
+```
+
+////
Такая реализация будет ожидать (конвертировать, валидировать, документировать и т.д) JSON-содержимое в следующем формате:
}
```
-!!! info "Информация"
- Заметьте, что теперь у ключа `images` есть список объектов изображений.
+/// info | "Информация"
+
+Заметьте, что теперь у ключа `images` есть список объектов изображений.
+
+///
## Глубоко вложенные модели
Вы можете определять модели с произвольным уровнем вложенности:
-=== "Python 3.10+"
+//// tab | Python 3.10+
+
+```Python hl_lines="7 12 18 21 25"
+{!> ../../../docs_src/body_nested_models/tutorial007_py310.py!}
+```
+
+////
- ```Python hl_lines="7 12 18 21 25"
- {!> ../../../docs_src/body_nested_models/tutorial007_py310.py!}
- ```
+//// tab | Python 3.9+
-=== "Python 3.9+"
+```Python hl_lines="9 14 20 23 27"
+{!> ../../../docs_src/body_nested_models/tutorial007_py39.py!}
+```
+
+////
+
+//// tab | Python 3.8+
+
+```Python hl_lines="9 14 20 23 27"
+{!> ../../../docs_src/body_nested_models/tutorial007.py!}
+```
- ```Python hl_lines="9 14 20 23 27"
- {!> ../../../docs_src/body_nested_models/tutorial007_py39.py!}
- ```
+////
-=== "Python 3.8+"
+/// info | "Информация"
- ```Python hl_lines="9 14 20 23 27"
- {!> ../../../docs_src/body_nested_models/tutorial007.py!}
- ```
+Заметьте, что у объекта `Offer` есть список объектов `Item`, которые, в свою очередь, могут содержать необязательный список объектов `Image`
-!!! info "Информация"
- Заметьте, что у объекта `Offer` есть список объектов `Item`, которые, в свою очередь, могут содержать необязательный список объектов `Image`
+///
## Тела с чистыми списками элементов
например так:
-=== "Python 3.9+"
+//// tab | Python 3.9+
+
+```Python hl_lines="13"
+{!> ../../../docs_src/body_nested_models/tutorial008_py39.py!}
+```
- ```Python hl_lines="13"
- {!> ../../../docs_src/body_nested_models/tutorial008_py39.py!}
- ```
+////
-=== "Python 3.8+"
+//// tab | Python 3.8+
- ```Python hl_lines="15"
- {!> ../../../docs_src/body_nested_models/tutorial008.py!}
- ```
+```Python hl_lines="15"
+{!> ../../../docs_src/body_nested_models/tutorial008.py!}
+```
+
+////
## Универсальная поддержка редактора
В этом случае вы принимаете `dict`, пока у него есть ключи типа `int` со значениями типа `float`:
-=== "Python 3.9+"
+//// tab | Python 3.9+
+
+```Python hl_lines="7"
+{!> ../../../docs_src/body_nested_models/tutorial009_py39.py!}
+```
+
+////
+
+//// tab | Python 3.8+
+
+```Python hl_lines="9"
+{!> ../../../docs_src/body_nested_models/tutorial009.py!}
+```
- ```Python hl_lines="7"
- {!> ../../../docs_src/body_nested_models/tutorial009_py39.py!}
- ```
+////
-=== "Python 3.8+"
+/// tip | "Совет"
- ```Python hl_lines="9"
- {!> ../../../docs_src/body_nested_models/tutorial009.py!}
- ```
+Имейте в виду, что JSON поддерживает только ключи типа `str`.
-!!! tip "Совет"
- Имейте в виду, что JSON поддерживает только ключи типа `str`.
+Но Pydantic обеспечивает автоматическое преобразование данных.
- Но Pydantic обеспечивает автоматическое преобразование данных.
+Это значит, что даже если пользователи вашего API могут отправлять только строки в качестве ключей, при условии, что эти строки содержат целые числа, Pydantic автоматический преобразует и валидирует эти данные.
- Это значит, что даже если пользователи вашего API могут отправлять только строки в качестве ключей, при условии, что эти строки содержат целые числа, Pydantic автоматический преобразует и валидирует эти данные.
+А `dict`, с именем `weights`, который вы получите в качестве ответа Pydantic, действительно будет иметь ключи типа `int` и значения типа `float`.
- А `dict`, с именем `weights`, который вы получите в качестве ответа Pydantic, действительно будет иметь ключи типа `int` и значения типа `float`.
+///
## Резюме
Вы можете использовать функцию `jsonable_encoder` для преобразования входных данных в JSON, так как нередки случаи, когда работать можно только с простыми типами данных (например, для хранения в NoSQL-базе данных).
-=== "Python 3.10+"
+//// tab | Python 3.10+
- ```Python hl_lines="28-33"
- {!> ../../../docs_src/body_updates/tutorial001_py310.py!}
- ```
+```Python hl_lines="28-33"
+{!> ../../../docs_src/body_updates/tutorial001_py310.py!}
+```
+
+////
+
+//// tab | Python 3.9+
+
+```Python hl_lines="30-35"
+{!> ../../../docs_src/body_updates/tutorial001_py39.py!}
+```
-=== "Python 3.9+"
+////
- ```Python hl_lines="30-35"
- {!> ../../../docs_src/body_updates/tutorial001_py39.py!}
- ```
+//// tab | Python 3.6+
-=== "Python 3.6+"
+```Python hl_lines="30-35"
+{!> ../../../docs_src/body_updates/tutorial001.py!}
+```
- ```Python hl_lines="30-35"
- {!> ../../../docs_src/body_updates/tutorial001.py!}
- ```
+////
`PUT` используется для получения данных, которые должны полностью заменить существующие данные.
Это означает, что можно передавать только те данные, которые необходимо обновить, оставляя остальные нетронутыми.
-!!! note "Технические детали"
- `PATCH` менее распространен и известен, чем `PUT`.
+/// note | "Технические детали"
+
+`PATCH` менее распространен и известен, чем `PUT`.
+
+А многие команды используют только `PUT`, даже для частичного обновления.
- А многие команды используют только `PUT`, даже для частичного обновления.
+Вы можете **свободно** использовать их как угодно, **FastAPI** не накладывает никаких ограничений.
- Вы можете **свободно** использовать их как угодно, **FastAPI** не накладывает никаких ограничений.
+Но в данном руководстве более или менее понятно, как они должны использоваться.
- Но в данном руководстве более или менее понятно, как они должны использоваться.
+///
### Использование параметра `exclude_unset` в Pydantic
В результате будет сгенерирован словарь, содержащий только те данные, которые были заданы при создании модели `item`, без учета значений по умолчанию. Затем вы можете использовать это для создания словаря только с теми данными, которые были установлены (отправлены в запросе), опуская значения по умолчанию:
-=== "Python 3.10+"
+//// tab | Python 3.10+
- ```Python hl_lines="32"
- {!> ../../../docs_src/body_updates/tutorial002_py310.py!}
- ```
+```Python hl_lines="32"
+{!> ../../../docs_src/body_updates/tutorial002_py310.py!}
+```
+
+////
-=== "Python 3.9+"
+//// tab | Python 3.9+
- ```Python hl_lines="34"
- {!> ../../../docs_src/body_updates/tutorial002_py39.py!}
- ```
+```Python hl_lines="34"
+{!> ../../../docs_src/body_updates/tutorial002_py39.py!}
+```
-=== "Python 3.6+"
+////
- ```Python hl_lines="34"
- {!> ../../../docs_src/body_updates/tutorial002.py!}
- ```
+//// tab | Python 3.6+
+
+```Python hl_lines="34"
+{!> ../../../docs_src/body_updates/tutorial002.py!}
+```
+
+////
### Использование параметра `update` в Pydantic
Например, `stored_item_model.copy(update=update_data)`:
-=== "Python 3.10+"
+//// tab | Python 3.10+
+
+```Python hl_lines="33"
+{!> ../../../docs_src/body_updates/tutorial002_py310.py!}
+```
+
+////
- ```Python hl_lines="33"
- {!> ../../../docs_src/body_updates/tutorial002_py310.py!}
- ```
+//// tab | Python 3.9+
+
+```Python hl_lines="35"
+{!> ../../../docs_src/body_updates/tutorial002_py39.py!}
+```
-=== "Python 3.9+"
+////
- ```Python hl_lines="35"
- {!> ../../../docs_src/body_updates/tutorial002_py39.py!}
- ```
+//// tab | Python 3.6+
-=== "Python 3.6+"
+```Python hl_lines="35"
+{!> ../../../docs_src/body_updates/tutorial002.py!}
+```
- ```Python hl_lines="35"
- {!> ../../../docs_src/body_updates/tutorial002.py!}
- ```
+////
### Кратко о частичном обновлении
* Сохранить данные в своей БД.
* Вернуть обновленную модель.
-=== "Python 3.10+"
+//// tab | Python 3.10+
+
+```Python hl_lines="28-35"
+{!> ../../../docs_src/body_updates/tutorial002_py310.py!}
+```
+
+////
+
+//// tab | Python 3.9+
+
+```Python hl_lines="30-37"
+{!> ../../../docs_src/body_updates/tutorial002_py39.py!}
+```
+
+////
+
+//// tab | Python 3.6+
+
+```Python hl_lines="30-37"
+{!> ../../../docs_src/body_updates/tutorial002.py!}
+```
- ```Python hl_lines="28-35"
- {!> ../../../docs_src/body_updates/tutorial002_py310.py!}
- ```
+////
-=== "Python 3.9+"
+/// tip | "Подсказка"
- ```Python hl_lines="30-37"
- {!> ../../../docs_src/body_updates/tutorial002_py39.py!}
- ```
+Эту же технику можно использовать и для операции HTTP `PUT`.
-=== "Python 3.6+"
+Но в приведенном примере используется `PATCH`, поскольку он был создан именно для таких случаев использования.
- ```Python hl_lines="30-37"
- {!> ../../../docs_src/body_updates/tutorial002.py!}
- ```
+///
-!!! tip "Подсказка"
- Эту же технику можно использовать и для операции HTTP `PUT`.
+/// note | "Технические детали"
- Но в приведенном примере используется `PATCH`, поскольку он был создан именно для таких случаев использования.
+Обратите внимание, что входная модель по-прежнему валидируется.
-!!! note "Технические детали"
- Обратите внимание, что входная модель по-прежнему валидируется.
+Таким образом, если вы хотите получать частичные обновления, в которых могут быть опущены все атрибуты, вам необходимо иметь модель, в которой все атрибуты помечены как необязательные (со значениями по умолчанию или `None`).
- Таким образом, если вы хотите получать частичные обновления, в которых могут быть опущены все атрибуты, вам необходимо иметь модель, в которой все атрибуты помечены как необязательные (со значениями по умолчанию или `None`).
+Чтобы отличить модели со всеми необязательными значениями для **обновления** от моделей с обязательными значениями для **создания**, можно воспользоваться идеями, описанными в [Дополнительные модели](extra-models.md){.internal-link target=_blank}.
- Чтобы отличить модели со всеми необязательными значениями для **обновления** от моделей с обязательными значениями для **создания**, можно воспользоваться идеями, описанными в [Дополнительные модели](extra-models.md){.internal-link target=_blank}.
+///
Чтобы объявить тело **запроса**, необходимо использовать модели <a href="https://docs.pydantic.dev/" class="external-link" target="_blank">Pydantic</a>, со всей их мощью и преимуществами.
-!!! info "Информация"
- Чтобы отправить данные, необходимо использовать один из методов: `POST` (обычно), `PUT`, `DELETE` или `PATCH`.
+/// info | "Информация"
- Отправка тела с запросом `GET` имеет неопределенное поведение в спецификациях, тем не менее, оно поддерживается FastAPI только для очень сложных/экстремальных случаев использования.
+Чтобы отправить данные, необходимо использовать один из методов: `POST` (обычно), `PUT`, `DELETE` или `PATCH`.
- Поскольку это не рекомендуется, интерактивная документация со Swagger UI не будет отображать информацию для тела при использовании метода GET, а промежуточные прокси-серверы могут не поддерживать такой вариант запроса.
+Отправка тела с запросом `GET` имеет неопределенное поведение в спецификациях, тем не менее, оно поддерживается FastAPI только для очень сложных/экстремальных случаев использования.
+
+Поскольку это не рекомендуется, интерактивная документация со Swagger UI не будет отображать информацию для тела при использовании метода GET, а промежуточные прокси-серверы могут не поддерживать такой вариант запроса.
+
+///
## Импортирование `BaseModel` из Pydantic
<img src="/img/tutorial/body/image05.png">
-!!! tip "Подсказка"
- Если вы используете <a href="https://www.jetbrains.com/pycharm/" class="external-link" target="_blank">PyCharm</a> в качестве редактора, то вам стоит попробовать плагин <a href="https://github.com/koxudaxi/pydantic-pycharm-plugin/" class="external-link" target="_blank">Pydantic PyCharm Plugin</a>.
+/// tip | "Подсказка"
+
+Если вы используете <a href="https://www.jetbrains.com/pycharm/" class="external-link" target="_blank">PyCharm</a> в качестве редактора, то вам стоит попробовать плагин <a href="https://github.com/koxudaxi/pydantic-pycharm-plugin/" class="external-link" target="_blank">Pydantic PyCharm Plugin</a>.
- Он улучшает поддержку редактором моделей Pydantic в части:
+Он улучшает поддержку редактором моделей Pydantic в части:
- * автодополнения,
- * проверки типов,
- * рефакторинга,
- * поиска,
- * инспектирования.
+* автодополнения,
+* проверки типов,
+* рефакторинга,
+* поиска,
+* инспектирования.
+
+///
## Использование модели
* Если аннотация типа параметра содержит **примитивный тип** (`int`, `float`, `str`, `bool` и т.п.), он будет интерпретирован как параметр **запроса**.
* Если аннотация типа параметра представляет собой **модель Pydantic**, он будет интерпретирован как параметр **тела запроса**.
-!!! note "Заметка"
- FastAPI понимает, что значение параметра `q` не является обязательным, потому что имеет значение по умолчанию `= None`.
+/// note | "Заметка"
+
+FastAPI понимает, что значение параметра `q` не является обязательным, потому что имеет значение по умолчанию `= None`.
+
+Аннотация `Optional` в `Optional[str]` не используется FastAPI, но помогает вашему редактору лучше понимать ваш код и обнаруживать ошибки.
- Аннотация `Optional` в `Optional[str]` не используется FastAPI, но помогает вашему редактору лучше понимать ваш код и обнаруживать ошибки.
+///
## Без Pydantic
Сначала импортируйте `Cookie`:
-=== "Python 3.10+"
+//// tab | Python 3.10+
- ```Python hl_lines="1"
- {!> ../../../docs_src/cookie_params/tutorial001_py310.py!}
- ```
+```Python hl_lines="1"
+{!> ../../../docs_src/cookie_params/tutorial001_py310.py!}
+```
-=== "Python 3.8+"
+////
- ```Python hl_lines="3"
- {!> ../../../docs_src/cookie_params/tutorial001.py!}
- ```
+//// tab | Python 3.8+
+
+```Python hl_lines="3"
+{!> ../../../docs_src/cookie_params/tutorial001.py!}
+```
+
+////
## Объявление параметров `Cookie`
Первое значение - это значение по умолчанию, вы можете передать все дополнительные параметры проверки или аннотации:
-=== "Python 3.10+"
+//// tab | Python 3.10+
+
+```Python hl_lines="7"
+{!> ../../../docs_src/cookie_params/tutorial001_py310.py!}
+```
+
+////
+
+//// tab | Python 3.8+
+
+```Python hl_lines="9"
+{!> ../../../docs_src/cookie_params/tutorial001.py!}
+```
+
+////
+
+/// note | "Технические детали"
- ```Python hl_lines="7"
- {!> ../../../docs_src/cookie_params/tutorial001_py310.py!}
- ```
+`Cookie` - это класс, родственный `Path` и `Query`. Он также наследуется от общего класса `Param`.
-=== "Python 3.8+"
+Но помните, что когда вы импортируете `Query`, `Path`, `Cookie` и другое из `fastapi`, это фактически функции, которые возвращают специальные классы.
- ```Python hl_lines="9"
- {!> ../../../docs_src/cookie_params/tutorial001.py!}
- ```
+///
-!!! note "Технические детали"
- `Cookie` - это класс, родственный `Path` и `Query`. Он также наследуется от общего класса `Param`.
+/// info | "Дополнительная информация"
- Но помните, что когда вы импортируете `Query`, `Path`, `Cookie` и другое из `fastapi`, это фактически функции, которые возвращают специальные классы.
+Для объявления cookies, вам нужно использовать `Cookie`, иначе параметры будут интерпретированы как параметры запроса.
-!!! info "Дополнительная информация"
- Для объявления cookies, вам нужно использовать `Cookie`, иначе параметры будут интерпретированы как параметры запроса.
+///
## Резюме
Для получения более подробной информации о <abbr title="Cross-Origin Resource Sharing">CORS</abbr>, обратитесь к <a href="https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS" class="external-link" target="_blank">Документации CORS от Mozilla</a>.
-!!! note "Технические детали"
- Вы также можете использовать `from starlette.middleware.cors import CORSMiddleware`.
+/// note | "Технические детали"
- **FastAPI** предоставляет несколько middleware в `fastapi.middleware` только для вашего удобства как разработчика. Но большинство доступных middleware взяты напрямую из Starlette.
+Вы также можете использовать `from starlette.middleware.cors import CORSMiddleware`.
+
+**FastAPI** предоставляет несколько middleware в `fastapi.middleware` только для вашего удобства как разработчика. Но большинство доступных middleware взяты напрямую из Starlette.
+
+///
не будет выполнена.
-!!! info "Информация"
- Для получения дополнительной информации, ознакомьтесь с <a href="https://docs.python.org/3/library/__main__.html" class="external-link" target="_blank">официальной документацией Python</a>.
+/// info | "Информация"
+
+Для получения дополнительной информации, ознакомьтесь с <a href="https://docs.python.org/3/library/__main__.html" class="external-link" target="_blank">официальной документацией Python</a>.
+
+///
## Запуск вашего кода с помощью отладчика
В предыдущем примере мы возвращали `словарь` из нашей зависимости:
-=== "Python 3.10+"
+//// tab | Python 3.10+
- ```Python hl_lines="9"
- {!> ../../../docs_src/dependencies/tutorial001_an_py310.py!}
- ```
+```Python hl_lines="9"
+{!> ../../../docs_src/dependencies/tutorial001_an_py310.py!}
+```
+
+////
+
+//// tab | Python 3.9+
+
+```Python hl_lines="11"
+{!> ../../../docs_src/dependencies/tutorial001_an_py39.py!}
+```
-=== "Python 3.9+"
+////
- ```Python hl_lines="11"
- {!> ../../../docs_src/dependencies/tutorial001_an_py39.py!}
- ```
+//// tab | Python 3.6+
-=== "Python 3.6+"
+```Python hl_lines="12"
+{!> ../../../docs_src/dependencies/tutorial001_an.py!}
+```
+
+////
+
+//// tab | Python 3.10+ без Annotated
- ```Python hl_lines="12"
- {!> ../../../docs_src/dependencies/tutorial001_an.py!}
- ```
+/// tip | "Подсказка"
-=== "Python 3.10+ без Annotated"
+Рекомендуется использовать версию с `Annotated` если возможно.
- !!! tip "Подсказка"
- Рекомендуется использовать версию с `Annotated` если возможно.
+///
+
+```Python hl_lines="7"
+{!> ../../../docs_src/dependencies/tutorial001_py310.py!}
+```
- ```Python hl_lines="7"
- {!> ../../../docs_src/dependencies/tutorial001_py310.py!}
- ```
+////
-=== "Python 3.6+ без Annotated"
+//// tab | Python 3.6+ без Annotated
- !!! tip "Подсказка"
- Рекомендуется использовать версию с `Annotated` если возможно.
+/// tip | "Подсказка"
- ```Python hl_lines="11"
- {!> ../../../docs_src/dependencies/tutorial001.py!}
- ```
+Рекомендуется использовать версию с `Annotated` если возможно.
+
+///
+
+```Python hl_lines="11"
+{!> ../../../docs_src/dependencies/tutorial001.py!}
+```
+
+////
Но затем мы получаем `словарь` в параметре `commons` *функции операции пути*. И мы знаем, что редакторы не могут обеспечить достаточную поддержку для `словаря`, поскольку они не могут знать их ключи и типы значений.
Теперь мы можем изменить зависимость `common_parameters`, указанную выше, на класс `CommonQueryParams`:
-=== "Python 3.10+"
+//// tab | Python 3.10+
- ```Python hl_lines="11-15"
- {!> ../../../docs_src/dependencies/tutorial002_an_py310.py!}
- ```
+```Python hl_lines="11-15"
+{!> ../../../docs_src/dependencies/tutorial002_an_py310.py!}
+```
-=== "Python 3.9+"
+////
- ```Python hl_lines="11-15"
- {!> ../../../docs_src/dependencies/tutorial002_an_py39.py!}
- ```
+//// tab | Python 3.9+
-=== "Python 3.6+"
+```Python hl_lines="11-15"
+{!> ../../../docs_src/dependencies/tutorial002_an_py39.py!}
+```
+
+////
- ```Python hl_lines="12-16"
- {!> ../../../docs_src/dependencies/tutorial002_an.py!}
- ```
+//// tab | Python 3.6+
-=== "Python 3.10+ без Annotated"
+```Python hl_lines="12-16"
+{!> ../../../docs_src/dependencies/tutorial002_an.py!}
+```
- !!! tip "Подсказка"
- Рекомендуется использовать версию с `Annotated` если возможно.
+////
- ```Python hl_lines="9-13"
- {!> ../../../docs_src/dependencies/tutorial002_py310.py!}
- ```
+//// tab | Python 3.10+ без Annotated
-=== "Python 3.6+ без Annotated"
+/// tip | "Подсказка"
- !!! tip "Подсказка"
- Рекомендуется использовать версию с `Annotated` если возможно.
+Рекомендуется использовать версию с `Annotated` если возможно.
- ```Python hl_lines="11-15"
- {!> ../../../docs_src/dependencies/tutorial002.py!}
- ```
+///
+
+```Python hl_lines="9-13"
+{!> ../../../docs_src/dependencies/tutorial002_py310.py!}
+```
+
+////
+
+//// tab | Python 3.6+ без Annotated
+
+/// tip | "Подсказка"
+
+Рекомендуется использовать версию с `Annotated` если возможно.
+
+///
+
+```Python hl_lines="11-15"
+{!> ../../../docs_src/dependencies/tutorial002.py!}
+```
+
+////
Обратите внимание на метод `__init__`, используемый для создания экземпляра класса:
-=== "Python 3.10+"
+//// tab | Python 3.10+
+
+```Python hl_lines="12"
+{!> ../../../docs_src/dependencies/tutorial002_an_py310.py!}
+```
+
+////
+
+//// tab | Python 3.9+
+
+```Python hl_lines="12"
+{!> ../../../docs_src/dependencies/tutorial002_an_py39.py!}
+```
+
+////
+
+//// tab | Python 3.6+
+
+```Python hl_lines="13"
+{!> ../../../docs_src/dependencies/tutorial002_an.py!}
+```
+
+////
- ```Python hl_lines="12"
- {!> ../../../docs_src/dependencies/tutorial002_an_py310.py!}
- ```
+//// tab | Python 3.10+ без Annotated
-=== "Python 3.9+"
+/// tip | "Подсказка"
- ```Python hl_lines="12"
- {!> ../../../docs_src/dependencies/tutorial002_an_py39.py!}
- ```
+Рекомендуется использовать версию с `Annotated` если возможно.
-=== "Python 3.6+"
+///
- ```Python hl_lines="13"
- {!> ../../../docs_src/dependencies/tutorial002_an.py!}
- ```
+```Python hl_lines="10"
+{!> ../../../docs_src/dependencies/tutorial002_py310.py!}
+```
-=== "Python 3.10+ без Annotated"
+////
- !!! tip "Подсказка"
- Рекомендуется использовать версию с `Annotated` если возможно.
+//// tab | Python 3.6+ без Annotated
- ```Python hl_lines="10"
- {!> ../../../docs_src/dependencies/tutorial002_py310.py!}
- ```
+/// tip | "Подсказка"
-=== "Python 3.6+ без Annotated"
+Рекомендуется использовать версию с `Annotated` если возможно.
- !!! tip "Подсказка"
- Рекомендуется использовать версию с `Annotated` если возможно.
+///
+
+```Python hl_lines="12"
+{!> ../../../docs_src/dependencies/tutorial002.py!}
+```
- ```Python hl_lines="12"
- {!> ../../../docs_src/dependencies/tutorial002.py!}
- ```
+////
...имеет те же параметры, что и ранее используемая функция `common_parameters`:
-=== "Python 3.10+"
+//// tab | Python 3.10+
- ```Python hl_lines="8"
- {!> ../../../docs_src/dependencies/tutorial001_an_py310.py!}
- ```
+```Python hl_lines="8"
+{!> ../../../docs_src/dependencies/tutorial001_an_py310.py!}
+```
+
+////
-=== "Python 3.9+"
+//// tab | Python 3.9+
- ```Python hl_lines="9"
- {!> ../../../docs_src/dependencies/tutorial001_an_py39.py!}
- ```
+```Python hl_lines="9"
+{!> ../../../docs_src/dependencies/tutorial001_an_py39.py!}
+```
-=== "Python 3.6+"
+////
- ```Python hl_lines="10"
- {!> ../../../docs_src/dependencies/tutorial001_an.py!}
- ```
+//// tab | Python 3.6+
+
+```Python hl_lines="10"
+{!> ../../../docs_src/dependencies/tutorial001_an.py!}
+```
-=== "Python 3.10+ без Annotated"
+////
- !!! tip "Подсказка"
- Рекомендуется использовать версию с `Annotated` если возможно.
+//// tab | Python 3.10+ без Annotated
- ```Python hl_lines="6"
- {!> ../../../docs_src/dependencies/tutorial001_py310.py!}
- ```
+/// tip | "Подсказка"
-=== "Python 3.6+ без Annotated"
+Рекомендуется использовать версию с `Annotated` если возможно.
- !!! tip "Подсказка"
- Рекомендуется использовать версию с `Annotated` если возможно.
+///
+
+```Python hl_lines="6"
+{!> ../../../docs_src/dependencies/tutorial001_py310.py!}
+```
+
+////
+
+//// tab | Python 3.6+ без Annotated
+
+/// tip | "Подсказка"
+
+Рекомендуется использовать версию с `Annotated` если возможно.
+
+///
+
+```Python hl_lines="9"
+{!> ../../../docs_src/dependencies/tutorial001.py!}
+```
- ```Python hl_lines="9"
- {!> ../../../docs_src/dependencies/tutorial001.py!}
- ```
+////
Эти параметры и будут использоваться **FastAPI** для "решения" зависимости.
Теперь вы можете объявить свою зависимость, используя этот класс.
-=== "Python 3.10+"
+//// tab | Python 3.10+
- ```Python hl_lines="19"
- {!> ../../../docs_src/dependencies/tutorial002_an_py310.py!}
- ```
+```Python hl_lines="19"
+{!> ../../../docs_src/dependencies/tutorial002_an_py310.py!}
+```
+
+////
+
+//// tab | Python 3.9+
+
+```Python hl_lines="19"
+{!> ../../../docs_src/dependencies/tutorial002_an_py39.py!}
+```
+
+////
+
+//// tab | Python 3.6+
+
+```Python hl_lines="20"
+{!> ../../../docs_src/dependencies/tutorial002_an.py!}
+```
-=== "Python 3.9+"
+////
- ```Python hl_lines="19"
- {!> ../../../docs_src/dependencies/tutorial002_an_py39.py!}
- ```
+//// tab | Python 3.10+ без Annotated
-=== "Python 3.6+"
+/// tip | "Подсказка"
- ```Python hl_lines="20"
- {!> ../../../docs_src/dependencies/tutorial002_an.py!}
- ```
+Рекомендуется использовать версию с `Annotated` если возможно.
-=== "Python 3.10+ без Annotated"
+///
- !!! tip "Подсказка"
- Рекомендуется использовать версию с `Annotated` если возможно.
+```Python hl_lines="17"
+{!> ../../../docs_src/dependencies/tutorial002_py310.py!}
+```
+
+////
+
+//// tab | Python 3.6+ без Annotated
- ```Python hl_lines="17"
- {!> ../../../docs_src/dependencies/tutorial002_py310.py!}
- ```
+/// tip | "Подсказка"
-=== "Python 3.6+ без Annotated"
+Рекомендуется использовать версию с `Annotated` если возможно.
- !!! tip "Подсказка"
- Рекомендуется использовать версию с `Annotated` если возможно.
+///
+
+```Python hl_lines="19"
+{!> ../../../docs_src/dependencies/tutorial002.py!}
+```
- ```Python hl_lines="19"
- {!> ../../../docs_src/dependencies/tutorial002.py!}
- ```
+////
**FastAPI** вызывает класс `CommonQueryParams`. При этом создается "экземпляр" этого класса, который будет передан в качестве параметра `commons` в вашу функцию.
Обратите внимание, что в приведенном выше коде мы два раза пишем `CommonQueryParams`:
-=== "Python 3.6+ без Annotated"
+//// tab | Python 3.6+ без Annotated
+
+/// tip | "Подсказка"
+
+Рекомендуется использовать версию с `Annotated` если возможно.
+
+///
+
+```Python
+commons: CommonQueryParams = Depends(CommonQueryParams)
+```
- !!! tip "Подсказка"
- Рекомендуется использовать версию с `Annotated` если возможно.
+////
- ```Python
- commons: CommonQueryParams = Depends(CommonQueryParams)
- ```
+//// tab | Python 3.6+
-=== "Python 3.6+"
+```Python
+commons: Annotated[CommonQueryParams, Depends(CommonQueryParams)]
+```
- ```Python
- commons: Annotated[CommonQueryParams, Depends(CommonQueryParams)]
- ```
+////
Последний параметр `CommonQueryParams`, в:
В этом случае первый `CommonQueryParams`, в:
-=== "Python 3.6+"
+//// tab | Python 3.6+
+
+```Python
+commons: Annotated[CommonQueryParams, ...
+```
+
+////
- ```Python
- commons: Annotated[CommonQueryParams, ...
- ```
+//// tab | Python 3.6+ без Annotated
-=== "Python 3.6+ без Annotated"
+/// tip | "Подсказка"
- !!! tip "Подсказка"
- Рекомендуется использовать версию с `Annotated` если возможно.
+Рекомендуется использовать версию с `Annotated` если возможно.
- ```Python
- commons: CommonQueryParams ...
- ```
+///
+
+```Python
+commons: CommonQueryParams ...
+```
+
+////
...не имеет никакого специального значения для **FastAPI**. FastAPI не будет использовать его для преобразования данных, валидации и т.д. (поскольку для этого используется `Depends(CommonQueryParams)`).
На самом деле можно написать просто:
-=== "Python 3.6+"
+//// tab | Python 3.6+
+
+```Python
+commons: Annotated[Any, Depends(CommonQueryParams)]
+```
- ```Python
- commons: Annotated[Any, Depends(CommonQueryParams)]
- ```
+////
-=== "Python 3.6+ без Annotated"
+//// tab | Python 3.6+ без Annotated
- !!! tip "Подсказка"
- Рекомендуется использовать версию с `Annotated` если возможно.
+/// tip | "Подсказка"
- ```Python
- commons = Depends(CommonQueryParams)
- ```
+Рекомендуется использовать версию с `Annotated` если возможно.
+
+///
+
+```Python
+commons = Depends(CommonQueryParams)
+```
+
+////
...как тут:
-=== "Python 3.10+"
+//// tab | Python 3.10+
+
+```Python hl_lines="19"
+{!> ../../../docs_src/dependencies/tutorial003_an_py310.py!}
+```
+
+////
+
+//// tab | Python 3.9+
+
+```Python hl_lines="19"
+{!> ../../../docs_src/dependencies/tutorial003_an_py39.py!}
+```
+
+////
+
+//// tab | Python 3.6+
- ```Python hl_lines="19"
- {!> ../../../docs_src/dependencies/tutorial003_an_py310.py!}
- ```
+```Python hl_lines="20"
+{!> ../../../docs_src/dependencies/tutorial003_an.py!}
+```
+
+////
-=== "Python 3.9+"
+//// tab | Python 3.10+ без Annotated
- ```Python hl_lines="19"
- {!> ../../../docs_src/dependencies/tutorial003_an_py39.py!}
- ```
+/// tip | "Подсказка"
-=== "Python 3.6+"
+Рекомендуется использовать версию с `Annotated` если возможно.
- ```Python hl_lines="20"
- {!> ../../../docs_src/dependencies/tutorial003_an.py!}
- ```
+///
-=== "Python 3.10+ без Annotated"
+```Python hl_lines="17"
+{!> ../../../docs_src/dependencies/tutorial003_py310.py!}
+```
- !!! tip "Подсказка"
- Рекомендуется использовать версию с `Annotated` если возможно.
+////
- ```Python hl_lines="17"
- {!> ../../../docs_src/dependencies/tutorial003_py310.py!}
- ```
+//// tab | Python 3.6+ без Annotated
-=== "Python 3.6+ без Annotated"
+/// tip | "Подсказка"
- !!! tip "Подсказка"
- Рекомендуется использовать версию с `Annotated` если возможно.
+Рекомендуется использовать версию с `Annotated` если возможно.
- ```Python hl_lines="19"
- {!> ../../../docs_src/dependencies/tutorial003.py!}
- ```
+///
+
+```Python hl_lines="19"
+{!> ../../../docs_src/dependencies/tutorial003.py!}
+```
+
+////
Но объявление типа приветствуется, так как в этом случае ваш редактор будет знать, что будет передано в качестве параметра `commons`, и тогда он сможет помочь вам с автодополнением, проверкой типов и т.д:
Но вы видите, что здесь мы имеем некоторое повторение кода, дважды написав `CommonQueryParams`:
-=== "Python 3.6+ без Annotated"
+//// tab | Python 3.6+ без Annotated
+
+/// tip | "Подсказка"
+
+Рекомендуется использовать версию с `Annotated` если возможно.
+
+///
- !!! tip "Подсказка"
- Рекомендуется использовать версию с `Annotated` если возможно.
+```Python
+commons: CommonQueryParams = Depends(CommonQueryParams)
+```
+
+////
- ```Python
- commons: CommonQueryParams = Depends(CommonQueryParams)
- ```
+//// tab | Python 3.6+
-=== "Python 3.6+"
+```Python
+commons: Annotated[CommonQueryParams, Depends(CommonQueryParams)]
+```
- ```Python
- commons: Annotated[CommonQueryParams, Depends(CommonQueryParams)]
- ```
+////
Для случаев, когда зависимостью является *конкретный* класс, который **FastAPI** "вызовет" для создания экземпляра этого класса, можно использовать укороченную запись.
Вместо того чтобы писать:
-=== "Python 3.6+"
+//// tab | Python 3.6+
- ```Python
- commons: Annotated[CommonQueryParams, Depends(CommonQueryParams)]
- ```
+```Python
+commons: Annotated[CommonQueryParams, Depends(CommonQueryParams)]
+```
+
+////
-=== "Python 3.6+ без Annotated"
+//// tab | Python 3.6+ без Annotated
- !!! tip "Подсказка"
- Рекомендуется использовать версию с `Annotated` если возможно.
+/// tip | "Подсказка"
- ```Python
- commons: CommonQueryParams = Depends(CommonQueryParams)
- ```
+Рекомендуется использовать версию с `Annotated` если возможно.
+
+///
+
+```Python
+commons: CommonQueryParams = Depends(CommonQueryParams)
+```
+
+////
...следует написать:
-=== "Python 3.6+"
+//// tab | Python 3.6+
- ```Python
- commons: Annotated[CommonQueryParams, Depends()]
- ```
+```Python
+commons: Annotated[CommonQueryParams, Depends()]
+```
-=== "Python 3.6 без Annotated"
+////
- !!! tip "Подсказка"
- Рекомендуется использовать версию с `Annotated` если возможно.
+//// tab | Python 3.6 без Annotated
- ```Python
- commons: CommonQueryParams = Depends()
- ```
+/// tip | "Подсказка"
+
+Рекомендуется использовать версию с `Annotated` если возможно.
+
+///
+
+```Python
+commons: CommonQueryParams = Depends()
+```
+
+////
Вы объявляете зависимость как тип параметра и используете `Depends()` без какого-либо параметра, вместо того чтобы *снова* писать полный класс внутри `Depends(CommonQueryParams)`.
Аналогичный пример будет выглядеть следующим образом:
-=== "Python 3.10+"
+//// tab | Python 3.10+
+
+```Python hl_lines="19"
+{!> ../../../docs_src/dependencies/tutorial004_an_py310.py!}
+```
+
+////
+
+//// tab | Python 3.9+
+
+```Python hl_lines="19"
+{!> ../../../docs_src/dependencies/tutorial004_an_py39.py!}
+```
+
+////
- ```Python hl_lines="19"
- {!> ../../../docs_src/dependencies/tutorial004_an_py310.py!}
- ```
+//// tab | Python 3.6+
-=== "Python 3.9+"
+```Python hl_lines="20"
+{!> ../../../docs_src/dependencies/tutorial004_an.py!}
+```
+
+////
- ```Python hl_lines="19"
- {!> ../../../docs_src/dependencies/tutorial004_an_py39.py!}
- ```
+//// tab | Python 3.10+ без Annotated
-=== "Python 3.6+"
+/// tip | "Подсказка"
- ```Python hl_lines="20"
- {!> ../../../docs_src/dependencies/tutorial004_an.py!}
- ```
+Рекомендуется использовать версию с `Annotated` если возможно.
-=== "Python 3.10+ без Annotated"
+///
- !!! tip "Подсказка"
- Рекомендуется использовать версию с `Annotated` если возможно.
+```Python hl_lines="17"
+{!> ../../../docs_src/dependencies/tutorial004_py310.py!}
+```
- ```Python hl_lines="17"
- {!> ../../../docs_src/dependencies/tutorial004_py310.py!}
- ```
+////
-=== "Python 3.6+ без Annotated"
+//// tab | Python 3.6+ без Annotated
- !!! tip "Подсказка"
- Рекомендуется использовать версию с `Annotated` если возможно.
+/// tip | "Подсказка"
- ```Python hl_lines="19"
- {!> ../../../docs_src/dependencies/tutorial004.py!}
- ```
+Рекомендуется использовать версию с `Annotated` если возможно.
+
+///
+
+```Python hl_lines="19"
+{!> ../../../docs_src/dependencies/tutorial004.py!}
+```
+
+////
...и **FastAPI** будет знать, что делать.
-!!! tip "Подсказка"
- Если это покажется вам более запутанным, чем полезным, не обращайте внимания, это вам не *нужно*.
+/// tip | "Подсказка"
+
+Если это покажется вам более запутанным, чем полезным, не обращайте внимания, это вам не *нужно*.
+
+Это просто сокращение. Потому что **FastAPI** заботится о том, чтобы помочь вам свести к минимуму повторение кода.
- Это просто сокращение. Потому что **FastAPI** заботится о том, чтобы помочь вам свести к минимуму повторение кода.
+///
Это должен быть `list` состоящий из `Depends()`:
-=== "Python 3.9+"
+//// tab | Python 3.9+
- ```Python hl_lines="19"
- {!> ../../../docs_src/dependencies/tutorial006_an_py39.py!}
- ```
+```Python hl_lines="19"
+{!> ../../../docs_src/dependencies/tutorial006_an_py39.py!}
+```
-=== "Python 3.8+"
+////
- ```Python hl_lines="18"
- {!> ../../../docs_src/dependencies/tutorial006_an.py!}
- ```
+//// tab | Python 3.8+
-=== "Python 3.8 без Annotated"
+```Python hl_lines="18"
+{!> ../../../docs_src/dependencies/tutorial006_an.py!}
+```
- !!! Подсказка
- Рекомендуется использовать версию с Annotated, если возможно.
+////
- ```Python hl_lines="17"
- {!> ../../../docs_src/dependencies/tutorial006.py!}
- ```
+//// tab | Python 3.8 без Annotated
+
+/// подсказка
+
+Рекомендуется использовать версию с Annotated, если возможно.
+
+///
+
+```Python hl_lines="17"
+{!> ../../../docs_src/dependencies/tutorial006.py!}
+```
+
+////
Зависимости из dependencies выполнятся так же, как и обычные зависимости. Но их значения (если они были) не будут переданы в *функцию операции пути*.
-!!! Подсказка
- Некоторые редакторы кода определяют неиспользуемые параметры функций и подсвечивают их как ошибку.
+/// подсказка
+
+Некоторые редакторы кода определяют неиспользуемые параметры функций и подсвечивают их как ошибку.
- Использование `dependencies` в *декораторе операции пути* гарантирует выполнение зависимостей, избегая при этом предупреждений редактора кода и других инструментов.
+Использование `dependencies` в *декораторе операции пути* гарантирует выполнение зависимостей, избегая при этом предупреждений редактора кода и других инструментов.
- Это также должно помочь предотвратить путаницу у начинающих разработчиков, которые видят неиспользуемые параметры в коде и могут подумать что в них нет необходимости.
+Это также должно помочь предотвратить путаницу у начинающих разработчиков, которые видят неиспользуемые параметры в коде и могут подумать что в них нет необходимости.
-!!! Дополнительная информация
- В этом примере мы используем выдуманные пользовательские заголовки `X-Key` и `X-Token`.
+///
- Но в реальных проектах, при внедрении системы безопасности, вы получите больше пользы используя интегрированные [средства защиты (следующая глава)](../security/index.md){.internal-link target=_blank}.
+/// дополнительная | информация
+
+В этом примере мы используем выдуманные пользовательские заголовки `X-Key` и `X-Token`.
+
+Но в реальных проектах, при внедрении системы безопасности, вы получите больше пользы используя интегрированные [средства защиты (следующая глава)](../security/index.md){.internal-link target=_blank}.
+
+///
## Исключения в dependencies и возвращаемые значения
Они могут объявлять требования к запросу (например заголовки) или другие подзависимости:
-=== "Python 3.9+"
+//// tab | Python 3.9+
+
+```Python hl_lines="8 13"
+{!> ../../../docs_src/dependencies/tutorial006_an_py39.py!}
+```
+
+////
+
+//// tab | Python 3.8+
- ```Python hl_lines="8 13"
- {!> ../../../docs_src/dependencies/tutorial006_an_py39.py!}
- ```
+```Python hl_lines="7 12"
+{!> ../../../docs_src/dependencies/tutorial006_an.py!}
+```
-=== "Python 3.8+"
+////
- ```Python hl_lines="7 12"
- {!> ../../../docs_src/dependencies/tutorial006_an.py!}
- ```
+//// tab | Python 3.8 без Annotated
-=== "Python 3.8 без Annotated"
+/// подсказка
- !!! Подсказка
- Рекомендуется использовать версию с Annotated, если возможно.
+Рекомендуется использовать версию с Annotated, если возможно.
- ```Python hl_lines="6 11"
- {!> ../../../docs_src/dependencies/tutorial006.py!}
- ```
+///
+
+```Python hl_lines="6 11"
+{!> ../../../docs_src/dependencies/tutorial006.py!}
+```
+
+////
### Вызов исключений
Зависимости из dependencies могут вызывать исключения с помощью `raise`, как и обычные зависимости:
-=== "Python 3.9+"
+//// tab | Python 3.9+
+
+```Python hl_lines="10 15"
+{!> ../../../docs_src/dependencies/tutorial006_an_py39.py!}
+```
+
+////
+
+//// tab | Python 3.8+
+
+```Python hl_lines="9 14"
+{!> ../../../docs_src/dependencies/tutorial006_an.py!}
+```
- ```Python hl_lines="10 15"
- {!> ../../../docs_src/dependencies/tutorial006_an_py39.py!}
- ```
+////
-=== "Python 3.8+"
+//// tab | Python 3.8 без Annotated
- ```Python hl_lines="9 14"
- {!> ../../../docs_src/dependencies/tutorial006_an.py!}
- ```
+/// подсказка
-=== "Python 3.8 без Annotated"
+Рекомендуется использовать версию с Annotated, если возможно.
- !!! Подсказка
- Рекомендуется использовать версию с Annotated, если возможно.
+///
- ```Python hl_lines="8 13"
- {!> ../../../docs_src/dependencies/tutorial006.py!}
- ```
+```Python hl_lines="8 13"
+{!> ../../../docs_src/dependencies/tutorial006.py!}
+```
+
+////
### Возвращаемые значения
Таким образом, вы можете переиспользовать обычную зависимость (возвращающую значение), которую вы уже используете где-то в другом месте, и хотя значение не будет использоваться, зависимость будет выполнена:
-=== "Python 3.9+"
+//// tab | Python 3.9+
+
+```Python hl_lines="11 16"
+{!> ../../../docs_src/dependencies/tutorial006_an_py39.py!}
+```
+
+////
+
+//// tab | Python 3.8+
+
+```Python hl_lines="10 15"
+{!> ../../../docs_src/dependencies/tutorial006_an.py!}
+```
+
+////
- ```Python hl_lines="11 16"
- {!> ../../../docs_src/dependencies/tutorial006_an_py39.py!}
- ```
+//// tab | Python 3.8 без Annotated
-=== "Python 3.8+"
+/// подсказка
- ```Python hl_lines="10 15"
- {!> ../../../docs_src/dependencies/tutorial006_an.py!}
- ```
+Рекомендуется использовать версию с Annotated, если возможно.
-=== "Python 3.8 без Annotated"
+///
- !!! Подсказка
- Рекомендуется использовать версию с Annotated, если возможно.
+```Python hl_lines="9 14"
+{!> ../../../docs_src/dependencies/tutorial006.py!}
+```
- ```Python hl_lines="9 14"
- {!> ../../../docs_src/dependencies/tutorial006.py!}
- ```
+////
## Dependencies для группы *операций путей*
Для этого используйте `yield` вместо `return`, а дополнительный код напишите после него.
-!!! tip "Подсказка"
- Обязательно используйте `yield` один-единственный раз.
+/// tip | "Подсказка"
-!!! note "Технические детали"
- Любая функция, с которой может работать:
+Обязательно используйте `yield` один-единственный раз.
- * <a href="https://docs.python.org/3/library/contextlib.html#contextlib.contextmanager" class="external-link" target="_blank">`@contextlib.contextmanager`</a> или
- * <a href="https://docs.python.org/3/library/contextlib.html#contextlib.asynccontextmanager" class="external-link" target="_blank">`@contextlib.asynccontextmanager`</a>
+///
- будет корректно использоваться в качестве **FastAPI**-зависимости.
+/// note | "Технические детали"
- На самом деле, FastAPI использует эту пару декораторов "под капотом".
+Любая функция, с которой может работать:
+
+* <a href="https://docs.python.org/3/library/contextlib.html#contextlib.contextmanager" class="external-link" target="_blank">`@contextlib.contextmanager`</a> или
+* <a href="https://docs.python.org/3/library/contextlib.html#contextlib.asynccontextmanager" class="external-link" target="_blank">`@contextlib.asynccontextmanager`</a>
+
+будет корректно использоваться в качестве **FastAPI**-зависимости.
+
+На самом деле, FastAPI использует эту пару декораторов "под капотом".
+
+///
## Зависимость базы данных с помощью `yield`
{!../../../docs_src/dependencies/tutorial007.py!}
```
-!!! tip "Подсказка"
- Можно использовать как `async` так и обычные функции.
+/// tip | "Подсказка"
+
+Можно использовать как `async` так и обычные функции.
- **FastAPI** это корректно обработает, и в обоих случаях будет делать то же самое, что и с обычными зависимостями.
+**FastAPI** это корректно обработает, и в обоих случаях будет делать то же самое, что и с обычными зависимостями.
+
+///
## Зависимость с `yield` и `try` одновременно
Например, `dependency_c` может иметь зависимость от `dependency_b`, а `dependency_b` от `dependency_a`:
-=== "Python 3.9+"
+//// tab | Python 3.9+
+
+```Python hl_lines="6 14 22"
+{!> ../../../docs_src/dependencies/tutorial008_an_py39.py!}
+```
- ```Python hl_lines="6 14 22"
- {!> ../../../docs_src/dependencies/tutorial008_an_py39.py!}
- ```
+////
-=== "Python 3.6+"
+//// tab | Python 3.6+
+
+```Python hl_lines="5 13 21"
+{!> ../../../docs_src/dependencies/tutorial008_an.py!}
+```
- ```Python hl_lines="5 13 21"
- {!> ../../../docs_src/dependencies/tutorial008_an.py!}
- ```
+////
-=== "Python 3.6+ без Annotated"
+//// tab | Python 3.6+ без Annotated
- !!! tip "Подсказка"
- Предпочтительнее использовать версию с аннотацией, если это возможно.
+/// tip | "Подсказка"
- ```Python hl_lines="4 12 20"
- {!> ../../../docs_src/dependencies/tutorial008.py!}
- ```
+Предпочтительнее использовать версию с аннотацией, если это возможно.
+
+///
+
+```Python hl_lines="4 12 20"
+{!> ../../../docs_src/dependencies/tutorial008.py!}
+```
+
+////
И все они могут использовать `yield`.
И, в свою очередь, `dependency_b` нуждается в том, чтобы значение из `dependency_a` (здесь `dep_a`) было доступно для ее завершающего кода.
-=== "Python 3.9+"
+//// tab | Python 3.9+
- ```Python hl_lines="18-19 26-27"
- {!> ../../../docs_src/dependencies/tutorial008_an_py39.py!}
- ```
+```Python hl_lines="18-19 26-27"
+{!> ../../../docs_src/dependencies/tutorial008_an_py39.py!}
+```
+
+////
+
+//// tab | Python 3.6+
+
+```Python hl_lines="17-18 25-26"
+{!> ../../../docs_src/dependencies/tutorial008_an.py!}
+```
-=== "Python 3.6+"
+////
- ```Python hl_lines="17-18 25-26"
- {!> ../../../docs_src/dependencies/tutorial008_an.py!}
- ```
+//// tab | Python 3.6+ без Annotated
-=== "Python 3.6+ без Annotated"
+/// tip | "Подсказка"
- !!! tip "Подсказка"
- Предпочтительнее использовать версию с аннотацией, если это возможно.
+Предпочтительнее использовать версию с аннотацией, если это возможно.
- ```Python hl_lines="16-17 24-25"
- {!> ../../../docs_src/dependencies/tutorial008.py!}
- ```
+///
+
+```Python hl_lines="16-17 24-25"
+{!> ../../../docs_src/dependencies/tutorial008.py!}
+```
+
+////
Точно так же можно иметь часть зависимостей с `yield`, часть с `return`, и какие-то из них могут зависеть друг от друга.
**FastAPI** проследит за тем, чтобы все выполнялось в правильном порядке.
-!!! note "Технические детали"
- Это работает благодаря <a href="https://docs.python.org/3/library/contextlib.html" class="external-link" target="_blank">Контекстным менеджерам</a> в Python.
+/// note | "Технические детали"
+
+Это работает благодаря <a href="https://docs.python.org/3/library/contextlib.html" class="external-link" target="_blank">Контекстным менеджерам</a> в Python.
+
+///
**FastAPI** использует их "под капотом" с этой целью.
Если у вас есть пользовательские исключения, которые вы хотите обрабатывать *до* возврата ответа и, возможно, модифицировать ответ, даже вызывая `HTTPException`, создайте [Cобственный обработчик исключений](../handling-errors.md#install-custom-exception-handlers){.internal-link target=_blank}.
-!!! tip "Подсказка"
- Вы все еще можете вызывать исключения, включая `HTTPException`, *до* `yield`. Но не после.
+/// tip | "Подсказка"
+
+Вы все еще можете вызывать исключения, включая `HTTPException`, *до* `yield`. Но не после.
+
+///
Последовательность выполнения примерно такая, как на этой схеме. Время течет сверху вниз. А каждый столбец - это одна из частей, взаимодействующих с кодом или выполняющих код.
end
```
-!!! info "Дополнительная информация"
- Клиенту будет отправлен только **один ответ**. Это может быть один из ответов об ошибке или это будет ответ от *операции пути*.
+/// info | "Дополнительная информация"
+
+Клиенту будет отправлен только **один ответ**. Это может быть один из ответов об ошибке или это будет ответ от *операции пути*.
+
+После отправки одного из этих ответов никакой другой ответ не может быть отправлен.
- После отправки одного из этих ответов никакой другой ответ не может быть отправлен.
+///
-!!! tip "Подсказка"
- На этой диаграмме показано "HttpException", но вы также можете вызвать любое другое исключение, для которого вы создаете [Пользовательский обработчик исключений](../handling-errors.md#install-custom-exception-handlers){.internal-link target=_blank}.
+/// tip | "Подсказка"
- Если вы создадите какое-либо исключение, оно будет передано зависимостям с yield, включая `HttpException`, а затем **снова** обработчикам исключений. Если для этого исключения нет обработчика исключений, то оно будет обработано внутренним "ServerErrorMiddleware" по умолчанию, возвращающим код состояния HTTP 500, чтобы уведомить клиента, что на сервере произошла ошибка.
+На этой диаграмме показано "HttpException", но вы также можете вызвать любое другое исключение, для которого вы создаете [Пользовательский обработчик исключений](../handling-errors.md#install-custom-exception-handlers){.internal-link target=_blank}.
+
+Если вы создадите какое-либо исключение, оно будет передано зависимостям с yield, включая `HttpException`, а затем **снова** обработчикам исключений. Если для этого исключения нет обработчика исключений, то оно будет обработано внутренним "ServerErrorMiddleware" по умолчанию, возвращающим код состояния HTTP 500, чтобы уведомить клиента, что на сервере произошла ошибка.
+
+///
## Зависимости с `yield`, `HTTPException` и фоновыми задачами
-!!! warning "Внимание"
- Скорее всего, вам не нужны эти технические подробности, вы можете пропустить этот раздел и продолжить ниже.
+/// warning | "Внимание"
+
+Скорее всего, вам не нужны эти технические подробности, вы можете пропустить этот раздел и продолжить ниже.
- Эти подробности полезны, главным образом, если вы использовали версию FastAPI до 0.106.0 и использовали ресурсы из зависимостей с `yield` в фоновых задачах.
+Эти подробности полезны, главным образом, если вы использовали версию FastAPI до 0.106.0 и использовали ресурсы из зависимостей с `yield` в фоновых задачах.
+
+///
До версии FastAPI 0.106.0 вызывать исключения после `yield` было невозможно, код выхода в зависимостях с `yield` выполнялся *после* отправки ответа, поэтому [Обработчик Ошибок](../handling-errors.md#install-custom-exception-handlers){.internal-link target=_blank} уже был бы запущен.
Тем не менее, поскольку это означало бы ожидание ответа в сети, а также ненужное удержание ресурса в зависимости от доходности (например, соединение с базой данных), это было изменено в FastAPI 0.106.0.
-!!! tip "Подсказка"
+/// tip | "Подсказка"
+
+Кроме того, фоновая задача обычно представляет собой независимый набор логики, который должен обрабатываться отдельно, со своими собственными ресурсами (например, собственным подключением к базе данных).
+Таким образом, вы, вероятно, получите более чистый код.
- Кроме того, фоновая задача обычно представляет собой независимый набор логики, который должен обрабатываться отдельно, со своими собственными ресурсами (например, собственным подключением к базе данных).
- Таким образом, вы, вероятно, получите более чистый код.
+///
Если вы полагались на это поведение, то теперь вам следует создавать ресурсы для фоновых задач внутри самой фоновой задачи, а внутри использовать только те данные, которые не зависят от ресурсов зависимостей с `yield`.
### Использование менеджеров контекста в зависимостях с помощью `yield`
-!!! warning "Внимание"
- Это более или менее "продвинутая" идея.
+/// warning | "Внимание"
- Если вы только начинаете работать с **FastAPI**, то лучше пока пропустить этот пункт.
+Это более или менее "продвинутая" идея.
+
+Если вы только начинаете работать с **FastAPI**, то лучше пока пропустить этот пункт.
+
+///
В Python для создания менеджеров контекста можно <a href="https://docs.python.org/3/reference/datamodel.html#context-managers" class="external-link" target="_blank">создать класс с двумя методами: `__enter__()` и `__exit__()`</a>.
{!../../../docs_src/dependencies/tutorial010.py!}
```
-!!! tip "Подсказка"
- Другой способ создания контекстного менеджера - с помощью:
+/// tip | "Подсказка"
+
+Другой способ создания контекстного менеджера - с помощью:
+
+* <a href="https://docs.python.org/3/library/contextlib.html#contextlib.contextmanager" class="external-link" target="_blank">`@contextlib.contextmanager`</a> или
+* <a href="https://docs.python.org/3/library/contextlib.html#contextlib.asynccontextmanager" class="external-link" target="_blank">`@contextlib.asynccontextmanager`</a>
- * <a href="https://docs.python.org/3/library/contextlib.html#contextlib.contextmanager" class="external-link" target="_blank">`@contextlib.contextmanager`</a> или
- * <a href="https://docs.python.org/3/library/contextlib.html#contextlib.asynccontextmanager" class="external-link" target="_blank">`@contextlib.asynccontextmanager`</a>
+используйте их для оформления функции с одним `yield`.
- используйте их для оформления функции с одним `yield`.
+Это то, что **FastAPI** использует внутри себя для зависимостей с `yield`.
- Это то, что **FastAPI** использует внутри себя для зависимостей с `yield`.
+Но использовать декораторы для зависимостей FastAPI не обязательно (да и не стоит).
- Но использовать декораторы для зависимостей FastAPI не обязательно (да и не стоит).
+FastAPI сделает это за вас на внутреннем уровне.
- FastAPI сделает это за вас на внутреннем уровне.
+///
В этом случае они будут применяться ко всем *операциям пути* в приложении:
-=== "Python 3.9+"
+//// tab | Python 3.9+
- ```Python hl_lines="16"
- {!> ../../../docs_src/dependencies/tutorial012_an_py39.py!}
- ```
+```Python hl_lines="16"
+{!> ../../../docs_src/dependencies/tutorial012_an_py39.py!}
+```
-=== "Python 3.8+"
+////
- ```Python hl_lines="16"
- {!> ../../../docs_src/dependencies/tutorial012_an.py!}
- ```
+//// tab | Python 3.8+
-=== "Python 3.8 non-Annotated"
+```Python hl_lines="16"
+{!> ../../../docs_src/dependencies/tutorial012_an.py!}
+```
- !!! tip "Подсказка"
- Рекомендуется использовать 'Annotated' версию, если это возможно.
+////
- ```Python hl_lines="15"
- {!> ../../../docs_src/dependencies/tutorial012.py!}
- ```
+//// tab | Python 3.8 non-Annotated
+
+/// tip | "Подсказка"
+
+Рекомендуется использовать 'Annotated' версию, если это возможно.
+
+///
+
+```Python hl_lines="15"
+{!> ../../../docs_src/dependencies/tutorial012.py!}
+```
+
+////
Все способы [добавления зависимостей в *декораторах операций пути*](dependencies-in-path-operation-decorators.md){.internal-link target=_blank} по-прежнему применимы, но в данном случае зависимости применяются ко всем *операциям пути* приложения.
Давайте для начала сфокусируемся на зависимостях.
Это просто функция, которая может принимать все те же параметры, что и *функции обработки пути*:
-=== "Python 3.10+"
+//// tab | Python 3.10+
- ```Python hl_lines="8-9"
- {!> ../../../docs_src/dependencies/tutorial001_an_py310.py!}
- ```
+```Python hl_lines="8-9"
+{!> ../../../docs_src/dependencies/tutorial001_an_py310.py!}
+```
+
+////
+
+//// tab | Python 3.9+
+
+```Python hl_lines="8-11"
+{!> ../../../docs_src/dependencies/tutorial001_an_py39.py!}
+```
+
+////
+
+//// tab | Python 3.8+
-=== "Python 3.9+"
+```Python hl_lines="9-12"
+{!> ../../../docs_src/dependencies/tutorial001_an.py!}
+```
+
+////
- ```Python hl_lines="8-11"
- {!> ../../../docs_src/dependencies/tutorial001_an_py39.py!}
- ```
+//// tab | Python 3.10+ non-Annotated
-=== "Python 3.8+"
+/// tip | "Подсказка"
- ```Python hl_lines="9-12"
- {!> ../../../docs_src/dependencies/tutorial001_an.py!}
- ```
+Настоятельно рекомендуем использовать `Annotated` версию насколько это возможно.
-=== "Python 3.10+ non-Annotated"
+///
- !!! tip "Подсказка"
- Настоятельно рекомендуем использовать `Annotated` версию насколько это возможно.
+```Python hl_lines="6-7"
+{!> ../../../docs_src/dependencies/tutorial001_py310.py!}
+```
- ```Python hl_lines="6-7"
- {!> ../../../docs_src/dependencies/tutorial001_py310.py!}
- ```
+////
-=== "Python 3.8+ non-Annotated"
+//// tab | Python 3.8+ non-Annotated
- !!! tip "Подсказка"
+/// tip | "Подсказка"
- Настоятельно рекомендуем использовать `Annotated` версию насколько это возможно.
+Настоятельно рекомендуем использовать `Annotated` версию насколько это возможно.
- ```Python hl_lines="8-11"
- {!> ../../../docs_src/dependencies/tutorial001.py!}
- ```
+///
+
+```Python hl_lines="8-11"
+{!> ../../../docs_src/dependencies/tutorial001.py!}
+```
+
+////
**И всё.**
И в конце она возвращает `dict`, содержащий эти значения.
-!!! info "Информация"
+/// info | "Информация"
+
+**FastAPI** добавил поддержку для `Annotated` (и начал её рекомендовать) в версии 0.95.0.
- **FastAPI** добавил поддержку для `Annotated` (и начал её рекомендовать) в версии 0.95.0.
+ Если у вас более старая версия, будут ошибки при попытке использовать `Annotated`.
- Если у вас более старая версия, будут ошибки при попытке использовать `Annotated`.
+Убедитесь, что вы [Обновили FastAPI версию](../../deployment/versions.md#fastapi_2){.internal-link target=_blank} до, как минимум 0.95.1, перед тем как использовать `Annotated`.
- Убедитесь, что вы [Обновили FastAPI версию](../../deployment/versions.md#fastapi_2){.internal-link target=_blank} до, как минимум 0.95.1, перед тем как использовать `Annotated`.
+///
### Import `Depends`
-=== "Python 3.10+"
+//// tab | Python 3.10+
- ```Python hl_lines="3"
- {!> ../../../docs_src/dependencies/tutorial001_an_py310.py!}
- ```
+```Python hl_lines="3"
+{!> ../../../docs_src/dependencies/tutorial001_an_py310.py!}
+```
+
+////
+
+//// tab | Python 3.9+
+
+```Python hl_lines="3"
+{!> ../../../docs_src/dependencies/tutorial001_an_py39.py!}
+```
+
+////
+
+//// tab | Python 3.8+
-=== "Python 3.9+"
+```Python hl_lines="3"
+{!> ../../../docs_src/dependencies/tutorial001_an.py!}
+```
+
+////
- ```Python hl_lines="3"
- {!> ../../../docs_src/dependencies/tutorial001_an_py39.py!}
- ```
+//// tab | Python 3.10+ non-Annotated
-=== "Python 3.8+"
+/// tip | "Подсказка"
- ```Python hl_lines="3"
- {!> ../../../docs_src/dependencies/tutorial001_an.py!}
- ```
+Настоятельно рекомендуем использовать `Annotated` версию насколько это возможно.
-=== "Python 3.10+ non-Annotated"
+///
+
+```Python hl_lines="1"
+{!> ../../../docs_src/dependencies/tutorial001_py310.py!}
+```
- !!! tip "Подсказка"
- Настоятельно рекомендуем использовать `Annotated` версию насколько это возможно.
+////
- ```Python hl_lines="1"
- {!> ../../../docs_src/dependencies/tutorial001_py310.py!}
- ```
+//// tab | Python 3.8+ non-Annotated
-=== "Python 3.8+ non-Annotated"
+/// tip | "Подсказка"
- !!! tip "Подсказка"
- Настоятельно рекомендуем использовать `Annotated` версию насколько это возможно.
+Настоятельно рекомендуем использовать `Annotated` версию насколько это возможно.
+
+///
+
+```Python hl_lines="3"
+{!> ../../../docs_src/dependencies/tutorial001.py!}
+```
- ```Python hl_lines="3"
- {!> ../../../docs_src/dependencies/tutorial001.py!}
- ```
+////
### Объявите зависимость в "зависимом"
Точно так же, как вы использовали `Body`, `Query` и т.д. с вашей *функцией обработки пути* для параметров, используйте `Depends` с новым параметром:
-=== "Python 3.10+"
+//// tab | Python 3.10+
- ```Python hl_lines="13 18"
- {!> ../../../docs_src/dependencies/tutorial001_an_py310.py!}
- ```
+```Python hl_lines="13 18"
+{!> ../../../docs_src/dependencies/tutorial001_an_py310.py!}
+```
+
+////
+
+//// tab | Python 3.9+
+
+```Python hl_lines="15 20"
+{!> ../../../docs_src/dependencies/tutorial001_an_py39.py!}
+```
+
+////
+
+//// tab | Python 3.8+
-=== "Python 3.9+"
+```Python hl_lines="16 21"
+{!> ../../../docs_src/dependencies/tutorial001_an.py!}
+```
+
+////
- ```Python hl_lines="15 20"
- {!> ../../../docs_src/dependencies/tutorial001_an_py39.py!}
- ```
+//// tab | Python 3.10+ non-Annotated
-=== "Python 3.8+"
+/// tip | "Подсказка"
- ```Python hl_lines="16 21"
- {!> ../../../docs_src/dependencies/tutorial001_an.py!}
- ```
+Настоятельно рекомендуем использовать `Annotated` версию насколько это возможно.
-=== "Python 3.10+ non-Annotated"
+///
+
+```Python hl_lines="11 16"
+{!> ../../../docs_src/dependencies/tutorial001_py310.py!}
+```
- !!! tip "Подсказка"
- Настоятельно рекомендуем использовать `Annotated` версию насколько это возможно.
+////
- ```Python hl_lines="11 16"
- {!> ../../../docs_src/dependencies/tutorial001_py310.py!}
- ```
+//// tab | Python 3.8+ non-Annotated
-=== "Python 3.8+ non-Annotated"
+/// tip | "Подсказка"
- !!! tip "Подсказка"
- Настоятельно рекомендуем использовать `Annotated` версию насколько это возможно.
+Настоятельно рекомендуем использовать `Annotated` версию насколько это возможно.
+
+///
+
+```Python hl_lines="15 20"
+{!> ../../../docs_src/dependencies/tutorial001.py!}
+```
- ```Python hl_lines="15 20"
- {!> ../../../docs_src/dependencies/tutorial001.py!}
- ```
+////
`Depends` работает немного иначе. Вы передаёте в `Depends` одиночный параметр, который будет похож на функцию.
И потом функция берёт параметры так же, как *функция обработки пути*.
-!!! tip "Подсказка"
- В следующей главе вы увидите, какие другие вещи, помимо функций, можно использовать в качестве зависимостей.
+/// tip | "Подсказка"
+
+В следующей главе вы увидите, какие другие вещи, помимо функций, можно использовать в качестве зависимостей.
+
+///
Каждый раз, когда новый запрос приходит, **FastAPI** позаботится о:
Таким образом, вы пишете общий код один раз, и **FastAPI** позаботится о его вызове для ваших *операций с путями*.
-!!! check "Проверка"
- Обратите внимание, что вы не создаёте специальный класс и не передаёте его куда-то в **FastAPI** для регистрации, или что-то в этом роде.
+/// check | "Проверка"
+
+Обратите внимание, что вы не создаёте специальный класс и не передаёте его куда-то в **FastAPI** для регистрации, или что-то в этом роде.
+
+Вы просто передаёте это в `Depends`, и **FastAPI** знает, что делать дальше.
- Вы просто передаёте это в `Depends`, и **FastAPI** знает, что делать дальше.
+///
## Объединяем с `Annotated` зависимостями
Но потому что мы используем `Annotated`, мы можем хранить `Annotated` значение в переменной и использовать его в нескольких местах:
-=== "Python 3.10+"
+//// tab | Python 3.10+
- ```Python hl_lines="12 16 21"
- {!> ../../../docs_src/dependencies/tutorial001_02_an_py310.py!}
- ```
+```Python hl_lines="12 16 21"
+{!> ../../../docs_src/dependencies/tutorial001_02_an_py310.py!}
+```
-=== "Python 3.9+"
+////
- ```Python hl_lines="14 18 23"
- {!> ../../../docs_src/dependencies/tutorial001_02_an_py39.py!}
- ```
+//// tab | Python 3.9+
-=== "Python 3.8+"
+```Python hl_lines="14 18 23"
+{!> ../../../docs_src/dependencies/tutorial001_02_an_py39.py!}
+```
- ```Python hl_lines="15 19 24"
- {!> ../../../docs_src/dependencies/tutorial001_02_an.py!}
- ```
+////
-!!! tip "Подсказка"
- Это стандартный синтаксис python и называется "type alias", это не особенность **FastAPI**.
+//// tab | Python 3.8+
- Но потому что **FastAPI** базируется на стандартах Python, включая `Annotated`, вы можете использовать этот трюк в вашем коде. 😎
+```Python hl_lines="15 19 24"
+{!> ../../../docs_src/dependencies/tutorial001_02_an.py!}
+```
+////
+
+/// tip | "Подсказка"
+
+Это стандартный синтаксис python и называется "type alias", это не особенность **FastAPI**.
+
+Но потому что **FastAPI** базируется на стандартах Python, включая `Annotated`, вы можете использовать этот трюк в вашем коде. 😎
+
+///
Зависимости продолжат работу как ожидалось, и **лучшая часть** в том, что **информация о типе будет сохранена**. Это означает, что ваш редактор кода будет корректно обрабатывать **автодополнения**, **встроенные ошибки** и так далее. То же самое относится и к инструментам, таким как `mypy`.
Это всё не важно. **FastAPI** знает, что нужно сделать. 😎
-!!! note "Информация"
- Если вам эта тема не знакома, прочтите [Async: *"In a hurry?"*](../../async.md){.internal-link target=_blank} раздел о `async` и `await` в документации.
+/// note | "Информация"
+
+Если вам эта тема не знакома, прочтите [Async: *"In a hurry?"*](../../async.md){.internal-link target=_blank} раздел о `async` и `await` в документации.
+
+///
## Интеграция с OpenAPI
Можно создать первую зависимость следующим образом:
-=== "Python 3.10+"
+//// tab | Python 3.10+
- ```Python hl_lines="8-9"
- {!> ../../../docs_src/dependencies/tutorial005_an_py310.py!}
- ```
+```Python hl_lines="8-9"
+{!> ../../../docs_src/dependencies/tutorial005_an_py310.py!}
+```
+
+////
-=== "Python 3.9+"
+//// tab | Python 3.9+
+
+```Python hl_lines="8-9"
+{!> ../../../docs_src/dependencies/tutorial005_an_py39.py!}
+```
- ```Python hl_lines="8-9"
- {!> ../../../docs_src/dependencies/tutorial005_an_py39.py!}
- ```
+////
+
+//// tab | Python 3.6+
+
+```Python hl_lines="9-10"
+{!> ../../../docs_src/dependencies/tutorial005_an.py!}
+```
-=== "Python 3.6+"
+////
+
+//// tab | Python 3.10 без Annotated
+
+/// tip | "Подсказка"
+
+Предпочтительнее использовать версию с аннотацией, если это возможно.
+
+///
+
+```Python hl_lines="6-7"
+{!> ../../../docs_src/dependencies/tutorial005_py310.py!}
+```
- ```Python hl_lines="9-10"
- {!> ../../../docs_src/dependencies/tutorial005_an.py!}
- ```
+////
-=== "Python 3.10 без Annotated"
+//// tab | Python 3.6 без Annotated
- !!! tip "Подсказка"
- Предпочтительнее использовать версию с аннотацией, если это возможно.
+/// tip | "Подсказка"
- ```Python hl_lines="6-7"
- {!> ../../../docs_src/dependencies/tutorial005_py310.py!}
- ```
+Предпочтительнее использовать версию с аннотацией, если это возможно.
-=== "Python 3.6 без Annotated"
+///
- !!! tip "Подсказка"
- Предпочтительнее использовать версию с аннотацией, если это возможно.
+```Python hl_lines="8-9"
+{!> ../../../docs_src/dependencies/tutorial005.py!}
+```
- ```Python hl_lines="8-9"
- {!> ../../../docs_src/dependencies/tutorial005.py!}
- ```
+////
Она объявляет необязательный параметр запроса `q` как строку, а затем возвращает его.
Затем можно создать еще одну функцию зависимости, которая в то же время содержит внутри себя первую зависимость (таким образом, она тоже является "зависимой"):
-=== "Python 3.10+"
+//// tab | Python 3.10+
+
+```Python hl_lines="13"
+{!> ../../../docs_src/dependencies/tutorial005_an_py310.py!}
+```
+
+////
+
+//// tab | Python 3.9+
+
+```Python hl_lines="13"
+{!> ../../../docs_src/dependencies/tutorial005_an_py39.py!}
+```
+
+////
+
+//// tab | Python 3.6+
+
+```Python hl_lines="14"
+{!> ../../../docs_src/dependencies/tutorial005_an.py!}
+```
+
+////
+
+//// tab | Python 3.10 без Annotated
- ```Python hl_lines="13"
- {!> ../../../docs_src/dependencies/tutorial005_an_py310.py!}
- ```
+/// tip | "Подсказка"
-=== "Python 3.9+"
+Предпочтительнее использовать версию с аннотацией, если это возможно.
- ```Python hl_lines="13"
- {!> ../../../docs_src/dependencies/tutorial005_an_py39.py!}
- ```
+///
-=== "Python 3.6+"
+```Python hl_lines="11"
+{!> ../../../docs_src/dependencies/tutorial005_py310.py!}
+```
- ```Python hl_lines="14"
- {!> ../../../docs_src/dependencies/tutorial005_an.py!}
- ```
+////
-=== "Python 3.10 без Annotated"
+//// tab | Python 3.6 без Annotated
- !!! tip "Подсказка"
- Предпочтительнее использовать версию с аннотацией, если это возможно.
+/// tip | "Подсказка"
- ```Python hl_lines="11"
- {!> ../../../docs_src/dependencies/tutorial005_py310.py!}
- ```
+Предпочтительнее использовать версию с аннотацией, если это возможно.
-=== "Python 3.6 без Annotated"
+///
- !!! tip "Подсказка"
- Предпочтительнее использовать версию с аннотацией, если это возможно.
+```Python hl_lines="13"
+{!> ../../../docs_src/dependencies/tutorial005.py!}
+```
- ```Python hl_lines="13"
- {!> ../../../docs_src/dependencies/tutorial005.py!}
- ```
+////
Остановимся на объявленных параметрах:
Затем мы можем использовать зависимость вместе с:
-=== "Python 3.10+"
+//// tab | Python 3.10+
+
+```Python hl_lines="23"
+{!> ../../../docs_src/dependencies/tutorial005_an_py310.py!}
+```
+
+////
+
+//// tab | Python 3.9+
+
+```Python hl_lines="23"
+{!> ../../../docs_src/dependencies/tutorial005_an_py39.py!}
+```
+
+////
+
+//// tab | Python 3.6+
+
+```Python hl_lines="24"
+{!> ../../../docs_src/dependencies/tutorial005_an.py!}
+```
+
+////
- ```Python hl_lines="23"
- {!> ../../../docs_src/dependencies/tutorial005_an_py310.py!}
- ```
+//// tab | Python 3.10 без Annotated
-=== "Python 3.9+"
+/// tip | "Подсказка"
- ```Python hl_lines="23"
- {!> ../../../docs_src/dependencies/tutorial005_an_py39.py!}
- ```
+Предпочтительнее использовать версию с аннотацией, если это возможно.
-=== "Python 3.6+"
+///
- ```Python hl_lines="24"
- {!> ../../../docs_src/dependencies/tutorial005_an.py!}
- ```
+```Python hl_lines="19"
+{!> ../../../docs_src/dependencies/tutorial005_py310.py!}
+```
+
+////
-=== "Python 3.10 без Annotated"
+//// tab | Python 3.6 без Annotated
- !!! tip "Подсказка"
- Предпочтительнее использовать версию с аннотацией, если это возможно.
+/// tip | "Подсказка"
- ```Python hl_lines="19"
- {!> ../../../docs_src/dependencies/tutorial005_py310.py!}
- ```
+Предпочтительнее использовать версию с аннотацией, если это возможно.
-=== "Python 3.6 без Annotated"
+///
+
+```Python hl_lines="22"
+{!> ../../../docs_src/dependencies/tutorial005.py!}
+```
- !!! tip "Подсказка"
- Предпочтительнее использовать версию с аннотацией, если это возможно.
+////
- ```Python hl_lines="22"
- {!> ../../../docs_src/dependencies/tutorial005.py!}
- ```
+/// info | "Дополнительная информация"
-!!! info "Дополнительная информация"
- Обратите внимание, что мы объявляем только одну зависимость в *функции операции пути* - `query_or_cookie_extractor`.
+Обратите внимание, что мы объявляем только одну зависимость в *функции операции пути* - `query_or_cookie_extractor`.
- Но **FastAPI** будет знать, что сначала он должен выполнить `query_extractor`, чтобы передать результаты этого в `query_or_cookie_extractor` при его вызове.
+Но **FastAPI** будет знать, что сначала он должен выполнить `query_extractor`, чтобы передать результаты этого в `query_or_cookie_extractor` при его вызове.
+
+///
```mermaid
graph TB
В расширенном сценарии, когда вы знаете, что вам нужно, чтобы зависимость вызывалась на каждом шаге (возможно, несколько раз) в одном и том же запросе, вместо использования "кэшированного" значения, вы можете установить параметр `use_cache=False` при использовании `Depends`:
-=== "Python 3.6+"
+//// tab | Python 3.6+
+
+```Python hl_lines="1"
+async def needy_dependency(fresh_value: Annotated[str, Depends(get_value, use_cache=False)]):
+ return {"fresh_value": fresh_value}
+```
- ```Python hl_lines="1"
- async def needy_dependency(fresh_value: Annotated[str, Depends(get_value, use_cache=False)]):
- return {"fresh_value": fresh_value}
- ```
+////
-=== "Python 3.6+ без Annotated"
+//// tab | Python 3.6+ без Annotated
- !!! tip "Подсказка"
- Предпочтительнее использовать версию с аннотацией, если это возможно.
+/// tip | "Подсказка"
- ```Python hl_lines="1"
- async def needy_dependency(fresh_value: str = Depends(get_value, use_cache=False)):
- return {"fresh_value": fresh_value}
- ```
+Предпочтительнее использовать версию с аннотацией, если это возможно.
+
+///
+
+```Python hl_lines="1"
+async def needy_dependency(fresh_value: str = Depends(get_value, use_cache=False)):
+ return {"fresh_value": fresh_value}
+```
+
+////
## Резюме
Но, тем не менее, эта система очень мощная и позволяет вам объявлять вложенные графы (деревья) зависимостей сколь угодно глубоко.
-!!! tip "Подсказка"
- Все это может показаться не столь полезным на этих простых примерах.
+/// tip | "Подсказка"
+
+Все это может показаться не столь полезным на этих простых примерах.
+
+Но вы увидите как это пригодится в главах посвященных безопасности.
- Но вы увидите как это пригодится в главах посвященных безопасности.
+И вы также увидите, сколько кода это вам сэкономит.
- И вы также увидите, сколько кода это вам сэкономит.
+///
Она принимает объект, например, модель Pydantic, и возвращает его версию, совместимую с JSON:
-=== "Python 3.10+"
+//// tab | Python 3.10+
- ```Python hl_lines="4 21"
- {!> ../../../docs_src/encoder/tutorial001_py310.py!}
- ```
+```Python hl_lines="4 21"
+{!> ../../../docs_src/encoder/tutorial001_py310.py!}
+```
-=== "Python 3.6+"
+////
- ```Python hl_lines="5 22"
- {!> ../../../docs_src/encoder/tutorial001.py!}
- ```
+//// tab | Python 3.6+
+
+```Python hl_lines="5 22"
+{!> ../../../docs_src/encoder/tutorial001.py!}
+```
+
+////
В данном примере она преобразует Pydantic модель в `dict`, а `datetime` - в `str`.
Функция не возвращает большой `str`, содержащий данные в формате JSON (в виде строки). Она возвращает стандартную структуру данных Python (например, `dict`) со значениями и подзначениями, которые совместимы с JSON.
-!!! note "Технические детали"
- `jsonable_encoder` фактически используется **FastAPI** внутри системы для преобразования данных. Однако он полезен и во многих других сценариях.
+/// note | "Технические детали"
+
+`jsonable_encoder` фактически используется **FastAPI** внутри системы для преобразования данных. Однако он полезен и во многих других сценариях.
+
+///
Вот пример *операции пути* с параметрами, который демонстрирует некоторые из вышеперечисленных типов.
-=== "Python 3.8 и выше"
+//// tab | Python 3.8 и выше
- ```Python hl_lines="1 3 12-16"
- {!> ../../../docs_src/extra_data_types/tutorial001.py!}
- ```
+```Python hl_lines="1 3 12-16"
+{!> ../../../docs_src/extra_data_types/tutorial001.py!}
+```
-=== "Python 3.10 и выше"
+////
- ```Python hl_lines="1 2 11-15"
- {!> ../../../docs_src/extra_data_types/tutorial001_py310.py!}
- ```
+//// tab | Python 3.10 и выше
+
+```Python hl_lines="1 2 11-15"
+{!> ../../../docs_src/extra_data_types/tutorial001_py310.py!}
+```
+
+////
Обратите внимание, что параметры внутри функции имеют свой естественный тип данных, и вы, например, можете выполнять обычные манипуляции с датами, такие как:
-=== "Python 3.8 и выше"
+//// tab | Python 3.8 и выше
+
+```Python hl_lines="18-19"
+{!> ../../../docs_src/extra_data_types/tutorial001.py!}
+```
+
+////
- ```Python hl_lines="18-19"
- {!> ../../../docs_src/extra_data_types/tutorial001.py!}
- ```
+//// tab | Python 3.10 и выше
-=== "Python 3.10 и выше"
+```Python hl_lines="17-18"
+{!> ../../../docs_src/extra_data_types/tutorial001_py310.py!}
+```
- ```Python hl_lines="17-18"
- {!> ../../../docs_src/extra_data_types/tutorial001_py310.py!}
- ```
+////
* **Модель для вывода** не должна содержать пароль.
* **Модель для базы данных**, возможно, должна содержать хэшированный пароль.
-!!! danger "Внимание"
- Никогда не храните пароли пользователей в чистом виде. Всегда храните "безопасный хэш", который вы затем сможете проверить.
+/// danger | "Внимание"
- Если вам это не знакомо, вы можете узнать про "хэш пароля" в [главах о безопасности](security/simple-oauth2.md#password-hashing){.internal-link target=_blank}.
+Никогда не храните пароли пользователей в чистом виде. Всегда храните "безопасный хэш", который вы затем сможете проверить.
+
+Если вам это не знакомо, вы можете узнать про "хэш пароля" в [главах о безопасности](security/simple-oauth2.md#password-hashing){.internal-link target=_blank}.
+
+///
## Множественные модели
Ниже изложена основная идея того, как могут выглядеть эти модели с полями для паролей, а также описаны места, где они используются:
-=== "Python 3.10+"
+//// tab | Python 3.10+
- ```Python hl_lines="7 9 14 20 22 27-28 31-33 38-39"
- {!> ../../../docs_src/extra_models/tutorial001_py310.py!}
- ```
+```Python hl_lines="7 9 14 20 22 27-28 31-33 38-39"
+{!> ../../../docs_src/extra_models/tutorial001_py310.py!}
+```
-=== "Python 3.8+"
+////
- ```Python hl_lines="9 11 16 22 24 29-30 33-35 40-41"
- {!> ../../../docs_src/extra_models/tutorial001.py!}
- ```
+//// tab | Python 3.8+
+
+```Python hl_lines="9 11 16 22 24 29-30 33-35 40-41"
+{!> ../../../docs_src/extra_models/tutorial001.py!}
+```
+
+////
### Про `**user_in.dict()`
)
```
-!!! warning "Предупреждение"
- Цель использованных в примере вспомогательных функций - не более чем демонстрация возможных операций с данными, но, конечно, они не обеспечивают настоящую безопасность.
+/// warning | "Предупреждение"
+
+Цель использованных в примере вспомогательных функций - не более чем демонстрация возможных операций с данными, но, конечно, они не обеспечивают настоящую безопасность.
+
+///
## Сократите дублирование
В этом случае мы можем определить только различия между моделями (с `password` в чистом виде, с `hashed_password` и без пароля):
-=== "Python 3.10+"
+//// tab | Python 3.10+
+
+```Python hl_lines="7 13-14 17-18 21-22"
+{!> ../../../docs_src/extra_models/tutorial002_py310.py!}
+```
+
+////
- ```Python hl_lines="7 13-14 17-18 21-22"
- {!> ../../../docs_src/extra_models/tutorial002_py310.py!}
- ```
+//// tab | Python 3.8+
-=== "Python 3.8+"
+```Python hl_lines="9 15-16 19-20 23-24"
+{!> ../../../docs_src/extra_models/tutorial002.py!}
+```
- ```Python hl_lines="9 15-16 19-20 23-24"
- {!> ../../../docs_src/extra_models/tutorial002.py!}
- ```
+////
## `Union` или `anyOf`
Для этого используйте стандартные аннотации типов в Python <a href="https://docs.python.org/3/library/typing.html#typing.Union" class="external-link" target="_blank">`typing.Union`</a>:
-!!! note "Примечание"
- При объявлении <a href="https://docs.pydantic.dev/latest/concepts/types/#unions" class="external-link" target="_blank">`Union`</a>, сначала указывайте наиболее детальные типы, затем менее детальные. В примере ниже более детальный `PlaneItem` стоит перед `CarItem` в `Union[PlaneItem, CarItem]`.
+/// note | "Примечание"
+
+При объявлении <a href="https://docs.pydantic.dev/latest/concepts/types/#unions" class="external-link" target="_blank">`Union`</a>, сначала указывайте наиболее детальные типы, затем менее детальные. В примере ниже более детальный `PlaneItem` стоит перед `CarItem` в `Union[PlaneItem, CarItem]`.
-=== "Python 3.10+"
+///
- ```Python hl_lines="1 14-15 18-20 33"
- {!> ../../../docs_src/extra_models/tutorial003_py310.py!}
- ```
+//// tab | Python 3.10+
-=== "Python 3.8+"
+```Python hl_lines="1 14-15 18-20 33"
+{!> ../../../docs_src/extra_models/tutorial003_py310.py!}
+```
+
+////
- ```Python hl_lines="1 14-15 18-20 33"
- {!> ../../../docs_src/extra_models/tutorial003.py!}
- ```
+//// tab | Python 3.8+
+
+```Python hl_lines="1 14-15 18-20 33"
+{!> ../../../docs_src/extra_models/tutorial003.py!}
+```
+
+////
### `Union` в Python 3.10
Для этого используйте `typing.List` из стандартной библиотеки Python (или просто `list` в Python 3.9 и выше):
-=== "Python 3.9+"
+//// tab | Python 3.9+
- ```Python hl_lines="18"
- {!> ../../../docs_src/extra_models/tutorial004_py39.py!}
- ```
+```Python hl_lines="18"
+{!> ../../../docs_src/extra_models/tutorial004_py39.py!}
+```
-=== "Python 3.8+"
+////
- ```Python hl_lines="1 20"
- {!> ../../../docs_src/extra_models/tutorial004.py!}
- ```
+//// tab | Python 3.8+
+
+```Python hl_lines="1 20"
+{!> ../../../docs_src/extra_models/tutorial004.py!}
+```
+
+////
## Ответ с произвольным `dict`
В этом случае вы можете использовать `typing.Dict` (или просто `dict` в Python 3.9 и выше):
-=== "Python 3.9+"
+//// tab | Python 3.9+
+
+```Python hl_lines="6"
+{!> ../../../docs_src/extra_models/tutorial005_py39.py!}
+```
+
+////
- ```Python hl_lines="6"
- {!> ../../../docs_src/extra_models/tutorial005_py39.py!}
- ```
+//// tab | Python 3.8+
-=== "Python 3.8+"
+```Python hl_lines="1 8"
+{!> ../../../docs_src/extra_models/tutorial005.py!}
+```
- ```Python hl_lines="1 8"
- {!> ../../../docs_src/extra_models/tutorial005.py!}
- ```
+////
## Резюме
</div>
-!!! note "Технические детали"
- Команда `uvicorn main:app` обращается к:
+/// note | "Технические детали"
- * `main`: файл `main.py` (модуль Python).
- * `app`: объект, созданный внутри файла `main.py` в строке `app = FastAPI()`.
- * `--reload`: перезапускает сервер после изменения кода. Используйте только для разработки.
+Команда `uvicorn main:app` обращается к:
+
+* `main`: файл `main.py` (модуль Python).
+* `app`: объект, созданный внутри файла `main.py` в строке `app = FastAPI()`.
+* `--reload`: перезапускает сервер после изменения кода. Используйте только для разработки.
+
+///
В окне вывода появится следующая строка:
`FastAPI` это класс в Python, который предоставляет всю функциональность для API.
-!!! note "Технические детали"
- `FastAPI` это класс, который наследуется непосредственно от `Starlette`.
+/// note | "Технические детали"
+
+`FastAPI` это класс, который наследуется непосредственно от `Starlette`.
- Вы можете использовать всю функциональность <a href="https://www.starlette.io/" class="external-link" target="_blank">Starlette</a> в `FastAPI`.
+Вы можете использовать всю функциональность <a href="https://www.starlette.io/" class="external-link" target="_blank">Starlette</a> в `FastAPI`.
+
+///
### Шаг 2: создайте экземпляр `FastAPI`
/items/foo
```
-!!! info "Дополнительная иформация"
- Термин "path" также часто называется "endpoint" или "route".
+/// info | "Дополнительная иформация"
+
+Термин "path" также часто называется "endpoint" или "route".
+
+///
При создании API, "путь" является основным способом разделения "задач" и "ресурсов".
* путь `/`
* использующих <abbr title="HTTP GET метод"><code>get</code> операцию</abbr>
-!!! info "`@decorator` Дополнительная информация"
- Синтаксис `@something` в Python называется "декоратор".
+/// info | "`@decorator` Дополнительная информация"
- Вы помещаете его над функцией. Как красивую декоративную шляпу (думаю, что оттуда и происходит этот термин).
+Синтаксис `@something` в Python называется "декоратор".
- "Декоратор" принимает функцию ниже и выполняет с ней какое-то действие.
+Вы помещаете его над функцией. Как красивую декоративную шляпу (думаю, что оттуда и происходит этот термин).
- В нашем случае, этот декоратор сообщает **FastAPI**, что функция ниже соответствует **пути** `/` и **операции** `get`.
+"Декоратор" принимает функцию ниже и выполняет с ней какое-то действие.
- Это и есть "**декоратор операции пути**".
+В нашем случае, этот декоратор сообщает **FastAPI**, что функция ниже соответствует **пути** `/` и **операции** `get`.
+
+Это и есть "**декоратор операции пути**".
+
+///
Можно также использовать операции:
* `@app.patch()`
* `@app.trace()`
-!!! tip "Подсказка"
- Вы можете использовать каждую операцию (HTTP-метод) по своему усмотрению.
+/// tip | "Подсказка"
+
+Вы можете использовать каждую операцию (HTTP-метод) по своему усмотрению.
- **FastAPI** не навязывает определенного значения для каждого метода.
+**FastAPI** не навязывает определенного значения для каждого метода.
- Информация здесь представлена как рекомендация, а не требование.
+Информация здесь представлена как рекомендация, а не требование.
- Например, при использовании GraphQL обычно все действия выполняются только с помощью POST операций.
+Например, при использовании GraphQL обычно все действия выполняются только с помощью POST операций.
+
+///
### Шаг 4: определите **функцию операции пути**
{!../../../docs_src/first_steps/tutorial003.py!}
```
-!!! note "Технические детали"
- Если не знаете в чём разница, посмотрите [Конкурентность: *"Нет времени?"*](../async.md#_1){.internal-link target=_blank}.
+/// note | "Технические детали"
+
+Если не знаете в чём разница, посмотрите [Конкурентность: *"Нет времени?"*](../async.md#_1){.internal-link target=_blank}.
+
+///
### Шаг 5: верните результат
}
```
-!!! tip "Подсказка"
- При вызове `HTTPException` в качестве параметра `detail` можно передавать любое значение, которое может быть преобразовано в JSON, а не только `str`.
+/// tip | "Подсказка"
- Вы можете передать `dict`, `list` и т.д.
+При вызове `HTTPException` в качестве параметра `detail` можно передавать любое значение, которое может быть преобразовано в JSON, а не только `str`.
- Они автоматически обрабатываются **FastAPI** и преобразуются в JSON.
+Вы можете передать `dict`, `list` и т.д.
+
+Они автоматически обрабатываются **FastAPI** и преобразуются в JSON.
+
+///
## Добавление пользовательских заголовков
{"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`, просто для удобства разработчика. Однако большинство доступных ответов поступает непосредственно из Starlette. То же самое касается и `Request`.
- **FastAPI** предоставляет тот же `starlette.responses`, что и `fastapi.responses`, просто для удобства разработчика. Однако большинство доступных ответов поступает непосредственно из Starlette. То же самое касается и `Request`.
+///
## Переопределение стандартных обработчиков исключений
#### `RequestValidationError` или `ValidationError`
-!!! warning "Внимание"
- Это технические детали, которые можно пропустить, если они не важны для вас сейчас.
+/// warning | "Внимание"
+
+Это технические детали, которые можно пропустить, если они не важны для вас сейчас.
+
+///
`RequestValidationError` является подклассом Pydantic <a href="https://docs.pydantic.dev/latest/concepts/models/#error-handling" class="external-link" target="_blank">`ValidationError`</a>.
{!../../../docs_src/handling_errors/tutorial004.py!}
```
-!!! note "Технические детали"
- Можно также использовать `from starlette.responses import PlainTextResponse`.
+/// note | "Технические детали"
+
+Можно также использовать `from starlette.responses import PlainTextResponse`.
+
+**FastAPI** предоставляет тот же `starlette.responses`, что и `fastapi.responses`, просто для удобства разработчика. Однако большинство доступных ответов поступает непосредственно из Starlette.
- **FastAPI** предоставляет тот же `starlette.responses`, что и `fastapi.responses`, просто для удобства разработчика. Однако большинство доступных ответов поступает непосредственно из Starlette.
+///
### Используйте тело `RequestValidationError`
Сперва импортируйте `Header`:
-=== "Python 3.10+"
+//// tab | Python 3.10+
- ```Python hl_lines="3"
- {!> ../../../docs_src/header_params/tutorial001_an_py310.py!}
- ```
+```Python hl_lines="3"
+{!> ../../../docs_src/header_params/tutorial001_an_py310.py!}
+```
+
+////
-=== "Python 3.9+"
+//// tab | Python 3.9+
- ```Python hl_lines="3"
- {!> ../../../docs_src/header_params/tutorial001_an_py39.py!}
- ```
+```Python hl_lines="3"
+{!> ../../../docs_src/header_params/tutorial001_an_py39.py!}
+```
-=== "Python 3.8+"
+////
- ```Python hl_lines="3"
- {!> ../../../docs_src/header_params/tutorial001_an.py!}
- ```
+//// tab | Python 3.8+
+
+```Python hl_lines="3"
+{!> ../../../docs_src/header_params/tutorial001_an.py!}
+```
-=== "Python 3.10+ без Annotated"
+////
- !!! tip "Подсказка"
- Предпочтительнее использовать версию с аннотацией, если это возможно.
+//// tab | Python 3.10+ без Annotated
- ```Python hl_lines="1"
- {!> ../../../docs_src/header_params/tutorial001_py310.py!}
- ```
+/// tip | "Подсказка"
+
+Предпочтительнее использовать версию с аннотацией, если это возможно.
+
+///
+
+```Python hl_lines="1"
+{!> ../../../docs_src/header_params/tutorial001_py310.py!}
+```
-=== "Python 3.8+ без Annotated"
+////
- !!! tip "Подсказка"
- Предпочтительнее использовать версию с аннотацией, если это возможно.
+//// tab | Python 3.8+ без Annotated
- ```Python hl_lines="3"
- {!> ../../../docs_src/header_params/tutorial001.py!}
- ```
+/// tip | "Подсказка"
+
+Предпочтительнее использовать версию с аннотацией, если это возможно.
+
+///
+
+```Python hl_lines="3"
+{!> ../../../docs_src/header_params/tutorial001.py!}
+```
+
+////
## Объявление параметров `Header`
Первое значение является значением по умолчанию, вы можете передать все дополнительные параметры валидации или аннотации:
-=== "Python 3.10+"
+//// tab | Python 3.10+
- ```Python hl_lines="9"
- {!> ../../../docs_src/header_params/tutorial001_an_py310.py!}
- ```
+```Python hl_lines="9"
+{!> ../../../docs_src/header_params/tutorial001_an_py310.py!}
+```
-=== "Python 3.9+"
+////
- ```Python hl_lines="9"
- {!> ../../../docs_src/header_params/tutorial001_an_py39.py!}
- ```
+//// tab | Python 3.9+
-=== "Python 3.8+"
+```Python hl_lines="9"
+{!> ../../../docs_src/header_params/tutorial001_an_py39.py!}
+```
- ```Python hl_lines="10"
- {!> ../../../docs_src/header_params/tutorial001_an.py!}
- ```
+////
-=== "Python 3.10+ без Annotated"
+//// tab | Python 3.8+
- !!! tip "Подсказка"
- Предпочтительнее использовать версию с аннотацией, если это возможно.
+```Python hl_lines="10"
+{!> ../../../docs_src/header_params/tutorial001_an.py!}
+```
- ```Python hl_lines="7"
- {!> ../../../docs_src/header_params/tutorial001_py310.py!}
- ```
+////
-=== "Python 3.8+ без Annotated"
+//// tab | Python 3.10+ без Annotated
- !!! tip "Подсказка"
- Предпочтительнее использовать версию с аннотацией, если это возможно.
+/// tip | "Подсказка"
- ```Python hl_lines="9"
- {!> ../../../docs_src/header_params/tutorial001.py!}
- ```
+Предпочтительнее использовать версию с аннотацией, если это возможно.
-!!! note "Технические детали"
- `Header` - это "родственный" класс `Path`, `Query` и `Cookie`. Он также наследуется от того же общего класса `Param`.
+///
- Но помните, что когда вы импортируете `Query`, `Path`, `Header` и другие из `fastapi`, на самом деле это функции, которые возвращают специальные классы.
+```Python hl_lines="7"
+{!> ../../../docs_src/header_params/tutorial001_py310.py!}
+```
+
+////
+
+//// tab | Python 3.8+ без Annotated
+
+/// tip | "Подсказка"
+
+Предпочтительнее использовать версию с аннотацией, если это возможно.
+
+///
+
+```Python hl_lines="9"
+{!> ../../../docs_src/header_params/tutorial001.py!}
+```
-!!! info "Дополнительная информация"
- Чтобы объявить заголовки, важно использовать `Header`, иначе параметры интерпретируются как query-параметры.
+////
+
+/// note | "Технические детали"
+
+`Header` - это "родственный" класс `Path`, `Query` и `Cookie`. Он также наследуется от того же общего класса `Param`.
+
+Но помните, что когда вы импортируете `Query`, `Path`, `Header` и другие из `fastapi`, на самом деле это функции, которые возвращают специальные классы.
+
+///
+
+/// info | "Дополнительная информация"
+
+Чтобы объявить заголовки, важно использовать `Header`, иначе параметры интерпретируются как query-параметры.
+
+///
## Автоматическое преобразование
Если по какой-либо причине вам необходимо отключить автоматическое преобразование подчеркиваний в дефисы, установите для параметра `convert_underscores` в `Header` значение `False`:
-=== "Python 3.10+"
+//// tab | Python 3.10+
+
+```Python hl_lines="10"
+{!> ../../../docs_src/header_params/tutorial002_an_py310.py!}
+```
+
+////
- ```Python hl_lines="10"
- {!> ../../../docs_src/header_params/tutorial002_an_py310.py!}
- ```
+//// tab | Python 3.9+
-=== "Python 3.9+"
+```Python hl_lines="11"
+{!> ../../../docs_src/header_params/tutorial002_an_py39.py!}
+```
- ```Python hl_lines="11"
- {!> ../../../docs_src/header_params/tutorial002_an_py39.py!}
- ```
+////
-=== "Python 3.8+"
+//// tab | Python 3.8+
+
+```Python hl_lines="12"
+{!> ../../../docs_src/header_params/tutorial002_an.py!}
+```
- ```Python hl_lines="12"
- {!> ../../../docs_src/header_params/tutorial002_an.py!}
- ```
+////
-=== "Python 3.10+ без Annotated"
+//// tab | Python 3.10+ без Annotated
- !!! tip "Подсказка"
- Предпочтительнее использовать версию с аннотацией, если это возможно.
+/// tip | "Подсказка"
+
+Предпочтительнее использовать версию с аннотацией, если это возможно.
+
+///
+
+```Python hl_lines="8"
+{!> ../../../docs_src/header_params/tutorial002_py310.py!}
+```
- ```Python hl_lines="8"
- {!> ../../../docs_src/header_params/tutorial002_py310.py!}
- ```
+////
-=== "Python 3.8+ без Annotated"
+//// tab | Python 3.8+ без Annotated
- !!! tip "Подсказка"
- Предпочтительнее использовать версию с аннотацией, если это возможно.
+/// tip | "Подсказка"
- ```Python hl_lines="10"
- {!> ../../../docs_src/header_params/tutorial002.py!}
- ```
+Предпочтительнее использовать версию с аннотацией, если это возможно.
-!!! warning "Внимание"
- Прежде чем установить для `convert_underscores` значение `False`, имейте в виду, что некоторые HTTP-прокси и серверы запрещают использование заголовков с подчеркиванием.
+///
+
+```Python hl_lines="10"
+{!> ../../../docs_src/header_params/tutorial002.py!}
+```
+
+////
+
+/// warning | "Внимание"
+
+Прежде чем установить для `convert_underscores` значение `False`, имейте в виду, что некоторые HTTP-прокси и серверы запрещают использование заголовков с подчеркиванием.
+
+///
## Повторяющиеся заголовки
Например, чтобы объявить заголовок `X-Token`, который может появляться более одного раза, вы можете написать:
-=== "Python 3.10+"
+//// tab | Python 3.10+
- ```Python hl_lines="9"
- {!> ../../../docs_src/header_params/tutorial003_an_py310.py!}
- ```
+```Python hl_lines="9"
+{!> ../../../docs_src/header_params/tutorial003_an_py310.py!}
+```
-=== "Python 3.9+"
+////
- ```Python hl_lines="9"
- {!> ../../../docs_src/header_params/tutorial003_an_py39.py!}
- ```
+//// tab | Python 3.9+
-=== "Python 3.8+"
+```Python hl_lines="9"
+{!> ../../../docs_src/header_params/tutorial003_an_py39.py!}
+```
- ```Python hl_lines="10"
- {!> ../../../docs_src/header_params/tutorial003_an.py!}
- ```
+////
-=== "Python 3.10+ без Annotated"
+//// tab | Python 3.8+
- !!! tip "Подсказка"
- Предпочтительнее использовать версию с аннотацией, если это возможно.
+```Python hl_lines="10"
+{!> ../../../docs_src/header_params/tutorial003_an.py!}
+```
+
+////
+
+//// tab | Python 3.10+ без Annotated
+
+/// tip | "Подсказка"
+
+Предпочтительнее использовать версию с аннотацией, если это возможно.
+
+///
+
+```Python hl_lines="7"
+{!> ../../../docs_src/header_params/tutorial003_py310.py!}
+```
- ```Python hl_lines="7"
- {!> ../../../docs_src/header_params/tutorial003_py310.py!}
- ```
+////
-=== "Python 3.9+ без Annotated"
+//// tab | Python 3.9+ без Annotated
- !!! tip "Подсказка"
- Предпочтительнее использовать версию с аннотацией, если это возможно.
+/// tip | "Подсказка"
- ```Python hl_lines="9"
- {!> ../../../docs_src/header_params/tutorial003_py39.py!}
- ```
+Предпочтительнее использовать версию с аннотацией, если это возможно.
-=== "Python 3.8+ без Annotated"
+///
- !!! tip "Подсказка"
- Предпочтительнее использовать версию с аннотацией, если это возможно.
+```Python hl_lines="9"
+{!> ../../../docs_src/header_params/tutorial003_py39.py!}
+```
+
+////
+
+//// tab | Python 3.8+ без Annotated
+
+/// tip | "Подсказка"
+
+Предпочтительнее использовать версию с аннотацией, если это возможно.
+
+///
+
+```Python hl_lines="9"
+{!> ../../../docs_src/header_params/tutorial003.py!}
+```
- ```Python hl_lines="9"
- {!> ../../../docs_src/header_params/tutorial003.py!}
- ```
+////
Если вы взаимодействуете с этой *операцией пути*, отправляя два HTTP-заголовка, таких как:
...это также включает `uvicorn`, который вы можете использовать в качестве сервера, который запускает ваш код.
-!!! note "Технические детали"
- Вы также можете установить его по частям.
+/// note | "Технические детали"
- Это то, что вы, вероятно, сделаете, когда захотите развернуть свое приложение в рабочей среде:
+Вы также можете установить его по частям.
- ```
- pip install fastapi
- ```
+Это то, что вы, вероятно, сделаете, когда захотите развернуть свое приложение в рабочей среде:
- Также установите `uvicorn` для работы в качестве сервера:
+```
+pip install fastapi
+```
+
+Также установите `uvicorn` для работы в качестве сервера:
+
+```
+pip install "uvicorn[standard]"
+```
- ```
- pip install "uvicorn[standard]"
- ```
+И то же самое для каждой из необязательных зависимостей, которые вы хотите использовать.
- И то же самое для каждой из необязательных зависимостей, которые вы хотите использовать.
+///
## Продвинутое руководство пользователя
{!../../../docs_src/metadata/tutorial001.py!}
```
-!!! tip "Подсказка"
- Вы можете использовать Markdown в поле `description`, и оно будет отображено в выводе.
+/// tip | "Подсказка"
+
+Вы можете использовать Markdown в поле `description`, и оно будет отображено в выводе.
+
+///
С этой конфигурацией автоматическая документация API будут выглядеть так:
Помните, что вы можете использовать Markdown внутри описания, к примеру "login" будет отображен жирным шрифтом (**login**) и "fancy" будет отображаться курсивом (_fancy_).
-!!! tip "Подсказка"
- Вам необязательно добавлять метаданные для всех используемых тегов
+/// tip | "Подсказка"
+
+Вам необязательно добавлять метаданные для всех используемых тегов
+
+///
### Используйте собственные теги
Используйте параметр `tags` с вашими *операциями пути* (и `APIRouter`ами), чтобы присвоить им различные теги:
{!../../../docs_src/metadata/tutorial004.py!}
```
-!!! info "Дополнительная информация"
- Узнайте больше о тегах в [Конфигурации операции пути](path-operation-configuration.md#_3){.internal-link target=_blank}.
+/// info | "Дополнительная информация"
+
+Узнайте больше о тегах в [Конфигурации операции пути](path-operation-configuration.md#_3){.internal-link target=_blank}.
+
+///
### Проверьте документацию
Существует несколько параметров, которые вы можете передать вашему *декоратору операций пути* для его настройки.
-!!! warning "Внимание"
- Помните, что эти параметры передаются непосредственно *декоратору операций пути*, а не вашей *функции-обработчику операций пути*.
+/// warning | "Внимание"
+
+Помните, что эти параметры передаются непосредственно *декоратору операций пути*, а не вашей *функции-обработчику операций пути*.
+
+///
## Коды состояния
Но если вы не помните, для чего нужен каждый числовой код, вы можете использовать сокращенные константы в параметре `status`:
-=== "Python 3.10+"
+//// tab | Python 3.10+
+
+```Python hl_lines="1 15"
+{!> ../../../docs_src/path_operation_configuration/tutorial001_py310.py!}
+```
+
+////
- ```Python hl_lines="1 15"
- {!> ../../../docs_src/path_operation_configuration/tutorial001_py310.py!}
- ```
+//// tab | Python 3.9+
-=== "Python 3.9+"
+```Python hl_lines="3 17"
+{!> ../../../docs_src/path_operation_configuration/tutorial001_py39.py!}
+```
+
+////
- ```Python hl_lines="3 17"
- {!> ../../../docs_src/path_operation_configuration/tutorial001_py39.py!}
- ```
+//// tab | Python 3.8+
-=== "Python 3.8+"
+```Python hl_lines="3 17"
+{!> ../../../docs_src/path_operation_configuration/tutorial001.py!}
+```
- ```Python hl_lines="3 17"
- {!> ../../../docs_src/path_operation_configuration/tutorial001.py!}
- ```
+////
Этот код состояния будет использован в ответе и будет добавлен в схему OpenAPI.
-!!! note "Технические детали"
- Вы также можете использовать `from starlette import status`.
+/// note | "Технические детали"
+
+Вы также можете использовать `from starlette import status`.
+
+**FastAPI** предоставляет тот же `starlette.status` под псевдонимом `fastapi.status` для удобства разработчика. Но его источник - это непосредственно Starlette.
- **FastAPI** предоставляет тот же `starlette.status` под псевдонимом `fastapi.status` для удобства разработчика. Но его источник - это непосредственно Starlette.
+///
## Теги
Вы можете добавлять теги к вашим *операциям пути*, добавив параметр `tags` с `list` заполненным `str`-значениями (обычно в нём только одна строка):
-=== "Python 3.10+"
+//// tab | Python 3.10+
- ```Python hl_lines="15 20 25"
- {!> ../../../docs_src/path_operation_configuration/tutorial002_py310.py!}
- ```
+```Python hl_lines="15 20 25"
+{!> ../../../docs_src/path_operation_configuration/tutorial002_py310.py!}
+```
+
+////
-=== "Python 3.9+"
+//// tab | Python 3.9+
- ```Python hl_lines="17 22 27"
- {!> ../../../docs_src/path_operation_configuration/tutorial002_py39.py!}
- ```
+```Python hl_lines="17 22 27"
+{!> ../../../docs_src/path_operation_configuration/tutorial002_py39.py!}
+```
-=== "Python 3.8+"
+////
- ```Python hl_lines="17 22 27"
- {!> ../../../docs_src/path_operation_configuration/tutorial002.py!}
- ```
+//// tab | Python 3.8+
+
+```Python hl_lines="17 22 27"
+{!> ../../../docs_src/path_operation_configuration/tutorial002.py!}
+```
+
+////
Они будут добавлены в схему OpenAPI и будут использованы в автоматической документации интерфейса:
Вы можете добавить параметры `summary` и `description`:
-=== "Python 3.10+"
+//// tab | Python 3.10+
+
+```Python hl_lines="18-19"
+{!> ../../../docs_src/path_operation_configuration/tutorial003_py310.py!}
+```
+
+////
- ```Python hl_lines="18-19"
- {!> ../../../docs_src/path_operation_configuration/tutorial003_py310.py!}
- ```
+//// tab | Python 3.9+
-=== "Python 3.9+"
+```Python hl_lines="20-21"
+{!> ../../../docs_src/path_operation_configuration/tutorial003_py39.py!}
+```
+
+////
- ```Python hl_lines="20-21"
- {!> ../../../docs_src/path_operation_configuration/tutorial003_py39.py!}
- ```
+//// tab | Python 3.8+
-=== "Python 3.8+"
+```Python hl_lines="20-21"
+{!> ../../../docs_src/path_operation_configuration/tutorial003.py!}
+```
- ```Python hl_lines="20-21"
- {!> ../../../docs_src/path_operation_configuration/tutorial003.py!}
- ```
+////
## Описание из строк документации
Вы можете использовать <a href="https://en.wikipedia.org/wiki/Markdown" class="external-link" target="_blank">Markdown</a> в строке документации, и он будет интерпретирован и отображён корректно (с учетом отступа в строке документации).
-=== "Python 3.10+"
+//// tab | Python 3.10+
+
+```Python hl_lines="17-25"
+{!> ../../../docs_src/path_operation_configuration/tutorial004_py310.py!}
+```
+
+////
- ```Python hl_lines="17-25"
- {!> ../../../docs_src/path_operation_configuration/tutorial004_py310.py!}
- ```
+//// tab | Python 3.9+
-=== "Python 3.9+"
+```Python hl_lines="19-27"
+{!> ../../../docs_src/path_operation_configuration/tutorial004_py39.py!}
+```
- ```Python hl_lines="19-27"
- {!> ../../../docs_src/path_operation_configuration/tutorial004_py39.py!}
- ```
+////
-=== "Python 3.8+"
+//// tab | Python 3.8+
- ```Python hl_lines="19-27"
- {!> ../../../docs_src/path_operation_configuration/tutorial004.py!}
- ```
+```Python hl_lines="19-27"
+{!> ../../../docs_src/path_operation_configuration/tutorial004.py!}
+```
+
+////
Он будет использован в интерактивной документации:
Вы можете указать описание ответа с помощью параметра `response_description`:
-=== "Python 3.10+"
+//// tab | Python 3.10+
+
+```Python hl_lines="19"
+{!> ../../../docs_src/path_operation_configuration/tutorial005_py310.py!}
+```
+
+////
+
+//// tab | Python 3.9+
+
+```Python hl_lines="21"
+{!> ../../../docs_src/path_operation_configuration/tutorial005_py39.py!}
+```
+
+////
+
+//// tab | Python 3.8+
+
+```Python hl_lines="21"
+{!> ../../../docs_src/path_operation_configuration/tutorial005.py!}
+```
- ```Python hl_lines="19"
- {!> ../../../docs_src/path_operation_configuration/tutorial005_py310.py!}
- ```
+////
-=== "Python 3.9+"
+/// info | "Дополнительная информация"
- ```Python hl_lines="21"
- {!> ../../../docs_src/path_operation_configuration/tutorial005_py39.py!}
- ```
+Помните, что `response_description` относится конкретно к ответу, а `description` относится к *операции пути* в целом.
-=== "Python 3.8+"
+///
- ```Python hl_lines="21"
- {!> ../../../docs_src/path_operation_configuration/tutorial005.py!}
- ```
+/// check | "Технические детали"
-!!! info "Дополнительная информация"
- Помните, что `response_description` относится конкретно к ответу, а `description` относится к *операции пути* в целом.
+OpenAPI указывает, что каждой *операции пути* необходимо описание ответа.
-!!! check "Технические детали"
- OpenAPI указывает, что каждой *операции пути* необходимо описание ответа.
+Если вдруг вы не укажете его, то **FastAPI** автоматически сгенерирует это описание с текстом "Successful response".
- Если вдруг вы не укажете его, то **FastAPI** автоматически сгенерирует это описание с текстом "Successful response".
+///
<img src="/img/tutorial/path-operation-configuration/image03.png">
Сначала импортируйте `Path` из `fastapi`, а также импортируйте `Annotated`:
-=== "Python 3.10+"
+//// tab | Python 3.10+
- ```Python hl_lines="1 3"
- {!> ../../../docs_src/path_params_numeric_validations/tutorial001_an_py310.py!}
- ```
+```Python hl_lines="1 3"
+{!> ../../../docs_src/path_params_numeric_validations/tutorial001_an_py310.py!}
+```
+
+////
+
+//// tab | Python 3.9+
+
+```Python hl_lines="1 3"
+{!> ../../../docs_src/path_params_numeric_validations/tutorial001_an_py39.py!}
+```
+
+////
+
+//// tab | Python 3.8+
+
+```Python hl_lines="3-4"
+{!> ../../../docs_src/path_params_numeric_validations/tutorial001_an.py!}
+```
+
+////
-=== "Python 3.9+"
+//// tab | Python 3.10+ без Annotated
- ```Python hl_lines="1 3"
- {!> ../../../docs_src/path_params_numeric_validations/tutorial001_an_py39.py!}
- ```
+/// tip | "Подсказка"
-=== "Python 3.8+"
+Рекомендуется использовать версию с `Annotated` если возможно.
- ```Python hl_lines="3-4"
- {!> ../../../docs_src/path_params_numeric_validations/tutorial001_an.py!}
- ```
+///
-=== "Python 3.10+ без Annotated"
+```Python hl_lines="1"
+{!> ../../../docs_src/path_params_numeric_validations/tutorial001_py310.py!}
+```
+
+////
+
+//// tab | Python 3.8+ без Annotated
+
+/// tip | "Подсказка"
+
+Рекомендуется использовать версию с `Annotated` если возможно.
- !!! tip "Подсказка"
- Рекомендуется использовать версию с `Annotated` если возможно.
+///
- ```Python hl_lines="1"
- {!> ../../../docs_src/path_params_numeric_validations/tutorial001_py310.py!}
- ```
+```Python hl_lines="3"
+{!> ../../../docs_src/path_params_numeric_validations/tutorial001.py!}
+```
-=== "Python 3.8+ без Annotated"
+////
- !!! tip "Подсказка"
- Рекомендуется использовать версию с `Annotated` если возможно.
+/// info | "Информация"
- ```Python hl_lines="3"
- {!> ../../../docs_src/path_params_numeric_validations/tutorial001.py!}
- ```
+Поддержка `Annotated` была добавлена в FastAPI начиная с версии 0.95.0 (и с этой версии рекомендуется использовать этот подход).
-!!! info "Информация"
- Поддержка `Annotated` была добавлена в FastAPI начиная с версии 0.95.0 (и с этой версии рекомендуется использовать этот подход).
+Если вы используете более старую версию, вы столкнётесь с ошибками при попытке использовать `Annotated`.
- Если вы используете более старую версию, вы столкнётесь с ошибками при попытке использовать `Annotated`.
+Убедитесь, что вы [обновили версию FastAPI](../deployment/versions.md#fastapi_2){.internal-link target=_blank} как минимум до 0.95.1 перед тем, как использовать `Annotated`.
- Убедитесь, что вы [обновили версию FastAPI](../deployment/versions.md#fastapi_2){.internal-link target=_blank} как минимум до 0.95.1 перед тем, как использовать `Annotated`.
+///
## Определите метаданные
Например, чтобы указать значение метаданных `title` для path-параметра `item_id`, вы можете написать:
-=== "Python 3.10+"
+//// tab | Python 3.10+
- ```Python hl_lines="10"
- {!> ../../../docs_src/path_params_numeric_validations/tutorial001_an_py310.py!}
- ```
+```Python hl_lines="10"
+{!> ../../../docs_src/path_params_numeric_validations/tutorial001_an_py310.py!}
+```
-=== "Python 3.9+"
+////
- ```Python hl_lines="10"
- {!> ../../../docs_src/path_params_numeric_validations/tutorial001_an_py39.py!}
- ```
+//// tab | Python 3.9+
-=== "Python 3.8+"
+```Python hl_lines="10"
+{!> ../../../docs_src/path_params_numeric_validations/tutorial001_an_py39.py!}
+```
- ```Python hl_lines="11"
- {!> ../../../docs_src/path_params_numeric_validations/tutorial001_an.py!}
- ```
+////
-=== "Python 3.10+ без Annotated"
+//// tab | Python 3.8+
- !!! tip "Подсказка"
- Рекомендуется использовать версию с `Annotated` если возможно.
+```Python hl_lines="11"
+{!> ../../../docs_src/path_params_numeric_validations/tutorial001_an.py!}
+```
- ```Python hl_lines="8"
- {!> ../../../docs_src/path_params_numeric_validations/tutorial001_py310.py!}
- ```
+////
-=== "Python 3.8+ без Annotated"
+//// tab | Python 3.10+ без Annotated
- !!! tip "Подсказка"
- Рекомендуется использовать версию с `Annotated` если возможно.
+/// tip | "Подсказка"
- ```Python hl_lines="10"
- {!> ../../../docs_src/path_params_numeric_validations/tutorial001.py!}
- ```
+Рекомендуется использовать версию с `Annotated` если возможно.
-!!! note "Примечание"
- Path-параметр всегда является обязательным, поскольку он составляет часть пути.
+///
- Поэтому следует объявить его с помощью `...`, чтобы обозначить, что этот параметр обязательный.
+```Python hl_lines="8"
+{!> ../../../docs_src/path_params_numeric_validations/tutorial001_py310.py!}
+```
- Тем не менее, даже если вы объявите его как `None` или установите для него значение по умолчанию, это ни на что не повлияет и параметр останется обязательным.
+////
+
+//// tab | Python 3.8+ без Annotated
+
+/// tip | "Подсказка"
+
+Рекомендуется использовать версию с `Annotated` если возможно.
+
+///
+
+```Python hl_lines="10"
+{!> ../../../docs_src/path_params_numeric_validations/tutorial001.py!}
+```
+
+////
+
+/// note | "Примечание"
+
+Path-параметр всегда является обязательным, поскольку он составляет часть пути.
+
+Поэтому следует объявить его с помощью `...`, чтобы обозначить, что этот параметр обязательный.
+
+Тем не менее, даже если вы объявите его как `None` или установите для него значение по умолчанию, это ни на что не повлияет и параметр останется обязательным.
+
+///
## Задайте нужный вам порядок параметров
-!!! tip "Подсказка"
- Это не имеет большого значения, если вы используете `Annotated`.
+/// tip | "Подсказка"
+
+Это не имеет большого значения, если вы используете `Annotated`.
+
+///
Допустим, вы хотите объявить query-параметр `q` как обязательный параметр типа `str`.
Поэтому вы можете определить функцию так:
-=== "Python 3.8 без Annotated"
+//// tab | Python 3.8 без Annotated
+
+/// tip | "Подсказка"
- !!! tip "Подсказка"
- Рекомендуется использовать версию с `Annotated` если возможно.
+Рекомендуется использовать версию с `Annotated` если возможно.
+
+///
+
+```Python hl_lines="7"
+{!> ../../../docs_src/path_params_numeric_validations/tutorial002.py!}
+```
- ```Python hl_lines="7"
- {!> ../../../docs_src/path_params_numeric_validations/tutorial002.py!}
- ```
+////
Но имейте в виду, что если вы используете `Annotated`, вы не столкнётесь с этой проблемой, так как вы не используете `Query()` или `Path()` в качестве значения по умолчанию для параметра функции.
-=== "Python 3.9+"
+//// tab | Python 3.9+
- ```Python hl_lines="10"
- {!> ../../../docs_src/path_params_numeric_validations/tutorial002_an_py39.py!}
- ```
+```Python hl_lines="10"
+{!> ../../../docs_src/path_params_numeric_validations/tutorial002_an_py39.py!}
+```
+
+////
-=== "Python 3.8+"
+//// tab | Python 3.8+
- ```Python hl_lines="9"
- {!> ../../../docs_src/path_params_numeric_validations/tutorial002_an.py!}
- ```
+```Python hl_lines="9"
+{!> ../../../docs_src/path_params_numeric_validations/tutorial002_an.py!}
+```
+
+////
## Задайте нужный вам порядок параметров, полезные приёмы
-!!! tip "Подсказка"
- Это не имеет большого значения, если вы используете `Annotated`.
+/// tip | "Подсказка"
+
+Это не имеет большого значения, если вы используете `Annotated`.
+
+///
Здесь описан **небольшой приём**, который может оказаться удобным, хотя часто он вам не понадобится.
Имейте в виду, что если вы используете `Annotated`, то, поскольку вы не используете значений по умолчанию для параметров функции, то у вас не возникнет подобной проблемы и вам не придётся использовать `*`.
-=== "Python 3.9+"
+//// tab | Python 3.9+
+
+```Python hl_lines="10"
+{!> ../../../docs_src/path_params_numeric_validations/tutorial003_an_py39.py!}
+```
- ```Python hl_lines="10"
- {!> ../../../docs_src/path_params_numeric_validations/tutorial003_an_py39.py!}
- ```
+////
-=== "Python 3.8+"
+//// tab | Python 3.8+
+
+```Python hl_lines="9"
+{!> ../../../docs_src/path_params_numeric_validations/tutorial003_an.py!}
+```
- ```Python hl_lines="9"
- {!> ../../../docs_src/path_params_numeric_validations/tutorial003_an.py!}
- ```
+////
## Валидация числовых данных: больше или равно
В этом примере при указании `ge=1`, параметр `item_id` должен быть больше или равен `1` ("`g`reater than or `e`qual").
-=== "Python 3.9+"
+//// tab | Python 3.9+
- ```Python hl_lines="10"
- {!> ../../../docs_src/path_params_numeric_validations/tutorial004_an_py39.py!}
- ```
+```Python hl_lines="10"
+{!> ../../../docs_src/path_params_numeric_validations/tutorial004_an_py39.py!}
+```
+
+////
+
+//// tab | Python 3.8+
+
+```Python hl_lines="9"
+{!> ../../../docs_src/path_params_numeric_validations/tutorial004_an.py!}
+```
-=== "Python 3.8+"
+////
- ```Python hl_lines="9"
- {!> ../../../docs_src/path_params_numeric_validations/tutorial004_an.py!}
- ```
+//// tab | Python 3.8+ без Annotated
-=== "Python 3.8+ без Annotated"
+/// tip | "Подсказка"
- !!! tip "Подсказка"
- Рекомендуется использовать версию с `Annotated` если возможно.
+Рекомендуется использовать версию с `Annotated` если возможно.
- ```Python hl_lines="8"
- {!> ../../../docs_src/path_params_numeric_validations/tutorial004.py!}
- ```
+///
+
+```Python hl_lines="8"
+{!> ../../../docs_src/path_params_numeric_validations/tutorial004.py!}
+```
+
+////
## Валидация числовых данных: больше и меньше или равно
* `gt`: больше (`g`reater `t`han)
* `le`: меньше или равно (`l`ess than or `e`qual)
-=== "Python 3.9+"
+//// tab | Python 3.9+
+
+```Python hl_lines="10"
+{!> ../../../docs_src/path_params_numeric_validations/tutorial005_an_py39.py!}
+```
+
+////
+
+//// tab | Python 3.8+
+
+```Python hl_lines="9"
+{!> ../../../docs_src/path_params_numeric_validations/tutorial005_an.py!}
+```
- ```Python hl_lines="10"
- {!> ../../../docs_src/path_params_numeric_validations/tutorial005_an_py39.py!}
- ```
+////
-=== "Python 3.8+"
+//// tab | Python 3.8+ без Annotated
- ```Python hl_lines="9"
- {!> ../../../docs_src/path_params_numeric_validations/tutorial005_an.py!}
- ```
+/// tip | "Подсказка"
-=== "Python 3.8+ без Annotated"
+Рекомендуется использовать версию с `Annotated` если возможно.
- !!! tip "Подсказка"
- Рекомендуется использовать версию с `Annotated` если возможно.
+///
- ```Python hl_lines="9"
- {!> ../../../docs_src/path_params_numeric_validations/tutorial005.py!}
- ```
+```Python hl_lines="9"
+{!> ../../../docs_src/path_params_numeric_validations/tutorial005.py!}
+```
+
+////
## Валидация числовых данных: числа с плавающей точкой, больше и меньше
То же самое справедливо и для <abbr title="less than"><code>lt</code></abbr>.
-=== "Python 3.9+"
+//// tab | Python 3.9+
- ```Python hl_lines="13"
- {!> ../../../docs_src/path_params_numeric_validations/tutorial006_an_py39.py!}
- ```
+```Python hl_lines="13"
+{!> ../../../docs_src/path_params_numeric_validations/tutorial006_an_py39.py!}
+```
-=== "Python 3.8+"
+////
- ```Python hl_lines="12"
- {!> ../../../docs_src/path_params_numeric_validations/tutorial006_an.py!}
- ```
+//// tab | Python 3.8+
+
+```Python hl_lines="12"
+{!> ../../../docs_src/path_params_numeric_validations/tutorial006_an.py!}
+```
-=== "Python 3.8+ без Annotated"
+////
- !!! tip "Подсказка"
- Рекомендуется использовать версию с `Annotated` если возможно.
+//// tab | Python 3.8+ без Annotated
- ```Python hl_lines="11"
- {!> ../../../docs_src/path_params_numeric_validations/tutorial006.py!}
- ```
+/// tip | "Подсказка"
+
+Рекомендуется использовать версию с `Annotated` если возможно.
+
+///
+
+```Python hl_lines="11"
+{!> ../../../docs_src/path_params_numeric_validations/tutorial006.py!}
+```
+
+////
## Резюме
* `lt`: меньше (`l`ess `t`han)
* `le`: меньше или равно (`l`ess than or `e`qual)
-!!! info "Информация"
- `Query`, `Path` и другие классы, которые мы разберём позже, являются наследниками общего класса `Param`.
+/// info | "Информация"
+
+`Query`, `Path` и другие классы, которые мы разберём позже, являются наследниками общего класса `Param`.
+
+Все они используют те же параметры для дополнительной валидации и метаданных, которые вы видели ранее.
+
+///
+
+/// note | "Технические детали"
- Все они используют те же параметры для дополнительной валидации и метаданных, которые вы видели ранее.
+`Query`, `Path` и другие "классы", которые вы импортируете из `fastapi`, на самом деле являются функциями, которые при вызове возвращают экземпляры одноимённых классов.
-!!! note "Технические детали"
- `Query`, `Path` и другие "классы", которые вы импортируете из `fastapi`, на самом деле являются функциями, которые при вызове возвращают экземпляры одноимённых классов.
+Объект `Query`, который вы импортируете, является функцией. И при вызове она возвращает экземпляр одноимённого класса `Query`.
- Объект `Query`, который вы импортируете, является функцией. И при вызове она возвращает экземпляр одноимённого класса `Query`.
+Использование функций (вместо использования классов напрямую) нужно для того, чтобы ваш редактор не подсвечивал ошибки, связанные с их типами.
- Использование функций (вместо использования классов напрямую) нужно для того, чтобы ваш редактор не подсвечивал ошибки, связанные с их типами.
+Таким образом вы можете использовать привычный вам редактор и инструменты разработки, не добавляя дополнительных конфигураций для игнорирования подобных ошибок.
- Таким образом вы можете использовать привычный вам редактор и инструменты разработки, не добавляя дополнительных конфигураций для игнорирования подобных ошибок.
+///
Здесь, `item_id` объявлен типом `int`.
-!!! check "Заметка"
- Это обеспечит поддержку редактора внутри функции (проверка ошибок, автодополнение и т.п.).
+/// check | "Заметка"
+
+Это обеспечит поддержку редактора внутри функции (проверка ошибок, автодополнение и т.п.).
+
+///
## <abbr title="Или сериализация, парсинг">Преобразование</abbr> данных
{"item_id":3}
```
-!!! check "Заметка"
- Обратите внимание на значение `3`, которое получила (и вернула) функция. Это целочисленный Python `int`, а не строка `"3"`.
+/// check | "Заметка"
+
+Обратите внимание на значение `3`, которое получила (и вернула) функция. Это целочисленный Python `int`, а не строка `"3"`.
+
+Используя определения типов, **FastAPI** выполняет автоматический <abbr title="преобразование строк из HTTP-запроса в типы данных Python">"парсинг"</abbr> запросов.
- Используя определения типов, **FastAPI** выполняет автоматический <abbr title="преобразование строк из HTTP-запроса в типы данных Python">"парсинг"</abbr> запросов.
+///
## <abbr title="Или валидация">Проверка</abbr> данных
Та же ошибка возникнет, если вместо `int` передать `float` , например: <a href="http://127.0.0.1:8000/items/4.2" class="external-link" target="_blank">http://127.0.0.1:8000/items/4.2</a>
-!!! check "Заметка"
- **FastAPI** обеспечивает проверку типов, используя всё те же определения типов.
+/// check | "Заметка"
- Обратите внимание, что в тексте ошибки явно указано место не прошедшее проверку.
+**FastAPI** обеспечивает проверку типов, используя всё те же определения типов.
- Это очень полезно при разработке и отладке кода, который взаимодействует с API.
+Обратите внимание, что в тексте ошибки явно указано место не прошедшее проверку.
+
+Это очень полезно при разработке и отладке кода, который взаимодействует с API.
+
+///
## Документация
<img src="/img/tutorial/path-params/image01.png">
-!!! check "Заметка"
- Ещё раз, просто используя определения типов, **FastAPI** обеспечивает автоматическую интерактивную документацию (с интеграцией Swagger UI).
+/// check | "Заметка"
+
+Ещё раз, просто используя определения типов, **FastAPI** обеспечивает автоматическую интерактивную документацию (с интеграцией Swagger UI).
+
+Обратите внимание, что параметр пути объявлен целочисленным.
- Обратите внимание, что параметр пути объявлен целочисленным.
+///
## Преимущества стандартизации, альтернативная документация
{!../../../docs_src/path_params/tutorial005.py!}
```
-!!! info "Дополнительная информация"
- <a href="https://docs.python.org/3/library/enum.html" class="external-link" target="_blank">Перечисления (enum) доступны в Python</a> начиная с версии 3.4.
+/// info | "Дополнительная информация"
-!!! tip "Подсказка"
- Если интересно, то "AlexNet", "ResNet" и "LeNet" - это названия <abbr title="Технически, это архитектуры моделей глубокого обучения">моделей</abbr> машинного обучения.
+<a href="https://docs.python.org/3/library/enum.html" class="external-link" target="_blank">Перечисления (enum) доступны в Python</a> начиная с версии 3.4.
+
+///
+
+/// tip | "Подсказка"
+
+Если интересно, то "AlexNet", "ResNet" и "LeNet" - это названия <abbr title="Технически, это архитектуры моделей глубокого обучения">моделей</abbr> машинного обучения.
+
+///
### Определение *параметра пути*
{!../../../docs_src/path_params/tutorial005.py!}
```
-!!! tip "Подсказка"
- Значение `"lenet"` также можно получить с помощью `ModelName.lenet.value`.
+/// tip | "Подсказка"
+
+Значение `"lenet"` также можно получить с помощью `ModelName.lenet.value`.
+
+///
#### Возврат *элементов перечисления*
{!../../../docs_src/path_params/tutorial004.py!}
```
-!!! tip "Подсказка"
- Возможно, вам понадобится, чтобы параметр содержал `/home/johndoe/myfile.txt` с ведущим слэшем (`/`).
+/// tip | "Подсказка"
+
+Возможно, вам понадобится, чтобы параметр содержал `/home/johndoe/myfile.txt` с ведущим слэшем (`/`).
+
+В этом случае URL будет таким: `/files//home/johndoe/myfile.txt`, с двойным слэшем (`//`) между `files` и `home`.
- В этом случае URL будет таким: `/files//home/johndoe/myfile.txt`, с двойным слэшем (`//`) между `files` и `home`.
+///
## Резюме
Используя **FastAPI** вместе со стандартными объявлениями типов Python (короткими и интуитивно понятными), вы получаете:
Давайте рассмотрим следующий пример:
-=== "Python 3.10+"
+//// tab | Python 3.10+
- ```Python hl_lines="7"
- {!> ../../../docs_src/query_params_str_validations/tutorial001_py310.py!}
- ```
+```Python hl_lines="7"
+{!> ../../../docs_src/query_params_str_validations/tutorial001_py310.py!}
+```
+
+////
-=== "Python 3.8+"
+//// tab | Python 3.8+
+
+```Python hl_lines="9"
+{!> ../../../docs_src/query_params_str_validations/tutorial001.py!}
+```
- ```Python hl_lines="9"
- {!> ../../../docs_src/query_params_str_validations/tutorial001.py!}
- ```
+////
Query-параметр `q` имеет тип `Union[str, None]` (или `str | None` в Python 3.10). Это означает, что входной параметр будет типа `str`, но может быть и `None`. Ещё параметр имеет значение по умолчанию `None`, из-за чего FastAPI определит параметр как необязательный.
-!!! note "Технические детали"
- FastAPI определит параметр `q` как необязательный, потому что его значение по умолчанию `= None`.
+/// note | "Технические детали"
- `Union` в `Union[str, None]` позволит редактору кода оказать вам лучшую поддержку и найти ошибки.
+FastAPI определит параметр `q` как необязательный, потому что его значение по умолчанию `= None`.
+
+`Union` в `Union[str, None]` позволит редактору кода оказать вам лучшую поддержку и найти ошибки.
+
+///
## Расширенная валидация
* `Query` из пакета `fastapi`:
* `Annotated` из пакета `typing` (или из `typing_extensions` для Python ниже 3.9)
-=== "Python 3.10+"
+//// tab | Python 3.10+
+
+В Python 3.9 или выше, `Annotated` является частью стандартной библиотеки, таким образом вы можете импортировать его из `typing`.
+
+```Python hl_lines="1 3"
+{!> ../../../docs_src/query_params_str_validations/tutorial002_an_py310.py!}
+```
- В Python 3.9 или выше, `Annotated` является частью стандартной библиотеки, таким образом вы можете импортировать его из `typing`.
+////
- ```Python hl_lines="1 3"
- {!> ../../../docs_src/query_params_str_validations/tutorial002_an_py310.py!}
- ```
+//// tab | Python 3.8+
-=== "Python 3.8+"
+В версиях Python ниже Python 3.9 `Annotation` импортируется из `typing_extensions`.
- В версиях Python ниже Python 3.9 `Annotation` импортируется из `typing_extensions`.
+Эта библиотека будет установлена вместе с FastAPI.
- Эта библиотека будет установлена вместе с FastAPI.
+```Python hl_lines="3-4"
+{!> ../../../docs_src/query_params_str_validations/tutorial002_an.py!}
+```
- ```Python hl_lines="3-4"
- {!> ../../../docs_src/query_params_str_validations/tutorial002_an.py!}
- ```
+////
## `Annotated` как тип для query-параметра `q`
У нас была аннотация следующего типа:
-=== "Python 3.10+"
+//// tab | Python 3.10+
- ```Python
- q: str | None = None
- ```
+```Python
+q: str | None = None
+```
-=== "Python 3.8+"
+////
- ```Python
- q: Union[str, None] = None
- ```
+//// tab | Python 3.8+
+
+```Python
+q: Union[str, None] = None
+```
+
+////
Вот что мы получим, если обернём это в `Annotated`:
-=== "Python 3.10+"
+//// tab | Python 3.10+
+
+```Python
+q: Annotated[str | None] = None
+```
+
+////
- ```Python
- q: Annotated[str | None] = None
- ```
+//// tab | Python 3.8+
-=== "Python 3.8+"
+```Python
+q: Annotated[Union[str, None]] = None
+```
- ```Python
- q: Annotated[Union[str, None]] = None
- ```
+////
Обе эти версии означают одно и тоже. `q` - это параметр, который может быть `str` или `None`, и по умолчанию он будет принимать `None`.
Теперь, когда у нас есть `Annotated`, где мы можем добавить больше метаданных, добавим `Query` со значением параметра `max_length` равным 50:
-=== "Python 3.10+"
+//// tab | Python 3.10+
- ```Python hl_lines="9"
- {!> ../../../docs_src/query_params_str_validations/tutorial002_an_py310.py!}
- ```
+```Python hl_lines="9"
+{!> ../../../docs_src/query_params_str_validations/tutorial002_an_py310.py!}
+```
+
+////
-=== "Python 3.8+"
+//// tab | Python 3.8+
+
+```Python hl_lines="10"
+{!> ../../../docs_src/query_params_str_validations/tutorial002_an.py!}
+```
- ```Python hl_lines="10"
- {!> ../../../docs_src/query_params_str_validations/tutorial002_an.py!}
- ```
+////
Обратите внимание, что значение по умолчанию всё ещё `None`, так что параметр остаётся необязательным.
В предыдущих версиях FastAPI (ниже <abbr title="ранее 2023-03">0.95.0</abbr>) необходимо было использовать `Query` как значение по умолчанию для query-параметра. Так было вместо размещения его в `Annotated`, так что велика вероятность, что вам встретится такой код. Сейчас объясню.
-!!! tip "Подсказка"
- При написании нового кода и везде где это возможно, используйте `Annotated`, как было описано ранее. У этого способа есть несколько преимуществ (о них дальше) и никаких недостатков. 🍰
+/// tip | "Подсказка"
+
+При написании нового кода и везде где это возможно, используйте `Annotated`, как было описано ранее. У этого способа есть несколько преимуществ (о них дальше) и никаких недостатков. 🍰
+
+///
Вот как вы могли бы использовать `Query()` в качестве значения по умолчанию параметра вашей функции, установив для параметра `max_length` значение 50:
-=== "Python 3.10+"
+//// tab | Python 3.10+
- ```Python hl_lines="7"
- {!> ../../../docs_src/query_params_str_validations/tutorial002_py310.py!}
- ```
+```Python hl_lines="7"
+{!> ../../../docs_src/query_params_str_validations/tutorial002_py310.py!}
+```
-=== "Python 3.8+"
+////
- ```Python hl_lines="9"
- {!> ../../../docs_src/query_params_str_validations/tutorial002.py!}
- ```
+//// tab | Python 3.8+
+
+```Python hl_lines="9"
+{!> ../../../docs_src/query_params_str_validations/tutorial002.py!}
+```
+
+////
В таком случае (без использования `Annotated`), мы заменили значение по умолчанию с `None` на `Query()` в функции. Теперь нам нужно установить значение по умолчанию для query-параметра `Query(default=None)`, что необходимо для тех же целей, как когда ранее просто указывалось значение по умолчанию (по крайней мере, для FastAPI).
Но он явно объявляет его как query-параметр.
-!!! info "Дополнительная информация"
- Запомните, важной частью объявления параметра как необязательного является:
+/// info | "Дополнительная информация"
+
+Запомните, важной частью объявления параметра как необязательного является:
- ```Python
- = None
- ```
+```Python
+= None
+```
- или:
+или:
- ```Python
- = Query(default=None)
- ```
+```Python
+= Query(default=None)
+```
- так как `None` указан в качестве значения по умолчанию, параметр будет **необязательным**.
+так как `None` указан в качестве значения по умолчанию, параметр будет **необязательным**.
- `Union[str, None]` позволит редактору кода оказать вам лучшую поддержку. Но это не то, на что обращает внимание FastAPI для определения необязательности параметра.
+`Union[str, None]` позволит редактору кода оказать вам лучшую поддержку. Но это не то, на что обращает внимание FastAPI для определения необязательности параметра.
+
+///
Теперь, мы можем указать больше параметров для `Query`. В данном случае, параметр `max_length` применяется к строкам:
Вы также можете добавить параметр `min_length`:
-=== "Python 3.10+"
+//// tab | Python 3.10+
+
+```Python hl_lines="10"
+{!> ../../../docs_src/query_params_str_validations/tutorial003_an_py310.py!}
+```
+
+////
+
+//// tab | Python 3.9+
+
+```Python hl_lines="10"
+{!> ../../../docs_src/query_params_str_validations/tutorial003_an_py39.py!}
+```
+
+////
+
+//// tab | Python 3.8+
+
+```Python hl_lines="11"
+{!> ../../../docs_src/query_params_str_validations/tutorial003_an.py!}
+```
+
+////
+
+//// tab | Python 3.10+ без Annotated
- ```Python hl_lines="10"
- {!> ../../../docs_src/query_params_str_validations/tutorial003_an_py310.py!}
- ```
+/// tip | "Подсказка"
-=== "Python 3.9+"
+Рекомендуется использовать версию с `Annotated` если возможно.
- ```Python hl_lines="10"
- {!> ../../../docs_src/query_params_str_validations/tutorial003_an_py39.py!}
- ```
+///
-=== "Python 3.8+"
+```Python hl_lines="7"
+{!> ../../../docs_src/query_params_str_validations/tutorial003_py310.py!}
+```
- ```Python hl_lines="11"
- {!> ../../../docs_src/query_params_str_validations/tutorial003_an.py!}
- ```
+////
-=== "Python 3.10+ без Annotated"
+//// tab | Python 3.8+ без Annotated
- !!! tip "Подсказка"
- Рекомендуется использовать версию с `Annotated` если возможно.
+/// tip | "Подсказка"
- ```Python hl_lines="7"
- {!> ../../../docs_src/query_params_str_validations/tutorial003_py310.py!}
- ```
+Рекомендуется использовать версию с `Annotated` если возможно.
-=== "Python 3.8+ без Annotated"
+///
- !!! tip "Подсказка"
- Рекомендуется использовать версию с `Annotated` если возможно.
+```Python hl_lines="10"
+{!> ../../../docs_src/query_params_str_validations/tutorial003.py!}
+```
- ```Python hl_lines="10"
- {!> ../../../docs_src/query_params_str_validations/tutorial003.py!}
- ```
+////
## Регулярные выражения
Вы можете определить <abbr title="Регулярное выражение, regex или regexp - это последовательность символов, определяющая шаблон для строк.">регулярное выражение</abbr>, которому должен соответствовать параметр:
-=== "Python 3.10+"
+//// tab | Python 3.10+
+
+```Python hl_lines="11"
+{!> ../../../docs_src/query_params_str_validations/tutorial004_an_py310.py!}
+```
+
+////
+
+//// tab | Python 3.9+
+
+```Python hl_lines="11"
+{!> ../../../docs_src/query_params_str_validations/tutorial004_an_py39.py!}
+```
+
+////
- ```Python hl_lines="11"
- {!> ../../../docs_src/query_params_str_validations/tutorial004_an_py310.py!}
- ```
+//// tab | Python 3.8+
-=== "Python 3.9+"
+```Python hl_lines="12"
+{!> ../../../docs_src/query_params_str_validations/tutorial004_an.py!}
+```
+
+////
+
+//// tab | Python 3.10+ без Annotated
+
+/// tip | "Подсказка"
- ```Python hl_lines="11"
- {!> ../../../docs_src/query_params_str_validations/tutorial004_an_py39.py!}
- ```
+Рекомендуется использовать версию с `Annotated` если возможно.
-=== "Python 3.8+"
+///
- ```Python hl_lines="12"
- {!> ../../../docs_src/query_params_str_validations/tutorial004_an.py!}
- ```
+```Python hl_lines="9"
+{!> ../../../docs_src/query_params_str_validations/tutorial004_py310.py!}
+```
+
+////
-=== "Python 3.10+ без Annotated"
+//// tab | Python 3.8+ без Annotated
- !!! tip "Подсказка"
- Рекомендуется использовать версию с `Annotated` если возможно.
+/// tip | "Подсказка"
- ```Python hl_lines="9"
- {!> ../../../docs_src/query_params_str_validations/tutorial004_py310.py!}
- ```
+Рекомендуется использовать версию с `Annotated` если возможно.
-=== "Python 3.8+ без Annotated"
+///
- !!! tip "Подсказка"
- Рекомендуется использовать версию с `Annotated` если возможно.
+```Python hl_lines="11"
+{!> ../../../docs_src/query_params_str_validations/tutorial004.py!}
+```
- ```Python hl_lines="11"
- {!> ../../../docs_src/query_params_str_validations/tutorial004.py!}
- ```
+////
Данное регулярное выражение проверяет, что полученное значение параметра:
Например, вы хотите для параметра запроса `q` указать, что он должен состоять минимум из 3 символов (`min_length=3`) и иметь значение по умолчанию `"fixedquery"`:
-=== "Python 3.9+"
+//// tab | Python 3.9+
+
+```Python hl_lines="9"
+{!> ../../../docs_src/query_params_str_validations/tutorial005_an_py39.py!}
+```
+
+////
+
+//// tab | Python 3.8+
+
+```Python hl_lines="8"
+{!> ../../../docs_src/query_params_str_validations/tutorial005_an.py!}
+```
+
+////
- ```Python hl_lines="9"
- {!> ../../../docs_src/query_params_str_validations/tutorial005_an_py39.py!}
- ```
+//// tab | Python 3.8+ без Annotated
-=== "Python 3.8+"
+/// tip | "Подсказка"
- ```Python hl_lines="8"
- {!> ../../../docs_src/query_params_str_validations/tutorial005_an.py!}
- ```
+Рекомендуется использовать версию с `Annotated` если возможно.
-=== "Python 3.8+ без Annotated"
+///
+
+```Python hl_lines="7"
+{!> ../../../docs_src/query_params_str_validations/tutorial005.py!}
+```
- !!! tip "Подсказка"
- Рекомендуется использовать версию с `Annotated` если возможно.
+////
- ```Python hl_lines="7"
- {!> ../../../docs_src/query_params_str_validations/tutorial005.py!}
- ```
+/// note | "Технические детали"
-!!! note "Технические детали"
- Наличие значения по умолчанию делает параметр необязательным.
+Наличие значения по умолчанию делает параметр необязательным.
+
+///
## Обязательный параметр
Но у нас query-параметр определён как `Query`. Например:
-=== "Annotated"
+//// tab | Annotated
+
+```Python
+q: Annotated[Union[str, None], Query(min_length=3)] = None
+```
+
+////
- ```Python
- q: Annotated[Union[str, None], Query(min_length=3)] = None
- ```
+//// tab | без Annotated
-=== "без Annotated"
+```Python
+q: Union[str, None] = Query(default=None, min_length=3)
+```
- ```Python
- q: Union[str, None] = Query(default=None, min_length=3)
- ```
+////
В таком случае, чтобы сделать query-параметр `Query` обязательным, вы можете просто не указывать значение по умолчанию:
-=== "Python 3.9+"
+//// tab | Python 3.9+
- ```Python hl_lines="9"
- {!> ../../../docs_src/query_params_str_validations/tutorial006_an_py39.py!}
- ```
+```Python hl_lines="9"
+{!> ../../../docs_src/query_params_str_validations/tutorial006_an_py39.py!}
+```
-=== "Python 3.8+"
+////
- ```Python hl_lines="8"
- {!> ../../../docs_src/query_params_str_validations/tutorial006_an.py!}
- ```
+//// tab | Python 3.8+
-=== "Python 3.8+ без Annotated"
+```Python hl_lines="8"
+{!> ../../../docs_src/query_params_str_validations/tutorial006_an.py!}
+```
+
+////
+
+//// tab | Python 3.8+ без Annotated
+
+/// tip | "Подсказка"
- !!! tip "Подсказка"
- Рекомендуется использовать версию с `Annotated` если возможно.
+Рекомендуется использовать версию с `Annotated` если возможно.
+
+///
+
+```Python hl_lines="7"
+{!> ../../../docs_src/query_params_str_validations/tutorial006.py!}
+```
- ```Python hl_lines="7"
- {!> ../../../docs_src/query_params_str_validations/tutorial006.py!}
- ```
+/// tip | "Подсказка"
- !!! tip "Подсказка"
- Обратите внимание, что даже когда `Query()` используется как значение по умолчанию для параметра функции, мы не передаём `default=None` в `Query()`.
+Обратите внимание, что даже когда `Query()` используется как значение по умолчанию для параметра функции, мы не передаём `default=None` в `Query()`.
- Лучше будет использовать версию с `Annotated`. 😉
+Лучше будет использовать версию с `Annotated`. 😉
+
+///
+
+////
### Обязательный параметр с Ellipsis (`...`)
Альтернативный способ указать обязательность параметра запроса - это указать параметр `default` через многоточие `...`:
-=== "Python 3.9+"
+//// tab | Python 3.9+
+
+```Python hl_lines="9"
+{!> ../../../docs_src/query_params_str_validations/tutorial006b_an_py39.py!}
+```
+
+////
+
+//// tab | Python 3.8+
- ```Python hl_lines="9"
- {!> ../../../docs_src/query_params_str_validations/tutorial006b_an_py39.py!}
- ```
+```Python hl_lines="8"
+{!> ../../../docs_src/query_params_str_validations/tutorial006b_an.py!}
+```
-=== "Python 3.8+"
+////
- ```Python hl_lines="8"
- {!> ../../../docs_src/query_params_str_validations/tutorial006b_an.py!}
- ```
+//// tab | Python 3.8+ без Annotated
-=== "Python 3.8+ без Annotated"
+/// tip | "Подсказка"
- !!! tip "Подсказка"
- Рекомендуется использовать версию с `Annotated` если возможно.
+Рекомендуется использовать версию с `Annotated` если возможно.
- ```Python hl_lines="7"
- {!> ../../../docs_src/query_params_str_validations/tutorial006b.py!}
- ```
+///
-!!! info "Дополнительная информация"
- Если вы ранее не сталкивались с `...`: это специальное значение, <a href="https://docs.python.org/3/library/constants.html#Ellipsis" class="external-link" target="_blank">часть языка Python и называется "Ellipsis"</a>.
+```Python hl_lines="7"
+{!> ../../../docs_src/query_params_str_validations/tutorial006b.py!}
+```
- Используется в Pydantic и FastAPI для определения, что значение требуется обязательно.
+////
+
+/// info | "Дополнительная информация"
+
+Если вы ранее не сталкивались с `...`: это специальное значение, <a href="https://docs.python.org/3/library/constants.html#Ellipsis" class="external-link" target="_blank">часть языка Python и называется "Ellipsis"</a>.
+
+Используется в Pydantic и FastAPI для определения, что значение требуется обязательно.
+
+///
Таким образом, **FastAPI** определяет, что параметр является обязательным.
Чтобы этого добиться, вам нужно определить `None` как валидный тип для параметра запроса, но также указать `default=...`:
-=== "Python 3.10+"
+//// tab | Python 3.10+
+
+```Python hl_lines="9"
+{!> ../../../docs_src/query_params_str_validations/tutorial006c_an_py310.py!}
+```
+
+////
- ```Python hl_lines="9"
- {!> ../../../docs_src/query_params_str_validations/tutorial006c_an_py310.py!}
- ```
+//// tab | Python 3.9+
-=== "Python 3.9+"
+```Python hl_lines="9"
+{!> ../../../docs_src/query_params_str_validations/tutorial006c_an_py39.py!}
+```
+
+////
+
+//// tab | Python 3.8+
+
+```Python hl_lines="10"
+{!> ../../../docs_src/query_params_str_validations/tutorial006c_an.py!}
+```
+
+////
- ```Python hl_lines="9"
- {!> ../../../docs_src/query_params_str_validations/tutorial006c_an_py39.py!}
- ```
+//// tab | Python 3.10+ без Annotated
-=== "Python 3.8+"
+/// tip | "Подсказка"
- ```Python hl_lines="10"
- {!> ../../../docs_src/query_params_str_validations/tutorial006c_an.py!}
- ```
+Рекомендуется использовать версию с `Annotated` если возможно.
-=== "Python 3.10+ без Annotated"
+///
- !!! tip "Подсказка"
- Рекомендуется использовать версию с `Annotated` если возможно.
+```Python hl_lines="7"
+{!> ../../../docs_src/query_params_str_validations/tutorial006c_py310.py!}
+```
- ```Python hl_lines="7"
- {!> ../../../docs_src/query_params_str_validations/tutorial006c_py310.py!}
- ```
+////
-=== "Python 3.8+ без Annotated"
+//// tab | Python 3.8+ без Annotated
- !!! tip "Подсказка"
- Рекомендуется использовать версию с `Annotated` если возможно.
+/// tip | "Подсказка"
- ```Python hl_lines="9"
- {!> ../../../docs_src/query_params_str_validations/tutorial006c.py!}
- ```
+Рекомендуется использовать версию с `Annotated` если возможно.
-!!! tip "Подсказка"
- Pydantic, мощь которого используется в FastAPI для валидации и сериализации, имеет специальное поведение для `Optional` или `Union[Something, None]` без значения по умолчанию. Вы можете узнать об этом больше в документации Pydantic, раздел <a href="https://docs.pydantic.dev/latest/concepts/models/#required-optional-fields" class="external-link" target="_blank">Обязательные Опциональные поля</a>.
+///
+
+```Python hl_lines="9"
+{!> ../../../docs_src/query_params_str_validations/tutorial006c.py!}
+```
+
+////
+
+/// tip | "Подсказка"
+
+Pydantic, мощь которого используется в FastAPI для валидации и сериализации, имеет специальное поведение для `Optional` или `Union[Something, None]` без значения по умолчанию. Вы можете узнать об этом больше в документации Pydantic, раздел <a href="https://docs.pydantic.dev/latest/concepts/models/#required-optional-fields" class="external-link" target="_blank">Обязательные Опциональные поля</a>.
+
+///
### Использование Pydantic's `Required` вместо Ellipsis (`...`)
Если вас смущает `...`, вы можете использовать `Required` из Pydantic:
-=== "Python 3.9+"
+//// tab | Python 3.9+
+
+```Python hl_lines="4 10"
+{!> ../../../docs_src/query_params_str_validations/tutorial006d_an_py39.py!}
+```
+
+////
+
+//// tab | Python 3.8+
+
+```Python hl_lines="2 9"
+{!> ../../../docs_src/query_params_str_validations/tutorial006d_an.py!}
+```
+
+////
+
+//// tab | Python 3.8+ без Annotated
- ```Python hl_lines="4 10"
- {!> ../../../docs_src/query_params_str_validations/tutorial006d_an_py39.py!}
- ```
+/// tip | "Подсказка"
-=== "Python 3.8+"
+Рекомендуется использовать версию с `Annotated` если возможно.
- ```Python hl_lines="2 9"
- {!> ../../../docs_src/query_params_str_validations/tutorial006d_an.py!}
- ```
+///
+
+```Python hl_lines="2 8"
+{!> ../../../docs_src/query_params_str_validations/tutorial006d.py!}
+```
-=== "Python 3.8+ без Annotated"
+////
- !!! tip "Подсказка"
- Рекомендуется использовать версию с `Annotated` если возможно.
+/// tip | "Подсказка"
- ```Python hl_lines="2 8"
- {!> ../../../docs_src/query_params_str_validations/tutorial006d.py!}
- ```
+Запомните, когда вам необходимо объявить query-параметр обязательным, вы можете просто не указывать параметр `default`. Таким образом, вам редко придётся использовать `...` или `Required`.
-!!! tip "Подсказка"
- Запомните, когда вам необходимо объявить query-параметр обязательным, вы можете просто не указывать параметр `default`. Таким образом, вам редко придётся использовать `...` или `Required`.
+///
## Множество значений для query-параметра
Например, query-параметр `q` может быть указан в URL несколько раз. И если вы ожидаете такой формат запроса, то можете указать это следующим образом:
-=== "Python 3.10+"
+//// tab | Python 3.10+
- ```Python hl_lines="9"
- {!> ../../../docs_src/query_params_str_validations/tutorial011_an_py310.py!}
- ```
+```Python hl_lines="9"
+{!> ../../../docs_src/query_params_str_validations/tutorial011_an_py310.py!}
+```
+
+////
+
+//// tab | Python 3.9+
+
+```Python hl_lines="9"
+{!> ../../../docs_src/query_params_str_validations/tutorial011_an_py39.py!}
+```
+
+////
-=== "Python 3.9+"
+//// tab | Python 3.8+
- ```Python hl_lines="9"
- {!> ../../../docs_src/query_params_str_validations/tutorial011_an_py39.py!}
- ```
+```Python hl_lines="10"
+{!> ../../../docs_src/query_params_str_validations/tutorial011_an.py!}
+```
-=== "Python 3.8+"
+////
- ```Python hl_lines="10"
- {!> ../../../docs_src/query_params_str_validations/tutorial011_an.py!}
- ```
+//// tab | Python 3.10+ без Annotated
-=== "Python 3.10+ без Annotated"
+/// tip | "Подсказка"
- !!! tip "Подсказка"
- Рекомендуется использовать версию с `Annotated` если возможно.
+Рекомендуется использовать версию с `Annotated` если возможно.
- ```Python hl_lines="7"
- {!> ../../../docs_src/query_params_str_validations/tutorial011_py310.py!}
- ```
+///
-=== "Python 3.9+ без Annotated"
+```Python hl_lines="7"
+{!> ../../../docs_src/query_params_str_validations/tutorial011_py310.py!}
+```
- !!! tip "Подсказка"
- Рекомендуется использовать версию с `Annotated` если возможно.
+////
- ```Python hl_lines="9"
- {!> ../../../docs_src/query_params_str_validations/tutorial011_py39.py!}
- ```
+//// tab | Python 3.9+ без Annotated
-=== "Python 3.8+ без Annotated"
+/// tip | "Подсказка"
- !!! tip "Подсказка"
- Рекомендуется использовать версию с `Annotated` если возможно.
+Рекомендуется использовать версию с `Annotated` если возможно.
- ```Python hl_lines="9"
- {!> ../../../docs_src/query_params_str_validations/tutorial011.py!}
- ```
+///
+
+```Python hl_lines="9"
+{!> ../../../docs_src/query_params_str_validations/tutorial011_py39.py!}
+```
+
+////
+
+//// tab | Python 3.8+ без Annotated
+
+/// tip | "Подсказка"
+
+Рекомендуется использовать версию с `Annotated` если возможно.
+
+///
+
+```Python hl_lines="9"
+{!> ../../../docs_src/query_params_str_validations/tutorial011.py!}
+```
+
+////
Затем, получив такой URL:
}
```
-!!! tip "Подсказка"
- Чтобы объявить query-параметр типом `list`, как в примере выше, вам нужно явно использовать `Query`, иначе он будет интерпретирован как тело запроса.
+/// tip | "Подсказка"
+
+Чтобы объявить query-параметр типом `list`, как в примере выше, вам нужно явно использовать `Query`, иначе он будет интерпретирован как тело запроса.
+
+///
Интерактивная документация API будет обновлена соответствующим образом, где будет разрешено множество значений:
Вы также можете указать тип `list` со списком значений по умолчанию на случай, если вам их не предоставят:
-=== "Python 3.9+"
+//// tab | Python 3.9+
- ```Python hl_lines="9"
- {!> ../../../docs_src/query_params_str_validations/tutorial012_an_py39.py!}
- ```
+```Python hl_lines="9"
+{!> ../../../docs_src/query_params_str_validations/tutorial012_an_py39.py!}
+```
-=== "Python 3.8+"
+////
- ```Python hl_lines="10"
- {!> ../../../docs_src/query_params_str_validations/tutorial012_an.py!}
- ```
+//// tab | Python 3.8+
-=== "Python 3.9+ без Annotated"
+```Python hl_lines="10"
+{!> ../../../docs_src/query_params_str_validations/tutorial012_an.py!}
+```
- !!! tip "Подсказка"
- Рекомендуется использовать версию с `Annotated` если возможно.
+////
- ```Python hl_lines="7"
- {!> ../../../docs_src/query_params_str_validations/tutorial012_py39.py!}
- ```
+//// tab | Python 3.9+ без Annotated
-=== "Python 3.8+ без Annotated"
+/// tip | "Подсказка"
- !!! tip "Подсказка"
- Рекомендуется использовать версию с `Annotated` если возможно.
+Рекомендуется использовать версию с `Annotated` если возможно.
- ```Python hl_lines="9"
- {!> ../../../docs_src/query_params_str_validations/tutorial012.py!}
- ```
+///
+
+```Python hl_lines="7"
+{!> ../../../docs_src/query_params_str_validations/tutorial012_py39.py!}
+```
+
+////
+
+//// tab | Python 3.8+ без Annotated
+
+/// tip | "Подсказка"
+
+Рекомендуется использовать версию с `Annotated` если возможно.
+
+///
+
+```Python hl_lines="9"
+{!> ../../../docs_src/query_params_str_validations/tutorial012.py!}
+```
+
+////
Если вы перейдёте по ссылке:
Вы также можете использовать `list` напрямую вместо `List[str]` (или `list[str]` в Python 3.9+):
-=== "Python 3.9+"
+//// tab | Python 3.9+
+
+```Python hl_lines="9"
+{!> ../../../docs_src/query_params_str_validations/tutorial013_an_py39.py!}
+```
+
+////
+
+//// tab | Python 3.8+
+
+```Python hl_lines="8"
+{!> ../../../docs_src/query_params_str_validations/tutorial013_an.py!}
+```
+
+////
+
+//// tab | Python 3.8+ без Annotated
- ```Python hl_lines="9"
- {!> ../../../docs_src/query_params_str_validations/tutorial013_an_py39.py!}
- ```
+/// tip | "Подсказка"
-=== "Python 3.8+"
+Рекомендуется использовать версию с `Annotated` если возможно.
- ```Python hl_lines="8"
- {!> ../../../docs_src/query_params_str_validations/tutorial013_an.py!}
- ```
+///
+
+```Python hl_lines="7"
+{!> ../../../docs_src/query_params_str_validations/tutorial013.py!}
+```
-=== "Python 3.8+ без Annotated"
+////
- !!! tip "Подсказка"
- Рекомендуется использовать версию с `Annotated` если возможно.
+/// note | "Технические детали"
- ```Python hl_lines="7"
- {!> ../../../docs_src/query_params_str_validations/tutorial013.py!}
- ```
+Запомните, что в таком случае, FastAPI не будет проверять содержимое списка.
-!!! note "Технические детали"
- Запомните, что в таком случае, FastAPI не будет проверять содержимое списка.
+Например, для List[int] список будет провалидирован (и задокументирован) на содержание только целочисленных элементов. Но для простого `list` такой проверки не будет.
- Например, для List[int] список будет провалидирован (и задокументирован) на содержание только целочисленных элементов. Но для простого `list` такой проверки не будет.
+///
## Больше метаданных
Указанная информация будет включена в генерируемую OpenAPI документацию и использована в пользовательском интерфейсе и внешних инструментах.
-!!! note "Технические детали"
- Имейте в виду, что разные инструменты могут иметь разные уровни поддержки OpenAPI.
+/// note | "Технические детали"
- Некоторые из них могут не отображать (на данный момент) всю заявленную дополнительную информацию, хотя в большинстве случаев отсутствующая функция уже запланирована к разработке.
+Имейте в виду, что разные инструменты могут иметь разные уровни поддержки OpenAPI.
+
+Некоторые из них могут не отображать (на данный момент) всю заявленную дополнительную информацию, хотя в большинстве случаев отсутствующая функция уже запланирована к разработке.
+
+///
Вы можете указать название query-параметра, используя параметр `title`:
-=== "Python 3.10+"
+//// tab | Python 3.10+
+
+```Python hl_lines="10"
+{!> ../../../docs_src/query_params_str_validations/tutorial007_an_py310.py!}
+```
+
+////
+
+//// tab | Python 3.9+
+
+```Python hl_lines="10"
+{!> ../../../docs_src/query_params_str_validations/tutorial007_an_py39.py!}
+```
+
+////
+
+//// tab | Python 3.8+
+
+```Python hl_lines="11"
+{!> ../../../docs_src/query_params_str_validations/tutorial007_an.py!}
+```
+
+////
- ```Python hl_lines="10"
- {!> ../../../docs_src/query_params_str_validations/tutorial007_an_py310.py!}
- ```
+//// tab | Python 3.10+ без Annotated
-=== "Python 3.9+"
+/// tip | "Подсказка"
- ```Python hl_lines="10"
- {!> ../../../docs_src/query_params_str_validations/tutorial007_an_py39.py!}
- ```
+Рекомендуется использовать версию с `Annotated` если возможно.
-=== "Python 3.8+"
+///
+
+```Python hl_lines="8"
+{!> ../../../docs_src/query_params_str_validations/tutorial007_py310.py!}
+```
- ```Python hl_lines="11"
- {!> ../../../docs_src/query_params_str_validations/tutorial007_an.py!}
- ```
+////
-=== "Python 3.10+ без Annotated"
+//// tab | Python 3.8+ без Annotated
- !!! tip "Подсказка"
- Рекомендуется использовать версию с `Annotated` если возможно.
+/// tip | "Подсказка"
- ```Python hl_lines="8"
- {!> ../../../docs_src/query_params_str_validations/tutorial007_py310.py!}
- ```
+Рекомендуется использовать версию с `Annotated` если возможно.
-=== "Python 3.8+ без Annotated"
+///
- !!! tip "Подсказка"
- Рекомендуется использовать версию с `Annotated` если возможно.
+```Python hl_lines="10"
+{!> ../../../docs_src/query_params_str_validations/tutorial007.py!}
+```
- ```Python hl_lines="10"
- {!> ../../../docs_src/query_params_str_validations/tutorial007.py!}
- ```
+////
Добавить описание, используя параметр `description`:
-=== "Python 3.10+"
+//// tab | Python 3.10+
+
+```Python hl_lines="14"
+{!> ../../../docs_src/query_params_str_validations/tutorial008_an_py310.py!}
+```
+
+////
- ```Python hl_lines="14"
- {!> ../../../docs_src/query_params_str_validations/tutorial008_an_py310.py!}
- ```
+//// tab | Python 3.9+
-=== "Python 3.9+"
+```Python hl_lines="14"
+{!> ../../../docs_src/query_params_str_validations/tutorial008_an_py39.py!}
+```
+
+////
+
+//// tab | Python 3.8+
+
+```Python hl_lines="15"
+{!> ../../../docs_src/query_params_str_validations/tutorial008_an.py!}
+```
+
+////
- ```Python hl_lines="14"
- {!> ../../../docs_src/query_params_str_validations/tutorial008_an_py39.py!}
- ```
+//// tab | Python 3.10+ без Annotated
-=== "Python 3.8+"
+/// tip | "Подсказка"
- ```Python hl_lines="15"
- {!> ../../../docs_src/query_params_str_validations/tutorial008_an.py!}
- ```
+Рекомендуется использовать версию с `Annotated` если возможно.
-=== "Python 3.10+ без Annotated"
+///
+
+```Python hl_lines="11"
+{!> ../../../docs_src/query_params_str_validations/tutorial008_py310.py!}
+```
- !!! tip "Подсказка"
- Рекомендуется использовать версию с `Annotated` если возможно.
+////
- ```Python hl_lines="11"
- {!> ../../../docs_src/query_params_str_validations/tutorial008_py310.py!}
- ```
+//// tab | Python 3.8+ без Annotated
-=== "Python 3.8+ без Annotated"
+/// tip | "Подсказка"
- !!! tip "Подсказка"
- Рекомендуется использовать версию с `Annotated` если возможно.
+Рекомендуется использовать версию с `Annotated` если возможно.
- ```Python hl_lines="13"
- {!> ../../../docs_src/query_params_str_validations/tutorial008.py!}
- ```
+///
+
+```Python hl_lines="13"
+{!> ../../../docs_src/query_params_str_validations/tutorial008.py!}
+```
+
+////
## Псевдонимы параметров
Тогда вы можете объявить `псевдоним`, и этот псевдоним будет использоваться для поиска значения параметра запроса:
-=== "Python 3.10+"
+//// tab | Python 3.10+
+
+```Python hl_lines="9"
+{!> ../../../docs_src/query_params_str_validations/tutorial009_an_py310.py!}
+```
- ```Python hl_lines="9"
- {!> ../../../docs_src/query_params_str_validations/tutorial009_an_py310.py!}
- ```
+////
-=== "Python 3.9+"
+//// tab | Python 3.9+
- ```Python hl_lines="9"
- {!> ../../../docs_src/query_params_str_validations/tutorial009_an_py39.py!}
- ```
+```Python hl_lines="9"
+{!> ../../../docs_src/query_params_str_validations/tutorial009_an_py39.py!}
+```
-=== "Python 3.8+"
+////
- ```Python hl_lines="10"
- {!> ../../../docs_src/query_params_str_validations/tutorial009_an.py!}
- ```
+//// tab | Python 3.8+
-=== "Python 3.10+ без Annotated"
+```Python hl_lines="10"
+{!> ../../../docs_src/query_params_str_validations/tutorial009_an.py!}
+```
- !!! tip "Подсказка"
- Рекомендуется использовать версию с `Annotated` если возможно.
+////
- ```Python hl_lines="7"
- {!> ../../../docs_src/query_params_str_validations/tutorial009_py310.py!}
- ```
+//// tab | Python 3.10+ без Annotated
-=== "Python 3.8+ без Annotated"
+/// tip | "Подсказка"
- !!! tip "Подсказка"
- Рекомендуется использовать версию с `Annotated` если возможно.
+Рекомендуется использовать версию с `Annotated` если возможно.
- ```Python hl_lines="9"
- {!> ../../../docs_src/query_params_str_validations/tutorial009.py!}
- ```
+///
+
+```Python hl_lines="7"
+{!> ../../../docs_src/query_params_str_validations/tutorial009_py310.py!}
+```
+
+////
+
+//// tab | Python 3.8+ без Annotated
+
+/// tip | "Подсказка"
+
+Рекомендуется использовать версию с `Annotated` если возможно.
+
+///
+
+```Python hl_lines="9"
+{!> ../../../docs_src/query_params_str_validations/tutorial009.py!}
+```
+
+////
## Устаревшие параметры
Тогда для `Query` укажите параметр `deprecated=True`:
-=== "Python 3.10+"
+//// tab | Python 3.10+
+
+```Python hl_lines="19"
+{!> ../../../docs_src/query_params_str_validations/tutorial010_an_py310.py!}
+```
+
+////
+
+//// tab | Python 3.9+
- ```Python hl_lines="19"
- {!> ../../../docs_src/query_params_str_validations/tutorial010_an_py310.py!}
- ```
+```Python hl_lines="19"
+{!> ../../../docs_src/query_params_str_validations/tutorial010_an_py39.py!}
+```
-=== "Python 3.9+"
+////
- ```Python hl_lines="19"
- {!> ../../../docs_src/query_params_str_validations/tutorial010_an_py39.py!}
- ```
+//// tab | Python 3.8+
-=== "Python 3.8+"
+```Python hl_lines="20"
+{!> ../../../docs_src/query_params_str_validations/tutorial010_an.py!}
+```
+
+////
+
+//// tab | Python 3.10+ без Annotated
+
+/// tip | "Подсказка"
+
+Рекомендуется использовать версию с `Annotated` если возможно.
+
+///
+
+```Python hl_lines="16"
+{!> ../../../docs_src/query_params_str_validations/tutorial010_py310.py!}
+```
- ```Python hl_lines="20"
- {!> ../../../docs_src/query_params_str_validations/tutorial010_an.py!}
- ```
+////
-=== "Python 3.10+ без Annotated"
+//// tab | Python 3.8+ без Annotated
- !!! tip "Подсказка"
- Рекомендуется использовать версию с `Annotated` если возможно.
+/// tip | "Подсказка"
- ```Python hl_lines="16"
- {!> ../../../docs_src/query_params_str_validations/tutorial010_py310.py!}
- ```
+Рекомендуется использовать версию с `Annotated` если возможно.
-=== "Python 3.8+ без Annotated"
+///
- !!! tip "Подсказка"
- Рекомендуется использовать версию с `Annotated` если возможно.
+```Python hl_lines="18"
+{!> ../../../docs_src/query_params_str_validations/tutorial010.py!}
+```
- ```Python hl_lines="18"
- {!> ../../../docs_src/query_params_str_validations/tutorial010.py!}
- ```
+////
В документации это будет отображено следующим образом:
Чтобы исключить query-параметр из генерируемой OpenAPI схемы (а также из системы автоматической генерации документации), укажите в `Query` параметр `include_in_schema=False`:
-=== "Python 3.10+"
+//// tab | Python 3.10+
+
+```Python hl_lines="10"
+{!> ../../../docs_src/query_params_str_validations/tutorial014_an_py310.py!}
+```
+
+////
- ```Python hl_lines="10"
- {!> ../../../docs_src/query_params_str_validations/tutorial014_an_py310.py!}
- ```
+//// tab | Python 3.9+
-=== "Python 3.9+"
+```Python hl_lines="10"
+{!> ../../../docs_src/query_params_str_validations/tutorial014_an_py39.py!}
+```
+
+////
- ```Python hl_lines="10"
- {!> ../../../docs_src/query_params_str_validations/tutorial014_an_py39.py!}
- ```
+//// tab | Python 3.8+
-=== "Python 3.8+"
+```Python hl_lines="11"
+{!> ../../../docs_src/query_params_str_validations/tutorial014_an.py!}
+```
- ```Python hl_lines="11"
- {!> ../../../docs_src/query_params_str_validations/tutorial014_an.py!}
- ```
+////
-=== "Python 3.10+ без Annotated"
+//// tab | Python 3.10+ без Annotated
- !!! tip "Подсказка"
- Рекомендуется использовать версию с `Annotated` если возможно.
+/// tip | "Подсказка"
- ```Python hl_lines="8"
- {!> ../../../docs_src/query_params_str_validations/tutorial014_py310.py!}
- ```
+Рекомендуется использовать версию с `Annotated` если возможно.
-=== "Python 3.8+ без Annotated"
+///
- !!! tip "Подсказка"
- Рекомендуется использовать версию с `Annotated` если возможно.
+```Python hl_lines="8"
+{!> ../../../docs_src/query_params_str_validations/tutorial014_py310.py!}
+```
+
+////
+
+//// tab | Python 3.8+ без Annotated
+
+/// tip | "Подсказка"
+
+Рекомендуется использовать версию с `Annotated` если возможно.
+
+///
+
+```Python hl_lines="10"
+{!> ../../../docs_src/query_params_str_validations/tutorial014.py!}
+```
- ```Python hl_lines="10"
- {!> ../../../docs_src/query_params_str_validations/tutorial014.py!}
- ```
+////
## Резюме
Аналогично, вы можете объявлять необязательные query-параметры, установив их значение по умолчанию, равное `None`:
-=== "Python 3.10+"
+//// tab | Python 3.10+
- ```Python hl_lines="7"
- {!> ../../../docs_src/query_params/tutorial002_py310.py!}
- ```
+```Python hl_lines="7"
+{!> ../../../docs_src/query_params/tutorial002_py310.py!}
+```
+
+////
+
+//// tab | Python 3.8+
-=== "Python 3.8+"
+```Python hl_lines="9"
+{!> ../../../docs_src/query_params/tutorial002.py!}
+```
- ```Python hl_lines="9"
- {!> ../../../docs_src/query_params/tutorial002.py!}
- ```
+////
В этом случае, параметр `q` будет не обязательным и будет иметь значение `None` по умолчанию.
-!!! check "Важно"
- Также обратите внимание, что **FastAPI** достаточно умён чтобы заметить, что параметр `item_id` является path-параметром, а `q` нет, поэтому, это параметр запроса.
+/// check | "Важно"
+
+Также обратите внимание, что **FastAPI** достаточно умён чтобы заметить, что параметр `item_id` является path-параметром, а `q` нет, поэтому, это параметр запроса.
+
+///
## Преобразование типа параметра запроса
Вы также можете объявлять параметры с типом `bool`, которые будут преобразованы соответственно:
-=== "Python 3.10+"
+//// tab | Python 3.10+
+
+```Python hl_lines="7"
+{!> ../../../docs_src/query_params/tutorial003_py310.py!}
+```
- ```Python hl_lines="7"
- {!> ../../../docs_src/query_params/tutorial003_py310.py!}
- ```
+////
-=== "Python 3.8+"
+//// tab | Python 3.8+
+
+```Python hl_lines="9"
+{!> ../../../docs_src/query_params/tutorial003.py!}
+```
- ```Python hl_lines="9"
- {!> ../../../docs_src/query_params/tutorial003.py!}
- ```
+////
В этом случае, если вы сделаете запрос:
Они будут обнаружены по именам:
-=== "Python 3.10+"
+//// tab | Python 3.10+
+
+```Python hl_lines="6 8"
+{!> ../../../docs_src/query_params/tutorial004_py310.py!}
+```
+
+////
- ```Python hl_lines="6 8"
- {!> ../../../docs_src/query_params/tutorial004_py310.py!}
- ```
+//// tab | Python 3.8+
-=== "Python 3.8+"
+```Python hl_lines="8 10"
+{!> ../../../docs_src/query_params/tutorial004.py!}
+```
- ```Python hl_lines="8 10"
- {!> ../../../docs_src/query_params/tutorial004.py!}
- ```
+////
## Обязательные query-параметры
Конечно, вы можете определить некоторые параметры как обязательные, некоторые - со значением по умполчанию, а некоторые - полностью необязательные:
-=== "Python 3.10+"
+//// tab | Python 3.10+
- ```Python hl_lines="8"
- {!> ../../../docs_src/query_params/tutorial006_py310.py!}
- ```
+```Python hl_lines="8"
+{!> ../../../docs_src/query_params/tutorial006_py310.py!}
+```
-=== "Python 3.8+"
+////
- ```Python hl_lines="10"
- {!> ../../../docs_src/query_params/tutorial006.py!}
- ```
+//// tab | Python 3.8+
+
+```Python hl_lines="10"
+{!> ../../../docs_src/query_params/tutorial006.py!}
+```
+
+////
В этом примере, у нас есть 3 параметра запроса:
* `skip`, типа `int` и со значением по умолчанию `0`.
* `limit`, необязательный `int`.
-!!! tip "Подсказка"
- Вы можете использовать класс `Enum` также, как ранее применяли его с [Path-параметрами](path-params.md#_7){.internal-link target=_blank}.
+/// tip | "Подсказка"
+
+Вы можете использовать класс `Enum` также, как ранее применяли его с [Path-параметрами](path-params.md#_7){.internal-link target=_blank}.
+
+///
Используя класс `File`, мы можем позволить клиентам загружать файлы.
-!!! info "Дополнительная информация"
- Чтобы получать загруженные файлы, сначала установите <a href="https://github.com/Kludex/python-multipart" class="external-link" target="_blank">`python-multipart`</a>.
+/// info | "Дополнительная информация"
- Например: `pip install python-multipart`.
+Чтобы получать загруженные файлы, сначала установите <a href="https://github.com/Kludex/python-multipart" class="external-link" target="_blank">`python-multipart`</a>.
- Это связано с тем, что загружаемые файлы передаются как данные формы.
+Например: `pip install python-multipart`.
+
+Это связано с тем, что загружаемые файлы передаются как данные формы.
+
+///
## Импорт `File`
Импортируйте `File` и `UploadFile` из модуля `fastapi`:
-=== "Python 3.9+"
+//// tab | Python 3.9+
+
+```Python hl_lines="3"
+{!> ../../../docs_src/request_files/tutorial001_an_py39.py!}
+```
+
+////
- ```Python hl_lines="3"
- {!> ../../../docs_src/request_files/tutorial001_an_py39.py!}
- ```
+//// tab | Python 3.6+
-=== "Python 3.6+"
+```Python hl_lines="1"
+{!> ../../../docs_src/request_files/tutorial001_an.py!}
+```
- ```Python hl_lines="1"
- {!> ../../../docs_src/request_files/tutorial001_an.py!}
- ```
+////
-=== "Python 3.6+ без Annotated"
+//// tab | Python 3.6+ без Annotated
- !!! tip "Подсказка"
- Предпочтительнее использовать версию с аннотацией, если это возможно.
+/// tip | "Подсказка"
- ```Python hl_lines="1"
- {!> ../../../docs_src/request_files/tutorial001.py!}
- ```
+Предпочтительнее использовать версию с аннотацией, если это возможно.
+
+///
+
+```Python hl_lines="1"
+{!> ../../../docs_src/request_files/tutorial001.py!}
+```
+
+////
## Определите параметры `File`
Создайте параметры `File` так же, как вы это делаете для `Body` или `Form`:
-=== "Python 3.9+"
+//// tab | Python 3.9+
+
+```Python hl_lines="9"
+{!> ../../../docs_src/request_files/tutorial001_an_py39.py!}
+```
+
+////
+
+//// tab | Python 3.6+
+
+```Python hl_lines="8"
+{!> ../../../docs_src/request_files/tutorial001_an.py!}
+```
+
+////
- ```Python hl_lines="9"
- {!> ../../../docs_src/request_files/tutorial001_an_py39.py!}
- ```
+//// tab | Python 3.6+ без Annotated
+
+/// tip | "Подсказка"
+
+Предпочтительнее использовать версию с аннотацией, если это возможно.
+
+///
+
+```Python hl_lines="7"
+{!> ../../../docs_src/request_files/tutorial001.py!}
+```
-=== "Python 3.6+"
+////
- ```Python hl_lines="8"
- {!> ../../../docs_src/request_files/tutorial001_an.py!}
- ```
+/// info | "Дополнительная информация"
-=== "Python 3.6+ без Annotated"
+`File` - это класс, который наследуется непосредственно от `Form`.
- !!! tip "Подсказка"
- Предпочтительнее использовать версию с аннотацией, если это возможно.
+Но помните, что когда вы импортируете `Query`, `Path`, `File` и другие из `fastapi`, на самом деле это функции, которые возвращают специальные классы.
- ```Python hl_lines="7"
- {!> ../../../docs_src/request_files/tutorial001.py!}
- ```
+///
-!!! info "Дополнительная информация"
- `File` - это класс, который наследуется непосредственно от `Form`.
+/// tip | "Подсказка"
- Но помните, что когда вы импортируете `Query`, `Path`, `File` и другие из `fastapi`, на самом деле это функции, которые возвращают специальные классы.
+Для объявления тела файла необходимо использовать `File`, поскольку в противном случае параметры будут интерпретироваться как параметры запроса или параметры тела (JSON).
-!!! tip "Подсказка"
- Для объявления тела файла необходимо использовать `File`, поскольку в противном случае параметры будут интерпретироваться как параметры запроса или параметры тела (JSON).
+///
Файлы будут загружены как данные формы.
Определите параметр файла с типом `UploadFile`:
-=== "Python 3.9+"
+//// tab | Python 3.9+
- ```Python hl_lines="14"
- {!> ../../../docs_src/request_files/tutorial001_an_py39.py!}
- ```
+```Python hl_lines="14"
+{!> ../../../docs_src/request_files/tutorial001_an_py39.py!}
+```
+
+////
+
+//// tab | Python 3.6+
-=== "Python 3.6+"
+```Python hl_lines="13"
+{!> ../../../docs_src/request_files/tutorial001_an.py!}
+```
+
+////
- ```Python hl_lines="13"
- {!> ../../../docs_src/request_files/tutorial001_an.py!}
- ```
+//// tab | Python 3.6+ без Annotated
-=== "Python 3.6+ без Annotated"
+/// tip | "Подсказка"
- !!! tip "Подсказка"
- Предпочтительнее использовать версию с аннотацией, если это возможно.
+Предпочтительнее использовать версию с аннотацией, если это возможно.
- ```Python hl_lines="12"
- {!> ../../../docs_src/request_files/tutorial001.py!}
- ```
+///
+
+```Python hl_lines="12"
+{!> ../../../docs_src/request_files/tutorial001.py!}
+```
+
+////
Использование `UploadFile` имеет ряд преимуществ перед `bytes`:
contents = myfile.file.read()
```
-!!! note "Технические детали `async`"
- При использовании методов `async` **FastAPI** запускает файловые методы в пуле потоков и ожидает их.
+/// note | "Технические детали `async`"
+
+При использовании методов `async` **FastAPI** запускает файловые методы в пуле потоков и ожидает их.
+
+///
+
+/// note | "Технические детали Starlette"
-!!! note "Технические детали Starlette"
- **FastAPI** наследует `UploadFile` непосредственно из **Starlette**, но добавляет некоторые детали для совместимости с **Pydantic** и другими частями FastAPI.
+**FastAPI** наследует `UploadFile` непосредственно из **Starlette**, но добавляет некоторые детали для совместимости с **Pydantic** и другими частями FastAPI.
+
+///
## Про данные формы ("Form Data")
**FastAPI** позаботится о том, чтобы считать эти данные из нужного места, а не из JSON.
-!!! note "Технические детали"
- Данные из форм обычно кодируются с использованием "media type" `application/x-www-form-urlencoded` когда он не включает файлы.
+/// note | "Технические детали"
+
+Данные из форм обычно кодируются с использованием "media type" `application/x-www-form-urlencoded` когда он не включает файлы.
+
+Но когда форма включает файлы, она кодируется как multipart/form-data. Если вы используете `File`, **FastAPI** будет знать, что ему нужно получить файлы из нужной части тела.
+
+Если вы хотите узнать больше об этих кодировках и полях форм, перейдите по ссылке <a href="https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods/POST" class="external-link" target="_blank"><abbr title="Mozilla Developer Network">MDN</abbr> web docs for <code>POST</code></a>.
+
+///
- Но когда форма включает файлы, она кодируется как multipart/form-data. Если вы используете `File`, **FastAPI** будет знать, что ему нужно получить файлы из нужной части тела.
+/// warning | "Внимание"
- Если вы хотите узнать больше об этих кодировках и полях форм, перейдите по ссылке <a href="https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods/POST" class="external-link" target="_blank"><abbr title="Mozilla Developer Network">MDN</abbr> web docs for <code>POST</code></a>.
+В операции *функции операции пути* можно объявить несколько параметров `File` и `Form`, но нельзя также объявлять поля `Body`, которые предполагается получить в виде JSON, поскольку тело запроса будет закодировано с помощью `multipart/form-data`, а не `application/json`.
-!!! warning "Внимание"
- В операции *функции операции пути* можно объявить несколько параметров `File` и `Form`, но нельзя также объявлять поля `Body`, которые предполагается получить в виде JSON, поскольку тело запроса будет закодировано с помощью `multipart/form-data`, а не `application/json`.
+Это не является ограничением **FastAPI**, это часть протокола HTTP.
- Это не является ограничением **FastAPI**, это часть протокола HTTP.
+///
## Необязательная загрузка файлов
Вы можете сделать загрузку файла необязательной, используя стандартные аннотации типов и установив значение по умолчанию `None`:
-=== "Python 3.10+"
+//// tab | Python 3.10+
+
+```Python hl_lines="9 17"
+{!> ../../../docs_src/request_files/tutorial001_02_an_py310.py!}
+```
+
+////
+
+//// tab | Python 3.9+
+
+```Python hl_lines="9 17"
+{!> ../../../docs_src/request_files/tutorial001_02_an_py39.py!}
+```
+
+////
+
+//// tab | Python 3.6+
- ```Python hl_lines="9 17"
- {!> ../../../docs_src/request_files/tutorial001_02_an_py310.py!}
- ```
+```Python hl_lines="10 18"
+{!> ../../../docs_src/request_files/tutorial001_02_an.py!}
+```
+
+////
-=== "Python 3.9+"
+//// tab | Python 3.10+ без Annotated
- ```Python hl_lines="9 17"
- {!> ../../../docs_src/request_files/tutorial001_02_an_py39.py!}
- ```
+/// tip | "Подсказка"
-=== "Python 3.6+"
+Предпочтительнее использовать версию с аннотацией, если это возможно.
- ```Python hl_lines="10 18"
- {!> ../../../docs_src/request_files/tutorial001_02_an.py!}
- ```
+///
-=== "Python 3.10+ без Annotated"
+```Python hl_lines="7 15"
+{!> ../../../docs_src/request_files/tutorial001_02_py310.py!}
+```
- !!! tip "Подсказка"
- Предпочтительнее использовать версию с аннотацией, если это возможно.
+////
- ```Python hl_lines="7 15"
- {!> ../../../docs_src/request_files/tutorial001_02_py310.py!}
- ```
+//// tab | Python 3.6+ без Annotated
-=== "Python 3.6+ без Annotated"
+/// tip | "Подсказка"
- !!! tip "Подсказка"
- Предпочтительнее использовать версию с аннотацией, если это возможно.
+Предпочтительнее использовать версию с аннотацией, если это возможно.
- ```Python hl_lines="9 17"
- {!> ../../../docs_src/request_files/tutorial001_02.py!}
- ```
+///
+
+```Python hl_lines="9 17"
+{!> ../../../docs_src/request_files/tutorial001_02.py!}
+```
+
+////
## `UploadFile` с дополнительными метаданными
Вы также можете использовать `File()` вместе с `UploadFile`, например, для установки дополнительных метаданных:
-=== "Python 3.9+"
+//// tab | Python 3.9+
+
+```Python hl_lines="9 15"
+{!> ../../../docs_src/request_files/tutorial001_03_an_py39.py!}
+```
+
+////
+
+//// tab | Python 3.6+
+
+```Python hl_lines="8 14"
+{!> ../../../docs_src/request_files/tutorial001_03_an.py!}
+```
+
+////
- ```Python hl_lines="9 15"
- {!> ../../../docs_src/request_files/tutorial001_03_an_py39.py!}
- ```
+//// tab | Python 3.6+ без Annotated
-=== "Python 3.6+"
+/// tip | "Подсказка"
- ```Python hl_lines="8 14"
- {!> ../../../docs_src/request_files/tutorial001_03_an.py!}
- ```
+Предпочтительнее использовать версию с аннотацией, если это возможно.
-=== "Python 3.6+ без Annotated"
+///
- !!! tip "Подсказка"
- Предпочтительнее использовать версию с аннотацией, если это возможно.
+```Python hl_lines="7 13"
+{!> ../../../docs_src/request_files/tutorial001_03.py!}
+```
- ```Python hl_lines="7 13"
- {!> ../../../docs_src/request_files/tutorial001_03.py!}
- ```
+////
## Загрузка нескольких файлов
Для этого необходимо объявить список `bytes` или `UploadFile`:
-=== "Python 3.9+"
+//// tab | Python 3.9+
- ```Python hl_lines="10 15"
- {!> ../../../docs_src/request_files/tutorial002_an_py39.py!}
- ```
+```Python hl_lines="10 15"
+{!> ../../../docs_src/request_files/tutorial002_an_py39.py!}
+```
+
+////
-=== "Python 3.6+"
+//// tab | Python 3.6+
- ```Python hl_lines="11 16"
- {!> ../../../docs_src/request_files/tutorial002_an.py!}
- ```
+```Python hl_lines="11 16"
+{!> ../../../docs_src/request_files/tutorial002_an.py!}
+```
-=== "Python 3.9+ без Annotated"
+////
- !!! tip "Подсказка"
- Предпочтительнее использовать версию с аннотацией, если это возможно.
+//// tab | Python 3.9+ без Annotated
- ```Python hl_lines="8 13"
- {!> ../../../docs_src/request_files/tutorial002_py39.py!}
- ```
+/// tip | "Подсказка"
-=== "Python 3.6+ без Annotated"
+Предпочтительнее использовать версию с аннотацией, если это возможно.
- !!! tip "Подсказка"
- Предпочтительнее использовать версию с аннотацией, если это возможно.
+///
+
+```Python hl_lines="8 13"
+{!> ../../../docs_src/request_files/tutorial002_py39.py!}
+```
- ```Python hl_lines="10 15"
- {!> ../../../docs_src/request_files/tutorial002.py!}
- ```
+////
+
+//// tab | Python 3.6+ без Annotated
+
+/// tip | "Подсказка"
+
+Предпочтительнее использовать версию с аннотацией, если это возможно.
+
+///
+
+```Python hl_lines="10 15"
+{!> ../../../docs_src/request_files/tutorial002.py!}
+```
+
+////
Вы получите, как и было объявлено, список `list` из `bytes` или `UploadFile`.
-!!! note "Technical Details"
- Можно также использовать `from starlette.responses import HTMLResponse`.
+/// note | "Technical Details"
+
+Можно также использовать `from starlette.responses import HTMLResponse`.
+
+**FastAPI** предоставляет тот же `starlette.responses`, что и `fastapi.responses`, просто для удобства разработчика. Однако большинство доступных ответов поступает непосредственно из Starlette.
- **FastAPI** предоставляет тот же `starlette.responses`, что и `fastapi.responses`, просто для удобства разработчика. Однако большинство доступных ответов поступает непосредственно из Starlette.
+///
### Загрузка нескольких файлов с дополнительными метаданными
Так же, как и раньше, вы можете использовать `File()` для задания дополнительных параметров, даже для `UploadFile`:
-=== "Python 3.9+"
+//// tab | Python 3.9+
- ```Python hl_lines="11 18-20"
- {!> ../../../docs_src/request_files/tutorial003_an_py39.py!}
- ```
+```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!}
- ```
+//// tab | Python 3.6+
-=== "Python 3.9+ без Annotated"
+```Python hl_lines="12 19-21"
+{!> ../../../docs_src/request_files/tutorial003_an.py!}
+```
- !!! tip "Подсказка"
- Предпочтительнее использовать версию с аннотацией, если это возможно.
+////
- ```Python hl_lines="9 16"
- {!> ../../../docs_src/request_files/tutorial003_py39.py!}
- ```
+//// tab | Python 3.9+ без Annotated
-=== "Python 3.6+ без Annotated"
+/// tip | "Подсказка"
- !!! tip "Подсказка"
- Предпочтительнее использовать версию с аннотацией, если это возможно.
+Предпочтительнее использовать версию с аннотацией, если это возможно.
+
+///
+
+```Python hl_lines="9 16"
+{!> ../../../docs_src/request_files/tutorial003_py39.py!}
+```
+
+////
+
+//// tab | Python 3.6+ без Annotated
+
+/// tip | "Подсказка"
+
+Предпочтительнее использовать версию с аннотацией, если это возможно.
+
+///
+
+```Python hl_lines="11 18"
+{!> ../../../docs_src/request_files/tutorial003.py!}
+```
- ```Python hl_lines="11 18"
- {!> ../../../docs_src/request_files/tutorial003.py!}
- ```
+////
## Резюме
Вы можете определять файлы и поля формы одновременно, используя `File` и `Form`.
-!!! info "Дополнительная информация"
- Чтобы получать загруженные файлы и/или данные форм, сначала установите <a href="https://github.com/Kludex/python-multipart" class="external-link" target="_blank">`python-multipart`</a>.
+/// info | "Дополнительная информация"
- Например: `pip install python-multipart`.
+Чтобы получать загруженные файлы и/или данные форм, сначала установите <a href="https://github.com/Kludex/python-multipart" class="external-link" target="_blank">`python-multipart`</a>.
+
+Например: `pip install python-multipart`.
+
+///
## Импортируйте `File` и `Form`
-=== "Python 3.9+"
+//// tab | Python 3.9+
+
+```Python hl_lines="3"
+{!> ../../../docs_src/request_forms_and_files/tutorial001_an_py39.py!}
+```
+
+////
+
+//// tab | Python 3.6+
+
+```Python hl_lines="1"
+{!> ../../../docs_src/request_forms_and_files/tutorial001_an.py!}
+```
+
+////
- ```Python hl_lines="3"
- {!> ../../../docs_src/request_forms_and_files/tutorial001_an_py39.py!}
- ```
+//// tab | Python 3.6+ без Annotated
-=== "Python 3.6+"
+/// tip | "Подсказка"
- ```Python hl_lines="1"
- {!> ../../../docs_src/request_forms_and_files/tutorial001_an.py!}
- ```
+Предпочтительнее использовать версию с аннотацией, если это возможно.
-=== "Python 3.6+ без Annotated"
+///
- !!! tip "Подсказка"
- Предпочтительнее использовать версию с аннотацией, если это возможно.
+```Python hl_lines="1"
+{!> ../../../docs_src/request_forms_and_files/tutorial001.py!}
+```
- ```Python hl_lines="1"
- {!> ../../../docs_src/request_forms_and_files/tutorial001.py!}
- ```
+////
## Определите параметры `File` и `Form`
Создайте параметры файла и формы таким же образом, как для `Body` или `Query`:
-=== "Python 3.9+"
+//// tab | Python 3.9+
- ```Python hl_lines="10-12"
- {!> ../../../docs_src/request_forms_and_files/tutorial001_an_py39.py!}
- ```
+```Python hl_lines="10-12"
+{!> ../../../docs_src/request_forms_and_files/tutorial001_an_py39.py!}
+```
-=== "Python 3.6+"
+////
- ```Python hl_lines="9-11"
- {!> ../../../docs_src/request_forms_and_files/tutorial001_an.py!}
- ```
+//// tab | Python 3.6+
-=== "Python 3.6+ без Annotated"
+```Python hl_lines="9-11"
+{!> ../../../docs_src/request_forms_and_files/tutorial001_an.py!}
+```
- !!! tip "Подсказка"
- Предпочтительнее использовать версию с аннотацией, если это возможно.
+////
- ```Python hl_lines="8"
- {!> ../../../docs_src/request_forms_and_files/tutorial001.py!}
- ```
+//// tab | Python 3.6+ без Annotated
+
+/// tip | "Подсказка"
+
+Предпочтительнее использовать версию с аннотацией, если это возможно.
+
+///
+
+```Python hl_lines="8"
+{!> ../../../docs_src/request_forms_and_files/tutorial001.py!}
+```
+
+////
Файлы и поля формы будут загружены в виде данных формы, и вы получите файлы и поля формы.
Вы можете объявить некоторые файлы как `bytes`, а некоторые - как `UploadFile`.
-!!! warning "Внимание"
- Вы можете объявить несколько параметров `File` и `Form` в операции *path*, но вы не можете также объявить поля `Body`, которые вы ожидаете получить в виде JSON, так как запрос будет иметь тело, закодированное с помощью `multipart/form-data` вместо `application/json`.
+/// warning | "Внимание"
+
+Вы можете объявить несколько параметров `File` и `Form` в операции *path*, но вы не можете также объявить поля `Body`, которые вы ожидаете получить в виде JSON, так как запрос будет иметь тело, закодированное с помощью `multipart/form-data` вместо `application/json`.
+
+Это не ограничение **Fast API**, это часть протокола HTTP.
- Это не ограничение **Fast API**, это часть протокола HTTP.
+///
## Резюме
Когда вам нужно получить поля формы вместо JSON, вы можете использовать `Form`.
-!!! info "Дополнительная информация"
- Чтобы использовать формы, сначала установите <a href="https://github.com/Kludex/python-multipart" class="external-link" target="_blank">`python-multipart`</a>.
+/// info | "Дополнительная информация"
- Например, выполните команду `pip install python-multipart`.
+Чтобы использовать формы, сначала установите <a href="https://github.com/Kludex/python-multipart" class="external-link" target="_blank">`python-multipart`</a>.
+
+Например, выполните команду `pip install python-multipart`.
+
+///
## Импорт `Form`
Импортируйте `Form` из `fastapi`:
-=== "Python 3.9+"
+//// tab | Python 3.9+
+
+```Python hl_lines="3"
+{!> ../../../docs_src/request_forms/tutorial001_an_py39.py!}
+```
+
+////
+
+//// tab | Python 3.8+
- ```Python hl_lines="3"
- {!> ../../../docs_src/request_forms/tutorial001_an_py39.py!}
- ```
+```Python hl_lines="1"
+{!> ../../../docs_src/request_forms/tutorial001_an.py!}
+```
-=== "Python 3.8+"
+////
- ```Python hl_lines="1"
- {!> ../../../docs_src/request_forms/tutorial001_an.py!}
- ```
+//// tab | Python 3.8+ без Annotated
-=== "Python 3.8+ без Annotated"
+/// tip | "Подсказка"
- !!! tip "Подсказка"
- Рекомендуется использовать 'Annotated' версию, если это возможно.
+Рекомендуется использовать 'Annotated' версию, если это возможно.
- ```Python hl_lines="1"
- {!> ../../../docs_src/request_forms/tutorial001.py!}
- ```
+///
+
+```Python hl_lines="1"
+{!> ../../../docs_src/request_forms/tutorial001.py!}
+```
+
+////
## Определение параметров `Form`
Создайте параметры формы так же, как это делается для `Body` или `Query`:
-=== "Python 3.9+"
+//// tab | Python 3.9+
+
+```Python hl_lines="9"
+{!> ../../../docs_src/request_forms/tutorial001_an_py39.py!}
+```
+
+////
+
+//// tab | Python 3.8+
- ```Python hl_lines="9"
- {!> ../../../docs_src/request_forms/tutorial001_an_py39.py!}
- ```
+```Python hl_lines="8"
+{!> ../../../docs_src/request_forms/tutorial001_an.py!}
+```
-=== "Python 3.8+"
+////
- ```Python hl_lines="8"
- {!> ../../../docs_src/request_forms/tutorial001_an.py!}
- ```
+//// tab | Python 3.8+ без Annotated
-=== "Python 3.8+ без Annotated"
+/// tip | "Подсказка"
- !!! tip "Подсказка"
- Рекомендуется использовать 'Annotated' версию, если это возможно.
+Рекомендуется использовать 'Annotated' версию, если это возможно.
- ```Python hl_lines="7"
- {!> ../../../docs_src/request_forms/tutorial001.py!}
- ```
+///
+
+```Python hl_lines="7"
+{!> ../../../docs_src/request_forms/tutorial001.py!}
+```
+
+////
Например, в одном из способов использования спецификации OAuth2 (называемом "потоком пароля") требуется отправить `username` и `password` в виде полей формы.
Вы можете настроить `Form` точно так же, как настраиваете и `Body` ( `Query`, `Path`, `Cookie`), включая валидации, примеры, псевдонимы (например, `user-name` вместо `username`) и т.д.
-!!! info "Дополнительная информация"
- `Form` - это класс, который наследуется непосредственно от `Body`.
+/// info | "Дополнительная информация"
+
+`Form` - это класс, который наследуется непосредственно от `Body`.
+
+///
+
+/// tip | "Подсказка"
-!!! tip "Подсказка"
- Вам необходимо явно указывать параметр `Form` при объявлении каждого поля, иначе поля будут интерпретироваться как параметры запроса или параметры тела (JSON).
+Вам необходимо явно указывать параметр `Form` при объявлении каждого поля, иначе поля будут интерпретироваться как параметры запроса или параметры тела (JSON).
+
+///
## О "полях формы"
**FastAPI** гарантирует правильное чтение этих данных из соответствующего места, а не из JSON.
-!!! note "Технические детали"
- Данные из форм обычно кодируются с использованием "типа медиа" `application/x-www-form-urlencoded`.
+/// note | "Технические детали"
+
+Данные из форм обычно кодируются с использованием "типа медиа" `application/x-www-form-urlencoded`.
+
+Но когда форма содержит файлы, она кодируется как `multipart/form-data`. Вы узнаете о работе с файлами в следующей главе.
+
+Если вы хотите узнать больше про кодировки и поля формы, ознакомьтесь с <a href="https://developer.mozilla.org/ru/docs/Web/HTTP/Methods/POST" class="external-link" target="_blank">документацией <abbr title="Mozilla Developer Network">MDN</abbr> для `POST` на веб-сайте</a>.
+
+///
- Но когда форма содержит файлы, она кодируется как `multipart/form-data`. Вы узнаете о работе с файлами в следующей главе.
+/// warning | "Предупреждение"
- Если вы хотите узнать больше про кодировки и поля формы, ознакомьтесь с <a href="https://developer.mozilla.org/ru/docs/Web/HTTP/Methods/POST" class="external-link" target="_blank">документацией <abbr title="Mozilla Developer Network">MDN</abbr> для `POST` на веб-сайте</a>.
+Вы можете объявлять несколько параметров `Form` в *операции пути*, но вы не можете одновременно с этим объявлять поля `Body`, которые вы ожидаете получить в виде JSON, так как запрос будет иметь тело, закодированное с использованием `application/x-www-form-urlencoded`, а не `application/json`.
-!!! warning "Предупреждение"
- Вы можете объявлять несколько параметров `Form` в *операции пути*, но вы не можете одновременно с этим объявлять поля `Body`, которые вы ожидаете получить в виде JSON, так как запрос будет иметь тело, закодированное с использованием `application/x-www-form-urlencoded`, а не `application/json`.
+Это не ограничение **FastAPI**, это часть протокола HTTP.
- Это не ограничение **FastAPI**, это часть протокола HTTP.
+///
## Резюме
FastAPI позволяет использовать **аннотации типов** таким же способом, как и для ввода данных в **параметры** функции, вы можете использовать модели Pydantic, списки, словари, скалярные типы (такие, как int, bool и т.д.).
-=== "Python 3.10+"
+//// tab | Python 3.10+
- ```Python hl_lines="16 21"
- {!> ../../../docs_src/response_model/tutorial001_01_py310.py!}
- ```
+```Python hl_lines="16 21"
+{!> ../../../docs_src/response_model/tutorial001_01_py310.py!}
+```
+
+////
+
+//// tab | Python 3.9+
-=== "Python 3.9+"
+```Python hl_lines="18 23"
+{!> ../../../docs_src/response_model/tutorial001_01_py39.py!}
+```
+
+////
- ```Python hl_lines="18 23"
- {!> ../../../docs_src/response_model/tutorial001_01_py39.py!}
- ```
+//// tab | Python 3.8+
-=== "Python 3.8+"
+```Python hl_lines="18 23"
+{!> ../../../docs_src/response_model/tutorial001_01.py!}
+```
- ```Python hl_lines="18 23"
- {!> ../../../docs_src/response_model/tutorial001_01.py!}
- ```
+////
FastAPI будет использовать этот возвращаемый тип для:
* `@app.delete()`
* и др.
-=== "Python 3.10+"
+//// tab | Python 3.10+
- ```Python hl_lines="17 22 24-27"
- {!> ../../../docs_src/response_model/tutorial001_py310.py!}
- ```
+```Python hl_lines="17 22 24-27"
+{!> ../../../docs_src/response_model/tutorial001_py310.py!}
+```
+
+////
-=== "Python 3.9+"
+//// tab | Python 3.9+
- ```Python hl_lines="17 22 24-27"
- {!> ../../../docs_src/response_model/tutorial001_py39.py!}
- ```
+```Python hl_lines="17 22 24-27"
+{!> ../../../docs_src/response_model/tutorial001_py39.py!}
+```
-=== "Python 3.8+"
+////
- ```Python hl_lines="17 22 24-27"
- {!> ../../../docs_src/response_model/tutorial001.py!}
- ```
+//// tab | Python 3.8+
+
+```Python hl_lines="17 22 24-27"
+{!> ../../../docs_src/response_model/tutorial001.py!}
+```
-!!! note "Технические детали"
- Помните, что параметр `response_model` является параметром именно декоратора http-методов (`get`, `post`, и т.п.). Не следует его указывать для *функций операций пути*, как вы бы поступили с другими параметрами или с телом запроса.
+////
+
+/// note | "Технические детали"
+
+Помните, что параметр `response_model` является параметром именно декоратора http-методов (`get`, `post`, и т.п.). Не следует его указывать для *функций операций пути*, как вы бы поступили с другими параметрами или с телом запроса.
+
+///
`response_model` принимает те же типы, которые можно указать для какого-либо поля в модели Pydantic. Таким образом, это может быть как одиночная модель Pydantic, так и `список (list)` моделей Pydantic. Например, `List[Item]`.
FastAPI будет использовать значение `response_model` для того, чтобы автоматически генерировать документацию, производить валидацию и т.п. А также для **конвертации и фильтрации выходных данных** в объявленный тип.
-!!! tip "Подсказка"
- Если вы используете анализаторы типов со строгой проверкой (например, mypy), можно указать `Any` в качестве типа возвращаемого значения функции.
+/// tip | "Подсказка"
+
+Если вы используете анализаторы типов со строгой проверкой (например, mypy), можно указать `Any` в качестве типа возвращаемого значения функции.
+
+Таким образом вы информируете ваш редактор кода, что намеренно возвращаете данные неопределенного типа. Но возможности FastAPI, такие как автоматическая генерация документации, валидация, фильтрация и т.д. все так же будут работать, просто используя параметр `response_model`.
- Таким образом вы информируете ваш редактор кода, что намеренно возвращаете данные неопределенного типа. Но возможности FastAPI, такие как автоматическая генерация документации, валидация, фильтрация и т.д. все так же будут работать, просто используя параметр `response_model`.
+///
### Приоритет `response_model`
Здесь мы объявили модель `UserIn`, которая хранит пользовательский пароль в открытом виде:
-=== "Python 3.10+"
+//// tab | Python 3.10+
- ```Python hl_lines="7 9"
- {!> ../../../docs_src/response_model/tutorial002_py310.py!}
- ```
+```Python hl_lines="7 9"
+{!> ../../../docs_src/response_model/tutorial002_py310.py!}
+```
+
+////
+
+//// tab | Python 3.8+
+
+```Python hl_lines="9 11"
+{!> ../../../docs_src/response_model/tutorial002.py!}
+```
-=== "Python 3.8+"
+////
- ```Python hl_lines="9 11"
- {!> ../../../docs_src/response_model/tutorial002.py!}
- ```
+/// info | "Информация"
-!!! info "Информация"
- Чтобы использовать `EmailStr`, прежде необходимо установить <a href="https://github.com/JoshData/python-email-validator" class="external-link" target="_blank">`email_validator`</a>.
- Используйте `pip install email-validator`
- или `pip install pydantic[email]`.
+Чтобы использовать `EmailStr`, прежде необходимо установить <a href="https://github.com/JoshData/python-email-validator" class="external-link" target="_blank">`email_validator`</a>.
+Используйте `pip install email-validator`
+или `pip install pydantic[email]`.
+
+///
Далее мы используем нашу модель в аннотациях типа как для аргумента функции, так и для выходного значения:
-=== "Python 3.10+"
+//// tab | Python 3.10+
+
+```Python hl_lines="16"
+{!> ../../../docs_src/response_model/tutorial002_py310.py!}
+```
- ```Python hl_lines="16"
- {!> ../../../docs_src/response_model/tutorial002_py310.py!}
- ```
+////
-=== "Python 3.8+"
+//// tab | Python 3.8+
+
+```Python hl_lines="18"
+{!> ../../../docs_src/response_model/tutorial002.py!}
+```
- ```Python hl_lines="18"
- {!> ../../../docs_src/response_model/tutorial002.py!}
- ```
+////
Теперь всякий раз, когда клиент создает пользователя с паролем, API будет возвращать его пароль в ответе.
Но что если мы захотим использовать эту модель для какой-либо другой *операции пути*? Мы можем, сами того не желая, отправить пароль любому другому пользователю.
-!!! danger "Осторожно"
- Никогда не храните пароли пользователей в открытом виде, а также никогда не возвращайте их в ответе, как в примере выше. В противном случае - убедитесь, что вы хорошо продумали и учли все возможные риски такого подхода и вам известно, что вы делаете.
+/// danger | "Осторожно"
+
+Никогда не храните пароли пользователей в открытом виде, а также никогда не возвращайте их в ответе, как в примере выше. В противном случае - убедитесь, что вы хорошо продумали и учли все возможные риски такого подхода и вам известно, что вы делаете.
+
+///
## Создание модели для ответа
Вместо этого мы можем создать входную модель, хранящую пароль в открытом виде и выходную модель без пароля:
-=== "Python 3.10+"
+//// tab | Python 3.10+
+
+```Python hl_lines="9 11 16"
+{!> ../../../docs_src/response_model/tutorial003_py310.py!}
+```
+
+////
- ```Python hl_lines="9 11 16"
- {!> ../../../docs_src/response_model/tutorial003_py310.py!}
- ```
+//// tab | Python 3.8+
-=== "Python 3.8+"
+```Python hl_lines="9 11 16"
+{!> ../../../docs_src/response_model/tutorial003.py!}
+```
- ```Python hl_lines="9 11 16"
- {!> ../../../docs_src/response_model/tutorial003.py!}
- ```
+////
В таком случае, даже несмотря на то, что наша *функция операции пути* возвращает тот же самый объект пользователя с паролем, полученным на вход:
-=== "Python 3.10+"
+//// tab | Python 3.10+
+
+```Python hl_lines="24"
+{!> ../../../docs_src/response_model/tutorial003_py310.py!}
+```
- ```Python hl_lines="24"
- {!> ../../../docs_src/response_model/tutorial003_py310.py!}
- ```
+////
-=== "Python 3.8+"
+//// tab | Python 3.8+
+
+```Python hl_lines="24"
+{!> ../../../docs_src/response_model/tutorial003.py!}
+```
- ```Python hl_lines="24"
- {!> ../../../docs_src/response_model/tutorial003.py!}
- ```
+////
...мы указали в `response_model` модель `UserOut`, в которой отсутствует поле, содержащее пароль - и он будет исключен из ответа:
-=== "Python 3.10+"
+//// tab | Python 3.10+
- ```Python hl_lines="22"
- {!> ../../../docs_src/response_model/tutorial003_py310.py!}
- ```
+```Python hl_lines="22"
+{!> ../../../docs_src/response_model/tutorial003_py310.py!}
+```
+
+////
-=== "Python 3.8+"
+//// tab | Python 3.8+
- ```Python hl_lines="22"
- {!> ../../../docs_src/response_model/tutorial003.py!}
- ```
+```Python hl_lines="22"
+{!> ../../../docs_src/response_model/tutorial003.py!}
+```
+
+////
Таким образом **FastAPI** позаботится о фильтрации ответа и исключит из него всё, что не указано в выходной модели (при помощи Pydantic).
И в таких случаях мы можем использовать классы и наследование, чтобы пользоваться преимуществами **аннотаций типов** и получать более полную статическую проверку типов. Но при этом все так же получать **фильтрацию ответа** от FastAPI.
-=== "Python 3.10+"
+//// tab | Python 3.10+
+
+```Python hl_lines="7-10 13-14 18"
+{!> ../../../docs_src/response_model/tutorial003_01_py310.py!}
+```
+
+////
- ```Python hl_lines="7-10 13-14 18"
- {!> ../../../docs_src/response_model/tutorial003_01_py310.py!}
- ```
+//// tab | Python 3.8+
-=== "Python 3.8+"
+```Python hl_lines="9-13 15-16 20"
+{!> ../../../docs_src/response_model/tutorial003_01.py!}
+```
- ```Python hl_lines="9-13 15-16 20"
- {!> ../../../docs_src/response_model/tutorial003_01.py!}
- ```
+////
Таким образом, мы получаем поддержку редактора кода и mypy в части типов, сохраняя при этом фильтрацию данных от FastAPI.
То же самое произошло бы, если бы у вас было что-то вроде <abbr title='Union разных типов буквально означает "любой из перечисленных типов".'>Union</abbr> различных типов и один или несколько из них не являлись бы допустимыми типами для Pydantic. Например, такой вариант приведет к ошибке 💥:
-=== "Python 3.10+"
+//// tab | Python 3.10+
- ```Python hl_lines="8"
- {!> ../../../docs_src/response_model/tutorial003_04_py310.py!}
- ```
+```Python hl_lines="8"
+{!> ../../../docs_src/response_model/tutorial003_04_py310.py!}
+```
+
+////
-=== "Python 3.8+"
+//// tab | Python 3.8+
- ```Python hl_lines="10"
- {!> ../../../docs_src/response_model/tutorial003_04.py!}
- ```
+```Python hl_lines="10"
+{!> ../../../docs_src/response_model/tutorial003_04.py!}
+```
+
+////
...такой код вызовет ошибку, потому что в аннотации указан неподдерживаемый Pydantic тип. А также этот тип не является классом или подклассом `Response`.
В таком случае, вы можете отключить генерацию модели ответа, указав `response_model=None`:
-=== "Python 3.10+"
+//// tab | Python 3.10+
+
+```Python hl_lines="7"
+{!> ../../../docs_src/response_model/tutorial003_05_py310.py!}
+```
- ```Python hl_lines="7"
- {!> ../../../docs_src/response_model/tutorial003_05_py310.py!}
- ```
+////
-=== "Python 3.8+"
+//// tab | Python 3.8+
+
+```Python hl_lines="9"
+{!> ../../../docs_src/response_model/tutorial003_05.py!}
+```
- ```Python hl_lines="9"
- {!> ../../../docs_src/response_model/tutorial003_05.py!}
- ```
+////
Тогда FastAPI не станет генерировать модель ответа и вы сможете сохранить такую аннотацию типа, которая вам требуется, никак не влияя на работу FastAPI. 🤓
Модель ответа может иметь значения по умолчанию, например:
-=== "Python 3.10+"
+//// tab | Python 3.10+
- ```Python hl_lines="9 11-12"
- {!> ../../../docs_src/response_model/tutorial004_py310.py!}
- ```
+```Python hl_lines="9 11-12"
+{!> ../../../docs_src/response_model/tutorial004_py310.py!}
+```
+
+////
+
+//// tab | Python 3.9+
+
+```Python hl_lines="11 13-14"
+{!> ../../../docs_src/response_model/tutorial004_py39.py!}
+```
-=== "Python 3.9+"
+////
- ```Python hl_lines="11 13-14"
- {!> ../../../docs_src/response_model/tutorial004_py39.py!}
- ```
+//// tab | Python 3.8+
-=== "Python 3.8+"
+```Python hl_lines="11 13-14"
+{!> ../../../docs_src/response_model/tutorial004.py!}
+```
- ```Python hl_lines="11 13-14"
- {!> ../../../docs_src/response_model/tutorial004.py!}
- ```
+////
* `description: Union[str, None] = None` (или `str | None = None` в Python 3.10), где `None` является значением по умолчанию.
* `tax: float = 10.5`, где `10.5` является значением по умолчанию.
Установите для *декоратора операции пути* параметр `response_model_exclude_unset=True`:
-=== "Python 3.10+"
+//// tab | Python 3.10+
- ```Python hl_lines="22"
- {!> ../../../docs_src/response_model/tutorial004_py310.py!}
- ```
+```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!}
- ```
+//// tab | Python 3.9+
-=== "Python 3.8+"
+```Python hl_lines="24"
+{!> ../../../docs_src/response_model/tutorial004_py39.py!}
+```
- ```Python hl_lines="24"
- {!> ../../../docs_src/response_model/tutorial004.py!}
- ```
+////
+
+//// tab | Python 3.8+
+
+```Python hl_lines="24"
+{!> ../../../docs_src/response_model/tutorial004.py!}
+```
+
+////
и тогда значения по умолчанию не будут включены в ответ. В нем будут только те поля, значения которых фактически были установлены.
}
```
-!!! info "Информация"
- "Под капотом" FastAPI использует метод `.dict()` у объектов моделей Pydantic <a href="https://docs.pydantic.dev/latest/concepts/serialization/#modeldict" class="external-link" target="_blank">с параметром `exclude_unset`</a>, чтобы достичь такого эффекта.
+/// info | "Информация"
+
+"Под капотом" FastAPI использует метод `.dict()` у объектов моделей Pydantic <a href="https://docs.pydantic.dev/latest/concepts/serialization/#modeldict" class="external-link" target="_blank">с параметром `exclude_unset`</a>, чтобы достичь такого эффекта.
+
+///
+
+/// info | "Информация"
-!!! info "Информация"
- Вы также можете использовать:
+Вы также можете использовать:
- * `response_model_exclude_defaults=True`
- * `response_model_exclude_none=True`
+* `response_model_exclude_defaults=True`
+* `response_model_exclude_none=True`
- как описано в <a href="https://docs.pydantic.dev/latest/concepts/serialization/#modeldict" class="external-link" target="_blank">документации Pydantic</a> для параметров `exclude_defaults` и `exclude_none`.
+как описано в <a href="https://docs.pydantic.dev/latest/concepts/serialization/#modeldict" class="external-link" target="_blank">документации Pydantic</a> для параметров `exclude_defaults` и `exclude_none`.
+
+///
#### Если значение поля отличается от значения по-умолчанию
И поэтому, они также будут включены в JSON ответа.
-!!! tip "Подсказка"
- Значением по умолчанию может быть что угодно, не только `None`.
+/// tip | "Подсказка"
+
+Значением по умолчанию может быть что угодно, не только `None`.
+
+Им может быть и список (`[]`), значение 10.5 типа `float`, и т.п.
- Им может быть и список (`[]`), значение 10.5 типа `float`, и т.п.
+///
### `response_model_include` и `response_model_exclude`
Это можно использовать как быстрый способ исключить данные из ответа, не создавая отдельную модель Pydantic.
-!!! tip "Подсказка"
- Но по-прежнему рекомендуется следовать изложенным выше советам и использовать несколько моделей вместо данных параметров.
+/// tip | "Подсказка"
+
+Но по-прежнему рекомендуется следовать изложенным выше советам и использовать несколько моделей вместо данных параметров.
+
+Потому как JSON схема OpenAPI, генерируемая вашим приложением (а также документация) все еще будет содержать все поля, даже если вы использовали `response_model_include` или `response_model_exclude` и исключили некоторые атрибуты.
- Потому как JSON схема OpenAPI, генерируемая вашим приложением (а также документация) все еще будет содержать все поля, даже если вы использовали `response_model_include` или `response_model_exclude` и исключили некоторые атрибуты.
+То же самое применимо к параметру `response_model_by_alias`.
- То же самое применимо к параметру `response_model_by_alias`.
+///
-=== "Python 3.10+"
+//// tab | Python 3.10+
- ```Python hl_lines="29 35"
- {!> ../../../docs_src/response_model/tutorial005_py310.py!}
- ```
+```Python hl_lines="29 35"
+{!> ../../../docs_src/response_model/tutorial005_py310.py!}
+```
+
+////
+
+//// tab | Python 3.8+
+
+```Python hl_lines="31 37"
+{!> ../../../docs_src/response_model/tutorial005.py!}
+```
-=== "Python 3.8+"
+////
- ```Python hl_lines="31 37"
- {!> ../../../docs_src/response_model/tutorial005.py!}
- ```
+/// tip | "Подсказка"
-!!! tip "Подсказка"
- При помощи кода `{"name","description"}` создается объект множества (`set`) с двумя строковыми значениями.
+При помощи кода `{"name","description"}` создается объект множества (`set`) с двумя строковыми значениями.
- Того же самого можно достичь используя `set(["name", "description"])`.
+Того же самого можно достичь используя `set(["name", "description"])`.
+
+///
#### Что если использовать `list` вместо `set`?
Если вы забыли про `set` и использовали структуру `list` или `tuple`, FastAPI автоматически преобразует этот объект в `set`, чтобы обеспечить корректную работу:
-=== "Python 3.10+"
+//// tab | Python 3.10+
+
+```Python hl_lines="29 35"
+{!> ../../../docs_src/response_model/tutorial006_py310.py!}
+```
- ```Python hl_lines="29 35"
- {!> ../../../docs_src/response_model/tutorial006_py310.py!}
- ```
+////
-=== "Python 3.8+"
+//// tab | Python 3.8+
+
+```Python hl_lines="31 37"
+{!> ../../../docs_src/response_model/tutorial006.py!}
+```
- ```Python hl_lines="31 37"
- {!> ../../../docs_src/response_model/tutorial006.py!}
- ```
+////
## Резюме
{!../../../docs_src/response_status_code/tutorial001.py!}
```
-!!! note "Примечание"
- Обратите внимание, что `status_code` является атрибутом метода-декоратора (`get`, `post` и т.д.), а не *функции-обработчика пути* в отличие от всех остальных параметров и тела запроса.
+/// note | "Примечание"
+
+Обратите внимание, что `status_code` является атрибутом метода-декоратора (`get`, `post` и т.д.), а не *функции-обработчика пути* в отличие от всех остальных параметров и тела запроса.
+
+///
Параметр `status_code` принимает число, обозначающее HTTP код статуса ответа.
-!!! info "Информация"
- В качестве значения параметра `status_code` также может использоваться `IntEnum`, например, из библиотеки <a href="https://docs.python.org/3/library/http.html#http.HTTPStatus" class="external-link" target="_blank">`http.HTTPStatus`</a> в Python.
+/// info | "Информация"
+
+В качестве значения параметра `status_code` также может использоваться `IntEnum`, например, из библиотеки <a href="https://docs.python.org/3/library/http.html#http.HTTPStatus" class="external-link" target="_blank">`http.HTTPStatus`</a> в Python.
+
+///
Это позволит:
<img src="/img/tutorial/response-status-code/image01.png">
-!!! note "Примечание"
- Некоторые коды статуса ответа (см. следующий раздел) указывают на то, что ответ не имеет тела.
+/// note | "Примечание"
+
+Некоторые коды статуса ответа (см. следующий раздел) указывают на то, что ответ не имеет тела.
+
+FastAPI знает об этом и создаст документацию OpenAPI, в которой будет указано, что тело ответа отсутствует.
- FastAPI знает об этом и создаст документацию OpenAPI, в которой будет указано, что тело ответа отсутствует.
+///
## Об HTTP кодах статуса ответа
-!!! note "Примечание"
- Если вы уже знаете, что представляют собой HTTP коды статуса ответа, можете перейти к следующему разделу.
+/// note | "Примечание"
+
+Если вы уже знаете, что представляют собой HTTP коды статуса ответа, можете перейти к следующему разделу.
+
+///
В протоколе HTTP числовой код состояния из 3 цифр отправляется как часть ответа.
* Для общих ошибок со стороны клиента можно просто использовать код `400`.
* `5XX` – статус-коды, сообщающие о серверной ошибке. Они почти никогда не используются разработчиками напрямую. Когда что-то идет не так в какой-то части кода вашего приложения или на сервере, он автоматически вернёт один из 5XX кодов.
-!!! tip "Подсказка"
- Чтобы узнать больше о HTTP кодах статуса и о том, для чего каждый из них предназначен, ознакомьтесь с <a href="https://developer.mozilla.org/en-US/docs/Web/HTTP/Status" class="external-link" target="_blank">документацией <abbr title="Mozilla Developer Network">MDN</abbr> об HTTP кодах статуса ответа</a>.
+/// tip | "Подсказка"
+
+Чтобы узнать больше о HTTP кодах статуса и о том, для чего каждый из них предназначен, ознакомьтесь с <a href="https://developer.mozilla.org/en-US/docs/Web/HTTP/Status" class="external-link" target="_blank">документацией <abbr title="Mozilla Developer Network">MDN</abbr> об HTTP кодах статуса ответа</a>.
+
+///
## Краткие обозначения для запоминания названий кодов
<img src="/img/tutorial/response-status-code/image02.png">
-!!! note "Технические детали"
- Вы также можете использовать `from starlette import status` вместо `from fastapi import status`.
+/// note | "Технические детали"
+
+Вы также можете использовать `from starlette import status` вместо `from fastapi import status`.
+
+**FastAPI** позволяет использовать как `starlette.status`, так и `fastapi.status` исключительно для удобства разработчиков. Но поставляется fastapi.status непосредственно из Starlette.
- **FastAPI** позволяет использовать как `starlette.status`, так и `fastapi.status` исключительно для удобства разработчиков. Но поставляется fastapi.status непосредственно из Starlette.
+///
## Изменение кода статуса по умолчанию
Вы можете объявить ключ `example` для модели Pydantic, используя класс `Config` и переменную `schema_extra`, как описано в <a href="https://docs.pydantic.dev/latest/concepts/json_schema/#schema-customization" class="external-link" target="_blank">Pydantic документации: Настройка схемы</a>:
-=== "Python 3.10+"
+//// tab | Python 3.10+
- ```Python hl_lines="13-21"
- {!> ../../../docs_src/schema_extra_example/tutorial001_py310.py!}
- ```
+```Python hl_lines="13-21"
+{!> ../../../docs_src/schema_extra_example/tutorial001_py310.py!}
+```
-=== "Python 3.8+"
+////
- ```Python hl_lines="15-23"
- {!> ../../../docs_src/schema_extra_example/tutorial001.py!}
- ```
+//// tab | Python 3.8+
+
+```Python hl_lines="15-23"
+{!> ../../../docs_src/schema_extra_example/tutorial001.py!}
+```
+
+////
Эта дополнительная информация будет включена в **JSON Schema** выходных данных для этой модели, и она будет использоваться в документации к API.
-!!! tip Подсказка
- Вы можете использовать тот же метод для расширения JSON-схемы и добавления своей собственной дополнительной информации.
+/// tip | Подсказка
+
+Вы можете использовать тот же метод для расширения JSON-схемы и добавления своей собственной дополнительной информации.
+
+Например, вы можете использовать это для добавления дополнительной информации для пользовательского интерфейса в вашем веб-приложении и т.д.
- Например, вы можете использовать это для добавления дополнительной информации для пользовательского интерфейса в вашем веб-приложении и т.д.
+///
## Дополнительные аргументы поля `Field`
Вы можете использовать это, чтобы добавить аргумент `example` для каждого поля:
-=== "Python 3.10+"
+//// tab | Python 3.10+
+
+```Python hl_lines="2 8-11"
+{!> ../../../docs_src/schema_extra_example/tutorial002_py310.py!}
+```
+
+////
+
+//// tab | Python 3.8+
- ```Python hl_lines="2 8-11"
- {!> ../../../docs_src/schema_extra_example/tutorial002_py310.py!}
- ```
+```Python hl_lines="4 10-13"
+{!> ../../../docs_src/schema_extra_example/tutorial002.py!}
+```
-=== "Python 3.8+"
+////
- ```Python hl_lines="4 10-13"
- {!> ../../../docs_src/schema_extra_example/tutorial002.py!}
- ```
+/// warning | Внимание
-!!! warning Внимание
- Имейте в виду, что эти дополнительные переданные аргументы не добавляют никакой валидации, только дополнительную информацию для документации.
+Имейте в виду, что эти дополнительные переданные аргументы не добавляют никакой валидации, только дополнительную информацию для документации.
+
+///
## Использование `example` и `examples` в OpenAPI
Здесь мы передаём аргумент `example`, как пример данных ожидаемых в параметре `Body()`:
-=== "Python 3.10+"
+//// tab | Python 3.10+
+
+```Python hl_lines="22-27"
+{!> ../../../docs_src/schema_extra_example/tutorial003_an_py310.py!}
+```
+
+////
+
+//// tab | Python 3.9+
+
+```Python hl_lines="22-27"
+{!> ../../../docs_src/schema_extra_example/tutorial003_an_py39.py!}
+```
+
+////
+
+//// tab | Python 3.8+
- ```Python hl_lines="22-27"
- {!> ../../../docs_src/schema_extra_example/tutorial003_an_py310.py!}
- ```
+```Python hl_lines="23-28"
+{!> ../../../docs_src/schema_extra_example/tutorial003_an.py!}
+```
-=== "Python 3.9+"
+////
- ```Python hl_lines="22-27"
- {!> ../../../docs_src/schema_extra_example/tutorial003_an_py39.py!}
- ```
+//// tab | Python 3.10+ non-Annotated
-=== "Python 3.8+"
+/// tip | Заметка
- ```Python hl_lines="23-28"
- {!> ../../../docs_src/schema_extra_example/tutorial003_an.py!}
- ```
+Рекомендуется использовать версию с `Annotated`, если это возможно.
-=== "Python 3.10+ non-Annotated"
+///
- !!! tip Заметка
- Рекомендуется использовать версию с `Annotated`, если это возможно.
+```Python hl_lines="18-23"
+{!> ../../../docs_src/schema_extra_example/tutorial003_py310.py!}
+```
- ```Python hl_lines="18-23"
- {!> ../../../docs_src/schema_extra_example/tutorial003_py310.py!}
- ```
+////
-=== "Python 3.8+ non-Annotated"
+//// tab | Python 3.8+ non-Annotated
- !!! tip Заметка
- Рекомендуется использовать версию с `Annotated`, если это возможно.
+/// tip | Заметка
- ```Python hl_lines="20-25"
- {!> ../../../docs_src/schema_extra_example/tutorial003.py!}
- ```
+Рекомендуется использовать версию с `Annotated`, если это возможно.
+
+///
+
+```Python hl_lines="20-25"
+{!> ../../../docs_src/schema_extra_example/tutorial003.py!}
+```
+
+////
### Аргумент "example" в UI документации
* `value`: Это конкретный пример, который отображается, например, в виде типа `dict`.
* `externalValue`: альтернатива параметру `value`, URL-адрес, указывающий на пример. Хотя это может не поддерживаться таким же количеством инструментов разработки и тестирования API, как параметр `value`.
-=== "Python 3.10+"
+//// tab | Python 3.10+
+
+```Python hl_lines="23-49"
+{!> ../../../docs_src/schema_extra_example/tutorial004_an_py310.py!}
+```
+
+////
+
+//// tab | Python 3.9+
+
+```Python hl_lines="23-49"
+{!> ../../../docs_src/schema_extra_example/tutorial004_an_py39.py!}
+```
- ```Python hl_lines="23-49"
- {!> ../../../docs_src/schema_extra_example/tutorial004_an_py310.py!}
- ```
+////
-=== "Python 3.9+"
+//// tab | Python 3.8+
- ```Python hl_lines="23-49"
- {!> ../../../docs_src/schema_extra_example/tutorial004_an_py39.py!}
- ```
+```Python hl_lines="24-50"
+{!> ../../../docs_src/schema_extra_example/tutorial004_an.py!}
+```
-=== "Python 3.8+"
+////
- ```Python hl_lines="24-50"
- {!> ../../../docs_src/schema_extra_example/tutorial004_an.py!}
- ```
+//// tab | Python 3.10+ non-Annotated
-=== "Python 3.10+ non-Annotated"
+/// tip | Заметка
- !!! tip Заметка
- Рекомендуется использовать версию с `Annotated`, если это возможно.
+Рекомендуется использовать версию с `Annotated`, если это возможно.
- ```Python hl_lines="19-45"
- {!> ../../../docs_src/schema_extra_example/tutorial004_py310.py!}
- ```
+///
-=== "Python 3.8+ non-Annotated"
+```Python hl_lines="19-45"
+{!> ../../../docs_src/schema_extra_example/tutorial004_py310.py!}
+```
- !!! tip Заметка
- Рекомендуется использовать версию с `Annotated`, если это возможно.
+////
- ```Python hl_lines="21-47"
- {!> ../../../docs_src/schema_extra_example/tutorial004.py!}
- ```
+//// tab | Python 3.8+ non-Annotated
+
+/// tip | Заметка
+
+Рекомендуется использовать версию с `Annotated`, если это возможно.
+
+///
+
+```Python hl_lines="21-47"
+{!> ../../../docs_src/schema_extra_example/tutorial004.py!}
+```
+
+////
### Аргумент "examples" в UI документации
## Технические Детали
-!!! warning Внимание
- Эти технические детали относятся к стандартам **JSON Schema** и **OpenAPI**.
+/// warning | Внимание
+
+Эти технические детали относятся к стандартам **JSON Schema** и **OpenAPI**.
+
+Если предложенные выше идеи уже работают для вас, возможно этого будет достаточно и эти детали вам не потребуются, можете спокойно их пропустить.
- Если предложенные выше идеи уже работают для вас, возможно этого будет достаточно и эти детали вам не потребуются, можете спокойно их пропустить.
+///
Когда вы добавляете пример внутрь модели Pydantic, используя `schema_extra` или `Field(example="something")`, этот пример добавляется в **JSON Schema** для данной модели Pydantic.
Скопируйте пример в файл `main.py`:
-=== "Python 3.9+"
+//// tab | Python 3.9+
- ```Python
- {!> ../../../docs_src/security/tutorial001_an_py39.py!}
- ```
+```Python
+{!> ../../../docs_src/security/tutorial001_an_py39.py!}
+```
+
+////
+
+//// tab | Python 3.8+
+
+```Python
+{!> ../../../docs_src/security/tutorial001_an.py!}
+```
+
+////
-=== "Python 3.8+"
+//// tab | Python 3.8+ без Annotated
- ```Python
- {!> ../../../docs_src/security/tutorial001_an.py!}
- ```
+/// tip | "Подсказка"
-=== "Python 3.8+ без Annotated"
+Предпочтительнее использовать версию с аннотацией, если это возможно.
- !!! tip "Подсказка"
- Предпочтительнее использовать версию с аннотацией, если это возможно.
+///
- ```Python
- {!> ../../../docs_src/security/tutorial001.py!}
- ```
+```Python
+{!> ../../../docs_src/security/tutorial001.py!}
+```
+////
## Запуск
-!!! info "Дополнительная информация"
- Вначале, установите библиотеку <a href="https://github.com/Kludex/python-multipart" class="external-link" target="_blank">`python-multipart`</a>.
+/// info | "Дополнительная информация"
- А именно: `pip install python-multipart`.
+Вначале, установите библиотеку <a href="https://github.com/Kludex/python-multipart" class="external-link" target="_blank">`python-multipart`</a>.
- Это связано с тем, что **OAuth2** использует "данные формы" для передачи `имени пользователя` и `пароля`.
+А именно: `pip install python-multipart`.
+
+Это связано с тем, что **OAuth2** использует "данные формы" для передачи `имени пользователя` и `пароля`.
+
+///
Запустите ваш сервер:
<img src="/img/tutorial/security/image01.png">
-!!! check "Кнопка авторизации!"
- У вас уже появилась новая кнопка "Authorize".
+/// check | "Кнопка авторизации!"
+
+У вас уже появилась новая кнопка "Authorize".
- А у *операции пути* теперь появился маленький замочек в правом верхнем углу, на который можно нажать.
+А у *операции пути* теперь появился маленький замочек в правом верхнем углу, на который можно нажать.
+
+///
При нажатии на нее появляется небольшая форма авторизации, в которую нужно ввести `имя пользователя` и `пароль` (и другие необязательные поля):
<img src="/img/tutorial/security/image02.png">
-!!! note "Технические детали"
- Неважно, что вы введете в форму, она пока не будет работать. Но мы к этому еще придем.
+/// note | "Технические детали"
+
+Неважно, что вы введете в форму, она пока не будет работать. Но мы к этому еще придем.
+
+///
Конечно, это не фронтенд для конечных пользователей, но это отличный автоматический инструмент для интерактивного документирования всех ваших API.
В данном примере мы будем использовать **OAuth2**, с аутентификацией по паролю, используя токен **Bearer**. Для этого мы используем класс `OAuth2PasswordBearer`.
-!!! info "Дополнительная информация"
- Токен "bearer" - не единственный вариант, но для нашего случая он является наилучшим.
+/// info | "Дополнительная информация"
+
+Токен "bearer" - не единственный вариант, но для нашего случая он является наилучшим.
+
+И это может быть лучшим вариантом для большинства случаев использования, если только вы не являетесь экспертом в области OAuth2 и точно знаете, почему вам лучше подходит какой-то другой вариант.
- И это может быть лучшим вариантом для большинства случаев использования, если только вы не являетесь экспертом в области OAuth2 и точно знаете, почему вам лучше подходит какой-то другой вариант.
+В этом случае **FastAPI** также предоставляет инструменты для его реализации.
- В этом случае **FastAPI** также предоставляет инструменты для его реализации.
+///
При создании экземпляра класса `OAuth2PasswordBearer` мы передаем в него параметр `tokenUrl`. Этот параметр содержит URL, который клиент (фронтенд, работающий в браузере пользователя) будет использовать для отправки `имени пользователя` и `пароля` с целью получения токена.
-=== "Python 3.9+"
+//// tab | Python 3.9+
+
+```Python hl_lines="8"
+{!> ../../../docs_src/security/tutorial001_an_py39.py!}
+```
+
+////
+
+//// tab | Python 3.8+
+
+```Python hl_lines="7"
+{!> ../../../docs_src/security/tutorial001_an.py!}
+```
+
+////
- ```Python hl_lines="8"
- {!> ../../../docs_src/security/tutorial001_an_py39.py!}
- ```
+//// tab | Python 3.8+ без Annotated
-=== "Python 3.8+"
+/// tip | "Подсказка"
- ```Python hl_lines="7"
- {!> ../../../docs_src/security/tutorial001_an.py!}
- ```
+Предпочтительнее использовать версию с аннотацией, если это возможно.
-=== "Python 3.8+ без Annotated"
+///
- !!! tip "Подсказка"
- Предпочтительнее использовать версию с аннотацией, если это возможно.
+```Python hl_lines="6"
+{!> ../../../docs_src/security/tutorial001.py!}
+```
+
+////
+
+/// tip | "Подсказка"
- ```Python hl_lines="6"
- {!> ../../../docs_src/security/tutorial001.py!}
- ```
+Здесь `tokenUrl="token"` ссылается на относительный URL `token`, который мы еще не создали. Поскольку это относительный URL, он эквивалентен `./token`.
-!!! tip "Подсказка"
- Здесь `tokenUrl="token"` ссылается на относительный URL `token`, который мы еще не создали. Поскольку это относительный URL, он эквивалентен `./token`.
+Поскольку мы используем относительный URL, если ваш API расположен по адресу `https://example.com/`, то он будет ссылаться на `https://example.com/token`. Если же ваш API расположен по адресу `https://example.com/api/v1/`, то он будет ссылаться на `https://example.com/api/v1/token`.
- Поскольку мы используем относительный URL, если ваш API расположен по адресу `https://example.com/`, то он будет ссылаться на `https://example.com/token`. Если же ваш API расположен по адресу `https://example.com/api/v1/`, то он будет ссылаться на `https://example.com/api/v1/token`.
+Использование относительного URL важно для того, чтобы ваше приложение продолжало работать даже в таких сложных случаях, как оно находится [за прокси-сервером](../../advanced/behind-a-proxy.md){.internal-link target=_blank}.
- Использование относительного URL важно для того, чтобы ваше приложение продолжало работать даже в таких сложных случаях, как оно находится [за прокси-сервером](../../advanced/behind-a-proxy.md){.internal-link target=_blank}.
+///
Этот параметр не создает конечную точку / *операцию пути*, а объявляет, что URL `/token` будет таким, который клиент должен использовать для получения токена. Эта информация используется в OpenAPI, а затем в интерактивных системах документации API.
Вскоре мы создадим и саму операцию пути.
-!!! info "Дополнительная информация"
- Если вы очень строгий "питонист", то вам может не понравиться стиль названия параметра `tokenUrl` вместо `token_url`.
+/// info | "Дополнительная информация"
+
+Если вы очень строгий "питонист", то вам может не понравиться стиль названия параметра `tokenUrl` вместо `token_url`.
+
+Это связано с тем, что тут используется то же имя, что и в спецификации OpenAPI. Таким образом, если вам необходимо более подробно изучить какую-либо из этих схем безопасности, вы можете просто использовать копирование/вставку, чтобы найти дополнительную информацию о ней.
- Это связано с тем, что тут используется то же имя, что и в спецификации OpenAPI. Таким образом, если вам необходимо более подробно изучить какую-либо из этих схем безопасности, вы можете просто использовать копирование/вставку, чтобы найти дополнительную информацию о ней.
+///
Переменная `oauth2_scheme` является экземпляром `OAuth2PasswordBearer`, но она также является "вызываемой".
Теперь вы можете передать ваш `oauth2_scheme` в зависимость с помощью `Depends`.
-=== "Python 3.9+"
+//// tab | Python 3.9+
- ```Python hl_lines="12"
- {!> ../../../docs_src/security/tutorial001_an_py39.py!}
- ```
+```Python hl_lines="12"
+{!> ../../../docs_src/security/tutorial001_an_py39.py!}
+```
+
+////
+
+//// tab | Python 3.8+
+
+```Python hl_lines="11"
+{!> ../../../docs_src/security/tutorial001_an.py!}
+```
-=== "Python 3.8+"
+////
- ```Python hl_lines="11"
- {!> ../../../docs_src/security/tutorial001_an.py!}
- ```
+//// tab | Python 3.8+ без Annotated
-=== "Python 3.8+ без Annotated"
+/// tip | "Подсказка"
- !!! tip "Подсказка"
- Предпочтительнее использовать версию с аннотацией, если это возможно.
+Предпочтительнее использовать версию с аннотацией, если это возможно.
- ```Python hl_lines="10"
- {!> ../../../docs_src/security/tutorial001.py!}
- ```
+///
+
+```Python hl_lines="10"
+{!> ../../../docs_src/security/tutorial001.py!}
+```
+
+////
Эта зависимость будет предоставлять `строку`, которая присваивается параметру `token` в *функции операции пути*.
**FastAPI** будет знать, что он может использовать эту зависимость для определения "схемы безопасности" в схеме OpenAPI (и автоматической документации по API).
-!!! info "Технические детали"
- **FastAPI** будет знать, что он может использовать класс `OAuth2PasswordBearer` (объявленный в зависимости) для определения схемы безопасности в OpenAPI, поскольку он наследуется от `fastapi.security.oauth2.OAuth2`, который, в свою очередь, наследуется от `fastapi.security.base.SecurityBase`.
+/// info | "Технические детали"
+
+**FastAPI** будет знать, что он может использовать класс `OAuth2PasswordBearer` (объявленный в зависимости) для определения схемы безопасности в OpenAPI, поскольку он наследуется от `fastapi.security.oauth2.OAuth2`, который, в свою очередь, наследуется от `fastapi.security.base.SecurityBase`.
+
+Все утилиты безопасности, интегрируемые в OpenAPI (и автоматическая документация по API), наследуются от `SecurityBase`, поэтому **FastAPI** может знать, как интегрировать их в OpenAPI.
- Все утилиты безопасности, интегрируемые в OpenAPI (и автоматическая документация по API), наследуются от `SecurityBase`, поэтому **FastAPI** может знать, как интегрировать их в OpenAPI.
+///
## Что он делает
OAuth2 не указывает, как шифровать сообщение, он ожидает, что ваше приложение будет обслуживаться по протоколу HTTPS.
-!!! tip "Подсказка"
- В разделе **Развертывание** вы увидите [как настроить протокол HTTPS бесплатно, используя Traefik и Let's Encrypt.](https://fastapi.tiangolo.com/ru/deployment/https/)
+/// tip | "Подсказка"
+В разделе **Развертывание** вы увидите [как настроить протокол HTTPS бесплатно, используя Traefik и Let's Encrypt.](https://fastapi.tiangolo.com/ru/deployment/https/)
+
+///
## OpenID Connect
* Это автоматическое обнаружение определено в спецификации OpenID Connect.
-!!! tip "Подсказка"
- Интеграция сторонних сервисов для аутентификации/авторизации таких как Google, Facebook, Twitter, GitHub и т.д. осуществляется достаточно легко.
+/// tip | "Подсказка"
+
+Интеграция сторонних сервисов для аутентификации/авторизации таких как Google, Facebook, Twitter, GitHub и т.д. осуществляется достаточно легко.
+
+Самой сложной проблемой является создание такого провайдера аутентификации/авторизации, но **FastAPI** предоставляет вам инструменты, позволяющие легко это сделать, выполняя при этом всю тяжелую работу за вас.
- Самой сложной проблемой является создание такого провайдера аутентификации/авторизации, но **FastAPI** предоставляет вам инструменты, позволяющие легко это сделать, выполняя при этом всю тяжелую работу за вас.
+///
## Преимущества **FastAPI**
{!../../../docs_src/static_files/tutorial001.py!}
```
-!!! note "Технические детали"
- Вы также можете использовать `from starlette.staticfiles import StaticFiles`.
+/// note | "Технические детали"
- **FastAPI** предоставляет `starlette.staticfiles` под псевдонимом `fastapi.staticfiles`, просто для вашего удобства, как разработчика. Но на самом деле это берётся напрямую из библиотеки Starlette.
+Вы также можете использовать `from starlette.staticfiles import StaticFiles`.
+
+**FastAPI** предоставляет `starlette.staticfiles` под псевдонимом `fastapi.staticfiles`, просто для вашего удобства, как разработчика. Но на самом деле это берётся напрямую из библиотеки Starlette.
+
+///
### Что такое "Монтирование"
## Использование класса `TestClient`
-!!! info "Информация"
- Для использования класса `TestClient` необходимо установить библиотеку <a href="https://www.python-httpx.org" class="external-link" target="_blank">`httpx`</a>.
+/// info | "Информация"
- Например, так: `pip install httpx`.
+Для использования класса `TestClient` необходимо установить библиотеку <a href="https://www.python-httpx.org" class="external-link" target="_blank">`httpx`</a>.
+
+Например, так: `pip install httpx`.
+
+///
Импортируйте `TestClient`.
{!../../../docs_src/app_testing/tutorial001.py!}
```
-!!! tip "Подсказка"
- Обратите внимание, что тестирующая функция является обычной `def`, а не асинхронной `async def`.
+/// tip | "Подсказка"
+
+Обратите внимание, что тестирующая функция является обычной `def`, а не асинхронной `async def`.
+
+И вызов клиента также осуществляется без `await`.
+
+Это позволяет вам использовать `pytest` без лишних усложнений.
+
+///
+
+/// note | "Технические детали"
+
+Также можно написать `from starlette.testclient import TestClient`.
- И вызов клиента также осуществляется без `await`.
+**FastAPI** предоставляет тот же самый `starlette.testclient` как `fastapi.testclient`. Это всего лишь небольшое удобство для Вас, как разработчика.
- Это позволяет вам использовать `pytest` без лишних усложнений.
+///
-!!! note "Технические детали"
- Также можно написать `from starlette.testclient import TestClient`.
+/// tip | "Подсказка"
- **FastAPI** предоставляет тот же самый `starlette.testclient` как `fastapi.testclient`. Это всего лишь небольшое удобство для Вас, как разработчика.
+Если для тестирования Вам, помимо запросов к приложению FastAPI, необходимо вызывать асинхронные функции (например, для подключения к базе данных с помощью асинхронного драйвера), то ознакомьтесь со страницей [Асинхронное тестирование](../advanced/async-tests.md){.internal-link target=_blank} в расширенном руководстве.
-!!! tip "Подсказка"
- Если для тестирования Вам, помимо запросов к приложению FastAPI, необходимо вызывать асинхронные функции (например, для подключения к базе данных с помощью асинхронного драйвера), то ознакомьтесь со страницей [Асинхронное тестирование](../advanced/async-tests.md){.internal-link target=_blank} в расширенном руководстве.
+///
## Разделение тестов и приложения
Обе *операции пути* требуют наличия в запросе заголовка `X-Token`.
-=== "Python 3.10+"
+//// tab | Python 3.10+
- ```Python
- {!> ../../../docs_src/app_testing/app_b_an_py310/main.py!}
- ```
+```Python
+{!> ../../../docs_src/app_testing/app_b_an_py310/main.py!}
+```
-=== "Python 3.9+"
+////
- ```Python
- {!> ../../../docs_src/app_testing/app_b_an_py39/main.py!}
- ```
+//// tab | Python 3.9+
-=== "Python 3.8+"
+```Python
+{!> ../../../docs_src/app_testing/app_b_an_py39/main.py!}
+```
- ```Python
- {!> ../../../docs_src/app_testing/app_b_an/main.py!}
- ```
+////
-=== "Python 3.10+ без Annotated"
+//// tab | Python 3.8+
+
+```Python
+{!> ../../../docs_src/app_testing/app_b_an/main.py!}
+```
- !!! tip "Подсказка"
- По возможности используйте версию с `Annotated`.
+////
- ```Python
- {!> ../../../docs_src/app_testing/app_b_py310/main.py!}
- ```
+//// tab | Python 3.10+ без Annotated
-=== "Python 3.8+ без Annotated"
+/// tip | "Подсказка"
- !!! tip "Подсказка"
- По возможности используйте версию с `Annotated`.
+По возможности используйте версию с `Annotated`.
- ```Python
- {!> ../../../docs_src/app_testing/app_b/main.py!}
- ```
+///
+
+```Python
+{!> ../../../docs_src/app_testing/app_b_py310/main.py!}
+```
+
+////
+
+//// tab | Python 3.8+ без Annotated
+
+/// tip | "Подсказка"
+
+По возможности используйте версию с `Annotated`.
+
+///
+
+```Python
+{!> ../../../docs_src/app_testing/app_b/main.py!}
+```
+
+////
### Расширенный файл тестов
Для получения дополнительной информации о передаче данных на бэкенд с помощью `httpx` или `TestClient` ознакомьтесь с <a href="https://www.python-httpx.org" class="external-link" target="_blank">документацией HTTPX</a>.
-!!! info "Информация"
- Обратите внимание, что `TestClient` принимает данные, которые можно конвертировать в JSON, но не модели Pydantic.
+/// info | "Информация"
+
+Обратите внимание, что `TestClient` принимает данные, которые можно конвертировать в JSON, но не модели Pydantic.
+
+Если в Ваших тестах есть модели Pydantic и Вы хотите отправить их в тестируемое приложение, то можете использовать функцию `jsonable_encoder`, описанную на странице [Кодировщик совместимый с JSON](encoder.md){.internal-link target=_blank}.
- Если в Ваших тестах есть модели Pydantic и Вы хотите отправить их в тестируемое приложение, то можете использовать функцию `jsonable_encoder`, описанную на странице [Кодировщик совместимый с JSON](encoder.md){.internal-link target=_blank}.
+///
## Запуск тестов
İ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**.
+/// tip | "İpucu"
- Kullanım şeklinize bağlı olarak, çözümünüz bu bölümlerden birinde olabilir.
+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: 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**.
+/// tip | "İpucu"
- Kullanım şeklinize bağlı olarak, çözümünüz bu bölümlerden birinde olabilir.
+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
{!../../../docs_src/app_testing/tutorial002.py!}
```
-!!! note "Not"
- Daha fazla detay için Starlette'in <a href="https://www.starlette.io/staticfiles/" class="external-link" target="_blank">Websockets'i Test Etmek</a> dokümantasyonunu inceleyin.
+/// note | "Not"
+
+Daha fazla detay için Starlette'in <a href="https://www.starlette.io/staticfiles/" class="external-link" target="_blank">Websockets'i Test Etmek</a> dokümantasyonunu inceleyin.
+
+///
**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.
+/// note | "Not"
-!!! 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ı.
+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ı.
+
+///
### <a href="https://flask.palletsprojects.com" class="external-link" target="_blank">Flask</a>
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ı.
+/// check | "**FastAPI**'a nasıl ilham verdi?"
- Basit ve kullanması kolay bir <abbr title="Yönlendirme: Routing">yönlendirme sistemine</abbr> sahip olmalı.
+Gereken araçları ve parçaları birleştirip eşleştirmeyi kolaylaştıracak bir mikro framework olmalı.
+
+Basit ve kullanması kolay bir <abbr title="Yönlendirme: Routing">yönlendirme sistemine</abbr> sahip olmalı.
+
+///
### <a href="https://requests.readthedocs.io" class="external-link" target="_blank">Requests</a>
`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ı.
+/// 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ı.
+
+///
### <a href="https://swagger.io/" class="external-link" target="_blank">Swagger</a> / <a href="https://github.com/OAI/OpenAPI-Specification/" class="external-link" target="_blank">OpenAPI</a>
İş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 <abbr title="Open Standard: Açık Standart, Açık kaynak olarak yayınlanan standart">açık standart</abbr> benimseyip kullanmalı.
+/// check | "**FastAPI**'a nasıl ilham verdi?"
+
+API spesifikasyonları için özel bir şema yerine bir <abbr title="Open Standard: Açık Standart, Açık kaynak olarak yayınlanan standart">açık standart</abbr> benimseyip kullanmalı.
+
+Ayrıca standarda bağlı kullanıcı arayüzü araçlarını entegre etmeli:
- Ayrıca standarda bağlı kullanıcı arayüzü araçlarını entegre etmeli:
+* <a href="https://github.com/swagger-api/swagger-ui" class="external-link" target="_blank">Swagger UI</a>
+* <a href="https://github.com/Rebilly/ReDoc" class="external-link" target="_blank">ReDoc</a>
- * <a href="https://github.com/swagger-api/swagger-ui" class="external-link" target="_blank">Swagger UI</a>
- * <a href="https://github.com/Rebilly/ReDoc" class="external-link" target="_blank">ReDoc</a>
+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.
- 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
Ama... Python'un tip belirteçleri gelmeden önce oluşturulmuştu. Yani her <abbr title="Verilerin nasıl oluşturulması gerektiğinin tanımı">şemayı</abbr> 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ı.
+/// check | "**FastAPI**'a nasıl ilham verdi?"
+
+Kod kullanarak otomatik olarak veri tipini ve veri doğrulamayı belirten "şemalar" tanımlamalı.
+
+///
### <a href="https://webargs.readthedocs.io/en/latest/" class="external-link" target="_blank">Webargs</a>
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.
+/// 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ı.
+///
+
+/// check | "**FastAPI**'a nasıl ilham verdi?"
+
+Gelen istek verisi için otomatik veri doğrulamaya sahip olmalı.
+
+///
### <a href="https://apispec.readthedocs.io/en/stable/" class="external-link" target="_blank">APISpec</a>
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.
+/// info | "Bilgi"
+
+APISpec de aynı Marshmallow geliştiricileri tarafından oluşturuldu.
+
+///
+
+/// check | "**FastAPI**'a nasıl ilham verdi?"
-!!! check "**FastAPI**'a nasıl ilham verdi?"
- API'lar için açık standart desteği olmalı (OpenAPI gibi).
+API'lar için açık standart desteği olmalı (OpenAPI gibi).
+
+///
### <a href="https://flask-apispec.readthedocs.io/en/latest/" class="external-link" target="_blank">Flask-apispec</a>
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.
+/// 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ı.
+/// 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ı.
+
+///
### <a href="https://nestjs.com/" class="external-link" target="_blank">NestJS</a> (and <a href="https://angular.io/" class="external-link" target="_blank">Angular</a>)
İç 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ı.
+/// 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ı.
+Güçlü bir bağımlılık enjeksiyon sistemine sahip olmalı. Kod tekrarını minimuma indirecek bir yol bulmalı.
+
+///
### <a href="https://sanic.readthedocs.io/en/latest/" class="external-link" target="_blank">Sanic</a>
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 <a href="https://github.com/MagicStack/uvloop" class="external-link" target="_blank">`uvloop`</a> kullanıldı. Hızının asıl kaynağı buydu.
+/// note | "Teknik detaylar"
+
+İçerisinde standart Python `asyncio` döngüsü yerine <a href="https://github.com/MagicStack/uvloop" class="external-link" target="_blank">`uvloop`</a> 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.
- 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ı.
+/// check | "**FastAPI**'a nasıl ilham oldu?"
- 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)
+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)
+
+///
### <a href="https://falconframework.org/" class="external-link" target="_blank">Falcon</a>
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ı.
+/// 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.
+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.
+FastAPI'da opsiyonel olmasına rağmen, daha çok header'lar, çerezler ve alternatif durum kodları belirlemede kullanılıyor.
+
+///
### <a href="https://moltenframework.com/" class="external-link" target="_blank">Molten</a>
<abbr title="Route: HTTP isteğinin gittiği yol">Yol</abbr>'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.
+/// 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.
- 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.
+///
### <a href="https://www.hug.rest/" class="external-link" target="_blank">Hug</a>
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 <a href="https://github.com/timothycrosley/isort" class="external-link" target="_blank">`isort`</a>'un geliştiricisi Timothy Crosley tarafından geliştirildi.
+/// info | "Bilgi"
+
+Hug, Python dosyalarında bulunan dahil etme satırlarını otomatik olarak sıralayan harika bir araç olan <a href="https://github.com/timothycrosley/isort" class="external-link" target="_blank">`isort`</a>'un geliştiricisi Timothy Crosley tarafından geliştirildi.
+
+///
+
+/// check | "**FastAPI**'a nasıl ilham oldu?"
-!!! 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.
+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**, 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ı.
+**FastAPI**'ın header ve çerez tanımlamak için fonksiyonlarda `response` parametresini belirtmesinde de Hug'dan ilham alındı.
+
+///
### <a href="https://github.com/encode/apistar" class="external-link" target="_blank">APIStar</a> (<= 0.5)
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:
+/// 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
- * 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.
+/// check | "**FastAPI**'a nasıl ilham 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.
+Var oldu.
- Uzunca bir süre boyunca benzer bir framework arayıp pek çok farklı alternatifi denedikten sonra, APIStar en iyi seçenekti.
+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.
- 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ı.
+Uzunca bir süre boyunca benzer bir framework arayıp pek çok farklı alternatifi denedikten sonra, APIStar en iyi seçenekti.
- Ben bu önceki araçlardan öğrendiklerime dayanarak **FastAPI**'ın özelliklerini arttırıp geliştiriyor, <abbr title="Tip desteği (typing support): kod yapısında parametrelere, argümanlara ve objelerin özelliklerine veri tipi atamak">tip desteği</abbr> sistemi ve diğer kısımları iyileştiriyorum ancak yine de **FastAPI**'ı APIStar'ın "ruhani varisi" olarak görüyorum.
+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, <abbr title="Tip desteği (typing support): kod yapısında parametrelere, argümanlara ve objelerin özelliklerine veri tipi atamak">tip desteği</abbr> 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
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!
+/// 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.
+**FastAPI** yaptığı her şeyin yanı sıra bu JSON Şema verisini alıp daha sonra OpenAPI'ya yerleştiriyor.
+
+///
### <a href="https://www.starlette.io/" class="external-link" target="_blank">Starlette</a>
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.
+/// 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.
- 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?"
+/// check | "**FastAPI** nerede kullanıyor?"
- Tüm temel web kısımlarında üzerine özellikler eklenerek kullanılmakta.
+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!
+`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.
+Yani, Starlette ile yapabileceğiniz her şeyi, Starlette'in bir nevi güçlendirilmiş hali olan **FastAPI** ile doğrudan yapabilirsiniz.
+
+///
### <a href="https://www.uvicorn.org/" class="external-link" target="_blank">Uvicorn</a>
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!
+/// 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!
- 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.
- 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
return results
```
-!!! note "Not"
- Sadece `async def` ile tanımlanan fonksiyonlar içinde `await` kullanabilirsiniz.
+/// note | "Not"
+
+Sadece `async def` ile tanımlanan fonksiyonlar içinde `await` kullanabilirsiniz.
+
+///
---
## Çok Teknik Detaylar
-!!! warning
- Muhtemelen burayı atlayabilirsiniz.
+/// warning
+
+Muhtemelen burayı atlayabilirsiniz.
+
+Bunlar, **FastAPI**'nin altta nasıl çalıştığına dair çok teknik ayrıntılardır.
- 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.
- 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
Bunlardan bazılarının tamamlanmamış bir listesi aşağıda bulunmaktadır.
-!!! tip "İpucu"
- Eğer **FastAPI** ile alakalı henüz burada listelenmemiş bir makale, proje, araç veya başka bir şeyiniz varsa, bunu eklediğiniz bir <a href="https://github.com/fastapi/fastapi/edit/master/docs/en/data/external_links.yml" class="external-link" target="_blank">Pull Request</a> oluşturabilirsiniz.
+/// tip | "İpucu"
+
+Eğer **FastAPI** ile alakalı henüz burada listelenmemiş bir makale, proje, araç veya başka bir şeyiniz varsa, bunu eklediğiniz bir <a href="https://github.com/fastapi/fastapi/edit/master/docs/en/data/external_links.yml" class="external-link" target="_blank">Pull Request</a> oluşturabilirsiniz.
+
+///
{% for section_name, section_content in external_links.items() %}
my_second_user: User = User(**second_user_data)
```
-!!! info
- `**second_user_data` şu anlama geliyor:
+/// info
- Key-Value çiftini direkt olarak `second_user_data` dictionarysine kaydet , yaptığın şey buna eşit olacak: `User(id=4, name="Mary", joined="2018-11-30")`
+`**second_user_data` şu anlama geliyor:
+
+Key-Value çiftini direkt olarak `second_user_data` dictionarysine kaydet , yaptığın şey buna eşit olacak: `User(id=4, name="Mary", joined="2018-11-30")`
+
+///
### Editor desteği
Projeniz için ilginç ve yararlı görünen bir şey varsa devam edin ve inceleyin, aksi halde bunları atlayabilirsiniz.
-!!! tip "İpucu"
+/// 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.
+**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.
+
+///
**FastAPI** kullanmayacak olsanız bile tür belirteçleri hakkında bilgi edinmenizde fayda var.
-!!! note "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
{!../../../docs_src/python_types/tutorial006.py!}
```
-!!! tip "Ipucu"
- Köşeli parantez içindeki bu dahili tiplere "tip parametreleri" denir.
+/// tip | "Ipucu"
+
+Köşeli parantez içindeki bu dahili tiplere "tip parametreleri" denir.
+
+Bu durumda `str`, `List`e iletilen tür parametresidir.
- 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".
{!../../../docs_src/python_types/tutorial011.py!}
```
-!!! info
- Daha fazla şey öğrenmek için <a href="https://docs.pydantic.dev/" class="external-link" target="_blank">Pydantic'i takip edin</a>.
+/// info
+
+Daha fazla şey öğrenmek için <a href="https://docs.pydantic.dev/" class="external-link" target="_blank">Pydantic'i takip edin</a>.
+
+///
**FastAPI** tamamen Pydantic'e dayanmaktadır.
Ö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:<a href="https://mypy.readthedocs.io/en/latest/cheat_sheet_py3.html" class="external-link" target="_blank"> the "cheat sheet" from `mypy`</a>.
+/// info
+
+Tüm öğreticiyi zaten okuduysanız ve türler hakkında daha fazla bilgi için geri döndüyseniz, iyi bir kaynak:<a href="https://mypy.readthedocs.io/en/latest/cheat_sheet_py3.html" class="external-link" target="_blank"> the "cheat sheet" from `mypy`</a>.
+
+///
Öncelikle, `Cookie`'yi projenize dahil edin:
-=== "Python 3.10+"
+//// tab | Python 3.10+
- ```Python hl_lines="3"
- {!> ../../../docs_src/cookie_params/tutorial001_an_py310.py!}
- ```
+```Python hl_lines="3"
+{!> ../../../docs_src/cookie_params/tutorial001_an_py310.py!}
+```
-=== "Python 3.9+"
+////
- ```Python hl_lines="3"
- {!> ../../../docs_src/cookie_params/tutorial001_an_py39.py!}
- ```
+//// tab | Python 3.9+
-=== "Python 3.8+"
+```Python hl_lines="3"
+{!> ../../../docs_src/cookie_params/tutorial001_an_py39.py!}
+```
- ```Python hl_lines="3"
- {!> ../../../docs_src/cookie_params/tutorial001_an.py!}
- ```
+////
-=== "Python 3.10+ non-Annotated"
+//// tab | Python 3.8+
- !!! tip "İpucu"
- Mümkün mertebe 'Annotated' sınıfını kullanmaya çalışın.
+```Python hl_lines="3"
+{!> ../../../docs_src/cookie_params/tutorial001_an.py!}
+```
- ```Python hl_lines="1"
- {!> ../../../docs_src/cookie_params/tutorial001_py310.py!}
- ```
+////
-=== "Python 3.8+ non-Annotated"
+//// tab | Python 3.10+ non-Annotated
- !!! tip "İpucu"
- Mümkün mertebe 'Annotated' sınıfını kullanmaya çalışın.
+/// tip | "İpucu"
- ```Python hl_lines="3"
- {!> ../../../docs_src/cookie_params/tutorial001.py!}
- ```
+Mümkün mertebe 'Annotated' sınıfını kullanmaya çalışın.
+
+///
+
+```Python hl_lines="1"
+{!> ../../../docs_src/cookie_params/tutorial001_py310.py!}
+```
+
+////
+
+//// tab | Python 3.8+ non-Annotated
+
+/// tip | "İpucu"
+
+Mümkün mertebe 'Annotated' sınıfını kullanmaya çalışın.
+
+///
+
+```Python hl_lines="3"
+{!> ../../../docs_src/cookie_params/tutorial001.py!}
+```
+
+////
## `Cookie` Parametrelerini Tanımlayın
İlk değer varsayılan değerdir; tüm ekstra doğrulama veya belirteç parametrelerini kullanabilirsiniz:
-=== "Python 3.10+"
+//// tab | Python 3.10+
+
+```Python hl_lines="9"
+{!> ../../../docs_src/cookie_params/tutorial001_an_py310.py!}
+```
+
+////
+
+//// tab | Python 3.9+
+
+```Python hl_lines="9"
+{!> ../../../docs_src/cookie_params/tutorial001_an_py39.py!}
+```
+
+////
+
+//// tab | Python 3.8+
+
+```Python hl_lines="10"
+{!> ../../../docs_src/cookie_params/tutorial001_an.py!}
+```
+
+////
+
+//// tab | Python 3.10+ non-Annotated
+
+/// tip | "İpucu"
+
+Mümkün mertebe 'Annotated' sınıfını kullanmaya çalışın.
+
+///
+
+```Python hl_lines="7"
+{!> ../../../docs_src/cookie_params/tutorial001_py310.py!}
+```
- ```Python hl_lines="9"
- {!> ../../../docs_src/cookie_params/tutorial001_an_py310.py!}
- ```
+////
-=== "Python 3.9+"
+//// tab | Python 3.8+ non-Annotated
- ```Python hl_lines="9"
- {!> ../../../docs_src/cookie_params/tutorial001_an_py39.py!}
- ```
+/// tip | "İpucu"
-=== "Python 3.8+"
+Mümkün mertebe 'Annotated' sınıfını kullanmaya çalışın.
- ```Python hl_lines="10"
- {!> ../../../docs_src/cookie_params/tutorial001_an.py!}
- ```
+///
-=== "Python 3.10+ non-Annotated"
+```Python hl_lines="9"
+{!> ../../../docs_src/cookie_params/tutorial001.py!}
+```
- !!! tip "İpucu"
- Mümkün mertebe 'Annotated' sınıfını kullanmaya çalışın.
+////
- ```Python hl_lines="7"
- {!> ../../../docs_src/cookie_params/tutorial001_py310.py!}
- ```
+/// note | "Teknik Detaylar"
-=== "Python 3.8+ non-Annotated"
+`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.
- !!! tip "İpucu"
- Mümkün mertebe 'Annotated' sınıfını kullanmaya çalışın.
+Ancak `fastapi`'dan projenize dahil ettiğiniz `Query`, `Path`, `Cookie` ve diğerleri aslında özel sınıflar döndüren birer fonksiyondur.
- ```Python hl_lines="9"
- {!> ../../../docs_src/cookie_params/tutorial001.py!}
- ```
+///
-!!! 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.
+/// info | "Bilgi"
- Ancak `fastapi`'dan projenize dahil ettiğiniz `Query`, `Path`, `Cookie` ve diğerleri aslında özel sınıflar döndüren birer fonksiyondur.
+Çerez tanımlamak için `Cookie` sınıfını kullanmanız gerekmektedir, aksi taktirde parametreler sorgu parametreleri olarak yorumlanır.
-!!! info "Bilgi"
- Çerez tanımlamak için `Cookie` sınıfını kullanmanız gerekmektedir, aksi taktirde parametreler sorgu parametreleri olarak yorumlanır.
+///
## Özet
</div>
-!!! note "Not"
- `uvicorn main:app` komutunu şu şekilde açıklayabiliriz:
+/// note | "Not"
- * `main`: dosya olan `main.py` (yani Python "modülü").
- * `app`: ise `main.py` dosyasının içerisinde `app = FastAPI()` satırında oluşturduğumuz `FastAPI` nesnesi.
- * `--reload`: kod değişikliklerinin ardından sunucuyu otomatik olarak yeniden başlatır. Bu parameteyi sadece geliştirme aşamasında kullanmalıyız.
+`uvicorn main:app` komutunu şu şekilde açıklayabiliriz:
+
+* `main`: dosya olan `main.py` (yani Python "modülü").
+* `app`: ise `main.py` dosyasının içerisinde `app = FastAPI()` satırında oluşturduğumuz `FastAPI` nesnesi.
+* `--reload`: kod değişikliklerinin ardından sunucuyu otomatik olarak yeniden başlatır. Bu parameteyi sadece geliştirme aşamasında kullanmalıyız.
+
+///
Çıktı olarak şöyle bir satır ile karşılaşacaksınız:
`FastAPI`, API'niz için tüm işlevselliği sağlayan bir Python sınıfıdır.
-!!! note "Teknik Detaylar"
- `FastAPI` doğrudan `Starlette`'i miras alan bir sınıftır.
+/// note | "Teknik Detaylar"
+
+`FastAPI` doğrudan `Starlette`'i miras alan bir sınıftır.
- <a href="https://www.starlette.io/" class="external-link" target="_blank">Starlette</a>'in tüm işlevselliğini `FastAPI` ile de kullanabilirsiniz.
+<a href="https://www.starlette.io/" class="external-link" target="_blank">Starlette</a>'in tüm işlevselliğini `FastAPI` ile de kullanabilirsiniz.
+
+///
### Adım 2: Bir `FastAPI` "Örneği" Oluşturalım
/items/foo
```
-!!! info "Bilgi"
- "Yol" genellikle "<abbr title="Endpoint: Bitim Noktası">endpoint</abbr>" veya "<abbr title="Route: Yönlendirme/Yön">route</abbr>" olarak adlandırılır.
+/// info | "Bilgi"
+
+"Yol" genellikle "<abbr title="Endpoint: Bitim Noktası">endpoint</abbr>" veya "<abbr title="Route: Yönlendirme/Yön">route</abbr>" olarak adlandırılır.
+
+///
Bir API oluştururken, "yol", "kaynaklar" ile "endişeleri" ayırmanın ana yöntemidir.
* <abbr title="Bir HTTP GET metodu"><code>get</code> operasyonu</abbr> ile
* `/` yoluna gelen istekler
-!!! info "`@decorator` Bilgisi"
- Python'da `@something` sözdizimi "<abbr title="Decorator">dekoratör</abbr>" olarak adlandırılır.
+/// info | "`@decorator` Bilgisi"
- Dekoratörler, dekoratif bir şapka gibi (sanırım terim buradan geliyor) fonksiyonların üzerlerine yerleştirilirler.
+Python'da `@something` sözdizimi "<abbr title="Decorator">dekoratör</abbr>" olarak adlandırılır.
- Bir "dekoratör" hemen altında bulunan fonksiyonu alır ve o fonksiyon ile bazı işlemler gerçekleştirir.
+Dekoratörler, dekoratif bir şapka gibi (sanırım terim buradan geliyor) fonksiyonların üzerlerine yerleştirilirler.
- Bizim durumumuzda, kullandığımız dekoratör, **FastAPI**'a altındaki fonksiyonun `/` yoluna gelen `get` metodlu isteklerden sorumlu olduğunu söyler.
+Bir "dekoratör" hemen altında bulunan fonksiyonu alır ve o fonksiyon ile bazı işlemler gerçekleştirir.
- Bu bir **yol operasyonu dekoratörüdür**.
+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.patch()`
* `@app.trace()`
-!!! tip "İpucu"
- Her işlemi (HTTP metod) istediğiniz gibi kullanmakta özgürsünüz.
+/// 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.
+**FastAPI** herhangi bir özel amacı veya anlamı olması konusunda ısrarcı olmaz.
- Buradaki bilgiler bir gereklilik değil, bir kılavuz olarak sunulmaktadır.
+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.
+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
{!../../../docs_src/first_steps/tutorial003.py!}
```
-!!! note "Not"
- Eğer farkı bilmiyorsanız, [Async: *"Aceleniz mi var?"*](../async.md#in-a-hurry){.internal-link target=_blank} sayfasını kontrol edebilirsiniz.
+/// 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
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.
+/// check | "Ek bilgi"
+
+Bu sayede, fonksiyon içerisinde hata denetimi, kod tamamlama gibi konularda editör desteğine kavuşacaksınız.
+
+///
## Veri <abbr title="Dönüşüm: serialization, parsing ve marshalling olarak da biliniyor">Dönüşümü</abbr>
{"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.
+/// 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 <abbr title="HTTP isteği ile birlikte gelen string'i Python verisine dönüştürme">"ayrıştırma"</abbr> özelliği sağlar.
- Bu tanımlamayla birlikte, **FastAPI** size otomatik istek <abbr title="HTTP isteği ile birlikte gelen string'i Python verisine dönüştürme">"ayrıştırma"</abbr> özelliği sağlar.
+///
## Veri Doğrulama
Aynı hata <a href="http://127.0.0.1:8000/items/4.2" class="external-link" target="_blank">http://127.0.0.1:8000/items/4.2</a> 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.
+/// check | "Ek bilgi"
- Dikkatinizi çekerim ki, karşılaştığınız hata, doğrulamanın geçersiz olduğu mutlak noktayı da açık bir şekilde belirtiyor.
+Böylece, aynı Python tip tanımlaması ile birlikte, **FastAPI** veri doğrulama özelliği sağlar.
- Bu özellik, API'ınızla iletişime geçen kodu geliştirirken ve ayıklarken inanılmaz derecede yararlı olacaktır.
+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
<img src="/img/tutorial/path-params/image01.png">
-!!! check "Ek bilgi"
- Üstelik, sadece aynı Python tip tanımlaması ile, **FastAPI** size otomatik ve interaktif (Swagger UI ile entegre) bir dokümantasyon sağlar.
+/// check | "Ek bilgi"
+
+Üstelik, sadece aynı Python tip tanımlaması ile, **FastAPI** size otomatik ve interaktif (Swagger UI ile entegre) bir dokümantasyon sağlar.
+
+Dikkatinizi çekerim ki, yol parametresi integer olarak tanımlanmıştır.
- Dikkatinizi çekerim ki, yol parametresi integer olarak tanımlanmıştır.
+///
## Standartlara Dayalı Avantajlar, Alternatif Dokümantasyon
{!../../../docs_src/path_params/tutorial005.py!}
```
-!!! info "Bilgi"
- 3.4 sürümünden beri <a href="https://docs.python.org/3/library/enum.html" class="external-link" target="_blank">enumerationlar (ya da enumlar) Python'da mevcuttur</a>.
+/// info | "Bilgi"
-!!! tip "İpucu"
- Merak ediyorsanız söyleyeyim, "AlexNet", "ResNet" ve "LeNet" isimleri Makine Öğrenmesi <abbr title="Teknik olarak, Derin Öğrenme model mimarileri">modellerini</abbr> temsil eder.
+3.4 sürümünden beri <a href="https://docs.python.org/3/library/enum.html" class="external-link" target="_blank">enumerationlar (ya da enumlar) Python'da mevcuttur</a>.
+
+///
+
+/// tip | "İpucu"
+
+Merak ediyorsanız söyleyeyim, "AlexNet", "ResNet" ve "LeNet" isimleri Makine Öğrenmesi <abbr title="Teknik olarak, Derin Öğrenme model mimarileri">modellerini</abbr> temsil eder.
+
+///
### Bir *Yol Parametresi* Tanımlayalım
{!../../../docs_src/path_params/tutorial005.py!}
```
-!!! tip "İpucu"
- `"lenet"` değerine `ModelName.lenet.value` tanımı ile de ulaşabilirsiniz.
+/// tip | "İpucu"
+
+`"lenet"` değerine `ModelName.lenet.value` tanımı ile de ulaşabilirsiniz.
+
+///
#### *Enumeration Üyelerini* Döndürelim
{!../../../docs_src/path_params/tutorial004.py!}
```
-!!! tip "İpucu"
- Parametrenin başında `/home/johndoe/myfile.txt` yolunda olduğu gibi (`/`) işareti ile birlikte kullanmanız gerektiği durumlar olabilir.
+/// tip | "İpucu"
+
+Parametrenin başında `/home/johndoe/myfile.txt` yolunda olduğu gibi (`/`) işareti ile birlikte kullanmanız gerektiği durumlar olabilir.
+
+Bu durumda, URL, `files` ile `home` arasında iki eğik çizgiye (`//`) sahip olup `/files//home/johndoe/myfile.txt` gibi gözükecektir.
- Bu durumda, URL, `files` ile `home` arasında iki eğik çizgiye (`//`) sahip olup `/files//home/johndoe/myfile.txt` gibi gözükecektir.
+///
## Özet
Aynı şekilde, varsayılan değerlerini `None` olarak atayarak isteğe bağlı parametreler tanımlayabilirsiniz:
-=== "Python 3.10+"
+//// tab | Python 3.10+
- ```Python hl_lines="7"
- {!> ../../../docs_src/query_params/tutorial002_py310.py!}
- ```
+```Python hl_lines="7"
+{!> ../../../docs_src/query_params/tutorial002_py310.py!}
+```
+
+////
+
+//// tab | Python 3.8+
-=== "Python 3.8+"
+```Python hl_lines="9"
+{!> ../../../docs_src/query_params/tutorial002.py!}
+```
- ```Python hl_lines="9"
- {!> ../../../docs_src/query_params/tutorial002.py!}
- ```
+////
Bu durumda, `q` fonksiyon parametresi isteğe bağlı olacak ve varsayılan değer olarak `None` alacaktır.
-!!! check "Ek bilgi"
- Ayrıca, dikkatinizi çekerim ki; **FastAPI**, `item_id` parametresinin bir yol parametresi olduğunu ve `q` parametresinin yol değil bir sorgu parametresi olduğunu fark edecek kadar beceriklidir.
+/// check | "Ek bilgi"
+
+Ayrıca, dikkatinizi çekerim ki; **FastAPI**, `item_id` parametresinin bir yol parametresi olduğunu ve `q` parametresinin yol değil bir sorgu parametresi olduğunu fark edecek kadar beceriklidir.
+
+///
## Sorgu Parametresi Tip Dönüşümü
Aşağıda görüldüğü gibi dönüştürülmek üzere `bool` tipleri de tanımlayabilirsiniz:
-=== "Python 3.10+"
+//// tab | Python 3.10+
+
+```Python hl_lines="7"
+{!> ../../../docs_src/query_params/tutorial003_py310.py!}
+```
- ```Python hl_lines="7"
- {!> ../../../docs_src/query_params/tutorial003_py310.py!}
- ```
+////
-=== "Python 3.8+"
+//// tab | Python 3.8+
+
+```Python hl_lines="9"
+{!> ../../../docs_src/query_params/tutorial003.py!}
+```
- ```Python hl_lines="9"
- {!> ../../../docs_src/query_params/tutorial003.py!}
- ```
+////
Bu durumda, eğer şu adrese giderseniz:
İsimlerine göre belirleneceklerdir:
-=== "Python 3.10+"
+//// tab | Python 3.10+
+
+```Python hl_lines="6 8"
+{!> ../../../docs_src/query_params/tutorial004_py310.py!}
+```
+
+////
- ```Python hl_lines="6 8"
- {!> ../../../docs_src/query_params/tutorial004_py310.py!}
- ```
+//// tab | Python 3.8+
-=== "Python 3.8+"
+```Python hl_lines="8 10"
+{!> ../../../docs_src/query_params/tutorial004.py!}
+```
- ```Python hl_lines="8 10"
- {!> ../../../docs_src/query_params/tutorial004.py!}
- ```
+////
## Zorunlu Sorgu Parametreleri
Ve elbette, bazı parametreleri zorunlu, bazılarını varsayılan değerli ve bazılarını tamamen opsiyonel olarak tanımlayabilirsiniz:
-=== "Python 3.10+"
+//// tab | Python 3.10+
- ```Python hl_lines="8"
- {!> ../../../docs_src/query_params/tutorial006_py310.py!}
- ```
+```Python hl_lines="8"
+{!> ../../../docs_src/query_params/tutorial006_py310.py!}
+```
-=== "Python 3.8+"
+////
- ```Python hl_lines="10"
- {!> ../../../docs_src/query_params/tutorial006.py!}
- ```
+//// tab | Python 3.8+
+
+```Python hl_lines="10"
+{!> ../../../docs_src/query_params/tutorial006.py!}
+```
+
+////
Bu durumda, 3 tane sorgu parametresi var olacaktır:
* `skip`, varsayılan değeri `0` olan bir `int`.
* `limit`, isteğe bağlı bir `int`.
-!!! tip "İpucu"
- Ayrıca, [Yol Parametrelerinde](path-params.md#on-tanml-degerler){.internal-link target=_blank} de kullanıldığı şekilde `Enum` sınıfından faydalanabilirsiniz.
+/// tip | "İpucu"
+
+Ayrıca, [Yol Parametrelerinde](path-params.md#on-tanml-degerler){.internal-link target=_blank} de kullanıldığı şekilde `Enum` sınıfından faydalanabilirsiniz.
+
+///
İstek gövdesinde JSON verisi yerine form alanlarını karşılamanız gerketiğinde `Form` sınıfını kullanabilirsiniz.
-!!! info "Bilgi"
- Formları kullanmak için öncelikle <a href="https://github.com/Kludex/python-multipart" class="external-link" target="_blank">`python-multipart`</a> paketini indirmeniz gerekmektedir.
+/// info | "Bilgi"
- Örneğin `pip install python-multipart`.
+Formları kullanmak için öncelikle <a href="https://github.com/Kludex/python-multipart" class="external-link" target="_blank">`python-multipart`</a> paketini indirmeniz gerekmektedir.
+
+Örneğin `pip install python-multipart`.
+
+///
## `Form` Sınıfını Projenize Dahil Edin
`Form` sınıfını `fastapi`'den projenize dahil edin:
-=== "Python 3.9+"
+//// tab | Python 3.9+
+
+```Python hl_lines="3"
+{!> ../../../docs_src/request_forms/tutorial001_an_py39.py!}
+```
+
+////
+
+//// tab | Python 3.8+
- ```Python hl_lines="3"
- {!> ../../../docs_src/request_forms/tutorial001_an_py39.py!}
- ```
+```Python hl_lines="1"
+{!> ../../../docs_src/request_forms/tutorial001_an.py!}
+```
-=== "Python 3.8+"
+////
- ```Python hl_lines="1"
- {!> ../../../docs_src/request_forms/tutorial001_an.py!}
- ```
+//// tab | Python 3.8+ non-Annotated
-=== "Python 3.8+ non-Annotated"
+/// tip
- !!! tip
- Prefer to use the `Annotated` version if possible.
+Prefer to use the `Annotated` version if possible.
- ```Python hl_lines="1"
- {!> ../../../docs_src/request_forms/tutorial001.py!}
- ```
+///
+
+```Python hl_lines="1"
+{!> ../../../docs_src/request_forms/tutorial001.py!}
+```
+
+////
## `Form` Parametrelerini Tanımlayın
Form parametrelerini `Body` veya `Query` için yaptığınız gibi oluşturun:
-=== "Python 3.9+"
+//// tab | Python 3.9+
+
+```Python hl_lines="9"
+{!> ../../../docs_src/request_forms/tutorial001_an_py39.py!}
+```
+
+////
+
+//// tab | Python 3.8+
- ```Python hl_lines="9"
- {!> ../../../docs_src/request_forms/tutorial001_an_py39.py!}
- ```
+```Python hl_lines="8"
+{!> ../../../docs_src/request_forms/tutorial001_an.py!}
+```
-=== "Python 3.8+"
+////
- ```Python hl_lines="8"
- {!> ../../../docs_src/request_forms/tutorial001_an.py!}
- ```
+//// tab | Python 3.8+ non-Annotated
-=== "Python 3.8+ non-Annotated"
+/// tip
- !!! tip
- Prefer to use the `Annotated` version if possible.
+Prefer to use the `Annotated` version if possible.
- ```Python hl_lines="7"
- {!> ../../../docs_src/request_forms/tutorial001.py!}
- ```
+///
+
+```Python hl_lines="7"
+{!> ../../../docs_src/request_forms/tutorial001.py!}
+```
+
+////
Örneğin, OAuth2 spesifikasyonunun kullanılabileceği ("şifre akışı" olarak adlandırılan) yollardan birinde, form alanları olarak <abbr title="Kullanıcı Adı: Username">"username"</abbr> ve <abbr title="Şifre: Password">"password"</abbr> gönderilmesi gerekir.
`Form` sınıfıyla tanımlama yaparken `Body`, `Query`, `Path` ve `Cookie` sınıflarında kullandığınız aynı validasyon, örnekler, isimlendirme (örneğin `username` yerine `user-name` kullanımı) ve daha fazla konfigurasyonu kullanabilirsiniz.
-!!! info "Bilgi"
- `Form` doğrudan `Body` sınıfını miras alan bir sınıftır.
+/// info | "Bilgi"
+
+`Form` doğrudan `Body` sınıfını miras alan bir sınıftır.
+
+///
+
+/// tip | "İpucu"
-!!! tip "İpucu"
- Form gövdelerini tanımlamak için `Form` sınıfını kullanmanız gerekir; çünkü bu olmadan parametreler sorgu parametreleri veya gövde (JSON) parametreleri olarak yorumlanır.
+Form gövdelerini tanımlamak için `Form` sınıfını kullanmanız gerekir; çünkü bu olmadan parametreler sorgu parametreleri veya gövde (JSON) parametreleri olarak yorumlanır.
+
+///
## "Form Alanları" Hakkında
**FastAPI** bu verilerin JSON yerine doğru şekilde okunmasını sağlayacaktır.
-!!! note "Teknik Detaylar"
- Form verileri normalde `application/x-www-form-urlencoded` medya tipiyle kodlanır.
+/// note | "Teknik Detaylar"
+
+Form verileri normalde `application/x-www-form-urlencoded` medya tipiyle kodlanır.
+
+Ancak form içerisinde dosyalar yer aldığında `multipart/form-data` olarak kodlanır. Bir sonraki bölümde dosyaların işlenmesi hakkında bilgi edineceksiniz.
+
+Form kodlama türleri ve form alanları hakkında daha fazla bilgi edinmek istiyorsanız <a href="https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods/POST" class="external-link" target="_blank"><abbr title="Mozilla Developer Network">MDN</abbr> web docs for <code>POST</code></a> sayfasını ziyaret edebilirsiniz.
+
+///
- Ancak form içerisinde dosyalar yer aldığında `multipart/form-data` olarak kodlanır. Bir sonraki bölümde dosyaların işlenmesi hakkında bilgi edineceksiniz.
+/// warning | "Uyarı"
- Form kodlama türleri ve form alanları hakkında daha fazla bilgi edinmek istiyorsanız <a href="https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods/POST" class="external-link" target="_blank"><abbr title="Mozilla Developer Network">MDN</abbr> web docs for <code>POST</code></a> sayfasını ziyaret edebilirsiniz.
+*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.
-!!! 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.
- Bu **FastAPI**'ın getirdiği bir kısıtlama değildir, HTTP protokolünün bir parçasıdır.
+///
## Özet
{!../../../docs_src/static_files/tutorial001.py!}
```
-!!! note "Teknik Detaylar"
- Projenize dahil etmek için `from starlette.staticfiles import StaticFiles` kullanabilirsiniz.
+/// note | "Teknik Detaylar"
- **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.
+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?
Це був один із перших прикладів **автоматичної документації API**, і саме це була одна з перших ідей, яка надихнула на «пошук» **FastAPI**.
-!!! note "Примітка"
- Django REST Framework створив Том Крісті. Той самий творець Starlette і Uvicorn, на яких базується **FastAPI**.
+/// note | "Примітка"
+Django REST Framework створив Том Крісті. Той самий творець Starlette і Uvicorn, на яких базується **FastAPI**.
-!!! check "Надихнуло **FastAPI** на"
- Мати автоматичний веб-інтерфейс документації API.
+///
+
+/// check | "Надихнуло **FastAPI** на"
+
+Мати автоматичний веб-інтерфейс документації API.
+
+///
### <a href="https://flask.palletsprojects.com" class="external-link" target="_blank">Flask</a>
Враховуючи простоту Flask, він здавався хорошим підходом для створення API. Наступним, що знайшов, був «Django REST Framework» для Flask.
-!!! check "Надихнуло **FastAPI** на"
- Бути мікрофреймоворком. Зробити легким комбінування та поєднання необхідних інструментів та частин.
+/// check | "Надихнуло **FastAPI** на"
- Мати просту та легку у використанні систему маршрутизації.
+Бути мікрофреймоворком. Зробити легким комбінування та поєднання необхідних інструментів та частин.
+ Мати просту та легку у використанні систему маршрутизації.
+
+///
### <a href="https://requests.readthedocs.io" class="external-link" target="_blank">Requests</a>
Зверніть увагу на схожість у `requests.get(...)` і `@app.get(...)`.
-!!! check "Надихнуло **FastAPI** на"
- * Майте простий та інтуїтивно зрозумілий API.
- * Використовуйте імена (операції) методів HTTP безпосередньо, простим та інтуїтивно зрозумілим способом.
- * Розумні параметри за замовчуванням, але потужні налаштування.
+/// check | "Надихнуло **FastAPI** на"
+
+* Майте простий та інтуїтивно зрозумілий API.
+ * Використовуйте імена (операції) методів HTTP безпосередньо, простим та інтуїтивно зрозумілим способом.
+ * Розумні параметри за замовчуванням, але потужні налаштування.
+///
### <a href="https://swagger.io/" class="external-link" target="_blank">Swagger</a> / <a href="https://github.com/OAI /OpenAPI-Specification/" class="external-link" target="_blank">OpenAPI</a>
Тому, коли говорять про версію 2.0, прийнято говорити «Swagger», а про версію 3+ «OpenAPI».
-!!! check "Надихнуло **FastAPI** на"
- Прийняти і використовувати відкритий стандарт для специфікацій API замість спеціальної схеми.
+/// check | "Надихнуло **FastAPI** на"
+
+Прийняти і використовувати відкритий стандарт для специфікацій API замість спеціальної схеми.
- Інтегрувати інструменти інтерфейсу на основі стандартів:
+ Інтегрувати інструменти інтерфейсу на основі стандартів:
- * <a href="https://github.com/swagger-api/swagger-ui" class="external-link" target="_blank">Інтерфейс Swagger</a>
- * <a href="https://github.com/Rebilly/ReDoc" class="external-link" target="_blank">ReDoc</a>
+ * <a href="https://github.com/swagger-api/swagger-ui" class="external-link" target="_blank">Інтерфейс Swagger</a>
+ * <a href="https://github.com/Rebilly/ReDoc" class="external-link" target="_blank">ReDoc</a>
- Ці два було обрано через те, що вони досить популярні та стабільні, але, виконавши швидкий пошук, ви можете знайти десятки додаткових альтернативних інтерфейсів для OpenAPI (які можна використовувати з **FastAPI**).
+ Ці два було обрано через те, що вони досить популярні та стабільні, але, виконавши швидкий пошук, ви можете знайти десятки додаткових альтернативних інтерфейсів для OpenAPI (які можна використовувати з **FastAPI**).
+
+///
### Фреймворки REST для Flask
Але він був створений до того, як існували підказки типу Python. Отже, щоб визначити кожну <abbr title="визначення того, як дані повинні бути сформовані">схему</abbr>, вам потрібно використовувати спеціальні утиліти та класи, надані Marshmallow.
-!!! check "Надихнуло **FastAPI** на"
- Використовувати код для автоматичного визначення "схем", які надають типи даних і перевірку.
+/// check | "Надихнуло **FastAPI** на"
+
+Використовувати код для автоматичного визначення "схем", які надають типи даних і перевірку.
+
+///
### <a href="https://webargs.readthedocs.io/en/latest/" class="external-link" target="_blank">Webargs</a>
Це чудовий інструмент, і я також часто використовував його, перш ніж створити **FastAPI**.
-!!! info "Інформація"
- Webargs був створений тими ж розробниками Marshmallow.
+/// info | "Інформація"
+
+Webargs був створений тими ж розробниками Marshmallow.
+
+///
+
+/// check | "Надихнуло **FastAPI** на"
-!!! check "Надихнуло **FastAPI** на"
- Мати автоматичну перевірку даних вхідного запиту.
+Мати автоматичну перевірку даних вхідного запиту.
+
+///
### <a href="https://apispec.readthedocs.io/en/stable/" class="external-link" target="_blank">APISpec</a>
Редактор тут нічим не може допомогти. І якщо ми змінимо параметри чи схеми Marshmallow і забудемо також змінити цю строку документа YAML, згенерована схема буде застарілою.
-!!! info "Інформація"
- APISpec був створений тими ж розробниками Marshmallow.
+/// info | "Інформація"
+
+APISpec був створений тими ж розробниками Marshmallow.
+
+///
+/// check | "Надихнуло **FastAPI** на"
-!!! check "Надихнуло **FastAPI** на"
- Підтримувати відкритий стандарт API, OpenAPI.
+Підтримувати відкритий стандарт API, OpenAPI.
+
+///
### <a href="https://flask-apispec.readthedocs.io/en/latest/" class="external-link" target="_blank">Flask-apispec</a>
І ці самі генератори повного стеку були основою [**FastAPI** генераторів проектів](project-generation.md){.internal-link target=_blank}.
-!!! info "Інформація"
- Flask-apispec був створений тими ж розробниками Marshmallow.
+/// info | "Інформація"
+
+Flask-apispec був створений тими ж розробниками Marshmallow.
+
+///
-!!! check "Надихнуло **FastAPI** на"
- Створення схеми OpenAPI автоматично з того самого коду, який визначає серіалізацію та перевірку.
+/// check | "Надихнуло **FastAPI** на"
+
+Створення схеми OpenAPI автоматично з того самого коду, який визначає серіалізацію та перевірку.
+
+///
### <a href="https://nestjs.com/" class="external-link" target="_blank">NestJS</a> (та <a href="https://angular.io/ " class="external-link" target="_blank">Angular</a>)
Він не дуже добре обробляє вкладені моделі. Отже, якщо тіло JSON у запиті є об’єктом JSON із внутрішніми полями, які, у свою чергу, є вкладеними об’єктами JSON, його неможливо належним чином задокументувати та перевірити.
-!!! check "Надихнуло **FastAPI** на"
- Використовувати типи Python, щоб мати чудову підтримку редактора.
+/// check | "Надихнуло **FastAPI** на"
+
+Використовувати типи Python, щоб мати чудову підтримку редактора.
- Мати потужну систему впровадження залежностей. Знайдіть спосіб звести до мінімуму повторення коду.
+ Мати потужну систему впровадження залежностей. Знайдіть спосіб звести до мінімуму повторення коду.
+
+///
### <a href="https://sanic.readthedocs.io/en/latest/" class="external-link" target="_blank">Sanic</a>
Це був один із перших надзвичайно швидких фреймворків Python на основі `asyncio`. Він був дуже схожий на Flask.
-!!! note "Технічні деталі"
- Він використовував <a href="https://github.com/MagicStack/uvloop" class="external-link" target="_blank">`uvloop`</a> замість стандартного циклу Python `asyncio`. Ось що зробило його таким швидким.
+/// note | "Технічні деталі"
+
+Він використовував <a href="https://github.com/MagicStack/uvloop" class="external-link" target="_blank">`uvloop`</a> замість стандартного циклу Python `asyncio`. Ось що зробило його таким швидким.
- Це явно надихнуло Uvicorn і Starlette, які зараз швидші за Sanic у відкритих тестах.
+ Це явно надихнуло Uvicorn і Starlette, які зараз швидші за Sanic у відкритих тестах.
-!!! check "Надихнуло **FastAPI** на"
- Знайти спосіб отримати божевільну продуктивність.
+///
- Ось чому **FastAPI** базується на Starlette, оскільки це найшвидша доступна структура (перевірена тестами сторонніх розробників).
+/// check | "Надихнуло **FastAPI** на"
+
+Знайти спосіб отримати божевільну продуктивність.
+
+ Ось чому **FastAPI** базується на Starlette, оскільки це найшвидша доступна структура (перевірена тестами сторонніх розробників).
+
+///
### <a href="https://falconframework.org/" class="external-link" target="_blank">Falcon</a>
Таким чином, перевірка даних, серіалізація та документація повинні виконуватися в коді, а не автоматично. Або вони повинні бути реалізовані як фреймворк поверх Falcon, як Hug. Така сама відмінність спостерігається в інших фреймворках, натхненних дизайном Falcon, що мають один об’єкт запиту та один об’єкт відповіді як параметри.
-!!! check "Надихнуло **FastAPI** на"
- Знайти способи отримати чудову продуктивність.
+/// check | "Надихнуло **FastAPI** на"
- Разом із Hug (оскільки Hug базується на Falcon) надихнув **FastAPI** оголосити параметр `response` у функціях.
+Знайти способи отримати чудову продуктивність.
- Хоча у FastAPI це необов’язково, і використовується в основному для встановлення заголовків, файлів cookie та альтернативних кодів стану.
+ Разом із Hug (оскільки Hug базується на Falcon) надихнув **FastAPI** оголосити параметр `response` у функціях.
+
+ Хоча у FastAPI це необов’язково, і використовується в основному для встановлення заголовків, файлів cookie та альтернативних кодів стану.
+
+///
### <a href="https://moltenframework.com/" class="external-link" target="_blank">Molten</a>
Маршрути оголошуються в одному місці з використанням функцій, оголошених в інших місцях (замість використання декораторів, які можна розмістити безпосередньо поверх функції, яка обробляє кінцеву точку). Це ближче до того, як це робить Django, ніж до Flask (і Starlette). Він розділяє в коді речі, які відносно тісно пов’язані.
-!!! check "Надихнуло **FastAPI** на"
- Визначити додаткові перевірки для типів даних, використовуючи значення "за замовчуванням" атрибутів моделі. Це покращує підтримку редактора, а раніше вона була недоступна в Pydantic.
+/// check | "Надихнуло **FastAPI** на"
+
+Визначити додаткові перевірки для типів даних, використовуючи значення "за замовчуванням" атрибутів моделі. Це покращує підтримку редактора, а раніше вона була недоступна в Pydantic.
- Це фактично надихнуло оновити частини Pydantic, щоб підтримувати той самий стиль оголошення перевірки (всі ці функції вже доступні в Pydantic).
+ Це фактично надихнуло оновити частини Pydantic, щоб підтримувати той самий стиль оголошення перевірки (всі ці функції вже доступні в Pydantic).
+
+///
### <a href="https://www.hug.rest/" class="external-link" target="_blank">Hug</a>
Оскільки він заснований на попередньому стандарті для синхронних веб-фреймворків Python (WSGI), він не може працювати з Websockets та іншими речами, хоча він також має високу продуктивність.
-!!! info "Інформація"
- Hug створив Тімоті Крослі, той самий творець <a href="https://github.com/timothycrosley/isort" class="external-link" target="_blank">`isort`</a>, чудовий інструмент для автоматичного сортування імпорту у файлах Python.
+/// info | "Інформація"
+
+Hug створив Тімоті Крослі, той самий творець <a href="https://github.com/timothycrosley/isort" class="external-link" target="_blank">`isort`</a>, чудовий інструмент для автоматичного сортування імпорту у файлах Python.
+
+///
-!!! check "Надихнуло **FastAPI** на"
- Hug надихнув частину APIStar і був одним із найбільш перспективних інструментів, поряд із APIStar.
+/// check | "Надихнуло **FastAPI** на"
- Hug надихнув **FastAPI** на використання підказок типу Python для оголошення параметрів і автоматичного створення схеми, що визначає API.
+Hug надихнув частину APIStar і був одним із найбільш перспективних інструментів, поряд із APIStar.
- Hug надихнув **FastAPI** оголосити параметр `response` у функціях для встановлення заголовків і файлів cookie.
+ Hug надихнув **FastAPI** на використання підказок типу Python для оголошення параметрів і автоматичного створення схеми, що визначає API.
+
+ Hug надихнув **FastAPI** оголосити параметр `response` у функціях для встановлення заголовків і файлів cookie.
+
+///
### <a href="https://github.com/encode/apistar" class="external-link" target="_blank">APIStar</a> (<= 0,5)
Тепер APIStar — це набір інструментів для перевірки специфікацій OpenAPI, а не веб-фреймворк.
-!!! info "Інформація"
- APIStar створив Том Крісті. Той самий хлопець, який створив:
+/// info | "Інформація"
+
+APIStar створив Том Крісті. Той самий хлопець, який створив:
- * Django REST Framework
- * Starlette (на якому базується **FastAPI**)
- * Uvicorn (використовується Starlette і **FastAPI**)
+ * Django REST Framework
+ * Starlette (на якому базується **FastAPI**)
+ * Uvicorn (використовується Starlette і **FastAPI**)
-!!! check "Надихнуло **FastAPI** на"
- Існувати.
+///
- Ідею оголошення кількох речей (перевірки даних, серіалізації та документації) за допомогою тих самих типів Python, які в той же час забезпечували чудову підтримку редактора, я вважав геніальною ідеєю.
+/// check | "Надихнуло **FastAPI** на"
- І після тривалого пошуку подібної структури та тестування багатьох різних альтернатив, APIStar став найкращим доступним варіантом.
+Існувати.
- Потім APIStar перестав існувати як сервер, і було створено Starlette, який став новою кращою основою для такої системи. Це стало останнім джерелом натхнення для створення **FastAPI**. Я вважаю **FastAPI** «духовним спадкоємцем» APIStar, удосконалюючи та розширюючи функції, систему введення тексту та інші частини на основі досвіду, отриманого від усіх цих попередніх інструментів.
+ Ідею оголошення кількох речей (перевірки даних, серіалізації та документації) за допомогою тих самих типів Python, які в той же час забезпечували чудову підтримку редактора, я вважав геніальною ідеєю.
+
+ І після тривалого пошуку подібної структури та тестування багатьох різних альтернатив, APIStar став найкращим доступним варіантом.
+
+ Потім APIStar перестав існувати як сервер, і було створено Starlette, який став новою кращою основою для такої системи. Це стало останнім джерелом натхнення для створення **FastAPI**. Я вважаю **FastAPI** «духовним спадкоємцем» APIStar, удосконалюючи та розширюючи функції, систему введення тексту та інші частини на основі досвіду, отриманого від усіх цих попередніх інструментів.
+
+///
## Використовується **FastAPI**
Його можна порівняти з Marshmallow. Хоча він швидший за Marshmallow у тестах. Оскільки він базується на тих самих підказках типу Python, підтримка редактора чудова.
-!!! check "**FastAPI** використовує його для"
- Виконання перевірки всіх даних, серіалізації даних і автоматичної документацію моделі (на основі схеми JSON).
+/// check | "**FastAPI** використовує його для"
- Потім **FastAPI** бере ці дані схеми JSON і розміщує їх у OpenAPI, окремо від усіх інших речей, які він робить.
+Виконання перевірки всіх даних, серіалізації даних і автоматичної документацію моделі (на основі схеми JSON).
+
+ Потім **FastAPI** бере ці дані схеми JSON і розміщує їх у OpenAPI, окремо від усіх інших речей, які він робить.
+
+///
### <a href="https://www.starlette.io/" class="external-link" target="_blank">Starlette</a>
Це одна з головних речей, які **FastAPI** додає зверху, все на основі підказок типу Python (з використанням Pydantic). Це, а також система впровадження залежностей, утиліти безпеки, створення схеми OpenAPI тощо.
-!!! note "Технічні деталі"
- ASGI — це новий «стандарт», який розробляється членами основної команди Django. Це ще не «стандарт Python» (PEP), хоча вони в процесі цього.
+/// note | "Технічні деталі"
+
+ASGI — це новий «стандарт», який розробляється членами основної команди Django. Це ще не «стандарт Python» (PEP), хоча вони в процесі цього.
- Тим не менш, він уже використовується як «стандарт» кількома інструментами. Це значно покращує сумісність, оскільки ви можете переключити Uvicorn на будь-який інший сервер ASGI (наприклад, Daphne або Hypercorn), або ви можете додати інструменти, сумісні з ASGI, як-от `python-socketio`.
+ Тим не менш, він уже використовується як «стандарт» кількома інструментами. Це значно покращує сумісність, оскільки ви можете переключити Uvicorn на будь-який інший сервер ASGI (наприклад, Daphne або Hypercorn), або ви можете додати інструменти, сумісні з ASGI, як-от `python-socketio`.
-!!! check "**FastAPI** використовує його для"
- Керування всіма основними веб-частинами. Додавання функцій зверху.
+///
- Сам клас `FastAPI` безпосередньо успадковує клас `Starlette`.
+/// check | "**FastAPI** використовує його для"
- Отже, усе, що ви можете робити зі Starlette, ви можете робити це безпосередньо за допомогою **FastAPI**, оскільки це, по суті, Starlette на стероїдах.
+Керування всіма основними веб-частинами. Додавання функцій зверху.
+
+ Сам клас `FastAPI` безпосередньо успадковує клас `Starlette`.
+
+ Отже, усе, що ви можете робити зі Starlette, ви можете робити це безпосередньо за допомогою **FastAPI**, оскільки це, по суті, Starlette на стероїдах.
+
+///
### <a href="https://www.uvicorn.org/" class="external-link" target="_blank">Uvicorn</a>
Це рекомендований сервер для Starlette і **FastAPI**.
-!!! check "**FastAPI** рекомендує це як"
- Основний веб-сервер для запуску програм **FastAPI**.
+/// check | "**FastAPI** рекомендує це як"
+
+Основний веб-сервер для запуску програм **FastAPI**.
+
+ Ви можете поєднати його з Gunicorn, щоб мати асинхронний багатопроцесний сервер.
- Ви можете поєднати його з Gunicorn, щоб мати асинхронний багатопроцесний сервер.
+ Додаткову інформацію див. у розділі [Розгортання](deployment/index.md){.internal-link target=_blank}.
- Додаткову інформацію див. у розділі [Розгортання](deployment/index.md){.internal-link target=_blank}.
+///
## Орієнтири та швидкість
Але навіть якщо ви ніколи не використаєте **FastAPI**, вам буде корисно дізнатись трохи про них.
-!!! note
- Якщо ви експерт у Python і ви вже знаєте усе про анотації типів - перейдіть до наступного розділу.
+/// note
+
+Якщо ви експерт у Python і ви вже знаєте усе про анотації типів - перейдіть до наступного розділу.
+
+///
## Мотивація
Наприклад, давайте визначимо змінну, яка буде `list` із `str`.
-=== "Python 3.8 і вище"
+//// tab | Python 3.8 і вище
+
+З модуля `typing`, імпортуємо `List` (з великої літери `L`):
+
+```Python hl_lines="1"
+{!> ../../../docs_src/python_types/tutorial006.py!}
+```
+
+Оголосимо змінну з тим самим синтаксисом двокрапки (`:`).
- З модуля `typing`, імпортуємо `List` (з великої літери `L`):
+Як тип вкажемо `List`, який ви імпортували з `typing`.
- ```Python hl_lines="1"
- {!> ../../../docs_src/python_types/tutorial006.py!}
- ```
+Оскільки список є типом, який містить деякі внутрішні типи, ви поміщаєте їх у квадратні дужки:
- Оголосимо змінну з тим самим синтаксисом двокрапки (`:`).
+```Python hl_lines="4"
+{!> ../../../docs_src/python_types/tutorial006.py!}
+```
+
+////
- Як тип вкажемо `List`, який ви імпортували з `typing`.
+//// tab | Python 3.9 і вище
- Оскільки список є типом, який містить деякі внутрішні типи, ви поміщаєте їх у квадратні дужки:
+Оголосимо змінну з тим самим синтаксисом двокрапки (`:`).
- ```Python hl_lines="4"
- {!> ../../../docs_src/python_types/tutorial006.py!}
- ```
+Як тип вкажемо `list`.
-=== "Python 3.9 і вище"
+Оскільки список є типом, який містить деякі внутрішні типи, ви поміщаєте їх у квадратні дужки:
- Оголосимо змінну з тим самим синтаксисом двокрапки (`:`).
+```Python hl_lines="1"
+{!> ../../../docs_src/python_types/tutorial006_py39.py!}
+```
- Як тип вкажемо `list`.
+////
- Оскільки список є типом, який містить деякі внутрішні типи, ви поміщаєте їх у квадратні дужки:
+/// info
- ```Python hl_lines="1"
- {!> ../../../docs_src/python_types/tutorial006_py39.py!}
- ```
+Ці внутрішні типи в квадратних дужках називаються "параметрами типу".
-!!! info
- Ці внутрішні типи в квадратних дужках називаються "параметрами типу".
+У цьому випадку, `str` це параметр типу переданий у `List` (або `list` у Python 3.9 і вище).
- У цьому випадку, `str` це параметр типу переданий у `List` (або `list` у Python 3.9 і вище).
+///
Це означає: "змінна `items` це `list`, і кожен з елементів у цьому списку - `str`".
-!!! tip
- Якщо ви використовуєте Python 3.9 і вище, вам не потрібно імпортувати `List` з `typing`, ви можете використовувати натомість тип `list`.
+/// tip
+
+Якщо ви використовуєте Python 3.9 і вище, вам не потрібно імпортувати `List` з `typing`, ви можете використовувати натомість тип `list`.
+
+///
Зробивши це, ваш редактор може надати підтримку навіть під час обробки елементів зі списку:
Ви повинні зробити те ж саме, щоб оголосити `tuple` і `set`:
-=== "Python 3.8 і вище"
+//// tab | Python 3.8 і вище
+
+```Python hl_lines="1 4"
+{!> ../../../docs_src/python_types/tutorial007.py!}
+```
- ```Python hl_lines="1 4"
- {!> ../../../docs_src/python_types/tutorial007.py!}
- ```
+////
-=== "Python 3.9 і вище"
+//// tab | Python 3.9 і вище
- ```Python hl_lines="1"
- {!> ../../../docs_src/python_types/tutorial007_py39.py!}
- ```
+```Python hl_lines="1"
+{!> ../../../docs_src/python_types/tutorial007_py39.py!}
+```
+
+////
Це означає:
Другий параметр типу для значення у `dict`:
-=== "Python 3.8 і вище"
+//// tab | Python 3.8 і вище
+
+```Python hl_lines="1 4"
+{!> ../../../docs_src/python_types/tutorial008.py!}
+```
+
+////
- ```Python hl_lines="1 4"
- {!> ../../../docs_src/python_types/tutorial008.py!}
- ```
+//// tab | Python 3.9 і вище
-=== "Python 3.9 і вище"
+```Python hl_lines="1"
+{!> ../../../docs_src/python_types/tutorial008_py39.py!}
+```
- ```Python hl_lines="1"
- {!> ../../../docs_src/python_types/tutorial008_py39.py!}
- ```
+////
Це означає:
У Python 3.10 також є **альтернативний синтаксис**, у якому ви можете розділити можливі типи за допомогою <abbr title='також називають «побітовим "або" оператором», але це значення тут не актуальне'>вертикальної смуги (`|`)</abbr>.
-=== "Python 3.8 і вище"
+//// tab | Python 3.8 і вище
+
+```Python hl_lines="1 4"
+{!> ../../../docs_src/python_types/tutorial008b.py!}
+```
+
+////
- ```Python hl_lines="1 4"
- {!> ../../../docs_src/python_types/tutorial008b.py!}
- ```
+//// tab | Python 3.10 і вище
-=== "Python 3.10 і вище"
+```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`.
Це також означає, що в Python 3.10 ви можете використовувати `Something | None`:
-=== "Python 3.8 і вище"
+//// tab | Python 3.8 і вище
+
+```Python hl_lines="1 4"
+{!> ../../../docs_src/python_types/tutorial009.py!}
+```
+
+////
- ```Python hl_lines="1 4"
- {!> ../../../docs_src/python_types/tutorial009.py!}
- ```
+//// tab | Python 3.8 і вище - альтернатива
-=== "Python 3.8 і вище - альтернатива"
+```Python hl_lines="1 4"
+{!> ../../../docs_src/python_types/tutorial009b.py!}
+```
- ```Python hl_lines="1 4"
- {!> ../../../docs_src/python_types/tutorial009b.py!}
- ```
+////
-=== "Python 3.10 і вище"
+//// tab | Python 3.10 і вище
- ```Python hl_lines="1"
- {!> ../../../docs_src/python_types/tutorial009_py310.py!}
- ```
+```Python hl_lines="1"
+{!> ../../../docs_src/python_types/tutorial009_py310.py!}
+```
+
+////
#### Generic типи
Ці типи, які приймають параметри типу у квадратних дужках, називаються **Generic types** or **Generics**, наприклад:
-=== "Python 3.8 і вище"
+//// tab | Python 3.8 і вище
+
+* `List`
+* `Tuple`
+* `Set`
+* `Dict`
+* `Union`
+* `Optional`
+* ...та інші.
+
+////
- * `List`
- * `Tuple`
- * `Set`
- * `Dict`
- * `Union`
- * `Optional`
- * ...та інші.
+//// tab | Python 3.9 і вище
-=== "Python 3.9 і вище"
+Ви можете використовувати ті самі вбудовані типи, як generic (з квадратними дужками та типами всередині):
- Ви можете використовувати ті самі вбудовані типи, як generic (з квадратними дужками та типами всередині):
+* `list`
+* `tuple`
+* `set`
+* `dict`
- * `list`
- * `tuple`
- * `set`
- * `dict`
+І те саме, що й у Python 3.8, із модуля `typing`:
- І те саме, що й у Python 3.8, із модуля `typing`:
+* `Union`
+* `Optional`
+* ...та інші.
- * `Union`
- * `Optional`
- * ...та інші.
+////
-=== "Python 3.10 і вище"
+//// tab | Python 3.10 і вище
- Ви можете використовувати ті самі вбудовані типи, як generic (з квадратними дужками та типами всередині):
+Ви можете використовувати ті самі вбудовані типи, як generic (з квадратними дужками та типами всередині):
- * `list`
- * `tuple`
- * `set`
- * `dict`
+* `list`
+* `tuple`
+* `set`
+* `dict`
- І те саме, що й у Python 3.8, із модуля `typing`:
+І те саме, що й у Python 3.8, із модуля `typing`:
- * `Union`
- * `Optional` (так само як у Python 3.8)
- * ...та інші.
+* `Union`
+* `Optional` (так само як у Python 3.8)
+* ...та інші.
- У Python 3.10, як альтернатива використанню `Union` та `Optional`, ви можете використовувати <abbr title='також називають «побітовим "або" оператором», але це значення тут не актуальне'>вертикальну смугу (`|`)</abbr> щоб оголосити об'єднання типів.
+У Python 3.10, як альтернатива використанню `Union` та `Optional`, ви можете використовувати <abbr title='також називають «побітовим "або" оператором», але це значення тут не актуальне'>вертикальну смугу (`|`)</abbr> щоб оголосити об'єднання типів.
+
+////
### Класи як типи
Приклад з документації Pydantic:
-=== "Python 3.8 і вище"
+//// tab | Python 3.8 і вище
+
+```Python
+{!> ../../../docs_src/python_types/tutorial011.py!}
+```
+
+////
+
+//// tab | Python 3.9 і вище
+
+```Python
+{!> ../../../docs_src/python_types/tutorial011_py39.py!}
+```
- ```Python
- {!> ../../../docs_src/python_types/tutorial011.py!}
- ```
+////
-=== "Python 3.9 і вище"
+//// tab | Python 3.10 і вище
- ```Python
- {!> ../../../docs_src/python_types/tutorial011_py39.py!}
- ```
+```Python
+{!> ../../../docs_src/python_types/tutorial011_py310.py!}
+```
-=== "Python 3.10 і вище"
+////
- ```Python
- {!> ../../../docs_src/python_types/tutorial011_py310.py!}
- ```
+/// info
-!!! info
- Щоб дізнатись більше про <a href="https://docs.pydantic.dev/" class="external-link" target="_blank">Pydantic, перегляньте його документацію</a>.
+Щоб дізнатись більше про <a href="https://docs.pydantic.dev/" class="external-link" target="_blank">Pydantic, перегляньте його документацію</a>.
+
+///
**FastAPI** повністю базується на Pydantic.
Важливо те, що за допомогою стандартних типів Python в одному місці (замість того, щоб додавати більше класів, декораторів тощо), **FastAPI** зробить багато роботи за вас.
-!!! info
- Якщо ви вже пройшли весь навчальний посібник і повернулися, щоб дізнатися більше про типи, ось хороший ресурс <a href="https://mypy.readthedocs.io/en/latest/cheat_sheet_py3.html" class="external-link" target="_blank">"шпаргалка" від `mypy`</a>.
+/// info
+
+Якщо ви вже пройшли весь навчальний посібник і повернулися, щоб дізнатися більше про типи, ось хороший ресурс <a href="https://mypy.readthedocs.io/en/latest/cheat_sheet_py3.html" class="external-link" target="_blank">"шпаргалка" від `mypy`</a>.
+
+///
Спочатку вам потрібно імпортувати це:
-=== "Python 3.10+"
+//// tab | Python 3.10+
- ```Python hl_lines="4"
- {!> ../../../docs_src/body_fields/tutorial001_an_py310.py!}
- ```
+```Python hl_lines="4"
+{!> ../../../docs_src/body_fields/tutorial001_an_py310.py!}
+```
-=== "Python 3.9+"
+////
- ```Python hl_lines="4"
- {!> ../../../docs_src/body_fields/tutorial001_an_py39.py!}
- ```
+//// tab | Python 3.9+
-=== "Python 3.8+"
+```Python hl_lines="4"
+{!> ../../../docs_src/body_fields/tutorial001_an_py39.py!}
+```
- ```Python hl_lines="4"
- {!> ../../../docs_src/body_fields/tutorial001_an.py!}
- ```
+////
-=== "Python 3.10+ non-Annotated"
+//// tab | Python 3.8+
- !!! tip
- Варто користуватись `Annotated` версією, якщо це можливо.
+```Python hl_lines="4"
+{!> ../../../docs_src/body_fields/tutorial001_an.py!}
+```
- ```Python hl_lines="2"
- {!> ../../../docs_src/body_fields/tutorial001_py310.py!}
- ```
+////
-=== "Python 3.8+ non-Annotated"
+//// tab | Python 3.10+ non-Annotated
- !!! tip
- Варто користуватись `Annotated` версією, якщо це можливо.
+/// tip
- ```Python hl_lines="4"
- {!> ../../../docs_src/body_fields/tutorial001.py!}
- ```
+Варто користуватись `Annotated` версією, якщо це можливо.
-!!! warning
- Зверніть увагу, що `Field` імпортується прямо з `pydantic`, а не з `fastapi`, як всі інші (`Query`, `Path`, `Body` тощо).
+///
+
+```Python hl_lines="2"
+{!> ../../../docs_src/body_fields/tutorial001_py310.py!}
+```
+
+////
+
+//// tab | Python 3.8+ non-Annotated
+
+/// tip
+
+Варто користуватись `Annotated` версією, якщо це можливо.
+
+///
+
+```Python hl_lines="4"
+{!> ../../../docs_src/body_fields/tutorial001.py!}
+```
+
+////
+
+/// warning
+
+Зверніть увагу, що `Field` імпортується прямо з `pydantic`, а не з `fastapi`, як всі інші (`Query`, `Path`, `Body` тощо).
+
+///
## Оголошення атрибутів моделі
Ви можете використовувати `Field` з атрибутами моделі:
-=== "Python 3.10+"
+//// tab | Python 3.10+
+
+```Python hl_lines="11-14"
+{!> ../../../docs_src/body_fields/tutorial001_an_py310.py!}
+```
+
+////
- ```Python hl_lines="11-14"
- {!> ../../../docs_src/body_fields/tutorial001_an_py310.py!}
- ```
+//// tab | Python 3.9+
-=== "Python 3.9+"
+```Python hl_lines="11-14"
+{!> ../../../docs_src/body_fields/tutorial001_an_py39.py!}
+```
- ```Python hl_lines="11-14"
- {!> ../../../docs_src/body_fields/tutorial001_an_py39.py!}
- ```
+////
-=== "Python 3.8+"
+//// tab | Python 3.8+
- ```Python hl_lines="12-15"
- {!> ../../../docs_src/body_fields/tutorial001_an.py!}
- ```
+```Python hl_lines="12-15"
+{!> ../../../docs_src/body_fields/tutorial001_an.py!}
+```
-=== "Python 3.10+ non-Annotated"
+////
- !!! tip
- Варто користуватись `Annotated` версією, якщо це можливо..
+//// tab | Python 3.10+ non-Annotated
- ```Python hl_lines="9-12"
- {!> ../../../docs_src/body_fields/tutorial001_py310.py!}
- ```
+/// tip
-=== "Python 3.8+ non-Annotated"
+Варто користуватись `Annotated` версією, якщо це можливо..
- !!! tip
- Варто користуватись `Annotated` версією, якщо це можливо..
+///
- ```Python hl_lines="11-14"
- {!> ../../../docs_src/body_fields/tutorial001.py!}
- ```
+```Python hl_lines="9-12"
+{!> ../../../docs_src/body_fields/tutorial001_py310.py!}
+```
+
+////
+
+//// tab | Python 3.8+ non-Annotated
+
+/// tip
+
+Варто користуватись `Annotated` версією, якщо це можливо..
+
+///
+
+```Python hl_lines="11-14"
+{!> ../../../docs_src/body_fields/tutorial001.py!}
+```
+
+////
`Field` працює так само, як `Query`, `Path` і `Body`, у нього такі самі параметри тощо.
-!!! note "Технічні деталі"
- Насправді, `Query`, `Path` та інші, що ви побачите далі, створюють об'єкти підкласів загального класу `Param`, котрий сам є підкласом класу `FieldInfo` з Pydantic.
+/// note | "Технічні деталі"
- І `Field` від Pydantic також повертає екземпляр `FieldInfo`.
+Насправді, `Query`, `Path` та інші, що ви побачите далі, створюють об'єкти підкласів загального класу `Param`, котрий сам є підкласом класу `FieldInfo` з Pydantic.
- `Body` також безпосередньо повертає об'єкти підкласу `FieldInfo`. І є інші підкласи, які ви побачите пізніше, що є підкласами класу Body.
+І `Field` від Pydantic також повертає екземпляр `FieldInfo`.
- Пам'ятайте, що коли ви імпортуєте 'Query', 'Path' та інше з 'fastapi', вони фактично є функціями, які повертають спеціальні класи.
+`Body` також безпосередньо повертає об'єкти підкласу `FieldInfo`. І є інші підкласи, які ви побачите пізніше, що є підкласами класу Body.
-!!! tip
- Зверніть увагу, що кожен атрибут моделі із типом, значенням за замовчуванням та `Field` має ту саму структуру, що й параметр *функції обробки шляху*, з `Field` замість `Path`, `Query` і `Body`.
+Пам'ятайте, що коли ви імпортуєте 'Query', 'Path' та інше з 'fastapi', вони фактично є функціями, які повертають спеціальні класи.
+
+///
+
+/// tip
+
+Зверніть увагу, що кожен атрибут моделі із типом, значенням за замовчуванням та `Field` має ту саму структуру, що й параметр *функції обробки шляху*, з `Field` замість `Path`, `Query` і `Body`.
+
+///
## Додавання додаткової інформації
Ви дізнаєтеся більше про додавання додаткової інформації пізніше у документації, коли вивчатимете визначення прикладів.
-!!! warning
- Додаткові ключі, передані в `Field`, також будуть присутні у згенерованій схемі OpenAPI для вашого додатка.
- Оскільки ці ключі не обов'язково можуть бути частиною специфікації OpenAPI, деякі інструменти OpenAPI, наприклад, [OpenAPI валідатор](https://validator.swagger.io/), можуть не працювати з вашою згенерованою схемою.
+/// warning
+
+Додаткові ключі, передані в `Field`, також будуть присутні у згенерованій схемі OpenAPI для вашого додатка.
+Оскільки ці ключі не обов'язково можуть бути частиною специфікації OpenAPI, деякі інструменти OpenAPI, наприклад, [OpenAPI валідатор](https://validator.swagger.io/), можуть не працювати з вашою згенерованою схемою.
+
+///
## Підсумок
Щоб оголосити тіло **запиту**, ви використовуєте <a href="https://docs.pydantic.dev/" class="external-link" target="_blank">Pydantic</a> моделі з усією їх потужністю та перевагами.
-!!! info
- Щоб надіслати дані, ви повинні використовувати один із: `POST` (більш поширений), `PUT`, `DELETE` або `PATCH`.
+/// info
- Надсилання тіла із запитом `GET` має невизначену поведінку в специфікаціях, проте воно підтримується FastAPI лише для дуже складних/екстремальних випадків використання.
+Щоб надіслати дані, ви повинні використовувати один із: `POST` (більш поширений), `PUT`, `DELETE` або `PATCH`.
- Оскільки це не рекомендується, інтерактивна документація з Swagger UI не відображатиме документацію для тіла запиту під час використання `GET`, і проксі-сервери в середині можуть не підтримувати її.
+Надсилання тіла із запитом `GET` має невизначену поведінку в специфікаціях, проте воно підтримується FastAPI лише для дуже складних/екстремальних випадків використання.
+
+Оскільки це не рекомендується, інтерактивна документація з Swagger UI не відображатиме документацію для тіла запиту під час використання `GET`, і проксі-сервери в середині можуть не підтримувати її.
+
+///
## Імпортуйте `BaseModel` від Pydantic
Спочатку вам потрібно імпортувати `BaseModel` з `pydantic`:
-=== "Python 3.8 і вище"
+//// tab | Python 3.8 і вище
+
+```Python hl_lines="4"
+{!> ../../../docs_src/body/tutorial001.py!}
+```
+
+////
- ```Python hl_lines="4"
- {!> ../../../docs_src/body/tutorial001.py!}
- ```
+//// tab | Python 3.10 і вище
-=== "Python 3.10 і вище"
+```Python hl_lines="2"
+{!> ../../../docs_src/body/tutorial001_py310.py!}
+```
- ```Python hl_lines="2"
- {!> ../../../docs_src/body/tutorial001_py310.py!}
- ```
+////
## Створіть свою модель даних
Використовуйте стандартні типи Python для всіх атрибутів:
-=== "Python 3.8 і вище"
+//// tab | Python 3.8 і вище
- ```Python hl_lines="7-11"
- {!> ../../../docs_src/body/tutorial001.py!}
- ```
+```Python hl_lines="7-11"
+{!> ../../../docs_src/body/tutorial001.py!}
+```
-=== "Python 3.10 і вище"
+////
- ```Python hl_lines="5-9"
- {!> ../../../docs_src/body/tutorial001_py310.py!}
- ```
+//// tab | Python 3.10 і вище
+
+```Python hl_lines="5-9"
+{!> ../../../docs_src/body/tutorial001_py310.py!}
+```
+
+////
Так само, як і при оголошенні параметрів запиту, коли атрибут моделі має значення за замовчуванням, він не є обов’язковим. В іншому випадку це потрібно. Використовуйте `None`, щоб зробити його необов'язковим.
Щоб додати модель даних до вашої *операції шляху*, оголосіть її так само, як ви оголосили параметри шляху та запиту:
-=== "Python 3.8 і вище"
+//// tab | Python 3.8 і вище
- ```Python hl_lines="18"
- {!> ../../../docs_src/body/tutorial001.py!}
- ```
+```Python hl_lines="18"
+{!> ../../../docs_src/body/tutorial001.py!}
+```
-=== "Python 3.10 і вище"
+////
- ```Python hl_lines="16"
- {!> ../../../docs_src/body/tutorial001_py310.py!}
- ```
+//// tab | Python 3.10 і вище
+
+```Python hl_lines="16"
+{!> ../../../docs_src/body/tutorial001_py310.py!}
+```
+
+////
...і вкажіть її тип як модель, яку ви створили, `Item`.
<img src="/img/tutorial/body/image05.png">
-!!! tip
- Якщо ви використовуєте <a href="https://www.jetbrains.com/pycharm/" class="external-link" target="_blank">PyCharm</a> як ваш редактор, ви можете використати <a href="https://github.com/koxudaxi/pydantic-pycharm-plugin/" class="external-link" target="_blank">Pydantic PyCharm Plugin</a>.
+/// tip
+
+Якщо ви використовуєте <a href="https://www.jetbrains.com/pycharm/" class="external-link" target="_blank">PyCharm</a> як ваш редактор, ви можете використати <a href="https://github.com/koxudaxi/pydantic-pycharm-plugin/" class="external-link" target="_blank">Pydantic PyCharm Plugin</a>.
- Він покращує підтримку редакторів для моделей Pydantic за допомогою:
+Він покращує підтримку редакторів для моделей Pydantic за допомогою:
- * автозаповнення
- * перевірки типу
- * рефакторингу
- * пошуку
- * інспекції
+* автозаповнення
+* перевірки типу
+* рефакторингу
+* пошуку
+* інспекції
+
+///
## Використовуйте модель
Усередині функції ви можете отримати прямий доступ до всіх атрибутів об’єкта моделі:
-=== "Python 3.8 і вище"
+//// tab | Python 3.8 і вище
+
+```Python hl_lines="21"
+{!> ../../../docs_src/body/tutorial002.py!}
+```
+
+////
- ```Python hl_lines="21"
- {!> ../../../docs_src/body/tutorial002.py!}
- ```
+//// tab | Python 3.10 і вище
-=== "Python 3.10 і вище"
+```Python hl_lines="19"
+{!> ../../../docs_src/body/tutorial002_py310.py!}
+```
- ```Python hl_lines="19"
- {!> ../../../docs_src/body/tutorial002_py310.py!}
- ```
+////
## Тіло запиту + параметри шляху
**FastAPI** розпізнає, що параметри функції, які відповідають параметрам шляху, мають бути **взяті з шляху**, а параметри функції, які оголошуються як моделі Pydantic, **взяті з тіла запиту**.
-=== "Python 3.8 і вище"
+//// tab | Python 3.8 і вище
+
+```Python hl_lines="17-18"
+{!> ../../../docs_src/body/tutorial003.py!}
+```
- ```Python hl_lines="17-18"
- {!> ../../../docs_src/body/tutorial003.py!}
- ```
+////
-=== "Python 3.10 і вище"
+//// tab | Python 3.10 і вище
- ```Python hl_lines="15-16"
- {!> ../../../docs_src/body/tutorial003_py310.py!}
- ```
+```Python hl_lines="15-16"
+{!> ../../../docs_src/body/tutorial003_py310.py!}
+```
+
+////
## Тіло запиту + шлях + параметри запиту
**FastAPI** розпізнає кожен з них і візьме дані з потрібного місця.
-=== "Python 3.8 і вище"
+//// tab | Python 3.8 і вище
+
+```Python hl_lines="18"
+{!> ../../../docs_src/body/tutorial004.py!}
+```
- ```Python hl_lines="18"
- {!> ../../../docs_src/body/tutorial004.py!}
- ```
+////
-=== "Python 3.10 і вище"
+//// tab | Python 3.10 і вище
- ```Python hl_lines="16"
- {!> ../../../docs_src/body/tutorial004_py310.py!}
- ```
+```Python hl_lines="16"
+{!> ../../../docs_src/body/tutorial004_py310.py!}
+```
+
+////
Параметри функції будуть розпізнаватися наступним чином:
* Якщо параметр має **сингулярний тип** (наприклад, `int`, `float`, `str`, `bool` тощо), він буде інтерпретуватися як параметр **запиту**.
* Якщо параметр оголошується як тип **Pydantic моделі**, він інтерпретується як **тіло** запиту.
-!!! note
- FastAPI буде знати, що значення "q" не є обов'язковим через значення за замовчуванням "= None".
+/// note
+
+FastAPI буде знати, що значення "q" не є обов'язковим через значення за замовчуванням "= None".
+
+`Optional` у `Optional[str]` не використовується FastAPI, але дозволить вашому редактору надати вам кращу підтримку та виявляти помилки.
- `Optional` у `Optional[str]` не використовується FastAPI, але дозволить вашому редактору надати вам кращу підтримку та виявляти помилки.
+///
## Без Pydantic
Спочатку імпортуйте `Cookie`:
-=== "Python 3.10+"
+//// tab | Python 3.10+
- ```Python hl_lines="3"
- {!> ../../../docs_src/cookie_params/tutorial001_an_py310.py!}
- ```
+```Python hl_lines="3"
+{!> ../../../docs_src/cookie_params/tutorial001_an_py310.py!}
+```
-=== "Python 3.9+"
+////
- ```Python hl_lines="3"
- {!> ../../../docs_src/cookie_params/tutorial001_an_py39.py!}
- ```
+//// tab | Python 3.9+
-=== "Python 3.8+"
+```Python hl_lines="3"
+{!> ../../../docs_src/cookie_params/tutorial001_an_py39.py!}
+```
- ```Python hl_lines="3"
- {!> ../../../docs_src/cookie_params/tutorial001_an.py!}
- ```
+////
-=== "Python 3.10+ non-Annotated"
+//// tab | Python 3.8+
- !!! tip
- Бажано використовувати `Annotated` версію, якщо це можливо.
+```Python hl_lines="3"
+{!> ../../../docs_src/cookie_params/tutorial001_an.py!}
+```
- ```Python hl_lines="1"
- {!> ../../../docs_src/cookie_params/tutorial001_py310.py!}
- ```
+////
-=== "Python 3.8+ non-Annotated"
+//// tab | Python 3.10+ non-Annotated
- !!! tip
- Бажано використовувати `Annotated` версію, якщо це можливо.
+/// tip
- ```Python hl_lines="3"
- {!> ../../../docs_src/cookie_params/tutorial001.py!}
- ```
+Бажано використовувати `Annotated` версію, якщо це можливо.
+
+///
+
+```Python hl_lines="1"
+{!> ../../../docs_src/cookie_params/tutorial001_py310.py!}
+```
+
+////
+
+//// tab | Python 3.8+ non-Annotated
+
+/// tip
+
+Бажано використовувати `Annotated` версію, якщо це можливо.
+
+///
+
+```Python hl_lines="3"
+{!> ../../../docs_src/cookie_params/tutorial001.py!}
+```
+
+////
## Визначення параметрів `Cookie`
Перше значення це значення за замовчуванням, ви можете також передати всі додаткові параметри валідації чи анотації:
-=== "Python 3.10+"
+//// tab | Python 3.10+
+
+```Python hl_lines="9"
+{!> ../../../docs_src/cookie_params/tutorial001_an_py310.py!}
+```
+
+////
+
+//// tab | Python 3.9+
+
+```Python hl_lines="9"
+{!> ../../../docs_src/cookie_params/tutorial001_an_py39.py!}
+```
+
+////
+
+//// tab | Python 3.8+
+
+```Python hl_lines="10"
+{!> ../../../docs_src/cookie_params/tutorial001_an.py!}
+```
+
+////
+
+//// tab | Python 3.10+ non-Annotated
+
+/// tip
+
+Бажано використовувати `Annotated` версію, якщо це можливо.
+
+///
+
+```Python hl_lines="7"
+{!> ../../../docs_src/cookie_params/tutorial001_py310.py!}
+```
- ```Python hl_lines="9"
- {!> ../../../docs_src/cookie_params/tutorial001_an_py310.py!}
- ```
+////
-=== "Python 3.9+"
+//// tab | Python 3.8+ non-Annotated
- ```Python hl_lines="9"
- {!> ../../../docs_src/cookie_params/tutorial001_an_py39.py!}
- ```
+/// tip
-=== "Python 3.8+"
+Бажано використовувати `Annotated` версію, якщо це можливо.
- ```Python hl_lines="10"
- {!> ../../../docs_src/cookie_params/tutorial001_an.py!}
- ```
+///
-=== "Python 3.10+ non-Annotated"
+```Python hl_lines="9"
+{!> ../../../docs_src/cookie_params/tutorial001.py!}
+```
- !!! tip
- Бажано використовувати `Annotated` версію, якщо це можливо.
+////
- ```Python hl_lines="7"
- {!> ../../../docs_src/cookie_params/tutorial001_py310.py!}
- ```
+/// note | "Технічні Деталі"
-=== "Python 3.8+ non-Annotated"
+`Cookie` це "сестра" класів `Path` і `Query`. Вони наслідуються від одного батьківського класу `Param`.
+Але пам'ятайте, що коли ви імпортуєте `Query`, `Path`, `Cookie` та інше з `fastapi`, це фактично функції, що повертають спеціальні класи.
- !!! tip
- Бажано використовувати `Annotated` версію, якщо це можливо.
+///
- ```Python hl_lines="9"
- {!> ../../../docs_src/cookie_params/tutorial001.py!}
- ```
+/// info
-!!! note "Технічні Деталі"
- `Cookie` це "сестра" класів `Path` і `Query`. Вони наслідуються від одного батьківського класу `Param`.
- Але пам'ятайте, що коли ви імпортуєте `Query`, `Path`, `Cookie` та інше з `fastapi`, це фактично функції, що повертають спеціальні класи.
+Для визначення cookies ви маєте використовувати `Cookie`, тому що в іншому випадку параметри будуть інтерпритовані, як параметри запиту.
-!!! info
- Для визначення cookies ви маєте використовувати `Cookie`, тому що в іншому випадку параметри будуть інтерпритовані, як параметри запиту.
+///
## Підсумки
Вона приймає об'єкт, такий як Pydantic model, і повертає його версію, сумісну з JSON:
-=== "Python 3.10+"
+//// tab | Python 3.10+
- ```Python hl_lines="4 21"
- {!> ../../../docs_src/encoder/tutorial001_py310.py!}
- ```
+```Python hl_lines="4 21"
+{!> ../../../docs_src/encoder/tutorial001_py310.py!}
+```
-=== "Python 3.8+"
+////
- ```Python hl_lines="5 22"
- {!> ../../../docs_src/encoder/tutorial001.py!}
- ```
+//// tab | Python 3.8+
+
+```Python hl_lines="5 22"
+{!> ../../../docs_src/encoder/tutorial001.py!}
+```
+
+////
У цьому прикладі вона конвертує Pydantic model у `dict`, а `datetime` у `str`.
Вона не повертає велику строку `str`, яка містить дані у форматі JSON (як строка). Вона повертає стандартну структуру даних Python (наприклад `dict`) із значеннями та підзначеннями, які є сумісними з JSON.
-!!! note "Примітка"
- `jsonable_encoder` фактично використовується **FastAPI** внутрішньо для перетворення даних. Проте вона корисна в багатьох інших сценаріях.
+/// note | "Примітка"
+
+`jsonable_encoder` фактично використовується **FastAPI** внутрішньо для перетворення даних. Проте вона корисна в багатьох інших сценаріях.
+
+///
Ось приклад *path operation* з параметрами, використовуючи деякі з вищезазначених типів.
-=== "Python 3.10+"
+//// tab | Python 3.10+
- ```Python hl_lines="1 3 12-16"
- {!> ../../../docs_src/extra_data_types/tutorial001_an_py310.py!}
- ```
+```Python hl_lines="1 3 12-16"
+{!> ../../../docs_src/extra_data_types/tutorial001_an_py310.py!}
+```
-=== "Python 3.9+"
+////
- ```Python hl_lines="1 3 12-16"
- {!> ../../../docs_src/extra_data_types/tutorial001_an_py39.py!}
- ```
+//// tab | Python 3.9+
-=== "Python 3.8+"
+```Python hl_lines="1 3 12-16"
+{!> ../../../docs_src/extra_data_types/tutorial001_an_py39.py!}
+```
- ```Python hl_lines="1 3 13-17"
- {!> ../../../docs_src/extra_data_types/tutorial001_an.py!}
- ```
+////
-=== "Python 3.10+ non-Annotated"
+//// tab | Python 3.8+
- !!! tip
- Бажано використовувати `Annotated` версію, якщо це можливо.
+```Python hl_lines="1 3 13-17"
+{!> ../../../docs_src/extra_data_types/tutorial001_an.py!}
+```
- ```Python hl_lines="1 2 11-15"
- {!> ../../../docs_src/extra_data_types/tutorial001_py310.py!}
- ```
+////
-=== "Python 3.8+ non-Annotated"
+//// tab | Python 3.10+ non-Annotated
- !!! tip
- Бажано використовувати `Annotated` версію, якщо це можливо.
+/// tip
- ```Python hl_lines="1 2 12-16"
- {!> ../../../docs_src/extra_data_types/tutorial001.py!}
- ```
+Бажано використовувати `Annotated` версію, якщо це можливо.
+
+///
+
+```Python hl_lines="1 2 11-15"
+{!> ../../../docs_src/extra_data_types/tutorial001_py310.py!}
+```
+
+////
+
+//// tab | Python 3.8+ non-Annotated
+
+/// tip
+
+Бажано використовувати `Annotated` версію, якщо це можливо.
+
+///
+
+```Python hl_lines="1 2 12-16"
+{!> ../../../docs_src/extra_data_types/tutorial001.py!}
+```
+
+////
Зверніть увагу, що параметри всередині функції мають свій звичайний тип даних, і ви можете, наприклад, виконувати звичайні маніпуляції з датами, такі як:
-=== "Python 3.10+"
+//// tab | Python 3.10+
+
+```Python hl_lines="18-19"
+{!> ../../../docs_src/extra_data_types/tutorial001_an_py310.py!}
+```
+
+////
+
+//// tab | Python 3.9+
+
+```Python hl_lines="18-19"
+{!> ../../../docs_src/extra_data_types/tutorial001_an_py39.py!}
+```
+
+////
+
+//// tab | Python 3.8+
+
+```Python hl_lines="19-20"
+{!> ../../../docs_src/extra_data_types/tutorial001_an.py!}
+```
+
+////
+
+//// tab | Python 3.10+ non-Annotated
- ```Python hl_lines="18-19"
- {!> ../../../docs_src/extra_data_types/tutorial001_an_py310.py!}
- ```
+/// tip
-=== "Python 3.9+"
+Бажано використовувати `Annotated` версію, якщо це можливо.
- ```Python hl_lines="18-19"
- {!> ../../../docs_src/extra_data_types/tutorial001_an_py39.py!}
- ```
+///
-=== "Python 3.8+"
+```Python hl_lines="17-18"
+{!> ../../../docs_src/extra_data_types/tutorial001_py310.py!}
+```
- ```Python hl_lines="19-20"
- {!> ../../../docs_src/extra_data_types/tutorial001_an.py!}
- ```
+////
-=== "Python 3.10+ non-Annotated"
+//// tab | Python 3.8+ non-Annotated
- !!! tip
- Бажано використовувати `Annotated` версію, якщо це можливо.
+/// tip
- ```Python hl_lines="17-18"
- {!> ../../../docs_src/extra_data_types/tutorial001_py310.py!}
- ```
+Бажано використовувати `Annotated` версію, якщо це можливо.
-=== "Python 3.8+ non-Annotated"
+///
- !!! tip
- Бажано використовувати `Annotated` версію, якщо це можливо.
+```Python hl_lines="18-19"
+{!> ../../../docs_src/extra_data_types/tutorial001.py!}
+```
- ```Python hl_lines="18-19"
- {!> ../../../docs_src/extra_data_types/tutorial001.py!}
- ```
+////
`FastAPI` це клас у Python, який надає всю функціональність для API.
-!!! note "Технічні деталі"
- `FastAPI` це клас, який успадковується безпосередньо від `Starlette`.
+/// note | "Технічні деталі"
- Ви також можете використовувати всю функціональність <a href="https://www.starlette.io/" class="external-link" target="_blank">Starlette</a> у `FastAPI`.
+`FastAPI` це клас, який успадковується безпосередньо від `Starlette`.
+
+Ви також можете використовувати всю функціональність <a href="https://www.starlette.io/" class="external-link" target="_blank">Starlette</a> у `FastAPI`.
+
+///
### Крок 2: створюємо екземпляр `FastAPI`
/items/foo
```
-!!! info "Додаткова інформація"
- "Шлях" (path) також зазвичай називають "ендпоінтом" (endpoint) або "маршрутом" (route).
+/// info | "Додаткова інформація"
+
+"Шлях" (path) також зазвичай називають "ендпоінтом" (endpoint) або "маршрутом" (route).
+
+///
При створенні API, "шлях" є основним способом розділення "завдань" і "ресурсів".
#### Operation
* шлях `/`
* використовуючи <abbr title="an HTTP GET method"><code>get</code> операцію</abbr>
-!!! info "`@decorator` Додаткова інформація"
- Синтаксис `@something` у Python називається "декоратором".
+/// info | "`@decorator` Додаткова інформація"
+
+Синтаксис `@something` у Python називається "декоратором".
- Ви розташовуєте його над функцією. Як гарний декоративний капелюх (мабуть, звідти походить термін).
+Ви розташовуєте його над функцією. Як гарний декоративний капелюх (мабуть, звідти походить термін).
- "Декоратор" приймає функцію нижче і виконує з нею якусь дію.
+"Декоратор" приймає функцію нижче і виконує з нею якусь дію.
- У нашому випадку, цей декоратор повідомляє **FastAPI**, що функція нижче відповідає **шляху** `/` і **операції** `get`.
+У нашому випадку, цей декоратор повідомляє **FastAPI**, що функція нижче відповідає **шляху** `/` і **операції** `get`.
- Це і є "декоратор операції шляху (path operation decorator)".
+Це і є "декоратор операції шляху (path operation decorator)".
+
+///
Можна також використовувати операції:
* `@app.patch()`
* `@app.trace()`
-!!! tip "Порада"
- Ви можете використовувати кожну операцію (HTTP-метод) на свій розсуд.
+/// tip | "Порада"
+
+Ви можете використовувати кожну операцію (HTTP-метод) на свій розсуд.
- **FastAPI** не нав'язує жодного певного значення для кожного методу.
+**FastAPI** не нав'язує жодного певного значення для кожного методу.
- Наведена тут інформація є рекомендацією, а не обов'язковою вимогою.
+Наведена тут інформація є рекомендацією, а не обов'язковою вимогою.
- Наприклад, під час використання GraphQL зазвичай усі дії виконуються тільки за допомогою `POST` операцій.
+Наприклад, під час використання GraphQL зазвичай усі дії виконуються тільки за допомогою `POST` операцій.
+///
### Крок 4: визначте **функцію операції шляху (path operation function)**
{!../../../docs_src/first_steps/tutorial003.py!}
```
-!!! note "Примітка"
- Якщо не знаєте в чому різниця, подивіться [Конкурентність: *"Поспішаєш?"*](../async.md#in-a-hurry){.internal-link target=_blank}.
+/// note | "Примітка"
+
+Якщо не знаєте в чому різниця, подивіться [Конкурентність: *"Поспішаєш?"*](../async.md#in-a-hurry){.internal-link target=_blank}.
+
+///
### Крок 5: поверніть результат
...який також включає `uvicorn`, який ви можете використовувати як сервер, який запускає ваш код.
-!!! note
- Ви також можете встановити його частина за частиною.
+/// note
- Це те, що ви, ймовірно, зробили б, коли захочете розгорнути свою програму у виробничому середовищі:
+Ви також можете встановити його частина за частиною.
- ```
- pip install fastapi
- ```
+Це те, що ви, ймовірно, зробили б, коли захочете розгорнути свою програму у виробничому середовищі:
- Також встановіть `uvicorn`, щоб він працював як сервер:
+```
+pip install fastapi
+```
+
+Також встановіть `uvicorn`, щоб він працював як сервер:
+
+```
+pip install "uvicorn[standard]"
+```
- ```
- pip install "uvicorn[standard]"
- ```
+І те саме для кожної з опціональних залежностей, які ви хочете використовувати.
- І те саме для кожної з опціональних залежностей, які ви хочете використовувати.
+///
## Розширений посібник користувача
my_second_user: User = User(**second_user_data)
```
-!!! info
- `**second_user_data` nghĩa là:
+/// info
- Truyền các khóa và giá trị của dict `second_user_data` trực tiếp như các tham số kiểu key-value, tương đương với: `User(id=4, name="Mary", joined="2018-11-30")`
+`**second_user_data` nghĩa là:
+
+Truyền các khóa và giá trị của dict `second_user_data` trực tiếp như các tham số kiểu key-value, tương đương với: `User(id=4, name="Mary", joined="2018-11-30")`
+
+///
### Được hỗ trợ từ các trình soạn thảo
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.
+/// 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
Ví dụ, hãy định nghĩa một biến là `list` các `str`.
-=== "Python 3.9+"
+//// tab | Python 3.9+
- Khai báo biến với cùng dấu hai chấm (`:`).
+Khai báo biến với cùng dấu hai chấm (`:`).
- Tương tự kiểu dữ liệu `list`.
+Tương tự kiểu dữ liệu `list`.
- Như danh sách là một kiểu dữ liệu chứa một vài kiểu dữ liệu có sẵn, bạn đặt chúng trong các dấu ngoặc vuông:
+Như danh sách là một kiểu dữ liệu chứa một vài kiểu dữ liệu có sẵn, bạn đặt chúng trong các dấu ngoặc vuông:
- ```Python hl_lines="1"
- {!> ../../../docs_src/python_types/tutorial006_py39.py!}
- ```
+```Python hl_lines="1"
+{!> ../../../docs_src/python_types/tutorial006_py39.py!}
+```
-=== "Python 3.8+"
+////
- Từ `typing`, import `List` (với chữ cái `L` viết hoa):
+//// tab | Python 3.8+
- ```Python hl_lines="1"
- {!> ../../../docs_src/python_types/tutorial006.py!}
- ```
+Từ `typing`, import `List` (với chữ cái `L` viết hoa):
- Khai báo biến với cùng dấu hai chấm (`:`).
+```Python hl_lines="1"
+{!> ../../../docs_src/python_types/tutorial006.py!}
+```
+
+Khai báo biến với cùng dấu hai chấm (`:`).
- Tương tự như kiểu dữ liệu, `List` bạn import từ `typing`.
+Tương tự như kiểu dữ liệu, `List` bạn import từ `typing`.
- Như danh sách là một kiểu dữ liệu chứa các kiểu dữ liệu có sẵn, bạn đặt chúng bên trong dấu ngoặc vuông:
+Như danh sách là một kiểu dữ liệu chứa các kiểu dữ liệu có sẵn, bạn đặt chúng bên trong dấu ngoặc vuông:
+
+```Python hl_lines="4"
+{!> ../../../docs_src/python_types/tutorial006.py!}
+```
- ```Python hl_lines="4"
- {!> ../../../docs_src/python_types/tutorial006.py!}
- ```
+////
-!!! info
- Các kiểu dữ liệu có sẵn bên trong dấu ngoặc vuông được gọi là "tham số kiểu dữ liệu".
+/// info
- Trong trường hợp này, `str` là tham số kiểu dữ liệu được truyền tới `List` (hoặc `list` trong Python 3.9 trở lên).
+Các kiểu dữ liệu có sẵn bên trong dấu ngoặc vuông được gọi là "tham số kiểu dữ liệu".
+
+Trong trường hợp này, `str` là tham số kiểu dữ liệu được truyền tới `List` (hoặc `list` trong Python 3.9 trở lên).
+
+///
Có nghĩa là: "biến `items` là một `list`, và mỗi phần tử trong danh sách này là một `str`".
-!!! tip
- Nếu bạn sử dụng Python 3.9 hoặc lớn hơn, bạn không phải import `List` từ `typing`, bạn có thể sử dụng `list` để thay thế.
+/// tip
+
+Nếu bạn sử dụng Python 3.9 hoặc lớn hơn, bạn không phải import `List` từ `typing`, bạn có thể sử dụng `list` để thay thế.
+
+///
Bằng cách này, trình soạn thảo của bạn có thể hỗ trợ trong khi xử lí các phần tử trong danh sách:
Bạn sẽ làm điều tương tự để khai báo các `tuple` và các `set`:
-=== "Python 3.9+"
+//// tab | Python 3.9+
- ```Python hl_lines="1"
- {!> ../../../docs_src/python_types/tutorial007_py39.py!}
- ```
+```Python hl_lines="1"
+{!> ../../../docs_src/python_types/tutorial007_py39.py!}
+```
-=== "Python 3.8+"
+////
- ```Python hl_lines="1 4"
- {!> ../../../docs_src/python_types/tutorial007.py!}
- ```
+//// tab | Python 3.8+
+
+```Python hl_lines="1 4"
+{!> ../../../docs_src/python_types/tutorial007.py!}
+```
+
+////
Điều này có nghĩa là:
Tham số kiểu dữ liệu thứ hai dành cho giá trị của `dict`.
-=== "Python 3.9+"
+//// tab | Python 3.9+
+
+```Python hl_lines="1"
+{!> ../../../docs_src/python_types/tutorial008_py39.py!}
+```
+
+////
- ```Python hl_lines="1"
- {!> ../../../docs_src/python_types/tutorial008_py39.py!}
- ```
+//// tab | Python 3.8+
-=== "Python 3.8+"
+```Python hl_lines="1 4"
+{!> ../../../docs_src/python_types/tutorial008.py!}
+```
- ```Python hl_lines="1 4"
- {!> ../../../docs_src/python_types/tutorial008.py!}
- ```
+////
Điều này có nghĩa là:
Trong Python 3.10 cũng có một **cú pháp mới** mà bạn có thể đặt những kiểu giá trị khả thi phân cách bởi một dấu <abbr title='cũng được gọi là "toán tử nhị phân"'>sổ dọc (`|`)</abbr>.
-=== "Python 3.10+"
+//// tab | Python 3.10+
- ```Python hl_lines="1"
- {!> ../../../docs_src/python_types/tutorial008b_py310.py!}
- ```
+```Python hl_lines="1"
+{!> ../../../docs_src/python_types/tutorial008b_py310.py!}
+```
+
+////
+
+//// tab | Python 3.8+
-=== "Python 3.8+"
+```Python hl_lines="1 4"
+{!> ../../../docs_src/python_types/tutorial008b.py!}
+```
- ```Python hl_lines="1 4"
- {!> ../../../docs_src/python_types/tutorial008b.py!}
- ```
+////
Trong cả hai trường hợp có nghĩa là `item` có thể là một `int` hoặc `str`.
Điều này cũng có nghĩa là trong Python 3.10, bạn có thể sử dụng `Something | None`:
-=== "Python 3.10+"
+//// tab | Python 3.10+
- ```Python hl_lines="1"
- {!> ../../../docs_src/python_types/tutorial009_py310.py!}
- ```
+```Python hl_lines="1"
+{!> ../../../docs_src/python_types/tutorial009_py310.py!}
+```
-=== "Python 3.8+"
+////
- ```Python hl_lines="1 4"
- {!> ../../../docs_src/python_types/tutorial009.py!}
- ```
+//// tab | Python 3.8+
-=== "Python 3.8+ alternative"
+```Python hl_lines="1 4"
+{!> ../../../docs_src/python_types/tutorial009.py!}
+```
+
+////
+
+//// tab | Python 3.8+ alternative
- ```Python hl_lines="1 4"
- {!> ../../../docs_src/python_types/tutorial009b.py!}
- ```
+```Python hl_lines="1 4"
+{!> ../../../docs_src/python_types/tutorial009b.py!}
+```
+
+////
#### Sử dụng `Union` hay `Optional`
Những kiểu dữ liệu này lấy tham số kiểu dữ liệu trong dấu ngoặc vuông được gọi là **Kiểu dữ liệu tổng quát**, cho ví dụ:
-=== "Python 3.10+"
+//// tab | Python 3.10+
+
+Bạn có thể sử dụng các kiểu dữ liệu có sẵn như là kiểu dữ liệu tổng quát (với ngoặc vuông và kiểu dữ liệu bên trong):
- Bạn có thể sử dụng các kiểu dữ liệu có sẵn như là kiểu dữ liệu tổng quát (với ngoặc vuông và kiểu dữ liệu bên trong):
+* `list`
+* `tuple`
+* `set`
+* `dict`
- * `list`
- * `tuple`
- * `set`
- * `dict`
+Và tương tự với Python 3.6, từ mô đun `typing`:
- Và tương tự với Python 3.6, từ mô đun `typing`:
+* `Union`
+* `Optional` (tương tự như Python 3.6)
+* ...và các kiểu dữ liệu khác.
- * `Union`
- * `Optional` (tương tự như Python 3.6)
- * ...và các kiểu dữ liệu khác.
+Trong Python 3.10, thay vì sử dụng `Union` và `Optional`, bạn có thể sử dụng <abbr title='cũng gọi là "toán tử nhị phân", nhưng ý nghĩa không liên quan ở đây'>sổ dọc ('|')</abbr> để khai báo hợp của các kiểu dữ liệu, điều đó tốt hơn và đơn giản hơn nhiều.
- Trong Python 3.10, thay vì sử dụng `Union` và `Optional`, bạn có thể sử dụng <abbr title='cũng gọi là "toán tử nhị phân", nhưng ý nghĩa không liên quan ở đây'>sổ dọc ('|')</abbr> để khai báo hợp của các kiểu dữ liệu, điều đó tốt hơn và đơn giản hơn nhiều.
+////
-=== "Python 3.9+"
+//// tab | Python 3.9+
- Bạn có thể sử dụng các kiểu dữ liệu có sẵn tương tự như (với ngoặc vuông và kiểu dữ liệu bên trong):
+Bạn có thể sử dụng các kiểu dữ liệu có sẵn tương tự như (với ngoặc vuông và kiểu dữ liệu bên trong):
- * `list`
- * `tuple`
- * `set`
- * `dict`
+* `list`
+* `tuple`
+* `set`
+* `dict`
- Và tương tự với Python 3.6, từ mô đun `typing`:
+Và tương tự với Python 3.6, từ mô đun `typing`:
- * `Union`
- * `Optional`
- * ...and others.
+* `Union`
+* `Optional`
+* ...and others.
-=== "Python 3.8+"
+////
- * `List`
- * `Tuple`
- * `Set`
- * `Dict`
- * `Union`
- * `Optional`
- * ...và các kiểu khác.
+//// tab | Python 3.8+
+
+* `List`
+* `Tuple`
+* `Set`
+* `Dict`
+* `Union`
+* `Optional`
+* ...và các kiểu khác.
+
+////
### Lớp như kiểu dữ liệu
Một ví dụ từ tài liệu chính thức của Pydantic:
-=== "Python 3.10+"
+//// tab | Python 3.10+
+
+```Python
+{!> ../../../docs_src/python_types/tutorial011_py310.py!}
+```
+
+////
+
+//// tab | Python 3.9+
+
+```Python
+{!> ../../../docs_src/python_types/tutorial011_py39.py!}
+```
- ```Python
- {!> ../../../docs_src/python_types/tutorial011_py310.py!}
- ```
+////
-=== "Python 3.9+"
+//// tab | Python 3.8+
+
+```Python
+{!> ../../../docs_src/python_types/tutorial011.py!}
+```
- ```Python
- {!> ../../../docs_src/python_types/tutorial011_py39.py!}
- ```
+////
-=== "Python 3.8+"
+/// info
- ```Python
- {!> ../../../docs_src/python_types/tutorial011.py!}
- ```
+Để học nhiều hơn về <a href="https://docs.pydantic.dev/" class="external-link" target="_blank">Pydantic, tham khảo tài liệu của nó</a>.
-!!! info
- Để học nhiều hơn về <a href="https://docs.pydantic.dev/" class="external-link" target="_blank">Pydantic, tham khảo tài liệu của nó</a>.
+///
**FastAPI** được dựa hoàn toàn trên Pydantic.
Bạn sẽ thấy nhiều ví dụ thực tế hơn trong [Hướng dẫn sử dụng](tutorial/index.md){.internal-link target=_blank}.
-!!! tip
- Pydantic có một hành vi đặc biệt khi bạn sử dụng `Optional` hoặc `Union[Something, None]` mà không có giá trị mặc dịnh, bạn có thể đọc nhiều hơn về nó trong tài liệu của Pydantic về <a href="https://docs.pydantic.dev/latest/concepts/models/#required-optional-fields" class="external-link" target="_blank">Required Optional fields</a>.
+/// tip
+
+Pydantic có một hành vi đặc biệt khi bạn sử dụng `Optional` hoặc `Union[Something, None]` mà không có giá trị mặc dịnh, bạn có thể đọc nhiều hơn về nó trong tài liệu của Pydantic về <a href="https://docs.pydantic.dev/latest/concepts/models/#required-optional-fields" class="external-link" target="_blank">Required Optional fields</a>.
+///
## Type Hints với Metadata Annotations
Python cũng có một tính năng cho phép đặt **metadata bổ sung** trong những gợi ý kiểu dữ liệu này bằng cách sử dụng `Annotated`.
-=== "Python 3.9+"
+//// tab | Python 3.9+
+
+Trong Python 3.9, `Annotated` là một phần của thư viện chuẩn, do đó bạn có thể import nó từ `typing`.
+
+```Python hl_lines="1 4"
+{!> ../../../docs_src/python_types/tutorial013_py39.py!}
+```
- Trong Python 3.9, `Annotated` là một phần của thư viện chuẩn, do đó bạn có thể import nó từ `typing`.
+////
- ```Python hl_lines="1 4"
- {!> ../../../docs_src/python_types/tutorial013_py39.py!}
- ```
+//// tab | Python 3.8+
-=== "Python 3.8+"
+Ở phiên bản dưới Python 3.9, bạn import `Annotated` từ `typing_extensions`.
- Ở phiên bản dưới Python 3.9, bạn import `Annotated` từ `typing_extensions`.
+Nó đã được cài đặt sẵng cùng với **FastAPI**.
- Nó đã được cài đặt sẵng cùng với **FastAPI**.
+```Python hl_lines="1 4"
+{!> ../../../docs_src/python_types/tutorial013.py!}
+```
- ```Python hl_lines="1 4"
- {!> ../../../docs_src/python_types/tutorial013.py!}
- ```
+////
Python bản thân nó không làm bất kì điều gì với `Annotated`. Với các trình soạn thảo và các công cụ khác, kiểu dữ liệu vẫn là `str`.
Sau đó, bạn sẽ thấy sự **mạnh mẽ** mà nó có thể làm.
-!!! tip
- Thực tế, cái này là **tiêu chuẩn của Python**, nghĩa là bạn vẫn sẽ có được **trải nghiệm phát triển tốt nhất có thể** với trình soạn thảo của bạn, với các công cụ bạn sử dụng để phân tích và tái cấu trúc code của bạn, etc. ✨
+/// tip
- Và code của bạn sẽ tương thích với nhiều công cụ và thư viện khác của Python. 🚀
+Thực tế, cái này là **tiêu chuẩn của Python**, nghĩa là bạn vẫn sẽ có được **trải nghiệm phát triển tốt nhất có thể** với trình soạn thảo của bạn, với các công cụ bạn sử dụng để phân tích và tái cấu trúc code của bạn, etc. ✨
+
+Và code của bạn sẽ tương thích với nhiều công cụ và thư viện khác của Python. 🚀
+
+///
## Các gợi ý kiểu dữ liệu trong **FastAPI**
Điều quan trọng là bằng việc sử dụng các kiểu dữ liệu chuẩn của Python (thay vì thêm các lớp, decorators,...), **FastAPI** sẽ thực hiện nhiều công việc cho bạn.
-!!! info
- Nếu bạn đã đi qua toàn bộ các hướng dẫn và quay trở lại để tìm hiểu nhiều hơn về các kiểu dữ liệu, một tài nguyên tốt như <a href="https://mypy.readthedocs.io/en/latest/cheat_sheet_py3.html" class="external-link" target="_blank">"cheat sheet" từ `mypy`</a>.
+/// info
+
+Nếu bạn đã đi qua toàn bộ các hướng dẫn và quay trở lại để tìm hiểu nhiều hơn về các kiểu dữ liệu, một tài nguyên tốt như <a href="https://mypy.readthedocs.io/en/latest/cheat_sheet_py3.html" class="external-link" target="_blank">"cheat sheet" từ `mypy`</a>.
+
+///
</div>
-!!! note
- Câu lệnh `uvicorn main:app` được giải thích như sau:
+/// note
- * `main`: tệp tin `main.py` (một Python "mô đun").
- * `app`: một object được tạo ra bên trong `main.py` với dòng `app = FastAPI()`.
- * `--reload`: làm server khởi động lại sau mỗi lần thay đổi. Chỉ sử dụng trong môi trường phát triển.
+Câu lệnh `uvicorn main:app` được giải thích như sau:
+
+* `main`: tệp tin `main.py` (một Python "mô đun").
+* `app`: một object được tạo ra bên trong `main.py` với dòng `app = FastAPI()`.
+* `--reload`: làm server khởi động lại sau mỗi lần thay đổi. Chỉ sử dụng trong môi trường phát triển.
+
+///
Trong output, có một dòng giống như:
`FastAPI` là một Python class cung cấp tất cả chức năng cho API của bạn.
-!!! note "Chi tiết kĩ thuật"
- `FastAPI` là một class kế thừa trực tiếp `Starlette`.
+/// note | "Chi tiết kĩ thuật"
+
+`FastAPI` là một class kế thừa trực tiếp `Starlette`.
- Bạn cũng có thể sử dụng tất cả <a href="https://www.starlette.io/" class="external-link" target="_blank">Starlette</a> chức năng với `FastAPI`.
+Bạn cũng có thể sử dụng tất cả <a href="https://www.starlette.io/" class="external-link" target="_blank">Starlette</a> chức năng với `FastAPI`.
+
+///
### Bước 2: Tạo một `FastAPI` "instance"
/items/foo
```
-!!! info
- Một đường dẫn cũng là một cách gọi chung cho một "endpoint" hoặc một "route".
+/// info
+
+Một đường dẫn cũng là một cách gọi chung cho một "endpoint" hoặc một "route".
+
+///
Trong khi xây dựng một API, "đường dẫn" là các chính để phân tách "mối quan hệ" và "tài nguyên".
* đường dẫn `/`
* sử dụng một <abbr title="an HTTP GET method">toán tử<code>get</code></abbr>
-!!! info Thông tin về "`@decorator`"
- Cú pháp `@something` trong Python được gọi là một "decorator".
+/// info | Thông tin về "`@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).
+Cú pháp `@something` trong Python được gọi là một "decorator".
- 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ó.
+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).
- 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`.
+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ó.
- Nó là một "**decorator đường dẫn toán tử**".
+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.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.
+/// 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.
+**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.
+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`.
+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ử**
{!../../../docs_src/first_steps/tutorial003.py!}
```
-!!! note
- Nếu bạn không biết sự khác nhau, kiểm tra [Async: *"Trong khi vội vàng?"*](../async.md#in-a-hurry){.internal-link target=_blank}.
+/// 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ề
...dó cũng bao gồm `uvicorn`, bạn có thể sử dụng như một server để chạy code của bạn.
-!!! note
- Bạn cũng có thể cài đặt nó từng phần.
+/// note
- Đây là những gì bạn có thể sẽ làm một lần duy nhất bạn muốn triển khai ứng dụng của bạn lên production:
+Bạn cũng có thể cài đặt nó từng phần.
- ```
- pip install fastapi
- ```
+Đây là những gì bạn có thể sẽ làm một lần duy nhất bạn muốn triển khai ứng dụng của bạn lên production:
- Cũng cài đặt `uvicorn` để làm việc như một server:
+```
+pip install fastapi
+```
+
+Cũng cài đặt `uvicorn` để làm việc như một server:
+
+```
+pip install "uvicorn[standard]"
+```
- ```
- pip install "uvicorn[standard]"
- ```
+Và tương tự với từng phụ thuộc tùy chọn mà bạn muốn sử dụng.
- Và tương tự với từng phụ thuộc tùy chọn mà bạn muốn sử dụng.
+///
## Hướng dẫn nâng cao
-# 基準測試\r
-\r
-由第三方機構 TechEmpower 的基準測試表明在 Uvicorn 下運行的 **FastAPI** 應用程式是 <a href="https://www.techempower.com/benchmarks/#section=test&runid=7464e520-0dc2-473d-bd34-dbdfd7e85911&hw=ph&test=query&l=zijzen-7" class="external-link" target="_blank">最快的 Python 可用框架之一</a>,僅次於 Starlette 和 Uvicorn 本身(於 FastAPI 內部使用)。\r
-\r
-但是在查看基準得分和對比時,請注意以下幾點。\r
-\r
-## 基準測試和速度\r
-\r
-當你查看基準測試時,時常會見到幾個不同類型的工具被同時進行測試。\r
-\r
-具體來說,是將 Uvicorn、Starlette 和 FastAPI 同時進行比較(以及許多其他工具)。\r
-\r
-該工具解決的問題越簡單,其效能就越好。而且大多數基準測試不會測試該工具提供的附加功能。\r
-\r
-層次結構如下:\r
-\r
-* **Uvicorn**:ASGI 伺服器\r
- * **Starlette**:(使用 Uvicorn)一個網頁微框架\r
- * **FastAPI**:(使用 Starlette)一個 API 微框架,具有用於建立 API 的多個附加功能、資料驗證等。\r
-\r
-* **Uvicorn**:\r
- * 具有最佳效能,因為除了伺服器本身之外,它沒有太多額外的程式碼。\r
- * 你不會直接在 Uvicorn 中編寫應用程式。這意味著你的程式碼必須或多或少地包含 Starlette(或 **FastAPI**)提供的所有程式碼。如果你這樣做,你的最終應用程式將具有與使用框架相同的開銷並最大限度地減少應用程式程式碼和錯誤。\r
- * 如果你要比較 Uvicorn,請將其與 Daphne、Hypercorn、uWSGI 等應用程式伺服器進行比較。\r
-* **Starlette**:\r
- * 繼 Uvicorn 之後的次佳表現。事實上,Starlette 使用 Uvicorn 來運行。因此它將可能只透過執行更多程式碼而變得比 Uvicorn「慢」。\r
- * 但它為你提供了建立簡單網頁應用程式的工具,以及基於路徑的路由等。\r
- * 如果你要比較 Starlette,請將其與 Sanic、Flask、Django 等網頁框架(或微框架)進行比較。\r
-* **FastAPI**:\r
- * 就像 Starlette 使用 Uvicorn 並不能比它更快一樣, **FastAPI** 使用 Starlette,所以它不能比它更快。\r
- * FastAPI 在 Starlette 基礎之上提供了更多功能。包含建構 API 時所需要的功能,例如資料驗證和序列化。FastAPI 可以幫助你自動產生 API 文件,(應用程式啟動時將會自動生成文件,所以不會增加應用程式運行時的開銷)。\r
- * 如果你沒有使用 FastAPI 而是直接使用 Starlette(或其他工具,如 Sanic、Flask、Responder 等),你將必須自行實現所有資料驗證和序列化。因此,你的最終應用程式仍然具有與使用 FastAPI 建置相同的開銷。在許多情況下,這種資料驗證和序列化是應用程式中編寫最大量的程式碼。\r
- * 因此透過使用 FastAPI,你可以節省開發時間、錯誤與程式碼數量,並且相比不使用 FastAPI 你很大可能會獲得相同或更好的效能(因為那樣你必須在程式碼中實現所有相同的功能)。\r
- * 如果你要與 FastAPI 比較,請將其與能夠提供資料驗證、序列化和文件的網頁應用程式框架(或工具集)進行比較,例如 Flask-apispec、NestJS、Molten 等框架。\r
+# 基準測試
+
+由第三方機構 TechEmpower 的基準測試表明在 Uvicorn 下運行的 **FastAPI** 應用程式是 <a href="https://www.techempower.com/benchmarks/#section=test&runid=7464e520-0dc2-473d-bd34-dbdfd7e85911&hw=ph&test=query&l=zijzen-7" class="external-link" target="_blank">最快的 Python 可用框架之一</a>,僅次於 Starlette 和 Uvicorn 本身(於 FastAPI 內部使用)。
+
+但是在查看基準得分和對比時,請注意以下幾點。
+
+## 基準測試和速度
+
+當你查看基準測試時,時常會見到幾個不同類型的工具被同時進行測試。
+
+具體來說,是將 Uvicorn、Starlette 和 FastAPI 同時進行比較(以及許多其他工具)。
+
+該工具解決的問題越簡單,其效能就越好。而且大多數基準測試不會測試該工具提供的附加功能。
+
+層次結構如下:
+
+* **Uvicorn**:ASGI 伺服器
+ * **Starlette**:(使用 Uvicorn)一個網頁微框架
+ * **FastAPI**:(使用 Starlette)一個 API 微框架,具有用於建立 API 的多個附加功能、資料驗證等。
+
+* **Uvicorn**:
+ * 具有最佳效能,因為除了伺服器本身之外,它沒有太多額外的程式碼。
+ * 你不會直接在 Uvicorn 中編寫應用程式。這意味著你的程式碼必須或多或少地包含 Starlette(或 **FastAPI**)提供的所有程式碼。如果你這樣做,你的最終應用程式將具有與使用框架相同的開銷並最大限度地減少應用程式程式碼和錯誤。
+ * 如果你要比較 Uvicorn,請將其與 Daphne、Hypercorn、uWSGI 等應用程式伺服器進行比較。
+* **Starlette**:
+ * 繼 Uvicorn 之後的次佳表現。事實上,Starlette 使用 Uvicorn 來運行。因此它將可能只透過執行更多程式碼而變得比 Uvicorn「慢」。
+ * 但它為你提供了建立簡單網頁應用程式的工具,以及基於路徑的路由等。
+ * 如果你要比較 Starlette,請將其與 Sanic、Flask、Django 等網頁框架(或微框架)進行比較。
+* **FastAPI**:
+ * 就像 Starlette 使用 Uvicorn 並不能比它更快一樣, **FastAPI** 使用 Starlette,所以它不能比它更快。
+ * FastAPI 在 Starlette 基礎之上提供了更多功能。包含建構 API 時所需要的功能,例如資料驗證和序列化。FastAPI 可以幫助你自動產生 API 文件,(應用程式啟動時將會自動生成文件,所以不會增加應用程式運行時的開銷)。
+ * 如果你沒有使用 FastAPI 而是直接使用 Starlette(或其他工具,如 Sanic、Flask、Responder 等),你將必須自行實現所有資料驗證和序列化。因此,你的最終應用程式仍然具有與使用 FastAPI 建置相同的開銷。在許多情況下,這種資料驗證和序列化是應用程式中編寫最大量的程式碼。
+ * 因此透過使用 FastAPI,你可以節省開發時間、錯誤與程式碼數量,並且相比不使用 FastAPI 你很大可能會獲得相同或更好的效能(因為那樣你必須在程式碼中實現所有相同的功能)。
+ * 如果你要與 FastAPI 比較,請將其與能夠提供資料驗證、序列化和文件的網頁應用程式框架(或工具集)進行比較,例如 Flask-apispec、NestJS、Molten 等框架。
他們透過幫助其他人,證明了自己是 **FastAPI 專家**。 ✨
-!!! 提示
- 你也可以成為官方的 FastAPI 專家!
+/// 提示
- 只需要在 [GitHub 中幫助他人解答問題](help-fastapi.md#help-others-with-questions-in-github){.internal-link target=_blank}。 🤓
+你也可以成為官方的 FastAPI 專家!
+
+只需要在 [GitHub 中幫助他人解答問題](help-fastapi.md#help-others-with-questions-in-github){.internal-link target=_blank}。 🤓
+
+///
你可以查看這些期間的 **FastAPI 專家**:
{!../../../docs_src/additional_responses/tutorial001.py!}
```
+/// note
-!!! Note
- 请记住,您必须直接返回 `JSONResponse` 。
+请记住,您必须直接返回 `JSONResponse` 。
-!!! Info
- `model` 密钥不是OpenAPI的一部分。
- **FastAPI**将从那里获取`Pydantic`模型,生成` JSON Schema` ,并将其放在正确的位置。
- - 正确的位置是:
- - 在键 `content` 中,其具有另一个`JSON`对象( `dict` )作为值,该`JSON`对象包含:
- - 媒体类型的密钥,例如 `application/json` ,它包含另一个`JSON`对象作为值,该对象包含:
- - 一个键` schema` ,它的值是来自模型的`JSON Schema`,正确的位置在这里。
- - **FastAPI**在这里添加了对OpenAPI中另一个地方的全局JSON模式的引用,而不是直接包含它。这样,其他应用程序和客户端可以直接使用这些JSON模式,提供更好的代码生成工具等。
+///
+/// info
+
+`model` 密钥不是OpenAPI的一部分。
+**FastAPI**将从那里获取`Pydantic`模型,生成` JSON Schema` ,并将其放在正确的位置。
+- 正确的位置是:
+ - 在键 `content` 中,其具有另一个`JSON`对象( `dict` )作为值,该`JSON`对象包含:
+ - 媒体类型的密钥,例如 `application/json` ,它包含另一个`JSON`对象作为值,该对象包含:
+ - 一个键` schema` ,它的值是来自模型的`JSON Schema`,正确的位置在这里。
+ - **FastAPI**在这里添加了对OpenAPI中另一个地方的全局JSON模式的引用,而不是直接包含它。这样,其他应用程序和客户端可以直接使用这些JSON模式,提供更好的代码生成工具等。
+
+///
**在OpenAPI中为该路径操作生成的响应将是:**
{!../../../docs_src/additional_responses/tutorial002.py!}
```
-!!! Note
- - 请注意,您必须直接使用 `FileResponse` 返回图像。
+/// note
+
+- 请注意,您必须直接使用 `FileResponse` 返回图像。
+
+///
+
+/// info
+
+- 除非在 `responses` 参数中明确指定不同的媒体类型,否则**FastAPI**将假定响应与主响应类具有相同的媒体类型(默认为` application/json` )。
+- 但是如果您指定了一个自定义响应类,并将 `None `作为其媒体类型,**FastAPI**将使用 `application/json` 作为具有关联模型的任何其他响应。
-!!! Info
- - 除非在 `responses` 参数中明确指定不同的媒体类型,否则**FastAPI**将假定响应与主响应类具有相同的媒体类型(默认为` application/json` )。
- - 但是如果您指定了一个自定义响应类,并将 `None `作为其媒体类型,**FastAPI**将使用 `application/json` 作为具有关联模型的任何其他响应。
+///
## 组合信息
您还可以联合接收来自多个位置的响应信息,包括 `response_model `、 `status_code` 和 `responses `参数。
{!../../../docs_src/additional_status_codes/tutorial001.py!}
```
-!!! warning "警告"
- 当你直接返回一个像上面例子中的 `Response` 对象时,它会直接返回。
+/// warning | "警告"
- FastAPI 不会用模型等对该响应进行序列化。
+当你直接返回一个像上面例子中的 `Response` 对象时,它会直接返回。
- 确保其中有你想要的数据,且返回的值为合法的 JSON(如果你使用 `JSONResponse` 的话)。
+FastAPI 不会用模型等对该响应进行序列化。
-!!! note "技术细节"
- 你也可以使用 `from starlette.responses import JSONResponse`。
+确保其中有你想要的数据,且返回的值为合法的 JSON(如果你使用 `JSONResponse` 的话)。
- 出于方便,**FastAPI** 为开发者提供同 `starlette.responses` 一样的 `fastapi.responses`。但是大多数可用的响应都是直接来自 Starlette。`status` 也是一样。
+///
+
+/// note | "技术细节"
+
+你也可以使用 `from starlette.responses import JSONResponse`。
+
+出于方便,**FastAPI** 为开发者提供同 `starlette.responses` 一样的 `fastapi.responses`。但是大多数可用的响应都是直接来自 Starlette。`status` 也是一样。
+
+///
## OpenAPI 和 API 文档
{!../../../docs_src/dependencies/tutorial011.py!}
```
-!!! tip "提示"
+/// tip | "提示"
- 本章示例有些刻意,也看不出有什么用处。
+本章示例有些刻意,也看不出有什么用处。
- 这个简例只是为了说明高级依赖项的运作机制。
+这个简例只是为了说明高级依赖项的运作机制。
- 在有关安全的章节中,工具函数将以这种方式实现。
+在有关安全的章节中,工具函数将以这种方式实现。
- 只要能理解本章内容,就能理解安全工具背后的运行机制。
+只要能理解本章内容,就能理解安全工具背后的运行机制。
+
+///
proxy --> server
```
-!!! tip "提示"
+/// tip | "提示"
- IP `0.0.0.0` 常用于指程序监听本机或服务器上的所有有效 IP。
+IP `0.0.0.0` 常用于指程序监听本机或服务器上的所有有效 IP。
+
+///
API 文档还需要 OpenAPI 概图声明 API `server` 位于 `/api/v1`(使用代理时的 URL)。例如:
Hypercorn 也支持 `--root-path `选项。
-!!! note "技术细节"
+/// note | "技术细节"
+
+ASGI 规范定义的 `root_path` 就是为了这种用例。
- ASGI 规范定义的 `root_path` 就是为了这种用例。
+并且 `--root-path` 命令行选项支持 `root_path`。
- 并且 `--root-path` 命令行选项支持 `root_path`。
+///
### 查看当前的 `root_path`
这个文件把 Traefik 监听端口设置为 `9999`,并设置要使用另一个文件 `routes.toml`。
-!!! tip "提示"
+/// tip | "提示"
- 使用端口 9999 代替标准的 HTTP 端口 80,这样就不必使用管理员权限运行(`sudo`)。
+使用端口 9999 代替标准的 HTTP 端口 80,这样就不必使用管理员权限运行(`sudo`)。
+
+///
接下来,创建 `routes.toml`:
}
```
-!!! tip "提示"
+/// tip | "提示"
+
+注意,就算访问 `http://127.0.0.1:8000/app`,也显示从选项 `--root-path` 中提取的 `/api/v1`,这是 `root_path` 的值。
- 注意,就算访问 `http://127.0.0.1:8000/app`,也显示从选项 `--root-path` 中提取的 `/api/v1`,这是 `root_path` 的值。
+///
打开含 Traefik 端口的 URL,包含路径前缀:<a href="http://127.0.0.1:9999/api/v1/app" class="external-link" target="_blank">http://127.0.0.1:9999/api/v1/app。</a>
## 附加的服务器
-!!! warning "警告"
+/// warning | "警告"
- 此用例较难,可以跳过。
+此用例较难,可以跳过。
+
+///
默认情况下,**FastAPI** 使用 `root_path` 的链接在 OpenAPI 概图中创建 `server`。
}
```
-!!! tip "提示"
+/// tip | "提示"
+
+注意,自动生成服务器时,`url` 的值 `/api/v1` 提取自 `roog_path`。
- 注意,自动生成服务器时,`url` 的值 `/api/v1` 提取自 `roog_path`。
+///
<a href="http://127.0.0.1:9999/api/v1/docs" class="external-link" target="_blank">http://127.0.0.1:9999/api/v1/docs 的 API 文档所示如下:</a>
<img src="/img/tutorial/behind-a-proxy/image03.png">
-!!! tip "提示"
+/// tip | "提示"
+
+API 文档与所选的服务器进行交互。
- API 文档与所选的服务器进行交互。
+///
### 从 `root_path` 禁用自动服务器
并且如果该 `Response` 有一个 JSON 媒体类型(`application/json`),比如使用 `JSONResponse` 或者 `UJSONResponse` 的时候,返回的数据将使用你在路径操作装饰器中声明的任何 Pydantic 的 `response_model` 自动转换(和过滤)。
-!!! note "说明"
- 如果你使用不带有任何媒体类型的响应类,FastAPI 认为你的响应没有任何内容,所以不会在生成的OpenAPI文档中记录响应格式。
+/// note | "说明"
+
+如果你使用不带有任何媒体类型的响应类,FastAPI 认为你的响应没有任何内容,所以不会在生成的OpenAPI文档中记录响应格式。
+
+///
## 使用 `ORJSONResponse`
{!../../../docs_src/custom_response/tutorial001b.py!}
```
-!!! info "提示"
- 参数 `response_class` 也会用来定义响应的「媒体类型」。
+/// info | "提示"
+
+参数 `response_class` 也会用来定义响应的「媒体类型」。
- 在这个例子中,HTTP 头的 `Content-Type` 会被设置成 `application/json`。
+在这个例子中,HTTP 头的 `Content-Type` 会被设置成 `application/json`。
- 并且在 OpenAPI 文档中也会这样记录。
+并且在 OpenAPI 文档中也会这样记录。
-!!! tip "小贴士"
- `ORJSONResponse` 目前只在 FastAPI 中可用,而在 Starlette 中不可用。
+///
+/// tip | "小贴士"
+`ORJSONResponse` 目前只在 FastAPI 中可用,而在 Starlette 中不可用。
+
+///
## HTML 响应
{!../../../docs_src/custom_response/tutorial002.py!}
```
-!!! info "提示"
- 参数 `response_class` 也会用来定义响应的「媒体类型」。
+/// info | "提示"
+
+参数 `response_class` 也会用来定义响应的「媒体类型」。
- 在这个例子中,HTTP 头的 `Content-Type` 会被设置成 `text/html`。
+在这个例子中,HTTP 头的 `Content-Type` 会被设置成 `text/html`。
- 并且在 OpenAPI 文档中也会这样记录。
+并且在 OpenAPI 文档中也会这样记录。
+
+///
### 返回一个 `Response`
{!../../../docs_src/custom_response/tutorial003.py!}
```
-!!! warning "警告"
- *路径操作函数* 直接返回的 `Response` 不会被 OpenAPI 的文档记录(比如,`Content-Type` 不会被文档记录),并且在自动化交互文档中也是不可见的。
+/// warning | "警告"
+
+*路径操作函数* 直接返回的 `Response` 不会被 OpenAPI 的文档记录(比如,`Content-Type` 不会被文档记录),并且在自动化交互文档中也是不可见的。
+
+///
+
+/// info | "提示"
-!!! info "提示"
- 当然,实际的 `Content-Type` 头,状态码等等,将来自于你返回的 `Response` 对象。
+当然,实际的 `Content-Type` 头,状态码等等,将来自于你返回的 `Response` 对象。
+
+///
### OpenAPI 中的文档和重载 `Response`
要记得你可以使用 `Response` 来返回任何其他东西,甚至创建一个自定义的子类。
-!!! note "技术细节"
- 你也可以使用 `from starlette.responses import HTMLResponse`。
+/// note | "技术细节"
+
+你也可以使用 `from starlette.responses import HTMLResponse`。
+
+**FastAPI** 提供了同 `fastapi.responses` 相同的 `starlette.responses` 只是为了方便开发者。但大多数可用的响应都直接来自 Starlette。
- **FastAPI** 提供了同 `fastapi.responses` 相同的 `starlette.responses` 只是为了方便开发者。但大多数可用的响应都直接来自 Starlette。
+///
### `Response`
`UJSONResponse` 是一个使用 <a href="https://github.com/ultrajson/ultrajson" class="external-link" target="_blank">`ujson`</a> 的可选 JSON 响应。
-!!! warning "警告"
- 在处理某些边缘情况时,`ujson` 不如 Python 的内置实现那么谨慎。
+/// warning | "警告"
+
+在处理某些边缘情况时,`ujson` 不如 Python 的内置实现那么谨慎。
+
+///
```Python hl_lines="2 7"
{!../../../docs_src/custom_response/tutorial001.py!}
```
-!!! tip "小贴士"
- `ORJSONResponse` 可能是一个更快的选择。
+/// tip | "小贴士"
+
+`ORJSONResponse` 可能是一个更快的选择。
+
+///
### `RedirectResponse`
{!../../../docs_src/custom_response/tutorial008.py!}
```
-!!! tip "小贴士"
- 注意在这里,因为我们使用的是不支持 `async` 和 `await` 的标准 `open()`,我们使用普通的 `def` 声明了路径操作。
+/// tip | "小贴士"
+
+注意在这里,因为我们使用的是不支持 `async` 和 `await` 的标准 `open()`,我们使用普通的 `def` 声明了路径操作。
+
+///
### `FileResponse`
数据类的和运作方式与 Pydantic 模型相同。实际上,它的底层使用的也是 Pydantic。
-!!! info "说明"
+/// info | "说明"
- 注意,数据类不支持 Pydantic 模型的所有功能。
+注意,数据类不支持 Pydantic 模型的所有功能。
- 因此,开发时仍需要使用 Pydantic 模型。
+因此,开发时仍需要使用 Pydantic 模型。
- 但如果数据类很多,这一技巧能给 FastAPI 开发 Web API 增添不少助力。🤓
+但如果数据类很多,这一技巧能给 FastAPI 开发 Web API 增添不少助力。🤓
+
+///
## `response_model` 使用数据类
事件函数既可以声明为异步函数(`async def`),也可以声明为普通函数(`def`)。
-!!! warning "警告"
+/// warning | "警告"
- **FastAPI** 只执行主应用中的事件处理器,不执行[子应用 - 挂载](sub-applications.md){.internal-link target=_blank}中的事件处理器。
+**FastAPI** 只执行主应用中的事件处理器,不执行[子应用 - 挂载](sub-applications.md){.internal-link target=_blank}中的事件处理器。
+
+///
## `startup` 事件
此处,`shutdown` 事件处理器函数在 `log.txt` 中写入一行文本 `Application shutdown`。
-!!! info "说明"
+/// info | "说明"
+
+`open()` 函数中,`mode="a"` 指的是**追加**。因此这行文本会添加在文件已有内容之后,不会覆盖之前的内容。
+
+///
+
+/// tip | "提示"
- `open()` 函数中,`mode="a"` 指的是**追加**。因此这行文本会添加在文件已有内容之后,不会覆盖之前的内容。
+注意,本例使用 Python `open()` 标准函数与文件交互。
-!!! tip "提示"
+这个函数执行 I/O(输入/输出)操作,需要等待内容写进磁盘。
- 注意,本例使用 Python `open()` 标准函数与文件交互。
+但 `open()` 函数不支持使用 `async` 与 `await`。
- 这个函数执行 I/O(输入/输出)操作,需要等待内容写进磁盘。
+因此,声明事件处理函数要使用 `def`,不能使用 `asnyc def`。
- 但 `open()` 函数不支持使用 `async` 与 `await`。
+///
- 因此,声明事件处理函数要使用 `def`,不能使用 `asnyc def`。
+/// info | "说明"
-!!! info "说明"
+有关事件处理器的详情,请参阅 <a href="https://www.starlette.io/events/" class="external-link" target="_blank">Starlette 官档 - 事件</a>。
- 有关事件处理器的详情,请参阅 <a href="https://www.starlette.io/events/" class="external-link" target="_blank">Starlette 官档 - 事件</a>。
+///
让我们从一个简单的 FastAPI 应用开始:
-=== "Python 3.9+"
+//// tab | Python 3.9+
- ```Python hl_lines="7-9 12-13 16-17 21"
- {!> ../../../docs_src/generate_clients/tutorial001_py39.py!}
- ```
+```Python hl_lines="7-9 12-13 16-17 21"
+{!> ../../../docs_src/generate_clients/tutorial001_py39.py!}
+```
+
+////
-=== "Python 3.8+"
+//// tab | Python 3.8+
+
+```Python hl_lines="9-11 14-15 18 19 23"
+{!> ../../../docs_src/generate_clients/tutorial001.py!}
+```
- ```Python hl_lines="9-11 14-15 18 19 23"
- {!> ../../../docs_src/generate_clients/tutorial001.py!}
- ```
+////
请注意,*路径操作* 定义了他们所用于请求数据和回应数据的模型,所使用的模型是`Item` 和 `ResponseMessage`。
<img src="/img/tutorial/generate-clients/image03.png">
-!!! tip
- 请注意, `name` 和 `price` 的自动补全,是通过其在`Item`模型(FastAPI)中的定义实现的。
+/// tip
+
+请注意, `name` 和 `price` 的自动补全,是通过其在`Item`模型(FastAPI)中的定义实现的。
+
+///
如果发送的数据字段不符,你也会看到编辑器的错误提示:
例如,您可以有一个用 `items` 的部分和另一个用于 `users` 的部分,它们可以用标签来分隔:
-=== "Python 3.9+"
+//// tab | Python 3.9+
+
+```Python hl_lines="21 26 34"
+{!> ../../../docs_src/generate_clients/tutorial002_py39.py!}
+```
+
+////
- ```Python hl_lines="21 26 34"
- {!> ../../../docs_src/generate_clients/tutorial002_py39.py!}
- ```
+//// tab | Python 3.8+
-=== "Python 3.8+"
+```Python hl_lines="23 28 36"
+{!> ../../../docs_src/generate_clients/tutorial002.py!}
+```
- ```Python hl_lines="23 28 36"
- {!> ../../../docs_src/generate_clients/tutorial002.py!}
- ```
+////
### 生成带有标签的 TypeScript 客户端
然后,你可以将这个自定义函数作为 `generate_unique_id_function` 参数传递给 **FastAPI**:
-=== "Python 3.9+"
+//// tab | Python 3.9+
- ```Python hl_lines="6-7 10"
- {!> ../../../docs_src/generate_clients/tutorial003_py39.py!}
- ```
+```Python hl_lines="6-7 10"
+{!> ../../../docs_src/generate_clients/tutorial003_py39.py!}
+```
-=== "Python 3.8+"
+////
+
+//// tab | Python 3.8+
+
+```Python hl_lines="8-9 12"
+{!> ../../../docs_src/generate_clients/tutorial003.py!}
+```
- ```Python hl_lines="8-9 12"
- {!> ../../../docs_src/generate_clients/tutorial003.py!}
- ```
+////
### 使用自定义操作ID生成TypeScript客户端
你会在接下来的章节中了解到其他的选项、配置以及额外的特性。
-!!! tip
- 接下来的章节**并不一定是**「高级的」。
+/// tip
- 而且对于你的使用场景来说,解决方案很可能就在其中。
+接下来的章节**并不一定是**「高级的」。
+
+而且对于你的使用场景来说,解决方案很可能就在其中。
+
+///
## 先阅读教程
**FastAPI** 为常见用例提供了一些中间件,下面介绍怎么使用这些中间件。
-!!! note "技术细节"
+/// note | "技术细节"
- 以下几个示例中也可以使用 `from starlette.middleware.something import SomethingMiddleware`。
+以下几个示例中也可以使用 `from starlette.middleware.something import SomethingMiddleware`。
- **FastAPI** 在 `fastapi.middleware` 中提供的中间件只是为了方便开发者使用,但绝大多数可用的中间件都直接继承自 Starlette。
+**FastAPI** 在 `fastapi.middleware` 中提供的中间件只是为了方便开发者使用,但绝大多数可用的中间件都直接继承自 Starlette。
+
+///
## `HTTPSRedirectMiddleware`
{!../../../docs_src/openapi_callbacks/tutorial001.py!}
```
-!!! tip "提示"
+/// tip | "提示"
- `callback_url` 查询参数使用 Pydantic 的 <a href="https://pydantic-docs.helpmanual.io/usage/types/#urls" class="external-link" target="_blank">URL</a> 类型。
+`callback_url` 查询参数使用 Pydantic 的 <a href="https://pydantic-docs.helpmanual.io/usage/types/#urls" class="external-link" target="_blank">URL</a> 类型。
+
+///
此处唯一比较新的内容是*路径操作装饰器*中的 `callbacks=invoices_callback_router.routes` 参数,下文介绍。
本例没有实现回调本身(只是一行代码),只有文档部分。
-!!! tip "提示"
+/// tip | "提示"
+
+实际的回调只是 HTTP 请求。
- 实际的回调只是 HTTP 请求。
+实现回调时,要使用 <a href="https://www.encode.io/httpx/" class="external-link" target="_blank">HTTPX</a> 或 <a href="https://requests.readthedocs.io/" class="external-link" target="_blank">Requests</a>。
- 实现回调时,要使用 <a href="https://www.encode.io/httpx/" class="external-link" target="_blank">HTTPX</a> 或 <a href="https://requests.readthedocs.io/" class="external-link" target="_blank">Requests</a>。
+///
## 编写回调文档代码
我们要使用与存档*外部 API* 相同的知识……通过创建外部 API 要实现的*路径操作*(您的 API 要调用的)。
-!!! tip "提示"
+/// tip | "提示"
+
+编写存档回调的代码时,假设您是*外部开发者*可能会用的上。并且您当前正在实现的是*外部 API*,不是*您自己的 API*。
- 编写存档回调的代码时,假设您是*外部开发者*可能会用的上。并且您当前正在实现的是*外部 API*,不是*您自己的 API*。
+临时改变(为外部开发者的)视角能让您更清楚该如何放置*外部 API* 响应和请求体的参数与 Pydantic 模型等。
- 临时改变(为外部开发者的)视角能让您更清楚该如何放置*外部 API* 响应和请求体的参数与 Pydantic 模型等。
+///
### 创建回调的 `APIRouter`
}
```
-!!! tip "提示"
+/// tip | "提示"
- 注意,回调 URL包含 `callback_url` (`https://www.external.org/events`)中的查询参数,还有 JSON 请求体内部的发票 ID(`2expen51ve`)。
+注意,回调 URL包含 `callback_url` (`https://www.external.org/events`)中的查询参数,还有 JSON 请求体内部的发票 ID(`2expen51ve`)。
+
+///
### 添加回调路由
{!../../../docs_src/openapi_callbacks/tutorial001.py!}
```
-!!! tip "提示"
+/// tip | "提示"
+
+注意,不能把路由本身(`invoices_callback_router`)传递给 `callback=`,要传递 `invoices_callback_router.routes` 中的 `.routes` 属性。
- 注意,不能把路由本身(`invoices_callback_router`)传递给 `callback=`,要传递 `invoices_callback_router.routes` 中的 `.routes` 属性。
+///
### 查看文档
## OpenAPI 的 operationId
-!!! warning
- 如果你并非 OpenAPI 的「专家」,你可能不需要这部分内容。
+/// warning
+
+如果你并非 OpenAPI 的「专家」,你可能不需要这部分内容。
+
+///
你可以在路径操作中通过参数 `operation_id` 设置要使用的 OpenAPI `operationId`。
{!../../../docs_src/path_operation_advanced_configuration/tutorial002.py!}
```
-!!! tip
- 如果你手动调用 `app.openapi()`,你应该在此之前更新 `operationId`。
+/// tip
+
+如果你手动调用 `app.openapi()`,你应该在此之前更新 `operationId`。
+
+///
+
+/// warning
+
+如果你这样做,务必确保你的每个 *路径操作函数* 的名字唯一。
-!!! warning
- 如果你这样做,务必确保你的每个 *路径操作函数* 的名字唯一。
+即使它们在不同的模块中(Python 文件)。
- 即使它们在不同的模块中(Python 文件)。
+///
## 从 OpenAPI 中排除
{!../../../docs_src/response_cookies/tutorial001.py!}
```
-!!! tip
- 需要注意,如果你直接反馈一个response对象,而不是使用`Response`入参,FastAPI则会直接反馈你封装的response对象。
+/// tip
- 所以你需要确保你响应数据类型的正确性,如:你可以使用`JSONResponse`来兼容JSON的场景。
+需要注意,如果你直接反馈一个response对象,而不是使用`Response`入参,FastAPI则会直接反馈你封装的response对象。
- 同时,你也应当仅反馈通过`response_model`过滤过的数据。
+所以你需要确保你响应数据类型的正确性,如:你可以使用`JSONResponse`来兼容JSON的场景。
+
+同时,你也应当仅反馈通过`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`。不过大部分response对象都是直接引用自Starlette。
- 为了方便开发者,**FastAPI** 封装了相同数据类型,如`starlette.responses` 和 `fastapi.responses`。不过大部分response对象都是直接引用自Starlette。
+因为`Response`对象可以非常便捷的设置headers和cookies,所以 **FastAPI** 同时也封装了`fastapi.Response`。
- 因为`Response`对象可以非常便捷的设置headers和cookies,所以 **FastAPI** 同时也封装了`fastapi.Response`。
+///
如果你想查看所有可用的参数和选项,可以参考 <a href="https://www.starlette.io/responses/#set-cookie" class="external-link" target="_blank">Starlette帮助文档</a>
事实上,你可以返回任意 `Response` 或者任意 `Response` 的子类。
-!!! tip "小贴士"
- `JSONResponse` 本身是一个 `Response` 的子类。
+/// tip | "小贴士"
+
+`JSONResponse` 本身是一个 `Response` 的子类。
+
+///
当你返回一个 `Response` 时,**FastAPI** 会直接传递它。
{!../../../docs_src/response_directly/tutorial001.py!}
```
-!!! note "技术细节"
- 你也可以使用 `from starlette.responses import JSONResponse`。
+/// note | "技术细节"
+
+你也可以使用 `from starlette.responses import JSONResponse`。
+
+出于方便,**FastAPI** 会提供与 `starlette.responses` 相同的 `fastapi.responses` 给开发者。但是大多数可用的响应都直接来自 Starlette。
- 出于方便,**FastAPI** 会提供与 `starlette.responses` 相同的 `fastapi.responses` 给开发者。但是大多数可用的响应都直接来自 Starlette。
+///
## 返回自定义 `Response`
```
-!!! note "技术细节"
- 你也可以使用`from starlette.responses import Response`或`from starlette.responses import JSONResponse`。
+/// note | "技术细节"
- **FastAPI**提供了与`fastapi.responses`相同的`starlette.responses`,只是为了方便开发者。但是,大多数可用的响应都直接来自Starlette。
+你也可以使用`from starlette.responses import Response`或`from starlette.responses import JSONResponse`。
- 由于`Response`经常用于设置头部和cookies,因此**FastAPI**还在`fastapi.Response`中提供了它。
+**FastAPI**提供了与`fastapi.responses`相同的`starlette.responses`,只是为了方便开发者。但是,大多数可用的响应都直接来自Starlette。
+
+由于`Response`经常用于设置头部和cookies,因此**FastAPI**还在`fastapi.Response`中提供了它。
+
+///
## 自定义头部
* 返回类型为 `HTTPBasicCredentials` 的对象:
* 包含发送的 `username` 与 `password`
-=== "Python 3.9+"
+//// tab | Python 3.9+
- ```Python hl_lines="4 8 12"
- {!> ../../../docs_src/security/tutorial006_an_py39.py!}
- ```
+```Python hl_lines="4 8 12"
+{!> ../../../docs_src/security/tutorial006_an_py39.py!}
+```
+
+////
-=== "Python 3.8+"
+//// tab | Python 3.8+
+
+```Python hl_lines="2 7 11"
+{!> ../../../docs_src/security/tutorial006_an.py!}
+```
- ```Python hl_lines="2 7 11"
- {!> ../../../docs_src/security/tutorial006_an.py!}
- ```
+////
-=== "Python 3.8+ non-Annotated"
+//// tab | Python 3.8+ non-Annotated
- !!! tip
- 尽可能选择使用 `Annotated` 的版本。
+/// tip
- ```Python hl_lines="2 6 10"
- {!> ../../../docs_src/security/tutorial006.py!}
- ```
+尽可能选择使用 `Annotated` 的版本。
+
+///
+
+```Python hl_lines="2 6 10"
+{!> ../../../docs_src/security/tutorial006.py!}
+```
+
+////
第一次打开 URL(或在 API 文档中点击 **Execute** 按钮)时,浏览器要求输入用户名与密码:
然后我们可以使用 `secrets.compare_digest()` 来确保 `credentials.username` 是 `"stanleyjobson"`,且 `credentials.password` 是`"swordfish"`。
-=== "Python 3.9+"
+//// tab | Python 3.9+
+
+```Python hl_lines="1 12-24"
+{!> ../../../docs_src/security/tutorial007_an_py39.py!}
+```
+
+////
+
+//// tab | Python 3.8+
- ```Python hl_lines="1 12-24"
- {!> ../../../docs_src/security/tutorial007_an_py39.py!}
- ```
+```Python hl_lines="1 12-24"
+{!> ../../../docs_src/security/tutorial007_an.py!}
+```
-=== "Python 3.8+"
+////
- ```Python hl_lines="1 12-24"
- {!> ../../../docs_src/security/tutorial007_an.py!}
- ```
+//// tab | Python 3.8+ non-Annotated
-=== "Python 3.8+ non-Annotated"
+/// tip
- !!! tip
- 尽可能选择使用 `Annotated` 的版本。
+尽可能选择使用 `Annotated` 的版本。
+
+///
+
+```Python hl_lines="1 11-21"
+{!> ../../../docs_src/security/tutorial007.py!}
+```
+
+////
- ```Python hl_lines="1 11-21"
- {!> ../../../docs_src/security/tutorial007.py!}
- ```
这类似于:
```Python
检测到凭证不正确后,返回 `HTTPException` 及状态码 401(与无凭证时返回的内容一样),并添加请求头 `WWW-Authenticate`,让浏览器再次显示登录提示:
-=== "Python 3.9+"
+//// tab | Python 3.9+
+
+```Python hl_lines="26-30"
+{!> ../../../docs_src/security/tutorial007_an_py39.py!}
+```
+
+////
+
+//// tab | Python 3.8+
+
+```Python hl_lines="26-30"
+{!> ../../../docs_src/security/tutorial007_an.py!}
+```
+
+////
- ```Python hl_lines="26-30"
- {!> ../../../docs_src/security/tutorial007_an_py39.py!}
- ```
+//// tab | Python 3.8+ non-Annotated
-=== "Python 3.8+"
+/// tip
- ```Python hl_lines="26-30"
- {!> ../../../docs_src/security/tutorial007_an.py!}
- ```
+尽可能选择使用 `Annotated` 的版本。
-=== "Python 3.8+ non-Annotated"
+///
- !!! tip
- 尽可能选择使用 `Annotated` 的版本。
+```Python hl_lines="23-27"
+{!> ../../../docs_src/security/tutorial007.py!}
+```
- ```Python hl_lines="23-27"
- {!> ../../../docs_src/security/tutorial007.py!}
- ```
+////
除 [教程 - 用户指南: 安全性](../../tutorial/security/index.md){.internal-link target=_blank} 中涵盖的功能之外,还有一些额外的功能来处理安全性.
-!!! tip "小贴士"
- 接下来的章节 **并不一定是 "高级的"**.
+/// tip | "小贴士"
- 而且对于你的使用场景来说,解决方案很可能就在其中。
+接下来的章节 **并不一定是 "高级的"**.
+
+而且对于你的使用场景来说,解决方案很可能就在其中。
+
+///
## 先阅读教程
本章介绍如何在 **FastAPI** 应用中使用 OAuth2 作用域管理验证与授权。
-!!! warning "警告"
+/// warning | "警告"
- 本章内容较难,刚接触 FastAPI 的新手可以跳过。
+本章内容较难,刚接触 FastAPI 的新手可以跳过。
- OAuth2 作用域不是必需的,没有它,您也可以处理身份验证与授权。
+OAuth2 作用域不是必需的,没有它,您也可以处理身份验证与授权。
- 但 OAuth2 作用域与 API(通过 OpenAPI)及 API 文档集成地更好。
+但 OAuth2 作用域与 API(通过 OpenAPI)及 API 文档集成地更好。
- 不管怎么说,**FastAPI** 支持在代码中使用作用域或其它安全/授权需求项。
+不管怎么说,**FastAPI** 支持在代码中使用作用域或其它安全/授权需求项。
- 很多情况下,OAuth2 作用域就像一把牛刀。
+很多情况下,OAuth2 作用域就像一把牛刀。
- 但如果您确定要使用作用域,或对它有兴趣,请继续阅读。
+但如果您确定要使用作用域,或对它有兴趣,请继续阅读。
+
+///
## OAuth2 作用域与 OpenAPI
* 脸书和 Instagram 使用 `instagram_basic`
* 谷歌使用 `https://www.googleapis.com/auth/drive`
-!!! info "说明"
+/// info | "说明"
+
+OAuth2 中,**作用域**只是声明特定权限的字符串。
- OAuth2 中,**作用域**只是声明特定权限的字符串。
+是否使用冒号 `:` 等符号,或是不是 URL 并不重要。
- 是否使用冒号 `:` 等符号,或是不是 URL 并不重要。
+这些细节只是特定的实现方式。
- 这些细节只是特定的实现方式。
+对 OAuth2 来说,它们都只是字符串而已。
- 对 OAuth2 来说,它们都只是字符串而已。
+///
## 全局纵览
这样,返回的 JWT 令牌中就包含了作用域。
-!!! danger "危险"
+/// danger | "危险"
- 为了简明起见,本例把接收的作用域直接添加到了令牌里。
+为了简明起见,本例把接收的作用域直接添加到了令牌里。
- 但在您的应用中,为了安全,应该只把作用域添加到确实需要作用域的用户,或预定义的用户。
+但在您的应用中,为了安全,应该只把作用域添加到确实需要作用域的用户,或预定义的用户。
+
+///
```Python hl_lines="153"
{!../../../docs_src/security/tutorial005.py!}
本例要求使用作用域 `me`(还可以使用更多作用域)。
-!!! note "笔记"
+/// note | "笔记"
+
+不必在不同位置添加不同的作用域。
- 不必在不同位置添加不同的作用域。
+本例使用的这种方式只是为了展示 **FastAPI** 如何处理在不同层级声明的作用域。
- 本例使用的这种方式只是为了展示 **FastAPI** 如何处理在不同层级声明的作用域。
+///
```Python hl_lines="4 139 166"
{!../../../docs_src/security/tutorial005.py!}
```
-!!! info "技术细节"
+/// info | "技术细节"
- `Security` 实际上是 `Depends` 的子类,而且只比 `Depends` 多一个参数。
+`Security` 实际上是 `Depends` 的子类,而且只比 `Depends` 多一个参数。
- 但使用 `Security` 代替 `Depends`,**FastAPI** 可以声明安全作用域,并在内部使用这些作用域,同时,使用 OpenAPI 存档 API。
+但使用 `Security` 代替 `Depends`,**FastAPI** 可以声明安全作用域,并在内部使用这些作用域,同时,使用 OpenAPI 存档 API。
- 但实际上,从 `fastapi` 导入的 `Query`、`Path`、`Depends`、`Security` 等对象,只是返回特殊类的函数。
+但实际上,从 `fastapi` 导入的 `Query`、`Path`、`Depends`、`Security` 等对象,只是返回特殊类的函数。
+
+///
## 使用 `SecurityScopes`
* `security_scopes.scopes` 包含*路径操作* `read_users_me` 的 `["me"]`,因为它在依赖项里被声明
* `security_scopes.scopes` 包含用于*路径操作* `read_system_status` 的 `[]`(空列表),并且它的依赖项 `get_current_user` 也没有声明任何 `scope`
-!!! tip "提示"
+/// tip | "提示"
+
+此处重要且**神奇**的事情是,`get_current_user` 检查每个*路径操作*时可以使用不同的 `scopes` 列表。
- 此处重要且**神奇**的事情是,`get_current_user` 检查每个*路径操作*时可以使用不同的 `scopes` 列表。
+所有这些都依赖于在每个*路径操作*和指定*路径操作*的依赖树中的每个依赖项。
- 所有这些都依赖于在每个*路径操作*和指定*路径操作*的依赖树中的每个依赖项。
+///
## `SecurityScopes` 的更多细节
最安全的是代码流,但实现起来更复杂,而且需要更多步骤。因为它更复杂,很多第三方身份验证应用最终建议使用隐式流。
-!!! note "笔记"
+/// note | "笔记"
+
+每个身份验证应用都会采用不同方式会命名流,以便融合入自己的品牌。
- 每个身份验证应用都会采用不同方式会命名流,以便融合入自己的品牌。
+但归根结底,它们使用的都是 OAuth2 标准。
- 但归根结底,它们使用的都是 OAuth2 标准。
+///
**FastAPI** 的 `fastapi.security.oauth2` 里包含了所有 OAuth2 身份验证流工具。
## 环境变量
-!!! tip
- 如果您已经知道什么是"环境变量"以及如何使用它们,请随意跳到下面的下一节。
+/// tip
+
+如果您已经知道什么是"环境变量"以及如何使用它们,请随意跳到下面的下一节。
+
+///
环境变量(也称为"env var")是一种存在于 Python 代码之外、存在于操作系统中的变量,可以被您的 Python 代码(或其他程序)读取。
您可以在 shell 中创建和使用环境变量,而无需使用 Python:
-=== "Linux、macOS、Windows Bash"
+//// tab | Linux、macOS、Windows Bash
+
+<div class="termy">
+
+```console
+// 您可以创建一个名为 MY_NAME 的环境变量
+$ export MY_NAME="Wade Wilson"
- <div class="termy">
+// 然后您可以与其他程序一起使用它,例如
+$ echo "Hello $MY_NAME"
- ```console
- // 您可以创建一个名为 MY_NAME 的环境变量
- $ export MY_NAME="Wade Wilson"
+Hello Wade Wilson
+```
- // 然后您可以与其他程序一起使用它,例如
- $ echo "Hello $MY_NAME"
+</div>
- Hello Wade Wilson
- ```
+////
- </div>
+//// tab | Windows PowerShell
-=== "Windows PowerShell"
+<div class="termy">
- <div class="termy">
+```console
+// 创建一个名为 MY_NAME 的环境变量
+$ $Env:MY_NAME = "Wade Wilson"
- ```console
- // 创建一个名为 MY_NAME 的环境变量
- $ $Env:MY_NAME = "Wade Wilson"
+// 与其他程序一起使用它,例如
+$ echo "Hello $Env:MY_NAME"
- // 与其他程序一起使用它,例如
- $ echo "Hello $Env:MY_NAME"
+Hello Wade Wilson
+```
- Hello Wade Wilson
- ```
+</div>
- </div>
+////
### 在 Python 中读取环境变量
print(f"Hello {name} from Python")
```
-!!! tip
- <a href="https://docs.python.org/3.8/library/os.html#os.getenv" class="external-link" target="_blank">`os.getenv()`</a> 的第二个参数是要返回的默认值。
+/// tip
+
+<a href="https://docs.python.org/3.8/library/os.html#os.getenv" class="external-link" target="_blank">`os.getenv()`</a> 的第二个参数是要返回的默认值。
- 如果没有提供默认值,默认为 `None`,此处我们提供了 `"World"` 作为要使用的默认值。
+如果没有提供默认值,默认为 `None`,此处我们提供了 `"World"` 作为要使用的默认值。
+
+///
然后,您可以调用该 Python 程序:
</div>
-!!! tip
- 您可以在 <a href="https://12factor.net/config" class="external-link" target="_blank">Twelve-Factor App: Config</a> 中阅读更多相关信息。
+/// tip
+
+您可以在 <a href="https://12factor.net/config" class="external-link" target="_blank">Twelve-Factor App: Config</a> 中阅读更多相关信息。
+
+///
### 类型和验证
{!../../../docs_src/settings/tutorial001.py!}
```
-!!! tip
- 如果您需要一个快速的复制粘贴示例,请不要使用此示例,而应使用下面的最后一个示例。
+/// tip
+
+如果您需要一个快速的复制粘贴示例,请不要使用此示例,而应使用下面的最后一个示例。
+
+///
然后,当您创建该 `Settings` 类的实例(在此示例中是 `settings` 对象)时,Pydantic 将以不区分大小写的方式读取环境变量,因此,大写的变量 `APP_NAME` 仍将为属性 `app_name` 读取。
</div>
-!!! tip
- 要为单个命令设置多个环境变量,只需用空格分隔它们,并将它们全部放在命令之前。
+/// tip
+
+要为单个命令设置多个环境变量,只需用空格分隔它们,并将它们全部放在命令之前。
+
+///
然后,`admin_email` 设置将为 `"deadpool@example.com"`。
```Python hl_lines="3 11-13"
{!../../../docs_src/settings/app01/main.py!}
```
-!!! tip
- 您还需要一个名为 `__init__.py` 的文件,就像您在[Bigger Applications - Multiple Files](../tutorial/bigger-applications.md){.internal-link target=_blank}中看到的那样。
+
+/// tip
+
+您还需要一个名为 `__init__.py` 的文件,就像您在[Bigger Applications - Multiple Files](../tutorial/bigger-applications.md){.internal-link target=_blank}中看到的那样。
+
+///
## 在依赖项中使用设置
现在我们创建一个依赖项,返回一个新的 `config.Settings()`。
-=== "Python 3.9+"
+//// tab | Python 3.9+
+
+```Python hl_lines="6 12-13"
+{!> ../../../docs_src/settings/app02_an_py39/main.py!}
+```
+
+////
+
+//// tab | Python 3.8+
- ```Python hl_lines="6 12-13"
- {!> ../../../docs_src/settings/app02_an_py39/main.py!}
- ```
+```Python hl_lines="6 12-13"
+{!> ../../../docs_src/settings/app02_an/main.py!}
+```
+
+////
-=== "Python 3.8+"
+//// tab | Python 3.8+ 非注解版本
- ```Python hl_lines="6 12-13"
- {!> ../../../docs_src/settings/app02_an/main.py!}
- ```
+/// tip
-=== "Python 3.8+ 非注解版本"
+如果可能,请尽量使用 `Annotated` 版本。
- !!! tip
- 如果可能,请尽量使用 `Annotated` 版本。
+///
+
+```Python hl_lines="5 11-12"
+{!> ../../../docs_src/settings/app02/main.py!}
+```
- ```Python hl_lines="5 11-12"
- {!> ../../../docs_src/settings/app02/main.py!}
- ```
+////
-!!! tip
- 我们稍后会讨论 `@lru_cache`。
+/// tip
- 目前,您可以将 `get_settings()` 视为普通函数。
+我们稍后会讨论 `@lru_cache`。
+
+目前,您可以将 `get_settings()` 视为普通函数。
+
+///
然后,我们可以将其作为依赖项从“路径操作函数”中引入,并在需要时使用它。
-=== "Python 3.9+"
+//// tab | Python 3.9+
+
+```Python hl_lines="17 19-21"
+{!> ../../../docs_src/settings/app02_an_py39/main.py!}
+```
+
+////
- ```Python hl_lines="17 19-21"
- {!> ../../../docs_src/settings/app02_an_py39/main.py!}
- ```
+//// tab | Python 3.8+
+
+```Python hl_lines="17 19-21"
+{!> ../../../docs_src/settings/app02_an/main.py!}
+```
-=== "Python 3.8+"
+////
- ```Python hl_lines="17 19-21"
- {!> ../../../docs_src/settings/app02_an/main.py!}
- ```
+//// tab | Python 3.8+ 非注解版本
-=== "Python 3.8+ 非注解版本"
+/// tip
- !!! tip
- 如果可能,请尽量使用 `Annotated` 版本。
+如果可能,请尽量使用 `Annotated` 版本。
+
+///
+
+```Python hl_lines="16 18-20"
+{!> ../../../docs_src/settings/app02/main.py!}
+```
- ```Python hl_lines="16 18-20"
- {!> ../../../docs_src/settings/app02/main.py!}
- ```
+////
### 设置和测试
这种做法相当常见,有一个名称,这些环境变量通常放在一个名为 `.env` 的文件中,该文件被称为“dotenv”。
-!!! tip
- 以点 (`.`) 开头的文件是 Unix-like 系统(如 Linux 和 macOS)中的隐藏文件。
+/// tip
- 但是,dotenv 文件实际上不一定要具有确切的文件名。
+以点 (`.`) 开头的文件是 Unix-like 系统(如 Linux 和 macOS)中的隐藏文件。
+
+但是,dotenv 文件实际上不一定要具有确切的文件名。
+
+///
Pydantic 支持使用外部库从这些类型的文件中读取。您可以在<a href="https://docs.pydantic.dev/latest/concepts/pydantic_settings/#dotenv-env-support" class="external-link" target="_blank">Pydantic 设置: Dotenv (.env) 支持</a>中阅读更多相关信息。
-!!! tip
- 要使其工作,您需要执行 `pip install python-dotenv`。
+/// tip
+
+要使其工作,您需要执行 `pip install python-dotenv`。
+
+///
### `.env` 文件
在这里,我们在 Pydantic 的 `Settings` 类中创建了一个名为 `Config` 的类,并将 `env_file` 设置为我们想要使用的 dotenv 文件的文件名。
-!!! tip
- `Config` 类仅用于 Pydantic 配置。您可以在<a href="https://docs.pydantic.dev/latest/api/config/" class="external-link" target="_blank">Pydantic Model Config</a>中阅读更多相关信息。
+/// tip
+
+`Config` 类仅用于 Pydantic 配置。您可以在<a href="https://docs.pydantic.dev/latest/api/config/" class="external-link" target="_blank">Pydantic Model Config</a>中阅读更多相关信息。
+
+///
### 使用 `lru_cache` 仅创建一次 `Settings`
但是,由于我们在顶部使用了 `@lru_cache` 装饰器,因此只有在第一次调用它时,才会创建 `Settings` 对象一次。 ✔️
-=== "Python 3.9+"
+//// tab | Python 3.9+
+
+```Python hl_lines="1 11"
+{!> ../../../docs_src/settings/app03_an_py39/main.py!}
+```
+
+////
- ```Python hl_lines="1 11"
- {!> ../../../docs_src/settings/app03_an_py39/main.py!}
- ```
+//// tab | Python 3.8+
+
+```Python hl_lines="1 11"
+{!> ../../../docs_src/settings/app03_an/main.py!}
+```
-=== "Python 3.8+"
+////
- ```Python hl_lines="1 11"
- {!> ../../../docs_src/settings/app03_an/main.py!}
- ```
+//// tab | Python 3.8+ 非注解版本
-=== "Python 3.8+ 非注解版本"
+/// tip
- !!! tip
- 如果可能,请尽量使用 `Annotated` 版本。
+如果可能,请尽量使用 `Annotated` 版本。
+
+///
+
+```Python hl_lines="1 10"
+{!> ../../../docs_src/settings/app03/main.py!}
+```
- ```Python hl_lines="1 10"
- {!> ../../../docs_src/settings/app03/main.py!}
- ```
+////
然后,在下一次请求的依赖项中对 `get_settings()` 进行任何后续调用时,它不会执行 `get_settings()` 的内部代码并创建新的 `Settings` 对象,而是返回在第一次调用时返回的相同对象,一次又一次。
{!../../../docs_src/templates/tutorial001.py!}
```
-!!! note "笔记"
+/// note | "笔记"
- 在FastAPI 0.108.0,Starlette 0.29.0之前,`name`是第一个参数。
- 并且,在此之前,`request`对象是作为context的一部分以键值对的形式传递的。
+在FastAPI 0.108.0,Starlette 0.29.0之前,`name`是第一个参数。
+并且,在此之前,`request`对象是作为context的一部分以键值对的形式传递的。
-!!! tip "提示"
+///
- 通过声明 `response_class=HTMLResponse`,API 文档就能识别响应的对象是 HTML。
+/// tip | "提示"
-!!! note "技术细节"
+通过声明 `response_class=HTMLResponse`,API 文档就能识别响应的对象是 HTML。
- 您还可以使用 `from starlette.templating import Jinja2Templates`。
+///
- **FastAPI** 的 `fastapi.templating` 只是为开发者提供的快捷方式。实际上,绝大多数可用响应都直接继承自 Starlette。 `Request` 与 `StaticFiles` 也一样。
+/// note | "技术细节"
+
+您还可以使用 `from starlette.templating import Jinja2Templates`。
+
+**FastAPI** 的 `fastapi.templating` 只是为开发者提供的快捷方式。实际上,绝大多数可用响应都直接继承自 Starlette。 `Request` 与 `StaticFiles` 也一样。
+
+///
## 编写模板
{!../../../docs_src/sql_databases/sql_app/tests/test_sql_app.py!}
```
-!!! tip "提示"
+/// tip | "提示"
- 为减少代码重复,最好把这段代码写成函数,在 `database.py` 与 `tests/test_sql_app.py`中使用。
+为减少代码重复,最好把这段代码写成函数,在 `database.py` 与 `tests/test_sql_app.py`中使用。
- 为了把注意力集中在测试代码上,本例只是复制了这段代码。
+为了把注意力集中在测试代码上,本例只是复制了这段代码。
+
+///
## 创建数据库
{!../../../docs_src/sql_databases/sql_app/tests/test_sql_app.py!}
```
-!!! tip "提示"
+/// tip | "提示"
+
+`overrider_get_db()` 与 `get_db` 的代码几乎完全一样,只是 `overrider_get_db` 中使用测试数据库的 `TestingSessionLocal`。
- `overrider_get_db()` 与 `get_db` 的代码几乎完全一样,只是 `overrider_get_db` 中使用测试数据库的 `TestingSessionLocal`。
+///
## 测试应用
{!../../../docs_src/dependency_testing/tutorial001.py!}
```
-!!! tip "提示"
+/// tip | "提示"
- **FastAPI** 应用中的任何位置都可以实现覆盖依赖项。
+**FastAPI** 应用中的任何位置都可以实现覆盖依赖项。
- 原依赖项可用于*路径操作函数*、*路径操作装饰器*(不需要返回值时)、`.include_router()` 调用等。
+原依赖项可用于*路径操作函数*、*路径操作装饰器*(不需要返回值时)、`.include_router()` 调用等。
- FastAPI 可以覆盖这些位置的依赖项。
+FastAPI 可以覆盖这些位置的依赖项。
+
+///
然后,使用 `app.dependency_overrides` 把覆盖依赖项重置为空**字典**:
app.dependency_overrides = {}
```
-!!! tip "提示"
+/// tip | "提示"
+
+如果只在某些测试时覆盖依赖项,您可以在测试开始时(在测试函数内)设置覆盖依赖项,并在结束时(在测试函数结尾)重置覆盖依赖项。
- 如果只在某些测试时覆盖依赖项,您可以在测试开始时(在测试函数内)设置覆盖依赖项,并在结束时(在测试函数结尾)重置覆盖依赖项。
+///
{!../../../docs_src/app_testing/tutorial002.py!}
```
-!!! note "笔记"
+/// note | "笔记"
- 更多细节详见 <a href="https://www.starlette.io/testclient/#testing-websocket-sessions" class="external-link" target="_blank">Starlette 官档 - 测试 WebSockets</a>。
+更多细节详见 <a href="https://www.starlette.io/testclient/#testing-websocket-sessions" class="external-link" target="_blank">Starlette 官档 - 测试 WebSockets</a>。
+
+///
把*路径操作函数*的参数类型声明为 `Request`,**FastAPI** 就能把 `Request` 传递到参数里。
-!!! tip "提示"
+/// tip | "提示"
- 注意,本例除了声明请求参数之外,还声明了路径参数。
+注意,本例除了声明请求参数之外,还声明了路径参数。
- 因此,能够提取、验证路径参数、并转换为指定类型,还可以用 OpenAPI 注释。
+因此,能够提取、验证路径参数、并转换为指定类型,还可以用 OpenAPI 注释。
- 同样,您也可以正常声明其它参数,而且还可以提取 `Request`。
+同样,您也可以正常声明其它参数,而且还可以提取 `Request`。
+
+///
## `Request` 文档
更多细节详见 <a href="https://www.starlette.io/requests/" class="external-link" target="_blank">Starlette 官档 - `Request` 对象</a>。
-!!! note "技术细节"
+/// note | "技术细节"
+
+您也可以使用 `from starlette.requests import Request`。
- 您也可以使用 `from starlette.requests import Request`。
+**FastAPI** 的 `from fastapi import Request` 只是为开发者提供的快捷方式,但其实它直接继承自 Starlette。
- **FastAPI** 的 `from fastapi import Request` 只是为开发者提供的快捷方式,但其实它直接继承自 Starlette。
+///
{!../../../docs_src/websockets/tutorial001.py!}
```
-!!! note "技术细节"
- 您也可以使用 `from starlette.websockets import WebSocket`。
+/// note | "技术细节"
- **FastAPI** 直接提供了相同的 `WebSocket`,只是为了方便开发人员。但它直接来自 Starlette。
+您也可以使用 `from starlette.websockets import WebSocket`。
+
+**FastAPI** 直接提供了相同的 `WebSocket`,只是为了方便开发人员。但它直接来自 Starlette。
+
+///
## 等待消息并发送消息
它们的工作方式与其他 FastAPI 端点/ *路径操作* 相同:
-=== "Python 3.10+"
+//// tab | Python 3.10+
+
+```Python hl_lines="68-69 82"
+{!> ../../../docs_src/websockets/tutorial002_an_py310.py!}
+```
+
+////
+
+//// tab | Python 3.9+
+
+```Python hl_lines="68-69 82"
+{!> ../../../docs_src/websockets/tutorial002_an_py39.py!}
+```
+
+////
+
+//// tab | Python 3.8+
+
+```Python hl_lines="69-70 83"
+{!> ../../../docs_src/websockets/tutorial002_an.py!}
+```
+
+////
- ```Python hl_lines="68-69 82"
- {!> ../../../docs_src/websockets/tutorial002_an_py310.py!}
- ```
+//// tab | Python 3.10+ 非带注解版本
-=== "Python 3.9+"
+/// tip
- ```Python hl_lines="68-69 82"
- {!> ../../../docs_src/websockets/tutorial002_an_py39.py!}
- ```
+如果可能,请尽量使用 `Annotated` 版本。
-=== "Python 3.8+"
+///
- ```Python hl_lines="69-70 83"
- {!> ../../../docs_src/websockets/tutorial002_an.py!}
- ```
+```Python hl_lines="66-67 79"
+{!> ../../../docs_src/websockets/tutorial002_py310.py!}
+```
+
+////
-=== "Python 3.10+ 非带注解版本"
+//// tab | Python 3.8+ 非带注解版本
- !!! tip
- 如果可能,请尽量使用 `Annotated` 版本。
+/// tip
- ```Python hl_lines="66-67 79"
- {!> ../../../docs_src/websockets/tutorial002_py310.py!}
- ```
+如果可能,请尽量使用 `Annotated` 版本。
-=== "Python 3.8+ 非带注解版本"
+///
+
+```Python hl_lines="68-69 81"
+{!> ../../../docs_src/websockets/tutorial002.py!}
+```
- !!! tip
- 如果可能,请尽量使用 `Annotated` 版本。
+////
- ```Python hl_lines="68-69 81"
- {!> ../../../docs_src/websockets/tutorial002.py!}
- ```
+/// info
-!!! info
- 由于这是一个 WebSocket,抛出 `HTTPException` 并不是很合理,而是抛出 `WebSocketException`。
+由于这是一个 WebSocket,抛出 `HTTPException` 并不是很合理,而是抛出 `WebSocketException`。
- 您可以使用<a href="https://tools.ietf.org/html/rfc6455#section-7.4.1" class="external-link" target="_blank">规范中定义的有效代码</a>。
+您可以使用<a href="https://tools.ietf.org/html/rfc6455#section-7.4.1" class="external-link" target="_blank">规范中定义的有效代码</a>。
+
+///
### 尝试带有依赖项的 WebSockets
* "Item ID",用于路径。
* "Token",作为查询参数。
-!!! tip
- 注意,查询参数 `token` 将由依赖项处理。
+/// tip
+
+注意,查询参数 `token` 将由依赖项处理。
+
+///
通过这样,您可以连接 WebSocket,然后发送和接收消息:
当 WebSocket 连接关闭时,`await websocket.receive_text()` 将引发 `WebSocketDisconnect` 异常,您可以捕获并处理该异常,就像本示例中的示例一样。
-=== "Python 3.9+"
+//// tab | Python 3.9+
- ```Python hl_lines="79-81"
- {!> ../../../docs_src/websockets/tutorial003_py39.py!}
- ```
+```Python hl_lines="79-81"
+{!> ../../../docs_src/websockets/tutorial003_py39.py!}
+```
+
+////
+
+//// tab | Python 3.8+
-=== "Python 3.8+"
+```Python hl_lines="81-83"
+{!> ../../../docs_src/websockets/tutorial003.py!}
+```
- ```Python hl_lines="81-83"
- {!> ../../../docs_src/websockets/tutorial003.py!}
- ```
+////
尝试以下操作:
Client #1596980209979 left the chat
```
-!!! tip
- 上面的应用程序是一个最小和简单的示例,用于演示如何处理和向多个 WebSocket 连接广播消息。
+/// tip
+
+上面的应用程序是一个最小和简单的示例,用于演示如何处理和向多个 WebSocket 连接广播消息。
+
+但请记住,由于所有内容都在内存中以单个列表的形式处理,因此它只能在进程运行时工作,并且只能使用单个进程。
- 但请记住,由于所有内容都在内存中以单个列表的形式处理,因此它只能在进程运行时工作,并且只能使用单个进程。
+如果您需要与 FastAPI 集成更简单但更强大的功能,支持 Redis、PostgreSQL 或其他功能,请查看 [encode/broadcaster](https://github.com/encode/broadcaster)。
- 如果您需要与 FastAPI 集成更简单但更强大的功能,支持 Redis、PostgreSQL 或其他功能,请查看 [encode/broadcaster](https://github.com/encode/broadcaster)。
+///
## 更多信息
return results
```
-!!! note
- 你只能在被 `async def` 创建的函数内使用 `await`
+/// note
+
+你只能在被 `async def` 创建的函数内使用 `await`
+
+///
---
<img src="/img/async/concurrent-burgers/concurrent-burgers-07.png" class="illustration">
-!!! info
- 漂亮的插画来自 <a href="https://www.instagram.com/ketrinadrawsalot" class="external-link" target="_blank">Ketrina Thompson</a>. 🎨
+/// info
+
+漂亮的插画来自 <a href="https://www.instagram.com/ketrinadrawsalot" class="external-link" target="_blank">Ketrina Thompson</a>. 🎨
+
+///
---
没有太多的交谈或调情,因为大部分时间 🕙 都在柜台前等待😞。
-!!! info
- 漂亮的插画来自 <a href="https://www.instagram.com/ketrinadrawsalot" class="external-link" target="_blank">Ketrina Thompson</a>. 🎨
+/// info
+
+漂亮的插画来自 <a href="https://www.instagram.com/ketrinadrawsalot" class="external-link" target="_blank">Ketrina Thompson</a>. 🎨
+
+///
---
## 非常技术性的细节
-!!! warning
- 你可以跳过这里。
+/// warning
+
+你可以跳过这里。
+
+这些都是 FastAPI 如何在内部工作的技术细节。
- 这些都是 FastAPI 如何在内部工作的技术细节。
+如果您有相当多的技术知识(协程、线程、阻塞等),并且对 FastAPI 如何处理 `async def` 与常规 `def` 感到好奇,请继续。
- 如果您有相当多的技术知识(协程、线程、阻塞等),并且对 FastAPI 如何处理 `async def` 与常规 `def` 感到好奇,请继续。
+///
### 路径操作函数
使用以下方法激活新环境:
-=== "Linux, macOS"
+//// tab | Linux, macOS
- <div class="termy">
+<div class="termy">
- ```console
- $ source ./env/bin/activate
- ```
+```console
+$ source ./env/bin/activate
+```
- </div>
+</div>
-=== "Windows PowerShell"
+////
- <div class="termy">
+//// tab | Windows PowerShell
- ```console
- $ .\env\Scripts\Activate.ps1
- ```
+<div class="termy">
- </div>
+```console
+$ .\env\Scripts\Activate.ps1
+```
-=== "Windows Bash"
+</div>
+
+////
+
+//// tab | Windows Bash
- Or if you use Bash for Windows (e.g. <a href="https://gitforwindows.org/" class="external-link" target="_blank">Git Bash</a>):
+Or if you use Bash for Windows (e.g. <a href="https://gitforwindows.org/" class="external-link" target="_blank">Git Bash</a>):
- <div class="termy">
+<div class="termy">
+
+```console
+$ source ./env/Scripts/activate
+```
- ```console
- $ source ./env/Scripts/activate
- ```
+</div>
- </div>
+////
要检查操作是否成功,运行:
-=== "Linux, macOS, Windows Bash"
+//// tab | Linux, macOS, Windows Bash
- <div class="termy">
+<div class="termy">
- ```console
- $ which pip
+```console
+$ which pip
- some/directory/fastapi/env/bin/pip
- ```
+some/directory/fastapi/env/bin/pip
+```
- </div>
+</div>
-=== "Windows PowerShell"
+////
- <div class="termy">
+//// tab | Windows PowerShell
- ```console
- $ Get-Command pip
+<div class="termy">
- some/directory/fastapi/env/bin/pip
- ```
+```console
+$ Get-Command pip
+
+some/directory/fastapi/env/bin/pip
+```
- </div>
+</div>
+
+////
如果显示 `pip` 程序文件位于 `env/bin/pip` 则说明激活成功。 🎉
</div>
-!!! tip
- 每一次你在该环境下使用 `pip` 安装了新软件包时,请再次激活该环境。
+/// tip
+
+每一次你在该环境下使用 `pip` 安装了新软件包时,请再次激活该环境。
- 这样可以确保你在使用由该软件包安装的终端程序时使用的是当前虚拟环境中的程序,而不是其他的可能是全局安装的程序。
+这样可以确保你在使用由该软件包安装的终端程序时使用的是当前虚拟环境中的程序,而不是其他的可能是全局安装的程序。
+
+///
### pip
这样,你不必再去重新"安装"你的本地版本即可测试所有更改。
-!!! note "技术细节"
- 仅当你使用此项目中的 `requirements.txt` 安装而不是直接使用 `pip install fastapi` 安装时,才会发生这种情况。
+/// note | "技术细节"
+
+仅当你使用此项目中的 `requirements.txt` 安装而不是直接使用 `pip install fastapi` 安装时,才会发生这种情况。
- 这是因为在 `requirements.txt` 中,本地的 FastAPI 是使用“可编辑” (`-e`)选项安装的
+这是因为在 `requirements.txt` 中,本地的 FastAPI 是使用“可编辑” (`-e`)选项安装的
+
+///
### 格式化
这样,你可以编辑文档 / 源文件并实时查看更改。
-!!! tip
- 或者你也可以手动执行和该脚本一样的操作
+/// tip
- 进入语言目录,如果是英文文档,目录则是 `docs/en/`:
+或者你也可以手动执行和该脚本一样的操作
- ```console
- $ cd docs/en/
- ```
+进入语言目录,如果是英文文档,目录则是 `docs/en/`:
- 在该目录执行 `mkdocs` 命令
+```console
+$ cd docs/en/
+```
- ```console
- $ mkdocs serve --dev-addr 8008
- ```
+在该目录执行 `mkdocs` 命令
+
+```console
+$ mkdocs serve --dev-addr 8008
+```
+
+///
#### Typer CLI (可选)
在 `./scripts/docs.py` 中还有额外工具 / 脚本来处理翻译。
-!!! tip
- 你不需要去了解 `./scripts/docs.py` 中的代码,只需在命令行中使用它即可。
+/// tip
+
+你不需要去了解 `./scripts/docs.py` 中的代码,只需在命令行中使用它即可。
+
+///
所有文档均在 `./docs/en/` 目录中以 Markdown 文件格式保存。
* 在当前 <a href="https://github.com/fastapi/fastapi/pulls" class="external-link" target="_blank">已有的 pull requests</a> 中查找你使用的语言,添加要求修改或同意合并的评审意见。
-!!! tip
- 你可以为已有的 pull requests <a href="https://help.github.com/en/github/collaborating-with-issues-and-pull-requests/commenting-on-a-pull-request" class="external-link" target="_blank">添加包含修改建议的评论</a>。
+/// tip
+
+你可以为已有的 pull requests <a href="https://help.github.com/en/github/collaborating-with-issues-and-pull-requests/commenting-on-a-pull-request" class="external-link" target="_blank">添加包含修改建议的评论</a>。
+
+详情可查看关于 <a href="https://help.github.com/en/github/collaborating-with-issues-and-pull-requests/about-pull-request-reviews" class="external-link" target="_blank">添加 pull request 评审意见</a> 以同意合并或要求修改的文档。
- 详情可查看关于 <a href="https://help.github.com/en/github/collaborating-with-issues-and-pull-requests/about-pull-request-reviews" class="external-link" target="_blank">添加 pull request 评审意见</a> 以同意合并或要求修改的文档。
+///
* 检查在 <a href="https://github.com/fastapi/fastapi/discussions/categories/translations" class="external-link" target="_blank">GitHub Discussion</a> 是否有关于你所用语言的协作翻译。 如果有,你可以订阅它,当有一条新的 PR 请求需要评审时,系统会自动将其添加到讨论中,你也会收到对应的推送。
对于西班牙语来说,它的两位字母代码是 `es`。所以西班牙语翻译的目录位于 `docs/es/`。
-!!! tip
- 默认语言是英语,位于 `docs/en/`目录。
+/// tip
+
+默认语言是英语,位于 `docs/en/`目录。
+
+///
现在为西班牙语文档运行实时服务器:
</div>
-!!! tip
- 或者你也可以手动执行和该脚本一样的操作
+/// tip
+
+或者你也可以手动执行和该脚本一样的操作
- 进入语言目录,对于西班牙语的翻译,目录是 `docs/es/`:
+进入语言目录,对于西班牙语的翻译,目录是 `docs/es/`:
+
+```console
+$ cd docs/es/
+```
- ```console
- $ cd docs/es/
- ```
+在该目录执行 `mkdocs` 命令
- 在该目录执行 `mkdocs` 命令
+```console
+$ mkdocs serve --dev-addr 8008
+```
- ```console
- $ mkdocs serve --dev-addr 8008
- ```
+///
现在你可以访问 <a href="http://127.0.0.1:8008" class="external-link" target="_blank">http://127.0.0.1:8008</a> 实时查看你所做的更改。
docs/es/docs/features.md
```
-!!! tip
- 注意路径和文件名的唯一变化是语言代码,从 `en` 更改为 `es`。
+/// tip
+
+注意路径和文件名的唯一变化是语言代码,从 `en` 更改为 `es`。
+
+///
回到浏览器你就可以看到刚刚更新的章节了。🎉
INHERIT: ../en/mkdocs.yml
```
-!!! tip
- 你也可以自己手动创建包含这些内容的文件。
+/// tip
+
+你也可以自己手动创建包含这些内容的文件。
+
+///
这条命令还会生成一个文档主页 `docs/ht/index.md`,你可以从这个文件开始翻译。
但在那些严重错误导致正在运行的**进程**崩溃的情况下,您需要一个外部组件来负责**重新启动**进程,至少尝试几次......
-!!! tip
+/// tip
- ...尽管如果整个应用程序只是**立即崩溃**,那么永远重新启动它可能没有意义。 但在这些情况下,您可能会在开发过程中注意到它,或者至少在部署后立即注意到它。
+...尽管如果整个应用程序只是**立即崩溃**,那么永远重新启动它可能没有意义。 但在这些情况下,您可能会在开发过程中注意到它,或者至少在部署后立即注意到它。
- 因此,让我们关注主要情况,在**未来**的某些特定情况下,它可能会完全崩溃,但重新启动它仍然有意义。
+ 因此,让我们关注主要情况,在**未来**的某些特定情况下,它可能会完全崩溃,但重新启动它仍然有意义。
+
+///
您可能希望让这个东西作为 **外部组件** 负责重新启动您的应用程序,因为到那时,使用 Uvicorn 和 Python 的同一应用程序已经崩溃了,因此同一应用程序的相同代码中没有东西可以对此做出什么。
-!!! tip
+/// tip
+
+如果这些关于 **容器**、Docker 或 Kubernetes 的内容还没有多大意义,请不要担心。
- 如果这些关于 **容器**、Docker 或 Kubernetes 的内容还没有多大意义,请不要担心。
+ 我将在以后的章节中向您详细介绍容器镜像、Docker、Kubernetes 等:[容器中的 FastAPI - Docker](docker.md){.internal-link target=_blank}。
- 我将在以后的章节中向您详细介绍容器镜像、Docker、Kubernetes 等:[容器中的 FastAPI - Docker](docker.md){.internal-link target=_blank}。
+///
## 启动之前的步骤
当然,也有一些情况,多次运行前面的步骤也没有问题,这样的话就好办多了。
-!!! tip
+/// tip
- 另外,请记住,根据您的设置,在某些情况下,您在开始应用程序之前**可能甚至不需要任何先前的步骤**。
+另外,请记住,根据您的设置,在某些情况下,您在开始应用程序之前**可能甚至不需要任何先前的步骤**。
- 在这种情况下,您就不必担心这些。 🤷
+ 在这种情况下,您就不必担心这些。 🤷
+///
### 前面步骤策略的示例
* 一个 bash 脚本,运行前面的步骤,然后启动您的应用程序
* 您仍然需要一种方法来启动/重新启动 bash 脚本、检测错误等。
-!!! tip
+/// tip
+
+我将在以后的章节中为您提供使用容器执行此操作的更具体示例:[容器中的 FastAPI - Docker](docker.md){.internal-link target=_blank}。
- 我将在以后的章节中为您提供使用容器执行此操作的更具体示例:[容器中的 FastAPI - Docker](docker.md){.internal-link target=_blank}。
+///
## 资源利用率
使用 Linux 容器有几个优点,包括**安全性**、**可复制性**、**简单性**等。
-!!! tip
- 赶时间并且已经知道这些东西了? 跳转到下面的 [`Dockerfile` 👇](#fastapi-docker_1)。
+/// tip
+赶时间并且已经知道这些东西了? 跳转到下面的 [`Dockerfile` 👇](#fastapi-docker_1)。
+
+///
<details>
<summary>Dockerfile Preview 👀</summary>
</div>
-!!! info
- 还有其他文件格式和工具来定义和安装依赖项。
+/// info
+
+还有其他文件格式和工具来定义和安装依赖项。
+
+ 我将在下面的部分中向你展示一个使用 Poetry 的示例。 👇
- 我将在下面的部分中向你展示一个使用 Poetry 的示例。 👇
+///
### 创建 **FastAPI** 代码
因为程序将从`/code`启动,并且其中包含你的代码的目录`./app`,所以**Uvicorn**将能够从`app.main`中查看并**import**`app`。
-!!! tip
- 通过单击代码中的每个数字气泡来查看每行的作用。 👆
+/// tip
+
+通过单击代码中的每个数字气泡来查看每行的作用。 👆
+
+///
你现在应该具有如下目录结构:
```
</div>
-!!! tip
- 注意最后的 `.`,它相当于`./`,它告诉 Docker 用于构建容器镜像的目录。
+/// tip
- 在本例中,它是相同的当前目录(`.`)。
+注意最后的 `.`,它相当于`./`,它告诉 Docker 用于构建容器镜像的目录。
+
+在本例中,它是相同的当前目录(`.`)。
+
+///
### 启动 Docker 容器
它可以是另一个容器,例如使用 <a href="https://traefik.io/" class="external-link" target="_blank">Traefik</a>,处理 **HTTPS** 和 **自动**获取**证书**。
-!!! tip
- Traefik可以与 Docker、Kubernetes 等集成,因此使用它为容器设置和配置 HTTPS 非常容易。
+/// tip
+
+Traefik可以与 Docker、Kubernetes 等集成,因此使用它为容器设置和配置 HTTPS 非常容易。
+
+///
或者,HTTPS 可以由云服务商作为其服务之一进行处理(同时仍在容器中运行应用程序)。
由于该组件将接受请求的**负载**并(希望)以**平衡**的方式在worker之间分配该请求,因此它通常也称为**负载均衡器**。
-!!! tip
- 用于 HTTPS **TLS 终止代理** 的相同组件也可能是 **负载均衡器**。
+/// tip
+
+用于 HTTPS **TLS 终止代理** 的相同组件也可能是 **负载均衡器**。
+
+///
当使用容器时,你用来启动和管理容器的同一系统已经具有内部工具来传输来自该**负载均衡器**(也可以是**TLS 终止代理**) 的**网络通信**(例如HTTP请求)到你的应用程序容器。
如果你有 **多个容器**,可能每个容器都运行一个 **单个进程**(例如,在 **Kubernetes** 集群中),那么你可能希望有一个 **单独的容器** 执行以下操作: 在单个容器中运行单个进程执行**先前步骤**,即运行复制的worker容器之前。
-!!! info
- 如果你使用 Kubernetes,这可能是 <a href="https://kubernetes.io/docs/concepts/workloads/pods/init-containers/" class="external-link" target="_blank">Init Container</a>。
+/// info
+
+如果你使用 Kubernetes,这可能是 <a href="https://kubernetes.io/docs/concepts/workloads/pods/init-containers/" class="external-link" target="_blank">Init Container</a>。
+
+///
如果在你的用例中,运行前面的步骤**并行多次**没有问题(例如,如果你没有运行数据库迁移,而只是检查数据库是否已准备好),那么你也可以将它们放在开始主进程之前在每个容器中。
* <a href="https://github.com/tiangolo/uvicorn-gunicorn-fastapi-docker" class="external-link" target="_blank">tiangolo/uvicorn-gunicorn-fastapi</a>.
-!!! warning
- 你很有可能不需要此基础镜像或任何其他类似的镜像,最好从头开始构建镜像,如[上面所述:为 FastAPI 构建 Docker 镜像](#build-a-docker-image-for-fastapi)。
+/// warning
+
+你很有可能不需要此基础镜像或任何其他类似的镜像,最好从头开始构建镜像,如[上面所述:为 FastAPI 构建 Docker 镜像](#build-a-docker-image-for-fastapi)。
+
+///
该镜像包含一个**自动调整**机制,用于根据可用的 CPU 核心设置**worker进程数**。
它还支持通过一个脚本运行<a href="https://github.com/tiangolo/uvicorn-gunicorn-fastapi-docker#pre_start_path" class="external-link" target="_blank">**开始前的先前步骤** </a>。
-!!! tip
- 要查看所有配置和选项,请转到 Docker 镜像页面: <a href="https://github.com/tiangolo/uvicorn-gunicorn-fastapi-docker" class="external-link" target="_blank" >tiangolo/uvicorn-gunicorn-fastapi</a>。
+/// tip
+
+要查看所有配置和选项,请转到 Docker 镜像页面: <a href="https://github.com/tiangolo/uvicorn-gunicorn-fastapi-docker" class="external-link" target="_blank" >tiangolo/uvicorn-gunicorn-fastapi</a>。
+
+///
### 官方 Docker 镜像上的进程数
11. 运行`uvicorn`命令,告诉它使用从`app.main`导入的`app`对象。
-!!! tip
- 单击气泡数字可查看每行的作用。
+/// tip
+
+单击气泡数字可查看每行的作用。
+
+///
**Docker stage** 是 `Dockerfile` 的一部分,用作 **临时容器镜像**,仅用于生成一些稍后使用的文件。
这个操作一般只需要在最开始执行一次。
-!!! tip
- 域名这部分发生在 HTTPS 之前,由于这一切都依赖于域名和 IP 地址,所以先在这里提一下。
+/// tip
+
+域名这部分发生在 HTTPS 之前,由于这一切都依赖于域名和 IP 地址,所以先在这里提一下。
+
+///
### DNS
这就是 **HTTPS**,它只是 **安全 TLS 连接** 内的普通 **HTTP**,而不是纯粹的(未加密的)TCP 连接。
-!!! tip
- 请注意,通信加密发生在 **TCP 层**,而不是 HTTP 层。
+/// tip
+
+请注意,通信加密发生在 **TCP 层**,而不是 HTTP 层。
+
+///
### HTTPS 请求
您可以使用以下命令安装 ASGI 兼容服务器:
-=== "Uvicorn"
+//// tab | Uvicorn
- * <a href="https://www.uvicorn.org/" class="external-link" target="_blank">Uvicorn</a>,一个快如闪电 ASGI 服务器,基于 uvloop 和 httptools 构建。
+* <a href="https://www.uvicorn.org/" class="external-link" target="_blank">Uvicorn</a>,一个快如闪电 ASGI 服务器,基于 uvloop 和 httptools 构建。
- <div class="termy">
+<div class="termy">
+
+```console
+$ pip install "uvicorn[standard]"
+
+---> 100%
+```
- ```console
- $ pip install "uvicorn[standard]"
+</div>
+
+/// tip
- ---> 100%
- ```
+通过添加`standard`,Uvicorn 将安装并使用一些推荐的额外依赖项。
- </div>
+其中包括`uvloop`,它是`asyncio`的高性能替代品,它提供了巨大的并发性能提升。
- !!! tip
- 通过添加`standard`,Uvicorn 将安装并使用一些推荐的额外依赖项。
+///
- 其中包括`uvloop`,它是`asyncio`的高性能替代品,它提供了巨大的并发性能提升。
+////
-=== "Hypercorn"
+//// tab | Hypercorn
- * <a href="https://github.com/pgjones/hypercorn" class="external-link" target="_blank">Hypercorn</a>,一个也与 HTTP/2 兼容的 ASGI 服务器。
+* <a href="https://github.com/pgjones/hypercorn" class="external-link" target="_blank">Hypercorn</a>,一个也与 HTTP/2 兼容的 ASGI 服务器。
- <div class="termy">
+<div class="termy">
- ```console
- $ pip install hypercorn
+```console
+$ pip install hypercorn
- ---> 100%
- ```
+---> 100%
+```
- </div>
+</div>
- ...或任何其他 ASGI 服务器。
+...或任何其他 ASGI 服务器。
+////
## 运行服务器程序
您可以按照之前教程中的相同方式运行应用程序,但不使用`--reload`选项,例如:
-=== "Uvicorn"
+//// tab | Uvicorn
+
+<div class="termy">
+
+```console
+$ uvicorn main:app --host 0.0.0.0 --port 80
+
+<span style="color: green;">INFO</span>: Uvicorn running on http://0.0.0.0:80 (Press CTRL+C to quit)
+```
- <div class="termy">
+</div>
- ```console
- $ uvicorn main:app --host 0.0.0.0 --port 80
+////
- <span style="color: green;">INFO</span>: Uvicorn running on http://0.0.0.0:80 (Press CTRL+C to quit)
- ```
+//// tab | Hypercorn
- </div>
+<div class="termy">
+```console
+$ hypercorn main:app --bind 0.0.0.0:80
-=== "Hypercorn"
+Running on 0.0.0.0:8080 over http (CTRL + C to quit)
+```
- <div class="termy">
+</div>
- ```console
- $ hypercorn main:app --bind 0.0.0.0:80
+////
- Running on 0.0.0.0:8080 over http (CTRL + C to quit)
- ```
+/// warning
- </div>
+如果您正在使用`--reload`选项,请记住删除它。
-!!! warning
- 如果您正在使用`--reload`选项,请记住删除它。
+ `--reload` 选项消耗更多资源,并且更不稳定。
- `--reload` 选项消耗更多资源,并且更不稳定。
+ 它在**开发**期间有很大帮助,但您**不应该**在**生产环境**中使用它。
- 它在**开发**期间有很大帮助,但您**不应该**在**生产环境**中使用它。
+///
## Hypercorn with Trio
在这里我将向您展示如何将 <a href="https://gunicorn.org/" class="external-link" target="_blank">**Gunicorn**</a> 与 **Uvicorn worker 进程** 一起使用。
-!!! info
- 如果您正在使用容器,例如 Docker 或 Kubernetes,我将在下一章中告诉您更多相关信息:[容器中的 FastAPI - Docker](docker.md){.internal-link target=_blank}。
+/// info
- 特别是,当在 **Kubernetes** 上运行时,您可能**不想**使用 Gunicorn,而是运行 **每个容器一个 Uvicorn 进程**,但我将在本章后面告诉您这一点。
+如果您正在使用容器,例如 Docker 或 Kubernetes,我将在下一章中告诉您更多相关信息:[容器中的 FastAPI - Docker](docker.md){.internal-link target=_blank}。
+特别是,当在 **Kubernetes** 上运行时,您可能**不想**使用 Gunicorn,而是运行 **每个容器一个 Uvicorn 进程**,但我将在本章后面告诉您这一点。
+///
## Gunicorn with Uvicorn Workers
FastAPI 还遵循这样的约定:任何`PATCH`版本更改都是为了bug修复和non-breaking changes。
-!!! tip
- "PATCH"是最后一个数字,例如,在`0.2.3`中,PATCH版本是`3`。
+/// tip
+
+"PATCH"是最后一个数字,例如,在`0.2.3`中,PATCH版本是`3`。
+
+///
因此,你应该能够固定到如下版本:
"MINOR"版本中会添加breaking changes和新功能。
-!!! tip
- "MINOR"是中间的数字,例如,在`0.2.3`中,MINOR版本是`2`。
+/// tip
+
+"MINOR"是中间的数字,例如,在`0.2.3`中,MINOR版本是`2`。
+
+///
## 升级FastAPI版本
在大多数情况下,你会(且应该)有一个“终止代理”在上层为你处理 HTTPS,这取决于你如何部署应用程序,你的服务提供商可能会为你处理此事,或者你可能需要自己设置。
-!!! tip "提示"
- 你可以在 [deployment documentation](deployment/index.md){.internal-link target=_blank} 获得更多信息。
+/// tip | "提示"
+
+你可以在 [deployment documentation](deployment/index.md){.internal-link target=_blank} 获得更多信息。
+
+///
他们通过帮助许多人而被证明是 **FastAPI 专家**。 ✨
-!!! 小提示
- 你也可以成为认可的 FastAPI 专家!
+/// 小提示
- 只需要 [帮助他人解决 GitHub 上的问题](help-fastapi.md#github_1){.internal-link target=_blank}。 🤓
+你也可以成为认可的 FastAPI 专家!
+
+只需要 [帮助他人解决 GitHub 上的问题](help-fastapi.md#github_1){.internal-link target=_blank}。 🤓
+
+///
你可以查看不同时期的 **FastAPI 专家**:
```
-!!! info
- `**second_user_data` 意思是:
+/// info
- 直接将`second_user_data`字典的键和值直接作为key-value参数传递,等同于:`User(id=4, name="Mary", joined="2018-11-30")`
+`**second_user_data` 意思是:
+
+直接将`second_user_data`字典的键和值直接作为key-value参数传递,等同于:`User(id=4, name="Mary", joined="2018-11-30")`
+
+///
### 编辑器支持
快加入 👥 <a href="https://discord.gg/VQjSZaeJmf" class="external-link" target="_blank">Discord 聊天服务器</a> 👥 和 FastAPI 社区里的小伙伴一起哈皮吧。
-!!! tip "提示"
+/// tip | "提示"
- 如有问题,请在 <a href="https://github.com/fastapi/fastapi/issues/new/choose" class="external-link" target="_blank">GitHub Issues</a> 里提问,在这里更容易得到 [FastAPI 专家](fastapi-people.md#_3){.internal-link target=_blank}的帮助。
+如有问题,请在 <a href="https://github.com/fastapi/fastapi/issues/new/choose" class="external-link" target="_blank">GitHub Issues</a> 里提问,在这里更容易得到 [FastAPI 专家](fastapi-people.md#_3){.internal-link target=_blank}的帮助。
- 聊天室仅供闲聊。
+聊天室仅供闲聊。
+
+///
### 别在聊天室里提问
如果某些内容看起来对你的项目有用,请继续查阅,否则请直接跳过它们。
-!!! 小技巧
+/// 小技巧
- 如果你想以系统的方式**学习 FastAPI**(推荐),请阅读 [教程 - 用户指南](../tutorial/index.md){.internal-link target=_blank} 的每一章节。
+如果你想以系统的方式**学习 FastAPI**(推荐),请阅读 [教程 - 用户指南](../tutorial/index.md){.internal-link target=_blank} 的每一章节。
+
+///
但即使你不会用到 **FastAPI**,了解一下类型提示也会让你从中受益。
-!!! note
- 如果你已经精通 Python,并且了解关于类型提示的一切知识,直接跳到下一章节吧。
+/// note
+
+如果你已经精通 Python,并且了解关于类型提示的一切知识,直接跳到下一章节吧。
+
+///
## 动机
{!../../../docs_src/python_types/tutorial010.py!}
```
-!!! info
- 想进一步了解 <a href="https://docs.pydantic.dev/" class="external-link" target="_blank">Pydantic,请阅读其文档</a>.
+/// info
+
+想进一步了解 <a href="https://docs.pydantic.dev/" class="external-link" target="_blank">Pydantic,请阅读其文档</a>.
+
+///
整个 **FastAPI** 建立在 Pydantic 的基础之上。
最重要的是,通过使用标准的 Python 类型,只需要在一个地方声明(而不是添加更多的类、装饰器等),**FastAPI** 会为你完成很多的工作。
-!!! info
- 如果你已经阅读了所有教程,回过头来想了解有关类型的更多信息,<a href="https://mypy.readthedocs.io/en/latest/cheat_sheet_py3.html" class="external-link" target="_blank">来自 `mypy` 的"速查表"</a>是不错的资源。
+/// info
+
+如果你已经阅读了所有教程,回过头来想了解有关类型的更多信息,<a href="https://mypy.readthedocs.io/en/latest/cheat_sheet_py3.html" class="external-link" target="_blank">来自 `mypy` 的"速查表"</a>是不错的资源。
+
+///
**FastAPI** 知道在每种情况下该做什么以及如何复用同一对象,因此所有后台任务被合并在一起并且随后在后台运行:
-=== "Python 3.10+"
+//// tab | Python 3.10+
- ```Python hl_lines="13 15 22 25"
- {!> ../../../docs_src/background_tasks/tutorial002_an_py310.py!}
- ```
+```Python hl_lines="13 15 22 25"
+{!> ../../../docs_src/background_tasks/tutorial002_an_py310.py!}
+```
+
+////
+
+//// tab | Python 3.9+
+
+```Python hl_lines="13 15 22 25"
+{!> ../../../docs_src/background_tasks/tutorial002_an_py39.py!}
+```
+
+////
+
+//// tab | Python 3.8+
-=== "Python 3.9+"
+```Python hl_lines="14 16 23 26"
+{!> ../../../docs_src/background_tasks/tutorial002_an.py!}
+```
+
+////
- ```Python hl_lines="13 15 22 25"
- {!> ../../../docs_src/background_tasks/tutorial002_an_py39.py!}
- ```
+//// tab | Python 3.10+ 没Annotated
-=== "Python 3.8+"
+/// tip
- ```Python hl_lines="14 16 23 26"
- {!> ../../../docs_src/background_tasks/tutorial002_an.py!}
- ```
+尽可能选择使用 `Annotated` 的版本。
-=== "Python 3.10+ 没Annotated"
+///
+
+```Python hl_lines="11 13 20 23"
+{!> ../../../docs_src/background_tasks/tutorial002_py310.py!}
+```
- !!! tip
- 尽可能选择使用 `Annotated` 的版本。
+////
- ```Python hl_lines="11 13 20 23"
- {!> ../../../docs_src/background_tasks/tutorial002_py310.py!}
- ```
+//// tab | Python 3.8+ 没Annotated
-=== "Python 3.8+ 没Annotated"
+/// tip
- !!! tip
- 尽可能选择使用 `Annotated` 的版本。
+尽可能选择使用 `Annotated` 的版本。
+
+///
+
+```Python hl_lines="13 15 22 25"
+{!> ../../../docs_src/background_tasks/tutorial002.py!}
+```
- ```Python hl_lines="13 15 22 25"
- {!> ../../../docs_src/background_tasks/tutorial002.py!}
- ```
+////
该示例中,信息会在响应发出 *之后* 被写到 `log.txt` 文件。
**FastAPI** 提供了一个方便的工具,可以在保持所有灵活性的同时构建你的应用程序。
-!!! info
- 如果你来自 Flask,那这将相当于 Flask 的 Blueprints。
+/// info
+
+如果你来自 Flask,那这将相当于 Flask 的 Blueprints。
+
+///
## 一个文件结构示例
│ └── 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`。
所有相同的 `parameters`、`responses`、`dependencies`、`tags` 等等。
-!!! tip
- 在此示例中,该变量被命名为 `router`,但你可以根据你的想法自由命名。
+/// tip
+
+在此示例中,该变量被命名为 `router`,但你可以根据你的想法自由命名。
+
+///
我们将在主 `FastAPI` 应用中包含该 `APIRouter`,但首先,让我们来看看依赖项和另一个 `APIRouter`。
{!../../../docs_src/bigger_applications/app/dependencies.py!}
```
-!!! tip
- 我们正在使用虚构的请求首部来简化此示例。
+/// tip
+
+我们正在使用虚构的请求首部来简化此示例。
+
+但在实际情况下,使用集成的[安全性实用工具](security/index.md){.internal-link target=_blank}会得到更好的效果。
- 但在实际情况下,使用集成的[安全性实用工具](security/index.md){.internal-link target=_blank}会得到更好的效果。
+///
## 其他使用 `APIRouter` 的模块
我们可以添加一个 `dependencies` 列表,这些依赖项将被添加到路由器中的所有*路径操作*中,并将针对向它们发起的每个请求执行/解决。
-!!! tip
- 请注意,和[*路径操作装饰器*中的依赖项](dependencies/dependencies-in-path-operation-decorators.md){.internal-link target=_blank}很类似,没有值会被传递给你的*路径操作函数*。
+/// tip
+
+请注意,和[*路径操作装饰器*中的依赖项](dependencies/dependencies-in-path-operation-decorators.md){.internal-link target=_blank}很类似,没有值会被传递给你的*路径操作函数*。
+
+///
最终结果是项目相关的路径现在为:
* 路由器的依赖项最先执行,然后是[装饰器中的 `dependencies`](dependencies/dependencies-in-path-operation-decorators.md){.internal-link target=_blank},再然后是普通的参数依赖项。
* 你还可以添加[具有 `scopes` 的 `Security` 依赖项](../advanced/security/oauth2-scopes.md){.internal-link target=_blank}。
-!!! tip
- 在 `APIRouter`中具有 `dependencies` 可以用来,例如,对一整组的*路径操作*要求身份认证。即使这些依赖项并没有分别添加到每个路径操作中。
+/// tip
+
+在 `APIRouter`中具有 `dependencies` 可以用来,例如,对一整组的*路径操作*要求身份认证。即使这些依赖项并没有分别添加到每个路径操作中。
+
+///
+
+/// check
-!!! check
- `prefix`、`tags`、`responses` 以及 `dependencies` 参数只是(和其他很多情况一样)**FastAPI** 的一个用于帮助你避免代码重复的功能。
+`prefix`、`tags`、`responses` 以及 `dependencies` 参数只是(和其他很多情况一样)**FastAPI** 的一个用于帮助你避免代码重复的功能。
+
+///
### 导入依赖项
#### 相对导入如何工作
-!!! tip
- 如果你完全了解导入的工作原理,请从下面的下一部分继续。
+/// tip
+
+如果你完全了解导入的工作原理,请从下面的下一部分继续。
+
+///
一个单点 `.`,例如:
{!../../../docs_src/bigger_applications/app/routers/items.py!}
```
-!!! tip
- 最后的这个路径操作将包含标签的组合:`["items","custom"]`。
+/// tip
+
+最后的这个路径操作将包含标签的组合:`["items","custom"]`。
- 并且在文档中也会有两个响应,一个用于 `404`,一个用于 `403`。
+并且在文档中也会有两个响应,一个用于 `404`,一个用于 `403`。
+
+///
## `FastAPI` 主体
from app.routers import items, users
```
-!!! info
- 第一个版本是「相对导入」:
+/// info
+
+第一个版本是「相对导入」:
- ```Python
- from .routers import items, users
- ```
+```Python
+from .routers import items, users
+```
- 第二个版本是「绝对导入」:
+第二个版本是「绝对导入」:
+
+```Python
+from app.routers import items, users
+```
- ```Python
- from app.routers import items, users
- ```
+要了解有关 Python 包和模块的更多信息,请查阅<a href="https://docs.python.org/3/tutorial/modules.html" class="external-link" target="_blank">关于 Modules 的 Python 官方文档</a>。
- 要了解有关 Python 包和模块的更多信息,请查阅<a href="https://docs.python.org/3/tutorial/modules.html" class="external-link" target="_blank">关于 Modules 的 Python 官方文档</a>。
+///
### 避免名称冲突
{!../../../docs_src/bigger_applications/app/main.py!}
```
-!!! info
- `users.router` 包含了 `app/routers/users.py` 文件中的 `APIRouter`。
+/// info
- `items.router` 包含了 `app/routers/items.py` 文件中的 `APIRouter`。
+`users.router` 包含了 `app/routers/users.py` 文件中的 `APIRouter`。
+
+`items.router` 包含了 `app/routers/items.py` 文件中的 `APIRouter`。
+
+///
使用 `app.include_router()`,我们可以将每个 `APIRouter` 添加到主 `FastAPI` 应用程序中。
它将包含来自该路由器的所有路由作为其一部分。
-!!! note "技术细节"
- 实际上,它将在内部为声明在 `APIRouter` 中的每个*路径操作*创建一个*路径操作*。
+/// note | "技术细节"
+
+实际上,它将在内部为声明在 `APIRouter` 中的每个*路径操作*创建一个*路径操作*。
+
+所以,在幕后,它实际上会像所有的东西都是同一个应用程序一样工作。
+
+///
- 所以,在幕后,它实际上会像所有的东西都是同一个应用程序一样工作。
+/// check
-!!! check
- 包含路由器时,你不必担心性能问题。
+包含路由器时,你不必担心性能问题。
- 这将花费几微秒时间,并且只会在启动时发生。
+这将花费几微秒时间,并且只会在启动时发生。
- 因此,它不会影响性能。⚡
+因此,它不会影响性能。⚡
+
+///
### 包含一个有自定义 `prefix`、`tags`、`responses` 和 `dependencies` 的 `APIRouter`
它将与通过 `app.include_router()` 添加的所有其他*路径操作*一起正常运行。
-!!! info "特别的技术细节"
- **注意**:这是一个非常技术性的细节,你也许可以**直接跳过**。
+/// info | "特别的技术细节"
+
+**注意**:这是一个非常技术性的细节,你也许可以**直接跳过**。
+
+---
- ---
+`APIRouter` 没有被「挂载」,它们与应用程序的其余部分没有隔离。
- `APIRouter` 没有被「挂载」,它们与应用程序的其余部分没有隔离。
+这是因为我们想要在 OpenAPI 模式和用户界面中包含它们的*路径操作*。
- 这是因为我们想要在 OpenAPI 模式和用户界面中包含它们的*路径操作*。
+由于我们不能仅仅隔离它们并独立于其余部分来「挂载」它们,因此*路径操作*是被「克隆的」(重新创建),而不是直接包含。
- 由于我们不能仅仅隔离它们并独立于其余部分来「挂载」它们,因此*路径操作*是被「克隆的」(重新创建),而不是直接包含。
+///
## 查看自动化的 API 文档
首先,从 Pydantic 中导入 `Field`:
-=== "Python 3.10+"
+//// tab | Python 3.10+
- ```Python hl_lines="4"
- {!> ../../../docs_src/body_fields/tutorial001_an_py310.py!}
- ```
+```Python hl_lines="4"
+{!> ../../../docs_src/body_fields/tutorial001_an_py310.py!}
+```
-=== "Python 3.9+"
+////
- ```Python hl_lines="4"
- {!> ../../../docs_src/body_fields/tutorial001_an_py39.py!}
- ```
+//// tab | Python 3.9+
-=== "Python 3.8+"
+```Python hl_lines="4"
+{!> ../../../docs_src/body_fields/tutorial001_an_py39.py!}
+```
- ```Python hl_lines="4"
- {!> ../../../docs_src/body_fields/tutorial001_an.py!}
- ```
+////
-=== "Python 3.10+ non-Annotated"
+//// tab | Python 3.8+
- !!! tip
- 尽可能选择使用 `Annotated` 的版本。
+```Python hl_lines="4"
+{!> ../../../docs_src/body_fields/tutorial001_an.py!}
+```
- ```Python hl_lines="2"
- {!> ../../../docs_src/body_fields/tutorial001_py310.py!}
- ```
+////
-=== "Python 3.8+ non-Annotated"
+//// tab | Python 3.10+ non-Annotated
- !!! tip
- 尽可能选择使用 `Annotated` 的版本。
+/// tip
- ```Python hl_lines="4"
- {!> ../../../docs_src/body_fields/tutorial001.py!}
- ```
+尽可能选择使用 `Annotated` 的版本。
-!!! warning "警告"
+///
- 注意,与从 `fastapi` 导入 `Query`,`Path`、`Body` 不同,要直接从 `pydantic` 导入 `Field` 。
+```Python hl_lines="2"
+{!> ../../../docs_src/body_fields/tutorial001_py310.py!}
+```
+
+////
+
+//// tab | Python 3.8+ non-Annotated
+
+/// tip
+
+尽可能选择使用 `Annotated` 的版本。
+
+///
+
+```Python hl_lines="4"
+{!> ../../../docs_src/body_fields/tutorial001.py!}
+```
+
+////
+
+/// warning | "警告"
+
+注意,与从 `fastapi` 导入 `Query`,`Path`、`Body` 不同,要直接从 `pydantic` 导入 `Field` 。
+
+///
## 声明模型属性
然后,使用 `Field` 定义模型的属性:
-=== "Python 3.10+"
+//// tab | Python 3.10+
+
+```Python hl_lines="11-14"
+{!> ../../../docs_src/body_fields/tutorial001_an_py310.py!}
+```
- ```Python hl_lines="11-14"
- {!> ../../../docs_src/body_fields/tutorial001_an_py310.py!}
- ```
+////
-=== "Python 3.9+"
+//// tab | Python 3.9+
- ```Python hl_lines="11-14"
- {!> ../../../docs_src/body_fields/tutorial001_an_py39.py!}
- ```
+```Python hl_lines="11-14"
+{!> ../../../docs_src/body_fields/tutorial001_an_py39.py!}
+```
-=== "Python 3.8+"
+////
- ```Python hl_lines="12-15"
- {!> ../../../docs_src/body_fields/tutorial001_an.py!}
- ```
+//// tab | Python 3.8+
-=== "Python 3.10+ non-Annotated"
+```Python hl_lines="12-15"
+{!> ../../../docs_src/body_fields/tutorial001_an.py!}
+```
- !!! tip
- Prefer to use the `Annotated` version if possible.
+////
- ```Python hl_lines="9-12"
- {!> ../../../docs_src/body_fields/tutorial001_py310.py!}
- ```
+//// tab | Python 3.10+ non-Annotated
-=== "Python 3.8+ non-Annotated"
+/// tip
- !!! tip
- Prefer to use the `Annotated` version if possible.
+Prefer to use the `Annotated` version if possible.
- ```Python hl_lines="11-14"
- {!> ../../../docs_src/body_fields/tutorial001.py!}
- ```
+///
+
+```Python hl_lines="9-12"
+{!> ../../../docs_src/body_fields/tutorial001_py310.py!}
+```
+
+////
+
+//// tab | Python 3.8+ non-Annotated
+
+/// tip
+
+Prefer to use the `Annotated` version if possible.
+
+///
+
+```Python hl_lines="11-14"
+{!> ../../../docs_src/body_fields/tutorial001.py!}
+```
+
+////
`Field` 的工作方式和 `Query`、`Path`、`Body` 相同,参数也相同。
-!!! note "技术细节"
+/// note | "技术细节"
+
+实际上,`Query`、`Path` 都是 `Params` 的子类,而 `Params` 类又是 Pydantic 中 `FieldInfo` 的子类。
+
+Pydantic 的 `Field` 返回也是 `FieldInfo` 的类实例。
- 实际上,`Query`、`Path` 都是 `Params` 的子类,而 `Params` 类又是 Pydantic 中 `FieldInfo` 的子类。
+`Body` 直接返回的也是 `FieldInfo` 的子类的对象。后文还会介绍一些 `Body` 的子类。
- Pydantic 的 `Field` 返回也是 `FieldInfo` 的类实例。
+注意,从 `fastapi` 导入的 `Query`、`Path` 等对象实际上都是返回特殊类的函数。
- `Body` 直接返回的也是 `FieldInfo` 的子类的对象。后文还会介绍一些 `Body` 的子类。
+///
- 注意,从 `fastapi` 导入的 `Query`、`Path` 等对象实际上都是返回特殊类的函数。
+/// tip | "提示"
-!!! tip "提示"
+注意,模型属性的类型、默认值及 `Field` 的代码结构与*路径操作函数*的参数相同,只不过是用 `Field` 替换了`Path`、`Query`、`Body`。
- 注意,模型属性的类型、默认值及 `Field` 的代码结构与*路径操作函数*的参数相同,只不过是用 `Field` 替换了`Path`、`Query`、`Body`。
+///
## 添加更多信息
你还可以通过将默认值设置为 `None` 来将请求体参数声明为可选参数:
-=== "Python 3.10+"
+//// tab | Python 3.10+
- ```Python hl_lines="18-20"
- {!> ../../../docs_src/body_multiple_params/tutorial001_an_py310.py!}
- ```
+```Python hl_lines="18-20"
+{!> ../../../docs_src/body_multiple_params/tutorial001_an_py310.py!}
+```
+
+////
+
+//// tab | Python 3.9+
+
+```Python hl_lines="18-20"
+{!> ../../../docs_src/body_multiple_params/tutorial001_an_py39.py!}
+```
+
+////
+
+//// tab | Python 3.8+
+
+```Python hl_lines="19-21"
+{!> ../../../docs_src/body_multiple_params/tutorial001_an.py!}
+```
+
+////
+
+//// tab | Python 3.10+ non-Annotated
+
+/// tip
-=== "Python 3.9+"
+尽可能选择使用 `Annotated` 的版本。
- ```Python hl_lines="18-20"
- {!> ../../../docs_src/body_multiple_params/tutorial001_an_py39.py!}
- ```
+///
-=== "Python 3.8+"
+```Python hl_lines="17-19"
+{!> ../../../docs_src/body_multiple_params/tutorial001_py310.py!}
+```
+
+////
- ```Python hl_lines="19-21"
- {!> ../../../docs_src/body_multiple_params/tutorial001_an.py!}
- ```
+//// tab | Python 3.8+ non-Annotated
-=== "Python 3.10+ non-Annotated"
+/// tip
- !!! tip
- 尽可能选择使用 `Annotated` 的版本。
+尽可能选择使用 `Annotated` 的版本。
- ```Python hl_lines="17-19"
- {!> ../../../docs_src/body_multiple_params/tutorial001_py310.py!}
- ```
+///
+
+```Python hl_lines="19-21"
+{!> ../../../docs_src/body_multiple_params/tutorial001.py!}
+```
-=== "Python 3.8+ non-Annotated"
+////
- !!! tip
- 尽可能选择使用 `Annotated` 的版本。
+/// note
- ```Python hl_lines="19-21"
- {!> ../../../docs_src/body_multiple_params/tutorial001.py!}
- ```
+请注意,在这种情况下,将从请求体获取的 `item` 是可选的。因为它的默认值为 `None`。
-!!! note
- 请注意,在这种情况下,将从请求体获取的 `item` 是可选的。因为它的默认值为 `None`。
+///
## 多个请求体参数
但是你也可以声明多个请求体参数,例如 `item` 和 `user`:
-=== "Python 3.10+"
+//// tab | Python 3.10+
- ```Python hl_lines="20"
- {!> ../../../docs_src/body_multiple_params/tutorial002_py310.py!}
- ```
+```Python hl_lines="20"
+{!> ../../../docs_src/body_multiple_params/tutorial002_py310.py!}
+```
+
+////
-=== "Python 3.8+"
+//// tab | Python 3.8+
+
+```Python hl_lines="22"
+{!> ../../../docs_src/body_multiple_params/tutorial002.py!}
+```
- ```Python hl_lines="22"
- {!> ../../../docs_src/body_multiple_params/tutorial002.py!}
- ```
+////
在这种情况下,**FastAPI** 将注意到该函数中有多个请求体参数(两个 Pydantic 模型参数)。
}
```
-!!! note
- 请注意,即使 `item` 的声明方式与之前相同,但现在它被期望通过 `item` 键内嵌在请求体中。
+/// note
+请注意,即使 `item` 的声明方式与之前相同,但现在它被期望通过 `item` 键内嵌在请求体中。
+
+///
**FastAPI** 将自动对请求中的数据进行转换,因此 `item` 参数将接收指定的内容,`user` 参数也是如此。
但是你可以使用 `Body` 指示 **FastAPI** 将其作为请求体的另一个键进行处理。
-=== "Python 3.10+"
+//// tab | Python 3.10+
+
+```Python hl_lines="23"
+{!> ../../../docs_src/body_multiple_params/tutorial003_an_py310.py!}
+```
+
+////
+
+//// tab | Python 3.9+
+
+```Python hl_lines="23"
+{!> ../../../docs_src/body_multiple_params/tutorial003_an_py39.py!}
+```
+
+////
+
+//// tab | Python 3.8+
+
+```Python hl_lines="24"
+{!> ../../../docs_src/body_multiple_params/tutorial003_an.py!}
+```
+
+////
+
+//// tab | Python 3.10+ non-Annotated
- ```Python hl_lines="23"
- {!> ../../../docs_src/body_multiple_params/tutorial003_an_py310.py!}
- ```
+/// tip
-=== "Python 3.9+"
+尽可能选择使用 `Annotated` 的版本。
- ```Python hl_lines="23"
- {!> ../../../docs_src/body_multiple_params/tutorial003_an_py39.py!}
- ```
+///
-=== "Python 3.8+"
+```Python hl_lines="20"
+{!> ../../../docs_src/body_multiple_params/tutorial003_py310.py!}
+```
- ```Python hl_lines="24"
- {!> ../../../docs_src/body_multiple_params/tutorial003_an.py!}
- ```
+////
-=== "Python 3.10+ non-Annotated"
+//// tab | Python 3.8+ non-Annotated
- !!! tip
- 尽可能选择使用 `Annotated` 的版本。
+/// tip
- ```Python hl_lines="20"
- {!> ../../../docs_src/body_multiple_params/tutorial003_py310.py!}
- ```
+尽可能选择使用 `Annotated` 的版本。
-=== "Python 3.8+ non-Annotated"
+///
- !!! tip
- 尽可能选择使用 `Annotated` 的版本。
+```Python hl_lines="22"
+{!> ../../../docs_src/body_multiple_params/tutorial003.py!}
+```
- ```Python hl_lines="22"
- {!> ../../../docs_src/body_multiple_params/tutorial003.py!}
- ```
+////
在这种情况下,**FastAPI** 将期望像这样的请求体:
比如:
-=== "Python 3.10+"
+//// tab | Python 3.10+
+
+```Python hl_lines="27"
+{!> ../../../docs_src/body_multiple_params/tutorial004_an_py310.py!}
+```
+
+////
+
+//// tab | Python 3.9+
+
+```Python hl_lines="27"
+{!> ../../../docs_src/body_multiple_params/tutorial004_an_py39.py!}
+```
+
+////
+
+//// tab | Python 3.8+
+
+```Python hl_lines="28"
+{!> ../../../docs_src/body_multiple_params/tutorial004_an.py!}
+```
+
+////
+
+//// tab | Python 3.10+ non-Annotated
+
+/// tip
- ```Python hl_lines="27"
- {!> ../../../docs_src/body_multiple_params/tutorial004_an_py310.py!}
- ```
+尽可能选择使用 `Annotated` 的版本。
-=== "Python 3.9+"
+///
- ```Python hl_lines="27"
- {!> ../../../docs_src/body_multiple_params/tutorial004_an_py39.py!}
- ```
+```Python hl_lines="25"
+{!> ../../../docs_src/body_multiple_params/tutorial004_py310.py!}
+```
-=== "Python 3.8+"
+////
- ```Python hl_lines="28"
- {!> ../../../docs_src/body_multiple_params/tutorial004_an.py!}
- ```
+//// tab | Python 3.8+ non-Annotated
-=== "Python 3.10+ non-Annotated"
+/// tip
- !!! tip
- 尽可能选择使用 `Annotated` 的版本。
+尽可能选择使用 `Annotated` 的版本。
- ```Python hl_lines="25"
- {!> ../../../docs_src/body_multiple_params/tutorial004_py310.py!}
- ```
+///
-=== "Python 3.8+ non-Annotated"
+```Python hl_lines="27"
+{!> ../../../docs_src/body_multiple_params/tutorial004.py!}
+```
- !!! tip
- 尽可能选择使用 `Annotated` 的版本。
+////
- ```Python hl_lines="27"
- {!> ../../../docs_src/body_multiple_params/tutorial004.py!}
- ```
+/// info
-!!! info
- `Body` 同样具有与 `Query`、`Path` 以及其他后面将看到的类完全相同的额外校验和元数据参数。
+`Body` 同样具有与 `Query`、`Path` 以及其他后面将看到的类完全相同的额外校验和元数据参数。
+///
## 嵌入单个请求体参数
比如:
-=== "Python 3.10+"
+//// tab | Python 3.10+
+
+```Python hl_lines="17"
+{!> ../../../docs_src/body_multiple_params/tutorial005_an_py310.py!}
+```
+
+////
+
+//// tab | Python 3.9+
+
+```Python hl_lines="17"
+{!> ../../../docs_src/body_multiple_params/tutorial005_an_py39.py!}
+```
+
+////
+
+//// tab | Python 3.8+
+
+```Python hl_lines="18"
+{!> ../../../docs_src/body_multiple_params/tutorial005_an.py!}
+```
+
+////
+
+//// tab | Python 3.10+ non-Annotated
- ```Python hl_lines="17"
- {!> ../../../docs_src/body_multiple_params/tutorial005_an_py310.py!}
- ```
+/// tip
-=== "Python 3.9+"
+尽可能选择使用 `Annotated` 的版本。
- ```Python hl_lines="17"
- {!> ../../../docs_src/body_multiple_params/tutorial005_an_py39.py!}
- ```
+///
-=== "Python 3.8+"
+```Python hl_lines="15"
+{!> ../../../docs_src/body_multiple_params/tutorial005_py310.py!}
+```
- ```Python hl_lines="18"
- {!> ../../../docs_src/body_multiple_params/tutorial005_an.py!}
- ```
+////
-=== "Python 3.10+ non-Annotated"
+//// tab | Python 3.8+ non-Annotated
- !!! tip
- 尽可能选择使用 `Annotated` 的版本。
+/// tip
- ```Python hl_lines="15"
- {!> ../../../docs_src/body_multiple_params/tutorial005_py310.py!}
- ```
+尽可能选择使用 `Annotated` 的版本。
-=== "Python 3.8+ non-Annotated"
+///
- !!! tip
- 尽可能选择使用 `Annotated` 的版本。
+```Python hl_lines="17"
+{!> ../../../docs_src/body_multiple_params/tutorial005.py!}
+```
- ```Python hl_lines="17"
- {!> ../../../docs_src/body_multiple_params/tutorial005.py!}
- ```
+////
在这种情况下,**FastAPI** 将期望像这样的请求体:
你可以将一个属性定义为拥有子元素的类型。例如 Python `list`:
-=== "Python 3.10+"
+//// tab | Python 3.10+
- ```Python hl_lines="12"
- {!> ../../../docs_src/body_nested_models/tutorial001_py310.py!}
- ```
+```Python hl_lines="12"
+{!> ../../../docs_src/body_nested_models/tutorial001_py310.py!}
+```
+
+////
-=== "Python 3.8+"
+//// tab | Python 3.8+
+
+```Python hl_lines="14"
+{!> ../../../docs_src/body_nested_models/tutorial001.py!}
+```
- ```Python hl_lines="14"
- {!> ../../../docs_src/body_nested_models/tutorial001.py!}
- ```
+////
这将使 `tags` 成为一个由元素组成的列表。不过它没有声明每个元素的类型。
因此,在我们的示例中,我们可以将 `tags` 明确地指定为一个「字符串列表」:
-=== "Python 3.10+"
+//// tab | Python 3.10+
+
+```Python hl_lines="12"
+{!> ../../../docs_src/body_nested_models/tutorial002_py310.py!}
+```
+
+////
+
+//// tab | Python 3.9+
- ```Python hl_lines="12"
- {!> ../../../docs_src/body_nested_models/tutorial002_py310.py!}
- ```
+```Python hl_lines="14"
+{!> ../../../docs_src/body_nested_models/tutorial002_py39.py!}
+```
-=== "Python 3.9+"
+////
- ```Python hl_lines="14"
- {!> ../../../docs_src/body_nested_models/tutorial002_py39.py!}
- ```
+//// tab | Python 3.8+
-=== "Python 3.8+"
+```Python hl_lines="14"
+{!> ../../../docs_src/body_nested_models/tutorial002.py!}
+```
- ```Python hl_lines="14"
- {!> ../../../docs_src/body_nested_models/tutorial002.py!}
- ```
+////
## Set 类型
然后我们可以导入 `Set` 并将 `tag` 声明为一个由 `str` 组成的 `set`:
-=== "Python 3.10+"
+//// tab | Python 3.10+
+
+```Python hl_lines="12"
+{!> ../../../docs_src/body_nested_models/tutorial003_py310.py!}
+```
+
+////
- ```Python hl_lines="12"
- {!> ../../../docs_src/body_nested_models/tutorial003_py310.py!}
- ```
+//// tab | Python 3.9+
-=== "Python 3.9+"
+```Python hl_lines="14"
+{!> ../../../docs_src/body_nested_models/tutorial003_py39.py!}
+```
- ```Python hl_lines="14"
- {!> ../../../docs_src/body_nested_models/tutorial003_py39.py!}
- ```
+////
-=== "Python 3.8+"
+//// tab | Python 3.8+
- ```Python hl_lines="1 14"
- {!> ../../../docs_src/body_nested_models/tutorial003.py!}
- ```
+```Python hl_lines="1 14"
+{!> ../../../docs_src/body_nested_models/tutorial003.py!}
+```
+
+////
这样,即使你收到带有重复数据的请求,这些数据也会被转换为一组唯一项。
例如,我们可以定义一个 `Image` 模型:
-=== "Python 3.10+"
+//// tab | Python 3.10+
+
+```Python hl_lines="7-9"
+{!> ../../../docs_src/body_nested_models/tutorial004_py310.py!}
+```
+
+////
- ```Python hl_lines="7-9"
- {!> ../../../docs_src/body_nested_models/tutorial004_py310.py!}
- ```
+//// tab | Python 3.9+
-=== "Python 3.9+"
+```Python hl_lines="9-11"
+{!> ../../../docs_src/body_nested_models/tutorial004_py39.py!}
+```
+
+////
- ```Python hl_lines="9-11"
- {!> ../../../docs_src/body_nested_models/tutorial004_py39.py!}
- ```
+//// tab | Python 3.8+
-=== "Python 3.8+"
+```Python hl_lines="9-11"
+{!> ../../../docs_src/body_nested_models/tutorial004.py!}
+```
- ```Python hl_lines="9-11"
- {!> ../../../docs_src/body_nested_models/tutorial004.py!}
- ```
+////
### 将子模型用作类型
然后我们可以将其用作一个属性的类型:
-=== "Python 3.10+"
+//// tab | Python 3.10+
- ```Python hl_lines="18"
- {!> ../../../docs_src/body_nested_models/tutorial004_py310.py!}
- ```
+```Python hl_lines="18"
+{!> ../../../docs_src/body_nested_models/tutorial004_py310.py!}
+```
-=== "Python 3.9+"
+////
- ```Python hl_lines="20"
- {!> ../../../docs_src/body_nested_models/tutorial004_py39.py!}
- ```
+//// tab | Python 3.9+
-=== "Python 3.8+"
+```Python hl_lines="20"
+{!> ../../../docs_src/body_nested_models/tutorial004_py39.py!}
+```
+
+////
- ```Python hl_lines="20"
- {!> ../../../docs_src/body_nested_models/tutorial004.py!}
- ```
+//// tab | Python 3.8+
+
+```Python hl_lines="20"
+{!> ../../../docs_src/body_nested_models/tutorial004.py!}
+```
+
+////
这意味着 **FastAPI** 将期望类似于以下内容的请求体:
例如,在 `Image` 模型中我们有一个 `url` 字段,我们可以把它声明为 Pydantic 的 `HttpUrl`,而不是 `str`:
-=== "Python 3.10+"
+//// tab | Python 3.10+
- ```Python hl_lines="2 8"
- {!> ../../../docs_src/body_nested_models/tutorial005_py310.py!}
- ```
+```Python hl_lines="2 8"
+{!> ../../../docs_src/body_nested_models/tutorial005_py310.py!}
+```
-=== "Python 3.9+"
+////
- ```Python hl_lines="4 10"
- {!> ../../../docs_src/body_nested_models/tutorial005_py39.py!}
- ```
+//// tab | Python 3.9+
-=== "Python 3.8+"
+```Python hl_lines="4 10"
+{!> ../../../docs_src/body_nested_models/tutorial005_py39.py!}
+```
- ```Python hl_lines="4 10"
- {!> ../../../docs_src/body_nested_models/tutorial005.py!}
- ```
+////
+
+//// tab | Python 3.8+
+
+```Python hl_lines="4 10"
+{!> ../../../docs_src/body_nested_models/tutorial005.py!}
+```
+
+////
该字符串将被检查是否为有效的 URL,并在 JSON Schema / OpenAPI 文档中进行记录。
你还可以将 Pydantic 模型用作 `list`、`set` 等的子类型:
-=== "Python 3.10+"
+//// tab | Python 3.10+
- ```Python hl_lines="18"
- {!> ../../../docs_src/body_nested_models/tutorial006_py310.py!}
- ```
+```Python hl_lines="18"
+{!> ../../../docs_src/body_nested_models/tutorial006_py310.py!}
+```
+
+////
-=== "Python 3.9+"
+//// tab | Python 3.9+
- ```Python hl_lines="20"
- {!> ../../../docs_src/body_nested_models/tutorial006_py39.py!}
- ```
+```Python hl_lines="20"
+{!> ../../../docs_src/body_nested_models/tutorial006_py39.py!}
+```
-=== "Python 3.8+"
+////
- ```Python hl_lines="20"
- {!> ../../../docs_src/body_nested_models/tutorial006.py!}
- ```
+//// tab | Python 3.8+
+
+```Python hl_lines="20"
+{!> ../../../docs_src/body_nested_models/tutorial006.py!}
+```
+
+////
这将期望(转换,校验,记录文档等)下面这样的 JSON 请求体:
}
```
-!!! info
- 请注意 `images` 键现在具有一组 image 对象是如何发生的。
+/// info
+
+请注意 `images` 键现在具有一组 image 对象是如何发生的。
+
+///
## 深度嵌套模型
你可以定义任意深度的嵌套模型:
-=== "Python 3.10+"
+//// tab | Python 3.10+
+
+```Python hl_lines="7 12 18 21 25"
+{!> ../../../docs_src/body_nested_models/tutorial007_py310.py!}
+```
+
+////
- ```Python hl_lines="7 12 18 21 25"
- {!> ../../../docs_src/body_nested_models/tutorial007_py310.py!}
- ```
+//// tab | Python 3.9+
-=== "Python 3.9+"
+```Python hl_lines="9 14 20 23 27"
+{!> ../../../docs_src/body_nested_models/tutorial007_py39.py!}
+```
+
+////
+
+//// tab | Python 3.8+
+
+```Python hl_lines="9 14 20 23 27"
+{!> ../../../docs_src/body_nested_models/tutorial007.py!}
+```
- ```Python hl_lines="9 14 20 23 27"
- {!> ../../../docs_src/body_nested_models/tutorial007_py39.py!}
- ```
+////
-=== "Python 3.8+"
+/// info
- ```Python hl_lines="9 14 20 23 27"
- {!> ../../../docs_src/body_nested_models/tutorial007.py!}
- ```
+请注意 `Offer` 拥有一组 `Item` 而反过来 `Item` 又是一个可选的 `Image` 列表是如何发生的。
-!!! info
- 请注意 `Offer` 拥有一组 `Item` 而反过来 `Item` 又是一个可选的 `Image` 列表是如何发生的。
+///
## 纯列表请求体
例如:
-=== "Python 3.9+"
+//// tab | Python 3.9+
+
+```Python hl_lines="13"
+{!> ../../../docs_src/body_nested_models/tutorial008_py39.py!}
+```
- ```Python hl_lines="13"
- {!> ../../../docs_src/body_nested_models/tutorial008_py39.py!}
- ```
+////
-=== "Python 3.8+"
+//// tab | Python 3.8+
- ```Python hl_lines="15"
- {!> ../../../docs_src/body_nested_models/tutorial008.py!}
- ```
+```Python hl_lines="15"
+{!> ../../../docs_src/body_nested_models/tutorial008.py!}
+```
+
+////
## 无处不在的编辑器支持
在下面的例子中,你将接受任意键为 `int` 类型并且值为 `float` 类型的 `dict`:
-=== "Python 3.9+"
+//// tab | Python 3.9+
+
+```Python hl_lines="7"
+{!> ../../../docs_src/body_nested_models/tutorial009_py39.py!}
+```
+
+////
+
+//// tab | Python 3.8+
+
+```Python hl_lines="9"
+{!> ../../../docs_src/body_nested_models/tutorial009.py!}
+```
- ```Python hl_lines="7"
- {!> ../../../docs_src/body_nested_models/tutorial009_py39.py!}
- ```
+////
-=== "Python 3.8+"
+/// tip
- ```Python hl_lines="9"
- {!> ../../../docs_src/body_nested_models/tutorial009.py!}
- ```
+请记住 JSON 仅支持将 `str` 作为键。
-!!! tip
- 请记住 JSON 仅支持将 `str` 作为键。
+但是 Pydantic 具有自动转换数据的功能。
- 但是 Pydantic 具有自动转换数据的功能。
+这意味着,即使你的 API 客户端只能将字符串作为键发送,只要这些字符串内容仅包含整数,Pydantic 就会对其进行转换并校验。
- 这意味着,即使你的 API 客户端只能将字符串作为键发送,只要这些字符串内容仅包含整数,Pydantic 就会对其进行转换并校验。
+然后你接收的名为 `weights` 的 `dict` 实际上将具有 `int` 类型的键和 `float` 类型的值。
- 然后你接收的名为 `weights` 的 `dict` 实际上将具有 `int` 类型的键和 `float` 类型的值。
+///
## 总结
即,只发送要更新的数据,其余数据保持不变。
-!!! note "笔记"
+/// note | "笔记"
- `PATCH` 没有 `PUT` 知名,也怎么不常用。
+`PATCH` 没有 `PUT` 知名,也怎么不常用。
- 很多人甚至只用 `PUT` 实现部分更新。
+很多人甚至只用 `PUT` 实现部分更新。
- **FastAPI** 对此没有任何限制,可以**随意**互换使用这两种操作。
+**FastAPI** 对此没有任何限制,可以**随意**互换使用这两种操作。
- 但本指南也会分别介绍这两种操作各自的用途。
+但本指南也会分别介绍这两种操作各自的用途。
+
+///
### 使用 Pydantic 的 `exclude_unset` 参数
{!../../../docs_src/body_updates/tutorial002.py!}
```
-!!! tip "提示"
+/// tip | "提示"
+
+实际上,HTTP `PUT` 也可以完成相同的操作。
+但本节以 `PATCH` 为例的原因是,该操作就是为了这种用例创建的。
+
+///
- 实际上,HTTP `PUT` 也可以完成相同的操作。
- 但本节以 `PATCH` 为例的原因是,该操作就是为了这种用例创建的。
+/// note | "笔记"
-!!! note "笔记"
+注意,输入模型仍需验证。
- 注意,输入模型仍需验证。
+因此,如果希望接收的部分更新数据可以省略其他所有属性,则要把模型中所有的属性标记为可选(使用默认值或 `None`)。
- 因此,如果希望接收的部分更新数据可以省略其他所有属性,则要把模型中所有的属性标记为可选(使用默认值或 `None`)。
+为了区分用于**更新**所有可选值的模型与用于**创建**包含必选值的模型,请参照[更多模型](extra-models.md){.internal-link target=_blank} 一节中的思路。
- 为了区分用于**更新**所有可选值的模型与用于**创建**包含必选值的模型,请参照[更多模型](extra-models.md){.internal-link target=_blank} 一节中的思路。
+///
使用 <a href="https://docs.pydantic.dev/" class="external-link" target="_blank">Pydantic</a> 模型声明**请求体**,能充分利用它的功能和优点。
-!!! info "说明"
+/// info | "说明"
- 发送数据使用 `POST`(最常用)、`PUT`、`DELETE`、`PATCH` 等操作。
+发送数据使用 `POST`(最常用)、`PUT`、`DELETE`、`PATCH` 等操作。
- 规范中没有定义使用 `GET` 发送请求体的操作,但不管怎样,FastAPI 也支持这种方式,只不过仅用于非常复杂或极端的用例。
+规范中没有定义使用 `GET` 发送请求体的操作,但不管怎样,FastAPI 也支持这种方式,只不过仅用于非常复杂或极端的用例。
- 我们不建议使用 `GET`,因此,在 Swagger UI 交互文档中不会显示有关 `GET` 的内容,而且代理协议也不一定支持 `GET`。
+我们不建议使用 `GET`,因此,在 Swagger UI 交互文档中不会显示有关 `GET` 的内容,而且代理协议也不一定支持 `GET`。
+
+///
## 导入 Pydantic 的 `BaseModel`
从 `pydantic` 中导入 `BaseModel`:
-=== "Python 3.10+"
+//// tab | Python 3.10+
+
+```Python hl_lines="2"
+{!> ../../../docs_src/body/tutorial001_py310.py!}
+```
- ```Python hl_lines="2"
- {!> ../../../docs_src/body/tutorial001_py310.py!}
- ```
+////
-=== "Python 3.8+"
+//// tab | Python 3.8+
- ```Python hl_lines="4"
- {!> ../../../docs_src/body/tutorial001.py!}
- ```
+```Python hl_lines="4"
+{!> ../../../docs_src/body/tutorial001.py!}
+```
+
+////
## 创建数据模型
使用 Python 标准类型声明所有属性:
-=== "Python 3.10+"
+//// tab | Python 3.10+
+
+```Python hl_lines="5-9"
+{!> ../../../docs_src/body/tutorial001_py310.py!}
+```
+
+////
- ```Python hl_lines="5-9"
- {!> ../../../docs_src/body/tutorial001_py310.py!}
- ```
+//// tab | Python 3.8+
-=== "Python 3.8+"
+```Python hl_lines="7-11"
+{!> ../../../docs_src/body/tutorial001.py!}
+```
- ```Python hl_lines="7-11"
- {!> ../../../docs_src/body/tutorial001.py!}
- ```
+////
与声明查询参数一样,包含默认值的模型属性是可选的,否则就是必选的。默认值为 `None` 的模型属性也是可选的。
使用与声明路径和查询参数相同的方式声明请求体,把请求体添加至*路径操作*:
-=== "Python 3.10+"
+//// tab | Python 3.10+
- ```Python hl_lines="16"
- {!> ../../../docs_src/body/tutorial001_py310.py!}
- ```
+```Python hl_lines="16"
+{!> ../../../docs_src/body/tutorial001_py310.py!}
+```
-=== "Python 3.8+"
+////
- ```Python hl_lines="18"
- {!> ../../../docs_src/body/tutorial001.py!}
- ```
+//// tab | Python 3.8+
+
+```Python hl_lines="18"
+{!> ../../../docs_src/body/tutorial001.py!}
+```
+
+////
……此处,请求体参数的类型为 `Item` 模型。
<img src="/img/tutorial/body/image05.png">
-!!! tip "提示"
+/// tip | "提示"
+
+使用 <a href="https://www.jetbrains.com/pycharm/" class="external-link" target="_blank">PyCharm</a> 编辑器时,推荐安装 <a href="https://github.com/koxudaxi/pydantic-pycharm-plugin/" class="external-link" target="_blank">Pydantic PyCharm 插件</a>。
- 使用 <a href="https://www.jetbrains.com/pycharm/" class="external-link" target="_blank">PyCharm</a> 编辑器时,推荐安装 <a href="https://github.com/koxudaxi/pydantic-pycharm-plugin/" class="external-link" target="_blank">Pydantic PyCharm 插件</a>。
+该插件用于完善 PyCharm 对 Pydantic 模型的支持,优化的功能如下:
- 该插件用于完善 PyCharm 对 Pydantic 模型的支持,优化的功能如下:
+* 自动补全
+* 类型检查
+* 代码重构
+* 查找
+* 代码审查
- * 自动补全
- * 类型检查
- * 代码重构
- * 查找
- * 代码审查
+///
## 使用模型
在*路径操作*函数内部直接访问模型对象的属性:
-=== "Python 3.10+"
+//// tab | Python 3.10+
- ```Python hl_lines="19"
- {!> ../../../docs_src/body/tutorial002_py310.py!}
- ```
+```Python hl_lines="19"
+{!> ../../../docs_src/body/tutorial002_py310.py!}
+```
+
+////
-=== "Python 3.8+"
+//// tab | Python 3.8+
+
+```Python hl_lines="21"
+{!> ../../../docs_src/body/tutorial002.py!}
+```
- ```Python hl_lines="21"
- {!> ../../../docs_src/body/tutorial002.py!}
- ```
+////
## 请求体 + 路径参数
**FastAPI** 能识别与**路径参数**匹配的函数参数,还能识别从**请求体**中获取的类型为 Pydantic 模型的函数参数。
-=== "Python 3.10+"
+//// tab | Python 3.10+
- ```Python hl_lines="15-16"
- {!> ../../../docs_src/body/tutorial003_py310.py!}
- ```
+```Python hl_lines="15-16"
+{!> ../../../docs_src/body/tutorial003_py310.py!}
+```
+
+////
-=== "Python 3.8+"
+//// tab | Python 3.8+
- ```Python hl_lines="17-18"
- {!> ../../../docs_src/body/tutorial003.py!}
- ```
+```Python hl_lines="17-18"
+{!> ../../../docs_src/body/tutorial003.py!}
+```
+
+////
## 请求体 + 路径参数 + 查询参数
**FastAPI** 能够正确识别这三种参数,并从正确的位置获取数据。
-=== "Python 3.10+"
+//// tab | Python 3.10+
+
+```Python hl_lines="16"
+{!> ../../../docs_src/body/tutorial004_py310.py!}
+```
+
+////
- ```Python hl_lines="16"
- {!> ../../../docs_src/body/tutorial004_py310.py!}
- ```
+//// tab | Python 3.8+
-=== "Python 3.8+"
+```Python hl_lines="18"
+{!> ../../../docs_src/body/tutorial004.py!}
+```
- ```Python hl_lines="18"
- {!> ../../../docs_src/body/tutorial004.py!}
- ```
+////
函数参数按如下规则进行识别:
- 类型是(`int`、`float`、`str`、`bool` 等)**单类型**的参数,是**查询**参数
- 类型是 **Pydantic 模型**的参数,是**请求体**
-!!! note "笔记"
+/// note | "笔记"
+
+因为默认值是 `None`, FastAPI 会把 `q` 当作可选参数。
- 因为默认值是 `None`, FastAPI 会把 `q` 当作可选参数。
+FastAPI 不使用 `Optional[str]` 中的 `Optional`, 但 `Optional` 可以让编辑器提供更好的支持,并检测错误。
- FastAPI 不使用 `Optional[str]` 中的 `Optional`, 但 `Optional` 可以让编辑器提供更好的支持,并检测错误。
+///
## 不使用 Pydantic
首先,导入 `Cookie`:
-=== "Python 3.10+"
+//// tab | Python 3.10+
- ```Python hl_lines="3"
- {!> ../../../docs_src/cookie_params/tutorial001_an_py310.py!}
- ```
+```Python hl_lines="3"
+{!> ../../../docs_src/cookie_params/tutorial001_an_py310.py!}
+```
-=== "Python 3.9+"
+////
- ```Python hl_lines="3"
- {!> ../../../docs_src/cookie_params/tutorial001_an_py39.py!}
- ```
+//// tab | Python 3.9+
-=== "Python 3.8+"
+```Python hl_lines="3"
+{!> ../../../docs_src/cookie_params/tutorial001_an_py39.py!}
+```
- ```Python hl_lines="3"
- {!> ../../../docs_src/cookie_params/tutorial001_an.py!}
- ```
+////
-=== "Python 3.10+ non-Annotated"
+//// tab | Python 3.8+
- !!! tip
- 尽可能选择使用 `Annotated` 的版本。
+```Python hl_lines="3"
+{!> ../../../docs_src/cookie_params/tutorial001_an.py!}
+```
- ```Python hl_lines="1"
- {!> ../../../docs_src/cookie_params/tutorial001_py310.py!}
- ```
+////
-=== "Python 3.8+ non-Annotated"
+//// tab | Python 3.10+ non-Annotated
- !!! tip
- 尽可能选择使用 `Annotated` 的版本。
+/// tip
- ```Python hl_lines="3"
- {!> ../../../docs_src/cookie_params/tutorial001.py!}
- ```
+尽可能选择使用 `Annotated` 的版本。
+
+///
+
+```Python hl_lines="1"
+{!> ../../../docs_src/cookie_params/tutorial001_py310.py!}
+```
+
+////
+
+//// tab | Python 3.8+ non-Annotated
+
+/// tip
+
+尽可能选择使用 `Annotated` 的版本。
+
+///
+
+```Python hl_lines="3"
+{!> ../../../docs_src/cookie_params/tutorial001.py!}
+```
+
+////
## 声明 `Cookie` 参数
第一个值是默认值,还可以传递所有验证参数或注释参数:
-=== "Python 3.10+"
+//// tab | Python 3.10+
+
+```Python hl_lines="9"
+{!> ../../../docs_src/cookie_params/tutorial001_an_py310.py!}
+```
+
+////
+
+//// tab | Python 3.9+
+
+```Python hl_lines="9"
+{!> ../../../docs_src/cookie_params/tutorial001_an_py39.py!}
+```
+
+////
+
+//// tab | Python 3.8+
+
+```Python hl_lines="10"
+{!> ../../../docs_src/cookie_params/tutorial001_an.py!}
+```
+
+////
+
+//// tab | Python 3.10+ non-Annotated
+
+/// tip
+
+尽可能选择使用 `Annotated` 的版本。
- ```Python hl_lines="9"
- {!> ../../../docs_src/cookie_params/tutorial001_an_py310.py!}
- ```
+///
-=== "Python 3.9+"
+```Python hl_lines="7"
+{!> ../../../docs_src/cookie_params/tutorial001_py310.py!}
+```
- ```Python hl_lines="9"
- {!> ../../../docs_src/cookie_params/tutorial001_an_py39.py!}
- ```
+////
-=== "Python 3.8+"
+//// tab | Python 3.8+ non-Annotated
- ```Python hl_lines="10"
- {!> ../../../docs_src/cookie_params/tutorial001_an.py!}
- ```
+/// tip
-=== "Python 3.10+ non-Annotated"
+尽可能选择使用 `Annotated` 的版本。
- !!! tip
- 尽可能选择使用 `Annotated` 的版本。
+///
- ```Python hl_lines="7"
- {!> ../../../docs_src/cookie_params/tutorial001_py310.py!}
- ```
+```Python hl_lines="9"
+{!> ../../../docs_src/cookie_params/tutorial001.py!}
+```
-=== "Python 3.8+ non-Annotated"
+////
- !!! tip
- 尽可能选择使用 `Annotated` 的版本。
+/// note | "技术细节"
- ```Python hl_lines="9"
- {!> ../../../docs_src/cookie_params/tutorial001.py!}
- ```
+`Cookie` 、`Path` 、`Query` 是**兄弟类**,都继承自共用的 `Param` 类。
-!!! note "技术细节"
+注意,从 `fastapi` 导入的 `Query`、`Path`、`Cookie` 等对象,实际上是返回特殊类的函数。
- `Cookie` 、`Path` 、`Query` 是**兄弟类**,都继承自共用的 `Param` 类。
+///
- 注意,从 `fastapi` 导入的 `Query`、`Path`、`Cookie` 等对象,实际上是返回特殊类的函数。
+/// info | "说明"
-!!! info "说明"
+必须使用 `Cookie` 声明 cookie 参数,否则该参数会被解释为查询参数。
- 必须使用 `Cookie` 声明 cookie 参数,否则该参数会被解释为查询参数。
+///
## 小结
更多关于 <abbr title="Cross-Origin Resource Sharing">CORS</abbr> 的信息,请查看 <a href="https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS" class="external-link" target="_blank">Mozilla CORS 文档</a>。
-!!! note "技术细节"
- 你也可以使用 `from starlette.middleware.cors import CORSMiddleware`。
+/// note | "技术细节"
- 出于方便,**FastAPI** 在 `fastapi.middleware` 中为开发者提供了几个中间件。但是大多数可用的中间件都是直接来自 Starlette。
+你也可以使用 `from starlette.middleware.cors import CORSMiddleware`。
+
+出于方便,**FastAPI** 在 `fastapi.middleware` 中为开发者提供了几个中间件。但是大多数可用的中间件都是直接来自 Starlette。
+
+///
uvicorn.run(app, host="0.0.0.0", port=8000)
```
-!!! info
- 更多信息请检查 <a href="https://docs.python.org/3/library/__main__.html" class="external-link" target="_blank">Python 官方文档</a>.
+/// info
+
+更多信息请检查 <a href="https://docs.python.org/3/library/__main__.html" class="external-link" target="_blank">Python 官方文档</a>.
+
+///
## 使用你的调试器运行代码
在前面的例子中, 我们从依赖项 ("可依赖对象") 中返回了一个 `dict`:
-=== "Python 3.10+"
+//// tab | Python 3.10+
- ```Python hl_lines="7"
- {!> ../../../docs_src/dependencies/tutorial001_py310.py!}
- ```
+```Python hl_lines="7"
+{!> ../../../docs_src/dependencies/tutorial001_py310.py!}
+```
+
+////
-=== "Python 3.8+"
+//// tab | Python 3.8+
+
+```Python hl_lines="9"
+{!> ../../../docs_src/dependencies/tutorial001.py!}
+```
- ```Python hl_lines="9"
- {!> ../../../docs_src/dependencies/tutorial001.py!}
- ```
+////
但是后面我们在路径操作函数的参数 `commons` 中得到了一个 `dict`。
所以,我们可以将上面的依赖项 "可依赖对象" `common_parameters` 更改为类 `CommonQueryParams`:
-=== "Python 3.10+"
+//// tab | Python 3.10+
- ```Python hl_lines="9-13"
- {!> ../../../docs_src/dependencies/tutorial002_py310.py!}
- ```
+```Python hl_lines="9-13"
+{!> ../../../docs_src/dependencies/tutorial002_py310.py!}
+```
+
+////
-=== "Python 3.8+"
+//// tab | Python 3.8+
+
+```Python hl_lines="11-15"
+{!> ../../../docs_src/dependencies/tutorial002.py!}
+```
- ```Python hl_lines="11-15"
- {!> ../../../docs_src/dependencies/tutorial002.py!}
- ```
+////
注意用于创建类实例的 `__init__` 方法:
-=== "Python 3.10+"
+//// tab | Python 3.10+
- ```Python hl_lines="10"
- {!> ../../../docs_src/dependencies/tutorial002_py310.py!}
- ```
+```Python hl_lines="10"
+{!> ../../../docs_src/dependencies/tutorial002_py310.py!}
+```
+
+////
-=== "Python 3.6+"
+//// tab | Python 3.6+
+
+```Python hl_lines="12"
+{!> ../../../docs_src/dependencies/tutorial002.py!}
+```
- ```Python hl_lines="12"
- {!> ../../../docs_src/dependencies/tutorial002.py!}
- ```
+////
...它与我们以前的 `common_parameters` 具有相同的参数:
-=== "Python 3.10+"
+//// tab | Python 3.10+
+
+```Python hl_lines="6"
+{!> ../../../docs_src/dependencies/tutorial001_py310.py!}
+```
+
+////
- ```Python hl_lines="6"
- {!> ../../../docs_src/dependencies/tutorial001_py310.py!}
- ```
+//// tab | Python 3.6+
-=== "Python 3.6+"
+```Python hl_lines="9"
+{!> ../../../docs_src/dependencies/tutorial001.py!}
+```
- ```Python hl_lines="9"
- {!> ../../../docs_src/dependencies/tutorial001.py!}
- ```
+////
这些参数就是 **FastAPI** 用来 "处理" 依赖项的。
现在,您可以使用这个类来声明你的依赖项了。
-=== "Python 3.10+"
+//// tab | Python 3.10+
+
+```Python hl_lines="17"
+{!> ../../../docs_src/dependencies/tutorial002_py310.py!}
+```
+
+////
- ```Python hl_lines="17"
- {!> ../../../docs_src/dependencies/tutorial002_py310.py!}
- ```
+//// tab | Python 3.6+
-=== "Python 3.6+"
+```Python hl_lines="19"
+{!> ../../../docs_src/dependencies/tutorial002.py!}
+```
- ```Python hl_lines="19"
- {!> ../../../docs_src/dependencies/tutorial002.py!}
- ```
+////
**FastAPI** 调用 `CommonQueryParams` 类。这将创建该类的一个 "实例",该实例将作为参数 `commons` 被传递给你的函数。
..就像:
-=== "Python 3.10+"
+//// tab | Python 3.10+
+
+```Python hl_lines="17"
+{!> ../../../docs_src/dependencies/tutorial003_py310.py!}
+```
- ```Python hl_lines="17"
- {!> ../../../docs_src/dependencies/tutorial003_py310.py!}
- ```
+////
-=== "Python 3.6+"
+//// tab | Python 3.6+
- ```Python hl_lines="19"
- {!> ../../../docs_src/dependencies/tutorial003.py!}
- ```
+```Python hl_lines="19"
+{!> ../../../docs_src/dependencies/tutorial003.py!}
+```
+
+////
但是声明类型是被鼓励的,因为那样你的编辑器就会知道将传递什么作为参数 `commons` ,然后它可以帮助你完成代码,类型检查,等等:
同样的例子看起来像这样:
-=== "Python 3.10+"
+//// tab | Python 3.10+
+
+```Python hl_lines="17"
+{!> ../../../docs_src/dependencies/tutorial004_py310.py!}
+```
- ```Python hl_lines="17"
- {!> ../../../docs_src/dependencies/tutorial004_py310.py!}
- ```
+////
-=== "Python 3.6+"
+//// tab | Python 3.6+
- ```Python hl_lines="19"
- {!> ../../../docs_src/dependencies/tutorial004.py!}
- ```
+```Python hl_lines="19"
+{!> ../../../docs_src/dependencies/tutorial004.py!}
+```
+
+////
... **FastAPI** 会知道怎么处理。
-!!! tip
- 如果这看起来更加混乱而不是更加有帮助,那么请忽略它,你不*需要*它。
+/// tip
+
+如果这看起来更加混乱而不是更加有帮助,那么请忽略它,你不*需要*它。
+
+这只是一个快捷方式。因为 **FastAPI** 关心的是帮助您减少代码重复。
- 这只是一个快捷方式。因为 **FastAPI** 关心的是帮助您减少代码重复。
+///
路径操作装饰器依赖项(以下简称为**“路径装饰器依赖项”**)的执行或解析方式和普通依赖项一样,但就算这些依赖项会返回值,它们的值也不会传递给*路径操作函数*。
-!!! tip "提示"
+/// tip | "提示"
- 有些编辑器会检查代码中没使用过的函数参数,并显示错误提示。
+有些编辑器会检查代码中没使用过的函数参数,并显示错误提示。
- 在*路径操作装饰器*中使用 `dependencies` 参数,可以确保在执行依赖项的同时,避免编辑器显示错误提示。
+在*路径操作装饰器*中使用 `dependencies` 参数,可以确保在执行依赖项的同时,避免编辑器显示错误提示。
- 使用路径装饰器依赖项还可以避免开发新人误会代码中包含无用的未使用参数。
+使用路径装饰器依赖项还可以避免开发新人误会代码中包含无用的未使用参数。
-!!! info "说明"
+///
- 本例中,使用的是自定义响应头 `X-Key` 和 `X-Token`。
+/// info | "说明"
- 但实际开发中,尤其是在实现安全措施时,最好使用 FastAPI 内置的[安全工具](../security/index.md){.internal-link target=_blank}(详见下一章)。
+本例中,使用的是自定义响应头 `X-Key` 和 `X-Token`。
+
+但实际开发中,尤其是在实现安全措施时,最好使用 FastAPI 内置的[安全工具](../security/index.md){.internal-link target=_blank}(详见下一章)。
+
+///
## 依赖项错误和返回值
为此,请使用 `yield` 而不是 `return`,然后再编写额外的步骤(代码)。
-!!! tip "提示"
- 确保只使用一次 `yield` 。
+/// tip | "提示"
-!!! note "技术细节"
+确保只使用一次 `yield` 。
- 任何一个可以与以下内容一起使用的函数:
+///
- * <a href="https://docs.python.org/3/library/contextlib.html#contextlib.contextmanager" class="external-link" target="_blank">`@contextlib.contextmanager`</a> 或者
- * <a href="https://docs.python.org/3/library/contextlib.html#contextlib.asynccontextmanager" class="external-link" target="_blank">`@contextlib.asynccontextmanager`</a>
+/// note | "技术细节"
- 都可以作为 **FastAPI** 的依赖项。
+任何一个可以与以下内容一起使用的函数:
- 实际上,FastAPI内部就使用了这两个装饰器。
+* <a href="https://docs.python.org/3/library/contextlib.html#contextlib.contextmanager" class="external-link" target="_blank">`@contextlib.contextmanager`</a> 或者
+* <a href="https://docs.python.org/3/library/contextlib.html#contextlib.asynccontextmanager" class="external-link" target="_blank">`@contextlib.asynccontextmanager`</a>
+都可以作为 **FastAPI** 的依赖项。
+
+实际上,FastAPI内部就使用了这两个装饰器。
+
+///
## 使用 `yield` 的数据库依赖项
{!../../../docs_src/dependencies/tutorial007.py!}
```
-!!! tip "提示"
+/// tip | "提示"
- 您可以使用 `async` 或普通函数。
+您可以使用 `async` 或普通函数。
- **FastAPI** 会像处理普通依赖关系一样,对每个依赖关系做正确的处理。
+**FastAPI** 会像处理普通依赖关系一样,对每个依赖关系做正确的处理。
+
+///
## 同时包含了 `yield` 和 `try` 的依赖项
例如,`dependency_c` 可以依赖于 `dependency_b`,而 `dependency_b` 则依赖于 `dependency_a`。
-=== "Python 3.9+"
+//// tab | Python 3.9+
+
+```Python hl_lines="6 14 22"
+{!> ../../../docs_src/dependencies/tutorial008_an_py39.py!}
+```
+
+////
+
+//// tab | Python 3.8+
- ```Python hl_lines="6 14 22"
- {!> ../../../docs_src/dependencies/tutorial008_an_py39.py!}
- ```
+```Python hl_lines="5 13 21"
+{!> ../../../docs_src/dependencies/tutorial008_an.py!}
+```
+
+////
-=== "Python 3.8+"
+//// tab | Python 3.8+ non-Annotated
- ```Python hl_lines="5 13 21"
- {!> ../../../docs_src/dependencies/tutorial008_an.py!}
- ```
+/// tip
-=== "Python 3.8+ non-Annotated"
+如果可能,请尽量使用“ Annotated”版本。
- !!! tip
- 如果可能,请尽量使用“ Annotated”版本。
+///
+
+```Python hl_lines="4 12 20"
+{!> ../../../docs_src/dependencies/tutorial008.py!}
+```
- ```Python hl_lines="4 12 20"
- {!> ../../../docs_src/dependencies/tutorial008.py!}
- ```
+////
所有这些依赖都可以使用`yield`。
而`dependency_b` 反过来则需要`dependency_a`(此处称为 `dep_a`)的值在其退出代码中可用。
-=== "Python 3.9+"
+//// tab | Python 3.9+
+
+```Python hl_lines="18-19 26-27"
+{!> ../../../docs_src/dependencies/tutorial008_an_py39.py!}
+```
+
+////
- ```Python hl_lines="18-19 26-27"
- {!> ../../../docs_src/dependencies/tutorial008_an_py39.py!}
- ```
+//// tab | Python 3.8+
-=== "Python 3.8+"
+```Python hl_lines="17-18 25-26"
+{!> ../../../docs_src/dependencies/tutorial008_an.py!}
+```
+
+////
- ```Python hl_lines="17-18 25-26"
- {!> ../../../docs_src/dependencies/tutorial008_an.py!}
- ```
+//// tab | Python 3.8+ non-Annotated
-=== "Python 3.8+ non-Annotated"
+/// tip
- !!! tip
- 如果可能,请尽量使用“ Annotated”版本。
+如果可能,请尽量使用“ Annotated”版本。
- ```Python hl_lines="16-17 24-25"
- {!> ../../../docs_src/dependencies/tutorial008.py!}
- ```
+///
+
+```Python hl_lines="16-17 24-25"
+{!> ../../../docs_src/dependencies/tutorial008.py!}
+```
+
+////
同样,你可以有混合了`yield`和`return`的依赖。
**FastAPI** 将确保按正确的顺序运行所有内容。
-!!! note "技术细节"
+/// note | "技术细节"
- 这是由 Python 的<a href="https://docs.python.org/3/library/contextlib.html" class="external-link" target="_blank">上下文管理器</a>完成的。
+这是由 Python 的<a href="https://docs.python.org/3/library/contextlib.html" class="external-link" target="_blank">上下文管理器</a>完成的。
- **FastAPI** 在内部使用它们来实现这一点。
+**FastAPI** 在内部使用它们来实现这一点。
+///
## 使用 `yield` 和 `HTTPException` 的依赖项
如果你有自定义异常,希望在返回响应之前处理,并且可能修改响应甚至触发`HTTPException`,可以创建[自定义异常处理程序](../handling-errors.md#install-custom-exception-handlers){.internal-link target=_blank}。
-!!! tip
+/// tip
+
+在`yield`之前仍然可以引发包括`HTTPException`在内的异常,但在`yield`之后则不行。
- 在`yield`之前仍然可以引发包括`HTTPException`在内的异常,但在`yield`之后则不行。
+///
执行的顺序大致如下图所示。时间从上到下流动。每列都是相互交互或执行代码的其中一部分。
end
```
-!!! info
- 只会向客户端发送**一次响应**,可能是一个错误响应之一,也可能是来自*路径操作*的响应。
+/// info
+
+只会向客户端发送**一次响应**,可能是一个错误响应之一,也可能是来自*路径操作*的响应。
- 在发送了其中一个响应之后,就无法再发送其他响应了。
+在发送了其中一个响应之后,就无法再发送其他响应了。
-!!! tip
- 这个图表展示了`HTTPException`,但你也可以引发任何其他你创建了[自定义异常处理程序](../handling-errors.md#install-custom-exception-handlers){.internal-link target=_blank}的异常。
+///
- 如果你引发任何异常,它将传递给带有`yield`的依赖,包括`HTTPException`,然后**再次**传递给异常处理程序。如果没有针对该异常的异常处理程序,那么它将被默认的内部`ServerErrorMiddleware`处理,返回500 HTTP状态码,告知客户端服务器发生了错误。
+/// tip
+
+这个图表展示了`HTTPException`,但你也可以引发任何其他你创建了[自定义异常处理程序](../handling-errors.md#install-custom-exception-handlers){.internal-link target=_blank}的异常。
+
+如果你引发任何异常,它将传递给带有`yield`的依赖,包括`HTTPException`,然后**再次**传递给异常处理程序。如果没有针对该异常的异常处理程序,那么它将被默认的内部`ServerErrorMiddleware`处理,返回500 HTTP状态码,告知客户端服务器发生了错误。
+
+///
## 上下文管理器
### 在依赖项中使用带有`yield`的上下文管理器
-!!! warning
- 这是一个更为“高级”的想法。
+/// warning
+
+这是一个更为“高级”的想法。
- 如果您刚开始使用**FastAPI**,您可能暂时可以跳过它。
+如果您刚开始使用**FastAPI**,您可能暂时可以跳过它。
+
+///
在Python中,你可以通过<a href="https://docs.python.org/3/reference/datamodel.html#context-managers" class="external-link" target="_blank">创建一个带有`__enter__()`和`__exit__()`方法的类</a>来创建上下文管理器。
{!../../../docs_src/dependencies/tutorial010.py!}
```
-!!! tip
- 另一种创建上下文管理器的方法是:
+/// tip
+
+另一种创建上下文管理器的方法是:
+
+* <a href="https://docs.python.org/zh-cn/3/library/contextlib.html#contextlib.contextmanager" class="external-link" target="_blank">`@contextlib.contextmanager`</a>或者
+* <a href="https://docs.python.org/zh-cn/3/library/contextlib.html#contextlib.asynccontextmanager" class="external-link" target="_blank">`@contextlib.asynccontextmanager`</a>
- * <a href="https://docs.python.org/zh-cn/3/library/contextlib.html#contextlib.contextmanager" class="external-link" target="_blank">`@contextlib.contextmanager`</a>或者
- * <a href="https://docs.python.org/zh-cn/3/library/contextlib.html#contextlib.asynccontextmanager" class="external-link" target="_blank">`@contextlib.asynccontextmanager`</a>
+使用上下文管理器装饰一个只有单个`yield`的函数。这就是**FastAPI**在内部用于带有`yield`的依赖项的方式。
- 使用上下文管理器装饰一个只有单个`yield`的函数。这就是**FastAPI**在内部用于带有`yield`的依赖项的方式。
+但是你不需要为FastAPI的依赖项使用这些装饰器(而且也不应该)。FastAPI会在内部为你处理这些。
- 但是你不需要为FastAPI的依赖项使用这些装饰器(而且也不应该)。FastAPI会在内部为你处理这些。
+///
该函数接收的参数和*路径操作函数*的参数一样。
-!!! tip "提示"
+/// tip | "提示"
- 下一章介绍,除了函数还有哪些「对象」可以用作依赖项。
+下一章介绍,除了函数还有哪些「对象」可以用作依赖项。
+
+///
接收到新的请求时,**FastAPI** 执行如下操作:
这样,只编写一次代码,**FastAPI** 就可以为多个*路径操作*共享这段代码 。
-!!! check "检查"
+/// check | "检查"
+
+注意,无需创建专门的类,并将之传递给 **FastAPI** 以进行「注册」或执行类似的操作。
- 注意,无需创建专门的类,并将之传递给 **FastAPI** 以进行「注册」或执行类似的操作。
+只要把它传递给 `Depends`,**FastAPI** 就知道该如何执行后续操作。
- 只要把它传递给 `Depends`,**FastAPI** 就知道该如何执行后续操作。
+///
## 要不要使用 `async`?
上述这些操作都是可行的,**FastAPI** 知道该怎么处理。
-!!! note "笔记"
+/// note | "笔记"
+
+如里不了解异步,请参阅[异步:*“着急了?”*](../../async.md){.internal-link target=_blank} 一章中 `async` 和 `await` 的内容。
- 如里不了解异步,请参阅[异步:*“着急了?”*](../../async.md){.internal-link target=_blank} 一章中 `async` 和 `await` 的内容。
+///
## 与 OpenAPI 集成
{!../../../docs_src/dependencies/tutorial005.py!}
```
-!!! info "信息"
+/// info | "信息"
- 注意,这里在*路径操作函数*中只声明了一个依赖项,即 `query_or_cookie_extractor` 。
+注意,这里在*路径操作函数*中只声明了一个依赖项,即 `query_or_cookie_extractor` 。
- 但 **FastAPI** 必须先处理 `query_extractor`,以便在调用 `query_or_cookie_extractor` 时使用 `query_extractor` 返回的结果。
+但 **FastAPI** 必须先处理 `query_extractor`,以便在调用 `query_or_cookie_extractor` 时使用 `query_extractor` 返回的结果。
+
+///
```mermaid
graph TB
但它依然非常强大,能够声明任意嵌套深度的「图」或树状的依赖结构。
-!!! tip "提示"
+/// tip | "提示"
+
+这些简单的例子现在看上去虽然没有什么实用价值,
- 这些简单的例子现在看上去虽然没有什么实用价值,
+但在**安全**一章中,您会了解到这些例子的用途,
- 但在**安全**一章中,您会了解到这些例子的用途,
+以及这些例子所能节省的代码量。
- 以及这些例子所能节省的代码量。
+///
它接收一个对象,比如Pydantic模型,并会返回一个JSON兼容的版本:
-=== "Python 3.10+"
+//// tab | Python 3.10+
- ```Python hl_lines="4 21"
- {!> ../../../docs_src/encoder/tutorial001_py310.py!}
- ```
+```Python hl_lines="4 21"
+{!> ../../../docs_src/encoder/tutorial001_py310.py!}
+```
-=== "Python 3.8+"
+////
- ```Python hl_lines="5 22"
- {!> ../../../docs_src/encoder/tutorial001.py!}
- ```
+//// tab | Python 3.8+
+
+```Python hl_lines="5 22"
+{!> ../../../docs_src/encoder/tutorial001.py!}
+```
+
+////
在这个例子中,它将Pydantic模型转换为`dict`,并将`datetime`转换为`str`。
这个操作不会返回一个包含JSON格式(作为字符串)数据的庞大的`str`。它将返回一个Python标准数据结构(例如`dict`),其值和子值都与JSON兼容。
-!!! note
- `jsonable_encoder`实际上是FastAPI内部用来转换数据的。但是它在许多其他场景中也很有用。
+/// note
+
+`jsonable_encoder`实际上是FastAPI内部用来转换数据的。但是它在许多其他场景中也很有用。
+
+///
下面是一个*路径操作*的示例,其中的参数使用了上面的一些类型。
-=== "Python 3.10+"
+//// tab | Python 3.10+
- ```Python hl_lines="1 3 12-16"
- {!> ../../../docs_src/extra_data_types/tutorial001_an_py310.py!}
- ```
+```Python hl_lines="1 3 12-16"
+{!> ../../../docs_src/extra_data_types/tutorial001_an_py310.py!}
+```
-=== "Python 3.9+"
+////
- ```Python hl_lines="1 3 12-16"
- {!> ../../../docs_src/extra_data_types/tutorial001_an_py39.py!}
- ```
+//// tab | Python 3.9+
-=== "Python 3.8+"
+```Python hl_lines="1 3 12-16"
+{!> ../../../docs_src/extra_data_types/tutorial001_an_py39.py!}
+```
- ```Python hl_lines="1 3 13-17"
- {!> ../../../docs_src/extra_data_types/tutorial001_an.py!}
- ```
+////
-=== "Python 3.10+ non-Annotated"
+//// tab | Python 3.8+
- !!! tip
- 尽可能选择使用 `Annotated` 的版本。
+```Python hl_lines="1 3 13-17"
+{!> ../../../docs_src/extra_data_types/tutorial001_an.py!}
+```
- ```Python hl_lines="1 2 11-15"
- {!> ../../../docs_src/extra_data_types/tutorial001_py310.py!}
- ```
+////
-=== "Python 3.8+ non-Annotated"
+//// tab | Python 3.10+ non-Annotated
- !!! tip
- 尽可能选择使用 `Annotated` 的版本。
+/// tip
- ```Python hl_lines="1 2 12-16"
- {!> ../../../docs_src/extra_data_types/tutorial001.py!}
- ```
+尽可能选择使用 `Annotated` 的版本。
+
+///
+
+```Python hl_lines="1 2 11-15"
+{!> ../../../docs_src/extra_data_types/tutorial001_py310.py!}
+```
+
+////
+
+//// tab | Python 3.8+ non-Annotated
+
+/// tip
+
+尽可能选择使用 `Annotated` 的版本。
+
+///
+
+```Python hl_lines="1 2 12-16"
+{!> ../../../docs_src/extra_data_types/tutorial001.py!}
+```
+
+////
注意,函数内的参数有原生的数据类型,你可以,例如,执行正常的日期操作,如:
-=== "Python 3.10+"
+//// tab | Python 3.10+
+
+```Python hl_lines="18-19"
+{!> ../../../docs_src/extra_data_types/tutorial001_an_py310.py!}
+```
+
+////
+
+//// tab | Python 3.9+
+
+```Python hl_lines="18-19"
+{!> ../../../docs_src/extra_data_types/tutorial001_an_py39.py!}
+```
+
+////
+
+//// tab | Python 3.8+
+
+```Python hl_lines="19-20"
+{!> ../../../docs_src/extra_data_types/tutorial001_an.py!}
+```
+
+////
+
+//// tab | Python 3.10+ non-Annotated
- ```Python hl_lines="18-19"
- {!> ../../../docs_src/extra_data_types/tutorial001_an_py310.py!}
- ```
+/// tip
-=== "Python 3.9+"
+尽可能选择使用 `Annotated` 的版本。
- ```Python hl_lines="18-19"
- {!> ../../../docs_src/extra_data_types/tutorial001_an_py39.py!}
- ```
+///
-=== "Python 3.8+"
+```Python hl_lines="17-18"
+{!> ../../../docs_src/extra_data_types/tutorial001_py310.py!}
+```
- ```Python hl_lines="19-20"
- {!> ../../../docs_src/extra_data_types/tutorial001_an.py!}
- ```
+////
-=== "Python 3.10+ non-Annotated"
+//// tab | Python 3.8+ non-Annotated
- !!! tip
- 尽可能选择使用 `Annotated` 的版本。
+/// tip
- ```Python hl_lines="17-18"
- {!> ../../../docs_src/extra_data_types/tutorial001_py310.py!}
- ```
+尽可能选择使用 `Annotated` 的版本。
-=== "Python 3.8+ non-Annotated"
+///
- !!! tip
- 尽可能选择使用 `Annotated` 的版本。
+```Python hl_lines="18-19"
+{!> ../../../docs_src/extra_data_types/tutorial001.py!}
+```
- ```Python hl_lines="18-19"
- {!> ../../../docs_src/extra_data_types/tutorial001.py!}
- ```
+////
* **输出模型**不应含密码
* **数据库模型**需要加密的密码
-!!! danger "危险"
+/// danger | "危险"
- 千万不要存储用户的明文密码。始终存储可以进行验证的**安全哈希值**。
+千万不要存储用户的明文密码。始终存储可以进行验证的**安全哈希值**。
- 如果不了解这方面的知识,请参阅[安全性中的章节](security/simple-oauth2.md#password-hashing){.internal-link target=_blank},了解什么是**密码哈希**。
+如果不了解这方面的知识,请参阅[安全性中的章节](security/simple-oauth2.md#password-hashing){.internal-link target=_blank},了解什么是**密码哈希**。
+
+///
## 多个模型
下面的代码展示了不同模型处理密码字段的方式,及使用位置的大致思路:
-=== "Python 3.10+"
+//// tab | Python 3.10+
+
+```Python hl_lines="7 9 14 20 22 27-28 31-33 38-39"
+{!> ../../../docs_src/extra_models/tutorial001_py310.py!}
+```
+
+////
- ```Python hl_lines="7 9 14 20 22 27-28 31-33 38-39"
- {!> ../../../docs_src/extra_models/tutorial001_py310.py!}
- ```
+//// tab | Python 3.8+
-=== "Python 3.8+"
+```Python hl_lines="9 11 16 22 24 29-30 33-35 40-41"
+{!> ../../../docs_src/extra_models/tutorial001.py!}
+```
- ```Python hl_lines="9 11 16 22 24 29-30 33-35 40-41"
- {!> ../../../docs_src/extra_models/tutorial001.py!}
- ```
+////
### `**user_in.dict()` 简介
)
```
-!!! warning "警告"
+/// warning | "警告"
+
+辅助的附加函数只是为了演示可能的数据流,但它们显然不能提供任何真正的安全机制。
- 辅助的附加函数只是为了演示可能的数据流,但它们显然不能提供任何真正的安全机制。
+///
## 减少重复
通过这种方式,可以只声明模型之间的区别(分别包含明文密码、哈希密码,以及无密码的模型)。
-=== "Python 3.10+"
+//// tab | Python 3.10+
- ```Python hl_lines="7 13-14 17-18 21-22"
- {!> ../../../docs_src/extra_models/tutorial002_py310.py!}
- ```
+```Python hl_lines="7 13-14 17-18 21-22"
+{!> ../../../docs_src/extra_models/tutorial002_py310.py!}
+```
+
+////
+
+//// tab | Python 3.8+
-=== "Python 3.8+"
+```Python hl_lines="9 15-16 19-20 23-24"
+{!> ../../../docs_src/extra_models/tutorial002.py!}
+```
- ```Python hl_lines="9 15-16 19-20 23-24"
- {!> ../../../docs_src/extra_models/tutorial002.py!}
- ```
+////
## `Union` 或者 `anyOf`
为此,请使用 Python 标准类型提示 <a href="https://docs.python.org/3/library/typing.html#typing.Union" class="external-link" target="_blank">`typing.Union`</a>:
-!!! note "笔记"
+/// note | "笔记"
+
+定义 <a href="https://docs.pydantic.dev/latest/concepts/types/#unions" class="external-link" target="_blank">`Union`</a> 类型时,要把详细的类型写在前面,然后是不太详细的类型。下例中,更详细的 `PlaneItem` 位于 `Union[PlaneItem,CarItem]` 中的 `CarItem` 之前。
- 定义 <a href="https://docs.pydantic.dev/latest/concepts/types/#unions" class="external-link" target="_blank">`Union`</a> 类型时,要把详细的类型写在前面,然后是不太详细的类型。下例中,更详细的 `PlaneItem` 位于 `Union[PlaneItem,CarItem]` 中的 `CarItem` 之前。
+///
-=== "Python 3.10+"
+//// tab | Python 3.10+
- ```Python hl_lines="1 14-15 18-20 33"
- {!> ../../../docs_src/extra_models/tutorial003_py310.py!}
- ```
+```Python hl_lines="1 14-15 18-20 33"
+{!> ../../../docs_src/extra_models/tutorial003_py310.py!}
+```
-=== "Python 3.8+"
+////
- ```Python hl_lines="1 14-15 18-20 33"
- {!> ../../../docs_src/extra_models/tutorial003.py!}
- ```
+//// tab | Python 3.8+
+
+```Python hl_lines="1 14-15 18-20 33"
+{!> ../../../docs_src/extra_models/tutorial003.py!}
+```
+
+////
## 模型列表
为此,请使用标准的 Python `typing.List`:
-=== "Python 3.9+"
+//// tab | Python 3.9+
- ```Python hl_lines="18"
- {!> ../../../docs_src/extra_models/tutorial004_py39.py!}
- ```
+```Python hl_lines="18"
+{!> ../../../docs_src/extra_models/tutorial004_py39.py!}
+```
+
+////
-=== "Python 3.8+"
+//// tab | Python 3.8+
- ```Python hl_lines="1 20"
- {!> ../../../docs_src/extra_models/tutorial004.py!}
- ```
+```Python hl_lines="1 20"
+{!> ../../../docs_src/extra_models/tutorial004.py!}
+```
+
+////
## 任意 `dict` 构成的响应
此时,可以使用 `typing.Dict`:
-=== "Python 3.9+"
+//// tab | Python 3.9+
+
+```Python hl_lines="6"
+{!> ../../../docs_src/extra_models/tutorial005_py39.py!}
+```
- ```Python hl_lines="6"
- {!> ../../../docs_src/extra_models/tutorial005_py39.py!}
- ```
+////
-=== "Python 3.8+"
+//// tab | Python 3.8+
+
+```Python hl_lines="1 8"
+{!> ../../../docs_src/extra_models/tutorial005.py!}
+```
- ```Python hl_lines="1 8"
- {!> ../../../docs_src/extra_models/tutorial005.py!}
- ```
+////
## 小结
</div>
-!!! note
- `uvicorn main:app` 命令含义如下:
+/// note
- * `main`:`main.py` 文件(一个 Python「模块」)。
- * `app`:在 `main.py` 文件中通过 `app = FastAPI()` 创建的对象。
- * `--reload`:让服务器在更新代码后重新启动。仅在开发时使用该选项。
+`uvicorn main:app` 命令含义如下:
+* `main`:`main.py` 文件(一个 Python「模块」)。
+* `app`:在 `main.py` 文件中通过 `app = FastAPI()` 创建的对象。
+* `--reload`:让服务器在更新代码后重新启动。仅在开发时使用该选项。
+
+///
在输出中,会有一行信息像下面这样:
`FastAPI` 是一个为你的 API 提供了所有功能的 Python 类。
-!!! note "技术细节"
- `FastAPI` 是直接从 `Starlette` 继承的类。
+/// note | "技术细节"
+
+`FastAPI` 是直接从 `Starlette` 继承的类。
+
+你可以通过 `FastAPI` 使用所有的 Starlette 的功能。
- 你可以通过 `FastAPI` 使用所有的 Starlette 的功能。
+///
### 步骤 2:创建一个 `FastAPI`「实例」
/items/foo
```
-!!! info
- 「路径」也通常被称为「端点」或「路由」。
+/// info
+
+「路径」也通常被称为「端点」或「路由」。
+
+///
开发 API 时,「路径」是用来分离「关注点」和「资源」的主要手段。
* 请求路径为 `/`
* 使用 <abbr title="HTTP GET 方法"><code>get</code> 操作</abbr>
-!!! info "`@decorator` Info"
- `@something` 语法在 Python 中被称为「装饰器」。
+/// info | "`@decorator` Info"
+
+`@something` 语法在 Python 中被称为「装饰器」。
- 像一顶漂亮的装饰帽一样,将它放在一个函数的上方(我猜测这个术语的命名就是这么来的)。
+像一顶漂亮的装饰帽一样,将它放在一个函数的上方(我猜测这个术语的命名就是这么来的)。
- 装饰器接收位于其下方的函数并且用它完成一些工作。
+装饰器接收位于其下方的函数并且用它完成一些工作。
- 在我们的例子中,这个装饰器告诉 **FastAPI** 位于其下方的函数对应着**路径** `/` 加上 `get` **操作**。
+在我们的例子中,这个装饰器告诉 **FastAPI** 位于其下方的函数对应着**路径** `/` 加上 `get` **操作**。
- 它是一个「**路径操作装饰器**」。
+它是一个「**路径操作装饰器**」。
+
+///
你也可以使用其他的操作:
* `@app.patch()`
* `@app.trace()`
-!!! tip
- 您可以随意使用任何一个操作(HTTP方法)。
+/// tip
+
+您可以随意使用任何一个操作(HTTP方法)。
+
+**FastAPI** 没有强制要求操作有任何特定的含义。
- **FastAPI** 没有强制要求操作有任何特定的含义。
+此处提供的信息仅作为指导,而不是要求。
- 此处提供的信息仅作为指导,而不是要求。
+比如,当使用 GraphQL 时通常你所有的动作都通过 `post` 一种方法执行。
- 比如,当使用 GraphQL 时通常你所有的动作都通过 `post` 一种方法执行。
+///
### 步骤 4:定义**路径操作函数**
{!../../../docs_src/first_steps/tutorial003.py!}
```
-!!! note
- 如果你不知道两者的区别,请查阅 [Async: *"In a hurry?"*](https://fastapi.tiangolo.com/async/#in-a-hurry){.internal-link target=_blank}。
+/// note
+
+如果你不知道两者的区别,请查阅 [Async: *"In a hurry?"*](https://fastapi.tiangolo.com/async/#in-a-hurry){.internal-link target=_blank}。
+
+///
### 步骤 5:返回内容
```
-!!! tip "提示"
+/// tip | "提示"
- 触发 `HTTPException` 时,可以用参数 `detail` 传递任何能转换为 JSON 的值,不仅限于 `str`。
+触发 `HTTPException` 时,可以用参数 `detail` 传递任何能转换为 JSON 的值,不仅限于 `str`。
- 还支持传递 `dict`、`list` 等数据结构。
+还支持传递 `dict`、`list` 等数据结构。
- **FastAPI** 能自动处理这些数据,并将之转换为 JSON。
+**FastAPI** 能自动处理这些数据,并将之转换为 JSON。
+///
## 添加自定义响应头
```
-!!! 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` 也是如此。
+///
## 覆盖默认异常处理器
### `RequestValidationError` vs `ValidationError`
-!!! warning "警告"
+/// warning | "警告"
- 如果您觉得现在还用不到以下技术细节,可以先跳过下面的内容。
+如果您觉得现在还用不到以下技术细节,可以先跳过下面的内容。
+///
`RequestValidationError` 是 Pydantic 的 <a href="https://docs.pydantic.dev/latest/concepts/models/#error-handling" class="external-link" target="_blank">`ValidationError`</a> 的子类。
```
-!!! 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` 的请求体
首先,导入 `Header`:
-=== "Python 3.10+"
+//// tab | Python 3.10+
- ```Python hl_lines="3"
- {!> ../../../docs_src/header_params/tutorial001_an_py310.py!}
- ```
+```Python hl_lines="3"
+{!> ../../../docs_src/header_params/tutorial001_an_py310.py!}
+```
+
+////
+
+//// tab | Python 3.9+
+
+```Python hl_lines="3"
+{!> ../../../docs_src/header_params/tutorial001_an_py39.py!}
+```
+
+////
+
+//// tab | Python 3.8+
+
+```Python hl_lines="3"
+{!> ../../../docs_src/header_params/tutorial001_an.py!}
+```
+
+////
+
+//// tab | Python 3.10+ non-Annotated
+
+/// tip
-=== "Python 3.9+"
+尽可能选择使用 `Annotated` 的版本。
- ```Python hl_lines="3"
- {!> ../../../docs_src/header_params/tutorial001_an_py39.py!}
- ```
+///
-=== "Python 3.8+"
+```Python hl_lines="1"
+{!> ../../../docs_src/header_params/tutorial001_py310.py!}
+```
- ```Python hl_lines="3"
- {!> ../../../docs_src/header_params/tutorial001_an.py!}
- ```
+////
-=== "Python 3.10+ non-Annotated"
+//// tab | Python 3.8+ non-Annotated
- !!! tip
- 尽可能选择使用 `Annotated` 的版本。
+/// tip
- ```Python hl_lines="1"
- {!> ../../../docs_src/header_params/tutorial001_py310.py!}
- ```
+尽可能选择使用 `Annotated` 的版本。
-=== "Python 3.8+ non-Annotated"
+///
- !!! tip
- 尽可能选择使用 `Annotated` 的版本。
+```Python hl_lines="3"
+{!> ../../../docs_src/header_params/tutorial001.py!}
+```
- ```Python hl_lines="3"
- {!> ../../../docs_src/header_params/tutorial001.py!}
- ```
+////
## 声明 `Header` 参数
第一个值是默认值,还可以传递所有验证参数或注释参数:
-=== "Python 3.10+"
+//// tab | Python 3.10+
- ```Python hl_lines="9"
- {!> ../../../docs_src/header_params/tutorial001_an_py310.py!}
- ```
+```Python hl_lines="9"
+{!> ../../../docs_src/header_params/tutorial001_an_py310.py!}
+```
-=== "Python 3.9+"
+////
- ```Python hl_lines="9"
- {!> ../../../docs_src/header_params/tutorial001_an_py39.py!}
- ```
+//// tab | Python 3.9+
-=== "Python 3.8+"
+```Python hl_lines="9"
+{!> ../../../docs_src/header_params/tutorial001_an_py39.py!}
+```
- ```Python hl_lines="10"
- {!> ../../../docs_src/header_params/tutorial001_an.py!}
- ```
+////
-=== "Python 3.10+ non-Annotated"
+//// tab | Python 3.8+
- !!! tip
- 尽可能选择使用 `Annotated` 的版本。
+```Python hl_lines="10"
+{!> ../../../docs_src/header_params/tutorial001_an.py!}
+```
+
+////
+
+//// tab | Python 3.10+ non-Annotated
+
+/// tip
- ```Python hl_lines="7"
- {!> ../../../docs_src/header_params/tutorial001_py310.py!}
- ```
+尽可能选择使用 `Annotated` 的版本。
-=== "Python 3.8+ non-Annotated"
+///
- !!! tip
- 尽可能选择使用 `Annotated` 的版本。
+```Python hl_lines="7"
+{!> ../../../docs_src/header_params/tutorial001_py310.py!}
+```
+
+////
- ```Python hl_lines="9"
- {!> ../../../docs_src/header_params/tutorial001.py!}
- ```
+//// tab | Python 3.8+ non-Annotated
-!!! note "技术细节"
+/// tip
- `Header` 是 `Path`、`Query`、`Cookie` 的**兄弟类**,都继承自共用的 `Param` 类。
+尽可能选择使用 `Annotated` 的版本。
- 注意,从 `fastapi` 导入的 `Query`、`Path`、`Header` 等对象,实际上是返回特殊类的函数。
+///
+
+```Python hl_lines="9"
+{!> ../../../docs_src/header_params/tutorial001.py!}
+```
-!!! info "说明"
+////
- 必须使用 `Header` 声明 header 参数,否则该参数会被解释为查询参数。
+/// note | "技术细节"
+
+`Header` 是 `Path`、`Query`、`Cookie` 的**兄弟类**,都继承自共用的 `Param` 类。
+
+注意,从 `fastapi` 导入的 `Query`、`Path`、`Header` 等对象,实际上是返回特殊类的函数。
+
+///
+
+/// info | "说明"
+
+必须使用 `Header` 声明 header 参数,否则该参数会被解释为查询参数。
+
+///
## 自动转换
如需禁用下划线自动转换为连字符,可以把 `Header` 的 `convert_underscores` 参数设置为 `False`:
-=== "Python 3.10+"
+//// tab | Python 3.10+
+
+```Python hl_lines="10"
+{!> ../../../docs_src/header_params/tutorial002_an_py310.py!}
+```
+
+////
+
+//// tab | Python 3.9+
+
+```Python hl_lines="11"
+{!> ../../../docs_src/header_params/tutorial002_an_py39.py!}
+```
+
+////
+
+//// tab | Python 3.8+
+
+```Python hl_lines="12"
+{!> ../../../docs_src/header_params/tutorial002_an.py!}
+```
+
+////
- ```Python hl_lines="10"
- {!> ../../../docs_src/header_params/tutorial002_an_py310.py!}
- ```
+//// tab | Python 3.10+ non-Annotated
-=== "Python 3.9+"
+/// tip
- ```Python hl_lines="11"
- {!> ../../../docs_src/header_params/tutorial002_an_py39.py!}
- ```
+尽可能选择使用 `Annotated` 的版本。
-=== "Python 3.8+"
+///
+
+```Python hl_lines="8"
+{!> ../../../docs_src/header_params/tutorial002_py310.py!}
+```
- ```Python hl_lines="12"
- {!> ../../../docs_src/header_params/tutorial002_an.py!}
- ```
+////
-=== "Python 3.10+ non-Annotated"
+//// tab | Python 3.8+ non-Annotated
- !!! tip
- 尽可能选择使用 `Annotated` 的版本。
+/// tip
- ```Python hl_lines="8"
- {!> ../../../docs_src/header_params/tutorial002_py310.py!}
- ```
+尽可能选择使用 `Annotated` 的版本。
-=== "Python 3.8+ non-Annotated"
+///
- !!! tip
- 尽可能选择使用 `Annotated` 的版本。
+```Python hl_lines="10"
+{!> ../../../docs_src/header_params/tutorial002.py!}
+```
- ```Python hl_lines="10"
- {!> ../../../docs_src/header_params/tutorial002.py!}
- ```
+////
-!!! warning "警告"
+/// warning | "警告"
- 注意,使用 `convert_underscores = False` 要慎重,有些 HTTP 代理和服务器不支持使用带有下划线的请求头。
+注意,使用 `convert_underscores = False` 要慎重,有些 HTTP 代理和服务器不支持使用带有下划线的请求头。
+///
## 重复的请求头
例如,声明 `X-Token` 多次出现的请求头,可以写成这样:
-=== "Python 3.10+"
+//// tab | Python 3.10+
- ```Python hl_lines="9"
- {!> ../../../docs_src/header_params/tutorial003_an_py310.py!}
- ```
+```Python hl_lines="9"
+{!> ../../../docs_src/header_params/tutorial003_an_py310.py!}
+```
-=== "Python 3.9+"
+////
- ```Python hl_lines="9"
- {!> ../../../docs_src/header_params/tutorial003_an_py39.py!}
- ```
+//// tab | Python 3.9+
-=== "Python 3.8+"
+```Python hl_lines="9"
+{!> ../../../docs_src/header_params/tutorial003_an_py39.py!}
+```
- ```Python hl_lines="10"
- {!> ../../../docs_src/header_params/tutorial003_an.py!}
- ```
+////
-=== "Python 3.10+ non-Annotated"
+//// tab | Python 3.8+
- !!! tip
- Prefer to use the `Annotated` version if possible.
+```Python hl_lines="10"
+{!> ../../../docs_src/header_params/tutorial003_an.py!}
+```
- ```Python hl_lines="7"
- {!> ../../../docs_src/header_params/tutorial003_py310.py!}
- ```
+////
-=== "Python 3.9+ non-Annotated"
+//// tab | Python 3.10+ non-Annotated
- !!! tip
- 尽可能选择使用 `Annotated` 的版本。
+/// tip
- ```Python hl_lines="9"
- {!> ../../../docs_src/header_params/tutorial003_py39.py!}
- ```
+Prefer to use the `Annotated` version if possible.
-=== "Python 3.8+ non-Annotated"
+///
- !!! tip
- 尽可能选择使用 `Annotated` 的版本。
+```Python hl_lines="7"
+{!> ../../../docs_src/header_params/tutorial003_py310.py!}
+```
+
+////
+
+//// tab | Python 3.9+ non-Annotated
+
+/// tip
+
+尽可能选择使用 `Annotated` 的版本。
+
+///
+
+```Python hl_lines="9"
+{!> ../../../docs_src/header_params/tutorial003_py39.py!}
+```
+
+////
+
+//// tab | Python 3.8+ non-Annotated
+
+/// tip
+
+尽可能选择使用 `Annotated` 的版本。
+
+///
+
+```Python hl_lines="9"
+{!> ../../../docs_src/header_params/tutorial003.py!}
+```
- ```Python hl_lines="9"
- {!> ../../../docs_src/header_params/tutorial003.py!}
- ```
+////
与*路径操作*通信时,以下面的方式发送两个 HTTP 请求头:
......以上安装还包括了 `uvicorn`,你可以将其用作运行代码的服务器。
-!!! note
- 你也可以分开来安装。
+/// note
- 假如你想将应用程序部署到生产环境,你可能要执行以下操作:
+你也可以分开来安装。
- ```
- pip install fastapi
- ```
+假如你想将应用程序部署到生产环境,你可能要执行以下操作:
- 并且安装`uvicorn`来作为服务器:
+```
+pip install fastapi
+```
+
+并且安装`uvicorn`来作为服务器:
+
+```
+pip install "uvicorn[standard]"
+```
- ```
- pip install "uvicorn[standard]"
- ```
+然后对你想使用的每个可选依赖项也执行相同的操作。
- 然后对你想使用的每个可选依赖项也执行相同的操作。
+///
## 进阶用户指南
-# 元数据和文档 URL\r
-\r
-你可以在 FastAPI 应用程序中自定义多个元数据配置。\r
-\r
-## API 元数据\r
-\r
-你可以在设置 OpenAPI 规范和自动 API 文档 UI 中使用的以下字段:\r
-\r
-| 参数 | 类型 | 描述 |\r
-|------------|------|-------------|\r
-| `title` | `str` | API 的标题。 |\r
-| `summary` | `str` | API 的简短摘要。 <small>自 OpenAPI 3.1.0、FastAPI 0.99.0 起可用。.</small> |\r
-| `description` | `str` | API 的简短描述。可以使用Markdown。 |\r
-| `version` | `string` | API 的版本。这是您自己的应用程序的版本,而不是 OpenAPI 的版本。例如 `2.5.0` 。 |\r
-| `terms_of_service` | `str` | API 服务条款的 URL。如果提供,则必须是 URL。 |\r
-| `contact` | `dict` | 公开的 API 的联系信息。它可以包含多个字段。<details><summary><code>contact</code> 字段</summary><table><thead><tr><th>参数</th><th>Type</th><th>描述</th></tr></thead><tbody><tr><td><code>name</code></td><td><code>str</code></td><td>联系人/组织的识别名称。</td></tr><tr><td><code>url</code></td><td><code>str</code></td><td>指向联系信息的 URL。必须采用 URL 格式。</td></tr><tr><td><code>email</code></td><td><code>str</code></td><td>联系人/组织的电子邮件地址。必须采用电子邮件地址的格式。</td></tr></tbody></table></details> |\r
-| `license_info` | `dict` | 公开的 API 的许可证信息。它可以包含多个字段。<details><summary><code>license_info</code> 字段</summary><table><thead><tr><th>参数</th><th>类型</th><th>描述</th></tr></thead><tbody><tr><td><code>name</code></td><td><code>str</code></td><td><strong>必须的</strong> (如果设置了<code>license_info</code>). 用于 API 的许可证名称。</td></tr><tr><td><code>identifier</code></td><td><code>str</code></td><td>一个API的<a href="https://spdx.org/licenses/" class="external-link" target="_blank">SPDX</a>许可证表达。 The <code>identifier</code> field is mutually exclusive of the <code>url</code> field. <small>自 OpenAPI 3.1.0、FastAPI 0.99.0 起可用。</small></td></tr><tr><td><code>url</code></td><td><code>str</code></td><td>用于 API 的许可证的 URL。必须采用 URL 格式。</td></tr></tbody></table></details> |\r
-\r
-你可以按如下方式设置它们:\r
-\r
-```Python hl_lines="4-6"\r
-{!../../../docs_src/metadata/tutorial001.py!}\r
-```\r
-\r
-!!! tip\r
- 您可以在 `description` 字段中编写 Markdown,它将在输出中呈现。\r
-\r
-通过这样设置,自动 API 文档看起来会像:\r
-\r
-<img src="/img/tutorial/metadata/image01.png">\r
-\r
-## 标签元数据\r
-\r
-### 创建标签元数据\r
-\r
-让我们在带有标签的示例中为 `users` 和 `items` 试一下。\r
-\r
-创建标签元数据并把它传递给 `openapi_tags` 参数:\r
-\r
-```Python hl_lines="3-16 18"\r
-{!../../../docs_src/metadata/tutorial004.py!}\r
-```\r
-\r
-注意你可以在描述内使用 Markdown,例如「login」会显示为粗体(**login**)以及「fancy」会显示为斜体(_fancy_)。\r
-\r
-!!! tip "提示"\r
- 不必为你使用的所有标签都添加元数据。\r
-\r
-### 使用你的标签\r
-\r
-将 `tags` 参数和*路径操作*(以及 `APIRouter`)一起使用,将其分配给不同的标签:\r
-\r
-```Python hl_lines="21 26"\r
-{!../../../docs_src/metadata/tutorial004.py!}\r
-```\r
-\r
-!!! info "信息"\r
- 阅读更多关于标签的信息[路径操作配置](path-operation-configuration.md#tags){.internal-link target=_blank}。\r
-\r
-### 查看文档\r
-\r
-如果你现在查看文档,它们会显示所有附加的元数据:\r
-\r
-<img src="/img/tutorial/metadata/image02.png">\r
-\r
-### 标签顺序\r
-\r
-每个标签元数据字典的顺序也定义了在文档用户界面显示的顺序。\r
-\r
-例如按照字母顺序,即使 `users` 排在 `items` 之后,它也会显示在前面,因为我们将它的元数据添加为列表内的第一个字典。\r
-\r
-## OpenAPI URL\r
-\r
-默认情况下,OpenAPI 模式服务于 `/openapi.json`。\r
-\r
-但是你可以通过参数 `openapi_url` 对其进行配置。\r
-\r
-例如,将其设置为服务于 `/api/v1/openapi.json`:\r
-\r
-```Python hl_lines="3"\r
-{!../../../docs_src/metadata/tutorial002.py!}\r
-```\r
-\r
-如果你想完全禁用 OpenAPI 模式,可以将其设置为 `openapi_url=None`,这样也会禁用使用它的文档用户界面。\r
-\r
-## 文档 URLs\r
-\r
-你可以配置两个文档用户界面,包括:\r
-\r
-* **Swagger UI**:服务于 `/docs`。\r
- * 可以使用参数 `docs_url` 设置它的 URL。\r
- * 可以通过设置 `docs_url=None` 禁用它。\r
-* ReDoc:服务于 `/redoc`。\r
- * 可以使用参数 `redoc_url` 设置它的 URL。\r
- * 可以通过设置 `redoc_url=None` 禁用它。\r
-\r
-例如,设置 Swagger UI 服务于 `/documentation` 并禁用 ReDoc:\r
-\r
-```Python hl_lines="3"\r
-{!../../../docs_src/metadata/tutorial003.py!}\r
-```\r
+# 元数据和文档 URL
+
+你可以在 FastAPI 应用程序中自定义多个元数据配置。
+
+## API 元数据
+
+你可以在设置 OpenAPI 规范和自动 API 文档 UI 中使用的以下字段:
+
+| 参数 | 类型 | 描述 |
+|------------|------|-------------|
+| `title` | `str` | API 的标题。 |
+| `summary` | `str` | API 的简短摘要。 <small>自 OpenAPI 3.1.0、FastAPI 0.99.0 起可用。.</small> |
+| `description` | `str` | API 的简短描述。可以使用Markdown。 |
+| `version` | `string` | API 的版本。这是您自己的应用程序的版本,而不是 OpenAPI 的版本。例如 `2.5.0` 。 |
+| `terms_of_service` | `str` | API 服务条款的 URL。如果提供,则必须是 URL。 |
+| `contact` | `dict` | 公开的 API 的联系信息。它可以包含多个字段。<details><summary><code>contact</code> 字段</summary><table><thead><tr><th>参数</th><th>Type</th><th>描述</th></tr></thead><tbody><tr><td><code>name</code></td><td><code>str</code></td><td>联系人/组织的识别名称。</td></tr><tr><td><code>url</code></td><td><code>str</code></td><td>指向联系信息的 URL。必须采用 URL 格式。</td></tr><tr><td><code>email</code></td><td><code>str</code></td><td>联系人/组织的电子邮件地址。必须采用电子邮件地址的格式。</td></tr></tbody></table></details> |
+| `license_info` | `dict` | 公开的 API 的许可证信息。它可以包含多个字段。<details><summary><code>license_info</code> 字段</summary><table><thead><tr><th>参数</th><th>类型</th><th>描述</th></tr></thead><tbody><tr><td><code>name</code></td><td><code>str</code></td><td><strong>必须的</strong> (如果设置了<code>license_info</code>). 用于 API 的许可证名称。</td></tr><tr><td><code>identifier</code></td><td><code>str</code></td><td>一个API的<a href="https://spdx.org/licenses/" class="external-link" target="_blank">SPDX</a>许可证表达。 The <code>identifier</code> field is mutually exclusive of the <code>url</code> field. <small>自 OpenAPI 3.1.0、FastAPI 0.99.0 起可用。</small></td></tr><tr><td><code>url</code></td><td><code>str</code></td><td>用于 API 的许可证的 URL。必须采用 URL 格式。</td></tr></tbody></table></details> |
+
+你可以按如下方式设置它们:
+
+```Python hl_lines="4-6"
+{!../../../docs_src/metadata/tutorial001.py!}
+```
+
+/// tip
+
+您可以在 `description` 字段中编写 Markdown,它将在输出中呈现。
+
+///
+
+通过这样设置,自动 API 文档看起来会像:
+
+<img src="/img/tutorial/metadata/image01.png">
+
+## 标签元数据
+
+### 创建标签元数据
+
+让我们在带有标签的示例中为 `users` 和 `items` 试一下。
+
+创建标签元数据并把它传递给 `openapi_tags` 参数:
+
+```Python hl_lines="3-16 18"
+{!../../../docs_src/metadata/tutorial004.py!}
+```
+
+注意你可以在描述内使用 Markdown,例如「login」会显示为粗体(**login**)以及「fancy」会显示为斜体(_fancy_)。
+
+/// tip | "提示"
+
+不必为你使用的所有标签都添加元数据。
+
+///
+
+### 使用你的标签
+
+将 `tags` 参数和*路径操作*(以及 `APIRouter`)一起使用,将其分配给不同的标签:
+
+```Python hl_lines="21 26"
+{!../../../docs_src/metadata/tutorial004.py!}
+```
+
+/// info | "信息"
+
+阅读更多关于标签的信息[路径操作配置](path-operation-configuration.md#tags){.internal-link target=_blank}。
+
+///
+
+### 查看文档
+
+如果你现在查看文档,它们会显示所有附加的元数据:
+
+<img src="/img/tutorial/metadata/image02.png">
+
+### 标签顺序
+
+每个标签元数据字典的顺序也定义了在文档用户界面显示的顺序。
+
+例如按照字母顺序,即使 `users` 排在 `items` 之后,它也会显示在前面,因为我们将它的元数据添加为列表内的第一个字典。
+
+## OpenAPI URL
+
+默认情况下,OpenAPI 模式服务于 `/openapi.json`。
+
+但是你可以通过参数 `openapi_url` 对其进行配置。
+
+例如,将其设置为服务于 `/api/v1/openapi.json`:
+
+```Python hl_lines="3"
+{!../../../docs_src/metadata/tutorial002.py!}
+```
+
+如果你想完全禁用 OpenAPI 模式,可以将其设置为 `openapi_url=None`,这样也会禁用使用它的文档用户界面。
+
+## 文档 URLs
+
+你可以配置两个文档用户界面,包括:
+
+* **Swagger UI**:服务于 `/docs`。
+ * 可以使用参数 `docs_url` 设置它的 URL。
+ * 可以通过设置 `docs_url=None` 禁用它。
+* ReDoc:服务于 `/redoc`。
+ * 可以使用参数 `redoc_url` 设置它的 URL。
+ * 可以通过设置 `redoc_url=None` 禁用它。
+
+例如,设置 Swagger UI 服务于 `/documentation` 并禁用 ReDoc:
+
+```Python hl_lines="3"
+{!../../../docs_src/metadata/tutorial003.py!}
+```
* 它可以对该**响应**做些什么或者执行任何需要的代码.
* 然后它返回这个 **响应**.
-!!! note "技术细节"
- 如果你使用了 `yield` 关键字依赖, 依赖中的退出代码将在执行中间件*后*执行.
+/// note | "技术细节"
- 如果有任何后台任务(稍后记录), 它们将在执行中间件*后*运行.
+如果你使用了 `yield` 关键字依赖, 依赖中的退出代码将在执行中间件*后*执行.
+
+如果有任何后台任务(稍后记录), 它们将在执行中间件*后*运行.
+
+///
## 创建中间件
{!../../../docs_src/middleware/tutorial001.py!}
```
-!!! tip
- 请记住可以 <a href="https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers" class="external-link" target="_blank">用'X-' 前缀</a>添加专有自定义请求头.
+/// tip
+
+请记住可以 <a href="https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers" class="external-link" target="_blank">用'X-' 前缀</a>添加专有自定义请求头.
+
+但是如果你想让浏览器中的客户端看到你的自定义请求头, 你需要把它们加到 CORS 配置 ([CORS (Cross-Origin Resource Sharing)](cors.md){.internal-link target=_blank}) 的 `expose_headers` 参数中,在 <a href="https://www.starlette.io/middleware/#corsmiddleware" class="external-link" target="_blank">Starlette's CORS docs</a>文档中.
+
+///
+
+/// note | "技术细节"
- 但是如果你想让浏览器中的客户端看到你的自定义请求头, 你需要把它们加到 CORS 配置 ([CORS (Cross-Origin Resource Sharing)](cors.md){.internal-link target=_blank}) 的 `expose_headers` 参数中,在 <a href="https://www.starlette.io/middleware/#corsmiddleware" class="external-link" target="_blank">Starlette's CORS docs</a>文档中.
+你也可以使用 `from starlette.requests import Request`.
-!!! note "技术细节"
- 你也可以使用 `from starlette.requests import Request`.
+**FastAPI** 为了开发者方便提供了该对象. 但其实它直接来自于 Starlette.
- **FastAPI** 为了开发者方便提供了该对象. 但其实它直接来自于 Starlette.
+///
### 在 `response` 的前和后
*路径操作装饰器*支持多种配置参数。
-!!! warning "警告"
+/// warning | "警告"
- 注意:以下参数应直接传递给**路径操作装饰器**,不能传递给*路径操作函数*。
+注意:以下参数应直接传递给**路径操作装饰器**,不能传递给*路径操作函数*。
+
+///
## `status_code` 状态码
状态码在响应中使用,并会被添加到 OpenAPI 概图。
-!!! note "技术细节"
+/// note | "技术细节"
+
+也可以使用 `from starlette import status` 导入状态码。
- 也可以使用 `from starlette import status` 导入状态码。
+**FastAPI** 的`fastapi.status` 和 `starlette.status` 一样,只是快捷方式。实际上,`fastapi.status` 直接继承自 Starlette。
- **FastAPI** 的`fastapi.status` 和 `starlette.status` 一样,只是快捷方式。实际上,`fastapi.status` 直接继承自 Starlette。
+///
## `tags` 参数
{!../../../docs_src/path_operation_configuration/tutorial005.py!}
```
-!!! info "说明"
+/// info | "说明"
+
+注意,`response_description` 只用于描述响应,`description` 一般则用于描述*路径操作*。
+
+///
- 注意,`response_description` 只用于描述响应,`description` 一般则用于描述*路径操作*。
+/// check | "检查"
-!!! check "检查"
+OpenAPI 规定每个*路径操作*都要有响应描述。
- OpenAPI 规定每个*路径操作*都要有响应描述。
+如果没有定义响应描述,**FastAPI** 则自动生成内容为 "Successful response" 的响应描述。
- 如果没有定义响应描述,**FastAPI** 则自动生成内容为 "Successful response" 的响应描述。
+///
<img src="/img/tutorial/path-operation-configuration/image03.png">
首先,从 `fastapi` 导入 `Path`:
-=== "Python 3.10+"
+//// tab | Python 3.10+
- ```Python hl_lines="1 3"
- {!> ../../../docs_src/path_params_numeric_validations/tutorial001_an_py310.py!}
- ```
+```Python hl_lines="1 3"
+{!> ../../../docs_src/path_params_numeric_validations/tutorial001_an_py310.py!}
+```
+
+////
+
+//// tab | Python 3.9+
-=== "Python 3.9+"
+```Python hl_lines="1 3"
+{!> ../../../docs_src/path_params_numeric_validations/tutorial001_an_py39.py!}
+```
+
+////
- ```Python hl_lines="1 3"
- {!> ../../../docs_src/path_params_numeric_validations/tutorial001_an_py39.py!}
- ```
+//// tab | Python 3.8+
-=== "Python 3.8+"
+```Python hl_lines="3-4"
+{!> ../../../docs_src/path_params_numeric_validations/tutorial001_an.py!}
+```
- ```Python hl_lines="3-4"
- {!> ../../../docs_src/path_params_numeric_validations/tutorial001_an.py!}
- ```
+////
-=== "Python 3.10+ non-Annotated"
+//// tab | Python 3.10+ non-Annotated
+
+/// tip
+
+尽可能选择使用 `Annotated` 的版本。
+
+///
+
+```Python hl_lines="1"
+{!> ../../../docs_src/path_params_numeric_validations/tutorial001_py310.py!}
+```
- !!! tip
- 尽可能选择使用 `Annotated` 的版本。
+////
- ```Python hl_lines="1"
- {!> ../../../docs_src/path_params_numeric_validations/tutorial001_py310.py!}
- ```
+//// tab | Python 3.8+ non-Annotated
-=== "Python 3.8+ non-Annotated"
+/// tip
- !!! tip
- 尽可能选择使用 `Annotated` 的版本。
+尽可能选择使用 `Annotated` 的版本。
- ```Python hl_lines="3"
- {!> ../../../docs_src/path_params_numeric_validations/tutorial001.py!}
- ```
+///
+
+```Python hl_lines="3"
+{!> ../../../docs_src/path_params_numeric_validations/tutorial001.py!}
+```
+
+////
## 声明元数据
例如,要声明路径参数 `item_id`的 `title` 元数据值,你可以输入:
-=== "Python 3.10+"
+//// tab | Python 3.10+
+
+```Python hl_lines="10"
+{!> ../../../docs_src/path_params_numeric_validations/tutorial001_an_py310.py!}
+```
- ```Python hl_lines="10"
- {!> ../../../docs_src/path_params_numeric_validations/tutorial001_an_py310.py!}
- ```
+////
-=== "Python 3.9+"
+//// tab | Python 3.9+
- ```Python hl_lines="10"
- {!> ../../../docs_src/path_params_numeric_validations/tutorial001_an_py39.py!}
- ```
+```Python hl_lines="10"
+{!> ../../../docs_src/path_params_numeric_validations/tutorial001_an_py39.py!}
+```
-=== "Python 3.8+"
+////
- ```Python hl_lines="11"
- {!> ../../../docs_src/path_params_numeric_validations/tutorial001_an.py!}
- ```
+//// tab | Python 3.8+
-=== "Python 3.10+ non-Annotated"
+```Python hl_lines="11"
+{!> ../../../docs_src/path_params_numeric_validations/tutorial001_an.py!}
+```
- !!! tip
- 尽可能选择使用 `Annotated` 的版本。
+////
- ```Python hl_lines="8"
- {!> ../../../docs_src/path_params_numeric_validations/tutorial001_py310.py!}
- ```
+//// tab | Python 3.10+ non-Annotated
-=== "Python 3.8+ non-Annotated"
+/// tip
- !!! tip
- 尽可能选择使用 `Annotated` 的版本。
+尽可能选择使用 `Annotated` 的版本。
- ```Python hl_lines="10"
- {!> ../../../docs_src/path_params_numeric_validations/tutorial001.py!}
- ```
+///
-!!! note
- 路径参数总是必需的,因为它必须是路径的一部分。
+```Python hl_lines="8"
+{!> ../../../docs_src/path_params_numeric_validations/tutorial001_py310.py!}
+```
- 所以,你应该在声明时使用 `...` 将其标记为必需参数。
+////
- 然而,即使你使用 `None` 声明路径参数或设置一个其他默认值也不会有任何影响,它依然会是必需参数。
+//// tab | Python 3.8+ non-Annotated
+
+/// tip
+
+尽可能选择使用 `Annotated` 的版本。
+
+///
+
+```Python hl_lines="10"
+{!> ../../../docs_src/path_params_numeric_validations/tutorial001.py!}
+```
+
+////
+
+/// note
+
+路径参数总是必需的,因为它必须是路径的一部分。
+
+所以,你应该在声明时使用 `...` 将其标记为必需参数。
+
+然而,即使你使用 `None` 声明路径参数或设置一个其他默认值也不会有任何影响,它依然会是必需参数。
+
+///
## 按需对参数排序
因此,你可以将函数声明为:
-=== "Python 3.8 non-Annotated"
+//// tab | Python 3.8 non-Annotated
+
+/// tip
+
+尽可能选择使用 `Annotated` 的版本。
- !!! tip
- 尽可能选择使用 `Annotated` 的版本。
+///
+
+```Python hl_lines="7"
+{!> ../../../docs_src/path_params_numeric_validations/tutorial002.py!}
+```
- ```Python hl_lines="7"
- {!> ../../../docs_src/path_params_numeric_validations/tutorial002.py!}
- ```
+////
## 按需对参数排序的技巧
* `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` 的类的实例。
+因为使用了这些函数(而不是直接使用类),所以你的编辑器不会标记有关其类型的错误。
- 因为使用了这些函数(而不是直接使用类),所以你的编辑器不会标记有关其类型的错误。
+这样,你可以使用常规的编辑器和编码工具,而不必添加自定义配置来忽略这些错误。
- 这样,你可以使用常规的编辑器和编码工具,而不必添加自定义配置来忽略这些错误。
+///
本例把 `item_id` 的类型声明为 `int`。
-!!! check "检查"
+/// check | "检查"
- 类型声明将为函数提供错误检查、代码补全等编辑器支持。
+类型声明将为函数提供错误检查、代码补全等编辑器支持。
+
+///
## 数据<abbr title="也称为:序列化、解析">转换</abbr>
{"item_id":3}
```
-!!! check "检查"
+/// check | "检查"
+
+注意,函数接收并返回的值是 `3`( `int`),不是 `"3"`(`str`)。
- 注意,函数接收并返回的值是 `3`( `int`),不是 `"3"`(`str`)。
+**FastAPI** 通过类型声明自动<abbr title="将来自 HTTP 请求中的字符串转换为 Python 数据类型">**解析**请求中的数据</abbr>。
- **FastAPI** 通过类型声明自动<abbr title="将来自 HTTP 请求中的字符串转换为 Python 数据类型">**解析**请求中的数据</abbr>。
+///
## 数据校验
值的类型不是 `int ` 而是浮点数(`float`)时也会显示同样的错误,比如: <a href="http://127.0.0.1:8000/items/4.2" class="external-link" target="_blank">http://127.0.0.1:8000/items/4.2。</a>
-!!! check "检查"
+/// check | "检查"
- **FastAPI** 使用 Python 类型声明实现了数据校验。
+**FastAPI** 使用 Python 类型声明实现了数据校验。
- 注意,上面的错误清晰地指出了未通过校验的具体原因。
+注意,上面的错误清晰地指出了未通过校验的具体原因。
- 这在开发调试与 API 交互的代码时非常有用。
+这在开发调试与 API 交互的代码时非常有用。
+
+///
## 查看文档
<img src="/img/tutorial/path-params/image01.png">
-!!! check "检查"
+/// check | "检查"
+
+还是使用 Python 类型声明,**FastAPI** 提供了(集成 Swagger UI 的)API 文档。
- 还是使用 Python 类型声明,**FastAPI** 提供了(集成 Swagger UI 的)API 文档。
+注意,路径参数的类型是整数。
- 注意,路径参数的类型是整数。
+///
## 基于标准的好处,备选文档
{!../../../docs_src/path_params/tutorial005.py!}
```
-!!! info "说明"
+/// info | "说明"
- Python 3.4 及之后版本支持<a href="https://docs.python.org/3/library/enum.html" class="external-link" target="_blank">枚举(即 enums)</a>。
+Python 3.4 及之后版本支持<a href="https://docs.python.org/3/library/enum.html" class="external-link" target="_blank">枚举(即 enums)</a>。
-!!! tip "提示"
+///
- **AlexNet**、**ResNet**、**LeNet** 是机器学习<abbr title="技术上来说是深度学习模型架构">模型</abbr>。
+/// tip | "提示"
+
+**AlexNet**、**ResNet**、**LeNet** 是机器学习<abbr title="技术上来说是深度学习模型架构">模型</abbr>。
+
+///
### 声明*路径参数*
{!../../../docs_src/path_params/tutorial005.py!}
```
-!!! tip "提示"
+/// tip | "提示"
- 使用 `ModelName.lenet.value` 也能获取值 `"lenet"`。
+使用 `ModelName.lenet.value` 也能获取值 `"lenet"`。
+
+///
#### 返回*枚举元素*
{!../../../docs_src/path_params/tutorial004.py!}
```
-!!! tip "提示"
+/// tip | "提示"
+
+注意,包含 `/home/johndoe/myfile.txt` 的路径参数要以斜杠(`/`)开头。
- 注意,包含 `/home/johndoe/myfile.txt` 的路径参数要以斜杠(`/`)开头。
+本例中的 URL 是 `/files//home/johndoe/myfile.txt`。注意,`files` 和 `home` 之间要使用**双斜杠**(`//`)。
- 本例中的 URL 是 `/files//home/johndoe/myfile.txt`。注意,`files` 和 `home` 之间要使用**双斜杠**(`//`)。
+///
## 小结
让我们以下面的应用程序为例:
-=== "Python 3.10+"
+//// tab | Python 3.10+
- ```Python hl_lines="7"
- {!> ../../../docs_src/query_params_str_validations/tutorial001_py310.py!}
- ```
+```Python hl_lines="7"
+{!> ../../../docs_src/query_params_str_validations/tutorial001_py310.py!}
+```
+
+////
-=== "Python 3.8+"
+//// tab | Python 3.8+
+
+```Python hl_lines="9"
+{!> ../../../docs_src/query_params_str_validations/tutorial001.py!}
+```
- ```Python hl_lines="9"
- {!> ../../../docs_src/query_params_str_validations/tutorial001.py!}
- ```
+////
查询参数 `q` 的类型为 `str`,默认值为 `None`,因此它是可选的。
{!../../../docs_src/query_params_str_validations/tutorial005.py!}
```
-!!! note
- 具有默认值还会使该参数成为可选参数。
+/// note
+
+具有默认值还会使该参数成为可选参数。
+
+///
## 声明为必需参数
{!../../../docs_src/query_params_str_validations/tutorial006b.py!}
```
-!!! info
- 如果你之前没见过 `...` 这种用法:它是一个特殊的单独值,它是 <a href="https://docs.python.org/3/library/constants.html#Ellipsis" class="external-link" target="_blank">Python 的一部分并且被称为「省略号」</a>。
- Pydantic 和 FastAPI 使用它来显式的声明需要一个值。
+/// info
+
+如果你之前没见过 `...` 这种用法:它是一个特殊的单独值,它是 <a href="https://docs.python.org/3/library/constants.html#Ellipsis" class="external-link" target="_blank">Python 的一部分并且被称为「省略号」</a>。
+Pydantic 和 FastAPI 使用它来显式的声明需要一个值。
+
+///
这将使 **FastAPI** 知道此查询参数是必需的。
{!../../../docs_src/query_params_str_validations/tutorial006c.py!}
```
-!!! tip
- Pydantic 是 FastAPI 中所有数据验证和序列化的核心,当你在没有设默认值的情况下使用 `Optional` 或 `Union[Something, None]` 时,它具有特殊行为,你可以在 Pydantic 文档中阅读有关<a href="https://docs.pydantic.dev/latest/concepts/models/#required-optional-fields" class="external-link" target="_blank">必需可选字段</a>的更多信息。
+/// tip
+
+Pydantic 是 FastAPI 中所有数据验证和序列化的核心,当你在没有设默认值的情况下使用 `Optional` 或 `Union[Something, None]` 时,它具有特殊行为,你可以在 Pydantic 文档中阅读有关<a href="https://docs.pydantic.dev/latest/concepts/models/#required-optional-fields" class="external-link" target="_blank">必需可选字段</a>的更多信息。
+
+///
### 使用Pydantic中的`Required`代替省略号(`...`)
{!../../../docs_src/query_params_str_validations/tutorial006d.py!}
```
-!!! tip
- 请记住,在大多数情况下,当你需要某些东西时,可以简单地省略 `default` 参数,因此你通常不必使用 `...` 或 `Required`
+/// tip
+
+请记住,在大多数情况下,当你需要某些东西时,可以简单地省略 `default` 参数,因此你通常不必使用 `...` 或 `Required`
+///
## 查询参数列表 / 多个值
}
```
-!!! tip
- 要声明类型为 `list` 的查询参数,如上例所示,你需要显式地使用 `Query`,否则该参数将被解释为请求体。
+/// tip
+
+要声明类型为 `list` 的查询参数,如上例所示,你需要显式地使用 `Query`,否则该参数将被解释为请求体。
+
+///
交互式 API 文档将会相应地进行更新,以允许使用多个值:
{!../../../docs_src/query_params_str_validations/tutorial013.py!}
```
-!!! note
- 请记住,在这种情况下 FastAPI 将不会检查列表的内容。
+/// note
- 例如,`List[int]` 将检查(并记录到文档)列表的内容必须是整数。但是单独的 `list` 不会。
+请记住,在这种情况下 FastAPI 将不会检查列表的内容。
+
+例如,`List[int]` 将检查(并记录到文档)列表的内容必须是整数。但是单独的 `list` 不会。
+
+///
## 声明更多元数据
这些信息将包含在生成的 OpenAPI 模式中,并由文档用户界面和外部工具所使用。
-!!! note
- 请记住,不同的工具对 OpenAPI 的支持程度可能不同。
+/// note
+
+请记住,不同的工具对 OpenAPI 的支持程度可能不同。
+
+其中一些可能不会展示所有已声明的额外信息,尽管在大多数情况下,缺少的这部分功能已经计划进行开发。
- 其中一些可能不会展示所有已声明的额外信息,尽管在大多数情况下,缺少的这部分功能已经计划进行开发。
+///
你可以添加 `title`:
同理,把默认值设为 `None` 即可声明**可选的**查询参数:
-=== "Python 3.10+"
+//// tab | Python 3.10+
- ```Python hl_lines="7"
- {!> ../../../docs_src/query_params/tutorial002_py310.py!}
- ```
+```Python hl_lines="7"
+{!> ../../../docs_src/query_params/tutorial002_py310.py!}
+```
-=== "Python 3.8+"
+////
- ```Python hl_lines="9"
- {!> ../../../docs_src/query_params/tutorial002.py!}
- ```
+//// tab | Python 3.8+
+```Python hl_lines="9"
+{!> ../../../docs_src/query_params/tutorial002.py!}
+```
+
+////
本例中,查询参数 `q` 是可选的,默认值为 `None`。
-!!! check "检查"
+/// check | "检查"
+
+注意,**FastAPI** 可以识别出 `item_id` 是路径参数,`q` 不是路径参数,而是查询参数。
- 注意,**FastAPI** 可以识别出 `item_id` 是路径参数,`q` 不是路径参数,而是查询参数。
+///
-!!! note "笔记"
+/// note | "笔记"
- 因为默认值为 `= None`,FastAPI 把 `q` 识别为可选参数。
+因为默认值为 `= None`,FastAPI 把 `q` 识别为可选参数。
- FastAPI 不使用 `Optional[str]` 中的 `Optional`(只使用 `str`),但 `Optional[str]` 可以帮助编辑器发现代码中的错误。
+FastAPI 不使用 `Optional[str]` 中的 `Optional`(只使用 `str`),但 `Optional[str]` 可以帮助编辑器发现代码中的错误。
+
+///
## 查询参数类型转换
参数还可以声明为 `bool` 类型,FastAPI 会自动转换参数类型:
-=== "Python 3.10+"
+//// tab | Python 3.10+
+
+```Python hl_lines="7"
+{!> ../../../docs_src/query_params/tutorial003_py310.py!}
+```
- ```Python hl_lines="7"
- {!> ../../../docs_src/query_params/tutorial003_py310.py!}
- ```
+////
-=== "Python 3.8+"
+//// tab | Python 3.8+
- ```Python hl_lines="9"
- {!> ../../../docs_src/query_params/tutorial003.py!}
- ```
+```Python hl_lines="9"
+{!> ../../../docs_src/query_params/tutorial003.py!}
+```
+////
本例中,访问:
FastAPI 通过参数名进行检测:
-=== "Python 3.10+"
+//// tab | Python 3.10+
- ```Python hl_lines="6 8"
- {!> ../../../docs_src/query_params/tutorial004_py310.py!}
- ```
+```Python hl_lines="6 8"
+{!> ../../../docs_src/query_params/tutorial004_py310.py!}
+```
+
+////
-=== "Python 3.8+"
+//// tab | Python 3.8+
- ```Python hl_lines="8 10"
- {!> ../../../docs_src/query_params/tutorial004.py!}
- ```
+```Python hl_lines="8 10"
+{!> ../../../docs_src/query_params/tutorial004.py!}
+```
+////
## 必选查询参数
当然,把一些参数定义为必选,为另一些参数设置默认值,再把其它参数定义为可选,这些操作都是可以的:
-=== "Python 3.10+"
+//// tab | Python 3.10+
- ```Python hl_lines="8"
- {!> ../../../docs_src/query_params/tutorial006_py310.py!}
- ```
+```Python hl_lines="8"
+{!> ../../../docs_src/query_params/tutorial006_py310.py!}
+```
-=== "Python 3.8+"
+////
- ```Python hl_lines="10"
- {!> ../../../docs_src/query_params/tutorial006.py!}
- ```
+//// tab | Python 3.8+
+
+```Python hl_lines="10"
+{!> ../../../docs_src/query_params/tutorial006.py!}
+```
+
+////
本例中有 3 个查询参数:
* `skip`,默认值为 `0` 的 `int` 类型参数
* `limit`,可选的 `int` 类型参数
-!!! tip "提示"
- 还可以像在[路径参数](path-params.md#_8){.internal-link target=_blank} 中那样使用 `Enum`。
+/// tip | "提示"
+
+还可以像在[路径参数](path-params.md#_8){.internal-link target=_blank} 中那样使用 `Enum`。
+
+///
`File` 用于定义客户端的上传文件。
-!!! info "说明"
+/// info | "说明"
- 因为上传文件以「表单数据」形式发送。
+因为上传文件以「表单数据」形式发送。
- 所以接收上传文件,要预先安装 <a href="https://github.com/Kludex/python-multipart" class="external-link" target="_blank">`python-multipart`</a>。
+所以接收上传文件,要预先安装 <a href="https://github.com/Kludex/python-multipart" class="external-link" target="_blank">`python-multipart`</a>。
- 例如: `pip install python-multipart`。
+例如: `pip install python-multipart`。
+
+///
## 导入 `File`
{!../../../docs_src/request_files/tutorial001.py!}
```
-!!! info "说明"
+/// info | "说明"
+
+`File` 是直接继承自 `Form` 的类。
+
+注意,从 `fastapi` 导入的 `Query`、`Path`、`File` 等项,实际上是返回特定类的函数。
- `File` 是直接继承自 `Form` 的类。
+///
- 注意,从 `fastapi` 导入的 `Query`、`Path`、`File` 等项,实际上是返回特定类的函数。
+/// tip | "提示"
-!!! tip "提示"
+声明文件体必须使用 `File`,否则,FastAPI 会把该参数当作查询参数或请求体(JSON)参数。
- 声明文件体必须使用 `File`,否则,FastAPI 会把该参数当作查询参数或请求体(JSON)参数。
+///
文件作为「表单数据」上传。
contents = myfile.file.read()
```
-!!! note "`async` 技术细节"
+/// note | "`async` 技术细节"
+
+使用 `async` 方法时,**FastAPI** 在线程池中执行文件方法,并 `await` 操作完成。
+
+///
- 使用 `async` 方法时,**FastAPI** 在线程池中执行文件方法,并 `await` 操作完成。
+/// note | "Starlette 技术细节"
-!!! note "Starlette 技术细节"
+**FastAPI** 的 `UploadFile` 直接继承自 **Starlette** 的 `UploadFile`,但添加了一些必要功能,使之与 **Pydantic** 及 FastAPI 的其它部件兼容。
- **FastAPI** 的 `UploadFile` 直接继承自 **Starlette** 的 `UploadFile`,但添加了一些必要功能,使之与 **Pydantic** 及 FastAPI 的其它部件兼容。
+///
## 什么是 「表单数据」
**FastAPI** 要确保从正确的位置读取数据,而不是读取 JSON。
-!!! note "技术细节"
+/// note | "技术细节"
- 不包含文件时,表单数据一般用 `application/x-www-form-urlencoded`「媒体类型」编码。
+不包含文件时,表单数据一般用 `application/x-www-form-urlencoded`「媒体类型」编码。
- 但表单包含文件时,编码为 `multipart/form-data`。使用了 `File`,**FastAPI** 就知道要从请求体的正确位置获取文件。
+但表单包含文件时,编码为 `multipart/form-data`。使用了 `File`,**FastAPI** 就知道要从请求体的正确位置获取文件。
- 编码和表单字段详见 <a href="https://developer.mozilla.org/zh-CN/docs/Web/HTTP/Methods/POST" class="external-link" target="_blank"><abbr title="Mozilla Developer Network">MDN</abbr> Web 文档的 <code>POST </code></a> 小节。
+编码和表单字段详见 <a href="https://developer.mozilla.org/zh-CN/docs/Web/HTTP/Methods/POST" class="external-link" target="_blank"><abbr title="Mozilla Developer Network">MDN</abbr> Web 文档的 <code>POST </code></a> 小节。
-!!! warning "警告"
+///
- 可在一个*路径操作*中声明多个 `File` 和 `Form` 参数,但不能同时声明要接收 JSON 的 `Body` 字段。因为此时请求体的编码是 `multipart/form-data`,不是 `application/json`。
+/// warning | "警告"
- 这不是 **FastAPI** 的问题,而是 HTTP 协议的规定。
+可在一个*路径操作*中声明多个 `File` 和 `Form` 参数,但不能同时声明要接收 JSON 的 `Body` 字段。因为此时请求体的编码是 `multipart/form-data`,不是 `application/json`。
+
+这不是 **FastAPI** 的问题,而是 HTTP 协议的规定。
+
+///
## 可选文件上传
您可以通过使用标准类型注解并将 None 作为默认值的方式将一个文件参数设为可选:
-=== "Python 3.9+"
+//// tab | Python 3.9+
+
+```Python hl_lines="7 14"
+{!> ../../../docs_src/request_files/tutorial001_02_py310.py!}
+```
+
+////
- ```Python hl_lines="7 14"
- {!> ../../../docs_src/request_files/tutorial001_02_py310.py!}
- ```
+//// tab | Python 3.8+
-=== "Python 3.8+"
+```Python hl_lines="9 17"
+{!> ../../../docs_src/request_files/tutorial001_02.py!}
+```
- ```Python hl_lines="9 17"
- {!> ../../../docs_src/request_files/tutorial001_02.py!}
- ```
+////
## 带有额外元数据的 `UploadFile`
上传多个文件时,要声明含 `bytes` 或 `UploadFile` 的列表(`List`):
-=== "Python 3.9+"
+//// tab | Python 3.9+
+
+```Python hl_lines="8 13"
+{!> ../../../docs_src/request_files/tutorial002_py39.py!}
+```
- ```Python hl_lines="8 13"
- {!> ../../../docs_src/request_files/tutorial002_py39.py!}
- ```
+////
-=== "Python 3.8+"
+//// tab | Python 3.8+
+
+```Python hl_lines="10 15"
+{!> ../../../docs_src/request_files/tutorial002.py!}
+```
- ```Python hl_lines="10 15"
- {!> ../../../docs_src/request_files/tutorial002.py!}
- ```
+////
接收的也是含 `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+"
+//// tab | Python 3.9+
+
+```Python hl_lines="16"
+{!> ../../../docs_src/request_files/tutorial003_py39.py!}
+```
- ```Python hl_lines="16"
- {!> ../../../docs_src/request_files/tutorial003_py39.py!}
- ```
+////
-=== "Python 3.8+"
+//// tab | Python 3.8+
+
+```Python hl_lines="18"
+{!> ../../../docs_src/request_files/tutorial003.py!}
+```
- ```Python hl_lines="18"
- {!> ../../../docs_src/request_files/tutorial003.py!}
- ```
+////
## 小结
FastAPI 支持同时使用 `File` 和 `Form` 定义文件和表单字段。
-!!! info "说明"
+/// info | "说明"
- 接收上传文件或表单数据,要预先安装 <a href="https://github.com/Kludex/python-multipart" class="external-link" target="_blank">`python-multipart`</a>。
+接收上传文件或表单数据,要预先安装 <a href="https://github.com/Kludex/python-multipart" class="external-link" target="_blank">`python-multipart`</a>。
- 例如,`pip install python-multipart`。
+例如,`pip install python-multipart`。
+
+///
## 导入 `File` 与 `Form`
声明文件可以使用 `bytes` 或 `UploadFile` 。
-!!! warning "警告"
+/// warning | "警告"
+
+可在一个*路径操作*中声明多个 `File` 与 `Form` 参数,但不能同时声明要接收 JSON 的 `Body` 字段。因为此时请求体的编码为 `multipart/form-data`,不是 `application/json`。
- 可在一个*路径操作*中声明多个 `File` 与 `Form` 参数,但不能同时声明要接收 JSON 的 `Body` 字段。因为此时请求体的编码为 `multipart/form-data`,不是 `application/json`。
+这不是 **FastAPI** 的问题,而是 HTTP 协议的规定。
- 这不是 **FastAPI** 的问题,而是 HTTP 协议的规定。
+///
## 小结
接收的不是 JSON,而是表单字段时,要使用 `Form`。
-!!! info "说明"
+/// info | "说明"
- 要使用表单,需预先安装 <a href="https://github.com/Kludex/python-multipart" class="external-link" target="_blank">`python-multipart`</a>。
+要使用表单,需预先安装 <a href="https://github.com/Kludex/python-multipart" class="external-link" target="_blank">`python-multipart`</a>。
- 例如,`pip install python-multipart`。
+例如,`pip install python-multipart`。
+
+///
## 导入 `Form`
使用 `Form` 可以声明与 `Body` (及 `Query`、`Path`、`Cookie`)相同的元数据和验证。
-!!! info "说明"
+/// info | "说明"
+
+`Form` 是直接继承自 `Body` 的类。
+
+///
- `Form` 是直接继承自 `Body` 的类。
+/// tip | "提示"
-!!! tip "提示"
+声明表单体要显式使用 `Form` ,否则,FastAPI 会把该参数当作查询参数或请求体(JSON)参数。
- 声明表单体要显式使用 `Form` ,否则,FastAPI 会把该参数当作查询参数或请求体(JSON)参数。
+///
## 关于 "表单字段"
**FastAPI** 要确保从正确的位置读取数据,而不是读取 JSON。
-!!! note "技术细节"
+/// note | "技术细节"
+
+表单数据的「媒体类型」编码一般为 `application/x-www-form-urlencoded`。
+
+但包含文件的表单编码为 `multipart/form-data`。文件处理详见下节。
- 表单数据的「媒体类型」编码一般为 `application/x-www-form-urlencoded`。
+编码和表单字段详见 <a href="https://developer.mozilla.org/zh-CN/docs/Web/HTTP/Methods/POST" class="external-link" target="_blank"><abbr title="Mozilla Developer Network">MDN</abbr> Web 文档的 <code>POST</code></a>小节。
- 但包含文件的表单编码为 `multipart/form-data`。文件处理详见下节。
+///
- 编码和表单字段详见 <a href="https://developer.mozilla.org/zh-CN/docs/Web/HTTP/Methods/POST" class="external-link" target="_blank"><abbr title="Mozilla Developer Network">MDN</abbr> Web 文档的 <code>POST</code></a>小节。
+/// 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 协议的规定。
+///
## 小结
* `@app.delete()`
* 等等。
-=== "Python 3.10+"
+//// tab | Python 3.10+
- ```Python hl_lines="17 22 24-27"
- {!> ../../../docs_src/response_model/tutorial001_py310.py!}
- ```
+```Python hl_lines="17 22 24-27"
+{!> ../../../docs_src/response_model/tutorial001_py310.py!}
+```
+
+////
-=== "Python 3.9+"
+//// tab | Python 3.9+
- ```Python hl_lines="17 22 24-27"
- {!> ../../../docs_src/response_model/tutorial001_py39.py!}
- ```
+```Python hl_lines="17 22 24-27"
+{!> ../../../docs_src/response_model/tutorial001_py39.py!}
+```
-=== "Python 3.8+"
+////
- ```Python hl_lines="17 22 24-27"
- {!> ../../../docs_src/response_model/tutorial001.py!}
- ```
+//// tab | Python 3.8+
+
+```Python hl_lines="17 22 24-27"
+{!> ../../../docs_src/response_model/tutorial001.py!}
+```
-!!! note
- 注意,`response_model`是「装饰器」方法(`get`,`post` 等)的一个参数。不像之前的所有参数和请求体,它不属于*路径操作函数*。
+////
+
+/// note
+
+注意,`response_model`是「装饰器」方法(`get`,`post` 等)的一个参数。不像之前的所有参数和请求体,它不属于*路径操作函数*。
+
+///
它接收的类型与你将为 Pydantic 模型属性所声明的类型相同,因此它可以是一个 Pydantic 模型,但也可以是一个由 Pydantic 模型组成的 `list`,例如 `List[Item]`。
* 会将输出数据限制在该模型定义内。下面我们会看到这一点有多重要。
-!!! note "技术细节"
- 响应模型在参数中被声明,而不是作为函数返回类型的注解,这是因为路径函数可能不会真正返回该响应模型,而是返回一个 `dict`、数据库对象或其他模型,然后再使用 `response_model` 来执行字段约束和序列化。
+/// note | "技术细节"
+
+响应模型在参数中被声明,而不是作为函数返回类型的注解,这是因为路径函数可能不会真正返回该响应模型,而是返回一个 `dict`、数据库对象或其他模型,然后再使用 `response_model` 来执行字段约束和序列化。
+
+///
## 返回与输入相同的数据
但是,如果我们在其他的*路径操作*中使用相同的模型,则可能会将用户的密码发送给每个客户端。
-!!! danger
- 永远不要存储用户的明文密码,也不要在响应中发送密码。
+/// danger
+
+永远不要存储用户的明文密码,也不要在响应中发送密码。
+
+///
## 添加输出模型
相反,我们可以创建一个有明文密码的输入模型和一个没有明文密码的输出模型:
-=== "Python 3.10+"
+//// tab | Python 3.10+
- ```Python hl_lines="9 11 16"
- {!> ../../../docs_src/response_model/tutorial003_py310.py!}
- ```
+```Python hl_lines="9 11 16"
+{!> ../../../docs_src/response_model/tutorial003_py310.py!}
+```
-=== "Python 3.8+"
+////
- ```Python hl_lines="9 11 16"
- {!> ../../../docs_src/response_model/tutorial003.py!}
- ```
+//// tab | Python 3.8+
+
+```Python hl_lines="9 11 16"
+{!> ../../../docs_src/response_model/tutorial003.py!}
+```
+
+////
这样,即便我们的*路径操作函数*将会返回包含密码的相同输入用户:
-=== "Python 3.10+"
+//// tab | Python 3.10+
+
+```Python hl_lines="24"
+{!> ../../../docs_src/response_model/tutorial003_py310.py!}
+```
+
+////
- ```Python hl_lines="24"
- {!> ../../../docs_src/response_model/tutorial003_py310.py!}
- ```
+//// tab | Python 3.8+
-=== "Python 3.8+"
+```Python hl_lines="24"
+{!> ../../../docs_src/response_model/tutorial003.py!}
+```
- ```Python hl_lines="24"
- {!> ../../../docs_src/response_model/tutorial003.py!}
- ```
+////
...我们已经将 `response_model` 声明为了不包含密码的 `UserOut` 模型:
-=== "Python 3.10+"
+//// tab | Python 3.10+
- ```Python hl_lines="22"
- {!> ../../../docs_src/response_model/tutorial003_py310.py!}
- ```
+```Python hl_lines="22"
+{!> ../../../docs_src/response_model/tutorial003_py310.py!}
+```
-=== "Python 3.8+"
+////
- ```Python hl_lines="22"
- {!> ../../../docs_src/response_model/tutorial003.py!}
- ```
+//// tab | Python 3.8+
+
+```Python hl_lines="22"
+{!> ../../../docs_src/response_model/tutorial003.py!}
+```
+
+////
因此,**FastAPI** 将会负责过滤掉未在输出模型中声明的所有数据(使用 Pydantic)。
}
```
-!!! info
- FastAPI 通过 Pydantic 模型的 `.dict()` 配合 <a href="https://docs.pydantic.dev/latest/concepts/serialization/#modeldict" class="external-link" target="_blank">该方法的 `exclude_unset` 参数</a> 来实现此功能。
+/// info
+
+FastAPI 通过 Pydantic 模型的 `.dict()` 配合 <a href="https://docs.pydantic.dev/latest/concepts/serialization/#modeldict" class="external-link" target="_blank">该方法的 `exclude_unset` 参数</a> 来实现此功能。
-!!! info
- 你还可以使用:
+///
- * `response_model_exclude_defaults=True`
- * `response_model_exclude_none=True`
+/// info
- 参考 <a href="https://docs.pydantic.dev/latest/concepts/serialization/#modeldict" class="external-link" target="_blank">Pydantic 文档</a> 中对 `exclude_defaults` 和 `exclude_none` 的描述。
+你还可以使用:
+
+* `response_model_exclude_defaults=True`
+* `response_model_exclude_none=True`
+
+参考 <a href="https://docs.pydantic.dev/latest/concepts/serialization/#modeldict" class="external-link" target="_blank">Pydantic 文档</a> 中对 `exclude_defaults` 和 `exclude_none` 的描述。
+
+///
#### 默认值字段有实际值的数据
因此,它们将包含在 JSON 响应中。
-!!! tip
- 请注意默认值可以是任何值,而不仅是`None`。
+/// tip
+
+请注意默认值可以是任何值,而不仅是`None`。
+
+它们可以是一个列表(`[]`),一个值为 `10.5`的 `float`,等等。
- 它们可以是一个列表(`[]`),一个值为 `10.5`的 `float`,等等。
+///
### `response_model_include` 和 `response_model_exclude`
如果你只有一个 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 仍将是完整的模型。
+
+这也适用于作用类似的 `response_model_by_alias`。
+
+///
```Python hl_lines="31 37"
{!../../../docs_src/response_model/tutorial005.py!}
```
-!!! tip
- `{"name", "description"}` 语法创建一个具有这两个值的 `set`。
+/// tip
+
+`{"name", "description"}` 语法创建一个具有这两个值的 `set`。
+
+等同于 `set(["name", "description"])`。
- 等同于 `set(["name", "description"])`。
+///
#### 使用 `list` 而不是 `set`
{!../../../docs_src/response_status_code/tutorial001.py!}
```
-!!! note "笔记"
+/// note | "笔记"
- 注意,`status_code` 是(`get`、`post` 等)**装饰器**方法中的参数。与之前的参数和请求体不同,不是*路径操作函数*的参数。
+注意,`status_code` 是(`get`、`post` 等)**装饰器**方法中的参数。与之前的参数和请求体不同,不是*路径操作函数*的参数。
+
+///
`status_code` 参数接收表示 HTTP 状态码的数字。
-!!! info "说明"
+/// info | "说明"
+
+`status_code` 还能接收 `IntEnum` 类型,比如 Python 的 <a href="https://docs.python.org/3/library/http.html#http.HTTPStatus" class="external-link" target="_blank">`http.HTTPStatus`</a>。
- `status_code` 还能接收 `IntEnum` 类型,比如 Python 的 <a href="https://docs.python.org/3/library/http.html#http.HTTPStatus" class="external-link" target="_blank">`http.HTTPStatus`</a>。
+///
它可以:
<img src="/img/tutorial/response-status-code/image01.png">
-!!! note "笔记"
+/// note | "笔记"
+
+某些响应状态码表示响应没有响应体(参阅下一章)。
- 某些响应状态码表示响应没有响应体(参阅下一章)。
+FastAPI 可以进行识别,并生成表明无响应体的 OpenAPI 文档。
- FastAPI 可以进行识别,并生成表明无响应体的 OpenAPI 文档。
+///
## 关于 HTTP 状态码
-!!! note "笔记"
+/// note | "笔记"
- 如果已经了解 HTTP 状态码,请跳到下一章。
+如果已经了解 HTTP 状态码,请跳到下一章。
+
+///
在 HTTP 协议中,发送 3 位数的数字状态码是响应的一部分。
* 对于来自客户端的一般错误,可以只使用 `400`
* `500` 及以上的状态码用于表示服务器端错误。几乎永远不会直接使用这些状态码。应用代码或服务器出现问题时,会自动返回这些状态代码
-!!! tip "提示"
+/// tip | "提示"
+
+状态码及适用场景的详情,请参阅 <a href="https://developer.mozilla.org/en-US/docs/Web/HTTP/Status" class="external-link" target="_blank"><abbr title="Mozilla Developer Network">MDN 的 HTTP 状态码</abbr>文档</a>。
- 状态码及适用场景的详情,请参阅 <a href="https://developer.mozilla.org/en-US/docs/Web/HTTP/Status" class="external-link" target="_blank"><abbr title="Mozilla Developer Network">MDN 的 HTTP 状态码</abbr>文档</a>。
+///
## 状态码名称快捷方式
<img src="../../../../../../img/tutorial/response-status-code/image02.png">
-!!! note "技术细节"
+/// note | "技术细节"
+
+也可以使用 `from starlette import status`。
- 也可以使用 `from starlette import status`。
+为了让开发者更方便,**FastAPI** 提供了与 `starlette.status` 完全相同的 `fastapi.status`。但它直接来自于 Starlette。
- 为了让开发者更方便,**FastAPI** 提供了与 `starlette.status` 完全相同的 `fastapi.status`。但它直接来自于 Starlette。
+///
## 更改默认状态码
您可以使用 `Config` 和 `schema_extra` 为Pydantic模型声明一个示例,如<a href="https://docs.pydantic.dev/latest/concepts/json_schema/#schema-customization" class="external-link" target="_blank">Pydantic 文档:定制 Schema </a>中所述:
-=== "Python 3.10+"
+//// tab | Python 3.10+
- ```Python hl_lines="13-21"
- {!> ../../../docs_src/schema_extra_example/tutorial001_py310.py!}
- ```
+```Python hl_lines="13-21"
+{!> ../../../docs_src/schema_extra_example/tutorial001_py310.py!}
+```
-=== "Python 3.8+"
+////
- ```Python hl_lines="15-23"
- {!> ../../../docs_src/schema_extra_example/tutorial001.py!}
- ```
+//// tab | Python 3.8+
+
+```Python hl_lines="15-23"
+{!> ../../../docs_src/schema_extra_example/tutorial001.py!}
+```
+
+////
这些额外的信息将按原样添加到输出的JSON模式中。
在 `Field`, `Path`, `Query`, `Body` 和其他你之后将会看到的工厂函数,你可以为JSON 模式声明额外信息,你也可以通过给工厂函数传递其他的任意参数来给JSON 模式声明额外信息,比如增加 `example`:
-=== "Python 3.10+"
+//// tab | Python 3.10+
+
+```Python hl_lines="2 8-11"
+{!> ../../../docs_src/schema_extra_example/tutorial002_py310.py!}
+```
+
+////
- ```Python hl_lines="2 8-11"
- {!> ../../../docs_src/schema_extra_example/tutorial002_py310.py!}
- ```
+//// tab | Python 3.8+
-=== "Python 3.8+"
+```Python hl_lines="4 10-13"
+{!> ../../../docs_src/schema_extra_example/tutorial002.py!}
+```
- ```Python hl_lines="4 10-13"
- {!> ../../../docs_src/schema_extra_example/tutorial002.py!}
- ```
+////
-!!! warning
- 请记住,传递的那些额外参数不会添加任何验证,只会添加注释,用于文档的目的。
+/// warning
+
+请记住,传递的那些额外参数不会添加任何验证,只会添加注释,用于文档的目的。
+
+///
## `Body` 额外参数
比如,你可以将请求体的一个 `example` 传递给 `Body`:
-=== "Python 3.10+"
+//// tab | Python 3.10+
+
+```Python hl_lines="22-27"
+{!> ../../../docs_src/schema_extra_example/tutorial003_an_py310.py!}
+```
+
+////
+
+//// tab | Python 3.9+
+
+```Python hl_lines="22-27"
+{!> ../../../docs_src/schema_extra_example/tutorial003_an_py39.py!}
+```
+
+////
+
+//// tab | Python 3.8+
+
+```Python hl_lines="23-28"
+{!> ../../../docs_src/schema_extra_example/tutorial003_an.py!}
+```
+
+////
+
+//// tab | Python 3.10+ non-Annotated
- ```Python hl_lines="22-27"
- {!> ../../../docs_src/schema_extra_example/tutorial003_an_py310.py!}
- ```
+/// tip
-=== "Python 3.9+"
+尽可能选择使用 `Annotated` 的版本。
- ```Python hl_lines="22-27"
- {!> ../../../docs_src/schema_extra_example/tutorial003_an_py39.py!}
- ```
+///
-=== "Python 3.8+"
+```Python hl_lines="18-23"
+{!> ../../../docs_src/schema_extra_example/tutorial003_py310.py!}
+```
- ```Python hl_lines="23-28"
- {!> ../../../docs_src/schema_extra_example/tutorial003_an.py!}
- ```
+////
-=== "Python 3.10+ non-Annotated"
+//// tab | Python 3.8+ non-Annotated
- !!! tip
- 尽可能选择使用 `Annotated` 的版本。
+/// tip
- ```Python hl_lines="18-23"
- {!> ../../../docs_src/schema_extra_example/tutorial003_py310.py!}
- ```
+尽可能选择使用 `Annotated` 的版本。
-=== "Python 3.8+ non-Annotated"
+///
- !!! tip
- 尽可能选择使用 `Annotated` 的版本。
+```Python hl_lines="20-25"
+{!> ../../../docs_src/schema_extra_example/tutorial003.py!}
+```
- ```Python hl_lines="20-25"
- {!> ../../../docs_src/schema_extra_example/tutorial003.py!}
- ```
+////
## 文档 UI 中的例子
把下面的示例代码复制到 `main.py`:
-=== "Python 3.9+"
+//// tab | Python 3.9+
- ```Python
- {!> ../../../docs_src/security/tutorial001_an_py39.py!}
- ```
+```Python
+{!> ../../../docs_src/security/tutorial001_an_py39.py!}
+```
+
+////
+
+//// tab | Python 3.8+
+
+```Python
+{!> ../../../docs_src/security/tutorial001_an.py!}
+```
+
+////
+
+//// tab | Python 3.8+ non-Annotated
-=== "Python 3.8+"
+/// tip
- ```Python
- {!> ../../../docs_src/security/tutorial001_an.py!}
- ```
+尽可能选择使用 `Annotated` 的版本。
-=== "Python 3.8+ non-Annotated"
+///
- !!! tip
- 尽可能选择使用 `Annotated` 的版本。
+```Python
+{!> ../../../docs_src/security/tutorial001.py!}
+```
- ```Python
- {!> ../../../docs_src/security/tutorial001.py!}
- ```
+////
## 运行
-!!! info "说明"
+/// info | "说明"
+
+先安装 <a href="https://github.com/Kludex/python-multipart" class="external-link" target="_blank">`python-multipart`</a>。
- 先安装 <a href="https://github.com/Kludex/python-multipart" class="external-link" target="_blank">`python-multipart`</a>。
+安装命令: `pip install python-multipart`。
- 安装命令: `pip install python-multipart`。
+这是因为 **OAuth2** 使用**表单数据**发送 `username` 与 `password`。
- 这是因为 **OAuth2** 使用**表单数据**发送 `username` 与 `password`。
+///
用下面的命令运行该示例:
<img src="/img/tutorial/security/image01.png">
-!!! check "Authorize 按钮!"
+/// check | "Authorize 按钮!"
- 页面右上角出现了一个「**Authorize**」按钮。
+页面右上角出现了一个「**Authorize**」按钮。
- *路径操作*的右上角也出现了一个可以点击的小锁图标。
+*路径操作*的右上角也出现了一个可以点击的小锁图标。
+
+///
点击 **Authorize** 按钮,弹出授权表单,输入 `username` 与 `password` 及其它可选字段:
<img src="/img/tutorial/security/image02.png">
-!!! note "笔记"
+/// note | "笔记"
+
+目前,在表单中输入内容不会有任何反应,后文会介绍相关内容。
- 目前,在表单中输入内容不会有任何反应,后文会介绍相关内容。
+///
虽然此文档不是给前端最终用户使用的,但这个自动工具非常实用,可在文档中与所有 API 交互。
本例使用 **OAuth2** 的 **Password** 流以及 **Bearer** 令牌(`Token`)。为此要使用 `OAuth2PasswordBearer` 类。
-!!! info "说明"
+/// info | "说明"
- `Bearer` 令牌不是唯一的选择。
+`Bearer` 令牌不是唯一的选择。
- 但它是最适合这个用例的方案。
+但它是最适合这个用例的方案。
- 甚至可以说,它是适用于绝大多数用例的最佳方案,除非您是 OAuth2 的专家,知道为什么其它方案更合适。
+甚至可以说,它是适用于绝大多数用例的最佳方案,除非您是 OAuth2 的专家,知道为什么其它方案更合适。
- 本例中,**FastAPI** 还提供了构建工具。
+本例中,**FastAPI** 还提供了构建工具。
+
+///
创建 `OAuth2PasswordBearer` 的类实例时,要传递 `tokenUrl` 参数。该参数包含客户端(用户浏览器中运行的前端) 的 URL,用于发送 `username` 与 `password`,并获取令牌。
{!../../../docs_src/security/tutorial001.py!}
```
-!!! tip "提示"
+/// tip | "提示"
+
+在此,`tokenUrl="token"` 指向的是暂未创建的相对 URL `token`。这个相对 URL 相当于 `./token`。
- 在此,`tokenUrl="token"` 指向的是暂未创建的相对 URL `token`。这个相对 URL 相当于 `./token`。
+因为使用的是相对 URL,如果 API 位于 `https://example.com/`,则指向 `https://example.com/token`。但如果 API 位于 `https://example.com/api/v1/`,它指向的就是`https://example.com/api/v1/token`。
- 因为使用的是相对 URL,如果 API 位于 `https://example.com/`,则指向 `https://example.com/token`。但如果 API 位于 `https://example.com/api/v1/`,它指向的就是`https://example.com/api/v1/token`。
+使用相对 URL 非常重要,可以确保应用在遇到[使用代理](../../advanced/behind-a-proxy.md){.internal-link target=_blank}这样的高级用例时,也能正常运行。
- 使用相对 URL 非常重要,可以确保应用在遇到[使用代理](../../advanced/behind-a-proxy.md){.internal-link target=_blank}这样的高级用例时,也能正常运行。
+///
该参数不会创建端点或*路径操作*,但会声明客户端用来获取令牌的 URL `/token` 。此信息用于 OpenAPI 及 API 文档。
接下来,学习如何创建实际的路径操作。
-!!! info "说明"
+/// info | "说明"
- 严苛的 **Pythonista** 可能不喜欢用 `tokenUrl` 这种命名风格代替 `token_url`。
+严苛的 **Pythonista** 可能不喜欢用 `tokenUrl` 这种命名风格代替 `token_url`。
- 这种命名方式是因为要使用与 OpenAPI 规范中相同的名字。以便在深入校验安全方案时,能通过复制粘贴查找更多相关信息。
+这种命名方式是因为要使用与 OpenAPI 规范中相同的名字。以便在深入校验安全方案时,能通过复制粘贴查找更多相关信息。
+
+///
`oauth2_scheme` 变量是 `OAuth2PasswordBearer` 的实例,也是**可调用项**。
**FastAPI** 使用依赖项在 OpenAPI 概图(及 API 文档)中定义**安全方案**。
-!!! info "技术细节"
+/// info | "技术细节"
+
+**FastAPI** 使用(在依赖项中声明的)类 `OAuth2PasswordBearer` 在 OpenAPI 中定义安全方案,这是因为它继承自 `fastapi.security.oauth2.OAuth2`,而该类又是继承自`fastapi.security.base.SecurityBase`。
- **FastAPI** 使用(在依赖项中声明的)类 `OAuth2PasswordBearer` 在 OpenAPI 中定义安全方案,这是因为它继承自 `fastapi.security.oauth2.OAuth2`,而该类又是继承自`fastapi.security.base.SecurityBase`。
+所有与 OpenAPI(及 API 文档)集成的安全工具都继承自 `SecurityBase`, 这就是为什么 **FastAPI** 能把它们集成至 OpenAPI 的原因。
- 所有与 OpenAPI(及 API 文档)集成的安全工具都继承自 `SecurityBase`, 这就是为什么 **FastAPI** 能把它们集成至 OpenAPI 的原因。
+///
## 实现的操作
这有助于在函数内部使用代码补全和类型检查。
-!!! tip "提示"
+/// tip | "提示"
- 还记得请求体也是使用 Pydantic 模型声明的吧。
+还记得请求体也是使用 Pydantic 模型声明的吧。
- 放心,因为使用了 `Depends`,**FastAPI** 不会搞混。
+放心,因为使用了 `Depends`,**FastAPI** 不会搞混。
-!!! check "检查"
+///
- 依赖系统的这种设计方式可以支持不同的依赖项返回同一个 `User` 模型。
+/// check | "检查"
- 而不是局限于只能有一个返回该类型数据的依赖项。
+依赖系统的这种设计方式可以支持不同的依赖项返回同一个 `User` 模型。
+而不是局限于只能有一个返回该类型数据的依赖项。
+
+///
## 其它模型
OAuth2 没有指定如何加密通信,它期望你为应用程序使用 HTTPS 进行通信。
-!!! tip
- 在有关**部署**的章节中,你将了解如何使用 Traefik 和 Let's Encrypt 免费设置 HTTPS。
+/// tip
+在有关**部署**的章节中,你将了解如何使用 Traefik 和 Let's Encrypt 免费设置 HTTPS。
+
+///
## OpenID Connect
* 此自动发现机制是 OpenID Connect 规范中定义的内容。
-!!! tip
- 集成其他身份认证/授权提供者(例如Google,Facebook,Twitter,GitHub等)也是可能的,而且较为容易。
+/// tip
+
+集成其他身份认证/授权提供者(例如Google,Facebook,Twitter,GitHub等)也是可能的,而且较为容易。
+
+最复杂的问题是创建一个像这样的身份认证/授权提供程序,但是 **FastAPI** 为你提供了轻松完成任务的工具,同时为你解决了重活。
- 最复杂的问题是创建一个像这样的身份认证/授权提供程序,但是 **FastAPI** 为你提供了轻松完成任务的工具,同时为你解决了重活。
+///
## **FastAPI** 实用工具
</div>
-!!! info "说明"
+/// info | "说明"
- 如果您打算使用类似 RSA 或 ECDSA 的数字签名算法,您应该安装加密库依赖项 `pyjwt[crypto]`。
+如果您打算使用类似 RSA 或 ECDSA 的数字签名算法,您应该安装加密库依赖项 `pyjwt[crypto]`。
- 您可以在 <a href="https://pyjwt.readthedocs.io/en/latest/installation.html" class="external-link" target="_blank">PyJWT Installation docs</a> 获得更多信息。
+您可以在 <a href="https://pyjwt.readthedocs.io/en/latest/installation.html" class="external-link" target="_blank">PyJWT Installation docs</a> 获得更多信息。
+
+///
## 密码哈希
</div>
-!!! tip "提示"
+/// tip | "提示"
+
+`passlib` 甚至可以读取 Django、Flask 的安全插件等工具创建的密码。
- `passlib` 甚至可以读取 Django、Flask 的安全插件等工具创建的密码。
+例如,把 Django 应用的数据共享给 FastAPI 应用的数据库。或利用同一个数据库,可以逐步把应用从 Django 迁移到 FastAPI。
- 例如,把 Django 应用的数据共享给 FastAPI 应用的数据库。或利用同一个数据库,可以逐步把应用从 Django 迁移到 FastAPI。
+并且,用户可以同时从 Django 应用或 FastAPI 应用登录。
- 并且,用户可以同时从 Django 应用或 FastAPI 应用登录。
+///
## 密码哈希与校验
创建用于密码哈希和身份校验的 PassLib **上下文**。
-!!! tip "提示"
+/// tip | "提示"
+
+PassLib 上下文还支持使用不同哈希算法的功能,包括只能校验的已弃用旧算法等。
- PassLib 上下文还支持使用不同哈希算法的功能,包括只能校验的已弃用旧算法等。
+例如,用它读取和校验其它系统(如 Django)生成的密码,但要使用其它算法,如 Bcrypt,生成新的哈希密码。
- 例如,用它读取和校验其它系统(如 Django)生成的密码,但要使用其它算法,如 Bcrypt,生成新的哈希密码。
+同时,这些功能都是兼容的。
- 同时,这些功能都是兼容的。
+///
接下来,创建三个工具函数,其中一个函数用于哈希用户的密码。
第三个函数用于身份验证,并返回用户。
-=== "Python 3.10+"
+//// tab | Python 3.10+
+
+```Python hl_lines="8 49 56-57 60-61 70-76"
+{!> ../../../docs_src/security/tutorial004_an_py310.py!}
+```
+
+////
+
+//// tab | Python 3.9+
+
+```Python hl_lines="8 49 56-57 60-61 70-76"
+{!> ../../../docs_src/security/tutorial004_an_py39.py!}
+```
+
+////
+
+//// tab | Python 3.8+
+
+```Python hl_lines="8 50 57-58 61-62 71-77"
+{!> ../../../docs_src/security/tutorial004_an.py!}
+```
+
+////
+
+//// tab | Python 3.10+ non-Annotated
- ```Python hl_lines="8 49 56-57 60-61 70-76"
- {!> ../../../docs_src/security/tutorial004_an_py310.py!}
- ```
+/// tip
-=== "Python 3.9+"
+Prefer to use the `Annotated` version if possible.
- ```Python hl_lines="8 49 56-57 60-61 70-76"
- {!> ../../../docs_src/security/tutorial004_an_py39.py!}
- ```
+///
-=== "Python 3.8+"
+```Python hl_lines="7 48 55-56 59-60 69-75"
+{!> ../../../docs_src/security/tutorial004_py310.py!}
+```
+
+////
- ```Python hl_lines="8 50 57-58 61-62 71-77"
- {!> ../../../docs_src/security/tutorial004_an.py!}
- ```
+//// tab | Python 3.8+ non-Annotated
-=== "Python 3.10+ non-Annotated"
+/// tip
- !!! tip
- Prefer to use the `Annotated` version if possible.
+Prefer to use the `Annotated` version if possible.
- ```Python hl_lines="7 48 55-56 59-60 69-75"
- {!> ../../../docs_src/security/tutorial004_py310.py!}
- ```
+///
-=== "Python 3.8+ non-Annotated"
+```Python hl_lines="8 49 56-57 60-61 70-76"
+{!> ../../../docs_src/security/tutorial004.py!}
+```
- !!! tip
- Prefer to use the `Annotated` version if possible.
+////
- ```Python hl_lines="8 49 56-57 60-61 70-76"
- {!> ../../../docs_src/security/tutorial004.py!}
- ```
+/// note | "笔记"
-!!! note "笔记"
+查看新的(伪)数据库 `fake_users_db`,就能看到哈希后的密码:`"$2b$12$EixZaYVK1fsbw1ZfbX3OXePaWxn96p36WQoeG6Lruj3vjPGga31lW"`。
- 查看新的(伪)数据库 `fake_users_db`,就能看到哈希后的密码:`"$2b$12$EixZaYVK1fsbw1ZfbX3OXePaWxn96p36WQoeG6Lruj3vjPGga31lW"`。
+///
## 处理 JWT 令牌
如果令牌无效,则直接返回 HTTP 错误。
-=== "Python 3.10+"
+//// tab | Python 3.10+
+
+```Python hl_lines="4 7 13-15 29-31 79-87"
+{!> ../../../docs_src/security/tutorial004_an_py310.py!}
+```
+
+////
+
+//// tab | Python 3.9+
+
+```Python hl_lines="4 7 13-15 29-31 79-87"
+{!> ../../../docs_src/security/tutorial004_an_py39.py!}
+```
+
+////
+
+//// tab | Python 3.8+
+
+```Python hl_lines="4 7 14-16 30-32 80-88"
+{!> ../../../docs_src/security/tutorial004_an.py!}
+```
+
+////
+
+//// tab | Python 3.10+ non-Annotated
- ```Python hl_lines="4 7 13-15 29-31 79-87"
- {!> ../../../docs_src/security/tutorial004_an_py310.py!}
- ```
+/// tip
-=== "Python 3.9+"
+Prefer to use the `Annotated` version if possible.
- ```Python hl_lines="4 7 13-15 29-31 79-87"
- {!> ../../../docs_src/security/tutorial004_an_py39.py!}
- ```
+///
-=== "Python 3.8+"
+```Python hl_lines="3 6 12-14 28-30 78-86"
+{!> ../../../docs_src/security/tutorial004_py310.py!}
+```
- ```Python hl_lines="4 7 14-16 30-32 80-88"
- {!> ../../../docs_src/security/tutorial004_an.py!}
- ```
+////
-=== "Python 3.10+ non-Annotated"
+//// tab | Python 3.8+ non-Annotated
- !!! tip
- Prefer to use the `Annotated` version if possible.
+/// tip
- ```Python hl_lines="3 6 12-14 28-30 78-86"
- {!> ../../../docs_src/security/tutorial004_py310.py!}
- ```
+Prefer to use the `Annotated` version if possible.
-=== "Python 3.8+ non-Annotated"
+///
- !!! tip
- Prefer to use the `Annotated` version if possible.
+```Python hl_lines="4 7 13-15 29-31 79-87"
+{!> ../../../docs_src/security/tutorial004.py!}
+```
- ```Python hl_lines="4 7 13-15 29-31 79-87"
- {!> ../../../docs_src/security/tutorial004.py!}
- ```
+////
## 更新 `/token` *路径操作*
创建并返回真正的 JWT 访问令牌。
-=== "Python 3.10+"
+//// tab | Python 3.10+
+
+```Python hl_lines="118-133"
+{!> ../../../docs_src/security/tutorial004_an_py310.py!}
+```
+
+////
+
+//// tab | Python 3.9+
- ```Python hl_lines="118-133"
- {!> ../../../docs_src/security/tutorial004_an_py310.py!}
- ```
+```Python hl_lines="118-133"
+{!> ../../../docs_src/security/tutorial004_an_py39.py!}
+```
+
+////
+
+//// tab | Python 3.8+
+
+```Python hl_lines="119-134"
+{!> ../../../docs_src/security/tutorial004_an.py!}
+```
+
+////
-=== "Python 3.9+"
+//// tab | Python 3.10+ non-Annotated
- ```Python hl_lines="118-133"
- {!> ../../../docs_src/security/tutorial004_an_py39.py!}
- ```
+/// tip
-=== "Python 3.8+"
+Prefer to use the `Annotated` version if possible.
- ```Python hl_lines="119-134"
- {!> ../../../docs_src/security/tutorial004_an.py!}
- ```
+///
-=== "Python 3.10+ non-Annotated"
+```Python hl_lines="115-130"
+{!> ../../../docs_src/security/tutorial004_py310.py!}
+```
+
+////
+
+//// tab | Python 3.8+ non-Annotated
- !!! tip
- Prefer to use the `Annotated` version if possible.
+/// tip
- ```Python hl_lines="115-130"
- {!> ../../../docs_src/security/tutorial004_py310.py!}
- ```
+Prefer to use the `Annotated` version if possible.
-=== "Python 3.8+ non-Annotated"
+///
- !!! tip
- Prefer to use the `Annotated` version if possible.
+```Python hl_lines="116-131"
+{!> ../../../docs_src/security/tutorial004.py!}
+```
- ```Python hl_lines="116-131"
- {!> ../../../docs_src/security/tutorial004.py!}
- ```
+////
### JWT `sub` 的技术细节
用户名: `johndoe` 密码: `secret`
-!!! check "检查"
+/// check | "检查"
+
+注意,代码中没有明文密码**`secret`**,只保存了它的哈希值。
- 注意,代码中没有明文密码**`secret`**,只保存了它的哈希值。
+///
<img src="https://fastapi.tiangolo.com/img/tutorial/security/image08.png">
<img src="https://fastapi.tiangolo.com/img/tutorial/security/image10.png">
-!!! note "笔记"
+/// note | "笔记"
+
+注意,请求中 `Authorization` 响应头的值以 `Bearer` 开头。
- 注意,请求中 `Authorization` 响应头的值以 `Bearer` 开头。
+///
## `scopes` 高级用法
* 脸书和 Instagram 使用 `instagram_basic`
* 谷歌使用 `https://www.googleapis.com/auth/drive`
-!!! info "说明"
+/// info | "说明"
- OAuth2 中,**作用域**只是声明指定权限的字符串。
+OAuth2 中,**作用域**只是声明指定权限的字符串。
- 是否使用冒号 `:` 等符号,或是不是 URL 并不重要。
+是否使用冒号 `:` 等符号,或是不是 URL 并不重要。
- 这些细节只是特定的实现方式。
+这些细节只是特定的实现方式。
- 对 OAuth2 来说,都只是字符串而已。
+对 OAuth2 来说,都只是字符串而已。
+
+///
## 获取 `username` 和 `password` 的代码
* 可选的 `scope` 字段,由多个空格分隔的字符串组成的长字符串
* 可选的 `grant_type`
-!!! tip "提示"
+/// tip | "提示"
+
+实际上,OAuth2 规范*要求* `grant_type` 字段使用固定值 `password`,但 `OAuth2PasswordRequestForm` 没有作强制约束。
- 实际上,OAuth2 规范*要求* `grant_type` 字段使用固定值 `password`,但 `OAuth2PasswordRequestForm` 没有作强制约束。
+如需强制使用固定值 `password`,则不要用 `OAuth2PasswordRequestForm`,而是用 `OAuth2PasswordRequestFormStrict`。
- 如需强制使用固定值 `password`,则不要用 `OAuth2PasswordRequestForm`,而是用 `OAuth2PasswordRequestFormStrict`。
+///
* 可选的 `client_id`(本例未使用)
* 可选的 `client_secret`(本例未使用)
-!!! info "说明"
+/// info | "说明"
- `OAuth2PasswordRequestForm` 与 `OAuth2PasswordBearer` 一样,都不是 FastAPI 的特殊类。
+`OAuth2PasswordRequestForm` 与 `OAuth2PasswordBearer` 一样,都不是 FastAPI 的特殊类。
- **FastAPI** 把 `OAuth2PasswordBearer` 识别为安全方案。因此,可以通过这种方式把它添加至 OpenAPI。
+**FastAPI** 把 `OAuth2PasswordBearer` 识别为安全方案。因此,可以通过这种方式把它添加至 OpenAPI。
- 但 `OAuth2PasswordRequestForm` 只是可以自行编写的类依赖项,也可以直接声明 `Form` 参数。
+但 `OAuth2PasswordRequestForm` 只是可以自行编写的类依赖项,也可以直接声明 `Form` 参数。
- 但由于这种用例很常见,FastAPI 为了简便,就直接提供了对它的支持。
+但由于这种用例很常见,FastAPI 为了简便,就直接提供了对它的支持。
+
+///
### 使用表单数据
-!!! tip "提示"
+/// tip | "提示"
+
+`OAuth2PasswordRequestForm` 类依赖项的实例没有以空格分隔的长字符串属性 `scope`,但它支持 `scopes` 属性,由已发送的 scope 字符串列表组成。
- `OAuth2PasswordRequestForm` 类依赖项的实例没有以空格分隔的长字符串属性 `scope`,但它支持 `scopes` 属性,由已发送的 scope 字符串列表组成。
+本例没有使用 `scopes`,但开发者也可以根据需要使用该属性。
- 本例没有使用 `scopes`,但开发者也可以根据需要使用该属性。
+///
现在,即可使用表单字段 `username`,从(伪)数据库中获取用户数据。
)
```
-!!! info "说明"
+/// info | "说明"
- `user_dict` 的说明,详见[**更多模型**一章](../extra-models.md#user_indict){.internal-link target=_blank}。
+`user_dict` 的说明,详见[**更多模型**一章](../extra-models.md#user_indict){.internal-link target=_blank}。
+
+///
## 返回 Token
本例只是简单的演示,返回的 Token 就是 `username`,但这种方式极不安全。
-!!! tip "提示"
+/// tip | "提示"
+
+下一章介绍使用哈希密码和 <abbr title="JSON Web Tokens">JWT</abbr> Token 的真正安全机制。
- 下一章介绍使用哈希密码和 <abbr title="JSON Web Tokens">JWT</abbr> Token 的真正安全机制。
+但现在,仅关注所需的特定细节。
- 但现在,仅关注所需的特定细节。
+///
```Python hl_lines="85"
{!../../../docs_src/security/tutorial003.py!}
```
-!!! tip "提示"
+/// tip | "提示"
- 按规范的要求,应像本示例一样,返回带有 `access_token` 和 `token_type` 的 JSON 对象。
+按规范的要求,应像本示例一样,返回带有 `access_token` 和 `token_type` 的 JSON 对象。
- 这是开发者必须在代码中自行完成的工作,并且要确保使用这些 JSON 的键。
+这是开发者必须在代码中自行完成的工作,并且要确保使用这些 JSON 的键。
- 这几乎是唯一需要开发者牢记在心,并按规范要求正确执行的事。
+这几乎是唯一需要开发者牢记在心,并按规范要求正确执行的事。
- **FastAPI** 则负责处理其它的工作。
+**FastAPI** 则负责处理其它的工作。
+
+///
## 更新依赖项
{!../../../docs_src/security/tutorial003.py!}
```
-!!! info "说明"
+/// info | "说明"
+
+此处返回值为 `Bearer` 的响应头 `WWW-Authenticate` 也是规范的一部分。
- 此处返回值为 `Bearer` 的响应头 `WWW-Authenticate` 也是规范的一部分。
+任何 401**UNAUTHORIZED**HTTP(错误)状态码都应返回 `WWW-Authenticate` 响应头。
- 任何 401**UNAUTHORIZED**HTTP(错误)状态码都应返回 `WWW-Authenticate` 响应头。
+本例中,因为使用的是 Bearer Token,该响应头的值应为 `Bearer`。
- 本例中,因为使用的是 Bearer Token,该响应头的值应为 `Bearer`。
+实际上,忽略这个附加响应头,也不会有什么问题。
- 实际上,忽略这个附加响应头,也不会有什么问题。
+之所以在此提供这个附加响应头,是为了符合规范的要求。
- 之所以在此提供这个附加响应头,是为了符合规范的要求。
+说不定什么时候,就有工具用得上它,而且,开发者或用户也可能用得上。
- 说不定什么时候,就有工具用得上它,而且,开发者或用户也可能用得上。
+这就是遵循标准的好处……
- 这就是遵循标准的好处……
+///
## 实际效果
# SQL (关系型) 数据库
-!!! info
- 这些文档即将被更新。🎉
+/// info
- 当前版本假设Pydantic v1和SQLAlchemy版本小于2。
+这些文档即将被更新。🎉
- 新的文档将包括Pydantic v2以及 <a href="https://sqlmodel.tiangolo.com/" class="external-link" target="_blank">SQLModel</a>(也是基于SQLAlchemy),一旦SQLModel更新为为使用Pydantic v2。
+当前版本假设Pydantic v1和SQLAlchemy版本小于2。
+
+新的文档将包括Pydantic v2以及 <a href="https://sqlmodel.tiangolo.com/" class="external-link" target="_blank">SQLModel</a>(也是基于SQLAlchemy),一旦SQLModel更新为为使用Pydantic v2。
+
+///
**FastAPI**不需要你使用SQL(关系型)数据库。
稍后,对于您的产品级别的应用程序,您可能会要使用像**PostgreSQL**这样的数据库服务器。
-!!! tip
- 这儿有一个**FastAPI**和**PostgreSQL**的官方项目生成器,全部基于**Docker**,包括前端和更多工具:<a href="https://github.com/tiangolo/full-stack-fastapi-postgresql" class="external-link" target="_blank">https://github.com/tiangolo/full-stack-fastapi-postgresql</a>
+/// tip
+
+这儿有一个**FastAPI**和**PostgreSQL**的官方项目生成器,全部基于**Docker**,包括前端和更多工具:<a href="https://github.com/tiangolo/full-stack-fastapi-postgresql" class="external-link" target="_blank">https://github.com/tiangolo/full-stack-fastapi-postgresql</a>
+
+///
-!!! note
- 请注意,大部分代码是`SQLAlchemy`的标准代码,您可以用于任何框架。FastAPI特定的代码和往常一样少。
+/// note
+
+请注意,大部分代码是`SQLAlchemy`的标准代码,您可以用于任何框架。FastAPI特定的代码和往常一样少。
+
+///
## ORMs(对象关系映射)
以类似的方式,您也可以使用任何其他 ORM。
-!!! tip
- 在文档中也有一篇使用 Peewee 的等效的文章。
+/// tip
+
+在文档中也有一篇使用 Peewee 的等效的文章。
+
+///
## 文件结构
...并根据您的数据库数据和相关凭据(也适用于 MySQL、MariaDB 或任何其他)对其进行调整。
-!!! tip
+/// tip
+
+如果您想使用不同的数据库,这是就是您必须修改的地方。
- 如果您想使用不同的数据库,这是就是您必须修改的地方。
+///
### 创建 SQLAlchemy 引擎
...仅用于`SQLite`,在其他数据库不需要它。
-!!! info "技术细节"
+/// info | "技术细节"
+
+默认情况下,SQLite 只允许一个线程与其通信,假设有多个线程的话,也只将处理一个独立的请求。
- 默认情况下,SQLite 只允许一个线程与其通信,假设有多个线程的话,也只将处理一个独立的请求。
+这是为了防止意外地为不同的事物(不同的请求)共享相同的连接。
- 这是为了防止意外地为不同的事物(不同的请求)共享相同的连接。
+但是在 FastAPI 中,使用普通函数(def)时,多个线程可以为同一个请求与数据库交互,所以我们需要使用`connect_args={"check_same_thread": False}`来让SQLite允许这样。
- 但是在 FastAPI 中,使用普通函数(def)时,多个线程可以为同一个请求与数据库交互,所以我们需要使用`connect_args={"check_same_thread": False}`来让SQLite允许这样。
+此外,我们将确保每个请求都在依赖项中获得自己的数据库连接会话,因此不需要该默认机制。
- 此外,我们将确保每个请求都在依赖项中获得自己的数据库连接会话,因此不需要该默认机制。
+///
### 创建一个`SessionLocal`类
我们将使用我们之前创建的`Base`类来创建 SQLAlchemy 模型。
-!!! tip
- SQLAlchemy 使用的“**模型**”这个术语 来指代与数据库交互的这些类和实例。
+/// tip
- 而 Pydantic 也使用“模型”这个术语 来指代不同的东西,即数据验证、转换以及文档类和实例。
+SQLAlchemy 使用的“**模型**”这个术语 来指代与数据库交互的这些类和实例。
+
+而 Pydantic 也使用“模型”这个术语 来指代不同的东西,即数据验证、转换以及文档类和实例。
+
+///
从`database`(来自上面的`database.py`文件)导入`Base`。
现在让我们查看一下文件`sql_app/schemas.py`。
-!!! tip
- 为了避免 SQLAlchemy*模型*和 Pydantic*模型*之间的混淆,我们将有`models.py`(SQLAlchemy 模型的文件)和`schemas.py`( Pydantic 模型的文件)。
+/// tip
+
+为了避免 SQLAlchemy*模型*和 Pydantic*模型*之间的混淆,我们将有`models.py`(SQLAlchemy 模型的文件)和`schemas.py`( Pydantic 模型的文件)。
- 这些 Pydantic 模型或多或少地定义了一个“schema”(一个有效的数据形状)。
+这些 Pydantic 模型或多或少地定义了一个“schema”(一个有效的数据形状)。
- 因此,这将帮助我们在使用两者时避免混淆。
+因此,这将帮助我们在使用两者时避免混淆。
+
+///
### 创建初始 Pydantic*模型*/模式
但是为了安全起见,`password`不会出现在其他同类 Pydantic*模型*中,例如通过API读取一个用户数据时,它不应当包含在内。
-=== "Python 3.10+"
+//// tab | Python 3.10+
+
+```Python hl_lines="1 4-6 9-10 21-22 25-26"
+{!> ../../../docs_src/sql_databases/sql_app_py310/schemas.py!}
+```
+
+////
+
+//// tab | Python 3.9+
- ```Python hl_lines="1 4-6 9-10 21-22 25-26"
- {!> ../../../docs_src/sql_databases/sql_app_py310/schemas.py!}
- ```
+```Python hl_lines="3 6-8 11-12 23-24 27-28"
+{!> ../../../docs_src/sql_databases/sql_app_py39/schemas.py!}
+```
-=== "Python 3.9+"
+////
- ```Python hl_lines="3 6-8 11-12 23-24 27-28"
- {!> ../../../docs_src/sql_databases/sql_app_py39/schemas.py!}
- ```
+//// tab | Python 3.8+
-=== "Python 3.8+"
+```Python hl_lines="3 6-8 11-12 23-24 27-28"
+{!> ../../../docs_src/sql_databases/sql_app/schemas.py!}
+```
- ```Python hl_lines="3 6-8 11-12 23-24 27-28"
- {!> ../../../docs_src/sql_databases/sql_app/schemas.py!}
- ```
+////
#### SQLAlchemy 风格和 Pydantic 风格
不仅是这些项目的 ID,还有我们在 Pydantic*模型*中定义的用于读取项目的所有数据:`Item`.
-=== "Python 3.10+"
+//// tab | Python 3.10+
+
+```Python hl_lines="13-15 29-32"
+{!> ../../../docs_src/sql_databases/sql_app_py310/schemas.py!}
+```
+
+////
- ```Python hl_lines="13-15 29-32"
- {!> ../../../docs_src/sql_databases/sql_app_py310/schemas.py!}
- ```
+//// tab | Python 3.9+
-=== "Python 3.9+"
+```Python hl_lines="15-17 31-34"
+{!> ../../../docs_src/sql_databases/sql_app_py39/schemas.py!}
+```
- ```Python hl_lines="15-17 31-34"
- {!> ../../../docs_src/sql_databases/sql_app_py39/schemas.py!}
- ```
+////
-=== "Python 3.8+"
+//// tab | Python 3.8+
- ```Python hl_lines="15-17 31-34"
- {!> ../../../docs_src/sql_databases/sql_app/schemas.py!}
- ```
+```Python hl_lines="15-17 31-34"
+{!> ../../../docs_src/sql_databases/sql_app/schemas.py!}
+```
-!!! tip
- 请注意,读取用户(从 API 返回)时将使用不包括`password`的`User` Pydantic*模型*。
+////
+
+/// tip
+
+请注意,读取用户(从 API 返回)时将使用不包括`password`的`User` Pydantic*模型*。
+
+///
### 使用 Pydantic 的`orm_mode`
在`Config`类中,设置属性`orm_mode = True`。
-=== "Python 3.10+"
+//// tab | Python 3.10+
+
+```Python hl_lines="13 17-18 29 34-35"
+{!> ../../../docs_src/sql_databases/sql_app_py310/schemas.py!}
+```
+
+////
- ```Python hl_lines="13 17-18 29 34-35"
- {!> ../../../docs_src/sql_databases/sql_app_py310/schemas.py!}
- ```
+//// tab | Python 3.9+
-=== "Python 3.9+"
+```Python hl_lines="15 19-20 31 36-37"
+{!> ../../../docs_src/sql_databases/sql_app_py39/schemas.py!}
+```
+
+////
+
+//// tab | Python 3.8+
- ```Python hl_lines="15 19-20 31 36-37"
- {!> ../../../docs_src/sql_databases/sql_app_py39/schemas.py!}
- ```
+```Python hl_lines="15 19-20 31 36-37"
+{!> ../../../docs_src/sql_databases/sql_app/schemas.py!}
+```
+
+////
-=== "Python 3.8+"
+/// tip
- ```Python hl_lines="15 19-20 31 36-37"
- {!> ../../../docs_src/sql_databases/sql_app/schemas.py!}
- ```
+请注意,它使用`=`分配一个值,例如:
-!!! tip
- 请注意,它使用`=`分配一个值,例如:
+`orm_mode = True`
- `orm_mode = True`
+它不使用之前的`:`来类型声明。
- 它不使用之前的`:`来类型声明。
+这是设置配置值,而不是声明类型。
- 这是设置配置值,而不是声明类型。
+///
Pydantic`orm_mode`将告诉 Pydantic*模型*读取数据,即它不是一个`dict`,而是一个 ORM 模型(或任何其他具有属性的任意对象)。
{!../../../docs_src/sql_databases/sql_app/crud.py!}
```
-!!! tip
- 通过创建仅专用于与数据库交互(获取用户或项目)的函数,独立于*路径操作函数*,您可以更轻松地在多个部分中重用它们,并为它们添加单元测试。
+/// tip
+
+通过创建仅专用于与数据库交互(获取用户或项目)的函数,独立于*路径操作函数*,您可以更轻松地在多个部分中重用它们,并为它们添加单元测试。
+
+///
### 创建数据
{!../../../docs_src/sql_databases/sql_app/crud.py!}
```
-!!! tip
- SQLAlchemy 模型`User`包含一个`hashed_password`,它应该是一个包含散列的安全密码。
+/// tip
+
+SQLAlchemy 模型`User`包含一个`hashed_password`,它应该是一个包含散列的安全密码。
+
+但由于 API 客户端提供的是原始密码,因此您需要将其提取并在应用程序中生成散列密码。
+
+然后将hashed_password参数与要保存的值一起传递。
+
+///
+
+/// warning
- 但由于 API 客户端提供的是原始密码,因此您需要将其提取并在应用程序中生成散列密码。
+此示例不安全,密码未经过哈希处理。
- 然后将hashed_password参数与要保存的值一起传递。
+在现实生活中的应用程序中,您需要对密码进行哈希处理,并且永远不要以明文形式保存它们。
-!!! warning
- 此示例不安全,密码未经过哈希处理。
+有关更多详细信息,请返回教程中的安全部分。
- 在现实生活中的应用程序中,您需要对密码进行哈希处理,并且永远不要以明文形式保存它们。
+在这里,我们只关注数据库的工具和机制。
- 有关更多详细信息,请返回教程中的安全部分。
+///
- 在这里,我们只关注数据库的工具和机制。
+/// tip
-!!! tip
- 这里不是将每个关键字参数传递给Item并从Pydantic模型中读取每个参数,而是先生成一个字典,其中包含Pydantic模型的数据:
+这里不是将每个关键字参数传递给Item并从Pydantic模型中读取每个参数,而是先生成一个字典,其中包含Pydantic模型的数据:
- `item.dict()`
+`item.dict()`
- 然后我们将dict的键值对 作为关键字参数传递给 SQLAlchemy `Item`:
+然后我们将dict的键值对 作为关键字参数传递给 SQLAlchemy `Item`:
- `Item(**item.dict())`
+`Item(**item.dict())`
- 然后我们传递 Pydantic模型未提供的额外关键字参数`owner_id`:
+然后我们传递 Pydantic模型未提供的额外关键字参数`owner_id`:
- `Item(**item.dict(), owner_id=user_id)`
+`Item(**item.dict(), owner_id=user_id)`
+
+///
## 主**FastAPI**应用程序
以非常简单的方式创建数据库表:
-=== "Python 3.9+"
+//// tab | Python 3.9+
+
+```Python hl_lines="7"
+{!> ../../../docs_src/sql_databases/sql_app_py39/main.py!}
+```
+
+////
- ```Python hl_lines="7"
- {!> ../../../docs_src/sql_databases/sql_app_py39/main.py!}
- ```
+//// tab | Python 3.8+
-=== "Python 3.8+"
+```Python hl_lines="9"
+{!> ../../../docs_src/sql_databases/sql_app/main.py!}
+```
- ```Python hl_lines="9"
- {!> ../../../docs_src/sql_databases/sql_app/main.py!}
- ```
+////
#### Alembic 注意
我们的依赖项将创建一个新的 SQLAlchemy `SessionLocal`,它将在单个请求中使用,然后在请求完成后关闭它。
-=== "Python 3.9+"
+//// tab | Python 3.9+
+
+```Python hl_lines="13-18"
+{!> ../../../docs_src/sql_databases/sql_app_py39/main.py!}
+```
+
+////
- ```Python hl_lines="13-18"
- {!> ../../../docs_src/sql_databases/sql_app_py39/main.py!}
- ```
+//// tab | Python 3.8+
+
+```Python hl_lines="15-20"
+{!> ../../../docs_src/sql_databases/sql_app/main.py!}
+```
-=== "Python 3.8+"
+////
- ```Python hl_lines="15-20"
- {!> ../../../docs_src/sql_databases/sql_app/main.py!}
- ```
+/// info
-!!! info
- 我们将`SessionLocal()`请求的创建和处理放在一个`try`块中。
+我们将`SessionLocal()`请求的创建和处理放在一个`try`块中。
- 然后我们在finally块中关闭它。
+然后我们在finally块中关闭它。
- 通过这种方式,我们确保数据库会话在请求后始终关闭。即使在处理请求时出现异常。
+通过这种方式,我们确保数据库会话在请求后始终关闭。即使在处理请求时出现异常。
- 但是您不能从退出代码中引发另一个异常(在yield之后)。可以查阅 [Dependencies with yield and HTTPException](https://fastapi.tiangolo.com/zh/tutorial/dependencies/dependencies-with-yield/#dependencies-with-yield-and-httpexception)
+但是您不能从退出代码中引发另一个异常(在yield之后)。可以查阅 [Dependencies with yield and HTTPException](https://fastapi.tiangolo.com/zh/tutorial/dependencies/dependencies-with-yield/#dependencies-with-yield-and-httpexception)
+
+///
*然后,当在路径操作函数*中使用依赖项时,我们使用`Session`,直接从 SQLAlchemy 导入的类型声明它。
*这将为我们在路径操作函数*中提供更好的编辑器支持,因为编辑器将知道`db`参数的类型`Session`:
-=== "Python 3.9+"
+//// tab | Python 3.9+
- ```Python hl_lines="22 30 36 45 51"
- {!> ../../../docs_src/sql_databases/sql_app_py39/main.py!}
- ```
+```Python hl_lines="22 30 36 45 51"
+{!> ../../../docs_src/sql_databases/sql_app_py39/main.py!}
+```
-=== "Python 3.8+"
+////
- ```Python hl_lines="24 32 38 47 53"
- {!> ../../../docs_src/sql_databases/sql_app/main.py!}
- ```
+//// tab | Python 3.8+
-!!! info "技术细节"
- 参数`db`实际上是 type `SessionLocal`,但是这个类(用 创建`sessionmaker()`)是 SQLAlchemy 的“代理” `Session`,所以,编辑器并不真正知道提供了哪些方法。
+```Python hl_lines="24 32 38 47 53"
+{!> ../../../docs_src/sql_databases/sql_app/main.py!}
+```
- 但是通过将类型声明为Session,编辑器现在可以知道可用的方法(.add()、.query()、.commit()等)并且可以提供更好的支持(比如完成)。类型声明不影响实际对象。
+////
+
+/// info | "技术细节"
+
+参数`db`实际上是 type `SessionLocal`,但是这个类(用 创建`sessionmaker()`)是 SQLAlchemy 的“代理” `Session`,所以,编辑器并不真正知道提供了哪些方法。
+
+但是通过将类型声明为Session,编辑器现在可以知道可用的方法(.add()、.query()、.commit()等)并且可以提供更好的支持(比如完成)。类型声明不影响实际对象。
+
+///
### 创建您的**FastAPI** *路径操作*
现在,到了最后,编写标准的**FastAPI** *路径操作*代码。
-=== "Python 3.9+"
+//// tab | Python 3.9+
- ```Python hl_lines="21-26 29-32 35-40 43-47 50-53"
- {!> ../../../docs_src/sql_databases/sql_app_py39/main.py!}
- ```
+```Python hl_lines="21-26 29-32 35-40 43-47 50-53"
+{!> ../../../docs_src/sql_databases/sql_app_py39/main.py!}
+```
-=== "Python 3.8+"
+////
- ```Python hl_lines="23-28 31-34 37-42 45-49 52-55"
- {!> ../../../docs_src/sql_databases/sql_app/main.py!}
- ```
+//// tab | Python 3.8+
+
+```Python hl_lines="23-28 31-34 37-42 45-49 52-55"
+{!> ../../../docs_src/sql_databases/sql_app/main.py!}
+```
+
+////
我们在依赖项中的每个请求之前利用`yield`创建数据库会话,然后关闭它。
这样,我们就可以直接从*路径操作函数*内部调用`crud.get_user`并使用该会话,来进行对数据库操作。
-!!! tip
- 请注意,您返回的值是 SQLAlchemy 模型或 SQLAlchemy 模型列表。
+/// tip
+
+请注意,您返回的值是 SQLAlchemy 模型或 SQLAlchemy 模型列表。
+
+但是由于所有路径操作的response_model都使用 Pydantic模型/使用orm_mode模式,因此您的 Pydantic 模型中声明的数据将从它们中提取并返回给客户端,并进行所有正常的过滤和验证。
+
+///
+
+/// tip
- 但是由于所有路径操作的response_model都使用 Pydantic模型/使用orm_mode模式,因此您的 Pydantic 模型中声明的数据将从它们中提取并返回给客户端,并进行所有正常的过滤和验证。
+另请注意,`response_models`应当是标准 Python 类型,例如`List[schemas.Item]`.
-!!! tip
- 另请注意,`response_models`应当是标准 Python 类型,例如`List[schemas.Item]`.
+但是由于它的内容/参数List是一个 使用orm_mode模式的Pydantic模型,所以数据将被正常检索并返回给客户端,所以没有问题。
- 但是由于它的内容/参数List是一个 使用orm_mode模式的Pydantic模型,所以数据将被正常检索并返回给客户端,所以没有问题。
+///
### 关于 `def` 对比 `async def`
...
```
-!!! info
- 如果您需要异步连接到关系数据库,请参阅[Async SQL (Relational) Databases](https://fastapi.tiangolo.com/zh/advanced/async-sql-databases/)
+/// info
-!!! note "Very Technical Details"
- 如果您很好奇并且拥有深厚的技术知识,您可以在[Async](https://fastapi.tiangolo.com/zh/async/#very-technical-details)文档中查看有关如何处理 `async def`于`def`差别的技术细节。
+如果您需要异步连接到关系数据库,请参阅[Async SQL (Relational) Databases](https://fastapi.tiangolo.com/zh/advanced/async-sql-databases/)
+
+///
+
+/// note | "Very Technical Details"
+
+如果您很好奇并且拥有深厚的技术知识,您可以在[Async](https://fastapi.tiangolo.com/zh/async/#very-technical-details)文档中查看有关如何处理 `async def`于`def`差别的技术细节。
+
+///
## 迁移
* `sql_app/schemas.py`:
-=== "Python 3.10+"
+//// tab | Python 3.10+
- ```Python
- {!> ../../../docs_src/sql_databases/sql_app_py310/schemas.py!}
- ```
+```Python
+{!> ../../../docs_src/sql_databases/sql_app_py310/schemas.py!}
+```
-=== "Python 3.9+"
+////
- ```Python
- {!> ../../../docs_src/sql_databases/sql_app_py39/schemas.py!}
- ```
+//// tab | Python 3.9+
-=== "Python 3.8+"
+```Python
+{!> ../../../docs_src/sql_databases/sql_app_py39/schemas.py!}
+```
+
+////
+
+//// tab | Python 3.8+
+
+```Python
+{!> ../../../docs_src/sql_databases/sql_app/schemas.py!}
+```
- ```Python
- {!> ../../../docs_src/sql_databases/sql_app/schemas.py!}
- ```
+////
* `sql_app/crud.py`:
* `sql_app/main.py`:
-=== "Python 3.9+"
+//// tab | Python 3.9+
+
+```Python
+{!> ../../../docs_src/sql_databases/sql_app_py39/main.py!}
+```
+
+////
- ```Python
- {!> ../../../docs_src/sql_databases/sql_app_py39/main.py!}
- ```
+//// tab | Python 3.8+
-=== "Python 3.8+"
+```Python
+{!> ../../../docs_src/sql_databases/sql_app/main.py!}
+```
- ```Python
- {!> ../../../docs_src/sql_databases/sql_app/main.py!}
- ```
+////
## 执行项目
您可以复制这些代码并按原样使用它。
-!!! info
+/// info
+
+事实上,这里的代码只是大多数测试代码的一部分。
- 事实上,这里的代码只是大多数测试代码的一部分。
+///
你可以用 Uvicorn 运行它:
我们要添加的中间件(只是一个函数)将为每个请求创建一个新的 SQLAlchemy`SessionLocal`,将其添加到请求中,然后在请求完成后关闭它。
-=== "Python 3.9+"
+//// tab | Python 3.9+
+
+```Python hl_lines="12-20"
+{!> ../../../docs_src/sql_databases/sql_app_py39/alt_main.py!}
+```
+
+////
+
+//// tab | Python 3.8+
- ```Python hl_lines="12-20"
- {!> ../../../docs_src/sql_databases/sql_app_py39/alt_main.py!}
- ```
+```Python hl_lines="14-22"
+{!> ../../../docs_src/sql_databases/sql_app/alt_main.py!}
+```
+
+////
-=== "Python 3.8+"
+/// info
- ```Python hl_lines="14-22"
- {!> ../../../docs_src/sql_databases/sql_app/alt_main.py!}
- ```
+我们将`SessionLocal()`请求的创建和处理放在一个`try`块中。
-!!! info
- 我们将`SessionLocal()`请求的创建和处理放在一个`try`块中。
+然后我们在finally块中关闭它。
- 然后我们在finally块中关闭它。
+通过这种方式,我们确保数据库会话在请求后始终关闭,即使在处理请求时出现异常也会关闭。
- 通过这种方式,我们确保数据库会话在请求后始终关闭,即使在处理请求时出现异常也会关闭。
+///
### 关于`request.state`
* 将为每个请求创建一个连接。
* 即使处理该请求的*路径操作*不需要数据库。
-!!! tip
- 最好使用带有yield的依赖项,如果这足够满足用例需求
+/// tip
+
+最好使用带有yield的依赖项,如果这足够满足用例需求
+
+///
+
+/// info
+
+带有`yield`的依赖项是最近刚加入**FastAPI**中的。
-!!! info
- 带有`yield`的依赖项是最近刚加入**FastAPI**中的。
+所以本教程的先前版本只有带有中间件的示例,并且可能有多个应用程序使用中间件进行数据库会话管理。
- 所以本教程的先前版本只有带有中间件的示例,并且可能有多个应用程序使用中间件进行数据库会话管理。
+///
{!../../../docs_src/static_files/tutorial001.py!}
```
-!!! note "技术细节"
- 你也可以用 `from starlette.staticfiles import StaticFiles`。
+/// note | "技术细节"
- **FastAPI** 提供了和 `starlette.staticfiles` 相同的 `fastapi.staticfiles` ,只是为了方便你,开发者。但它确实来自Starlette。
+你也可以用 `from starlette.staticfiles import StaticFiles`。
+
+**FastAPI** 提供了和 `starlette.staticfiles` 相同的 `fastapi.staticfiles` ,只是为了方便你,开发者。但它确实来自Starlette。
+
+///
### 什么是"挂载"(Mounting)
## 使用 `TestClient`
-!!! info "信息"
- 要使用 `TestClient`,先要安装 <a href="https://www.python-httpx.org" class="external-link" target="_blank">`httpx`</a>.
+/// info | "信息"
- 例:`pip install httpx`.
+要使用 `TestClient`,先要安装 <a href="https://www.python-httpx.org" class="external-link" target="_blank">`httpx`</a>.
+
+例:`pip install httpx`.
+
+///
导入 `TestClient`.
{!../../../docs_src/app_testing/tutorial001.py!}
```
-!!! tip "提示"
- 注意测试函数是普通的 `def`,不是 `async def`。
+/// tip | "提示"
+
+注意测试函数是普通的 `def`,不是 `async def`。
+
+还有client的调用也是普通的调用,不是用 `await`。
+
+这让你可以直接使用 `pytest` 而不会遇到麻烦。
+
+///
+
+/// note | "技术细节"
+
+你也可以用 `from starlette.testclient import TestClient`。
- 还有client的调用也是普通的调用,不是用 `await`。
+**FastAPI** 提供了和 `starlette.testclient` 一样的 `fastapi.testclient`,只是为了方便开发者。但它直接来自Starlette。
- 这让你可以直接使用 `pytest` 而不会遇到麻烦。
+///
-!!! note "技术细节"
- 你也可以用 `from starlette.testclient import TestClient`。
+/// tip | "提示"
- **FastAPI** 提供了和 `starlette.testclient` 一样的 `fastapi.testclient`,只是为了方便开发者。但它直接来自Starlette。
+除了发送请求之外,如果你还想测试时在FastAPI应用中调用 `async` 函数(例如异步数据库函数), 可以在高级教程中看下 [Async Tests](../advanced/async-tests.md){.internal-link target=_blank} 。
-!!! tip "提示"
- 除了发送请求之外,如果你还想测试时在FastAPI应用中调用 `async` 函数(例如异步数据库函数), 可以在高级教程中看下 [Async Tests](../advanced/async-tests.md){.internal-link target=_blank} 。
+///
## 分离测试
所有*路径操作* 都需要一个`X-Token` 头。
-=== "Python 3.10+"
+//// tab | Python 3.10+
- ```Python
- {!> ../../../docs_src/app_testing/app_b_an_py310/main.py!}
- ```
+```Python
+{!> ../../../docs_src/app_testing/app_b_an_py310/main.py!}
+```
-=== "Python 3.9+"
+////
- ```Python
- {!> ../../../docs_src/app_testing/app_b_an_py39/main.py!}
- ```
+//// tab | Python 3.9+
-=== "Python 3.8+"
+```Python
+{!> ../../../docs_src/app_testing/app_b_an_py39/main.py!}
+```
- ```Python
- {!> ../../../docs_src/app_testing/app_b_an/main.py!}
- ```
+////
-=== "Python 3.10+ non-Annotated"
+//// tab | Python 3.8+
+
+```Python
+{!> ../../../docs_src/app_testing/app_b_an/main.py!}
+```
- !!! tip "提示"
- Prefer to use the `Annotated` version if possible.
+////
- ```Python
- {!> ../../../docs_src/app_testing/app_b_py310/main.py!}
- ```
+//// tab | Python 3.10+ non-Annotated
-=== "Python 3.8+ non-Annotated"
+/// tip | "提示"
- !!! tip "提示"
- Prefer to use the `Annotated` version if possible.
+Prefer to use the `Annotated` version if possible.
- ```Python
- {!> ../../../docs_src/app_testing/app_b/main.py!}
- ```
+///
+
+```Python
+{!> ../../../docs_src/app_testing/app_b_py310/main.py!}
+```
+
+////
+
+//// tab | Python 3.8+ non-Annotated
+
+/// tip | "提示"
+
+Prefer to use the `Annotated` version if possible.
+
+///
+
+```Python
+{!> ../../../docs_src/app_testing/app_b/main.py!}
+```
+
+////
### 扩展后的测试文件
关于如何传数据给后端的更多信息 (使用`httpx` 或 `TestClient`),请查阅 <a href="https://www.python-httpx.org" class="external-link" target="_blank">HTTPX 文档</a>.
-!!! info "信息"
- 注意 `TestClient` 接收可以被转化为JSON的数据,而不是Pydantic模型。
+/// info | "信息"
+
+注意 `TestClient` 接收可以被转化为JSON的数据,而不是Pydantic模型。
+
+如果你在测试中有一个Pydantic模型,并且你想在测试时发送它的数据给应用,你可以使用在[JSON Compatible Encoder](encoder.md){.internal-link target=_blank}介绍的`jsonable_encoder` 。
- 如果你在测试中有一个Pydantic模型,并且你想在测试时发送它的数据给应用,你可以使用在[JSON Compatible Encoder](encoder.md){.internal-link target=_blank}介绍的`jsonable_encoder` 。
+///
## 运行起来
--- /dev/null
+git+https://${TOKEN}@github.com/squidfunk/mkdocs-material-insiders.git@9.5.30-insiders-4.53.11
+git+https://${TOKEN}@github.com/pawamoy-insiders/griffe-typing-deprecated.git
+git+https://${TOKEN}@github.com/pawamoy-insiders/mkdocstrings-python.git
mkdocs-material==9.5.18
mdx-include >=1.4.1,<2.0.0
mkdocs-redirects>=1.2.1,<1.3.0
-typer >=0.12.0
+typer == 0.12.3
pyyaml >=5.3.1,<7.0.0
# For Material for MkDocs, Chinese search
jieba==0.42.1
# For image processing by Material for MkDocs
pillow==10.3.0
# For image processing by Material for MkDocs
-cairosvg==2.7.0
-mkdocstrings[python]==0.24.3
-griffe-typingdoc==0.2.2
+cairosvg==2.7.1
+mkdocstrings[python]==0.25.1
+griffe-typingdoc==0.2.5
# For griffe, it formats with black
black==24.3.0
mkdocs-macros-plugin==1.0.5
from pathlib import Path
from typing import Any, Dict, List, Optional, Union
-import mkdocs.commands.build
-import mkdocs.commands.serve
-import mkdocs.config
import mkdocs.utils
import typer
import yaml
pre_content = content[frontmatter_end:pre_end]
post_content = content[post_start:]
new_content = pre_content + message + post_content
+ # Remove content between <!-- only-mkdocs --> and <!-- /only-mkdocs -->
+ new_content = re.sub(
+ r"<!-- only-mkdocs -->.*?<!-- /only-mkdocs -->",
+ "",
+ new_content,
+ flags=re.DOTALL,
+ )
return new_content
en.
"""
# Enable line numbers during local development to make it easier to highlight
- os.environ["LINENUMS"] = "true"
if lang is None:
lang = "en"
lang_path: Path = docs_path / lang
- os.chdir(lang_path)
- mkdocs.commands.serve.serve(dev_addr="127.0.0.1:8008")
+ subprocess.run(
+ ["mkdocs", "serve", "--dev-addr", "127.0.0.1:8008", "--dirty"],
+ env={**os.environ, "LINENUMS": "true"},
+ cwd=lang_path,
+ check=True,
+ )
def get_updated_config_content() -> Dict[str, Any]: