diff --git a/.github/workflows/build-docs.yml b/.github/workflows/build-docs.yml
index 9b167ee66c..4ff5e26cbf 100644
--- a/.github/workflows/build-docs.yml
+++ b/.github/workflows/build-docs.yml
@@ -45,7 +45,7 @@ jobs:
uses: actions/setup-python@v5
with:
python-version: "3.11"
- - uses: actions/cache@v3
+ - uses: actions/cache@v4
id: cache
with:
path: ${{ env.pythonLocation }}
@@ -86,7 +86,7 @@ jobs:
uses: actions/setup-python@v5
with:
python-version: "3.11"
- - uses: actions/cache@v3
+ - uses: actions/cache@v4
id: cache
with:
path: ${{ env.pythonLocation }}
@@ -102,7 +102,7 @@ jobs:
pip install git+https://${{ secrets.FASTAPI_MKDOCS_MATERIAL_INSIDERS }}@github.com/pawamoy-insiders/mkdocstrings-python.git
- name: Update Languages
run: python ./scripts/docs.py update-languages
- - uses: actions/cache@v3
+ - uses: actions/cache@v4
with:
key: mkdocs-cards-${{ matrix.lang }}-${{ github.ref }}
path: docs/${{ matrix.lang }}/.cache
diff --git a/.github/workflows/publish.yml b/.github/workflows/publish.yml
index 899e49057f..a5cbf6da42 100644
--- a/.github/workflows/publish.yml
+++ b/.github/workflows/publish.yml
@@ -21,12 +21,17 @@ jobs:
# Issue ref: https://github.com/actions/setup-python/issues/436
# cache: "pip"
# cache-dependency-path: pyproject.toml
+ - uses: actions/cache@v4
+ id: cache
+ with:
+ path: ${{ env.pythonLocation }}
+ key: ${{ runner.os }}-python-${{ env.pythonLocation }}-${{ hashFiles('pyproject.toml') }}-publish
- name: Install build dependencies
run: pip install build
- name: Build distribution
run: python -m build
- name: Publish
- uses: pypa/gh-action-pypi-publish@v1.8.11
+ uses: pypa/gh-action-pypi-publish@v1.8.14
with:
password: ${{ secrets.PYPI_API_TOKEN }}
- name: Dump GitHub context
diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml
index b6b1736851..fe1e419d68 100644
--- a/.github/workflows/test.yml
+++ b/.github/workflows/test.yml
@@ -8,6 +8,9 @@ on:
types:
- opened
- synchronize
+ schedule:
+ # cron every week on monday
+ - cron: "0 0 * * 1"
jobs:
lint:
@@ -25,11 +28,11 @@ jobs:
# Issue ref: https://github.com/actions/setup-python/issues/436
# cache: "pip"
# cache-dependency-path: pyproject.toml
- - uses: actions/cache@v3
+ - uses: actions/cache@v4
id: cache
with:
path: ${{ env.pythonLocation }}
- key: ${{ runner.os }}-python-${{ env.pythonLocation }}-pydantic-v2-${{ hashFiles('pyproject.toml', 'requirements-tests.txt', 'requirements-docs-tests.txt') }}-test-v07
+ key: ${{ runner.os }}-python-${{ env.pythonLocation }}-pydantic-v2-${{ hashFiles('pyproject.toml', 'requirements-tests.txt', 'requirements-docs-tests.txt') }}-test-v08
- name: Install Dependencies
if: steps.cache.outputs.cache-hit != 'true'
run: pip install -r requirements-tests.txt
@@ -63,11 +66,11 @@ jobs:
# Issue ref: https://github.com/actions/setup-python/issues/436
# cache: "pip"
# cache-dependency-path: pyproject.toml
- - uses: actions/cache@v3
+ - uses: actions/cache@v4
id: cache
with:
path: ${{ env.pythonLocation }}
- key: ${{ runner.os }}-python-${{ env.pythonLocation }}-${{ matrix.pydantic-version }}-${{ hashFiles('pyproject.toml', 'requirements-tests.txt', 'requirements-docs-tests.txt') }}-test-v07
+ key: ${{ runner.os }}-python-${{ env.pythonLocation }}-${{ matrix.pydantic-version }}-${{ hashFiles('pyproject.toml', 'requirements-tests.txt', 'requirements-docs-tests.txt') }}-test-v08
- name: Install Dependencies
if: steps.cache.outputs.cache-hit != 'true'
run: pip install -r requirements-tests.txt
diff --git a/docs/az/docs/fastapi-people.md b/docs/az/docs/fastapi-people.md
index 2ca8e109ee..60494f1915 100644
--- a/docs/az/docs/fastapi-people.md
+++ b/docs/az/docs/fastapi-people.md
@@ -119,7 +119,7 @@ Başqalarının Pull Request-lərinə **Ən çox rəy verənlər** 🕵️ kodun
Bunlar **Sponsorlar**dır. 😎
-Onlar mənim **FastAPI** (və digər) işlərimi əsasən GitHub Sponsorlar vasitəsilə dəstəkləyirlər.
+Onlar mənim **FastAPI** (və digər) işlərimi əsasən GitHub Sponsorlar vasitəsilə dəstəkləyirlər.
{% if sponsors %}
diff --git a/docs/bn/docs/python-types.md b/docs/bn/docs/python-types.md
new file mode 100644
index 0000000000..6923363ddb
--- /dev/null
+++ b/docs/bn/docs/python-types.md
@@ -0,0 +1,537 @@
+# পাইথন এর টাইপ্স পরিচিতি
+
+Python-এ ঐচ্ছিক "টাইপ হিন্ট" (যা "টাইপ অ্যানোটেশন" নামেও পরিচিত) এর জন্য সাপোর্ট রয়েছে।
+
+এই **"টাইপ হিন্ট"** বা অ্যানোটেশনগুলি এক ধরণের বিশেষ সিনট্যাক্স যা একটি ভেরিয়েবলের টাইপ ঘোষণা করতে দেয়।
+
+ভেরিয়েবলগুলির জন্য টাইপ ঘোষণা করলে, এডিটর এবং টুলগুলি আপনাকে আরও ভালো সাপোর্ট দিতে পারে।
+
+এটি পাইথন টাইপ হিন্ট সম্পর্কে একটি দ্রুত **টিউটোরিয়াল / রিফ্রেশার** মাত্র। এটি **FastAPI** এর সাথে ব্যবহার করার জন্য শুধুমাত্র ন্যূনতম প্রয়োজনীয়তা কভার করে... যা আসলে খুব একটা বেশি না।
+
+**FastAPI** এই টাইপ হিন্টগুলির উপর ভিত্তি করে নির্মিত, যা এটিকে অনেক সুবিধা এবং লাভ প্রদান করে।
+
+তবে, আপনি যদি কখনো **FastAPI** ব্যবহার নাও করেন, তবুও এগুলি সম্পর্কে একটু শেখা আপনার উপকারে আসবে।
+
+!!! Note
+ যদি আপনি একজন Python বিশেষজ্ঞ হন, এবং টাইপ হিন্ট সম্পর্কে সবকিছু জানেন, তাহলে পরবর্তী অধ্যায়ে চলে যান।
+
+## প্রেরণা
+
+চলুন একটি সাধারণ উদাহরণ দিয়ে শুরু করি:
+
+```Python
+{!../../../docs_src/python_types/tutorial001.py!}
+```
+
+এই প্রোগ্রামটি কল করলে আউটপুট হয়:
+
+```
+John Doe
+```
+
+ফাংশনটি নিম্নলিখিত কাজ করে:
+
+* `first_name` এবং `last_name` নেয়।
+* প্রতিটির প্রথম অক্ষরকে `title()` ব্যবহার করে বড় হাতের অক্ষরে রূপান্তর করে।
+* তাদেরকে মাঝখানে একটি স্পেস দিয়ে concatenate করে।
+
+```Python hl_lines="2"
+{!../../../docs_src/python_types/tutorial001.py!}
+```
+
+### এটি সম্পাদনা করুন
+
+এটি একটি খুব সাধারণ প্রোগ্রাম।
+
+কিন্তু এখন কল্পনা করুন যে আপনি এটি শুরু থেকে লিখছিলেন।
+
+এক পর্যায়ে আপনি ফাংশনের সংজ্ঞা শুরু করেছিলেন, আপনার প্যারামিটারগুলি প্রস্তুত ছিল...
+
+কিন্তু তারপর আপনাকে "সেই method কল করতে হবে যা প্রথম অক্ষরকে বড় হাতের অক্ষরে রূপান্তর করে"।
+
+এটা কি `upper` ছিল? নাকি `uppercase`? `first_uppercase`? `capitalize`?
+
+তারপর, আপনি পুরোনো প্রোগ্রামারের বন্ধু, এডিটর অটোকমপ্লিশনের সাহায্যে নেওয়ার চেষ্টা করেন।
+
+আপনি ফাংশনের প্রথম প্যারামিটার `first_name` টাইপ করেন, তারপর একটি ডট (`.`) টাইপ করেন এবং `Ctrl+Space` চাপেন অটোকমপ্লিশন ট্রিগার করার জন্য।
+
+কিন্তু, দুর্ভাগ্যবশত, আপনি কিছুই উপযোগী পান না:
+
+
+
+### টাইপ যোগ করুন
+
+আসুন আগের সংস্করণ থেকে একটি লাইন পরিবর্তন করি।
+
+আমরা ঠিক এই অংশটি পরিবর্তন করব অর্থাৎ ফাংশনের প্যারামিটারগুলি, এইগুলি:
+
+```Python
+ first_name, last_name
+```
+
+থেকে এইগুলি:
+
+```Python
+ first_name: str, last_name: str
+```
+
+ব্যাস।
+
+এগুলিই "টাইপ হিন্ট":
+
+```Python hl_lines="1"
+{!../../../docs_src/python_types/tutorial002.py!}
+```
+
+এটি ডিফল্ট ভ্যালু ঘোষণা করার মত নয় যেমন:
+
+```Python
+ first_name="john", last_name="doe"
+```
+
+এটি একটি ভিন্ন জিনিস।
+
+আমরা সমান (`=`) নয়, কোলন (`:`) ব্যবহার করছি।
+
+এবং টাইপ হিন্ট যোগ করা সাধারণত তেমন কিছু পরিবর্তন করে না যা টাইপ হিন্ট ছাড়াই ঘটত।
+
+কিন্তু এখন, কল্পনা করুন আপনি আবার সেই ফাংশন তৈরির মাঝখানে আছেন, কিন্তু টাইপ হিন্ট সহ।
+
+একই পর্যায়ে, আপনি অটোকমপ্লিট ট্রিগার করতে `Ctrl+Space` চাপেন এবং আপনি দেখতে পান:
+
+
+
+এর সাথে, আপনি অপশনগুলি দেখে, স্ক্রল করতে পারেন, যতক্ষণ না আপনি এমন একটি অপশন খুঁজে পান যা কিছু মনে পরিয়ে দেয়:
+
+
+
+## আরও প্রেরণা
+
+এই ফাংশনটি দেখুন, এটিতে ইতিমধ্যে টাইপ হিন্ট রয়েছে:
+
+```Python hl_lines="1"
+{!../../../docs_src/python_types/tutorial003.py!}
+```
+
+এডিটর ভেরিয়েবলগুলির টাইপ জানার কারণে, আপনি শুধুমাত্র অটোকমপ্লিশনই পান না, আপনি এরর চেকও পান:
+
+
+
+এখন আপনি জানেন যে আপনাকে এটি ঠিক করতে হবে, `age`-কে একটি স্ট্রিং হিসেবে রূপান্তর করতে `str(age)` ব্যবহার করতে হবে:
+
+```Python hl_lines="2"
+{!../../../docs_src/python_types/tutorial004.py!}
+```
+
+## টাইপ ঘোষণা
+
+আপনি এতক্ষন টাইপ হিন্ট ঘোষণা করার মূল স্থানটি দেখে ফেলেছেন-- ফাংশন প্যারামিটার হিসেবে।
+
+সাধারণত এটি **FastAPI** এর ক্ষেত্রেও একই।
+
+### সিম্পল টাইপ
+
+আপনি `str` ছাড়াও সমস্ত স্ট্যান্ডার্ড পাইথন টাইপ ঘোষণা করতে পারেন।
+
+উদাহরণস্বরূপ, আপনি এগুলো ব্যবহার করতে পারেন:
+
+* `int`
+* `float`
+* `bool`
+* `bytes`
+
+```Python hl_lines="1"
+{!../../../docs_src/python_types/tutorial005.py!}
+```
+
+### টাইপ প্যারামিটার সহ জেনেরিক টাইপ
+
+কিছু ডাটা স্ট্রাকচার অন্যান্য মান ধারণ করতে পারে, যেমন `dict`, `list`, `set` এবং `tuple`। এবং অভ্যন্তরীণ মানগুলোরও নিজেদের টাইপ থাকতে পারে।
+
+এই ধরনের টাইপগুলিকে বলা হয় "**জেনেরিক**" টাইপ এবং এগুলিকে তাদের অভ্যন্তরীণ টাইপগুলি সহ ঘোষণা করা সম্ভব।
+
+এই টাইপগুলি এবং অভ্যন্তরীণ টাইপগুলি ঘোষণা করতে, আপনি Python মডিউল `typing` ব্যবহার করতে পারেন। এটি বিশেষভাবে এই টাইপ হিন্টগুলি সমর্থন করার জন্য রয়েছে।
+
+#### Python এর নতুন সংস্করণ
+
+`typing` ব্যবহার করা সিনট্যাক্সটি Python 3.6 থেকে সর্বশেষ সংস্করণগুলি পর্যন্ত, অর্থাৎ Python 3.9, Python 3.10 ইত্যাদি সহ সকল সংস্করণের সাথে **সামঞ্জস্যপূর্ণ**।
+
+Python যত এগিয়ে যাচ্ছে, **নতুন সংস্করণগুলি** এই টাইপ অ্যানোটেশনগুলির জন্য তত উন্নত সাপোর্ট নিয়ে আসছে এবং অনেক ক্ষেত্রে আপনাকে টাইপ অ্যানোটেশন ঘোষণা করতে `typing` মডিউল ইম্পোর্ট এবং ব্যবহার করার প্রয়োজন হবে না।
+
+যদি আপনি আপনার প্রজেক্টের জন্য Python-এর আরও সাম্প্রতিক সংস্করণ নির্বাচন করতে পারেন, তাহলে আপনি সেই অতিরিক্ত সরলতা থেকে সুবিধা নিতে পারবেন।
+
+ডক্সে রয়েছে Python-এর প্রতিটি সংস্করণের সাথে সামঞ্জস্যপূর্ণ উদাহরণগুলি (যখন পার্থক্য আছে)।
+
+উদাহরণস্বরূপ, "**Python 3.6+**" মানে এটি Python 3.6 বা তার উপরে সামঞ্জস্যপূর্ণ (যার মধ্যে 3.7, 3.8, 3.9, 3.10, ইত্যাদি অন্তর্ভুক্ত)। এবং "**Python 3.9+**" মানে এটি Python 3.9 বা তার উপরে সামঞ্জস্যপূর্ণ (যার মধ্যে 3.10, ইত্যাদি অন্তর্ভুক্ত)।
+
+যদি আপনি Python-এর **সর্বশেষ সংস্করণগুলি ব্যবহার করতে পারেন**, তাহলে সর্বশেষ সংস্করণের জন্য উদাহরণগুলি ব্যবহার করুন, সেগুলি আপনাকে **সর্বোত্তম এবং সহজতম সিনট্যাক্স** প্রদান করবে, যেমন, "**Python 3.10+**"।
+
+#### লিস্ট
+
+উদাহরণস্বরূপ, একটি ভেরিয়েবলকে `str`-এর একটি `list` হিসেবে সংজ্ঞায়িত করা যাক।
+
+=== "Python 3.9+"
+
+ ভেরিয়েবলটি ঘোষণা করুন, একই কোলন (`:`) সিনট্যাক্স ব্যবহার করে।
+
+ টাইপ হিসেবে, `list` ব্যবহার করুন।
+
+ যেহেতু লিস্ট এমন একটি টাইপ যা অভ্যন্তরীণ টাইপগুলি ধারণ করে, আপনি তাদের স্কোয়ার ব্রাকেটের ভিতরে ব্যবহার করুন:
+
+ ```Python hl_lines="1"
+ {!> ../../../docs_src/python_types/tutorial006_py39.py!}
+ ```
+
+=== "Python 3.8+"
+
+ `typing` থেকে `List` (বড় হাতের `L` দিয়ে) ইমপোর্ট করুন:
+
+ ``` Python hl_lines="1"
+ {!> ../../../docs_src/python_types/tutorial006.py!}
+ ```
+
+ ভেরিয়েবলটি ঘোষণা করুন, একই কোলন (`:`) সিনট্যাক্স ব্যবহার করে।
+
+ টাইপ হিসেবে, `typing` থেকে আপনার ইম্পোর্ট করা `List` ব্যবহার করুন।
+
+ যেহেতু লিস্ট এমন একটি টাইপ যা অভ্যন্তরীণ টাইপগুলি ধারণ করে, আপনি তাদের স্কোয়ার ব্রাকেটের ভিতরে করুন:
+
+ ```Python hl_lines="4"
+ {!> ../../../docs_src/python_types/tutorial006.py!}
+ ```
+
+!!! Info
+ স্কোয়ার ব্রাকেট এর ভিতরে ব্যবহৃত এইসব অভন্তরীন টাইপগুলোকে "ইন্টারনাল টাইপ" বলে।
+
+ এই উদাহরণে, এটি হচ্ছে `List`(অথবা পাইথন ৩.৯ বা তার উপরের সংস্করণের ক্ষেত্রে `list`) এ পাস করা টাইপ প্যারামিটার।
+
+এর অর্থ হচ্ছে: "ভেরিয়েবল `items` একটি `list`, এবং এই লিস্টের প্রতিটি আইটেম একটি `str`।"
+
+!!! Tip
+ যদি আপনি Python 3.9 বা তার উপরে ব্যবহার করেন, আপনার `typing` থেকে `List` আমদানি করতে হবে না, আপনি সাধারণ `list` ওই টাইপের পরিবর্তে ব্যবহার করতে পারেন।
+
+এর মাধ্যমে, আপনার এডিটর লিস্ট থেকে আইটেম প্রসেস করার সময় সাপোর্ট প্রদান করতে পারবে:
+
+
+
+টাইপগুলি ছাড়া, এটি করা প্রায় অসম্ভব।
+
+লক্ষ্য করুন যে ভেরিয়েবল `item` হল `items` লিস্টের একটি এলিমেন্ট।
+
+তবুও, এডিটর জানে যে এটি একটি `str`, এবং তার জন্য সাপোর্ট প্রদান করে।
+
+#### টাপল এবং সেট
+
+আপনি `tuple` এবং `set` ঘোষণা করার জন্য একই প্রক্রিয়া অনুসরণ করবেন:
+
+=== "Python 3.9+"
+
+ ```Python hl_lines="1"
+ {!> ../../../docs_src/python_types/tutorial007_py39.py!}
+ ```
+
+=== "Python 3.8+"
+
+ ```Python hl_lines="1 4"
+ {!> ../../../docs_src/python_types/tutorial007.py!}
+ ```
+
+এর মানে হল:
+
+* ভেরিয়েবল `items_t` হল একটি `tuple` যা ৩টি আইটেম ধারণ করে, একটি `int`, অন্য একটি `int`, এবং একটি `str`।
+* ভেরিয়েবল `items_s` হল একটি `set`, এবং এর প্রতিটি আইটেম হল `bytes` টাইপের।
+
+#### ডিক্ট
+
+একটি `dict` সংজ্ঞায়িত করতে, আপনি ২টি টাইপ প্যারামিটার কমা দ্বারা পৃথক করে দেবেন।
+
+প্রথম টাইপ প্যারামিটারটি হল `dict`-এর কীগুলির জন্য।
+
+দ্বিতীয় টাইপ প্যারামিটারটি হল `dict`-এর মানগুলির জন্য:
+
+=== "Python 3.9+"
+
+ ```Python hl_lines="1"
+ {!> ../../../docs_src/python_types/tutorial008_py39.py!}
+ ```
+
+=== "Python 3.8+"
+
+ ```Python hl_lines="1 4"
+ {!> ../../../docs_src/python_types/tutorial008.py!}
+ ```
+
+
+এর মানে হল:
+
+* ভেরিয়েবল `prices` হল একটি `dict`:
+ * এই `dict`-এর কীগুলি হল `str` টাইপের (ধরা যাক, প্রতিটি আইটেমের নাম)।
+ * এই `dict`-এর মানগুলি হল `float` টাইপের (ধরা যাক, প্রতিটি আইটেমের দাম)।
+
+#### ইউনিয়ন
+
+আপনি একটি ভেরিয়েবলকে এমনভাবে ঘোষণা করতে পারেন যেন তা **একাধিক টাইপের** হয়, উদাহরণস্বরূপ, একটি `int` অথবা `str`।
+
+Python 3.6 এবং তার উপরের সংস্করণগুলিতে (Python 3.10 অন্তর্ভুক্ত) আপনি `typing` থেকে `Union` টাইপ ব্যবহার করতে পারেন এবং স্কোয়ার ব্র্যাকেটের মধ্যে গ্রহণযোগ্য টাইপগুলি রাখতে পারেন।
+
+Python 3.10-এ একটি **নতুন সিনট্যাক্স** আছে যেখানে আপনি সম্ভাব্য টাইপগুলিকে একটি ভার্টিকাল বার (`|`) দ্বারা পৃথক করতে পারেন।
+
+=== "Python 3.10+"
+
+ ```Python hl_lines="1"
+ {!> ../../../docs_src/python_types/tutorial008b_py310.py!}
+ ```
+
+=== "Python 3.8+"
+
+ ```Python hl_lines="1 4"
+ {!> ../../../docs_src/python_types/tutorial008b.py!}
+ ```
+
+উভয় ক্ষেত্রেই এর মানে হল যে `item` হতে পারে একটি `int` অথবা `str`।
+
+#### সম্ভবত `None`
+
+আপনি এমনভাবে ঘোষণা করতে পারেন যে একটি মান হতে পারে এক টাইপের, যেমন `str`, আবার এটি `None`-ও হতে পারে।
+
+Python 3.6 এবং তার উপরের সংস্করণগুলিতে (Python 3.10 অনতর্ভুক্ত) আপনি `typing` মডিউল থেকে `Optional` ইমপোর্ট করে এটি ঘোষণা এবং ব্যবহার করতে পারেন।
+
+```Python hl_lines="1 4"
+{!../../../docs_src/python_types/tutorial009.py!}
+```
+
+`Optional[str]` ব্যবহার করা মানে হল শুধু `str` নয়, এটি হতে পারে `None`-ও, যা আপনার এডিটরকে সেই ত্রুটিগুলি শনাক্ত করতে সাহায্য করবে যেখানে আপনি ধরে নিচ্ছেন যে একটি মান সবসময় `str` হবে, অথচ এটি `None`-ও হতে পারেও।
+
+`Optional[Something]` মূলত `Union[Something, None]`-এর একটি শর্টকাট, এবং তারা সমতুল্য।
+
+এর মানে হল, Python 3.10-এ, আপনি টাইপগুলির ইউনিয়ন ঘোষণা করতে `Something | None` ব্যবহার করতে পারেন:
+
+=== "Python 3.10+"
+
+ ```Python hl_lines="1"
+ {!> ../../../docs_src/python_types/tutorial009_py310.py!}
+ ```
+
+=== "Python 3.8+"
+
+ ```Python hl_lines="1 4"
+ {!> ../../../docs_src/python_types/tutorial009.py!}
+ ```
+
+=== "Python 3.8+ বিকল্প"
+
+ ```Python hl_lines="1 4"
+ {!> ../../../docs_src/python_types/tutorial009b.py!}
+ ```
+
+#### `Union` বা `Optional` ব্যবহার
+
+যদি আপনি Python 3.10-এর নীচের সংস্করণ ব্যবহার করেন, তবে এখানে আমার খুবই **ব্যক্তিগত** দৃষ্টিভঙ্গি থেকে একটি টিপস:
+
+* 🚨 `Optional[SomeType]` ব্যবহার এড়িয়ে চলুন।
+* এর পরিবর্তে ✨ **`Union[SomeType, None]` ব্যবহার করুন** ✨।
+
+উভয়ই সমতুল্য এবং মূলে একই, কিন্তু আমি `Union`-এর পক্ষে সুপারিশ করব কারণ "**অপশনাল**" শব্দটি মনে হতে পারে যে মানটি ঐচ্ছিক,অথচ এটি আসলে মানে "এটি হতে পারে `None`", এমনকি যদি এটি ঐচ্ছিক না হয়েও আবশ্যিক হয়।
+
+আমি মনে করি `Union[SomeType, None]` এর অর্থ আরও স্পষ্টভাবে প্রকাশ করে।
+
+এটি কেবল শব্দ এবং নামের ব্যাপার। কিন্তু সেই শব্দগুলি আপনি এবং আপনার সহকর্মীরা কোড সম্পর্কে কীভাবে চিন্তা করেন তা প্রভাবিত করতে পারে।
+
+একটি উদাহরণ হিসেবে, এই ফাংশনটি নিন:
+
+```Python hl_lines="1 4"
+{!../../../docs_src/python_types/tutorial009c.py!}
+```
+
+`name` প্যারামিটারটি `Optional[str]` হিসেবে সংজ্ঞায়িত হয়েছে, কিন্তু এটি **অপশনাল নয়**, আপনি প্যারামিটার ছাড়া ফাংশনটি কল করতে পারবেন না:
+
+```Python
+say_hi() # ওহ না, এটি একটি ত্রুটি নিক্ষেপ করবে! 😱
+```
+
+`name` প্যারামিটারটি **এখনও আবশ্যিক** (নন-অপশনাল) কারণ এটির কোনো ডিফল্ট মান নেই। তবুও, `name` এর মান হিসেবে `None` গ্রহণযোগ্য:
+
+```Python
+say_hi(name=None) # এটি কাজ করে, None বৈধ 🎉
+```
+
+সুখবর হল, একবার আপনি Python 3.10 ব্যবহার করা শুরু করলে, আপনাকে এগুলোর ব্যাপারে আর চিন্তা করতে হবে না, যেহুতু আপনি | ব্যবহার করেই ইউনিয়ন ঘোষণা করতে পারবেন:
+
+```Python hl_lines="1 4"
+{!../../../docs_src/python_types/tutorial009c_py310.py!}
+```
+
+এবং তারপর আপনাকে নামগুলি যেমন `Optional` এবং `Union` নিয়ে আর চিন্তা করতে হবে না। 😎
+
+#### জেনেরিক টাইপস
+
+স্কোয়ার ব্র্যাকেটে টাইপ প্যারামিটার নেওয়া এই টাইপগুলিকে **জেনেরিক টাইপ** বা **জেনেরিকস** বলা হয়, যেমন:
+
+=== "Python 3.10+"
+ আপনি সেই একই বিল্টইন টাইপ জেনেরিক্স হিসেবে ব্যবহার করতে পারবেন(ভিতরে টাইপ সহ স্কয়ারে ব্রাকেট দিয়ে):
+
+ * `list`
+ * `tuple`
+ * `set`
+ * `dict`
+
+ এবং Python 3.8 এর মতোই, `typing` মডিউল থেকে:
+
+ * `Union`
+ * `Optional` (Python 3.8 এর মতোই)
+ * ...এবং অন্যান্য।
+
+ Python 3.10-এ, `Union` এবং `Optional` জেনেরিকস ব্যবহার করার বিকল্প হিসেবে, আপনি টাইপগুলির ইউনিয়ন ঘোষণা করতে ভার্টিকাল বার (`|`) ব্যবহার করতে পারেন, যা ওদের থেকে অনেক ভালো এবং সহজ।
+
+=== "Python 3.9+"
+
+ আপনি সেই একই বিল্টইন টাইপ জেনেরিক্স হিসেবে ব্যবহার করতে পারবেন(ভিতরে টাইপ সহ স্কয়ারে ব্রাকেট দিয়ে):
+
+ * `list`
+ * `tuple`
+ * `set`
+ * `dict`
+
+ এবং Python 3.8 এর মতোই, `typing` মডিউল থেকে:
+
+ * `Union`
+ * `Optional`
+ * ...এবং অন্যান্য।
+
+=== "Python 3.8+"
+
+ * `List`
+ * `Tuple`
+ * `Set`
+ * `Dict`
+ * `Union`
+ * `Optional`
+ * ...এবং অন্যান্য।
+
+### ক্লাস হিসেবে টাইপস
+
+আপনি একটি ভেরিয়েবলের টাইপ হিসেবে একটি ক্লাস ঘোষণা করতে পারেন।
+
+ধরুন আপনার কাছে `Person` নামে একটি ক্লাস আছে, যার একটি নাম আছে:
+
+```Python hl_lines="1-3"
+{!../../../docs_src/python_types/tutorial010.py!}
+```
+
+তারপর আপনি একটি ভেরিয়েবলকে `Person` টাইপের হিসেবে ঘোষণা করতে পারেন:
+
+```Python hl_lines="6"
+{!../../../docs_src/python_types/tutorial010.py!}
+```
+
+এবং তারপর, আবার, আপনি এডিটর সাপোর্ট পেয়ে যাবেন:
+
+
+
+লক্ষ্য করুন যে এর মানে হল "`one_person` হল ক্লাস `Person`-এর একটি **ইন্সট্যান্স**।"
+
+এর মানে এটি নয় যে "`one_person` হল **ক্লাস** যাকে বলা হয় `Person`।"
+
+## Pydantic মডেল
+
+[Pydantic](https://docs.pydantic.dev/) হল একটি Python লাইব্রেরি যা ডাটা ভ্যালিডেশন সম্পাদন করে।
+
+আপনি ডাটার "আকার" এট্রিবিউট সহ ক্লাস হিসেবে ঘোষণা করেন।
+
+এবং প্রতিটি এট্রিবিউট এর একটি টাইপ থাকে।
+
+তারপর আপনি যদি কিছু মান দিয়ে সেই ক্লাসের একটি ইন্সট্যান্স তৈরি করেন-- এটি মানগুলিকে ভ্যালিডেট করবে, প্রয়োজন অনুযায়ী তাদেরকে উপযুক্ত টাইপে রূপান্তর করবে এবং আপনাকে সমস্ত ডাটা সহ একটি অবজেক্ট প্রদান করবে।
+
+এবং আপনি সেই ফলাফল অবজেক্টের সাথে এডিটর সাপোর্ট পাবেন।
+
+অফিসিয়াল Pydantic ডক্স থেকে একটি উদাহরণ:
+
+=== "Python 3.10+"
+
+ ```Python
+ {!> ../../../docs_src/python_types/tutorial011_py310.py!}
+ ```
+
+=== "Python 3.9+"
+
+ ```Python
+ {!> ../../../docs_src/python_types/tutorial011_py39.py!}
+ ```
+
+=== "Python 3.8+"
+
+ ```Python
+ {!> ../../../docs_src/python_types/tutorial011.py!}
+ ```
+
+!!! Info
+ [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) সম্পর্কে আরও পড়তে পারেন।
+
+## মেটাডাটা অ্যানোটেশন সহ টাইপ হিন্টস
+
+Python-এ এমন একটি ফিচার আছে যা `Annotated` ব্যবহার করে এই টাইপ হিন্টগুলিতে **অতিরিক্ত মেটাডাটা** রাখতে দেয়।
+
+=== "Python 3.9+"
+
+ Python 3.9-এ, `Annotated` স্ট্যান্ডার্ড লাইব্রেরিতে অন্তর্ভুক্ত, তাই আপনি এটি `typing` থেকে ইমপোর্ট করতে পারেন।
+
+ ```Python hl_lines="1 4"
+ {!> ../../../docs_src/python_types/tutorial013_py39.py!}
+ ```
+
+=== "Python 3.8+"
+
+ Python 3.9-এর নীচের সংস্করণগুলিতে, আপনি `Annotated`-কে `typing_extensions` থেকে ইমপোর্ট করেন।
+
+ এটি **FastAPI** এর সাথে ইতিমদ্ধে ইনস্টল হয়ে থাকবে।
+
+ ```Python hl_lines="1 4"
+ {!> ../../../docs_src/python_types/tutorial013.py!}
+ ```
+
+Python নিজে এই `Annotated` দিয়ে কিছুই করে না। এবং এডিটর এবং অন্যান্য টুলগুলির জন্য, টাইপটি এখনও `str`।
+
+কিন্তু আপনি এই `Annotated` এর মধ্যকার জায়গাটির মধ্যে **FastAPI**-এ কীভাবে আপনার অ্যাপ্লিকেশন আচরণ করুক তা সম্পর্কে অতিরিক্ত মেটাডাটা প্রদান করার জন্য ব্যবহার করতে পারেন।
+
+মনে রাখার গুরুত্বপূর্ণ বিষয় হল যে **প্রথম *টাইপ প্যারামিটার*** আপনি `Annotated`-এ পাস করেন সেটি হল **আসল টাইপ**। বাকি শুধুমাত্র অন্যান্য টুলগুলির জন্য মেটাডাটা।
+
+এখন আপনার কেবল জানা প্রয়োজন যে `Annotated` বিদ্যমান, এবং এটি স্ট্যান্ডার্ড Python। 😎
+
+পরবর্তীতে আপনি দেখবেন এটি কতটা **শক্তিশালী** হতে পারে।
+
+!!! Tip
+ এটি **স্ট্যান্ডার্ড Python** হওয়ার মানে হল আপনি আপনার এডিটরে, আপনি যে টুলগুলি কোড বিশ্লেষণ এবং রিফ্যাক্টর করার জন্য ব্যবহার করেন তাতে **সেরা সম্ভাব্য ডেভেলপার এক্সপেরিয়েন্স** পাবেন। ✨
+
+ এবং এছাড়াও আপনার কোড অন্যান্য অনেক Python টুল এবং লাইব্রেরিগুলির সাথে খুব সামঞ্জস্যপূর্ণ হবে। 🚀
+
+## **FastAPI**-এ টাইপ হিন্টস
+
+**FastAPI** এই টাইপ হিন্টগুলি ব্যবহার করে বেশ কিছু জিনিস করে।
+
+**FastAPI**-এ আপনি টাইপ হিন্টগুলি সহ প্যারামিটার ঘোষণা করেন এবং আপনি পান:
+
+* **এডিটর সাপোর্ট**।
+* **টাইপচেক**।
+
+...এবং **FastAPI** একই ঘোষণাগুলি ব্যবহার করে:
+
+* **রিকুইরেমেন্টস সংজ্ঞায়িত করে**: রিকোয়েস্ট পাথ প্যারামিটার, কুয়েরি প্যারামিটার, হেডার, বডি, ডিপেন্ডেন্সিস, ইত্যাদি থেকে।
+* **ডেটা রূপান্তর করে**: রিকোয়েস্ট থেকে প্রয়োজনীয় টাইপে ডেটা।
+* **ডেটা যাচাই করে**: প্রতিটি রিকোয়েস্ট থেকে আসা ডেটা:
+ * যখন ডেটা অবৈধ হয় তখন **স্বয়ংক্রিয় ত্রুটি** গ্রাহকের কাছে ফেরত পাঠানো।
+* **API ডকুমেন্টেশন তৈরি করে**: OpenAPI ব্যবহার করে:
+ * যা স্বয়ংক্রিয় ইন্টার্যাক্টিভ ডকুমেন্টেশন ইউজার ইন্টারফেস দ্বারা ব্যবহৃত হয়।
+
+এই সব কিছু আপনার কাছে অস্পষ্ট মনে হতে পারে। চিন্তা করবেন না। আপনি [টিউটোরিয়াল - ইউজার গাইড](https://fastapi.tiangolo.com/tutorial/) এ এই সব কিছু প্র্যাকটিসে দেখতে পাবেন।
+
+গুরুত্বপূর্ণ বিষয় হল, আপনি যদি স্ট্যান্ডার্ড Python টাইপগুলি ব্যবহার করেন, তবে আরও বেশি ক্লাস, ডেকোরেটর ইত্যাদি যোগ না করেই একই স্থানে **FastAPI** আপনার অনেক কাজ করে দিবে।
+
+!!! Info
+ যদি আপনি টিউটোরিয়ালের সমস্ত বিষয় পড়ে ফেলে থাকেন এবং টাইপ সম্পর্কে আরও জানতে চান, তবে একটি ভালো রিসোর্স হল [mypy এর "cheat sheet"](https://mypy.readthedocs.io/en/latest/cheat_sheet_py3.html)। এই "cheat sheet" এ আপনি Python টাইপ হিন্ট সম্পর্কে বেসিক থেকে উন্নত লেভেলের ধারণা পেতে পারেন, যা আপনার কোডে টাইপ সেফটি এবং স্পষ্টতা বাড়াতে সাহায্য করবে।
diff --git a/docs/de/docs/advanced/generate-clients.md b/docs/de/docs/advanced/generate-clients.md
index 2fcba59569..7d1d693536 100644
--- a/docs/de/docs/advanced/generate-clients.md
+++ b/docs/de/docs/advanced/generate-clients.md
@@ -10,7 +10,7 @@ Es gibt viele Tools zum Generieren von Clients aus **OpenAPI**.
Ein gängiges Tool ist OpenAPI Generator.
-Wenn Sie ein **Frontend** erstellen, ist openapi-typescript-codegen eine sehr interessante Alternative.
+Wenn Sie ein **Frontend** erstellen, ist openapi-ts eine sehr interessante Alternative.
## Client- und SDK-Generatoren – Sponsor
@@ -58,14 +58,14 @@ Und dieselben Informationen aus den Modellen, die in OpenAPI enthalten sind, kö
Nachdem wir nun die Anwendung mit den Modellen haben, können wir den Client-Code für das Frontend generieren.
-#### `openapi-typescript-codegen` installieren
+#### `openapi-ts` installieren
-Sie können `openapi-typescript-codegen` in Ihrem Frontend-Code installieren mit:
+Sie können `openapi-ts` in Ihrem Frontend-Code installieren mit:
+
+!!! 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.
+
+## Ü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.
+
+In HTTP senden Sie als Teil der Response einen aus drei Ziffern bestehenden numerischen Statuscode.
+
+Diese Statuscodes haben einen Namen zugeordnet, um sie besser zu erkennen, aber der wichtige Teil ist die Zahl.
+
+Kurz:
+
+* `100` und darüber stehen für „Information“. Diese verwenden Sie selten direkt. Responses mit diesen Statuscodes können keinen Body haben.
+* **`200`** und darüber stehen für Responses, die „Successful“ („Erfolgreich“) waren. Diese verwenden Sie am häufigsten.
+ * `200` ist der Default-Statuscode, welcher bedeutet, alles ist „OK“.
+ * Ein anderes Beispiel ist `201`, „Created“ („Erzeugt“). Wird in der Regel verwendet, wenn ein neuer Datensatz in der Datenbank erzeugt wurde.
+ * Ein spezieller Fall ist `204`, „No Content“ („Kein Inhalt“). Diese Response wird verwendet, wenn es keinen Inhalt gibt, der zum Client zurückgeschickt wird, diese Response hat also keinen Body.
+* **`300`** und darüber steht für „Redirection“ („Umleitung“). Responses mit diesen Statuscodes können einen oder keinen Body haben, mit Ausnahme von `304`, „Not Modified“ („Nicht verändert“), welche keinen haben darf.
+* **`400`** und darüber stehen für „Client error“-Responses („Client-Fehler“). Auch diese verwenden Sie am häufigsten.
+ * Ein Beispiel ist `404`, für eine „Not Found“-Response („Nicht gefunden“).
+ * 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 MDN Dokumentation über HTTP-Statuscodes.
+
+## Abkürzung, um die Namen zu erinnern
+
+Schauen wir uns das vorherige Beispiel noch einmal an:
+
+```Python hl_lines="6"
+{!../../../docs_src/response_status_code/tutorial001.py!}
+```
+
+`201` ist der Statuscode für „Created“ („Erzeugt“).
+
+Aber Sie müssen sich nicht daran erinnern, welcher dieser Codes was bedeutet.
+
+Sie können die Hilfsvariablen von `fastapi.status` verwenden.
+
+```Python hl_lines="1 6"
+{!../../../docs_src/response_status_code/tutorial002.py!}
+```
+
+Diese sind nur eine Annehmlichkeit und enthalten dieselbe Nummer, aber auf diese Weise können Sie die Autovervollständigung Ihres Editors verwenden, um sie zu finden:
+
+
+
+!!! 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.
+
+## Den Defaultwert ändern
+
+Später sehen Sie, im [Handbuch für fortgeschrittene Benutzer](../advanced/response-change-status-code.md){.internal-link target=_blank}, wie Sie einen anderen Statuscode zurückgeben können, als den Default, den Sie hier deklarieren.
diff --git a/docs/em/docs/advanced/behind-a-proxy.md b/docs/em/docs/advanced/behind-a-proxy.md
index 12afe638c6..e3fd267354 100644
--- a/docs/em/docs/advanced/behind-a-proxy.md
+++ b/docs/em/docs/advanced/behind-a-proxy.md
@@ -341,6 +341,6 @@ $ uvicorn main:app --root-path /api/v1
## 🗜 🎧-🈸
-🚥 👆 💪 🗻 🎧-🈸 (🔬 [🎧 🈸 - 🗻](./sub-applications.md){.internal-link target=_blank}) ⏪ ⚙️ 🗳 ⏮️ `root_path`, 👆 💪 ⚫️ 🛎, 👆 🔜 ⌛.
+🚥 👆 💪 🗻 🎧-🈸 (🔬 [🎧 🈸 - 🗻](sub-applications.md){.internal-link target=_blank}) ⏪ ⚙️ 🗳 ⏮️ `root_path`, 👆 💪 ⚫️ 🛎, 👆 🔜 ⌛.
FastAPI 🔜 🔘 ⚙️ `root_path` 🎆, ⚫️ 🔜 👷. 👶
diff --git a/docs/em/docs/advanced/events.md b/docs/em/docs/advanced/events.md
index 671e81b186..19421ff58a 100644
--- a/docs/em/docs/advanced/events.md
+++ b/docs/em/docs/advanced/events.md
@@ -157,4 +157,4 @@ async with lifespan(app):
## 🎧 🈸
-👶 ✔️ 🤯 👈 👫 🔆 🎉 (🕴 & 🤫) 🔜 🕴 🛠️ 👑 🈸, 🚫 [🎧 🈸 - 🗻](./sub-applications.md){.internal-link target=_blank}.
+👶 ✔️ 🤯 👈 👫 🔆 🎉 (🕴 & 🤫) 🔜 🕴 🛠️ 👑 🈸, 🚫 [🎧 🈸 - 🗻](sub-applications.md){.internal-link target=_blank}.
diff --git a/docs/em/docs/advanced/generate-clients.md b/docs/em/docs/advanced/generate-clients.md
index 30560c8c65..261f9fb612 100644
--- a/docs/em/docs/advanced/generate-clients.md
+++ b/docs/em/docs/advanced/generate-clients.md
@@ -10,7 +10,7 @@
⚠ 🧰 🗄 🚂.
-🚥 👆 🏗 **🕸**, 📶 😌 🎛 🗄-📕-🇦🇪.
+🚥 👆 🏗 **🕸**, 📶 😌 🎛 🗄-📕-🇦🇪.
## 🏗 📕 🕸 👩💻
@@ -46,14 +46,14 @@
🔜 👈 👥 ✔️ 📱 ⏮️ 🏷, 👥 💪 🏗 👩💻 📟 🕸.
-#### ❎ `openapi-typescript-codegen`
+#### ❎ `openapi-ts`
-👆 💪 ❎ `openapi-typescript-codegen` 👆 🕸 📟 ⏮️:
+👆 💪 ❎ `openapi-ts` 👆 🕸 📟 ⏮️:
diff --git a/docs/en/docs/advanced/path-operation-advanced-configuration.md b/docs/en/docs/advanced/path-operation-advanced-configuration.md
index 8b79bfe22a..c5544a78bc 100644
--- a/docs/en/docs/advanced/path-operation-advanced-configuration.md
+++ b/docs/en/docs/advanced/path-operation-advanced-configuration.md
@@ -59,7 +59,7 @@ That defines the metadata about the main response of a *path operation*.
You can also declare additional responses with their models, status codes, etc.
-There's a whole chapter here in the documentation about it, you can read it at [Additional Responses in OpenAPI](./additional-responses.md){.internal-link target=_blank}.
+There's a whole chapter here in the documentation about it, you can read it at [Additional Responses in OpenAPI](additional-responses.md){.internal-link target=_blank}.
## OpenAPI Extra
@@ -77,7 +77,7 @@ This *path operation*-specific OpenAPI schema is normally generated automaticall
!!! 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`.
diff --git a/docs/en/docs/advanced/settings.md b/docs/en/docs/advanced/settings.md
index f6db8d2b15..8f72bf63a8 100644
--- a/docs/en/docs/advanced/settings.md
+++ b/docs/en/docs/advanced/settings.md
@@ -232,7 +232,7 @@ And then use it in a file `main.py`:
```
!!! tip
- You would also need a file `__init__.py` as you saw on [Bigger Applications - Multiple Files](../tutorial/bigger-applications.md){.internal-link target=_blank}.
+ 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
diff --git a/docs/en/docs/advanced/sub-applications.md b/docs/en/docs/advanced/sub-applications.md
index a089632acf..8c52e091f0 100644
--- a/docs/en/docs/advanced/sub-applications.md
+++ b/docs/en/docs/advanced/sub-applications.md
@@ -70,4 +70,4 @@ That way, the sub-application will know to use that path prefix for the docs UI.
And the sub-application could also have its own mounted sub-applications and everything would work correctly, because FastAPI handles all these `root_path`s automatically.
-You will learn more about the `root_path` and how to use it explicitly in the section about [Behind a Proxy](./behind-a-proxy.md){.internal-link target=_blank}.
+You will learn more about the `root_path` and how to use it explicitly in the section about [Behind a Proxy](behind-a-proxy.md){.internal-link target=_blank}.
diff --git a/docs/en/docs/advanced/wsgi.md b/docs/en/docs/advanced/wsgi.md
index cfe3c78c11..852e250199 100644
--- a/docs/en/docs/advanced/wsgi.md
+++ b/docs/en/docs/advanced/wsgi.md
@@ -1,6 +1,6 @@
# Including WSGI - Flask, Django, others
-You can mount WSGI applications as you saw with [Sub Applications - Mounts](./sub-applications.md){.internal-link target=_blank}, [Behind a Proxy](./behind-a-proxy.md){.internal-link target=_blank}.
+You can mount WSGI applications as you saw with [Sub Applications - Mounts](sub-applications.md){.internal-link target=_blank}, [Behind a Proxy](behind-a-proxy.md){.internal-link target=_blank}.
For that, you can use the `WSGIMiddleware` and use it to wrap your WSGI application, for example, Flask, Django, etc.
diff --git a/docs/en/docs/alternatives.md b/docs/en/docs/alternatives.md
index d351c4e0b7..9a101a8a1b 100644
--- a/docs/en/docs/alternatives.md
+++ b/docs/en/docs/alternatives.md
@@ -1,6 +1,6 @@
# Alternatives, Inspiration and Comparisons
-What inspired **FastAPI**, how it compares to other alternatives and what it learned from them.
+What inspired **FastAPI**, how it compares to alternatives and what it learned from them.
## Intro
@@ -117,7 +117,7 @@ That's why when talking about version 2.0 it's common to say "Swagger", and for
* Swagger UI
* ReDoc
- These two were chosen for being fairly popular and stable, but doing a quick search, you could find dozens of additional 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
@@ -291,7 +291,7 @@ As it is based on the previous standard for synchronous Python web frameworks (W
!!! info
Hug was created by Timothy Crosley, the same creator of `isort`, a great tool to automatically sort imports in Python files.
-!!! check "Ideas inspired in **FastAPI**"
+!!! check "Ideas inspiring **FastAPI**"
Hug inspired parts of APIStar, and was one of the tools I found most promising, alongside APIStar.
Hug helped inspiring **FastAPI** to use Python type hints to declare parameters, and to generate a schema defining the API automatically.
diff --git a/docs/en/docs/async.md b/docs/en/docs/async.md
index ff322635ad..a0c00933ad 100644
--- a/docs/en/docs/async.md
+++ b/docs/en/docs/async.md
@@ -397,7 +397,7 @@ All that is what powers FastAPI (through Starlette) and what makes it have such
These are very technical details of how **FastAPI** works underneath.
- If you have quite some technical knowledge (co-routines, 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
@@ -409,11 +409,11 @@ Still, in both situations, chances are that **FastAPI** will [still be faster](i
### Dependencies
-The same applies for [dependencies](./tutorial/dependencies/index.md){.internal-link target=_blank}. If a dependency is a standard `def` function instead of `async def`, it is run in the external threadpool.
+The same applies for [dependencies](tutorial/dependencies/index.md){.internal-link target=_blank}. If a dependency is a standard `def` function instead of `async def`, it is run in the external threadpool.
### Sub-dependencies
-You can have multiple dependencies and [sub-dependencies](./tutorial/dependencies/sub-dependencies.md){.internal-link target=_blank} requiring each other (as parameters of the function definitions), some of them might be created with `async def` and some with normal `def`. It would still work, and the ones created with normal `def` would be called on an external thread (from the threadpool) instead of being "awaited".
+You can have multiple dependencies and [sub-dependencies](tutorial/dependencies/sub-dependencies.md){.internal-link target=_blank} requiring each other (as parameters of the function definitions), some of them might be created with `async def` and some with normal `def`. It would still work, and the ones created with normal `def` would be called on an external thread (from the threadpool) instead of being "awaited".
### Other utility functions
diff --git a/docs/en/docs/benchmarks.md b/docs/en/docs/benchmarks.md
index d746b6d7c4..62266c449b 100644
--- a/docs/en/docs/benchmarks.md
+++ b/docs/en/docs/benchmarks.md
@@ -1,6 +1,6 @@
# Benchmarks
-Independent TechEmpower benchmarks show **FastAPI** applications running under Uvicorn as one of the fastest Python frameworks available, only below Starlette and Uvicorn themselves (used internally by FastAPI). (*)
+Independent TechEmpower benchmarks show **FastAPI** applications running under Uvicorn as one of the fastest Python frameworks available, only below Starlette and Uvicorn themselves (used internally by FastAPI).
But when checking benchmarks and comparisons you should keep the following in mind.
diff --git a/docs/en/docs/deployment/concepts.md b/docs/en/docs/deployment/concepts.md
index cc01fb24e1..b771ae6634 100644
--- a/docs/en/docs/deployment/concepts.md
+++ b/docs/en/docs/deployment/concepts.md
@@ -25,7 +25,7 @@ But for now, let's check these important **conceptual ideas**. These concepts al
## Security - HTTPS
-In the [previous chapter about HTTPS](./https.md){.internal-link target=_blank} we learned about how HTTPS provides encryption for your API.
+In the [previous chapter about HTTPS](https.md){.internal-link target=_blank} we learned about how HTTPS provides encryption for your API.
We also saw that HTTPS is normally provided by a component **external** to your application server, a **TLS Termination Proxy**.
@@ -187,7 +187,7 @@ When you run **multiple processes** of the same API program, they are commonly c
### Worker Processes and Ports
-Remember from the docs [About HTTPS](./https.md){.internal-link target=_blank} that only one process can be listening on one combination of port and IP address in a server?
+Remember from the docs [About HTTPS](https.md){.internal-link target=_blank} that only one process can be listening on one combination of port and IP address in a server?
This is still true.
@@ -230,18 +230,18 @@ The main constraint to consider is that there has to be a **single** component h
Here are some possible combinations and strategies:
* **Gunicorn** managing **Uvicorn workers**
- * Gunicorn would be the **process manager** listening on the **IP** and **port**, the replication would be by having **multiple Uvicorn worker processes**
+ * Gunicorn would be the **process manager** listening on the **IP** and **port**, the replication would be by having **multiple Uvicorn worker processes**.
* **Uvicorn** managing **Uvicorn workers**
- * One Uvicorn **process manager** would listen on the **IP** and **port**, and it would start **multiple Uvicorn worker processes**
+ * One Uvicorn **process manager** would listen on the **IP** and **port**, and it would start **multiple Uvicorn worker processes**.
* **Kubernetes** and other distributed **container systems**
- * Something in the **Kubernetes** layer would listen on the **IP** and **port**. The replication would be by having **multiple containers**, each with **one Uvicorn process** running
+ * Something in the **Kubernetes** layer would listen on the **IP** and **port**. The replication would be by having **multiple containers**, each with **one Uvicorn process** running.
* **Cloud services** that handle this for 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.
- 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
@@ -273,7 +273,7 @@ Here are some possible ideas:
* 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}.
+ 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
diff --git a/docs/en/docs/deployment/docker.md b/docs/en/docs/deployment/docker.md
index 8a542622e4..467ba72deb 100644
--- a/docs/en/docs/deployment/docker.md
+++ b/docs/en/docs/deployment/docker.md
@@ -108,7 +108,7 @@ It would depend mainly on the tool you use to **install** those requirements.
The most common way to do it is to have a file `requirements.txt` with the package names and their versions, one per line.
-You would of course use the same ideas you read in [About FastAPI versions](./versions.md){.internal-link target=_blank} to set the ranges of versions.
+You would of course use the same ideas you read in [About FastAPI versions](versions.md){.internal-link target=_blank} to set the ranges of versions.
For example, your `requirements.txt` could look like:
@@ -373,7 +373,7 @@ Then adjust the Uvicorn command to use the new module `main` instead of `app.mai
## Deployment Concepts
-Let's talk again about some of the same [Deployment Concepts](./concepts.md){.internal-link target=_blank} in terms of containers.
+Let's talk again about some of the same [Deployment Concepts](concepts.md){.internal-link target=_blank} in terms of containers.
Containers are mainly a tool to simplify the process of **building and deploying** an application, but they don't enforce a particular approach to handle these **deployment concepts**, and there are several possible strategies.
@@ -514,7 +514,7 @@ If you have a simple setup, with a **single container** that then starts multipl
## Official Docker Image with Gunicorn - Uvicorn
-There is an official Docker image that includes Gunicorn running with Uvicorn workers, as detailed in a previous chapter: [Server Workers - Gunicorn with Uvicorn](./server-workers.md){.internal-link target=_blank}.
+There is an official Docker image that includes Gunicorn running with Uvicorn workers, as detailed in a previous chapter: [Server Workers - Gunicorn with Uvicorn](server-workers.md){.internal-link target=_blank}.
This image would be useful mainly in the situations described above in: [Containers with Multiple Processes and Special Cases](#containers-with-multiple-processes-and-special-cases).
diff --git a/docs/en/docs/deployment/server-workers.md b/docs/en/docs/deployment/server-workers.md
index 2df9f3d432..5fe2309a94 100644
--- a/docs/en/docs/deployment/server-workers.md
+++ b/docs/en/docs/deployment/server-workers.md
@@ -13,12 +13,12 @@ Up to this point, with all the tutorials in the docs, you have probably been run
When deploying applications you will probably want to have some **replication of processes** to take advantage of **multiple cores** and to be able to handle more requests.
-As you saw in the previous chapter about [Deployment Concepts](./concepts.md){.internal-link target=_blank}, there are multiple strategies you can use.
+As you saw in the previous chapter about [Deployment Concepts](concepts.md){.internal-link target=_blank}, there are multiple strategies you can use.
Here I'll show you how to use **Gunicorn** 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}.
+ 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.
@@ -165,7 +165,7 @@ From the list of deployment concepts from above, using workers would mainly help
## Containers and Docker
-In the next chapter about [FastAPI in Containers - Docker](./docker.md){.internal-link target=_blank} I'll tell some strategies you could use to handle the other **deployment concepts**.
+In the next chapter about [FastAPI in Containers - Docker](docker.md){.internal-link target=_blank} I'll tell some strategies you could use to handle the other **deployment concepts**.
I'll also show you the **official Docker image** that includes **Gunicorn with Uvicorn workers** and some default configurations that can be useful for simple cases.
diff --git a/docs/en/docs/help-fastapi.md b/docs/en/docs/help-fastapi.md
index 1d76aca5e5..1214477397 100644
--- a/docs/en/docs/help-fastapi.md
+++ b/docs/en/docs/help-fastapi.md
@@ -51,7 +51,7 @@ You can:
* Tell me how you use FastAPI (I love to hear that).
* Hear when I make announcements or release new tools.
* You can also follow @fastapi on Twitter (a separate account).
-* Follow me on **Linkedin**.
+* Follow me on **LinkedIn**.
* Hear when I make announcements or release new tools (although I use Twitter more often 🤷♂).
* Read what I write (or follow me) on **Dev.to** or **Medium**.
* Read other ideas, articles, and read about tools I have created.
@@ -78,7 +78,7 @@ You can try and help others with their questions in:
In many cases you might already know the answer for those questions. 🤓
-If you are helping a lot of people with their questions, you will become an official [FastAPI Expert](fastapi-people.md#experts){.internal-link target=_blank}. 🎉
+If you are helping a lot of people with their questions, you will become an official [FastAPI Expert](fastapi-people.md#fastapi-experts){.internal-link target=_blank}. 🎉
Just remember, the most important point is: try to be kind. People come with their frustrations and in many cases don't ask in the best way, but try as best as you can to be kind. 🤗
@@ -227,7 +227,7 @@ If you can help me with that, **you are helping me maintain FastAPI** and making
Join the 👥 Discord chat server 👥 and hang out with others in the FastAPI community.
!!! tip
- For questions, ask them in GitHub Discussions, there's a much better chance you will receive help by the [FastAPI Experts](fastapi-people.md#experts){.internal-link target=_blank}.
+ For questions, ask them in GitHub Discussions, there's a much better chance you will receive help by the [FastAPI Experts](fastapi-people.md#fastapi-experts){.internal-link target=_blank}.
Use the chat only for other general conversations.
@@ -237,7 +237,7 @@ Keep in mind that as chats allow more "free conversation", it's easy to ask ques
In GitHub, the template will guide you to write the right question so that you can more easily get a good answer, or even solve the problem yourself even before asking. And in GitHub I can make sure I always answer everything, even if it takes some time. I can't personally do that with the chat systems. 😅
-Conversations in the chat systems are also not as easily searchable as in GitHub, so questions and answers might get lost in the conversation. And only the ones in GitHub count to become a [FastAPI Expert](fastapi-people.md#experts){.internal-link target=_blank}, so you will most probably receive more attention in GitHub.
+Conversations in the chat systems are also not as easily searchable as in GitHub, so questions and answers might get lost in the conversation. And only the ones in GitHub count to become a [FastAPI Expert](fastapi-people.md#fastapi-experts){.internal-link target=_blank}, so you will most probably receive more attention in GitHub.
On the other side, there are thousands of users in the chat systems, so there's a high chance you'll find someone to talk to there, almost all the time. 😄
diff --git a/docs/en/docs/how-to/async-sql-encode-databases.md b/docs/en/docs/how-to/async-sql-encode-databases.md
index c7b340d679..4d53f53a7f 100644
--- a/docs/en/docs/how-to/async-sql-encode-databases.md
+++ b/docs/en/docs/how-to/async-sql-encode-databases.md
@@ -100,7 +100,7 @@ Create the *path operation function* to read notes:
{!../../../docs_src/async_sql_databases/tutorial001.py!}
```
-!!! Note
+!!! 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]`
@@ -122,7 +122,7 @@ Create the *path operation function* to create notes:
The examples here use `.dict()` for compatibility with Pydantic v1, but you should use `.model_dump()` instead if you can use Pydantic v2.
-!!! Note
+!!! 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}`
diff --git a/docs/en/docs/how-to/configure-swagger-ui.md b/docs/en/docs/how-to/configure-swagger-ui.md
index f36ba5ba8c..108afb929b 100644
--- a/docs/en/docs/how-to/configure-swagger-ui.md
+++ b/docs/en/docs/how-to/configure-swagger-ui.md
@@ -45,7 +45,7 @@ FastAPI includes some default configuration parameters appropriate for most of t
It includes these default configurations:
```Python
-{!../../../fastapi/openapi/docs.py[ln:7-13]!}
+{!../../../fastapi/openapi/docs.py[ln:7-23]!}
```
You can override any of them by setting a different value in the argument `swagger_ui_parameters`.
diff --git a/docs/en/docs/python-types.md b/docs/en/docs/python-types.md
index 51db744ff5..3e8267aea0 100644
--- a/docs/en/docs/python-types.md
+++ b/docs/en/docs/python-types.md
@@ -186,7 +186,7 @@ For example, let's define a variable to be a `list` of `str`.
From `typing`, import `List` (with a capital `L`):
- ``` Python hl_lines="1"
+ ```Python hl_lines="1"
{!> ../../../docs_src/python_types/tutorial006.py!}
```
diff --git a/docs/en/docs/reference/apirouter.md b/docs/en/docs/reference/apirouter.md
index b779ad2914..d77364e45e 100644
--- a/docs/en/docs/reference/apirouter.md
+++ b/docs/en/docs/reference/apirouter.md
@@ -1,7 +1,6 @@
# `APIRouter` class
-Here's the reference information for the `APIRouter` class, with all its parameters,
-attributes and methods.
+Here's the reference information for the `APIRouter` class, with all its parameters, attributes and methods.
You can import the `APIRouter` class directly from `fastapi`:
diff --git a/docs/en/docs/reference/background.md b/docs/en/docs/reference/background.md
index e0c0be899f..f65619590e 100644
--- a/docs/en/docs/reference/background.md
+++ b/docs/en/docs/reference/background.md
@@ -1,8 +1,6 @@
# Background Tasks - `BackgroundTasks`
-You can declare a parameter in a *path operation function* or dependency function
-with the type `BackgroundTasks`, and then you can use it to schedule the execution
-of background tasks after the response is sent.
+You can declare a parameter in a *path operation function* or dependency function with the type `BackgroundTasks`, and then you can use it to schedule the execution of background tasks after the response is sent.
You can import it directly from `fastapi`:
diff --git a/docs/en/docs/reference/dependencies.md b/docs/en/docs/reference/dependencies.md
index 0999682679..2959a21dae 100644
--- a/docs/en/docs/reference/dependencies.md
+++ b/docs/en/docs/reference/dependencies.md
@@ -2,8 +2,7 @@
## `Depends()`
-Dependencies are handled mainly with the special function `Depends()` that takes a
-callable.
+Dependencies are handled mainly with the special function `Depends()` that takes a callable.
Here is the reference for it and its parameters.
@@ -17,11 +16,9 @@ from fastapi import Depends
## `Security()`
-For many scenarios, you can handle security (authorization, authentication, etc.) with
-dependencies, using `Depends()`.
+For many scenarios, you can handle security (authorization, authentication, etc.) with dependencies, using `Depends()`.
-But when you want to also declare OAuth2 scopes, you can use `Security()` instead of
-`Depends()`.
+But when you want to also declare OAuth2 scopes, you can use `Security()` instead of `Depends()`.
You can import `Security()` directly from `fastapi`:
diff --git a/docs/en/docs/reference/exceptions.md b/docs/en/docs/reference/exceptions.md
index 7c48083492..1392d2a80e 100644
--- a/docs/en/docs/reference/exceptions.md
+++ b/docs/en/docs/reference/exceptions.md
@@ -2,9 +2,7 @@
These are the exceptions that you can raise to show errors to the client.
-When you raise an exception, as would happen with normal Python, the rest of the
-execution is aborted. This way you can raise these exceptions from anywhere in the
-code to abort a request and show the error to the client.
+When you raise an exception, as would happen with normal Python, the rest of the execution is aborted. This way you can raise these exceptions from anywhere in the code to abort a request and show the error to the client.
You can use:
diff --git a/docs/en/docs/reference/fastapi.md b/docs/en/docs/reference/fastapi.md
index 8b87664cb3..d5367ff347 100644
--- a/docs/en/docs/reference/fastapi.md
+++ b/docs/en/docs/reference/fastapi.md
@@ -1,7 +1,6 @@
# `FastAPI` class
-Here's the reference information for the `FastAPI` class, with all its parameters,
-attributes and methods.
+Here's the reference information for the `FastAPI` class, with all its parameters, attributes and methods.
You can import the `FastAPI` class directly from `fastapi`:
diff --git a/docs/en/docs/reference/httpconnection.md b/docs/en/docs/reference/httpconnection.md
index 43dfc46f94..b7b87871a8 100644
--- a/docs/en/docs/reference/httpconnection.md
+++ b/docs/en/docs/reference/httpconnection.md
@@ -1,8 +1,6 @@
# `HTTPConnection` class
-When you want to define dependencies that should be compatible with both HTTP and
-WebSockets, you can define a parameter that takes an `HTTPConnection` instead of a
-`Request` or a `WebSocket`.
+When you want to define dependencies that should be compatible with both HTTP and WebSockets, you can define a parameter that takes an `HTTPConnection` instead of a `Request` or a `WebSocket`.
You can import it from `fastapi.requests`:
diff --git a/docs/en/docs/reference/middleware.md b/docs/en/docs/reference/middleware.md
index 89704d3c8b..3c666ccdaa 100644
--- a/docs/en/docs/reference/middleware.md
+++ b/docs/en/docs/reference/middleware.md
@@ -2,8 +2,7 @@
There are several middlewares available provided by Starlette directly.
-Read more about them in the
-[FastAPI docs for Middleware](https://fastapi.tiangolo.com/advanced/middleware/).
+Read more about them in the [FastAPI docs for Middleware](https://fastapi.tiangolo.com/advanced/middleware/).
::: fastapi.middleware.cors.CORSMiddleware
diff --git a/docs/en/docs/reference/parameters.md b/docs/en/docs/reference/parameters.md
index 8f77f0161b..d304c013c7 100644
--- a/docs/en/docs/reference/parameters.md
+++ b/docs/en/docs/reference/parameters.md
@@ -2,8 +2,7 @@
Here's the reference information for the request parameters.
-These are the special functions that you can put in *path operation function*
-parameters or dependency functions with `Annotated` to get data from the request.
+These are the special functions that you can put in *path operation function* parameters or dependency functions with `Annotated` to get data from the request.
It includes:
diff --git a/docs/en/docs/reference/request.md b/docs/en/docs/reference/request.md
index 91ec7d37b6..0326f3fc73 100644
--- a/docs/en/docs/reference/request.md
+++ b/docs/en/docs/reference/request.md
@@ -1,8 +1,6 @@
# `Request` class
-You can declare a parameter in a *path operation function* or dependency to be of type
-`Request` and then you can access the raw request object directly, without any
-validation, etc.
+You can declare a parameter in a *path operation function* or dependency to be of type `Request` and then you can access the raw request object directly, without any validation, etc.
You can import it directly from `fastapi`:
@@ -11,8 +9,6 @@ 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`.
+ When you want to define dependencies that should be compatible with both HTTP and WebSockets, you can define a parameter that takes an `HTTPConnection` instead of a `Request` or a `WebSocket`.
::: fastapi.Request
diff --git a/docs/en/docs/reference/response.md b/docs/en/docs/reference/response.md
index 9162545831..00cf2c499c 100644
--- a/docs/en/docs/reference/response.md
+++ b/docs/en/docs/reference/response.md
@@ -1,10 +1,8 @@
# `Response` class
-You can declare a parameter in a *path operation function* or dependency to be of type
-`Response` and then you can set data for the response like headers or cookies.
+You can declare a parameter in a *path operation function* or dependency to be of type `Response` and then you can set data for the response like headers or cookies.
-You can also use it directly to create an instance of it and return it from your *path
-operations*.
+You can also use it directly to create an instance of it and return it from your *path operations*.
You can import it directly from `fastapi`:
diff --git a/docs/en/docs/reference/responses.md b/docs/en/docs/reference/responses.md
index 2cbbd89632..46f014fcc8 100644
--- a/docs/en/docs/reference/responses.md
+++ b/docs/en/docs/reference/responses.md
@@ -1,10 +1,8 @@
# Custom Response Classes - File, HTML, Redirect, Streaming, etc.
-There are several custom response classes you can use to create an instance and return
-them directly from your *path operations*.
+There are several custom response classes you can use to create an instance and return them directly from your *path operations*.
-Read more about it in the
-[FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/).
+Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/).
You can import them directly from `fastapi.responses`:
diff --git a/docs/en/docs/reference/security/index.md b/docs/en/docs/reference/security/index.md
index ff86e9e30c..9a5c5e15fb 100644
--- a/docs/en/docs/reference/security/index.md
+++ b/docs/en/docs/reference/security/index.md
@@ -2,12 +2,9 @@
When you need to declare dependencies with OAuth2 scopes you use `Security()`.
-But you still need to define what is the dependable, the callable that you pass as
-a parameter to `Depends()` or `Security()`.
+But you still need to define what is the dependable, the callable that you pass as a parameter to `Depends()` or `Security()`.
-There are multiple tools that you can use to create those dependables, and they get
-integrated into OpenAPI so they are shown in the automatic docs UI, they can be used
-by automatically generated clients and SDKs, etc.
+There are multiple tools that you can use to create those dependables, and they get integrated into OpenAPI so they are shown in the automatic docs UI, they can be used by automatically generated clients and SDKs, etc.
You can import them from `fastapi.security`:
diff --git a/docs/en/docs/reference/staticfiles.md b/docs/en/docs/reference/staticfiles.md
index ce66f17b3d..2712310783 100644
--- a/docs/en/docs/reference/staticfiles.md
+++ b/docs/en/docs/reference/staticfiles.md
@@ -2,8 +2,7 @@
You can use the `StaticFiles` class to serve static files, like JavaScript, CSS, images, etc.
-Read more about it in the
-[FastAPI docs for Static Files](https://fastapi.tiangolo.com/tutorial/static-files/).
+Read more about it in the [FastAPI docs for Static Files](https://fastapi.tiangolo.com/tutorial/static-files/).
You can import it directly from `fastapi.staticfiles`:
diff --git a/docs/en/docs/reference/status.md b/docs/en/docs/reference/status.md
index a238007923..6e0e816d33 100644
--- a/docs/en/docs/reference/status.md
+++ b/docs/en/docs/reference/status.md
@@ -16,12 +16,9 @@ For example:
* 403: `status.HTTP_403_FORBIDDEN`
* etc.
-It can be convenient to quickly access HTTP (and WebSocket) status codes in your app,
-using autocompletion for the name without having to remember the integer status codes
-by memory.
+It can be convenient to quickly access HTTP (and WebSocket) status codes in your app, using autocompletion for the name without having to remember the integer status codes by memory.
-Read more about it in the
-[FastAPI docs about Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/).
+Read more about it in the [FastAPI docs about Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/).
## Example
diff --git a/docs/en/docs/reference/templating.md b/docs/en/docs/reference/templating.md
index c865badfcb..eedfe44d54 100644
--- a/docs/en/docs/reference/templating.md
+++ b/docs/en/docs/reference/templating.md
@@ -2,8 +2,7 @@
You can use the `Jinja2Templates` class to render Jinja templates.
-Read more about it in the
-[FastAPI docs for Templates](https://fastapi.tiangolo.com/advanced/templates/).
+Read more about it in the [FastAPI docs for Templates](https://fastapi.tiangolo.com/advanced/templates/).
You can import it directly from `fastapi.templating`:
diff --git a/docs/en/docs/reference/testclient.md b/docs/en/docs/reference/testclient.md
index e391d964a2..2966ed792c 100644
--- a/docs/en/docs/reference/testclient.md
+++ b/docs/en/docs/reference/testclient.md
@@ -2,8 +2,7 @@
You can use the `TestClient` class to test FastAPI applications without creating an actual HTTP and socket connection, just communicating directly with the FastAPI code.
-Read more about it in the
-[FastAPI docs for Testing](https://fastapi.tiangolo.com/tutorial/testing/).
+Read more about it in the [FastAPI docs for Testing](https://fastapi.tiangolo.com/tutorial/testing/).
You can import it directly from `fastapi.testclient`:
diff --git a/docs/en/docs/reference/uploadfile.md b/docs/en/docs/reference/uploadfile.md
index 45c644b18d..43a7537303 100644
--- a/docs/en/docs/reference/uploadfile.md
+++ b/docs/en/docs/reference/uploadfile.md
@@ -1,7 +1,6 @@
# `UploadFile` class
-You can define *path operation function* parameters to be of the type `UploadFile`
-to receive files from the request.
+You can define *path operation function* parameters to be of the type `UploadFile` to receive files from the request.
You can import it directly from `fastapi`:
diff --git a/docs/en/docs/reference/websockets.md b/docs/en/docs/reference/websockets.md
index 2a04694678..d21e81a07d 100644
--- a/docs/en/docs/reference/websockets.md
+++ b/docs/en/docs/reference/websockets.md
@@ -1,7 +1,6 @@
# WebSockets
-When defining WebSockets, you normally declare a parameter of type `WebSocket` and
-with it you can read data from the client and send data to it.
+When defining WebSockets, you normally declare a parameter of type `WebSocket` and with it you can read data from the client and send data to it.
It is provided directly by Starlette, but you can import it from `fastapi`:
@@ -10,9 +9,7 @@ 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`.
+ 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:
@@ -44,8 +41,7 @@ from fastapi import WebSocket
- send_json
- close
-When a client disconnects, a `WebSocketDisconnect` exception is raised, you can catch
-it.
+When a client disconnects, a `WebSocketDisconnect` exception is raised, you can catch it.
You can import it directly form `fastapi`:
diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md
index e5b9a5a9d6..49df7a7711 100644
--- a/docs/en/docs/release-notes.md
+++ b/docs/en/docs/release-notes.md
@@ -7,10 +7,55 @@ hide:
## Latest Changes
+### Fixes
+
+* 🐛 Fix support for query parameters with list types, handle JSON encoding Pydantic `UndefinedType`. PR [#9929](https://github.com/tiangolo/fastapi/pull/9929) by [@arjwilliams](https://github.com/arjwilliams).
+
### Refactors
+* ♻️ Simplify Pydantic configs in OpenAPI models in `fastapi/openapi/models.py`. PR [#10886](https://github.com/tiangolo/fastapi/pull/10886) by [@JoeTanto2](https://github.com/JoeTanto2).
+* ✨ Add support for Pydantic's 2.7 new deprecated Field parameter, remove URL from validation errors response. PR [#11461](https://github.com/tiangolo/fastapi/pull/11461) by [@tiangolo](https://github.com/tiangolo).
+
+### Docs
+
+* 📝 Tweak docs and translations links, typos, format. PR [#11389](https://github.com/tiangolo/fastapi/pull/11389) by [@nilslindemann](https://github.com/nilslindemann).
+* 📝 Fix typo in `docs/es/docs/async.md`. PR [#11400](https://github.com/tiangolo/fastapi/pull/11400) by [@fabianfalon](https://github.com/fabianfalon).
+* 📝 Update OpenAPI client generation docs to use `@hey-api/openapi-ts`. PR [#11339](https://github.com/tiangolo/fastapi/pull/11339) by [@jordanshatford](https://github.com/jordanshatford).
+
+### Translations
+
+* 🌐 Update Chinese translation for `docs/zh/docs/index.html`. PR [#11430](https://github.com/tiangolo/fastapi/pull/11430) by [@waketzheng](https://github.com/waketzheng).
+* 🌐 Add Russian translation for `docs/ru/docs/tutorial/dependencies/dependencies-in-path-operation-decorators.md`. PR [#11411](https://github.com/tiangolo/fastapi/pull/11411) by [@anton2yakovlev](https://github.com/anton2yakovlev).
+* 🌐 Add Portuguese translations for `learn/index.md` `resources/index.md` `help/index.md` `about/index.md`. PR [#10807](https://github.com/tiangolo/fastapi/pull/10807) by [@nazarepiedady](https://github.com/nazarepiedady).
+* 🌐 Update Russian translations for deployments docs. PR [#11271](https://github.com/tiangolo/fastapi/pull/11271) by [@Lufa1u](https://github.com/Lufa1u).
+* 🌐 Add Bengali translations for `docs/bn/docs/python-types.md`. PR [#11376](https://github.com/tiangolo/fastapi/pull/11376) by [@imtiaz101325](https://github.com/imtiaz101325).
+* 🌐 Add Korean translation for `docs/ko/docs/tutorial/security/simple-oauth2.md`. PR [#5744](https://github.com/tiangolo/fastapi/pull/5744) by [@KdHyeon0661](https://github.com/KdHyeon0661).
+* 🌐 Add Korean translation for `docs/ko/docs/help-fastapi.md`. PR [#4139](https://github.com/tiangolo/fastapi/pull/4139) by [@kty4119](https://github.com/kty4119).
+* 🌐 Add Korean translation for `docs/ko/docs/advanced/events.md`. PR [#5087](https://github.com/tiangolo/fastapi/pull/5087) by [@pers0n4](https://github.com/pers0n4).
+* 🌐 Add Japanese translation for `docs/ja/docs/tutorial/path-operation-configuration.md`. PR [#1954](https://github.com/tiangolo/fastapi/pull/1954) by [@SwftAlpc](https://github.com/SwftAlpc).
+* 🌐 Add Japanese translation for `docs/ja/docs/tutorial/request-forms-and-files.md`. PR [#1946](https://github.com/tiangolo/fastapi/pull/1946) by [@SwftAlpc](https://github.com/SwftAlpc).
+* 🌐 Add Russian translation for `docs/ru/docs/tutorial/dependencies/dependencies-with-yield.md`. PR [#10532](https://github.com/tiangolo/fastapi/pull/10532) by [@AlertRED](https://github.com/AlertRED).
+* 🌐 Add Korean translation for `docs/ko/docs/tutorial/debugging.md`. PR [#5695](https://github.com/tiangolo/fastapi/pull/5695) by [@JungWooGeon](https://github.com/JungWooGeon).
+
+### Internal
+
+* ⬆️ Upgrade version of typer for docs. PR [#11393](https://github.com/tiangolo/fastapi/pull/11393) by [@tiangolo](https://github.com/tiangolo).
+
+## 0.110.1
+
+### Fixes
+
+* 🐛 Fix parameterless `Depends()` with generics. PR [#9479](https://github.com/tiangolo/fastapi/pull/9479) by [@nzig](https://github.com/nzig).
+
+### Refactors
+
+* ♻️ Update mypy. PR [#11049](https://github.com/tiangolo/fastapi/pull/11049) by [@k0t3n](https://github.com/k0t3n).
* ♻️ Simplify string format with f-strings in `fastapi/applications.py`. PR [#11335](https://github.com/tiangolo/fastapi/pull/11335) by [@igeni](https://github.com/igeni).
+### Upgrades
+
+* ⬆️ Upgrade Starlette to >=0.37.2,<0.38.0, remove Starlette filterwarning for internal tests. PR [#11266](https://github.com/tiangolo/fastapi/pull/11266) by [@nothielf](https://github.com/nothielf).
+
### Docs
* 📝 Tweak docs and translations links and remove old docs translations. PR [#11381](https://github.com/tiangolo/fastapi/pull/11381) by [@tiangolo](https://github.com/tiangolo).
@@ -27,6 +72,11 @@ hide:
### Translations
+* 🌐 Add German translation for `docs/de/docs/tutorial/response-status-code.md`. PR [#10357](https://github.com/tiangolo/fastapi/pull/10357) by [@nilslindemann](https://github.com/nilslindemann).
+* 🌐 Update Chinese translation for `docs/zh/docs/tutorial/query-params.md`. PR [#3480](https://github.com/tiangolo/fastapi/pull/3480) by [@jaystone776](https://github.com/jaystone776).
+* 🌐 Update Chinese translation for `docs/zh/docs/tutorial/body.md`. PR [#3481](https://github.com/tiangolo/fastapi/pull/3481) by [@jaystone776](https://github.com/jaystone776).
+* 🌐 Update Chinese translation for `docs/zh/docs/tutorial/path-params.md`. PR [#3479](https://github.com/tiangolo/fastapi/pull/3479) by [@jaystone776](https://github.com/jaystone776).
+* 🌐 Update Chinese translation for `docs/tutorial/body-fields.md`. PR [#3496](https://github.com/tiangolo/fastapi/pull/3496) by [@jaystone776](https://github.com/jaystone776).
* 🌐 Update Chinese translation for `docs/tutorial/extra-models.md`. PR [#3497](https://github.com/tiangolo/fastapi/pull/3497) by [@jaystone776](https://github.com/jaystone776).
* 🌐 Add Japanese translation for `docs/ja/docs/tutorial/metadata.md`. PR [#2667](https://github.com/tiangolo/fastapi/pull/2667) by [@tokusumi](https://github.com/tokusumi).
* 🌐 Add German translation for `docs/de/docs/contributing.md`. PR [#10487](https://github.com/tiangolo/fastapi/pull/10487) by [@nilslindemann](https://github.com/nilslindemann).
@@ -158,6 +208,13 @@ hide:
### Internal
+* 👥 Update FastAPI People. PR [#11387](https://github.com/tiangolo/fastapi/pull/11387) by [@tiangolo](https://github.com/tiangolo).
+* ⬆ Bump actions/cache from 3 to 4. PR [#10988](https://github.com/tiangolo/fastapi/pull/10988) by [@dependabot[bot]](https://github.com/apps/dependabot).
+* ⬆ Bump pypa/gh-action-pypi-publish from 1.8.11 to 1.8.14. PR [#11318](https://github.com/tiangolo/fastapi/pull/11318) by [@dependabot[bot]](https://github.com/apps/dependabot).
+* ⬆ Bump pillow from 10.1.0 to 10.2.0. PR [#11011](https://github.com/tiangolo/fastapi/pull/11011) by [@dependabot[bot]](https://github.com/apps/dependabot).
+* ⬆ Bump black from 23.3.0 to 24.3.0. PR [#11325](https://github.com/tiangolo/fastapi/pull/11325) by [@dependabot[bot]](https://github.com/apps/dependabot).
+* 👷 Add cron to run test once a week on monday. PR [#11377](https://github.com/tiangolo/fastapi/pull/11377) by [@estebanx64](https://github.com/estebanx64).
+* ➕ Replace mkdocs-markdownextradata-plugin with mkdocs-macros-plugin. PR [#11383](https://github.com/tiangolo/fastapi/pull/11383) by [@tiangolo](https://github.com/tiangolo).
* 👷 Disable MkDocs insiders social plugin while an issue in MkDocs Material is handled. PR [#11373](https://github.com/tiangolo/fastapi/pull/11373) by [@tiangolo](https://github.com/tiangolo).
* 👷 Fix logic for when to install and use MkDocs Insiders. PR [#11372](https://github.com/tiangolo/fastapi/pull/11372) by [@tiangolo](https://github.com/tiangolo).
* 👷 Do not use Python packages cache for publish. PR [#11366](https://github.com/tiangolo/fastapi/pull/11366) by [@tiangolo](https://github.com/tiangolo).
diff --git a/docs/en/docs/tutorial/bigger-applications.md b/docs/en/docs/tutorial/bigger-applications.md
index b2d9284052..eccdd8aebe 100644
--- a/docs/en/docs/tutorial/bigger-applications.md
+++ b/docs/en/docs/tutorial/bigger-applications.md
@@ -136,7 +136,7 @@ We will now use a simple dependency to read a custom `X-Token` header:
!!! 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}.
+ 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`
@@ -329,7 +329,7 @@ The section:
from .routers import items, users
```
-Means:
+means:
* Starting in the same package that this module (the file `app/main.py`) lives in (the directory `app/`)...
* look for the subpackage `routers` (the directory at `app/routers/`)...
@@ -373,7 +373,7 @@ from .routers.items import router
from .routers.users import router
```
-The `router` from `users` would overwrite the one from `items` and we wouldn't be able to use them at the same time.
+the `router` from `users` would overwrite the one from `items` and we wouldn't be able to use them at the same time.
So, to be able to use both of them in the same file, we import the submodules directly:
diff --git a/docs/en/docs/tutorial/body-updates.md b/docs/en/docs/tutorial/body-updates.md
index 39d133c55f..3ba2632d8f 100644
--- a/docs/en/docs/tutorial/body-updates.md
+++ b/docs/en/docs/tutorial/body-updates.md
@@ -48,7 +48,7 @@ You can also use the
-Cojes tus hamburguesas 🍔 y vas a la mesa con esa persona 😍.
+Coges tus hamburguesas 🍔 y vas a la mesa con esa persona 😍.
Sólo las comes y listo 🍔 ⏹.
@@ -400,7 +400,7 @@ Cuando declaras una *path operation function* con `def` normal en lugar de `asyn
Si vienes de otro framework asíncrono que no funciona de la manera descrita anteriormente y estás acostumbrado a definir *path operation functions* del tipo sólo cálculo con `def` simple para una pequeña ganancia de rendimiento (aproximadamente 100 nanosegundos), ten en cuenta que en **FastAPI** el efecto sería bastante opuesto. En estos casos, es mejor usar `async def` a menos que tus *path operation functions* usen un código que realice el bloqueo I/O.
-Aún así, en ambas situaciones, es probable que **FastAPI** sea [aún más rápido](index.md#performance){.Internal-link target=_blank} que (o al menos comparable) a tu framework anterior.
+Aún así, en ambas situaciones, es probable que **FastAPI** sea [aún más rápido](index.md#rendimiento){.Internal-link target=_blank} que (o al menos comparable) a tu framework anterior.
### Dependencias
diff --git a/docs/es/docs/index.md b/docs/es/docs/index.md
index b3d9c8bf22..776d98ce52 100644
--- a/docs/es/docs/index.md
+++ b/docs/es/docs/index.md
@@ -1,3 +1,12 @@
+---
+hide:
+ - navigation
+---
+
+
+
diff --git a/docs/es/docs/tutorial/first-steps.md b/docs/es/docs/tutorial/first-steps.md
index 2cb7e63084..c37ce00fb2 100644
--- a/docs/es/docs/tutorial/first-steps.md
+++ b/docs/es/docs/tutorial/first-steps.md
@@ -310,7 +310,7 @@ También podrías definirla como una función estándar en lugar de `async def`:
```
!!! note "Nota"
- Si no sabes la diferencia, revisa el [Async: *"¿Tienes prisa?"*](../async.md#in-a-hurry){.internal-link target=_blank}.
+ Si no sabes la diferencia, revisa el [Async: *"¿Tienes prisa?"*](../async.md#tienes-prisa){.internal-link target=_blank}.
### Paso 5: devuelve el contenido
diff --git a/docs/es/docs/tutorial/index.md b/docs/es/docs/tutorial/index.md
index f0dff02b42..f11820ef2c 100644
--- a/docs/es/docs/tutorial/index.md
+++ b/docs/es/docs/tutorial/index.md
@@ -50,7 +50,7 @@ $ pip install "fastapi[all]"
...eso también incluye `uvicorn` que puedes usar como el servidor que ejecuta tu código.
-!!! nota
+!!! note "Nota"
También puedes instalarlo parte por parte.
Esto es lo que probablemente harías una vez que desees implementar tu aplicación en producción:
diff --git a/docs/es/docs/tutorial/query-params.md b/docs/es/docs/tutorial/query-params.md
index 482af8dc06..76dc331a93 100644
--- a/docs/es/docs/tutorial/query-params.md
+++ b/docs/es/docs/tutorial/query-params.md
@@ -194,4 +194,4 @@ En este caso hay 3 parámetros de query:
* `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#predefined-values){.internal-link target=_blank}.
+ 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}.
diff --git a/docs/fa/docs/advanced/sub-applications.md b/docs/fa/docs/advanced/sub-applications.md
index f3a948414a..6f2359b94e 100644
--- a/docs/fa/docs/advanced/sub-applications.md
+++ b/docs/fa/docs/advanced/sub-applications.md
@@ -69,4 +69,4 @@ $ uvicorn main:app --reload
و زیر برنامه ها نیز می تواند زیر برنامه های متصل شده خود را داشته باشد و همه چیز به درستی کار کند، زیرا FastAPI تمام این مسیرهای `root_path` را به طور خودکار مدیریت می کند.
-در بخش [پشت پراکسی](./behind-a-proxy.md){.internal-link target=_blank}. درباره `root_path` و نحوه استفاده درست از آن بیشتر خواهید آموخت.
+در بخش [پشت پراکسی](behind-a-proxy.md){.internal-link target=_blank}. درباره `root_path` و نحوه استفاده درست از آن بیشتر خواهید آموخت.
diff --git a/docs/fa/docs/index.md b/docs/fa/docs/index.md
index e5231ec8d5..71c23b7f7b 100644
--- a/docs/fa/docs/index.md
+++ b/docs/fa/docs/index.md
@@ -1,3 +1,12 @@
+---
+hide:
+ - navigation
+---
+
+
+
@@ -30,7 +39,7 @@ FastAPI یک وب فریمورک مدرن و سریع (با کارایی با
ویژگیهای کلیدی این فریمورک عبارتند از:
-* **سرعت**: کارایی بسیار بالا و قابل مقایسه با **NodeJS** و **Go** (با تشکر از Starlette و Pydantic). [یکی از سریعترین فریمورکهای پایتونی موجود](#performance).
+* **سرعت**: کارایی بسیار بالا و قابل مقایسه با **NodeJS** و **Go** (با تشکر از Starlette و Pydantic). [یکی از سریعترین فریمورکهای پایتونی موجود](#_10).
* **کدنویسی سریع**: افزایش ۲۰۰ تا ۳۰۰ درصدی سرعت توسعه قابلیتهای جدید. *
* **باگ کمتر**: کاهش ۴۰ درصدی خطاهای انسانی (برنامهنویسی). *
diff --git a/docs/fr/docs/advanced/additional-responses.md b/docs/fr/docs/advanced/additional-responses.md
index 35b57594d5..685a054ad6 100644
--- a/docs/fr/docs/advanced/additional-responses.md
+++ b/docs/fr/docs/advanced/additional-responses.md
@@ -1,6 +1,6 @@
# Réponses supplémentaires dans OpenAPI
-!!! Attention
+!!! warning "Attention"
Ceci concerne un sujet plutôt avancé.
Si vous débutez avec **FastAPI**, vous n'en aurez peut-être pas besoin.
@@ -27,10 +27,10 @@ Par exemple, pour déclarer une autre réponse avec un code HTTP `404` et un mod
{!../../../docs_src/additional_responses/tutorial001.py!}
```
-!!! Remarque
+!!! note "Remarque"
Gardez à l'esprit que vous devez renvoyer directement `JSONResponse`.
-!!! Info
+!!! info
La clé `model` ne fait pas partie d'OpenAPI.
**FastAPI** prendra le modèle Pydantic à partir de là, générera le `JSON Schema` et le placera au bon endroit.
@@ -172,10 +172,10 @@ Par exemple, vous pouvez ajouter un type de média supplémentaire `image/png`,
{!../../../docs_src/additional_responses/tutorial002.py!}
```
-!!! Remarque
+!!! note "Remarque"
Notez que vous devez retourner l'image en utilisant directement un `FileResponse`.
-!!! Info
+!!! info
À moins que vous ne spécifiiez explicitement un type de média différent dans votre paramètre `responses`, FastAPI supposera que la réponse a le même type de média que la classe de réponse principale (par défaut `application/json`).
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.
@@ -206,7 +206,7 @@ Vous voulez peut-être avoir des réponses prédéfinies qui s'appliquent à de
Dans ces cas, vous pouvez utiliser la technique Python "d'affection par décomposition" (appelé _unpacking_ en anglais) d'un `dict` avec `**dict_to_unpack` :
-``` Python
+```Python
old_dict = {
"old key": "old value",
"second old key": "second old value",
@@ -216,7 +216,7 @@ new_dict = {**old_dict, "new key": "new value"}
Ici, `new_dict` contiendra toutes les paires clé-valeur de `old_dict` plus la nouvelle paire clé-valeur :
-``` Python
+```Python
{
"old key": "old value",
"second old key": "second old value",
diff --git a/docs/fr/docs/advanced/additional-status-codes.md b/docs/fr/docs/advanced/additional-status-codes.md
index e7b003707b..51f0db7371 100644
--- a/docs/fr/docs/advanced/additional-status-codes.md
+++ b/docs/fr/docs/advanced/additional-status-codes.md
@@ -18,7 +18,7 @@ Pour y parvenir, importez `JSONResponse` et renvoyez-y directement votre contenu
{!../../../docs_src/additional_status_codes/tutorial001.py!}
```
-!!! Attention
+!!! warning "Attention"
Lorsque vous renvoyez une `Response` directement, comme dans l'exemple ci-dessus, elle sera renvoyée directement.
Elle ne sera pas sérialisée avec un modèle.
diff --git a/docs/fr/docs/advanced/index.md b/docs/fr/docs/advanced/index.md
index aa37f18063..4599bcb6ff 100644
--- a/docs/fr/docs/advanced/index.md
+++ b/docs/fr/docs/advanced/index.md
@@ -6,7 +6,7 @@ Le [Tutoriel - Guide de l'utilisateur](../tutorial/index.md){.internal-link targ
Dans les sections suivantes, vous verrez des options, configurations et fonctionnalités supplémentaires.
-!!! Note
+!!! note "Remarque"
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.
diff --git a/docs/fr/docs/advanced/path-operation-advanced-configuration.md b/docs/fr/docs/advanced/path-operation-advanced-configuration.md
index 7ded97ce17..77f551aea9 100644
--- a/docs/fr/docs/advanced/path-operation-advanced-configuration.md
+++ b/docs/fr/docs/advanced/path-operation-advanced-configuration.md
@@ -2,7 +2,7 @@
## ID d'opération OpenAPI
-!!! Attention
+!!! 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`.
@@ -23,10 +23,10 @@ Vous devriez le faire après avoir ajouté toutes vos *paramètres de chemin*.
{!../../../docs_src/path_operation_advanced_configuration/tutorial002.py!}
```
-!!! Astuce
+!!! tip "Astuce"
Si vous appelez manuellement `app.openapi()`, vous devez mettre à jour les `operationId` avant.
-!!! Attention
+!!! 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).
@@ -59,7 +59,7 @@ Cela définit les métadonnées sur la réponse principale d'une *opération de
Vous pouvez également déclarer des réponses supplémentaires avec leurs modèles, codes de statut, etc.
-Il y a un chapitre entier ici dans la documentation à ce sujet, vous pouvez le lire sur [Réponses supplémentaires dans OpenAPI](./additional-responses.md){.internal-link target=_blank}.
+Il y a un chapitre entier ici dans la documentation à ce sujet, vous pouvez le lire sur [Réponses supplémentaires dans OpenAPI](additional-responses.md){.internal-link target=_blank}.
## OpenAPI supplémentaire
@@ -74,8 +74,8 @@ Il inclut les `tags`, `parameters`, `requestBody`, `responses`, etc.
Ce schéma OpenAPI spécifique aux *operations* est normalement généré automatiquement par **FastAPI**, mais vous pouvez également l'étendre.
-!!! Astuce
- Si vous avez seulement besoin de déclarer des réponses supplémentaires, un moyen plus pratique de le faire est d'utiliser les [réponses supplémentaires dans OpenAPI](./additional-responses.md){.internal-link target=_blank}.
+!!! tip "Astuce"
+ Si vous avez seulement besoin de déclarer des réponses supplémentaires, un moyen plus pratique de le faire est d'utiliser les [réponses supplémentaires dans OpenAPI](additional-responses.md){.internal-link target=_blank}.
Vous pouvez étendre le schéma OpenAPI pour une *opération de chemin* en utilisant le paramètre `openapi_extra`.
@@ -162,7 +162,7 @@ Et nous analysons directement ce contenu YAML, puis nous utilisons à nouveau le
{!../../../docs_src/path_operation_advanced_configuration/tutorial007.py!}
```
-!!! Astuce
+!!! 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.
diff --git a/docs/fr/docs/advanced/response-directly.md b/docs/fr/docs/advanced/response-directly.md
index 1c923fb82c..ed29446d4c 100644
--- a/docs/fr/docs/advanced/response-directly.md
+++ b/docs/fr/docs/advanced/response-directly.md
@@ -14,7 +14,7 @@ Cela peut être utile, par exemple, pour retourner des en-têtes personnalisés
En fait, vous pouvez retourner n'importe quelle `Response` ou n'importe quelle sous-classe de celle-ci.
-!!! Note
+!!! note "Remarque"
`JSONResponse` est elle-même une sous-classe de `Response`.
Et quand vous retournez une `Response`, **FastAPI** la transmet directement.
diff --git a/docs/fr/docs/fastapi-people.md b/docs/fr/docs/fastapi-people.md
index 275a9bd37c..d99dcd9c2b 100644
--- a/docs/fr/docs/fastapi-people.md
+++ b/docs/fr/docs/fastapi-people.md
@@ -1,3 +1,8 @@
+---
+hide:
+ - navigation
+---
+
# La communauté FastAPI
FastAPI a une communauté extraordinaire qui accueille des personnes de tous horizons.
@@ -18,7 +23,7 @@ C'est moi :
+
+## レスポンスの説明
+
+`response_description`パラメータでレスポンスの説明をすることができます。
+
+```Python hl_lines="21"
+{!../../../docs_src/path_operation_configuration/tutorial005.py!}
+```
+
+!!! info "情報"
+ `respnse_description`は具体的にレスポンスを参照し、`description`は*path operation*全般を参照していることに注意してください。
+
+!!! check "確認"
+ OpenAPIは*path operation*ごとにレスポンスの説明を必要としています。
+
+ そのため、それを提供しない場合は、**FastAPI** が自動的に「成功のレスポンス」を生成します。
+
+
+
+## 非推奨の*path operation*
+
+*path operation*をdeprecatedとしてマークする必要があるが、それを削除しない場合は、`deprecated`パラメータを渡します:
+
+```Python hl_lines="16"
+{!../../../docs_src/path_operation_configuration/tutorial006.py!}
+```
+
+対話的ドキュメントでは非推奨と明記されます:
+
+
+
+*path operations*が非推奨である場合とそうでない場合でどのように見えるかを確認してください:
+
+
+
+## まとめ
+
+*path operationデコレータ*にパラメータを渡すことで、*path operations*のメタデータを簡単に設定・追加することができます。
diff --git a/docs/ja/docs/tutorial/query-params.md b/docs/ja/docs/tutorial/query-params.md
index 957726b9f0..5c4cfc5fcc 100644
--- a/docs/ja/docs/tutorial/query-params.md
+++ b/docs/ja/docs/tutorial/query-params.md
@@ -191,4 +191,4 @@ http://127.0.0.1:8000/items/foo-item?needy=sooooneedy
!!! tip "豆知識"
- [パスパラメータ](path-params.md#predefined-values){.internal-link target=_blank}と同様に `Enum` を使用できます。
+ [パスパラメータ](path-params.md#_8){.internal-link target=_blank}と同様に `Enum` を使用できます。
diff --git a/docs/ja/docs/tutorial/request-forms-and-files.md b/docs/ja/docs/tutorial/request-forms-and-files.md
new file mode 100644
index 0000000000..86913ccaca
--- /dev/null
+++ b/docs/ja/docs/tutorial/request-forms-and-files.md
@@ -0,0 +1,35 @@
+# リクエストフォームとファイル
+
+`File`と`Form`を同時に使うことでファイルとフォームフィールドを定義することができます。
+
+!!! info "情報"
+ アップロードされたファイルやフォームデータを受信するには、まず`python-multipart`をインストールします。
+
+ 例えば、`pip install python-multipart`のように。
+
+## `File`と`Form`のインポート
+
+```Python hl_lines="1"
+{!../../../docs_src/request_forms_and_files/tutorial001.py!}
+```
+
+## `File`と`Form`のパラメータの定義
+
+ファイルやフォームのパラメータは`Body`や`Query`の場合と同じように作成します:
+
+```Python hl_lines="8"
+{!../../../docs_src/request_forms_and_files/tutorial001.py!}
+```
+
+ファイルとフォームフィールドがフォームデータとしてアップロードされ、ファイルとフォームフィールドを受け取ります。
+
+また、いくつかのファイルを`bytes`として、いくつかのファイルを`UploadFile`として宣言することができます。
+
+!!! warning "注意"
+ *path operation*で複数の`File`と`Form`パラメータを宣言することができますが、JSONとして受け取ることを期待している`Body`フィールドを宣言することはできません。なぜなら、リクエストのボディは`application/json`の代わりに`multipart/form-data`を使ってエンコードされているからです。
+
+ これは **FastAPI** の制限ではなく、HTTPプロトコルの一部です。
+
+## まとめ
+
+同じリクエストでデータやファイルを受け取る必要がある場合は、`File` と`Form`を一緒に使用します。
diff --git a/docs/ja/docs/tutorial/security/first-steps.md b/docs/ja/docs/tutorial/security/first-steps.md
index f1c43b7b45..dc3267e62b 100644
--- a/docs/ja/docs/tutorial/security/first-steps.md
+++ b/docs/ja/docs/tutorial/security/first-steps.md
@@ -125,7 +125,7 @@ OAuth2は、バックエンドやAPIがユーザーを認証するサーバー
相対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 ドキュメントシステムで使われます。
diff --git a/docs/ko/docs/advanced/events.md b/docs/ko/docs/advanced/events.md
new file mode 100644
index 0000000000..d3227497bc
--- /dev/null
+++ b/docs/ko/docs/advanced/events.md
@@ -0,0 +1,45 @@
+# 이벤트: startup과 shutdown
+
+필요에 따라 응용 프로그램이 시작되기 전이나 종료될 때 실행되는 이벤트 핸들러(함수)를 정의할 수 있습니다.
+
+이 함수들은 `async def` 또는 평범하게 `def`으로 선언할 수 있습니다.
+
+!!! warning "경고"
+ 이벤트 핸들러는 주 응용 프로그램에서만 작동합니다. [하위 응용 프로그램 - 마운트](./sub-applications.md){.internal-link target=_blank}에서는 작동하지 않습니다.
+
+## `startup` 이벤트
+
+응용 프로그램을 시작하기 전에 실행하려는 함수를 "startup" 이벤트로 선언합니다:
+
+```Python hl_lines="8"
+{!../../../docs_src/events/tutorial001.py!}
+```
+
+이 경우 `startup` 이벤트 핸들러 함수는 단순히 몇 가지 값으로 구성된 `dict` 형식의 "데이터베이스"를 초기화합니다.
+
+하나 이상의 이벤트 핸들러 함수를 추가할 수도 있습니다.
+
+그리고 응용 프로그램은 모든 `startup` 이벤트 핸들러가 완료될 때까지 요청을 받지 않습니다.
+
+## `shutdown` 이벤트
+
+응용 프로그램이 종료될 때 실행하려는 함수를 추가하려면 `"shutdown"` 이벤트로 선언합니다:
+
+```Python hl_lines="6"
+{!../../../docs_src/events/tutorial002.py!}
+```
+
+이 예제에서 `shutdown` 이벤트 핸들러 함수는 `"Application shutdown"`이라는 텍스트가 적힌 `log.txt` 파일을 추가할 것입니다.
+
+!!! info "정보"
+ `open()` 함수에서 `mode="a"`는 "추가"를 의미합니다. 따라서 이미 존재하는 파일의 내용을 덮어쓰지 않고 새로운 줄을 추가합니다.
+
+!!! tip "팁"
+ 이 예제에서는 파일과 상호작용 하기 위해 파이썬 표준 함수인 `open()`을 사용하고 있습니다.
+
+ 따라서 디스크에 데이터를 쓰기 위해 "대기"가 필요한 I/O (입력/출력) 작업을 수행합니다.
+
+ 그러나 `open()`은 `async`와 `await`을 사용하지 않기 때문에 이벤트 핸들러 함수는 `async def`가 아닌 표준 `def`로 선언하고 있습니다.
+
+!!! info "정보"
+ 이벤트 핸들러에 관한 내용은 Starlette 이벤트 문서에서 추가로 확인할 수 있습니다.
diff --git a/docs/ko/docs/async.md b/docs/ko/docs/async.md
index 9bcebd3676..65ee124ecd 100644
--- a/docs/ko/docs/async.md
+++ b/docs/ko/docs/async.md
@@ -2,7 +2,7 @@
*경로 작동 함수*에서의 `async def` 문법에 대한 세부사항과 비동기 코드, 동시성 및 병렬성에 대한 배경
-## 바쁘신 경우
+## 바쁘신 경우
요약
@@ -263,7 +263,7 @@ CPU에 묶인 연산에 관한 흔한 예시는 복잡한 수학 처리를 필
파이썬이 **데이터 사이언스**, 머신러닝과 특히 딥러닝에 의 주된 언어라는 간단한 사실에 더해서, 이것은 FastAPI를 데이터 사이언스 / 머신러닝 웹 API와 응용프로그램에 (다른 것들보다) 좋은 선택지가 되게 합니다.
-배포시 병렬을 어떻게 가능하게 하는지 알고싶다면, [배포](/ko/deployment){.internal-link target=_blank}문서를 참고하십시오.
+배포시 병렬을 어떻게 가능하게 하는지 알고싶다면, [배포](deployment/index.md){.internal-link target=_blank}문서를 참고하십시오.
## `async`와 `await`
@@ -379,7 +379,7 @@ FastAPI를 사용하지 않더라도, 높은 호환성 및 I/O를 수행하는 코드를 사용하지 않는 한 `async def`를 사용하는 편이 더 낫습니다.
-하지만 두 경우 모두, FastAPI가 당신이 전에 사용하던 프레임워크보다 [더 빠를](index.md#performance){.internal-link target=_blank} (최소한 비견될) 확률이 높습니다.
+하지만 두 경우 모두, FastAPI가 당신이 전에 사용하던 프레임워크보다 [더 빠를](index.md#_11){.internal-link target=_blank} (최소한 비견될) 확률이 높습니다.
### 의존성
@@ -401,4 +401,4 @@ FastAPI를 사용하지 않더라도, 높은 호환성 및 **구니콘**을 **유비콘 워커 프로세스**와 함께 사용하는 방법을 알려드리겠습니다.
-!!! 정보
- 만약 도커와 쿠버네티스 같은 컨테이너를 사용하고 있다면 다음 챕터 [FastAPI와 컨테이너 - 도커](./docker.md){.internal-link target=_blank}에서 더 많은 정보를 얻을 수 있습니다.
+!!! info "정보"
+ 만약 도커와 쿠버네티스 같은 컨테이너를 사용하고 있다면 다음 챕터 [FastAPI와 컨테이너 - 도커](docker.md){.internal-link target=_blank}에서 더 많은 정보를 얻을 수 있습니다.
특히, 쿠버네티스에서 실행할 때는 구니콘을 사용하지 않고 대신 컨테이너당 하나의 유비콘 프로세스를 실행하는 것이 좋습니다. 이 장의 뒷부분에서 설명하겠습니다.
@@ -165,7 +165,7 @@ $ uvicorn main:app --host 0.0.0.0 --port 8080 --workers 4
## 컨테이너와 도커
-다음 장인 [FastAPI와 컨테이너 - 도커](./docker.md){.internal-link target=_blank}에서 다른 **배포 개념들**을 다루는 전략들을 알려드리겠습니다.
+다음 장인 [FastAPI와 컨테이너 - 도커](docker.md){.internal-link target=_blank}에서 다른 **배포 개념들**을 다루는 전략들을 알려드리겠습니다.
또한 간단한 케이스에서 사용할 수 있는, **구니콘과 유비콘 워커**가 포함돼 있는 **공식 도커 이미지**와 함께 몇 가지 기본 구성을 보여드리겠습니다.
diff --git a/docs/ko/docs/features.md b/docs/ko/docs/features.md
index 54479165e8..f7b35557ca 100644
--- a/docs/ko/docs/features.md
+++ b/docs/ko/docs/features.md
@@ -68,7 +68,7 @@ second_user_data = {
my_second_user: User = User(**second_user_data)
```
-!!! 정보
+!!! info "정보"
`**second_user_data`가 뜻하는 것:
`second_user_data` 딕셔너리의 키와 값을 키-값 인자로서 바로 넘겨줍니다. 다음과 동일합니다: `User(id=4, name="Mary", joined="2018-11-30")`
diff --git a/docs/ko/docs/help-fastapi.md b/docs/ko/docs/help-fastapi.md
new file mode 100644
index 0000000000..4faf4c1f05
--- /dev/null
+++ b/docs/ko/docs/help-fastapi.md
@@ -0,0 +1,158 @@
+* # FastAPI 지원 - 도움말 받기
+
+ **FastAPI** 가 마음에 드시나요?
+
+ FastAPI, 다른 사용자, 개발자를 응원하고 싶으신가요?
+
+ 혹은 **FastAPI** 에 대해 도움이 필요하신가요?
+
+ 아주 간단하게 응원할 수 있습니다 (몇 번의 클릭만으로).
+
+ 또한 도움을 받을 수 있는 방법도 몇 가지 있습니다.
+
+ ## 뉴스레터 구독
+
+ [**FastAPI와 친구** 뉴스레터](https://github.com/tiangolo/fastapi/blob/master/newsletter)를 구독하여 최신 정보를 유지할 수 있습니다{.internal-link target=_blank}:
+
+ - FastAPI 와 그 친구들에 대한 뉴스 🚀
+ - 가이드 📝
+ - 특징 ✨
+ - 획기적인 변화 🚨
+ - 팁과 요령 ✅
+
+ ## 트위터에서 FastAPI 팔로우하기
+
+ [Follow @fastapi on **Twitter**](https://twitter.com/fastapi) 를 팔로우하여 **FastAPI** 에 대한 최신 뉴스를 얻을 수 있습니다. 🐦
+
+ ## Star **FastAPI** in GitHub
+
+ GitHub에서 FastAPI에 "star"를 붙일 수 있습니다(오른쪽 상단의 star 버튼을 클릭): https://github.com/tiangolo/fastapi. ⭐️
+
+ 스타를 늘림으로써, 다른 사용자들이 좀 더 쉽게 찾을 수 있고, 많은 사람들에게 유용한 것임을 나타낼 수 있습니다.
+
+ ## GitHub 저장소에서 릴리즈 확인
+
+ GitHub에서 FastAPI를 "watch"할 수 있습니다 (오른쪽 상단 watch 버튼을 클릭): https://github.com/tiangolo/fastapi. 👀
+
+ 여기서 "Releases only"을 선택할 수 있습니다.
+
+ 이렇게하면, **FastAPI** 의 버그 수정 및 새로운 기능의 구현 등의 새로운 자료 (최신 버전)이 있을 때마다 (이메일) 통지를 받을 수 있습니다.
+
+ ## 개발자와의 연결
+
+ 개발자인 [me (Sebastián Ramírez / `tiangolo`)](https://tiangolo.com/) 와 연락을 취할 수 있습니다.
+
+ 여러분은 할 수 있습니다:
+
+ - [**GitHub**에서 팔로우하기](https://github.com/tiangolo).
+ - 당신에게 도움이 될 저의 다른 오픈소스 프로젝트를 확인하십시오.
+ - 새로운 오픈소스 프로젝트를 만들었을 때 확인하려면 팔로우 하십시오.
+
+ - [**Twitter**에서 팔로우하기](https://twitter.com/tiangolo).
+ - FastAPI의 사용 용도를 알려주세요 (그것을 듣는 것을 좋아합니다).
+ - 발표 또는 새로운 툴 출시할 때 들으십시오.
+ - [follow @fastapi on Twitter](https://twitter.com/fastapi) (별도 계정에서) 할 수 있습니다.
+
+ - [**Linkedin**에서의 연결](https://www.linkedin.com/in/tiangolo/).
+ - 새로운 툴의 발표나 릴리스를 들을 수 있습니다 (단, Twitter를 더 자주 사용합니다 🤷♂).
+
+ - [**Dev.to**](https://dev.to/tiangolo) 또는 [**Medium**](https://medium.com/@tiangolo)에서 제가 작성한 내용을 읽어 보십시오(또는 팔로우).
+ - 다른 기사나 아이디어들을 읽고, 제가 만들어왔던 툴에 대해서도 읽으십시오.
+ - 새로운 기사를 읽기 위해 팔로우 하십시오.
+
+ ## **FastAPI**에 대한 트윗
+
+ [**FastAPI**에 대해 트윗](https://twitter.com/compose/tweet?text=I'm loving @fastapi because... https://github.com/tiangolo/fastapi) 하고 FastAPI가 마음에 드는 이유를 알려주세요. 🎉
+
+ **FastAPI**가 어떻게 사용되고 있는지, 어떤 점이 마음에 들었는지, 어떤 프로젝트/회사에서 사용하고 있는지 등에 대해 듣고 싶습니다.
+
+ ## FastAPI에 투표하기
+
+ - [Slant에서 **FastAPI** 에 대해 투표하십시오](https://www.slant.co/options/34241/~fastapi-review).
+ - [AlternativeTo**FastAPI** 에 대해 투표하십시오](https://alternativeto.net/software/fastapi/).
+
+ ## GitHub의 이슈로 다른사람 돕기
+
+ [존재하는 이슈](https://github.com/tiangolo/fastapi/issues)를 확인하고 그것을 시도하고 도와줄 수 있습니다. 대부분의 경우 이미 답을 알고 있는 질문입니다. 🤓
+
+ 많은 사람들의 문제를 도와준다면, 공식적인 [FastAPI 전문가](https://github.com/tiangolo/fastapi/blob/master/docs/en/docs/fastapi-people.md#experts) 가 될 수 있습니다{.internal-link target=_blank}. 🎉
+
+ ## GitHub 저장소 보기
+
+ GitHub에서 FastAPI를 "watch"할 수 있습니다 (오른쪽 상단 watch 버튼을 클릭): https://github.com/tiangolo/fastapi. 👀
+
+ "Releases only" 대신 "Watching"을 선택하면 다른 사용자가 새로운 issue를 생성할 때 알림이 수신됩니다.
+
+ 그런 다음 이런 issues를 해결 할 수 있도록 도움을 줄 수 있습니다.
+
+ ## 이슈 생성하기
+
+ GitHub 저장소에 [새로운 이슈 생성](https://github.com/tiangolo/fastapi/issues/new/choose) 을 할 수 있습니다, 예를들면 다음과 같습니다:
+
+ - **질문**을 하거나 **문제**에 대해 질문합니다.
+ - 새로운 **기능**을 제안 합니다.
+
+ **참고**: 만약 이슈를 생성한다면, 저는 여러분에게 다른 사람들을 도와달라고 부탁할 것입니다. 😉
+
+ ## Pull Request를 만드십시오
+
+ Pull Requests를 이용하여 소스코드에 [컨트리뷰트](https://github.com/tiangolo/fastapi/blob/master/docs/en/docs/contributing.md){.internal-link target=_blank} 할 수 있습니다. 예를 들면 다음과 같습니다:
+
+ - 문서에서 찾은 오타를 수정할 때.
+
+ - FastAPI를 [편집하여](https://github.com/tiangolo/fastapi/edit/master/docs/en/data/external_links.yml) 작성했거나 찾은 문서, 비디오 또는 팟캐스트를 공유할 때.
+
+ - 해당 섹션의 시작 부분에 링크를 추가했는지 확인하십시오.
+
+ - 당신의 언어로 [문서 번역하는데](https://github.com/tiangolo/fastapi/blob/master/docs/en/docs/contributing.md#translations){.internal-link target=_blank} 기여할 때.
+
+ - 또한 다른 사용자가 만든 번역을 검토하는데 도움을 줄 수도 있습니다.
+
+ - 새로운 문서의 섹션을 제안할 때.
+
+ - 기존 문제/버그를 수정할 때.
+
+ - 새로운 feature를 추가할 때.
+
+ ## 채팅에 참여하십시오
+
+ 👥 [디스코드 채팅 서버](https://discord.gg/VQjSZaeJmf) 👥 에 가입하고 FastAPI 커뮤니티에서 다른 사람들과 어울리세요.
+
+ !!! tip 질문이 있는 경우, [GitHub 이슈 ](https://github.com/tiangolo/fastapi/issues/new/choose) 에서 질문하십시오, [FastAPI 전문가](https://github.com/tiangolo/fastapi/blob/master/docs/en/docs/fastapi-people.md#experts) 의 도움을 받을 가능성이 높습니다{.internal-link target=_blank} .
+
+ ```
+ 다른 일반적인 대화에서만 채팅을 사용하십시오.
+ ```
+
+ 기존 [지터 채팅](https://gitter.im/tiangolo/fastapi) 이 있지만 채널과 고급기능이 없어서 대화를 하기가 조금 어렵기 때문에 지금은 디스코드가 권장되는 시스템입니다.
+
+ ### 질문을 위해 채팅을 사용하지 마십시오
+
+ 채팅은 더 많은 "자유로운 대화"를 허용하기 때문에, 너무 일반적인 질문이나 대답하기 어려운 질문을 쉽게 질문을 할 수 있으므로, 답변을 받지 못할 수 있습니다.
+
+ GitHub 이슈에서의 템플릿은 올바른 질문을 작성하도록 안내하여 더 쉽게 좋은 답변을 얻거나 질문하기 전에 스스로 문제를 해결할 수도 있습니다. 그리고 GitHub에서는 시간이 조금 걸리더라도 항상 모든 것에 답할 수 있습니다. 채팅 시스템에서는 개인적으로 그렇게 할 수 없습니다. 😅
+
+ 채팅 시스템에서의 대화 또한 GitHub에서 처럼 쉽게 검색할 수 없기 때문에 대화 중에 질문과 답변이 손실될 수 있습니다. 그리고 GitHub 이슈에 있는 것만 [FastAPI 전문가](https://github.com/tiangolo/fastapi/blob/master/docs/en/docs/fastapi-people.md#experts)가 되는 것으로 간주되므로{.internal-link target=_blank} , GitHub 이슈에서 더 많은 관심을 받을 것입니다.
+
+ 반면, 채팅 시스템에는 수천 명의 사용자가 있기 때문에, 거의 항상 대화 상대를 찾을 가능성이 높습니다. 😄
+
+ ## 개발자 스폰서가 되십시오
+
+ [GitHub 스폰서](https://github.com/sponsors/tiangolo) 를 통해 개발자를 경제적으로 지원할 수 있습니다.
+
+ 감사하다는 말로 커피를 ☕️ 한잔 사줄 수 있습니다. 😄
+
+ 또한 FastAPI의 실버 또는 골드 스폰서가 될 수 있습니다. 🏅🎉
+
+ ## FastAPI를 강화하는 도구의 스폰서가 되십시오
+
+ 문서에서 보았듯이, FastAPI는 Starlette과 Pydantic 라는 거인의 어깨에 타고 있습니다.
+
+ 다음의 스폰서가 될 수 있습니다
+
+ - [Samuel Colvin (Pydantic)](https://github.com/sponsors/samuelcolvin)
+ - [Encode (Starlette, Uvicorn)](https://github.com/sponsors/encode)
+
+ ------
+
+ 감사합니다! 🚀
diff --git a/docs/ko/docs/index.md b/docs/ko/docs/index.md
index eeadc0363c..85482718e5 100644
--- a/docs/ko/docs/index.md
+++ b/docs/ko/docs/index.md
@@ -1,3 +1,12 @@
+---
+hide:
+ - navigation
+---
+
+
+
@@ -28,7 +37,7 @@ FastAPI는 현대적이고, 빠르며(고성능), 파이썬 표준 타입 힌트
주요 특징으로:
-* **빠름**: (Starlette과 Pydantic 덕분에) **NodeJS** 및 **Go**와 대등할 정도로 매우 높은 성능. [사용 가능한 가장 빠른 파이썬 프레임워크 중 하나](#performance).
+* **빠름**: (Starlette과 Pydantic 덕분에) **NodeJS** 및 **Go**와 대등할 정도로 매우 높은 성능. [사용 가능한 가장 빠른 파이썬 프레임워크 중 하나](#_11).
* **빠른 코드 작성**: 약 200%에서 300%까지 기능 개발 속도 증가. *
* **적은 버그**: 사람(개발자)에 의한 에러 약 40% 감소. *
diff --git a/docs/ko/docs/tutorial/body-fields.md b/docs/ko/docs/tutorial/body-fields.md
index fc7209726c..c91d6130b9 100644
--- a/docs/ko/docs/tutorial/body-fields.md
+++ b/docs/ko/docs/tutorial/body-fields.md
@@ -26,7 +26,7 @@
=== "Python 3.10+ Annotated가 없는 경우"
- !!! 팁
+ !!! tip "팁"
가능하다면 `Annotated`가 달린 버전을 권장합니다.
```Python hl_lines="2"
diff --git a/docs/ko/docs/tutorial/body.md b/docs/ko/docs/tutorial/body.md
index 8b98284bb2..0ab8b71626 100644
--- a/docs/ko/docs/tutorial/body.md
+++ b/docs/ko/docs/tutorial/body.md
@@ -8,7 +8,7 @@
**요청** 본문을 선언하기 위해서 모든 강력함과 이점을 갖춘 Pydantic 모델을 사용합니다.
-!!! 정보
+!!! info "정보"
데이터를 보내기 위해, (좀 더 보편적인) `POST`, `PUT`, `DELETE` 혹은 `PATCH` 중에 하나를 사용하는 것이 좋습니다.
`GET` 요청에 본문을 담아 보내는 것은 명세서에 정의되지 않은 행동입니다. 그럼에도 불구하고, 이 방식은 아주 복잡한/극한의 사용 상황에서만 FastAPI에 의해 지원됩니다.
@@ -134,7 +134,7 @@
-!!! 팁
+!!! tip "팁"
만약 PyCharm를 편집기로 사용한다면, Pydantic PyCharm Plugin을 사용할 수 있습니다.
다음 사항을 포함해 Pydantic 모델에 대한 편집기 지원을 향상시킵니다:
@@ -203,11 +203,11 @@
* 만약 매개변수가 (`int`, `float`, `str`, `bool` 등과 같은) **유일한 타입**으로 되어있으면, **쿼리** 매개변수로 해석될 것입니다.
* 만약 매개변수가 **Pydantic 모델** 타입으로 선언되어 있으면, 요청 **본문**으로 해석될 것입니다.
-!!! 참고
+!!! note "참고"
FastAPI는 `q`의 값이 필요없음을 알게 될 것입니다. 기본 값이 `= None`이기 때문입니다.
`Union[str, None]`에 있는 `Union`은 FastAPI에 의해 사용된 것이 아니지만, 편집기로 하여금 더 나은 지원과 에러 탐지를 지원할 것입니다.
## Pydantic없이
-만약 Pydantic 모델을 사용하고 싶지 않다면, **Body** 매개변수를 사용할 수도 있습니다. [Body - 다중 매개변수: 본문에 있는 유일한 값](body-multiple-params.md#singular-values-in-body){.internal-link target=_blank} 문서를 확인하세요.
+만약 Pydantic 모델을 사용하고 싶지 않다면, **Body** 매개변수를 사용할 수도 있습니다. [Body - 다중 매개변수: 본문에 있는 유일한 값](body-multiple-params.md#_2){.internal-link target=_blank} 문서를 확인하세요.
diff --git a/docs/ko/docs/tutorial/debugging.md b/docs/ko/docs/tutorial/debugging.md
new file mode 100644
index 0000000000..c3e5885375
--- /dev/null
+++ b/docs/ko/docs/tutorial/debugging.md
@@ -0,0 +1,112 @@
+# 디버깅
+
+예를 들면 Visual Studio Code 또는 PyCharm을 사용하여 편집기에서 디버거를 연결할 수 있습니다.
+
+## `uvicorn` 호출
+
+FastAPI 애플리케이션에서 `uvicorn`을 직접 임포트하여 실행합니다
+
+```Python hl_lines="1 15"
+{!../../../docs_src/debugging/tutorial001.py!}
+```
+
+### `__name__ == "__main__"` 에 대하여
+
+`__name__ == "__main__"`의 주요 목적은 다음과 같이 파일이 호출될 때 실행되는 일부 코드를 갖는 것입니다.
+
+
+
+---
+
+Pycharm을 사용하는 경우 다음을 수행할 수 있습니다
+
+* "Run" 메뉴를 엽니다
+* "Debug..." 옵션을 선택합니다.
+* 그러면 상황에 맞는 메뉴가 나타납니다.
+* 디버그할 파일을 선택합니다(이 경우 `main.py`).
+
+그런 다음 **FastAPI** 코드로 서버를 시작하고 중단점 등에서 중지합니다.
+
+다음과 같이 표시됩니다.
+
+
diff --git a/docs/ko/docs/tutorial/dependencies/index.md b/docs/ko/docs/tutorial/dependencies/index.md
index c56dddae3a..d06864ab81 100644
--- a/docs/ko/docs/tutorial/dependencies/index.md
+++ b/docs/ko/docs/tutorial/dependencies/index.md
@@ -85,12 +85,12 @@
그 후 위의 값을 포함한 `dict` 자료형으로 반환할 뿐입니다.
-!!! 정보
+!!! info "정보"
FastAPI는 0.95.0 버전부터 `Annotated`에 대한 지원을 (그리고 이를 사용하기 권장합니다) 추가했습니다.
옛날 버전을 가지고 있는 경우, `Annotated`를 사용하려 하면 에러를 맞이하게 될 것입니다.
- `Annotated`를 사용하기 전에 최소 0.95.1로 [FastAPI 버전 업그레이드](../../deployment/versions.md#upgrading-the-fastapi-versions){.internal-link target=_blank}를 확실하게 하세요.
+ `Annotated`를 사용하기 전에 최소 0.95.1로 [FastAPI 버전 업그레이드](../../deployment/versions.md#fastapi_2){.internal-link target=_blank}를 확실하게 하세요.
### `Depends` 불러오기
diff --git a/docs/ko/docs/tutorial/first-steps.md b/docs/ko/docs/tutorial/first-steps.md
index e3b42bce73..bdec3a3776 100644
--- a/docs/ko/docs/tutorial/first-steps.md
+++ b/docs/ko/docs/tutorial/first-steps.md
@@ -310,7 +310,7 @@ URL "`/`"에 대한 `GET` 작동을 사용하는 요청을 받을 때마다 **Fa
```
!!! note "참고"
- 차이점을 모르겠다면 [Async: *"In a hurry?"*](../async.md#in-a-hurry){.internal-link target=_blank}을 확인하세요.
+ 차이점을 모르겠다면 [Async: *"바쁘신 경우"*](../async.md#_1){.internal-link target=_blank}을 확인하세요.
### 5 단계: 콘텐츠 반환
diff --git a/docs/ko/docs/tutorial/query-params.md b/docs/ko/docs/tutorial/query-params.md
index 8c7f9167b0..43a6c1a36f 100644
--- a/docs/ko/docs/tutorial/query-params.md
+++ b/docs/ko/docs/tutorial/query-params.md
@@ -195,4 +195,4 @@ http://127.0.0.1:8000/items/foo-item?needy=sooooneedy
* `limit`, 선택적인 `int`.
!!! tip "팁"
- [경로 매개변수](path-params.md#predefined-values){.internal-link target=_blank}와 마찬가지로 `Enum`을 사용할 수 있습니다.
+ [경로 매개변수](path-params.md#_8){.internal-link target=_blank}와 마찬가지로 `Enum`을 사용할 수 있습니다.
diff --git a/docs/ko/docs/tutorial/security/get-current-user.md b/docs/ko/docs/tutorial/security/get-current-user.md
index 5bc2cee7a0..f4b6f94717 100644
--- a/docs/ko/docs/tutorial/security/get-current-user.md
+++ b/docs/ko/docs/tutorial/security/get-current-user.md
@@ -86,12 +86,12 @@ Pydantic 모델인 `User`로 `current_user`의 타입을 선언하는 것을 알
이것은 모든 완료 및 타입 검사를 통해 함수 내부에서 우리를 도울 것입니다.
-!!! 팁
+!!! tip "팁"
요청 본문도 Pydantic 모델로 선언된다는 것을 기억할 것입니다.
여기서 **FastAPI**는 `Depends`를 사용하고 있기 때문에 혼동되지 않습니다.
-!!! 확인
+!!! check "확인"
이 의존성 시스템이 설계된 방식은 모두 `User` 모델을 반환하는 다양한 의존성(다른 "의존적인")을 가질 수 있도록 합니다.
해당 타입의 데이터를 반환할 수 있는 의존성이 하나만 있는 것으로 제한되지 않습니다.
diff --git a/docs/ko/docs/tutorial/security/simple-oauth2.md b/docs/ko/docs/tutorial/security/simple-oauth2.md
new file mode 100644
index 0000000000..1e33f57667
--- /dev/null
+++ b/docs/ko/docs/tutorial/security/simple-oauth2.md
@@ -0,0 +1,315 @@
+# 패스워드와 Bearer를 이용한 간단한 OAuth2
+
+이제 이전 장에서 빌드하고 누락된 부분을 추가하여 완전한 보안 흐름을 갖도록 하겠습니다.
+
+## `username`와 `password` 얻기
+
+**FastAPI** 보안 유틸리티를 사용하여 `username` 및 `password`를 가져올 것입니다.
+
+OAuth2는 (우리가 사용하고 있는) "패스워드 플로우"을 사용할 때 클라이언트/유저가 `username` 및 `password` 필드를 폼 데이터로 보내야 함을 지정합니다.
+
+그리고 사양에는 필드의 이름을 그렇게 지정해야 한다고 나와 있습니다. 따라서 `user-name` 또는 `email`은 작동하지 않습니다.
+
+하지만 걱정하지 않아도 됩니다. 프런트엔드에서 최종 사용자에게 원하는 대로 표시할 수 있습니다.
+
+그리고 데이터베이스 모델은 원하는 다른 이름을 사용할 수 있습니다.
+
+그러나 로그인 *경로 작동*의 경우 사양과 호환되도록 이러한 이름을 사용해야 합니다(예를 들어 통합 API 문서 시스템을 사용할 수 있어야 합니다).
+
+사양에는 또한 `username`과 `password`가 폼 데이터로 전송되어야 한다고 명시되어 있습니다(따라서 여기에는 JSON이 없습니다).
+
+### `scope`
+
+사양에는 클라이언트가 다른 폼 필드 "`scope`"를 보낼 수 있다고 나와 있습니다.
+
+폼 필드 이름은 `scope`(단수형)이지만 실제로는 공백으로 구분된 "범위"가 있는 긴 문자열입니다.
+
+각 "범위"는 공백이 없는 문자열입니다.
+
+일반적으로 특정 보안 권한을 선언하는 데 사용됩니다. 다음을 봅시다:
+
+* `users:read` 또는 `users:write`는 일반적인 예시입니다.
+* `instagram_basic`은 페이스북/인스타그램에서 사용합니다.
+* `https://www.googleapis.com/auth/drive`는 Google에서 사용합니다.
+
+!!! 정보
+ OAuth2에서 "범위"는 필요한 특정 권한을 선언하는 문자열입니다.
+
+ `:`과 같은 다른 문자가 있는지 또는 URL인지는 중요하지 않습니다.
+
+ 이러한 세부 사항은 구현에 따라 다릅니다.
+
+ OAuth2의 경우 문자열일 뿐입니다.
+
+## `username`과 `password`를 가져오는 코드
+
+이제 **FastAPI**에서 제공하는 유틸리티를 사용하여 이를 처리해 보겠습니다.
+
+### `OAuth2PasswordRequestForm`
+
+먼저 `OAuth2PasswordRequestForm`을 가져와 `/token`에 대한 *경로 작동*에서 `Depends`의 의존성으로 사용합니다.
+
+=== "파이썬 3.7 이상"
+
+ ```Python hl_lines="4 76"
+ {!> ../../../docs_src/security/tutorial003.py!}
+ ```
+
+=== "파이썬 3.10 이상"
+
+ ```Python hl_lines="2 74"
+ {!> ../../../docs_src/security/tutorial003_py310.py!}
+ ```
+
+`OAuth2PasswordRequestForm`은 다음을 사용하여 폼 본문을 선언하는 클래스 의존성입니다:
+
+* `username`.
+* `password`.
+* `scope`는 선택적인 필드로 공백으로 구분된 문자열로 구성된 큰 문자열입니다.
+* `grant_type`(선택적으로 사용).
+
+!!! 팁
+ OAuth2 사양은 실제로 `password`라는 고정 값이 있는 `grant_type` 필드를 *요구*하지만 `OAuth2PasswordRequestForm`은 이를 강요하지 않습니다.
+
+ 사용해야 한다면 `OAuth2PasswordRequestForm` 대신 `OAuth2PasswordRequestFormStrict`를 사용하면 됩니다.
+
+* `client_id`(선택적으로 사용) (예제에서는 필요하지 않습니다).
+* `client_secret`(선택적으로 사용) (예제에서는 필요하지 않습니다).
+
+!!! 정보
+ `OAuth2PasswordRequestForm`은 `OAuth2PasswordBearer`와 같이 **FastAPI**에 대한 특수 클래스가 아닙니다.
+
+ `OAuth2PasswordBearer`는 **FastAPI**가 보안 체계임을 알도록 합니다. 그래서 OpenAPI에 그렇게 추가됩니다.
+
+ 그러나 `OAuth2PasswordRequestForm`은 직접 작성하거나 `Form` 매개변수를 직접 선언할 수 있는 클래스 의존성일 뿐입니다.
+
+ 그러나 일반적인 사용 사례이므로 더 쉽게 하기 위해 **FastAPI**에서 직접 제공합니다.
+
+### 폼 데이터 사용하기
+
+!!! 팁
+ 종속성 클래스 `OAuth2PasswordRequestForm`의 인스턴스에는 공백으로 구분된 긴 문자열이 있는 `scope` 속성이 없고 대신 전송된 각 범위에 대한 실제 문자열 목록이 있는 `scopes` 속성이 있습니다.
+
+ 이 예제에서는 `scopes`를 사용하지 않지만 필요한 경우, 기능이 있습니다.
+
+이제 폼 필드의 `username`을 사용하여 (가짜) 데이터베이스에서 유저 데이터를 가져옵니다.
+
+해당 사용자가 없으면 "잘못된 사용자 이름 또는 패스워드"라는 오류가 반환됩니다.
+
+오류의 경우 `HTTPException` 예외를 사용합니다:
+
+=== "파이썬 3.7 이상"
+
+ ```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!}
+ ```
+
+### 패스워드 확인하기
+
+이 시점에서 데이터베이스의 사용자 데이터 형식을 확인했지만 암호를 확인하지 않았습니다.
+
+먼저 데이터를 Pydantic `UserInDB` 모델에 넣겠습니다.
+
+일반 텍스트 암호를 저장하면 안 되니 (가짜) 암호 해싱 시스템을 사용합니다.
+
+두 패스워드가 일치하지 않으면 동일한 오류가 반환됩니다.
+
+#### 패스워드 해싱
+
+"해싱"은 일부 콘텐츠(이 경우 패스워드)를 횡설수설하는 것처럼 보이는 일련의 바이트(문자열)로 변환하는 것을 의미합니다.
+
+정확히 동일한 콘텐츠(정확히 동일한 패스워드)를 전달할 때마다 정확히 동일한 횡설수설이 발생합니다.
+
+그러나 횡설수설에서 암호로 다시 변환할 수는 없습니다.
+
+##### 패스워드 해싱을 사용해야 하는 이유
+
+데이터베이스가 유출된 경우 해커는 사용자의 일반 텍스트 암호가 아니라 해시만 갖게 됩니다.
+
+따라서 해커는 다른 시스템에서 동일한 암호를 사용하려고 시도할 수 없습니다(많은 사용자가 모든 곳에서 동일한 암호를 사용하므로 이는 위험할 수 있습니다).
+
+=== "P파이썬 3.7 이상"
+
+ ```Python hl_lines="80-83"
+ {!> ../../../docs_src/security/tutorial003.py!}
+ ```
+
+=== "파이썬 3.10 이상"
+
+ ```Python hl_lines="78-81"
+ {!> ../../../docs_src/security/tutorial003_py310.py!}
+ ```
+
+#### `**user_dict`에 대해
+
+`UserInDB(**user_dict)`는 다음을 의미한다:
+
+*`user_dict`의 키와 값을 다음과 같은 키-값 인수로 직접 전달합니다:*
+
+```Python
+UserInDB(
+ username = user_dict["username"],
+ email = user_dict["email"],
+ full_name = user_dict["full_name"],
+ disabled = user_dict["disabled"],
+ hashed_password = user_dict["hashed_password"],
+)
+```
+
+!!! 정보
+ `**user_dict`에 대한 자세한 설명은 [**추가 모델** 문서](../extra-models.md#about-user_indict){.internal-link target=_blank}를 다시 읽어봅시다.
+
+## 토큰 반환하기
+
+`token` 엔드포인트의 응답은 JSON 객체여야 합니다.
+
+`token_type`이 있어야 합니다. 여기서는 "Bearer" 토큰을 사용하므로 토큰 유형은 "`bearer`"여야 합니다.
+
+그리고 액세스 토큰을 포함하는 문자열과 함께 `access_token`이 있어야 합니다.
+
+이 간단한 예제에서는 완전히 안전하지 않고, 동일한 `username`을 토큰으로 반환합니다.
+
+!!! 팁
+ 다음 장에서는 패스워드 해싱 및 JWT 토큰을 사용하여 실제 보안 구현을 볼 수 있습니다.
+
+ 하지만 지금은 필요한 세부 정보에 집중하겠습니다.
+
+=== "파이썬 3.7 이상"
+
+ ```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을 반환해야 합니다.
+
+ 이는 코드에서 직접 수행해야 하며 해당 JSON 키를 사용해야 합니다.
+
+ 사양을 준수하기 위해 스스로 올바르게 수행하기 위해 거의 유일하게 기억해야 하는 것입니다.
+
+ 나머지는 **FastAPI**가 처리합니다.
+
+## 의존성 업데이트하기
+
+이제 의존성을 업데이트를 할 겁니다.
+
+이 사용자가 활성화되어 있는 *경우에만* `current_user`를 가져올 겁니다.
+
+따라서 `get_current_user`를 의존성으로 사용하는 추가 종속성 `get_current_active_user`를 만듭니다.
+
+이러한 의존성 모두, 사용자가 존재하지 않거나 비활성인 경우 HTTP 오류를 반환합니다.
+
+따라서 엔드포인트에서는 사용자가 존재하고 올바르게 인증되었으며 활성 상태인 경우에만 사용자를 얻습니다:
+
+=== "파이썬 3.7 이상"
+
+ ```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`도 사양의 일부입니다.
+
+ 모든 HTTP(오류) 상태 코드 401 "UNAUTHORIZED"는 `WWW-Authenticate` 헤더도 반환해야 합니다.
+
+ 베어러 토큰의 경우(지금의 경우) 해당 헤더의 값은 `Bearer`여야 합니다.
+
+ 실제로 추가 헤더를 건너뛸 수 있으며 여전히 작동합니다.
+
+ 그러나 여기에서는 사양을 준수하도록 제공됩니다.
+
+ 또한 이를 예상하고 (현재 또는 미래에) 사용하는 도구가 있을 수 있으며, 현재 또는 미래에 자신 혹은 자신의 유저들에게 유용할 것입니다.
+
+ 그것이 표준의 이점입니다 ...
+
+## 확인하기
+
+대화형 문서 열기: http://127.0.0.1:8000/docs.
+
+### 인증하기
+
+"Authorize" 버튼을 눌러봅시다.
+
+자격 증명을 사용합니다.
+
+유저명: `johndoe`
+
+패스워드: `secret`
+
+
+
+시스템에서 인증하면 다음과 같이 표시됩니다:
+
+
+
+### 자신의 유저 데이터 가져오기
+
+이제 `/users/me` 경로에 `GET` 작업을 진행합시다.
+
+다음과 같은 사용자 데이터를 얻을 수 있습니다:
+
+```JSON
+{
+ "username": "johndoe",
+ "email": "johndoe@example.com",
+ "full_name": "John Doe",
+ "disabled": false,
+ "hashed_password": "fakehashedsecret"
+}
+```
+
+
+
+잠금 아이콘을 클릭하고 로그아웃한 다음 동일한 작업을 다시 시도하면 다음과 같은 HTTP 401 오류가 발생합니다.
+
+```JSON
+{
+ "detail": "Not authenticated"
+}
+```
+
+### 비활성된 유저
+
+이제 비활성된 사용자로 시도하고, 인증해봅시다:
+
+유저명: `alice`
+
+패스워드: `secret2`
+
+그리고 `/users/me` 경로와 함께 `GET` 작업을 사용해 봅시다.
+
+다음과 같은 "Inactive user" 오류가 발생합니다:
+
+```JSON
+{
+ "detail": "Inactive user"
+}
+```
+
+## 요약
+
+이제 API에 대한 `username` 및 `password`를 기반으로 완전한 보안 시스템을 구현할 수 있는 도구가 있습니다.
+
+이러한 도구를 사용하여 보안 시스템을 모든 데이터베이스 및 모든 사용자 또는 데이터 모델과 호환되도록 만들 수 있습니다.
+
+유일한 오점은 아직 실제로 "안전"하지 않다는 것입니다.
+
+다음 장에서는 안전한 패스워드 해싱 라이브러리와 JWT 토큰을 사용하는 방법을 살펴보겠습니다.
diff --git a/docs/pl/docs/features.md b/docs/pl/docs/features.md
index a6435977c9..7c20137995 100644
--- a/docs/pl/docs/features.md
+++ b/docs/pl/docs/features.md
@@ -1,3 +1,8 @@
+---
+hide:
+ - navigation
+---
+
# Cechy
## Cechy FastAPI
diff --git a/docs/pl/docs/help-fastapi.md b/docs/pl/docs/help-fastapi.md
index 54c172664f..fdc3b0bf93 100644
--- a/docs/pl/docs/help-fastapi.md
+++ b/docs/pl/docs/help-fastapi.md
@@ -78,7 +78,7 @@ Możesz spróbować pomóc innym, odpowiadając w:
W wielu przypadkach możesz już znać odpowiedź na te pytania. 🤓
-Jeśli pomożesz wielu ludziom, możesz zostać oficjalnym [Ekspertem FastAPI](fastapi-people.md#experts){.internal-link target=_blank}. 🎉
+Jeśli pomożesz wielu ludziom, możesz zostać oficjalnym [Ekspertem FastAPI](fastapi-people.md#fastapi-experts){.internal-link target=_blank}. 🎉
Pamiętaj tylko o najważniejszym: bądź życzliwy. Ludzie przychodzą sfrustrowani i w wielu przypadkach nie zadają pytań w najlepszy sposób, ale mimo to postaraj się być dla nich jak najbardziej życzliwy. 🤗
@@ -215,8 +215,8 @@ Jest wiele pracy do zrobienia, a w większości przypadków **TY** możesz to zr
Główne zadania, które możesz wykonać teraz to:
-* [Pomóc innym z pytaniami na GitHubie](#help-others-with-questions-in-github){.internal-link target=_blank} (zobacz sekcję powyżej).
-* [Oceniać Pull Requesty](#review-pull-requests){.internal-link target=_blank} (zobacz sekcję powyżej).
+* [Pomóc innym z pytaniami na GitHubie](#pomagaj-innym-odpowiadajac-na-ich-pytania-na-githubie){.internal-link target=_blank} (zobacz sekcję powyżej).
+* [Oceniać Pull Requesty](#przegladaj-pull-requesty){.internal-link target=_blank} (zobacz sekcję powyżej).
Te dwie czynności **zajmują najwięcej czasu**. To główna praca związana z utrzymaniem FastAPI.
@@ -226,8 +226,8 @@ Jeśli możesz mi w tym pomóc, **pomożesz mi utrzymać FastAPI** i zapewnisz
Dołącz do 👥 serwera czatu na Discordzie 👥 i spędzaj czas z innymi w społeczności FastAPI.
-!!! wskazówka
- Jeśli masz pytania, zadaj je w Dyskusjach na GitHubie, jest dużo większa szansa, że otrzymasz pomoc od [Ekspertów FastAPI](fastapi-people.md#experts){.internal-link target=_blank}.
+!!! tip "Wskazówka"
+ Jeśli masz pytania, zadaj je w Dyskusjach na GitHubie, jest dużo większa szansa, że otrzymasz pomoc od [Ekspertów FastAPI](fastapi-people.md#fastapi-experts){.internal-link target=_blank}.
Używaj czatu tylko do innych ogólnych rozmów.
@@ -237,7 +237,7 @@ Miej na uwadze, że ponieważ czaty pozwalają na bardziej "swobodną rozmowę",
Na GitHubie szablon poprowadzi Cię do napisania odpowiedniego pytania, dzięki czemu łatwiej uzyskasz dobrą odpowiedź, a nawet rozwiążesz problem samodzielnie, zanim zapytasz. Ponadto na GitHubie mogę się upewnić, że zawsze odpowiadam na wszystko, nawet jeśli zajmuje to trochę czasu. Osobiście nie mogę tego zrobić z systemami czatu. 😅
-Rozmów w systemach czatu nie można tak łatwo przeszukiwać, jak na GitHubie, więc pytania i odpowiedzi mogą zaginąć w rozmowie. A tylko te na GitHubie liczą się do zostania [Ekspertem FastAPI](fastapi-people.md#experts){.internal-link target=_blank}, więc najprawdopodobniej otrzymasz więcej uwagi na GitHubie.
+Rozmów w systemach czatu nie można tak łatwo przeszukiwać, jak na GitHubie, więc pytania i odpowiedzi mogą zaginąć w rozmowie. A tylko te na GitHubie liczą się do zostania [Ekspertem FastAPI](fastapi-people.md#fastapi-experts){.internal-link target=_blank}, więc najprawdopodobniej otrzymasz więcej uwagi na GitHubie.
Z drugiej strony w systemach czatu są tysiące użytkowników, więc jest duża szansa, że znajdziesz tam kogoś do rozmowy, prawie w każdej chwili. 😄
diff --git a/docs/pl/docs/index.md b/docs/pl/docs/index.md
index ab33bfb9c8..b168b9e5e7 100644
--- a/docs/pl/docs/index.md
+++ b/docs/pl/docs/index.md
@@ -1,3 +1,12 @@
+---
+hide:
+ - navigation
+---
+
+
+
diff --git a/docs/pl/docs/tutorial/first-steps.md b/docs/pl/docs/tutorial/first-steps.md
index 9406d703d5..ce71f8b83d 100644
--- a/docs/pl/docs/tutorial/first-steps.md
+++ b/docs/pl/docs/tutorial/first-steps.md
@@ -311,7 +311,7 @@ Możesz również zdefiniować to jako normalną funkcję zamiast `async def`:
```
!!! note
- Jeśli nie znasz różnicy, sprawdź [Async: *"In a hurry?"*](/async/#in-a-hurry){.internal-link target=_blank}.
+ Jeśli nie znasz różnicy, sprawdź [Async: *"In a hurry?"*](../async.md#in-a-hurry){.internal-link target=_blank}.
### Krok 5: zwróć zawartość
diff --git a/docs/pt/docs/about/index.md b/docs/pt/docs/about/index.md
new file mode 100644
index 0000000000..1f42e88318
--- /dev/null
+++ b/docs/pt/docs/about/index.md
@@ -0,0 +1,3 @@
+# Sobre
+
+Sobre o FastAPI, seus padrões, inspirações e muito mais. 🤓
diff --git a/docs/pt/docs/advanced/events.md b/docs/pt/docs/advanced/events.md
index 7f6cb6f5d4..12aa93f298 100644
--- a/docs/pt/docs/advanced/events.md
+++ b/docs/pt/docs/advanced/events.md
@@ -160,4 +160,4 @@ Por baixo, na especificação técnica ASGI, essa é a parte do
@@ -109,7 +109,7 @@ Isso pode depender principalmente da ferramenta que você usa para **instalar**
O caminho mais comum de fazer isso é ter um arquivo `requirements.txt` com os nomes dos pacotes e suas versões, um por linha.
-Você, naturalmente, usaria as mesmas ideias que você leu em [Sobre Versões do FastAPI](./versions.md){.internal-link target=_blank} para definir os intervalos de versões.
+Você, naturalmente, usaria as mesmas ideias que você leu em [Sobre Versões do FastAPI](versions.md){.internal-link target=_blank} para definir os intervalos de versões.
Por exemplo, seu `requirements.txt` poderia parecer com:
@@ -374,7 +374,7 @@ Então ajuste o comando Uvicorn para usar o novo módulo `main` em vez de `app.m
## Conceitos de Implantação
-Vamos falar novamente sobre alguns dos mesmos [Conceitos de Implantação](./concepts.md){.internal-link target=_blank} em termos de contêineres.
+Vamos falar novamente sobre alguns dos mesmos [Conceitos de Implantação](concepts.md){.internal-link target=_blank} em termos de contêineres.
Contêineres são principalmente uma ferramenta para simplificar o processo de **construção e implantação** de um aplicativo, mas eles não impõem uma abordagem particular para lidar com esses **conceitos de implantação** e existem várias estratégias possíveis.
@@ -515,14 +515,14 @@ Se você tiver uma configuração simples, com um **único contêiner** que ent
## Imagem Oficial do Docker com Gunicorn - Uvicorn
-Há uma imagem oficial do Docker que inclui o Gunicorn executando com trabalhadores Uvicorn, conforme detalhado em um capítulo anterior: [Server Workers - Gunicorn com Uvicorn](./server-workers.md){.internal-link target=_blank}.
+Há uma imagem oficial do Docker que inclui o Gunicorn executando com trabalhadores Uvicorn, conforme detalhado em um capítulo anterior: [Server Workers - Gunicorn com Uvicorn](server-workers.md){.internal-link target=_blank}.
-Essa imagem seria útil principalmente nas situações descritas acima em: [Contêineres com Múltiplos Processos e Casos Especiais](#contêineres-com-múltiplos-processos-e-casos-Especiais).
+Essa imagem seria útil principalmente nas situações descritas acima em: [Contêineres com Múltiplos Processos e Casos Especiais](#conteineres-com-multiplos-processos-e-casos-especiais).
* tiangolo/uvicorn-gunicorn-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](#construa-uma-imagem-docker-para-o-fastapi).
+ 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.
@@ -579,7 +579,7 @@ COPY ./app /app/app
Você provavelmente **não** deve usar essa imagem base oficial (ou qualquer outra semelhante) se estiver usando **Kubernetes** (ou outros) e já estiver definindo **replicação** no nível do cluster, com vários **contêineres**. Nesses casos, é melhor **construir uma imagem do zero** conforme descrito acima: [Construindo uma Imagem Docker para FastAPI](#construindo-uma-imagem-docker-para-fastapi).
-Essa imagem seria útil principalmente nos casos especiais descritos acima em [Contêineres com Múltiplos Processos e Casos Especiais](#contêineres-com-múltiplos-processos-e-casos-Especiais). Por exemplo, se sua aplicação for **simples o suficiente** para que a configuração padrão de número de processos com base na CPU funcione bem, você não quer se preocupar com a configuração manual da replicação no nível do cluster e não está executando mais de um contêiner com seu aplicativo. Ou se você estiver implantando com **Docker Compose**, executando em um único servidor, etc.
+Essa imagem seria útil principalmente nos casos especiais descritos acima em [Contêineres com Múltiplos Processos e Casos Especiais](#conteineres-com-multiplos-processos-e-casos-especiais). Por exemplo, se sua aplicação for **simples o suficiente** para que a configuração padrão de número de processos com base na CPU funcione bem, você não quer se preocupar com a configuração manual da replicação no nível do cluster e não está executando mais de um contêiner com seu aplicativo. Ou se você estiver implantando com **Docker Compose**, executando em um único servidor, etc.
## Deploy da Imagem do Contêiner
diff --git a/docs/pt/docs/fastapi-people.md b/docs/pt/docs/fastapi-people.md
index 20061bfd93..93c3479f25 100644
--- a/docs/pt/docs/fastapi-people.md
+++ b/docs/pt/docs/fastapi-people.md
@@ -1,3 +1,8 @@
+---
+hide:
+ - navigation
+---
+
# Pessoas do FastAPI
FastAPI possue uma comunidade incrível que recebe pessoas de todos os níveis.
@@ -18,7 +23,7 @@ Este sou eu:
-!!! marque o "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.
@@ -61,7 +61,7 @@ E se você clicar, você terá um pequeno formulário de autorização para digi
-!!! 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.
@@ -104,7 +104,7 @@ Então, vamos rever de um ponto de vista simplificado:
Neste exemplo, nós vamos usar o **OAuth2** com o fluxo de **Senha**, usando um token **Bearer**. Fazemos isso usando a classe `OAuth2PasswordBearer`.
-!!! informação
+!!! info "informação"
Um token "bearer" não é a única opção.
Mas é a melhor no nosso caso.
@@ -119,7 +119,7 @@ Quando nós criamos uma instância da classe `OAuth2PasswordBearer`, nós passam
{!../../../docs_src/security/tutorial001.py!}
```
-!!! 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`.
@@ -130,7 +130,7 @@ Esse parâmetro não cria um endpoint / *path operation*, mas declara que a URL
Em breve também criaremos o atual path operation.
-!!! 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.
@@ -157,7 +157,7 @@ Esse dependência vai fornecer uma `str` que é atribuído ao parâmetro `token
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).
-!!! informação "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.
diff --git a/docs/ru/docs/async.md b/docs/ru/docs/async.md
index 4d3ce2adfe..20dbb108b4 100644
--- a/docs/ru/docs/async.md
+++ b/docs/ru/docs/async.md
@@ -468,7 +468,7 @@ Starlette (и **FastAPI**) основаны на
Ещё раз повторим, что все эти технические подробности полезны, только если вы специально их искали.
-В противном случае просто ознакомьтесь с основными принципами в разделе выше: Нет времени?.
+В противном случае просто ознакомьтесь с основными принципами в разделе выше: Нет времени?.
diff --git a/docs/ru/docs/deployment/concepts.md b/docs/ru/docs/deployment/concepts.md
index 681acf15ea..26db356c10 100644
--- a/docs/ru/docs/deployment/concepts.md
+++ b/docs/ru/docs/deployment/concepts.md
@@ -1,6 +1,6 @@
# Концепции развёртывания
-Существует несколько концепций, применяемых для развёртывания приложений **FastAPI**, равно как и для любых других типов веб-приложений, среди которых Вы можете выбрать **наиболее подходящий** способ.
+Существует несколько концепций, применяемых для развёртывания приложений **FastAPI**, равно как и для любых других типов веб-приложений, среди которых вы можете выбрать **наиболее подходящий** способ.
Самые важные из них:
@@ -13,11 +13,11 @@
Рассмотрим ниже влияние каждого из них на процесс **развёртывания**.
-Наша конечная цель - **обслуживать клиентов Вашего API безопасно** и **бесперебойно**, с максимально эффективным использованием **вычислительных ресурсов** (например, удалённых серверов/виртуальных машин). 🚀
+Наша конечная цель - **обслуживать клиентов вашего API безопасно** и **бесперебойно**, с максимально эффективным использованием **вычислительных ресурсов** (например, удалённых серверов/виртуальных машин). 🚀
-Здесь я немного расскажу Вам об этих **концепциях** и надеюсь, что у Вас сложится **интуитивное понимание**, какой способ выбрать при развертывании Вашего API в различных окружениях, возможно, даже **ещё не существующих**.
+Здесь я немного расскажу Вам об этих **концепциях** и надеюсь, что у вас сложится **интуитивное понимание**, какой способ выбрать при развертывании вашего API в различных окружениях, возможно, даже **ещё не существующих**.
-Ознакомившись с этими концепциями, Вы сможете **оценить и выбрать** лучший способ развёртывании **Вашего API**.
+Ознакомившись с этими концепциями, вы сможете **оценить и выбрать** лучший способ развёртывании **Вашего API**.
В последующих главах я предоставлю Вам **конкретные рецепты** развёртывания приложения FastAPI.
@@ -25,15 +25,15 @@
## Использование более безопасного протокола HTTPS
-В [предыдущей главе об HTTPS](./https.md){.internal-link target=_blank} мы рассмотрели, как HTTPS обеспечивает шифрование для Вашего API.
+В [предыдущей главе об HTTPS](https.md){.internal-link target=_blank} мы рассмотрели, как HTTPS обеспечивает шифрование для вашего API.
-Также мы заметили, что обычно для работы с HTTPS Вашему приложению нужен **дополнительный** компонент - **прокси-сервер завершения работы TLS**.
+Также мы заметили, что обычно для работы с HTTPS вашему приложению нужен **дополнительный** компонент - **прокси-сервер завершения работы TLS**.
И если прокси-сервер не умеет сам **обновлять сертификаты HTTPS**, то нужен ещё один компонент для этого действия.
### Примеры инструментов для работы с HTTPS
-Вот некоторые инструменты, которые Вы можете применять как прокси-серверы:
+Вот некоторые инструменты, которые вы можете применять как прокси-серверы:
* Traefik
* С автоматическим обновлением сертификатов ✨
@@ -47,7 +47,7 @@
* С дополнительным компонентом типа cert-manager для обновления сертификатов
* Использование услуг облачного провайдера (читайте ниже 👇)
-В последнем варианте Вы можете воспользоваться услугами **облачного сервиса**, который сделает большую часть работы, включая настройку HTTPS. Это может наложить дополнительные ограничения или потребовать дополнительную плату и т.п. Зато Вам не понадобится самостоятельно заниматься настройками прокси-сервера.
+В последнем варианте вы можете воспользоваться услугами **облачного сервиса**, который сделает большую часть работы, включая настройку HTTPS. Это может наложить дополнительные ограничения или потребовать дополнительную плату и т.п. Зато Вам не понадобится самостоятельно заниматься настройками прокси-сервера.
В дальнейшем я покажу Вам некоторые конкретные примеры их применения.
@@ -63,7 +63,7 @@
Термином **программа** обычно описывают множество вещей:
-* **Код**, который Вы написали, в нашем случае **Python-файлы**.
+* **Код**, который вы написали, в нашем случае **Python-файлы**.
* **Файл**, который может быть **исполнен** операционной системой, например `python`, `python.exe` или `uvicorn`.
* Конкретная программа, **запущенная** операционной системой и использующая центральный процессор и память. В таком случае это также называется **процесс**.
@@ -74,13 +74,13 @@
* Конкретная программа, **запущенная** операционной системой.
* Это не имеет отношения к какому-либо файлу или коду, но нечто **определённое**, управляемое и **выполняемое** операционной системой.
* Любая программа, любой код, **могут делать что-то** только когда они **выполняются**. То есть, когда являются **работающим процессом**.
-* Процесс может быть **прерван** (или "убит") Вами или Вашей операционной системой. В результате чего он перестанет исполняться и **не будет продолжать делать что-либо**.
-* Каждое приложение, которое Вы запустили на своём компьютере, каждая программа, каждое "окно" запускает какой-то процесс. И обычно на включенном компьютере **одновременно** запущено множество процессов.
+* Процесс может быть **прерван** (или "убит") Вами или вашей операционной системой. В результате чего он перестанет исполняться и **не будет продолжать делать что-либо**.
+* Каждое приложение, которое вы запустили на своём компьютере, каждая программа, каждое "окно" запускает какой-то процесс. И обычно на включенном компьютере **одновременно** запущено множество процессов.
* И **одна программа** может запустить **несколько параллельных процессов**.
-Если Вы заглянете в "диспетчер задач" или "системный монитор" (или аналогичные инструменты) Вашей операционной системы, то увидите множество работающих процессов.
+Если вы заглянете в "диспетчер задач" или "системный монитор" (или аналогичные инструменты) вашей операционной системы, то увидите множество работающих процессов.
-Вполне вероятно, что Вы увидите несколько процессов с одним и тем же названием браузерной программы (Firefox, Chrome, Edge и т. Д.). Обычно браузеры запускают один процесс на вкладку и вдобавок некоторые дополнительные процессы.
+Вполне вероятно, что вы увидите несколько процессов с одним и тем же названием браузерной программы (Firefox, Chrome, Edge и т. Д.). Обычно браузеры запускают один процесс на вкладку и вдобавок некоторые дополнительные процессы.
@@ -90,21 +90,21 @@
## Настройки запуска приложения
-В большинстве случаев когда Вы создаёте веб-приложение, то желаете, чтоб оно **работало постоянно** и непрерывно, предоставляя клиентам доступ в любое время. Хотя иногда у Вас могут быть причины, чтоб оно запускалось только при определённых условиях.
+В большинстве случаев когда вы создаёте веб-приложение, то желаете, чтоб оно **работало постоянно** и непрерывно, предоставляя клиентам доступ в любое время. Хотя иногда у вас могут быть причины, чтоб оно запускалось только при определённых условиях.
### Удалённый сервер
-Когда Вы настраиваете удалённый сервер (облачный сервер, виртуальную машину и т.п.), самое простое, что можно сделать, запустить Uvicorn (или его аналог) вручную, как Вы делаете при локальной разработке.
+Когда вы настраиваете удалённый сервер (облачный сервер, виртуальную машину и т.п.), самое простое, что можно сделать, запустить Uvicorn (или его аналог) вручную, как вы делаете при локальной разработке.
Это рабочий способ и он полезен **во время разработки**.
-Но если Вы потеряете соединение с сервером, то не сможете отслеживать - работает ли всё ещё **запущенный Вами процесс**.
+Но если вы потеряете соединение с сервером, то не сможете отслеживать - работает ли всё ещё **запущенный Вами процесс**.
-И если сервер перезагрузится (например, после обновления или каких-то действий облачного провайдера), Вы скорее всего **этого не заметите**, чтобы снова запустить процесс вручную. Вследствие этого Ваш API останется мёртвым. 😱
+И если сервер перезагрузится (например, после обновления или каких-то действий облачного провайдера), вы скорее всего **этого не заметите**, чтобы снова запустить процесс вручную. Вследствие этого Ваш API останется мёртвым. 😱
### Автоматический запуск программ
-Вероятно Вы пожелаете, чтоб Ваша серверная программа (такая как Uvicorn) стартовала автоматически при включении сервера, без **человеческого вмешательства** и всегда могла управлять Вашим API (так как Uvicorn запускает приложение FastAPI).
+Вероятно вы захотите, чтоб Ваша серверная программа (такая, как Uvicorn) стартовала автоматически при включении сервера, без **человеческого вмешательства** и всегда могла управлять Вашим API (так как Uvicorn запускает приложение FastAPI).
### Отдельная программа
@@ -127,7 +127,7 @@
## Перезапуск
-Вы, вероятно, также пожелаете, чтоб Ваше приложение **перезапускалось**, если в нём произошёл сбой.
+Вы, вероятно, также захотите, чтоб ваше приложение **перезапускалось**, если в нём произошёл сбой.
### Мы ошибаемся
@@ -137,7 +137,7 @@
### Небольшие ошибки обрабатываются автоматически
-Когда Вы создаёте свои API на основе FastAPI и допускаете в коде ошибку, то FastAPI обычно остановит её распространение внутри одного запроса, при обработке которого она возникла. 🛡
+Когда вы создаёте свои API на основе FastAPI и допускаете в коде ошибку, то FastAPI обычно остановит её распространение внутри одного запроса, при обработке которого она возникла. 🛡
Клиент получит ошибку **500 Internal Server Error** в ответ на свой запрос, но приложение не сломается и будет продолжать работать с последующими запросами.
@@ -152,11 +152,11 @@
Для случаев, когда ошибки приводят к сбою в запущенном **процессе**, Вам понадобится добавить компонент, который **перезапустит** процесс хотя бы пару раз...
!!! tip "Заметка"
- ... Если приложение падает сразу же после запуска, вероятно бесполезно его бесконечно перезапускать. Но полагаю, Вы заметите такое поведение во время разработки или, по крайней мере, сразу после развёртывания.
+ ... Если приложение падает сразу же после запуска, вероятно бесполезно его бесконечно перезапускать. Но полагаю, вы заметите такое поведение во время разработки или, по крайней мере, сразу после развёртывания.
Так что давайте сосредоточимся на конкретных случаях, когда приложение может полностью выйти из строя, но всё ещё есть смысл его запустить заново.
-Возможно Вы захотите, чтоб был некий **внешний компонент**, ответственный за перезапуск Вашего приложения даже если уже не работает Uvicorn или Python. То есть ничего из того, что написано в Вашем коде внутри приложения, не может быть выполнено в принципе.
+Возможно вы захотите, чтоб был некий **внешний компонент**, ответственный за перезапуск вашего приложения даже если уже не работает Uvicorn или Python. То есть ничего из того, что написано в вашем коде внутри приложения, не может быть выполнено в принципе.
### Примеры инструментов для автоматического перезапуска
@@ -181,13 +181,13 @@
### Множество процессов - Воркеры (Workers)
-Если количество Ваших клиентов больше, чем может обслужить один процесс (допустим, что виртуальная машина не слишком мощная), но при этом Вам доступно **несколько ядер процессора**, то Вы можете запустить **несколько процессов** одного и того же приложения параллельно и распределить запросы между этими процессами.
+Если количество Ваших клиентов больше, чем может обслужить один процесс (допустим, что виртуальная машина не слишком мощная), но при этом Вам доступно **несколько ядер процессора**, то вы можете запустить **несколько процессов** одного и того же приложения параллельно и распределить запросы между этими процессами.
**Несколько запущенных процессов** одной и той же API-программы часто называют **воркерами**.
### Процессы и порты́
-Помните ли Вы, как на странице [Об HTTPS](./https.md){.internal-link target=_blank} мы обсуждали, что на сервере только один процесс может слушать одну комбинацию IP-адреса и порта?
+Помните ли Вы, как на странице [Об HTTPS](https.md){.internal-link target=_blank} мы обсуждали, что на сервере только один процесс может слушать одну комбинацию IP-адреса и порта?
С тех пор ничего не изменилось.
@@ -197,11 +197,11 @@
Работающая программа загружает в память данные, необходимые для её работы, например, переменные содержащие модели машинного обучения или большие файлы. Каждая переменная **потребляет некоторое количество оперативной памяти (RAM)** сервера.
-Обычно процессы **не делятся памятью друг с другом**. Сие означает, что каждый работающий процесс имеет свои данные, переменные и свой кусок памяти. И если для выполнения Вашего кода процессу нужно много памяти, то **каждый такой же процесс** запущенный дополнительно, потребует такого же количества памяти.
+Обычно процессы **не делятся памятью друг с другом**. Сие означает, что каждый работающий процесс имеет свои данные, переменные и свой кусок памяти. И если для выполнения вашего кода процессу нужно много памяти, то **каждый такой же процесс** запущенный дополнительно, потребует такого же количества памяти.
### Память сервера
-Допустим, что Ваш код загружает модель машинного обучения **размером 1 ГБ**. Когда Вы запустите своё API как один процесс, он займёт в оперативной памяти не менее 1 ГБ. А если Вы запустите **4 таких же процесса** (4 воркера), то каждый из них займёт 1 ГБ оперативной памяти. В результате Вашему API потребуется **4 ГБ оперативной памяти (RAM)**.
+Допустим, что Ваш код загружает модель машинного обучения **размером 1 ГБ**. Когда вы запустите своё API как один процесс, он займёт в оперативной памяти не менее 1 ГБ. А если вы запустите **4 таких же процесса** (4 воркера), то каждый из них займёт 1 ГБ оперативной памяти. В результате вашему API потребуется **4 ГБ оперативной памяти (RAM)**.
И если Ваш удалённый сервер или виртуальная машина располагает только 3 ГБ памяти, то попытка загрузить в неё 4 ГБ данных вызовет проблемы. 🚨
@@ -211,15 +211,15 @@
Менеджер процессов будет слушать определённый **сокет** (IP:порт) и передавать данные работающим процессам.
-Каждый из этих процессов будет запускать Ваше приложение для обработки полученного **запроса** и возвращения вычисленного **ответа** и они будут использовать оперативную память.
+Каждый из этих процессов будет запускать ваше приложение для обработки полученного **запроса** и возвращения вычисленного **ответа** и они будут использовать оперативную память.
uvicorn - 用于加载和运行你的应用程序的服务器。
* orjson - 使用 `ORJSONResponse` 时安装。
-你可以通过 `pip install fastapi[all]` 命令来安装以上所有依赖。
+你可以通过 `pip install "fastapi[all]"` 命令来安装以上所有依赖。
## 许可协议
diff --git a/docs/zh/docs/tutorial/bigger-applications.md b/docs/zh/docs/tutorial/bigger-applications.md
index 1389595669..422cd7c168 100644
--- a/docs/zh/docs/tutorial/bigger-applications.md
+++ b/docs/zh/docs/tutorial/bigger-applications.md
@@ -119,7 +119,7 @@
!!! tip
我们正在使用虚构的请求首部来简化此示例。
- 但在实际情况下,使用集成的[安全性实用工具](./security/index.md){.internal-link target=_blank}会得到更好的效果。
+ 但在实际情况下,使用集成的[安全性实用工具](security/index.md){.internal-link target=_blank}会得到更好的效果。
## 其他使用 `APIRouter` 的模块
diff --git a/docs/zh/docs/tutorial/body-fields.md b/docs/zh/docs/tutorial/body-fields.md
index fb6c6d9b6a..6c68f10087 100644
--- a/docs/zh/docs/tutorial/body-fields.md
+++ b/docs/zh/docs/tutorial/body-fields.md
@@ -1,10 +1,10 @@
# 请求体 - 字段
-与使用 `Query`、`Path` 和 `Body` 在*路径操作函数*中声明额外的校验和元数据的方式相同,你可以使用 Pydantic 的 `Field` 在 Pydantic 模型内部声明校验和元数据。
+与在*路径操作函数*中使用 `Query`、`Path` 、`Body` 声明校验与元数据的方式一样,可以使用 Pydantic 的 `Field` 在 Pydantic 模型内部声明校验和元数据。
## 导入 `Field`
-首先,你必须导入它:
+首先,从 Pydantic 中导入 `Field`:
=== "Python 3.10+"
@@ -42,12 +42,13 @@
{!> ../../../docs_src/body_fields/tutorial001.py!}
```
-!!! warning
- 注意,`Field` 是直接从 `pydantic` 导入的,而不是像其他的(`Query`,`Path`,`Body` 等)都从 `fastapi` 导入。
+!!! warning "警告"
+
+ 注意,与从 `fastapi` 导入 `Query`,`Path`、`Body` 不同,要直接从 `pydantic` 导入 `Field` 。
## 声明模型属性
-然后,你可以对模型属性使用 `Field`:
+然后,使用 `Field` 定义模型的属性:
=== "Python 3.10+"
@@ -85,28 +86,30 @@
{!> ../../../docs_src/body_fields/tutorial001.py!}
```
-`Field` 的工作方式和 `Query`、`Path` 和 `Body` 相同,包括它们的参数等等也完全相同。
+`Field` 的工作方式和 `Query`、`Path`、`Body` 相同,参数也相同。
!!! note "技术细节"
- 实际上,`Query`、`Path` 和其他你将在之后看到的类,创建的是由一个共同的 `Params` 类派生的子类的对象,该共同类本身又是 Pydantic 的 `FieldInfo` 类的子类。
- Pydantic 的 `Field` 也会返回一个 `FieldInfo` 的实例。
+ 实际上,`Query`、`Path` 都是 `Params` 的子类,而 `Params` 类又是 Pydantic 中 `FieldInfo` 的子类。
- `Body` 也直接返回 `FieldInfo` 的一个子类的对象。还有其他一些你之后会看到的类是 `Body` 类的子类。
+ Pydantic 的 `Field` 返回也是 `FieldInfo` 的类实例。
- 请记住当你从 `fastapi` 导入 `Query`、`Path` 等对象时,他们实际上是返回特殊类的函数。
+ `Body` 直接返回的也是 `FieldInfo` 的子类的对象。后文还会介绍一些 `Body` 的子类。
-!!! tip
- 注意每个模型属性如何使用类型、默认值和 `Field` 在代码结构上和*路径操作函数*的参数是相同的,区别是用 `Field` 替换`Path`、`Query` 和 `Body`。
+ 注意,从 `fastapi` 导入的 `Query`、`Path` 等对象实际上都是返回特殊类的函数。
-## 添加额外信息
+!!! tip "提示"
-你可以在 `Field`、`Query`、`Body` 中声明额外的信息。这些信息将包含在生成的 JSON Schema 中。
+ 注意,模型属性的类型、默认值及 `Field` 的代码结构与*路径操作函数*的参数相同,只不过是用 `Field` 替换了`Path`、`Query`、`Body`。
-你将在文档的后面部分学习声明示例时,了解到更多有关添加额外信息的知识。
+## 添加更多信息
-## 总结
+`Field`、`Query`、`Body` 等对象里可以声明更多信息,并且 JSON Schema 中也会集成这些信息。
-你可以使用 Pydantic 的 `Field` 为模型属性声明额外的校验和元数据。
+*声明示例*一章中将详细介绍添加更多信息的知识。
-你还可以使用额外的关键字参数来传递额外的 JSON Schema 元数据。
+## 小结
+
+Pydantic 的 `Field` 可以为模型属性声明更多校验和元数据。
+
+传递 JSON Schema 元数据还可以使用更多关键字参数。
diff --git a/docs/zh/docs/tutorial/body-updates.md b/docs/zh/docs/tutorial/body-updates.md
index 43f20f8fcb..e529fc914f 100644
--- a/docs/zh/docs/tutorial/body-updates.md
+++ b/docs/zh/docs/tutorial/body-updates.md
@@ -34,7 +34,7 @@
即,只发送要更新的数据,其余数据保持不变。
-!!! Note "笔记"
+!!! note "笔记"
`PATCH` 没有 `PUT` 知名,也怎么不常用。
diff --git a/docs/zh/docs/tutorial/body.md b/docs/zh/docs/tutorial/body.md
index 3d615be399..65d459cd17 100644
--- a/docs/zh/docs/tutorial/body.md
+++ b/docs/zh/docs/tutorial/body.md
@@ -1,21 +1,24 @@
# 请求体
-当你需要将数据从客户端(例如浏览器)发送给 API 时,你将其作为「请求体」发送。
+FastAPI 使用**请求体**从客户端(例如浏览器)向 API 发送数据。
-**请求**体是客户端发送给 API 的数据。**响应**体是 API 发送给客户端的数据。
+**请求体**是客户端发送给 API 的数据。**响应体**是 API 发送给客户端的数据。
-你的 API 几乎总是要发送**响应**体。但是客户端并不总是需要发送**请求**体。
+API 基本上肯定要发送**响应体**,但是客户端不一定发送**请求体**。
-我们使用 Pydantic 模型来声明**请求**体,并能够获得它们所具有的所有能力和优点。
+使用 Pydantic 模型声明**请求体**,能充分利用它的功能和优点。
-!!! info
- 你不能使用 `GET` 操作(HTTP 方法)发送请求体。
+!!! info "说明"
- 要发送数据,你必须使用下列方法之一:`POST`(较常见)、`PUT`、`DELETE` 或 `PATCH`。
+ 发送数据使用 `POST`(最常用)、`PUT`、`DELETE`、`PATCH` 等操作。
+
+ 规范中没有定义使用 `GET` 发送请求体的操作,但不管怎样,FastAPI 也支持这种方式,只不过仅用于非常复杂或极端的用例。
+
+ 我们不建议使用 `GET`,因此,在 Swagger UI 交互文档中不会显示有关 `GET` 的内容,而且代理协议也不一定支持 `GET`。
## 导入 Pydantic 的 `BaseModel`
-首先,你需要从 `pydantic` 中导入 `BaseModel`:
+从 `pydantic` 中导入 `BaseModel`:
=== "Python 3.10+"
@@ -31,9 +34,9 @@
## 创建数据模型
-然后,将你的数据模型声明为继承自 `BaseModel` 的类。
+把数据模型声明为继承 `BaseModel` 的类。
-使用标准的 Python 类型来声明所有属性:
+使用 Python 标准类型声明所有属性:
=== "Python 3.10+"
@@ -47,9 +50,9 @@
{!> ../../../docs_src/body/tutorial001.py!}
```
-和声明查询参数时一样,当一个模型属性具有默认值时,它不是必需的。否则它是一个必需属性。将默认值设为 `None` 可使其成为可选属性。
+与声明查询参数一样,包含默认值的模型属性是可选的,否则就是必选的。默认值为 `None` 的模型属性也是可选的。
-例如,上面的模型声明了一个这样的 JSON「`object`」(或 Python `dict`):
+例如,上述模型声明如下 JSON **对象**(即 Python **字典**):
```JSON
{
@@ -60,7 +63,7 @@
}
```
-...由于 `description` 和 `tax` 是可选的(它们的默认值为 `None`),下面的 JSON「`object`」也将是有效的:
+……由于 `description` 和 `tax` 是可选的(默认值为 `None`),下面的 JSON **对象**也有效:
```JSON
{
@@ -69,9 +72,9 @@
}
```
-## 声明为参数
+## 声明请求体参数
-使用与声明路径和查询参数的相同方式声明请求体,即可将其添加到「路径操作」中:
+使用与声明路径和查询参数相同的方式声明请求体,把请求体添加至*路径操作*:
=== "Python 3.10+"
@@ -85,56 +88,68 @@
{!> ../../../docs_src/body/tutorial001.py!}
```
-...并且将它的类型声明为你创建的 `Item` 模型。
+……此处,请求体参数的类型为 `Item` 模型。
-## 结果
+## 结论
-仅仅使用了 Python 类型声明,**FastAPI** 将会:
+仅使用 Python 类型声明,**FastAPI** 就可以:
-* 将请求体作为 JSON 读取。
-* 转换为相应的类型(在需要时)。
-* 校验数据。
- * 如果数据无效,将返回一条清晰易读的错误信息,指出不正确数据的确切位置和内容。
-* 将接收的数据赋值到参数 `item` 中。
- * 由于你已经在函数中将它声明为 `Item` 类型,你还将获得对于所有属性及其类型的一切编辑器支持(代码补全等)。
-* 为你的模型生成 JSON 模式 定义,你还可以在其他任何对你的项目有意义的地方使用它们。
-* 这些模式将成为生成的 OpenAPI 模式的一部分,并且被自动化文档 UI 所使用。
+* 以 JSON 形式读取请求体
+* (在必要时)把请求体转换为对应的类型
+* 校验数据:
+ * 数据无效时返回错误信息,并指出错误数据的确切位置和内容
+* 把接收的数据赋值给参数 `item`
+ * 把函数中请求体参数的类型声明为 `Item`,还能获得代码补全等编辑器支持
+* 为模型生成 JSON Schema,在项目中所需的位置使用
+* 这些概图是 OpenAPI 概图的部件,用于 API 文档 UI
-## 自动化文档
+## API 文档
-你所定义模型的 JSON 模式将成为生成的 OpenAPI 模式的一部分,并且在交互式 API 文档中展示:
+Pydantic 模型的 JSON 概图是 OpenAPI 生成的概图部件,可在 API 文档中显示:
-
+
-而且还将在每一个需要它们的*路径操作*的 API 文档中使用:
+而且,还会用于 API 文档中使用了概图的*路径操作*:
-
+
## 编辑器支持
-在你的编辑器中,你会在函数内部的任意地方得到类型提示和代码补全(如果你接收的是一个 `dict` 而不是 Pydantic 模型,则不会发生这种情况):
+在编辑器中,函数内部均可使用类型提示、代码补全(如果接收的不是 Pydantic 模型,而是**字典**,就没有这样的支持):
-
+
-你还会获得对不正确的类型操作的错误检查:
+还支持检查错误的类型操作:
-
+
-这并非偶然,整个框架都是围绕该设计而构建。
+这并非偶然,整个 **FastAPI** 框架都是围绕这种思路精心设计的。
-并且在进行任何实现之前,已经在设计阶段经过了全面测试,以确保它可以在所有的编辑器中生效。
+并且,在 FastAPI 的设计阶段,我们就已经进行了全面测试,以确保 FastAPI 可以获得所有编辑器的支持。
-Pydantic 本身甚至也进行了一些更改以支持此功能。
+我们还改进了 Pydantic,让它也支持这些功能。
-上面的截图取自 Visual Studio Code。
+虽然上面的截图取自 Visual Studio Code。
-但是在 PyCharm 和绝大多数其他 Python 编辑器中你也会获得同样的编辑器支持:
+但 PyCharm 和大多数 Python 编辑器也支持同样的功能:
-
+
+
+!!! tip "提示"
+
+ 使用 PyCharm 编辑器时,推荐安装 Pydantic PyCharm 插件。
+
+ 该插件用于完善 PyCharm 对 Pydantic 模型的支持,优化的功能如下:
+
+ * 自动补全
+ * 类型检查
+ * 代码重构
+ * 查找
+ * 代码审查
## 使用模型
-在函数内部,你可以直接访问模型对象的所有属性:
+在*路径操作*函数内部直接访问模型对象的属性:
=== "Python 3.10+"
@@ -150,9 +165,9 @@ Pydantic 本身甚至也进行了一些更改以支持此功能。
## 请求体 + 路径参数
-你可以同时声明路径参数和请求体。
+**FastAPI** 支持同时声明路径参数和请求体。
-**FastAPI** 将识别出与路径参数匹配的函数参数应**从路径中获取**,而声明为 Pydantic 模型的函数参数应**从请求体中获取**。
+**FastAPI** 能识别与**路径参数**匹配的函数参数,还能识别从**请求体**中获取的类型为 Pydantic 模型的函数参数。
=== "Python 3.10+"
@@ -168,9 +183,9 @@ Pydantic 本身甚至也进行了一些更改以支持此功能。
## 请求体 + 路径参数 + 查询参数
-你还可以同时声明**请求体**、**路径参数**和**查询参数**。
+**FastAPI** 支持同时声明**请求体**、**路径参数**和**查询参数**。
-**FastAPI** 会识别它们中的每一个,并从正确的位置获取数据。
+**FastAPI** 能够正确识别这三种参数,并从正确的位置获取数据。
=== "Python 3.10+"
@@ -184,12 +199,18 @@ Pydantic 本身甚至也进行了一些更改以支持此功能。
{!> ../../../docs_src/body/tutorial004.py!}
```
-函数参数将依次按如下规则进行识别:
+函数参数按如下规则进行识别:
-* 如果在**路径**中也声明了该参数,它将被用作路径参数。
-* 如果参数属于**单一类型**(比如 `int`、`float`、`str`、`bool` 等)它将被解释为**查询**参数。
-* 如果参数的类型被声明为一个 **Pydantic 模型**,它将被解释为**请求体**。
+- **路径**中声明了相同参数的参数,是路径参数
+- 类型是(`int`、`float`、`str`、`bool` 等)**单类型**的参数,是**查询**参数
+- 类型是 **Pydantic 模型**的参数,是**请求体**
+
+!!! note "笔记"
+
+ 因为默认值是 `None`, FastAPI 会把 `q` 当作可选参数。
+
+ FastAPI 不使用 `Optional[str]` 中的 `Optional`, 但 `Optional` 可以让编辑器提供更好的支持,并检测错误。
## 不使用 Pydantic
-如果你不想使用 Pydantic 模型,你还可以使用 **Body** 参数。请参阅文档 [请求体 - 多个参数:请求体中的单一值](body-multiple-params.md#singular-values-in-body){.internal-link target=_blank}。
+即便不使用 Pydantic 模型也能使用 **Body** 参数。详见[请求体 - 多参数:请求体中的单值](body-multiple-params.md#_2){.internal-link target=\_blank}。
diff --git a/docs/zh/docs/tutorial/dependencies/dependencies-with-yield.md b/docs/zh/docs/tutorial/dependencies/dependencies-with-yield.md
index e24b9409f6..4159d626ec 100644
--- a/docs/zh/docs/tutorial/dependencies/dependencies-with-yield.md
+++ b/docs/zh/docs/tutorial/dependencies/dependencies-with-yield.md
@@ -4,10 +4,10 @@ FastAPI支持在完成后执行一些http://127.0.0.1:8000/items/foo,将会看到如下响应:
+运行示例并访问 http://127.0.0.1:8000/items/foo,可获得如下响应:
```JSON
{"item_id":"foo"}
```
-## 有类型的路径参数
+## 声明路径参数的类型
-你可以使用标准的 Python 类型标注为函数中的路径参数声明类型。
+使用 Python 标准类型注解,声明路径操作函数中路径参数的类型。
```Python hl_lines="7"
{!../../../docs_src/path_params/tutorial002.py!}
```
-在这个例子中,`item_id` 被声明为 `int` 类型。
+本例把 `item_id` 的类型声明为 `int`。
-!!! check
- 这将为你的函数提供编辑器支持,包括错误检查、代码补全等等。
+!!! check "检查"
-## 数据转换
+ 类型声明将为函数提供错误检查、代码补全等编辑器支持。
-如果你运行示例并打开浏览器访问 http://127.0.0.1:8000/items/3,将得到如下响应:
+## 数据转换
+
+运行示例并访问 http://127.0.0.1:8000/items/3,返回的响应如下:
```JSON
{"item_id":3}
```
-!!! check
- 注意函数接收(并返回)的值为 3,是一个 Python `int` 值,而不是字符串 `"3"`。
+!!! check "检查"
- 所以,**FastAPI** 通过上面的类型声明提供了对请求的自动"解析"。
+ 注意,函数接收并返回的值是 `3`( `int`),不是 `"3"`(`str`)。
+
+ **FastAPI** 通过类型声明自动**解析**请求中的数据。
## 数据校验
-但如果你通过浏览器访问 http://127.0.0.1:8000/items/foo,你会看到一个清晰可读的 HTTP 错误:
+通过浏览器访问 http://127.0.0.1:8000/items/foo,接收如下 HTTP 错误信息:
```JSON
{
@@ -59,86 +61,91 @@
}
```
-因为路径参数 `item_id` 传入的值为 `"foo"`,它不是一个 `int`。
+这是因为路径参数 `item_id` 的值 (`"foo"`)的类型不是 `int`。
-如果你提供的是 `float` 而非整数也会出现同样的错误,比如: http://127.0.0.1:8000/items/4.2
+值的类型不是 `int ` 而是浮点数(`float`)时也会显示同样的错误,比如: http://127.0.0.1:8000/items/4.2。
-!!! check
- 所以,通过同样的 Python 类型声明,**FastAPI** 提供了数据校验功能。
+!!! check "检查"
- 注意上面的错误同样清楚地指出了校验未通过的具体原因。
+ **FastAPI** 使用 Python 类型声明实现了数据校验。
- 在开发和调试与你的 API 进行交互的代码时,这非常有用。
+ 注意,上面的错误清晰地指出了未通过校验的具体原因。
-## 文档
+ 这在开发调试与 API 交互的代码时非常有用。
-当你打开浏览器访问 http://127.0.0.1:8000/docs,你将看到自动生成的交互式 API 文档:
+## 查看文档
-
+访问 http://127.0.0.1:8000/docs,查看自动生成的 API 文档:
-!!! check
- 再一次,还是通过相同的 Python 类型声明,**FastAPI** 为你提供了自动生成的交互式文档(集成 Swagger UI)。
+
- 注意这里的路径参数被声明为一个整数。
+!!! check "检查"
-## 基于标准的好处:可选文档
+ 还是使用 Python 类型声明,**FastAPI** 提供了(集成 Swagger UI 的)API 文档。
-由于生成的 API 模式来自于 OpenAPI 标准,所以有很多工具与其兼容。
+ 注意,路径参数的类型是整数。
-正因如此,**FastAPI** 内置了一个可选的 API 文档(使用 Redoc):
+## 基于标准的好处,备选文档
-
+**FastAPI** 使用 OpenAPI 生成概图,所以能兼容很多工具。
-同样的,还有很多其他兼容的工具,包括适用于多种语言的代码生成工具。
+因此,**FastAPI** 还内置了 ReDoc 生成的备选 API 文档,可在此查看 http://127.0.0.1:8000/redoc:
+
+
+
+同样,还有很多兼容工具,包括多种语言的代码生成工具。
## Pydantic
-所有的数据校验都由 Pydantic 在幕后完成,所以你可以从它所有的优点中受益。并且你知道它在这方面非常胜任。
+FastAPI 充分地利用了 Pydantic 的优势,用它在后台校验数据。众所周知,Pydantic 擅长的就是数据校验。
-你可以使用同样的类型声明来声明 `str`、`float`、`bool` 以及许多其他的复合数据类型。
+同样,`str`、`float`、`bool` 以及很多复合数据类型都可以使用类型声明。
-本教程的下一章节将探讨其中的一些内容。
+下一章介绍详细内容。
## 顺序很重要
-在创建*路径操作*时,你会发现有些情况下路径是固定的。
+有时,*路径操作*中的路径是写死的。
-比如 `/users/me`,我们假设它用来获取关于当前用户的数据.
+比如要使用 `/users/me` 获取当前用户的数据。
-然后,你还可以使用路径 `/users/{user_id}` 来通过用户 ID 获取关于特定用户的数据。
+然后还要使用 `/users/{user_id}`,通过用户 ID 获取指定用户的数据。
+
+由于*路径操作*是按顺序依次运行的,因此,一定要在 `/users/{user_id}` 之前声明 `/users/me` :
-由于*路径操作*是按顺序依次运行的,你需要确保路径 `/users/me` 声明在路径 `/users/{user_id}`之前:
```Python hl_lines="6 11"
{!../../../docs_src/path_params/tutorial003.py!}
```
-否则,`/users/{user_id}` 的路径还将与 `/users/me` 相匹配,"认为"自己正在接收一个值为 `"me"` 的 `user_id` 参数。
+否则,`/users/{user_id}` 将匹配 `/users/me`,FastAPI 会**认为**正在接收值为 `"me"` 的 `user_id` 参数。
## 预设值
-如果你有一个接收路径参数的路径操作,但你希望预先设定可能的有效参数值,则可以使用标准的 Python `Enum` 类型。
+路径操作使用 Python 的 `Enum` 类型接收预设的*路径参数*。
-### 创建一个 `Enum` 类
+### 创建 `Enum` 类
-导入 `Enum` 并创建一个继承自 `str` 和 `Enum` 的子类。
+导入 `Enum` 并创建继承自 `str` 和 `Enum` 的子类。
-通过从 `str` 继承,API 文档将能够知道这些值必须为 `string` 类型并且能够正确地展示出来。
+通过从 `str` 继承,API 文档就能把值的类型定义为**字符串**,并且能正确渲染。
-然后创建具有固定值的类属性,这些固定值将是可用的有效值:
+然后,创建包含固定值的类属性,这些固定值是可用的有效值:
```Python hl_lines="1 6-9"
{!../../../docs_src/path_params/tutorial005.py!}
```
-!!! info
- 枚举(或 enums)从 3.4 版本起在 Python 中可用。
+!!! info "说明"
-!!! tip
- 如果你想知道,"AlexNet"、"ResNet" 和 "LeNet" 只是机器学习中的模型名称。
+ Python 3.4 及之后版本支持枚举(即 enums)。
+
+!!! tip "提示"
+
+ **AlexNet**、**ResNet**、**LeNet** 是机器学习模型。
### 声明*路径参数*
-然后使用你定义的枚举类(`ModelName`)创建一个带有类型标注的*路径参数*:
+使用 Enum 类(`ModelName`)创建使用类型注解的*路径参数*:
```Python hl_lines="16"
{!../../../docs_src/path_params/tutorial005.py!}
@@ -146,17 +153,17 @@
### 查看文档
-因为已经指定了*路径参数*的可用值,所以交互式文档可以恰当地展示它们:
+ API 文档会显示预定义*路径参数*的可用值:
-
+
-### 使用 Python *枚举类型*
+### 使用 Python _枚举类型_
-*路径参数*的值将是一个*枚举成员*。
+*路径参数*的值是枚举的元素。
-#### 比较*枚举成员*
+#### 比较*枚举元素*
-你可以将它与你创建的枚举类 `ModelName` 中的*枚举成员*进行比较:
+枚举类 `ModelName` 中的*枚举元素*支持比较操作:
```Python hl_lines="17"
{!../../../docs_src/path_params/tutorial005.py!}
@@ -164,71 +171,82 @@
#### 获取*枚举值*
-你可以使用 `model_name.value` 或通常来说 `your_enum_member.value` 来获取实际的值(在这个例子中为 `str`):
+使用 `model_name.value` 或 `your_enum_member.value` 获取实际的值(本例中为**字符串**):
-```Python hl_lines="19"
+```Python hl_lines="20"
{!../../../docs_src/path_params/tutorial005.py!}
```
-!!! tip
- 你也可以通过 `ModelName.lenet.value` 来获取值 `"lenet"`。
+!!! tip "提示"
-#### 返回*枚举成员*
+ 使用 `ModelName.lenet.value` 也能获取值 `"lenet"`。
-你可以从*路径操作*中返回*枚举成员*,即使嵌套在 JSON 结构中(例如一个 `dict` 中)。
+#### 返回*枚举元素*
-在返回给客户端之前,它们将被转换为对应的值:
+即使嵌套在 JSON 请求体里(例如, `dict`),也可以从*路径操作*返回*枚举元素*。
-```Python hl_lines="18-21"
+返回给客户端之前,要把枚举元素转换为对应的值(本例中为字符串):
+
+```Python hl_lines="18 21 23"
{!../../../docs_src/path_params/tutorial005.py!}
```
+客户端中的 JSON 响应如下:
+
+```JSON
+{
+ "model_name": "alexnet",
+ "message": "Deep Learning FTW!"
+}
+```
+
## 包含路径的路径参数
-假设你有一个*路径操作*,它的路径为 `/files/{file_path}`。
+假设*路径操作*的路径为 `/files/{file_path}`。
-但是你需要 `file_path` 自身也包含*路径*,比如 `home/johndoe/myfile.txt`。
+但需要 `file_path` 中也包含*路径*,比如,`home/johndoe/myfile.txt`。
-因此,该文件的URL将类似于这样:`/files/home/johndoe/myfile.txt`。
+此时,该文件的 URL 是这样的:`/files/home/johndoe/myfile.txt`。
### OpenAPI 支持
-OpenAPI 不支持任何方式去声明*路径参数*以在其内部包含*路径*,因为这可能会导致难以测试和定义的情况出现。
+OpenAPI 不支持声明包含路径的*路径参数*,因为这会导致测试和定义更加困难。
-不过,你仍然可以通过 Starlette 的一个内部工具在 **FastAPI** 中实现它。
+不过,仍可使用 Starlette 内置工具在 **FastAPI** 中实现这一功能。
-而且文档依旧可以使用,但是不会添加任何该参数应包含路径的说明。
+而且不影响文档正常运行,但是不会添加该参数包含路径的说明。
### 路径转换器
-你可以使用直接来自 Starlette 的选项来声明一个包含*路径*的*路径参数*:
+直接使用 Starlette 的选项声明包含*路径*的*路径参数*:
```
/files/{file_path:path}
```
-在这种情况下,参数的名称为 `file_path`,结尾部分的 `:path` 说明该参数应匹配任意的*路径*。
+本例中,参数名为 `file_path`,结尾部分的 `:path` 说明该参数应匹配*路径*。
-因此,你可以这样使用它:
+用法如下:
```Python hl_lines="6"
{!../../../docs_src/path_params/tutorial004.py!}
```
-!!! tip
- 你可能会需要参数包含 `/home/johndoe/myfile.txt`,以斜杠(`/`)开头。
+!!! tip "提示"
- 在这种情况下,URL 将会是 `/files//home/johndoe/myfile.txt`,在`files` 和 `home` 之间有一个双斜杠(`//`)。
+ 注意,包含 `/home/johndoe/myfile.txt` 的路径参数要以斜杠(`/`)开头。
-## 总结
+ 本例中的 URL 是 `/files//home/johndoe/myfile.txt`。注意,`files` 和 `home` 之间要使用**双斜杠**(`//`)。
-使用 **FastAPI**,通过简短、直观和标准的 Python 类型声明,你将获得:
+## 小结
-* 编辑器支持:错误检查,代码补全等
-* 数据 "解析"
-* 数据校验
-* API 标注和自动生成的文档
+通过简短、直观的 Python 标准类型声明,**FastAPI** 可以获得:
-而且你只需要声明一次即可。
+- 编辑器支持:错误检查,代码自动补全等
+- 数据**解析**
+- 数据校验
+- API 注解和 API 文档
-这可能是 **FastAPI** 与其他框架相比主要的明显优势(除了原始性能以外)。
+只需要声明一次即可。
+
+这可能是除了性能以外,**FastAPI** 与其它框架相比的主要优势。
diff --git a/docs/zh/docs/tutorial/query-params.md b/docs/zh/docs/tutorial/query-params.md
index a0cc7fea39..77138de510 100644
--- a/docs/zh/docs/tutorial/query-params.md
+++ b/docs/zh/docs/tutorial/query-params.md
@@ -1,67 +1,67 @@
# 查询参数
-声明不属于路径参数的其他函数参数时,它们将被自动解释为"查询字符串"参数
+声明的参数不是路径参数时,路径操作函数会把该参数自动解释为**查询**参数。
```Python hl_lines="9"
{!../../../docs_src/query_params/tutorial001.py!}
```
-查询字符串是键值对的集合,这些键值对位于 URL 的 `?` 之后,并以 `&` 符号分隔。
+查询字符串是键值对的集合,这些键值对位于 URL 的 `?` 之后,以 `&` 分隔。
-例如,在以下 url 中:
+例如,以下 URL 中:
```
http://127.0.0.1:8000/items/?skip=0&limit=10
```
-...查询参数为:
+……查询参数为:
-* `skip`:对应的值为 `0`
-* `limit`:对应的值为 `10`
+* `skip`:值为 `0`
+* `limit`:值为 `10`
-由于它们是 URL 的一部分,因此它们的"原始值"是字符串。
+这些值都是 URL 的组成部分,因此,它们的类型**本应**是字符串。
-但是,当你为它们声明了 Python 类型(在上面的示例中为 `int`)时,它们将转换为该类型并针对该类型进行校验。
+但声明 Python 类型(上例中为 `int`)之后,这些值就会转换为声明的类型,并进行类型校验。
-应用于路径参数的所有相同过程也适用于查询参数:
+所有应用于路径参数的流程也适用于查询参数:
-* (很明显的)编辑器支持
-* 数据"解析"
+* (显而易见的)编辑器支持
+* 数据**解析**
* 数据校验
-* 自动生成文档
+* API 文档
## 默认值
-由于查询参数不是路径的固定部分,因此它们可以是可选的,并且可以有默认值。
+查询参数不是路径的固定内容,它是可选的,还支持默认值。
-在上面的示例中,它们具有 `skip=0` 和 `limit=10` 的默认值。
+上例用 `skip=0` 和 `limit=10` 设定默认值。
-因此,访问 URL:
+访问 URL:
```
http://127.0.0.1:8000/items/
```
-将与访问以下地址相同:
+与访问以下地址相同:
```
http://127.0.0.1:8000/items/?skip=0&limit=10
```
-但是,如果你访问的是:
+但如果访问:
```
http://127.0.0.1:8000/items/?skip=20
```
-函数中的参数值将会是:
+查询参数的值就是:
* `skip=20`:在 URL 中设定的值
* `limit=10`:使用默认值
## 可选参数
-通过同样的方式,你可以将它们的默认值设置为 `None` 来声明可选查询参数:
+同理,把默认值设为 `None` 即可声明**可选的**查询参数:
=== "Python 3.10+"
@@ -76,20 +76,27 @@ http://127.0.0.1:8000/items/?skip=20
```
-在这个例子中,函数参数 `q` 将是可选的,并且默认值为 `None`。
+本例中,查询参数 `q` 是可选的,默认值为 `None`。
-!!! check
- 还要注意的是,**FastAPI** 足够聪明,能够分辨出参数 `item_id` 是路径参数而 `q` 不是,因此 `q` 是一个查询参数。
+!!! check "检查"
+
+ 注意,**FastAPI** 可以识别出 `item_id` 是路径参数,`q` 不是路径参数,而是查询参数。
+
+!!! note "笔记"
+
+ 因为默认值为 `= None`,FastAPI 把 `q` 识别为可选参数。
+
+ FastAPI 不使用 `Optional[str]` 中的 `Optional`(只使用 `str`),但 `Optional[str]` 可以帮助编辑器发现代码中的错误。
## 查询参数类型转换
-你还可以声明 `bool` 类型,它们将被自动转换:
+参数还可以声明为 `bool` 类型,FastAPI 会自动转换参数类型:
-```Python hl_lines="7"
+```Python hl_lines="9"
{!../../../docs_src/query_params/tutorial003.py!}
```
-这个例子中,如果你访问:
+本例中,访问:
```
http://127.0.0.1:8000/items/foo?short=1
@@ -119,42 +126,42 @@ http://127.0.0.1:8000/items/foo?short=on
http://127.0.0.1:8000/items/foo?short=yes
```
-或任何其他的变体形式(大写,首字母大写等等),你的函数接收的 `short` 参数都会是布尔值 `True`。对于值为 `False` 的情况也是一样的。
+或其它任意大小写形式(大写、首字母大写等),函数接收的 `short` 参数都是布尔值 `True`。值为 `False` 时也一样。
## 多个路径和查询参数
-你可以同时声明多个路径参数和查询参数,**FastAPI** 能够识别它们。
+**FastAPI** 可以识别同时声明的多个路径参数和查询参数。
-而且你不需要以任何特定的顺序来声明。
+而且声明查询参数的顺序并不重要。
-它们将通过名称被检测到:
+FastAPI 通过参数名进行检测:
-```Python hl_lines="6 8"
+```Python hl_lines="8 10"
{!../../../docs_src/query_params/tutorial004.py!}
```
-## 必需查询参数
+## 必选查询参数
-当你为非路径参数声明了默认值时(目前而言,我们所知道的仅有查询参数),则该参数不是必需的。
+为不是路径参数的参数声明默认值(至此,仅有查询参数),该参数就**不是必选**的了。
-如果你不想添加一个特定的值,而只是想使该参数成为可选的,则将默认值设置为 `None`。
+如果只想把参数设为**可选**,但又不想指定参数的值,则要把默认值设为 `None`。
-但当你想让一个查询参数成为必需的,不声明任何默认值就可以:
+如果要把查询参数设置为**必选**,就不要声明默认值:
```Python hl_lines="6-7"
{!../../../docs_src/query_params/tutorial005.py!}
```
-这里的查询参数 `needy` 是类型为 `str` 的必需查询参数。
+这里的查询参数 `needy` 是类型为 `str` 的必选查询参数。
-如果你在浏览器中打开一个像下面的 URL:
+在浏览器中打开如下 URL:
```
http://127.0.0.1:8000/items/foo-item
```
-...因为没有添加必需的参数 `needy`,你将看到类似以下的错误:
+……因为路径中没有必选参数 `needy`,返回的响应中会显示如下错误信息:
```JSON
{
@@ -171,13 +178,13 @@ http://127.0.0.1:8000/items/foo-item
}
```
-由于 `needy` 是必需参数,因此你需要在 URL 中设置它的值:
+`needy` 是必选参数,因此要在 URL 中设置值:
```
http://127.0.0.1:8000/items/foo-item?needy=sooooneedy
```
-...这样就正常了:
+……这样就正常了:
```JSON
{
@@ -186,17 +193,17 @@ http://127.0.0.1:8000/items/foo-item?needy=sooooneedy
}
```
-当然,你也可以定义一些参数为必需的,一些具有默认值,而某些则完全是可选的:
+当然,把一些参数定义为必选,为另一些参数设置默认值,再把其它参数定义为可选,这些操作都是可以的:
-```Python hl_lines="7"
+```Python hl_lines="10"
{!../../../docs_src/query_params/tutorial006.py!}
```
-在这个例子中,有3个查询参数:
+本例中有 3 个查询参数:
-* `needy`,一个必需的 `str` 类型参数。
-* `skip`,一个默认值为 `0` 的 `int` 类型参数。
-* `limit`,一个可选的 `int` 类型参数。
+* `needy`,必选的 `str` 类型参数
+* `skip`,默认值为 `0` 的 `int` 类型参数
+* `limit`,可选的 `int` 类型参数
-!!! tip
- 你还可以像在 [路径参数](path-params.md#predefined-values){.internal-link target=_blank} 中那样使用 `Enum`。
+!!! tip "提示"
+ 还可以像在[路径参数](path-params.md#_8){.internal-link target=_blank} 中那样使用 `Enum`。
diff --git a/docs/zh/docs/tutorial/security/simple-oauth2.md b/docs/zh/docs/tutorial/security/simple-oauth2.md
index c7f46177f0..751767ea22 100644
--- a/docs/zh/docs/tutorial/security/simple-oauth2.md
+++ b/docs/zh/docs/tutorial/security/simple-oauth2.md
@@ -144,7 +144,7 @@ UserInDB(
!!! info "说明"
- `user_dict` 的说明,详见[**更多模型**一章](../extra-models.md#about-user_indict){.internal-link target=_blank}。
+ `user_dict` 的说明,详见[**更多模型**一章](../extra-models.md#user_indict){.internal-link target=_blank}。
## 返回 Token
diff --git a/docs/zh/docs/tutorial/testing.md b/docs/zh/docs/tutorial/testing.md
index 77fff75964..69841978c7 100644
--- a/docs/zh/docs/tutorial/testing.md
+++ b/docs/zh/docs/tutorial/testing.md
@@ -8,7 +8,7 @@
## 使用 `TestClient`
-!!! 信息
+!!! info "信息"
要使用 `TestClient`,先要安装 `httpx`.
例:`pip install httpx`.
@@ -27,7 +27,7 @@
{!../../../docs_src/app_testing/tutorial001.py!}
```
-!!! 提示
+!!! tip "提示"
注意测试函数是普通的 `def`,不是 `async def`。
还有client的调用也是普通的调用,不是用 `await`。
@@ -39,7 +39,7 @@
**FastAPI** 提供了和 `starlette.testclient` 一样的 `fastapi.testclient`,只是为了方便开发者。但它直接来自Starlette。
-!!! 提示
+!!! tip "提示"
除了发送请求之外,如果你还想测试时在FastAPI应用中调用 `async` 函数(例如异步数据库函数), 可以在高级教程中看下 [Async Tests](../advanced/async-tests.md){.internal-link target=_blank} 。
## 分离测试
@@ -50,7 +50,7 @@
### **FastAPI** app 文件
-假设你有一个像 [更大的应用](./bigger-applications.md){.internal-link target=_blank} 中所描述的文件结构:
+假设你有一个像 [更大的应用](bigger-applications.md){.internal-link target=_blank} 中所描述的文件结构:
```
.
@@ -130,7 +130,7 @@
=== "Python 3.10+ non-Annotated"
- !!! tip
+ !!! tip "提示"
Prefer to use the `Annotated` version if possible.
```Python
@@ -139,7 +139,7 @@
=== "Python 3.8+ non-Annotated"
- !!! tip
+ !!! tip "提示"
Prefer to use the `Annotated` version if possible.
```Python
@@ -168,7 +168,7 @@
关于如何传数据给后端的更多信息 (使用`httpx` 或 `TestClient`),请查阅 HTTPX 文档.
-!!! 信息
+!!! info "信息"
注意 `TestClient` 接收可以被转化为JSON的数据,而不是Pydantic模型。
如果你在测试中有一个Pydantic模型,并且你想在测试时发送它的数据给应用,你可以使用在[JSON Compatible Encoder](encoder.md){.internal-link target=_blank}介绍的`jsonable_encoder` 。
diff --git a/docs_src/path_operation_advanced_configuration/tutorial007.py b/docs_src/path_operation_advanced_configuration/tutorial007.py
index 972ddbd2cc..54e2e9399e 100644
--- a/docs_src/path_operation_advanced_configuration/tutorial007.py
+++ b/docs_src/path_operation_advanced_configuration/tutorial007.py
@@ -30,5 +30,5 @@ async def create_item(request: Request):
try:
item = Item.model_validate(data)
except ValidationError as e:
- raise HTTPException(status_code=422, detail=e.errors())
+ raise HTTPException(status_code=422, detail=e.errors(include_url=False))
return item
diff --git a/fastapi/__init__.py b/fastapi/__init__.py
index 2349692566..5a77101fb7 100644
--- a/fastapi/__init__.py
+++ b/fastapi/__init__.py
@@ -1,6 +1,6 @@
"""FastAPI framework, high performance, easy to learn, fast to code, ready for production"""
-__version__ = "0.110.0"
+__version__ = "0.110.1"
from starlette import status as status
diff --git a/fastapi/_compat.py b/fastapi/_compat.py
index 35d4a87231..06b847b4f3 100644
--- a/fastapi/_compat.py
+++ b/fastapi/_compat.py
@@ -20,10 +20,12 @@ from typing import (
from fastapi.exceptions import RequestErrorModel
from fastapi.types import IncEx, ModelNameMap, UnionType
from pydantic import BaseModel, create_model
-from pydantic.version import VERSION as PYDANTIC_VERSION
+from pydantic.version import VERSION as P_VERSION
from starlette.datastructures import UploadFile
from typing_extensions import Annotated, Literal, get_args, get_origin
+# Reassign variable to make it reexported for mypy
+PYDANTIC_VERSION = P_VERSION
PYDANTIC_V2 = PYDANTIC_VERSION.startswith("2.")
@@ -127,7 +129,7 @@ if PYDANTIC_V2:
)
except ValidationError as exc:
return None, _regenerate_error_with_loc(
- errors=exc.errors(), loc_prefix=loc
+ errors=exc.errors(include_url=False), loc_prefix=loc
)
def serialize(
@@ -266,7 +268,7 @@ if PYDANTIC_V2:
def get_missing_field_error(loc: Tuple[str, ...]) -> Dict[str, Any]:
error = ValidationError.from_exception_data(
"Field required", [{"type": "missing", "loc": loc, "input": {}}]
- ).errors()[0]
+ ).errors(include_url=False)[0]
error["input"] = None
return error # type: ignore[return-value]
diff --git a/fastapi/applications.py b/fastapi/applications.py
index d3edcc8802..4446cacfb5 100644
--- a/fastapi/applications.py
+++ b/fastapi/applications.py
@@ -40,7 +40,7 @@ from starlette.requests import Request
from starlette.responses import HTMLResponse, JSONResponse, Response
from starlette.routing import BaseRoute
from starlette.types import ASGIApp, Lifespan, Receive, Scope, Send
-from typing_extensions import Annotated, Doc, deprecated # type: ignore [attr-defined]
+from typing_extensions import Annotated, Doc, deprecated
AppType = TypeVar("AppType", bound="FastAPI")
diff --git a/fastapi/background.py b/fastapi/background.py
index 35ab1b2270..203578a41f 100644
--- a/fastapi/background.py
+++ b/fastapi/background.py
@@ -1,7 +1,7 @@
from typing import Any, Callable
from starlette.background import BackgroundTasks as StarletteBackgroundTasks
-from typing_extensions import Annotated, Doc, ParamSpec # type: ignore [attr-defined]
+from typing_extensions import Annotated, Doc, ParamSpec
P = ParamSpec("P")
diff --git a/fastapi/datastructures.py b/fastapi/datastructures.py
index ce03e3ce47..cf8406b0fc 100644
--- a/fastapi/datastructures.py
+++ b/fastapi/datastructures.py
@@ -24,7 +24,7 @@ from starlette.datastructures import Headers as Headers # noqa: F401
from starlette.datastructures import QueryParams as QueryParams # noqa: F401
from starlette.datastructures import State as State # noqa: F401
from starlette.datastructures import UploadFile as StarletteUploadFile
-from typing_extensions import Annotated, Doc # type: ignore [attr-defined]
+from typing_extensions import Annotated, Doc
class UploadFile(StarletteUploadFile):
diff --git a/fastapi/dependencies/utils.py b/fastapi/dependencies/utils.py
index 02284b4ed0..4f984177a4 100644
--- a/fastapi/dependencies/utils.py
+++ b/fastapi/dependencies/utils.py
@@ -1,6 +1,6 @@
import inspect
from contextlib import AsyncExitStack, contextmanager
-from copy import deepcopy
+from copy import copy, deepcopy
from typing import (
Any,
Callable,
@@ -384,6 +384,8 @@ def analyze_param(
field_info.annotation = type_annotation
if depends is not None and depends.dependency is None:
+ # Copy `depends` before mutating it
+ depends = copy(depends)
depends.dependency = type_annotation
if lenient_issubclass(
diff --git a/fastapi/encoders.py b/fastapi/encoders.py
index 431387f716..451ea0760f 100644
--- a/fastapi/encoders.py
+++ b/fastapi/encoders.py
@@ -22,9 +22,9 @@ from pydantic import BaseModel
from pydantic.color import Color
from pydantic.networks import AnyUrl, NameEmail
from pydantic.types import SecretBytes, SecretStr
-from typing_extensions import Annotated, Doc # type: ignore [attr-defined]
+from typing_extensions import Annotated, Doc
-from ._compat import PYDANTIC_V2, Url, _model_dump
+from ._compat import PYDANTIC_V2, UndefinedType, Url, _model_dump
# Taken from Pydantic v1 as is
@@ -259,6 +259,8 @@ def jsonable_encoder(
return str(obj)
if isinstance(obj, (str, int, float, type(None))):
return obj
+ if isinstance(obj, UndefinedType):
+ return None
if isinstance(obj, dict):
encoded_dict = {}
allowed_keys = set(obj.keys())
diff --git a/fastapi/exceptions.py b/fastapi/exceptions.py
index 680d288e4d..44d4ada86d 100644
--- a/fastapi/exceptions.py
+++ b/fastapi/exceptions.py
@@ -3,7 +3,7 @@ from typing import Any, Dict, Optional, Sequence, Type, Union
from pydantic import BaseModel, create_model
from starlette.exceptions import HTTPException as StarletteHTTPException
from starlette.exceptions import WebSocketException as StarletteWebSocketException
-from typing_extensions import Annotated, Doc # type: ignore [attr-defined]
+from typing_extensions import Annotated, Doc
class HTTPException(StarletteHTTPException):
diff --git a/fastapi/openapi/docs.py b/fastapi/openapi/docs.py
index 69473d19cb..67815e0fb5 100644
--- a/fastapi/openapi/docs.py
+++ b/fastapi/openapi/docs.py
@@ -3,7 +3,7 @@ from typing import Any, Dict, Optional
from fastapi.encoders import jsonable_encoder
from starlette.responses import HTMLResponse
-from typing_extensions import Annotated, Doc # type: ignore [attr-defined]
+from typing_extensions import Annotated, Doc
swagger_ui_default_parameters: Annotated[
Dict[str, Any],
diff --git a/fastapi/openapi/models.py b/fastapi/openapi/models.py
index 5f3bdbb206..ed07b40f57 100644
--- a/fastapi/openapi/models.py
+++ b/fastapi/openapi/models.py
@@ -55,35 +55,29 @@ except ImportError: # pragma: no cover
return with_info_plain_validator_function(cls._validate)
-class Contact(BaseModel):
+class BaseModelWithConfig(BaseModel):
+ if PYDANTIC_V2:
+ model_config = {"extra": "allow"}
+
+ else:
+
+ class Config:
+ extra = "allow"
+
+
+class Contact(BaseModelWithConfig):
name: Optional[str] = None
url: Optional[AnyUrl] = None
email: Optional[EmailStr] = None
- if PYDANTIC_V2:
- model_config = {"extra": "allow"}
- else:
-
- class Config:
- extra = "allow"
-
-
-class License(BaseModel):
+class License(BaseModelWithConfig):
name: str
identifier: Optional[str] = None
url: Optional[AnyUrl] = None
- if PYDANTIC_V2:
- model_config = {"extra": "allow"}
- else:
-
- class Config:
- extra = "allow"
-
-
-class Info(BaseModel):
+class Info(BaseModelWithConfig):
title: str
summary: Optional[str] = None
description: Optional[str] = None
@@ -92,42 +86,18 @@ class Info(BaseModel):
license: Optional[License] = None
version: str
- if PYDANTIC_V2:
- model_config = {"extra": "allow"}
- else:
-
- class Config:
- extra = "allow"
-
-
-class ServerVariable(BaseModel):
+class ServerVariable(BaseModelWithConfig):
enum: Annotated[Optional[List[str]], Field(min_length=1)] = None
default: str
description: Optional[str] = None
- if PYDANTIC_V2:
- model_config = {"extra": "allow"}
- else:
-
- class Config:
- extra = "allow"
-
-
-class Server(BaseModel):
+class Server(BaseModelWithConfig):
url: Union[AnyUrl, str]
description: Optional[str] = None
variables: Optional[Dict[str, ServerVariable]] = None
- if PYDANTIC_V2:
- model_config = {"extra": "allow"}
-
- else:
-
- class Config:
- extra = "allow"
-
class Reference(BaseModel):
ref: str = Field(alias="$ref")
@@ -138,36 +108,20 @@ class Discriminator(BaseModel):
mapping: Optional[Dict[str, str]] = None
-class XML(BaseModel):
+class XML(BaseModelWithConfig):
name: Optional[str] = None
namespace: Optional[str] = None
prefix: Optional[str] = None
attribute: Optional[bool] = None
wrapped: Optional[bool] = None
- if PYDANTIC_V2:
- model_config = {"extra": "allow"}
- else:
-
- class Config:
- extra = "allow"
-
-
-class ExternalDocumentation(BaseModel):
+class ExternalDocumentation(BaseModelWithConfig):
description: Optional[str] = None
url: AnyUrl
- if PYDANTIC_V2:
- model_config = {"extra": "allow"}
- else:
-
- class Config:
- extra = "allow"
-
-
-class Schema(BaseModel):
+class Schema(BaseModelWithConfig):
# Ref: JSON Schema 2020-12: https://json-schema.org/draft/2020-12/json-schema-core.html#name-the-json-schema-core-vocabu
# Core Vocabulary
schema_: Optional[str] = Field(default=None, alias="$schema")
@@ -253,14 +207,6 @@ class Schema(BaseModel):
),
] = None
- if PYDANTIC_V2:
- model_config = {"extra": "allow"}
-
- else:
-
- class Config:
- extra = "allow"
-
# Ref: https://json-schema.org/draft/2020-12/json-schema-core.html#name-json-schema-documents
# A JSON Schema MUST be an object or a boolean.
@@ -289,38 +235,22 @@ class ParameterInType(Enum):
cookie = "cookie"
-class Encoding(BaseModel):
+class Encoding(BaseModelWithConfig):
contentType: Optional[str] = None
headers: Optional[Dict[str, Union["Header", Reference]]] = None
style: Optional[str] = None
explode: Optional[bool] = None
allowReserved: Optional[bool] = None
- if PYDANTIC_V2:
- model_config = {"extra": "allow"}
- else:
-
- class Config:
- extra = "allow"
-
-
-class MediaType(BaseModel):
+class MediaType(BaseModelWithConfig):
schema_: Optional[Union[Schema, Reference]] = Field(default=None, alias="schema")
example: Optional[Any] = None
examples: Optional[Dict[str, Union[Example, Reference]]] = None
encoding: Optional[Dict[str, Encoding]] = None
- if PYDANTIC_V2:
- model_config = {"extra": "allow"}
- else:
-
- class Config:
- extra = "allow"
-
-
-class ParameterBase(BaseModel):
+class ParameterBase(BaseModelWithConfig):
description: Optional[str] = None
required: Optional[bool] = None
deprecated: Optional[bool] = None
@@ -334,14 +264,6 @@ class ParameterBase(BaseModel):
# Serialization rules for more complex scenarios
content: Optional[Dict[str, MediaType]] = None
- if PYDANTIC_V2:
- model_config = {"extra": "allow"}
-
- else:
-
- class Config:
- extra = "allow"
-
class Parameter(ParameterBase):
name: str
@@ -352,21 +274,13 @@ class Header(ParameterBase):
pass
-class RequestBody(BaseModel):
+class RequestBody(BaseModelWithConfig):
description: Optional[str] = None
content: Dict[str, MediaType]
required: Optional[bool] = None
- if PYDANTIC_V2:
- model_config = {"extra": "allow"}
- else:
-
- class Config:
- extra = "allow"
-
-
-class Link(BaseModel):
+class Link(BaseModelWithConfig):
operationRef: Optional[str] = None
operationId: Optional[str] = None
parameters: Optional[Dict[str, Union[Any, str]]] = None
@@ -374,31 +288,15 @@ class Link(BaseModel):
description: Optional[str] = None
server: Optional[Server] = None
- if PYDANTIC_V2:
- model_config = {"extra": "allow"}
- else:
-
- class Config:
- extra = "allow"
-
-
-class Response(BaseModel):
+class Response(BaseModelWithConfig):
description: str
headers: Optional[Dict[str, Union[Header, Reference]]] = None
content: Optional[Dict[str, MediaType]] = None
links: Optional[Dict[str, Union[Link, Reference]]] = None
- if PYDANTIC_V2:
- model_config = {"extra": "allow"}
- else:
-
- class Config:
- extra = "allow"
-
-
-class Operation(BaseModel):
+class Operation(BaseModelWithConfig):
tags: Optional[List[str]] = None
summary: Optional[str] = None
description: Optional[str] = None
@@ -413,16 +311,8 @@ class Operation(BaseModel):
security: Optional[List[Dict[str, List[str]]]] = None
servers: Optional[List[Server]] = None
- if PYDANTIC_V2:
- model_config = {"extra": "allow"}
- else:
-
- class Config:
- extra = "allow"
-
-
-class PathItem(BaseModel):
+class PathItem(BaseModelWithConfig):
ref: Optional[str] = Field(default=None, alias="$ref")
summary: Optional[str] = None
description: Optional[str] = None
@@ -437,14 +327,6 @@ class PathItem(BaseModel):
servers: Optional[List[Server]] = None
parameters: Optional[List[Union[Parameter, Reference]]] = None
- if PYDANTIC_V2:
- model_config = {"extra": "allow"}
-
- else:
-
- class Config:
- extra = "allow"
-
class SecuritySchemeType(Enum):
apiKey = "apiKey"
@@ -453,18 +335,10 @@ class SecuritySchemeType(Enum):
openIdConnect = "openIdConnect"
-class SecurityBase(BaseModel):
+class SecurityBase(BaseModelWithConfig):
type_: SecuritySchemeType = Field(alias="type")
description: Optional[str] = None
- if PYDANTIC_V2:
- model_config = {"extra": "allow"}
-
- else:
-
- class Config:
- extra = "allow"
-
class APIKeyIn(Enum):
query = "query"
@@ -488,18 +362,10 @@ class HTTPBearer(HTTPBase):
bearerFormat: Optional[str] = None
-class OAuthFlow(BaseModel):
+class OAuthFlow(BaseModelWithConfig):
refreshUrl: Optional[str] = None
scopes: Dict[str, str] = {}
- if PYDANTIC_V2:
- model_config = {"extra": "allow"}
-
- else:
-
- class Config:
- extra = "allow"
-
class OAuthFlowImplicit(OAuthFlow):
authorizationUrl: str
@@ -518,20 +384,12 @@ class OAuthFlowAuthorizationCode(OAuthFlow):
tokenUrl: str
-class OAuthFlows(BaseModel):
+class OAuthFlows(BaseModelWithConfig):
implicit: Optional[OAuthFlowImplicit] = None
password: Optional[OAuthFlowPassword] = None
clientCredentials: Optional[OAuthFlowClientCredentials] = None
authorizationCode: Optional[OAuthFlowAuthorizationCode] = None
- if PYDANTIC_V2:
- model_config = {"extra": "allow"}
-
- else:
-
- class Config:
- extra = "allow"
-
class OAuth2(SecurityBase):
type_: SecuritySchemeType = Field(default=SecuritySchemeType.oauth2, alias="type")
@@ -548,7 +406,7 @@ class OpenIdConnect(SecurityBase):
SecurityScheme = Union[APIKey, HTTPBase, OAuth2, OpenIdConnect, HTTPBearer]
-class Components(BaseModel):
+class Components(BaseModelWithConfig):
schemas: Optional[Dict[str, Union[Schema, Reference]]] = None
responses: Optional[Dict[str, Union[Response, Reference]]] = None
parameters: Optional[Dict[str, Union[Parameter, Reference]]] = None
@@ -561,30 +419,14 @@ class Components(BaseModel):
callbacks: Optional[Dict[str, Union[Dict[str, PathItem], Reference, Any]]] = None
pathItems: Optional[Dict[str, Union[PathItem, Reference]]] = None
- if PYDANTIC_V2:
- model_config = {"extra": "allow"}
- else:
-
- class Config:
- extra = "allow"
-
-
-class Tag(BaseModel):
+class Tag(BaseModelWithConfig):
name: str
description: Optional[str] = None
externalDocs: Optional[ExternalDocumentation] = None
- if PYDANTIC_V2:
- model_config = {"extra": "allow"}
- else:
-
- class Config:
- extra = "allow"
-
-
-class OpenAPI(BaseModel):
+class OpenAPI(BaseModelWithConfig):
openapi: str
info: Info
jsonSchemaDialect: Optional[str] = None
@@ -597,14 +439,6 @@ class OpenAPI(BaseModel):
tags: Optional[List[Tag]] = None
externalDocs: Optional[ExternalDocumentation] = None
- if PYDANTIC_V2:
- model_config = {"extra": "allow"}
-
- else:
-
- class Config:
- extra = "allow"
-
_model_rebuild(Schema)
_model_rebuild(Operation)
diff --git a/fastapi/openapi/utils.py b/fastapi/openapi/utils.py
index 5bfb5acef7..79ad9f83f2 100644
--- a/fastapi/openapi/utils.py
+++ b/fastapi/openapi/utils.py
@@ -123,7 +123,7 @@ def get_openapi_operation_parameters(
elif field_info.example != Undefined:
parameter["example"] = jsonable_encoder(field_info.example)
if field_info.deprecated:
- parameter["deprecated"] = field_info.deprecated
+ parameter["deprecated"] = True
parameters.append(parameter)
return parameters
diff --git a/fastapi/param_functions.py b/fastapi/param_functions.py
index 3f6dbc959d..3b25d774ad 100644
--- a/fastapi/param_functions.py
+++ b/fastapi/param_functions.py
@@ -3,7 +3,7 @@ from typing import Any, Callable, Dict, List, Optional, Sequence, Union
from fastapi import params
from fastapi._compat import Undefined
from fastapi.openapi.models import Example
-from typing_extensions import Annotated, Doc, deprecated # type: ignore [attr-defined]
+from typing_extensions import Annotated, Doc, deprecated
_Unset: Any = Undefined
@@ -240,7 +240,7 @@ def Path( # noqa: N802
),
] = None,
deprecated: Annotated[
- Optional[bool],
+ Union[deprecated, str, bool, None],
Doc(
"""
Mark this parameter field as deprecated.
@@ -565,7 +565,7 @@ def Query( # noqa: N802
),
] = None,
deprecated: Annotated[
- Optional[bool],
+ Union[deprecated, str, bool, None],
Doc(
"""
Mark this parameter field as deprecated.
@@ -880,7 +880,7 @@ def Header( # noqa: N802
),
] = None,
deprecated: Annotated[
- Optional[bool],
+ Union[deprecated, str, bool, None],
Doc(
"""
Mark this parameter field as deprecated.
@@ -1185,7 +1185,7 @@ def Cookie( # noqa: N802
),
] = None,
deprecated: Annotated[
- Optional[bool],
+ Union[deprecated, str, bool, None],
Doc(
"""
Mark this parameter field as deprecated.
@@ -1512,7 +1512,7 @@ def Body( # noqa: N802
),
] = None,
deprecated: Annotated[
- Optional[bool],
+ Union[deprecated, str, bool, None],
Doc(
"""
Mark this parameter field as deprecated.
@@ -1827,7 +1827,7 @@ def Form( # noqa: N802
),
] = None,
deprecated: Annotated[
- Optional[bool],
+ Union[deprecated, str, bool, None],
Doc(
"""
Mark this parameter field as deprecated.
@@ -2141,7 +2141,7 @@ def File( # noqa: N802
),
] = None,
deprecated: Annotated[
- Optional[bool],
+ Union[deprecated, str, bool, None],
Doc(
"""
Mark this parameter field as deprecated.
diff --git a/fastapi/params.py b/fastapi/params.py
index b40944dba6..860146531a 100644
--- a/fastapi/params.py
+++ b/fastapi/params.py
@@ -6,7 +6,7 @@ from fastapi.openapi.models import Example
from pydantic.fields import FieldInfo
from typing_extensions import Annotated, deprecated
-from ._compat import PYDANTIC_V2, Undefined
+from ._compat import PYDANTIC_V2, PYDANTIC_VERSION, Undefined
_Unset: Any = Undefined
@@ -63,12 +63,11 @@ class Param(FieldInfo):
),
] = _Unset,
openapi_examples: Optional[Dict[str, Example]] = None,
- deprecated: Optional[bool] = None,
+ deprecated: Union[deprecated, str, bool, None] = None,
include_in_schema: bool = True,
json_schema_extra: Union[Dict[str, Any], None] = None,
**extra: Any,
):
- self.deprecated = deprecated
if example is not _Unset:
warnings.warn(
"`example` has been deprecated, please use `examples` instead",
@@ -106,6 +105,10 @@ class Param(FieldInfo):
stacklevel=4,
)
current_json_schema_extra = json_schema_extra or extra
+ if PYDANTIC_VERSION < "2.7.0":
+ self.deprecated = deprecated
+ else:
+ kwargs["deprecated"] = deprecated
if PYDANTIC_V2:
kwargs.update(
{
@@ -174,7 +177,7 @@ class Path(Param):
),
] = _Unset,
openapi_examples: Optional[Dict[str, Example]] = None,
- deprecated: Optional[bool] = None,
+ deprecated: Union[deprecated, str, bool, None] = None,
include_in_schema: bool = True,
json_schema_extra: Union[Dict[str, Any], None] = None,
**extra: Any,
@@ -260,7 +263,7 @@ class Query(Param):
),
] = _Unset,
openapi_examples: Optional[Dict[str, Example]] = None,
- deprecated: Optional[bool] = None,
+ deprecated: Union[deprecated, str, bool, None] = None,
include_in_schema: bool = True,
json_schema_extra: Union[Dict[str, Any], None] = None,
**extra: Any,
@@ -345,7 +348,7 @@ class Header(Param):
),
] = _Unset,
openapi_examples: Optional[Dict[str, Example]] = None,
- deprecated: Optional[bool] = None,
+ deprecated: Union[deprecated, str, bool, None] = None,
include_in_schema: bool = True,
json_schema_extra: Union[Dict[str, Any], None] = None,
**extra: Any,
@@ -430,7 +433,7 @@ class Cookie(Param):
),
] = _Unset,
openapi_examples: Optional[Dict[str, Example]] = None,
- deprecated: Optional[bool] = None,
+ deprecated: Union[deprecated, str, bool, None] = None,
include_in_schema: bool = True,
json_schema_extra: Union[Dict[str, Any], None] = None,
**extra: Any,
@@ -514,14 +517,13 @@ class Body(FieldInfo):
),
] = _Unset,
openapi_examples: Optional[Dict[str, Example]] = None,
- deprecated: Optional[bool] = None,
+ deprecated: Union[deprecated, str, bool, None] = None,
include_in_schema: bool = True,
json_schema_extra: Union[Dict[str, Any], None] = None,
**extra: Any,
):
self.embed = embed
self.media_type = media_type
- self.deprecated = deprecated
if example is not _Unset:
warnings.warn(
"`example` has been deprecated, please use `examples` instead",
@@ -559,6 +561,10 @@ class Body(FieldInfo):
stacklevel=4,
)
current_json_schema_extra = json_schema_extra or extra
+ if PYDANTIC_VERSION < "2.7.0":
+ self.deprecated = deprecated
+ else:
+ kwargs["deprecated"] = deprecated
if PYDANTIC_V2:
kwargs.update(
{
@@ -627,7 +633,7 @@ class Form(Body):
),
] = _Unset,
openapi_examples: Optional[Dict[str, Example]] = None,
- deprecated: Optional[bool] = None,
+ deprecated: Union[deprecated, str, bool, None] = None,
include_in_schema: bool = True,
json_schema_extra: Union[Dict[str, Any], None] = None,
**extra: Any,
@@ -712,7 +718,7 @@ class File(Form):
),
] = _Unset,
openapi_examples: Optional[Dict[str, Example]] = None,
- deprecated: Optional[bool] = None,
+ deprecated: Union[deprecated, str, bool, None] = None,
include_in_schema: bool = True,
json_schema_extra: Union[Dict[str, Any], None] = None,
**extra: Any,
diff --git a/fastapi/routing.py b/fastapi/routing.py
index 23a32d15fd..fa1351859f 100644
--- a/fastapi/routing.py
+++ b/fastapi/routing.py
@@ -69,7 +69,7 @@ from starlette.routing import (
from starlette.routing import Mount as Mount # noqa
from starlette.types import ASGIApp, Lifespan, Scope
from starlette.websockets import WebSocket
-from typing_extensions import Annotated, Doc, deprecated # type: ignore [attr-defined]
+from typing_extensions import Annotated, Doc, deprecated
def _prepare_response_content(
diff --git a/fastapi/security/api_key.py b/fastapi/security/api_key.py
index b1a6b4f94b..b74a017f17 100644
--- a/fastapi/security/api_key.py
+++ b/fastapi/security/api_key.py
@@ -5,7 +5,7 @@ from fastapi.security.base import SecurityBase
from starlette.exceptions import HTTPException
from starlette.requests import Request
from starlette.status import HTTP_403_FORBIDDEN
-from typing_extensions import Annotated, Doc # type: ignore [attr-defined]
+from typing_extensions import Annotated, Doc
class APIKeyBase(SecurityBase):
diff --git a/fastapi/security/http.py b/fastapi/security/http.py
index 738455de38..b45bee55c9 100644
--- a/fastapi/security/http.py
+++ b/fastapi/security/http.py
@@ -10,7 +10,7 @@ from fastapi.security.utils import get_authorization_scheme_param
from pydantic import BaseModel
from starlette.requests import Request
from starlette.status import HTTP_401_UNAUTHORIZED, HTTP_403_FORBIDDEN
-from typing_extensions import Annotated, Doc # type: ignore [attr-defined]
+from typing_extensions import Annotated, Doc
class HTTPBasicCredentials(BaseModel):
diff --git a/fastapi/security/oauth2.py b/fastapi/security/oauth2.py
index d7ba44bcea..9720cace05 100644
--- a/fastapi/security/oauth2.py
+++ b/fastapi/security/oauth2.py
@@ -10,7 +10,7 @@ from starlette.requests import Request
from starlette.status import HTTP_401_UNAUTHORIZED, HTTP_403_FORBIDDEN
# TODO: import from typing when deprecating Python 3.9
-from typing_extensions import Annotated, Doc # type: ignore [attr-defined]
+from typing_extensions import Annotated, Doc
class OAuth2PasswordRequestForm:
diff --git a/fastapi/security/open_id_connect_url.py b/fastapi/security/open_id_connect_url.py
index 1d255877db..c8cceb911c 100644
--- a/fastapi/security/open_id_connect_url.py
+++ b/fastapi/security/open_id_connect_url.py
@@ -5,7 +5,7 @@ from fastapi.security.base import SecurityBase
from starlette.exceptions import HTTPException
from starlette.requests import Request
from starlette.status import HTTP_403_FORBIDDEN
-from typing_extensions import Annotated, Doc # type: ignore [attr-defined]
+from typing_extensions import Annotated, Doc
class OpenIdConnect(SecurityBase):
diff --git a/fastapi/utils.py b/fastapi/utils.py
index 53b2fa0c36..dfda4e678a 100644
--- a/fastapi/utils.py
+++ b/fastapi/utils.py
@@ -221,9 +221,3 @@ def get_value_or_default(
if not isinstance(item, DefaultPlaceholder):
return item
return first_item
-
-
-def match_pydantic_error_url(error_type: str) -> Any:
- from dirty_equals import IsStr
-
- return IsStr(regex=rf"^https://errors\.pydantic\.dev/.*/v/{error_type}")
diff --git a/pyproject.toml b/pyproject.toml
index c3801600a1..6c3bebf2bc 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -41,7 +41,7 @@ classifiers = [
"Topic :: Internet :: WWW/HTTP",
]
dependencies = [
- "starlette>=0.36.3,<0.37.0",
+ "starlette>=0.37.2,<0.38.0",
"pydantic>=1.7.4,!=1.8,!=1.8.1,!=2.0.0,!=2.0.1,!=2.1.0,<3.0.0",
"typing-extensions>=4.8.0",
]
@@ -121,9 +121,6 @@ filterwarnings = [
# - https://github.com/mpdavis/python-jose/issues/332
# - https://github.com/mpdavis/python-jose/issues/334
'ignore:datetime\.datetime\.utcnow\(\) is deprecated and scheduled for removal in a future version\..*:DeprecationWarning:jose',
- # TODO: remove after upgrading Starlette to a version including https://github.com/encode/starlette/pull/2406
- # Probably Starlette 0.36.0
- "ignore: The 'method' parameter is not used, and it will be removed.:DeprecationWarning:starlette",
]
[tool.coverage.run]
diff --git a/requirements-docs.txt b/requirements-docs.txt
index 28408a9f1b..8fa64cf39c 100644
--- a/requirements-docs.txt
+++ b/requirements-docs.txt
@@ -2,18 +2,17 @@
-r requirements-docs-tests.txt
mkdocs-material==9.4.7
mdx-include >=1.4.1,<2.0.0
-mkdocs-markdownextradata-plugin >=0.1.7,<0.3.0
mkdocs-redirects>=1.2.1,<1.3.0
-typer-cli >=0.0.13,<0.0.14
-typer[all] >=0.6.1,<0.8.0
+typer >=0.12.0
pyyaml >=5.3.1,<7.0.0
# For Material for MkDocs, Chinese search
jieba==0.42.1
# For image processing by Material for MkDocs
-pillow==10.1.0
+pillow==10.2.0
# For image processing by Material for MkDocs
cairosvg==2.7.0
mkdocstrings[python]==0.23.0
griffe-typingdoc==0.2.2
# For griffe, it formats with black
-black==23.3.0
+black==24.3.0
+mkdocs-macros-plugin==1.0.5
diff --git a/requirements-tests.txt b/requirements-tests.txt
index 09ca9cb52c..30762bc64c 100644
--- a/requirements-tests.txt
+++ b/requirements-tests.txt
@@ -3,7 +3,7 @@
pydantic-settings >=2.0.0
pytest >=7.1.3,<8.0.0
coverage[toml] >= 6.5.0,< 8.0
-mypy ==1.4.1
+mypy ==1.8.0
ruff ==0.2.0
email_validator >=1.1.1,<3.0.0
dirty-equals ==0.6.0
diff --git a/tests/main.py b/tests/main.py
index 15760c0396..6927eab61b 100644
--- a/tests/main.py
+++ b/tests/main.py
@@ -1,5 +1,5 @@
import http
-from typing import FrozenSet, Optional
+from typing import FrozenSet, List, Optional
from fastapi import FastAPI, Path, Query
@@ -192,3 +192,13 @@ def get_enum_status_code():
@app.get("/query/frozenset")
def get_query_type_frozenset(query: FrozenSet[int] = Query(...)):
return ",".join(map(str, sorted(query)))
+
+
+@app.get("/query/list")
+def get_query_list(device_ids: List[int] = Query()) -> List[int]:
+ return device_ids
+
+
+@app.get("/query/list-default")
+def get_query_list_default(device_ids: List[int] = Query(default=[])) -> List[int]:
+ return device_ids
diff --git a/tests/test_annotated.py b/tests/test_annotated.py
index 2222be9783..473d33e52c 100644
--- a/tests/test_annotated.py
+++ b/tests/test_annotated.py
@@ -2,7 +2,6 @@ import pytest
from dirty_equals import IsDict
from fastapi import APIRouter, FastAPI, Query
from fastapi.testclient import TestClient
-from fastapi.utils import match_pydantic_error_url
from typing_extensions import Annotated
app = FastAPI()
@@ -38,7 +37,6 @@ foo_is_missing = {
"msg": "Field required",
"type": "missing",
"input": None,
- "url": match_pydantic_error_url("missing"),
}
)
# TODO: remove when deprecating Pydantic v1
@@ -60,7 +58,6 @@ foo_is_short = {
"msg": "String should have at least 1 character",
"type": "string_too_short",
"input": "",
- "url": match_pydantic_error_url("string_too_short"),
}
)
# TODO: remove when deprecating Pydantic v1
diff --git a/tests/test_application.py b/tests/test_application.py
index ea7a80128f..5c62f5f6e2 100644
--- a/tests/test_application.py
+++ b/tests/test_application.py
@@ -1163,6 +1163,91 @@ def test_openapi_schema():
},
}
},
+ "/query/list": {
+ "get": {
+ "summary": "Get Query List",
+ "operationId": "get_query_list_query_list_get",
+ "parameters": [
+ {
+ "name": "device_ids",
+ "in": "query",
+ "required": True,
+ "schema": {
+ "type": "array",
+ "items": {"type": "integer"},
+ "title": "Device Ids",
+ },
+ }
+ ],
+ "responses": {
+ "200": {
+ "description": "Successful Response",
+ "content": {
+ "application/json": {
+ "schema": {
+ "type": "array",
+ "items": {"type": "integer"},
+ "title": "Response Get Query List Query List Get",
+ }
+ }
+ },
+ },
+ "422": {
+ "description": "Validation Error",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/HTTPValidationError"
+ }
+ }
+ },
+ },
+ },
+ }
+ },
+ "/query/list-default": {
+ "get": {
+ "summary": "Get Query List Default",
+ "operationId": "get_query_list_default_query_list_default_get",
+ "parameters": [
+ {
+ "name": "device_ids",
+ "in": "query",
+ "required": False,
+ "schema": {
+ "type": "array",
+ "items": {"type": "integer"},
+ "default": [],
+ "title": "Device Ids",
+ },
+ }
+ ],
+ "responses": {
+ "200": {
+ "description": "Successful Response",
+ "content": {
+ "application/json": {
+ "schema": {
+ "type": "array",
+ "items": {"type": "integer"},
+ "title": "Response Get Query List Default Query List Default Get",
+ }
+ }
+ },
+ },
+ "422": {
+ "description": "Validation Error",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/HTTPValidationError"
+ }
+ }
+ },
+ },
+ },
+ }
+ },
},
"components": {
"schemas": {
diff --git a/tests/test_dependency_duplicates.py b/tests/test_dependency_duplicates.py
index 0882cc41d7..8e8d07c2d6 100644
--- a/tests/test_dependency_duplicates.py
+++ b/tests/test_dependency_duplicates.py
@@ -3,7 +3,6 @@ from typing import List
from dirty_equals import IsDict
from fastapi import Depends, FastAPI
from fastapi.testclient import TestClient
-from fastapi.utils import match_pydantic_error_url
from pydantic import BaseModel
app = FastAPI()
@@ -57,7 +56,6 @@ def test_no_duplicates_invalid():
"loc": ["body", "item2"],
"msg": "Field required",
"input": None,
- "url": match_pydantic_error_url("missing"),
}
]
}
diff --git a/tests/test_dependency_overrides.py b/tests/test_dependency_overrides.py
index 21cff998d1..154937fa0b 100644
--- a/tests/test_dependency_overrides.py
+++ b/tests/test_dependency_overrides.py
@@ -4,7 +4,6 @@ import pytest
from dirty_equals import IsDict
from fastapi import APIRouter, Depends, FastAPI
from fastapi.testclient import TestClient
-from fastapi.utils import match_pydantic_error_url
app = FastAPI()
@@ -63,7 +62,6 @@ def test_main_depends():
"loc": ["query", "q"],
"msg": "Field required",
"input": None,
- "url": match_pydantic_error_url("missing"),
}
]
}
@@ -110,7 +108,6 @@ def test_decorator_depends():
"loc": ["query", "q"],
"msg": "Field required",
"input": None,
- "url": match_pydantic_error_url("missing"),
}
]
}
@@ -151,7 +148,6 @@ def test_router_depends():
"loc": ["query", "q"],
"msg": "Field required",
"input": None,
- "url": match_pydantic_error_url("missing"),
}
]
}
@@ -198,7 +194,6 @@ def test_router_decorator_depends():
"loc": ["query", "q"],
"msg": "Field required",
"input": None,
- "url": match_pydantic_error_url("missing"),
}
]
}
@@ -285,7 +280,6 @@ def test_override_with_sub_main_depends():
"loc": ["query", "k"],
"msg": "Field required",
"input": None,
- "url": match_pydantic_error_url("missing"),
}
]
}
@@ -316,7 +310,6 @@ def test_override_with_sub__main_depends_q_foo():
"loc": ["query", "k"],
"msg": "Field required",
"input": None,
- "url": match_pydantic_error_url("missing"),
}
]
}
@@ -355,7 +348,6 @@ def test_override_with_sub_decorator_depends():
"loc": ["query", "k"],
"msg": "Field required",
"input": None,
- "url": match_pydantic_error_url("missing"),
}
]
}
@@ -386,7 +378,6 @@ def test_override_with_sub_decorator_depends_q_foo():
"loc": ["query", "k"],
"msg": "Field required",
"input": None,
- "url": match_pydantic_error_url("missing"),
}
]
}
@@ -425,7 +416,6 @@ def test_override_with_sub_router_depends():
"loc": ["query", "k"],
"msg": "Field required",
"input": None,
- "url": match_pydantic_error_url("missing"),
}
]
}
@@ -456,7 +446,6 @@ def test_override_with_sub_router_depends_q_foo():
"loc": ["query", "k"],
"msg": "Field required",
"input": None,
- "url": match_pydantic_error_url("missing"),
}
]
}
@@ -495,7 +484,6 @@ def test_override_with_sub_router_decorator_depends():
"loc": ["query", "k"],
"msg": "Field required",
"input": None,
- "url": match_pydantic_error_url("missing"),
}
]
}
@@ -526,7 +514,6 @@ def test_override_with_sub_router_decorator_depends_q_foo():
"loc": ["query", "k"],
"msg": "Field required",
"input": None,
- "url": match_pydantic_error_url("missing"),
}
]
}
diff --git a/tests/test_filter_pydantic_sub_model_pv2.py b/tests/test_filter_pydantic_sub_model_pv2.py
index 9097d2ce52..2e2c26ddcb 100644
--- a/tests/test_filter_pydantic_sub_model_pv2.py
+++ b/tests/test_filter_pydantic_sub_model_pv2.py
@@ -5,7 +5,6 @@ from dirty_equals import HasRepr, IsDict, IsOneOf
from fastapi import Depends, FastAPI
from fastapi.exceptions import ResponseValidationError
from fastapi.testclient import TestClient
-from fastapi.utils import match_pydantic_error_url
from .utils import needs_pydanticv2
@@ -67,7 +66,6 @@ def test_validator_is_cloned(client: TestClient):
"msg": "Value error, name must end in A",
"input": "modelX",
"ctx": {"error": HasRepr("ValueError('name must end in A')")},
- "url": match_pydantic_error_url("value_error"),
}
)
| IsDict(
diff --git a/tests/test_generic_parameterless_depends.py b/tests/test_generic_parameterless_depends.py
new file mode 100644
index 0000000000..fe13ff89b8
--- /dev/null
+++ b/tests/test_generic_parameterless_depends.py
@@ -0,0 +1,77 @@
+from typing import TypeVar
+
+from fastapi import Depends, FastAPI
+from fastapi.testclient import TestClient
+from typing_extensions import Annotated
+
+app = FastAPI()
+
+T = TypeVar("T")
+
+Dep = Annotated[T, Depends()]
+
+
+class A:
+ pass
+
+
+class B:
+ pass
+
+
+@app.get("/a")
+async def a(dep: Dep[A]):
+ return {"cls": dep.__class__.__name__}
+
+
+@app.get("/b")
+async def b(dep: Dep[B]):
+ return {"cls": dep.__class__.__name__}
+
+
+client = TestClient(app)
+
+
+def test_generic_parameterless_depends():
+ response = client.get("/a")
+ assert response.status_code == 200, response.text
+ assert response.json() == {"cls": "A"}
+
+ response = client.get("/b")
+ assert response.status_code == 200, response.text
+ assert response.json() == {"cls": "B"}
+
+
+def test_openapi_schema():
+ response = client.get("/openapi.json")
+ assert response.status_code == 200, response.text
+ assert response.json() == {
+ "info": {"title": "FastAPI", "version": "0.1.0"},
+ "openapi": "3.1.0",
+ "paths": {
+ "/a": {
+ "get": {
+ "operationId": "a_a_get",
+ "responses": {
+ "200": {
+ "content": {"application/json": {"schema": {}}},
+ "description": "Successful " "Response",
+ }
+ },
+ "summary": "A",
+ }
+ },
+ "/b": {
+ "get": {
+ "operationId": "b_b_get",
+ "responses": {
+ "200": {
+ "content": {"application/json": {"schema": {}}},
+ "description": "Successful " "Response",
+ }
+ },
+ "summary": "B",
+ }
+ },
+ },
+ }
diff --git a/tests/test_jsonable_encoder.py b/tests/test_jsonable_encoder.py
index 7c8338ff37..1906d6bf17 100644
--- a/tests/test_jsonable_encoder.py
+++ b/tests/test_jsonable_encoder.py
@@ -7,7 +7,7 @@ from pathlib import PurePath, PurePosixPath, PureWindowsPath
from typing import Optional
import pytest
-from fastapi._compat import PYDANTIC_V2
+from fastapi._compat import PYDANTIC_V2, Undefined
from fastapi.encoders import jsonable_encoder
from pydantic import BaseModel, Field, ValidationError
@@ -310,3 +310,9 @@ def test_encode_deque_encodes_child_models():
dq = deque([Model(test="test")])
assert jsonable_encoder(dq)[0]["test"] == "test"
+
+
+@needs_pydanticv2
+def test_encode_pydantic_undefined():
+ data = {"value": Undefined}
+ assert jsonable_encoder(data) == {"value": None}
diff --git a/tests/test_multi_body_errors.py b/tests/test_multi_body_errors.py
index a51ca7253f..0102f0f1a0 100644
--- a/tests/test_multi_body_errors.py
+++ b/tests/test_multi_body_errors.py
@@ -4,7 +4,6 @@ from typing import List
from dirty_equals import IsDict, IsOneOf
from fastapi import FastAPI
from fastapi.testclient import TestClient
-from fastapi.utils import match_pydantic_error_url
from pydantic import BaseModel, condecimal
app = FastAPI()
@@ -52,7 +51,6 @@ def test_jsonable_encoder_requiring_error():
"msg": "Input should be greater than 0",
"input": -1.0,
"ctx": {"gt": 0},
- "url": match_pydantic_error_url("greater_than"),
}
]
}
@@ -82,28 +80,24 @@ def test_put_incorrect_body_multiple():
"loc": ["body", 0, "name"],
"msg": "Field required",
"input": {"age": "five"},
- "url": match_pydantic_error_url("missing"),
},
{
"type": "decimal_parsing",
"loc": ["body", 0, "age"],
"msg": "Input should be a valid decimal",
"input": "five",
- "url": match_pydantic_error_url("decimal_parsing"),
},
{
"type": "missing",
"loc": ["body", 1, "name"],
"msg": "Field required",
"input": {"age": "six"},
- "url": match_pydantic_error_url("missing"),
},
{
"type": "decimal_parsing",
"loc": ["body", 1, "age"],
"msg": "Input should be a valid decimal",
"input": "six",
- "url": match_pydantic_error_url("decimal_parsing"),
},
]
}
diff --git a/tests/test_multi_query_errors.py b/tests/test_multi_query_errors.py
index 470a358083..8162d986c5 100644
--- a/tests/test_multi_query_errors.py
+++ b/tests/test_multi_query_errors.py
@@ -3,7 +3,6 @@ from typing import List
from dirty_equals import IsDict
from fastapi import FastAPI, Query
from fastapi.testclient import TestClient
-from fastapi.utils import match_pydantic_error_url
app = FastAPI()
@@ -33,14 +32,12 @@ def test_multi_query_incorrect():
"loc": ["query", "q", 0],
"msg": "Input should be a valid integer, unable to parse string as an integer",
"input": "five",
- "url": match_pydantic_error_url("int_parsing"),
},
{
"type": "int_parsing",
"loc": ["query", "q", 1],
"msg": "Input should be a valid integer, unable to parse string as an integer",
"input": "six",
- "url": match_pydantic_error_url("int_parsing"),
},
]
}
diff --git a/tests/test_path.py b/tests/test_path.py
index 848b245e2c..09c1f13fb1 100644
--- a/tests/test_path.py
+++ b/tests/test_path.py
@@ -1,6 +1,5 @@
from dirty_equals import IsDict
from fastapi.testclient import TestClient
-from fastapi.utils import match_pydantic_error_url
from .main import app
@@ -54,7 +53,6 @@ def test_path_int_foobar():
"loc": ["path", "item_id"],
"msg": "Input should be a valid integer, unable to parse string as an integer",
"input": "foobar",
- "url": match_pydantic_error_url("int_parsing"),
}
]
}
@@ -83,7 +81,6 @@ def test_path_int_True():
"loc": ["path", "item_id"],
"msg": "Input should be a valid integer, unable to parse string as an integer",
"input": "True",
- "url": match_pydantic_error_url("int_parsing"),
}
]
}
@@ -118,7 +115,6 @@ def test_path_int_42_5():
"loc": ["path", "item_id"],
"msg": "Input should be a valid integer, unable to parse string as an integer",
"input": "42.5",
- "url": match_pydantic_error_url("int_parsing"),
}
]
}
@@ -147,7 +143,6 @@ def test_path_float_foobar():
"loc": ["path", "item_id"],
"msg": "Input should be a valid number, unable to parse string as a number",
"input": "foobar",
- "url": match_pydantic_error_url("float_parsing"),
}
]
}
@@ -176,7 +171,6 @@ def test_path_float_True():
"loc": ["path", "item_id"],
"msg": "Input should be a valid number, unable to parse string as a number",
"input": "True",
- "url": match_pydantic_error_url("float_parsing"),
}
]
}
@@ -217,7 +211,6 @@ def test_path_bool_foobar():
"loc": ["path", "item_id"],
"msg": "Input should be a valid boolean, unable to interpret input",
"input": "foobar",
- "url": match_pydantic_error_url("bool_parsing"),
}
]
}
@@ -252,7 +245,6 @@ def test_path_bool_42():
"loc": ["path", "item_id"],
"msg": "Input should be a valid boolean, unable to interpret input",
"input": "42",
- "url": match_pydantic_error_url("bool_parsing"),
}
]
}
@@ -281,7 +273,6 @@ def test_path_bool_42_5():
"loc": ["path", "item_id"],
"msg": "Input should be a valid boolean, unable to interpret input",
"input": "42.5",
- "url": match_pydantic_error_url("bool_parsing"),
}
]
}
@@ -353,7 +344,6 @@ def test_path_param_minlength_fo():
"msg": "String should have at least 3 characters",
"input": "fo",
"ctx": {"min_length": 3},
- "url": match_pydantic_error_url("string_too_short"),
}
]
}
@@ -390,7 +380,6 @@ def test_path_param_maxlength_foobar():
"msg": "String should have at most 3 characters",
"input": "foobar",
"ctx": {"max_length": 3},
- "url": match_pydantic_error_url("string_too_long"),
}
]
}
@@ -427,7 +416,6 @@ def test_path_param_min_maxlength_foobar():
"msg": "String should have at most 3 characters",
"input": "foobar",
"ctx": {"max_length": 3},
- "url": match_pydantic_error_url("string_too_long"),
}
]
}
@@ -458,7 +446,6 @@ def test_path_param_min_maxlength_f():
"msg": "String should have at least 2 characters",
"input": "f",
"ctx": {"min_length": 2},
- "url": match_pydantic_error_url("string_too_short"),
}
]
}
@@ -494,7 +481,6 @@ def test_path_param_gt_2():
"msg": "Input should be greater than 3",
"input": "2",
"ctx": {"gt": 3.0},
- "url": match_pydantic_error_url("greater_than"),
}
]
}
@@ -531,7 +517,6 @@ def test_path_param_gt0_0():
"msg": "Input should be greater than 0",
"input": "0",
"ctx": {"gt": 0.0},
- "url": match_pydantic_error_url("greater_than"),
}
]
}
@@ -574,7 +559,6 @@ def test_path_param_ge_2():
"msg": "Input should be greater than or equal to 3",
"input": "2",
"ctx": {"ge": 3.0},
- "url": match_pydantic_error_url("greater_than_equal"),
}
]
}
@@ -605,7 +589,6 @@ def test_path_param_lt_42():
"msg": "Input should be less than 3",
"input": "42",
"ctx": {"lt": 3.0},
- "url": match_pydantic_error_url("less_than"),
}
]
}
@@ -648,7 +631,6 @@ def test_path_param_lt0_0():
"msg": "Input should be less than 0",
"input": "0",
"ctx": {"lt": 0.0},
- "url": match_pydantic_error_url("less_than"),
}
]
}
@@ -679,7 +661,6 @@ def test_path_param_le_42():
"msg": "Input should be less than or equal to 3",
"input": "42",
"ctx": {"le": 3.0},
- "url": match_pydantic_error_url("less_than_equal"),
}
]
}
@@ -728,7 +709,6 @@ def test_path_param_lt_gt_4():
"msg": "Input should be less than 3",
"input": "4",
"ctx": {"lt": 3.0},
- "url": match_pydantic_error_url("less_than"),
}
]
}
@@ -759,7 +739,6 @@ def test_path_param_lt_gt_0():
"msg": "Input should be greater than 1",
"input": "0",
"ctx": {"gt": 1.0},
- "url": match_pydantic_error_url("greater_than"),
}
]
}
@@ -807,7 +786,6 @@ def test_path_param_le_ge_4():
"msg": "Input should be less than or equal to 3",
"input": "4",
"ctx": {"le": 3.0},
- "url": match_pydantic_error_url("less_than_equal"),
}
]
}
@@ -844,7 +822,6 @@ def test_path_param_lt_int_42():
"msg": "Input should be less than 3",
"input": "42",
"ctx": {"lt": 3},
- "url": match_pydantic_error_url("less_than"),
}
]
}
@@ -874,7 +851,6 @@ def test_path_param_lt_int_2_7():
"loc": ["path", "item_id"],
"msg": "Input should be a valid integer, unable to parse string as an integer",
"input": "2.7",
- "url": match_pydantic_error_url("int_parsing"),
}
]
}
@@ -910,7 +886,6 @@ def test_path_param_gt_int_2():
"msg": "Input should be greater than 3",
"input": "2",
"ctx": {"gt": 3},
- "url": match_pydantic_error_url("greater_than"),
}
]
}
@@ -940,7 +915,6 @@ def test_path_param_gt_int_2_7():
"loc": ["path", "item_id"],
"msg": "Input should be a valid integer, unable to parse string as an integer",
"input": "2.7",
- "url": match_pydantic_error_url("int_parsing"),
}
]
}
@@ -970,7 +944,6 @@ def test_path_param_le_int_42():
"msg": "Input should be less than or equal to 3",
"input": "42",
"ctx": {"le": 3},
- "url": match_pydantic_error_url("less_than_equal"),
}
]
}
@@ -1012,7 +985,6 @@ def test_path_param_le_int_2_7():
"loc": ["path", "item_id"],
"msg": "Input should be a valid integer, unable to parse string as an integer",
"input": "2.7",
- "url": match_pydantic_error_url("int_parsing"),
}
]
}
@@ -1054,7 +1026,6 @@ def test_path_param_ge_int_2():
"msg": "Input should be greater than or equal to 3",
"input": "2",
"ctx": {"ge": 3},
- "url": match_pydantic_error_url("greater_than_equal"),
}
]
}
@@ -1084,7 +1055,6 @@ def test_path_param_ge_int_2_7():
"loc": ["path", "item_id"],
"msg": "Input should be a valid integer, unable to parse string as an integer",
"input": "2.7",
- "url": match_pydantic_error_url("int_parsing"),
}
]
}
@@ -1120,7 +1090,6 @@ def test_path_param_lt_gt_int_4():
"msg": "Input should be less than 3",
"input": "4",
"ctx": {"lt": 3},
- "url": match_pydantic_error_url("less_than"),
}
]
}
@@ -1151,7 +1120,6 @@ def test_path_param_lt_gt_int_0():
"msg": "Input should be greater than 1",
"input": "0",
"ctx": {"gt": 1},
- "url": match_pydantic_error_url("greater_than"),
}
]
}
@@ -1181,7 +1149,6 @@ def test_path_param_lt_gt_int_2_7():
"loc": ["path", "item_id"],
"msg": "Input should be a valid integer, unable to parse string as an integer",
"input": "2.7",
- "url": match_pydantic_error_url("int_parsing"),
}
]
}
@@ -1229,7 +1196,6 @@ def test_path_param_le_ge_int_4():
"msg": "Input should be less than or equal to 3",
"input": "4",
"ctx": {"le": 3},
- "url": match_pydantic_error_url("less_than_equal"),
}
]
}
@@ -1259,7 +1225,6 @@ def test_path_param_le_ge_int_2_7():
"loc": ["path", "item_id"],
"msg": "Input should be a valid integer, unable to parse string as an integer",
"input": "2.7",
- "url": match_pydantic_error_url("int_parsing"),
}
]
}
diff --git a/tests/test_query.py b/tests/test_query.py
index 5bb9995d6c..57f551d2ab 100644
--- a/tests/test_query.py
+++ b/tests/test_query.py
@@ -1,6 +1,5 @@
from dirty_equals import IsDict
from fastapi.testclient import TestClient
-from fastapi.utils import match_pydantic_error_url
from .main import app
@@ -18,7 +17,6 @@ def test_query():
"loc": ["query", "query"],
"msg": "Field required",
"input": None,
- "url": match_pydantic_error_url("missing"),
}
]
}
@@ -53,7 +51,6 @@ def test_query_not_declared_baz():
"loc": ["query", "query"],
"msg": "Field required",
"input": None,
- "url": match_pydantic_error_url("missing"),
}
]
}
@@ -100,7 +97,6 @@ def test_query_int():
"loc": ["query", "query"],
"msg": "Field required",
"input": None,
- "url": match_pydantic_error_url("missing"),
}
]
}
@@ -135,7 +131,6 @@ def test_query_int_query_42_5():
"loc": ["query", "query"],
"msg": "Input should be a valid integer, unable to parse string as an integer",
"input": "42.5",
- "url": match_pydantic_error_url("int_parsing"),
}
]
}
@@ -164,7 +159,6 @@ def test_query_int_query_baz():
"loc": ["query", "query"],
"msg": "Input should be a valid integer, unable to parse string as an integer",
"input": "baz",
- "url": match_pydantic_error_url("int_parsing"),
}
]
}
@@ -193,7 +187,6 @@ def test_query_int_not_declared_baz():
"loc": ["query", "query"],
"msg": "Field required",
"input": None,
- "url": match_pydantic_error_url("missing"),
}
]
}
@@ -234,7 +227,6 @@ def test_query_int_optional_query_foo():
"loc": ["query", "query"],
"msg": "Input should be a valid integer, unable to parse string as an integer",
"input": "foo",
- "url": match_pydantic_error_url("int_parsing"),
}
]
}
@@ -275,7 +267,6 @@ def test_query_int_default_query_foo():
"loc": ["query", "query"],
"msg": "Input should be a valid integer, unable to parse string as an integer",
"input": "foo",
- "url": match_pydantic_error_url("int_parsing"),
}
]
}
@@ -316,7 +307,6 @@ def test_query_param_required():
"loc": ["query", "query"],
"msg": "Field required",
"input": None,
- "url": match_pydantic_error_url("missing"),
}
]
}
@@ -351,7 +341,6 @@ def test_query_param_required_int():
"loc": ["query", "query"],
"msg": "Field required",
"input": None,
- "url": match_pydantic_error_url("missing"),
}
]
}
@@ -386,7 +375,6 @@ def test_query_param_required_int_query_foo():
"loc": ["query", "query"],
"msg": "Input should be a valid integer, unable to parse string as an integer",
"input": "foo",
- "url": match_pydantic_error_url("int_parsing"),
}
]
}
@@ -408,3 +396,26 @@ def test_query_frozenset_query_1_query_1_query_2():
response = client.get("/query/frozenset/?query=1&query=1&query=2")
assert response.status_code == 200
assert response.json() == "1,2"
+
+
+def test_query_list():
+ response = client.get("/query/list/?device_ids=1&device_ids=2")
+ assert response.status_code == 200
+ assert response.json() == [1, 2]
+
+
+def test_query_list_empty():
+ response = client.get("/query/list/")
+ assert response.status_code == 422
+
+
+def test_query_list_default():
+ response = client.get("/query/list-default/?device_ids=1&device_ids=2")
+ assert response.status_code == 200
+ assert response.json() == [1, 2]
+
+
+def test_query_list_default_empty():
+ response = client.get("/query/list-default/")
+ assert response.status_code == 200
+ assert response.json() == []
diff --git a/tests/test_regex_deprecated_body.py b/tests/test_regex_deprecated_body.py
index 7afddd9ae0..74654ff3ce 100644
--- a/tests/test_regex_deprecated_body.py
+++ b/tests/test_regex_deprecated_body.py
@@ -2,7 +2,6 @@ import pytest
from dirty_equals import IsDict
from fastapi import FastAPI, Form
from fastapi.testclient import TestClient
-from fastapi.utils import match_pydantic_error_url
from typing_extensions import Annotated
from .utils import needs_py310
@@ -55,7 +54,6 @@ def test_query_nonregexquery():
"msg": "String should match pattern '^fixedquery$'",
"input": "nonregexquery",
"ctx": {"pattern": "^fixedquery$"},
- "url": match_pydantic_error_url("string_pattern_mismatch"),
}
]
}
diff --git a/tests/test_regex_deprecated_params.py b/tests/test_regex_deprecated_params.py
index 7190b543cb..2ce64c6862 100644
--- a/tests/test_regex_deprecated_params.py
+++ b/tests/test_regex_deprecated_params.py
@@ -2,7 +2,6 @@ import pytest
from dirty_equals import IsDict
from fastapi import FastAPI, Query
from fastapi.testclient import TestClient
-from fastapi.utils import match_pydantic_error_url
from typing_extensions import Annotated
from .utils import needs_py310
@@ -55,7 +54,6 @@ def test_query_params_str_validations_item_query_nonregexquery():
"msg": "String should match pattern '^fixedquery$'",
"input": "nonregexquery",
"ctx": {"pattern": "^fixedquery$"},
- "url": match_pydantic_error_url("string_pattern_mismatch"),
}
]
}
diff --git a/tests/test_security_oauth2.py b/tests/test_security_oauth2.py
index e98f80ebfb..7d914d0345 100644
--- a/tests/test_security_oauth2.py
+++ b/tests/test_security_oauth2.py
@@ -2,7 +2,6 @@ from dirty_equals import IsDict
from fastapi import Depends, FastAPI, Security
from fastapi.security import OAuth2, OAuth2PasswordRequestFormStrict
from fastapi.testclient import TestClient
-from fastapi.utils import match_pydantic_error_url
from pydantic import BaseModel
app = FastAPI()
@@ -71,21 +70,18 @@ def test_strict_login_no_data():
"loc": ["body", "grant_type"],
"msg": "Field required",
"input": None,
- "url": match_pydantic_error_url("missing"),
},
{
"type": "missing",
"loc": ["body", "username"],
"msg": "Field required",
"input": None,
- "url": match_pydantic_error_url("missing"),
},
{
"type": "missing",
"loc": ["body", "password"],
"msg": "Field required",
"input": None,
- "url": match_pydantic_error_url("missing"),
},
]
}
@@ -124,7 +120,6 @@ def test_strict_login_no_grant_type():
"loc": ["body", "grant_type"],
"msg": "Field required",
"input": None,
- "url": match_pydantic_error_url("missing"),
}
]
}
@@ -157,7 +152,6 @@ def test_strict_login_incorrect_grant_type():
"msg": "String should match pattern 'password'",
"input": "incorrect",
"ctx": {"pattern": "password"},
- "url": match_pydantic_error_url("string_pattern_mismatch"),
}
]
}
diff --git a/tests/test_security_oauth2_optional.py b/tests/test_security_oauth2_optional.py
index d06c01bba0..0da3b911e8 100644
--- a/tests/test_security_oauth2_optional.py
+++ b/tests/test_security_oauth2_optional.py
@@ -4,7 +4,6 @@ from dirty_equals import IsDict
from fastapi import Depends, FastAPI, Security
from fastapi.security import OAuth2, OAuth2PasswordRequestFormStrict
from fastapi.testclient import TestClient
-from fastapi.utils import match_pydantic_error_url
from pydantic import BaseModel
app = FastAPI()
@@ -75,21 +74,18 @@ def test_strict_login_no_data():
"loc": ["body", "grant_type"],
"msg": "Field required",
"input": None,
- "url": match_pydantic_error_url("missing"),
},
{
"type": "missing",
"loc": ["body", "username"],
"msg": "Field required",
"input": None,
- "url": match_pydantic_error_url("missing"),
},
{
"type": "missing",
"loc": ["body", "password"],
"msg": "Field required",
"input": None,
- "url": match_pydantic_error_url("missing"),
},
]
}
@@ -128,7 +124,6 @@ def test_strict_login_no_grant_type():
"loc": ["body", "grant_type"],
"msg": "Field required",
"input": None,
- "url": match_pydantic_error_url("missing"),
}
]
}
@@ -161,7 +156,6 @@ def test_strict_login_incorrect_grant_type():
"msg": "String should match pattern 'password'",
"input": "incorrect",
"ctx": {"pattern": "password"},
- "url": match_pydantic_error_url("string_pattern_mismatch"),
}
]
}
diff --git a/tests/test_security_oauth2_optional_description.py b/tests/test_security_oauth2_optional_description.py
index 9287e4366e..85a9f9b391 100644
--- a/tests/test_security_oauth2_optional_description.py
+++ b/tests/test_security_oauth2_optional_description.py
@@ -4,7 +4,6 @@ from dirty_equals import IsDict
from fastapi import Depends, FastAPI, Security
from fastapi.security import OAuth2, OAuth2PasswordRequestFormStrict
from fastapi.testclient import TestClient
-from fastapi.utils import match_pydantic_error_url
from pydantic import BaseModel
app = FastAPI()
@@ -76,21 +75,18 @@ def test_strict_login_None():
"loc": ["body", "grant_type"],
"msg": "Field required",
"input": None,
- "url": match_pydantic_error_url("missing"),
},
{
"type": "missing",
"loc": ["body", "username"],
"msg": "Field required",
"input": None,
- "url": match_pydantic_error_url("missing"),
},
{
"type": "missing",
"loc": ["body", "password"],
"msg": "Field required",
"input": None,
- "url": match_pydantic_error_url("missing"),
},
]
}
@@ -129,7 +125,6 @@ def test_strict_login_no_grant_type():
"loc": ["body", "grant_type"],
"msg": "Field required",
"input": None,
- "url": match_pydantic_error_url("missing"),
}
]
}
@@ -162,7 +157,6 @@ def test_strict_login_incorrect_grant_type():
"msg": "String should match pattern 'password'",
"input": "incorrect",
"ctx": {"pattern": "password"},
- "url": match_pydantic_error_url("string_pattern_mismatch"),
}
]
}
diff --git a/tests/test_tutorial/test_bigger_applications/test_main.py b/tests/test_tutorial/test_bigger_applications/test_main.py
index 526e265a61..35fdfa4a66 100644
--- a/tests/test_tutorial/test_bigger_applications/test_main.py
+++ b/tests/test_tutorial/test_bigger_applications/test_main.py
@@ -1,7 +1,6 @@
import pytest
from dirty_equals import IsDict
from fastapi.testclient import TestClient
-from fastapi.utils import match_pydantic_error_url
@pytest.fixture(name="client")
@@ -29,7 +28,6 @@ def test_users_with_no_token(client: TestClient):
"loc": ["query", "token"],
"msg": "Field required",
"input": None,
- "url": match_pydantic_error_url("missing"),
}
]
}
@@ -64,7 +62,6 @@ def test_users_foo_with_no_token(client: TestClient):
"loc": ["query", "token"],
"msg": "Field required",
"input": None,
- "url": match_pydantic_error_url("missing"),
}
]
}
@@ -99,7 +96,6 @@ def test_users_me_with_no_token(client: TestClient):
"loc": ["query", "token"],
"msg": "Field required",
"input": None,
- "url": match_pydantic_error_url("missing"),
}
]
}
@@ -145,7 +141,6 @@ def test_items_with_no_token_jessica(client: TestClient):
"loc": ["query", "token"],
"msg": "Field required",
"input": None,
- "url": match_pydantic_error_url("missing"),
}
]
}
@@ -192,7 +187,6 @@ def test_items_plumbus_with_no_token(client: TestClient):
"loc": ["query", "token"],
"msg": "Field required",
"input": None,
- "url": match_pydantic_error_url("missing"),
}
]
}
@@ -233,7 +227,6 @@ def test_items_with_missing_x_token_header(client: TestClient):
"loc": ["header", "x-token"],
"msg": "Field required",
"input": None,
- "url": match_pydantic_error_url("missing"),
}
]
}
@@ -262,7 +255,6 @@ def test_items_plumbus_with_missing_x_token_header(client: TestClient):
"loc": ["header", "x-token"],
"msg": "Field required",
"input": None,
- "url": match_pydantic_error_url("missing"),
}
]
}
@@ -297,7 +289,6 @@ def test_root_with_no_token(client: TestClient):
"loc": ["query", "token"],
"msg": "Field required",
"input": None,
- "url": match_pydantic_error_url("missing"),
}
]
}
@@ -326,14 +317,12 @@ def test_put_no_header(client: TestClient):
"loc": ["query", "token"],
"msg": "Field required",
"input": None,
- "url": match_pydantic_error_url("missing"),
},
{
"type": "missing",
"loc": ["header", "x-token"],
"msg": "Field required",
"input": None,
- "url": match_pydantic_error_url("missing"),
},
]
}
diff --git a/tests/test_tutorial/test_bigger_applications/test_main_an.py b/tests/test_tutorial/test_bigger_applications/test_main_an.py
index c0b77d4a72..4e2e3e74d7 100644
--- a/tests/test_tutorial/test_bigger_applications/test_main_an.py
+++ b/tests/test_tutorial/test_bigger_applications/test_main_an.py
@@ -1,7 +1,6 @@
import pytest
from dirty_equals import IsDict
from fastapi.testclient import TestClient
-from fastapi.utils import match_pydantic_error_url
@pytest.fixture(name="client")
@@ -29,7 +28,6 @@ def test_users_with_no_token(client: TestClient):
"loc": ["query", "token"],
"msg": "Field required",
"input": None,
- "url": match_pydantic_error_url("missing"),
}
]
}
@@ -64,7 +62,6 @@ def test_users_foo_with_no_token(client: TestClient):
"loc": ["query", "token"],
"msg": "Field required",
"input": None,
- "url": match_pydantic_error_url("missing"),
}
]
}
@@ -99,7 +96,6 @@ def test_users_me_with_no_token(client: TestClient):
"loc": ["query", "token"],
"msg": "Field required",
"input": None,
- "url": match_pydantic_error_url("missing"),
}
]
}
@@ -145,7 +141,6 @@ def test_items_with_no_token_jessica(client: TestClient):
"loc": ["query", "token"],
"msg": "Field required",
"input": None,
- "url": match_pydantic_error_url("missing"),
}
]
}
@@ -192,7 +187,6 @@ def test_items_plumbus_with_no_token(client: TestClient):
"loc": ["query", "token"],
"msg": "Field required",
"input": None,
- "url": match_pydantic_error_url("missing"),
}
]
}
@@ -233,7 +227,6 @@ def test_items_with_missing_x_token_header(client: TestClient):
"loc": ["header", "x-token"],
"msg": "Field required",
"input": None,
- "url": match_pydantic_error_url("missing"),
}
]
}
@@ -262,7 +255,6 @@ def test_items_plumbus_with_missing_x_token_header(client: TestClient):
"loc": ["header", "x-token"],
"msg": "Field required",
"input": None,
- "url": match_pydantic_error_url("missing"),
}
]
}
@@ -297,7 +289,6 @@ def test_root_with_no_token(client: TestClient):
"loc": ["query", "token"],
"msg": "Field required",
"input": None,
- "url": match_pydantic_error_url("missing"),
}
]
}
@@ -326,14 +317,12 @@ def test_put_no_header(client: TestClient):
"loc": ["query", "token"],
"msg": "Field required",
"input": None,
- "url": match_pydantic_error_url("missing"),
},
{
"type": "missing",
"loc": ["header", "x-token"],
"msg": "Field required",
"input": None,
- "url": match_pydantic_error_url("missing"),
},
]
}
diff --git a/tests/test_tutorial/test_bigger_applications/test_main_an_py39.py b/tests/test_tutorial/test_bigger_applications/test_main_an_py39.py
index 948331b5dd..8c9e976df2 100644
--- a/tests/test_tutorial/test_bigger_applications/test_main_an_py39.py
+++ b/tests/test_tutorial/test_bigger_applications/test_main_an_py39.py
@@ -1,7 +1,6 @@
import pytest
from dirty_equals import IsDict
from fastapi.testclient import TestClient
-from fastapi.utils import match_pydantic_error_url
from ...utils import needs_py39
@@ -33,7 +32,6 @@ def test_users_with_no_token(client: TestClient):
"loc": ["query", "token"],
"msg": "Field required",
"input": None,
- "url": match_pydantic_error_url("missing"),
}
]
}
@@ -70,7 +68,6 @@ def test_users_foo_with_no_token(client: TestClient):
"loc": ["query", "token"],
"msg": "Field required",
"input": None,
- "url": match_pydantic_error_url("missing"),
}
]
}
@@ -107,7 +104,6 @@ def test_users_me_with_no_token(client: TestClient):
"loc": ["query", "token"],
"msg": "Field required",
"input": None,
- "url": match_pydantic_error_url("missing"),
}
]
}
@@ -156,7 +152,6 @@ def test_items_with_no_token_jessica(client: TestClient):
"loc": ["query", "token"],
"msg": "Field required",
"input": None,
- "url": match_pydantic_error_url("missing"),
}
]
}
@@ -206,7 +201,6 @@ def test_items_plumbus_with_no_token(client: TestClient):
"loc": ["query", "token"],
"msg": "Field required",
"input": None,
- "url": match_pydantic_error_url("missing"),
}
]
}
@@ -250,7 +244,6 @@ def test_items_with_missing_x_token_header(client: TestClient):
"loc": ["header", "x-token"],
"msg": "Field required",
"input": None,
- "url": match_pydantic_error_url("missing"),
}
]
}
@@ -280,7 +273,6 @@ def test_items_plumbus_with_missing_x_token_header(client: TestClient):
"loc": ["header", "x-token"],
"msg": "Field required",
"input": None,
- "url": match_pydantic_error_url("missing"),
}
]
}
@@ -317,7 +309,6 @@ def test_root_with_no_token(client: TestClient):
"loc": ["query", "token"],
"msg": "Field required",
"input": None,
- "url": match_pydantic_error_url("missing"),
}
]
}
@@ -347,14 +338,12 @@ def test_put_no_header(client: TestClient):
"loc": ["query", "token"],
"msg": "Field required",
"input": None,
- "url": match_pydantic_error_url("missing"),
},
{
"type": "missing",
"loc": ["header", "x-token"],
"msg": "Field required",
"input": None,
- "url": match_pydantic_error_url("missing"),
},
]
}
diff --git a/tests/test_tutorial/test_body/test_tutorial001.py b/tests/test_tutorial/test_body/test_tutorial001.py
index 2476b773f4..0d55d73ebe 100644
--- a/tests/test_tutorial/test_body/test_tutorial001.py
+++ b/tests/test_tutorial/test_body/test_tutorial001.py
@@ -3,7 +3,6 @@ from unittest.mock import patch
import pytest
from dirty_equals import IsDict
from fastapi.testclient import TestClient
-from fastapi.utils import match_pydantic_error_url
@pytest.fixture
@@ -74,7 +73,6 @@ def test_post_with_only_name(client: TestClient):
"loc": ["body", "price"],
"msg": "Field required",
"input": {"name": "Foo"},
- "url": match_pydantic_error_url("missing"),
}
]
}
@@ -103,7 +101,6 @@ def test_post_with_only_name_price(client: TestClient):
"loc": ["body", "price"],
"msg": "Input should be a valid number, unable to parse string as a number",
"input": "twenty",
- "url": match_pydantic_error_url("float_parsing"),
}
]
}
@@ -132,14 +129,12 @@ def test_post_with_no_data(client: TestClient):
"loc": ["body", "name"],
"msg": "Field required",
"input": {},
- "url": match_pydantic_error_url("missing"),
},
{
"type": "missing",
"loc": ["body", "price"],
"msg": "Field required",
"input": {},
- "url": match_pydantic_error_url("missing"),
},
]
}
@@ -173,7 +168,6 @@ def test_post_with_none(client: TestClient):
"loc": ["body"],
"msg": "Field required",
"input": None,
- "url": match_pydantic_error_url("missing"),
}
]
}
@@ -244,7 +238,6 @@ def test_post_form_for_json(client: TestClient):
"loc": ["body"],
"msg": "Input should be a valid dictionary or object to extract fields from",
"input": "name=Foo&price=50.5",
- "url": match_pydantic_error_url("model_attributes_type"),
}
]
}
@@ -308,9 +301,6 @@ def test_wrong_headers(client: TestClient):
"loc": ["body"],
"msg": "Input should be a valid dictionary or object to extract fields from",
"input": '{"name": "Foo", "price": 50.5}',
- "url": match_pydantic_error_url(
- "model_attributes_type"
- ), # "https://errors.pydantic.dev/0.38.0/v/dict_attributes_type",
}
]
}
@@ -339,7 +329,6 @@ def test_wrong_headers(client: TestClient):
"loc": ["body"],
"msg": "Input should be a valid dictionary or object to extract fields from",
"input": '{"name": "Foo", "price": 50.5}',
- "url": match_pydantic_error_url("model_attributes_type"),
}
]
}
@@ -367,7 +356,6 @@ def test_wrong_headers(client: TestClient):
"loc": ["body"],
"msg": "Input should be a valid dictionary or object to extract fields from",
"input": '{"name": "Foo", "price": 50.5}',
- "url": match_pydantic_error_url("model_attributes_type"),
}
]
}
diff --git a/tests/test_tutorial/test_body/test_tutorial001_py310.py b/tests/test_tutorial/test_body/test_tutorial001_py310.py
index b64d860053..4b9c128063 100644
--- a/tests/test_tutorial/test_body/test_tutorial001_py310.py
+++ b/tests/test_tutorial/test_body/test_tutorial001_py310.py
@@ -3,7 +3,6 @@ from unittest.mock import patch
import pytest
from dirty_equals import IsDict
from fastapi.testclient import TestClient
-from fastapi.utils import match_pydantic_error_url
from ...utils import needs_py310
@@ -81,7 +80,6 @@ def test_post_with_only_name(client: TestClient):
"loc": ["body", "price"],
"msg": "Field required",
"input": {"name": "Foo"},
- "url": match_pydantic_error_url("missing"),
}
]
}
@@ -111,7 +109,6 @@ def test_post_with_only_name_price(client: TestClient):
"loc": ["body", "price"],
"msg": "Input should be a valid number, unable to parse string as a number",
"input": "twenty",
- "url": match_pydantic_error_url("float_parsing"),
}
]
}
@@ -141,14 +138,12 @@ def test_post_with_no_data(client: TestClient):
"loc": ["body", "name"],
"msg": "Field required",
"input": {},
- "url": match_pydantic_error_url("missing"),
},
{
"type": "missing",
"loc": ["body", "price"],
"msg": "Field required",
"input": {},
- "url": match_pydantic_error_url("missing"),
},
]
}
@@ -183,7 +178,6 @@ def test_post_with_none(client: TestClient):
"loc": ["body"],
"msg": "Field required",
"input": None,
- "url": match_pydantic_error_url("missing"),
}
]
}
@@ -256,7 +250,6 @@ def test_post_form_for_json(client: TestClient):
"loc": ["body"],
"msg": "Input should be a valid dictionary or object to extract fields from",
"input": "name=Foo&price=50.5",
- "url": match_pydantic_error_url("model_attributes_type"),
}
]
}
@@ -324,7 +317,6 @@ def test_wrong_headers(client: TestClient):
"loc": ["body"],
"msg": "Input should be a valid dictionary or object to extract fields from",
"input": '{"name": "Foo", "price": 50.5}',
- "url": match_pydantic_error_url("model_attributes_type"),
}
]
}
@@ -353,7 +345,6 @@ def test_wrong_headers(client: TestClient):
"loc": ["body"],
"msg": "Input should be a valid dictionary or object to extract fields from",
"input": '{"name": "Foo", "price": 50.5}',
- "url": match_pydantic_error_url("model_attributes_type"),
}
]
}
@@ -381,7 +372,6 @@ def test_wrong_headers(client: TestClient):
"loc": ["body"],
"msg": "Input should be a valid dictionary or object to extract fields from",
"input": '{"name": "Foo", "price": 50.5}',
- "url": match_pydantic_error_url("model_attributes_type"),
}
]
}
diff --git a/tests/test_tutorial/test_body_fields/test_tutorial001.py b/tests/test_tutorial/test_body_fields/test_tutorial001.py
index 1ff2d95760..fd6139eb9b 100644
--- a/tests/test_tutorial/test_body_fields/test_tutorial001.py
+++ b/tests/test_tutorial/test_body_fields/test_tutorial001.py
@@ -1,7 +1,6 @@
import pytest
from dirty_equals import IsDict
from fastapi.testclient import TestClient
-from fastapi.utils import match_pydantic_error_url
@pytest.fixture(name="client")
@@ -57,7 +56,6 @@ def test_invalid_price(client: TestClient):
"msg": "Input should be greater than 0",
"input": -3.0,
"ctx": {"gt": 0.0},
- "url": match_pydantic_error_url("greater_than"),
}
]
}
diff --git a/tests/test_tutorial/test_body_fields/test_tutorial001_an.py b/tests/test_tutorial/test_body_fields/test_tutorial001_an.py
index 907d6842a4..72c18c1f73 100644
--- a/tests/test_tutorial/test_body_fields/test_tutorial001_an.py
+++ b/tests/test_tutorial/test_body_fields/test_tutorial001_an.py
@@ -1,7 +1,6 @@
import pytest
from dirty_equals import IsDict
from fastapi.testclient import TestClient
-from fastapi.utils import match_pydantic_error_url
@pytest.fixture(name="client")
@@ -57,7 +56,6 @@ def test_invalid_price(client: TestClient):
"msg": "Input should be greater than 0",
"input": -3.0,
"ctx": {"gt": 0.0},
- "url": match_pydantic_error_url("greater_than"),
}
]
}
diff --git a/tests/test_tutorial/test_body_fields/test_tutorial001_an_py310.py b/tests/test_tutorial/test_body_fields/test_tutorial001_an_py310.py
index 431d2d1819..1bc62868fd 100644
--- a/tests/test_tutorial/test_body_fields/test_tutorial001_an_py310.py
+++ b/tests/test_tutorial/test_body_fields/test_tutorial001_an_py310.py
@@ -1,7 +1,6 @@
import pytest
from dirty_equals import IsDict
from fastapi.testclient import TestClient
-from fastapi.utils import match_pydantic_error_url
from ...utils import needs_py310
@@ -62,7 +61,6 @@ def test_invalid_price(client: TestClient):
"msg": "Input should be greater than 0",
"input": -3.0,
"ctx": {"gt": 0.0},
- "url": match_pydantic_error_url("greater_than"),
}
]
}
diff --git a/tests/test_tutorial/test_body_fields/test_tutorial001_an_py39.py b/tests/test_tutorial/test_body_fields/test_tutorial001_an_py39.py
index 8cef6c154c..3c5557a1b2 100644
--- a/tests/test_tutorial/test_body_fields/test_tutorial001_an_py39.py
+++ b/tests/test_tutorial/test_body_fields/test_tutorial001_an_py39.py
@@ -1,7 +1,6 @@
import pytest
from dirty_equals import IsDict
from fastapi.testclient import TestClient
-from fastapi.utils import match_pydantic_error_url
from ...utils import needs_py39
@@ -62,7 +61,6 @@ def test_invalid_price(client: TestClient):
"msg": "Input should be greater than 0",
"input": -3.0,
"ctx": {"gt": 0.0},
- "url": match_pydantic_error_url("greater_than"),
}
]
}
diff --git a/tests/test_tutorial/test_body_fields/test_tutorial001_py310.py b/tests/test_tutorial/test_body_fields/test_tutorial001_py310.py
index b48cd9ec26..8c1386aa67 100644
--- a/tests/test_tutorial/test_body_fields/test_tutorial001_py310.py
+++ b/tests/test_tutorial/test_body_fields/test_tutorial001_py310.py
@@ -1,7 +1,6 @@
import pytest
from dirty_equals import IsDict
from fastapi.testclient import TestClient
-from fastapi.utils import match_pydantic_error_url
from ...utils import needs_py310
@@ -62,7 +61,6 @@ def test_invalid_price(client: TestClient):
"msg": "Input should be greater than 0",
"input": -3.0,
"ctx": {"gt": 0.0},
- "url": match_pydantic_error_url("greater_than"),
}
]
}
diff --git a/tests/test_tutorial/test_body_multiple_params/test_tutorial001.py b/tests/test_tutorial/test_body_multiple_params/test_tutorial001.py
index e5dc13b268..6275ebe95f 100644
--- a/tests/test_tutorial/test_body_multiple_params/test_tutorial001.py
+++ b/tests/test_tutorial/test_body_multiple_params/test_tutorial001.py
@@ -1,7 +1,6 @@
import pytest
from dirty_equals import IsDict
from fastapi.testclient import TestClient
-from fastapi.utils import match_pydantic_error_url
@pytest.fixture(name="client")
@@ -50,7 +49,6 @@ def test_post_id_foo(client: TestClient):
"loc": ["path", "item_id"],
"msg": "Input should be a valid integer, unable to parse string as an integer",
"input": "foo",
- "url": match_pydantic_error_url("int_parsing"),
}
]
}
diff --git a/tests/test_tutorial/test_body_multiple_params/test_tutorial001_an.py b/tests/test_tutorial/test_body_multiple_params/test_tutorial001_an.py
index 51e8e3a4e9..5cd3e2c4aa 100644
--- a/tests/test_tutorial/test_body_multiple_params/test_tutorial001_an.py
+++ b/tests/test_tutorial/test_body_multiple_params/test_tutorial001_an.py
@@ -1,7 +1,6 @@
import pytest
from dirty_equals import IsDict
from fastapi.testclient import TestClient
-from fastapi.utils import match_pydantic_error_url
@pytest.fixture(name="client")
@@ -50,7 +49,6 @@ def test_post_id_foo(client: TestClient):
"loc": ["path", "item_id"],
"msg": "Input should be a valid integer, unable to parse string as an integer",
"input": "foo",
- "url": match_pydantic_error_url("int_parsing"),
}
]
}
diff --git a/tests/test_tutorial/test_body_multiple_params/test_tutorial001_an_py310.py b/tests/test_tutorial/test_body_multiple_params/test_tutorial001_an_py310.py
index 8ac1f72618..0173ab21b3 100644
--- a/tests/test_tutorial/test_body_multiple_params/test_tutorial001_an_py310.py
+++ b/tests/test_tutorial/test_body_multiple_params/test_tutorial001_an_py310.py
@@ -1,7 +1,6 @@
import pytest
from dirty_equals import IsDict
from fastapi.testclient import TestClient
-from fastapi.utils import match_pydantic_error_url
from ...utils import needs_py310
@@ -56,7 +55,6 @@ def test_post_id_foo(client: TestClient):
"loc": ["path", "item_id"],
"msg": "Input should be a valid integer, unable to parse string as an integer",
"input": "foo",
- "url": match_pydantic_error_url("int_parsing"),
}
]
}
diff --git a/tests/test_tutorial/test_body_multiple_params/test_tutorial001_an_py39.py b/tests/test_tutorial/test_body_multiple_params/test_tutorial001_an_py39.py
index 7ada42c528..cda19918ac 100644
--- a/tests/test_tutorial/test_body_multiple_params/test_tutorial001_an_py39.py
+++ b/tests/test_tutorial/test_body_multiple_params/test_tutorial001_an_py39.py
@@ -1,7 +1,6 @@
import pytest
from dirty_equals import IsDict
from fastapi.testclient import TestClient
-from fastapi.utils import match_pydantic_error_url
from ...utils import needs_py39
@@ -56,7 +55,6 @@ def test_post_id_foo(client: TestClient):
"loc": ["path", "item_id"],
"msg": "Input should be a valid integer, unable to parse string as an integer",
"input": "foo",
- "url": match_pydantic_error_url("int_parsing"),
}
]
}
diff --git a/tests/test_tutorial/test_body_multiple_params/test_tutorial001_py310.py b/tests/test_tutorial/test_body_multiple_params/test_tutorial001_py310.py
index 0a832eaf6f..6632919331 100644
--- a/tests/test_tutorial/test_body_multiple_params/test_tutorial001_py310.py
+++ b/tests/test_tutorial/test_body_multiple_params/test_tutorial001_py310.py
@@ -1,7 +1,6 @@
import pytest
from dirty_equals import IsDict
from fastapi.testclient import TestClient
-from fastapi.utils import match_pydantic_error_url
from ...utils import needs_py310
@@ -56,7 +55,6 @@ def test_post_id_foo(client: TestClient):
"loc": ["path", "item_id"],
"msg": "Input should be a valid integer, unable to parse string as an integer",
"input": "foo",
- "url": match_pydantic_error_url("int_parsing"),
}
]
}
diff --git a/tests/test_tutorial/test_body_multiple_params/test_tutorial003.py b/tests/test_tutorial/test_body_multiple_params/test_tutorial003.py
index 2046579a94..c26f8b89bc 100644
--- a/tests/test_tutorial/test_body_multiple_params/test_tutorial003.py
+++ b/tests/test_tutorial/test_body_multiple_params/test_tutorial003.py
@@ -1,7 +1,6 @@
import pytest
from dirty_equals import IsDict
from fastapi.testclient import TestClient
-from fastapi.utils import match_pydantic_error_url
@pytest.fixture(name="client")
@@ -46,21 +45,18 @@ def test_post_body_no_data(client: TestClient):
"loc": ["body", "item"],
"msg": "Field required",
"input": None,
- "url": match_pydantic_error_url("missing"),
},
{
"type": "missing",
"loc": ["body", "user"],
"msg": "Field required",
"input": None,
- "url": match_pydantic_error_url("missing"),
},
{
"type": "missing",
"loc": ["body", "importance"],
"msg": "Field required",
"input": None,
- "url": match_pydantic_error_url("missing"),
},
]
}
@@ -99,21 +95,18 @@ def test_post_body_empty_list(client: TestClient):
"loc": ["body", "item"],
"msg": "Field required",
"input": None,
- "url": match_pydantic_error_url("missing"),
},
{
"type": "missing",
"loc": ["body", "user"],
"msg": "Field required",
"input": None,
- "url": match_pydantic_error_url("missing"),
},
{
"type": "missing",
"loc": ["body", "importance"],
"msg": "Field required",
"input": None,
- "url": match_pydantic_error_url("missing"),
},
]
}
diff --git a/tests/test_tutorial/test_body_multiple_params/test_tutorial003_an.py b/tests/test_tutorial/test_body_multiple_params/test_tutorial003_an.py
index 1282483e07..62c7e2fad8 100644
--- a/tests/test_tutorial/test_body_multiple_params/test_tutorial003_an.py
+++ b/tests/test_tutorial/test_body_multiple_params/test_tutorial003_an.py
@@ -1,7 +1,6 @@
import pytest
from dirty_equals import IsDict
from fastapi.testclient import TestClient
-from fastapi.utils import match_pydantic_error_url
@pytest.fixture(name="client")
@@ -46,21 +45,18 @@ def test_post_body_no_data(client: TestClient):
"loc": ["body", "item"],
"msg": "Field required",
"input": None,
- "url": match_pydantic_error_url("missing"),
},
{
"type": "missing",
"loc": ["body", "user"],
"msg": "Field required",
"input": None,
- "url": match_pydantic_error_url("missing"),
},
{
"type": "missing",
"loc": ["body", "importance"],
"msg": "Field required",
"input": None,
- "url": match_pydantic_error_url("missing"),
},
]
}
@@ -99,21 +95,18 @@ def test_post_body_empty_list(client: TestClient):
"loc": ["body", "item"],
"msg": "Field required",
"input": None,
- "url": match_pydantic_error_url("missing"),
},
{
"type": "missing",
"loc": ["body", "user"],
"msg": "Field required",
"input": None,
- "url": match_pydantic_error_url("missing"),
},
{
"type": "missing",
"loc": ["body", "importance"],
"msg": "Field required",
"input": None,
- "url": match_pydantic_error_url("missing"),
},
]
}
diff --git a/tests/test_tutorial/test_body_multiple_params/test_tutorial003_an_py310.py b/tests/test_tutorial/test_body_multiple_params/test_tutorial003_an_py310.py
index 577c079d00..f46430fb5a 100644
--- a/tests/test_tutorial/test_body_multiple_params/test_tutorial003_an_py310.py
+++ b/tests/test_tutorial/test_body_multiple_params/test_tutorial003_an_py310.py
@@ -1,7 +1,6 @@
import pytest
from dirty_equals import IsDict
from fastapi.testclient import TestClient
-from fastapi.utils import match_pydantic_error_url
from ...utils import needs_py310
@@ -50,21 +49,18 @@ def test_post_body_no_data(client: TestClient):
"loc": ["body", "item"],
"msg": "Field required",
"input": None,
- "url": match_pydantic_error_url("missing"),
},
{
"type": "missing",
"loc": ["body", "user"],
"msg": "Field required",
"input": None,
- "url": match_pydantic_error_url("missing"),
},
{
"type": "missing",
"loc": ["body", "importance"],
"msg": "Field required",
"input": None,
- "url": match_pydantic_error_url("missing"),
},
]
}
@@ -104,21 +100,18 @@ def test_post_body_empty_list(client: TestClient):
"loc": ["body", "item"],
"msg": "Field required",
"input": None,
- "url": match_pydantic_error_url("missing"),
},
{
"type": "missing",
"loc": ["body", "user"],
"msg": "Field required",
"input": None,
- "url": match_pydantic_error_url("missing"),
},
{
"type": "missing",
"loc": ["body", "importance"],
"msg": "Field required",
"input": None,
- "url": match_pydantic_error_url("missing"),
},
]
}
diff --git a/tests/test_tutorial/test_body_multiple_params/test_tutorial003_an_py39.py b/tests/test_tutorial/test_body_multiple_params/test_tutorial003_an_py39.py
index 0ec04151cc..29071cddca 100644
--- a/tests/test_tutorial/test_body_multiple_params/test_tutorial003_an_py39.py
+++ b/tests/test_tutorial/test_body_multiple_params/test_tutorial003_an_py39.py
@@ -1,7 +1,6 @@
import pytest
from dirty_equals import IsDict
from fastapi.testclient import TestClient
-from fastapi.utils import match_pydantic_error_url
from ...utils import needs_py39
@@ -50,21 +49,18 @@ def test_post_body_no_data(client: TestClient):
"loc": ["body", "item"],
"msg": "Field required",
"input": None,
- "url": match_pydantic_error_url("missing"),
},
{
"type": "missing",
"loc": ["body", "user"],
"msg": "Field required",
"input": None,
- "url": match_pydantic_error_url("missing"),
},
{
"type": "missing",
"loc": ["body", "importance"],
"msg": "Field required",
"input": None,
- "url": match_pydantic_error_url("missing"),
},
]
}
@@ -104,21 +100,18 @@ def test_post_body_empty_list(client: TestClient):
"loc": ["body", "item"],
"msg": "Field required",
"input": None,
- "url": match_pydantic_error_url("missing"),
},
{
"type": "missing",
"loc": ["body", "user"],
"msg": "Field required",
"input": None,
- "url": match_pydantic_error_url("missing"),
},
{
"type": "missing",
"loc": ["body", "importance"],
"msg": "Field required",
"input": None,
- "url": match_pydantic_error_url("missing"),
},
]
}
diff --git a/tests/test_tutorial/test_body_multiple_params/test_tutorial003_py310.py b/tests/test_tutorial/test_body_multiple_params/test_tutorial003_py310.py
index 9caf5fe6cb..133afe9b5e 100644
--- a/tests/test_tutorial/test_body_multiple_params/test_tutorial003_py310.py
+++ b/tests/test_tutorial/test_body_multiple_params/test_tutorial003_py310.py
@@ -1,7 +1,6 @@
import pytest
from dirty_equals import IsDict
from fastapi.testclient import TestClient
-from fastapi.utils import match_pydantic_error_url
from ...utils import needs_py310
@@ -50,21 +49,18 @@ def test_post_body_no_data(client: TestClient):
"loc": ["body", "item"],
"msg": "Field required",
"input": None,
- "url": match_pydantic_error_url("missing"),
},
{
"type": "missing",
"loc": ["body", "user"],
"msg": "Field required",
"input": None,
- "url": match_pydantic_error_url("missing"),
},
{
"type": "missing",
"loc": ["body", "importance"],
"msg": "Field required",
"input": None,
- "url": match_pydantic_error_url("missing"),
},
]
}
@@ -104,21 +100,18 @@ def test_post_body_empty_list(client: TestClient):
"loc": ["body", "item"],
"msg": "Field required",
"input": None,
- "url": match_pydantic_error_url("missing"),
},
{
"type": "missing",
"loc": ["body", "user"],
"msg": "Field required",
"input": None,
- "url": match_pydantic_error_url("missing"),
},
{
"type": "missing",
"loc": ["body", "importance"],
"msg": "Field required",
"input": None,
- "url": match_pydantic_error_url("missing"),
},
]
}
diff --git a/tests/test_tutorial/test_body_nested_models/test_tutorial009.py b/tests/test_tutorial/test_body_nested_models/test_tutorial009.py
index f4a76be449..762073aea6 100644
--- a/tests/test_tutorial/test_body_nested_models/test_tutorial009.py
+++ b/tests/test_tutorial/test_body_nested_models/test_tutorial009.py
@@ -1,7 +1,6 @@
import pytest
from dirty_equals import IsDict
from fastapi.testclient import TestClient
-from fastapi.utils import match_pydantic_error_url
@pytest.fixture(name="client")
@@ -31,7 +30,6 @@ def test_post_invalid_body(client: TestClient):
"loc": ["body", "foo", "[key]"],
"msg": "Input should be a valid integer, unable to parse string as an integer",
"input": "foo",
- "url": match_pydantic_error_url("int_parsing"),
}
]
}
diff --git a/tests/test_tutorial/test_body_nested_models/test_tutorial009_py39.py b/tests/test_tutorial/test_body_nested_models/test_tutorial009_py39.py
index 8ab9bcac83..24623ceccb 100644
--- a/tests/test_tutorial/test_body_nested_models/test_tutorial009_py39.py
+++ b/tests/test_tutorial/test_body_nested_models/test_tutorial009_py39.py
@@ -1,7 +1,6 @@
import pytest
from dirty_equals import IsDict
from fastapi.testclient import TestClient
-from fastapi.utils import match_pydantic_error_url
from ...utils import needs_py39
@@ -35,7 +34,6 @@ def test_post_invalid_body(client: TestClient):
"loc": ["body", "foo", "[key]"],
"msg": "Input should be a valid integer, unable to parse string as an integer",
"input": "foo",
- "url": match_pydantic_error_url("int_parsing"),
}
]
}
diff --git a/tests/test_tutorial/test_custom_request_and_route/test_tutorial002.py b/tests/test_tutorial/test_custom_request_and_route/test_tutorial002.py
index ad142ec887..6f7355aaa1 100644
--- a/tests/test_tutorial/test_custom_request_and_route/test_tutorial002.py
+++ b/tests/test_tutorial/test_custom_request_and_route/test_tutorial002.py
@@ -1,6 +1,5 @@
from dirty_equals import IsDict
from fastapi.testclient import TestClient
-from fastapi.utils import match_pydantic_error_url
from docs_src.custom_request_and_route.tutorial002 import app
@@ -23,7 +22,6 @@ def test_exception_handler_body_access():
"loc": ["body"],
"msg": "Input should be a valid list",
"input": {"numbers": [1, 2, 3]},
- "url": match_pydantic_error_url("list_type"),
}
],
"body": '{"numbers": [1, 2, 3]}',
diff --git a/tests/test_tutorial/test_dataclasses/test_tutorial001.py b/tests/test_tutorial/test_dataclasses/test_tutorial001.py
index 9f1200f373..762654d29d 100644
--- a/tests/test_tutorial/test_dataclasses/test_tutorial001.py
+++ b/tests/test_tutorial/test_dataclasses/test_tutorial001.py
@@ -1,6 +1,5 @@
from dirty_equals import IsDict
from fastapi.testclient import TestClient
-from fastapi.utils import match_pydantic_error_url
from docs_src.dataclasses.tutorial001 import app
@@ -29,7 +28,6 @@ def test_post_invalid_item():
"loc": ["body", "price"],
"msg": "Input should be a valid number, unable to parse string as a number",
"input": "invalid price",
- "url": match_pydantic_error_url("float_parsing"),
}
]
}
diff --git a/tests/test_tutorial/test_dependencies/test_tutorial006.py b/tests/test_tutorial/test_dependencies/test_tutorial006.py
index 704e389a5b..5f14d9a3ba 100644
--- a/tests/test_tutorial/test_dependencies/test_tutorial006.py
+++ b/tests/test_tutorial/test_dependencies/test_tutorial006.py
@@ -1,6 +1,5 @@
from dirty_equals import IsDict
from fastapi.testclient import TestClient
-from fastapi.utils import match_pydantic_error_url
from docs_src.dependencies.tutorial006 import app
@@ -18,14 +17,12 @@ def test_get_no_headers():
"loc": ["header", "x-token"],
"msg": "Field required",
"input": None,
- "url": match_pydantic_error_url("missing"),
},
{
"type": "missing",
"loc": ["header", "x-key"],
"msg": "Field required",
"input": None,
- "url": match_pydantic_error_url("missing"),
},
]
}
diff --git a/tests/test_tutorial/test_dependencies/test_tutorial006_an.py b/tests/test_tutorial/test_dependencies/test_tutorial006_an.py
index 5034fceba5..a307ff8087 100644
--- a/tests/test_tutorial/test_dependencies/test_tutorial006_an.py
+++ b/tests/test_tutorial/test_dependencies/test_tutorial006_an.py
@@ -1,6 +1,5 @@
from dirty_equals import IsDict
from fastapi.testclient import TestClient
-from fastapi.utils import match_pydantic_error_url
from docs_src.dependencies.tutorial006_an import app
@@ -18,14 +17,12 @@ def test_get_no_headers():
"loc": ["header", "x-token"],
"msg": "Field required",
"input": None,
- "url": match_pydantic_error_url("missing"),
},
{
"type": "missing",
"loc": ["header", "x-key"],
"msg": "Field required",
"input": None,
- "url": match_pydantic_error_url("missing"),
},
]
}
diff --git a/tests/test_tutorial/test_dependencies/test_tutorial006_an_py39.py b/tests/test_tutorial/test_dependencies/test_tutorial006_an_py39.py
index 3fc22dd3c2..b41b1537ec 100644
--- a/tests/test_tutorial/test_dependencies/test_tutorial006_an_py39.py
+++ b/tests/test_tutorial/test_dependencies/test_tutorial006_an_py39.py
@@ -1,7 +1,6 @@
import pytest
from dirty_equals import IsDict
from fastapi.testclient import TestClient
-from fastapi.utils import match_pydantic_error_url
from ...utils import needs_py39
@@ -26,14 +25,12 @@ def test_get_no_headers(client: TestClient):
"loc": ["header", "x-token"],
"msg": "Field required",
"input": None,
- "url": match_pydantic_error_url("missing"),
},
{
"type": "missing",
"loc": ["header", "x-key"],
"msg": "Field required",
"input": None,
- "url": match_pydantic_error_url("missing"),
},
]
}
diff --git a/tests/test_tutorial/test_dependencies/test_tutorial012.py b/tests/test_tutorial/test_dependencies/test_tutorial012.py
index 753e62e43e..6b53c83bb5 100644
--- a/tests/test_tutorial/test_dependencies/test_tutorial012.py
+++ b/tests/test_tutorial/test_dependencies/test_tutorial012.py
@@ -1,6 +1,5 @@
from dirty_equals import IsDict
from fastapi.testclient import TestClient
-from fastapi.utils import match_pydantic_error_url
from docs_src.dependencies.tutorial012 import app
@@ -18,14 +17,12 @@ def test_get_no_headers_items():
"loc": ["header", "x-token"],
"msg": "Field required",
"input": None,
- "url": match_pydantic_error_url("missing"),
},
{
"type": "missing",
"loc": ["header", "x-key"],
"msg": "Field required",
"input": None,
- "url": match_pydantic_error_url("missing"),
},
]
}
@@ -59,14 +56,12 @@ def test_get_no_headers_users():
"loc": ["header", "x-token"],
"msg": "Field required",
"input": None,
- "url": match_pydantic_error_url("missing"),
},
{
"type": "missing",
"loc": ["header", "x-key"],
"msg": "Field required",
"input": None,
- "url": match_pydantic_error_url("missing"),
},
]
}
diff --git a/tests/test_tutorial/test_dependencies/test_tutorial012_an.py b/tests/test_tutorial/test_dependencies/test_tutorial012_an.py
index 4157d46128..75adb69fc7 100644
--- a/tests/test_tutorial/test_dependencies/test_tutorial012_an.py
+++ b/tests/test_tutorial/test_dependencies/test_tutorial012_an.py
@@ -1,6 +1,5 @@
from dirty_equals import IsDict
from fastapi.testclient import TestClient
-from fastapi.utils import match_pydantic_error_url
from docs_src.dependencies.tutorial012_an import app
@@ -18,14 +17,12 @@ def test_get_no_headers_items():
"loc": ["header", "x-token"],
"msg": "Field required",
"input": None,
- "url": match_pydantic_error_url("missing"),
},
{
"type": "missing",
"loc": ["header", "x-key"],
"msg": "Field required",
"input": None,
- "url": match_pydantic_error_url("missing"),
},
]
}
@@ -59,14 +56,12 @@ def test_get_no_headers_users():
"loc": ["header", "x-token"],
"msg": "Field required",
"input": None,
- "url": match_pydantic_error_url("missing"),
},
{
"type": "missing",
"loc": ["header", "x-key"],
"msg": "Field required",
"input": None,
- "url": match_pydantic_error_url("missing"),
},
]
}
diff --git a/tests/test_tutorial/test_dependencies/test_tutorial012_an_py39.py b/tests/test_tutorial/test_dependencies/test_tutorial012_an_py39.py
index 9e46758cbd..e0a3d1ec27 100644
--- a/tests/test_tutorial/test_dependencies/test_tutorial012_an_py39.py
+++ b/tests/test_tutorial/test_dependencies/test_tutorial012_an_py39.py
@@ -1,7 +1,6 @@
import pytest
from dirty_equals import IsDict
from fastapi.testclient import TestClient
-from fastapi.utils import match_pydantic_error_url
from ...utils import needs_py39
@@ -26,14 +25,12 @@ def test_get_no_headers_items(client: TestClient):
"loc": ["header", "x-token"],
"msg": "Field required",
"input": None,
- "url": match_pydantic_error_url("missing"),
},
{
"type": "missing",
"loc": ["header", "x-key"],
"msg": "Field required",
"input": None,
- "url": match_pydantic_error_url("missing"),
},
]
}
@@ -68,14 +65,12 @@ def test_get_no_headers_users(client: TestClient):
"loc": ["header", "x-token"],
"msg": "Field required",
"input": None,
- "url": match_pydantic_error_url("missing"),
},
{
"type": "missing",
"loc": ["header", "x-key"],
"msg": "Field required",
"input": None,
- "url": match_pydantic_error_url("missing"),
},
]
}
diff --git a/tests/test_tutorial/test_handling_errors/test_tutorial005.py b/tests/test_tutorial/test_handling_errors/test_tutorial005.py
index 494c317cab..581b2e4c75 100644
--- a/tests/test_tutorial/test_handling_errors/test_tutorial005.py
+++ b/tests/test_tutorial/test_handling_errors/test_tutorial005.py
@@ -1,6 +1,5 @@
from dirty_equals import IsDict
from fastapi.testclient import TestClient
-from fastapi.utils import match_pydantic_error_url
from docs_src.handling_errors.tutorial005 import app
@@ -18,7 +17,6 @@ def test_post_validation_error():
"loc": ["body", "size"],
"msg": "Input should be a valid integer, unable to parse string as an integer",
"input": "XL",
- "url": match_pydantic_error_url("int_parsing"),
}
],
"body": {"title": "towel", "size": "XL"},
diff --git a/tests/test_tutorial/test_handling_errors/test_tutorial006.py b/tests/test_tutorial/test_handling_errors/test_tutorial006.py
index cc2b496a83..7d2f553aac 100644
--- a/tests/test_tutorial/test_handling_errors/test_tutorial006.py
+++ b/tests/test_tutorial/test_handling_errors/test_tutorial006.py
@@ -1,6 +1,5 @@
from dirty_equals import IsDict
from fastapi.testclient import TestClient
-from fastapi.utils import match_pydantic_error_url
from docs_src.handling_errors.tutorial006 import app
@@ -18,7 +17,6 @@ def test_get_validation_error():
"loc": ["path", "item_id"],
"msg": "Input should be a valid integer, unable to parse string as an integer",
"input": "foo",
- "url": match_pydantic_error_url("int_parsing"),
}
]
}
diff --git a/tests/test_tutorial/test_path_operation_advanced_configurations/test_tutorial007.py b/tests/test_tutorial/test_path_operation_advanced_configurations/test_tutorial007.py
index 2d28022691..8240b60a62 100644
--- a/tests/test_tutorial/test_path_operation_advanced_configurations/test_tutorial007.py
+++ b/tests/test_tutorial/test_path_operation_advanced_configurations/test_tutorial007.py
@@ -1,6 +1,5 @@
import pytest
from fastapi.testclient import TestClient
-from fastapi.utils import match_pydantic_error_url
from ...utils import needs_pydanticv2
@@ -64,7 +63,6 @@ def test_post_invalid(client: TestClient):
"loc": ["tags", 3],
"msg": "Input should be a valid string",
"input": {"sneaky": "object"},
- "url": match_pydantic_error_url("string_type"),
}
]
}
diff --git a/tests/test_tutorial/test_query_params/test_tutorial005.py b/tests/test_tutorial/test_query_params/test_tutorial005.py
index 9215863576..05ae85b451 100644
--- a/tests/test_tutorial/test_query_params/test_tutorial005.py
+++ b/tests/test_tutorial/test_query_params/test_tutorial005.py
@@ -1,6 +1,5 @@
from dirty_equals import IsDict
from fastapi.testclient import TestClient
-from fastapi.utils import match_pydantic_error_url
from docs_src.query_params.tutorial005 import app
@@ -24,7 +23,6 @@ def test_foo_no_needy():
"loc": ["query", "needy"],
"msg": "Field required",
"input": None,
- "url": match_pydantic_error_url("missing"),
}
]
}
diff --git a/tests/test_tutorial/test_query_params/test_tutorial006.py b/tests/test_tutorial/test_query_params/test_tutorial006.py
index e07803d6c9..dbd63da160 100644
--- a/tests/test_tutorial/test_query_params/test_tutorial006.py
+++ b/tests/test_tutorial/test_query_params/test_tutorial006.py
@@ -1,7 +1,6 @@
import pytest
from dirty_equals import IsDict
from fastapi.testclient import TestClient
-from fastapi.utils import match_pydantic_error_url
@pytest.fixture(name="client")
@@ -34,21 +33,18 @@ def test_foo_no_needy(client: TestClient):
"loc": ["query", "needy"],
"msg": "Field required",
"input": None,
- "url": match_pydantic_error_url("missing"),
},
{
"type": "int_parsing",
"loc": ["query", "skip"],
"msg": "Input should be a valid integer, unable to parse string as an integer",
"input": "a",
- "url": match_pydantic_error_url("int_parsing"),
},
{
"type": "int_parsing",
"loc": ["query", "limit"],
"msg": "Input should be a valid integer, unable to parse string as an integer",
"input": "b",
- "url": match_pydantic_error_url("int_parsing"),
},
]
}
diff --git a/tests/test_tutorial/test_query_params/test_tutorial006_py310.py b/tests/test_tutorial/test_query_params/test_tutorial006_py310.py
index 6c4c0b4dc8..5055e38052 100644
--- a/tests/test_tutorial/test_query_params/test_tutorial006_py310.py
+++ b/tests/test_tutorial/test_query_params/test_tutorial006_py310.py
@@ -1,7 +1,6 @@
import pytest
from dirty_equals import IsDict
from fastapi.testclient import TestClient
-from fastapi.utils import match_pydantic_error_url
from ...utils import needs_py310
@@ -38,21 +37,18 @@ def test_foo_no_needy(client: TestClient):
"loc": ["query", "needy"],
"msg": "Field required",
"input": None,
- "url": match_pydantic_error_url("missing"),
},
{
"type": "int_parsing",
"loc": ["query", "skip"],
"msg": "Input should be a valid integer, unable to parse string as an integer",
"input": "a",
- "url": match_pydantic_error_url("int_parsing"),
},
{
"type": "int_parsing",
"loc": ["query", "limit"],
"msg": "Input should be a valid integer, unable to parse string as an integer",
"input": "b",
- "url": match_pydantic_error_url("int_parsing"),
},
]
}
diff --git a/tests/test_tutorial/test_query_params_str_validations/test_tutorial010.py b/tests/test_tutorial/test_query_params_str_validations/test_tutorial010.py
index 287c2e8f8e..945cee3d26 100644
--- a/tests/test_tutorial/test_query_params_str_validations/test_tutorial010.py
+++ b/tests/test_tutorial/test_query_params_str_validations/test_tutorial010.py
@@ -1,7 +1,6 @@
import pytest
from dirty_equals import IsDict
from fastapi.testclient import TestClient
-from fastapi.utils import match_pydantic_error_url
@pytest.fixture(name="client")
@@ -45,7 +44,6 @@ def test_query_params_str_validations_item_query_nonregexquery(client: TestClien
"msg": "String should match pattern '^fixedquery$'",
"input": "nonregexquery",
"ctx": {"pattern": "^fixedquery$"},
- "url": match_pydantic_error_url("string_pattern_mismatch"),
}
]
}
diff --git a/tests/test_tutorial/test_query_params_str_validations/test_tutorial010_an.py b/tests/test_tutorial/test_query_params_str_validations/test_tutorial010_an.py
index 5b0515070a..23951a9aa3 100644
--- a/tests/test_tutorial/test_query_params_str_validations/test_tutorial010_an.py
+++ b/tests/test_tutorial/test_query_params_str_validations/test_tutorial010_an.py
@@ -1,7 +1,6 @@
import pytest
from dirty_equals import IsDict
from fastapi.testclient import TestClient
-from fastapi.utils import match_pydantic_error_url
@pytest.fixture(name="client")
@@ -45,7 +44,6 @@ def test_query_params_str_validations_item_query_nonregexquery(client: TestClien
"msg": "String should match pattern '^fixedquery$'",
"input": "nonregexquery",
"ctx": {"pattern": "^fixedquery$"},
- "url": match_pydantic_error_url("string_pattern_mismatch"),
}
]
}
diff --git a/tests/test_tutorial/test_query_params_str_validations/test_tutorial010_an_py310.py b/tests/test_tutorial/test_query_params_str_validations/test_tutorial010_an_py310.py
index d22b1ce204..2968af563c 100644
--- a/tests/test_tutorial/test_query_params_str_validations/test_tutorial010_an_py310.py
+++ b/tests/test_tutorial/test_query_params_str_validations/test_tutorial010_an_py310.py
@@ -1,7 +1,6 @@
import pytest
from dirty_equals import IsDict
from fastapi.testclient import TestClient
-from fastapi.utils import match_pydantic_error_url
from ...utils import needs_py310
@@ -51,7 +50,6 @@ def test_query_params_str_validations_item_query_nonregexquery(client: TestClien
"msg": "String should match pattern '^fixedquery$'",
"input": "nonregexquery",
"ctx": {"pattern": "^fixedquery$"},
- "url": match_pydantic_error_url("string_pattern_mismatch"),
}
]
}
diff --git a/tests/test_tutorial/test_query_params_str_validations/test_tutorial010_an_py39.py b/tests/test_tutorial/test_query_params_str_validations/test_tutorial010_an_py39.py
index 3e7d5d3adb..534ba87594 100644
--- a/tests/test_tutorial/test_query_params_str_validations/test_tutorial010_an_py39.py
+++ b/tests/test_tutorial/test_query_params_str_validations/test_tutorial010_an_py39.py
@@ -1,7 +1,6 @@
import pytest
from dirty_equals import IsDict
from fastapi.testclient import TestClient
-from fastapi.utils import match_pydantic_error_url
from ...utils import needs_py39
@@ -51,7 +50,6 @@ def test_query_params_str_validations_item_query_nonregexquery(client: TestClien
"msg": "String should match pattern '^fixedquery$'",
"input": "nonregexquery",
"ctx": {"pattern": "^fixedquery$"},
- "url": match_pydantic_error_url("string_pattern_mismatch"),
}
]
}
diff --git a/tests/test_tutorial/test_query_params_str_validations/test_tutorial010_py310.py b/tests/test_tutorial/test_query_params_str_validations/test_tutorial010_py310.py
index 1c3a09d399..886bceca21 100644
--- a/tests/test_tutorial/test_query_params_str_validations/test_tutorial010_py310.py
+++ b/tests/test_tutorial/test_query_params_str_validations/test_tutorial010_py310.py
@@ -1,7 +1,6 @@
import pytest
from dirty_equals import IsDict
from fastapi.testclient import TestClient
-from fastapi.utils import match_pydantic_error_url
from ...utils import needs_py310
@@ -51,7 +50,6 @@ def test_query_params_str_validations_item_query_nonregexquery(client: TestClien
"msg": "String should match pattern '^fixedquery$'",
"input": "nonregexquery",
"ctx": {"pattern": "^fixedquery$"},
- "url": match_pydantic_error_url("string_pattern_mismatch"),
}
]
}
diff --git a/tests/test_tutorial/test_request_files/test_tutorial001.py b/tests/test_tutorial/test_request_files/test_tutorial001.py
index 91cc2b6365..f5817593bb 100644
--- a/tests/test_tutorial/test_request_files/test_tutorial001.py
+++ b/tests/test_tutorial/test_request_files/test_tutorial001.py
@@ -1,6 +1,5 @@
from dirty_equals import IsDict
from fastapi.testclient import TestClient
-from fastapi.utils import match_pydantic_error_url
from docs_src.request_files.tutorial001 import app
@@ -29,7 +28,6 @@ def test_post_form_no_body():
"loc": ["body", "file"],
"msg": "Field required",
"input": None,
- "url": match_pydantic_error_url("missing"),
}
]
}
@@ -58,7 +56,6 @@ def test_post_body_json():
"loc": ["body", "file"],
"msg": "Field required",
"input": None,
- "url": match_pydantic_error_url("missing"),
}
]
}
diff --git a/tests/test_tutorial/test_request_files/test_tutorial001_an.py b/tests/test_tutorial/test_request_files/test_tutorial001_an.py
index 3021eb3c3c..1c78e3679e 100644
--- a/tests/test_tutorial/test_request_files/test_tutorial001_an.py
+++ b/tests/test_tutorial/test_request_files/test_tutorial001_an.py
@@ -1,6 +1,5 @@
from dirty_equals import IsDict
from fastapi.testclient import TestClient
-from fastapi.utils import match_pydantic_error_url
from docs_src.request_files.tutorial001_an import app
@@ -18,7 +17,6 @@ def test_post_form_no_body():
"loc": ["body", "file"],
"msg": "Field required",
"input": None,
- "url": match_pydantic_error_url("missing"),
}
]
}
@@ -47,7 +45,6 @@ def test_post_body_json():
"loc": ["body", "file"],
"msg": "Field required",
"input": None,
- "url": match_pydantic_error_url("missing"),
}
]
}
diff --git a/tests/test_tutorial/test_request_files/test_tutorial001_an_py39.py b/tests/test_tutorial/test_request_files/test_tutorial001_an_py39.py
index 04f3a4693b..843fcec287 100644
--- a/tests/test_tutorial/test_request_files/test_tutorial001_an_py39.py
+++ b/tests/test_tutorial/test_request_files/test_tutorial001_an_py39.py
@@ -1,7 +1,6 @@
import pytest
from dirty_equals import IsDict
from fastapi.testclient import TestClient
-from fastapi.utils import match_pydantic_error_url
from ...utils import needs_py39
@@ -26,7 +25,6 @@ def test_post_form_no_body(client: TestClient):
"loc": ["body", "file"],
"msg": "Field required",
"input": None,
- "url": match_pydantic_error_url("missing"),
}
]
}
@@ -56,7 +54,6 @@ def test_post_body_json(client: TestClient):
"loc": ["body", "file"],
"msg": "Field required",
"input": None,
- "url": match_pydantic_error_url("missing"),
}
]
}
diff --git a/tests/test_tutorial/test_request_files/test_tutorial002.py b/tests/test_tutorial/test_request_files/test_tutorial002.py
index ed9680b62b..db1552e5c6 100644
--- a/tests/test_tutorial/test_request_files/test_tutorial002.py
+++ b/tests/test_tutorial/test_request_files/test_tutorial002.py
@@ -1,6 +1,5 @@
from dirty_equals import IsDict
from fastapi.testclient import TestClient
-from fastapi.utils import match_pydantic_error_url
from docs_src.request_files.tutorial002 import app
@@ -18,7 +17,6 @@ def test_post_form_no_body():
"loc": ["body", "files"],
"msg": "Field required",
"input": None,
- "url": match_pydantic_error_url("missing"),
}
]
}
@@ -47,7 +45,6 @@ def test_post_body_json():
"loc": ["body", "files"],
"msg": "Field required",
"input": None,
- "url": match_pydantic_error_url("missing"),
}
]
}
diff --git a/tests/test_tutorial/test_request_files/test_tutorial002_an.py b/tests/test_tutorial/test_request_files/test_tutorial002_an.py
index ea8c1216c0..b16da16691 100644
--- a/tests/test_tutorial/test_request_files/test_tutorial002_an.py
+++ b/tests/test_tutorial/test_request_files/test_tutorial002_an.py
@@ -1,6 +1,5 @@
from dirty_equals import IsDict
from fastapi.testclient import TestClient
-from fastapi.utils import match_pydantic_error_url
from docs_src.request_files.tutorial002_an import app
@@ -18,7 +17,6 @@ def test_post_form_no_body():
"loc": ["body", "files"],
"msg": "Field required",
"input": None,
- "url": match_pydantic_error_url("missing"),
}
]
}
@@ -47,7 +45,6 @@ def test_post_body_json():
"loc": ["body", "files"],
"msg": "Field required",
"input": None,
- "url": match_pydantic_error_url("missing"),
}
]
}
diff --git a/tests/test_tutorial/test_request_files/test_tutorial002_an_py39.py b/tests/test_tutorial/test_request_files/test_tutorial002_an_py39.py
index 6d58778367..e092a516d5 100644
--- a/tests/test_tutorial/test_request_files/test_tutorial002_an_py39.py
+++ b/tests/test_tutorial/test_request_files/test_tutorial002_an_py39.py
@@ -2,7 +2,6 @@ import pytest
from dirty_equals import IsDict
from fastapi import FastAPI
from fastapi.testclient import TestClient
-from fastapi.utils import match_pydantic_error_url
from ...utils import needs_py39
@@ -32,7 +31,6 @@ def test_post_form_no_body(client: TestClient):
"loc": ["body", "files"],
"msg": "Field required",
"input": None,
- "url": match_pydantic_error_url("missing"),
}
]
}
@@ -62,7 +60,6 @@ def test_post_body_json(client: TestClient):
"loc": ["body", "files"],
"msg": "Field required",
"input": None,
- "url": match_pydantic_error_url("missing"),
}
]
}
diff --git a/tests/test_tutorial/test_request_files/test_tutorial002_py39.py b/tests/test_tutorial/test_request_files/test_tutorial002_py39.py
index 2d0445421b..341a9ac8ed 100644
--- a/tests/test_tutorial/test_request_files/test_tutorial002_py39.py
+++ b/tests/test_tutorial/test_request_files/test_tutorial002_py39.py
@@ -2,7 +2,6 @@ import pytest
from dirty_equals import IsDict
from fastapi import FastAPI
from fastapi.testclient import TestClient
-from fastapi.utils import match_pydantic_error_url
from ...utils import needs_py39
@@ -43,7 +42,6 @@ def test_post_form_no_body(client: TestClient):
"loc": ["body", "files"],
"msg": "Field required",
"input": None,
- "url": match_pydantic_error_url("missing"),
}
]
}
@@ -73,7 +71,6 @@ def test_post_body_json(client: TestClient):
"loc": ["body", "files"],
"msg": "Field required",
"input": None,
- "url": match_pydantic_error_url("missing"),
}
]
}
diff --git a/tests/test_tutorial/test_request_forms/test_tutorial001.py b/tests/test_tutorial/test_request_forms/test_tutorial001.py
index 805daeb10f..cbef9d30fb 100644
--- a/tests/test_tutorial/test_request_forms/test_tutorial001.py
+++ b/tests/test_tutorial/test_request_forms/test_tutorial001.py
@@ -1,7 +1,6 @@
import pytest
from dirty_equals import IsDict
from fastapi.testclient import TestClient
-from fastapi.utils import match_pydantic_error_url
@pytest.fixture(name="client")
@@ -29,7 +28,6 @@ def test_post_body_form_no_password(client: TestClient):
"loc": ["body", "password"],
"msg": "Field required",
"input": None,
- "url": match_pydantic_error_url("missing"),
}
]
}
@@ -58,7 +56,6 @@ def test_post_body_form_no_username(client: TestClient):
"loc": ["body", "username"],
"msg": "Field required",
"input": None,
- "url": match_pydantic_error_url("missing"),
}
]
}
@@ -87,14 +84,12 @@ def test_post_body_form_no_data(client: TestClient):
"loc": ["body", "username"],
"msg": "Field required",
"input": None,
- "url": match_pydantic_error_url("missing"),
},
{
"type": "missing",
"loc": ["body", "password"],
"msg": "Field required",
"input": None,
- "url": match_pydantic_error_url("missing"),
},
]
}
@@ -128,14 +123,12 @@ def test_post_body_json(client: TestClient):
"loc": ["body", "username"],
"msg": "Field required",
"input": None,
- "url": match_pydantic_error_url("missing"),
},
{
"type": "missing",
"loc": ["body", "password"],
"msg": "Field required",
"input": None,
- "url": match_pydantic_error_url("missing"),
},
]
}
diff --git a/tests/test_tutorial/test_request_forms/test_tutorial001_an.py b/tests/test_tutorial/test_request_forms/test_tutorial001_an.py
index c43a0b6955..88b8452bca 100644
--- a/tests/test_tutorial/test_request_forms/test_tutorial001_an.py
+++ b/tests/test_tutorial/test_request_forms/test_tutorial001_an.py
@@ -1,7 +1,6 @@
import pytest
from dirty_equals import IsDict
from fastapi.testclient import TestClient
-from fastapi.utils import match_pydantic_error_url
@pytest.fixture(name="client")
@@ -29,7 +28,6 @@ def test_post_body_form_no_password(client: TestClient):
"loc": ["body", "password"],
"msg": "Field required",
"input": None,
- "url": match_pydantic_error_url("missing"),
}
]
}
@@ -58,7 +56,6 @@ def test_post_body_form_no_username(client: TestClient):
"loc": ["body", "username"],
"msg": "Field required",
"input": None,
- "url": match_pydantic_error_url("missing"),
}
]
}
@@ -87,14 +84,12 @@ def test_post_body_form_no_data(client: TestClient):
"loc": ["body", "username"],
"msg": "Field required",
"input": None,
- "url": match_pydantic_error_url("missing"),
},
{
"type": "missing",
"loc": ["body", "password"],
"msg": "Field required",
"input": None,
- "url": match_pydantic_error_url("missing"),
},
]
}
@@ -128,14 +123,12 @@ def test_post_body_json(client: TestClient):
"loc": ["body", "username"],
"msg": "Field required",
"input": None,
- "url": match_pydantic_error_url("missing"),
},
{
"type": "missing",
"loc": ["body", "password"],
"msg": "Field required",
"input": None,
- "url": match_pydantic_error_url("missing"),
},
]
}
diff --git a/tests/test_tutorial/test_request_forms/test_tutorial001_an_py39.py b/tests/test_tutorial/test_request_forms/test_tutorial001_an_py39.py
index 078b812aa5..3229897c9f 100644
--- a/tests/test_tutorial/test_request_forms/test_tutorial001_an_py39.py
+++ b/tests/test_tutorial/test_request_forms/test_tutorial001_an_py39.py
@@ -1,7 +1,6 @@
import pytest
from dirty_equals import IsDict
from fastapi.testclient import TestClient
-from fastapi.utils import match_pydantic_error_url
from ...utils import needs_py39
@@ -33,7 +32,6 @@ def test_post_body_form_no_password(client: TestClient):
"loc": ["body", "password"],
"msg": "Field required",
"input": None,
- "url": match_pydantic_error_url("missing"),
}
]
}
@@ -63,7 +61,6 @@ def test_post_body_form_no_username(client: TestClient):
"loc": ["body", "username"],
"msg": "Field required",
"input": None,
- "url": match_pydantic_error_url("missing"),
}
]
}
@@ -93,14 +90,12 @@ def test_post_body_form_no_data(client: TestClient):
"loc": ["body", "username"],
"msg": "Field required",
"input": None,
- "url": match_pydantic_error_url("missing"),
},
{
"type": "missing",
"loc": ["body", "password"],
"msg": "Field required",
"input": None,
- "url": match_pydantic_error_url("missing"),
},
]
}
@@ -135,14 +130,12 @@ def test_post_body_json(client: TestClient):
"loc": ["body", "username"],
"msg": "Field required",
"input": None,
- "url": match_pydantic_error_url("missing"),
},
{
"type": "missing",
"loc": ["body", "password"],
"msg": "Field required",
"input": None,
- "url": match_pydantic_error_url("missing"),
},
]
}
diff --git a/tests/test_tutorial/test_request_forms_and_files/test_tutorial001.py b/tests/test_tutorial/test_request_forms_and_files/test_tutorial001.py
index cac58639f1..1e1ad2a872 100644
--- a/tests/test_tutorial/test_request_forms_and_files/test_tutorial001.py
+++ b/tests/test_tutorial/test_request_forms_and_files/test_tutorial001.py
@@ -2,7 +2,6 @@ import pytest
from dirty_equals import IsDict
from fastapi import FastAPI
from fastapi.testclient import TestClient
-from fastapi.utils import match_pydantic_error_url
@pytest.fixture(name="app")
@@ -29,21 +28,18 @@ def test_post_form_no_body(client: TestClient):
"loc": ["body", "file"],
"msg": "Field required",
"input": None,
- "url": match_pydantic_error_url("missing"),
},
{
"type": "missing",
"loc": ["body", "fileb"],
"msg": "Field required",
"input": None,
- "url": match_pydantic_error_url("missing"),
},
{
"type": "missing",
"loc": ["body", "token"],
"msg": "Field required",
"input": None,
- "url": match_pydantic_error_url("missing"),
},
]
}
@@ -82,14 +78,12 @@ def test_post_form_no_file(client: TestClient):
"loc": ["body", "file"],
"msg": "Field required",
"input": None,
- "url": match_pydantic_error_url("missing"),
},
{
"type": "missing",
"loc": ["body", "fileb"],
"msg": "Field required",
"input": None,
- "url": match_pydantic_error_url("missing"),
},
]
}
@@ -123,21 +117,18 @@ def test_post_body_json(client: TestClient):
"loc": ["body", "file"],
"msg": "Field required",
"input": None,
- "url": match_pydantic_error_url("missing"),
},
{
"type": "missing",
"loc": ["body", "fileb"],
"msg": "Field required",
"input": None,
- "url": match_pydantic_error_url("missing"),
},
{
"type": "missing",
"loc": ["body", "token"],
"msg": "Field required",
"input": None,
- "url": match_pydantic_error_url("missing"),
},
]
}
@@ -181,14 +172,12 @@ def test_post_file_no_token(tmp_path, app: FastAPI):
"loc": ["body", "fileb"],
"msg": "Field required",
"input": None,
- "url": match_pydantic_error_url("missing"),
},
{
"type": "missing",
"loc": ["body", "token"],
"msg": "Field required",
"input": None,
- "url": match_pydantic_error_url("missing"),
},
]
}
diff --git a/tests/test_tutorial/test_request_forms_and_files/test_tutorial001_an.py b/tests/test_tutorial/test_request_forms_and_files/test_tutorial001_an.py
index 009568048e..5daf4dbf49 100644
--- a/tests/test_tutorial/test_request_forms_and_files/test_tutorial001_an.py
+++ b/tests/test_tutorial/test_request_forms_and_files/test_tutorial001_an.py
@@ -2,7 +2,6 @@ import pytest
from dirty_equals import IsDict
from fastapi import FastAPI
from fastapi.testclient import TestClient
-from fastapi.utils import match_pydantic_error_url
@pytest.fixture(name="app")
@@ -29,21 +28,18 @@ def test_post_form_no_body(client: TestClient):
"loc": ["body", "file"],
"msg": "Field required",
"input": None,
- "url": match_pydantic_error_url("missing"),
},
{
"type": "missing",
"loc": ["body", "fileb"],
"msg": "Field required",
"input": None,
- "url": match_pydantic_error_url("missing"),
},
{
"type": "missing",
"loc": ["body", "token"],
"msg": "Field required",
"input": None,
- "url": match_pydantic_error_url("missing"),
},
]
}
@@ -82,14 +78,12 @@ def test_post_form_no_file(client: TestClient):
"loc": ["body", "file"],
"msg": "Field required",
"input": None,
- "url": match_pydantic_error_url("missing"),
},
{
"type": "missing",
"loc": ["body", "fileb"],
"msg": "Field required",
"input": None,
- "url": match_pydantic_error_url("missing"),
},
]
}
@@ -123,21 +117,18 @@ def test_post_body_json(client: TestClient):
"loc": ["body", "file"],
"msg": "Field required",
"input": None,
- "url": match_pydantic_error_url("missing"),
},
{
"type": "missing",
"loc": ["body", "fileb"],
"msg": "Field required",
"input": None,
- "url": match_pydantic_error_url("missing"),
},
{
"type": "missing",
"loc": ["body", "token"],
"msg": "Field required",
"input": None,
- "url": match_pydantic_error_url("missing"),
},
]
}
@@ -181,14 +172,12 @@ def test_post_file_no_token(tmp_path, app: FastAPI):
"loc": ["body", "fileb"],
"msg": "Field required",
"input": None,
- "url": match_pydantic_error_url("missing"),
},
{
"type": "missing",
"loc": ["body", "token"],
"msg": "Field required",
"input": None,
- "url": match_pydantic_error_url("missing"),
},
]
}
diff --git a/tests/test_tutorial/test_request_forms_and_files/test_tutorial001_an_py39.py b/tests/test_tutorial/test_request_forms_and_files/test_tutorial001_an_py39.py
index 3d007e90ba..3f1204efa7 100644
--- a/tests/test_tutorial/test_request_forms_and_files/test_tutorial001_an_py39.py
+++ b/tests/test_tutorial/test_request_forms_and_files/test_tutorial001_an_py39.py
@@ -2,7 +2,6 @@ import pytest
from dirty_equals import IsDict
from fastapi import FastAPI
from fastapi.testclient import TestClient
-from fastapi.utils import match_pydantic_error_url
from ...utils import needs_py39
@@ -32,21 +31,18 @@ def test_post_form_no_body(client: TestClient):
"loc": ["body", "file"],
"msg": "Field required",
"input": None,
- "url": match_pydantic_error_url("missing"),
},
{
"type": "missing",
"loc": ["body", "fileb"],
"msg": "Field required",
"input": None,
- "url": match_pydantic_error_url("missing"),
},
{
"type": "missing",
"loc": ["body", "token"],
"msg": "Field required",
"input": None,
- "url": match_pydantic_error_url("missing"),
},
]
}
@@ -86,14 +82,12 @@ def test_post_form_no_file(client: TestClient):
"loc": ["body", "file"],
"msg": "Field required",
"input": None,
- "url": match_pydantic_error_url("missing"),
},
{
"type": "missing",
"loc": ["body", "fileb"],
"msg": "Field required",
"input": None,
- "url": match_pydantic_error_url("missing"),
},
]
}
@@ -128,21 +122,18 @@ def test_post_body_json(client: TestClient):
"loc": ["body", "file"],
"msg": "Field required",
"input": None,
- "url": match_pydantic_error_url("missing"),
},
{
"type": "missing",
"loc": ["body", "fileb"],
"msg": "Field required",
"input": None,
- "url": match_pydantic_error_url("missing"),
},
{
"type": "missing",
"loc": ["body", "token"],
"msg": "Field required",
"input": None,
- "url": match_pydantic_error_url("missing"),
},
]
}
@@ -187,14 +178,12 @@ def test_post_file_no_token(tmp_path, app: FastAPI):
"loc": ["body", "fileb"],
"msg": "Field required",
"input": None,
- "url": match_pydantic_error_url("missing"),
},
{
"type": "missing",
"loc": ["body", "token"],
"msg": "Field required",
"input": None,
- "url": match_pydantic_error_url("missing"),
},
]
}