diff --git a/.github/workflows/build-docs.yml b/.github/workflows/build-docs.yml
index 73e1c6b67a..cd27179f57 100644
--- a/.github/workflows/build-docs.yml
+++ b/.github/workflows/build-docs.yml
@@ -60,8 +60,6 @@ jobs:
pyproject.toml
- name: Install docs extras
run: uv pip install -r requirements-docs.txt
- - name: Verify Docs
- run: python ./scripts/docs.py verify-docs
- name: Export Language Codes
id: show-langs
run: |
diff --git a/.github/workflows/pre-commit.yml b/.github/workflows/pre-commit.yml
index fa0574d7d1..b397912e67 100644
--- a/.github/workflows/pre-commit.yml
+++ b/.github/workflows/pre-commit.yml
@@ -7,7 +7,8 @@ on:
- synchronize
env:
- IS_FORK: ${{ github.event.pull_request.head.repo.full_name != github.repository }}
+ # Forks and Dependabot don't have access to secrets
+ HAS_SECRETS: ${{ secrets.PRE_COMMIT != '' }}
jobs:
pre-commit:
@@ -19,16 +20,23 @@ jobs:
run: echo "$GITHUB_CONTEXT"
- uses: actions/checkout@v5
name: Checkout PR for own repo
- if: env.IS_FORK == 'false'
+ if: env.HAS_SECRETS == 'true'
with:
- # To be able to commit it needs more than the last commit
+ # To be able to commit it needs to fetch the head of the branch, not the
+ # merge commit
ref: ${{ github.head_ref }}
+ # And it needs the full history to be able to compute diffs
+ fetch-depth: 0
# A token other than the default GITHUB_TOKEN is needed to be able to trigger CI
token: ${{ secrets.PRE_COMMIT }}
# pre-commit lite ci needs the default checkout configs to work
- uses: actions/checkout@v5
name: Checkout PR for fork
- if: env.IS_FORK == 'true'
+ if: env.HAS_SECRETS == 'false'
+ with:
+ # To be able to commit it needs the head branch of the PR, the remote one
+ ref: ${{ github.event.pull_request.head.sha }}
+ fetch-depth: 0
- name: Set up Python
uses: actions/setup-python@v6
with:
@@ -44,15 +52,12 @@ jobs:
run: |
uv venv
uv pip install -r requirements.txt
- - name: Run pre-commit
+ - name: Run prek - pre-commit
id: precommit
- run: |
- # Fetch the base branch for comparison
- git fetch origin ${{ github.base_ref }}
- uvx pre-commit run --from-ref origin/${{ github.base_ref }} --to-ref HEAD --show-diff-on-failure
+ run: uvx prek run --from-ref origin/${GITHUB_BASE_REF} --to-ref HEAD --show-diff-on-failure
continue-on-error: true
- name: Commit and push changes
- if: env.IS_FORK == 'false'
+ if: env.HAS_SECRETS == 'true'
run: |
git config user.name "github-actions[bot]"
git config user.email "github-actions[bot]@users.noreply.github.com"
@@ -64,7 +69,7 @@ jobs:
git push
fi
- uses: pre-commit-ci/lite-action@v1.1.0
- if: env.IS_FORK == 'true'
+ if: env.HAS_SECRETS == 'false'
with:
msg: 🎨 Auto format
- name: Error out on pre-commit errors
diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml
index c430854265..3ad630d94b 100644
--- a/.github/workflows/test.yml
+++ b/.github/workflows/test.yml
@@ -16,66 +16,31 @@ env:
UV_SYSTEM_PYTHON: 1
jobs:
- lint:
- runs-on: ubuntu-latest
- steps:
- - name: Dump GitHub context
- env:
- GITHUB_CONTEXT: ${{ toJson(github) }}
- run: echo "$GITHUB_CONTEXT"
- - uses: actions/checkout@v6
- - name: Set up Python
- uses: actions/setup-python@v6
- with:
- python-version: "3.11"
- - name: Setup uv
- uses: astral-sh/setup-uv@v7
- with:
- cache-dependency-glob: |
- requirements**.txt
- pyproject.toml
- - name: Install Dependencies
- run: uv pip install -r requirements-tests.txt
- - name: Lint
- run: bash scripts/lint.sh
-
test:
strategy:
matrix:
os: [ windows-latest, macos-latest ]
python-version: [ "3.14" ]
- pydantic-version: [ "pydantic>=2.0.2,<3.0.0" ]
include:
- - os: macos-latest
- python-version: "3.8"
- pydantic-version: "pydantic>=1.10.0,<2.0.0"
- - os: windows-latest
- python-version: "3.8"
- pydantic-version: "pydantic>=2.0.2,<3.0.0"
- coverage: coverage
- os: ubuntu-latest
python-version: "3.9"
- pydantic-version: "pydantic>=1.10.0,<2.0.0"
coverage: coverage
- os: macos-latest
python-version: "3.10"
- pydantic-version: "pydantic>=2.0.2,<3.0.0"
+ coverage: coverage
- os: windows-latest
- python-version: "3.11"
- pydantic-version: "pydantic>=1.10.0,<2.0.0"
- - os: ubuntu-latest
python-version: "3.12"
- pydantic-version: "pydantic>=2.0.2,<3.0.0"
- - os: macos-latest
- python-version: "3.13"
- pydantic-version: "pydantic>=1.10.0,<2.0.0"
- - os: windows-latest
- python-version: "3.13"
- pydantic-version: "pydantic>=2.0.2,<3.0.0"
coverage: coverage
+ - os: ubuntu-latest
+ python-version: "3.13"
+ coverage: coverage
+ # Ubuntu with 3.13 needs coverage for CodSpeed benchmarks
+ - os: ubuntu-latest
+ python-version: "3.13"
+ coverage: coverage
+ codspeed: codspeed
- os: ubuntu-latest
python-version: "3.14"
- pydantic-version: "pydantic>=2.0.2,<3.0.0"
coverage: coverage
fail-fast: false
runs-on: ${{ matrix.os }}
@@ -99,18 +64,22 @@ jobs:
pyproject.toml
- name: Install Dependencies
run: uv pip install -r requirements-tests.txt
- - name: Install Pydantic
- run: uv pip install "${{ matrix.pydantic-version }}"
- # TODO: Remove this once Python 3.8 is no longer supported
- - name: Install older AnyIO in Python 3.8
- if: matrix.python-version == '3.8'
- run: uv pip install "anyio[trio]<4.0.0"
- run: mkdir coverage
- name: Test
+ if: matrix.codspeed != 'codspeed'
run: bash scripts/test.sh
env:
COVERAGE_FILE: coverage/.coverage.${{ runner.os }}-py${{ matrix.python-version }}
CONTEXT: ${{ runner.os }}-py${{ matrix.python-version }}
+ - name: CodSpeed benchmarks
+ if: matrix.codspeed == 'codspeed'
+ uses: CodSpeedHQ/action@v4
+ env:
+ COVERAGE_FILE: coverage/.coverage.${{ runner.os }}-py${{ matrix.python-version }}
+ CONTEXT: ${{ runner.os }}-py${{ matrix.python-version }}
+ with:
+ mode: simulation
+ run: coverage run -m pytest tests/ --codspeed
# Do not store coverage for all possible combinations to avoid file size max errors in Smokeshow
- name: Store coverage files
if: matrix.coverage == 'coverage'
@@ -131,7 +100,7 @@ jobs:
- uses: actions/checkout@v6
- uses: actions/setup-python@v6
with:
- python-version: '3.8'
+ python-version: '3.11'
- name: Setup uv
uses: astral-sh/setup-uv@v7
with:
diff --git a/.github/workflows/translate.yml b/.github/workflows/translate.yml
index e681762ca3..f1267d21f5 100644
--- a/.github/workflows/translate.yml
+++ b/.github/workflows/translate.yml
@@ -1,8 +1,8 @@
name: Translate
on:
- schedule:
- - cron: "0 5 15 * *" # Run at 05:00 on the 15 of every month
+ # schedule:
+ # - cron: "0 5 15 * *" # Run at 05:00 on the 15 of every month
workflow_dispatch:
inputs:
diff --git a/.gitignore b/.gitignore
index 6016ffa598..3dc12ca951 100644
--- a/.gitignore
+++ b/.gitignore
@@ -31,3 +31,5 @@ archive.zip
# Ignore while the setup still depends on requirements.txt files
uv.lock
+
+.codspeed
diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml
index 8e6d93fb7d..10a0949e48 100644
--- a/.pre-commit-config.yaml
+++ b/.pre-commit-config.yaml
@@ -5,25 +5,55 @@ repos:
rev: v6.0.0
hooks:
- id: check-added-large-files
+ args: ['--maxkb=750']
- id: check-toml
- id: check-yaml
args:
- --unsafe
- id: end-of-file-fixer
- id: trailing-whitespace
- - repo: https://github.com/astral-sh/ruff-pre-commit
- rev: v0.14.3
- hooks:
- - id: ruff
- args:
- - --fix
- - id: ruff-format
+
- repo: local
hooks:
- - id: local-script
+ - id: local-ruff-check
+ name: ruff check
+ entry: uv run ruff check --force-exclude --fix --exit-non-zero-on-fix
+ require_serial: true
language: unsupported
- name: local script
+ types: [python]
+
+ - id: local-ruff-format
+ name: ruff format
+ entry: uv run ruff format --force-exclude --exit-non-zero-on-format
+ require_serial: true
+ language: unsupported
+ types: [python]
+
+ - id: add-permalinks-pages
+ language: unsupported
+ name: add-permalinks-pages
entry: uv run ./scripts/docs.py add-permalinks-pages
args:
- --update-existing
files: ^docs/en/docs/.*\.md$
+
+ - id: generate-readme
+ language: unsupported
+ name: generate README.md from index.md
+ entry: uv run ./scripts/docs.py generate-readme
+ files: ^docs/en/docs/index\.md|docs/en/data/sponsors\.yml|scripts/docs\.py$
+ pass_filenames: false
+
+ - id: update-languages
+ language: unsupported
+ name: update languages
+ entry: uv run ./scripts/docs.py update-languages
+ files: ^docs/.*|scripts/docs\.py$
+ pass_filenames: false
+
+ - id: ensure-non-translated
+ language: unsupported
+ name: ensure non-translated files are not modified
+ entry: uv run ./scripts/docs.py ensure-non-translated
+ files: ^docs/(?!en/).*|^scripts/docs\.py$
+ pass_filenames: false
diff --git a/README.md b/README.md
index a42cedae69..1057b86942 100644
--- a/README.md
+++ b/README.md
@@ -120,6 +120,12 @@ The key features are:
---
+## FastAPI mini documentary
+
+There's a FastAPI mini documentary released at the end of 2025, you can watch it online:
+
+
+
## **Typer**, the FastAPI of CLIs
diff --git a/docs/de/docs/advanced/additional-responses.md b/docs/de/docs/advanced/additional-responses.md
index 29a0a14777..0f9b122516 100644
--- a/docs/de/docs/advanced/additional-responses.md
+++ b/docs/de/docs/advanced/additional-responses.md
@@ -26,7 +26,7 @@ Jedes dieser Response-`dict`s kann einen Schlüssel `model` haben, welcher ein P
Um beispielsweise eine weitere Response mit dem Statuscode `404` und einem Pydantic-Modell `Message` zu deklarieren, können Sie schreiben:
-{* ../../docs_src/additional_responses/tutorial001.py hl[18,22] *}
+{* ../../docs_src/additional_responses/tutorial001_py39.py hl[18,22] *}
/// note | Hinweis
@@ -203,7 +203,7 @@ Sie können beispielsweise eine Response mit dem Statuscode `404` deklarieren, d
Und eine Response mit dem Statuscode `200`, die Ihr `response_model` verwendet, aber ein benutzerdefiniertes Beispiel (`example`) enthält:
-{* ../../docs_src/additional_responses/tutorial003.py hl[20:31] *}
+{* ../../docs_src/additional_responses/tutorial003_py39.py hl[20:31] *}
Es wird alles kombiniert und in Ihre OpenAPI eingebunden und in der API-Dokumentation angezeigt:
diff --git a/docs/de/docs/advanced/async-tests.md b/docs/de/docs/advanced/async-tests.md
index ad82452052..7206f136fd 100644
--- a/docs/de/docs/advanced/async-tests.md
+++ b/docs/de/docs/advanced/async-tests.md
@@ -32,11 +32,11 @@ Betrachten wir als einfaches Beispiel eine Dateistruktur ähnlich der in [Größ
Die Datei `main.py` hätte als Inhalt:
-{* ../../docs_src/async_tests/main.py *}
+{* ../../docs_src/async_tests/app_a_py39/main.py *}
Die Datei `test_main.py` hätte die Tests für `main.py`, das könnte jetzt so aussehen:
-{* ../../docs_src/async_tests/test_main.py *}
+{* ../../docs_src/async_tests/app_a_py39/test_main.py *}
## Es ausführen { #run-it }
@@ -56,7 +56,7 @@ $ pytest
Der Marker `@pytest.mark.anyio` teilt pytest mit, dass diese Testfunktion asynchron aufgerufen werden soll:
-{* ../../docs_src/async_tests/test_main.py hl[7] *}
+{* ../../docs_src/async_tests/app_a_py39/test_main.py hl[7] *}
/// tip | Tipp
@@ -66,7 +66,7 @@ Beachten Sie, dass die Testfunktion jetzt `async def` ist und nicht nur `def` wi
Dann können wir einen `AsyncClient` mit der App erstellen und mit `await` asynchrone Requests an ihn senden.
-{* ../../docs_src/async_tests/test_main.py hl[9:12] *}
+{* ../../docs_src/async_tests/app_a_py39/test_main.py hl[9:12] *}
Das ist das Äquivalent zu:
diff --git a/docs/de/docs/advanced/behind-a-proxy.md b/docs/de/docs/advanced/behind-a-proxy.md
index 183d0beeef..1c74590503 100644
--- a/docs/de/docs/advanced/behind-a-proxy.md
+++ b/docs/de/docs/advanced/behind-a-proxy.md
@@ -44,7 +44,7 @@ $ fastapi run --forwarded-allow-ips="*"
Angenommen, Sie definieren eine *Pfadoperation* `/items/`:
-{* ../../docs_src/behind_a_proxy/tutorial001_01.py hl[6] *}
+{* ../../docs_src/behind_a_proxy/tutorial001_01_py39.py hl[6] *}
Wenn der Client versucht, zu `/items` zu gehen, würde er standardmäßig zu `/items/` umgeleitet.
@@ -115,7 +115,7 @@ In diesem Fall würde der ursprüngliche Pfad `/app` tatsächlich unter `/api/v1
Auch wenn Ihr gesamter Code unter der Annahme geschrieben ist, dass es nur `/app` gibt.
-{* ../../docs_src/behind_a_proxy/tutorial001.py hl[6] *}
+{* ../../docs_src/behind_a_proxy/tutorial001_py39.py hl[6] *}
Und der Proxy würde das **Pfadpräfix** on-the-fly **„entfernen“**, bevor er den Request an den Anwendungsserver (wahrscheinlich Uvicorn via FastAPI CLI) übermittelt, dafür sorgend, dass Ihre Anwendung davon überzeugt ist, dass sie unter `/app` bereitgestellt wird, sodass Sie nicht Ihren gesamten Code dahingehend aktualisieren müssen, das Präfix `/api/v1` zu verwenden.
@@ -193,7 +193,7 @@ Sie können den aktuellen `root_path` abrufen, der von Ihrer Anwendung für jede
Hier fügen wir ihn, nur zu Demonstrationszwecken, in die Nachricht ein.
-{* ../../docs_src/behind_a_proxy/tutorial001.py hl[8] *}
+{* ../../docs_src/behind_a_proxy/tutorial001_py39.py hl[8] *}
Wenn Sie Uvicorn dann starten mit:
@@ -220,7 +220,7 @@ wäre die `dataclasses`:
-{* ../../docs_src/dataclasses/tutorial001_py310.py hl[1,6:11,18:19] *}
+{* ../../docs_src/dataclasses_/tutorial001_py310.py hl[1,6:11,18:19] *}
Das ist dank **Pydantic** ebenfalls möglich, da es `dataclasses` intern unterstützt.
@@ -32,7 +32,7 @@ Wenn Sie jedoch eine Menge Datenklassen herumliegen haben, ist dies ein guter Tr
Sie können `dataclasses` auch im Parameter `response_model` verwenden:
-{* ../../docs_src/dataclasses/tutorial002_py310.py hl[1,6:12,18] *}
+{* ../../docs_src/dataclasses_/tutorial002_py310.py hl[1,6:12,18] *}
Die Datenklasse wird automatisch in eine Pydantic-Datenklasse konvertiert.
@@ -48,7 +48,7 @@ In einigen Fällen müssen Sie möglicherweise immer noch Pydantics Version von
In diesem Fall können Sie einfach die Standard-`dataclasses` durch `pydantic.dataclasses` ersetzen, was einen direkten Ersatz darstellt:
-{* ../../docs_src/dataclasses/tutorial003_py310.py hl[1,4,7:10,13:16,22:24,27] *}
+{* ../../docs_src/dataclasses_/tutorial003_py310.py hl[1,4,7:10,13:16,22:24,27] *}
1. Wir importieren `field` weiterhin von Standard-`dataclasses`.
diff --git a/docs/de/docs/advanced/events.md b/docs/de/docs/advanced/events.md
index f94526b4fc..7e1191b55e 100644
--- a/docs/de/docs/advanced/events.md
+++ b/docs/de/docs/advanced/events.md
@@ -30,7 +30,7 @@ Beginnen wir mit einem Beispiel und sehen es uns dann im Detail an.
Wir erstellen eine asynchrone Funktion `lifespan()` mit `yield` wie folgt:
-{* ../../docs_src/events/tutorial003.py hl[16,19] *}
+{* ../../docs_src/events/tutorial003_py39.py hl[16,19] *}
Hier simulieren wir den langsamen *Startup*, das Laden des Modells, indem wir die (Fake-)Modellfunktion vor dem `yield` in das Dictionary mit Modellen für maschinelles Lernen einfügen. Dieser Code wird ausgeführt, **bevor** die Anwendung **beginnt, Requests entgegenzunehmen**, während des *Startups*.
@@ -48,7 +48,7 @@ Möglicherweise müssen Sie eine neue Version starten, oder Sie haben es einfach
Das Erste, was auffällt, ist, dass wir eine asynchrone Funktion mit `yield` definieren. Das ist sehr ähnlich zu Abhängigkeiten mit `yield`.
-{* ../../docs_src/events/tutorial003.py hl[14:19] *}
+{* ../../docs_src/events/tutorial003_py39.py hl[14:19] *}
Der erste Teil der Funktion, vor dem `yield`, wird ausgeführt **bevor** die Anwendung startet.
@@ -60,7 +60,7 @@ Wie Sie sehen, ist die Funktion mit einem `@asynccontextmanager` versehen.
Dadurch wird die Funktion in einen sogenannten „**asynchronen Kontextmanager**“ umgewandelt.
-{* ../../docs_src/events/tutorial003.py hl[1,13] *}
+{* ../../docs_src/events/tutorial003_py39.py hl[1,13] *}
Ein **Kontextmanager** in Python ist etwas, das Sie in einer `with`-Anweisung verwenden können, zum Beispiel kann `open()` als Kontextmanager verwendet werden:
@@ -82,7 +82,7 @@ In unserem obigen Codebeispiel verwenden wir ihn nicht direkt, sondern übergebe
Der Parameter `lifespan` der `FastAPI`-App benötigt einen **asynchronen Kontextmanager**, wir können ihm also unseren neuen asynchronen Kontextmanager `lifespan` übergeben.
-{* ../../docs_src/events/tutorial003.py hl[22] *}
+{* ../../docs_src/events/tutorial003_py39.py hl[22] *}
## Alternative Events (deprecatet) { #alternative-events-deprecated }
@@ -104,7 +104,7 @@ Diese Funktionen können mit `async def` oder normalem `def` deklariert werden.
Um eine Funktion hinzuzufügen, die vor dem Start der Anwendung ausgeführt werden soll, deklarieren Sie diese mit dem Event `startup`:
-{* ../../docs_src/events/tutorial001.py hl[8] *}
+{* ../../docs_src/events/tutorial001_py39.py hl[8] *}
In diesem Fall initialisiert die Eventhandler-Funktion `startup` die „Datenbank“ der Items (nur ein `dict`) mit einigen Werten.
@@ -116,7 +116,7 @@ Und Ihre Anwendung empfängt erst dann Requests, wenn alle `startup`-Eventhandle
Um eine Funktion hinzuzufügen, die beim Shutdown der Anwendung ausgeführt werden soll, deklarieren Sie sie mit dem Event `shutdown`:
-{* ../../docs_src/events/tutorial002.py hl[6] *}
+{* ../../docs_src/events/tutorial002_py39.py hl[6] *}
Hier schreibt die `shutdown`-Eventhandler-Funktion eine Textzeile `"Application shutdown"` in eine Datei `log.txt`.
diff --git a/docs/de/docs/advanced/generate-clients.md b/docs/de/docs/advanced/generate-clients.md
index d8836295b6..659343f5bc 100644
--- a/docs/de/docs/advanced/generate-clients.md
+++ b/docs/de/docs/advanced/generate-clients.md
@@ -167,7 +167,7 @@ Aber für den generierten Client könnten wir die OpenAPI-Operation-IDs direkt v
Wir könnten das OpenAPI-JSON in eine Datei `openapi.json` herunterladen und dann mit einem Skript wie dem folgenden **den präfixierten Tag entfernen**:
-{* ../../docs_src/generate_clients/tutorial004.py *}
+{* ../../docs_src/generate_clients/tutorial004_py39.py *}
//// tab | Node.js
diff --git a/docs/de/docs/advanced/middleware.md b/docs/de/docs/advanced/middleware.md
index 8396a626b6..ccc6a64c3b 100644
--- a/docs/de/docs/advanced/middleware.md
+++ b/docs/de/docs/advanced/middleware.md
@@ -57,13 +57,13 @@ Erzwingt, dass alle eingehenden geparst, sondern direkt als `bytes` gelesen und die Funktion `magic_data_reader()` wäre dafür verantwortlich, ihn in irgendeiner Weise zu parsen.
@@ -153,48 +153,16 @@ Und Sie könnten dies auch tun, wenn der Datentyp im Request nicht JSON ist.
In der folgenden Anwendung verwenden wir beispielsweise weder die integrierte Funktionalität von FastAPI zum Extrahieren des JSON-Schemas aus Pydantic-Modellen noch die automatische Validierung für JSON. Tatsächlich deklarieren wir den Request-Content-Type als YAML und nicht als JSON:
-//// tab | Pydantic v2
-
{* ../../docs_src/path_operation_advanced_configuration/tutorial007_py39.py hl[15:20, 22] *}
-////
-
-//// tab | Pydantic v1
-
-{* ../../docs_src/path_operation_advanced_configuration/tutorial007_pv1_py39.py hl[15:20, 22] *}
-
-////
-
-/// info | Info
-
-In Pydantic Version 1 hieß die Methode zum Abrufen des JSON-Schemas für ein Modell `Item.schema()`, in Pydantic Version 2 heißt die Methode `Item.model_json_schema()`.
-
-///
-
Obwohl wir nicht die standardmäßig integrierte Funktionalität verwenden, verwenden wir dennoch ein Pydantic-Modell, um das JSON-Schema für die Daten, die wir in YAML empfangen möchten, manuell zu generieren.
-Dann verwenden wir den Request direkt und extrahieren den Body als `bytes`. Das bedeutet, dass FastAPI nicht einmal versucht, den Request-Payload als JSON zu parsen.
+Dann verwenden wir den Request direkt und extrahieren den Body als `bytes`. Das bedeutet, dass FastAPI nicht einmal versucht, die Request-Payload als JSON zu parsen.
Und dann parsen wir in unserem Code diesen YAML-Inhalt direkt und verwenden dann wieder dasselbe Pydantic-Modell, um den YAML-Inhalt zu validieren:
-//// tab | Pydantic v2
-
{* ../../docs_src/path_operation_advanced_configuration/tutorial007_py39.py hl[24:31] *}
-////
-
-//// tab | Pydantic v1
-
-{* ../../docs_src/path_operation_advanced_configuration/tutorial007_pv1_py39.py hl[24:31] *}
-
-////
-
-/// info | Info
-
-In Pydantic Version 1 war die Methode zum Parsen und Validieren eines Objekts `Item.parse_obj()`, in Pydantic Version 2 heißt die Methode `Item.model_validate()`.
-
-///
-
/// tip | Tipp
Hier verwenden wir dasselbe Pydantic-Modell wieder.
diff --git a/docs/de/docs/advanced/response-change-status-code.md b/docs/de/docs/advanced/response-change-status-code.md
index b079e241d1..b209c2d671 100644
--- a/docs/de/docs/advanced/response-change-status-code.md
+++ b/docs/de/docs/advanced/response-change-status-code.md
@@ -20,7 +20,7 @@ Sie können einen Parameter vom Typ `Response` in Ihrer *Pfadoperation-Funktion*
Anschließend können Sie den `status_code` in diesem *vorübergehenden* Response-Objekt festlegen.
-{* ../../docs_src/response_change_status_code/tutorial001.py hl[1,9,12] *}
+{* ../../docs_src/response_change_status_code/tutorial001_py39.py hl[1,9,12] *}
Und dann können Sie jedes benötigte Objekt zurückgeben, wie Sie es normalerweise tun würden (ein `dict`, ein Datenbankmodell usw.).
diff --git a/docs/de/docs/advanced/response-cookies.md b/docs/de/docs/advanced/response-cookies.md
index 02fe99c26a..87e636cfaf 100644
--- a/docs/de/docs/advanced/response-cookies.md
+++ b/docs/de/docs/advanced/response-cookies.md
@@ -6,7 +6,7 @@ Sie können einen Parameter vom Typ `Response` in Ihrer *Pfadoperation-Funktion*
Und dann können Sie Cookies in diesem *vorübergehenden* Response-Objekt setzen.
-{* ../../docs_src/response_cookies/tutorial002.py hl[1, 8:9] *}
+{* ../../docs_src/response_cookies/tutorial002_py39.py hl[1, 8:9] *}
Anschließend können Sie wie gewohnt jedes gewünschte Objekt zurückgeben (ein `dict`, ein Datenbankmodell, usw.).
@@ -24,7 +24,7 @@ Dazu können Sie eine Response erstellen, wie unter [Eine Response direkt zurüc
Setzen Sie dann Cookies darin und geben Sie sie dann zurück:
-{* ../../docs_src/response_cookies/tutorial001.py hl[10:12] *}
+{* ../../docs_src/response_cookies/tutorial001_py39.py hl[10:12] *}
/// tip | Tipp
diff --git a/docs/de/docs/advanced/response-directly.md b/docs/de/docs/advanced/response-directly.md
index 06ec2c32ed..0a28a6d0e2 100644
--- a/docs/de/docs/advanced/response-directly.md
+++ b/docs/de/docs/advanced/response-directly.md
@@ -54,7 +54,7 @@ Nehmen wir an, Sie möchten eine Response-Objekt festlegen.
-{* ../../docs_src/response_headers/tutorial002.py hl[1, 7:8] *}
+{* ../../docs_src/response_headers/tutorial002_py39.py hl[1, 7:8] *}
Anschließend können Sie wie gewohnt jedes gewünschte Objekt zurückgeben (ein `dict`, ein Datenbankmodell, usw.).
@@ -22,7 +22,7 @@ Sie können auch Header hinzufügen, wenn Sie eine `Response` direkt zurückgebe
Erstellen Sie eine Response wie in [Eine Response direkt zurückgeben](response-directly.md){.internal-link target=_blank} beschrieben und übergeben Sie die Header als zusätzlichen Parameter:
-{* ../../docs_src/response_headers/tutorial001.py hl[10:12] *}
+{* ../../docs_src/response_headers/tutorial001_py39.py hl[10:12] *}
/// note | Technische Details
diff --git a/docs/de/docs/advanced/settings.md b/docs/de/docs/advanced/settings.md
index 03263a28b0..ea4540e10e 100644
--- a/docs/de/docs/advanced/settings.md
+++ b/docs/de/docs/advanced/settings.md
@@ -60,23 +60,7 @@ Auf die gleiche Weise wie bei Pydantic-Modellen deklarieren Sie Klassenattribute
Sie können dieselben Validierungs-Funktionen und -Tools verwenden, die Sie für Pydantic-Modelle verwenden, z. B. verschiedene Datentypen und zusätzliche Validierungen mit `Field()`.
-//// tab | Pydantic v2
-
-{* ../../docs_src/settings/tutorial001.py hl[2,5:8,11] *}
-
-////
-
-//// tab | Pydantic v1
-
-/// info | Info
-
-In Pydantic v1 würden Sie `BaseSettings` direkt von `pydantic` statt von `pydantic_settings` importieren.
-
-///
-
-{* ../../docs_src/settings/tutorial001_pv1.py hl[2,5:8,11] *}
-
-////
+{* ../../docs_src/settings/tutorial001_py39.py hl[2,5:8,11] *}
/// tip | Tipp
@@ -92,7 +76,7 @@ Als Nächstes werden die Daten konvertiert und validiert. Wenn Sie also dieses `
Dann können Sie das neue `settings`-Objekt in Ihrer Anwendung verwenden:
-{* ../../docs_src/settings/tutorial001.py hl[18:20] *}
+{* ../../docs_src/settings/tutorial001_py39.py hl[18:20] *}
### Den Server ausführen { #run-the-server }
@@ -126,11 +110,11 @@ Sie könnten diese Einstellungen in eine andere Moduldatei einfügen, wie Sie in
Sie könnten beispielsweise eine Datei `config.py` haben mit:
-{* ../../docs_src/settings/app01/config.py *}
+{* ../../docs_src/settings/app01_py39/config.py *}
Und dann verwenden Sie diese in einer Datei `main.py`:
-{* ../../docs_src/settings/app01/main.py hl[3,11:13] *}
+{* ../../docs_src/settings/app01_py39/main.py hl[3,11:13] *}
/// tip | Tipp
@@ -215,8 +199,6 @@ APP_NAME="ChimichangApp"
Und dann aktualisieren Sie Ihre `config.py` mit:
-//// tab | Pydantic v2
-
{* ../../docs_src/settings/app03_an_py39/config.py hl[9] *}
/// tip | Tipp
@@ -225,26 +207,6 @@ Das Attribut `model_config` wird nur für die Pydantic-Konfiguration verwendet.
///
-////
-
-//// tab | Pydantic v1
-
-{* ../../docs_src/settings/app03_an_py39/config_pv1.py hl[9:10] *}
-
-/// tip | Tipp
-
-Die Klasse `Config` wird nur für die Pydantic-Konfiguration verwendet. Weitere Informationen finden Sie unter Pydantic Model Config.
-
-///
-
-////
-
-/// info | Info
-
-In Pydantic Version 1 erfolgte die Konfiguration in einer internen Klasse `Config`, in Pydantic Version 2 erfolgt sie in einem Attribut `model_config`. Dieses Attribut akzeptiert ein `dict`. Um automatische Codevervollständigung und Inline-Fehlerberichte zu erhalten, können Sie `SettingsConfigDict` importieren und verwenden, um dieses `dict` zu definieren.
-
-///
-
Hier definieren wir die Konfiguration `env_file` innerhalb Ihrer Pydantic-`Settings`-Klasse und setzen den Wert auf den Dateinamen mit der dotenv-Datei, die wir verwenden möchten.
### Die `Settings` nur einmal laden mittels `lru_cache` { #creating-the-settings-only-once-with-lru-cache }
diff --git a/docs/de/docs/advanced/sub-applications.md b/docs/de/docs/advanced/sub-applications.md
index d634aac23b..081574d0a9 100644
--- a/docs/de/docs/advanced/sub-applications.md
+++ b/docs/de/docs/advanced/sub-applications.md
@@ -10,7 +10,7 @@ Wenn Sie zwei unabhängige FastAPI-Anwendungen mit deren eigenen unabhängigen O
Erstellen Sie zunächst die Hauptanwendung **FastAPI** und deren *Pfadoperationen*:
-{* ../../docs_src/sub_applications/tutorial001.py hl[3, 6:8] *}
+{* ../../docs_src/sub_applications/tutorial001_py39.py hl[3, 6:8] *}
### Unteranwendung { #sub-application }
@@ -18,7 +18,7 @@ Erstellen Sie dann Ihre Unteranwendung und deren *Pfadoperationen*.
Diese Unteranwendung ist nur eine weitere Standard-FastAPI-Anwendung, aber diese wird „gemountet“:
-{* ../../docs_src/sub_applications/tutorial001.py hl[11, 14:16] *}
+{* ../../docs_src/sub_applications/tutorial001_py39.py hl[11, 14:16] *}
### Die Unteranwendung mounten { #mount-the-sub-application }
@@ -26,7 +26,7 @@ Mounten Sie in Ihrer Top-Level-Anwendung `app` die Unteranwendung `subapi`.
In diesem Fall wird sie im Pfad `/subapi` gemountet:
-{* ../../docs_src/sub_applications/tutorial001.py hl[11, 19] *}
+{* ../../docs_src/sub_applications/tutorial001_py39.py hl[11, 19] *}
### Die automatische API-Dokumentation testen { #check-the-automatic-api-docs }
diff --git a/docs/de/docs/advanced/templates.md b/docs/de/docs/advanced/templates.md
index 65c7998b8a..97a45e6126 100644
--- a/docs/de/docs/advanced/templates.md
+++ b/docs/de/docs/advanced/templates.md
@@ -27,7 +27,7 @@ $ pip install jinja2
* Deklarieren Sie einen `Request`-Parameter in der *Pfadoperation*, welcher ein Template zurückgibt.
* Verwenden Sie die von Ihnen erstellten `templates`, um eine `TemplateResponse` zu rendern und zurückzugeben, übergeben Sie den Namen des Templates, das Requestobjekt und ein „Kontext“-Dictionary mit Schlüssel-Wert-Paaren, die innerhalb des Jinja2-Templates verwendet werden sollen.
-{* ../../docs_src/templates/tutorial001.py hl[4,11,15:18] *}
+{* ../../docs_src/templates/tutorial001_py39.py hl[4,11,15:18] *}
/// note | Hinweis
diff --git a/docs/de/docs/advanced/testing-events.md b/docs/de/docs/advanced/testing-events.md
index 569518c51d..5b12f3f186 100644
--- a/docs/de/docs/advanced/testing-events.md
+++ b/docs/de/docs/advanced/testing-events.md
@@ -2,11 +2,11 @@
Wenn Sie `lifespan` in Ihren Tests ausführen müssen, können Sie den `TestClient` mit einer `with`-Anweisung verwenden:
-{* ../../docs_src/app_testing/tutorial004.py hl[9:15,18,27:28,30:32,41:43] *}
+{* ../../docs_src/app_testing/tutorial004_py39.py hl[9:15,18,27:28,30:32,41:43] *}
Sie können mehr Details unter [„Lifespan in Tests ausführen in der offiziellen Starlette-Dokumentation.“](https://www.starlette.dev/lifespan/#running-lifespan-in-tests) nachlesen.
Für die deprecateten Events `startup` und `shutdown` können Sie den `TestClient` wie folgt verwenden:
-{* ../../docs_src/app_testing/tutorial003.py hl[9:12,20:24] *}
+{* ../../docs_src/app_testing/tutorial003_py39.py hl[9:12,20:24] *}
diff --git a/docs/de/docs/advanced/testing-websockets.md b/docs/de/docs/advanced/testing-websockets.md
index f25aa4fd04..9ecca7a4f7 100644
--- a/docs/de/docs/advanced/testing-websockets.md
+++ b/docs/de/docs/advanced/testing-websockets.md
@@ -4,7 +4,7 @@ Sie können den schon bekannten `TestClient` zum Testen von WebSockets verwenden
Dazu verwenden Sie den `TestClient` in einer `with`-Anweisung, eine Verbindung zum WebSocket herstellend:
-{* ../../docs_src/app_testing/tutorial002.py hl[27:31] *}
+{* ../../docs_src/app_testing/tutorial002_py39.py hl[27:31] *}
/// note | Hinweis
diff --git a/docs/de/docs/advanced/using-request-directly.md b/docs/de/docs/advanced/using-request-directly.md
index 8ec6741d07..36d73b8067 100644
--- a/docs/de/docs/advanced/using-request-directly.md
+++ b/docs/de/docs/advanced/using-request-directly.md
@@ -29,7 +29,7 @@ Angenommen, Sie möchten auf die IP-Adresse/den Host des Clients in Ihrer *Pfado
Dazu müssen Sie direkt auf den Request zugreifen.
-{* ../../docs_src/using_request_directly/tutorial001.py hl[1,7:8] *}
+{* ../../docs_src/using_request_directly/tutorial001_py39.py hl[1,7:8] *}
Durch die Deklaration eines *Pfadoperation-Funktionsparameters*, dessen Typ der `Request` ist, weiß **FastAPI**, dass es den `Request` diesem Parameter übergeben soll.
diff --git a/docs/de/docs/advanced/websockets.md b/docs/de/docs/advanced/websockets.md
index 5f662770f0..05ae5a4b31 100644
--- a/docs/de/docs/advanced/websockets.md
+++ b/docs/de/docs/advanced/websockets.md
@@ -38,13 +38,13 @@ In der Produktion hätten Sie eine der oben genannten Optionen.
Aber es ist der einfachste Weg, sich auf die Serverseite von WebSockets zu konzentrieren und ein funktionierendes Beispiel zu haben:
-{* ../../docs_src/websockets/tutorial001.py hl[2,6:38,41:43] *}
+{* ../../docs_src/websockets/tutorial001_py39.py hl[2,6:38,41:43] *}
## Einen `websocket` erstellen { #create-a-websocket }
Erstellen Sie in Ihrer **FastAPI**-Anwendung einen `websocket`:
-{* ../../docs_src/websockets/tutorial001.py hl[1,46:47] *}
+{* ../../docs_src/websockets/tutorial001_py39.py hl[1,46:47] *}
/// note | Technische Details
@@ -58,7 +58,7 @@ Sie könnten auch `from starlette.websockets import WebSocket` verwenden.
In Ihrer WebSocket-Route können Sie Nachrichten `await`en und Nachrichten senden.
-{* ../../docs_src/websockets/tutorial001.py hl[48:52] *}
+{* ../../docs_src/websockets/tutorial001_py39.py hl[48:52] *}
Sie können Binär-, Text- und JSON-Daten empfangen und senden.
diff --git a/docs/de/docs/advanced/wsgi.md b/docs/de/docs/advanced/wsgi.md
index 1de9739dde..3cd776a6ab 100644
--- a/docs/de/docs/advanced/wsgi.md
+++ b/docs/de/docs/advanced/wsgi.md
@@ -12,7 +12,7 @@ Wrappen Sie dann die WSGI-Anwendung (z. B. Flask) mit der Middleware.
Und dann mounten Sie das auf einem Pfad.
-{* ../../docs_src/wsgi/tutorial001.py hl[2:3,3] *}
+{* ../../docs_src/wsgi/tutorial001_py39.py hl[2:3,3] *}
## Es testen { #check-it }
diff --git a/docs/de/docs/how-to/conditional-openapi.md b/docs/de/docs/how-to/conditional-openapi.md
index f6a2fad3bc..6e665cc4c0 100644
--- a/docs/de/docs/how-to/conditional-openapi.md
+++ b/docs/de/docs/how-to/conditional-openapi.md
@@ -29,7 +29,7 @@ Sie können problemlos dieselben Pydantic-Einstellungen verwenden, um Ihre gener
Zum Beispiel:
-{* ../../docs_src/conditional_openapi/tutorial001.py hl[6,11] *}
+{* ../../docs_src/conditional_openapi/tutorial001_py39.py hl[6,11] *}
Hier deklarieren wir die Einstellung `openapi_url` mit dem gleichen Defaultwert `"/openapi.json"`.
diff --git a/docs/de/docs/how-to/configure-swagger-ui.md b/docs/de/docs/how-to/configure-swagger-ui.md
index 3616f03ac4..1c3f5c0c5a 100644
--- a/docs/de/docs/how-to/configure-swagger-ui.md
+++ b/docs/de/docs/how-to/configure-swagger-ui.md
@@ -18,7 +18,7 @@ Ohne Änderung der Einstellungen ist die Syntaxhervorhebung standardmäßig akti
Sie können sie jedoch deaktivieren, indem Sie `syntaxHighlight` auf `False` setzen:
-{* ../../docs_src/configure_swagger_ui/tutorial001.py hl[3] *}
+{* ../../docs_src/configure_swagger_ui/tutorial001_py39.py hl[3] *}
... und dann zeigt die Swagger-Oberfläche die Syntaxhervorhebung nicht mehr an:
@@ -28,7 +28,7 @@ Sie können sie jedoch deaktivieren, indem Sie `syntaxHighlight` auf `False` set
Auf die gleiche Weise könnten Sie das Theme der Syntaxhervorhebung mit dem Schlüssel `"syntaxHighlight.theme"` festlegen (beachten Sie, dass er einen Punkt in der Mitte hat):
-{* ../../docs_src/configure_swagger_ui/tutorial002.py hl[3] *}
+{* ../../docs_src/configure_swagger_ui/tutorial002_py39.py hl[3] *}
Obige Konfiguration würde das Theme für die Farbe der Syntaxhervorhebung ändern:
@@ -46,7 +46,7 @@ Sie können jede davon überschreiben, indem Sie im Argument `swagger_ui_paramet
Um beispielsweise `deepLinking` zu deaktivieren, könnten Sie folgende Einstellungen an `swagger_ui_parameters` übergeben:
-{* ../../docs_src/configure_swagger_ui/tutorial003.py hl[3] *}
+{* ../../docs_src/configure_swagger_ui/tutorial003_py39.py hl[3] *}
## Andere Parameter der Swagger-Oberfläche { #other-swagger-ui-parameters }
diff --git a/docs/de/docs/how-to/custom-docs-ui-assets.md b/docs/de/docs/how-to/custom-docs-ui-assets.md
index 6b8b1a1767..6b1d654adf 100644
--- a/docs/de/docs/how-to/custom-docs-ui-assets.md
+++ b/docs/de/docs/how-to/custom-docs-ui-assets.md
@@ -18,7 +18,7 @@ Der erste Schritt besteht darin, die automatischen Dokumentationen zu deaktivier
Um diese zu deaktivieren, setzen Sie deren URLs beim Erstellen Ihrer `FastAPI`-App auf `None`:
-{* ../../docs_src/custom_docs_ui/tutorial001.py hl[8] *}
+{* ../../docs_src/custom_docs_ui/tutorial001_py39.py hl[8] *}
### Die benutzerdefinierten Dokumentationen hinzufügen { #include-the-custom-docs }
@@ -34,7 +34,7 @@ Sie können die internen Funktionen von FastAPI wiederverwenden, um die HTML-Sei
Und ähnlich für ReDoc ...
-{* ../../docs_src/custom_docs_ui/tutorial001.py hl[2:6,11:19,22:24,27:33] *}
+{* ../../docs_src/custom_docs_ui/tutorial001_py39.py hl[2:6,11:19,22:24,27:33] *}
/// tip | Tipp
@@ -50,7 +50,7 @@ Swagger UI erledigt das hinter den Kulissen für Sie, benötigt aber diesen „U
Um nun testen zu können, ob alles funktioniert, erstellen Sie eine *Pfadoperation*:
-{* ../../docs_src/custom_docs_ui/tutorial001.py hl[36:38] *}
+{* ../../docs_src/custom_docs_ui/tutorial001_py39.py hl[36:38] *}
### Es testen { #test-it }
@@ -118,7 +118,7 @@ Danach könnte Ihre Dateistruktur wie folgt aussehen:
* Importieren Sie `StaticFiles`.
* „Mounten“ Sie eine `StaticFiles()`-Instanz in einem bestimmten Pfad.
-{* ../../docs_src/custom_docs_ui/tutorial002.py hl[7,11] *}
+{* ../../docs_src/custom_docs_ui/tutorial002_py39.py hl[7,11] *}
### Die statischen Dateien testen { #test-the-static-files }
@@ -144,7 +144,7 @@ Wie bei der Verwendung eines benutzerdefinierten CDN besteht der erste Schritt d
Um sie zu deaktivieren, setzen Sie deren URLs beim Erstellen Ihrer `FastAPI`-App auf `None`:
-{* ../../docs_src/custom_docs_ui/tutorial002.py hl[9] *}
+{* ../../docs_src/custom_docs_ui/tutorial002_py39.py hl[9] *}
### Die benutzerdefinierten Dokumentationen für statische Dateien hinzufügen { #include-the-custom-docs-for-static-files }
@@ -160,7 +160,7 @@ Auch hier können Sie die internen Funktionen von FastAPI wiederverwenden, um di
Und ähnlich für ReDoc ...
-{* ../../docs_src/custom_docs_ui/tutorial002.py hl[2:6,14:22,25:27,30:36] *}
+{* ../../docs_src/custom_docs_ui/tutorial002_py39.py hl[2:6,14:22,25:27,30:36] *}
/// tip | Tipp
@@ -176,7 +176,7 @@ Swagger UI erledigt das hinter den Kulissen für Sie, benötigt aber diesen „U
Um nun testen zu können, ob alles funktioniert, erstellen Sie eine *Pfadoperation*:
-{* ../../docs_src/custom_docs_ui/tutorial002.py hl[39:41] *}
+{* ../../docs_src/custom_docs_ui/tutorial002_py39.py hl[39:41] *}
### Benutzeroberfläche mit statischen Dateien testen { #test-static-files-ui }
diff --git a/docs/de/docs/how-to/extending-openapi.md b/docs/de/docs/how-to/extending-openapi.md
index 146ee098bc..c07ed2aa08 100644
--- a/docs/de/docs/how-to/extending-openapi.md
+++ b/docs/de/docs/how-to/extending-openapi.md
@@ -43,19 +43,19 @@ Fügen wir beispielsweise Requests verwendet.
-{* ../../docs_src/extending_openapi/tutorial001.py hl[13:14,25:26] *}
+{* ../../docs_src/extending_openapi/tutorial001_py39.py hl[13:14,25:26] *}
### Die Methode überschreiben { #override-the-method }
Jetzt können Sie die Methode `.openapi()` durch Ihre neue Funktion ersetzen.
-{* ../../docs_src/extending_openapi/tutorial001.py hl[29] *}
+{* ../../docs_src/extending_openapi/tutorial001_py39.py hl[29] *}
### Es testen { #check-it }
diff --git a/docs/de/docs/how-to/graphql.md b/docs/de/docs/how-to/graphql.md
index d2958dcd9e..5c908cec4a 100644
--- a/docs/de/docs/how-to/graphql.md
+++ b/docs/de/docs/how-to/graphql.md
@@ -35,7 +35,7 @@ Abhängig von Ihrem Anwendungsfall könnten Sie eine andere Bibliothek vorziehen
Hier ist eine kleine Vorschau, wie Sie Strawberry mit FastAPI integrieren können:
-{* ../../docs_src/graphql/tutorial001.py hl[3,22,25] *}
+{* ../../docs_src/graphql_/tutorial001_py39.py hl[3,22,25] *}
Weitere Informationen zu Strawberry finden Sie in der Strawberry-Dokumentation.
diff --git a/docs/de/docs/how-to/migrate-from-pydantic-v1-to-pydantic-v2.md b/docs/de/docs/how-to/migrate-from-pydantic-v1-to-pydantic-v2.md
index 7f60492ee9..a8eff3b2b0 100644
--- a/docs/de/docs/how-to/migrate-from-pydantic-v1-to-pydantic-v2.md
+++ b/docs/de/docs/how-to/migrate-from-pydantic-v1-to-pydantic-v2.md
@@ -2,21 +2,23 @@
Wenn Sie eine ältere FastAPI-App haben, nutzen Sie möglicherweise Pydantic Version 1.
-FastAPI unterstützt seit Version 0.100.0 sowohl Pydantic v1 als auch v2.
+FastAPI Version 0.100.0 unterstützte sowohl Pydantic v1 als auch v2. Es verwendete, was auch immer Sie installiert hatten.
-Wenn Sie Pydantic v2 installiert hatten, wurde dieses verwendet. Wenn stattdessen Pydantic v1 installiert war, wurde jenes verwendet.
+FastAPI Version 0.119.0 führte eine teilweise Unterstützung für Pydantic v1 innerhalb von Pydantic v2 (als `pydantic.v1`) ein, um die Migration zu v2 zu erleichtern.
-Pydantic v1 ist jetzt deprecatet und die Unterstützung dafür wird in den nächsten Versionen von FastAPI entfernt, Sie sollten also zu **Pydantic v2 migrieren**. Auf diese Weise erhalten Sie die neuesten Features, Verbesserungen und Fixes.
+FastAPI 0.126.0 entfernte die Unterstützung für Pydantic v1, während `pydantic.v1` noch eine Weile unterstützt wurde.
/// warning | Achtung
-Außerdem hat das Pydantic-Team die Unterstützung für Pydantic v1 in den neuesten Python-Versionen eingestellt, beginnend mit **Python 3.14**.
+Das Pydantic-Team hat die Unterstützung für Pydantic v1 in den neuesten Python-Versionen eingestellt, beginnend mit **Python 3.14**.
+
+Dies schließt `pydantic.v1` ein, das unter Python 3.14 und höher nicht mehr unterstützt wird.
Wenn Sie die neuesten Features von Python nutzen möchten, müssen Sie sicherstellen, dass Sie Pydantic v2 verwenden.
///
-Wenn Sie eine ältere FastAPI-App mit Pydantic v1 haben, zeige ich Ihnen hier, wie Sie sie zu Pydantic v2 migrieren, und die **neuen Features in FastAPI 0.119.0**, die Ihnen bei einer schrittweisen Migration helfen.
+Wenn Sie eine ältere FastAPI-App mit Pydantic v1 haben, zeige ich Ihnen hier, wie Sie sie zu Pydantic v2 migrieren, und die **Features in FastAPI 0.119.0**, die Ihnen bei einer schrittweisen Migration helfen.
## Offizieller Leitfaden { #official-guide }
@@ -44,7 +46,7 @@ Danach können Sie die Tests ausführen und prüfen, ob alles funktioniert. Fall
## Pydantic v1 in v2 { #pydantic-v1-in-v2 }
-Pydantic v2 enthält alles aus Pydantic v1 als Untermodul `pydantic.v1`.
+Pydantic v2 enthält alles aus Pydantic v1 als Untermodul `pydantic.v1`. Dies wird aber in Versionen oberhalb von Python 3.13 nicht mehr unterstützt.
Das bedeutet, Sie können die neueste Version von Pydantic v2 installieren und die alten Pydantic‑v1‑Komponenten aus diesem Untermodul importieren und verwenden, als hätten Sie das alte Pydantic v1 installiert.
diff --git a/docs/de/docs/how-to/separate-openapi-schemas.md b/docs/de/docs/how-to/separate-openapi-schemas.md
index 31653590b5..16f9c8a144 100644
--- a/docs/de/docs/how-to/separate-openapi-schemas.md
+++ b/docs/de/docs/how-to/separate-openapi-schemas.md
@@ -1,6 +1,6 @@
# Separate OpenAPI-Schemas für Eingabe und Ausgabe oder nicht { #separate-openapi-schemas-for-input-and-output-or-not }
-Bei Verwendung von **Pydantic v2** ist die generierte OpenAPI etwas genauer und **korrekter** als zuvor. 😎
+Seit der Veröffentlichung von **Pydantic v2** ist die generierte OpenAPI etwas genauer und **korrekter** als zuvor. 😎
Tatsächlich gibt es in einigen Fällen sogar **zwei JSON-Schemas** in OpenAPI für dasselbe Pydantic-Modell, für Eingabe und Ausgabe, je nachdem, ob sie **Defaultwerte** haben.
@@ -100,5 +100,3 @@ Und jetzt wird es ein einziges Schema für die Eingabe und Ausgabe des Modells g
-
-Dies ist das gleiche Verhalten wie in Pydantic v1. 🤓
diff --git a/docs/de/docs/index.md b/docs/de/docs/index.md
index 1920df8ff3..11fb6c9832 100644
--- a/docs/de/docs/index.md
+++ b/docs/de/docs/index.md
@@ -117,6 +117,12 @@ Seine Schlüssel-Merkmale sind:
---
+## FastAPI Mini-Dokumentarfilm { #fastapi-mini-documentary }
+
+Es gibt einen FastAPI-Mini-Dokumentarfilm, veröffentlicht Ende 2025, Sie können ihn online ansehen:
+
+
+
## **Typer**, das FastAPI der CLIs { #typer-the-fastapi-of-clis }
@@ -233,7 +239,7 @@ INFO: Application startup complete.
-Was der Befehl fastapi dev main.py macht ...
+Über den Befehl fastapi dev main.py ...
Der Befehl `fastapi dev` liest Ihre `main.py`-Datei, erkennt die **FastAPI**-App darin und startet einen Server mit Uvicorn.
@@ -276,7 +282,7 @@ Sie sehen die alternative automatische Dokumentation (bereitgestellt von Body eines `PUT`-Requests zu empfangen.
@@ -326,7 +332,7 @@ Gehen Sie jetzt auf Dependency Injection**.
+* Ein sehr leistungsfähiges und einfach zu bedienendes System für **Dependency Injection**.
* Sicherheit und Authentifizierung, einschließlich Unterstützung für **OAuth2** mit **JWT-Tokens** und **HTTP Basic** Authentifizierung.
* Fortgeschrittenere (aber ebenso einfache) Techniken zur Deklaration **tief verschachtelter JSON-Modelle** (dank Pydantic).
* **GraphQL**-Integration mit Strawberry und anderen Bibliotheken.
@@ -452,7 +458,7 @@ Für ein vollständigeres Beispiel, mit weiteren Funktionen, siehe das FastAPI Cloud deployen, treten Sie der Warteliste bei, falls noch nicht geschehen. 🚀
+Optional können Sie Ihre FastAPI-App in die FastAPI Cloud deployen, gehen Sie und treten Sie der Warteliste bei, falls noch nicht geschehen. 🚀
Wenn Sie bereits ein **FastAPI Cloud**-Konto haben (wir haben Sie von der Warteliste eingeladen 😉), können Sie Ihre Anwendung mit einem einzigen Befehl deployen.
@@ -494,7 +500,7 @@ Es vereinfacht den Prozess des **Erstellens**, **Deployens** und **Zugreifens**
Es bringt die gleiche **Developer-Experience** beim Erstellen von Apps mit FastAPI auch zum **Deployment** in der Cloud. 🎉
-FastAPI Cloud ist der Hauptsponsor und Finanzierer der „FastAPI and friends“ Open-Source-Projekte. ✨
+FastAPI Cloud ist der Hauptsponsor und Finanzierer der *FastAPI and friends* Open-Source-Projekte. ✨
#### Bei anderen Cloudanbietern deployen { #deploy-to-other-cloud-providers }
diff --git a/docs/de/docs/project-generation.md b/docs/de/docs/project-generation.md
index 290f605b38..62702d8529 100644
--- a/docs/de/docs/project-generation.md
+++ b/docs/de/docs/project-generation.md
@@ -13,7 +13,7 @@ GitHub-Repository: Verkettet sie mit einem Leerzeichen in der Mitte.
+* Verkettet sie mit einem Leerzeichen in der Mitte.
-{* ../../docs_src/python_types/tutorial001.py hl[2] *}
+{* ../../docs_src/python_types/tutorial001_py39.py hl[2] *}
### Es bearbeiten { #edit-it }
@@ -78,7 +78,7 @@ Das war's.
Das sind die „Typhinweise“:
-{* ../../docs_src/python_types/tutorial002.py hl[1] *}
+{* ../../docs_src/python_types/tutorial002_py39.py hl[1] *}
Das ist nicht das gleiche wie das Deklarieren von Defaultwerten, wie es hier der Fall ist:
@@ -106,7 +106,7 @@ Hier können Sie durch die Optionen blättern, bis Sie diejenige finden, bei der
Sehen Sie sich diese Funktion an, sie hat bereits Typhinweise:
-{* ../../docs_src/python_types/tutorial003.py hl[1] *}
+{* ../../docs_src/python_types/tutorial003_py39.py hl[1] *}
Da der Editor die Typen der Variablen kennt, erhalten Sie nicht nur Code-Vervollständigung, sondern auch eine Fehlerprüfung:
@@ -114,7 +114,7 @@ Da der Editor die Typen der Variablen kennt, erhalten Sie nicht nur Code-Vervoll
Jetzt, da Sie wissen, dass Sie das reparieren müssen, konvertieren Sie `age` mittels `str(age)` in einen String:
-{* ../../docs_src/python_types/tutorial004.py hl[2] *}
+{* ../../docs_src/python_types/tutorial004_py39.py hl[2] *}
## Deklarieren von Typen { #declaring-types }
@@ -133,7 +133,7 @@ Zum Beispiel diese:
* `bool`
* `bytes`
-{* ../../docs_src/python_types/tutorial005.py hl[1] *}
+{* ../../docs_src/python_types/tutorial005_py39.py hl[1] *}
### Generische Typen mit Typ-Parametern { #generic-types-with-type-parameters }
@@ -161,56 +161,24 @@ Wenn Sie über die **neueste Version von Python** verfügen, verwenden Sie die B
Definieren wir zum Beispiel eine Variable, die eine `list` von `str` – eine Liste von Strings – sein soll.
-//// tab | Python 3.9+
-
Deklarieren Sie die Variable mit der gleichen Doppelpunkt-Syntax (`:`).
Als Typ nehmen Sie `list`.
Da die Liste ein Typ ist, welcher innere Typen enthält, werden diese von eckigen Klammern umfasst:
-```Python hl_lines="1"
-{!> ../../docs_src/python_types/tutorial006_py39.py!}
-```
-
-////
-
-//// tab | Python 3.8+
-
-Von `typing` importieren Sie `List` (mit Großbuchstaben `L`):
-
-```Python hl_lines="1"
-{!> ../../docs_src/python_types/tutorial006.py!}
-```
-
-Deklarieren Sie die Variable mit der gleichen Doppelpunkt-Syntax (`:`).
-
-Als Typ nehmen Sie das `List`, das Sie von `typing` importiert haben.
-
-Da die Liste ein Typ ist, welcher innere Typen enthält, werden diese von eckigen Klammern umfasst:
-
-```Python hl_lines="4"
-{!> ../../docs_src/python_types/tutorial006.py!}
-```
-
-////
+{* ../../docs_src/python_types/tutorial006_py39.py hl[1] *}
/// info | Info
Die inneren Typen in den eckigen Klammern werden als „Typ-Parameter“ bezeichnet.
-In diesem Fall ist `str` der Typ-Parameter, der an `List` übergeben wird (oder `list` in Python 3.9 und darüber).
+In diesem Fall ist `str` der Typ-Parameter, der an `list` übergeben wird.
///
Das bedeutet: Die Variable `items` ist eine Liste – `list` – und jedes der Elemente in dieser Liste ist ein String – `str`.
-/// tip | Tipp
-
-Wenn Sie Python 3.9 oder höher verwenden, müssen Sie `List` nicht von `typing` importieren, Sie können stattdessen den regulären `list`-Typ verwenden.
-
-///
-
Auf diese Weise kann Ihr Editor Sie auch bei der Bearbeitung von Einträgen aus der Liste unterstützen:
@@ -225,21 +193,7 @@ Und trotzdem weiß der Editor, dass es sich um ein `str` handelt, und bietet ent
Das Gleiche gilt für die Deklaration eines Tupels – `tuple` – und einer Menge – `set`:
-//// tab | Python 3.9+
-
-```Python hl_lines="1"
-{!> ../../docs_src/python_types/tutorial007_py39.py!}
-```
-
-////
-
-//// tab | Python 3.8+
-
-```Python hl_lines="1 4"
-{!> ../../docs_src/python_types/tutorial007.py!}
-```
-
-////
+{* ../../docs_src/python_types/tutorial007_py39.py hl[1] *}
Das bedeutet:
@@ -254,21 +208,7 @@ Der erste Typ-Parameter ist für die Schlüssel des `dict`.
Der zweite Typ-Parameter ist für die Werte des `dict`:
-//// tab | Python 3.9+
-
-```Python hl_lines="1"
-{!> ../../docs_src/python_types/tutorial008_py39.py!}
-```
-
-////
-
-//// tab | Python 3.8+
-
-```Python hl_lines="1 4"
-{!> ../../docs_src/python_types/tutorial008.py!}
-```
-
-////
+{* ../../docs_src/python_types/tutorial008_py39.py hl[1] *}
Das bedeutet:
@@ -282,7 +222,7 @@ Sie können deklarieren, dass eine Variable einer von **verschiedenen Typen** se
In Python 3.6 und höher (inklusive Python 3.10) können Sie den `Union`-Typ von `typing` verwenden und die möglichen Typen innerhalb der eckigen Klammern auflisten.
-In Python 3.10 gibt es zusätzlich eine **neue Syntax**, die es erlaubt, die möglichen Typen getrennt von einem vertikalen Balken (`|`) aufzulisten.
+In Python 3.10 gibt es zusätzlich eine **neue Syntax**, die es erlaubt, die möglichen Typen getrennt von einem vertikalen Balken (`|`) aufzulisten.
//// tab | Python 3.10+
@@ -292,10 +232,10 @@ In Python 3.10 gibt es zusätzlich eine **neue Syntax**, die es erlaubt, die mö
////
-//// tab | Python 3.8+
+//// tab | Python 3.9+
```Python hl_lines="1 4"
-{!> ../../docs_src/python_types/tutorial008b.py!}
+{!> ../../docs_src/python_types/tutorial008b_py39.py!}
```
////
@@ -309,7 +249,7 @@ Sie können deklarieren, dass ein Wert ein `str`, aber vielleicht auch `None` se
In Python 3.6 und darüber (inklusive Python 3.10) können Sie das deklarieren, indem Sie `Optional` vom `typing` Modul importieren und verwenden.
```Python hl_lines="1 4"
-{!../../docs_src/python_types/tutorial009.py!}
+{!../../docs_src/python_types/tutorial009_py39.py!}
```
Wenn Sie `Optional[str]` anstelle von nur `str` verwenden, wird Ihr Editor Ihnen dabei helfen, Fehler zu erkennen, bei denen Sie annehmen könnten, dass ein Wert immer eine String (`str`) ist, obwohl er auch `None` sein könnte.
@@ -326,18 +266,18 @@ Das bedeutet auch, dass Sie in Python 3.10 `Something | None` verwenden können:
////
-//// tab | Python 3.8+
+//// tab | Python 3.9+
```Python hl_lines="1 4"
-{!> ../../docs_src/python_types/tutorial009.py!}
+{!> ../../docs_src/python_types/tutorial009_py39.py!}
```
////
-//// tab | Python 3.8+ Alternative
+//// tab | Python 3.9+ Alternative
```Python hl_lines="1 4"
-{!> ../../docs_src/python_types/tutorial009b.py!}
+{!> ../../docs_src/python_types/tutorial009b_py39.py!}
```
////
@@ -353,11 +293,11 @@ Beide sind äquivalent und im Hintergrund dasselbe, aber ich empfehle `Union` st
Ich denke, `Union[SomeType, None]` ist expliziter bezüglich seiner Bedeutung.
-Es geht nur um Wörter und Namen. Aber diese Worte können beeinflussen, wie Sie und Ihre Teamkollegen über den Code denken.
+Es geht nur um Worte und Namen. Aber diese Worte können beeinflussen, wie Sie und Ihre Teamkollegen über den Code denken.
Nehmen wir zum Beispiel diese Funktion:
-{* ../../docs_src/python_types/tutorial009c.py hl[1,4] *}
+{* ../../docs_src/python_types/tutorial009c_py39.py hl[1,4] *}
Der Parameter `name` ist definiert als `Optional[str]`, aber er ist **nicht optional**, Sie können die Funktion nicht ohne diesen Parameter aufrufen:
@@ -390,13 +330,13 @@ Sie können die eingebauten Typen als Generics verwenden (mit eckigen Klammern u
* `set`
* `dict`
-Verwenden Sie für den Rest, wie unter Python 3.8, das `typing`-Modul:
+Und ebenso wie bei früheren Python-Versionen, aus dem `typing`-Modul:
* `Union`
-* `Optional` (so wie unter Python 3.8)
+* `Optional`
* ... und andere.
-In Python 3.10 können Sie als Alternative zu den Generics `Union` und `Optional` den vertikalen Balken (`|`) verwenden, um Vereinigungen von Typen zu deklarieren, das ist besser und einfacher.
+In Python 3.10 können Sie als Alternative zu den Generics `Union` und `Optional` den vertikalen Balken (`|`) verwenden, um Vereinigungen von Typen zu deklarieren, das ist besser und einfacher.
////
@@ -409,7 +349,7 @@ Sie können die eingebauten Typen als Generics verwenden (mit eckigen Klammern u
* `set`
* `dict`
-Verwenden Sie für den Rest, wie unter Python 3.8, das `typing`-Modul:
+Und Generics aus dem `typing`-Modul:
* `Union`
* `Optional`
@@ -417,29 +357,17 @@ Verwenden Sie für den Rest, wie unter Python 3.8, das `typing`-Modul:
////
-//// tab | Python 3.8+
-
-* `List`
-* `Tuple`
-* `Set`
-* `Dict`
-* `Union`
-* `Optional`
-* ... und andere.
-
-////
-
### Klassen als Typen { #classes-as-types }
Sie können auch eine Klasse als Typ einer Variablen deklarieren.
Nehmen wir an, Sie haben eine Klasse `Person`, mit einem Namen:
-{* ../../docs_src/python_types/tutorial010.py hl[1:3] *}
+{* ../../docs_src/python_types/tutorial010_py39.py hl[1:3] *}
Dann können Sie eine Variable vom Typ `Person` deklarieren:
-{* ../../docs_src/python_types/tutorial010.py hl[6] *}
+{* ../../docs_src/python_types/tutorial010_py39.py hl[6] *}
Und wiederum bekommen Sie die volle Editor-Unterstützung:
@@ -463,29 +391,7 @@ Und Sie erhalten volle Editor-Unterstützung für dieses Objekt.
Ein Beispiel aus der offiziellen Pydantic Dokumentation:
-//// tab | Python 3.10+
-
-```Python
-{!> ../../docs_src/python_types/tutorial011_py310.py!}
-```
-
-////
-
-//// tab | Python 3.9+
-
-```Python
-{!> ../../docs_src/python_types/tutorial011_py39.py!}
-```
-
-////
-
-//// tab | Python 3.8+
-
-```Python
-{!> ../../docs_src/python_types/tutorial011.py!}
-```
-
-////
+{* ../../docs_src/python_types/tutorial011_py310.py *}
/// info | Info
@@ -507,27 +413,9 @@ Pydantic verhält sich speziell, wenn Sie `Optional` oder `Union[Something, None
Python bietet auch die Möglichkeit, **zusätzliche Metadaten** in Typhinweisen unterzubringen, mittels `Annotated`.
-//// tab | Python 3.9+
+Seit Python 3.9 ist `Annotated` ein Teil der Standardbibliothek, Sie können es von `typing` importieren.
-In Python 3.9 ist `Annotated` ein Teil der Standardbibliothek, Sie können es von `typing` importieren.
-
-```Python hl_lines="1 4"
-{!> ../../docs_src/python_types/tutorial013_py39.py!}
-```
-
-////
-
-//// tab | Python 3.8+
-
-In Versionen niedriger als Python 3.9 importieren Sie `Annotated` von `typing_extensions`.
-
-Es wird bereits mit **FastAPI** installiert sein.
-
-```Python hl_lines="1 4"
-{!> ../../docs_src/python_types/tutorial013.py!}
-```
-
-////
+{* ../../docs_src/python_types/tutorial013_py39.py hl[1,4] *}
Python selbst macht nichts mit `Annotated`. Für Editoren und andere Tools ist der Typ immer noch `str`.
diff --git a/docs/de/docs/tutorial/background-tasks.md b/docs/de/docs/tutorial/background-tasks.md
index 2c381ccfac..1d34430dc6 100644
--- a/docs/de/docs/tutorial/background-tasks.md
+++ b/docs/de/docs/tutorial/background-tasks.md
@@ -15,7 +15,7 @@ Hierzu zählen beispielsweise:
Importieren Sie zunächst `BackgroundTasks` und definieren Sie einen Parameter in Ihrer *Pfadoperation-Funktion* mit der Typdeklaration `BackgroundTasks`:
-{* ../../docs_src/background_tasks/tutorial001.py hl[1,13] *}
+{* ../../docs_src/background_tasks/tutorial001_py39.py hl[1,13] *}
**FastAPI** erstellt für Sie das Objekt vom Typ `BackgroundTasks` und übergibt es als diesen Parameter.
@@ -31,13 +31,13 @@ In diesem Fall schreibt die Taskfunktion in eine Datei (den Versand einer E-Mail
Und da der Schreibvorgang nicht `async` und `await` verwendet, definieren wir die Funktion mit normalem `def`:
-{* ../../docs_src/background_tasks/tutorial001.py hl[6:9] *}
+{* ../../docs_src/background_tasks/tutorial001_py39.py hl[6:9] *}
## Den Hintergrundtask hinzufügen { #add-the-background-task }
Übergeben Sie innerhalb Ihrer *Pfadoperation-Funktion* Ihre Taskfunktion mit der Methode `.add_task()` an das *Hintergrundtasks*-Objekt:
-{* ../../docs_src/background_tasks/tutorial001.py hl[14] *}
+{* ../../docs_src/background_tasks/tutorial001_py39.py hl[14] *}
`.add_task()` erhält als Argumente:
diff --git a/docs/de/docs/tutorial/body-nested-models.md b/docs/de/docs/tutorial/body-nested-models.md
index 324d31928d..65a5d7c1de 100644
--- a/docs/de/docs/tutorial/body-nested-models.md
+++ b/docs/de/docs/tutorial/body-nested-models.md
@@ -14,35 +14,14 @@ Das bewirkt, dass `tags` eine Liste ist, wenngleich es nichts über den Typ der
Aber Python erlaubt es, Listen mit inneren Typen, auch „Typ-Parameter“ genannt, zu deklarieren.
-### `List` von `typing` importieren { #import-typings-list }
-
-In Python 3.9 oder darüber können Sie einfach `list` verwenden, um diese Typannotationen zu deklarieren, wie wir unten sehen werden. 💡
-
-In Python-Versionen vor 3.9 (3.6 und darüber), müssen Sie zuerst `List` von Pythons Standardmodul `typing` importieren.
-
-{* ../../docs_src/body_nested_models/tutorial002.py hl[1] *}
-
### Eine `list` mit einem Typ-Parameter deklarieren { #declare-a-list-with-a-type-parameter }
-Um Typen wie `list`, `dict`, `tuple` mit inneren Typ-Parametern (inneren Typen) zu deklarieren:
-
-* Wenn Sie eine Python-Version kleiner als 3.9 verwenden, importieren Sie das Äquivalent zum entsprechenden Typ vom `typing`-Modul
-* Überreichen Sie den/die inneren Typ(en) von eckigen Klammern umschlossen, `[` und `]`, als „Typ-Parameter“
-
-In Python 3.9 wäre das:
+Um Typen zu deklarieren, die Typ-Parameter (innere Typen) haben, wie `list`, `dict`, `tuple`, übergeben Sie den/die inneren Typ(en) als „Typ-Parameter“ in eckigen Klammern: `[` und `]`
```Python
my_list: list[str]
```
-Und in Python-Versionen vor 3.9:
-
-```Python
-from typing import List
-
-my_list: List[str]
-```
-
Das ist alles Standard-Python-Syntax für Typdeklarationen.
Verwenden Sie dieselbe Standardsyntax für Modellattribute mit inneren Typen.
@@ -178,12 +157,6 @@ Beachten Sie, wie `Offer` eine Liste von `Item`s hat, die ihrerseits eine option
Wenn das äußerste Element des JSON-Bodys, das Sie erwarten, ein JSON-`array` (eine Python-`list`) ist, können Sie den Typ im Funktionsparameter deklarieren, mit der gleichen Syntax wie in Pydantic-Modellen:
-```Python
-images: List[Image]
-```
-
-oder in Python 3.9 und darüber:
-
```Python
images: list[Image]
```
diff --git a/docs/de/docs/tutorial/body-updates.md b/docs/de/docs/tutorial/body-updates.md
index aa62199feb..d260998e91 100644
--- a/docs/de/docs/tutorial/body-updates.md
+++ b/docs/de/docs/tutorial/body-updates.md
@@ -50,14 +50,6 @@ Wenn Sie Teil-Aktualisierungen entgegennehmen, ist der `exclude_unset`-Parameter
Wie in `item.model_dump(exclude_unset=True)`.
-/// info | Info
-
-In Pydantic v1 hieß diese Methode `.dict()`, in Pydantic v2 wurde sie deprecatet (aber immer noch unterstützt) und in `.model_dump()` umbenannt.
-
-Die Beispiele hier verwenden `.dict()` für die Kompatibilität mit Pydantic v1, Sie sollten jedoch stattdessen `.model_dump()` verwenden, wenn Sie Pydantic v2 verwenden können.
-
-///
-
Das wird ein `dict` erstellen, mit nur den Daten, die gesetzt wurden, als das `item`-Modell erstellt wurde, Defaultwerte ausgeschlossen.
Sie können das verwenden, um ein `dict` zu erstellen, das nur die (im Request) gesendeten Daten enthält, ohne Defaultwerte:
@@ -68,14 +60,6 @@ Sie können das verwenden, um ein `dict` zu erstellen, das nur die (im deprecatet (aber immer noch unterstützt) und in `.model_copy()` umbenannt.
-
-Die Beispiele hier verwenden `.copy()` für die Kompatibilität mit Pydantic v1, Sie sollten jedoch stattdessen `.model_copy()` verwenden, wenn Sie Pydantic v2 verwenden können.
-
-///
-
Wie in `stored_item_model.model_copy(update=update_data)`:
{* ../../docs_src/body_updates/tutorial002_py310.py hl[33] *}
diff --git a/docs/de/docs/tutorial/body.md b/docs/de/docs/tutorial/body.md
index 1e6382b6f2..cdf3122f2f 100644
--- a/docs/de/docs/tutorial/body.md
+++ b/docs/de/docs/tutorial/body.md
@@ -127,14 +127,6 @@ Innerhalb der Funktion können Sie alle Attribute des Modellobjekts direkt verwe
{* ../../docs_src/body/tutorial002_py310.py *}
-/// info | Info
-
-In Pydantic v1 hieß die Methode `.dict()`, sie wurde in Pydantic v2 deprecatet (aber weiterhin unterstützt) und in `.model_dump()` umbenannt.
-
-Die Beispiele hier verwenden `.dict()` zur Kompatibilität mit Pydantic v1, aber Sie sollten stattdessen `.model_dump()` verwenden, wenn Sie Pydantic v2 nutzen können.
-
-///
-
## Requestbody- + Pfad-Parameter { #request-body-path-parameters }
Sie können Pfad-Parameter und den Requestbody gleichzeitig deklarieren.
@@ -162,7 +154,7 @@ Die Funktionsparameter werden wie folgt erkannt:
FastAPI weiß, dass der Wert von `q` nicht erforderlich ist, aufgrund des definierten Defaultwertes `= None`.
-Das `str | None` (Python 3.10+) oder `Union` in `Union[str, None]` (Python 3.8+) wird von FastAPI nicht verwendet, um zu bestimmen, dass der Wert nicht erforderlich ist. FastAPI weiß, dass er nicht erforderlich ist, weil er einen Defaultwert von `= None` hat.
+Das `str | None` (Python 3.10+) oder `Union` in `Union[str, None]` (Python 3.9+) wird von FastAPI nicht verwendet, um zu bestimmen, dass der Wert nicht erforderlich ist. FastAPI weiß, dass er nicht erforderlich ist, weil er einen Defaultwert von `= None` hat.
Das Hinzufügen der Typannotationen ermöglicht jedoch Ihrem Editor, Ihnen eine bessere Unterstützung zu bieten und Fehler zu erkennen.
diff --git a/docs/de/docs/tutorial/cors.md b/docs/de/docs/tutorial/cors.md
index 191a7b4ef3..81f0f36051 100644
--- a/docs/de/docs/tutorial/cors.md
+++ b/docs/de/docs/tutorial/cors.md
@@ -46,7 +46,7 @@ Sie können auch angeben, ob Ihr Backend erlaubt:
* Bestimmte HTTP-Methoden (`POST`, `PUT`) oder alle mit der Wildcard `"*"`.
* Bestimmte HTTP-Header oder alle mit der Wildcard `"*"`.
-{* ../../docs_src/cors/tutorial001.py hl[2,6:11,13:19] *}
+{* ../../docs_src/cors/tutorial001_py39.py hl[2,6:11,13:19] *}
Die von der `CORSMiddleware`-Implementierung verwendeten Defaultparameter sind standardmäßig restriktiv, daher müssen Sie bestimmte Origins, Methoden oder Header ausdrücklich aktivieren, damit Browser sie in einem Cross-Domain-Kontext verwenden dürfen.
diff --git a/docs/de/docs/tutorial/debugging.md b/docs/de/docs/tutorial/debugging.md
index 0a31f86536..0d12877c10 100644
--- a/docs/de/docs/tutorial/debugging.md
+++ b/docs/de/docs/tutorial/debugging.md
@@ -6,7 +6,7 @@ Sie können den Debugger in Ihrem Editor verbinden, zum Beispiel mit Visual Stud
Importieren und führen Sie `uvicorn` direkt in Ihrer FastAPI-Anwendung aus:
-{* ../../docs_src/debugging/tutorial001.py hl[1,15] *}
+{* ../../docs_src/debugging/tutorial001_py39.py hl[1,15] *}
### Über `__name__ == "__main__"` { #about-name-main }
diff --git a/docs/de/docs/tutorial/dependencies/classes-as-dependencies.md b/docs/de/docs/tutorial/dependencies/classes-as-dependencies.md
index 3d4493f353..7df0842eb1 100644
--- a/docs/de/docs/tutorial/dependencies/classes-as-dependencies.md
+++ b/docs/de/docs/tutorial/dependencies/classes-as-dependencies.md
@@ -101,7 +101,7 @@ Jetzt können Sie Ihre Abhängigkeit mithilfe dieser Klasse deklarieren.
Beachten Sie, wie wir `CommonQueryParams` im obigen Code zweimal schreiben:
-//// tab | Python 3.8+
+//// tab | Python 3.9+
```Python
commons: Annotated[CommonQueryParams, Depends(CommonQueryParams)]
@@ -109,7 +109,7 @@ commons: Annotated[CommonQueryParams, Depends(CommonQueryParams)]
////
-//// tab | Python 3.8+ nicht annotiert
+//// tab | Python 3.9+ nicht annotiert
/// tip | Tipp
@@ -137,7 +137,7 @@ Aus diesem extrahiert FastAPI die deklarierten Parameter, und dieses ist es, was
In diesem Fall hat das erste `CommonQueryParams` in:
-//// tab | Python 3.8+
+//// tab | Python 3.9+
```Python
commons: Annotated[CommonQueryParams, ...
@@ -145,7 +145,7 @@ commons: Annotated[CommonQueryParams, ...
////
-//// tab | Python 3.8+ nicht annotiert
+//// tab | Python 3.9+ nicht annotiert
/// tip | Tipp
@@ -163,7 +163,7 @@ commons: CommonQueryParams ...
Sie könnten tatsächlich einfach schreiben:
-//// tab | Python 3.8+
+//// tab | Python 3.9+
```Python
commons: Annotated[Any, Depends(CommonQueryParams)]
@@ -171,7 +171,7 @@ commons: Annotated[Any, Depends(CommonQueryParams)]
////
-//// tab | Python 3.8+ nicht annotiert
+//// tab | Python 3.9+ nicht annotiert
/// tip | Tipp
@@ -197,7 +197,7 @@ Es wird jedoch empfohlen, den Typ zu deklarieren, da Ihr Editor so weiß, was al
Aber Sie sehen, dass wir hier etwas Codeduplizierung haben, indem wir `CommonQueryParams` zweimal schreiben:
-//// tab | Python 3.8+
+//// tab | Python 3.9+
```Python
commons: Annotated[CommonQueryParams, Depends(CommonQueryParams)]
@@ -205,7 +205,7 @@ commons: Annotated[CommonQueryParams, Depends(CommonQueryParams)]
////
-//// tab | Python 3.8+ nicht annotiert
+//// tab | Python 3.9+ nicht annotiert
/// tip | Tipp
@@ -225,7 +225,7 @@ In diesem speziellen Fall können Sie Folgendes tun:
Anstatt zu schreiben:
-//// tab | Python 3.8+
+//// tab | Python 3.9+
```Python
commons: Annotated[CommonQueryParams, Depends(CommonQueryParams)]
@@ -233,7 +233,7 @@ commons: Annotated[CommonQueryParams, Depends(CommonQueryParams)]
////
-//// tab | Python 3.8+ nicht annotiert
+//// tab | Python 3.9+ nicht annotiert
/// tip | Tipp
@@ -249,7 +249,7 @@ commons: CommonQueryParams = Depends(CommonQueryParams)
... schreiben Sie:
-//// tab | Python 3.8+
+//// tab | Python 3.9+
```Python
commons: Annotated[CommonQueryParams, Depends()]
@@ -257,7 +257,7 @@ commons: Annotated[CommonQueryParams, Depends()]
////
-//// tab | Python 3.8 nicht annotiert
+//// tab | Python 3.9+ nicht annotiert
/// tip | Tipp
diff --git a/docs/de/docs/tutorial/dependencies/dependencies-with-yield.md b/docs/de/docs/tutorial/dependencies/dependencies-with-yield.md
index 34db6c6bed..0083e7e7ea 100644
--- a/docs/de/docs/tutorial/dependencies/dependencies-with-yield.md
+++ b/docs/de/docs/tutorial/dependencies/dependencies-with-yield.md
@@ -29,15 +29,15 @@ Sie könnten damit beispielsweise eine Datenbanksession erstellen und diese nach
Nur der Code vor und einschließlich der `yield`-Anweisung wird ausgeführt, bevor eine Response erzeugt wird:
-{* ../../docs_src/dependencies/tutorial007.py hl[2:4] *}
+{* ../../docs_src/dependencies/tutorial007_py39.py hl[2:4] *}
Der ge`yield`ete Wert ist das, was in *Pfadoperationen* und andere Abhängigkeiten eingefügt wird:
-{* ../../docs_src/dependencies/tutorial007.py hl[4] *}
+{* ../../docs_src/dependencies/tutorial007_py39.py hl[4] *}
Der auf die `yield`-Anweisung folgende Code wird nach der Response ausgeführt:
-{* ../../docs_src/dependencies/tutorial007.py hl[5:6] *}
+{* ../../docs_src/dependencies/tutorial007_py39.py hl[5:6] *}
/// tip | Tipp
@@ -57,7 +57,7 @@ Sie können also mit `except SomeException` diese bestimmte Exception innerhalb
Auf die gleiche Weise können Sie `finally` verwenden, um sicherzustellen, dass die Exit-Schritte ausgeführt werden, unabhängig davon, ob eine Exception geworfen wurde oder nicht.
-{* ../../docs_src/dependencies/tutorial007.py hl[3,5] *}
+{* ../../docs_src/dependencies/tutorial007_py39.py hl[3,5] *}
## Unterabhängigkeiten mit `yield` { #sub-dependencies-with-yield }
@@ -268,7 +268,7 @@ In Python können Sie Kontextmanager erstellen, indem Sie deprecatet (aber weiterhin unterstützt) und in `.model_dump()` umbenannt.
-
-Die Beispiele hier verwenden `.dict()` für die Kompatibilität mit Pydantic v1, aber Sie sollten `.model_dump()` verwenden, wenn Sie Pydantic v2 verwenden können.
-
-///
-
-### Über `**user_in.dict()` { #about-user-in-dict }
-
-#### Die `.dict()`-Methode von Pydantic { #pydantics-dict }
+#### Pydantics `.model_dump()` { #pydantics-model-dump }
`user_in` ist ein Pydantic-Modell der Klasse `UserIn`.
-Pydantic-Modelle haben eine `.dict()`-Methode, die ein `dict` mit den Daten des Modells zurückgibt.
+Pydantic-Modelle haben eine `.model_dump()`-Methode, die ein `dict` mit den Daten des Modells zurückgibt.
Wenn wir also ein Pydantic-Objekt `user_in` erstellen, etwa so:
@@ -47,7 +39,7 @@ user_in = UserIn(username="john", password="secret", email="john.doe@example.com
und dann aufrufen:
```Python
-user_dict = user_in.dict()
+user_dict = user_in.model_dump()
```
haben wir jetzt ein `dict` mit den Daten in der Variablen `user_dict` (es ist ein `dict` statt eines Pydantic-Modellobjekts).
@@ -103,20 +95,20 @@ UserInDB(
#### Ein Pydantic-Modell aus dem Inhalt eines anderen { #a-pydantic-model-from-the-contents-of-another }
-Da wir im obigen Beispiel `user_dict` von `user_in.dict()` bekommen haben, wäre dieser Code:
+Da wir im obigen Beispiel `user_dict` von `user_in.model_dump()` bekommen haben, wäre dieser Code:
```Python
-user_dict = user_in.dict()
+user_dict = user_in.model_dump()
UserInDB(**user_dict)
```
gleichwertig zu:
```Python
-UserInDB(**user_in.dict())
+UserInDB(**user_in.model_dump())
```
-... weil `user_in.dict()` ein `dict` ist, und dann lassen wir Python es „entpacken“, indem wir es an `UserInDB` mit vorangestelltem `**` übergeben.
+... weil `user_in.model_dump()` ein `dict` ist, und dann lassen wir Python es „entpacken“, indem wir es an `UserInDB` mit vorangestelltem `**` übergeben.
Auf diese Weise erhalten wir ein Pydantic-Modell aus den Daten eines anderen Pydantic-Modells.
@@ -125,7 +117,7 @@ Auf diese Weise erhalten wir ein Pydantic-Modell aus den Daten eines anderen Pyd
Und dann fügen wir das zusätzliche Schlüsselwort-Argument `hashed_password=hashed_password` hinzu, wie in:
```Python
-UserInDB(**user_in.dict(), hashed_password=hashed_password)
+UserInDB(**user_in.model_dump(), hashed_password=hashed_password)
```
... was so ist wie:
@@ -180,7 +172,6 @@ Wenn Sie eine Requests zuständig ist, die an:
@@ -320,7 +320,7 @@ Das ist unsere „**Pfadoperation-Funktion**“:
* **Operation**: ist `get`.
* **Funktion**: ist die Funktion direkt unter dem „Dekorator“ (unter `@app.get("/")`).
-{* ../../docs_src/first_steps/tutorial001.py hl[7] *}
+{* ../../docs_src/first_steps/tutorial001_py39.py hl[7] *}
Dies ist eine Python-Funktion.
@@ -332,7 +332,7 @@ In diesem Fall handelt es sich um eine `async`-Funktion.
Sie könnten sie auch als normale Funktion anstelle von `async def` definieren:
-{* ../../docs_src/first_steps/tutorial003.py hl[7] *}
+{* ../../docs_src/first_steps/tutorial003_py39.py hl[7] *}
/// note | Hinweis
@@ -342,7 +342,7 @@ Wenn Sie den Unterschied nicht kennen, lesen Sie [Async: *„In Eile?“*](../as
### Schritt 5: den Inhalt zurückgeben { #step-5-return-the-content }
-{* ../../docs_src/first_steps/tutorial001.py hl[8] *}
+{* ../../docs_src/first_steps/tutorial001_py39.py hl[8] *}
Sie können ein `dict`, eine `list`, einzelne Werte wie `str`, `int`, usw. zurückgeben.
diff --git a/docs/de/docs/tutorial/handling-errors.md b/docs/de/docs/tutorial/handling-errors.md
index a39c3db37a..d890b44629 100644
--- a/docs/de/docs/tutorial/handling-errors.md
+++ b/docs/de/docs/tutorial/handling-errors.md
@@ -25,7 +25,7 @@ Um HTTP-deprecatet kennzeichnen möchten, ohne sie zu entfernen, fügen Sie den Parameter `deprecated` hinzu:
-{* ../../docs_src/path_operation_configuration/tutorial006.py hl[16] *}
+{* ../../docs_src/path_operation_configuration/tutorial006_py39.py hl[16] *}
Sie wird in der interaktiven Dokumentation gut sichtbar als deprecatet markiert werden:
diff --git a/docs/de/docs/tutorial/path-params-numeric-validations.md b/docs/de/docs/tutorial/path-params-numeric-validations.md
index 5b74749447..8b52e8b42f 100644
--- a/docs/de/docs/tutorial/path-params-numeric-validations.md
+++ b/docs/de/docs/tutorial/path-params-numeric-validations.md
@@ -54,7 +54,7 @@ Für **FastAPI** spielt es keine Rolle. Es erkennt die Parameter anhand ihrer Na
Sie können Ihre Funktion also so deklarieren:
-{* ../../docs_src/path_params_numeric_validations/tutorial002.py hl[7] *}
+{* ../../docs_src/path_params_numeric_validations/tutorial002_py39.py hl[7] *}
Aber bedenken Sie, dass Sie dieses Problem nicht haben, wenn Sie `Annotated` verwenden, da es nicht darauf ankommt, dass Sie keine Funktionsparameter-Defaultwerte für `Query()` oder `Path()` verwenden.
@@ -83,7 +83,7 @@ Wenn Sie:
Python wird nichts mit diesem `*` machen, aber es wird wissen, dass alle folgenden Parameter als Schlüsselwortargumente (Schlüssel-Wert-Paare) verwendet werden sollen, auch bekannt als kwargs. Selbst wenn diese keinen Defaultwert haben.
-{* ../../docs_src/path_params_numeric_validations/tutorial003.py hl[7] *}
+{* ../../docs_src/path_params_numeric_validations/tutorial003_py39.py hl[7] *}
### Besser mit `Annotated` { #better-with-annotated }
diff --git a/docs/de/docs/tutorial/path-params.md b/docs/de/docs/tutorial/path-params.md
index 1db288fb87..1de4973155 100644
--- a/docs/de/docs/tutorial/path-params.md
+++ b/docs/de/docs/tutorial/path-params.md
@@ -2,7 +2,7 @@
Sie können Pfad-„Parameter“ oder -„Variablen“ mit der gleichen Syntax deklarieren, welche in Python-Formatstrings verwendet wird:
-{* ../../docs_src/path_params/tutorial001.py hl[6:7] *}
+{* ../../docs_src/path_params/tutorial001_py39.py hl[6:7] *}
Der Wert des Pfad-Parameters `item_id` wird Ihrer Funktion als das Argument `item_id` übergeben.
@@ -16,7 +16,7 @@ Wenn Sie dieses Beispiel ausführen und auf Enumerationen (oder Enums) gibt es in Python seit Version 3.4.
-
-///
/// tip | Tipp
@@ -158,7 +153,7 @@ Falls Sie sich fragen, was „AlexNet“, „ResNet“ und „LeNet“ ist, das
Dann erstellen Sie einen *Pfad-Parameter*, der als Typ die gerade erstellte Enum-Klasse hat (`ModelName`):
-{* ../../docs_src/path_params/tutorial005.py hl[16] *}
+{* ../../docs_src/path_params/tutorial005_py39.py hl[16] *}
### Die API-Dokumentation testen { #check-the-docs }
@@ -174,13 +169,13 @@ Der *Pfad-Parameter* wird ein *Query ist die Menge von Schlüssel-Wert-Paaren, die nach dem `?` in einer URL folgen und durch `&`-Zeichen getrennt sind.
@@ -127,7 +127,7 @@ Wenn Sie keinen spezifischen Wert haben wollen, sondern der Parameter einfach op
Aber wenn Sie wollen, dass ein Query-Parameter erforderlich ist, vergeben Sie einfach keinen Defaultwert:
-{* ../../docs_src/query_params/tutorial005.py hl[6:7] *}
+{* ../../docs_src/query_params/tutorial005_py39.py hl[6:7] *}
Hier ist `needy` ein erforderlicher Query-Parameter vom Typ `str`.
diff --git a/docs/de/docs/tutorial/response-model.md b/docs/de/docs/tutorial/response-model.md
index 7b77125cb5..f759bb2571 100644
--- a/docs/de/docs/tutorial/response-model.md
+++ b/docs/de/docs/tutorial/response-model.md
@@ -183,7 +183,7 @@ Es kann Fälle geben, bei denen Sie etwas zurückgeben, das kein gültiges Pydan
Der häufigste Anwendungsfall ist, wenn Sie [eine Response direkt zurückgeben, wie es später im Handbuch für fortgeschrittene Benutzer erläutert wird](../advanced/response-directly.md){.internal-link target=_blank}.
-{* ../../docs_src/response_model/tutorial003_02.py hl[8,10:11] *}
+{* ../../docs_src/response_model/tutorial003_02_py39.py hl[8,10:11] *}
Dieser einfache Anwendungsfall wird automatisch von FastAPI gehandhabt, weil die Annotation des Rückgabetyps die Klasse (oder eine Unterklasse von) `Response` ist.
@@ -193,7 +193,7 @@ Und Tools werden auch glücklich sein, weil sowohl `RedirectResponse` als auch `
Sie können auch eine Unterklasse von `Response` in der Typannotation verwenden.
-{* ../../docs_src/response_model/tutorial003_03.py hl[8:9] *}
+{* ../../docs_src/response_model/tutorial003_03_py39.py hl[8:9] *}
Das wird ebenfalls funktionieren, weil `RedirectResponse` eine Unterklasse von `Response` ist, und FastAPI sich um diesen einfachen Anwendungsfall automatisch kümmert.
@@ -252,20 +252,6 @@ Wenn Sie also den Artikel mit der ID `foo` bei der *Pfadoperation* anfragen, wir
/// info | Info
-In Pydantic v1 hieß diese Methode `.dict()`, in Pydantic v2 wurde sie deprecatet (aber immer noch unterstützt) und in `.model_dump()` umbenannt.
-
-Die Beispiele hier verwenden `.dict()` für die Kompatibilität mit Pydantic v1, Sie sollten jedoch stattdessen `.model_dump()` verwenden, wenn Sie Pydantic v2 verwenden können.
-
-///
-
-/// info | Info
-
-FastAPI verwendet `.dict()` von Pydantic Modellen, mit dessen `exclude_unset`-Parameter, um das zu erreichen.
-
-///
-
-/// info | Info
-
Sie können auch:
* `response_model_exclude_defaults=True`
diff --git a/docs/de/docs/tutorial/response-status-code.md b/docs/de/docs/tutorial/response-status-code.md
index 928003c3fc..fd17c99336 100644
--- a/docs/de/docs/tutorial/response-status-code.md
+++ b/docs/de/docs/tutorial/response-status-code.md
@@ -8,7 +8,7 @@ Genauso wie Sie ein Responsemodell angeben können, können Sie auch den HTTP-St
* `@app.delete()`
* usw.
-{* ../../docs_src/response_status_code/tutorial001.py hl[6] *}
+{* ../../docs_src/response_status_code/tutorial001_py39.py hl[6] *}
/// note | Hinweis
@@ -74,7 +74,7 @@ Um mehr über die einzelnen Statuscodes zu erfahren und welcher wofür verwendet
Lassen Sie uns das vorherige Beispiel noch einmal anschauen:
-{* ../../docs_src/response_status_code/tutorial001.py hl[6] *}
+{* ../../docs_src/response_status_code/tutorial001_py39.py hl[6] *}
`201` ist der Statuscode für „Created“ („Erzeugt“).
@@ -82,7 +82,7 @@ Aber Sie müssen sich nicht merken, was jeder dieser Codes bedeutet.
Sie können die Annehmlichkeit von Variablen aus `fastapi.status` nutzen.
-{* ../../docs_src/response_status_code/tutorial002.py hl[1,6] *}
+{* ../../docs_src/response_status_code/tutorial002_py39.py hl[1,6] *}
Diese sind nur eine Annehmlichkeit, sie enthalten dieselbe Zahl, aber so können Sie die Autovervollständigung Ihres Editors verwenden, um sie zu finden:
diff --git a/docs/de/docs/tutorial/schema-extra-example.md b/docs/de/docs/tutorial/schema-extra-example.md
index e2ffed292e..07fe8c5d92 100644
--- a/docs/de/docs/tutorial/schema-extra-example.md
+++ b/docs/de/docs/tutorial/schema-extra-example.md
@@ -8,36 +8,14 @@ Hier sind mehrere Möglichkeiten, das zu tun.
Sie können `examples` („Beispiele“) für ein Pydantic-Modell deklarieren, welche dem generierten JSON-Schema hinzugefügt werden.
-//// tab | Pydantic v2
-
{* ../../docs_src/schema_extra_example/tutorial001_py310.py hl[13:24] *}
-////
-
-//// tab | Pydantic v1
-
-{* ../../docs_src/schema_extra_example/tutorial001_pv1_py310.py hl[13:23] *}
-
-////
-
Diese zusätzlichen Informationen werden unverändert zum für dieses Modell ausgegebenen **JSON-Schema** hinzugefügt und in der API-Dokumentation verwendet.
-//// tab | Pydantic v2
-
-In Pydantic Version 2 würden Sie das Attribut `model_config` verwenden, das ein `dict` akzeptiert, wie beschrieben in Pydantic-Dokumentation: Configuration.
+Sie können das Attribut `model_config` verwenden, das ein `dict` akzeptiert, wie beschrieben in Pydantic-Dokumentation: Configuration.
Sie können `json_schema_extra` setzen, mit einem `dict`, das alle zusätzlichen Daten enthält, die im generierten JSON-Schema angezeigt werden sollen, einschließlich `examples`.
-////
-
-//// tab | Pydantic v1
-
-In Pydantic Version 1 würden Sie eine interne Klasse `Config` und `schema_extra` verwenden, wie beschrieben in Pydantic-Dokumentation: Schema customization.
-
-Sie können `schema_extra` setzen, mit einem `dict`, das alle zusätzlichen Daten enthält, die im generierten JSON-Schema angezeigt werden sollen, einschließlich `examples`.
-
-////
-
/// tip | Tipp
Mit derselben Technik können Sie das JSON-Schema erweitern und Ihre eigenen benutzerdefinierten Zusatzinformationen hinzufügen.
diff --git a/docs/de/docs/tutorial/static-files.md b/docs/de/docs/tutorial/static-files.md
index 0c4e7c8abd..9ba2501756 100644
--- a/docs/de/docs/tutorial/static-files.md
+++ b/docs/de/docs/tutorial/static-files.md
@@ -7,7 +7,7 @@ Mit `StaticFiles` können Sie statische Dateien aus einem Verzeichnis automatisc
* Importieren Sie `StaticFiles`.
* „Mounten“ Sie eine `StaticFiles()`-Instanz in einem bestimmten Pfad.
-{* ../../docs_src/static_files/tutorial001.py hl[2,6] *}
+{* ../../docs_src/static_files/tutorial001_py39.py hl[2,6] *}
/// note | Technische Details
diff --git a/docs/de/docs/tutorial/testing.md b/docs/de/docs/tutorial/testing.md
index b18469998d..d889b1e1fb 100644
--- a/docs/de/docs/tutorial/testing.md
+++ b/docs/de/docs/tutorial/testing.md
@@ -30,7 +30,7 @@ Verwenden Sie das `TestClient`-Objekt auf die gleiche Weise wie `httpx`.
Schreiben Sie einfache `assert`-Anweisungen mit den Standard-Python-Ausdrücken, die Sie überprüfen müssen (wiederum, Standard-`pytest`).
-{* ../../docs_src/app_testing/tutorial001.py hl[2,12,15:18] *}
+{* ../../docs_src/app_testing/tutorial001_py39.py hl[2,12,15:18] *}
/// tip | Tipp
@@ -76,7 +76,7 @@ Nehmen wir an, Sie haben eine Dateistruktur wie in [Größere Anwendungen](bigge
In der Datei `main.py` haben Sie Ihre **FastAPI**-Anwendung:
-{* ../../docs_src/app_testing/main.py *}
+{* ../../docs_src/app_testing/app_a_py39/main.py *}
### Testdatei { #testing-file }
@@ -93,7 +93,7 @@ Dann könnten Sie eine Datei `test_main.py` mit Ihren Tests haben. Sie könnte s
Da sich diese Datei im selben Package befindet, können Sie relative Importe verwenden, um das Objekt `app` aus dem `main`-Modul (`main.py`) zu importieren:
-{* ../../docs_src/app_testing/test_main.py hl[3] *}
+{* ../../docs_src/app_testing/app_a_py39/test_main.py hl[3] *}
... und haben den Code für die Tests wie zuvor.
diff --git a/docs/de/llm-prompt.md b/docs/de/llm-prompt.md
index 5df904ac7a..2d345bf6d1 100644
--- a/docs/de/llm-prompt.md
+++ b/docs/de/llm-prompt.md
@@ -4,213 +4,197 @@ Translate to German (Deutsch).
Language code: de.
-
-### Definitions
-
-"hyphen"
- The character «-»
- Unicode U+002D (HYPHEN-MINUS)
- Alternative names: hyphen, dash, minus sign
-
-"dash"
- The character «–»
- Unicode U+2013 (EN DASH)
- German name: Halbgeviertstrich
-
-
### Grammar to use when talking to the reader
-Use the formal grammar (use «Sie» instead of «Du»).
-
+Use the formal grammar (use `Sie` instead of `Du`).
### Quotes
-1) Convert neutral double quotes («"») and English double typographic quotes («“» and «”») to German double typographic quotes («„» and «“»). Convert neutral single quotes («'») and English single typographic quotes («‘» and «’») to German single typographic quotes («‚» and «‘»). Do NOT convert «`"» to «„», do NOT convert «"`» to «“».
+1) Convert neutral double quotes (`"`) to German double typographic quotes (`„` and `“`). Convert neutral single quotes (`'`) to German single typographic quotes (`‚` and `‘`).
+
+Do NOT convert quotes in code snippets and code blocks to their German typographic equivalents.
Examples:
- Source (English):
+Source (English):
- «««
- "Hello world"
- “Hello Universe”
- "He said: 'Hello'"
- “my name is ‘Nils’”
- `"__main__"`
- `"items"`
- »»»
+```
+"Hello world"
+“Hello Universe”
+"He said: 'Hello'"
+“my name is ‘Nils’”
+`"__main__"`
+`"items"`
+```
- Result (German):
-
- «««
- „Hallo Welt“
- „Hallo Universum“
- „Er sagte: ‚Hallo‘“
- „Mein Name ist ‚Nils‘“
- `"__main__"`
- `"items"`
- »»»
+Result (German):
+```
+„Hallo Welt“
+„Hallo Universum“
+„Er sagte: ‚Hallo‘“
+„Mein Name ist ‚Nils‘“
+`"__main__"`
+`"items"`
+```
### Ellipsis
-1) Make sure there is a space between an ellipsis and a word following or preceding the ellipsis.
+- Make sure there is a space between an ellipsis and a word following or preceding the ellipsis.
Examples:
- Source (English):
+Source (English):
- «««
- ...as we intended.
- ...this would work:
- ...etc.
- others...
- More to come...
- »»»
+```
+...as we intended.
+...this would work:
+...etc.
+others...
+More to come...
+```
- Result (German):
+Result (German):
- «««
- ... wie wir es beabsichtigt hatten.
- ... das würde funktionieren:
- ... usw.
- Andere ...
- Später mehr ...
- »»»
-
-2) This does not apply in URLs, code blocks, and code snippets. Do not remove or add spaces there.
+```
+... wie wir es beabsichtigt hatten.
+... das würde funktionieren:
+... usw.
+Andere ...
+Später mehr ...
+```
+- This does not apply in URLs, code blocks, and code snippets. Do not remove or add spaces there.
### Headings
-1) Translate headings using the infinite form.
+- Translate headings using the infinite form.
Examples:
- Source (English):
+Source (English):
- «««
- ## Create a Project { #create-a-project }
- »»»
+```
+## Create a Project { #create-a-project }
+```
- Translate with (German):
+Result (German):
- «««
- ## Ein Projekt erstellen { #create-a-project }
- »»»
+```
+## Ein Projekt erstellen { #create-a-project }
+```
- Do NOT translate with (German):
+Do NOT translate with (German):
- «««
- ## Erstellen Sie ein Projekt { #create-a-project }
- »»»
+```
+## Erstellen Sie ein Projekt { #create-a-project }
+```
- Source (English):
+Source (English):
- «««
- # Install Packages { #install-packages }
- »»»
+```
+# Install Packages { #install-packages }
+```
- Translate with (German):
+Translate with (German):
- «««
- # Pakete installieren { #install-packages }
- »»»
+```
+# Pakete installieren { #install-packages }
+```
- Do NOT translate with (German):
+Do NOT translate with (German):
- «««
- # Installieren Sie Pakete { #install-packages }
- »»»
+```
+# Installieren Sie Pakete { #install-packages }
+```
- Source (English):
+Source (English):
- «««
- ### Run Your Program { #run-your-program }
- »»»
+```
+### Run Your Program { #run-your-program }
+```
- Translate with (German):
+Translate with (German):
- «««
- ### Ihr Programm ausführen { #run-your-program }
- »»»
+```
+### Ihr Programm ausführen { #run-your-program }
+```
- Do NOT translate with (German):
+Do NOT translate with (German):
- «««
- ### Führen Sie Ihr Programm aus { #run-your-program }
- »»»
+```
+### Führen Sie Ihr Programm aus { #run-your-program }
+```
-2) Make sure that the translated part of the heading does not end with a period.
+- Make sure that the translated part of the heading does not end with a period.
Example:
- Source (English):
+Source (English):
- «««
- ## Another module with `APIRouter` { #another-module-with-apirouter }
- »»»
+```
+## Another module with `APIRouter` { #another-module-with-apirouter }
+```
- Translate with (German):
+Translate with (German):
- «««
- ## Ein weiteres Modul mit `APIRouter` { #another-module-with-apirouter }
- »»»
+```
+## Ein weiteres Modul mit `APIRouter` { #another-module-with-apirouter }
+```
- Do NOT translate with (German) – notice the added period:
+Do NOT translate with (German) – notice the added period:
- «««
- ## Ein weiteres Modul mit `APIRouter`. { #another-module-with-apirouter }
- »»»
+```
+## Ein weiteres Modul mit `APIRouter`. { #another-module-with-apirouter }
+```
-3) Replace occurrences of literal « - » (a space followed by a hyphen followed by a space) with « – » (a space followed by a dash followed by a space) in the translated part of the heading.
+- Replace occurrences of literal ` - ` (a space followed by a hyphen followed by a space) with ` – ` (a space followed by a dash followed by a space) in the translated part of the heading.
Example:
- Source (English):
+Source (English):
- «««
- # FastAPI in Containers - Docker { #fastapi-in-containers-docker }
- »»»
+```
+# FastAPI in Containers - Docker { #fastapi-in-containers-docker }
+```
- Translate with (German) – notice the dash:
+Translate with (German) – notice the dash:
- «««
- # FastAPI in Containern – Docker { #fastapi-in-containers-docker }
- »»»
+```
+# FastAPI in Containern – Docker { #fastapi-in-containers-docker }
+```
- Do NOT translate with (German) – notice the hyphen:
+Do NOT translate with (German) – notice the hyphen:
- «««
- # FastAPI in Containern - Docker { #fastapi-in-containers-docker }
- »»»
+```
+# FastAPI in Containern - Docker { #fastapi-in-containers-docker }
+```
-3.1) Do not apply rule 3 when there is no space before or no space after the hyphen.
+- Do not apply rule 3 when there is no space before or no space after the hyphen.
Example:
- Source (English):
+Source (English):
- «««
- ## Type hints and annotations { #type-hints-and-annotations }
- »»»
+```
+## Type hints and annotations { #type-hints-and-annotations }
+```
- Translate with (German) – notice the hyphen:
+Translate with (German) - notice the hyphen:
- «««
- ## Typhinweise und -annotationen { #type-hints-and-annotations }
- »»»
+```
+## Typhinweise und -annotationen { #type-hints-and-annotations }
+```
- Do NOT translate with (German) – notice the dash:
+Do NOT translate with (German) - notice the dash:
- «««
- ## Typhinweise und –annotationen { #type-hints-and-annotations }
- »»»
+```
+## Typhinweise und –annotationen { #type-hints-and-annotations }
+```
-3.2) Do not apply rule 3 to the untranslated part of the heading inside curly brackets, which you shall not translate.
+- Do not modify the hyphens in the content in headers inside of curly braces, which you shall not translate.
-
-### German instructions, when to use and when not to use hyphens in words (written in first person, which is you)
+### German instructions, when to use and when not to use hyphens in words (written in first person, which is you).
In der Regel versuche ich so weit wie möglich Worte zusammenzuschreiben, also ohne Bindestrich, es sei denn, es ist Konkretesding-Klassevondingen, etwa «Pydantic-Modell» (aber: «Datenbankmodell»), «Python-Modul» (aber: «Standardmodul»). Ich setze auch einen Bindestrich, wenn er die gleichen Buchstaben verbindet, etwa «Enum-Member», «Cloud-Dienst», «Template-Engine». Oder wenn das Wort sonst einfach zu lang wird, etwa, «Performance-Optimierung». Oder um etwas visuell besser zu dokumentieren, etwa «Pfadoperation-Dekorator», «Pfadoperation-Funktion».
@@ -219,122 +203,122 @@ In der Regel versuche ich so weit wie möglich Worte zusammenzuschreiben, also o
Ich versuche nicht, alles einzudeutschen. Das bezieht sich besonders auf Begriffe aus dem Bereich der Programmierung. Ich wandele zwar korrekt in Großschreibung um und setze Bindestriche, wo notwendig, aber ansonsten lasse ich solch ein Wort unverändert. Beispielsweise wird aus dem englischen Wort «string» in der deutschen Übersetzung «String», aber nicht «Zeichenkette». Oder aus dem englischen Wort «request body» wird in der deutschen Übersetzung «Requestbody», aber nicht «Anfragekörper». Oder aus dem englischen «response» wird im Deutschen «Response», aber nicht «Antwort».
-
### List of English terms and their preferred German translations
-Below is a list of English terms and their preferred German translations, separated by a colon («:»). Use these translations, do not use your own. If an existing translation does not use these terms, update it to use them. In the below list, a term or a translation may be followed by an explanation in brackets, which explains when to translate the term this way. If a translation is preceded by «NOT», then that means: do NOT use this translation for this term. English nouns, starting with the word «the», have the German genus – «der», «die», «das» – prepended to their German translation, to help you to grammatically decline them in the translation. They are given in singular case, unless they have «(plural)» attached, which means they are given in plural case. Verbs are given in the full infinitive – starting with the word «to».
+Below is a list of English terms and their preferred German translations, separated by a colon (:). Use these translations, do not use your own. If an existing translation does not use these terms, update it to use them. In the below list, a term or a translation may be followed by an explanation in brackets, which explains when to translate the term this way. If a translation is preceded by `NOT`, then that means: do NOT use this translation for this term. English nouns, starting with the word `the`, have the German genus – `der`, `die`, `das` – prepended to their German translation, to help you to grammatically decline them in the translation. They are given in singular case, unless they have `(plural)` attached, which means they are given in plural case. Verbs are given in the full infinitive – starting with the word `to`.
-* «/// check»: «/// check | Testen»
-* «/// danger»: «/// danger | Gefahr»
-* «/// info»: «/// info | Info»
-* «/// note | Technical Details»: «/// note | Technische Details»
-* «/// note»: «/// note | Hinweis»
-* «/// tip»: «/// tip | Tipp»
-* «/// warning»: «/// warning | Achtung»
-* «you»: «Sie»
-* «your»: «Ihr»
-* «e.g»: «z. B.»
-* «etc.»: «usw.»
-* «ref»: «Ref.»
-* «the Tutorial - User guide»: «das Tutorial – Benutzerhandbuch»
-* «the Advanced User Guide»: «das Handbuch für fortgeschrittene Benutzer»
-* «the SQLModel docs»: «die SQLModel-Dokumentation»
-* «the docs»: «die Dokumentation» (use singular case)
-* «the env var»: «die Umgebungsvariable»
-* «the `PATH` environment variable»: «die `PATH`-Umgebungsvariable»
-* «the `PATH`»: «der `PATH`»
-* «the `requirements.txt`»: «die `requirements.txt`»
-* «the API Router»: «der API-Router»
-* «the Authorization-Header»: «der Autorisierungsheader»
-* «the `Authorization`-Header»: «der `Authorization`-Header»
-* «the background task»: «der Hintergrundtask»
-* «the button»: «der Button»
-* «the cloud provider»: «der Cloudanbieter»
-* «the CLI»: «Das CLI»
-* «the command line interface»: «Das Kommandozeileninterface»
-* «the default value»: «der Defaultwert»
-* «the default value»: NOT «der Standardwert»
-* «the default declaration»: «die Default-Deklaration»
-* «the deployment»: «das Deployment»
-* «the dict»: «das Dict»
-* «the dictionary»: «das Dictionary»
-* «the enumeration»: «die Enumeration»
-* «the enum»: «das Enum»
-* «the engine»: «die Engine»
-* «the error response»: «die Error-Response»
-* «the event»: «das Event»
-* «the exception»: «die Exception»
-* «the exception handler»: «der Exceptionhandler»
-* «the form model»: «das Formularmodell»
-* «the form body»: «der Formularbody»
-* «the header»: «der Header»
-* «the headers» (plural): «die Header»
-* «in headers» (plural): «in Headern»
-* «the forwarded header»: «der Forwarded-Header»
-* «the lifespan event»: «das Lifespan-Event»
-* «the lock»: «der Lock»
-* «the locking»: «das Locking»
-* «the mobile application»: «die Mobile-Anwendung»
-* «the model object»: «das Modellobjekt»
-* «the mounting»: «das Mounten»
-* «mounted»: «gemountet»
-* «the origin»: «das Origin»
-* «the override»: «Die Überschreibung»
-* «the parameter»: «der Parameter»
-* «the parameters» (plural): «die Parameter»
-* «the function parameter»: «der Funktionsparameter»
-* «the default parameter»: «der Defaultparameter»
-* «the body parameter»: «der Body-Parameter»
-* «the request body parameter»: «der Requestbody-Parameter»
-* «the path parameter»: «der Pfad-Parameter»
-* «the query parameter»: «der Query-Parameter»
-* «the cookie parameter»: «der Cookie-Parameter»
-* «the header parameter»: «der Header-Parameter»
-* «the form parameter»: «der Formular-Parameter»
-* «the payload»: «die Payload»
-* «the performance»: NOT «die Performance»
-* «the query»: «die Query»
-* «the recap»: «die Zusammenfassung»
-* «the request» (what the client sends to the server): «der Request»
-* «the request body»: «der Requestbody»
-* «the request bodies» (plural): «die Requestbodys»
-* «the response» (what the server sends back to the client): «die Response»
-* «the return type»: «der Rückgabetyp»
-* «the return value»: «der Rückgabewert»
-* «the startup» (the event of the app): «der Startup»
-* «the shutdown» (the event of the app): «der Shutdown»
-* «the startup event»: «das Startup-Event»
-* «the shutdown event»: «das Shutdown-Event»
-* «the startup» (of the server): «das Hochfahren»
-* «the startup» (the company): «das Startup»
-* «the SDK»: «das SDK»
-* «the tag»: «der Tag»
-* «the type annotation»: «die Typannotation»
-* «the type hint»: «der Typhinweis»
-* «the wildcard»: «die Wildcard»
-* «the worker class»: «die Workerklasse»
-* «the worker class»: NOT «die Arbeiterklasse»
-* «the worker process»: «der Workerprozess»
-* «the worker process»: NOT «der Arbeiterprozess»
-* «to commit»: «committen»
-* «to deploy» (in the cloud): «deployen»
-* «to modify»: «ändern»
-* «to serve» (an application): «bereitstellen»
-* «to serve» (a response): «ausliefern»
-* «to serve»: NOT «bedienen»
-* «to upgrade»: «aktualisieren»
-* «to wrap»: «wrappen»
-* «to wrap»: NOT «hüllen»
-* «`foo` as a `type`»: «`foo` vom Typ `type`»
-* «`foo` as a `type`»: «`foo`, ein `type`»
-* «FastAPI's X»: «FastAPIs X»
-* «Starlette's Y»: «Starlettes Y»
-* «X is case-sensitive»: «Groß-/Kleinschreibung ist relevant in X»
-* «X is case-insensitive»: «Groß-/Kleinschreibung ist nicht relevant in X»
-* «standard Python»: «Standard-Python»
-* «deprecated»: «deprecatet»
+* /// check: /// check | Testen
+* /// danger: /// danger | Gefahr
+* /// info: /// info | Info
+* /// note | Technical Details: /// note | Technische Details
+* /// note: /// note | Hinweis
+* /// tip: /// tip | Tipp
+* /// warning: /// warning | Achtung
+* you: Sie
+* your: Ihr
+* e.g: z. B.
+* etc.: usw.
+* ref: Ref.
+* the Tutorial - User guide: das Tutorial – Benutzerhandbuch
+* the Advanced User Guide: das Handbuch für fortgeschrittene Benutzer
+* the SQLModel docs: die SQLModel-Dokumentation
+* the docs: die Dokumentation (use singular case)
+* the env var: die Umgebungsvariable
+* the `PATH` environment variable: die `PATH`-Umgebungsvariable
+* the `PATH`: der `PATH`
+* the `requirements.txt`: die `requirements.txt`
+* the API Router: der API-Router
+* the Authorization-Header: der Autorisierungsheader
+* the `Authorization`-Header: der `Authorization`-Header
+* the background task: der Hintergrundtask
+* the button: der Button
+* the cloud provider: der Cloudanbieter
+* the CLI: Das CLI
+* the coverage: Die Testabdeckung
+* the command line interface: Das Kommandozeileninterface
+* the default value: der Defaultwert
+* the default value: NOT der Standardwert
+* the default declaration: die Default-Deklaration
+* the deployment: das Deployment
+* the dict: das Dict
+* the dictionary: das Dictionary
+* the enumeration: die Enumeration
+* the enum: das Enum
+* the engine: die Engine
+* the error response: die Error-Response
+* the event: das Event
+* the exception: die Exception
+* the exception handler: der Exceptionhandler
+* the form model: das Formularmodell
+* the form body: der Formularbody
+* the header: der Header
+* the headers (plural): die Header
+* in headers (plural): in Headern
+* the forwarded header: der Forwarded-Header
+* the lifespan event: das Lifespan-Event
+* the lock: der Lock
+* the locking: das Locking
+* the mobile application: die Mobile-Anwendung
+* the model object: das Modellobjekt
+* the mounting: das Mounten
+* mounted: gemountet
+* the origin: das Origin
+* the override: Die Überschreibung
+* the parameter: der Parameter
+* the parameters (plural): die Parameter
+* the function parameter: der Funktionsparameter
+* the default parameter: der Defaultparameter
+* the body parameter: der Body-Parameter
+* the request body parameter: der Requestbody-Parameter
+* the path parameter: der Pfad-Parameter
+* the query parameter: der Query-Parameter
+* the cookie parameter: der Cookie-Parameter
+* the header parameter: der Header-Parameter
+* the form parameter: der Formular-Parameter
+* the payload: die Payload
+* the performance: NOT die Performance
+* the query: die Query
+* the recap: die Zusammenfassung
+* the request (what the client sends to the server): der Request
+* the request body: der Requestbody
+* the request bodies (plural): die Requestbodys
+* the response (what the server sends back to the client): die Response
+* the return type: der Rückgabetyp
+* the return value: der Rückgabewert
+* the startup (the event of the app): der Startup
+* the shutdown (the event of the app): der Shutdown
+* the startup event: das Startup-Event
+* the shutdown event: das Shutdown-Event
+* the startup (of the server): das Hochfahren
+* the startup (the company): das Startup
+* the SDK: das SDK
+* the tag: der Tag
+* the type annotation: die Typannotation
+* the type hint: der Typhinweis
+* the wildcard: die Wildcard
+* the worker class: die Workerklasse
+* the worker class: NOT die Arbeiterklasse
+* the worker process: der Workerprozess
+* the worker process: NOT der Arbeiterprozess
+* to commit: committen
+* to deploy (in the cloud): deployen
+* to modify: ändern
+* to serve (an application): bereitstellen
+* to serve (a response): ausliefern
+* to serve: NOT bedienen
+* to upgrade: aktualisieren
+* to wrap: wrappen
+* to wrap: NOT hüllen
+* `foo` as a `type`: `foo` vom Typ `type`
+* `foo` as a `type`: `foo`, ein `type`
+* FastAPI's X: FastAPIs X
+* Starlette's Y: Starlettes Y
+* X is case-sensitive: Groß-/Kleinschreibung ist relevant in X
+* X is case-insensitive: Groß-/Kleinschreibung ist nicht relevant in X
+* standard Python: Standard-Python
+* deprecated: deprecatet
### Other rules
-Preserve indentation. Keep emoticons. Encode in utf-8. Use Linux line breaks (LF).
+Preserve indentation. Keep emojis. Encode in utf-8. Use Linux line breaks (LF).
diff --git a/docs/en/data/contributors.yml b/docs/en/data/contributors.yml
index 163dc68e37..0c144cd4ce 100644
--- a/docs/en/data/contributors.yml
+++ b/docs/en/data/contributors.yml
@@ -1,6 +1,6 @@
tiangolo:
login: tiangolo
- count: 808
+ count: 857
avatarUrl: https://avatars.githubusercontent.com/u/1326112?u=cb5d06e73a9e1998141b1641aa88e443c6717651&v=4
url: https://github.com/tiangolo
dependabot:
@@ -10,7 +10,7 @@ dependabot:
url: https://github.com/apps/dependabot
alejsdev:
login: alejsdev
- count: 52
+ count: 53
avatarUrl: https://avatars.githubusercontent.com/u/90076947?u=85ceac49fb87138aebe8d663912e359447329090&v=4
url: https://github.com/alejsdev
pre-commit-ci:
@@ -18,6 +18,11 @@ pre-commit-ci:
count: 50
avatarUrl: https://avatars.githubusercontent.com/in/68672?v=4
url: https://github.com/apps/pre-commit-ci
+YuriiMotov:
+ login: YuriiMotov
+ count: 36
+ avatarUrl: https://avatars.githubusercontent.com/u/109919500?u=b9b13d598dddfab529a52d264df80a900bfe7060&v=4
+ url: https://github.com/YuriiMotov
github-actions:
login: github-actions
count: 26
@@ -28,26 +33,21 @@ Kludex:
count: 25
avatarUrl: https://avatars.githubusercontent.com/u/7353520?u=df8a3f06ba8f55ae1967a3e2d5ed882903a4e330&v=4
url: https://github.com/Kludex
-YuriiMotov:
- login: YuriiMotov
- count: 20
- avatarUrl: https://avatars.githubusercontent.com/u/109919500?u=b9b13d598dddfab529a52d264df80a900bfe7060&v=4
- url: https://github.com/YuriiMotov
dmontagu:
login: dmontagu
count: 17
avatarUrl: https://avatars.githubusercontent.com/u/35119617?u=540f30c937a6450812628b9592a1dfe91bbe148e&v=4
url: https://github.com/dmontagu
+svlandeg:
+ login: svlandeg
+ count: 16
+ avatarUrl: https://avatars.githubusercontent.com/u/8796347?u=556c97650c27021911b0b9447ec55e75987b0e8a&v=4
+ url: https://github.com/svlandeg
nilslindemann:
login: nilslindemann
count: 15
avatarUrl: https://avatars.githubusercontent.com/u/6892179?u=1dca6a22195d6cd1ab20737c0e19a4c55d639472&v=4
url: https://github.com/nilslindemann
-svlandeg:
- login: svlandeg
- count: 14
- avatarUrl: https://avatars.githubusercontent.com/u/8796347?u=556c97650c27021911b0b9447ec55e75987b0e8a&v=4
- url: https://github.com/svlandeg
euri10:
login: euri10
count: 13
@@ -553,6 +553,11 @@ DanielKusyDev:
count: 2
avatarUrl: https://avatars.githubusercontent.com/u/36250676?u=2ea6114ff751fc48b55f231987a0e2582c6b1bd2&v=4
url: https://github.com/DanielKusyDev
+Viicos:
+ login: Viicos
+ count: 2
+ avatarUrl: https://avatars.githubusercontent.com/u/65306057?u=fcd677dc1b9bef12aa103613e5ccb3f8ce305af9&v=4
+ url: https://github.com/Viicos
DanielYang59:
login: DanielYang59
count: 2
diff --git a/docs/en/data/github_sponsors.yml b/docs/en/data/github_sponsors.yml
index 24780603de..971687d8a9 100644
--- a/docs/en/data/github_sponsors.yml
+++ b/docs/en/data/github_sponsors.yml
@@ -2,57 +2,51 @@ sponsors:
- - login: renderinc
avatarUrl: https://avatars.githubusercontent.com/u/36424661?v=4
url: https://github.com/renderinc
- - login: andrew-propelauth
- avatarUrl: https://avatars.githubusercontent.com/u/89474256?u=c98993dec8553c09d424ede67bbe86e5c35f48c9&v=4
- url: https://github.com/andrew-propelauth
- - login: blockbee-io
- avatarUrl: https://avatars.githubusercontent.com/u/115143449?u=1b8620c2d6567c4df2111a371b85a51f448f9b85&v=4
- url: https://github.com/blockbee-io
- - login: zuplo
- avatarUrl: https://avatars.githubusercontent.com/u/85497839?v=4
- url: https://github.com/zuplo
- - login: coderabbitai
- avatarUrl: https://avatars.githubusercontent.com/u/132028505?v=4
- url: https://github.com/coderabbitai
- - login: greptileai
- avatarUrl: https://avatars.githubusercontent.com/u/140149887?v=4
- url: https://github.com/greptileai
- login: subtotal
avatarUrl: https://avatars.githubusercontent.com/u/176449348?v=4
url: https://github.com/subtotal
+ - login: greptileai
+ avatarUrl: https://avatars.githubusercontent.com/u/140149887?v=4
+ url: https://github.com/greptileai
+ - login: coderabbitai
+ avatarUrl: https://avatars.githubusercontent.com/u/132028505?v=4
+ url: https://github.com/coderabbitai
+ - login: zuplo
+ avatarUrl: https://avatars.githubusercontent.com/u/85497839?v=4
+ url: https://github.com/zuplo
+ - login: blockbee-io
+ avatarUrl: https://avatars.githubusercontent.com/u/115143449?u=1b8620c2d6567c4df2111a371b85a51f448f9b85&v=4
+ url: https://github.com/blockbee-io
+ - login: andrew-propelauth
+ avatarUrl: https://avatars.githubusercontent.com/u/89474256?u=c98993dec8553c09d424ede67bbe86e5c35f48c9&v=4
+ url: https://github.com/andrew-propelauth
- login: railwayapp
avatarUrl: https://avatars.githubusercontent.com/u/66716858?v=4
url: https://github.com/railwayapp
-- - login: dribia
- avatarUrl: https://avatars.githubusercontent.com/u/41189616?v=4
- url: https://github.com/dribia
- - login: svix
- avatarUrl: https://avatars.githubusercontent.com/u/80175132?v=4
- url: https://github.com/svix
+- - login: speakeasy-api
+ avatarUrl: https://avatars.githubusercontent.com/u/91446104?v=4
+ url: https://github.com/speakeasy-api
- login: stainless-api
avatarUrl: https://avatars.githubusercontent.com/u/88061651?v=4
url: https://github.com/stainless-api
- - login: speakeasy-api
- avatarUrl: https://avatars.githubusercontent.com/u/91446104?v=4
- url: https://github.com/speakeasy-api
- - login: databento
- avatarUrl: https://avatars.githubusercontent.com/u/64141749?v=4
- url: https://github.com/databento
+ - login: svix
+ avatarUrl: https://avatars.githubusercontent.com/u/80175132?v=4
+ url: https://github.com/svix
- login: permitio
avatarUrl: https://avatars.githubusercontent.com/u/71775833?v=4
url: https://github.com/permitio
-- - login: Ponte-Energy-Partners
- avatarUrl: https://avatars.githubusercontent.com/u/114745848?v=4
- url: https://github.com/Ponte-Energy-Partners
- - login: LambdaTest-Inc
+ - login: databento
+ avatarUrl: https://avatars.githubusercontent.com/u/64141749?v=4
+ url: https://github.com/databento
+- - login: LambdaTest-Inc
avatarUrl: https://avatars.githubusercontent.com/u/171592363?u=96606606a45fa170427206199014f2a5a2a4920b&v=4
url: https://github.com/LambdaTest-Inc
+ - login: Ponte-Energy-Partners
+ avatarUrl: https://avatars.githubusercontent.com/u/114745848?v=4
+ url: https://github.com/Ponte-Energy-Partners
- login: BoostryJP
avatarUrl: https://avatars.githubusercontent.com/u/57932412?v=4
url: https://github.com/BoostryJP
- - login: requestly
- avatarUrl: https://avatars.githubusercontent.com/u/12287519?v=4
- url: https://github.com/requestly
- login: acsone
avatarUrl: https://avatars.githubusercontent.com/u/7601056?v=4
url: https://github.com/acsone
@@ -68,9 +62,6 @@ sponsors:
- login: Doist
avatarUrl: https://avatars.githubusercontent.com/u/2565372?v=4
url: https://github.com/Doist
- - login: bholagabbar
- avatarUrl: https://avatars.githubusercontent.com/u/11693595?v=4
- url: https://github.com/bholagabbar
- - login: mainframeindustries
avatarUrl: https://avatars.githubusercontent.com/u/55092103?v=4
url: https://github.com/mainframeindustries
@@ -86,6 +77,9 @@ sponsors:
- login: ChargeStorm
avatarUrl: https://avatars.githubusercontent.com/u/26000165?v=4
url: https://github.com/ChargeStorm
+ - login: ibrahimpelumi6142
+ avatarUrl: https://avatars.githubusercontent.com/u/113442282?v=4
+ url: https://github.com/ibrahimpelumi6142
- login: nilslindemann
avatarUrl: https://avatars.githubusercontent.com/u/6892179?u=1dca6a22195d6cd1ab20737c0e19a4c55d639472&v=4
url: https://github.com/nilslindemann
@@ -116,124 +110,127 @@ sponsors:
- login: Leay15
avatarUrl: https://avatars.githubusercontent.com/u/32212558?u=c4aa9c1737e515959382a5515381757b1fd86c53&v=4
url: https://github.com/Leay15
- - login: Karine-Bauch
- avatarUrl: https://avatars.githubusercontent.com/u/90465103?u=7feb1018abb1a5631cfd9a91fea723d1ceb5f49b&v=4
- url: https://github.com/Karine-Bauch
- login: jugeeem
avatarUrl: https://avatars.githubusercontent.com/u/116043716?u=ae590d79c38ac79c91b9c5caa6887d061e865a3d&v=4
url: https://github.com/jugeeem
- - login: patsatsia
- avatarUrl: https://avatars.githubusercontent.com/u/61111267?u=3271b85f7a37b479c8d0ae0a235182e83c166edf&v=4
- url: https://github.com/patsatsia
- - login: anthonycepeda
- avatarUrl: https://avatars.githubusercontent.com/u/72019805?u=60bdf46240cff8fca482ff0fc07d963fd5e1a27c&v=4
- url: https://github.com/anthonycepeda
- - login: patricioperezv
- avatarUrl: https://avatars.githubusercontent.com/u/73832292?u=5f471f156e19ee7920e62ae0f4a47b95580e61cf&v=4
- url: https://github.com/patricioperezv
- - login: chickenandstats
- avatarUrl: https://avatars.githubusercontent.com/u/79477966?u=ae2b894aa954070db1d7830dab99b49eba4e4567&v=4
- url: https://github.com/chickenandstats
+ - login: Karine-Bauch
+ avatarUrl: https://avatars.githubusercontent.com/u/90465103?u=7feb1018abb1a5631cfd9a91fea723d1ceb5f49b&v=4
+ url: https://github.com/Karine-Bauch
- login: kaoru0310
avatarUrl: https://avatars.githubusercontent.com/u/80977929?u=1b61d10142b490e56af932ddf08a390fae8ee94f&v=4
url: https://github.com/kaoru0310
- - login: jstanden
- avatarUrl: https://avatars.githubusercontent.com/u/63288?u=c3658d57d2862c607a0e19c2101c3c51876e36ad&v=4
- url: https://github.com/jstanden
- - login: knallgelb
- avatarUrl: https://avatars.githubusercontent.com/u/2358812?u=c48cb6362b309d74cbf144bd6ad3aed3eb443e82&v=4
- url: https://github.com/knallgelb
- - login: dblackrun
- avatarUrl: https://avatars.githubusercontent.com/u/3528486?v=4
- url: https://github.com/dblackrun
- - login: zsinx6
- avatarUrl: https://avatars.githubusercontent.com/u/3532625?u=ba75a5dc744d1116ccfeaaf30d41cb2fe81fe8dd&v=4
- url: https://github.com/zsinx6
- - login: kennywakeland
- avatarUrl: https://avatars.githubusercontent.com/u/3631417?u=7c8f743f1ae325dfadea7c62bbf1abd6a824fc55&v=4
- url: https://github.com/kennywakeland
- - login: aacayaco
- avatarUrl: https://avatars.githubusercontent.com/u/3634801?u=eaadda178c964178fcb64886f6c732172c8f8219&v=4
- url: https://github.com/aacayaco
- - login: anomaly
- avatarUrl: https://avatars.githubusercontent.com/u/3654837?v=4
- url: https://github.com/anomaly
- - login: mj0331
- avatarUrl: https://avatars.githubusercontent.com/u/3890353?u=1c627ac1a024515b4871de5c3ebbfaa1a57f65d4&v=4
- url: https://github.com/mj0331
- - login: gorhack
- avatarUrl: https://avatars.githubusercontent.com/u/4141690?u=ec119ebc4bdf00a7bc84657a71aa17834f4f27f3&v=4
- url: https://github.com/gorhack
- - login: Ryandaydev
- avatarUrl: https://avatars.githubusercontent.com/u/4292423?u=679ff84cb7b988c5795a5fa583857f574a055763&v=4
- url: https://github.com/Ryandaydev
- - login: jaredtrog
- avatarUrl: https://avatars.githubusercontent.com/u/4381365?v=4
- url: https://github.com/jaredtrog
+ - login: chickenandstats
+ avatarUrl: https://avatars.githubusercontent.com/u/79477966?u=ae2b894aa954070db1d7830dab99b49eba4e4567&v=4
+ url: https://github.com/chickenandstats
+ - login: patricioperezv
+ avatarUrl: https://avatars.githubusercontent.com/u/73832292?u=5f471f156e19ee7920e62ae0f4a47b95580e61cf&v=4
+ url: https://github.com/patricioperezv
+ - login: anthonycepeda
+ avatarUrl: https://avatars.githubusercontent.com/u/72019805?u=60bdf46240cff8fca482ff0fc07d963fd5e1a27c&v=4
+ url: https://github.com/anthonycepeda
+ - login: AalbatrossGuy
+ avatarUrl: https://avatars.githubusercontent.com/u/68378354?u=0bdeea9356d24f638244131f6d8d1e2d2f3601ca&v=4
+ url: https://github.com/AalbatrossGuy
+ - login: patsatsia
+ avatarUrl: https://avatars.githubusercontent.com/u/61111267?u=3271b85f7a37b479c8d0ae0a235182e83c166edf&v=4
+ url: https://github.com/patsatsia
- login: oliverxchen
avatarUrl: https://avatars.githubusercontent.com/u/4471774?u=534191f25e32eeaadda22dfab4b0a428733d5489&v=4
url: https://github.com/oliverxchen
- - login: paulcwatts
- avatarUrl: https://avatars.githubusercontent.com/u/150269?u=1819e145d573b44f0ad74b87206d21cd60331d4e&v=4
- url: https://github.com/paulcwatts
- - login: robintw
- avatarUrl: https://avatars.githubusercontent.com/u/296686?v=4
- url: https://github.com/robintw
- - login: pamelafox
- avatarUrl: https://avatars.githubusercontent.com/u/297042?v=4
- url: https://github.com/pamelafox
- - login: wshayes
- avatarUrl: https://avatars.githubusercontent.com/u/365303?u=07ca03c5ee811eb0920e633cc3c3db73dbec1aa5&v=4
- url: https://github.com/wshayes
- - login: koxudaxi
- avatarUrl: https://avatars.githubusercontent.com/u/630670?u=507d8577b4b3670546b449c4c2ccbc5af40d72f7&v=4
- url: https://github.com/koxudaxi
- - login: falkben
- avatarUrl: https://avatars.githubusercontent.com/u/653031?u=ad9838e089058c9e5a0bab94c0eec7cc181e0cd0&v=4
- url: https://github.com/falkben
- - login: mintuhouse
- avatarUrl: https://avatars.githubusercontent.com/u/769950?u=ecfbd79a97d33177e0d093ddb088283cf7fe8444&v=4
- url: https://github.com/mintuhouse
+ - login: jaredtrog
+ avatarUrl: https://avatars.githubusercontent.com/u/4381365?v=4
+ url: https://github.com/jaredtrog
+ - login: Ryandaydev
+ avatarUrl: https://avatars.githubusercontent.com/u/4292423?u=679ff84cb7b988c5795a5fa583857f574a055763&v=4
+ url: https://github.com/Ryandaydev
+ - login: gorhack
+ avatarUrl: https://avatars.githubusercontent.com/u/4141690?u=ec119ebc4bdf00a7bc84657a71aa17834f4f27f3&v=4
+ url: https://github.com/gorhack
+ - login: mj0331
+ avatarUrl: https://avatars.githubusercontent.com/u/3890353?u=1c627ac1a024515b4871de5c3ebbfaa1a57f65d4&v=4
+ url: https://github.com/mj0331
+ - login: anomaly
+ avatarUrl: https://avatars.githubusercontent.com/u/3654837?v=4
+ url: https://github.com/anomaly
+ - login: aacayaco
+ avatarUrl: https://avatars.githubusercontent.com/u/3634801?u=eaadda178c964178fcb64886f6c732172c8f8219&v=4
+ url: https://github.com/aacayaco
+ - login: kennywakeland
+ avatarUrl: https://avatars.githubusercontent.com/u/3631417?u=7c8f743f1ae325dfadea7c62bbf1abd6a824fc55&v=4
+ url: https://github.com/kennywakeland
+ - login: zsinx6
+ avatarUrl: https://avatars.githubusercontent.com/u/3532625?u=ba75a5dc744d1116ccfeaaf30d41cb2fe81fe8dd&v=4
+ url: https://github.com/zsinx6
+ - login: dblackrun
+ avatarUrl: https://avatars.githubusercontent.com/u/3528486?v=4
+ url: https://github.com/dblackrun
+ - login: knallgelb
+ avatarUrl: https://avatars.githubusercontent.com/u/2358812?u=c48cb6362b309d74cbf144bd6ad3aed3eb443e82&v=4
+ url: https://github.com/knallgelb
- login: dodo5522
avatarUrl: https://avatars.githubusercontent.com/u/1362607?u=9bf1e0e520cccc547c046610c468ce6115bbcf9f&v=4
url: https://github.com/dodo5522
- - login: wdwinslow
- avatarUrl: https://avatars.githubusercontent.com/u/11562137?u=371272f2c69e680e0559a7b0a57385e83a5dc728&v=4
- url: https://github.com/wdwinslow
- - login: jsoques
- avatarUrl: https://avatars.githubusercontent.com/u/12414216?u=620921d94196546cc8b9eae2cc4cbc3f95bab42f&v=4
- url: https://github.com/jsoques
- - login: dannywade
- avatarUrl: https://avatars.githubusercontent.com/u/13680237?u=418ee985bd41577b20fde81417fb2d901e875e8a&v=4
- url: https://github.com/dannywade
- - login: khadrawy
- avatarUrl: https://avatars.githubusercontent.com/u/13686061?u=59f25ef42ecf04c22657aac4238ce0e2d3d30304&v=4
- url: https://github.com/khadrawy
- - login: mjohnsey
- avatarUrl: https://avatars.githubusercontent.com/u/16784016?u=38fad2e6b411244560b3af99c5f5a4751bc81865&v=4
- url: https://github.com/mjohnsey
- - login: ashi-agrawal
- avatarUrl: https://avatars.githubusercontent.com/u/17105294?u=99c7a854035e5398d8e7b674f2d42baae6c957f8&v=4
- url: https://github.com/ashi-agrawal
+ - login: mintuhouse
+ avatarUrl: https://avatars.githubusercontent.com/u/769950?u=ecfbd79a97d33177e0d093ddb088283cf7fe8444&v=4
+ url: https://github.com/mintuhouse
+ - login: falkben
+ avatarUrl: https://avatars.githubusercontent.com/u/653031?u=ad9838e089058c9e5a0bab94c0eec7cc181e0cd0&v=4
+ url: https://github.com/falkben
+ - login: koxudaxi
+ avatarUrl: https://avatars.githubusercontent.com/u/630670?u=507d8577b4b3670546b449c4c2ccbc5af40d72f7&v=4
+ url: https://github.com/koxudaxi
+ - login: wshayes
+ avatarUrl: https://avatars.githubusercontent.com/u/365303?u=07ca03c5ee811eb0920e633cc3c3db73dbec1aa5&v=4
+ url: https://github.com/wshayes
+ - login: pamelafox
+ avatarUrl: https://avatars.githubusercontent.com/u/297042?v=4
+ url: https://github.com/pamelafox
+ - login: robintw
+ avatarUrl: https://avatars.githubusercontent.com/u/296686?v=4
+ url: https://github.com/robintw
+ - login: jstanden
+ avatarUrl: https://avatars.githubusercontent.com/u/63288?u=c3658d57d2862c607a0e19c2101c3c51876e36ad&v=4
+ url: https://github.com/jstanden
- login: RaamEEIL
avatarUrl: https://avatars.githubusercontent.com/u/20320552?v=4
url: https://github.com/RaamEEIL
- - login: ternaus
- avatarUrl: https://avatars.githubusercontent.com/u/5481618?u=513a26b02a39e7a28d587cd37c6cc877ea368e6e&v=4
- url: https://github.com/ternaus
- - login: eseglem
- avatarUrl: https://avatars.githubusercontent.com/u/5920492?u=208d419cf667b8ac594c82a8db01932c7e50d057&v=4
- url: https://github.com/eseglem
- - login: FernandoCelmer
- avatarUrl: https://avatars.githubusercontent.com/u/6262214?u=58ba6d5888fa7f355934e52db19f950e20b38162&v=4
- url: https://github.com/FernandoCelmer
- - login: Rehket
- avatarUrl: https://avatars.githubusercontent.com/u/7015688?u=3afb0ba200feebbc7f958950e92db34df2a3c172&v=4
- url: https://github.com/Rehket
+ - login: ashi-agrawal
+ avatarUrl: https://avatars.githubusercontent.com/u/17105294?u=99c7a854035e5398d8e7b674f2d42baae6c957f8&v=4
+ url: https://github.com/ashi-agrawal
+ - login: mjohnsey
+ avatarUrl: https://avatars.githubusercontent.com/u/16784016?u=38fad2e6b411244560b3af99c5f5a4751bc81865&v=4
+ url: https://github.com/mjohnsey
+ - login: khadrawy
+ avatarUrl: https://avatars.githubusercontent.com/u/13686061?u=59f25ef42ecf04c22657aac4238ce0e2d3d30304&v=4
+ url: https://github.com/khadrawy
+ - login: dannywade
+ avatarUrl: https://avatars.githubusercontent.com/u/13680237?u=418ee985bd41577b20fde81417fb2d901e875e8a&v=4
+ url: https://github.com/dannywade
+ - login: jsoques
+ avatarUrl: https://avatars.githubusercontent.com/u/12414216?u=620921d94196546cc8b9eae2cc4cbc3f95bab42f&v=4
+ url: https://github.com/jsoques
+ - login: wdwinslow
+ avatarUrl: https://avatars.githubusercontent.com/u/11562137?u=371272f2c69e680e0559a7b0a57385e83a5dc728&v=4
+ url: https://github.com/wdwinslow
- login: hiancdtrsnm
avatarUrl: https://avatars.githubusercontent.com/u/7343177?v=4
url: https://github.com/hiancdtrsnm
-- - login: manoelpqueiroz
+ - login: Rehket
+ avatarUrl: https://avatars.githubusercontent.com/u/7015688?u=3afb0ba200feebbc7f958950e92db34df2a3c172&v=4
+ url: https://github.com/Rehket
+ - login: FernandoCelmer
+ avatarUrl: https://avatars.githubusercontent.com/u/6262214?u=58ba6d5888fa7f355934e52db19f950e20b38162&v=4
+ url: https://github.com/FernandoCelmer
+ - login: eseglem
+ avatarUrl: https://avatars.githubusercontent.com/u/5920492?u=208d419cf667b8ac594c82a8db01932c7e50d057&v=4
+ url: https://github.com/eseglem
+ - login: ternaus
+ avatarUrl: https://avatars.githubusercontent.com/u/5481618?u=513a26b02a39e7a28d587cd37c6cc877ea368e6e&v=4
+ url: https://github.com/ternaus
+- - login: Artur-Galstyan
+ avatarUrl: https://avatars.githubusercontent.com/u/63471891?u=e8691f386037e51a737cc0ba866cd8c89e5cf109&v=4
+ url: https://github.com/Artur-Galstyan
+ - login: manoelpqueiroz
avatarUrl: https://avatars.githubusercontent.com/u/23669137?u=b12e84b28a84369ab5b30bd5a79e5788df5a0756&v=4
url: https://github.com/manoelpqueiroz
- - login: pawamoy
@@ -254,9 +251,12 @@ sponsors:
- login: hgalytoby
avatarUrl: https://avatars.githubusercontent.com/u/50397689?u=6cc9028f3db63f8f60ad21c17b1ce4b88c4e2e60&v=4
url: https://github.com/hgalytoby
- - login: nisutec
- avatarUrl: https://avatars.githubusercontent.com/u/25281462?u=e562484c451fdfc59053163f64405f8eb262b8b0&v=4
- url: https://github.com/nisutec
+ - login: johnl28
+ avatarUrl: https://avatars.githubusercontent.com/u/54412955?u=47dd06082d1c39caa90c752eb55566e4f3813957&v=4
+ url: https://github.com/johnl28
+ - login: danielunderwood
+ avatarUrl: https://avatars.githubusercontent.com/u/4472301?v=4
+ url: https://github.com/danielunderwood
- login: hoenie-ams
avatarUrl: https://avatars.githubusercontent.com/u/25708487?u=cda07434f0509ac728d9edf5e681117c0f6b818b&v=4
url: https://github.com/hoenie-ams
@@ -267,93 +267,87 @@ sponsors:
avatarUrl: https://avatars.githubusercontent.com/u/33275230?u=eb223cad27017bb1e936ee9b429b450d092d0236&v=4
url: https://github.com/engineerjoe440
- login: bnkc
- avatarUrl: https://avatars.githubusercontent.com/u/34930566?u=db5e6f4f87836cad26c2aa90ce390ce49041c5a9&v=4
+ avatarUrl: https://avatars.githubusercontent.com/u/34930566?u=4771ac4e64066f0847d40e5b29910adabd9b2372&v=4
url: https://github.com/bnkc
- login: petercool
avatarUrl: https://avatars.githubusercontent.com/u/37613029?u=75aa8c6729e6e8f85a300561c4dbeef9d65c8797&v=4
url: https://github.com/petercool
- - login: johnl28
- avatarUrl: https://avatars.githubusercontent.com/u/54412955?u=47dd06082d1c39caa90c752eb55566e4f3813957&v=4
- url: https://github.com/johnl28
- - login: PunRabbit
- avatarUrl: https://avatars.githubusercontent.com/u/70463212?u=1a835cfbc99295a60c8282f6aa6199d1b42241a5&v=4
- url: https://github.com/PunRabbit
- login: PelicanQ
avatarUrl: https://avatars.githubusercontent.com/u/77930606?v=4
url: https://github.com/PelicanQ
- - login: WillHogan
- avatarUrl: https://avatars.githubusercontent.com/u/1661551?u=8a80356e3e7d5a417157aba7ea565dabc8678327&v=4
- url: https://github.com/WillHogan
+ - login: PunRabbit
+ avatarUrl: https://avatars.githubusercontent.com/u/70463212?u=1a835cfbc99295a60c8282f6aa6199d1b42241a5&v=4
+ url: https://github.com/PunRabbit
- login: my3
avatarUrl: https://avatars.githubusercontent.com/u/1825270?v=4
url: https://github.com/my3
- - login: danielunderwood
- avatarUrl: https://avatars.githubusercontent.com/u/4472301?v=4
- url: https://github.com/danielunderwood
- - login: ddanier
- avatarUrl: https://avatars.githubusercontent.com/u/113563?u=ed1dc79de72f93bd78581f88ebc6952b62f472da&v=4
- url: https://github.com/ddanier
- - login: bryanculbertson
- avatarUrl: https://avatars.githubusercontent.com/u/144028?u=defda4f90e93429221cc667500944abde60ebe4a&v=4
- url: https://github.com/bryanculbertson
- - login: slafs
- avatarUrl: https://avatars.githubusercontent.com/u/210173?v=4
- url: https://github.com/slafs
- - login: ceb10n
- avatarUrl: https://avatars.githubusercontent.com/u/235213?u=edcce471814a1eba9f0cdaa4cd0de18921a940a6&v=4
- url: https://github.com/ceb10n
- - login: tochikuji
- avatarUrl: https://avatars.githubusercontent.com/u/851759?v=4
- url: https://github.com/tochikuji
+ - login: WillHogan
+ avatarUrl: https://avatars.githubusercontent.com/u/1661551?u=8a80356e3e7d5a417157aba7ea565dabc8678327&v=4
+ url: https://github.com/WillHogan
- login: miguelgr
avatarUrl: https://avatars.githubusercontent.com/u/1484589?u=54556072b8136efa12ae3b6902032ea2a39ace4b&v=4
url: https://github.com/miguelgr
- - login: xncbf
- avatarUrl: https://avatars.githubusercontent.com/u/9462045?u=a80a7bb349555b277645632ed66639ff43400614&v=4
- url: https://github.com/xncbf
- - login: DMantis
- avatarUrl: https://avatars.githubusercontent.com/u/9536869?u=652dd0d49717803c0cbcbf44f7740e53cf2d4892&v=4
- url: https://github.com/DMantis
- - login: hard-coders
- avatarUrl: https://avatars.githubusercontent.com/u/9651103?u=95db33927bbff1ed1c07efddeb97ac2ff33068ed&v=4
- url: https://github.com/hard-coders
- - login: mntolia
- avatarUrl: https://avatars.githubusercontent.com/u/10390224?v=4
- url: https://github.com/mntolia
- - login: Zuzah
- avatarUrl: https://avatars.githubusercontent.com/u/10934846?u=1ef43e075ddc87bd1178372bf4d95ee6175cae27&v=4
- url: https://github.com/Zuzah
- - login: TheR1D
- avatarUrl: https://avatars.githubusercontent.com/u/16740832?u=b0dfdbdb27b79729430c71c6128962f77b7b53f7&v=4
- url: https://github.com/TheR1D
+ - login: tochikuji
+ avatarUrl: https://avatars.githubusercontent.com/u/851759?v=4
+ url: https://github.com/tochikuji
+ - login: ceb10n
+ avatarUrl: https://avatars.githubusercontent.com/u/235213?u=edcce471814a1eba9f0cdaa4cd0de18921a940a6&v=4
+ url: https://github.com/ceb10n
+ - login: slafs
+ avatarUrl: https://avatars.githubusercontent.com/u/210173?v=4
+ url: https://github.com/slafs
+ - login: bryanculbertson
+ avatarUrl: https://avatars.githubusercontent.com/u/144028?u=defda4f90e93429221cc667500944abde60ebe4a&v=4
+ url: https://github.com/bryanculbertson
+ - login: ddanier
+ avatarUrl: https://avatars.githubusercontent.com/u/113563?u=ed1dc79de72f93bd78581f88ebc6952b62f472da&v=4
+ url: https://github.com/ddanier
+ - login: nisutec
+ avatarUrl: https://avatars.githubusercontent.com/u/25281462?u=e562484c451fdfc59053163f64405f8eb262b8b0&v=4
+ url: https://github.com/nisutec
- login: joshuatz
avatarUrl: https://avatars.githubusercontent.com/u/17817563?u=f1bf05b690d1fc164218f0b420cdd3acb7913e21&v=4
url: https://github.com/joshuatz
- - login: rangulvers
- avatarUrl: https://avatars.githubusercontent.com/u/5235430?u=e254d4af4ace5a05fa58372ae677c7d26f0d5a53&v=4
- url: https://github.com/rangulvers
- - login: sdevkota
- avatarUrl: https://avatars.githubusercontent.com/u/5250987?u=4ed9a120c89805a8aefda1cbdc0cf6512e64d1b4&v=4
- url: https://github.com/sdevkota
- - login: Baghdady92
- avatarUrl: https://avatars.githubusercontent.com/u/5708590?v=4
- url: https://github.com/Baghdady92
- - login: KentShikama
- avatarUrl: https://avatars.githubusercontent.com/u/6329898?u=8b236810db9b96333230430837e1f021f9246da1&v=4
- url: https://github.com/KentShikama
- - login: katnoria
- avatarUrl: https://avatars.githubusercontent.com/u/7674948?u=09767eb13e07e09496c5fee4e5ce21d9eac34a56&v=4
- url: https://github.com/katnoria
- - login: harsh183
- avatarUrl: https://avatars.githubusercontent.com/u/7780198?v=4
- url: https://github.com/harsh183
+ - login: TheR1D
+ avatarUrl: https://avatars.githubusercontent.com/u/16740832?u=b0dfdbdb27b79729430c71c6128962f77b7b53f7&v=4
+ url: https://github.com/TheR1D
+ - login: Zuzah
+ avatarUrl: https://avatars.githubusercontent.com/u/10934846?u=1ef43e075ddc87bd1178372bf4d95ee6175cae27&v=4
+ url: https://github.com/Zuzah
+ - login: mntolia
+ avatarUrl: https://avatars.githubusercontent.com/u/10390224?v=4
+ url: https://github.com/mntolia
+ - login: hard-coders
+ avatarUrl: https://avatars.githubusercontent.com/u/9651103?u=78d12d1acdf853c817700145e73de7fd9e5d068b&v=4
+ url: https://github.com/hard-coders
+ - login: DMantis
+ avatarUrl: https://avatars.githubusercontent.com/u/9536869?u=652dd0d49717803c0cbcbf44f7740e53cf2d4892&v=4
+ url: https://github.com/DMantis
+ - login: xncbf
+ avatarUrl: https://avatars.githubusercontent.com/u/9462045?u=a80a7bb349555b277645632ed66639ff43400614&v=4
+ url: https://github.com/xncbf
- login: moonape1226
avatarUrl: https://avatars.githubusercontent.com/u/8532038?u=d9f8b855a429fff9397c3833c2ff83849ebf989d&v=4
url: https://github.com/moonape1226
-- - login: andrecorumba
- avatarUrl: https://avatars.githubusercontent.com/u/37807517?u=9b9be3b41da9bda60957da9ef37b50dbf65baa61&v=4
- url: https://github.com/andrecorumba
- - login: KOZ39
+ - login: harsh183
+ avatarUrl: https://avatars.githubusercontent.com/u/7780198?v=4
+ url: https://github.com/harsh183
+ - login: katnoria
+ avatarUrl: https://avatars.githubusercontent.com/u/7674948?u=09767eb13e07e09496c5fee4e5ce21d9eac34a56&v=4
+ url: https://github.com/katnoria
+ - login: KentShikama
+ avatarUrl: https://avatars.githubusercontent.com/u/6329898?u=8b236810db9b96333230430837e1f021f9246da1&v=4
+ url: https://github.com/KentShikama
+ - login: Baghdady92
+ avatarUrl: https://avatars.githubusercontent.com/u/5708590?v=4
+ url: https://github.com/Baghdady92
+ - login: sdevkota
+ avatarUrl: https://avatars.githubusercontent.com/u/5250987?u=4ed9a120c89805a8aefda1cbdc0cf6512e64d1b4&v=4
+ url: https://github.com/sdevkota
+ - login: rangulvers
+ avatarUrl: https://avatars.githubusercontent.com/u/5235430?u=e254d4af4ace5a05fa58372ae677c7d26f0d5a53&v=4
+ url: https://github.com/rangulvers
+- - login: KOZ39
avatarUrl: https://avatars.githubusercontent.com/u/38822500?u=9dfc0a697df1c9628f08e20dc3fb17b1afc4e5a7&v=4
url: https://github.com/KOZ39
- login: rwxd
@@ -365,27 +359,24 @@ sponsors:
- login: Olegt0rr
avatarUrl: https://avatars.githubusercontent.com/u/25399456?u=3e87b5239a2f4600975ba13be73054f8567c6060&v=4
url: https://github.com/Olegt0rr
- - login: dinoz0rg
- avatarUrl: https://avatars.githubusercontent.com/u/32940067?u=739cda1eb123a2dd5e1db45c361396f239e23f8b&v=4
- url: https://github.com/dinoz0rg
- login: larsyngvelundin
avatarUrl: https://avatars.githubusercontent.com/u/34173819?u=74958599695bf83ac9f1addd935a51548a10c6b0&v=4
url: https://github.com/larsyngvelundin
- - login: hippoley
- avatarUrl: https://avatars.githubusercontent.com/u/135493401?u=1164ef48a645a7c12664fabc1638fbb7e1c459b0&v=4
- url: https://github.com/hippoley
- - login: 4anklee
- avatarUrl: https://avatars.githubusercontent.com/u/144109238?u=a79c0d581b2a3d8f3897e7ef4c012640a6c1eb3a&v=4
- url: https://github.com/4anklee
+ - login: andrecorumba
+ avatarUrl: https://avatars.githubusercontent.com/u/37807517?u=9b9be3b41da9bda60957da9ef37b50dbf65baa61&v=4
+ url: https://github.com/andrecorumba
- login: CoderDeltaLAN
avatarUrl: https://avatars.githubusercontent.com/u/152043745?u=4ff541efffb7d134e60c5fcf2dd1e343f90bb782&v=4
url: https://github.com/CoderDeltaLAN
- - login: onestn
- avatarUrl: https://avatars.githubusercontent.com/u/62360849?u=746dd21c34e7e06eefb11b03e8bb01aaae3c2a4f&v=4
- url: https://github.com/onestn
+ - login: hippoley
+ avatarUrl: https://avatars.githubusercontent.com/u/135493401?u=1164ef48a645a7c12664fabc1638fbb7e1c459b0&v=4
+ url: https://github.com/hippoley
- login: nayasinghania
avatarUrl: https://avatars.githubusercontent.com/u/74111380?u=752e99a5e139389fdc0a0677122adc08438eb076&v=4
url: https://github.com/nayasinghania
+ - login: onestn
+ avatarUrl: https://avatars.githubusercontent.com/u/62360849?u=746dd21c34e7e06eefb11b03e8bb01aaae3c2a4f&v=4
+ url: https://github.com/onestn
- login: Toothwitch
avatarUrl: https://avatars.githubusercontent.com/u/1710406?u=5eebb23b46cd26e48643b9e5179536cad491c17a&v=4
url: https://github.com/Toothwitch
diff --git a/docs/en/data/topic_repos.yml b/docs/en/data/topic_repos.yml
index cb7e3c033e..d089c7e5a7 100644
--- a/docs/en/data/topic_repos.yml
+++ b/docs/en/data/topic_repos.yml
@@ -1,495 +1,495 @@
- name: full-stack-fastapi-template
html_url: https://github.com/fastapi/full-stack-fastapi-template
- stars: 39475
+ stars: 40334
owner_login: fastapi
owner_html_url: https://github.com/fastapi
- name: Hello-Python
html_url: https://github.com/mouredev/Hello-Python
- stars: 33090
+ stars: 33628
owner_login: mouredev
owner_html_url: https://github.com/mouredev
- name: serve
html_url: https://github.com/jina-ai/serve
- stars: 21798
+ stars: 21817
owner_login: jina-ai
owner_html_url: https://github.com/jina-ai
- name: HivisionIDPhotos
html_url: https://github.com/Zeyi-Lin/HivisionIDPhotos
- stars: 20258
+ stars: 20409
owner_login: Zeyi-Lin
owner_html_url: https://github.com/Zeyi-Lin
- name: sqlmodel
html_url: https://github.com/fastapi/sqlmodel
- stars: 17212
+ stars: 17415
owner_login: fastapi
owner_html_url: https://github.com/fastapi
-- name: Douyin_TikTok_Download_API
- html_url: https://github.com/Evil0ctal/Douyin_TikTok_Download_API
- stars: 15145
- owner_login: Evil0ctal
- owner_html_url: https://github.com/Evil0ctal
- name: fastapi-best-practices
html_url: https://github.com/zhanymkanov/fastapi-best-practices
- stars: 14644
+ stars: 15776
owner_login: zhanymkanov
owner_html_url: https://github.com/zhanymkanov
+- name: Douyin_TikTok_Download_API
+ html_url: https://github.com/Evil0ctal/Douyin_TikTok_Download_API
+ stars: 15588
+ owner_login: Evil0ctal
+ owner_html_url: https://github.com/Evil0ctal
- name: machine-learning-zoomcamp
html_url: https://github.com/DataTalksClub/machine-learning-zoomcamp
- stars: 12320
+ stars: 12447
owner_login: DataTalksClub
owner_html_url: https://github.com/DataTalksClub
-- name: fastapi_mcp
- html_url: https://github.com/tadata-org/fastapi_mcp
- stars: 11174
- owner_login: tadata-org
- owner_html_url: https://github.com/tadata-org
- name: SurfSense
html_url: https://github.com/MODSetter/SurfSense
- stars: 10858
+ stars: 12128
owner_login: MODSetter
owner_html_url: https://github.com/MODSetter
+- name: fastapi_mcp
+ html_url: https://github.com/tadata-org/fastapi_mcp
+ stars: 11326
+ owner_login: tadata-org
+ owner_html_url: https://github.com/tadata-org
- name: awesome-fastapi
html_url: https://github.com/mjhea0/awesome-fastapi
- stars: 10758
+ stars: 10901
owner_login: mjhea0
owner_html_url: https://github.com/mjhea0
- name: XHS-Downloader
html_url: https://github.com/JoeanAmier/XHS-Downloader
- stars: 9313
+ stars: 9584
owner_login: JoeanAmier
owner_html_url: https://github.com/JoeanAmier
-- name: FastUI
- html_url: https://github.com/pydantic/FastUI
- stars: 8915
- owner_login: pydantic
- owner_html_url: https://github.com/pydantic
- name: polar
html_url: https://github.com/polarsource/polar
- stars: 8339
+ stars: 8951
owner_login: polarsource
owner_html_url: https://github.com/polarsource
+- name: FastUI
+ html_url: https://github.com/pydantic/FastUI
+ stars: 8934
+ owner_login: pydantic
+ owner_html_url: https://github.com/pydantic
- name: FileCodeBox
html_url: https://github.com/vastsa/FileCodeBox
- stars: 7721
+ stars: 7934
owner_login: vastsa
owner_html_url: https://github.com/vastsa
- name: nonebot2
html_url: https://github.com/nonebot/nonebot2
- stars: 7170
+ stars: 7248
owner_login: nonebot
owner_html_url: https://github.com/nonebot
- name: hatchet
html_url: https://github.com/hatchet-dev/hatchet
- stars: 6253
+ stars: 6392
owner_login: hatchet-dev
owner_html_url: https://github.com/hatchet-dev
- name: fastapi-users
html_url: https://github.com/fastapi-users/fastapi-users
- stars: 5849
+ stars: 5899
owner_login: fastapi-users
owner_html_url: https://github.com/fastapi-users
- name: serge
html_url: https://github.com/serge-chat/serge
- stars: 5756
+ stars: 5754
owner_login: serge-chat
owner_html_url: https://github.com/serge-chat
- name: strawberry
html_url: https://github.com/strawberry-graphql/strawberry
- stars: 4569
+ stars: 4577
owner_login: strawberry-graphql
owner_html_url: https://github.com/strawberry-graphql
-- name: chatgpt-web-share
- html_url: https://github.com/chatpire/chatgpt-web-share
- stars: 4294
- owner_login: chatpire
- owner_html_url: https://github.com/chatpire
- name: poem
html_url: https://github.com/poem-web/poem
- stars: 4276
+ stars: 4303
owner_login: poem-web
owner_html_url: https://github.com/poem-web
+- name: chatgpt-web-share
+ html_url: https://github.com/chatpire/chatgpt-web-share
+ stars: 4287
+ owner_login: chatpire
+ owner_html_url: https://github.com/chatpire
- name: dynaconf
html_url: https://github.com/dynaconf/dynaconf
- stars: 4202
+ stars: 4221
owner_login: dynaconf
owner_html_url: https://github.com/dynaconf
-- name: atrilabs-engine
- html_url: https://github.com/Atri-Labs/atrilabs-engine
- stars: 4093
- owner_login: Atri-Labs
- owner_html_url: https://github.com/Atri-Labs
- name: Kokoro-FastAPI
html_url: https://github.com/remsky/Kokoro-FastAPI
- stars: 4019
+ stars: 4181
owner_login: remsky
owner_html_url: https://github.com/remsky
+- name: atrilabs-engine
+ html_url: https://github.com/Atri-Labs/atrilabs-engine
+ stars: 4090
+ owner_login: Atri-Labs
+ owner_html_url: https://github.com/Atri-Labs
+- name: devpush
+ html_url: https://github.com/hunvreus/devpush
+ stars: 4037
+ owner_login: hunvreus
+ owner_html_url: https://github.com/hunvreus
- name: logfire
html_url: https://github.com/pydantic/logfire
- stars: 3805
+ stars: 3896
owner_login: pydantic
owner_html_url: https://github.com/pydantic
- name: LitServe
html_url: https://github.com/Lightning-AI/LitServe
- stars: 3719
+ stars: 3756
owner_login: Lightning-AI
owner_html_url: https://github.com/Lightning-AI
-- name: fastapi-admin
- html_url: https://github.com/fastapi-admin/fastapi-admin
- stars: 3632
- owner_login: fastapi-admin
- owner_html_url: https://github.com/fastapi-admin
-- name: datamodel-code-generator
- html_url: https://github.com/koxudaxi/datamodel-code-generator
- stars: 3609
- owner_login: koxudaxi
- owner_html_url: https://github.com/koxudaxi
- name: huma
html_url: https://github.com/danielgtaylor/huma
- stars: 3603
+ stars: 3702
owner_login: danielgtaylor
owner_html_url: https://github.com/danielgtaylor
+- name: Yuxi-Know
+ html_url: https://github.com/xerrors/Yuxi-Know
+ stars: 3680
+ owner_login: xerrors
+ owner_html_url: https://github.com/xerrors
+- name: datamodel-code-generator
+ html_url: https://github.com/koxudaxi/datamodel-code-generator
+ stars: 3675
+ owner_login: koxudaxi
+ owner_html_url: https://github.com/koxudaxi
+- name: fastapi-admin
+ html_url: https://github.com/fastapi-admin/fastapi-admin
+ stars: 3659
+ owner_login: fastapi-admin
+ owner_html_url: https://github.com/fastapi-admin
- name: farfalle
html_url: https://github.com/rashadphz/farfalle
- stars: 3490
+ stars: 3497
owner_login: rashadphz
owner_html_url: https://github.com/rashadphz
- name: tracecat
html_url: https://github.com/TracecatHQ/tracecat
- stars: 3379
+ stars: 3421
owner_login: TracecatHQ
owner_html_url: https://github.com/TracecatHQ
- name: opyrator
html_url: https://github.com/ml-tooling/opyrator
- stars: 3135
+ stars: 3136
owner_login: ml-tooling
owner_html_url: https://github.com/ml-tooling
- name: docarray
html_url: https://github.com/docarray/docarray
- stars: 3114
+ stars: 3111
owner_login: docarray
owner_html_url: https://github.com/docarray
-- name: devpush
- html_url: https://github.com/hunvreus/devpush
- stars: 3097
- owner_login: hunvreus
- owner_html_url: https://github.com/hunvreus
- name: fastapi-realworld-example-app
html_url: https://github.com/nsidnev/fastapi-realworld-example-app
- stars: 3050
+ stars: 3051
owner_login: nsidnev
owner_html_url: https://github.com/nsidnev
-- name: uvicorn-gunicorn-fastapi-docker
- html_url: https://github.com/tiangolo/uvicorn-gunicorn-fastapi-docker
- stars: 2911
- owner_login: tiangolo
- owner_html_url: https://github.com/tiangolo
- name: mcp-context-forge
html_url: https://github.com/IBM/mcp-context-forge
- stars: 2899
+ stars: 3034
owner_login: IBM
owner_html_url: https://github.com/IBM
-- name: best-of-web-python
- html_url: https://github.com/ml-tooling/best-of-web-python
- stars: 2648
- owner_login: ml-tooling
- owner_html_url: https://github.com/ml-tooling
+- name: uvicorn-gunicorn-fastapi-docker
+ html_url: https://github.com/tiangolo/uvicorn-gunicorn-fastapi-docker
+ stars: 2904
+ owner_login: tiangolo
+ owner_html_url: https://github.com/tiangolo
- name: FastAPI-template
html_url: https://github.com/s3rius/FastAPI-template
- stars: 2637
+ stars: 2680
owner_login: s3rius
owner_html_url: https://github.com/s3rius
+- name: best-of-web-python
+ html_url: https://github.com/ml-tooling/best-of-web-python
+ stars: 2662
+ owner_login: ml-tooling
+ owner_html_url: https://github.com/ml-tooling
- name: YC-Killer
html_url: https://github.com/sahibzada-allahyar/YC-Killer
- stars: 2599
+ stars: 2614
owner_login: sahibzada-allahyar
owner_html_url: https://github.com/sahibzada-allahyar
-- name: fastapi-react
- html_url: https://github.com/Buuntu/fastapi-react
- stars: 2569
- owner_login: Buuntu
- owner_html_url: https://github.com/Buuntu
-- name: Yuxi-Know
- html_url: https://github.com/xerrors/Yuxi-Know
- stars: 2563
- owner_login: xerrors
- owner_html_url: https://github.com/xerrors
- name: sqladmin
html_url: https://github.com/aminalaee/sqladmin
- stars: 2558
+ stars: 2587
owner_login: aminalaee
owner_html_url: https://github.com/aminalaee
+- name: fastapi-react
+ html_url: https://github.com/Buuntu/fastapi-react
+ stars: 2566
+ owner_login: Buuntu
+ owner_html_url: https://github.com/Buuntu
- name: RasaGPT
html_url: https://github.com/paulpierre/RasaGPT
- stars: 2451
+ stars: 2456
owner_login: paulpierre
owner_html_url: https://github.com/paulpierre
- name: supabase-py
html_url: https://github.com/supabase/supabase-py
- stars: 2344
+ stars: 2394
owner_login: supabase
owner_html_url: https://github.com/supabase
- name: nextpy
html_url: https://github.com/dot-agent/nextpy
- stars: 2335
+ stars: 2338
owner_login: dot-agent
owner_html_url: https://github.com/dot-agent
- name: fastapi-utils
html_url: https://github.com/fastapiutils/fastapi-utils
- stars: 2291
+ stars: 2289
owner_login: fastapiutils
owner_html_url: https://github.com/fastapiutils
-- name: 30-Days-of-Python
- html_url: https://github.com/codingforentrepreneurs/30-Days-of-Python
- stars: 2220
- owner_login: codingforentrepreneurs
- owner_html_url: https://github.com/codingforentrepreneurs
- name: langserve
html_url: https://github.com/langchain-ai/langserve
- stars: 2215
+ stars: 2234
owner_login: langchain-ai
owner_html_url: https://github.com/langchain-ai
+- name: 30-Days-of-Python
+ html_url: https://github.com/codingforentrepreneurs/30-Days-of-Python
+ stars: 2232
+ owner_login: codingforentrepreneurs
+ owner_html_url: https://github.com/codingforentrepreneurs
- name: solara
html_url: https://github.com/widgetti/solara
- stars: 2122
+ stars: 2141
owner_login: widgetti
owner_html_url: https://github.com/widgetti
- name: mangum
html_url: https://github.com/Kludex/mangum
- stars: 2029
+ stars: 2046
owner_login: Kludex
owner_html_url: https://github.com/Kludex
+- name: fastapi_best_architecture
+ html_url: https://github.com/fastapi-practices/fastapi_best_architecture
+ stars: 1963
+ owner_login: fastapi-practices
+ owner_html_url: https://github.com/fastapi-practices
+- name: NoteDiscovery
+ html_url: https://github.com/gamosoft/NoteDiscovery
+ stars: 1943
+ owner_login: gamosoft
+ owner_html_url: https://github.com/gamosoft
- name: agentkit
html_url: https://github.com/BCG-X-Official/agentkit
- stars: 1912
+ stars: 1936
owner_login: BCG-X-Official
owner_html_url: https://github.com/BCG-X-Official
+- name: vue-fastapi-admin
+ html_url: https://github.com/mizhexiaoxiao/vue-fastapi-admin
+ stars: 1909
+ owner_login: mizhexiaoxiao
+ owner_html_url: https://github.com/mizhexiaoxiao
- name: manage-fastapi
html_url: https://github.com/ycd/manage-fastapi
- stars: 1885
+ stars: 1887
owner_login: ycd
owner_html_url: https://github.com/ycd
- name: openapi-python-client
html_url: https://github.com/openapi-generators/openapi-python-client
- stars: 1862
+ stars: 1879
owner_login: openapi-generators
owner_html_url: https://github.com/openapi-generators
-- name: piccolo
- html_url: https://github.com/piccolo-orm/piccolo
- stars: 1836
- owner_login: piccolo-orm
- owner_html_url: https://github.com/piccolo-orm
-- name: vue-fastapi-admin
- html_url: https://github.com/mizhexiaoxiao/vue-fastapi-admin
- stars: 1831
- owner_login: mizhexiaoxiao
- owner_html_url: https://github.com/mizhexiaoxiao
-- name: python-week-2022
- html_url: https://github.com/rochacbruno/python-week-2022
- stars: 1817
- owner_login: rochacbruno
- owner_html_url: https://github.com/rochacbruno
- name: slowapi
html_url: https://github.com/laurentS/slowapi
- stars: 1798
+ stars: 1845
owner_login: laurentS
owner_html_url: https://github.com/laurentS
+- name: piccolo
+ html_url: https://github.com/piccolo-orm/piccolo
+ stars: 1843
+ owner_login: piccolo-orm
+ owner_html_url: https://github.com/piccolo-orm
+- name: python-week-2022
+ html_url: https://github.com/rochacbruno/python-week-2022
+ stars: 1813
+ owner_login: rochacbruno
+ owner_html_url: https://github.com/rochacbruno
- name: fastapi-cache
html_url: https://github.com/long2ice/fastapi-cache
- stars: 1789
+ stars: 1805
owner_login: long2ice
owner_html_url: https://github.com/long2ice
- name: ormar
html_url: https://github.com/collerek/ormar
- stars: 1783
+ stars: 1785
owner_login: collerek
owner_html_url: https://github.com/collerek
-- name: termpair
- html_url: https://github.com/cs01/termpair
- stars: 1716
- owner_login: cs01
- owner_html_url: https://github.com/cs01
-- name: FastAPI-boilerplate
- html_url: https://github.com/benavlabs/FastAPI-boilerplate
- stars: 1660
- owner_login: benavlabs
- owner_html_url: https://github.com/benavlabs
- name: fastapi-langgraph-agent-production-ready-template
html_url: https://github.com/wassim249/fastapi-langgraph-agent-production-ready-template
- stars: 1638
+ stars: 1780
owner_login: wassim249
owner_html_url: https://github.com/wassim249
-- name: langchain-serve
- html_url: https://github.com/jina-ai/langchain-serve
- stars: 1635
- owner_login: jina-ai
- owner_html_url: https://github.com/jina-ai
-- name: awesome-fastapi-projects
- html_url: https://github.com/Kludex/awesome-fastapi-projects
- stars: 1589
- owner_login: Kludex
- owner_html_url: https://github.com/Kludex
-- name: fastapi-pagination
- html_url: https://github.com/uriyyo/fastapi-pagination
- stars: 1585
- owner_login: uriyyo
- owner_html_url: https://github.com/uriyyo
-- name: coronavirus-tracker-api
- html_url: https://github.com/ExpDev07/coronavirus-tracker-api
- stars: 1574
- owner_login: ExpDev07
- owner_html_url: https://github.com/ExpDev07
+- name: FastAPI-boilerplate
+ html_url: https://github.com/benavlabs/FastAPI-boilerplate
+ stars: 1734
+ owner_login: benavlabs
+ owner_html_url: https://github.com/benavlabs
+- name: termpair
+ html_url: https://github.com/cs01/termpair
+ stars: 1724
+ owner_login: cs01
+ owner_html_url: https://github.com/cs01
- name: fastapi-crudrouter
html_url: https://github.com/awtkns/fastapi-crudrouter
- stars: 1559
+ stars: 1671
owner_login: awtkns
owner_html_url: https://github.com/awtkns
+- name: langchain-serve
+ html_url: https://github.com/jina-ai/langchain-serve
+ stars: 1633
+ owner_login: jina-ai
+ owner_html_url: https://github.com/jina-ai
+- name: fastapi-pagination
+ html_url: https://github.com/uriyyo/fastapi-pagination
+ stars: 1588
+ owner_login: uriyyo
+ owner_html_url: https://github.com/uriyyo
+- name: awesome-fastapi-projects
+ html_url: https://github.com/Kludex/awesome-fastapi-projects
+ stars: 1583
+ owner_login: Kludex
+ owner_html_url: https://github.com/Kludex
+- name: coronavirus-tracker-api
+ html_url: https://github.com/ExpDev07/coronavirus-tracker-api
+ stars: 1571
+ owner_login: ExpDev07
+ owner_html_url: https://github.com/ExpDev07
- name: bracket
html_url: https://github.com/evroon/bracket
- stars: 1489
+ stars: 1549
owner_login: evroon
owner_html_url: https://github.com/evroon
- name: fastapi-amis-admin
html_url: https://github.com/amisadmin/fastapi-amis-admin
- stars: 1475
+ stars: 1491
owner_login: amisadmin
owner_html_url: https://github.com/amisadmin
- name: fastapi-boilerplate
html_url: https://github.com/teamhide/fastapi-boilerplate
- stars: 1436
+ stars: 1452
owner_login: teamhide
owner_html_url: https://github.com/teamhide
-- name: awesome-python-resources
- html_url: https://github.com/DjangoEx/awesome-python-resources
- stars: 1426
- owner_login: DjangoEx
- owner_html_url: https://github.com/DjangoEx
- name: fastcrud
html_url: https://github.com/benavlabs/fastcrud
- stars: 1414
+ stars: 1452
owner_login: benavlabs
owner_html_url: https://github.com/benavlabs
+- name: awesome-python-resources
+ html_url: https://github.com/DjangoEx/awesome-python-resources
+ stars: 1430
+ owner_login: DjangoEx
+ owner_html_url: https://github.com/DjangoEx
- name: prometheus-fastapi-instrumentator
html_url: https://github.com/trallnag/prometheus-fastapi-instrumentator
- stars: 1388
+ stars: 1399
owner_login: trallnag
owner_html_url: https://github.com/trallnag
-- name: fastapi_best_architecture
- html_url: https://github.com/fastapi-practices/fastapi_best_architecture
- stars: 1378
- owner_login: fastapi-practices
- owner_html_url: https://github.com/fastapi-practices
- name: fastapi-code-generator
html_url: https://github.com/koxudaxi/fastapi-code-generator
- stars: 1375
+ stars: 1371
owner_login: koxudaxi
owner_html_url: https://github.com/koxudaxi
+- name: fastapi-tutorial
+ html_url: https://github.com/liaogx/fastapi-tutorial
+ stars: 1346
+ owner_login: liaogx
+ owner_html_url: https://github.com/liaogx
- name: budgetml
html_url: https://github.com/ebhy/budgetml
stars: 1345
owner_login: ebhy
owner_html_url: https://github.com/ebhy
-- name: fastapi-tutorial
- html_url: https://github.com/liaogx/fastapi-tutorial
- stars: 1327
- owner_login: liaogx
- owner_html_url: https://github.com/liaogx
-- name: fastapi-alembic-sqlmodel-async
- html_url: https://github.com/jonra1993/fastapi-alembic-sqlmodel-async
- stars: 1259
- owner_login: jonra1993
- owner_html_url: https://github.com/jonra1993
- name: fastapi-scaff
html_url: https://github.com/atpuxiner/fastapi-scaff
- stars: 1255
+ stars: 1331
owner_login: atpuxiner
owner_html_url: https://github.com/atpuxiner
-- name: bedrock-chat
- html_url: https://github.com/aws-samples/bedrock-chat
- stars: 1254
- owner_login: aws-samples
- owner_html_url: https://github.com/aws-samples
- name: bolt-python
html_url: https://github.com/slackapi/bolt-python
- stars: 1253
+ stars: 1266
owner_login: slackapi
owner_html_url: https://github.com/slackapi
+- name: bedrock-chat
+ html_url: https://github.com/aws-samples/bedrock-chat
+ stars: 1266
+ owner_login: aws-samples
+ owner_html_url: https://github.com/aws-samples
+- name: fastapi-alembic-sqlmodel-async
+ html_url: https://github.com/jonra1993/fastapi-alembic-sqlmodel-async
+ stars: 1260
+ owner_login: jonra1993
+ owner_html_url: https://github.com/jonra1993
- name: fastapi_production_template
html_url: https://github.com/zhanymkanov/fastapi_production_template
- stars: 1217
+ stars: 1222
owner_login: zhanymkanov
owner_html_url: https://github.com/zhanymkanov
- name: langchain-extract
html_url: https://github.com/langchain-ai/langchain-extract
- stars: 1176
+ stars: 1179
owner_login: langchain-ai
owner_html_url: https://github.com/langchain-ai
- name: restish
html_url: https://github.com/rest-sh/restish
- stars: 1140
+ stars: 1152
owner_login: rest-sh
owner_html_url: https://github.com/rest-sh
- name: odmantic
html_url: https://github.com/art049/odmantic
- stars: 1138
+ stars: 1143
owner_login: art049
owner_html_url: https://github.com/art049
- name: authx
html_url: https://github.com/yezz123/authx
- stars: 1119
+ stars: 1128
owner_login: yezz123
owner_html_url: https://github.com/yezz123
-- name: NoteDiscovery
- html_url: https://github.com/gamosoft/NoteDiscovery
- stars: 1107
- owner_login: gamosoft
- owner_html_url: https://github.com/gamosoft
-- name: flock
- html_url: https://github.com/Onelevenvy/flock
- stars: 1055
- owner_login: Onelevenvy
- owner_html_url: https://github.com/Onelevenvy
-- name: fastapi-observability
- html_url: https://github.com/blueswen/fastapi-observability
- stars: 1038
- owner_login: blueswen
- owner_html_url: https://github.com/blueswen
+- name: SAG
+ html_url: https://github.com/Zleap-AI/SAG
+ stars: 1104
+ owner_login: Zleap-AI
+ owner_html_url: https://github.com/Zleap-AI
- name: aktools
html_url: https://github.com/akfamily/aktools
- stars: 1027
+ stars: 1072
owner_login: akfamily
owner_html_url: https://github.com/akfamily
- name: RuoYi-Vue3-FastAPI
html_url: https://github.com/insistence/RuoYi-Vue3-FastAPI
- stars: 1016
+ stars: 1063
owner_login: insistence
owner_html_url: https://github.com/insistence
-- name: autollm
- html_url: https://github.com/viddexa/autollm
- stars: 1002
- owner_login: viddexa
- owner_html_url: https://github.com/viddexa
-- name: titiler
- html_url: https://github.com/developmentseed/titiler
- stars: 999
- owner_login: developmentseed
- owner_html_url: https://github.com/developmentseed
-- name: lanarky
- html_url: https://github.com/ajndkr/lanarky
- stars: 994
- owner_login: ajndkr
- owner_html_url: https://github.com/ajndkr
-- name: every-pdf
- html_url: https://github.com/DDULDDUCK/every-pdf
- stars: 985
- owner_login: DDULDDUCK
- owner_html_url: https://github.com/DDULDDUCK
+- name: flock
+ html_url: https://github.com/Onelevenvy/flock
+ stars: 1059
+ owner_login: Onelevenvy
+ owner_html_url: https://github.com/Onelevenvy
+- name: fastapi-observability
+ html_url: https://github.com/blueswen/fastapi-observability
+ stars: 1046
+ owner_login: blueswen
+ owner_html_url: https://github.com/blueswen
- name: enterprise-deep-research
html_url: https://github.com/SalesforceAIResearch/enterprise-deep-research
- stars: 973
+ stars: 1019
owner_login: SalesforceAIResearch
owner_html_url: https://github.com/SalesforceAIResearch
-- name: fastapi-mail
- html_url: https://github.com/sabuhish/fastapi-mail
- stars: 964
- owner_login: sabuhish
- owner_html_url: https://github.com/sabuhish
+- name: titiler
+ html_url: https://github.com/developmentseed/titiler
+ stars: 1016
+ owner_login: developmentseed
+ owner_html_url: https://github.com/developmentseed
+- name: every-pdf
+ html_url: https://github.com/DDULDDUCK/every-pdf
+ stars: 1004
+ owner_login: DDULDDUCK
+ owner_html_url: https://github.com/DDULDDUCK
+- name: autollm
+ html_url: https://github.com/viddexa/autollm
+ stars: 1003
+ owner_login: viddexa
+ owner_html_url: https://github.com/viddexa
+- name: lanarky
+ html_url: https://github.com/ajndkr/lanarky
+ stars: 996
+ owner_login: ajndkr
+ owner_html_url: https://github.com/ajndkr
diff --git a/docs/en/data/translation_reviewers.yml b/docs/en/data/translation_reviewers.yml
index c3d3d0388d..62db8e805d 100644
--- a/docs/en/data/translation_reviewers.yml
+++ b/docs/en/data/translation_reviewers.yml
@@ -15,7 +15,7 @@ sodaMelon:
url: https://github.com/sodaMelon
ceb10n:
login: ceb10n
- count: 116
+ count: 117
avatarUrl: https://avatars.githubusercontent.com/u/235213?u=edcce471814a1eba9f0cdaa4cd0de18921a940a6&v=4
url: https://github.com/ceb10n
tokusumi:
@@ -23,16 +23,16 @@ tokusumi:
count: 104
avatarUrl: https://avatars.githubusercontent.com/u/41147016?u=55010621aece725aa702270b54fed829b6a1fe60&v=4
url: https://github.com/tokusumi
+hard-coders:
+ login: hard-coders
+ count: 96
+ avatarUrl: https://avatars.githubusercontent.com/u/9651103?u=78d12d1acdf853c817700145e73de7fd9e5d068b&v=4
+ url: https://github.com/hard-coders
hasansezertasan:
login: hasansezertasan
count: 95
avatarUrl: https://avatars.githubusercontent.com/u/13135006?u=99f0b0f0fc47e88e8abb337b4447357939ef93e7&v=4
url: https://github.com/hasansezertasan
-hard-coders:
- login: hard-coders
- count: 93
- avatarUrl: https://avatars.githubusercontent.com/u/9651103?u=95db33927bbff1ed1c07efddeb97ac2ff33068ed&v=4
- url: https://github.com/hard-coders
alv2017:
login: alv2017
count: 88
@@ -40,7 +40,7 @@ alv2017:
url: https://github.com/alv2017
nazarepiedady:
login: nazarepiedady
- count: 86
+ count: 87
avatarUrl: https://avatars.githubusercontent.com/u/31008635?u=f69ddc4ea8bda3bdfac7aa0e2ea38de282e6ee2d&v=4
url: https://github.com/nazarepiedady
AlertRED:
@@ -48,6 +48,11 @@ AlertRED:
count: 81
avatarUrl: https://avatars.githubusercontent.com/u/15695000?u=f5a4944c6df443030409c88da7d7fa0b7ead985c&v=4
url: https://github.com/AlertRED
+tiangolo:
+ login: tiangolo
+ count: 73
+ avatarUrl: https://avatars.githubusercontent.com/u/1326112?u=cb5d06e73a9e1998141b1641aa88e443c6717651&v=4
+ url: https://github.com/tiangolo
Alexandrhub:
login: Alexandrhub
count: 68
@@ -63,21 +68,16 @@ cassiobotaro:
count: 62
avatarUrl: https://avatars.githubusercontent.com/u/3127847?u=a08022b191ddbd0a6159b2981d9d878b6d5bb71f&v=4
url: https://github.com/cassiobotaro
+mattwang44:
+ login: mattwang44
+ count: 61
+ avatarUrl: https://avatars.githubusercontent.com/u/24987826?u=58e37fb3927b9124b458945ac4c97aa0f1062d85&v=4
+ url: https://github.com/mattwang44
nilslindemann:
login: nilslindemann
count: 59
avatarUrl: https://avatars.githubusercontent.com/u/6892179?u=1dca6a22195d6cd1ab20737c0e19a4c55d639472&v=4
url: https://github.com/nilslindemann
-mattwang44:
- login: mattwang44
- count: 59
- avatarUrl: https://avatars.githubusercontent.com/u/24987826?u=58e37fb3927b9124b458945ac4c97aa0f1062d85&v=4
- url: https://github.com/mattwang44
-tiangolo:
- login: tiangolo
- count: 56
- avatarUrl: https://avatars.githubusercontent.com/u/1326112?u=cb5d06e73a9e1998141b1641aa88e443c6717651&v=4
- url: https://github.com/tiangolo
Laineyzhang55:
login: Laineyzhang55
count: 48
@@ -88,6 +88,11 @@ Kludex:
count: 47
avatarUrl: https://avatars.githubusercontent.com/u/7353520?u=df8a3f06ba8f55ae1967a3e2d5ed882903a4e330&v=4
url: https://github.com/Kludex
+YuriiMotov:
+ login: YuriiMotov
+ count: 46
+ avatarUrl: https://avatars.githubusercontent.com/u/109919500?u=b9b13d598dddfab529a52d264df80a900bfe7060&v=4
+ url: https://github.com/YuriiMotov
komtaki:
login: komtaki
count: 45
@@ -118,11 +123,6 @@ Winand:
count: 40
avatarUrl: https://avatars.githubusercontent.com/u/53390?u=bb0e71a2fc3910a8e0ee66da67c33de40ea695f8&v=4
url: https://github.com/Winand
-YuriiMotov:
- login: YuriiMotov
- count: 40
- avatarUrl: https://avatars.githubusercontent.com/u/109919500?u=b9b13d598dddfab529a52d264df80a900bfe7060&v=4
- url: https://github.com/YuriiMotov
solomein-sv:
login: solomein-sv
count: 38
@@ -138,6 +138,11 @@ alejsdev:
count: 37
avatarUrl: https://avatars.githubusercontent.com/u/90076947?u=85ceac49fb87138aebe8d663912e359447329090&v=4
url: https://github.com/alejsdev
+mezgoodle:
+ login: mezgoodle
+ count: 37
+ avatarUrl: https://avatars.githubusercontent.com/u/41520940?u=4a9c765af688389d54296845d18b8f6cd6ddf09a&v=4
+ url: https://github.com/mezgoodle
stlucasgarcia:
login: stlucasgarcia
count: 36
@@ -153,11 +158,6 @@ timothy-jeong:
count: 36
avatarUrl: https://avatars.githubusercontent.com/u/53824764?u=db3d0cea2f5fab64d810113c5039a369699a2774&v=4
url: https://github.com/timothy-jeong
-mezgoodle:
- login: mezgoodle
- count: 35
- avatarUrl: https://avatars.githubusercontent.com/u/41520940?u=4a9c765af688389d54296845d18b8f6cd6ddf09a&v=4
- url: https://github.com/mezgoodle
rjNemo:
login: rjNemo
count: 34
@@ -173,6 +173,11 @@ akarev0:
count: 33
avatarUrl: https://avatars.githubusercontent.com/u/53393089?u=6e528bb4789d56af887ce6fe237bea4010885406&v=4
url: https://github.com/akarev0
+Vincy1230:
+ login: Vincy1230
+ count: 33
+ avatarUrl: https://avatars.githubusercontent.com/u/81342412?u=ab5e256a4077a4a91f3f9cd2115ba80780454cbe&v=4
+ url: https://github.com/Vincy1230
romashevchenko:
login: romashevchenko
count: 32
@@ -183,11 +188,6 @@ LorhanSohaky:
count: 30
avatarUrl: https://avatars.githubusercontent.com/u/16273730?u=095b66f243a2cd6a0aadba9a095009f8aaf18393&v=4
url: https://github.com/LorhanSohaky
-Vincy1230:
- login: Vincy1230
- count: 30
- avatarUrl: https://avatars.githubusercontent.com/u/81342412?u=ab5e256a4077a4a91f3f9cd2115ba80780454cbe&v=4
- url: https://github.com/Vincy1230
black-redoc:
login: black-redoc
count: 29
@@ -250,7 +250,7 @@ mycaule:
url: https://github.com/mycaule
Aruelius:
login: Aruelius
- count: 24
+ count: 25
avatarUrl: https://avatars.githubusercontent.com/u/25380989?u=574f8cfcda3ea77a3f81884f6b26a97068e36a9d&v=4
url: https://github.com/Aruelius
wisderfin:
@@ -263,6 +263,11 @@ OzgunCaglarArslan:
count: 24
avatarUrl: https://avatars.githubusercontent.com/u/86166426?v=4
url: https://github.com/OzgunCaglarArslan
+ycd:
+ login: ycd
+ count: 23
+ avatarUrl: https://avatars.githubusercontent.com/u/62724709?u=f1e7bae394a315da950912c92dc861a8eaf95d4c&v=4
+ url: https://github.com/ycd
sh0nk:
login: sh0nk
count: 23
@@ -288,11 +293,6 @@ Attsun1031:
count: 20
avatarUrl: https://avatars.githubusercontent.com/u/1175560?v=4
url: https://github.com/Attsun1031
-ycd:
- login: ycd
- count: 20
- avatarUrl: https://avatars.githubusercontent.com/u/62724709?u=f1e7bae394a315da950912c92dc861a8eaf95d4c&v=4
- url: https://github.com/ycd
delhi09:
login: delhi09
count: 20
@@ -418,6 +418,11 @@ mattkoehne:
count: 14
avatarUrl: https://avatars.githubusercontent.com/u/80362153?v=4
url: https://github.com/mattkoehne
+maru0123-2004:
+ login: maru0123-2004
+ count: 14
+ avatarUrl: https://avatars.githubusercontent.com/u/43961566?u=16ed8603a4d6a4665cb6c53a7aece6f31379b769&v=4
+ url: https://github.com/maru0123-2004
jovicon:
login: jovicon
count: 13
@@ -443,6 +448,11 @@ impocode:
count: 13
avatarUrl: https://avatars.githubusercontent.com/u/109408819?u=9cdfc5ccb31a2094c520f41b6087012fa9048982&v=4
url: https://github.com/impocode
+waketzheng:
+ login: waketzheng
+ count: 13
+ avatarUrl: https://avatars.githubusercontent.com/u/35413830?u=df19e4fd5bb928e7d086e053ef26a46aad23bf84&v=4
+ url: https://github.com/waketzheng
wesinalves:
login: wesinalves
count: 13
@@ -538,21 +548,16 @@ Lufa1u:
count: 11
avatarUrl: https://avatars.githubusercontent.com/u/112495876?u=087658920ed9e74311597bdd921d8d2de939d276&v=4
url: https://github.com/Lufa1u
-waketzheng:
- login: waketzheng
- count: 11
- avatarUrl: https://avatars.githubusercontent.com/u/35413830?u=df19e4fd5bb928e7d086e053ef26a46aad23bf84&v=4
- url: https://github.com/waketzheng
KNChiu:
login: KNChiu
count: 11
avatarUrl: https://avatars.githubusercontent.com/u/36751646?v=4
url: https://github.com/KNChiu
-maru0123-2004:
- login: maru0123-2004
+Zhongheng-Cheng:
+ login: Zhongheng-Cheng
count: 11
- avatarUrl: https://avatars.githubusercontent.com/u/43961566?u=16ed8603a4d6a4665cb6c53a7aece6f31379b769&v=4
- url: https://github.com/maru0123-2004
+ avatarUrl: https://avatars.githubusercontent.com/u/95612344?u=a0f7730a3cc7486827965e01a119ad610bda4b0a&v=4
+ url: https://github.com/Zhongheng-Cheng
mariacamilagl:
login: mariacamilagl
count: 10
@@ -608,16 +613,16 @@ nick-cjyx9:
count: 10
avatarUrl: https://avatars.githubusercontent.com/u/119087246?u=7227a2de948c68fb8396d5beff1ee5b0e057c42e&v=4
url: https://github.com/nick-cjyx9
+marcelomarkus:
+ login: marcelomarkus
+ count: 10
+ avatarUrl: https://avatars.githubusercontent.com/u/20115018?u=dda090ce9160ef0cd2ff69b1e5ea741283425cba&v=4
+ url: https://github.com/marcelomarkus
lucasbalieiro:
login: lucasbalieiro
count: 10
- avatarUrl: https://avatars.githubusercontent.com/u/37416577?u=dad91601ee4f40458d691774ec439aff308344d7&v=4
+ avatarUrl: https://avatars.githubusercontent.com/u/37416577?u=d144221c34c08adac8b20e1833d776ffa1c4b1d0&v=4
url: https://github.com/lucasbalieiro
-Zhongheng-Cheng:
- login: Zhongheng-Cheng
- count: 10
- avatarUrl: https://avatars.githubusercontent.com/u/95612344?u=a0f7730a3cc7486827965e01a119ad610bda4b0a&v=4
- url: https://github.com/Zhongheng-Cheng
RunningIkkyu:
login: RunningIkkyu
count: 9
@@ -668,11 +673,6 @@ yodai-yodai:
count: 9
avatarUrl: https://avatars.githubusercontent.com/u/7031039?u=4f3593f5931892b931a745cfab846eff6e9332e7&v=4
url: https://github.com/yodai-yodai
-marcelomarkus:
- login: marcelomarkus
- count: 9
- avatarUrl: https://avatars.githubusercontent.com/u/20115018?u=dda090ce9160ef0cd2ff69b1e5ea741283425cba&v=4
- url: https://github.com/marcelomarkus
JoaoGustavoRogel:
login: JoaoGustavoRogel
count: 9
@@ -683,6 +683,11 @@ Yarous:
count: 9
avatarUrl: https://avatars.githubusercontent.com/u/61277193?u=5b462347458a373b2d599c6f416d2b75eddbffad&v=4
url: https://github.com/Yarous
+Pyth3rEx:
+ login: Pyth3rEx
+ count: 9
+ avatarUrl: https://avatars.githubusercontent.com/u/26427764?u=087724f74d813c95925d51e354554bd4b6d6bb60&v=4
+ url: https://github.com/Pyth3rEx
dimaqq:
login: dimaqq
count: 8
@@ -1023,6 +1028,11 @@ devluisrodrigues:
count: 5
avatarUrl: https://avatars.githubusercontent.com/u/21125286?v=4
url: https://github.com/11kkw
+EdmilsonRodrigues:
+ login: EdmilsonRodrigues
+ count: 5
+ avatarUrl: https://avatars.githubusercontent.com/u/62777025?u=217d6f3cd6cc750bb8818a3af7726c8d74eb7c2d&v=4
+ url: https://github.com/EdmilsonRodrigues
lpdswing:
login: lpdswing
count: 4
@@ -1163,6 +1173,11 @@ AbolfazlKameli:
count: 4
avatarUrl: https://avatars.githubusercontent.com/u/120686133?u=af8f025278cce0d489007071254e4055df60b78c&v=4
url: https://github.com/AbolfazlKameli
+SBillion:
+ login: SBillion
+ count: 4
+ avatarUrl: https://avatars.githubusercontent.com/u/1070649?u=3ab493dfc88b39da0eb1600e3b8e7df1c90a5dee&v=4
+ url: https://github.com/SBillion
tyronedamasceno:
login: tyronedamasceno
count: 3
@@ -1211,7 +1226,7 @@ phamquanganh31101998:
peebbv6364:
login: peebbv6364
count: 3
- avatarUrl: https://avatars.githubusercontent.com/u/26784747?u=75583df215ee01a5cd2dc646aecb81e7dbd33d06&v=4
+ avatarUrl: https://avatars.githubusercontent.com/u/26784747?u=3bf07017eb4f4fa3639ba8d4ed19980a34bf8f90&v=4
url: https://github.com/peebbv6364
mrparalon:
login: mrparalon
@@ -1413,11 +1428,6 @@ Mohammad222PR:
count: 3
avatarUrl: https://avatars.githubusercontent.com/u/116789737?u=25810a5fe049d2f1618e2e7417cea011cc353ce4&v=4
url: https://github.com/Mohammad222PR
-EdmilsonRodrigues:
- login: EdmilsonRodrigues
- count: 3
- avatarUrl: https://avatars.githubusercontent.com/u/62777025?u=217d6f3cd6cc750bb8818a3af7726c8d74eb7c2d&v=4
- url: https://github.com/EdmilsonRodrigues
blaisep:
login: blaisep
count: 2
@@ -1838,11 +1848,11 @@ NavesSapnis:
count: 2
avatarUrl: https://avatars.githubusercontent.com/u/79222417?u=b5b10291b8e9130ca84fd20f0a641e04ed94b6b1&v=4
url: https://github.com/NavesSapnis
-eqsdxr:
- login: eqsdxr
+isgin01:
+ login: isgin01
count: 2
- avatarUrl: https://avatars.githubusercontent.com/u/157279130?u=7927dc0366995334f9a18c3204a41d3a34d6d96f&v=4
- url: https://github.com/eqsdxr
+ avatarUrl: https://avatars.githubusercontent.com/u/157279130?u=ddffde10876b50f35dc90d1337f507a630530a6a&v=4
+ url: https://github.com/isgin01
syedasamina56:
login: syedasamina56
count: 2
diff --git a/docs/en/data/translators.yml b/docs/en/data/translators.yml
index c66eff4d42..940b128da2 100644
--- a/docs/en/data/translators.yml
+++ b/docs/en/data/translators.yml
@@ -1,6 +1,6 @@
nilslindemann:
login: nilslindemann
- count: 125
+ count: 130
avatarUrl: https://avatars.githubusercontent.com/u/6892179?u=1dca6a22195d6cd1ab20737c0e19a4c55d639472&v=4
url: https://github.com/nilslindemann
jaystone776:
@@ -28,6 +28,11 @@ SwftAlpc:
count: 23
avatarUrl: https://avatars.githubusercontent.com/u/52768429?u=6a3aa15277406520ad37f6236e89466ed44bc5b8&v=4
url: https://github.com/SwftAlpc
+tiangolo:
+ login: tiangolo
+ count: 22
+ avatarUrl: https://avatars.githubusercontent.com/u/1326112?u=cb5d06e73a9e1998141b1641aa88e443c6717651&v=4
+ url: https://github.com/tiangolo
hasansezertasan:
login: hasansezertasan
count: 22
@@ -46,7 +51,7 @@ AlertRED:
hard-coders:
login: hard-coders
count: 15
- avatarUrl: https://avatars.githubusercontent.com/u/9651103?u=95db33927bbff1ed1c07efddeb97ac2ff33068ed&v=4
+ avatarUrl: https://avatars.githubusercontent.com/u/9651103?u=78d12d1acdf853c817700145e73de7fd9e5d068b&v=4
url: https://github.com/hard-coders
Joao-Pedro-P-Holanda:
login: Joao-Pedro-P-Holanda
@@ -103,11 +108,6 @@ pablocm83:
count: 8
avatarUrl: https://avatars.githubusercontent.com/u/28315068?u=3310fbb05bb8bfc50d2c48b6cb64ac9ee4a14549&v=4
url: https://github.com/pablocm83
-tiangolo:
- login: tiangolo
- count: 7
- avatarUrl: https://avatars.githubusercontent.com/u/1326112?u=cb5d06e73a9e1998141b1641aa88e443c6717651&v=4
- url: https://github.com/tiangolo
ptt3199:
login: ptt3199
count: 7
@@ -126,13 +126,18 @@ batlopes:
lucasbalieiro:
login: lucasbalieiro
count: 6
- avatarUrl: https://avatars.githubusercontent.com/u/37416577?u=dad91601ee4f40458d691774ec439aff308344d7&v=4
+ avatarUrl: https://avatars.githubusercontent.com/u/37416577?u=d144221c34c08adac8b20e1833d776ffa1c4b1d0&v=4
url: https://github.com/lucasbalieiro
Alexandrhub:
login: Alexandrhub
count: 6
avatarUrl: https://avatars.githubusercontent.com/u/119126536?u=9fc0d48f3307817bafecc5861eb2168401a6cb04&v=4
url: https://github.com/Alexandrhub
+YuriiMotov:
+ login: YuriiMotov
+ count: 6
+ avatarUrl: https://avatars.githubusercontent.com/u/109919500?u=b9b13d598dddfab529a52d264df80a900bfe7060&v=4
+ url: https://github.com/YuriiMotov
Serrones:
login: Serrones
count: 5
@@ -358,11 +363,6 @@ ruzia:
count: 3
avatarUrl: https://avatars.githubusercontent.com/u/24503?v=4
url: https://github.com/ruzia
-YuriiMotov:
- login: YuriiMotov
- count: 3
- avatarUrl: https://avatars.githubusercontent.com/u/109919500?u=b9b13d598dddfab529a52d264df80a900bfe7060&v=4
- url: https://github.com/YuriiMotov
izaguerreiro:
login: izaguerreiro
count: 2
diff --git a/docs/en/docs/_llm-test.md b/docs/en/docs/_llm-test.md
index 9f216f9d79..d218f7c76f 100644
--- a/docs/en/docs/_llm-test.md
+++ b/docs/en/docs/_llm-test.md
@@ -6,7 +6,7 @@ Tests added here will be seen by all designers of language specific prompts.
Use as follows:
-* Have a language specific prompt – `docs/{language code}/llm-prompt.md`.
+* Have a language specific prompt - `docs/{language code}/llm-prompt.md`.
* Do a fresh translation of this document into your desired target language (see e.g. the `translate-page` command of the `translate.py`). This will create the translation under `docs/{language code}/docs/_llm-test.md`.
* Check if things are okay in the translation.
* If necessary, improve your language specific prompt, the general prompt, or the English document.
diff --git a/docs/en/docs/advanced/additional-responses.md b/docs/en/docs/advanced/additional-responses.md
index cb3a40d13e..bb70753edd 100644
--- a/docs/en/docs/advanced/additional-responses.md
+++ b/docs/en/docs/advanced/additional-responses.md
@@ -26,7 +26,7 @@ Each of those response `dict`s can have a key `model`, containing a Pydantic mod
For example, to declare another response with a status code `404` and a Pydantic model `Message`, you can write:
-{* ../../docs_src/additional_responses/tutorial001.py hl[18,22] *}
+{* ../../docs_src/additional_responses/tutorial001_py39.py hl[18,22] *}
/// note
@@ -203,7 +203,7 @@ For example, you can declare a response with a status code `404` that uses a Pyd
And a response with a status code `200` that uses your `response_model`, but includes a custom `example`:
-{* ../../docs_src/additional_responses/tutorial003.py hl[20:31] *}
+{* ../../docs_src/additional_responses/tutorial003_py39.py hl[20:31] *}
It will all be combined and included in your OpenAPI, and shown in the API docs:
diff --git a/docs/en/docs/advanced/async-tests.md b/docs/en/docs/advanced/async-tests.md
index e920e22c3c..65ddc60b2d 100644
--- a/docs/en/docs/advanced/async-tests.md
+++ b/docs/en/docs/advanced/async-tests.md
@@ -32,11 +32,11 @@ For a simple example, let's consider a file structure similar to the one describ
The file `main.py` would have:
-{* ../../docs_src/async_tests/main.py *}
+{* ../../docs_src/async_tests/app_a_py39/main.py *}
The file `test_main.py` would have the tests for `main.py`, it could look like this now:
-{* ../../docs_src/async_tests/test_main.py *}
+{* ../../docs_src/async_tests/app_a_py39/test_main.py *}
## Run it { #run-it }
@@ -56,7 +56,7 @@ $ pytest
The marker `@pytest.mark.anyio` tells pytest that this test function should be called asynchronously:
-{* ../../docs_src/async_tests/test_main.py hl[7] *}
+{* ../../docs_src/async_tests/app_a_py39/test_main.py hl[7] *}
/// tip
@@ -66,7 +66,7 @@ Note that the test function is now `async def` instead of just `def` as before w
Then we can create an `AsyncClient` with the app, and send async requests to it, using `await`.
-{* ../../docs_src/async_tests/test_main.py hl[9:12] *}
+{* ../../docs_src/async_tests/app_a_py39/test_main.py hl[9:12] *}
This is the equivalent to:
diff --git a/docs/en/docs/advanced/behind-a-proxy.md b/docs/en/docs/advanced/behind-a-proxy.md
index f4dbd45607..4fef02bd1c 100644
--- a/docs/en/docs/advanced/behind-a-proxy.md
+++ b/docs/en/docs/advanced/behind-a-proxy.md
@@ -44,7 +44,7 @@ $ fastapi run --forwarded-allow-ips="*"
For example, let's say you define a *path operation* `/items/`:
-{* ../../docs_src/behind_a_proxy/tutorial001_01.py hl[6] *}
+{* ../../docs_src/behind_a_proxy/tutorial001_01_py39.py hl[6] *}
If the client tries to go to `/items`, by default, it would be redirected to `/items/`.
@@ -115,7 +115,7 @@ In this case, the original path `/app` would actually be served at `/api/v1/app`
Even though all your code is written assuming there's just `/app`.
-{* ../../docs_src/behind_a_proxy/tutorial001.py hl[6] *}
+{* ../../docs_src/behind_a_proxy/tutorial001_py39.py hl[6] *}
And the proxy would be **"stripping"** the **path prefix** on the fly before transmitting the request to the app server (probably Uvicorn via FastAPI CLI), keeping your application convinced that it is being served at `/app`, so that you don't have to update all your code to include the prefix `/api/v1`.
@@ -193,7 +193,7 @@ You can get the current `root_path` used by your application for each request, i
Here we are including it in the message just for demonstration purposes.
-{* ../../docs_src/behind_a_proxy/tutorial001.py hl[8] *}
+{* ../../docs_src/behind_a_proxy/tutorial001_py39.py hl[8] *}
Then, if you start Uvicorn with:
@@ -220,7 +220,7 @@ The response would be something like:
Alternatively, if you don't have a way to provide a command line option like `--root-path` or equivalent, you can set the `root_path` parameter when creating your FastAPI app:
-{* ../../docs_src/behind_a_proxy/tutorial002.py hl[3] *}
+{* ../../docs_src/behind_a_proxy/tutorial002_py39.py hl[3] *}
Passing the `root_path` to `FastAPI` would be the equivalent of passing the `--root-path` command line option to Uvicorn or Hypercorn.
@@ -400,7 +400,7 @@ If you pass a custom list of `servers` and there's a `root_path` (because your A
For example:
-{* ../../docs_src/behind_a_proxy/tutorial003.py hl[4:7] *}
+{* ../../docs_src/behind_a_proxy/tutorial003_py39.py hl[4:7] *}
Will generate an OpenAPI schema like:
@@ -455,7 +455,7 @@ If you don't specify the `servers` parameter and `root_path` is equal to `/`, th
If you don't want **FastAPI** to include an automatic server using the `root_path`, you can use the parameter `root_path_in_servers=False`:
-{* ../../docs_src/behind_a_proxy/tutorial004.py hl[9] *}
+{* ../../docs_src/behind_a_proxy/tutorial004_py39.py hl[9] *}
and then it won't include it in the OpenAPI schema.
diff --git a/docs/en/docs/advanced/custom-response.md b/docs/en/docs/advanced/custom-response.md
index 0f3d8b7017..e53409c39d 100644
--- a/docs/en/docs/advanced/custom-response.md
+++ b/docs/en/docs/advanced/custom-response.md
@@ -30,7 +30,7 @@ This is because by default, FastAPI will inspect every item inside and make sure
But if you are certain that the content that you are returning is **serializable with JSON**, you can pass it directly to the response class and avoid the extra overhead that FastAPI would have by passing your return content through the `jsonable_encoder` before passing it to the response class.
-{* ../../docs_src/custom_response/tutorial001b.py hl[2,7] *}
+{* ../../docs_src/custom_response/tutorial001b_py39.py hl[2,7] *}
/// info
@@ -55,7 +55,7 @@ To return a response with HTML directly from **FastAPI**, use `HTMLResponse`.
* Import `HTMLResponse`.
* Pass `HTMLResponse` as the parameter `response_class` of your *path operation decorator*.
-{* ../../docs_src/custom_response/tutorial002.py hl[2,7] *}
+{* ../../docs_src/custom_response/tutorial002_py39.py hl[2,7] *}
/// info
@@ -73,7 +73,7 @@ As seen in [Return a Response directly](response-directly.md){.internal-link tar
The same example from above, returning an `HTMLResponse`, could look like:
-{* ../../docs_src/custom_response/tutorial003.py hl[2,7,19] *}
+{* ../../docs_src/custom_response/tutorial003_py39.py hl[2,7,19] *}
/// warning
@@ -97,7 +97,7 @@ The `response_class` will then be used only to document the OpenAPI *path operat
For example, it could be something like:
-{* ../../docs_src/custom_response/tutorial004.py hl[7,21,23] *}
+{* ../../docs_src/custom_response/tutorial004_py39.py hl[7,21,23] *}
In this example, the function `generate_html_response()` already generates and returns a `Response` instead of returning the HTML in a `str`.
@@ -136,7 +136,7 @@ It accepts the following parameters:
FastAPI (actually Starlette) will automatically include a Content-Length header. It will also include a Content-Type header, based on the `media_type` and appending a charset for text types.
-{* ../../docs_src/response_directly/tutorial002.py hl[1,18] *}
+{* ../../docs_src/response_directly/tutorial002_py39.py hl[1,18] *}
### `HTMLResponse` { #htmlresponse }
@@ -146,7 +146,7 @@ Takes some text or bytes and returns an HTML response, as you read above.
Takes some text or bytes and returns a plain text response.
-{* ../../docs_src/custom_response/tutorial005.py hl[2,7,9] *}
+{* ../../docs_src/custom_response/tutorial005_py39.py hl[2,7,9] *}
### `JSONResponse` { #jsonresponse }
@@ -180,7 +180,7 @@ This requires installing `ujson` for example with `pip install ujson`.
///
-{* ../../docs_src/custom_response/tutorial001.py hl[2,7] *}
+{* ../../docs_src/custom_response/tutorial001_py39.py hl[2,7] *}
/// tip
@@ -194,14 +194,14 @@ Returns an HTTP redirect. Uses a 307 status code (Temporary Redirect) by default
You can return a `RedirectResponse` directly:
-{* ../../docs_src/custom_response/tutorial006.py hl[2,9] *}
+{* ../../docs_src/custom_response/tutorial006_py39.py hl[2,9] *}
---
Or you can use it in the `response_class` parameter:
-{* ../../docs_src/custom_response/tutorial006b.py hl[2,7,9] *}
+{* ../../docs_src/custom_response/tutorial006b_py39.py hl[2,7,9] *}
If you do that, then you can return the URL directly from your *path operation* function.
@@ -211,13 +211,13 @@ In this case, the `status_code` used will be the default one for the `RedirectRe
You can also use the `status_code` parameter combined with the `response_class` parameter:
-{* ../../docs_src/custom_response/tutorial006c.py hl[2,7,9] *}
+{* ../../docs_src/custom_response/tutorial006c_py39.py hl[2,7,9] *}
### `StreamingResponse` { #streamingresponse }
Takes an async generator or a normal generator/iterator and streams the response body.
-{* ../../docs_src/custom_response/tutorial007.py hl[2,14] *}
+{* ../../docs_src/custom_response/tutorial007_py39.py hl[2,14] *}
#### Using `StreamingResponse` with file-like objects { #using-streamingresponse-with-file-like-objects }
@@ -227,7 +227,7 @@ That way, you don't have to read it all first in memory, and you can pass that g
This includes many libraries to interact with cloud storage, video processing, and others.
-{* ../../docs_src/custom_response/tutorial008.py hl[2,10:12,14] *}
+{* ../../docs_src/custom_response/tutorial008_py39.py hl[2,10:12,14] *}
1. This is the generator function. It's a "generator function" because it contains `yield` statements inside.
2. By using a `with` block, we make sure that the file-like object is closed after the generator function is done. So, after it finishes sending the response.
@@ -256,11 +256,11 @@ Takes a different set of arguments to instantiate than the other response types:
File responses will include appropriate `Content-Length`, `Last-Modified` and `ETag` headers.
-{* ../../docs_src/custom_response/tutorial009.py hl[2,10] *}
+{* ../../docs_src/custom_response/tutorial009_py39.py hl[2,10] *}
You can also use the `response_class` parameter:
-{* ../../docs_src/custom_response/tutorial009b.py hl[2,8,10] *}
+{* ../../docs_src/custom_response/tutorial009b_py39.py hl[2,8,10] *}
In this case, you can return the file path directly from your *path operation* function.
@@ -274,7 +274,7 @@ Let's say you want it to return indented and formatted JSON, so you want to use
You could create a `CustomORJSONResponse`. The main thing you have to do is create a `Response.render(content)` method that returns the content as `bytes`:
-{* ../../docs_src/custom_response/tutorial009c.py hl[9:14,17] *}
+{* ../../docs_src/custom_response/tutorial009c_py39.py hl[9:14,17] *}
Now instead of returning:
@@ -300,7 +300,7 @@ The parameter that defines this is `default_response_class`.
In the example below, **FastAPI** will use `ORJSONResponse` by default, in all *path operations*, instead of `JSONResponse`.
-{* ../../docs_src/custom_response/tutorial010.py hl[2,4] *}
+{* ../../docs_src/custom_response/tutorial010_py39.py hl[2,4] *}
/// tip
diff --git a/docs/en/docs/advanced/dataclasses.md b/docs/en/docs/advanced/dataclasses.md
index 574beb65f4..dbc91409a5 100644
--- a/docs/en/docs/advanced/dataclasses.md
+++ b/docs/en/docs/advanced/dataclasses.md
@@ -4,7 +4,7 @@ FastAPI is built on top of **Pydantic**, and I have been showing you how to use
But FastAPI also supports using `dataclasses` the same way:
-{* ../../docs_src/dataclasses/tutorial001_py310.py hl[1,6:11,18:19] *}
+{* ../../docs_src/dataclasses_/tutorial001_py310.py hl[1,6:11,18:19] *}
This is still supported thanks to **Pydantic**, as it has internal support for `dataclasses`.
@@ -32,7 +32,7 @@ But if you have a bunch of dataclasses laying around, this is a nice trick to us
You can also use `dataclasses` in the `response_model` parameter:
-{* ../../docs_src/dataclasses/tutorial002_py310.py hl[1,6:12,18] *}
+{* ../../docs_src/dataclasses_/tutorial002_py310.py hl[1,6:12,18] *}
The dataclass will be automatically converted to a Pydantic dataclass.
@@ -48,7 +48,7 @@ In some cases, you might still have to use Pydantic's version of `dataclasses`.
In that case, you can simply swap the standard `dataclasses` with `pydantic.dataclasses`, which is a drop-in replacement:
-{* ../../docs_src/dataclasses/tutorial003_py310.py hl[1,4,7:10,13:16,22:24,27] *}
+{* ../../docs_src/dataclasses_/tutorial003_py310.py hl[1,4,7:10,13:16,22:24,27] *}
1. We still import `field` from standard `dataclasses`.
diff --git a/docs/en/docs/advanced/events.md b/docs/en/docs/advanced/events.md
index d9e3cb52e7..9414b7a3f0 100644
--- a/docs/en/docs/advanced/events.md
+++ b/docs/en/docs/advanced/events.md
@@ -30,7 +30,7 @@ Let's start with an example and then see it in detail.
We create an async function `lifespan()` with `yield` like this:
-{* ../../docs_src/events/tutorial003.py hl[16,19] *}
+{* ../../docs_src/events/tutorial003_py39.py hl[16,19] *}
Here we are simulating the expensive *startup* operation of loading the model by putting the (fake) model function in the dictionary with machine learning models before the `yield`. This code will be executed **before** the application **starts taking requests**, during the *startup*.
@@ -48,7 +48,7 @@ Maybe you need to start a new version, or you just got tired of running it. 🤷
The first thing to notice, is that we are defining an async function with `yield`. This is very similar to Dependencies with `yield`.
-{* ../../docs_src/events/tutorial003.py hl[14:19] *}
+{* ../../docs_src/events/tutorial003_py39.py hl[14:19] *}
The first part of the function, before the `yield`, will be executed **before** the application starts.
@@ -60,7 +60,7 @@ If you check, the function is decorated with an `@asynccontextmanager`.
That converts the function into something called an "**async context manager**".
-{* ../../docs_src/events/tutorial003.py hl[1,13] *}
+{* ../../docs_src/events/tutorial003_py39.py hl[1,13] *}
A **context manager** in Python is something that you can use in a `with` statement, for example, `open()` can be used as a context manager:
@@ -82,7 +82,7 @@ In our code example above, we don't use it directly, but we pass it to FastAPI f
The `lifespan` parameter of the `FastAPI` app takes an **async context manager**, so we can pass our new `lifespan` async context manager to it.
-{* ../../docs_src/events/tutorial003.py hl[22] *}
+{* ../../docs_src/events/tutorial003_py39.py hl[22] *}
## Alternative Events (deprecated) { #alternative-events-deprecated }
@@ -104,7 +104,7 @@ These functions can be declared with `async def` or normal `def`.
To add a function that should be run before the application starts, declare it with the event `"startup"`:
-{* ../../docs_src/events/tutorial001.py hl[8] *}
+{* ../../docs_src/events/tutorial001_py39.py hl[8] *}
In this case, the `startup` event handler function will initialize the items "database" (just a `dict`) with some values.
@@ -116,7 +116,7 @@ And your application won't start receiving requests until all the `startup` even
To add a function that should be run when the application is shutting down, declare it with the event `"shutdown"`:
-{* ../../docs_src/events/tutorial002.py hl[6] *}
+{* ../../docs_src/events/tutorial002_py39.py hl[6] *}
Here, the `shutdown` event handler function will write a text line `"Application shutdown"` to a file `log.txt`.
diff --git a/docs/en/docs/advanced/generate-clients.md b/docs/en/docs/advanced/generate-clients.md
index 897c308086..2d0c2aa0c9 100644
--- a/docs/en/docs/advanced/generate-clients.md
+++ b/docs/en/docs/advanced/generate-clients.md
@@ -167,7 +167,7 @@ But for the generated client, we could **modify** the OpenAPI operation IDs righ
We could download the OpenAPI JSON to a file `openapi.json` and then we could **remove that prefixed tag** with a script like this:
-{* ../../docs_src/generate_clients/tutorial004.py *}
+{* ../../docs_src/generate_clients/tutorial004_py39.py *}
//// tab | Node.js
diff --git a/docs/en/docs/advanced/middleware.md b/docs/en/docs/advanced/middleware.md
index 8deb0d917d..765b389329 100644
--- a/docs/en/docs/advanced/middleware.md
+++ b/docs/en/docs/advanced/middleware.md
@@ -57,13 +57,13 @@ Enforces that all incoming requests must either be `https` or `wss`.
Any incoming request to `http` or `ws` will be redirected to the secure scheme instead.
-{* ../../docs_src/advanced_middleware/tutorial001.py hl[2,6] *}
+{* ../../docs_src/advanced_middleware/tutorial001_py39.py hl[2,6] *}
## `TrustedHostMiddleware` { #trustedhostmiddleware }
Enforces that all incoming requests have a correctly set `Host` header, in order to guard against HTTP Host Header attacks.
-{* ../../docs_src/advanced_middleware/tutorial002.py hl[2,6:8] *}
+{* ../../docs_src/advanced_middleware/tutorial002_py39.py hl[2,6:8] *}
The following arguments are supported:
@@ -78,7 +78,7 @@ Handles GZip responses for any request that includes `"gzip"` in the `Accept-Enc
The middleware will handle both standard and streaming responses.
-{* ../../docs_src/advanced_middleware/tutorial003.py hl[2,6] *}
+{* ../../docs_src/advanced_middleware/tutorial003_py39.py hl[2,6] *}
The following arguments are supported:
diff --git a/docs/en/docs/advanced/openapi-webhooks.md b/docs/en/docs/advanced/openapi-webhooks.md
index 416cf4b75b..59f060c032 100644
--- a/docs/en/docs/advanced/openapi-webhooks.md
+++ b/docs/en/docs/advanced/openapi-webhooks.md
@@ -32,7 +32,7 @@ Webhooks are available in OpenAPI 3.1.0 and above, supported by FastAPI `0.99.0`
When you create a **FastAPI** application, there is a `webhooks` attribute that you can use to define *webhooks*, the same way you would define *path operations*, for example with `@app.webhooks.post()`.
-{* ../../docs_src/openapi_webhooks/tutorial001.py hl[9:13,36:53] *}
+{* ../../docs_src/openapi_webhooks/tutorial001_py39.py hl[9:13,36:53] *}
The webhooks that you define will end up in the **OpenAPI** schema and the automatic **docs UI**.
diff --git a/docs/en/docs/advanced/path-operation-advanced-configuration.md b/docs/en/docs/advanced/path-operation-advanced-configuration.md
index 5879bc5c71..e0e3c96a0e 100644
--- a/docs/en/docs/advanced/path-operation-advanced-configuration.md
+++ b/docs/en/docs/advanced/path-operation-advanced-configuration.md
@@ -12,7 +12,7 @@ You can set the OpenAPI `operationId` to be used in your *path operation* with t
You would have to make sure that it is unique for each operation.
-{* ../../docs_src/path_operation_advanced_configuration/tutorial001.py hl[6] *}
+{* ../../docs_src/path_operation_advanced_configuration/tutorial001_py39.py hl[6] *}
### Using the *path operation function* name as the operationId { #using-the-path-operation-function-name-as-the-operationid }
@@ -20,7 +20,7 @@ If you want to use your APIs' function names as `operationId`s, you can iterate
You should do it after adding all your *path operations*.
-{* ../../docs_src/path_operation_advanced_configuration/tutorial002.py hl[2, 12:21, 24] *}
+{* ../../docs_src/path_operation_advanced_configuration/tutorial002_py39.py hl[2, 12:21, 24] *}
/// tip
@@ -40,7 +40,7 @@ Even if they are in different modules (Python files).
To exclude a *path operation* from the generated OpenAPI schema (and thus, from the automatic documentation systems), use the parameter `include_in_schema` and set it to `False`:
-{* ../../docs_src/path_operation_advanced_configuration/tutorial003.py hl[6] *}
+{* ../../docs_src/path_operation_advanced_configuration/tutorial003_py39.py hl[6] *}
## Advanced description from docstring { #advanced-description-from-docstring }
@@ -92,7 +92,7 @@ You can extend the OpenAPI schema for a *path operation* using the parameter `op
This `openapi_extra` can be helpful, for example, to declare [OpenAPI Extensions](https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.3.md#specificationExtensions):
-{* ../../docs_src/path_operation_advanced_configuration/tutorial005.py hl[6] *}
+{* ../../docs_src/path_operation_advanced_configuration/tutorial005_py39.py hl[6] *}
If you open the automatic API docs, your extension will show up at the bottom of the specific *path operation*.
@@ -139,7 +139,7 @@ For example, you could decide to read and validate the request with your own cod
You could do that with `openapi_extra`:
-{* ../../docs_src/path_operation_advanced_configuration/tutorial006.py hl[19:36, 39:40] *}
+{* ../../docs_src/path_operation_advanced_configuration/tutorial006_py39.py hl[19:36, 39:40] *}
In this example, we didn't declare any Pydantic model. In fact, the request body is not even parsed as JSON, it is read directly as `bytes`, and the function `magic_data_reader()` would be in charge of parsing it in some way.
@@ -153,48 +153,16 @@ And you could do this even if the data type in the request is not JSON.
For example, in this application we don't use FastAPI's integrated functionality to extract the JSON Schema from Pydantic models nor the automatic validation for JSON. In fact, we are declaring the request content type as YAML, not JSON:
-//// tab | Pydantic v2
-
{* ../../docs_src/path_operation_advanced_configuration/tutorial007_py39.py hl[15:20, 22] *}
-////
-
-//// tab | Pydantic v1
-
-{* ../../docs_src/path_operation_advanced_configuration/tutorial007_pv1_py39.py hl[15:20, 22] *}
-
-////
-
-/// info
-
-In Pydantic version 1 the method to get the JSON Schema for a model was called `Item.schema()`, in Pydantic version 2, the method is called `Item.model_json_schema()`.
-
-///
-
Nevertheless, although we are not using the default integrated functionality, we are still using a Pydantic model to manually generate the JSON Schema for the data that we want to receive in YAML.
Then we use the request directly, and extract the body as `bytes`. This means that FastAPI won't even try to parse the request payload as JSON.
And then in our code, we parse that YAML content directly, and then we are again using the same Pydantic model to validate the YAML content:
-//// tab | Pydantic v2
-
{* ../../docs_src/path_operation_advanced_configuration/tutorial007_py39.py hl[24:31] *}
-////
-
-//// tab | Pydantic v1
-
-{* ../../docs_src/path_operation_advanced_configuration/tutorial007_pv1_py39.py hl[24:31] *}
-
-////
-
-/// info
-
-In Pydantic version 1 the method to parse and validate an object was `Item.parse_obj()`, in Pydantic version 2, the method is called `Item.model_validate()`.
-
-///
-
/// tip
Here we reuse the same Pydantic model.
diff --git a/docs/en/docs/advanced/response-change-status-code.md b/docs/en/docs/advanced/response-change-status-code.md
index 912ed0f1a1..d9708aa627 100644
--- a/docs/en/docs/advanced/response-change-status-code.md
+++ b/docs/en/docs/advanced/response-change-status-code.md
@@ -20,7 +20,7 @@ You can declare a parameter of type `Response` in your *path operation function*
And then you can set the `status_code` in that *temporal* response object.
-{* ../../docs_src/response_change_status_code/tutorial001.py hl[1,9,12] *}
+{* ../../docs_src/response_change_status_code/tutorial001_py39.py hl[1,9,12] *}
And then you can return any object you need, as you normally would (a `dict`, a database model, etc).
diff --git a/docs/en/docs/advanced/response-cookies.md b/docs/en/docs/advanced/response-cookies.md
index 1f41d84b7c..5b6fab112b 100644
--- a/docs/en/docs/advanced/response-cookies.md
+++ b/docs/en/docs/advanced/response-cookies.md
@@ -6,7 +6,7 @@ You can declare a parameter of type `Response` in your *path operation function*
And then you can set cookies in that *temporal* response object.
-{* ../../docs_src/response_cookies/tutorial002.py hl[1, 8:9] *}
+{* ../../docs_src/response_cookies/tutorial002_py39.py hl[1, 8:9] *}
And then you can return any object you need, as you normally would (a `dict`, a database model, etc).
@@ -24,7 +24,7 @@ To do that, you can create a response as described in [Return a Response Directl
Then set Cookies in it, and then return it:
-{* ../../docs_src/response_cookies/tutorial001.py hl[10:12] *}
+{* ../../docs_src/response_cookies/tutorial001_py39.py hl[10:12] *}
/// tip
diff --git a/docs/en/docs/advanced/response-directly.md b/docs/en/docs/advanced/response-directly.md
index 156b4dac7e..4374cb9637 100644
--- a/docs/en/docs/advanced/response-directly.md
+++ b/docs/en/docs/advanced/response-directly.md
@@ -54,7 +54,7 @@ Let's say that you want to return an
-/// info
-
-In Pydantic v1 it came included with the main package. Now it is distributed as this independent package so that you can choose to install it or not if you don't need that functionality.
-
-///
-
### Create the `Settings` object { #create-the-settings-object }
Import `BaseSettings` from Pydantic and create a sub-class, very much like with a Pydantic model.
@@ -60,23 +54,7 @@ The same way as with Pydantic models, you declare class attributes with type ann
You can use all the same validation features and tools you use for Pydantic models, like different data types and additional validations with `Field()`.
-//// tab | Pydantic v2
-
-{* ../../docs_src/settings/tutorial001.py hl[2,5:8,11] *}
-
-////
-
-//// tab | Pydantic v1
-
-/// info
-
-In Pydantic v1 you would import `BaseSettings` directly from `pydantic` instead of from `pydantic_settings`.
-
-///
-
-{* ../../docs_src/settings/tutorial001_pv1.py hl[2,5:8,11] *}
-
-////
+{* ../../docs_src/settings/tutorial001_py39.py hl[2,5:8,11] *}
/// tip
@@ -92,7 +70,7 @@ Next it will convert and validate the data. So, when you use that `settings` obj
Then you can use the new `settings` object in your application:
-{* ../../docs_src/settings/tutorial001.py hl[18:20] *}
+{* ../../docs_src/settings/tutorial001_py39.py hl[18:20] *}
### Run the server { #run-the-server }
@@ -126,11 +104,11 @@ You could put those settings in another module file as you saw in [Bigger Applic
For example, you could have a file `config.py` with:
-{* ../../docs_src/settings/app01/config.py *}
+{* ../../docs_src/settings/app01_py39/config.py *}
And then use it in a file `main.py`:
-{* ../../docs_src/settings/app01/main.py hl[3,11:13] *}
+{* ../../docs_src/settings/app01_py39/main.py hl[3,11:13] *}
/// tip
@@ -215,8 +193,6 @@ APP_NAME="ChimichangApp"
And then update your `config.py` with:
-//// tab | Pydantic v2
-
{* ../../docs_src/settings/app03_an_py39/config.py hl[9] *}
/// tip
@@ -225,26 +201,6 @@ The `model_config` attribute is used just for Pydantic configuration. You can re
///
-////
-
-//// tab | Pydantic v1
-
-{* ../../docs_src/settings/app03_an_py39/config_pv1.py hl[9:10] *}
-
-/// tip
-
-The `Config` class is used just for Pydantic configuration. You can read more at Pydantic Model Config.
-
-///
-
-////
-
-/// info
-
-In Pydantic version 1 the configuration was done in an internal class `Config`, in Pydantic version 2 it's done in an attribute `model_config`. This attribute takes a `dict`, and to get autocompletion and inline errors you can import and use `SettingsConfigDict` to define that `dict`.
-
-///
-
Here we define the config `env_file` inside of your Pydantic `Settings` class, and set the value to the filename with the dotenv file we want to use.
### Creating the `Settings` only once with `lru_cache` { #creating-the-settings-only-once-with-lru-cache }
diff --git a/docs/en/docs/advanced/sub-applications.md b/docs/en/docs/advanced/sub-applications.md
index fbd0e1af39..60bb15c029 100644
--- a/docs/en/docs/advanced/sub-applications.md
+++ b/docs/en/docs/advanced/sub-applications.md
@@ -10,7 +10,7 @@ If you need to have two independent FastAPI applications, with their own indepen
First, create the main, top-level, **FastAPI** application, and its *path operations*:
-{* ../../docs_src/sub_applications/tutorial001.py hl[3, 6:8] *}
+{* ../../docs_src/sub_applications/tutorial001_py39.py hl[3, 6:8] *}
### Sub-application { #sub-application }
@@ -18,7 +18,7 @@ Then, create your sub-application, and its *path operations*.
This sub-application is just another standard FastAPI application, but this is the one that will be "mounted":
-{* ../../docs_src/sub_applications/tutorial001.py hl[11, 14:16] *}
+{* ../../docs_src/sub_applications/tutorial001_py39.py hl[11, 14:16] *}
### Mount the sub-application { #mount-the-sub-application }
@@ -26,7 +26,7 @@ In your top-level application, `app`, mount the sub-application, `subapi`.
In this case, it will be mounted at the path `/subapi`:
-{* ../../docs_src/sub_applications/tutorial001.py hl[11, 19] *}
+{* ../../docs_src/sub_applications/tutorial001_py39.py hl[11, 19] *}
### Check the automatic API docs { #check-the-automatic-api-docs }
diff --git a/docs/en/docs/advanced/templates.md b/docs/en/docs/advanced/templates.md
index 356f4d9caf..c843d60f73 100644
--- a/docs/en/docs/advanced/templates.md
+++ b/docs/en/docs/advanced/templates.md
@@ -27,7 +27,7 @@ $ pip install jinja2
* Declare a `Request` parameter in the *path operation* that will return a template.
* Use the `templates` you created to render and return a `TemplateResponse`, pass the name of the template, the request object, and a "context" dictionary with key-value pairs to be used inside of the Jinja2 template.
-{* ../../docs_src/templates/tutorial001.py hl[4,11,15:18] *}
+{* ../../docs_src/templates/tutorial001_py39.py hl[4,11,15:18] *}
/// note
diff --git a/docs/en/docs/advanced/testing-events.md b/docs/en/docs/advanced/testing-events.md
index dd93374c4c..13c6e2a259 100644
--- a/docs/en/docs/advanced/testing-events.md
+++ b/docs/en/docs/advanced/testing-events.md
@@ -2,11 +2,11 @@
When you need `lifespan` to run in your tests, you can use the `TestClient` with a `with` statement:
-{* ../../docs_src/app_testing/tutorial004.py hl[9:15,18,27:28,30:32,41:43] *}
+{* ../../docs_src/app_testing/tutorial004_py39.py hl[9:15,18,27:28,30:32,41:43] *}
You can read more details about the ["Running lifespan in tests in the official Starlette documentation site."](https://www.starlette.dev/lifespan/#running-lifespan-in-tests)
For the deprecated `startup` and `shutdown` events, you can use the `TestClient` as follows:
-{* ../../docs_src/app_testing/tutorial003.py hl[9:12,20:24] *}
+{* ../../docs_src/app_testing/tutorial003_py39.py hl[9:12,20:24] *}
diff --git a/docs/en/docs/advanced/testing-websockets.md b/docs/en/docs/advanced/testing-websockets.md
index 27eb2de2fc..a3cc381a33 100644
--- a/docs/en/docs/advanced/testing-websockets.md
+++ b/docs/en/docs/advanced/testing-websockets.md
@@ -4,7 +4,7 @@ You can use the same `TestClient` to test WebSockets.
For this, you use the `TestClient` in a `with` statement, connecting to the WebSocket:
-{* ../../docs_src/app_testing/tutorial002.py hl[27:31] *}
+{* ../../docs_src/app_testing/tutorial002_py39.py hl[27:31] *}
/// note
diff --git a/docs/en/docs/advanced/using-request-directly.md b/docs/en/docs/advanced/using-request-directly.md
index c71d3b05d1..bc23f2df90 100644
--- a/docs/en/docs/advanced/using-request-directly.md
+++ b/docs/en/docs/advanced/using-request-directly.md
@@ -29,7 +29,7 @@ Let's imagine you want to get the client's IP address/host inside of your *path
For that you need to access the request directly.
-{* ../../docs_src/using_request_directly/tutorial001.py hl[1,7:8] *}
+{* ../../docs_src/using_request_directly/tutorial001_py39.py hl[1,7:8] *}
By declaring a *path operation function* parameter with the type being the `Request` **FastAPI** will know to pass the `Request` in that parameter.
diff --git a/docs/en/docs/advanced/websockets.md b/docs/en/docs/advanced/websockets.md
index ce11485a89..286df69432 100644
--- a/docs/en/docs/advanced/websockets.md
+++ b/docs/en/docs/advanced/websockets.md
@@ -38,13 +38,13 @@ In production you would have one of the options above.
But it's the simplest way to focus on the server-side of WebSockets and have a working example:
-{* ../../docs_src/websockets/tutorial001.py hl[2,6:38,41:43] *}
+{* ../../docs_src/websockets/tutorial001_py39.py hl[2,6:38,41:43] *}
## Create a `websocket` { #create-a-websocket }
In your **FastAPI** application, create a `websocket`:
-{* ../../docs_src/websockets/tutorial001.py hl[1,46:47] *}
+{* ../../docs_src/websockets/tutorial001_py39.py hl[1,46:47] *}
/// note | Technical Details
@@ -58,7 +58,7 @@ You could also use `from starlette.websockets import WebSocket`.
In your WebSocket route you can `await` for messages and send messages.
-{* ../../docs_src/websockets/tutorial001.py hl[48:52] *}
+{* ../../docs_src/websockets/tutorial001_py39.py hl[48:52] *}
You can receive and send binary, text, and JSON data.
diff --git a/docs/en/docs/advanced/wsgi.md b/docs/en/docs/advanced/wsgi.md
index 29fd2d359c..07147df0a8 100644
--- a/docs/en/docs/advanced/wsgi.md
+++ b/docs/en/docs/advanced/wsgi.md
@@ -12,7 +12,7 @@ Then wrap the WSGI (e.g. Flask) app with the middleware.
And then mount that under a path.
-{* ../../docs_src/wsgi/tutorial001.py hl[2:3,3] *}
+{* ../../docs_src/wsgi/tutorial001_py39.py hl[2:3,3] *}
## Check it { #check-it }
diff --git a/docs/en/docs/how-to/conditional-openapi.md b/docs/en/docs/how-to/conditional-openapi.md
index e5893e584b..ecb45b4a5b 100644
--- a/docs/en/docs/how-to/conditional-openapi.md
+++ b/docs/en/docs/how-to/conditional-openapi.md
@@ -29,7 +29,7 @@ You can easily use the same Pydantic settings to configure your generated OpenAP
For example:
-{* ../../docs_src/conditional_openapi/tutorial001.py hl[6,11] *}
+{* ../../docs_src/conditional_openapi/tutorial001_py39.py hl[6,11] *}
Here we declare the setting `openapi_url` with the same default of `"/openapi.json"`.
diff --git a/docs/en/docs/how-to/configure-swagger-ui.md b/docs/en/docs/how-to/configure-swagger-ui.md
index 3dbfcffeca..ff46dc5b1b 100644
--- a/docs/en/docs/how-to/configure-swagger-ui.md
+++ b/docs/en/docs/how-to/configure-swagger-ui.md
@@ -18,7 +18,7 @@ Without changing the settings, syntax highlighting is enabled by default:
But you can disable it by setting `syntaxHighlight` to `False`:
-{* ../../docs_src/configure_swagger_ui/tutorial001.py hl[3] *}
+{* ../../docs_src/configure_swagger_ui/tutorial001_py39.py hl[3] *}
...and then Swagger UI won't show the syntax highlighting anymore:
@@ -28,7 +28,7 @@ But you can disable it by setting `syntaxHighlight` to `False`:
The same way you could set the syntax highlighting theme with the key `"syntaxHighlight.theme"` (notice that it has a dot in the middle):
-{* ../../docs_src/configure_swagger_ui/tutorial002.py hl[3] *}
+{* ../../docs_src/configure_swagger_ui/tutorial002_py39.py hl[3] *}
That configuration would change the syntax highlighting color theme:
@@ -46,7 +46,7 @@ You can override any of them by setting a different value in the argument `swagg
For example, to disable `deepLinking` you could pass these settings to `swagger_ui_parameters`:
-{* ../../docs_src/configure_swagger_ui/tutorial003.py hl[3] *}
+{* ../../docs_src/configure_swagger_ui/tutorial003_py39.py hl[3] *}
## Other Swagger UI Parameters { #other-swagger-ui-parameters }
diff --git a/docs/en/docs/how-to/custom-docs-ui-assets.md b/docs/en/docs/how-to/custom-docs-ui-assets.md
index 91228c8c93..61a97dca2b 100644
--- a/docs/en/docs/how-to/custom-docs-ui-assets.md
+++ b/docs/en/docs/how-to/custom-docs-ui-assets.md
@@ -18,7 +18,7 @@ The first step is to disable the automatic docs, as by default, those use the de
To disable them, set their URLs to `None` when creating your `FastAPI` app:
-{* ../../docs_src/custom_docs_ui/tutorial001.py hl[8] *}
+{* ../../docs_src/custom_docs_ui/tutorial001_py39.py hl[8] *}
### Include the custom docs { #include-the-custom-docs }
@@ -34,7 +34,7 @@ You can reuse FastAPI's internal functions to create the HTML pages for the docs
And similarly for ReDoc...
-{* ../../docs_src/custom_docs_ui/tutorial001.py hl[2:6,11:19,22:24,27:33] *}
+{* ../../docs_src/custom_docs_ui/tutorial001_py39.py hl[2:6,11:19,22:24,27:33] *}
/// tip
@@ -50,7 +50,7 @@ Swagger UI will handle it behind the scenes for you, but it needs this "redirect
Now, to be able to test that everything works, create a *path operation*:
-{* ../../docs_src/custom_docs_ui/tutorial001.py hl[36:38] *}
+{* ../../docs_src/custom_docs_ui/tutorial001_py39.py hl[36:38] *}
### Test it { #test-it }
@@ -118,7 +118,7 @@ After that, your file structure could look like:
* Import `StaticFiles`.
* "Mount" a `StaticFiles()` instance in a specific path.
-{* ../../docs_src/custom_docs_ui/tutorial002.py hl[7,11] *}
+{* ../../docs_src/custom_docs_ui/tutorial002_py39.py hl[7,11] *}
### Test the static files { #test-the-static-files }
@@ -144,7 +144,7 @@ The same as when using a custom CDN, the first step is to disable the automatic
To disable them, set their URLs to `None` when creating your `FastAPI` app:
-{* ../../docs_src/custom_docs_ui/tutorial002.py hl[9] *}
+{* ../../docs_src/custom_docs_ui/tutorial002_py39.py hl[9] *}
### Include the custom docs for static files { #include-the-custom-docs-for-static-files }
@@ -160,7 +160,7 @@ Again, you can reuse FastAPI's internal functions to create the HTML pages for t
And similarly for ReDoc...
-{* ../../docs_src/custom_docs_ui/tutorial002.py hl[2:6,14:22,25:27,30:36] *}
+{* ../../docs_src/custom_docs_ui/tutorial002_py39.py hl[2:6,14:22,25:27,30:36] *}
/// tip
@@ -176,7 +176,7 @@ Swagger UI will handle it behind the scenes for you, but it needs this "redirect
Now, to be able to test that everything works, create a *path operation*:
-{* ../../docs_src/custom_docs_ui/tutorial002.py hl[39:41] *}
+{* ../../docs_src/custom_docs_ui/tutorial002_py39.py hl[39:41] *}
### Test Static Files UI { #test-static-files-ui }
diff --git a/docs/en/docs/how-to/extending-openapi.md b/docs/en/docs/how-to/extending-openapi.md
index 5e672665ef..2dc262cbad 100644
--- a/docs/en/docs/how-to/extending-openapi.md
+++ b/docs/en/docs/how-to/extending-openapi.md
@@ -43,19 +43,19 @@ For example, let's add Strawberry documentation.
diff --git a/docs/en/docs/how-to/migrate-from-pydantic-v1-to-pydantic-v2.md b/docs/en/docs/how-to/migrate-from-pydantic-v1-to-pydantic-v2.md
index e85d122be8..fc90220b89 100644
--- a/docs/en/docs/how-to/migrate-from-pydantic-v1-to-pydantic-v2.md
+++ b/docs/en/docs/how-to/migrate-from-pydantic-v1-to-pydantic-v2.md
@@ -2,21 +2,23 @@
If you have an old FastAPI app, you might be using Pydantic version 1.
-FastAPI has had support for either Pydantic v1 or v2 since version 0.100.0.
+FastAPI version 0.100.0 had support for either Pydantic v1 or v2. It would use whichever you had installed.
-If you had installed Pydantic v2, it would use it. If instead you had Pydantic v1, it would use that.
+FastAPI version 0.119.0 introduced partial support for Pydantic v1 from inside of Pydantic v2 (as `pydantic.v1`), to facilitate the migration to v2.
-Pydantic v1 is now deprecated and support for it will be removed in the next versions of FastAPI, you should **migrate to Pydantic v2**. This way you will get the latest features, improvements, and fixes.
+FastAPI 0.126.0 dropped support for Pydantic v1, while still supporting `pydantic.v1` for a little while.
/// warning
-Also, the Pydantic team stopped support for Pydantic v1 for the latest versions of Python, starting with **Python 3.14**.
+The Pydantic team stopped support for Pydantic v1 for the latest versions of Python, starting with **Python 3.14**.
+
+This includes `pydantic.v1`, which is no longer supported in Python 3.14 and above.
If you want to use the latest features of Python, you will need to make sure you use Pydantic v2.
///
-If you have an old FastAPI app with Pydantic v1, here I'll show you how to migrate it to Pydantic v2, and the **new features in FastAPI 0.119.0** to help you with a gradual migration.
+If you have an old FastAPI app with Pydantic v1, here I'll show you how to migrate it to Pydantic v2, and the **features in FastAPI 0.119.0** to help you with a gradual migration.
## Official Guide { #official-guide }
@@ -44,7 +46,7 @@ After this, you can run the tests and check if everything works. If it does, you
## Pydantic v1 in v2 { #pydantic-v1-in-v2 }
-Pydantic v2 includes everything from Pydantic v1 as a submodule `pydantic.v1`.
+Pydantic v2 includes everything from Pydantic v1 as a submodule `pydantic.v1`. But this is no longer supported in versions above Python 3.13.
This means that you can install the latest version of Pydantic v2 and import and use the old Pydantic v1 components from this submodule, as if you had the old Pydantic v1 installed.
diff --git a/docs/en/docs/how-to/separate-openapi-schemas.md b/docs/en/docs/how-to/separate-openapi-schemas.md
index 3c78a56d36..d790c600bb 100644
--- a/docs/en/docs/how-to/separate-openapi-schemas.md
+++ b/docs/en/docs/how-to/separate-openapi-schemas.md
@@ -1,6 +1,6 @@
# Separate OpenAPI Schemas for Input and Output or Not { #separate-openapi-schemas-for-input-and-output-or-not }
-When using **Pydantic v2**, the generated OpenAPI is a bit more exact and **correct** than before. 😎
+Since **Pydantic v2** was released, the generated OpenAPI is a bit more exact and **correct** than before. 😎
In fact, in some cases, it will even have **two JSON Schemas** in OpenAPI for the same Pydantic model, for input and output, depending on if they have **default values**.
@@ -100,5 +100,3 @@ And now there will be one single schema for input and output for the model, only
-
-This is the same behavior as in Pydantic v1. 🤓
diff --git a/docs/en/docs/img/fastapi-documentary.jpg b/docs/en/docs/img/fastapi-documentary.jpg
new file mode 100644
index 0000000000..3ddbfdb389
Binary files /dev/null and b/docs/en/docs/img/fastapi-documentary.jpg differ
diff --git a/docs/en/docs/index.md b/docs/en/docs/index.md
index a0a5de3b71..5eb47c7b32 100644
--- a/docs/en/docs/index.md
+++ b/docs/en/docs/index.md
@@ -117,6 +117,12 @@ The key features are:
---
+## FastAPI mini documentary { #fastapi-mini-documentary }
+
+There's a FastAPI mini documentary released at the end of 2025, you can watch it online:
+
+
+
## **Typer**, the FastAPI of CLIs { #typer-the-fastapi-of-clis }
diff --git a/docs/en/docs/management-tasks.md b/docs/en/docs/management-tasks.md
index 05cd5d27d0..aac4d6fe40 100644
--- a/docs/en/docs/management-tasks.md
+++ b/docs/en/docs/management-tasks.md
@@ -239,7 +239,7 @@ A PR should have a specific use case that it is solving.
* If the PR is for a feature, it should have docs.
* Unless it's a feature we want to discourage, like support for a corner case that we don't want users to use.
* The docs should include a source example file, not write Python directly in Markdown.
-* If the source example(s) file can have different syntax for Python 3.8, 3.9, 3.10, there should be different versions of the file, and they should be shown in tabs in the docs.
+* If the source example(s) file can have different syntax for different Python versions, there should be different versions of the file, and they should be shown in tabs in the docs.
* There should be tests testing the source example.
* Before the PR is applied, the new tests should fail.
* After applying the PR, the new tests should pass.
diff --git a/docs/en/docs/python-types.md b/docs/en/docs/python-types.md
index e4bd2a8749..b685deef29 100644
--- a/docs/en/docs/python-types.md
+++ b/docs/en/docs/python-types.md
@@ -22,7 +22,7 @@ If you are a Python expert, and you already know everything about type hints, sk
Let's start with a simple example:
-{* ../../docs_src/python_types/tutorial001.py *}
+{* ../../docs_src/python_types/tutorial001_py39.py *}
Calling this program outputs:
@@ -36,7 +36,7 @@ The function does the following:
* Converts the first letter of each one to upper case with `title()`.
* Concatenates them with a space in the middle.
-{* ../../docs_src/python_types/tutorial001.py hl[2] *}
+{* ../../docs_src/python_types/tutorial001_py39.py hl[2] *}
### Edit it { #edit-it }
@@ -78,7 +78,7 @@ That's it.
Those are the "type hints":
-{* ../../docs_src/python_types/tutorial002.py hl[1] *}
+{* ../../docs_src/python_types/tutorial002_py39.py hl[1] *}
That is not the same as declaring default values like would be with:
@@ -106,7 +106,7 @@ With that, you can scroll, seeing the options, until you find the one that "ring
Check this function, it already has type hints:
-{* ../../docs_src/python_types/tutorial003.py hl[1] *}
+{* ../../docs_src/python_types/tutorial003_py39.py hl[1] *}
Because the editor knows the types of the variables, you don't only get completion, you also get error checks:
@@ -114,7 +114,7 @@ Because the editor knows the types of the variables, you don't only get completi
Now you know that you have to fix it, convert `age` to a string with `str(age)`:
-{* ../../docs_src/python_types/tutorial004.py hl[2] *}
+{* ../../docs_src/python_types/tutorial004_py39.py hl[2] *}
## Declaring types { #declaring-types }
@@ -133,7 +133,7 @@ You can use, for example:
* `bool`
* `bytes`
-{* ../../docs_src/python_types/tutorial005.py hl[1] *}
+{* ../../docs_src/python_types/tutorial005_py39.py hl[1] *}
### Generic types with type parameters { #generic-types-with-type-parameters }
@@ -161,56 +161,24 @@ If you can use the **latest versions of Python**, use the examples for the lates
For example, let's define a variable to be a `list` of `str`.
-//// tab | Python 3.9+
-
Declare the variable, with the same colon (`:`) syntax.
As the type, put `list`.
As the list is a type that contains some internal types, you put them in square brackets:
-```Python hl_lines="1"
-{!> ../../docs_src/python_types/tutorial006_py39.py!}
-```
-
-////
-
-//// tab | Python 3.8+
-
-From `typing`, import `List` (with a capital `L`):
-
-```Python hl_lines="1"
-{!> ../../docs_src/python_types/tutorial006.py!}
-```
-
-Declare the variable, with the same colon (`:`) syntax.
-
-As the type, put the `List` that you imported from `typing`.
-
-As the list is a type that contains some internal types, you put them in square brackets:
-
-```Python hl_lines="4"
-{!> ../../docs_src/python_types/tutorial006.py!}
-```
-
-////
+{* ../../docs_src/python_types/tutorial006_py39.py hl[1] *}
/// info
Those internal types in the square brackets are called "type parameters".
-In this case, `str` is the type parameter passed to `List` (or `list` in Python 3.9 and above).
+In this case, `str` is the type parameter passed to `list`.
///
That means: "the variable `items` is a `list`, and each of the items in this list is a `str`".
-/// tip
-
-If you use Python 3.9 or above, you don't have to import `List` from `typing`, you can use the same regular `list` type instead.
-
-///
-
By doing that, your editor can provide support even while processing items from the list:
@@ -225,21 +193,7 @@ And still, the editor knows it is a `str`, and provides support for that.
You would do the same to declare `tuple`s and `set`s:
-//// tab | Python 3.9+
-
-```Python hl_lines="1"
-{!> ../../docs_src/python_types/tutorial007_py39.py!}
-```
-
-////
-
-//// tab | Python 3.8+
-
-```Python hl_lines="1 4"
-{!> ../../docs_src/python_types/tutorial007.py!}
-```
-
-////
+{* ../../docs_src/python_types/tutorial007_py39.py hl[1] *}
This means:
@@ -254,21 +208,7 @@ The first type parameter is for the keys of the `dict`.
The second type parameter is for the values of the `dict`:
-//// tab | Python 3.9+
-
-```Python hl_lines="1"
-{!> ../../docs_src/python_types/tutorial008_py39.py!}
-```
-
-////
-
-//// tab | Python 3.8+
-
-```Python hl_lines="1 4"
-{!> ../../docs_src/python_types/tutorial008.py!}
-```
-
-////
+{* ../../docs_src/python_types/tutorial008_py39.py hl[1] *}
This means:
@@ -292,10 +232,10 @@ In Python 3.10 there's also a **new syntax** where you can put the possible type
////
-//// tab | Python 3.8+
+//// tab | Python 3.9+
```Python hl_lines="1 4"
-{!> ../../docs_src/python_types/tutorial008b.py!}
+{!> ../../docs_src/python_types/tutorial008b_py39.py!}
```
////
@@ -309,7 +249,7 @@ You can declare that a value could have a type, like `str`, but that it could al
In Python 3.6 and above (including Python 3.10) you can declare it by importing and using `Optional` from the `typing` module.
```Python hl_lines="1 4"
-{!../../docs_src/python_types/tutorial009.py!}
+{!../../docs_src/python_types/tutorial009_py39.py!}
```
Using `Optional[str]` instead of just `str` will let the editor help you detect errors where you could be assuming that a value is always a `str`, when it could actually be `None` too.
@@ -326,18 +266,18 @@ This also means that in Python 3.10, you can use `Something | None`:
////
-//// tab | Python 3.8+
+//// tab | Python 3.9+
```Python hl_lines="1 4"
-{!> ../../docs_src/python_types/tutorial009.py!}
+{!> ../../docs_src/python_types/tutorial009_py39.py!}
```
////
-//// tab | Python 3.8+ alternative
+//// tab | Python 3.9+ alternative
```Python hl_lines="1 4"
-{!> ../../docs_src/python_types/tutorial009b.py!}
+{!> ../../docs_src/python_types/tutorial009b_py39.py!}
```
////
@@ -357,7 +297,7 @@ It's just about the words and names. But those words can affect how you and your
As an example, let's take this function:
-{* ../../docs_src/python_types/tutorial009c.py hl[1,4] *}
+{* ../../docs_src/python_types/tutorial009c_py39.py hl[1,4] *}
The parameter `name` is defined as `Optional[str]`, but it is **not optional**, you cannot call the function without the parameter:
@@ -390,10 +330,10 @@ You can use the same builtin types as generics (with square brackets and types i
* `set`
* `dict`
-And the same as with Python 3.8, from the `typing` module:
+And the same as with previous Python versions, from the `typing` module:
* `Union`
-* `Optional` (the same as with Python 3.8)
+* `Optional`
* ...and others.
In Python 3.10, as an alternative to using the generics `Union` and `Optional`, you can use the vertical bar (`|`) to declare unions of types, that's a lot better and simpler.
@@ -409,7 +349,7 @@ You can use the same builtin types as generics (with square brackets and types i
* `set`
* `dict`
-And the same as with Python 3.8, from the `typing` module:
+And generics from the `typing` module:
* `Union`
* `Optional`
@@ -417,29 +357,17 @@ And the same as with Python 3.8, from the `typing` module:
////
-//// tab | Python 3.8+
-
-* `List`
-* `Tuple`
-* `Set`
-* `Dict`
-* `Union`
-* `Optional`
-* ...and others.
-
-////
-
### Classes as types { #classes-as-types }
You can also declare a class as the type of a variable.
Let's say you have a class `Person`, with a name:
-{* ../../docs_src/python_types/tutorial010.py hl[1:3] *}
+{* ../../docs_src/python_types/tutorial010_py39.py hl[1:3] *}
Then you can declare a variable to be of type `Person`:
-{* ../../docs_src/python_types/tutorial010.py hl[6] *}
+{* ../../docs_src/python_types/tutorial010_py39.py hl[6] *}
And then, again, you get all the editor support:
@@ -463,29 +391,7 @@ And you get all the editor support with that resulting object.
An example from the official Pydantic docs:
-//// tab | Python 3.10+
-
-```Python
-{!> ../../docs_src/python_types/tutorial011_py310.py!}
-```
-
-////
-
-//// tab | Python 3.9+
-
-```Python
-{!> ../../docs_src/python_types/tutorial011_py39.py!}
-```
-
-////
-
-//// tab | Python 3.8+
-
-```Python
-{!> ../../docs_src/python_types/tutorial011.py!}
-```
-
-////
+{* ../../docs_src/python_types/tutorial011_py310.py *}
/// info
@@ -507,27 +413,9 @@ Pydantic has a special behavior when you use `Optional` or `Union[Something, Non
Python also has a feature that allows putting **additional metadata** in these type hints using `Annotated`.
-//// tab | Python 3.9+
+Since Python 3.9, `Annotated` is a part of the standard library, so you can import it from `typing`.
-In Python 3.9, `Annotated` is part of the standard library, so you can import it from `typing`.
-
-```Python hl_lines="1 4"
-{!> ../../docs_src/python_types/tutorial013_py39.py!}
-```
-
-////
-
-//// tab | Python 3.8+
-
-In versions below Python 3.9, you import `Annotated` from `typing_extensions`.
-
-It will already be installed with **FastAPI**.
-
-```Python hl_lines="1 4"
-{!> ../../docs_src/python_types/tutorial013.py!}
-```
-
-////
+{* ../../docs_src/python_types/tutorial013_py39.py hl[1,4] *}
Python itself doesn't do anything with this `Annotated`. And for editors and other tools, the type is still `str`.
diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md
index bb72f4001e..9bd794f03a 100644
--- a/docs/en/docs/release-notes.md
+++ b/docs/en/docs/release-notes.md
@@ -9,6 +9,110 @@ hide:
### Translations
+* 🔧 Add LLM prompt file for Turkish, generated from the existing translations. PR [#14547](https://github.com/fastapi/fastapi/pull/14547) by [@tiangolo](https://github.com/tiangolo).
+* 🔧 Add LLM prompt file for Traditional Chinese, generated from the existing translations. PR [#14550](https://github.com/fastapi/fastapi/pull/14550) by [@tiangolo](https://github.com/tiangolo).
+* 🔧 Add LLM prompt file for Simplified Chinese, generated from the existing translations. PR [#14549](https://github.com/fastapi/fastapi/pull/14549) by [@tiangolo](https://github.com/tiangolo).
+
+### Internal
+
+* 👥 Update FastAPI People - Sponsors. PR [#14626](https://github.com/fastapi/fastapi/pull/14626) by [@tiangolo](https://github.com/tiangolo).
+* 👥 Update FastAPI GitHub topic repositories. PR [#14630](https://github.com/fastapi/fastapi/pull/14630) by [@tiangolo](https://github.com/tiangolo).
+* 👥 Update FastAPI People - Contributors and Translators. PR [#14625](https://github.com/fastapi/fastapi/pull/14625) by [@tiangolo](https://github.com/tiangolo).
+* 🌐 Update translation prompts. PR [#14619](https://github.com/fastapi/fastapi/pull/14619) by [@tiangolo](https://github.com/tiangolo).
+* 🔨 Update LLM translation script to guide reviewers to change the prompt. PR [#14614](https://github.com/fastapi/fastapi/pull/14614) by [@tiangolo](https://github.com/tiangolo).
+* 👷 Do not run translations on cron while finishing updating existing languages. PR [#14613](https://github.com/fastapi/fastapi/pull/14613) by [@tiangolo](https://github.com/tiangolo).
+* 🔥 Remove test variants for Pydantic v1 in test_request_params. PR [#14612](https://github.com/fastapi/fastapi/pull/14612) by [@tiangolo](https://github.com/tiangolo).
+* 🔥 Remove Pydantic v1 specific test variants. PR [#14611](https://github.com/fastapi/fastapi/pull/14611) by [@tiangolo](https://github.com/tiangolo).
+
+## 0.128.0
+
+### Breaking Changes
+
+* ➖ Drop support for `pydantic.v1`. PR [#14609](https://github.com/fastapi/fastapi/pull/14609) by [@tiangolo](https://github.com/tiangolo).
+
+### Internal
+
+* ✅ Run performance tests only on Pydantic v2. PR [#14608](https://github.com/fastapi/fastapi/pull/14608) by [@tiangolo](https://github.com/tiangolo).
+
+## 0.127.1
+
+### Refactors
+
+* 🔊 Add a custom `FastAPIDeprecationWarning`. PR [#14605](https://github.com/fastapi/fastapi/pull/14605) by [@tiangolo](https://github.com/tiangolo).
+
+### Docs
+
+* 📝 Add documentary to website. PR [#14600](https://github.com/fastapi/fastapi/pull/14600) by [@tiangolo](https://github.com/tiangolo).
+
+### Translations
+
+* 🌐 Update translations for de (update-outdated). PR [#14602](https://github.com/fastapi/fastapi/pull/14602) by [@nilslindemann](https://github.com/nilslindemann).
+* 🌐 Update translations for de (update-outdated). PR [#14581](https://github.com/fastapi/fastapi/pull/14581) by [@nilslindemann](https://github.com/nilslindemann).
+
+### Internal
+
+* 🔧 Update pre-commit to use local Ruff instead of hook. PR [#14604](https://github.com/fastapi/fastapi/pull/14604) by [@tiangolo](https://github.com/tiangolo).
+* ✅ Add missing tests for code examples. PR [#14569](https://github.com/fastapi/fastapi/pull/14569) by [@YuriiMotov](https://github.com/YuriiMotov).
+* 👷 Remove `lint` job from `test` CI workflow. PR [#14593](https://github.com/fastapi/fastapi/pull/14593) by [@YuriiMotov](https://github.com/YuriiMotov).
+* 👷 Update secrets check. PR [#14592](https://github.com/fastapi/fastapi/pull/14592) by [@tiangolo](https://github.com/tiangolo).
+* 👷 Run CodSpeed tests in parallel to other tests to speed up CI. PR [#14586](https://github.com/fastapi/fastapi/pull/14586) by [@tiangolo](https://github.com/tiangolo).
+* 🔨 Update scripts and pre-commit to autofix files. PR [#14585](https://github.com/fastapi/fastapi/pull/14585) by [@tiangolo](https://github.com/tiangolo).
+
+## 0.127.0
+
+### Breaking Changes
+
+* 🔊 Add deprecation warnings when using `pydantic.v1`. PR [#14583](https://github.com/fastapi/fastapi/pull/14583) by [@tiangolo](https://github.com/tiangolo).
+
+### Translations
+
+* 🔧 Add LLM prompt file for Korean, generated from the existing translations. PR [#14546](https://github.com/fastapi/fastapi/pull/14546) by [@tiangolo](https://github.com/tiangolo).
+* 🔧 Add LLM prompt file for Japanese, generated from the existing translations. PR [#14545](https://github.com/fastapi/fastapi/pull/14545) by [@tiangolo](https://github.com/tiangolo).
+
+### Internal
+
+* ⬆️ Upgrade OpenAI model for translations to gpt-5.2. PR [#14579](https://github.com/fastapi/fastapi/pull/14579) by [@tiangolo](https://github.com/tiangolo).
+
+## 0.126.0
+
+### Upgrades
+
+* ➖ Drop support for Pydantic v1, keeping short temporary support for Pydantic v2's `pydantic.v1`. PR [#14575](https://github.com/fastapi/fastapi/pull/14575) by [@tiangolo](https://github.com/tiangolo).
+ * The minimum version of Pydantic installed is now `pydantic >=2.7.0`.
+ * The `standard` dependencies now include `pydantic-settings >=2.0.0` and `pydantic-extra-types >=2.0.0`.
+
+### Docs
+
+* 📝 Fix duplicated variable in `docs_src/python_types/tutorial005_py39.py`. PR [#14565](https://github.com/fastapi/fastapi/pull/14565) by [@paras-verma7454](https://github.com/paras-verma7454).
+
+### Translations
+
+* 🔧 Add LLM prompt file for Ukrainian, generated from the existing translations. PR [#14548](https://github.com/fastapi/fastapi/pull/14548) by [@tiangolo](https://github.com/tiangolo).
+
+### Internal
+
+* 🔧 Tweak pre-commit to allow committing release-notes. PR [#14577](https://github.com/fastapi/fastapi/pull/14577) by [@tiangolo](https://github.com/tiangolo).
+* ⬆️ Use prek as a pre-commit alternative. PR [#14572](https://github.com/fastapi/fastapi/pull/14572) by [@tiangolo](https://github.com/tiangolo).
+* 👷 Add performance tests with CodSpeed. PR [#14558](https://github.com/fastapi/fastapi/pull/14558) by [@tiangolo](https://github.com/tiangolo).
+
+## 0.125.0
+
+### Breaking Changes
+
+* 🔧 Drop support for Python 3.8. PR [#14563](https://github.com/fastapi/fastapi/pull/14563) by [@tiangolo](https://github.com/tiangolo).
+ * This would actually not be a _breaking_ change as no code would really break. Any Python 3.8 installer would just refuse to install the latest version of FastAPI and would only install 0.124.4. Only marking it as a "breaking change" to make it visible.
+
+### Refactors
+
+* ♻️ Upgrade internal syntax to Python 3.9+ 🎉. PR [#14564](https://github.com/fastapi/fastapi/pull/14564) by [@tiangolo](https://github.com/tiangolo).
+
+### Docs
+
+* ⚰️ Remove Python 3.8 from CI and remove Python 3.8 examples from source docs. PR [#14559](https://github.com/fastapi/fastapi/pull/14559) by [@YuriiMotov](https://github.com/YuriiMotov) and [@tiangolo](https://github.com/tiangolo).
+
+### Translations
+
+* 🌐 Update translations for pt (add-missing). PR [#14539](https://github.com/fastapi/fastapi/pull/14539) by [@tiangolo](https://github.com/tiangolo).
* 🔧 Add LLM prompt file for French, generated from the existing French docs. PR [#14544](https://github.com/fastapi/fastapi/pull/14544) by [@tiangolo](https://github.com/tiangolo).
* 🌐 Sync Portuguese docs (pages found with script). PR [#14554](https://github.com/fastapi/fastapi/pull/14554) by [@YuriiMotov](https://github.com/YuriiMotov).
* 🌐 Sync Spanish docs (outdated pages found with script). PR [#14553](https://github.com/fastapi/fastapi/pull/14553) by [@YuriiMotov](https://github.com/YuriiMotov).
diff --git a/docs/en/docs/tutorial/background-tasks.md b/docs/en/docs/tutorial/background-tasks.md
index ab44f89c19..be7ecd5871 100644
--- a/docs/en/docs/tutorial/background-tasks.md
+++ b/docs/en/docs/tutorial/background-tasks.md
@@ -15,7 +15,7 @@ This includes, for example:
First, import `BackgroundTasks` and define a parameter in your *path operation function* with a type declaration of `BackgroundTasks`:
-{* ../../docs_src/background_tasks/tutorial001.py hl[1,13] *}
+{* ../../docs_src/background_tasks/tutorial001_py39.py hl[1,13] *}
**FastAPI** will create the object of type `BackgroundTasks` for you and pass it as that parameter.
@@ -31,13 +31,13 @@ In this case, the task function will write to a file (simulating sending an emai
And as the write operation doesn't use `async` and `await`, we define the function with normal `def`:
-{* ../../docs_src/background_tasks/tutorial001.py hl[6:9] *}
+{* ../../docs_src/background_tasks/tutorial001_py39.py hl[6:9] *}
## Add the background task { #add-the-background-task }
Inside of your *path operation function*, pass your task function to the *background tasks* object with the method `.add_task()`:
-{* ../../docs_src/background_tasks/tutorial001.py hl[14] *}
+{* ../../docs_src/background_tasks/tutorial001_py39.py hl[14] *}
`.add_task()` receives as arguments:
diff --git a/docs/en/docs/tutorial/body-nested-models.md b/docs/en/docs/tutorial/body-nested-models.md
index 445235a420..5fd83a8f3c 100644
--- a/docs/en/docs/tutorial/body-nested-models.md
+++ b/docs/en/docs/tutorial/body-nested-models.md
@@ -14,35 +14,15 @@ This will make `tags` be a list, although it doesn't declare the type of the ele
But Python has a specific way to declare lists with internal types, or "type parameters":
-### Import typing's `List` { #import-typings-list }
-
-In Python 3.9 and above you can use the standard `list` to declare these type annotations as we'll see below. 💡
-
-But in Python versions before 3.9 (3.6 and above), you first need to import `List` from standard Python's `typing` module:
-
-{* ../../docs_src/body_nested_models/tutorial002.py hl[1] *}
-
### Declare a `list` with a type parameter { #declare-a-list-with-a-type-parameter }
-To declare types that have type parameters (internal types), like `list`, `dict`, `tuple`:
-
-* If you are in a Python version lower than 3.9, import their equivalent version from the `typing` module
-* Pass the internal type(s) as "type parameters" using square brackets: `[` and `]`
-
-In Python 3.9 it would be:
+To declare types that have type parameters (internal types), like `list`, `dict`, `tuple`,
+pass the internal type(s) as "type parameters" using square brackets: `[` and `]`
```Python
my_list: list[str]
```
-In versions of Python before 3.9, it would be:
-
-```Python
-from typing import List
-
-my_list: List[str]
-```
-
That's all standard Python syntax for type declarations.
Use that same standard syntax for model attributes with internal types.
@@ -178,12 +158,6 @@ Notice how `Offer` has a list of `Item`s, which in turn have an optional list of
If the top level value of the JSON body you expect is a JSON `array` (a Python `list`), you can declare the type in the parameter of the function, the same as in Pydantic models:
-```Python
-images: List[Image]
-```
-
-or in Python 3.9 and above:
-
```Python
images: list[Image]
```
diff --git a/docs/en/docs/tutorial/body-updates.md b/docs/en/docs/tutorial/body-updates.md
index baeb53ec6f..1b7fd70661 100644
--- a/docs/en/docs/tutorial/body-updates.md
+++ b/docs/en/docs/tutorial/body-updates.md
@@ -50,14 +50,6 @@ If you want to receive partial updates, it's very useful to use the parameter `e
Like `item.model_dump(exclude_unset=True)`.
-/// info
-
-In Pydantic v1 the method was called `.dict()`, it was deprecated (but still supported) in Pydantic v2, and renamed to `.model_dump()`.
-
-The examples here use `.dict()` for compatibility with Pydantic v1, but you should use `.model_dump()` instead if you can use Pydantic v2.
-
-///
-
That would generate a `dict` with only the data that was set when creating the `item` model, excluding default values.
Then you can use this to generate a `dict` with only the data that was set (sent in the request), omitting default values:
@@ -68,14 +60,6 @@ Then you can use this to generate a `dict` with only the data that was set (sent
Now, you can create a copy of the existing model using `.model_copy()`, and pass the `update` parameter with a `dict` containing the data to update.
-/// info
-
-In Pydantic v1 the method was called `.copy()`, it was deprecated (but still supported) in Pydantic v2, and renamed to `.model_copy()`.
-
-The examples here use `.copy()` for compatibility with Pydantic v1, but you should use `.model_copy()` instead if you can use Pydantic v2.
-
-///
-
Like `stored_item_model.model_copy(update=update_data)`:
{* ../../docs_src/body_updates/tutorial002_py310.py hl[33] *}
diff --git a/docs/en/docs/tutorial/body.md b/docs/en/docs/tutorial/body.md
index a820802f74..2d0dfcbb59 100644
--- a/docs/en/docs/tutorial/body.md
+++ b/docs/en/docs/tutorial/body.md
@@ -128,14 +128,6 @@ Inside of the function, you can access all the attributes of the model object di
{* ../../docs_src/body/tutorial002_py310.py *}
-/// info
-
-In Pydantic v1 the method was called `.dict()`, it was deprecated (but still supported) in Pydantic v2, and renamed to `.model_dump()`.
-
-The examples here use `.dict()` for compatibility with Pydantic v1, but you should use `.model_dump()` instead if you can use Pydantic v2.
-
-///
-
## Request body + path parameters { #request-body-path-parameters }
You can declare path parameters and request body at the same time.
@@ -163,7 +155,7 @@ The function parameters will be recognized as follows:
FastAPI will know that the value of `q` is not required because of the default value `= None`.
-The `str | None` (Python 3.10+) or `Union` in `Union[str, None]` (Python 3.8+) is not used by FastAPI to determine that the value is not required, it will know it's not required because it has a default value of `= None`.
+The `str | None` (Python 3.10+) or `Union` in `Union[str, None]` (Python 3.9+) is not used by FastAPI to determine that the value is not required, it will know it's not required because it has a default value of `= None`.
But adding the type annotations will allow your editor to give you better support and detect errors.
diff --git a/docs/en/docs/tutorial/cors.md b/docs/en/docs/tutorial/cors.md
index e3de37b43c..8a3a8eb0a8 100644
--- a/docs/en/docs/tutorial/cors.md
+++ b/docs/en/docs/tutorial/cors.md
@@ -46,7 +46,7 @@ You can also specify whether your backend allows:
* Specific HTTP methods (`POST`, `PUT`) or all of them with the wildcard `"*"`.
* Specific HTTP headers or all of them with the wildcard `"*"`.
-{* ../../docs_src/cors/tutorial001.py hl[2,6:11,13:19] *}
+{* ../../docs_src/cors/tutorial001_py39.py hl[2,6:11,13:19] *}
The default parameters used by the `CORSMiddleware` implementation are restrictive by default, so you'll need to explicitly enable particular origins, methods, or headers, in order for browsers to be permitted to use them in a Cross-Domain context.
diff --git a/docs/en/docs/tutorial/debugging.md b/docs/en/docs/tutorial/debugging.md
index 08b440084e..a2edfe7203 100644
--- a/docs/en/docs/tutorial/debugging.md
+++ b/docs/en/docs/tutorial/debugging.md
@@ -6,7 +6,7 @@ You can connect the debugger in your editor, for example with Visual Studio Code
In your FastAPI application, import and run `uvicorn` directly:
-{* ../../docs_src/debugging/tutorial001.py hl[1,15] *}
+{* ../../docs_src/debugging/tutorial001_py39.py hl[1,15] *}
### About `__name__ == "__main__"` { #about-name-main }
diff --git a/docs/en/docs/tutorial/dependencies/classes-as-dependencies.md b/docs/en/docs/tutorial/dependencies/classes-as-dependencies.md
index 686a5632e2..0a6a786b50 100644
--- a/docs/en/docs/tutorial/dependencies/classes-as-dependencies.md
+++ b/docs/en/docs/tutorial/dependencies/classes-as-dependencies.md
@@ -101,7 +101,7 @@ Now you can declare your dependency using this class.
Notice how we write `CommonQueryParams` twice in the above code:
-//// tab | Python 3.8+
+//// tab | Python 3.9+
```Python
commons: Annotated[CommonQueryParams, Depends(CommonQueryParams)]
@@ -109,7 +109,7 @@ commons: Annotated[CommonQueryParams, Depends(CommonQueryParams)]
////
-//// tab | Python 3.8+ non-Annotated
+//// tab | Python 3.9+ non-Annotated
/// tip
@@ -137,7 +137,7 @@ It is from this one that FastAPI will extract the declared parameters and that i
In this case, the first `CommonQueryParams`, in:
-//// tab | Python 3.8+
+//// tab | Python 3.9+
```Python
commons: Annotated[CommonQueryParams, ...
@@ -145,7 +145,7 @@ commons: Annotated[CommonQueryParams, ...
////
-//// tab | Python 3.8+ non-Annotated
+//// tab | Python 3.9+ non-Annotated
/// tip
@@ -163,7 +163,7 @@ commons: CommonQueryParams ...
You could actually write just:
-//// tab | Python 3.8+
+//// tab | Python 3.9+
```Python
commons: Annotated[Any, Depends(CommonQueryParams)]
@@ -171,7 +171,7 @@ commons: Annotated[Any, Depends(CommonQueryParams)]
////
-//// tab | Python 3.8+ non-Annotated
+//// tab | Python 3.9+ non-Annotated
/// tip
@@ -197,7 +197,7 @@ But declaring the type is encouraged as that way your editor will know what will
But you see that we are having some code repetition here, writing `CommonQueryParams` twice:
-//// tab | Python 3.8+
+//// tab | Python 3.9+
```Python
commons: Annotated[CommonQueryParams, Depends(CommonQueryParams)]
@@ -205,7 +205,7 @@ commons: Annotated[CommonQueryParams, Depends(CommonQueryParams)]
////
-//// tab | Python 3.8+ non-Annotated
+//// tab | Python 3.9+ non-Annotated
/// tip
@@ -225,7 +225,7 @@ For those specific cases, you can do the following:
Instead of writing:
-//// tab | Python 3.8+
+//// tab | Python 3.9+
```Python
commons: Annotated[CommonQueryParams, Depends(CommonQueryParams)]
@@ -233,7 +233,7 @@ commons: Annotated[CommonQueryParams, Depends(CommonQueryParams)]
////
-//// tab | Python 3.8+ non-Annotated
+//// tab | Python 3.9+ non-Annotated
/// tip
@@ -249,7 +249,7 @@ commons: CommonQueryParams = Depends(CommonQueryParams)
...you write:
-//// tab | Python 3.8+
+//// tab | Python 3.9+
```Python
commons: Annotated[CommonQueryParams, Depends()]
@@ -257,7 +257,7 @@ commons: Annotated[CommonQueryParams, Depends()]
////
-//// tab | Python 3.8 non-Annotated
+//// tab | Python 3.9+ non-Annotated
/// tip
diff --git a/docs/en/docs/tutorial/dependencies/dependencies-with-yield.md b/docs/en/docs/tutorial/dependencies/dependencies-with-yield.md
index 494c40efab..d9f3345619 100644
--- a/docs/en/docs/tutorial/dependencies/dependencies-with-yield.md
+++ b/docs/en/docs/tutorial/dependencies/dependencies-with-yield.md
@@ -29,15 +29,15 @@ For example, you could use this to create a database session and close it after
Only the code prior to and including the `yield` statement is executed before creating a response:
-{* ../../docs_src/dependencies/tutorial007.py hl[2:4] *}
+{* ../../docs_src/dependencies/tutorial007_py39.py hl[2:4] *}
The yielded value is what is injected into *path operations* and other dependencies:
-{* ../../docs_src/dependencies/tutorial007.py hl[4] *}
+{* ../../docs_src/dependencies/tutorial007_py39.py hl[4] *}
The code following the `yield` statement is executed after the response:
-{* ../../docs_src/dependencies/tutorial007.py hl[5:6] *}
+{* ../../docs_src/dependencies/tutorial007_py39.py hl[5:6] *}
/// tip
@@ -57,7 +57,7 @@ So, you can look for that specific exception inside the dependency with `except
In the same way, you can use `finally` to make sure the exit steps are executed, no matter if there was an exception or not.
-{* ../../docs_src/dependencies/tutorial007.py hl[3,5] *}
+{* ../../docs_src/dependencies/tutorial007_py39.py hl[3,5] *}
## Sub-dependencies with `yield` { #sub-dependencies-with-yield }
@@ -269,7 +269,7 @@ In Python, you can create Context Managers by deprecated, but without removing it, pass the parameter `deprecated`:
-{* ../../docs_src/path_operation_configuration/tutorial006.py hl[16] *}
+{* ../../docs_src/path_operation_configuration/tutorial006_py39.py hl[16] *}
It will be clearly marked as deprecated in the interactive docs:
diff --git a/docs/en/docs/tutorial/path-params-numeric-validations.md b/docs/en/docs/tutorial/path-params-numeric-validations.md
index f7f2d6ceb0..8b1b8a8392 100644
--- a/docs/en/docs/tutorial/path-params-numeric-validations.md
+++ b/docs/en/docs/tutorial/path-params-numeric-validations.md
@@ -54,7 +54,7 @@ It doesn't matter for **FastAPI**. It will detect the parameters by their names,
So, you can declare your function as:
-{* ../../docs_src/path_params_numeric_validations/tutorial002.py hl[7] *}
+{* ../../docs_src/path_params_numeric_validations/tutorial002_py39.py hl[7] *}
But keep in mind that if you use `Annotated`, you won't have this problem, it won't matter as you're not using the function parameter default values for `Query()` or `Path()`.
@@ -83,7 +83,7 @@ Pass `*`, as the first parameter of the function.
Python won't do anything with that `*`, but it will know that all the following parameters should be called as keyword arguments (key-value pairs), also known as kwargs. Even if they don't have a default value.
-{* ../../docs_src/path_params_numeric_validations/tutorial003.py hl[7] *}
+{* ../../docs_src/path_params_numeric_validations/tutorial003_py39.py hl[7] *}
### Better with `Annotated` { #better-with-annotated }
diff --git a/docs/en/docs/tutorial/path-params.md b/docs/en/docs/tutorial/path-params.md
index 457cc2713f..ea4307900c 100644
--- a/docs/en/docs/tutorial/path-params.md
+++ b/docs/en/docs/tutorial/path-params.md
@@ -2,7 +2,7 @@
You can declare path "parameters" or "variables" with the same syntax used by Python format strings:
-{* ../../docs_src/path_params/tutorial001.py hl[6:7] *}
+{* ../../docs_src/path_params/tutorial001_py39.py hl[6:7] *}
The value of the path parameter `item_id` will be passed to your function as the argument `item_id`.
@@ -16,7 +16,7 @@ So, if you run this example and go to Enumerations (or enums) are available in Python since version 3.4.
-
-///
+{* ../../docs_src/path_params/tutorial005_py39.py hl[1,6:9] *}
/// tip
@@ -158,7 +152,7 @@ If you are wondering, "AlexNet", "ResNet", and "LeNet" are just names of Machine
Then create a *path parameter* with a type annotation using the enum class you created (`ModelName`):
-{* ../../docs_src/path_params/tutorial005.py hl[16] *}
+{* ../../docs_src/path_params/tutorial005_py39.py hl[16] *}
### Check the docs { #check-the-docs }
@@ -174,13 +168,13 @@ The value of the *path parameter* will be an *enumeration member*.
You can compare it with the *enumeration member* in your created enum `ModelName`:
-{* ../../docs_src/path_params/tutorial005.py hl[17] *}
+{* ../../docs_src/path_params/tutorial005_py39.py hl[17] *}
#### Get the *enumeration value* { #get-the-enumeration-value }
You can get the actual value (a `str` in this case) using `model_name.value`, or in general, `your_enum_member.value`:
-{* ../../docs_src/path_params/tutorial005.py hl[20] *}
+{* ../../docs_src/path_params/tutorial005_py39.py hl[20] *}
/// tip
@@ -194,7 +188,7 @@ You can return *enum members* from your *path operation*, even nested in a JSON
They will be converted to their corresponding values (strings in this case) before returning them to the client:
-{* ../../docs_src/path_params/tutorial005.py hl[18,21,23] *}
+{* ../../docs_src/path_params/tutorial005_py39.py hl[18,21,23] *}
In your client you will get a JSON response like:
@@ -233,7 +227,7 @@ In this case, the name of the parameter is `file_path`, and the last part, `:pat
So, you can use it with:
-{* ../../docs_src/path_params/tutorial004.py hl[6] *}
+{* ../../docs_src/path_params/tutorial004_py39.py hl[6] *}
/// tip
diff --git a/docs/en/docs/tutorial/query-params-str-validations.md b/docs/en/docs/tutorial/query-params-str-validations.md
index adf08a9249..4b8cc9d297 100644
--- a/docs/en/docs/tutorial/query-params-str-validations.md
+++ b/docs/en/docs/tutorial/query-params-str-validations.md
@@ -55,7 +55,7 @@ q: str | None = None
////
-//// tab | Python 3.8+
+//// tab | Python 3.9+
```Python
q: Union[str, None] = None
@@ -73,7 +73,7 @@ q: Annotated[str | None] = None
////
-//// tab | Python 3.8+
+//// tab | Python 3.9+
```Python
q: Annotated[Union[str, None]] = None
@@ -206,20 +206,6 @@ If you feel lost with all these **"regular expression"** ideas, don't worry. The
Now you know that whenever you need them you can use them in **FastAPI**.
-### Pydantic v1 `regex` instead of `pattern` { #pydantic-v1-regex-instead-of-pattern }
-
-Before Pydantic version 2 and before FastAPI 0.100.0, the parameter was called `regex` instead of `pattern`, but it's now deprecated.
-
-You could still see some code using it:
-
-//// tab | Pydantic v1
-
-{* ../../docs_src/query_params_str_validations/tutorial004_regex_an_py310.py hl[11] *}
-
-////
-
-But know that this is deprecated and it should be updated to use the new parameter `pattern`. 🤓
-
## Default values { #default-values }
You can, of course, use default values other than `None`.
diff --git a/docs/en/docs/tutorial/query-params.md b/docs/en/docs/tutorial/query-params.md
index 2323b83c7c..3c9c225fb0 100644
--- a/docs/en/docs/tutorial/query-params.md
+++ b/docs/en/docs/tutorial/query-params.md
@@ -2,7 +2,7 @@
When you declare other function parameters that are not part of the path parameters, they are automatically interpreted as "query" parameters.
-{* ../../docs_src/query_params/tutorial001.py hl[9] *}
+{* ../../docs_src/query_params/tutorial001_py39.py hl[9] *}
The query is the set of key-value pairs that go after the `?` in a URL, separated by `&` characters.
@@ -128,7 +128,7 @@ If you don't want to add a specific value but just make it optional, set the def
But when you want to make a query parameter required, you can just not declare any default value:
-{* ../../docs_src/query_params/tutorial005.py hl[6:7] *}
+{* ../../docs_src/query_params/tutorial005_py39.py hl[6:7] *}
Here the query parameter `needy` is a required query parameter of type `str`.
diff --git a/docs/en/docs/tutorial/response-model.md b/docs/en/docs/tutorial/response-model.md
index 5090dbcdfd..b287cdf50a 100644
--- a/docs/en/docs/tutorial/response-model.md
+++ b/docs/en/docs/tutorial/response-model.md
@@ -183,7 +183,7 @@ There might be cases where you return something that is not a valid Pydantic fie
The most common case would be [returning a Response directly as explained later in the advanced docs](../advanced/response-directly.md){.internal-link target=_blank}.
-{* ../../docs_src/response_model/tutorial003_02.py hl[8,10:11] *}
+{* ../../docs_src/response_model/tutorial003_02_py39.py hl[8,10:11] *}
This simple case is handled automatically by FastAPI because the return type annotation is the class (or a subclass of) `Response`.
@@ -193,7 +193,7 @@ And tools will also be happy because both `RedirectResponse` and `JSONResponse`
You can also use a subclass of `Response` in the type annotation:
-{* ../../docs_src/response_model/tutorial003_03.py hl[8:9] *}
+{* ../../docs_src/response_model/tutorial003_03_py39.py hl[8:9] *}
This will also work because `RedirectResponse` is a subclass of `Response`, and FastAPI will automatically handle this simple case.
@@ -252,20 +252,6 @@ So, if you send a request to that *path operation* for the item with ID `foo`, t
/// info
-In Pydantic v1 the method was called `.dict()`, it was deprecated (but still supported) in Pydantic v2, and renamed to `.model_dump()`.
-
-The examples here use `.dict()` for compatibility with Pydantic v1, but you should use `.model_dump()` instead if you can use Pydantic v2.
-
-///
-
-/// info
-
-FastAPI uses Pydantic model's `.dict()` with its `exclude_unset` parameter to achieve this.
-
-///
-
-/// info
-
You can also use:
* `response_model_exclude_defaults=True`
diff --git a/docs/en/docs/tutorial/response-status-code.md b/docs/en/docs/tutorial/response-status-code.md
index a2d9757b28..6389592486 100644
--- a/docs/en/docs/tutorial/response-status-code.md
+++ b/docs/en/docs/tutorial/response-status-code.md
@@ -8,7 +8,7 @@ The same way you can specify a response model, you can also declare the HTTP sta
* `@app.delete()`
* etc.
-{* ../../docs_src/response_status_code/tutorial001.py hl[6] *}
+{* ../../docs_src/response_status_code/tutorial001_py39.py hl[6] *}
/// note
@@ -74,7 +74,7 @@ To know more about each status code and which code is for what, check the Pydantic's docs: Configuration.
+You can use the attribute `model_config` that takes a `dict` as described in Pydantic's docs: Configuration.
You can set `"json_schema_extra"` with a `dict` containing any additional data you would like to show up in the generated JSON Schema, including `examples`.
-////
-
-//// tab | Pydantic v1
-
-In Pydantic version 1, you would use an internal class `Config` and `schema_extra`, as described in Pydantic's docs: Schema customization.
-
-You can set `schema_extra` with a `dict` containing any additional data you would like to show up in the generated JSON Schema, including `examples`.
-
-////
-
/// tip
You could use the same technique to extend the JSON Schema and add your own custom extra info.
diff --git a/docs/en/docs/tutorial/static-files.md b/docs/en/docs/tutorial/static-files.md
index 66b934d4f6..8cf5a5a8ae 100644
--- a/docs/en/docs/tutorial/static-files.md
+++ b/docs/en/docs/tutorial/static-files.md
@@ -7,7 +7,7 @@ You can serve static files automatically from a directory using `StaticFiles`.
* Import `StaticFiles`.
* "Mount" a `StaticFiles()` instance in a specific path.
-{* ../../docs_src/static_files/tutorial001.py hl[2,6] *}
+{* ../../docs_src/static_files/tutorial001_py39.py hl[2,6] *}
/// note | Technical Details
diff --git a/docs/en/docs/tutorial/testing.md b/docs/en/docs/tutorial/testing.md
index c6a0e5b7d5..f61e62ac54 100644
--- a/docs/en/docs/tutorial/testing.md
+++ b/docs/en/docs/tutorial/testing.md
@@ -30,7 +30,7 @@ Use the `TestClient` object the same way as you do with `httpx`.
Write simple `assert` statements with the standard Python expressions that you need to check (again, standard `pytest`).
-{* ../../docs_src/app_testing/tutorial001.py hl[2,12,15:18] *}
+{* ../../docs_src/app_testing/tutorial001_py39.py hl[2,12,15:18] *}
/// tip
@@ -76,7 +76,7 @@ Let's say you have a file structure as described in [Bigger Applications](bigger
In the file `main.py` you have your **FastAPI** app:
-{* ../../docs_src/app_testing/main.py *}
+{* ../../docs_src/app_testing/app_a_py39/main.py *}
### Testing file { #testing-file }
@@ -92,7 +92,7 @@ Then you could have a file `test_main.py` with your tests. It could live on the
Because this file is in the same package, you can use relative imports to import the object `app` from the `main` module (`main.py`):
-{* ../../docs_src/app_testing/test_main.py hl[3] *}
+{* ../../docs_src/app_testing/app_a_py39/test_main.py hl[3] *}
...and have the code for the tests just like before.
diff --git a/docs/es/docs/advanced/additional-responses.md b/docs/es/docs/advanced/additional-responses.md
index 08f0a080b5..d0baa97a45 100644
--- a/docs/es/docs/advanced/additional-responses.md
+++ b/docs/es/docs/advanced/additional-responses.md
@@ -26,7 +26,7 @@ Cada uno de esos `dict`s de response puede tener una clave `model`, conteniendo
Por ejemplo, para declarar otro response con un código de estado `404` y un modelo Pydantic `Message`, puedes escribir:
-{* ../../docs_src/additional_responses/tutorial001.py hl[18,22] *}
+{* ../../docs_src/additional_responses/tutorial001_py39.py hl[18,22] *}
/// note | Nota
@@ -203,7 +203,7 @@ Por ejemplo, puedes declarar un response con un código de estado `404` que usa
Y un response con un código de estado `200` que usa tu `response_model`, pero incluye un `example` personalizado:
-{* ../../docs_src/additional_responses/tutorial003.py hl[20:31] *}
+{* ../../docs_src/additional_responses/tutorial003_py39.py hl[20:31] *}
Todo se combinará e incluirá en tu OpenAPI, y se mostrará en la documentación de la API:
diff --git a/docs/es/docs/advanced/async-tests.md b/docs/es/docs/advanced/async-tests.md
index 3a663d50ea..4627e9bd18 100644
--- a/docs/es/docs/advanced/async-tests.md
+++ b/docs/es/docs/advanced/async-tests.md
@@ -32,11 +32,11 @@ Para un ejemplo simple, consideremos una estructura de archivos similar a la des
El archivo `main.py` tendría:
-{* ../../docs_src/async_tests/main.py *}
+{* ../../docs_src/async_tests/app_a_py39/main.py *}
El archivo `test_main.py` tendría los tests para `main.py`, podría verse así ahora:
-{* ../../docs_src/async_tests/test_main.py *}
+{* ../../docs_src/async_tests/app_a_py39/test_main.py *}
## Ejecútalo { #run-it }
@@ -56,7 +56,7 @@ $ pytest
El marcador `@pytest.mark.anyio` le dice a pytest que esta función de test debe ser llamada asíncronamente:
-{* ../../docs_src/async_tests/test_main.py hl[7] *}
+{* ../../docs_src/async_tests/app_a_py39/test_main.py hl[7] *}
/// tip | Consejo
@@ -66,7 +66,7 @@ Nota que la función de test ahora es `async def` en lugar de solo `def` como an
Luego podemos crear un `AsyncClient` con la app y enviar requests asíncronos a ella, usando `await`.
-{* ../../docs_src/async_tests/test_main.py hl[9:12] *}
+{* ../../docs_src/async_tests/app_a_py39/test_main.py hl[9:12] *}
Esto es equivalente a:
diff --git a/docs/es/docs/advanced/behind-a-proxy.md b/docs/es/docs/advanced/behind-a-proxy.md
index 407a35d2dd..f81c16ee81 100644
--- a/docs/es/docs/advanced/behind-a-proxy.md
+++ b/docs/es/docs/advanced/behind-a-proxy.md
@@ -44,7 +44,7 @@ $ fastapi run --forwarded-allow-ips="*"
Por ejemplo, digamos que defines una *path operation* `/items/`:
-{* ../../docs_src/behind_a_proxy/tutorial001_01.py hl[6] *}
+{* ../../docs_src/behind_a_proxy/tutorial001_01_py39.py hl[6] *}
Si el cliente intenta ir a `/items`, por defecto, sería redirigido a `/items/`.
@@ -115,7 +115,7 @@ En este caso, el path original `/app` realmente sería servido en `/api/v1/app`.
Aunque todo tu código esté escrito asumiendo que solo existe `/app`.
-{* ../../docs_src/behind_a_proxy/tutorial001.py hl[6] *}
+{* ../../docs_src/behind_a_proxy/tutorial001_py39.py hl[6] *}
Y el proxy estaría **"eliminando"** el **prefijo del path** sobre la marcha antes de transmitir el request al servidor de aplicaciones (probablemente Uvicorn a través de FastAPI CLI), manteniendo a tu aplicación convencida de que está siendo servida en `/app`, así que no tienes que actualizar todo tu código para incluir el prefijo `/api/v1`.
@@ -193,7 +193,7 @@ Puedes obtener el `root_path` actual utilizado por tu aplicación para cada requ
Aquí lo estamos incluyendo en el mensaje solo con fines de demostración.
-{* ../../docs_src/behind_a_proxy/tutorial001.py hl[8] *}
+{* ../../docs_src/behind_a_proxy/tutorial001_py39.py hl[8] *}
Luego, si inicias Uvicorn con:
@@ -220,7 +220,7 @@ El response sería algo como:
Alternativamente, si no tienes una forma de proporcionar una opción de línea de comandos como `--root-path` o su equivalente, puedes configurar el parámetro `root_path` al crear tu app de FastAPI:
-{* ../../docs_src/behind_a_proxy/tutorial002.py hl[3] *}
+{* ../../docs_src/behind_a_proxy/tutorial002_py39.py hl[3] *}
Pasar el `root_path` a `FastAPI` sería el equivalente a pasar la opción de línea de comandos `--root-path` a Uvicorn o Hypercorn.
@@ -400,7 +400,7 @@ Si pasas una lista personalizada de `servers` y hay un `root_path` (porque tu AP
Por ejemplo:
-{* ../../docs_src/behind_a_proxy/tutorial003.py hl[4:7] *}
+{* ../../docs_src/behind_a_proxy/tutorial003_py39.py hl[4:7] *}
Generará un esquema de OpenAPI como:
@@ -455,7 +455,7 @@ Si no especificas el parámetro `servers` y `root_path` es igual a `/`, la propi
Si no quieres que **FastAPI** incluya un server automático usando el `root_path`, puedes usar el parámetro `root_path_in_servers=False`:
-{* ../../docs_src/behind_a_proxy/tutorial004.py hl[9] *}
+{* ../../docs_src/behind_a_proxy/tutorial004_py39.py hl[9] *}
y entonces no lo incluirá en el esquema de OpenAPI.
diff --git a/docs/es/docs/advanced/custom-response.md b/docs/es/docs/advanced/custom-response.md
index ace26b3e04..0884c41a74 100644
--- a/docs/es/docs/advanced/custom-response.md
+++ b/docs/es/docs/advanced/custom-response.md
@@ -30,7 +30,7 @@ Esto se debe a que, por defecto, FastAPI inspeccionará cada elemento dentro y s
Pero si estás seguro de que el contenido que estás devolviendo es **serializable con JSON**, puedes pasarlo directamente a la clase de response y evitar la sobrecarga extra que FastAPI tendría al pasar tu contenido de retorno a través de `jsonable_encoder` antes de pasarlo a la clase de response.
-{* ../../docs_src/custom_response/tutorial001b.py hl[2,7] *}
+{* ../../docs_src/custom_response/tutorial001b_py39.py hl[2,7] *}
/// info | Información
@@ -55,7 +55,7 @@ Para devolver un response con HTML directamente desde **FastAPI**, usa `HTMLResp
* Importa `HTMLResponse`.
* Pasa `HTMLResponse` como parámetro `response_class` de tu *path operation decorator*.
-{* ../../docs_src/custom_response/tutorial002.py hl[2,7] *}
+{* ../../docs_src/custom_response/tutorial002_py39.py hl[2,7] *}
/// info | Información
@@ -73,7 +73,7 @@ Como se ve en [Devolver una Response directamente](response-directly.md){.intern
El mismo ejemplo de arriba, devolviendo una `HTMLResponse`, podría verse así:
-{* ../../docs_src/custom_response/tutorial003.py hl[2,7,19] *}
+{* ../../docs_src/custom_response/tutorial003_py39.py hl[2,7,19] *}
/// warning | Advertencia
@@ -97,7 +97,7 @@ El `response_class` solo se usará para documentar el OpenAPI *path operation*,
Por ejemplo, podría ser algo así:
-{* ../../docs_src/custom_response/tutorial004.py hl[7,21,23] *}
+{* ../../docs_src/custom_response/tutorial004_py39.py hl[7,21,23] *}
En este ejemplo, la función `generate_html_response()` ya genera y devuelve una `Response` en lugar de devolver el HTML en un `str`.
@@ -136,7 +136,7 @@ Acepta los siguientes parámetros:
FastAPI (de hecho Starlette) incluirá automáticamente un header Content-Length. También incluirá un header Content-Type, basado en el `media_type` y añadiendo un conjunto de caracteres para tipos de texto.
-{* ../../docs_src/response_directly/tutorial002.py hl[1,18] *}
+{* ../../docs_src/response_directly/tutorial002_py39.py hl[1,18] *}
### `HTMLResponse` { #htmlresponse }
@@ -146,7 +146,7 @@ Toma algún texto o bytes y devuelve un response HTML, como leíste arriba.
Toma algún texto o bytes y devuelve un response de texto plano.
-{* ../../docs_src/custom_response/tutorial005.py hl[2,7,9] *}
+{* ../../docs_src/custom_response/tutorial005_py39.py hl[2,7,9] *}
### `JSONResponse` { #jsonresponse }
@@ -180,7 +180,7 @@ Esto requiere instalar `ujson`, por ejemplo, con `pip install ujson`.
///
-{* ../../docs_src/custom_response/tutorial001.py hl[2,7] *}
+{* ../../docs_src/custom_response/tutorial001_py39.py hl[2,7] *}
/// tip | Consejo
@@ -194,13 +194,13 @@ Devuelve una redirección HTTP. Usa un código de estado 307 (Redirección Tempo
Puedes devolver un `RedirectResponse` directamente:
-{* ../../docs_src/custom_response/tutorial006.py hl[2,9] *}
+{* ../../docs_src/custom_response/tutorial006_py39.py hl[2,9] *}
---
O puedes usarlo en el parámetro `response_class`:
-{* ../../docs_src/custom_response/tutorial006b.py hl[2,7,9] *}
+{* ../../docs_src/custom_response/tutorial006b_py39.py hl[2,7,9] *}
Si haces eso, entonces puedes devolver la URL directamente desde tu *path operation function*.
@@ -210,13 +210,13 @@ En este caso, el `status_code` utilizado será el por defecto para `RedirectResp
También puedes usar el parámetro `status_code` combinado con el parámetro `response_class`:
-{* ../../docs_src/custom_response/tutorial006c.py hl[2,7,9] *}
+{* ../../docs_src/custom_response/tutorial006c_py39.py hl[2,7,9] *}
### `StreamingResponse` { #streamingresponse }
Toma un generador `async` o un generador/iterador normal y transmite el cuerpo del response.
-{* ../../docs_src/custom_response/tutorial007.py hl[2,14] *}
+{* ../../docs_src/custom_response/tutorial007_py39.py hl[2,14] *}
#### Usando `StreamingResponse` con objetos similares a archivos { #using-streamingresponse-with-file-like-objects }
@@ -226,7 +226,7 @@ De esa manera, no tienes que leerlo todo primero en memoria, y puedes pasar esa
Esto incluye muchos paquetes para interactuar con almacenamiento en la nube, procesamiento de video y otros.
-{* ../../docs_src/custom_response/tutorial008.py hl[2,10:12,14] *}
+{* ../../docs_src/custom_response/tutorial008_py39.py hl[2,10:12,14] *}
1. Esta es la función generadora. Es una "función generadora" porque contiene declaraciones `yield` dentro.
2. Al usar un bloque `with`, nos aseguramos de que el objeto similar a un archivo se cierre después de que la función generadora termine. Así, después de que termina de enviar el response.
@@ -255,11 +255,11 @@ Toma un conjunto diferente de argumentos para crear un instance que los otros ti
Los responses de archivos incluirán los headers apropiados `Content-Length`, `Last-Modified` y `ETag`.
-{* ../../docs_src/custom_response/tutorial009.py hl[2,10] *}
+{* ../../docs_src/custom_response/tutorial009_py39.py hl[2,10] *}
También puedes usar el parámetro `response_class`:
-{* ../../docs_src/custom_response/tutorial009b.py hl[2,8,10] *}
+{* ../../docs_src/custom_response/tutorial009b_py39.py hl[2,8,10] *}
En este caso, puedes devolver la path del archivo directamente desde tu *path operation* function.
@@ -273,7 +273,7 @@ Digamos que quieres que devuelva JSON con sangría y formato, por lo que quieres
Podrías crear un `CustomORJSONResponse`. Lo principal que tienes que hacer es crear un método `Response.render(content)` que devuelva el contenido como `bytes`:
-{* ../../docs_src/custom_response/tutorial009c.py hl[9:14,17] *}
+{* ../../docs_src/custom_response/tutorial009c_py39.py hl[9:14,17] *}
Ahora en lugar de devolver:
@@ -299,7 +299,7 @@ El parámetro que define esto es `default_response_class`.
En el ejemplo a continuación, **FastAPI** usará `ORJSONResponse` por defecto, en todas las *path operations*, en lugar de `JSONResponse`.
-{* ../../docs_src/custom_response/tutorial010.py hl[2,4] *}
+{* ../../docs_src/custom_response/tutorial010_py39.py hl[2,4] *}
/// tip | Consejo
diff --git a/docs/es/docs/advanced/dataclasses.md b/docs/es/docs/advanced/dataclasses.md
index 8d96171c7e..3a07482ad1 100644
--- a/docs/es/docs/advanced/dataclasses.md
+++ b/docs/es/docs/advanced/dataclasses.md
@@ -4,7 +4,7 @@ FastAPI está construido sobre **Pydantic**, y te he estado mostrando cómo usar
Pero FastAPI también soporta el uso de `dataclasses` de la misma manera:
-{* ../../docs_src/dataclasses/tutorial001_py310.py hl[1,6:11,18:19] *}
+{* ../../docs_src/dataclasses_/tutorial001_py310.py hl[1,6:11,18:19] *}
Esto sigue siendo soportado gracias a **Pydantic**, ya que tiene soporte interno para `dataclasses`.
@@ -32,7 +32,7 @@ Pero si tienes un montón de dataclasses por ahí, este es un buen truco para us
También puedes usar `dataclasses` en el parámetro `response_model`:
-{* ../../docs_src/dataclasses/tutorial002_py310.py hl[1,6:12,18] *}
+{* ../../docs_src/dataclasses_/tutorial002_py310.py hl[1,6:12,18] *}
El dataclass será automáticamente convertido a un dataclass de Pydantic.
@@ -48,7 +48,7 @@ En algunos casos, todavía podrías tener que usar la versión de `dataclasses`
En ese caso, simplemente puedes intercambiar los `dataclasses` estándar con `pydantic.dataclasses`, que es un reemplazo directo:
-{* ../../docs_src/dataclasses/tutorial003_py310.py hl[1,4,7:10,13:16,22:24,27] *}
+{* ../../docs_src/dataclasses_/tutorial003_py310.py hl[1,4,7:10,13:16,22:24,27] *}
1. Todavía importamos `field` de los `dataclasses` estándar.
diff --git a/docs/es/docs/advanced/events.md b/docs/es/docs/advanced/events.md
index bf06e715a7..c2002a6f53 100644
--- a/docs/es/docs/advanced/events.md
+++ b/docs/es/docs/advanced/events.md
@@ -30,7 +30,7 @@ Comencemos con un ejemplo y luego veámoslo en detalle.
Creamos una función asíncrona `lifespan()` con `yield` así:
-{* ../../docs_src/events/tutorial003.py hl[16,19] *}
+{* ../../docs_src/events/tutorial003_py39.py hl[16,19] *}
Aquí estamos simulando la operación costosa de *startup* de cargar el modelo poniendo la función del (falso) modelo en el diccionario con modelos de machine learning antes del `yield`. Este código será ejecutado **antes** de que la aplicación **comience a tomar requests**, durante el *startup*.
@@ -48,7 +48,7 @@ Quizás necesites iniciar una nueva versión, o simplemente te cansaste de ejecu
Lo primero que hay que notar es que estamos definiendo una función asíncrona con `yield`. Esto es muy similar a las Dependencias con `yield`.
-{* ../../docs_src/events/tutorial003.py hl[14:19] *}
+{* ../../docs_src/events/tutorial003_py39.py hl[14:19] *}
La primera parte de la función, antes del `yield`, será ejecutada **antes** de que la aplicación comience.
@@ -60,7 +60,7 @@ Si revisas, la función está decorada con un `@asynccontextmanager`.
Eso convierte a la función en algo llamado un "**async context manager**".
-{* ../../docs_src/events/tutorial003.py hl[1,13] *}
+{* ../../docs_src/events/tutorial003_py39.py hl[1,13] *}
Un **context manager** en Python es algo que puedes usar en un statement `with`, por ejemplo, `open()` puede ser usado como un context manager:
@@ -82,7 +82,7 @@ En nuestro ejemplo de código arriba, no lo usamos directamente, pero se lo pasa
El parámetro `lifespan` de la app de `FastAPI` toma un **async context manager**, por lo que podemos pasar nuestro nuevo `lifespan` async context manager a él.
-{* ../../docs_src/events/tutorial003.py hl[22] *}
+{* ../../docs_src/events/tutorial003_py39.py hl[22] *}
## Eventos Alternativos (obsoleto) { #alternative-events-deprecated }
@@ -104,7 +104,7 @@ Estas funciones pueden ser declaradas con `async def` o `def` normal.
Para añadir una función que debería ejecutarse antes de que la aplicación inicie, declárala con el evento `"startup"`:
-{* ../../docs_src/events/tutorial001.py hl[8] *}
+{* ../../docs_src/events/tutorial001_py39.py hl[8] *}
En este caso, la función manejadora del evento `startup` inicializará los ítems de la "base de datos" (solo un `dict`) con algunos valores.
@@ -116,7 +116,7 @@ Y tu aplicación no comenzará a recibir requests hasta que todos los manejadore
Para añadir una función que debería ejecutarse cuando la aplicación se esté cerrando, declárala con el evento `"shutdown"`:
-{* ../../docs_src/events/tutorial002.py hl[6] *}
+{* ../../docs_src/events/tutorial002_py39.py hl[6] *}
Aquí, la función manejadora del evento `shutdown` escribirá una línea de texto `"Application shutdown"` a un archivo `log.txt`.
diff --git a/docs/es/docs/advanced/generate-clients.md b/docs/es/docs/advanced/generate-clients.md
index 861b58b508..daf6cefed3 100644
--- a/docs/es/docs/advanced/generate-clients.md
+++ b/docs/es/docs/advanced/generate-clients.md
@@ -167,7 +167,7 @@ Pero para el cliente generado podríamos **modificar** los operation IDs de Open
Podríamos descargar el JSON de OpenAPI a un archivo `openapi.json` y luego podríamos **remover ese tag prefijado** con un script como este:
-{* ../../docs_src/generate_clients/tutorial004.py *}
+{* ../../docs_src/generate_clients/tutorial004_py39.py *}
//// tab | Node.js
diff --git a/docs/es/docs/advanced/middleware.md b/docs/es/docs/advanced/middleware.md
index 4783612a4b..7eead8ae14 100644
--- a/docs/es/docs/advanced/middleware.md
+++ b/docs/es/docs/advanced/middleware.md
@@ -57,13 +57,13 @@ Impone que todas las requests entrantes deben ser `https` o `wss`.
Cualquier request entrante a `http` o `ws` será redirigida al esquema seguro.
-{* ../../docs_src/advanced_middleware/tutorial001.py hl[2,6] *}
+{* ../../docs_src/advanced_middleware/tutorial001_py39.py hl[2,6] *}
## `TrustedHostMiddleware` { #trustedhostmiddleware }
Impone que todas las requests entrantes tengan correctamente configurado el header `Host`, para proteger contra ataques de HTTP Host Header.
-{* ../../docs_src/advanced_middleware/tutorial002.py hl[2,6:8] *}
+{* ../../docs_src/advanced_middleware/tutorial002_py39.py hl[2,6:8] *}
Se soportan los siguientes argumentos:
@@ -78,7 +78,7 @@ Maneja responses GZip para cualquier request que incluya `"gzip"` en el header `
El middleware manejará tanto responses estándar como en streaming.
-{* ../../docs_src/advanced_middleware/tutorial003.py hl[2,6] *}
+{* ../../docs_src/advanced_middleware/tutorial003_py39.py hl[2,6] *}
Se soportan los siguientes argumentos:
diff --git a/docs/es/docs/advanced/openapi-webhooks.md b/docs/es/docs/advanced/openapi-webhooks.md
index 2dfa74b210..c358a14008 100644
--- a/docs/es/docs/advanced/openapi-webhooks.md
+++ b/docs/es/docs/advanced/openapi-webhooks.md
@@ -32,7 +32,7 @@ Los webhooks están disponibles en OpenAPI 3.1.0 y superiores, soportados por Fa
Cuando creas una aplicación de **FastAPI**, hay un atributo `webhooks` que puedes usar para definir *webhooks*, de la misma manera que definirías *path operations*, por ejemplo con `@app.webhooks.post()`.
-{* ../../docs_src/openapi_webhooks/tutorial001.py hl[9:13,36:53] *}
+{* ../../docs_src/openapi_webhooks/tutorial001_py39.py hl[9:13,36:53] *}
Los webhooks que defines terminarán en el esquema de **OpenAPI** y en la interfaz automática de **documentación**.
diff --git a/docs/es/docs/advanced/path-operation-advanced-configuration.md b/docs/es/docs/advanced/path-operation-advanced-configuration.md
index 98965ee9e2..396159868b 100644
--- a/docs/es/docs/advanced/path-operation-advanced-configuration.md
+++ b/docs/es/docs/advanced/path-operation-advanced-configuration.md
@@ -12,7 +12,7 @@ Puedes establecer el `operationId` de OpenAPI para ser usado en tu *path operati
Tienes que asegurarte de que sea único para cada operación.
-{* ../../docs_src/path_operation_advanced_configuration/tutorial001.py hl[6] *}
+{* ../../docs_src/path_operation_advanced_configuration/tutorial001_py39.py hl[6] *}
### Usar el nombre de la *path operation function* como el operationId { #using-the-path-operation-function-name-as-the-operationid }
@@ -20,7 +20,7 @@ Si quieres usar los nombres de las funciones de tus APIs como `operationId`s, pu
Deberías hacerlo después de agregar todas tus *path operations*.
-{* ../../docs_src/path_operation_advanced_configuration/tutorial002.py hl[2, 12:21, 24] *}
+{* ../../docs_src/path_operation_advanced_configuration/tutorial002_py39.py hl[2, 12:21, 24] *}
/// tip | Consejo
@@ -40,7 +40,7 @@ Incluso si están en diferentes módulos (archivos de Python).
Para excluir una *path operation* del esquema OpenAPI generado (y por lo tanto, de los sistemas de documentación automática), utiliza el parámetro `include_in_schema` y configúralo en `False`:
-{* ../../docs_src/path_operation_advanced_configuration/tutorial003.py hl[6] *}
+{* ../../docs_src/path_operation_advanced_configuration/tutorial003_py39.py hl[6] *}
## Descripción avanzada desde el docstring { #advanced-description-from-docstring }
@@ -92,7 +92,7 @@ Puedes extender el esquema de OpenAPI para una *path operation* usando el parám
Este `openapi_extra` puede ser útil, por ejemplo, para declarar [Extensiones de OpenAPI](https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.3.md#specificationExtensions):
-{* ../../docs_src/path_operation_advanced_configuration/tutorial005.py hl[6] *}
+{* ../../docs_src/path_operation_advanced_configuration/tutorial005_py39.py hl[6] *}
Si abres la documentación automática de la API, tu extensión aparecerá en la parte inferior de la *path operation* específica.
@@ -139,7 +139,7 @@ Por ejemplo, podrías decidir leer y validar el request con tu propio código, s
Podrías hacer eso con `openapi_extra`:
-{* ../../docs_src/path_operation_advanced_configuration/tutorial006.py hl[19:36, 39:40] *}
+{* ../../docs_src/path_operation_advanced_configuration/tutorial006_py39.py hl[19:36, 39:40] *}
En este ejemplo, no declaramos ningún modelo Pydantic. De hecho, el cuerpo del request ni siquiera se parse como JSON, se lee directamente como `bytes`, y la función `magic_data_reader()` sería la encargada de parsearlo de alguna manera.
diff --git a/docs/es/docs/advanced/response-change-status-code.md b/docs/es/docs/advanced/response-change-status-code.md
index 067267750b..940f1dd3ff 100644
--- a/docs/es/docs/advanced/response-change-status-code.md
+++ b/docs/es/docs/advanced/response-change-status-code.md
@@ -20,7 +20,7 @@ Puedes declarar un parámetro de tipo `Response` en tu *path operation function*
Y luego puedes establecer el `status_code` en ese objeto de response *temporal*.
-{* ../../docs_src/response_change_status_code/tutorial001.py hl[1,9,12] *}
+{* ../../docs_src/response_change_status_code/tutorial001_py39.py hl[1,9,12] *}
Y luego puedes devolver cualquier objeto que necesites, como lo harías normalmente (un `dict`, un modelo de base de datos, etc.).
diff --git a/docs/es/docs/advanced/response-cookies.md b/docs/es/docs/advanced/response-cookies.md
index ce2ff0281d..550a5d97a7 100644
--- a/docs/es/docs/advanced/response-cookies.md
+++ b/docs/es/docs/advanced/response-cookies.md
@@ -6,7 +6,7 @@ Puedes declarar un parámetro de tipo `Response` en tu *path operation function*
Y luego puedes establecer cookies en ese objeto de response *temporal*.
-{* ../../docs_src/response_cookies/tutorial002.py hl[1, 8:9] *}
+{* ../../docs_src/response_cookies/tutorial002_py39.py hl[1, 8:9] *}
Y entonces puedes devolver cualquier objeto que necesites, como normalmente lo harías (un `dict`, un modelo de base de datos, etc).
@@ -24,7 +24,7 @@ Para hacer eso, puedes crear un response como se describe en [Devolver un Respon
Luego establece Cookies en ella, y luego devuélvela:
-{* ../../docs_src/response_cookies/tutorial001.py hl[10:12] *}
+{* ../../docs_src/response_cookies/tutorial001_py39.py hl[10:12] *}
/// tip | Consejo
diff --git a/docs/es/docs/advanced/response-directly.md b/docs/es/docs/advanced/response-directly.md
index 96b30b915c..2da4e84e70 100644
--- a/docs/es/docs/advanced/response-directly.md
+++ b/docs/es/docs/advanced/response-directly.md
@@ -54,7 +54,7 @@ Digamos que quieres devolver un response en documentación de Strawberry.
diff --git a/docs/es/docs/python-types.md b/docs/es/docs/python-types.md
index e51c2352c5..60b50a08ff 100644
--- a/docs/es/docs/python-types.md
+++ b/docs/es/docs/python-types.md
@@ -22,7 +22,7 @@ Si eres un experto en Python, y ya sabes todo sobre las anotaciones de tipos, sa
Comencemos con un ejemplo simple:
-{* ../../docs_src/python_types/tutorial001.py *}
+{* ../../docs_src/python_types/tutorial001_py39.py *}
Llamar a este programa genera:
@@ -36,7 +36,7 @@ La función hace lo siguiente:
* Convierte la primera letra de cada uno a mayúsculas con `title()`.
* Concatena ambos con un espacio en el medio.
-{* ../../docs_src/python_types/tutorial001.py hl[2] *}
+{* ../../docs_src/python_types/tutorial001_py39.py hl[2] *}
### Edítalo { #edit-it }
@@ -78,7 +78,7 @@ Eso es todo.
Esas son las "anotaciones de tipos":
-{* ../../docs_src/python_types/tutorial002.py hl[1] *}
+{* ../../docs_src/python_types/tutorial002_py39.py hl[1] *}
Eso no es lo mismo que declarar valores predeterminados como sería con:
@@ -106,7 +106,7 @@ Con eso, puedes desplazarte, viendo las opciones, hasta que encuentres la que "t
Revisa esta función, ya tiene anotaciones de tipos:
-{* ../../docs_src/python_types/tutorial003.py hl[1] *}
+{* ../../docs_src/python_types/tutorial003_py39.py hl[1] *}
Porque el editor conoce los tipos de las variables, no solo obtienes autocompletado, también obtienes chequeo de errores:
@@ -114,7 +114,7 @@ Porque el editor conoce los tipos de las variables, no solo obtienes autocomplet
Ahora sabes que debes corregirlo, convertir `age` a un string con `str(age)`:
-{* ../../docs_src/python_types/tutorial004.py hl[2] *}
+{* ../../docs_src/python_types/tutorial004_py39.py hl[2] *}
## Declaración de tipos { #declaring-types }
@@ -133,7 +133,7 @@ Puedes usar, por ejemplo:
* `bool`
* `bytes`
-{* ../../docs_src/python_types/tutorial005.py hl[1] *}
+{* ../../docs_src/python_types/tutorial005_py39.py hl[1] *}
### Tipos genéricos con parámetros de tipo { #generic-types-with-type-parameters }
@@ -161,56 +161,24 @@ Si puedes usar las **últimas versiones de Python**, utiliza los ejemplos para l
Por ejemplo, vamos a definir una variable para ser una `list` de `str`.
-//// tab | Python 3.9+
-
Declara la variable, con la misma sintaxis de dos puntos (`:`).
Como tipo, pon `list`.
Como la lista es un tipo que contiene algunos tipos internos, los pones entre corchetes:
-```Python hl_lines="1"
-{!> ../../docs_src/python_types/tutorial006_py39.py!}
-```
-
-////
-
-//// tab | Python 3.8+
-
-De `typing`, importa `List` (con una `L` mayúscula):
-
-```Python hl_lines="1"
-{!> ../../docs_src/python_types/tutorial006.py!}
-```
-
-Declara la variable, con la misma sintaxis de dos puntos (`:`).
-
-Como tipo, pon el `List` que importaste de `typing`.
-
-Como la lista es un tipo que contiene algunos tipos internos, los pones entre corchetes:
-
-```Python hl_lines="4"
-{!> ../../docs_src/python_types/tutorial006.py!}
-```
-
-////
+{* ../../docs_src/python_types/tutorial006_py39.py hl[1] *}
/// info | Información
Esos tipos internos en los corchetes se denominan "parámetros de tipo".
-En este caso, `str` es el parámetro de tipo pasado a `List` (o `list` en Python 3.9 y superior).
+En este caso, `str` es el parámetro de tipo pasado a `list`.
///
Eso significa: "la variable `items` es una `list`, y cada uno de los ítems en esta lista es un `str`".
-/// tip | Consejo
-
-Si usas Python 3.9 o superior, no tienes que importar `List` de `typing`, puedes usar el mismo tipo `list` regular en su lugar.
-
-///
-
Al hacer eso, tu editor puede proporcionar soporte incluso mientras procesa elementos de la lista:
@@ -225,21 +193,7 @@ Y aún así, el editor sabe que es un `str` y proporciona soporte para eso.
Harías lo mismo para declarar `tuple`s y `set`s:
-//// tab | Python 3.9+
-
-```Python hl_lines="1"
-{!> ../../docs_src/python_types/tutorial007_py39.py!}
-```
-
-////
-
-//// tab | Python 3.8+
-
-```Python hl_lines="1 4"
-{!> ../../docs_src/python_types/tutorial007.py!}
-```
-
-////
+{* ../../docs_src/python_types/tutorial007_py39.py hl[1] *}
Esto significa:
@@ -254,21 +208,7 @@ El primer parámetro de tipo es para las claves del `dict`.
El segundo parámetro de tipo es para los valores del `dict`:
-//// tab | Python 3.9+
-
-```Python hl_lines="1"
-{!> ../../docs_src/python_types/tutorial008_py39.py!}
-```
-
-////
-
-//// tab | Python 3.8+
-
-```Python hl_lines="1 4"
-{!> ../../docs_src/python_types/tutorial008.py!}
-```
-
-////
+{* ../../docs_src/python_types/tutorial008_py39.py hl[1] *}
Esto significa:
@@ -292,10 +232,10 @@ En Python 3.10 también hay una **nueva sintaxis** donde puedes poner los posibl
////
-//// tab | Python 3.8+
+//// tab | Python 3.9+
```Python hl_lines="1 4"
-{!> ../../docs_src/python_types/tutorial008b.py!}
+{!> ../../docs_src/python_types/tutorial008b_py39.py!}
```
////
@@ -309,7 +249,7 @@ Puedes declarar que un valor podría tener un tipo, como `str`, pero que tambié
En Python 3.6 y posteriores (incluyendo Python 3.10) puedes declararlo importando y usando `Optional` del módulo `typing`.
```Python hl_lines="1 4"
-{!../../docs_src/python_types/tutorial009.py!}
+{!../../docs_src/python_types/tutorial009_py39.py!}
```
Usar `Optional[str]` en lugar de solo `str` te permitirá al editor ayudarte a detectar errores donde podrías estar asumiendo que un valor siempre es un `str`, cuando en realidad también podría ser `None`.
@@ -326,18 +266,18 @@ Esto también significa que en Python 3.10, puedes usar `Something | None`:
////
-//// tab | Python 3.8+
+//// tab | Python 3.9+
```Python hl_lines="1 4"
-{!> ../../docs_src/python_types/tutorial009.py!}
+{!> ../../docs_src/python_types/tutorial009_py39.py!}
```
////
-//// tab | Python 3.8+ alternativa
+//// tab | Python 3.9+ alternativa
```Python hl_lines="1 4"
-{!> ../../docs_src/python_types/tutorial009b.py!}
+{!> ../../docs_src/python_types/tutorial009b_py39.py!}
```
////
@@ -357,7 +297,7 @@ Se trata solo de las palabras y nombres. Pero esas palabras pueden afectar cómo
Como ejemplo, tomemos esta función:
-{* ../../docs_src/python_types/tutorial009c.py hl[1,4] *}
+{* ../../docs_src/python_types/tutorial009c_py39.py hl[1,4] *}
El parámetro `name` está definido como `Optional[str]`, pero **no es opcional**, no puedes llamar a la función sin el parámetro:
@@ -390,10 +330,10 @@ Puedes usar los mismos tipos integrados como genéricos (con corchetes y tipos d
* `set`
* `dict`
-Y lo mismo que con Python 3.8, desde el módulo `typing`:
+Y, como con versiones anteriores de Python, desde el módulo `typing`:
* `Union`
-* `Optional` (lo mismo que con Python 3.8)
+* `Optional`
* ...y otros.
En Python 3.10, como alternativa a usar los genéricos `Union` y `Optional`, puedes usar la barra vertical (`|`) para declarar uniones de tipos, eso es mucho mejor y más simple.
@@ -409,7 +349,7 @@ Puedes usar los mismos tipos integrados como genéricos (con corchetes y tipos d
* `set`
* `dict`
-Y lo mismo que con Python 3.8, desde el módulo `typing`:
+Y generics desde el módulo `typing`:
* `Union`
* `Optional`
@@ -417,29 +357,17 @@ Y lo mismo que con Python 3.8, desde el módulo `typing`:
////
-//// tab | Python 3.8+
-
-* `List`
-* `Tuple`
-* `Set`
-* `Dict`
-* `Union`
-* `Optional`
-* ...y otros.
-
-////
-
### Clases como tipos { #classes-as-types }
También puedes declarar una clase como el tipo de una variable.
Digamos que tienes una clase `Person`, con un nombre:
-{* ../../docs_src/python_types/tutorial010.py hl[1:3] *}
+{* ../../docs_src/python_types/tutorial010_py39.py hl[1:3] *}
Luego puedes declarar una variable para que sea de tipo `Person`:
-{* ../../docs_src/python_types/tutorial010.py hl[6] *}
+{* ../../docs_src/python_types/tutorial010_py39.py hl[6] *}
Y luego, nuevamente, obtienes todo el soporte del editor:
@@ -463,29 +391,7 @@ Y obtienes todo el soporte del editor con ese objeto resultante.
Un ejemplo de la documentación oficial de Pydantic:
-//// tab | Python 3.10+
-
-```Python
-{!> ../../docs_src/python_types/tutorial011_py310.py!}
-```
-
-////
-
-//// tab | Python 3.9+
-
-```Python
-{!> ../../docs_src/python_types/tutorial011_py39.py!}
-```
-
-////
-
-//// tab | Python 3.8+
-
-```Python
-{!> ../../docs_src/python_types/tutorial011.py!}
-```
-
-////
+{* ../../docs_src/python_types/tutorial011_py310.py *}
/// info | Información
@@ -507,27 +413,9 @@ Pydantic tiene un comportamiento especial cuando utilizas `Optional` o `Union[So
Python también tiene una funcionalidad que permite poner **metadatos adicional** en estas anotaciones de tipos usando `Annotated`.
-//// tab | Python 3.9+
+Desde Python 3.9, `Annotated` es parte de la standard library, así que puedes importarlo desde `typing`.
-En Python 3.9, `Annotated` es parte de la standard library, así que puedes importarlo desde `typing`.
-
-```Python hl_lines="1 4"
-{!> ../../docs_src/python_types/tutorial013_py39.py!}
-```
-
-////
-
-//// tab | Python 3.8+
-
-En versiones por debajo de Python 3.9, importas `Annotated` de `typing_extensions`.
-
-Ya estará instalado con **FastAPI**.
-
-```Python hl_lines="1 4"
-{!> ../../docs_src/python_types/tutorial013.py!}
-```
-
-////
+{* ../../docs_src/python_types/tutorial013_py39.py hl[1,4] *}
Python en sí no hace nada con este `Annotated`. Y para los editores y otras herramientas, el tipo sigue siendo `str`.
diff --git a/docs/es/docs/tutorial/background-tasks.md b/docs/es/docs/tutorial/background-tasks.md
index 8cd0767f8e..cc8a2c9cbe 100644
--- a/docs/es/docs/tutorial/background-tasks.md
+++ b/docs/es/docs/tutorial/background-tasks.md
@@ -15,7 +15,7 @@ Esto incluye, por ejemplo:
Primero, importa `BackgroundTasks` y define un parámetro en tu *path operation function* con una declaración de tipo de `BackgroundTasks`:
-{* ../../docs_src/background_tasks/tutorial001.py hl[1,13] *}
+{* ../../docs_src/background_tasks/tutorial001_py39.py hl[1,13] *}
**FastAPI** creará el objeto de tipo `BackgroundTasks` por ti y lo pasará como ese parámetro.
@@ -31,13 +31,13 @@ En este caso, la función de tarea escribirá en un archivo (simulando el envío
Y como la operación de escritura no usa `async` y `await`, definimos la función con un `def` normal:
-{* ../../docs_src/background_tasks/tutorial001.py hl[6:9] *}
+{* ../../docs_src/background_tasks/tutorial001_py39.py hl[6:9] *}
## Agregar la tarea en segundo plano { #add-the-background-task }
Dentro de tu *path operation function*, pasa tu función de tarea al objeto de *background tasks* con el método `.add_task()`:
-{* ../../docs_src/background_tasks/tutorial001.py hl[14] *}
+{* ../../docs_src/background_tasks/tutorial001_py39.py hl[14] *}
`.add_task()` recibe como argumentos:
diff --git a/docs/es/docs/tutorial/body-nested-models.md b/docs/es/docs/tutorial/body-nested-models.md
index 04f4b39c4a..0dfd6576f1 100644
--- a/docs/es/docs/tutorial/body-nested-models.md
+++ b/docs/es/docs/tutorial/body-nested-models.md
@@ -14,35 +14,15 @@ Esto hará que `tags` sea una lista, aunque no declare el tipo de los elementos
Pero Python tiene una forma específica de declarar listas con tipos internos, o "parámetros de tipo":
-### Importar `List` de typing { #import-typings-list }
-
-En Python 3.9 y superior, puedes usar el `list` estándar para declarar estas anotaciones de tipo como veremos a continuación. 💡
-
-Pero en versiones de Python anteriores a 3.9 (desde 3.6 en adelante), primero necesitas importar `List` del módulo `typing` estándar de Python:
-
-{* ../../docs_src/body_nested_models/tutorial002.py hl[1] *}
-
### Declarar una `list` con un parámetro de tipo { #declare-a-list-with-a-type-parameter }
-Para declarar tipos que tienen parámetros de tipo (tipos internos), como `list`, `dict`, `tuple`:
-
-* Si estás en una versión de Python inferior a 3.9, importa su versión equivalente del módulo `typing`
-* Pasa el/los tipo(s) interno(s) como "parámetros de tipo" usando corchetes: `[` y `]`
-
-En Python 3.9 sería:
+Para declarar tipos que tienen parámetros de tipo (tipos internos), como `list`, `dict`, `tuple`,
+pasa el/los tipo(s) interno(s) como "parámetros de tipo" usando corchetes: `[` y `]`
```Python
my_list: list[str]
```
-En versiones de Python anteriores a 3.9, sería:
-
-```Python
-from typing import List
-
-my_list: List[str]
-```
-
Eso es toda la sintaxis estándar de Python para declaraciones de tipo.
Usa esa misma sintaxis estándar para atributos de modelos con tipos internos.
@@ -178,12 +158,6 @@ Observa cómo `Offer` tiene una lista de `Item`s, que a su vez tienen una lista
Si el valor superior del cuerpo JSON que esperas es un `array` JSON (una `list` en Python), puedes declarar el tipo en el parámetro de la función, al igual que en los modelos Pydantic:
-```Python
-images: List[Image]
-```
-
-o en Python 3.9 y superior:
-
```Python
images: list[Image]
```
diff --git a/docs/es/docs/tutorial/body.md b/docs/es/docs/tutorial/body.md
index 58877c5c46..06a70dbc79 100644
--- a/docs/es/docs/tutorial/body.md
+++ b/docs/es/docs/tutorial/body.md
@@ -161,7 +161,7 @@ Los parámetros de la función se reconocerán de la siguiente manera:
FastAPI sabrá que el valor de `q` no es requerido debido al valor por defecto `= None`.
-El `str | None` (Python 3.10+) o `Union` en `Union[str, None]` (Python 3.8+) no es utilizado por FastAPI para determinar que el valor no es requerido, sabrá que no es requerido porque tiene un valor por defecto de `= None`.
+El `str | None` (Python 3.10+) o `Union` en `Union[str, None]` (Python 3.9+) no es utilizado por FastAPI para determinar que el valor no es requerido, sabrá que no es requerido porque tiene un valor por defecto de `= None`.
Pero agregar las anotaciones de tipos permitirá que tu editor te brinde un mejor soporte y detecte errores.
diff --git a/docs/es/docs/tutorial/cors.md b/docs/es/docs/tutorial/cors.md
index d6bc7ea61f..c1a23295e1 100644
--- a/docs/es/docs/tutorial/cors.md
+++ b/docs/es/docs/tutorial/cors.md
@@ -46,7 +46,7 @@ También puedes especificar si tu backend permite:
* Métodos HTTP específicos (`POST`, `PUT`) o todos ellos con el comodín `"*"`.
* Headers HTTP específicos o todos ellos con el comodín `"*"`.
-{* ../../docs_src/cors/tutorial001.py hl[2,6:11,13:19] *}
+{* ../../docs_src/cors/tutorial001_py39.py hl[2,6:11,13:19] *}
Los parámetros predeterminados utilizados por la implementación de `CORSMiddleware` son restrictivos por defecto, por lo que necesitarás habilitar explícitamente orígenes, métodos o headers particulares para que los navegadores estén permitidos de usarlos en un contexto de Cross-Domain.
diff --git a/docs/es/docs/tutorial/debugging.md b/docs/es/docs/tutorial/debugging.md
index 1e57df2092..c31daf40f4 100644
--- a/docs/es/docs/tutorial/debugging.md
+++ b/docs/es/docs/tutorial/debugging.md
@@ -6,7 +6,7 @@ Puedes conectar el depurador en tu editor, por ejemplo con Visual Studio Code o
En tu aplicación de FastAPI, importa y ejecuta `uvicorn` directamente:
-{* ../../docs_src/debugging/tutorial001.py hl[1,15] *}
+{* ../../docs_src/debugging/tutorial001_py39.py hl[1,15] *}
### Acerca de `__name__ == "__main__"` { #about-name-main }
diff --git a/docs/es/docs/tutorial/dependencies/classes-as-dependencies.md b/docs/es/docs/tutorial/dependencies/classes-as-dependencies.md
index 37cc2e2133..a3a75efcd9 100644
--- a/docs/es/docs/tutorial/dependencies/classes-as-dependencies.md
+++ b/docs/es/docs/tutorial/dependencies/classes-as-dependencies.md
@@ -101,7 +101,7 @@ Ahora puedes declarar tu dependencia usando esta clase.
Nota cómo escribimos `CommonQueryParams` dos veces en el código anterior:
-//// tab | Python 3.8+
+//// tab | Python 3.9+
```Python
commons: Annotated[CommonQueryParams, Depends(CommonQueryParams)]
@@ -109,7 +109,7 @@ commons: Annotated[CommonQueryParams, Depends(CommonQueryParams)]
////
-//// tab | Python 3.8+ sin `Annotated`
+//// tab | Python 3.9+ sin `Annotated`
/// tip | Consejo
@@ -137,7 +137,7 @@ Es a partir de este que **FastAPI** extraerá los parámetros declarados y es lo
En este caso, el primer `CommonQueryParams`, en:
-//// tab | Python 3.8+
+//// tab | Python 3.9+
```Python
commons: Annotated[CommonQueryParams, ...
@@ -145,7 +145,7 @@ commons: Annotated[CommonQueryParams, ...
////
-//// tab | Python 3.8+ sin `Annotated`
+//// tab | Python 3.9+ sin `Annotated`
/// tip | Consejo
@@ -163,7 +163,7 @@ commons: CommonQueryParams ...
De hecho, podrías escribir simplemente:
-//// tab | Python 3.8+
+//// tab | Python 3.9+
```Python
commons: Annotated[Any, Depends(CommonQueryParams)]
@@ -171,7 +171,7 @@ commons: Annotated[Any, Depends(CommonQueryParams)]
////
-//// tab | Python 3.8+ sin `Annotated`
+//// tab | Python 3.9+ sin `Annotated`
/// tip | Consejo
@@ -197,7 +197,7 @@ Pero declarar el tipo es recomendable, ya que de esa manera tu editor sabrá lo
Pero ves que estamos teniendo algo de repetición de código aquí, escribiendo `CommonQueryParams` dos veces:
-//// tab | Python 3.8+
+//// tab | Python 3.9+
```Python
commons: Annotated[CommonQueryParams, Depends(CommonQueryParams)]
@@ -205,7 +205,7 @@ commons: Annotated[CommonQueryParams, Depends(CommonQueryParams)]
////
-//// tab | Python 3.8+ sin `Annotated`
+//// tab | Python 3.9+ sin `Annotated`
/// tip | Consejo
@@ -225,7 +225,7 @@ Para esos casos específicos, puedes hacer lo siguiente:
En lugar de escribir:
-//// tab | Python 3.8+
+//// tab | Python 3.9+
```Python
commons: Annotated[CommonQueryParams, Depends(CommonQueryParams)]
@@ -233,7 +233,7 @@ commons: Annotated[CommonQueryParams, Depends(CommonQueryParams)]
////
-//// tab | Python 3.8+ sin `Annotated`
+//// tab | Python 3.9+ sin `Annotated`
/// tip | Consejo
@@ -249,7 +249,7 @@ commons: CommonQueryParams = Depends(CommonQueryParams)
...escribes:
-//// tab | Python 3.8+
+//// tab | Python 3.9+
```Python
commons: Annotated[CommonQueryParams, Depends()]
@@ -257,7 +257,7 @@ commons: Annotated[CommonQueryParams, Depends()]
////
-//// tab | Python 3.8 sin `Annotated`
+//// tab | Python 3.9+ sin `Annotated`
/// tip | Consejo
diff --git a/docs/es/docs/tutorial/dependencies/dependencies-with-yield.md b/docs/es/docs/tutorial/dependencies/dependencies-with-yield.md
index e29c749a5f..aa645daa47 100644
--- a/docs/es/docs/tutorial/dependencies/dependencies-with-yield.md
+++ b/docs/es/docs/tutorial/dependencies/dependencies-with-yield.md
@@ -29,15 +29,15 @@ Por ejemplo, podrías usar esto para crear una sesión de base de datos y cerrar
Solo el código anterior e incluyendo la declaración `yield` se ejecuta antes de crear un response:
-{* ../../docs_src/dependencies/tutorial007.py hl[2:4] *}
+{* ../../docs_src/dependencies/tutorial007_py39.py hl[2:4] *}
El valor generado es lo que se inyecta en *path operations* y otras dependencias:
-{* ../../docs_src/dependencies/tutorial007.py hl[4] *}
+{* ../../docs_src/dependencies/tutorial007_py39.py hl[4] *}
El código posterior a la declaración `yield` se ejecuta después del response:
-{* ../../docs_src/dependencies/tutorial007.py hl[5:6] *}
+{* ../../docs_src/dependencies/tutorial007_py39.py hl[5:6] *}
/// tip | Consejo
@@ -57,7 +57,7 @@ Por lo tanto, puedes buscar esa excepción específica dentro de la dependencia
Del mismo modo, puedes usar `finally` para asegurarte de que los pasos de salida se ejecuten, sin importar si hubo una excepción o no.
-{* ../../docs_src/dependencies/tutorial007.py hl[3,5] *}
+{* ../../docs_src/dependencies/tutorial007_py39.py hl[3,5] *}
## Sub-dependencias con `yield` { #sub-dependencies-with-yield }
@@ -270,7 +270,7 @@ En Python, puedes crear Context Managers deprecated, pero sin eliminarla, pasa el parámetro `deprecated`:
-{* ../../docs_src/path_operation_configuration/tutorial006.py hl[16] *}
+{* ../../docs_src/path_operation_configuration/tutorial006_py39.py hl[16] *}
Se marcará claramente como deprecado en la documentación interactiva:
diff --git a/docs/es/docs/tutorial/path-params-numeric-validations.md b/docs/es/docs/tutorial/path-params-numeric-validations.md
index a6f0a4cd3d..569dd03dd0 100644
--- a/docs/es/docs/tutorial/path-params-numeric-validations.md
+++ b/docs/es/docs/tutorial/path-params-numeric-validations.md
@@ -54,7 +54,7 @@ No importa para **FastAPI**. Detectará los parámetros por sus nombres, tipos y
Así que puedes declarar tu función como:
-{* ../../docs_src/path_params_numeric_validations/tutorial002.py hl[7] *}
+{* ../../docs_src/path_params_numeric_validations/tutorial002_py39.py hl[7] *}
Pero ten en cuenta que si usas `Annotated`, no tendrás este problema, no importará ya que no estás usando los valores por defecto de los parámetros de la función para `Query()` o `Path()`.
@@ -83,7 +83,7 @@ Pasa `*`, como el primer parámetro de la función.
Python no hará nada con ese `*`, pero sabrá que todos los parámetros siguientes deben ser llamados como argumentos de palabras clave (parejas key-value), también conocidos como kwargs. Incluso si no tienen un valor por defecto.
-{* ../../docs_src/path_params_numeric_validations/tutorial003.py hl[7] *}
+{* ../../docs_src/path_params_numeric_validations/tutorial003_py39.py hl[7] *}
### Mejor con `Annotated` { #better-with-annotated }
diff --git a/docs/es/docs/tutorial/path-params.md b/docs/es/docs/tutorial/path-params.md
index c49b31c44e..7ba49f3b0b 100644
--- a/docs/es/docs/tutorial/path-params.md
+++ b/docs/es/docs/tutorial/path-params.md
@@ -2,7 +2,7 @@
Puedes declarar "parámetros" o "variables" de path con la misma sintaxis que se usa en los format strings de Python:
-{* ../../docs_src/path_params/tutorial001.py hl[6:7] *}
+{* ../../docs_src/path_params/tutorial001_py39.py hl[6:7] *}
El valor del parámetro de path `item_id` se pasará a tu función como el argumento `item_id`.
@@ -16,7 +16,7 @@ Así que, si ejecutas este ejemplo y vas a Las enumeraciones (o enums) están disponibles en Python desde la versión 3.4.
-
-///
+{* ../../docs_src/path_params/tutorial005_py39.py hl[1,6:9] *}
/// tip | Consejo
@@ -158,7 +152,7 @@ Si te estás preguntando, "AlexNet", "ResNet" y "LeNet" son solo nombres de `dataclasses` da mesma forma:
-{* ../../docs_src/dataclasses/tutorial001_py310.py hl[1,6:11,18:19] *}
+{* ../../docs_src/dataclasses_/tutorial001_py310.py hl[1,6:11,18:19] *}
Isso ainda é suportado graças ao **Pydantic**, pois ele tem suporte interno para `dataclasses`.
@@ -32,7 +32,7 @@ Mas se você tem um monte de dataclasses por aí, este é um truque legal para u
Você também pode usar `dataclasses` no parâmetro `response_model`:
-{* ../../docs_src/dataclasses/tutorial002_py310.py hl[1,6:12,18] *}
+{* ../../docs_src/dataclasses_/tutorial002_py310.py hl[1,6:12,18] *}
A dataclass será automaticamente convertida para uma dataclass Pydantic.
@@ -48,7 +48,7 @@ Em alguns casos, você ainda pode ter que usar a versão do Pydantic das `datacl
Nesse caso, você pode simplesmente trocar as `dataclasses` padrão por `pydantic.dataclasses`, que é um substituto direto:
-{* ../../docs_src/dataclasses/tutorial003_py310.py hl[1,4,7:10,13:16,22:24,27] *}
+{* ../../docs_src/dataclasses_/tutorial003_py310.py hl[1,4,7:10,13:16,22:24,27] *}
1. Ainda importamos `field` das `dataclasses` padrão.
diff --git a/docs/pt/docs/advanced/events.md b/docs/pt/docs/advanced/events.md
index e29ece8e3c..8cdc358289 100644
--- a/docs/pt/docs/advanced/events.md
+++ b/docs/pt/docs/advanced/events.md
@@ -30,7 +30,7 @@ Vamos começar com um exemplo e depois ver em detalhes.
Nós criamos uma função assíncrona `lifespan()` com `yield` assim:
-{* ../../docs_src/events/tutorial003.py hl[16,19] *}
+{* ../../docs_src/events/tutorial003_py39.py hl[16,19] *}
Aqui estamos simulando a operação de *inicialização* custosa de carregar o modelo, colocando a (falsa) função do modelo no dicionário com modelos de machine learning antes do `yield`. Esse código será executado **antes** de a aplicação **começar a receber requisições**, durante a *inicialização*.
@@ -48,7 +48,7 @@ Talvez você precise iniciar uma nova versão, ou apenas cansou de executá-la.
A primeira coisa a notar é que estamos definindo uma função assíncrona com `yield`. Isso é muito semelhante a Dependências com `yield`.
-{* ../../docs_src/events/tutorial003.py hl[14:19] *}
+{* ../../docs_src/events/tutorial003_py39.py hl[14:19] *}
A primeira parte da função, antes do `yield`, será executada **antes** de a aplicação iniciar.
@@ -60,7 +60,7 @@ Se você verificar, a função está decorada com um `@asynccontextmanager`.
Isso converte a função em algo chamado "**gerenciador de contexto assíncrono**".
-{* ../../docs_src/events/tutorial003.py hl[1,13] *}
+{* ../../docs_src/events/tutorial003_py39.py hl[1,13] *}
Um **gerenciador de contexto** em Python é algo que você pode usar em uma declaração `with`, por exemplo, `open()` pode ser usado como um gerenciador de contexto:
@@ -82,7 +82,7 @@ No nosso exemplo de código acima, não o usamos diretamente, mas passamos para
O parâmetro `lifespan` da aplicação `FastAPI` aceita um **gerenciador de contexto assíncrono**, então podemos passar para ele nosso novo gerenciador de contexto assíncrono `lifespan`.
-{* ../../docs_src/events/tutorial003.py hl[22] *}
+{* ../../docs_src/events/tutorial003_py39.py hl[22] *}
## Eventos alternativos (descontinuados) { #alternative-events-deprecated }
@@ -104,7 +104,7 @@ Essas funções podem ser declaradas com `async def` ou `def` normal.
Para adicionar uma função que deve rodar antes de a aplicação iniciar, declare-a com o evento `"startup"`:
-{* ../../docs_src/events/tutorial001.py hl[8] *}
+{* ../../docs_src/events/tutorial001_py39.py hl[8] *}
Nesse caso, a função de manipulador do evento `startup` inicializará os itens do "banco de dados" (apenas um `dict`) com alguns valores.
@@ -116,7 +116,7 @@ E sua aplicação não começará a receber requisições até que todos os mani
Para adicionar uma função que deve ser executada quando a aplicação estiver encerrando, declare-a com o evento `"shutdown"`:
-{* ../../docs_src/events/tutorial002.py hl[6] *}
+{* ../../docs_src/events/tutorial002_py39.py hl[6] *}
Aqui, a função de manipulador do evento `shutdown` escreverá uma linha de texto `"Application shutdown"` no arquivo `log.txt`.
diff --git a/docs/pt/docs/advanced/generate-clients.md b/docs/pt/docs/advanced/generate-clients.md
index 253a7e6cdd..5134bc7cb5 100644
--- a/docs/pt/docs/advanced/generate-clients.md
+++ b/docs/pt/docs/advanced/generate-clients.md
@@ -167,7 +167,7 @@ Mas para o cliente gerado, poderíamos **modificar** os IDs de operação do Ope
Poderíamos baixar o JSON do OpenAPI para um arquivo `openapi.json` e então poderíamos **remover essa tag prefixada** com um script como este:
-{* ../../docs_src/generate_clients/tutorial004.py *}
+{* ../../docs_src/generate_clients/tutorial004_py39.py *}
//// tab | Node.js
diff --git a/docs/pt/docs/advanced/middleware.md b/docs/pt/docs/advanced/middleware.md
index 9186bcb494..30c1834790 100644
--- a/docs/pt/docs/advanced/middleware.md
+++ b/docs/pt/docs/advanced/middleware.md
@@ -57,13 +57,13 @@ Garante que todas as requisições devem ser `https` ou `wss`.
Qualquer requisição para `http` ou `ws` será redirecionada para o esquema seguro.
-{* ../../docs_src/advanced_middleware/tutorial001.py hl[2,6] *}
+{* ../../docs_src/advanced_middleware/tutorial001_py39.py hl[2,6] *}
## `TrustedHostMiddleware` { #trustedhostmiddleware }
Garante que todas as requisições recebidas tenham um cabeçalho `Host` corretamente configurado, a fim de proteger contra ataques de cabeçalho de host HTTP.
-{* ../../docs_src/advanced_middleware/tutorial002.py hl[2,6:8] *}
+{* ../../docs_src/advanced_middleware/tutorial002_py39.py hl[2,6:8] *}
Os seguintes argumentos são suportados:
@@ -78,7 +78,7 @@ Gerencia respostas GZip para qualquer requisição que inclua `"gzip"` no cabeç
O middleware lidará com respostas padrão e de streaming.
-{* ../../docs_src/advanced_middleware/tutorial003.py hl[2,6] *}
+{* ../../docs_src/advanced_middleware/tutorial003_py39.py hl[2,6] *}
Os seguintes argumentos são suportados:
diff --git a/docs/pt/docs/advanced/openapi-webhooks.md b/docs/pt/docs/advanced/openapi-webhooks.md
index fa3840fb35..011898e8cd 100644
--- a/docs/pt/docs/advanced/openapi-webhooks.md
+++ b/docs/pt/docs/advanced/openapi-webhooks.md
@@ -32,7 +32,7 @@ Webhooks estão disponíveis a partir do OpenAPI 3.1.0, e possui suporte do Fast
Quando você cria uma aplicação com o **FastAPI**, existe um atributo chamado `webhooks`, que você utilizar para defini-los da mesma maneira que você definiria as suas **operações de rotas**, utilizando por exemplo `@app.webhooks.post()`.
-{* ../../docs_src/openapi_webhooks/tutorial001.py hl[9:13,36:53] *}
+{* ../../docs_src/openapi_webhooks/tutorial001_py39.py hl[9:13,36:53] *}
Os webhooks que você define aparecerão no esquema do **OpenAPI** e na **página de documentação** gerada automaticamente.
diff --git a/docs/pt/docs/advanced/path-operation-advanced-configuration.md b/docs/pt/docs/advanced/path-operation-advanced-configuration.md
index 12505a9a87..e1c3e5ab89 100644
--- a/docs/pt/docs/advanced/path-operation-advanced-configuration.md
+++ b/docs/pt/docs/advanced/path-operation-advanced-configuration.md
@@ -12,7 +12,7 @@ Você pode definir o `operationId` do OpenAPI que será utilizado na sua *opera
Você precisa ter certeza que ele é único para cada operação.
-{* ../../docs_src/path_operation_advanced_configuration/tutorial001.py hl[6] *}
+{* ../../docs_src/path_operation_advanced_configuration/tutorial001_py39.py hl[6] *}
### Utilizando o nome da *função de operação de rota* como o operationId { #using-the-path-operation-function-name-as-the-operationid }
@@ -20,7 +20,7 @@ Se você quiser utilizar o nome das funções da sua API como `operationId`s, vo
Você deve fazer isso depois de adicionar todas as suas *operações de rota*.
-{* ../../docs_src/path_operation_advanced_configuration/tutorial002.py hl[2, 12:21, 24] *}
+{* ../../docs_src/path_operation_advanced_configuration/tutorial002_py39.py hl[2, 12:21, 24] *}
/// tip | Dica
@@ -40,7 +40,7 @@ Mesmo que elas estejam em módulos (arquivos Python) diferentes.
Para excluir uma *operação de rota* do esquema OpenAPI gerado (e por consequência, dos sistemas de documentação automáticos), utilize o parâmetro `include_in_schema` e defina ele como `False`:
-{* ../../docs_src/path_operation_advanced_configuration/tutorial003.py hl[6] *}
+{* ../../docs_src/path_operation_advanced_configuration/tutorial003_py39.py hl[6] *}
## Descrição avançada a partir de docstring { #advanced-description-from-docstring }
@@ -92,7 +92,7 @@ Você pode estender o esquema do OpenAPI para uma *operação de rota* utilizand
Esse parâmetro `openapi_extra` pode ser útil, por exemplo, para declarar [Extensões do OpenAPI](https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.3.md#specificationExtensions):
-{* ../../docs_src/path_operation_advanced_configuration/tutorial005.py hl[6] *}
+{* ../../docs_src/path_operation_advanced_configuration/tutorial005_py39.py hl[6] *}
Se você abrir os documentos criados automaticamente para a API, sua extensão aparecerá no final da *operação de rota* específica.
@@ -139,7 +139,7 @@ Por exemplo, você poderia optar por ler e validar a requisição com seu própr
Você pode fazer isso com `openapi_extra`:
-{* ../../docs_src/path_operation_advanced_configuration/tutorial006.py hl[19:36, 39:40] *}
+{* ../../docs_src/path_operation_advanced_configuration/tutorial006_py39.py hl[19:36, 39:40] *}
Nesse exemplo, nós não declaramos nenhum modelo do Pydantic. Na verdade, o corpo da requisição não está nem mesmo analisado como JSON, ele é lido diretamente como `bytes` e a função `magic_data_reader()` seria a responsável por analisar ele de alguma forma.
diff --git a/docs/pt/docs/advanced/response-change-status-code.md b/docs/pt/docs/advanced/response-change-status-code.md
index 0f08873f67..ee81f0bfc8 100644
--- a/docs/pt/docs/advanced/response-change-status-code.md
+++ b/docs/pt/docs/advanced/response-change-status-code.md
@@ -20,7 +20,7 @@ Você pode declarar um parâmetro do tipo `Response` em sua *função de operaç
E então você pode definir o `status_code` neste objeto de retorno temporal.
-{* ../../docs_src/response_change_status_code/tutorial001.py hl[1,9,12] *}
+{* ../../docs_src/response_change_status_code/tutorial001_py39.py hl[1,9,12] *}
E então você pode retornar qualquer objeto que você precise, como você faria normalmente (um `dict`, um modelo de banco de dados, etc.).
diff --git a/docs/pt/docs/advanced/response-cookies.md b/docs/pt/docs/advanced/response-cookies.md
index 41fc000133..67820b433b 100644
--- a/docs/pt/docs/advanced/response-cookies.md
+++ b/docs/pt/docs/advanced/response-cookies.md
@@ -6,7 +6,7 @@ Você pode declarar um parâmetro do tipo `Response` na sua *função de operaç
E então você pode definir cookies nesse objeto de resposta *temporário*.
-{* ../../docs_src/response_cookies/tutorial002.py hl[1, 8:9] *}
+{* ../../docs_src/response_cookies/tutorial002_py39.py hl[1, 8:9] *}
Em seguida, você pode retornar qualquer objeto que precise, como normalmente faria (um `dict`, um modelo de banco de dados, etc).
@@ -24,7 +24,7 @@ Para fazer isso, você pode criar uma resposta como descrito em [Retorne uma Res
Então, defina os cookies nela e a retorne:
-{* ../../docs_src/response_cookies/tutorial001.py hl[10:12] *}
+{* ../../docs_src/response_cookies/tutorial001_py39.py hl[10:12] *}
/// tip | Dica
diff --git a/docs/pt/docs/advanced/response-directly.md b/docs/pt/docs/advanced/response-directly.md
index 0c0144e9a1..bbbef2f913 100644
--- a/docs/pt/docs/advanced/response-directly.md
+++ b/docs/pt/docs/advanced/response-directly.md
@@ -54,7 +54,7 @@ Vamos dizer que você quer retornar uma resposta FastAPI Cloud com um **único comando**; entre na lista de espera, caso ainda não tenha feito isso. 🚀
+
+## Login { #login }
+
+Certifique-se de que você já tem uma conta no **FastAPI Cloud** (nós convidamos você a partir da lista de espera 😉).
+
+Depois, faça login:
+
+
+
+```console
+$ fastapi login
+
+You are logged in to FastAPI Cloud 🚀
+```
+
+
+
+## Implantar { #deploy }
+
+Agora, implante sua aplicação, com **um único comando**:
+
+
+
+```console
+$ fastapi deploy
+
+Deploying to FastAPI Cloud...
+
+✅ Deployment successful!
+
+🐔 Ready the chicken! Your app is ready at https://myapp.fastapicloud.dev
+```
+
+
+
+É isso! Agora você pode acessar sua aplicação nesse URL. ✨
+
+## Sobre o FastAPI Cloud { #about-fastapi-cloud }
+
+O **FastAPI Cloud** é desenvolvido pelo mesmo autor e equipe por trás do **FastAPI**.
+
+Ele simplifica o processo de **criar**, **implantar** e **acessar** uma API com esforço mínimo.
+
+Traz a mesma **experiência do desenvolvedor** de criar aplicações com FastAPI para **implantá-las** na nuvem. 🎉
+
+Ele também cuidará da maioria das coisas de que você precisaria ao implantar uma aplicação, como:
+
+* HTTPS
+* Replicação, com dimensionamento automático baseado em requests
+* etc.
+
+O FastAPI Cloud é o patrocinador principal e provedor de financiamento dos projetos open source do ecossistema *FastAPI and friends*. ✨
+
+## Implantar em outros provedores de nuvem { #deploy-to-other-cloud-providers }
+
+FastAPI é open source e baseado em padrões. Você pode implantar aplicações FastAPI em qualquer provedor de nuvem que escolher.
+
+Siga os tutoriais do seu provedor de nuvem para implantar aplicações FastAPI com esse provedor. 🤓
+
+## Implantar no seu próprio servidor { #deploy-your-own-server }
+
+Também vou lhe ensinar, mais adiante neste guia de **Implantação**, todos os detalhes, para que você possa entender o que está acontecendo, o que precisa acontecer, ou como implantar aplicações FastAPI por conta própria, inclusive nos seus próprios servidores. 🤓
diff --git a/docs/pt/docs/how-to/authentication-error-status-code.md b/docs/pt/docs/how-to/authentication-error-status-code.md
new file mode 100644
index 0000000000..878a1ca1ac
--- /dev/null
+++ b/docs/pt/docs/how-to/authentication-error-status-code.md
@@ -0,0 +1,17 @@
+# Usar antigos códigos de status de erro de autenticação 403 { #use-old-403-authentication-error-status-codes }
+
+Antes da versão `0.122.0` do FastAPI, quando os utilitários de segurança integrados retornavam um erro ao cliente após uma falha na autenticação, eles usavam o código de status HTTP `403 Forbidden`.
+
+A partir da versão `0.122.0` do FastAPI, eles usam o código de status HTTP `401 Unauthorized`, mais apropriado, e retornam um cabeçalho `WWW-Authenticate` adequado na response, seguindo as especificações HTTP, RFC 7235, RFC 9110.
+
+Mas, se por algum motivo seus clientes dependem do comportamento antigo, você pode voltar a ele sobrescrevendo o método `make_not_authenticated_error` nas suas classes de segurança.
+
+Por exemplo, você pode criar uma subclasse de `HTTPBearer` que retorne um erro `403 Forbidden` em vez do erro padrão `401 Unauthorized`:
+
+{* ../../docs_src/authentication_error_status_code/tutorial001_an_py39.py hl[9:13] *}
+
+/// tip | Dica
+
+Perceba que a função retorna a instância da exceção, ela não a lança. O lançamento é feito no restante do código interno.
+
+///
diff --git a/docs/pt/docs/how-to/conditional-openapi.md b/docs/pt/docs/how-to/conditional-openapi.md
index da4f5f7642..b475dae6d6 100644
--- a/docs/pt/docs/how-to/conditional-openapi.md
+++ b/docs/pt/docs/how-to/conditional-openapi.md
@@ -29,7 +29,7 @@ Você pode usar facilmente as mesmas configurações do Pydantic para configurar
Por exemplo:
-{* ../../docs_src/conditional_openapi/tutorial001.py hl[6,11] *}
+{* ../../docs_src/conditional_openapi/tutorial001_py39.py hl[6,11] *}
Aqui declaramos a configuração `openapi_url` com o mesmo padrão de `"/openapi.json"`.
diff --git a/docs/pt/docs/how-to/configure-swagger-ui.md b/docs/pt/docs/how-to/configure-swagger-ui.md
index 163316932f..2d1863c64c 100644
--- a/docs/pt/docs/how-to/configure-swagger-ui.md
+++ b/docs/pt/docs/how-to/configure-swagger-ui.md
@@ -18,7 +18,7 @@ Sem alterar as configurações, o destaque de sintaxe é habilitado por padrão:
Mas você pode desabilitá-lo definindo `syntaxHighlight` como `False`:
-{* ../../docs_src/configure_swagger_ui/tutorial001.py hl[3] *}
+{* ../../docs_src/configure_swagger_ui/tutorial001_py39.py hl[3] *}
...e então o Swagger UI não mostrará mais o destaque de sintaxe:
@@ -28,7 +28,7 @@ Mas você pode desabilitá-lo definindo `syntaxHighlight` como `False`:
Da mesma forma que você pode definir o tema de destaque de sintaxe com a chave `"syntaxHighlight.theme"` (observe que há um ponto no meio):
-{* ../../docs_src/configure_swagger_ui/tutorial002.py hl[3] *}
+{* ../../docs_src/configure_swagger_ui/tutorial002_py39.py hl[3] *}
Essa configuração alteraria o tema de cores de destaque de sintaxe:
@@ -46,7 +46,7 @@ Você pode substituir qualquer um deles definindo um valor diferente no argument
Por exemplo, para desabilitar `deepLinking` você pode passar essas configurações para `swagger_ui_parameters`:
-{* ../../docs_src/configure_swagger_ui/tutorial003.py hl[3] *}
+{* ../../docs_src/configure_swagger_ui/tutorial003_py39.py hl[3] *}
## Outros parâmetros da UI do Swagger { #other-swagger-ui-parameters }
diff --git a/docs/pt/docs/how-to/custom-docs-ui-assets.md b/docs/pt/docs/how-to/custom-docs-ui-assets.md
index 30224c72bb..adda9eca50 100644
--- a/docs/pt/docs/how-to/custom-docs-ui-assets.md
+++ b/docs/pt/docs/how-to/custom-docs-ui-assets.md
@@ -18,7 +18,7 @@ O primeiro passo é desativar a documentação automática, pois por padrão, el
Para desativá-los, defina suas URLs como `None` ao criar sua aplicação FastAPI:
-{* ../../docs_src/custom_docs_ui/tutorial001.py hl[8] *}
+{* ../../docs_src/custom_docs_ui/tutorial001_py39.py hl[8] *}
### Incluir a documentação personalizada { #include-the-custom-docs }
@@ -34,7 +34,7 @@ Você pode reutilizar as funções internas do FastAPI para criar as páginas HT
E de forma semelhante para o ReDoc...
-{* ../../docs_src/custom_docs_ui/tutorial001.py hl[2:6,11:19,22:24,27:33] *}
+{* ../../docs_src/custom_docs_ui/tutorial001_py39.py hl[2:6,11:19,22:24,27:33] *}
/// tip | Dica
@@ -50,7 +50,7 @@ Swagger UI lidará com isso nos bastidores para você, mas ele precisa desse aux
Agora, para poder testar se tudo funciona, crie uma *operação de rota*:
-{* ../../docs_src/custom_docs_ui/tutorial001.py hl[36:38] *}
+{* ../../docs_src/custom_docs_ui/tutorial001_py39.py hl[36:38] *}
### Teste { #test-it }
@@ -118,7 +118,7 @@ Depois disso, sua estrutura de arquivos deve se parecer com:
* Importe `StaticFiles`.
* "Monte" a instância `StaticFiles()` em um caminho específico.
-{* ../../docs_src/custom_docs_ui/tutorial002.py hl[7,11] *}
+{* ../../docs_src/custom_docs_ui/tutorial002_py39.py hl[7,11] *}
### Teste os arquivos estáticos { #test-the-static-files }
@@ -144,7 +144,7 @@ Da mesma forma que ao usar um CDN personalizado, o primeiro passo é desativar a
Para desativá-los, defina suas URLs como `None` ao criar sua aplicação FastAPI:
-{* ../../docs_src/custom_docs_ui/tutorial002.py hl[9] *}
+{* ../../docs_src/custom_docs_ui/tutorial002_py39.py hl[9] *}
### Incluir a documentação personalizada para arquivos estáticos { #include-the-custom-docs-for-static-files }
@@ -160,7 +160,7 @@ Novamente, você pode reutilizar as funções internas do FastAPI para criar as
E de forma semelhante para o ReDoc...
-{* ../../docs_src/custom_docs_ui/tutorial002.py hl[2:6,14:22,25:27,30:36] *}
+{* ../../docs_src/custom_docs_ui/tutorial002_py39.py hl[2:6,14:22,25:27,30:36] *}
/// tip | Dica
@@ -176,7 +176,7 @@ Swagger UI lidará com isso nos bastidores para você, mas ele precisa desse aux
Agora, para poder testar se tudo funciona, crie uma *operação de rota*:
-{* ../../docs_src/custom_docs_ui/tutorial002.py hl[39:41] *}
+{* ../../docs_src/custom_docs_ui/tutorial002_py39.py hl[39:41] *}
### Teste a UI de Arquivos Estáticos { #test-static-files-ui }
diff --git a/docs/pt/docs/how-to/extending-openapi.md b/docs/pt/docs/how-to/extending-openapi.md
index 54d56b95ae..b1b50ce654 100644
--- a/docs/pt/docs/how-to/extending-openapi.md
+++ b/docs/pt/docs/how-to/extending-openapi.md
@@ -43,19 +43,19 @@ Por exemplo, vamos adicionar documentação do Strawberry.
diff --git a/docs/pt/docs/python-types.md b/docs/pt/docs/python-types.md
index 3e2d1ccb30..fc983d1df1 100644
--- a/docs/pt/docs/python-types.md
+++ b/docs/pt/docs/python-types.md
@@ -22,7 +22,7 @@ Se você é um especialista em Python e já sabe tudo sobre type hints, pule par
Vamos começar com um exemplo simples:
-{* ../../docs_src/python_types/tutorial001.py *}
+{* ../../docs_src/python_types/tutorial001_py39.py *}
A chamada deste programa gera:
@@ -36,7 +36,7 @@ A função faz o seguinte:
* Converte a primeira letra de cada uma em maiúsculas com `title()`.
* Concatena com um espaço no meio.
-{* ../../docs_src/python_types/tutorial001.py hl[2] *}
+{* ../../docs_src/python_types/tutorial001_py39.py hl[2] *}
### Edite-o { #edit-it }
@@ -78,7 +78,7 @@ para:
Esses são os "type hints":
-{* ../../docs_src/python_types/tutorial002.py hl[1] *}
+{* ../../docs_src/python_types/tutorial002_py39.py hl[1] *}
Isso não é o mesmo que declarar valores padrão como seria com:
@@ -106,7 +106,7 @@ Com isso, você pode rolar, vendo as opções, até encontrar o que "soa familia
Verifique esta função, ela já possui type hints:
-{* ../../docs_src/python_types/tutorial003.py hl[1] *}
+{* ../../docs_src/python_types/tutorial003_py39.py hl[1] *}
Como o editor conhece os tipos de variáveis, você não obtém apenas o preenchimento automático, mas também as verificações de erro:
@@ -114,7 +114,7 @@ Como o editor conhece os tipos de variáveis, você não obtém apenas o preench
Agora você sabe que precisa corrigí-lo, converta `age` em uma string com `str(age)`:
-{* ../../docs_src/python_types/tutorial004.py hl[2] *}
+{* ../../docs_src/python_types/tutorial004_py39.py hl[2] *}
## Declarando Tipos { #declaring-types }
@@ -133,7 +133,7 @@ Você pode usar, por exemplo:
* `bool`
* `bytes`
-{* ../../docs_src/python_types/tutorial005.py hl[1] *}
+{* ../../docs_src/python_types/tutorial005_py39.py hl[1] *}
### Tipos genéricos com parâmetros de tipo { #generic-types-with-type-parameters }
@@ -161,56 +161,24 @@ Se você pode utilizar a **versão mais recente do Python**, utilize os exemplos
Por exemplo, vamos definir uma variável para ser uma `list` de `str`.
-//// tab | Python 3.9+
+Declare a variável, com a mesma sintaxe com dois pontos (`:`).
-Declare uma variável com a mesma sintaxe com dois pontos (`:`)
+Como o tipo, coloque `list`.
-Como tipo, coloque `list`.
+Como a lista é um tipo que contém tipos internos, você os coloca entre colchetes:
-Como a lista é o tipo que contém algum tipo interno, você coloca o tipo dentro de colchetes:
-
-```Python hl_lines="1"
-{!> ../../docs_src/python_types/tutorial006_py39.py!}
-```
-
-////
-
-//// tab | Python 3.8+
-
-De `typing`, importe `List` (com o `L` maiúsculo):
-
-```Python hl_lines="1"
-{!> ../../docs_src/python_types/tutorial006.py!}
-```
-
-Declare uma variável com a mesma sintaxe com dois pontos (`:`)
-
-Como tipo, coloque o `List` que você importou de `typing`.
-
-Como a lista é o tipo que contém algum tipo interno, você coloca o tipo dentro de colchetes:
-
-```Python hl_lines="4"
-{!> ../../docs_src/python_types/tutorial006.py!}
-```
-
-////
+{* ../../docs_src/python_types/tutorial006_py39.py hl[1] *}
/// info | Informação
Estes tipos internos dentro dos colchetes são chamados "parâmetros de tipo" (type parameters).
-Neste caso, `str` é o parâmetro de tipo passado para `List` (ou `list` no Python 3.9 ou superior).
+Neste caso, `str` é o parâmetro de tipo passado para `list`.
///
Isso significa: "a variável `items` é uma `list`, e cada um dos itens desta lista é uma `str`".
-/// tip | Dica
-
-Se você usa o Python 3.9 ou superior, você não precisa importar `List` de `typing`. Você pode utilizar o mesmo tipo `list` no lugar.
-
-///
-
Ao fazer isso, seu editor pode fornecer suporte mesmo durante o processamento de itens da lista:
@@ -225,21 +193,7 @@ E, ainda assim, o editor sabe que é um `str` e fornece suporte para isso.
Você faria o mesmo para declarar `tuple`s e `set`s:
-//// tab | Python 3.9+
-
-```Python hl_lines="1"
-{!> ../../docs_src/python_types/tutorial007_py39.py!}
-```
-
-////
-
-//// tab | Python 3.8+
-
-```Python hl_lines="1 4"
-{!> ../../docs_src/python_types/tutorial007.py!}
-```
-
-////
+{* ../../docs_src/python_types/tutorial007_py39.py hl[1] *}
Isso significa que:
@@ -254,21 +208,7 @@ O primeiro parâmetro de tipo é para as chaves do `dict`.
O segundo parâmetro de tipo é para os valores do `dict`:
-//// tab | Python 3.9+
-
-```Python hl_lines="1"
-{!> ../../docs_src/python_types/tutorial008_py39.py!}
-```
-
-////
-
-//// tab | Python 3.8+
-
-```Python hl_lines="1 4"
-{!> ../../docs_src/python_types/tutorial008.py!}
-```
-
-////
+{* ../../docs_src/python_types/tutorial008_py39.py hl[1] *}
Isso significa que:
@@ -292,10 +232,10 @@ No Python 3.10 também existe uma **nova sintaxe** onde você pode colocar os po
////
-//// tab | Python 3.8+
+//// tab | Python 3.9+
```Python hl_lines="1 4"
-{!> ../../docs_src/python_types/tutorial008b.py!}
+{!> ../../docs_src/python_types/tutorial008b_py39.py!}
```
////
@@ -309,7 +249,7 @@ Você pode declarar que um valor pode ter um tipo, como `str`, mas que ele tamb
No Python 3.6 e superior (incluindo o Python 3.10) você pode declará-lo importando e utilizando `Optional` do módulo `typing`.
```Python hl_lines="1 4"
-{!../../docs_src/python_types/tutorial009.py!}
+{!../../docs_src/python_types/tutorial009_py39.py!}
```
O uso de `Optional[str]` em vez de apenas `str` permitirá que o editor o ajude a detectar erros, onde você pode estar assumindo que um valor é sempre um `str`, quando na verdade também pode ser `None`.
@@ -326,18 +266,18 @@ Isso também significa que no Python 3.10, você pode utilizar `Something | None
////
-//// tab | Python 3.8+
+//// tab | Python 3.9+
```Python hl_lines="1 4"
-{!> ../../docs_src/python_types/tutorial009.py!}
+{!> ../../docs_src/python_types/tutorial009_py39.py!}
```
////
-//// tab | Python 3.8+ alternativa
+//// tab | Python 3.9+ alternativa
```Python hl_lines="1 4"
-{!> ../../docs_src/python_types/tutorial009b.py!}
+{!> ../../docs_src/python_types/tutorial009b_py39.py!}
```
////
@@ -357,7 +297,7 @@ Isso é apenas sobre palavras e nomes. Mas estas palavras podem afetar como os s
Por exemplo, vamos pegar esta função:
-{* ../../docs_src/python_types/tutorial009c.py hl[1,4] *}
+{* ../../docs_src/python_types/tutorial009c_py39.py hl[1,4] *}
O parâmetro `name` é definido como `Optional[str]`, mas ele **não é opcional**, você não pode chamar a função sem o parâmetro:
@@ -390,10 +330,10 @@ Você pode utilizar os mesmos tipos internos como genéricos (com colchetes e ti
* `set`
* `dict`
-E o mesmo como no Python 3.8, do módulo `typing`:
+E o mesmo que com versões anteriores do Python, do módulo `typing`:
* `Union`
-* `Optional` (o mesmo que com o 3.8)
+* `Optional`
* ...entre outros.
No Python 3.10, como uma alternativa para a utilização dos genéricos `Union` e `Optional`, você pode usar a barra vertical (`|`) para declarar uniões de tipos. Isso é muito melhor e mais simples.
@@ -409,7 +349,7 @@ Você pode utilizar os mesmos tipos internos como genéricos (com colchetes e ti
* `set`
* `dict`
-E o mesmo como no Python 3.8, do módulo `typing`:
+E genéricos do módulo `typing`:
* `Union`
* `Optional`
@@ -417,31 +357,19 @@ E o mesmo como no Python 3.8, do módulo `typing`:
////
-//// tab | Python 3.8+
-
-* `List`
-* `Tuple`
-* `Set`
-* `Dict`
-* `Union`
-* `Optional`
-* ...entre outros.
-
-////
-
### Classes como tipos { #classes-as-types }
Você também pode declarar uma classe como o tipo de uma variável.
Digamos que você tenha uma classe `Person`, com um nome:
-{* ../../docs_src/python_types/tutorial010.py hl[1:3] *}
+{* ../../docs_src/python_types/tutorial010_py39.py hl[1:3] *}
Então você pode declarar que uma variável é do tipo `Person`:
-{* ../../docs_src/python_types/tutorial010.py hl[6] *}
+{* ../../docs_src/python_types/tutorial010_py39.py hl[6] *}
-E então, novamente, você recebe todo o suporte do editor:
+E então, novamente, você recebe todo o apoio do editor:
@@ -461,31 +389,9 @@ Em seguida, você cria uma instância dessa classe com alguns valores e ela os v
E você recebe todo o suporte do editor com esse objeto resultante.
-Retirado dos documentos oficiais dos Pydantic:
+Um exemplo da documentação oficial do Pydantic:
-//// tab | Python 3.10+
-
-```Python
-{!> ../../docs_src/python_types/tutorial011_py310.py!}
-```
-
-////
-
-//// tab | Python 3.9+
-
-```Python
-{!> ../../docs_src/python_types/tutorial011_py39.py!}
-```
-
-////
-
-//// tab | Python 3.8+
-
-```Python
-{!> ../../docs_src/python_types/tutorial011.py!}
-```
-
-////
+{* ../../docs_src/python_types/tutorial011_py310.py *}
/// info | Informação
@@ -507,27 +413,9 @@ O Pydantic tem um comportamento especial quando você usa `Optional` ou `Union[S
O Python possui uma funcionalidade que nos permite incluir **metadados adicionais** nos type hints utilizando `Annotated`.
-//// tab | Python 3.9+
+Desde o Python 3.9, `Annotated` faz parte da biblioteca padrão, então você pode importá-lo de `typing`.
-No Python 3.9, `Annotated` é parte da biblioteca padrão, então você pode importá-lo de `typing`.
-
-```Python hl_lines="1 4"
-{!> ../../docs_src/python_types/tutorial013_py39.py!}
-```
-
-////
-
-//// tab | Python 3.8+
-
-Em versões abaixo do Python 3.9, você importa `Annotated` de `typing_extensions`.
-
-Ele já estará instalado com o **FastAPI**.
-
-```Python hl_lines="1 4"
-{!> ../../docs_src/python_types/tutorial013.py!}
-```
-
-////
+{* ../../docs_src/python_types/tutorial013_py39.py hl[1,4] *}
O Python em si não faz nada com este `Annotated`. E para editores e outras ferramentas, o tipo ainda é `str`.
diff --git a/docs/pt/docs/tutorial/background-tasks.md b/docs/pt/docs/tutorial/background-tasks.md
index af0c8b2acd..34805364b4 100644
--- a/docs/pt/docs/tutorial/background-tasks.md
+++ b/docs/pt/docs/tutorial/background-tasks.md
@@ -15,7 +15,7 @@ Isso inclui, por exemplo:
Primeiro, importe `BackgroundTasks` e defina um parâmetro na sua *função de operação de rota* com uma declaração de tipo `BackgroundTasks`:
-{* ../../docs_src/background_tasks/tutorial001.py hl[1,13] *}
+{* ../../docs_src/background_tasks/tutorial001_py39.py hl[1,13] *}
O **FastAPI** criará o objeto do tipo `BackgroundTasks` para você e o passará como esse parâmetro.
@@ -31,13 +31,13 @@ Neste caso, a função da tarefa escreverá em um arquivo (simulando o envio de
E como a operação de escrita não usa `async` e `await`, definimos a função com um `def` normal:
-{* ../../docs_src/background_tasks/tutorial001.py hl[6:9] *}
+{* ../../docs_src/background_tasks/tutorial001_py39.py hl[6:9] *}
## Adicione a tarefa em segundo plano { #add-the-background-task }
Dentro da sua *função de operação de rota*, passe sua função de tarefa para o objeto de *tarefas em segundo plano* com o método `.add_task()`:
-{* ../../docs_src/background_tasks/tutorial001.py hl[14] *}
+{* ../../docs_src/background_tasks/tutorial001_py39.py hl[14] *}
O `.add_task()` recebe como argumentos:
diff --git a/docs/pt/docs/tutorial/body-nested-models.md b/docs/pt/docs/tutorial/body-nested-models.md
index 4f3ca661fb..f2bec19a2f 100644
--- a/docs/pt/docs/tutorial/body-nested-models.md
+++ b/docs/pt/docs/tutorial/body-nested-models.md
@@ -14,35 +14,15 @@ Isso fará com que tags seja uma lista de itens mesmo sem declarar o tipo dos el
Mas o Python tem uma maneira específica de declarar listas com tipos internos ou "parâmetros de tipo":
-### Importe `List` do typing { #import-typings-list }
-
-No Python 3.9 e superior você pode usar a `list` padrão para declarar essas anotações de tipo, como veremos abaixo. 💡
-
-Mas nas versões do Python anteriores à 3.9 (3.6 e superiores), primeiro é necessário importar `List` do módulo padrão `typing` do Python:
-
-{* ../../docs_src/body_nested_models/tutorial002.py hl[1] *}
-
### Declare uma `list` com um parâmetro de tipo { #declare-a-list-with-a-type-parameter }
-Para declarar tipos que têm parâmetros de tipo (tipos internos), como `list`, `dict`, `tuple`:
-
-* Se você estiver em uma versão do Python inferior a 3.9, importe a versão equivalente do módulo `typing`
-* Passe o(s) tipo(s) interno(s) como "parâmetros de tipo" usando colchetes: `[` e `]`
-
-No Python 3.9, seria:
+Para declarar tipos que têm parâmetros de tipo (tipos internos), como `list`, `dict`, `tuple`,
+passe o(s) tipo(s) interno(s) como "parâmetros de tipo" usando colchetes: `[` e `]`
```Python
my_list: list[str]
```
-Em versões do Python anteriores à 3.9, seria:
-
-```Python
-from typing import List
-
-my_list: List[str]
-```
-
Essa é a sintaxe padrão do Python para declarações de tipo.
Use a mesma sintaxe padrão para atributos de modelo com tipos internos.
@@ -178,12 +158,6 @@ Observe como `Offer` tem uma lista de `Item`s, que por sua vez têm uma lista op
Se o valor de primeiro nível do corpo JSON que você espera for um `array` do JSON (uma` lista` do Python), você pode declarar o tipo no parâmetro da função, da mesma forma que nos modelos do Pydantic:
-```Python
-images: List[Image]
-```
-
-ou no Python 3.9 e superior:
-
```Python
images: list[Image]
```
diff --git a/docs/pt/docs/tutorial/body.md b/docs/pt/docs/tutorial/body.md
index ef00b9a7a7..1330f4458f 100644
--- a/docs/pt/docs/tutorial/body.md
+++ b/docs/pt/docs/tutorial/body.md
@@ -161,7 +161,7 @@ Os parâmetros da função serão reconhecidos conforme abaixo:
O FastAPI saberá que o valor de `q` não é obrigatório por causa do valor padrão `= None`.
-O `str | None` (Python 3.10+) ou o `Union` em `Union[str, None]` (Python 3.8+) não é utilizado pelo FastAPI para determinar que o valor não é obrigatório, ele saberá que não é obrigatório porque tem um valor padrão `= None`.
+O `str | None` (Python 3.10+) ou o `Union` em `Union[str, None]` (Python 3.9+) não é utilizado pelo FastAPI para determinar que o valor não é obrigatório, ele saberá que não é obrigatório porque tem um valor padrão `= None`.
Mas adicionar as anotações de tipo permitirá ao seu editor oferecer um suporte melhor e detectar erros.
diff --git a/docs/pt/docs/tutorial/cors.md b/docs/pt/docs/tutorial/cors.md
index c08191db14..0f99db888e 100644
--- a/docs/pt/docs/tutorial/cors.md
+++ b/docs/pt/docs/tutorial/cors.md
@@ -46,7 +46,7 @@ Você também pode especificar se o seu backend permite:
* Métodos HTTP específicos (`POST`, `PUT`) ou todos eles com o curinga `"*"`.
* Cabeçalhos HTTP específicos ou todos eles com o curinga `"*"`.
-{* ../../docs_src/cors/tutorial001.py hl[2,6:11,13:19] *}
+{* ../../docs_src/cors/tutorial001_py39.py hl[2,6:11,13:19] *}
Os parâmetros padrão usados pela implementação `CORSMiddleware` são restritivos por padrão, então você precisará habilitar explicitamente as origens, métodos ou cabeçalhos específicos para que os navegadores tenham permissão para usá-los em um contexto cross domain.
diff --git a/docs/pt/docs/tutorial/debugging.md b/docs/pt/docs/tutorial/debugging.md
index 21d1d527bd..e39c7d1280 100644
--- a/docs/pt/docs/tutorial/debugging.md
+++ b/docs/pt/docs/tutorial/debugging.md
@@ -6,7 +6,7 @@ Você pode conectar o depurador no seu editor, por exemplo, com o Visual Studio
Em sua aplicação FastAPI, importe e execute `uvicorn` diretamente:
-{* ../../docs_src/debugging/tutorial001.py hl[1,15] *}
+{* ../../docs_src/debugging/tutorial001_py39.py hl[1,15] *}
### Sobre `__name__ == "__main__"` { #about-name-main }
diff --git a/docs/pt/docs/tutorial/dependencies/classes-as-dependencies.md b/docs/pt/docs/tutorial/dependencies/classes-as-dependencies.md
index aa26d158f4..c30d0b5f08 100644
--- a/docs/pt/docs/tutorial/dependencies/classes-as-dependencies.md
+++ b/docs/pt/docs/tutorial/dependencies/classes-as-dependencies.md
@@ -101,7 +101,7 @@ O **FastAPI** chama a classe `CommonQueryParams`. Isso cria uma "instância" des
Perceba como escrevemos `CommonQueryParams` duas vezes no código abaixo:
-//// tab | Python 3.8+
+//// tab | Python 3.9+
```Python
commons: Annotated[CommonQueryParams, Depends(CommonQueryParams)]
@@ -109,7 +109,7 @@ commons: Annotated[CommonQueryParams, Depends(CommonQueryParams)]
////
-//// tab | Python 3.8+ non-Annotated
+//// tab | Python 3.9+ non-Annotated
/// tip | Dica
@@ -137,7 +137,7 @@ O último `CommonQueryParams`, em:
Nesse caso, o primeiro `CommonQueryParams`, em:
-//// tab | Python 3.8+
+//// tab | Python 3.9+
```Python
commons: Annotated[CommonQueryParams, ...
@@ -145,7 +145,7 @@ commons: Annotated[CommonQueryParams, ...
////
-//// tab | Python 3.8+ non-Annotated
+//// tab | Python 3.9+ non-Annotated
/// tip | Dica
@@ -163,7 +163,7 @@ commons: CommonQueryParams ...
Na verdade você poderia escrever apenas:
-//// tab | Python 3.8+
+//// tab | Python 3.9+
```Python
commons: Annotated[Any, Depends(CommonQueryParams)]
@@ -171,7 +171,7 @@ commons: Annotated[Any, Depends(CommonQueryParams)]
////
-//// tab | Python 3.8+ non-Annotated
+//// tab | Python 3.9+ non-Annotated
/// tip | Dica
@@ -197,7 +197,7 @@ Mas declarar o tipo é encorajado por que é a forma que o seu editor de texto s
Mas você pode ver que temos uma repetição do código neste exemplo, escrevendo `CommonQueryParams` duas vezes:
-//// tab | Python 3.8+
+//// tab | Python 3.9+
```Python
commons: Annotated[CommonQueryParams, Depends(CommonQueryParams)]
@@ -205,7 +205,7 @@ commons: Annotated[CommonQueryParams, Depends(CommonQueryParams)]
////
-//// tab | Python 3.8+ non-Annotated
+//// tab | Python 3.9+ non-Annotated
/// tip | Dica
@@ -225,7 +225,7 @@ Para esses casos específicos, você pode fazer o seguinte:
Em vez de escrever:
-//// tab | Python 3.8+
+//// tab | Python 3.9+
```Python
commons: Annotated[CommonQueryParams, Depends(CommonQueryParams)]
@@ -233,7 +233,7 @@ commons: Annotated[CommonQueryParams, Depends(CommonQueryParams)]
////
-//// tab | Python 3.8+ non-Annotated
+//// tab | Python 3.9+ non-Annotated
/// tip | Dica
@@ -249,7 +249,7 @@ commons: CommonQueryParams = Depends(CommonQueryParams)
...escreva:
-//// tab | Python 3.8+
+//// tab | Python 3.9+
```Python
commons: Annotated[CommonQueryParams, Depends()]
@@ -257,7 +257,7 @@ commons: Annotated[CommonQueryParams, Depends()]
////
-//// tab | Python 3.8 non-Annotated
+//// tab | Python 3.9+ non-Annotated
/// tip | Dica
diff --git a/docs/pt/docs/tutorial/dependencies/dependencies-with-yield.md b/docs/pt/docs/tutorial/dependencies/dependencies-with-yield.md
index 0aedcfb31e..3678730139 100644
--- a/docs/pt/docs/tutorial/dependencies/dependencies-with-yield.md
+++ b/docs/pt/docs/tutorial/dependencies/dependencies-with-yield.md
@@ -29,15 +29,15 @@ Por exemplo, você poderia utilizar isso para criar uma sessão do banco de dado
Apenas o código anterior à declaração com `yield` e o código contendo essa declaração são executados antes de criar uma resposta:
-{* ../../docs_src/dependencies/tutorial007.py hl[2:4] *}
+{* ../../docs_src/dependencies/tutorial007_py39.py hl[2:4] *}
O valor gerado (yielded) é o que é injetado nas *operações de rota* e outras dependências:
-{* ../../docs_src/dependencies/tutorial007.py hl[4] *}
+{* ../../docs_src/dependencies/tutorial007_py39.py hl[4] *}
O código após o `yield` é executado após a resposta:
-{* ../../docs_src/dependencies/tutorial007.py hl[5:6] *}
+{* ../../docs_src/dependencies/tutorial007_py39.py hl[5:6] *}
/// tip | Dica
@@ -57,7 +57,7 @@ Então, você pode procurar por essa exceção específica dentro da dependênci
Da mesma forma, você pode utilizar `finally` para garantir que os passos de saída são executados, com ou sem exceções.
-{* ../../docs_src/dependencies/tutorial007.py hl[3,5] *}
+{* ../../docs_src/dependencies/tutorial007_py39.py hl[3,5] *}
## Subdependências com `yield` { #sub-dependencies-with-yield }
@@ -269,7 +269,7 @@ Em Python, você pode criar Gerenciadores de Contexto ao descontinuada, mas sem removê-la, passe o parâmetro `deprecated`:
-{* ../../docs_src/path_operation_configuration/tutorial006.py hl[16] *}
+{* ../../docs_src/path_operation_configuration/tutorial006_py39.py hl[16] *}
Ela será claramente marcada como descontinuada nas documentações interativas:
diff --git a/docs/pt/docs/tutorial/path-params-numeric-validations.md b/docs/pt/docs/tutorial/path-params-numeric-validations.md
index cec744fd5e..9f12ba38fe 100644
--- a/docs/pt/docs/tutorial/path-params-numeric-validations.md
+++ b/docs/pt/docs/tutorial/path-params-numeric-validations.md
@@ -54,7 +54,7 @@ Isso não faz diferença para o **FastAPI**. Ele vai detectar os parâmetros pel
Então, você pode declarar sua função assim:
-{* ../../docs_src/path_params_numeric_validations/tutorial002.py hl[7] *}
+{* ../../docs_src/path_params_numeric_validations/tutorial002_py39.py hl[7] *}
Mas tenha em mente que, se você usar `Annotated`, você não terá esse problema, não fará diferença, pois você não está usando valores padrão de parâmetros de função para `Query()` ou `Path()`.
@@ -83,7 +83,7 @@ Passe `*`, como o primeiro parâmetro da função.
O Python não fará nada com esse `*`, mas saberá que todos os parâmetros seguintes devem ser chamados como argumentos nomeados (pares chave-valor), também conhecidos como kwargs. Mesmo que eles não tenham um valor padrão.
-{* ../../docs_src/path_params_numeric_validations/tutorial003.py hl[7] *}
+{* ../../docs_src/path_params_numeric_validations/tutorial003_py39.py hl[7] *}
### Melhor com `Annotated` { #better-with-annotated }
diff --git a/docs/pt/docs/tutorial/path-params.md b/docs/pt/docs/tutorial/path-params.md
index d795d5b2a0..1f47ca6e59 100644
--- a/docs/pt/docs/tutorial/path-params.md
+++ b/docs/pt/docs/tutorial/path-params.md
@@ -2,7 +2,7 @@
Você pode declarar "parâmetros" ou "variáveis" de path com a mesma sintaxe usada por strings de formatação do Python:
-{* ../../docs_src/path_params/tutorial001.py hl[6:7] *}
+{* ../../docs_src/path_params/tutorial001_py39.py hl[6:7] *}
O valor do parâmetro de path `item_id` será passado para a sua função como o argumento `item_id`.
@@ -16,7 +16,7 @@ Então, se você executar este exemplo e acessar Enumerations (ou enums) estão disponíveis no Python desde a versão 3.4.
-///
+{* ../../docs_src/path_params/tutorial005_py39.py hl[1,6:9] *}
/// tip | Dica
Se você está se perguntando, "AlexNet", "ResNet" e "LeNet" são apenas nomes de modelos de Aprendizado de Máquina.
@@ -146,7 +142,7 @@ Se você está se perguntando, "AlexNet", "ResNet" e "LeNet" são apenas nomes d
Em seguida, crie um *parâmetro de path* com anotação de tipo usando a classe enum que você criou (`ModelName`):
-{* ../../docs_src/path_params/tutorial005.py hl[16] *}
+{* ../../docs_src/path_params/tutorial005_py39.py hl[16] *}
### Verifique a documentação { #check-the-docs }
@@ -162,13 +158,13 @@ O valor do *parâmetro de path* será um *membro de enumeração*.
Você pode compará-lo com o *membro de enumeração* no seu enum `ModelName` criado:
-{* ../../docs_src/path_params/tutorial005.py hl[17] *}
+{* ../../docs_src/path_params/tutorial005_py39.py hl[17] *}
#### Obtenha o valor da enumeração { #get-the-enumeration-value }
Você pode obter o valor real (um `str` neste caso) usando `model_name.value`, ou, em geral, `your_enum_member.value`:
-{* ../../docs_src/path_params/tutorial005.py hl[20] *}
+{* ../../docs_src/path_params/tutorial005_py39.py hl[20] *}
/// tip | Dica
Você também pode acessar o valor `"lenet"` com `ModelName.lenet.value`.
@@ -180,7 +176,7 @@ Você pode retornar *membros de enum* da sua *operação de rota*, até mesmo an
Eles serão convertidos para seus valores correspondentes (strings neste caso) antes de serem retornados ao cliente:
-{* ../../docs_src/path_params/tutorial005.py hl[18,21,23] *}
+{* ../../docs_src/path_params/tutorial005_py39.py hl[18,21,23] *}
No seu cliente, você receberá uma resposta JSON como:
@@ -219,7 +215,7 @@ Nesse caso, o nome do parâmetro é `file_path`, e a última parte, `:path`, diz
Então, você pode usá-lo com:
-{* ../../docs_src/path_params/tutorial004.py hl[6] *}
+{* ../../docs_src/path_params/tutorial004_py39.py hl[6] *}
/// tip | Dica
Você pode precisar que o parâmetro contenha `/home/johndoe/myfile.txt`, com uma barra inicial (`/`).
diff --git a/docs/pt/docs/tutorial/query-params-str-validations.md b/docs/pt/docs/tutorial/query-params-str-validations.md
index 948f8ca8fa..5ec1b1b55e 100644
--- a/docs/pt/docs/tutorial/query-params-str-validations.md
+++ b/docs/pt/docs/tutorial/query-params-str-validations.md
@@ -55,7 +55,7 @@ q: str | None = None
////
-//// tab | Python 3.8+
+//// tab | Python 3.9+
```Python
q: Union[str, None] = None
@@ -73,7 +73,7 @@ q: Annotated[str | None] = None
////
-//// tab | Python 3.8+
+//// tab | Python 3.9+
```Python
q: Annotated[Union[str, None]] = None
diff --git a/docs/pt/docs/tutorial/query-params.md b/docs/pt/docs/tutorial/query-params.md
index 5a3fed0359..8826602a25 100644
--- a/docs/pt/docs/tutorial/query-params.md
+++ b/docs/pt/docs/tutorial/query-params.md
@@ -2,7 +2,7 @@
Quando você declara outros parâmetros na função que não fazem parte dos parâmetros da rota, esses parâmetros são automaticamente interpretados como parâmetros de "consulta".
-{* ../../docs_src/query_params/tutorial001.py hl[9] *}
+{* ../../docs_src/query_params/tutorial001_py39.py hl[9] *}
A consulta é o conjunto de pares chave-valor que vai depois de `?` na URL, separado pelo caractere `&`.
@@ -127,7 +127,7 @@ Caso você não queira adicionar um valor específico mas queira apenas torná-l
Porém, quando você quiser fazer com que o parâmetro de consulta seja obrigatório, você pode simplesmente não declarar nenhum valor como padrão.
-{* ../../docs_src/query_params/tutorial005.py hl[6:7] *}
+{* ../../docs_src/query_params/tutorial005_py39.py hl[6:7] *}
Aqui o parâmetro de consulta `needy` é um valor obrigatório, do tipo `str`.
diff --git a/docs/pt/docs/tutorial/response-model.md b/docs/pt/docs/tutorial/response-model.md
index 5958240e4c..dc66bb46c4 100644
--- a/docs/pt/docs/tutorial/response-model.md
+++ b/docs/pt/docs/tutorial/response-model.md
@@ -183,7 +183,7 @@ Pode haver casos em que você retorna algo que não é um campo Pydantic válido
O caso mais comum seria [retornar uma Response diretamente, conforme explicado posteriormente na documentação avançada](../advanced/response-directly.md){.internal-link target=_blank}.
-{* ../../docs_src/response_model/tutorial003_02.py hl[8,10:11] *}
+{* ../../docs_src/response_model/tutorial003_02_py39.py hl[8,10:11] *}
Este caso simples é tratado automaticamente pelo FastAPI porque a anotação do tipo de retorno é a classe (ou uma subclasse de) `Response`.
@@ -193,7 +193,7 @@ E as ferramentas também ficarão felizes porque `RedirectResponse` e `JSO
Você também pode usar uma subclasse de `Response` na anotação de tipo:
-{* ../../docs_src/response_model/tutorial003_03.py hl[8:9] *}
+{* ../../docs_src/response_model/tutorial003_03_py39.py hl[8:9] *}
Isso também funcionará porque `RedirectResponse` é uma subclasse de `Response`, e o FastAPI tratará automaticamente este caso simples.
diff --git a/docs/pt/docs/tutorial/response-status-code.md b/docs/pt/docs/tutorial/response-status-code.md
index 854bf57c9d..756c86dada 100644
--- a/docs/pt/docs/tutorial/response-status-code.md
+++ b/docs/pt/docs/tutorial/response-status-code.md
@@ -8,7 +8,7 @@ Da mesma forma que você pode especificar um modelo de resposta, você também p
* `@app.delete()`
* etc.
-{* ../../docs_src/response_status_code/tutorial001.py hl[6] *}
+{* ../../docs_src/response_status_code/tutorial001_py39.py hl[6] *}
/// note | Nota
@@ -74,7 +74,7 @@ Para saber mais sobre cada código de status e qual código serve para quê, ver
Vamos ver o exemplo anterior novamente:
-{* ../../docs_src/response_status_code/tutorial001.py hl[6] *}
+{* ../../docs_src/response_status_code/tutorial001_py39.py hl[6] *}
`201` é o código de status para "Criado".
@@ -82,7 +82,7 @@ Mas você não precisa memorizar o que cada um desses códigos significa.
Você pode usar as variáveis de conveniência de `fastapi.status`.
-{* ../../docs_src/response_status_code/tutorial002.py hl[1,6] *}
+{* ../../docs_src/response_status_code/tutorial002_py39.py hl[1,6] *}
Eles são apenas uma conveniência, eles possuem o mesmo número, mas dessa forma você pode usar o preenchimento automático do editor para encontrá-los:
diff --git a/docs/pt/docs/tutorial/static-files.md b/docs/pt/docs/tutorial/static-files.md
index 13313a909e..04a02c7f96 100644
--- a/docs/pt/docs/tutorial/static-files.md
+++ b/docs/pt/docs/tutorial/static-files.md
@@ -7,7 +7,7 @@ Você pode servir arquivos estáticos automaticamente a partir de um diretório
* Importe `StaticFiles`.
* "Monte" uma instância de `StaticFiles()` em um path específico.
-{* ../../docs_src/static_files/tutorial001.py hl[2,6] *}
+{* ../../docs_src/static_files/tutorial001_py39.py hl[2,6] *}
/// note | Detalhes Técnicos
diff --git a/docs/pt/docs/tutorial/testing.md b/docs/pt/docs/tutorial/testing.md
index 03f1981a3c..e56edcb8c2 100644
--- a/docs/pt/docs/tutorial/testing.md
+++ b/docs/pt/docs/tutorial/testing.md
@@ -30,7 +30,7 @@ Use o objeto `TestClient` da mesma forma que você faz com `httpx`.
Escreva instruções `assert` simples com as expressões Python padrão que você precisa verificar (novamente, `pytest` padrão).
-{* ../../docs_src/app_testing/tutorial001.py hl[2,12,15:18] *}
+{* ../../docs_src/app_testing/tutorial001_py39.py hl[2,12,15:18] *}
/// tip | Dica
@@ -76,7 +76,7 @@ Digamos que você tenha uma estrutura de arquivo conforme descrito em [Aplicaç
No arquivo `main.py` você tem sua aplicação **FastAPI**:
-{* ../../docs_src/app_testing/main.py *}
+{* ../../docs_src/app_testing/app_a_py39/main.py *}
### Arquivo de teste { #testing-file }
@@ -92,7 +92,7 @@ Então você poderia ter um arquivo `test_main.py` com seus testes. Ele poderia
Como esse arquivo está no mesmo pacote, você pode usar importações relativas para importar o objeto `app` do módulo `main` (`main.py`):
-{* ../../docs_src/app_testing/test_main.py hl[3] *}
+{* ../../docs_src/app_testing/app_a_py39/test_main.py hl[3] *}
...e ter o código para os testes como antes.
diff --git a/docs/pt/llm-prompt.md b/docs/pt/llm-prompt.md
index 01ce4143cb..3f5208e910 100644
--- a/docs/pt/llm-prompt.md
+++ b/docs/pt/llm-prompt.md
@@ -14,15 +14,15 @@ When translating documentation into Portuguese, use neutral and widely understan
For the next terms, use the following translations:
-* «/// check»: «/// check | Verifique»
-* «/// danger»: «/// danger | Cuidado»
-* «/// info»: «/// info | Informação»
-* «/// note | Technical Details»: «/// note | Detalhes Técnicos»
-* «/// info | Very Technical Details»: «/// note | Detalhes Técnicos Avançados»
-* «/// note»: «/// note | Nota»
-* «/// tip»: «/// tip | Dica»
-* «/// warning»: «/// warning | Atenção»
-* «(you should)»: «(você deveria)»
+* /// check: /// check | Verifique
+* /// danger: /// danger | Cuidado
+* /// info: /// info | Informação
+* /// note | Technical Details: /// note | Detalhes Técnicos
+* /// info | Very Technical Details: /// note | Detalhes Técnicos Avançados
+* /// note: /// note | Nota
+* /// tip: /// tip | Dica
+* /// warning: /// warning | Atenção
+* (you should): (você deveria)
* async context manager: gerenciador de contexto assíncrono
* autocomplete: autocompletar
* autocompletion: preenchimento automático
@@ -47,7 +47,7 @@ For the next terms, use the following translations:
* list (as in Python list): list
* Machine Learning: Aprendizado de Máquina
* media type: media type (do not translate to "tipo de mídia")
-* non-Annotated: non-Annotated (do not translate non-Annotated when it comes after a Python version.e.g., “Python 3.8+ non-Annotated”)
+* non-Annotated: non-Annotated (do not translate non-Annotated when it comes after a Python version.e.g., “Python 3.10+ non-Annotated”)
* operation IDs: IDs de operação
* path (as in URL path): path
* path operation: operação de rota
diff --git a/docs/ru/docs/advanced/additional-responses.md b/docs/ru/docs/advanced/additional-responses.md
index 1fc3715e41..fca4f072da 100644
--- a/docs/ru/docs/advanced/additional-responses.md
+++ b/docs/ru/docs/advanced/additional-responses.md
@@ -26,7 +26,7 @@
Например, чтобы объявить ещё один ответ со статус-кодом `404` и Pydantic-моделью `Message`, можно написать:
-{* ../../docs_src/additional_responses/tutorial001.py hl[18,22] *}
+{* ../../docs_src/additional_responses/tutorial001_py39.py hl[18,22] *}
/// note | Примечание
@@ -203,7 +203,7 @@
А также ответ со статус-кодом `200`, который использует ваш `response_model`, но включает пользовательский `example`:
-{* ../../docs_src/additional_responses/tutorial003.py hl[20:31] *}
+{* ../../docs_src/additional_responses/tutorial003_py39.py hl[20:31] *}
Всё это будет объединено и включено в ваш OpenAPI и отображено в документации API:
diff --git a/docs/ru/docs/advanced/async-tests.md b/docs/ru/docs/advanced/async-tests.md
index 5062bc52e7..e689704066 100644
--- a/docs/ru/docs/advanced/async-tests.md
+++ b/docs/ru/docs/advanced/async-tests.md
@@ -32,11 +32,11 @@
Файл `main.py`:
-{* ../../docs_src/async_tests/main.py *}
+{* ../../docs_src/async_tests/app_a_py39/main.py *}
Файл `test_main.py` содержит тесты для `main.py`, теперь он может выглядеть так:
-{* ../../docs_src/async_tests/test_main.py *}
+{* ../../docs_src/async_tests/app_a_py39/test_main.py *}
## Запуск тестов { #run-it }
@@ -56,7 +56,7 @@ $ pytest
Маркер `@pytest.mark.anyio` говорит pytest, что тестовая функция должна быть вызвана асинхронно:
-{* ../../docs_src/async_tests/test_main.py hl[7] *}
+{* ../../docs_src/async_tests/app_a_py39/test_main.py hl[7] *}
/// tip | Подсказка
@@ -66,7 +66,7 @@ $ pytest
Затем мы можем создать `AsyncClient` со ссылкой на приложение и посылать асинхронные запросы, используя `await`.
-{* ../../docs_src/async_tests/test_main.py hl[9:12] *}
+{* ../../docs_src/async_tests/app_a_py39/test_main.py hl[9:12] *}
Это эквивалентно следующему:
diff --git a/docs/ru/docs/advanced/behind-a-proxy.md b/docs/ru/docs/advanced/behind-a-proxy.md
index 7119efe2dc..f78da01a09 100644
--- a/docs/ru/docs/advanced/behind-a-proxy.md
+++ b/docs/ru/docs/advanced/behind-a-proxy.md
@@ -44,7 +44,7 @@ $ fastapi run --forwarded-allow-ips="*"
Например, вы объявили операцию пути `/items/`:
-{* ../../docs_src/behind_a_proxy/tutorial001_01.py hl[6] *}
+{* ../../docs_src/behind_a_proxy/tutorial001_01_py39.py hl[6] *}
Если клиент обратится к `/items`, по умолчанию произойдёт редирект на `/items/`.
@@ -115,7 +115,7 @@ sequenceDiagram
Хотя весь ваш код написан с расчётом, что путь один — `/app`.
-{* ../../docs_src/behind_a_proxy/tutorial001.py hl[6] *}
+{* ../../docs_src/behind_a_proxy/tutorial001_py39.py hl[6] *}
Прокси будет «обрезать» префикс пути на лету перед передачей запроса на сервер приложения (скорее всего Uvicorn, запущенный через FastAPI CLI), поддерживая у вашего приложения иллюзию, что его обслуживают по `/app`, чтобы вам не пришлось менять весь код и добавлять префикс `/api/v1`.
@@ -193,7 +193,7 @@ $ fastapi run main.py --forwarded-allow-ips="*" --root-path /api/v1
Здесь мы добавляем его в сообщение лишь для демонстрации.
-{* ../../docs_src/behind_a_proxy/tutorial001.py hl[8] *}
+{* ../../docs_src/behind_a_proxy/tutorial001_py39.py hl[8] *}
Затем, если вы запустите Uvicorn так:
@@ -220,7 +220,7 @@ $ fastapi run main.py --forwarded-allow-ips="*" --root-path /api/v1
Если нет возможности передать опцию командной строки `--root-path` (или аналог), вы можете указать параметр `root_path` при создании приложения FastAPI:
-{* ../../docs_src/behind_a_proxy/tutorial002.py hl[3] *}
+{* ../../docs_src/behind_a_proxy/tutorial002_py39.py hl[3] *}
Передача `root_path` в `FastAPI` эквивалентна опции командной строки `--root-path` для Uvicorn или Hypercorn.
@@ -400,7 +400,7 @@ $ fastapi run main.py --forwarded-allow-ips="*" --root-path /api/v1
Например:
-{* ../../docs_src/behind_a_proxy/tutorial003.py hl[4:7] *}
+{* ../../docs_src/behind_a_proxy/tutorial003_py39.py hl[4:7] *}
Будет сгенерирована схема OpenAPI примерно такая:
@@ -455,7 +455,7 @@ $ fastapi run main.py --forwarded-allow-ips="*" --root-path /api/v1
Если вы не хотите, чтобы FastAPI добавлял автоматический сервер, используя `root_path`, укажите параметр `root_path_in_servers=False`:
-{* ../../docs_src/behind_a_proxy/tutorial004.py hl[9] *}
+{* ../../docs_src/behind_a_proxy/tutorial004_py39.py hl[9] *}
и тогда этот сервер не будет добавлен в схему OpenAPI.
diff --git a/docs/ru/docs/advanced/custom-response.md b/docs/ru/docs/advanced/custom-response.md
index 2c238bd95b..49550b49ff 100644
--- a/docs/ru/docs/advanced/custom-response.md
+++ b/docs/ru/docs/advanced/custom-response.md
@@ -30,7 +30,7 @@
Но если вы уверены, что содержимое, которое вы возвращаете, **сериализуемо в JSON**, вы можете передать его напрямую в класс ответа и избежать дополнительных накладных расходов, которые FastAPI понёс бы, пропуская возвращаемое содержимое через `jsonable_encoder` перед передачей в класс ответа.
-{* ../../docs_src/custom_response/tutorial001b.py hl[2,7] *}
+{* ../../docs_src/custom_response/tutorial001b_py39.py hl[2,7] *}
/// info | Информация
@@ -55,7 +55,7 @@
- Импортируйте `HTMLResponse`.
- Передайте `HTMLResponse` в параметр `response_class` вашего декоратора операции пути.
-{* ../../docs_src/custom_response/tutorial002.py hl[2,7] *}
+{* ../../docs_src/custom_response/tutorial002_py39.py hl[2,7] *}
/// info | Информация
@@ -73,7 +73,7 @@
Тот же пример сверху, возвращающий `HTMLResponse`, может выглядеть так:
-{* ../../docs_src/custom_response/tutorial003.py hl[2,7,19] *}
+{* ../../docs_src/custom_response/tutorial003_py39.py hl[2,7,19] *}
/// warning | Предупреждение
@@ -97,7 +97,7 @@
Например, это может быть что-то вроде:
-{* ../../docs_src/custom_response/tutorial004.py hl[7,21,23] *}
+{* ../../docs_src/custom_response/tutorial004_py39.py hl[7,21,23] *}
В этом примере функция `generate_html_response()` уже генерирует и возвращает `Response` вместо возврата HTML в `str`.
@@ -136,7 +136,7 @@
FastAPI (фактически Starlette) автоматически добавит заголовок Content-Length. Также будет добавлен заголовок Content-Type, основанный на `media_type` и с добавлением charset для текстовых типов.
-{* ../../docs_src/response_directly/tutorial002.py hl[1,18] *}
+{* ../../docs_src/response_directly/tutorial002_py39.py hl[1,18] *}
### `HTMLResponse` { #htmlresponse }
@@ -146,7 +146,7 @@ FastAPI (фактически Starlette) автоматически добави
Принимает текст или байты и возвращает ответ в виде простого текста.
-{* ../../docs_src/custom_response/tutorial005.py hl[2,7,9] *}
+{* ../../docs_src/custom_response/tutorial005_py39.py hl[2,7,9] *}
### `JSONResponse` { #jsonresponse }
@@ -180,7 +180,7 @@ FastAPI (фактически Starlette) автоматически добави
///
-{* ../../docs_src/custom_response/tutorial001.py hl[2,7] *}
+{* ../../docs_src/custom_response/tutorial001_py39.py hl[2,7] *}
/// tip | Совет
@@ -194,13 +194,13 @@ FastAPI (фактически Starlette) автоматически добави
Вы можете вернуть `RedirectResponse` напрямую:
-{* ../../docs_src/custom_response/tutorial006.py hl[2,9] *}
+{* ../../docs_src/custom_response/tutorial006_py39.py hl[2,9] *}
---
Или можно использовать его в параметре `response_class`:
-{* ../../docs_src/custom_response/tutorial006b.py hl[2,7,9] *}
+{* ../../docs_src/custom_response/tutorial006b_py39.py hl[2,7,9] *}
Если вы сделаете так, то сможете возвращать URL напрямую из своей функции-обработчика пути.
@@ -210,13 +210,13 @@ FastAPI (фактически Starlette) автоматически добави
Также вы можете использовать параметр `status_code` в сочетании с параметром `response_class`:
-{* ../../docs_src/custom_response/tutorial006c.py hl[2,7,9] *}
+{* ../../docs_src/custom_response/tutorial006c_py39.py hl[2,7,9] *}
### `StreamingResponse` { #streamingresponse }
Принимает асинхронный генератор или обычный генератор/итератор и отправляет тело ответа потоково.
-{* ../../docs_src/custom_response/tutorial007.py hl[2,14] *}
+{* ../../docs_src/custom_response/tutorial007_py39.py hl[2,14] *}
#### Использование `StreamingResponse` с файлоподобными объектами { #using-streamingresponse-with-file-like-objects }
@@ -226,7 +226,7 @@ FastAPI (фактически Starlette) автоматически добави
Это включает многие библиотеки для работы с облачным хранилищем, обработки видео и т.д.
-{* ../../docs_src/custom_response/tutorial008.py hl[2,10:12,14] *}
+{* ../../docs_src/custom_response/tutorial008_py39.py hl[2,10:12,14] *}
1. Это функция-генератор. Она является «функцией-генератором», потому что содержит оператор(ы) `yield` внутри.
2. Используя блок `with`, мы гарантируем, что файлоподобный объект будет закрыт после завершения работы функции-генератора. То есть после того, как она закончит отправку ответа.
@@ -255,11 +255,11 @@ FastAPI (фактически Starlette) автоматически добави
Файловые ответы будут содержать соответствующие заголовки `Content-Length`, `Last-Modified` и `ETag`.
-{* ../../docs_src/custom_response/tutorial009.py hl[2,10] *}
+{* ../../docs_src/custom_response/tutorial009_py39.py hl[2,10] *}
Вы также можете использовать параметр `response_class`:
-{* ../../docs_src/custom_response/tutorial009b.py hl[2,8,10] *}
+{* ../../docs_src/custom_response/tutorial009b_py39.py hl[2,8,10] *}
В этом случае вы можете возвращать путь к файлу напрямую из своей функции-обработчика пути.
@@ -273,7 +273,7 @@ FastAPI (фактически Starlette) автоматически добави
Вы могли бы создать `CustomORJSONResponse`. Главное, что вам нужно сделать — реализовать метод `Response.render(content)`, который возвращает содержимое как `bytes`:
-{* ../../docs_src/custom_response/tutorial009c.py hl[9:14,17] *}
+{* ../../docs_src/custom_response/tutorial009c_py39.py hl[9:14,17] *}
Теперь вместо того, чтобы возвращать:
@@ -299,7 +299,7 @@ FastAPI (фактически Starlette) автоматически добави
В примере ниже **FastAPI** будет использовать `ORJSONResponse` по умолчанию во всех операциях пути вместо `JSONResponse`.
-{* ../../docs_src/custom_response/tutorial010.py hl[2,4] *}
+{* ../../docs_src/custom_response/tutorial010_py39.py hl[2,4] *}
/// tip | Совет
diff --git a/docs/ru/docs/advanced/dataclasses.md b/docs/ru/docs/advanced/dataclasses.md
index c37ce30236..b3ced37c1e 100644
--- a/docs/ru/docs/advanced/dataclasses.md
+++ b/docs/ru/docs/advanced/dataclasses.md
@@ -4,7 +4,7 @@ FastAPI построен поверх **Pydantic**, и я показывал в
Но FastAPI также поддерживает использование `dataclasses` тем же способом:
-{* ../../docs_src/dataclasses/tutorial001_py310.py hl[1,6:11,18:19] *}
+{* ../../docs_src/dataclasses_/tutorial001_py310.py hl[1,6:11,18:19] *}
Это по-прежнему поддерживается благодаря **Pydantic**, так как в нём есть встроенная поддержка `dataclasses`.
@@ -32,7 +32,7 @@ FastAPI построен поверх **Pydantic**, и я показывал в
Вы также можете использовать `dataclasses` в параметре `response_model`:
-{* ../../docs_src/dataclasses/tutorial002_py310.py hl[1,6:12,18] *}
+{* ../../docs_src/dataclasses_/tutorial002_py310.py hl[1,6:12,18] *}
Этот dataclass будет автоматически преобразован в Pydantic dataclass.
@@ -48,7 +48,7 @@ FastAPI построен поверх **Pydantic**, и я показывал в
В таком случае вы можете просто заменить стандартные `dataclasses` на `pydantic.dataclasses`, которая является полностью совместимой заменой (drop-in replacement):
-{* ../../docs_src/dataclasses/tutorial003_py310.py hl[1,4,7:10,13:16,22:24,27] *}
+{* ../../docs_src/dataclasses_/tutorial003_py310.py hl[1,4,7:10,13:16,22:24,27] *}
1. Мы по-прежнему импортируем `field` из стандартных `dataclasses`.
diff --git a/docs/ru/docs/advanced/events.md b/docs/ru/docs/advanced/events.md
index 20d1df98a9..db73d9094e 100644
--- a/docs/ru/docs/advanced/events.md
+++ b/docs/ru/docs/advanced/events.md
@@ -30,7 +30,7 @@
Мы создаём асинхронную функцию `lifespan()` с `yield` примерно так:
-{* ../../docs_src/events/tutorial003.py hl[16,19] *}
+{* ../../docs_src/events/tutorial003_py39.py hl[16,19] *}
Здесь мы симулируем дорогую операцию startup по загрузке модели, помещая (фиктивную) функцию модели в словарь с моделями Машинного обучения до `yield`. Этот код будет выполнен до того, как приложение начнет принимать запросы, во время startup.
@@ -48,7 +48,7 @@
Первое, на что стоит обратить внимание, — мы определяем асинхронную функцию с `yield`. Это очень похоже на Зависимости с `yield`.
-{* ../../docs_src/events/tutorial003.py hl[14:19] *}
+{* ../../docs_src/events/tutorial003_py39.py hl[14:19] *}
Первая часть функции, до `yield`, будет выполнена до запуска приложения.
@@ -60,7 +60,7 @@
Это превращает функцию в «асинхронный менеджер контекста».
-{* ../../docs_src/events/tutorial003.py hl[1,13] *}
+{* ../../docs_src/events/tutorial003_py39.py hl[1,13] *}
Менеджер контекста в Python — это то, что можно использовать в операторе `with`. Например, `open()` можно использовать как менеджер контекста:
@@ -82,7 +82,7 @@ async with lifespan(app):
Параметр `lifespan` приложения `FastAPI` принимает асинхронный менеджер контекста, поэтому мы можем передать ему наш новый асинхронный менеджер контекста `lifespan`.
-{* ../../docs_src/events/tutorial003.py hl[22] *}
+{* ../../docs_src/events/tutorial003_py39.py hl[22] *}
## Альтернативные события (устаревшие) { #alternative-events-deprecated }
@@ -104,7 +104,7 @@ async with lifespan(app):
Чтобы добавить функцию, которую нужно запустить до старта приложения, объявите её как обработчик события `"startup"`:
-{* ../../docs_src/events/tutorial001.py hl[8] *}
+{* ../../docs_src/events/tutorial001_py39.py hl[8] *}
В этом случае функция-обработчик события `startup` инициализирует «базу данных» items (это просто `dict`) некоторыми значениями.
@@ -116,7 +116,7 @@ async with lifespan(app):
Чтобы добавить функцию, которую нужно запустить при завершении работы приложения, объявите её как обработчик события `"shutdown"`:
-{* ../../docs_src/events/tutorial002.py hl[6] *}
+{* ../../docs_src/events/tutorial002_py39.py hl[6] *}
Здесь функция-обработчик события `shutdown` запишет строку текста `"Application shutdown"` в файл `log.txt`.
diff --git a/docs/ru/docs/advanced/generate-clients.md b/docs/ru/docs/advanced/generate-clients.md
index ee52412c6d..00bdd31fe8 100644
--- a/docs/ru/docs/advanced/generate-clients.md
+++ b/docs/ru/docs/advanced/generate-clients.md
@@ -167,7 +167,7 @@ FastAPI использует **уникальный ID** для каждой *о
Мы можем скачать OpenAPI JSON в файл `openapi.json`, а затем **убрать этот префикс‑тег** таким скриптом:
-{* ../../docs_src/generate_clients/tutorial004.py *}
+{* ../../docs_src/generate_clients/tutorial004_py39.py *}
//// tab | Node.js
diff --git a/docs/ru/docs/advanced/middleware.md b/docs/ru/docs/advanced/middleware.md
index 82c86b2317..5ebe010782 100644
--- a/docs/ru/docs/advanced/middleware.md
+++ b/docs/ru/docs/advanced/middleware.md
@@ -57,13 +57,13 @@ app.add_middleware(UnicornMiddleware, some_config="rainbow")
Любой входящий запрос по `http` или `ws` будет перенаправлен на безопасную схему.
-{* ../../docs_src/advanced_middleware/tutorial001.py hl[2,6] *}
+{* ../../docs_src/advanced_middleware/tutorial001_py39.py hl[2,6] *}
## `TrustedHostMiddleware` { #trustedhostmiddleware }
Гарантирует, что во всех входящих запросах корректно установлен `Host`‑заголовок, чтобы защититься от атак на HTTP‑заголовок Host.
-{* ../../docs_src/advanced_middleware/tutorial002.py hl[2,6:8] *}
+{* ../../docs_src/advanced_middleware/tutorial002_py39.py hl[2,6:8] *}
Поддерживаются следующие аргументы:
@@ -78,7 +78,7 @@ app.add_middleware(UnicornMiddleware, some_config="rainbow")
Это middleware обрабатывает как обычные, так и потоковые ответы.
-{* ../../docs_src/advanced_middleware/tutorial003.py hl[2,6] *}
+{* ../../docs_src/advanced_middleware/tutorial003_py39.py hl[2,6] *}
Поддерживаются следующие аргументы:
diff --git a/docs/ru/docs/advanced/openapi-webhooks.md b/docs/ru/docs/advanced/openapi-webhooks.md
index d38cf315f7..3a2b9fff74 100644
--- a/docs/ru/docs/advanced/openapi-webhooks.md
+++ b/docs/ru/docs/advanced/openapi-webhooks.md
@@ -32,7 +32,7 @@
При создании приложения на **FastAPI** есть атрибут `webhooks`, с помощью которого можно объявлять вебхуки так же, как вы объявляете операции пути (обработчики пути), например с `@app.webhooks.post()`.
-{* ../../docs_src/openapi_webhooks/tutorial001.py hl[9:13,36:53] *}
+{* ../../docs_src/openapi_webhooks/tutorial001_py39.py hl[9:13,36:53] *}
Определенные вами вебхуки попадут в схему **OpenAPI** и в автоматический **интерфейс документации**.
diff --git a/docs/ru/docs/advanced/path-operation-advanced-configuration.md b/docs/ru/docs/advanced/path-operation-advanced-configuration.md
index 78a16a5583..eaf9ad0528 100644
--- a/docs/ru/docs/advanced/path-operation-advanced-configuration.md
+++ b/docs/ru/docs/advanced/path-operation-advanced-configuration.md
@@ -12,7 +12,7 @@
Нужно убедиться, что он уникален для каждой операции.
-{* ../../docs_src/path_operation_advanced_configuration/tutorial001.py hl[6] *}
+{* ../../docs_src/path_operation_advanced_configuration/tutorial001_py39.py hl[6] *}
### Использование имени функции-обработчика пути как operationId { #using-the-path-operation-function-name-as-the-operationid }
@@ -20,7 +20,7 @@
Делать это следует после добавления всех *операций пути*.
-{* ../../docs_src/path_operation_advanced_configuration/tutorial002.py hl[2, 12:21, 24] *}
+{* ../../docs_src/path_operation_advanced_configuration/tutorial002_py39.py hl[2, 12:21, 24] *}
/// tip | Совет
@@ -40,7 +40,7 @@
Чтобы исключить *операцию пути* из генерируемой схемы OpenAPI (а значит, и из автоматической документации), используйте параметр `include_in_schema` и установите его в `False`:
-{* ../../docs_src/path_operation_advanced_configuration/tutorial003.py hl[6] *}
+{* ../../docs_src/path_operation_advanced_configuration/tutorial003_py39.py hl[6] *}
## Расширенное описание из docstring { #advanced-description-from-docstring }
@@ -92,7 +92,7 @@
`openapi_extra` может пригодиться, например, чтобы объявить [Расширения OpenAPI](https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.3.md#specificationExtensions):
-{* ../../docs_src/path_operation_advanced_configuration/tutorial005.py hl[6] *}
+{* ../../docs_src/path_operation_advanced_configuration/tutorial005_py39.py hl[6] *}
Если вы откроете автоматическую документацию API, ваше расширение появится внизу страницы конкретной *операции пути*.
@@ -139,7 +139,7 @@
Это можно сделать с помощью `openapi_extra`:
-{* ../../docs_src/path_operation_advanced_configuration/tutorial006.py hl[19:36, 39:40] *}
+{* ../../docs_src/path_operation_advanced_configuration/tutorial006_py39.py hl[19:36, 39:40] *}
В этом примере мы не объявляли никакую Pydantic-модель. Фактически тело запроса даже не распарсено как JSON, оно читается напрямую как `bytes`, а функция `magic_data_reader()` будет отвечать за его парсинг каким-то способом.
diff --git a/docs/ru/docs/advanced/response-change-status-code.md b/docs/ru/docs/advanced/response-change-status-code.md
index e9e1c9470f..85d9050ffc 100644
--- a/docs/ru/docs/advanced/response-change-status-code.md
+++ b/docs/ru/docs/advanced/response-change-status-code.md
@@ -20,7 +20,7 @@
И затем вы можете установить `status_code` в этом *временном* объекте ответа.
-{* ../../docs_src/response_change_status_code/tutorial001.py hl[1,9,12] *}
+{* ../../docs_src/response_change_status_code/tutorial001_py39.py hl[1,9,12] *}
После этого вы можете вернуть любой объект, который вам нужен, как обычно (`dict`, модель базы данных и т.д.).
diff --git a/docs/ru/docs/advanced/response-cookies.md b/docs/ru/docs/advanced/response-cookies.md
index 9319aba6e2..2872d6c0ad 100644
--- a/docs/ru/docs/advanced/response-cookies.md
+++ b/docs/ru/docs/advanced/response-cookies.md
@@ -6,7 +6,7 @@
Затем установить cookies в этом временном объекте ответа.
-{* ../../docs_src/response_cookies/tutorial002.py hl[1, 8:9] *}
+{* ../../docs_src/response_cookies/tutorial002_py39.py hl[1, 8:9] *}
После этого можно вернуть любой объект, как и раньше (например, `dict`, объект модели базы данных и так далее).
@@ -24,7 +24,7 @@
Затем установите cookies и верните этот объект:
-{* ../../docs_src/response_cookies/tutorial001.py hl[10:12] *}
+{* ../../docs_src/response_cookies/tutorial001_py39.py hl[10:12] *}
/// tip | Совет
diff --git a/docs/ru/docs/advanced/response-directly.md b/docs/ru/docs/advanced/response-directly.md
index 3c10633e91..b452810714 100644
--- a/docs/ru/docs/advanced/response-directly.md
+++ b/docs/ru/docs/advanced/response-directly.md
@@ -54,7 +54,7 @@
Вы можете поместить ваш XML-контент в строку, поместить её в `Response` и вернуть:
-{* ../../docs_src/response_directly/tutorial002.py hl[1,18] *}
+{* ../../docs_src/response_directly/tutorial002_py39.py hl[1,18] *}
## Примечания { #notes }
diff --git a/docs/ru/docs/advanced/response-headers.md b/docs/ru/docs/advanced/response-headers.md
index 1c9360b31d..8f24f05b07 100644
--- a/docs/ru/docs/advanced/response-headers.md
+++ b/docs/ru/docs/advanced/response-headers.md
@@ -6,7 +6,7 @@
А затем вы можете устанавливать HTTP-заголовки в этом *временном* объекте ответа.
-{* ../../docs_src/response_headers/tutorial002.py hl[1, 7:8] *}
+{* ../../docs_src/response_headers/tutorial002_py39.py hl[1, 7:8] *}
После этого вы можете вернуть любой нужный объект, как обычно (например, `dict`, модель из базы данных и т.д.).
@@ -22,7 +22,7 @@
Создайте ответ, как описано в [Вернуть Response напрямую](response-directly.md){.internal-link target=_blank}, и передайте заголовки как дополнительный параметр:
-{* ../../docs_src/response_headers/tutorial001.py hl[10:12] *}
+{* ../../docs_src/response_headers/tutorial001_py39.py hl[10:12] *}
/// note | Технические детали
diff --git a/docs/ru/docs/advanced/settings.md b/docs/ru/docs/advanced/settings.md
index 0ef46fb13c..b96ee44a3a 100644
--- a/docs/ru/docs/advanced/settings.md
+++ b/docs/ru/docs/advanced/settings.md
@@ -62,7 +62,7 @@ $ pip install "fastapi[all]"
//// tab | Pydantic v2
-{* ../../docs_src/settings/tutorial001.py hl[2,5:8,11] *}
+{* ../../docs_src/settings/tutorial001_py39.py hl[2,5:8,11] *}
////
@@ -74,7 +74,7 @@ $ pip install "fastapi[all]"
///
-{* ../../docs_src/settings/tutorial001_pv1.py hl[2,5:8,11] *}
+{* ../../docs_src/settings/tutorial001_pv1_py39.py hl[2,5:8,11] *}
////
@@ -92,7 +92,7 @@ $ pip install "fastapi[all]"
Затем вы можете использовать новый объект `settings` в вашем приложении:
-{* ../../docs_src/settings/tutorial001.py hl[18:20] *}
+{* ../../docs_src/settings/tutorial001_py39.py hl[18:20] *}
### Запуск сервера { #run-the-server }
@@ -126,11 +126,11 @@ $ ADMIN_EMAIL="deadpool@example.com" APP_NAME="ChimichangApp" fastapi run main.p
Например, у вас может быть файл `config.py` со следующим содержимым:
-{* ../../docs_src/settings/app01/config.py *}
+{* ../../docs_src/settings/app01_py39/config.py *}
А затем использовать его в файле `main.py`:
-{* ../../docs_src/settings/app01/main.py hl[3,11:13] *}
+{* ../../docs_src/settings/app01_py39/main.py hl[3,11:13] *}
/// tip | Совет
diff --git a/docs/ru/docs/advanced/sub-applications.md b/docs/ru/docs/advanced/sub-applications.md
index 3464f17040..fa5a683f45 100644
--- a/docs/ru/docs/advanced/sub-applications.md
+++ b/docs/ru/docs/advanced/sub-applications.md
@@ -10,7 +10,7 @@
Сначала создайте основное, верхнего уровня, приложение **FastAPI** и его *операции пути*:
-{* ../../docs_src/sub_applications/tutorial001.py hl[3, 6:8] *}
+{* ../../docs_src/sub_applications/tutorial001_py39.py hl[3, 6:8] *}
### Подприложение { #sub-application }
@@ -18,7 +18,7 @@
Это подприложение — обычное стандартное приложение FastAPI, но именно оно будет «смонтировано»:
-{* ../../docs_src/sub_applications/tutorial001.py hl[11, 14:16] *}
+{* ../../docs_src/sub_applications/tutorial001_py39.py hl[11, 14:16] *}
### Смонтируйте подприложение { #mount-the-sub-application }
@@ -26,7 +26,7 @@
В этом случае оно будет смонтировано по пути `/subapi`:
-{* ../../docs_src/sub_applications/tutorial001.py hl[11, 19] *}
+{* ../../docs_src/sub_applications/tutorial001_py39.py hl[11, 19] *}
### Проверьте автоматическую документацию API { #check-the-automatic-api-docs }
diff --git a/docs/ru/docs/advanced/templates.md b/docs/ru/docs/advanced/templates.md
index 204e887605..460e2e4660 100644
--- a/docs/ru/docs/advanced/templates.md
+++ b/docs/ru/docs/advanced/templates.md
@@ -27,7 +27,7 @@ $ pip install jinja2
- Объявите параметр `Request` в *операции пути*, которая будет возвращать шаблон.
- Используйте созданный `templates`, чтобы отрендерить и вернуть `TemplateResponse`; передайте имя шаблона, объект `request` и словарь «context» с парами ключ-значение для использования внутри шаблона Jinja2.
-{* ../../docs_src/templates/tutorial001.py hl[4,11,15:18] *}
+{* ../../docs_src/templates/tutorial001_py39.py hl[4,11,15:18] *}
/// note | Примечание
diff --git a/docs/ru/docs/advanced/testing-events.md b/docs/ru/docs/advanced/testing-events.md
index e0ec774399..82caea845b 100644
--- a/docs/ru/docs/advanced/testing-events.md
+++ b/docs/ru/docs/advanced/testing-events.md
@@ -2,11 +2,11 @@
Если вам нужно, чтобы `lifespan` выполнялся в ваших тестах, вы можете использовать `TestClient` вместе с оператором `with`:
-{* ../../docs_src/app_testing/tutorial004.py hl[9:15,18,27:28,30:32,41:43] *}
+{* ../../docs_src/app_testing/tutorial004_py39.py hl[9:15,18,27:28,30:32,41:43] *}
Вы можете узнать больше подробностей в статье [Запуск lifespan в тестах на официальном сайте документации Starlette.](https://www.starlette.dev/lifespan/#running-lifespan-in-tests)
Для устаревших событий `startup` и `shutdown` вы можете использовать `TestClient` следующим образом:
-{* ../../docs_src/app_testing/tutorial003.py hl[9:12,20:24] *}
+{* ../../docs_src/app_testing/tutorial003_py39.py hl[9:12,20:24] *}
diff --git a/docs/ru/docs/advanced/testing-websockets.md b/docs/ru/docs/advanced/testing-websockets.md
index e840a03f28..b6626679e4 100644
--- a/docs/ru/docs/advanced/testing-websockets.md
+++ b/docs/ru/docs/advanced/testing-websockets.md
@@ -4,7 +4,7 @@
Для этого используйте `TestClient` с менеджером контекста `with`, подключаясь к WebSocket:
-{* ../../docs_src/app_testing/tutorial002.py hl[27:31] *}
+{* ../../docs_src/app_testing/tutorial002_py39.py hl[27:31] *}
/// note | Примечание
diff --git a/docs/ru/docs/advanced/using-request-directly.md b/docs/ru/docs/advanced/using-request-directly.md
index b922216105..cdf500c0e2 100644
--- a/docs/ru/docs/advanced/using-request-directly.md
+++ b/docs/ru/docs/advanced/using-request-directly.md
@@ -29,7 +29,7 @@
Для этого нужно обратиться к запросу напрямую.
-{* ../../docs_src/using_request_directly/tutorial001.py hl[1,7:8] *}
+{* ../../docs_src/using_request_directly/tutorial001_py39.py hl[1,7:8] *}
Если объявить параметр *функции-обработчика пути* с типом `Request`, **FastAPI** поймёт, что нужно передать объект `Request` в этот параметр.
diff --git a/docs/ru/docs/advanced/websockets.md b/docs/ru/docs/advanced/websockets.md
index f26185bea5..fa5e4738eb 100644
--- a/docs/ru/docs/advanced/websockets.md
+++ b/docs/ru/docs/advanced/websockets.md
@@ -38,13 +38,13 @@ $ pip install websockets
Для примера нам нужен наиболее простой способ, который позволит сосредоточиться на серверной части веб‑сокетов и получить рабочий код:
-{* ../../docs_src/websockets/tutorial001.py hl[2,6:38,41:43] *}
+{* ../../docs_src/websockets/tutorial001_py39.py hl[2,6:38,41:43] *}
## Создание `websocket` { #create-a-websocket }
Создайте `websocket` в своем **FastAPI** приложении:
-{* ../../docs_src/websockets/tutorial001.py hl[1,46:47] *}
+{* ../../docs_src/websockets/tutorial001_py39.py hl[1,46:47] *}
/// note | Технические детали
@@ -58,7 +58,7 @@ $ pip install websockets
Через эндпоинт веб-сокета вы можете получать и отправлять сообщения.
-{* ../../docs_src/websockets/tutorial001.py hl[48:52] *}
+{* ../../docs_src/websockets/tutorial001_py39.py hl[48:52] *}
Вы можете получать и отправлять двоичные, текстовые и JSON данные.
diff --git a/docs/ru/docs/advanced/wsgi.md b/docs/ru/docs/advanced/wsgi.md
index 1c5bf0a626..64d7c7a289 100644
--- a/docs/ru/docs/advanced/wsgi.md
+++ b/docs/ru/docs/advanced/wsgi.md
@@ -12,7 +12,7 @@
После этого смонтируйте его на путь.
-{* ../../docs_src/wsgi/tutorial001.py hl[2:3,3] *}
+{* ../../docs_src/wsgi/tutorial001_py39.py hl[2:3,3] *}
## Проверьте { #check-it }
diff --git a/docs/ru/docs/how-to/conditional-openapi.md b/docs/ru/docs/how-to/conditional-openapi.md
index dc987ae26b..d0845b91e2 100644
--- a/docs/ru/docs/how-to/conditional-openapi.md
+++ b/docs/ru/docs/how-to/conditional-openapi.md
@@ -29,7 +29,7 @@
Например:
-{* ../../docs_src/conditional_openapi/tutorial001.py hl[6,11] *}
+{* ../../docs_src/conditional_openapi/tutorial001_py39.py hl[6,11] *}
Здесь мы объявляем настройку `openapi_url` с тем же значением по умолчанию — `"/openapi.json"`.
diff --git a/docs/ru/docs/how-to/configure-swagger-ui.md b/docs/ru/docs/how-to/configure-swagger-ui.md
index 9d104423d7..b3b1c1ba62 100644
--- a/docs/ru/docs/how-to/configure-swagger-ui.md
+++ b/docs/ru/docs/how-to/configure-swagger-ui.md
@@ -18,7 +18,7 @@ FastAPI преобразует эти настройки в **JSON**, чтобы
Но вы можете отключить её, установив `syntaxHighlight` в `False`:
-{* ../../docs_src/configure_swagger_ui/tutorial001.py hl[3] *}
+{* ../../docs_src/configure_swagger_ui/tutorial001_py39.py hl[3] *}
…и после этого Swagger UI больше не будет показывать подсветку синтаксиса:
@@ -28,7 +28,7 @@ FastAPI преобразует эти настройки в **JSON**, чтобы
Аналогично вы можете задать тему подсветки синтаксиса с ключом "syntaxHighlight.theme" (обратите внимание, что посередине стоит точка):
-{* ../../docs_src/configure_swagger_ui/tutorial002.py hl[3] *}
+{* ../../docs_src/configure_swagger_ui/tutorial002_py39.py hl[3] *}
Эта настройка изменит цветовую тему подсветки синтаксиса:
@@ -46,7 +46,7 @@ FastAPI включает некоторые параметры конфигур
Например, чтобы отключить `deepLinking`, можно передать такие настройки в `swagger_ui_parameters`:
-{* ../../docs_src/configure_swagger_ui/tutorial003.py hl[3] *}
+{* ../../docs_src/configure_swagger_ui/tutorial003_py39.py hl[3] *}
## Другие параметры Swagger UI { #other-swagger-ui-parameters }
diff --git a/docs/ru/docs/how-to/custom-docs-ui-assets.md b/docs/ru/docs/how-to/custom-docs-ui-assets.md
index c07a9695b9..f524911e65 100644
--- a/docs/ru/docs/how-to/custom-docs-ui-assets.md
+++ b/docs/ru/docs/how-to/custom-docs-ui-assets.md
@@ -18,7 +18,7 @@
Чтобы отключить её, установите их URL в значение `None` при создании вашего приложения `FastAPI`:
-{* ../../docs_src/custom_docs_ui/tutorial001.py hl[8] *}
+{* ../../docs_src/custom_docs_ui/tutorial001_py39.py hl[8] *}
### Подключить пользовательскую документацию { #include-the-custom-docs }
@@ -34,7 +34,7 @@
Аналогично и для ReDoc...
-{* ../../docs_src/custom_docs_ui/tutorial001.py hl[2:6,11:19,22:24,27:33] *}
+{* ../../docs_src/custom_docs_ui/tutorial001_py39.py hl[2:6,11:19,22:24,27:33] *}
/// tip | Совет
@@ -50,7 +50,7 @@ Swagger UI сделает это за вас «за кулисами», но д
Чтобы убедиться, что всё работает, создайте *операцию пути*:
-{* ../../docs_src/custom_docs_ui/tutorial001.py hl[36:38] *}
+{* ../../docs_src/custom_docs_ui/tutorial001_py39.py hl[36:38] *}
### Тестирование { #test-it }
@@ -118,7 +118,7 @@ Swagger UI сделает это за вас «за кулисами», но д
* Импортируйте `StaticFiles`.
* Смонтируйте экземпляр `StaticFiles()` в определённый путь.
-{* ../../docs_src/custom_docs_ui/tutorial002.py hl[7,11] *}
+{* ../../docs_src/custom_docs_ui/tutorial002_py39.py hl[7,11] *}
### Протестируйте статические файлы { #test-the-static-files }
@@ -144,7 +144,7 @@ Swagger UI сделает это за вас «за кулисами», но д
Чтобы отключить её, установите их URL в значение `None` при создании вашего приложения `FastAPI`:
-{* ../../docs_src/custom_docs_ui/tutorial002.py hl[9] *}
+{* ../../docs_src/custom_docs_ui/tutorial002_py39.py hl[9] *}
### Подключить пользовательскую документацию со статическими файлами { #include-the-custom-docs-for-static-files }
@@ -160,7 +160,7 @@ Swagger UI сделает это за вас «за кулисами», но д
Аналогично и для ReDoc...
-{* ../../docs_src/custom_docs_ui/tutorial002.py hl[2:6,14:22,25:27,30:36] *}
+{* ../../docs_src/custom_docs_ui/tutorial002_py39.py hl[2:6,14:22,25:27,30:36] *}
/// tip | Совет
@@ -176,7 +176,7 @@ Swagger UI сделает это за вас «за кулисами», но д
Чтобы убедиться, что всё работает, создайте *операцию пути*:
-{* ../../docs_src/custom_docs_ui/tutorial002.py hl[39:41] *}
+{* ../../docs_src/custom_docs_ui/tutorial002_py39.py hl[39:41] *}
### Тестирование UI со статическими файлами { #test-static-files-ui }
diff --git a/docs/ru/docs/how-to/extending-openapi.md b/docs/ru/docs/how-to/extending-openapi.md
index 2897fb89ba..1d69cbdb3a 100644
--- a/docs/ru/docs/how-to/extending-openapi.md
+++ b/docs/ru/docs/how-to/extending-openapi.md
@@ -43,19 +43,19 @@
Сначала напишите приложение **FastAPI** как обычно:
-{* ../../docs_src/extending_openapi/tutorial001.py hl[1,4,7:9] *}
+{* ../../docs_src/extending_openapi/tutorial001_py39.py hl[1,4,7:9] *}
### Сгенерируйте схему OpenAPI { #generate-the-openapi-schema }
Затем используйте ту же вспомогательную функцию для генерации схемы OpenAPI внутри функции `custom_openapi()`:
-{* ../../docs_src/extending_openapi/tutorial001.py hl[2,15:21] *}
+{* ../../docs_src/extending_openapi/tutorial001_py39.py hl[2,15:21] *}
### Измените схему OpenAPI { #modify-the-openapi-schema }
Теперь можно добавить расширение ReDoc, добавив кастомный `x-logo` в «объект» `info` в схеме OpenAPI:
-{* ../../docs_src/extending_openapi/tutorial001.py hl[22:24] *}
+{* ../../docs_src/extending_openapi/tutorial001_py39.py hl[22:24] *}
### Кэшируйте схему OpenAPI { #cache-the-openapi-schema }
@@ -65,13 +65,13 @@
Она будет создана один раз, а затем тот же кэшированный вариант будет использоваться для последующих запросов.
-{* ../../docs_src/extending_openapi/tutorial001.py hl[13:14,25:26] *}
+{* ../../docs_src/extending_openapi/tutorial001_py39.py hl[13:14,25:26] *}
### Переопределите метод { #override-the-method }
Теперь вы можете заменить метод `.openapi()` на вашу новую функцию.
-{* ../../docs_src/extending_openapi/tutorial001.py hl[29] *}
+{* ../../docs_src/extending_openapi/tutorial001_py39.py hl[29] *}
### Проверьте { #check-it }
diff --git a/docs/ru/docs/how-to/graphql.md b/docs/ru/docs/how-to/graphql.md
index 9ed6d95ca1..50c321e7dd 100644
--- a/docs/ru/docs/how-to/graphql.md
+++ b/docs/ru/docs/how-to/graphql.md
@@ -35,7 +35,7 @@
Вот небольшой пример того, как можно интегрировать Strawberry с FastAPI:
-{* ../../docs_src/graphql/tutorial001.py hl[3,22,25] *}
+{* ../../docs_src/graphql_/tutorial001_py39.py hl[3,22,25] *}
Подробнее о Strawberry можно узнать в документации Strawberry.
diff --git a/docs/ru/docs/python-types.md b/docs/ru/docs/python-types.md
index 84a901f547..ae4a1e2b79 100644
--- a/docs/ru/docs/python-types.md
+++ b/docs/ru/docs/python-types.md
@@ -22,7 +22,7 @@ Python поддерживает необязательные «подсказк
Давайте начнем с простого примера:
-{* ../../docs_src/python_types/tutorial001.py *}
+{* ../../docs_src/python_types/tutorial001_py39.py *}
Вызов этой программы выводит:
@@ -36,7 +36,7 @@ John Doe
* Преобразует первую букву каждого значения в верхний регистр с помощью `title()`.
* Соединяет их пробелом посередине.
-{* ../../docs_src/python_types/tutorial001.py hl[2] *}
+{* ../../docs_src/python_types/tutorial001_py39.py hl[2] *}
### Отредактируем пример { #edit-it }
@@ -78,7 +78,7 @@ John Doe
Это и есть «подсказки типов»:
-{* ../../docs_src/python_types/tutorial002.py hl[1] *}
+{* ../../docs_src/python_types/tutorial002_py39.py hl[1] *}
Это не то же самое, что объявление значений по умолчанию, как, например:
@@ -106,7 +106,7 @@ John Doe
Посмотрите на эту функцию — у неё уже есть подсказки типов:
-{* ../../docs_src/python_types/tutorial003.py hl[1] *}
+{* ../../docs_src/python_types/tutorial003_py39.py hl[1] *}
Так как редактор кода знает типы переменных, вы получаете не только автозавершение, но и проверки ошибок:
@@ -114,7 +114,7 @@ John Doe
Теперь вы знаете, что нужно исправить — преобразовать `age` в строку с помощью `str(age)`:
-{* ../../docs_src/python_types/tutorial004.py hl[2] *}
+{* ../../docs_src/python_types/tutorial004_py39.py hl[2] *}
## Объявление типов { #declaring-types }
@@ -133,7 +133,7 @@ John Doe
* `bool`
* `bytes`
-{* ../../docs_src/python_types/tutorial005.py hl[1] *}
+{* ../../docs_src/python_types/tutorial005_py39.py hl[1] *}
### Generic-типы с параметрами типов { #generic-types-with-type-parameters }
@@ -161,56 +161,24 @@ John Doe
Например, давайте определим переменную как `list` из `str`.
-//// tab | Python 3.9+
-
Объявите переменную с тем же синтаксисом двоеточия (`:`).
В качестве типа укажите `list`.
Так как список — это тип, содержащий внутренние типы, укажите их в квадратных скобках:
-```Python hl_lines="1"
-{!> ../../docs_src/python_types/tutorial006_py39.py!}
-```
-
-////
-
-//// tab | Python 3.8+
-
-Из `typing` импортируйте `List` (с заглавной `L`):
-
-```Python hl_lines="1"
-{!> ../../docs_src/python_types/tutorial006.py!}
-```
-
-Объявите переменную с тем же синтаксисом двоеточия (`:`).
-
-В качестве типа используйте `List`, который вы импортировали из `typing`.
-
-Так как список — это тип, содержащий внутренние типы, укажите их в квадратных скобках:
-
-```Python hl_lines="4"
-{!> ../../docs_src/python_types/tutorial006.py!}
-```
-
-////
+{* ../../docs_src/python_types/tutorial006_py39.py hl[1] *}
/// info | Информация
Эти внутренние типы в квадратных скобках называются «параметрами типов».
-В данном случае `str` — это параметр типа, передаваемый в `List` (или `list` в Python 3.9 и выше).
+В данном случае `str` — это параметр типа, передаваемый в `list`.
///
Это означает: «переменная `items` — это `list`, и каждый элемент этого списка — `str`».
-/// tip | Совет
-
-Если вы используете Python 3.9 или выше, вам не нужно импортировать `List` из `typing`, можно использовать обычный встроенный тип `list`.
-
-///
-
Таким образом, ваш редактор кода сможет помогать даже при обработке элементов списка:
@@ -225,21 +193,7 @@ John Doe
Аналогично вы бы объявили `tuple` и `set`:
-//// tab | Python 3.9+
-
-```Python hl_lines="1"
-{!> ../../docs_src/python_types/tutorial007_py39.py!}
-```
-
-////
-
-//// tab | Python 3.8+
-
-```Python hl_lines="1 4"
-{!> ../../docs_src/python_types/tutorial007.py!}
-```
-
-////
+{* ../../docs_src/python_types/tutorial007_py39.py hl[1] *}
Это означает:
@@ -254,21 +208,7 @@ John Doe
Второй параметр типа — для значений `dict`:
-//// tab | Python 3.9+
-
-```Python hl_lines="1"
-{!> ../../docs_src/python_types/tutorial008_py39.py!}
-```
-
-////
-
-//// tab | Python 3.8+
-
-```Python hl_lines="1 4"
-{!> ../../docs_src/python_types/tutorial008.py!}
-```
-
-////
+{* ../../docs_src/python_types/tutorial008_py39.py hl[1] *}
Это означает:
@@ -292,10 +232,10 @@ John Doe
////
-//// tab | Python 3.8+
+//// tab | Python 3.9+
```Python hl_lines="1 4"
-{!> ../../docs_src/python_types/tutorial008b.py!}
+{!> ../../docs_src/python_types/tutorial008b_py39.py!}
```
////
@@ -309,7 +249,7 @@ John Doe
В Python 3.6 и выше (включая Python 3.10) это можно объявить, импортировав и используя `Optional` из модуля `typing`.
```Python hl_lines="1 4"
-{!../../docs_src/python_types/tutorial009.py!}
+{!../../docs_src/python_types/tutorial009_py39.py!}
```
Использование `Optional[str]` вместо просто `str` позволит редактору кода помочь вам обнаружить ошибки, когда вы предполагаете, что значение всегда `str`, хотя на самом деле оно может быть и `None`.
@@ -326,18 +266,18 @@ John Doe
////
-//// tab | Python 3.8+
+//// tab | Python 3.9+
```Python hl_lines="1 4"
-{!> ../../docs_src/python_types/tutorial009.py!}
+{!> ../../docs_src/python_types/tutorial009_py39.py!}
```
////
-//// tab | Python 3.8+ альтернативный вариант
+//// tab | Python 3.9+ альтернативный вариант
```Python hl_lines="1 4"
-{!> ../../docs_src/python_types/tutorial009b.py!}
+{!> ../../docs_src/python_types/tutorial009b_py39.py!}
```
////
@@ -357,7 +297,7 @@ John Doe
В качестве примера возьмём эту функцию:
-{* ../../docs_src/python_types/tutorial009c.py hl[1,4] *}
+{* ../../docs_src/python_types/tutorial009c_py39.py hl[1,4] *}
Параметр `name` определён как `Optional[str]`, но он **не необязательный** — вы не можете вызвать функцию без этого параметра:
@@ -390,10 +330,10 @@ say_hi(name=None) # Это работает, None допустим 🎉
* `set`
* `dict`
-И, как и в Python 3.8, из модуля `typing`:
+И, как и в предыдущих версиях Python, из модуля `typing`:
* `Union`
-* `Optional` (так же, как в Python 3.8)
+* `Optional`
* ...и другие.
В Python 3.10, как альтернативу generics `Union` и `Optional`, можно использовать вертикальную черту (`|`) для объявления объединений типов — это гораздо лучше и проще.
@@ -409,7 +349,7 @@ say_hi(name=None) # Это работает, None допустим 🎉
* `set`
* `dict`
-И, как и в Python 3.8, из модуля `typing`:
+И generics из модуля `typing`:
* `Union`
* `Optional`
@@ -417,29 +357,17 @@ say_hi(name=None) # Это работает, None допустим 🎉
////
-//// tab | Python 3.8+
-
-* `List`
-* `Tuple`
-* `Set`
-* `Dict`
-* `Union`
-* `Optional`
-* ...и другие.
-
-////
-
### Классы как типы { #classes-as-types }
Вы также можете объявлять класс как тип переменной.
Допустим, у вас есть класс `Person` с именем:
-{* ../../docs_src/python_types/tutorial010.py hl[1:3] *}
+{* ../../docs_src/python_types/tutorial010_py39.py hl[1:3] *}
Тогда вы можете объявить переменную типа `Person`:
-{* ../../docs_src/python_types/tutorial010.py hl[6] *}
+{* ../../docs_src/python_types/tutorial010_py39.py hl[6] *}
И снова вы получите полную поддержку редактора кода:
@@ -463,29 +391,7 @@ say_hi(name=None) # Это работает, None допустим 🎉
Пример из официальной документации Pydantic:
-//// tab | Python 3.10+
-
-```Python
-{!> ../../docs_src/python_types/tutorial011_py310.py!}
-```
-
-////
-
-//// tab | Python 3.9+
-
-```Python
-{!> ../../docs_src/python_types/tutorial011_py39.py!}
-```
-
-////
-
-//// tab | Python 3.8+
-
-```Python
-{!> ../../docs_src/python_types/tutorial011.py!}
-```
-
-////
+{* ../../docs_src/python_types/tutorial011_py310.py *}
/// info | Информация
@@ -507,27 +413,9 @@ say_hi(name=None) # Это работает, None допустим 🎉
В Python также есть возможность добавлять **дополнительные метаданные** к подсказкам типов с помощью `Annotated`.
-//// tab | Python 3.9+
+Начиная с Python 3.9, `Annotated` входит в стандартную библиотеку, поэтому вы можете импортировать его из `typing`.
-В Python 3.9 `Annotated` входит в стандартную библиотеку, поэтому вы можете импортировать его из `typing`.
-
-```Python hl_lines="1 4"
-{!> ../../docs_src/python_types/tutorial013_py39.py!}
-```
-
-////
-
-//// tab | Python 3.8+
-
-В версиях ниже Python 3.9 импортируйте `Annotated` из `typing_extensions`.
-
-Он уже будет установлен вместе с **FastAPI**.
-
-```Python hl_lines="1 4"
-{!> ../../docs_src/python_types/tutorial013.py!}
-```
-
-////
+{* ../../docs_src/python_types/tutorial013_py39.py hl[1,4] *}
Сам Python ничего не делает с `Annotated`. А для редакторов кода и других инструментов тип по-прежнему `str`.
@@ -558,7 +446,7 @@ say_hi(name=None) # Это работает, None допустим 🎉
...и **FastAPI** использует эти же объявления для:
-* **Определения требований**: из path-параметров, query-параметров, HTTP-заголовков, тел запросов, зависимостей и т.д.
+* **Определения требований**: из path-параметров пути запроса, query-параметров, HTTP-заголовков, тел запросов, зависимостей и т.д.
* **Преобразования данных**: из HTTP-запроса к требуемому типу.
* **Валидации данных**: приходящих с каждого HTTP-запроса:
* Генерации **автоматических ошибок**, возвращаемых клиенту, когда данные некорректны.
diff --git a/docs/ru/docs/tutorial/background-tasks.md b/docs/ru/docs/tutorial/background-tasks.md
index 1ed8522d69..8d7b7442f9 100644
--- a/docs/ru/docs/tutorial/background-tasks.md
+++ b/docs/ru/docs/tutorial/background-tasks.md
@@ -15,7 +15,7 @@
Сначала импортируйте `BackgroundTasks` и объявите параметр в вашей функции‑обработчике пути с типом `BackgroundTasks`:
-{* ../../docs_src/background_tasks/tutorial001.py hl[1,13] *}
+{* ../../docs_src/background_tasks/tutorial001_py39.py hl[1,13] *}
**FastAPI** создаст объект типа `BackgroundTasks` для вас и передаст его через этот параметр.
@@ -31,13 +31,13 @@
Так как операция записи не использует `async` и `await`, мы определим функцию как обычную `def`:
-{* ../../docs_src/background_tasks/tutorial001.py hl[6:9] *}
+{* ../../docs_src/background_tasks/tutorial001_py39.py hl[6:9] *}
## Добавление фоновой задачи { #add-the-background-task }
Внутри вашей функции‑обработчика пути передайте функцию задачи объекту фоновых задач методом `.add_task()`:
-{* ../../docs_src/background_tasks/tutorial001.py hl[14] *}
+{* ../../docs_src/background_tasks/tutorial001_py39.py hl[14] *}
`.add_task()` принимает следующие аргументы:
diff --git a/docs/ru/docs/tutorial/body-nested-models.md b/docs/ru/docs/tutorial/body-nested-models.md
index 5bb5abbe63..4c914b97f0 100644
--- a/docs/ru/docs/tutorial/body-nested-models.md
+++ b/docs/ru/docs/tutorial/body-nested-models.md
@@ -14,35 +14,14 @@
В Python есть специальный способ объявлять списки с внутренними типами, или «параметрами типа»:
-### Импортируйте `List` из модуля typing { #import-typings-list }
-
-В Python 3.9 и выше вы можете использовать стандартный тип `list` для объявления аннотаций типов, как мы увидим ниже. 💡
-
-Но в версиях Python до 3.9 (начиная с 3.6) сначала вам необходимо импортировать `List` из стандартного модуля `typing`:
-
-{* ../../docs_src/body_nested_models/tutorial002.py hl[1] *}
-
### Объявите `list` с параметром типа { #declare-a-list-with-a-type-parameter }
-Для объявления типов, у которых есть параметры типа (внутренние типы), таких как `list`, `dict`, `tuple`:
-
-* Если у вас Python версии ниже 3.9, импортируйте их аналоги из модуля `typing`
-* Передайте внутренний(ие) тип(ы) как «параметры типа», используя квадратные скобки: `[` и `]`
-
-В Python 3.9 это будет:
+Для объявления типов, у которых есть параметры типа (внутренние типы), таких как `list`, `dict`, `tuple`, передайте внутренний(ие) тип(ы) как «параметры типа», используя квадратные скобки: `[` и `]`
```Python
my_list: list[str]
```
-В версиях Python до 3.9 это будет:
-
-```Python
-from typing import List
-
-my_list: List[str]
-```
-
Это всё стандартный синтаксис Python для объявления типов.
Используйте этот же стандартный синтаксис для атрибутов модели с внутренними типами.
@@ -107,7 +86,7 @@ my_list: List[str]
Ещё раз: сделав такое объявление, с помощью **FastAPI** вы получите:
-* Поддержку редактора кода (автозавершение и т. д.), даже для вложенных моделей
+* Поддержку редактора кода (автозавершение и т.д.), даже для вложенных моделей
* Преобразование данных
* Валидацию данных
* Автоматическую документацию
@@ -178,12 +157,6 @@ my_list: List[str]
Если верхний уровень значения тела JSON-объекта представляет собой JSON `array` (в Python — `list`), вы можете объявить тип в параметре функции, так же как в моделях Pydantic:
-```Python
-images: List[Image]
-```
-
-или в Python 3.9 и выше:
-
```Python
images: list[Image]
```
diff --git a/docs/ru/docs/tutorial/body.md b/docs/ru/docs/tutorial/body.md
index 16ff6466c1..b61f3e7a09 100644
--- a/docs/ru/docs/tutorial/body.md
+++ b/docs/ru/docs/tutorial/body.md
@@ -161,7 +161,7 @@ JSON Schema ваших моделей будет частью сгенериро
FastAPI понимает, что значение `q` не является обязательным из-за значения по умолчанию `= None`.
-Аннотации типов `str | None` (Python 3.10+) или `Union[str, None]` (Python 3.8+) не используются FastAPI для определения обязательности; он узнает, что параметр не обязателен, потому что у него есть значение по умолчанию `= None`.
+Аннотации типов `str | None` (Python 3.10+) или `Union[str, None]` (Python 3.9+) не используются FastAPI для определения обязательности; он узнает, что параметр не обязателен, потому что у него есть значение по умолчанию `= None`.
Но добавление аннотаций типов позволит вашему редактору кода лучше вас поддерживать и обнаруживать ошибки.
diff --git a/docs/ru/docs/tutorial/cors.md b/docs/ru/docs/tutorial/cors.md
index b0704351a9..d09a31e2c3 100644
--- a/docs/ru/docs/tutorial/cors.md
+++ b/docs/ru/docs/tutorial/cors.md
@@ -46,7 +46,7 @@
* Отдельных HTTP-методов (`POST`, `PUT`) или всех вместе, используя `"*"`.
* Отдельных HTTP-заголовков или всех вместе, используя `"*"`.
-{* ../../docs_src/cors/tutorial001.py hl[2,6:11,13:19] *}
+{* ../../docs_src/cors/tutorial001_py39.py hl[2,6:11,13:19] *}
`CORSMiddleware` использует "запрещающие" значения по умолчанию, поэтому вам нужно явным образом разрешить использование отдельных источников, методов или заголовков, чтобы браузеры могли использовать их в кросс-доменном контексте.
diff --git a/docs/ru/docs/tutorial/debugging.md b/docs/ru/docs/tutorial/debugging.md
index a5340af089..51955835e6 100644
--- a/docs/ru/docs/tutorial/debugging.md
+++ b/docs/ru/docs/tutorial/debugging.md
@@ -6,7 +6,7 @@
В вашем FastAPI приложении, импортируйте и вызовите `uvicorn` напрямую:
-{* ../../docs_src/debugging/tutorial001.py hl[1,15] *}
+{* ../../docs_src/debugging/tutorial001_py39.py hl[1,15] *}
### Описание `__name__ == "__main__"` { #about-name-main }
diff --git a/docs/ru/docs/tutorial/dependencies/classes-as-dependencies.md b/docs/ru/docs/tutorial/dependencies/classes-as-dependencies.md
index ec7770d960..a38e885d43 100644
--- a/docs/ru/docs/tutorial/dependencies/classes-as-dependencies.md
+++ b/docs/ru/docs/tutorial/dependencies/classes-as-dependencies.md
@@ -101,7 +101,7 @@ fluffy = Cat(name="Mr Fluffy")
Обратите внимание, что в приведенном выше коде мы два раза пишем `CommonQueryParams`:
-//// tab | Python 3.8+
+//// tab | Python 3.9+
```Python
commons: Annotated[CommonQueryParams, Depends(CommonQueryParams)]
@@ -109,7 +109,7 @@ commons: Annotated[CommonQueryParams, Depends(CommonQueryParams)]
////
-//// tab | Python 3.8+ non-Annotated
+//// tab | Python 3.9+ non-Annotated
/// tip | Подсказка
@@ -137,7 +137,7 @@ commons: CommonQueryParams = Depends(CommonQueryParams)
В этом случае первый `CommonQueryParams`, в:
-//// tab | Python 3.8+
+//// tab | Python 3.9+
```Python
commons: Annotated[CommonQueryParams, ...
@@ -145,7 +145,7 @@ commons: Annotated[CommonQueryParams, ...
////
-//// tab | Python 3.8+ non-Annotated
+//// tab | Python 3.9+ non-Annotated
/// tip | Подсказка
@@ -163,7 +163,7 @@ commons: CommonQueryParams ...
На самом деле можно написать просто:
-//// tab | Python 3.8+
+//// tab | Python 3.9+
```Python
commons: Annotated[Any, Depends(CommonQueryParams)]
@@ -171,7 +171,7 @@ commons: Annotated[Any, Depends(CommonQueryParams)]
////
-//// tab | Python 3.8+ non-Annotated
+//// tab | Python 3.9+ non-Annotated
/// tip | Подсказка
@@ -197,7 +197,7 @@ commons = Depends(CommonQueryParams)
Но вы видите, что здесь мы имеем некоторое повторение кода, дважды написав `CommonQueryParams`:
-//// tab | Python 3.8+
+//// tab | Python 3.9+
```Python
commons: Annotated[CommonQueryParams, Depends(CommonQueryParams)]
@@ -205,7 +205,7 @@ commons: Annotated[CommonQueryParams, Depends(CommonQueryParams)]
////
-//// tab | Python 3.8+ non-Annotated
+//// tab | Python 3.9+ non-Annotated
/// tip | Подсказка
@@ -225,7 +225,7 @@ commons: CommonQueryParams = Depends(CommonQueryParams)
Вместо того чтобы писать:
-//// tab | Python 3.8+
+//// tab | Python 3.9+
```Python
commons: Annotated[CommonQueryParams, Depends(CommonQueryParams)]
@@ -233,7 +233,7 @@ commons: Annotated[CommonQueryParams, Depends(CommonQueryParams)]
////
-//// tab | Python 3.8+ non-Annotated
+//// tab | Python 3.9+ non-Annotated
/// tip | Подсказка
@@ -249,7 +249,7 @@ commons: CommonQueryParams = Depends(CommonQueryParams)
...следует написать:
-//// tab | Python 3.8+
+//// tab | Python 3.9+
```Python
commons: Annotated[CommonQueryParams, Depends()]
@@ -257,7 +257,7 @@ commons: Annotated[CommonQueryParams, Depends()]
////
-//// tab | Python 3.8 non-Annotated
+//// tab | Python 3.9+ non-Annotated
/// tip | Подсказка
diff --git a/docs/ru/docs/tutorial/dependencies/dependencies-with-yield.md b/docs/ru/docs/tutorial/dependencies/dependencies-with-yield.md
index 7ff85246dc..dc202db616 100644
--- a/docs/ru/docs/tutorial/dependencies/dependencies-with-yield.md
+++ b/docs/ru/docs/tutorial/dependencies/dependencies-with-yield.md
@@ -29,15 +29,15 @@ FastAPI поддерживает зависимости, которые выпо
Перед созданием ответа будет выполнен только код до и включая оператор `yield`:
-{* ../../docs_src/dependencies/tutorial007.py hl[2:4] *}
+{* ../../docs_src/dependencies/tutorial007_py39.py hl[2:4] *}
Значение, полученное из `yield`, внедряется в *операции пути* и другие зависимости:
-{* ../../docs_src/dependencies/tutorial007.py hl[4] *}
+{* ../../docs_src/dependencies/tutorial007_py39.py hl[4] *}
Код, следующий за оператором `yield`, выполняется после ответа:
-{* ../../docs_src/dependencies/tutorial007.py hl[5:6] *}
+{* ../../docs_src/dependencies/tutorial007_py39.py hl[5:6] *}
/// tip | Подсказка
@@ -57,7 +57,7 @@ FastAPI поддерживает зависимости, которые выпо
Точно так же можно использовать `finally`, чтобы убедиться, что обязательные шаги при выходе выполнены независимо от того, было ли исключение или нет.
-{* ../../docs_src/dependencies/tutorial007.py hl[3,5] *}
+{* ../../docs_src/dependencies/tutorial007_py39.py hl[3,5] *}
## Подзависимости с `yield` { #sub-dependencies-with-yield }
@@ -269,7 +269,7 @@ with open("./somefile.txt") as f:
Их также можно использовать внутри зависимостей **FastAPI** с `yield`, применяя операторы
`with` или `async with` внутри функции зависимости:
-{* ../../docs_src/dependencies/tutorial010.py hl[1:9,13] *}
+{* ../../docs_src/dependencies/tutorial010_py39.py hl[1:9,13] *}
/// tip | Подсказка
diff --git a/docs/ru/docs/tutorial/dependencies/global-dependencies.md b/docs/ru/docs/tutorial/dependencies/global-dependencies.md
index 075d6b0baa..2347c6dd83 100644
--- a/docs/ru/docs/tutorial/dependencies/global-dependencies.md
+++ b/docs/ru/docs/tutorial/dependencies/global-dependencies.md
@@ -6,7 +6,7 @@
В этом случае они будут применяться ко всем *операциям пути* в приложении:
-{* ../../docs_src/dependencies/tutorial012_an_py39.py hl[16] *}
+{* ../../docs_src/dependencies/tutorial012_an_py39.py hl[17] *}
Все способы [добавления `dependencies` (зависимостей) в *декораторах операций пути*](dependencies-in-path-operation-decorators.md){.internal-link target=_blank} по-прежнему применимы, но в данном случае зависимости применяются ко всем *операциям пути* приложения.
diff --git a/docs/ru/docs/tutorial/dependencies/sub-dependencies.md b/docs/ru/docs/tutorial/dependencies/sub-dependencies.md
index efe8d98c31..da31a6682f 100644
--- a/docs/ru/docs/tutorial/dependencies/sub-dependencies.md
+++ b/docs/ru/docs/tutorial/dependencies/sub-dependencies.md
@@ -62,7 +62,7 @@ query_extractor --> query_or_cookie_extractor --> read_query
В расширенном сценарии, когда вы знаете, что вам нужно, чтобы зависимость вызывалась на каждом шаге (возможно, несколько раз) в одном и том же запросе, вместо использования "кэшированного" значения, вы можете установить параметр `use_cache=False` при использовании `Depends`:
-//// tab | Python 3.8+
+//// tab | Python 3.9+
```Python hl_lines="1"
async def needy_dependency(fresh_value: Annotated[str, Depends(get_value, use_cache=False)]):
@@ -71,7 +71,7 @@ async def needy_dependency(fresh_value: Annotated[str, Depends(get_value, use_ca
////
-//// tab | Python 3.8+ без Annotated
+//// tab | Python 3.9+ без Annotated
/// tip | Подсказка
diff --git a/docs/ru/docs/tutorial/first-steps.md b/docs/ru/docs/tutorial/first-steps.md
index 6f59d72054..798c03d517 100644
--- a/docs/ru/docs/tutorial/first-steps.md
+++ b/docs/ru/docs/tutorial/first-steps.md
@@ -2,7 +2,7 @@
Самый простой файл FastAPI может выглядеть так:
-{* ../../docs_src/first_steps/tutorial001.py *}
+{* ../../docs_src/first_steps/tutorial001_py39.py *}
Скопируйте это в файл `main.py`.
@@ -183,7 +183,7 @@ Deploying to FastAPI Cloud...
### Шаг 1: импортируйте `FastAPI` { #step-1-import-fastapi }
-{* ../../docs_src/first_steps/tutorial001.py hl[1] *}
+{* ../../docs_src/first_steps/tutorial001_py39.py hl[1] *}
`FastAPI` — это класс на Python, который предоставляет всю функциональность для вашего API.
@@ -197,7 +197,7 @@ Deploying to FastAPI Cloud...
### Шаг 2: создайте экземпляр `FastAPI` { #step-2-create-a-fastapi-instance }
-{* ../../docs_src/first_steps/tutorial001.py hl[3] *}
+{* ../../docs_src/first_steps/tutorial001_py39.py hl[3] *}
Здесь переменная `app` будет экземпляром класса `FastAPI`.
@@ -266,7 +266,7 @@ https://example.com/items/foo
#### Определите *декоратор операции пути (path operation decorator)* { #define-a-path-operation-decorator }
-{* ../../docs_src/first_steps/tutorial001.py hl[6] *}
+{* ../../docs_src/first_steps/tutorial001_py39.py hl[6] *}
`@app.get("/")` сообщает **FastAPI**, что функция прямо под ним отвечает за обработку запросов, поступающих:
@@ -320,7 +320,7 @@ https://example.com/items/foo
* **операция**: `get`.
* **функция**: функция ниже «декоратора» (ниже `@app.get("/")`).
-{* ../../docs_src/first_steps/tutorial001.py hl[7] *}
+{* ../../docs_src/first_steps/tutorial001_py39.py hl[7] *}
Это функция на Python.
@@ -332,7 +332,7 @@ https://example.com/items/foo
Вы также можете определить её как обычную функцию вместо `async def`:
-{* ../../docs_src/first_steps/tutorial003.py hl[7] *}
+{* ../../docs_src/first_steps/tutorial003_py39.py hl[7] *}
/// note | Примечание
@@ -342,7 +342,7 @@ https://example.com/items/foo
### Шаг 5: верните содержимое { #step-5-return-the-content }
-{* ../../docs_src/first_steps/tutorial001.py hl[8] *}
+{* ../../docs_src/first_steps/tutorial001_py39.py hl[8] *}
Вы можете вернуть `dict`, `list`, отдельные значения `str`, `int` и т.д.
diff --git a/docs/ru/docs/tutorial/handling-errors.md b/docs/ru/docs/tutorial/handling-errors.md
index 63ca8665ef..2e00d70759 100644
--- a/docs/ru/docs/tutorial/handling-errors.md
+++ b/docs/ru/docs/tutorial/handling-errors.md
@@ -25,7 +25,7 @@
### Импортируйте `HTTPException` { #import-httpexception }
-{* ../../docs_src/handling_errors/tutorial001.py hl[1] *}
+{* ../../docs_src/handling_errors/tutorial001_py39.py hl[1] *}
### Вызовите `HTTPException` в своем коде { #raise-an-httpexception-in-your-code }
@@ -39,7 +39,7 @@
В данном примере, когда клиент запрашивает элемент по несуществующему ID, возникает исключение со статус-кодом `404`:
-{* ../../docs_src/handling_errors/tutorial001.py hl[11] *}
+{* ../../docs_src/handling_errors/tutorial001_py39.py hl[11] *}
### Возвращаемый ответ { #the-resulting-response }
@@ -77,7 +77,7 @@
Но в случае, если это необходимо для продвинутого сценария, можно добавить пользовательские заголовки:
-{* ../../docs_src/handling_errors/tutorial002.py hl[14] *}
+{* ../../docs_src/handling_errors/tutorial002_py39.py hl[14] *}
## Установка пользовательских обработчиков исключений { #install-custom-exception-handlers }
@@ -89,7 +89,7 @@
Можно добавить собственный обработчик исключений с помощью `@app.exception_handler()`:
-{* ../../docs_src/handling_errors/tutorial003.py hl[5:7,13:18,24] *}
+{* ../../docs_src/handling_errors/tutorial003_py39.py hl[5:7,13:18,24] *}
Здесь, если запросить `/unicorns/yolo`, то *операция пути* вызовет `UnicornException`.
@@ -127,7 +127,7 @@
Обработчик исключения получит объект `Request` и исключение.
-{* ../../docs_src/handling_errors/tutorial004.py hl[2,14:19] *}
+{* ../../docs_src/handling_errors/tutorial004_py39.py hl[2,14:19] *}
Теперь, если перейти к `/items/foo`, то вместо стандартной JSON-ошибки с:
@@ -159,7 +159,7 @@ Field: ('path', 'item_id'), Error: Input should be a valid integer, unable to pa
Например, для этих ошибок можно вернуть обычный текстовый ответ вместо JSON:
-{* ../../docs_src/handling_errors/tutorial004.py hl[3:4,9:11,25] *}
+{* ../../docs_src/handling_errors/tutorial004_py39.py hl[3:4,9:11,25] *}
/// note | Технические детали
@@ -183,7 +183,7 @@ Field: ('path', 'item_id'), Error: Input should be a valid integer, unable to pa
Вы можете использовать его при разработке приложения для регистрации тела и его отладки, возврата пользователю и т.д.
-{* ../../docs_src/handling_errors/tutorial005.py hl[14] *}
+{* ../../docs_src/handling_errors/tutorial005_py39.py hl[14] *}
Теперь попробуйте отправить недействительный элемент, например:
@@ -239,6 +239,6 @@ from starlette.exceptions import HTTPException as StarletteHTTPException
Если вы хотите использовать исключение вместе с теми же обработчиками исключений по умолчанию из **FastAPI**, вы можете импортировать и повторно использовать обработчики исключений по умолчанию из `fastapi.exception_handlers`:
-{* ../../docs_src/handling_errors/tutorial006.py hl[2:5,15,21] *}
+{* ../../docs_src/handling_errors/tutorial006_py39.py hl[2:5,15,21] *}
В этом примере вы просто `выводите в терминал` ошибку с очень выразительным сообщением, но идея вам понятна. Вы можете использовать исключение, а затем просто повторно использовать стандартные обработчики исключений.
diff --git a/docs/ru/docs/tutorial/metadata.md b/docs/ru/docs/tutorial/metadata.md
index 2e359752e1..e4fe5fb544 100644
--- a/docs/ru/docs/tutorial/metadata.md
+++ b/docs/ru/docs/tutorial/metadata.md
@@ -18,7 +18,7 @@
Вы можете задать их следующим образом:
-{* ../../docs_src/metadata/tutorial001.py hl[3:16, 19:32] *}
+{* ../../docs_src/metadata/tutorial001_py39.py hl[3:16, 19:32] *}
/// tip | Подсказка
@@ -36,7 +36,7 @@
К примеру:
-{* ../../docs_src/metadata/tutorial001_1.py hl[31] *}
+{* ../../docs_src/metadata/tutorial001_1_py39.py hl[31] *}
## Метаданные для тегов { #metadata-for-tags }
@@ -58,7 +58,7 @@
Создайте метаданные для ваших тегов и передайте их в параметре `openapi_tags`:
-{* ../../docs_src/metadata/tutorial004.py hl[3:16,18] *}
+{* ../../docs_src/metadata/tutorial004_py39.py hl[3:16,18] *}
Помните, что вы можете использовать Markdown внутри описания, к примеру "login" будет отображен жирным шрифтом (**login**) и "fancy" будет отображаться курсивом (_fancy_).
@@ -72,7 +72,7 @@
Используйте параметр `tags` с вашими *операциями пути* (и `APIRouter`ами), чтобы присвоить им различные теги:
-{* ../../docs_src/metadata/tutorial004.py hl[21,26] *}
+{* ../../docs_src/metadata/tutorial004_py39.py hl[21,26] *}
/// info | Дополнительная информация
@@ -100,7 +100,7 @@
К примеру, чтобы задать её отображение по адресу `/api/v1/openapi.json`:
-{* ../../docs_src/metadata/tutorial002.py hl[3] *}
+{* ../../docs_src/metadata/tutorial002_py39.py hl[3] *}
Если вы хотите отключить схему OpenAPI полностью, вы можете задать `openapi_url=None`, это также отключит пользовательские интерфейсы документации, которые её используют.
@@ -117,4 +117,4 @@
К примеру, чтобы задать отображение Swagger UI по адресу `/documentation` и отключить ReDoc:
-{* ../../docs_src/metadata/tutorial003.py hl[3] *}
+{* ../../docs_src/metadata/tutorial003_py39.py hl[3] *}
diff --git a/docs/ru/docs/tutorial/middleware.md b/docs/ru/docs/tutorial/middleware.md
index 5803b398b9..a83d3c0111 100644
--- a/docs/ru/docs/tutorial/middleware.md
+++ b/docs/ru/docs/tutorial/middleware.md
@@ -33,7 +33,7 @@
* Затем она возвращает ответ `response`, сгенерированный *операцией пути*.
* Также имеется возможность видоизменить `response`, перед тем как его вернуть.
-{* ../../docs_src/middleware/tutorial001.py hl[8:9,11,14] *}
+{* ../../docs_src/middleware/tutorial001_py39.py hl[8:9,11,14] *}
/// tip | Примечание
@@ -59,7 +59,7 @@
Например, вы можете добавить собственный заголовок `X-Process-Time`, содержащий время в секундах, необходимое для обработки запроса и генерации ответа:
-{* ../../docs_src/middleware/tutorial001.py hl[10,12:13] *}
+{* ../../docs_src/middleware/tutorial001_py39.py hl[10,12:13] *}
/// tip | Примечание
diff --git a/docs/ru/docs/tutorial/path-operation-configuration.md b/docs/ru/docs/tutorial/path-operation-configuration.md
index 63b48a3941..96a54ffea0 100644
--- a/docs/ru/docs/tutorial/path-operation-configuration.md
+++ b/docs/ru/docs/tutorial/path-operation-configuration.md
@@ -46,7 +46,7 @@
**FastAPI** поддерживает это так же, как и в случае с обычными строками:
-{* ../../docs_src/path_operation_configuration/tutorial002b.py hl[1,8:10,13,18] *}
+{* ../../docs_src/path_operation_configuration/tutorial002b_py39.py hl[1,8:10,13,18] *}
## Краткое и развёрнутое содержание { #summary-and-description }
@@ -92,7 +92,7 @@ OpenAPI указывает, что каждой *операции пути* не
Если вам необходимо пометить *операцию пути* как устаревшую, при этом не удаляя её, передайте параметр `deprecated`:
-{* ../../docs_src/path_operation_configuration/tutorial006.py hl[16] *}
+{* ../../docs_src/path_operation_configuration/tutorial006_py39.py hl[16] *}
Он будет четко помечен как устаревший в интерактивной документации:
diff --git a/docs/ru/docs/tutorial/path-params-numeric-validations.md b/docs/ru/docs/tutorial/path-params-numeric-validations.md
index ccea1945e4..f0fe788051 100644
--- a/docs/ru/docs/tutorial/path-params-numeric-validations.md
+++ b/docs/ru/docs/tutorial/path-params-numeric-validations.md
@@ -54,7 +54,7 @@ Path-параметр всегда является обязательным, п
Поэтому вы можете определить функцию так:
-{* ../../docs_src/path_params_numeric_validations/tutorial002.py hl[7] *}
+{* ../../docs_src/path_params_numeric_validations/tutorial002_py39.py hl[7] *}
Но имейте в виду, что если вы используете `Annotated`, вы не столкнётесь с этой проблемой, так как вы не используете значения по умолчанию параметров функции для `Query()` или `Path()`.
@@ -83,7 +83,7 @@ Path-параметр всегда является обязательным, п
Python не будет ничего делать с `*`, но он будет знать, что все следующие параметры являются именованными аргументами (парами ключ-значение), также известными как kwargs, даже если у них нет значений по умолчанию.
-{* ../../docs_src/path_params_numeric_validations/tutorial003.py hl[7] *}
+{* ../../docs_src/path_params_numeric_validations/tutorial003_py39.py hl[7] *}
### Лучше с `Annotated` { #better-with-annotated }
diff --git a/docs/ru/docs/tutorial/path-params.md b/docs/ru/docs/tutorial/path-params.md
index f7d138afbe..83a7ed3ffe 100644
--- a/docs/ru/docs/tutorial/path-params.md
+++ b/docs/ru/docs/tutorial/path-params.md
@@ -2,7 +2,7 @@
Вы можете определить "параметры" или "переменные" пути, используя синтаксис форматированных строк Python:
-{* ../../docs_src/path_params/tutorial001.py hl[6:7] *}
+{* ../../docs_src/path_params/tutorial001_py39.py hl[6:7] *}
Значение параметра пути `item_id` будет передано в функцию в качестве аргумента `item_id`.
@@ -16,7 +16,7 @@
Вы можете объявить тип параметра пути в функции, используя стандартные аннотации типов Python:
-{* ../../docs_src/path_params/tutorial002.py hl[7] *}
+{* ../../docs_src/path_params/tutorial002_py39.py hl[7] *}
Здесь, `item_id` объявлен типом `int`.
@@ -118,13 +118,13 @@
Поскольку *операции пути* выполняются в порядке их объявления, необходимо, чтобы путь для `/users/me` был объявлен раньше, чем путь для `/users/{user_id}`:
-{* ../../docs_src/path_params/tutorial003.py hl[6,11] *}
+{* ../../docs_src/path_params/tutorial003_py39.py hl[6,11] *}
Иначе путь для `/users/{user_id}` также будет соответствовать `/users/me`, "подразумевая", что он получает параметр `user_id` со значением `"me"`.
Аналогично, вы не можете переопределить операцию с путем:
-{* ../../docs_src/path_params/tutorial003b.py hl[6,11] *}
+{* ../../docs_src/path_params/tutorial003b_py39.py hl[6,11] *}
Первый будет выполняться всегда, так как путь совпадает первым.
@@ -140,13 +140,7 @@
Затем создайте атрибуты класса с фиксированными допустимыми значениями:
-{* ../../docs_src/path_params/tutorial005.py hl[1,6:9] *}
-
-/// info | Дополнительная информация
-
-Перечисления (enum) доступны в Python начиная с версии 3.4.
-
-///
+{* ../../docs_src/path_params/tutorial005_py39.py hl[1,6:9] *}
/// tip | Подсказка
@@ -158,7 +152,7 @@
Определите *параметр пути*, используя в аннотации типа класс перечисления (`ModelName`), созданный ранее:
-{* ../../docs_src/path_params/tutorial005.py hl[16] *}
+{* ../../docs_src/path_params/tutorial005_py39.py hl[16] *}
### Проверьте документацию { #check-the-docs }
@@ -174,13 +168,13 @@
Вы можете сравнить это значение с *элементом перечисления* класса `ModelName`:
-{* ../../docs_src/path_params/tutorial005.py hl[17] *}
+{* ../../docs_src/path_params/tutorial005_py39.py hl[17] *}
#### Получение *значения перечисления* { #get-the-enumeration-value }
Можно получить фактическое значение (в данном случае - `str`) с помощью `model_name.value` или в общем случае `your_enum_member.value`:
-{* ../../docs_src/path_params/tutorial005.py hl[20] *}
+{* ../../docs_src/path_params/tutorial005_py39.py hl[20] *}
/// tip | Подсказка
@@ -194,7 +188,7 @@
Они будут преобразованы в соответствующие значения (в данном случае - строки) перед их возвратом клиенту:
-{* ../../docs_src/path_params/tutorial005.py hl[18,21,23] *}
+{* ../../docs_src/path_params/tutorial005_py39.py hl[18,21,23] *}
Вы отправите клиенту такой JSON-ответ:
```JSON
@@ -232,7 +226,7 @@ OpenAPI не поддерживает способов объявления *п
Можете использовать так:
-{* ../../docs_src/path_params/tutorial004.py hl[6] *}
+{* ../../docs_src/path_params/tutorial004_py39.py hl[6] *}
/// tip | Подсказка
diff --git a/docs/ru/docs/tutorial/query-params-str-validations.md b/docs/ru/docs/tutorial/query-params-str-validations.md
index 302901d4ec..3a4ecc37dc 100644
--- a/docs/ru/docs/tutorial/query-params-str-validations.md
+++ b/docs/ru/docs/tutorial/query-params-str-validations.md
@@ -55,7 +55,7 @@ q: str | None = None
////
-//// tab | Python 3.8+
+//// tab | Python 3.9+
```Python
q: Union[str, None] = None
@@ -73,7 +73,7 @@ q: Annotated[str | None] = None
////
-//// tab | Python 3.8+
+//// tab | Python 3.9+
```Python
q: Annotated[Union[str, None]] = None
diff --git a/docs/ru/docs/tutorial/query-params.md b/docs/ru/docs/tutorial/query-params.md
index 5a84f9768c..be1c0e46e1 100644
--- a/docs/ru/docs/tutorial/query-params.md
+++ b/docs/ru/docs/tutorial/query-params.md
@@ -2,7 +2,7 @@
Когда вы объявляете параметры функции, которые не являются параметрами пути, они автоматически интерпретируются как "query"-параметры.
-{* ../../docs_src/query_params/tutorial001.py hl[9] *}
+{* ../../docs_src/query_params/tutorial001_py39.py hl[9] *}
Query-параметры представляют из себя набор пар ключ-значение, которые идут после знака `?` в URL-адресе, разделенные символами `&`.
@@ -127,7 +127,7 @@ http://127.0.0.1:8000/items/foo?short=yes
Но если вы хотите сделать query-параметр обязательным, вы можете просто не указывать значение по умолчанию:
-{* ../../docs_src/query_params/tutorial005.py hl[6:7] *}
+{* ../../docs_src/query_params/tutorial005_py39.py hl[6:7] *}
Здесь параметр запроса `needy` является обязательным параметром с типом данных `str`.
diff --git a/docs/ru/docs/tutorial/response-model.md b/docs/ru/docs/tutorial/response-model.md
index c045f9ed78..07308c1db2 100644
--- a/docs/ru/docs/tutorial/response-model.md
+++ b/docs/ru/docs/tutorial/response-model.md
@@ -183,7 +183,7 @@ FastAPI делает несколько вещей внутри вместе с
Самый распространённый случай — [возвращать Response напрямую, как описано далее в разделах для продвинутых](../advanced/response-directly.md){.internal-link target=_blank}.
-{* ../../docs_src/response_model/tutorial003_02.py hl[8,10:11] *}
+{* ../../docs_src/response_model/tutorial003_02_py39.py hl[8,10:11] *}
Этот простой случай обрабатывается FastAPI автоматически, потому что аннотация возвращаемого типа — это класс (или подкласс) `Response`.
@@ -193,7 +193,7 @@ FastAPI делает несколько вещей внутри вместе с
Вы также можете использовать подкласс `Response` в аннотации типа:
-{* ../../docs_src/response_model/tutorial003_03.py hl[8:9] *}
+{* ../../docs_src/response_model/tutorial003_03_py39.py hl[8:9] *}
Это тоже сработает, так как `RedirectResponse` — подкласс `Response`, и FastAPI автоматически обработает этот случай.
diff --git a/docs/ru/docs/tutorial/response-status-code.md b/docs/ru/docs/tutorial/response-status-code.md
index f5b1ff6ad7..30f642b643 100644
--- a/docs/ru/docs/tutorial/response-status-code.md
+++ b/docs/ru/docs/tutorial/response-status-code.md
@@ -8,7 +8,7 @@
* `@app.delete()`
* и других.
-{* ../../docs_src/response_status_code/tutorial001.py hl[6] *}
+{* ../../docs_src/response_status_code/tutorial001_py39.py hl[6] *}
/// note | Примечание
@@ -74,7 +74,7 @@ FastAPI знает об этом и создаст документацию Open
Рассмотрим предыдущий пример еще раз:
-{* ../../docs_src/response_status_code/tutorial001.py hl[6] *}
+{* ../../docs_src/response_status_code/tutorial001_py39.py hl[6] *}
`201` – это код статуса "Создано".
@@ -82,7 +82,7 @@ FastAPI знает об этом и создаст документацию Open
Для удобства вы можете использовать переменные из `fastapi.status`.
-{* ../../docs_src/response_status_code/tutorial002.py hl[1,6] *}
+{* ../../docs_src/response_status_code/tutorial002_py39.py hl[1,6] *}
Они содержат те же числовые значения, но позволяют использовать автозавершение редактора кода для выбора кода статуса:
diff --git a/docs/ru/docs/tutorial/static-files.md b/docs/ru/docs/tutorial/static-files.md
index 8455aea0a2..f40cfe9b04 100644
--- a/docs/ru/docs/tutorial/static-files.md
+++ b/docs/ru/docs/tutorial/static-files.md
@@ -7,7 +7,7 @@
* Импортируйте `StaticFiles`.
* "Примонтируйте" экземпляр `StaticFiles()` к определённому пути.
-{* ../../docs_src/static_files/tutorial001.py hl[2,6] *}
+{* ../../docs_src/static_files/tutorial001_py39.py hl[2,6] *}
/// note | Технические детали
diff --git a/docs/ru/docs/tutorial/testing.md b/docs/ru/docs/tutorial/testing.md
index 7354ed895f..ab58429c51 100644
--- a/docs/ru/docs/tutorial/testing.md
+++ b/docs/ru/docs/tutorial/testing.md
@@ -30,7 +30,7 @@ $ pip install httpx
Напишите простое утверждение с `assert` дабы проверить истинность Python-выражения (это тоже стандарт `pytest`).
-{* ../../docs_src/app_testing/tutorial001.py hl[2,12,15:18] *}
+{* ../../docs_src/app_testing/tutorial001_py39.py hl[2,12,15:18] *}
/// tip | Подсказка
@@ -76,7 +76,7 @@ $ pip install httpx
В файле `main.py` находится Ваше приложение **FastAPI**:
-{* ../../docs_src/app_testing/main.py *}
+{* ../../docs_src/app_testing/app_a_py39/main.py *}
### Файл тестов { #testing-file }
@@ -92,7 +92,7 @@ $ pip install httpx
Так как оба файла находятся в одной директории, для импорта объекта приложения из файла `main` в файл `test_main` Вы можете использовать относительный импорт:
-{* ../../docs_src/app_testing/test_main.py hl[3] *}
+{* ../../docs_src/app_testing/app_a_py39/test_main.py hl[3] *}
...и писать дальше тесты, как и раньше.
diff --git a/docs/tr/llm-prompt.md b/docs/tr/llm-prompt.md
new file mode 100644
index 0000000000..297b0a0e6c
--- /dev/null
+++ b/docs/tr/llm-prompt.md
@@ -0,0 +1,52 @@
+### Target language
+
+Translate to Turkish (Türkçe).
+
+Language code: tr.
+
+### Grammar and tone
+
+- Use instructional Turkish, consistent with existing Turkish docs.
+- Use imperative/guide language when appropriate (e.g. “açalım”, “gidin”, “kopyalayalım”).
+
+### Headings
+
+- Follow existing Turkish heading style (Title Case where used; no trailing period).
+
+### Quotes
+
+- Alıntı stili mevcut Türkçe dokümanlarla tutarlı tutun (genellikle metin içinde ASCII tırnak işaretleri kullanılır).
+- Satır içi kod, kod blokları, URL'ler veya dosya yolları içindeki tırnak işaretlerini asla değiştirmeyin.
+
+### Ellipsis
+
+- Üç nokta (...) stili mevcut Türkçe dokümanlarla tutarlı tutun.
+- Kod, URL veya CLI örneklerindeki `...` ifadesini asla değiştirmeyin.
+
+### Preferred translations / glossary
+
+Do not translate technical terms like path, route, request, response, query, body, cookie, and header, keep them as is.
+
+- Suffixing is very important, when adding Turkish suffixes to the English words, do that based on the pronunciation of the word and with an apostrophe.
+
+- Suffixes also changes based on what word comes next in Turkish too, here is an example:
+
+"Server'a gelen request'leri intercept... " or this could have been "request'e", "request'i" etc.
+
+- Some words are tricky like "path'e" can't be used like "path'a" but it could have been "path'i" "path'leri" etc.
+
+- You can use a more instructional style, that is consistent with the document, you can add the Turkish version of the term in parenthesis if it is not something very obvious, or an advanced concept, but do not over do it, do it only the first time it is mentioned, but keep the English term as the primary word.
+
+### `///` admonitions
+
+- Keep the admonition keyword in English (do not translate `note`, `tip`, etc.).
+- If a title is present, prefer these canonical titles:
+
+- `/// note | Not`
+- `/// note | Teknik Detaylar`
+- `/// tip | İpucu`
+- `/// warning | Uyarı`
+- `/// info | Bilgi`
+- `/// check | Ek bilgi`
+
+Prefer `İpucu` over `Ipucu`.
diff --git a/docs/uk/llm-prompt.md b/docs/uk/llm-prompt.md
new file mode 100644
index 0000000000..f1c5377a48
--- /dev/null
+++ b/docs/uk/llm-prompt.md
@@ -0,0 +1,46 @@
+### Target language
+
+Translate to Ukrainian (українська).
+
+Language code: uk.
+
+### Grammar and tone
+
+- Use polite/formal address consistent with existing Ukrainian docs (use “ви/ваш”).
+- Keep the tone concise and technical.
+
+### Headings
+
+- Follow existing Ukrainian heading style; keep headings short and instructional.
+- Do not add trailing punctuation to headings.
+
+### Quotes
+
+- Prefer Ukrainian guillemets «…» for quoted terms in prose, matching existing Ukrainian docs.
+- Never change quotes inside inline code, code blocks, URLs, or file paths.
+
+### Ellipsis
+
+- Keep ellipsis style consistent with existing Ukrainian docs.
+- Never change `...` in code, URLs, or CLI examples.
+
+### Preferred translations / glossary
+
+Use the following preferred translations when they apply in documentation prose:
+
+- request (HTTP): запит
+- response (HTTP): відповідь
+- path operation: операція шляху
+- path operation function: функція операції шляху
+
+### `///` admonitions
+
+- Keep the admonition keyword in English (do not translate `note`, `tip`, etc.).
+- If a title is present, prefer these canonical titles (choose one canonical form where variants exist):
+
+- `/// note | Примітка`
+- `/// note | Технічні деталі`
+- `/// tip | Порада`
+- `/// warning | Попередження`
+- `/// info | Інформація`
+- `/// danger | Обережно`
diff --git a/docs/zh-hant/llm-prompt.md b/docs/zh-hant/llm-prompt.md
new file mode 100644
index 0000000000..d44709015c
--- /dev/null
+++ b/docs/zh-hant/llm-prompt.md
@@ -0,0 +1,60 @@
+### Target language
+
+Translate to Traditional Chinese (繁體中文).
+
+Language code: zh-hant.
+
+### Grammar and tone
+
+- Use clear, concise technical Traditional Chinese consistent with existing docs.
+- Address the reader naturally (commonly using “你/你的”).
+
+### Headings
+
+- Follow existing Traditional Chinese heading style (short and descriptive).
+- Do not add trailing punctuation to headings.
+
+### Quotes and punctuation
+
+- Keep punctuation style consistent with existing Traditional Chinese docs (they often mix English terms like “FastAPI” with Chinese text).
+- Never change punctuation inside inline code, code blocks, URLs, or file paths.
+- For more details, please follow the [Chinese Copywriting Guidelines](https://github.com/sparanoid/chinese-copywriting-guidelines).
+
+### Ellipsis
+
+- Keep ellipsis style consistent within each document, prefer `...` over `……`.
+- Never change ellipsis in code, URLs, or CLI examples.
+
+### Preferred translations / glossary
+
+- Should avoid using simplified Chinese characters and terms. Always examine if the translation can be easily comprehended by the Traditional Chinese readers.
+- For some Python-specific terms like "pickle", "list", "dict" etc, we don't have to translate them.
+- Use the following preferred translations when they apply in documentation prose:
+
+- request (HTTP): 請求
+- response (HTTP): 回應
+- path operation: 路徑操作
+- path operation function: 路徑操作函式
+
+The translation can optionally include the original English text only in the first occurrence of each page (e.g. "路徑操作 (path operation)") if the translation is hard to be comprehended by most of the Chinese readers.
+
+### `///` admonitions
+
+1) Keep the admonition keyword in English (do not translate `note`, `tip`, etc.).
+2) Many Traditional Chinese docs currently omit titles in `///` blocks; that is OK.
+3) If a generic title is present, prefer these canonical titles:
+
+- `/// note | 注意`
+
+Notes:
+
+- `details` blocks exist; keep `/// details` as-is and translate only the title after `|`.
+- Example canonical titles used in existing docs:
+
+```
+/// details | 上述指令的含義
+```
+
+```
+/// details | 關於 `requirements.txt`
+```
diff --git a/docs/zh/docs/advanced/dataclasses.md b/docs/zh/docs/advanced/dataclasses.md
index c74ce65c3e..4e8e77d2ac 100644
--- a/docs/zh/docs/advanced/dataclasses.md
+++ b/docs/zh/docs/advanced/dataclasses.md
@@ -4,7 +4,7 @@ FastAPI 基于 **Pydantic** 构建,前文已经介绍过如何使用 Pydantic
但 FastAPI 还可以使用数据类(`dataclasses`):
-{* ../../docs_src/dataclasses/tutorial001.py hl[1,7:12,19:20] *}
+{* ../../docs_src/dataclasses_/tutorial001.py hl[1,7:12,19:20] *}
这还是借助于 **Pydantic** 及其内置的 `dataclasses`。
@@ -32,7 +32,7 @@ FastAPI 基于 **Pydantic** 构建,前文已经介绍过如何使用 Pydantic
在 `response_model` 参数中使用 `dataclasses`:
-{* ../../docs_src/dataclasses/tutorial002.py hl[1,7:13,19] *}
+{* ../../docs_src/dataclasses_/tutorial002.py hl[1,7:13,19] *}
本例把数据类自动转换为 Pydantic 数据类。
@@ -49,7 +49,7 @@ API 文档中也会显示相关概图:
本例把标准的 `dataclasses` 直接替换为 `pydantic.dataclasses`:
```{ .python .annotate hl_lines="1 5 8-11 14-17 23-25 28" }
-{!../../docs_src/dataclasses/tutorial003.py!}
+{!../../docs_src/dataclasses_/tutorial003.py!}
```
1. 本例依然要从标准的 `dataclasses` 中导入 `field`;
diff --git a/docs/zh/llm-prompt.md b/docs/zh/llm-prompt.md
new file mode 100644
index 0000000000..7ce6f96a47
--- /dev/null
+++ b/docs/zh/llm-prompt.md
@@ -0,0 +1,46 @@
+### Target language
+
+Translate to Simplified Chinese (简体中文).
+
+Language code: zh.
+
+### Grammar and tone
+
+- Use clear, concise technical Chinese consistent with existing docs.
+- Address the reader naturally (commonly using “你/你的”).
+
+### Headings
+
+- Follow existing Simplified Chinese heading style (short and descriptive).
+- Do not add trailing punctuation to headings.
+- If a heading contains only the name of a FastAPI feature, do not translate it.
+
+### Quotes and punctuation
+
+- Keep punctuation style consistent with existing Simplified Chinese docs (they often mix English terms like “FastAPI” with Chinese text).
+- Never change punctuation inside inline code, code blocks, URLs, or file paths.
+
+### Ellipsis
+
+- Keep ellipsis style consistent within each document, prefer `...` over `……`.
+- Never change ellipsis in code, URLs, or CLI examples.
+
+### Preferred translations / glossary
+
+Use the following preferred translations when they apply in documentation prose:
+
+- request (HTTP): 请求
+- response (HTTP): 响应
+- path operation: 路径操作
+- path operation function: 路径操作函数
+
+### `///` admonitions
+
+- Keep the admonition keyword in English (do not translate `note`, `tip`, etc.).
+- If a title is present, prefer these canonical titles:
+
+- `/// tip | 提示`
+- `/// note | 注意`
+- `/// warning | 警告`
+- `/// info | 信息`
+- `/// danger | 危险`
diff --git a/docs_src/app_testing/app_b/__init__.py b/docs_src/additional_responses/__init__.py
similarity index 100%
rename from docs_src/app_testing/app_b/__init__.py
rename to docs_src/additional_responses/__init__.py
diff --git a/docs_src/additional_responses/tutorial001.py b/docs_src/additional_responses/tutorial001_py39.py
similarity index 100%
rename from docs_src/additional_responses/tutorial001.py
rename to docs_src/additional_responses/tutorial001_py39.py
diff --git a/docs_src/additional_responses/tutorial002.py b/docs_src/additional_responses/tutorial002_py39.py
similarity index 100%
rename from docs_src/additional_responses/tutorial002.py
rename to docs_src/additional_responses/tutorial002_py39.py
diff --git a/docs_src/additional_responses/tutorial003.py b/docs_src/additional_responses/tutorial003_py39.py
similarity index 100%
rename from docs_src/additional_responses/tutorial003.py
rename to docs_src/additional_responses/tutorial003_py39.py
diff --git a/docs_src/additional_responses/tutorial004.py b/docs_src/additional_responses/tutorial004_py39.py
similarity index 100%
rename from docs_src/additional_responses/tutorial004.py
rename to docs_src/additional_responses/tutorial004_py39.py
diff --git a/docs_src/app_testing/app_b_an/__init__.py b/docs_src/additional_status_codes/__init__.py
similarity index 100%
rename from docs_src/app_testing/app_b_an/__init__.py
rename to docs_src/additional_status_codes/__init__.py
diff --git a/docs_src/additional_status_codes/tutorial001_an.py b/docs_src/additional_status_codes/tutorial001_an.py
deleted file mode 100644
index b5ad6a16b6..0000000000
--- a/docs_src/additional_status_codes/tutorial001_an.py
+++ /dev/null
@@ -1,26 +0,0 @@
-from typing import Union
-
-from fastapi import Body, FastAPI, status
-from fastapi.responses import JSONResponse
-from typing_extensions import Annotated
-
-app = FastAPI()
-
-items = {"foo": {"name": "Fighters", "size": 6}, "bar": {"name": "Tenders", "size": 3}}
-
-
-@app.put("/items/{item_id}")
-async def upsert_item(
- item_id: str,
- name: Annotated[Union[str, None], Body()] = None,
- size: Annotated[Union[int, None], Body()] = None,
-):
- if item_id in items:
- item = items[item_id]
- item["name"] = name
- item["size"] = size
- return item
- else:
- item = {"name": name, "size": size}
- items[item_id] = item
- return JSONResponse(status_code=status.HTTP_201_CREATED, content=item)
diff --git a/docs_src/additional_status_codes/tutorial001.py b/docs_src/additional_status_codes/tutorial001_py39.py
similarity index 100%
rename from docs_src/additional_status_codes/tutorial001.py
rename to docs_src/additional_status_codes/tutorial001_py39.py
diff --git a/docs_src/bigger_applications/app/__init__.py b/docs_src/advanced_middleware/__init__.py
similarity index 100%
rename from docs_src/bigger_applications/app/__init__.py
rename to docs_src/advanced_middleware/__init__.py
diff --git a/docs_src/advanced_middleware/tutorial001.py b/docs_src/advanced_middleware/tutorial001_py39.py
similarity index 100%
rename from docs_src/advanced_middleware/tutorial001.py
rename to docs_src/advanced_middleware/tutorial001_py39.py
diff --git a/docs_src/advanced_middleware/tutorial002.py b/docs_src/advanced_middleware/tutorial002_py39.py
similarity index 100%
rename from docs_src/advanced_middleware/tutorial002.py
rename to docs_src/advanced_middleware/tutorial002_py39.py
diff --git a/docs_src/advanced_middleware/tutorial003.py b/docs_src/advanced_middleware/tutorial003_py39.py
similarity index 100%
rename from docs_src/advanced_middleware/tutorial003.py
rename to docs_src/advanced_middleware/tutorial003_py39.py
diff --git a/docs_src/bigger_applications/app/internal/__init__.py b/docs_src/app_testing/app_a_py39/__init__.py
similarity index 100%
rename from docs_src/bigger_applications/app/internal/__init__.py
rename to docs_src/app_testing/app_a_py39/__init__.py
diff --git a/docs_src/app_testing/main.py b/docs_src/app_testing/app_a_py39/main.py
similarity index 100%
rename from docs_src/app_testing/main.py
rename to docs_src/app_testing/app_a_py39/main.py
diff --git a/docs_src/app_testing/test_main.py b/docs_src/app_testing/app_a_py39/test_main.py
similarity index 100%
rename from docs_src/app_testing/test_main.py
rename to docs_src/app_testing/app_a_py39/test_main.py
diff --git a/docs_src/app_testing/app_b_an/main.py b/docs_src/app_testing/app_b_an/main.py
deleted file mode 100644
index c66278fdd0..0000000000
--- a/docs_src/app_testing/app_b_an/main.py
+++ /dev/null
@@ -1,39 +0,0 @@
-from typing import Union
-
-from fastapi import FastAPI, Header, HTTPException
-from pydantic import BaseModel
-from typing_extensions import Annotated
-
-fake_secret_token = "coneofsilence"
-
-fake_db = {
- "foo": {"id": "foo", "title": "Foo", "description": "There goes my hero"},
- "bar": {"id": "bar", "title": "Bar", "description": "The bartenders"},
-}
-
-app = FastAPI()
-
-
-class Item(BaseModel):
- id: str
- title: str
- description: Union[str, None] = None
-
-
-@app.get("/items/{item_id}", response_model=Item)
-async def read_main(item_id: str, x_token: Annotated[str, Header()]):
- if x_token != fake_secret_token:
- raise HTTPException(status_code=400, detail="Invalid X-Token header")
- if item_id not in fake_db:
- raise HTTPException(status_code=404, detail="Item not found")
- return fake_db[item_id]
-
-
-@app.post("/items/", response_model=Item)
-async def create_item(item: Item, x_token: Annotated[str, Header()]):
- if x_token != fake_secret_token:
- raise HTTPException(status_code=400, detail="Invalid X-Token header")
- if item.id in fake_db:
- raise HTTPException(status_code=409, detail="Item already exists")
- fake_db[item.id] = item
- return item
diff --git a/docs_src/app_testing/app_b_an/test_main.py b/docs_src/app_testing/app_b_an/test_main.py
deleted file mode 100644
index 4e1c51ecc8..0000000000
--- a/docs_src/app_testing/app_b_an/test_main.py
+++ /dev/null
@@ -1,65 +0,0 @@
-from fastapi.testclient import TestClient
-
-from .main import app
-
-client = TestClient(app)
-
-
-def test_read_item():
- response = client.get("/items/foo", headers={"X-Token": "coneofsilence"})
- assert response.status_code == 200
- assert response.json() == {
- "id": "foo",
- "title": "Foo",
- "description": "There goes my hero",
- }
-
-
-def test_read_item_bad_token():
- response = client.get("/items/foo", headers={"X-Token": "hailhydra"})
- assert response.status_code == 400
- assert response.json() == {"detail": "Invalid X-Token header"}
-
-
-def test_read_nonexistent_item():
- response = client.get("/items/baz", headers={"X-Token": "coneofsilence"})
- assert response.status_code == 404
- assert response.json() == {"detail": "Item not found"}
-
-
-def test_create_item():
- response = client.post(
- "/items/",
- headers={"X-Token": "coneofsilence"},
- json={"id": "foobar", "title": "Foo Bar", "description": "The Foo Barters"},
- )
- assert response.status_code == 200
- assert response.json() == {
- "id": "foobar",
- "title": "Foo Bar",
- "description": "The Foo Barters",
- }
-
-
-def test_create_item_bad_token():
- response = client.post(
- "/items/",
- headers={"X-Token": "hailhydra"},
- json={"id": "bazz", "title": "Bazz", "description": "Drop the bazz"},
- )
- assert response.status_code == 400
- assert response.json() == {"detail": "Invalid X-Token header"}
-
-
-def test_create_existing_item():
- response = client.post(
- "/items/",
- headers={"X-Token": "coneofsilence"},
- json={
- "id": "foo",
- "title": "The Foo ID Stealers",
- "description": "There goes my stealer",
- },
- )
- assert response.status_code == 409
- assert response.json() == {"detail": "Item already exists"}
diff --git a/docs_src/bigger_applications/app/routers/__init__.py b/docs_src/app_testing/app_b_py39/__init__.py
similarity index 100%
rename from docs_src/bigger_applications/app/routers/__init__.py
rename to docs_src/app_testing/app_b_py39/__init__.py
diff --git a/docs_src/app_testing/app_b/main.py b/docs_src/app_testing/app_b_py39/main.py
similarity index 100%
rename from docs_src/app_testing/app_b/main.py
rename to docs_src/app_testing/app_b_py39/main.py
diff --git a/docs_src/app_testing/app_b/test_main.py b/docs_src/app_testing/app_b_py39/test_main.py
similarity index 100%
rename from docs_src/app_testing/app_b/test_main.py
rename to docs_src/app_testing/app_b_py39/test_main.py
diff --git a/docs_src/app_testing/tutorial001.py b/docs_src/app_testing/tutorial001_py39.py
similarity index 100%
rename from docs_src/app_testing/tutorial001.py
rename to docs_src/app_testing/tutorial001_py39.py
diff --git a/docs_src/app_testing/tutorial002.py b/docs_src/app_testing/tutorial002_py39.py
similarity index 100%
rename from docs_src/app_testing/tutorial002.py
rename to docs_src/app_testing/tutorial002_py39.py
diff --git a/docs_src/app_testing/tutorial003.py b/docs_src/app_testing/tutorial003_py39.py
similarity index 100%
rename from docs_src/app_testing/tutorial003.py
rename to docs_src/app_testing/tutorial003_py39.py
diff --git a/docs_src/app_testing/tutorial004.py b/docs_src/app_testing/tutorial004_py39.py
similarity index 100%
rename from docs_src/app_testing/tutorial004.py
rename to docs_src/app_testing/tutorial004_py39.py
diff --git a/docs_src/bigger_applications/app_an/__init__.py b/docs_src/async_tests/app_a_py39/__init__.py
similarity index 100%
rename from docs_src/bigger_applications/app_an/__init__.py
rename to docs_src/async_tests/app_a_py39/__init__.py
diff --git a/docs_src/async_tests/main.py b/docs_src/async_tests/app_a_py39/main.py
similarity index 100%
rename from docs_src/async_tests/main.py
rename to docs_src/async_tests/app_a_py39/main.py
diff --git a/docs_src/async_tests/test_main.py b/docs_src/async_tests/app_a_py39/test_main.py
similarity index 100%
rename from docs_src/async_tests/test_main.py
rename to docs_src/async_tests/app_a_py39/test_main.py
diff --git a/docs_src/bigger_applications/app_an/internal/__init__.py b/docs_src/authentication_error_status_code/__init__.py
similarity index 100%
rename from docs_src/bigger_applications/app_an/internal/__init__.py
rename to docs_src/authentication_error_status_code/__init__.py
diff --git a/docs_src/authentication_error_status_code/tutorial001_an.py b/docs_src/authentication_error_status_code/tutorial001_an.py
deleted file mode 100644
index 40678e858d..0000000000
--- a/docs_src/authentication_error_status_code/tutorial001_an.py
+++ /dev/null
@@ -1,20 +0,0 @@
-from fastapi import Depends, FastAPI, HTTPException, status
-from fastapi.security import HTTPAuthorizationCredentials, HTTPBearer
-from typing_extensions import Annotated
-
-app = FastAPI()
-
-
-class HTTPBearer403(HTTPBearer):
- def make_not_authenticated_error(self) -> HTTPException:
- return HTTPException(
- status_code=status.HTTP_403_FORBIDDEN, detail="Not authenticated"
- )
-
-
-CredentialsDep = Annotated[HTTPAuthorizationCredentials, Depends(HTTPBearer403())]
-
-
-@app.get("/me")
-def read_me(credentials: CredentialsDep):
- return {"message": "You are authenticated", "token": credentials.credentials}
diff --git a/docs_src/bigger_applications/app_an/routers/__init__.py b/docs_src/background_tasks/__init__.py
similarity index 100%
rename from docs_src/bigger_applications/app_an/routers/__init__.py
rename to docs_src/background_tasks/__init__.py
diff --git a/docs_src/background_tasks/tutorial001.py b/docs_src/background_tasks/tutorial001_py39.py
similarity index 100%
rename from docs_src/background_tasks/tutorial001.py
rename to docs_src/background_tasks/tutorial001_py39.py
diff --git a/docs_src/background_tasks/tutorial002_an.py b/docs_src/background_tasks/tutorial002_an.py
deleted file mode 100644
index f63502b09a..0000000000
--- a/docs_src/background_tasks/tutorial002_an.py
+++ /dev/null
@@ -1,27 +0,0 @@
-from typing import Union
-
-from fastapi import BackgroundTasks, Depends, FastAPI
-from typing_extensions import Annotated
-
-app = FastAPI()
-
-
-def write_log(message: str):
- with open("log.txt", mode="a") as log:
- log.write(message)
-
-
-def get_query(background_tasks: BackgroundTasks, q: Union[str, None] = None):
- if q:
- message = f"found query: {q}\n"
- background_tasks.add_task(write_log, message)
- return q
-
-
-@app.post("/send-notification/{email}")
-async def send_notification(
- email: str, background_tasks: BackgroundTasks, q: Annotated[str, Depends(get_query)]
-):
- message = f"message to {email}\n"
- background_tasks.add_task(write_log, message)
- return {"message": "Message sent"}
diff --git a/docs_src/background_tasks/tutorial002.py b/docs_src/background_tasks/tutorial002_py39.py
similarity index 100%
rename from docs_src/background_tasks/tutorial002.py
rename to docs_src/background_tasks/tutorial002_py39.py
diff --git a/docs_src/settings/app01/__init__.py b/docs_src/behind_a_proxy/__init__.py
similarity index 100%
rename from docs_src/settings/app01/__init__.py
rename to docs_src/behind_a_proxy/__init__.py
diff --git a/docs_src/behind_a_proxy/tutorial001_01.py b/docs_src/behind_a_proxy/tutorial001_01_py39.py
similarity index 100%
rename from docs_src/behind_a_proxy/tutorial001_01.py
rename to docs_src/behind_a_proxy/tutorial001_01_py39.py
diff --git a/docs_src/behind_a_proxy/tutorial001.py b/docs_src/behind_a_proxy/tutorial001_py39.py
similarity index 100%
rename from docs_src/behind_a_proxy/tutorial001.py
rename to docs_src/behind_a_proxy/tutorial001_py39.py
diff --git a/docs_src/behind_a_proxy/tutorial002.py b/docs_src/behind_a_proxy/tutorial002_py39.py
similarity index 100%
rename from docs_src/behind_a_proxy/tutorial002.py
rename to docs_src/behind_a_proxy/tutorial002_py39.py
diff --git a/docs_src/behind_a_proxy/tutorial003.py b/docs_src/behind_a_proxy/tutorial003_py39.py
similarity index 100%
rename from docs_src/behind_a_proxy/tutorial003.py
rename to docs_src/behind_a_proxy/tutorial003_py39.py
diff --git a/docs_src/behind_a_proxy/tutorial004.py b/docs_src/behind_a_proxy/tutorial004_py39.py
similarity index 100%
rename from docs_src/behind_a_proxy/tutorial004.py
rename to docs_src/behind_a_proxy/tutorial004_py39.py
diff --git a/docs_src/bigger_applications/app_an/dependencies.py b/docs_src/bigger_applications/app_an/dependencies.py
deleted file mode 100644
index 1374c54b31..0000000000
--- a/docs_src/bigger_applications/app_an/dependencies.py
+++ /dev/null
@@ -1,12 +0,0 @@
-from fastapi import Header, HTTPException
-from typing_extensions import Annotated
-
-
-async def get_token_header(x_token: Annotated[str, Header()]):
- if x_token != "fake-super-secret-token":
- raise HTTPException(status_code=400, detail="X-Token header invalid")
-
-
-async def get_query_token(token: str):
- if token != "jessica":
- raise HTTPException(status_code=400, detail="No Jessica token provided")
diff --git a/docs_src/bigger_applications/app_an/internal/admin.py b/docs_src/bigger_applications/app_an/internal/admin.py
deleted file mode 100644
index 99d3da86b9..0000000000
--- a/docs_src/bigger_applications/app_an/internal/admin.py
+++ /dev/null
@@ -1,8 +0,0 @@
-from fastapi import APIRouter
-
-router = APIRouter()
-
-
-@router.post("/")
-async def update_admin():
- return {"message": "Admin getting schwifty"}
diff --git a/docs_src/bigger_applications/app_an/main.py b/docs_src/bigger_applications/app_an/main.py
deleted file mode 100644
index ae544a3aac..0000000000
--- a/docs_src/bigger_applications/app_an/main.py
+++ /dev/null
@@ -1,23 +0,0 @@
-from fastapi import Depends, FastAPI
-
-from .dependencies import get_query_token, get_token_header
-from .internal import admin
-from .routers import items, users
-
-app = FastAPI(dependencies=[Depends(get_query_token)])
-
-
-app.include_router(users.router)
-app.include_router(items.router)
-app.include_router(
- admin.router,
- prefix="/admin",
- tags=["admin"],
- dependencies=[Depends(get_token_header)],
- responses={418: {"description": "I'm a teapot"}},
-)
-
-
-@app.get("/")
-async def root():
- return {"message": "Hello Bigger Applications!"}
diff --git a/docs_src/bigger_applications/app_an/routers/items.py b/docs_src/bigger_applications/app_an/routers/items.py
deleted file mode 100644
index bde9ff4d55..0000000000
--- a/docs_src/bigger_applications/app_an/routers/items.py
+++ /dev/null
@@ -1,38 +0,0 @@
-from fastapi import APIRouter, Depends, HTTPException
-
-from ..dependencies import get_token_header
-
-router = APIRouter(
- prefix="/items",
- tags=["items"],
- dependencies=[Depends(get_token_header)],
- responses={404: {"description": "Not found"}},
-)
-
-
-fake_items_db = {"plumbus": {"name": "Plumbus"}, "gun": {"name": "Portal Gun"}}
-
-
-@router.get("/")
-async def read_items():
- return fake_items_db
-
-
-@router.get("/{item_id}")
-async def read_item(item_id: str):
- if item_id not in fake_items_db:
- raise HTTPException(status_code=404, detail="Item not found")
- return {"name": fake_items_db[item_id]["name"], "item_id": item_id}
-
-
-@router.put(
- "/{item_id}",
- tags=["custom"],
- responses={403: {"description": "Operation forbidden"}},
-)
-async def update_item(item_id: str):
- if item_id != "plumbus":
- raise HTTPException(
- status_code=403, detail="You can only update the item: plumbus"
- )
- return {"item_id": item_id, "name": "The great Plumbus"}
diff --git a/docs_src/bigger_applications/app_an/routers/users.py b/docs_src/bigger_applications/app_an/routers/users.py
deleted file mode 100644
index 39b3d7e7cf..0000000000
--- a/docs_src/bigger_applications/app_an/routers/users.py
+++ /dev/null
@@ -1,18 +0,0 @@
-from fastapi import APIRouter
-
-router = APIRouter()
-
-
-@router.get("/users/", tags=["users"])
-async def read_users():
- return [{"username": "Rick"}, {"username": "Morty"}]
-
-
-@router.get("/users/me", tags=["users"])
-async def read_user_me():
- return {"username": "fakecurrentuser"}
-
-
-@router.get("/users/{username}", tags=["users"])
-async def read_user(username: str):
- return {"username": username}
diff --git a/docs_src/settings/app02/__init__.py b/docs_src/bigger_applications/app_py39/__init__.py
similarity index 100%
rename from docs_src/settings/app02/__init__.py
rename to docs_src/bigger_applications/app_py39/__init__.py
diff --git a/docs_src/bigger_applications/app/dependencies.py b/docs_src/bigger_applications/app_py39/dependencies.py
similarity index 100%
rename from docs_src/bigger_applications/app/dependencies.py
rename to docs_src/bigger_applications/app_py39/dependencies.py
diff --git a/docs_src/settings/app02_an/__init__.py b/docs_src/bigger_applications/app_py39/internal/__init__.py
similarity index 100%
rename from docs_src/settings/app02_an/__init__.py
rename to docs_src/bigger_applications/app_py39/internal/__init__.py
diff --git a/docs_src/bigger_applications/app/internal/admin.py b/docs_src/bigger_applications/app_py39/internal/admin.py
similarity index 100%
rename from docs_src/bigger_applications/app/internal/admin.py
rename to docs_src/bigger_applications/app_py39/internal/admin.py
diff --git a/docs_src/bigger_applications/app/main.py b/docs_src/bigger_applications/app_py39/main.py
similarity index 100%
rename from docs_src/bigger_applications/app/main.py
rename to docs_src/bigger_applications/app_py39/main.py
diff --git a/docs_src/settings/app03/__init__.py b/docs_src/bigger_applications/app_py39/routers/__init__.py
similarity index 100%
rename from docs_src/settings/app03/__init__.py
rename to docs_src/bigger_applications/app_py39/routers/__init__.py
diff --git a/docs_src/bigger_applications/app/routers/items.py b/docs_src/bigger_applications/app_py39/routers/items.py
similarity index 100%
rename from docs_src/bigger_applications/app/routers/items.py
rename to docs_src/bigger_applications/app_py39/routers/items.py
diff --git a/docs_src/bigger_applications/app/routers/users.py b/docs_src/bigger_applications/app_py39/routers/users.py
similarity index 100%
rename from docs_src/bigger_applications/app/routers/users.py
rename to docs_src/bigger_applications/app_py39/routers/users.py
diff --git a/docs_src/settings/app03_an/__init__.py b/docs_src/body/__init__.py
similarity index 100%
rename from docs_src/settings/app03_an/__init__.py
rename to docs_src/body/__init__.py
diff --git a/docs_src/body/tutorial001.py b/docs_src/body/tutorial001_py39.py
similarity index 100%
rename from docs_src/body/tutorial001.py
rename to docs_src/body/tutorial001_py39.py
diff --git a/docs_src/body/tutorial002_py310.py b/docs_src/body/tutorial002_py310.py
index 454c45c886..a829a4dc9d 100644
--- a/docs_src/body/tutorial002_py310.py
+++ b/docs_src/body/tutorial002_py310.py
@@ -14,7 +14,7 @@ app = FastAPI()
@app.post("/items/")
async def create_item(item: Item):
- item_dict = item.dict()
+ item_dict = item.model_dump()
if item.tax is not None:
price_with_tax = item.price + item.tax
item_dict.update({"price_with_tax": price_with_tax})
diff --git a/docs_src/body/tutorial002.py b/docs_src/body/tutorial002_py39.py
similarity index 92%
rename from docs_src/body/tutorial002.py
rename to docs_src/body/tutorial002_py39.py
index 5cd86216b3..fb212e8e79 100644
--- a/docs_src/body/tutorial002.py
+++ b/docs_src/body/tutorial002_py39.py
@@ -16,7 +16,7 @@ app = FastAPI()
@app.post("/items/")
async def create_item(item: Item):
- item_dict = item.dict()
+ item_dict = item.model_dump()
if item.tax is not None:
price_with_tax = item.price + item.tax
item_dict.update({"price_with_tax": price_with_tax})
diff --git a/docs_src/body/tutorial003_py310.py b/docs_src/body/tutorial003_py310.py
index 440b210e6b..51ac8aafac 100644
--- a/docs_src/body/tutorial003_py310.py
+++ b/docs_src/body/tutorial003_py310.py
@@ -14,4 +14,4 @@ app = FastAPI()
@app.put("/items/{item_id}")
async def update_item(item_id: int, item: Item):
- return {"item_id": item_id, **item.dict()}
+ return {"item_id": item_id, **item.model_dump()}
diff --git a/docs_src/body/tutorial003.py b/docs_src/body/tutorial003_py39.py
similarity index 85%
rename from docs_src/body/tutorial003.py
rename to docs_src/body/tutorial003_py39.py
index 2f33cc0389..636ba2275a 100644
--- a/docs_src/body/tutorial003.py
+++ b/docs_src/body/tutorial003_py39.py
@@ -16,4 +16,4 @@ app = FastAPI()
@app.put("/items/{item_id}")
async def update_item(item_id: int, item: Item):
- return {"item_id": item_id, **item.dict()}
+ return {"item_id": item_id, **item.model_dump()}
diff --git a/docs_src/body/tutorial004_py310.py b/docs_src/body/tutorial004_py310.py
index b352b70ab6..53b10d97b6 100644
--- a/docs_src/body/tutorial004_py310.py
+++ b/docs_src/body/tutorial004_py310.py
@@ -14,7 +14,7 @@ app = FastAPI()
@app.put("/items/{item_id}")
async def update_item(item_id: int, item: Item, q: str | None = None):
- result = {"item_id": item_id, **item.dict()}
+ result = {"item_id": item_id, **item.model_dump()}
if q:
result.update({"q": q})
return result
diff --git a/docs_src/body/tutorial004.py b/docs_src/body/tutorial004_py39.py
similarity index 87%
rename from docs_src/body/tutorial004.py
rename to docs_src/body/tutorial004_py39.py
index 0671e0a278..2c157abfa1 100644
--- a/docs_src/body/tutorial004.py
+++ b/docs_src/body/tutorial004_py39.py
@@ -16,7 +16,7 @@ app = FastAPI()
@app.put("/items/{item_id}")
async def update_item(item_id: int, item: Item, q: Union[str, None] = None):
- result = {"item_id": item_id, **item.dict()}
+ result = {"item_id": item_id, **item.model_dump()}
if q:
result.update({"q": q})
return result
diff --git a/tests/test_filter_pydantic_sub_model/__init__.py b/docs_src/body_fields/__init__.py
similarity index 100%
rename from tests/test_filter_pydantic_sub_model/__init__.py
rename to docs_src/body_fields/__init__.py
diff --git a/docs_src/body_fields/tutorial001_an.py b/docs_src/body_fields/tutorial001_an.py
deleted file mode 100644
index 15ea1b53dc..0000000000
--- a/docs_src/body_fields/tutorial001_an.py
+++ /dev/null
@@ -1,22 +0,0 @@
-from typing import Union
-
-from fastapi import Body, FastAPI
-from pydantic import BaseModel, Field
-from typing_extensions import Annotated
-
-app = FastAPI()
-
-
-class Item(BaseModel):
- name: str
- description: Union[str, None] = Field(
- default=None, title="The description of the item", max_length=300
- )
- price: float = Field(gt=0, description="The price must be greater than zero")
- tax: Union[float, None] = None
-
-
-@app.put("/items/{item_id}")
-async def update_item(item_id: int, item: Annotated[Item, Body(embed=True)]):
- results = {"item_id": item_id, "item": item}
- return results
diff --git a/docs_src/body_fields/tutorial001.py b/docs_src/body_fields/tutorial001_py39.py
similarity index 100%
rename from docs_src/body_fields/tutorial001.py
rename to docs_src/body_fields/tutorial001_py39.py
diff --git a/tests/test_pydantic_v1_v2_multifile/__init__.py b/docs_src/body_multiple_params/__init__.py
similarity index 100%
rename from tests/test_pydantic_v1_v2_multifile/__init__.py
rename to docs_src/body_multiple_params/__init__.py
diff --git a/docs_src/body_multiple_params/tutorial001_an.py b/docs_src/body_multiple_params/tutorial001_an.py
deleted file mode 100644
index 308eee8544..0000000000
--- a/docs_src/body_multiple_params/tutorial001_an.py
+++ /dev/null
@@ -1,28 +0,0 @@
-from typing import Union
-
-from fastapi import FastAPI, Path
-from pydantic import BaseModel
-from typing_extensions import Annotated
-
-app = FastAPI()
-
-
-class Item(BaseModel):
- name: str
- description: Union[str, None] = None
- price: float
- tax: Union[float, None] = None
-
-
-@app.put("/items/{item_id}")
-async def update_item(
- item_id: Annotated[int, Path(title="The ID of the item to get", ge=0, le=1000)],
- q: Union[str, None] = None,
- item: Union[Item, None] = None,
-):
- results = {"item_id": item_id}
- if q:
- results.update({"q": q})
- if item:
- results.update({"item": item})
- return results
diff --git a/docs_src/body_multiple_params/tutorial001.py b/docs_src/body_multiple_params/tutorial001_py39.py
similarity index 100%
rename from docs_src/body_multiple_params/tutorial001.py
rename to docs_src/body_multiple_params/tutorial001_py39.py
diff --git a/docs_src/body_multiple_params/tutorial002.py b/docs_src/body_multiple_params/tutorial002_py39.py
similarity index 100%
rename from docs_src/body_multiple_params/tutorial002.py
rename to docs_src/body_multiple_params/tutorial002_py39.py
diff --git a/docs_src/body_multiple_params/tutorial003_an.py b/docs_src/body_multiple_params/tutorial003_an.py
deleted file mode 100644
index 39ef7340a5..0000000000
--- a/docs_src/body_multiple_params/tutorial003_an.py
+++ /dev/null
@@ -1,27 +0,0 @@
-from typing import Union
-
-from fastapi import Body, FastAPI
-from pydantic import BaseModel
-from typing_extensions import Annotated
-
-app = FastAPI()
-
-
-class Item(BaseModel):
- name: str
- description: Union[str, None] = None
- price: float
- tax: Union[float, None] = None
-
-
-class User(BaseModel):
- username: str
- full_name: Union[str, None] = None
-
-
-@app.put("/items/{item_id}")
-async def update_item(
- item_id: int, item: Item, user: User, importance: Annotated[int, Body()]
-):
- results = {"item_id": item_id, "item": item, "user": user, "importance": importance}
- return results
diff --git a/docs_src/body_multiple_params/tutorial003.py b/docs_src/body_multiple_params/tutorial003_py39.py
similarity index 100%
rename from docs_src/body_multiple_params/tutorial003.py
rename to docs_src/body_multiple_params/tutorial003_py39.py
diff --git a/docs_src/body_multiple_params/tutorial004_an.py b/docs_src/body_multiple_params/tutorial004_an.py
deleted file mode 100644
index f6830f3920..0000000000
--- a/docs_src/body_multiple_params/tutorial004_an.py
+++ /dev/null
@@ -1,34 +0,0 @@
-from typing import Union
-
-from fastapi import Body, FastAPI
-from pydantic import BaseModel
-from typing_extensions import Annotated
-
-app = FastAPI()
-
-
-class Item(BaseModel):
- name: str
- description: Union[str, None] = None
- price: float
- tax: Union[float, None] = None
-
-
-class User(BaseModel):
- username: str
- full_name: Union[str, None] = None
-
-
-@app.put("/items/{item_id}")
-async def update_item(
- *,
- item_id: int,
- item: Item,
- user: User,
- importance: Annotated[int, Body(gt=0)],
- q: Union[str, None] = None,
-):
- results = {"item_id": item_id, "item": item, "user": user, "importance": importance}
- if q:
- results.update({"q": q})
- return results
diff --git a/docs_src/body_multiple_params/tutorial004.py b/docs_src/body_multiple_params/tutorial004_py39.py
similarity index 100%
rename from docs_src/body_multiple_params/tutorial004.py
rename to docs_src/body_multiple_params/tutorial004_py39.py
diff --git a/docs_src/body_multiple_params/tutorial005_an.py b/docs_src/body_multiple_params/tutorial005_an.py
deleted file mode 100644
index dadde80b55..0000000000
--- a/docs_src/body_multiple_params/tutorial005_an.py
+++ /dev/null
@@ -1,20 +0,0 @@
-from typing import Union
-
-from fastapi import Body, FastAPI
-from pydantic import BaseModel
-from typing_extensions import Annotated
-
-app = FastAPI()
-
-
-class Item(BaseModel):
- name: str
- description: Union[str, None] = None
- price: float
- tax: Union[float, None] = None
-
-
-@app.put("/items/{item_id}")
-async def update_item(item_id: int, item: Annotated[Item, Body(embed=True)]):
- results = {"item_id": item_id, "item": item}
- return results
diff --git a/docs_src/body_multiple_params/tutorial005.py b/docs_src/body_multiple_params/tutorial005_py39.py
similarity index 100%
rename from docs_src/body_multiple_params/tutorial005.py
rename to docs_src/body_multiple_params/tutorial005_py39.py
diff --git a/tests/test_tutorial/test_pydantic_v1_in_v2/__init__.py b/docs_src/body_nested_models/__init__.py
similarity index 100%
rename from tests/test_tutorial/test_pydantic_v1_in_v2/__init__.py
rename to docs_src/body_nested_models/__init__.py
diff --git a/docs_src/body_nested_models/tutorial001.py b/docs_src/body_nested_models/tutorial001_py39.py
similarity index 100%
rename from docs_src/body_nested_models/tutorial001.py
rename to docs_src/body_nested_models/tutorial001_py39.py
diff --git a/docs_src/body_nested_models/tutorial002.py b/docs_src/body_nested_models/tutorial002.py
deleted file mode 100644
index 155cff7885..0000000000
--- a/docs_src/body_nested_models/tutorial002.py
+++ /dev/null
@@ -1,20 +0,0 @@
-from typing import List, Union
-
-from fastapi import FastAPI
-from pydantic import BaseModel
-
-app = FastAPI()
-
-
-class Item(BaseModel):
- name: str
- description: Union[str, None] = None
- price: float
- tax: Union[float, None] = None
- tags: List[str] = []
-
-
-@app.put("/items/{item_id}")
-async def update_item(item_id: int, item: Item):
- results = {"item_id": item_id, "item": item}
- return results
diff --git a/docs_src/body_nested_models/tutorial003.py b/docs_src/body_nested_models/tutorial003.py
deleted file mode 100644
index 84ed18bf48..0000000000
--- a/docs_src/body_nested_models/tutorial003.py
+++ /dev/null
@@ -1,20 +0,0 @@
-from typing import Set, Union
-
-from fastapi import FastAPI
-from pydantic import BaseModel
-
-app = FastAPI()
-
-
-class Item(BaseModel):
- name: str
- description: Union[str, None] = None
- price: float
- tax: Union[float, None] = None
- tags: Set[str] = set()
-
-
-@app.put("/items/{item_id}")
-async def update_item(item_id: int, item: Item):
- results = {"item_id": item_id, "item": item}
- return results
diff --git a/docs_src/body_nested_models/tutorial004.py b/docs_src/body_nested_models/tutorial004.py
deleted file mode 100644
index a07bfacac1..0000000000
--- a/docs_src/body_nested_models/tutorial004.py
+++ /dev/null
@@ -1,26 +0,0 @@
-from typing import Set, Union
-
-from fastapi import FastAPI
-from pydantic import BaseModel
-
-app = FastAPI()
-
-
-class Image(BaseModel):
- url: str
- name: str
-
-
-class Item(BaseModel):
- name: str
- description: Union[str, None] = None
- price: float
- tax: Union[float, None] = None
- tags: Set[str] = set()
- image: Union[Image, None] = None
-
-
-@app.put("/items/{item_id}")
-async def update_item(item_id: int, item: Item):
- results = {"item_id": item_id, "item": item}
- return results
diff --git a/docs_src/body_nested_models/tutorial005.py b/docs_src/body_nested_models/tutorial005.py
deleted file mode 100644
index 5a01264eda..0000000000
--- a/docs_src/body_nested_models/tutorial005.py
+++ /dev/null
@@ -1,26 +0,0 @@
-from typing import Set, Union
-
-from fastapi import FastAPI
-from pydantic import BaseModel, HttpUrl
-
-app = FastAPI()
-
-
-class Image(BaseModel):
- url: HttpUrl
- name: str
-
-
-class Item(BaseModel):
- name: str
- description: Union[str, None] = None
- price: float
- tax: Union[float, None] = None
- tags: Set[str] = set()
- image: Union[Image, None] = None
-
-
-@app.put("/items/{item_id}")
-async def update_item(item_id: int, item: Item):
- results = {"item_id": item_id, "item": item}
- return results
diff --git a/docs_src/body_nested_models/tutorial006.py b/docs_src/body_nested_models/tutorial006.py
deleted file mode 100644
index 75f1f30e33..0000000000
--- a/docs_src/body_nested_models/tutorial006.py
+++ /dev/null
@@ -1,26 +0,0 @@
-from typing import List, Set, Union
-
-from fastapi import FastAPI
-from pydantic import BaseModel, HttpUrl
-
-app = FastAPI()
-
-
-class Image(BaseModel):
- url: HttpUrl
- name: str
-
-
-class Item(BaseModel):
- name: str
- description: Union[str, None] = None
- price: float
- tax: Union[float, None] = None
- tags: Set[str] = set()
- images: Union[List[Image], None] = None
-
-
-@app.put("/items/{item_id}")
-async def update_item(item_id: int, item: Item):
- results = {"item_id": item_id, "item": item}
- return results
diff --git a/docs_src/body_nested_models/tutorial007.py b/docs_src/body_nested_models/tutorial007.py
deleted file mode 100644
index 641f09dced..0000000000
--- a/docs_src/body_nested_models/tutorial007.py
+++ /dev/null
@@ -1,32 +0,0 @@
-from typing import List, Set, Union
-
-from fastapi import FastAPI
-from pydantic import BaseModel, HttpUrl
-
-app = FastAPI()
-
-
-class Image(BaseModel):
- url: HttpUrl
- name: str
-
-
-class Item(BaseModel):
- name: str
- description: Union[str, None] = None
- price: float
- tax: Union[float, None] = None
- tags: Set[str] = set()
- images: Union[List[Image], None] = None
-
-
-class Offer(BaseModel):
- name: str
- description: Union[str, None] = None
- price: float
- items: List[Item]
-
-
-@app.post("/offers/")
-async def create_offer(offer: Offer):
- return offer
diff --git a/docs_src/body_nested_models/tutorial008.py b/docs_src/body_nested_models/tutorial008.py
deleted file mode 100644
index 3431cc6365..0000000000
--- a/docs_src/body_nested_models/tutorial008.py
+++ /dev/null
@@ -1,16 +0,0 @@
-from typing import List
-
-from fastapi import FastAPI
-from pydantic import BaseModel, HttpUrl
-
-app = FastAPI()
-
-
-class Image(BaseModel):
- url: HttpUrl
- name: str
-
-
-@app.post("/images/multiple/")
-async def create_multiple_images(images: List[Image]):
- return images
diff --git a/docs_src/body_nested_models/tutorial009.py b/docs_src/body_nested_models/tutorial009.py
deleted file mode 100644
index 41dce946ec..0000000000
--- a/docs_src/body_nested_models/tutorial009.py
+++ /dev/null
@@ -1,10 +0,0 @@
-from typing import Dict
-
-from fastapi import FastAPI
-
-app = FastAPI()
-
-
-@app.post("/index-weights/")
-async def create_index_weights(weights: Dict[int, float]):
- return weights
diff --git a/docs_src/body_updates/__init__.py b/docs_src/body_updates/__init__.py
new file mode 100644
index 0000000000..e69de29bb2
diff --git a/docs_src/body_updates/tutorial001.py b/docs_src/body_updates/tutorial001.py
deleted file mode 100644
index 4e65d77e26..0000000000
--- a/docs_src/body_updates/tutorial001.py
+++ /dev/null
@@ -1,34 +0,0 @@
-from typing import List, Union
-
-from fastapi import FastAPI
-from fastapi.encoders import jsonable_encoder
-from pydantic import BaseModel
-
-app = FastAPI()
-
-
-class Item(BaseModel):
- name: Union[str, None] = None
- description: Union[str, None] = None
- price: Union[float, None] = None
- tax: float = 10.5
- tags: List[str] = []
-
-
-items = {
- "foo": {"name": "Foo", "price": 50.2},
- "bar": {"name": "Bar", "description": "The bartenders", "price": 62, "tax": 20.2},
- "baz": {"name": "Baz", "description": None, "price": 50.2, "tax": 10.5, "tags": []},
-}
-
-
-@app.get("/items/{item_id}", response_model=Item)
-async def read_item(item_id: str):
- return items[item_id]
-
-
-@app.put("/items/{item_id}", response_model=Item)
-async def update_item(item_id: str, item: Item):
- update_item_encoded = jsonable_encoder(item)
- items[item_id] = update_item_encoded
- return update_item_encoded
diff --git a/docs_src/body_updates/tutorial002.py b/docs_src/body_updates/tutorial002.py
deleted file mode 100644
index c3a0fe79ea..0000000000
--- a/docs_src/body_updates/tutorial002.py
+++ /dev/null
@@ -1,37 +0,0 @@
-from typing import List, Union
-
-from fastapi import FastAPI
-from fastapi.encoders import jsonable_encoder
-from pydantic import BaseModel
-
-app = FastAPI()
-
-
-class Item(BaseModel):
- name: Union[str, None] = None
- description: Union[str, None] = None
- price: Union[float, None] = None
- tax: float = 10.5
- tags: List[str] = []
-
-
-items = {
- "foo": {"name": "Foo", "price": 50.2},
- "bar": {"name": "Bar", "description": "The bartenders", "price": 62, "tax": 20.2},
- "baz": {"name": "Baz", "description": None, "price": 50.2, "tax": 10.5, "tags": []},
-}
-
-
-@app.get("/items/{item_id}", response_model=Item)
-async def read_item(item_id: str):
- return items[item_id]
-
-
-@app.patch("/items/{item_id}", response_model=Item)
-async def update_item(item_id: str, item: Item):
- stored_item_data = items[item_id]
- stored_item_model = Item(**stored_item_data)
- update_data = item.dict(exclude_unset=True)
- updated_item = stored_item_model.copy(update=update_data)
- items[item_id] = jsonable_encoder(updated_item)
- return updated_item
diff --git a/docs_src/body_updates/tutorial002_py310.py b/docs_src/body_updates/tutorial002_py310.py
index 3498414966..e5db711108 100644
--- a/docs_src/body_updates/tutorial002_py310.py
+++ b/docs_src/body_updates/tutorial002_py310.py
@@ -29,7 +29,7 @@ async def read_item(item_id: str):
async def update_item(item_id: str, item: Item):
stored_item_data = items[item_id]
stored_item_model = Item(**stored_item_data)
- update_data = item.dict(exclude_unset=True)
- updated_item = stored_item_model.copy(update=update_data)
+ update_data = item.model_dump(exclude_unset=True)
+ updated_item = stored_item_model.model_copy(update=update_data)
items[item_id] = jsonable_encoder(updated_item)
return updated_item
diff --git a/docs_src/body_updates/tutorial002_py39.py b/docs_src/body_updates/tutorial002_py39.py
index eb35b35215..eddd7af716 100644
--- a/docs_src/body_updates/tutorial002_py39.py
+++ b/docs_src/body_updates/tutorial002_py39.py
@@ -31,7 +31,7 @@ async def read_item(item_id: str):
async def update_item(item_id: str, item: Item):
stored_item_data = items[item_id]
stored_item_model = Item(**stored_item_data)
- update_data = item.dict(exclude_unset=True)
- updated_item = stored_item_model.copy(update=update_data)
+ update_data = item.model_dump(exclude_unset=True)
+ updated_item = stored_item_model.model_copy(update=update_data)
items[item_id] = jsonable_encoder(updated_item)
return updated_item
diff --git a/docs_src/conditional_openapi/__init__.py b/docs_src/conditional_openapi/__init__.py
new file mode 100644
index 0000000000..e69de29bb2
diff --git a/docs_src/conditional_openapi/tutorial001.py b/docs_src/conditional_openapi/tutorial001_py39.py
similarity index 100%
rename from docs_src/conditional_openapi/tutorial001.py
rename to docs_src/conditional_openapi/tutorial001_py39.py
diff --git a/docs_src/configure_swagger_ui/__init__.py b/docs_src/configure_swagger_ui/__init__.py
new file mode 100644
index 0000000000..e69de29bb2
diff --git a/docs_src/configure_swagger_ui/tutorial001.py b/docs_src/configure_swagger_ui/tutorial001_py39.py
similarity index 100%
rename from docs_src/configure_swagger_ui/tutorial001.py
rename to docs_src/configure_swagger_ui/tutorial001_py39.py
diff --git a/docs_src/configure_swagger_ui/tutorial002.py b/docs_src/configure_swagger_ui/tutorial002_py39.py
similarity index 100%
rename from docs_src/configure_swagger_ui/tutorial002.py
rename to docs_src/configure_swagger_ui/tutorial002_py39.py
diff --git a/docs_src/configure_swagger_ui/tutorial003.py b/docs_src/configure_swagger_ui/tutorial003_py39.py
similarity index 100%
rename from docs_src/configure_swagger_ui/tutorial003.py
rename to docs_src/configure_swagger_ui/tutorial003_py39.py
diff --git a/docs_src/cookie_param_models/__init__.py b/docs_src/cookie_param_models/__init__.py
new file mode 100644
index 0000000000..e69de29bb2
diff --git a/docs_src/cookie_param_models/tutorial001_an.py b/docs_src/cookie_param_models/tutorial001_an.py
deleted file mode 100644
index e5839ffd54..0000000000
--- a/docs_src/cookie_param_models/tutorial001_an.py
+++ /dev/null
@@ -1,18 +0,0 @@
-from typing import Union
-
-from fastapi import Cookie, FastAPI
-from pydantic import BaseModel
-from typing_extensions import Annotated
-
-app = FastAPI()
-
-
-class Cookies(BaseModel):
- session_id: str
- fatebook_tracker: Union[str, None] = None
- googall_tracker: Union[str, None] = None
-
-
-@app.get("/items/")
-async def read_items(cookies: Annotated[Cookies, Cookie()]):
- return cookies
diff --git a/docs_src/cookie_param_models/tutorial001.py b/docs_src/cookie_param_models/tutorial001_py39.py
similarity index 100%
rename from docs_src/cookie_param_models/tutorial001.py
rename to docs_src/cookie_param_models/tutorial001_py39.py
diff --git a/docs_src/cookie_param_models/tutorial002_an.py b/docs_src/cookie_param_models/tutorial002_an.py
deleted file mode 100644
index ce5644b7bd..0000000000
--- a/docs_src/cookie_param_models/tutorial002_an.py
+++ /dev/null
@@ -1,20 +0,0 @@
-from typing import Union
-
-from fastapi import Cookie, FastAPI
-from pydantic import BaseModel
-from typing_extensions import Annotated
-
-app = FastAPI()
-
-
-class Cookies(BaseModel):
- model_config = {"extra": "forbid"}
-
- session_id: str
- fatebook_tracker: Union[str, None] = None
- googall_tracker: Union[str, None] = None
-
-
-@app.get("/items/")
-async def read_items(cookies: Annotated[Cookies, Cookie()]):
- return cookies
diff --git a/docs_src/cookie_param_models/tutorial002_pv1.py b/docs_src/cookie_param_models/tutorial002_pv1.py
deleted file mode 100644
index 13f78b850e..0000000000
--- a/docs_src/cookie_param_models/tutorial002_pv1.py
+++ /dev/null
@@ -1,20 +0,0 @@
-from typing import Union
-
-from fastapi import Cookie, FastAPI
-from pydantic import BaseModel
-
-app = FastAPI()
-
-
-class Cookies(BaseModel):
- class Config:
- extra = "forbid"
-
- session_id: str
- fatebook_tracker: Union[str, None] = None
- googall_tracker: Union[str, None] = None
-
-
-@app.get("/items/")
-async def read_items(cookies: Cookies = Cookie()):
- return cookies
diff --git a/docs_src/cookie_param_models/tutorial002_pv1_an.py b/docs_src/cookie_param_models/tutorial002_pv1_an.py
deleted file mode 100644
index ddfda9b6f5..0000000000
--- a/docs_src/cookie_param_models/tutorial002_pv1_an.py
+++ /dev/null
@@ -1,21 +0,0 @@
-from typing import Union
-
-from fastapi import Cookie, FastAPI
-from pydantic import BaseModel
-from typing_extensions import Annotated
-
-app = FastAPI()
-
-
-class Cookies(BaseModel):
- class Config:
- extra = "forbid"
-
- session_id: str
- fatebook_tracker: Union[str, None] = None
- googall_tracker: Union[str, None] = None
-
-
-@app.get("/items/")
-async def read_items(cookies: Annotated[Cookies, Cookie()]):
- return cookies
diff --git a/docs_src/cookie_param_models/tutorial002_pv1_an_py310.py b/docs_src/cookie_param_models/tutorial002_pv1_an_py310.py
deleted file mode 100644
index ac00360b60..0000000000
--- a/docs_src/cookie_param_models/tutorial002_pv1_an_py310.py
+++ /dev/null
@@ -1,20 +0,0 @@
-from typing import Annotated
-
-from fastapi import Cookie, FastAPI
-from pydantic import BaseModel
-
-app = FastAPI()
-
-
-class Cookies(BaseModel):
- class Config:
- extra = "forbid"
-
- session_id: str
- fatebook_tracker: str | None = None
- googall_tracker: str | None = None
-
-
-@app.get("/items/")
-async def read_items(cookies: Annotated[Cookies, Cookie()]):
- return cookies
diff --git a/docs_src/cookie_param_models/tutorial002_pv1_an_py39.py b/docs_src/cookie_param_models/tutorial002_pv1_an_py39.py
deleted file mode 100644
index 573caea4b1..0000000000
--- a/docs_src/cookie_param_models/tutorial002_pv1_an_py39.py
+++ /dev/null
@@ -1,20 +0,0 @@
-from typing import Annotated, Union
-
-from fastapi import Cookie, FastAPI
-from pydantic import BaseModel
-
-app = FastAPI()
-
-
-class Cookies(BaseModel):
- class Config:
- extra = "forbid"
-
- session_id: str
- fatebook_tracker: Union[str, None] = None
- googall_tracker: Union[str, None] = None
-
-
-@app.get("/items/")
-async def read_items(cookies: Annotated[Cookies, Cookie()]):
- return cookies
diff --git a/docs_src/cookie_param_models/tutorial002_pv1_py310.py b/docs_src/cookie_param_models/tutorial002_pv1_py310.py
deleted file mode 100644
index 2c59aad123..0000000000
--- a/docs_src/cookie_param_models/tutorial002_pv1_py310.py
+++ /dev/null
@@ -1,18 +0,0 @@
-from fastapi import Cookie, FastAPI
-from pydantic import BaseModel
-
-app = FastAPI()
-
-
-class Cookies(BaseModel):
- class Config:
- extra = "forbid"
-
- session_id: str
- fatebook_tracker: str | None = None
- googall_tracker: str | None = None
-
-
-@app.get("/items/")
-async def read_items(cookies: Cookies = Cookie()):
- return cookies
diff --git a/docs_src/cookie_param_models/tutorial002.py b/docs_src/cookie_param_models/tutorial002_py39.py
similarity index 100%
rename from docs_src/cookie_param_models/tutorial002.py
rename to docs_src/cookie_param_models/tutorial002_py39.py
diff --git a/docs_src/cookie_params/__init__.py b/docs_src/cookie_params/__init__.py
new file mode 100644
index 0000000000..e69de29bb2
diff --git a/docs_src/cookie_params/tutorial001_an.py b/docs_src/cookie_params/tutorial001_an.py
deleted file mode 100644
index 6d5931229c..0000000000
--- a/docs_src/cookie_params/tutorial001_an.py
+++ /dev/null
@@ -1,11 +0,0 @@
-from typing import Union
-
-from fastapi import Cookie, FastAPI
-from typing_extensions import Annotated
-
-app = FastAPI()
-
-
-@app.get("/items/")
-async def read_items(ads_id: Annotated[Union[str, None], Cookie()] = None):
- return {"ads_id": ads_id}
diff --git a/docs_src/cookie_params/tutorial001.py b/docs_src/cookie_params/tutorial001_py39.py
similarity index 100%
rename from docs_src/cookie_params/tutorial001.py
rename to docs_src/cookie_params/tutorial001_py39.py
diff --git a/docs_src/cors/__init__.py b/docs_src/cors/__init__.py
new file mode 100644
index 0000000000..e69de29bb2
diff --git a/docs_src/cors/tutorial001.py b/docs_src/cors/tutorial001_py39.py
similarity index 100%
rename from docs_src/cors/tutorial001.py
rename to docs_src/cors/tutorial001_py39.py
diff --git a/docs_src/custom_docs_ui/__init__.py b/docs_src/custom_docs_ui/__init__.py
new file mode 100644
index 0000000000..e69de29bb2
diff --git a/docs_src/custom_docs_ui/tutorial001.py b/docs_src/custom_docs_ui/tutorial001_py39.py
similarity index 100%
rename from docs_src/custom_docs_ui/tutorial001.py
rename to docs_src/custom_docs_ui/tutorial001_py39.py
diff --git a/docs_src/custom_docs_ui/tutorial002.py b/docs_src/custom_docs_ui/tutorial002_py39.py
similarity index 100%
rename from docs_src/custom_docs_ui/tutorial002.py
rename to docs_src/custom_docs_ui/tutorial002_py39.py
diff --git a/docs_src/custom_request_and_route/__init__.py b/docs_src/custom_request_and_route/__init__.py
new file mode 100644
index 0000000000..e69de29bb2
diff --git a/docs_src/custom_request_and_route/tutorial001.py b/docs_src/custom_request_and_route/tutorial001.py
deleted file mode 100644
index 268ce9019e..0000000000
--- a/docs_src/custom_request_and_route/tutorial001.py
+++ /dev/null
@@ -1,35 +0,0 @@
-import gzip
-from typing import Callable, List
-
-from fastapi import Body, FastAPI, Request, Response
-from fastapi.routing import APIRoute
-
-
-class GzipRequest(Request):
- async def body(self) -> bytes:
- if not hasattr(self, "_body"):
- body = await super().body()
- if "gzip" in self.headers.getlist("Content-Encoding"):
- body = gzip.decompress(body)
- self._body = body
- return self._body
-
-
-class GzipRoute(APIRoute):
- def get_route_handler(self) -> Callable:
- original_route_handler = super().get_route_handler()
-
- async def custom_route_handler(request: Request) -> Response:
- request = GzipRequest(request.scope, request.receive)
- return await original_route_handler(request)
-
- return custom_route_handler
-
-
-app = FastAPI()
-app.router.route_class = GzipRoute
-
-
-@app.post("/sum")
-async def sum_numbers(numbers: List[int] = Body()):
- return {"sum": sum(numbers)}
diff --git a/docs_src/custom_request_and_route/tutorial001_an.py b/docs_src/custom_request_and_route/tutorial001_an.py
deleted file mode 100644
index 6224ba8254..0000000000
--- a/docs_src/custom_request_and_route/tutorial001_an.py
+++ /dev/null
@@ -1,36 +0,0 @@
-import gzip
-from typing import Callable, List
-
-from fastapi import Body, FastAPI, Request, Response
-from fastapi.routing import APIRoute
-from typing_extensions import Annotated
-
-
-class GzipRequest(Request):
- async def body(self) -> bytes:
- if not hasattr(self, "_body"):
- body = await super().body()
- if "gzip" in self.headers.getlist("Content-Encoding"):
- body = gzip.decompress(body)
- self._body = body
- return self._body
-
-
-class GzipRoute(APIRoute):
- def get_route_handler(self) -> Callable:
- original_route_handler = super().get_route_handler()
-
- async def custom_route_handler(request: Request) -> Response:
- request = GzipRequest(request.scope, request.receive)
- return await original_route_handler(request)
-
- return custom_route_handler
-
-
-app = FastAPI()
-app.router.route_class = GzipRoute
-
-
-@app.post("/sum")
-async def sum_numbers(numbers: Annotated[List[int], Body()]):
- return {"sum": sum(numbers)}
diff --git a/docs_src/custom_request_and_route/tutorial002.py b/docs_src/custom_request_and_route/tutorial002.py
deleted file mode 100644
index cee4a95f08..0000000000
--- a/docs_src/custom_request_and_route/tutorial002.py
+++ /dev/null
@@ -1,29 +0,0 @@
-from typing import Callable, List
-
-from fastapi import Body, FastAPI, HTTPException, Request, Response
-from fastapi.exceptions import RequestValidationError
-from fastapi.routing import APIRoute
-
-
-class ValidationErrorLoggingRoute(APIRoute):
- def get_route_handler(self) -> Callable:
- original_route_handler = super().get_route_handler()
-
- async def custom_route_handler(request: Request) -> Response:
- try:
- return await original_route_handler(request)
- except RequestValidationError as exc:
- body = await request.body()
- detail = {"errors": exc.errors(), "body": body.decode()}
- raise HTTPException(status_code=422, detail=detail)
-
- return custom_route_handler
-
-
-app = FastAPI()
-app.router.route_class = ValidationErrorLoggingRoute
-
-
-@app.post("/")
-async def sum_numbers(numbers: List[int] = Body()):
- return sum(numbers)
diff --git a/docs_src/custom_request_and_route/tutorial002_an.py b/docs_src/custom_request_and_route/tutorial002_an.py
deleted file mode 100644
index 127f7a9ce0..0000000000
--- a/docs_src/custom_request_and_route/tutorial002_an.py
+++ /dev/null
@@ -1,30 +0,0 @@
-from typing import Callable, List
-
-from fastapi import Body, FastAPI, HTTPException, Request, Response
-from fastapi.exceptions import RequestValidationError
-from fastapi.routing import APIRoute
-from typing_extensions import Annotated
-
-
-class ValidationErrorLoggingRoute(APIRoute):
- def get_route_handler(self) -> Callable:
- original_route_handler = super().get_route_handler()
-
- async def custom_route_handler(request: Request) -> Response:
- try:
- return await original_route_handler(request)
- except RequestValidationError as exc:
- body = await request.body()
- detail = {"errors": exc.errors(), "body": body.decode()}
- raise HTTPException(status_code=422, detail=detail)
-
- return custom_route_handler
-
-
-app = FastAPI()
-app.router.route_class = ValidationErrorLoggingRoute
-
-
-@app.post("/")
-async def sum_numbers(numbers: Annotated[List[int], Body()]):
- return sum(numbers)
diff --git a/docs_src/custom_request_and_route/tutorial003.py b/docs_src/custom_request_and_route/tutorial003_py39.py
similarity index 100%
rename from docs_src/custom_request_and_route/tutorial003.py
rename to docs_src/custom_request_and_route/tutorial003_py39.py
diff --git a/docs_src/custom_response/__init__.py b/docs_src/custom_response/__init__.py
new file mode 100644
index 0000000000..e69de29bb2
diff --git a/docs_src/custom_response/tutorial001.py b/docs_src/custom_response/tutorial001_py39.py
similarity index 100%
rename from docs_src/custom_response/tutorial001.py
rename to docs_src/custom_response/tutorial001_py39.py
diff --git a/docs_src/custom_response/tutorial001b.py b/docs_src/custom_response/tutorial001b_py39.py
similarity index 100%
rename from docs_src/custom_response/tutorial001b.py
rename to docs_src/custom_response/tutorial001b_py39.py
diff --git a/docs_src/custom_response/tutorial002.py b/docs_src/custom_response/tutorial002_py39.py
similarity index 100%
rename from docs_src/custom_response/tutorial002.py
rename to docs_src/custom_response/tutorial002_py39.py
diff --git a/docs_src/custom_response/tutorial003.py b/docs_src/custom_response/tutorial003_py39.py
similarity index 100%
rename from docs_src/custom_response/tutorial003.py
rename to docs_src/custom_response/tutorial003_py39.py
diff --git a/docs_src/custom_response/tutorial004.py b/docs_src/custom_response/tutorial004_py39.py
similarity index 100%
rename from docs_src/custom_response/tutorial004.py
rename to docs_src/custom_response/tutorial004_py39.py
diff --git a/docs_src/custom_response/tutorial005.py b/docs_src/custom_response/tutorial005_py39.py
similarity index 100%
rename from docs_src/custom_response/tutorial005.py
rename to docs_src/custom_response/tutorial005_py39.py
diff --git a/docs_src/custom_response/tutorial006.py b/docs_src/custom_response/tutorial006_py39.py
similarity index 100%
rename from docs_src/custom_response/tutorial006.py
rename to docs_src/custom_response/tutorial006_py39.py
diff --git a/docs_src/custom_response/tutorial006b.py b/docs_src/custom_response/tutorial006b_py39.py
similarity index 100%
rename from docs_src/custom_response/tutorial006b.py
rename to docs_src/custom_response/tutorial006b_py39.py
diff --git a/docs_src/custom_response/tutorial006c.py b/docs_src/custom_response/tutorial006c_py39.py
similarity index 100%
rename from docs_src/custom_response/tutorial006c.py
rename to docs_src/custom_response/tutorial006c_py39.py
diff --git a/docs_src/custom_response/tutorial007.py b/docs_src/custom_response/tutorial007_py39.py
similarity index 100%
rename from docs_src/custom_response/tutorial007.py
rename to docs_src/custom_response/tutorial007_py39.py
diff --git a/docs_src/custom_response/tutorial008.py b/docs_src/custom_response/tutorial008_py39.py
similarity index 100%
rename from docs_src/custom_response/tutorial008.py
rename to docs_src/custom_response/tutorial008_py39.py
diff --git a/docs_src/custom_response/tutorial009.py b/docs_src/custom_response/tutorial009_py39.py
similarity index 100%
rename from docs_src/custom_response/tutorial009.py
rename to docs_src/custom_response/tutorial009_py39.py
diff --git a/docs_src/custom_response/tutorial009b.py b/docs_src/custom_response/tutorial009b_py39.py
similarity index 100%
rename from docs_src/custom_response/tutorial009b.py
rename to docs_src/custom_response/tutorial009b_py39.py
diff --git a/docs_src/custom_response/tutorial009c.py b/docs_src/custom_response/tutorial009c_py39.py
similarity index 100%
rename from docs_src/custom_response/tutorial009c.py
rename to docs_src/custom_response/tutorial009c_py39.py
diff --git a/docs_src/custom_response/tutorial010.py b/docs_src/custom_response/tutorial010_py39.py
similarity index 100%
rename from docs_src/custom_response/tutorial010.py
rename to docs_src/custom_response/tutorial010_py39.py
diff --git a/docs_src/dataclasses/tutorial002.py b/docs_src/dataclasses/tutorial002.py
deleted file mode 100644
index ece2f150cc..0000000000
--- a/docs_src/dataclasses/tutorial002.py
+++ /dev/null
@@ -1,26 +0,0 @@
-from dataclasses import dataclass, field
-from typing import List, Union
-
-from fastapi import FastAPI
-
-
-@dataclass
-class Item:
- name: str
- price: float
- tags: List[str] = field(default_factory=list)
- description: Union[str, None] = None
- tax: Union[float, None] = None
-
-
-app = FastAPI()
-
-
-@app.get("/items/next", response_model=Item)
-async def read_next_item():
- return {
- "name": "Island In The Moon",
- "price": 12.99,
- "description": "A place to be playin' and havin' fun",
- "tags": ["breater"],
- }
diff --git a/docs_src/dataclasses/tutorial003.py b/docs_src/dataclasses/tutorial003.py
deleted file mode 100644
index c613155133..0000000000
--- a/docs_src/dataclasses/tutorial003.py
+++ /dev/null
@@ -1,55 +0,0 @@
-from dataclasses import field # (1)
-from typing import List, Union
-
-from fastapi import FastAPI
-from pydantic.dataclasses import dataclass # (2)
-
-
-@dataclass
-class Item:
- name: str
- description: Union[str, None] = None
-
-
-@dataclass
-class Author:
- name: str
- items: List[Item] = field(default_factory=list) # (3)
-
-
-app = FastAPI()
-
-
-@app.post("/authors/{author_id}/items/", response_model=Author) # (4)
-async def create_author_items(author_id: str, items: List[Item]): # (5)
- return {"name": author_id, "items": items} # (6)
-
-
-@app.get("/authors/", response_model=List[Author]) # (7)
-def get_authors(): # (8)
- return [ # (9)
- {
- "name": "Breaters",
- "items": [
- {
- "name": "Island In The Moon",
- "description": "A place to be playin' and havin' fun",
- },
- {"name": "Holy Buddies"},
- ],
- },
- {
- "name": "System of an Up",
- "items": [
- {
- "name": "Salt",
- "description": "The kombucha mushroom people's favorite",
- },
- {"name": "Pad Thai"},
- {
- "name": "Lonely Night",
- "description": "The mostests lonliest nightiest of allest",
- },
- ],
- },
- ]
diff --git a/docs_src/dataclasses_/__init__.py b/docs_src/dataclasses_/__init__.py
new file mode 100644
index 0000000000..e69de29bb2
diff --git a/docs_src/dataclasses/tutorial001_py310.py b/docs_src/dataclasses_/tutorial001_py310.py
similarity index 100%
rename from docs_src/dataclasses/tutorial001_py310.py
rename to docs_src/dataclasses_/tutorial001_py310.py
diff --git a/docs_src/dataclasses/tutorial001.py b/docs_src/dataclasses_/tutorial001_py39.py
similarity index 100%
rename from docs_src/dataclasses/tutorial001.py
rename to docs_src/dataclasses_/tutorial001_py39.py
diff --git a/docs_src/dataclasses/tutorial002_py310.py b/docs_src/dataclasses_/tutorial002_py310.py
similarity index 100%
rename from docs_src/dataclasses/tutorial002_py310.py
rename to docs_src/dataclasses_/tutorial002_py310.py
diff --git a/docs_src/dataclasses/tutorial002_py39.py b/docs_src/dataclasses_/tutorial002_py39.py
similarity index 100%
rename from docs_src/dataclasses/tutorial002_py39.py
rename to docs_src/dataclasses_/tutorial002_py39.py
diff --git a/docs_src/dataclasses/tutorial003_py310.py b/docs_src/dataclasses_/tutorial003_py310.py
similarity index 100%
rename from docs_src/dataclasses/tutorial003_py310.py
rename to docs_src/dataclasses_/tutorial003_py310.py
diff --git a/docs_src/dataclasses/tutorial003_py39.py b/docs_src/dataclasses_/tutorial003_py39.py
similarity index 100%
rename from docs_src/dataclasses/tutorial003_py39.py
rename to docs_src/dataclasses_/tutorial003_py39.py
diff --git a/docs_src/debugging/__init__.py b/docs_src/debugging/__init__.py
new file mode 100644
index 0000000000..e69de29bb2
diff --git a/docs_src/debugging/tutorial001.py b/docs_src/debugging/tutorial001_py39.py
similarity index 100%
rename from docs_src/debugging/tutorial001.py
rename to docs_src/debugging/tutorial001_py39.py
diff --git a/docs_src/dependencies/__init__.py b/docs_src/dependencies/__init__.py
new file mode 100644
index 0000000000..e69de29bb2
diff --git a/docs_src/dependencies/tutorial001_02_an.py b/docs_src/dependencies/tutorial001_02_an.py
deleted file mode 100644
index 455d60c822..0000000000
--- a/docs_src/dependencies/tutorial001_02_an.py
+++ /dev/null
@@ -1,25 +0,0 @@
-from typing import Union
-
-from fastapi import Depends, FastAPI
-from typing_extensions import Annotated
-
-app = FastAPI()
-
-
-async def common_parameters(
- q: Union[str, None] = None, skip: int = 0, limit: int = 100
-):
- return {"q": q, "skip": skip, "limit": limit}
-
-
-CommonsDep = Annotated[dict, Depends(common_parameters)]
-
-
-@app.get("/items/")
-async def read_items(commons: CommonsDep):
- return commons
-
-
-@app.get("/users/")
-async def read_users(commons: CommonsDep):
- return commons
diff --git a/docs_src/dependencies/tutorial001_an.py b/docs_src/dependencies/tutorial001_an.py
deleted file mode 100644
index 81e24fe86c..0000000000
--- a/docs_src/dependencies/tutorial001_an.py
+++ /dev/null
@@ -1,22 +0,0 @@
-from typing import Union
-
-from fastapi import Depends, FastAPI
-from typing_extensions import Annotated
-
-app = FastAPI()
-
-
-async def common_parameters(
- q: Union[str, None] = None, skip: int = 0, limit: int = 100
-):
- return {"q": q, "skip": skip, "limit": limit}
-
-
-@app.get("/items/")
-async def read_items(commons: Annotated[dict, Depends(common_parameters)]):
- return commons
-
-
-@app.get("/users/")
-async def read_users(commons: Annotated[dict, Depends(common_parameters)]):
- return commons
diff --git a/docs_src/dependencies/tutorial001.py b/docs_src/dependencies/tutorial001_py39.py
similarity index 100%
rename from docs_src/dependencies/tutorial001.py
rename to docs_src/dependencies/tutorial001_py39.py
diff --git a/docs_src/dependencies/tutorial002_an.py b/docs_src/dependencies/tutorial002_an.py
deleted file mode 100644
index 964ccf66ca..0000000000
--- a/docs_src/dependencies/tutorial002_an.py
+++ /dev/null
@@ -1,26 +0,0 @@
-from typing import Union
-
-from fastapi import Depends, FastAPI
-from typing_extensions import Annotated
-
-app = FastAPI()
-
-
-fake_items_db = [{"item_name": "Foo"}, {"item_name": "Bar"}, {"item_name": "Baz"}]
-
-
-class CommonQueryParams:
- def __init__(self, q: Union[str, None] = None, skip: int = 0, limit: int = 100):
- self.q = q
- self.skip = skip
- self.limit = limit
-
-
-@app.get("/items/")
-async def read_items(commons: Annotated[CommonQueryParams, Depends(CommonQueryParams)]):
- response = {}
- if commons.q:
- response.update({"q": commons.q})
- items = fake_items_db[commons.skip : commons.skip + commons.limit]
- response.update({"items": items})
- return response
diff --git a/docs_src/dependencies/tutorial002.py b/docs_src/dependencies/tutorial002_py39.py
similarity index 100%
rename from docs_src/dependencies/tutorial002.py
rename to docs_src/dependencies/tutorial002_py39.py
diff --git a/docs_src/dependencies/tutorial003_an.py b/docs_src/dependencies/tutorial003_an.py
deleted file mode 100644
index ba8e9f7174..0000000000
--- a/docs_src/dependencies/tutorial003_an.py
+++ /dev/null
@@ -1,26 +0,0 @@
-from typing import Any, Union
-
-from fastapi import Depends, FastAPI
-from typing_extensions import Annotated
-
-app = FastAPI()
-
-
-fake_items_db = [{"item_name": "Foo"}, {"item_name": "Bar"}, {"item_name": "Baz"}]
-
-
-class CommonQueryParams:
- def __init__(self, q: Union[str, None] = None, skip: int = 0, limit: int = 100):
- self.q = q
- self.skip = skip
- self.limit = limit
-
-
-@app.get("/items/")
-async def read_items(commons: Annotated[Any, Depends(CommonQueryParams)]):
- response = {}
- if commons.q:
- response.update({"q": commons.q})
- items = fake_items_db[commons.skip : commons.skip + commons.limit]
- response.update({"items": items})
- return response
diff --git a/docs_src/dependencies/tutorial003.py b/docs_src/dependencies/tutorial003_py39.py
similarity index 100%
rename from docs_src/dependencies/tutorial003.py
rename to docs_src/dependencies/tutorial003_py39.py
diff --git a/docs_src/dependencies/tutorial004_an.py b/docs_src/dependencies/tutorial004_an.py
deleted file mode 100644
index 78881a354c..0000000000
--- a/docs_src/dependencies/tutorial004_an.py
+++ /dev/null
@@ -1,26 +0,0 @@
-from typing import Union
-
-from fastapi import Depends, FastAPI
-from typing_extensions import Annotated
-
-app = FastAPI()
-
-
-fake_items_db = [{"item_name": "Foo"}, {"item_name": "Bar"}, {"item_name": "Baz"}]
-
-
-class CommonQueryParams:
- def __init__(self, q: Union[str, None] = None, skip: int = 0, limit: int = 100):
- self.q = q
- self.skip = skip
- self.limit = limit
-
-
-@app.get("/items/")
-async def read_items(commons: Annotated[CommonQueryParams, Depends()]):
- response = {}
- if commons.q:
- response.update({"q": commons.q})
- items = fake_items_db[commons.skip : commons.skip + commons.limit]
- response.update({"items": items})
- return response
diff --git a/docs_src/dependencies/tutorial004.py b/docs_src/dependencies/tutorial004_py39.py
similarity index 100%
rename from docs_src/dependencies/tutorial004.py
rename to docs_src/dependencies/tutorial004_py39.py
diff --git a/docs_src/dependencies/tutorial005_an.py b/docs_src/dependencies/tutorial005_an.py
deleted file mode 100644
index 1d78c17a2a..0000000000
--- a/docs_src/dependencies/tutorial005_an.py
+++ /dev/null
@@ -1,26 +0,0 @@
-from typing import Union
-
-from fastapi import Cookie, Depends, FastAPI
-from typing_extensions import Annotated
-
-app = FastAPI()
-
-
-def query_extractor(q: Union[str, None] = None):
- return q
-
-
-def query_or_cookie_extractor(
- q: Annotated[str, Depends(query_extractor)],
- last_query: Annotated[Union[str, None], Cookie()] = None,
-):
- if not q:
- return last_query
- return q
-
-
-@app.get("/items/")
-async def read_query(
- query_or_default: Annotated[str, Depends(query_or_cookie_extractor)],
-):
- return {"q_or_cookie": query_or_default}
diff --git a/docs_src/dependencies/tutorial005.py b/docs_src/dependencies/tutorial005_py39.py
similarity index 100%
rename from docs_src/dependencies/tutorial005.py
rename to docs_src/dependencies/tutorial005_py39.py
diff --git a/docs_src/dependencies/tutorial006_an.py b/docs_src/dependencies/tutorial006_an.py
deleted file mode 100644
index 5aaea04d16..0000000000
--- a/docs_src/dependencies/tutorial006_an.py
+++ /dev/null
@@ -1,20 +0,0 @@
-from fastapi import Depends, FastAPI, Header, HTTPException
-from typing_extensions import Annotated
-
-app = FastAPI()
-
-
-async def verify_token(x_token: Annotated[str, Header()]):
- if x_token != "fake-super-secret-token":
- raise HTTPException(status_code=400, detail="X-Token header invalid")
-
-
-async def verify_key(x_key: Annotated[str, Header()]):
- if x_key != "fake-super-secret-key":
- raise HTTPException(status_code=400, detail="X-Key header invalid")
- return x_key
-
-
-@app.get("/items/", dependencies=[Depends(verify_token), Depends(verify_key)])
-async def read_items():
- return [{"item": "Foo"}, {"item": "Bar"}]
diff --git a/docs_src/dependencies/tutorial006.py b/docs_src/dependencies/tutorial006_py39.py
similarity index 100%
rename from docs_src/dependencies/tutorial006.py
rename to docs_src/dependencies/tutorial006_py39.py
diff --git a/docs_src/dependencies/tutorial007.py b/docs_src/dependencies/tutorial007_py39.py
similarity index 100%
rename from docs_src/dependencies/tutorial007.py
rename to docs_src/dependencies/tutorial007_py39.py
diff --git a/docs_src/dependencies/tutorial008_an.py b/docs_src/dependencies/tutorial008_an.py
deleted file mode 100644
index 2de86f042d..0000000000
--- a/docs_src/dependencies/tutorial008_an.py
+++ /dev/null
@@ -1,26 +0,0 @@
-from fastapi import Depends
-from typing_extensions import Annotated
-
-
-async def dependency_a():
- dep_a = generate_dep_a()
- try:
- yield dep_a
- finally:
- dep_a.close()
-
-
-async def dependency_b(dep_a: Annotated[DepA, Depends(dependency_a)]):
- dep_b = generate_dep_b()
- try:
- yield dep_b
- finally:
- dep_b.close(dep_a)
-
-
-async def dependency_c(dep_b: Annotated[DepB, Depends(dependency_b)]):
- dep_c = generate_dep_c()
- try:
- yield dep_c
- finally:
- dep_c.close(dep_b)
diff --git a/docs_src/dependencies/tutorial008.py b/docs_src/dependencies/tutorial008_py39.py
similarity index 100%
rename from docs_src/dependencies/tutorial008.py
rename to docs_src/dependencies/tutorial008_py39.py
diff --git a/docs_src/dependencies/tutorial008b_an.py b/docs_src/dependencies/tutorial008b_an.py
deleted file mode 100644
index 84d8f12c14..0000000000
--- a/docs_src/dependencies/tutorial008b_an.py
+++ /dev/null
@@ -1,31 +0,0 @@
-from fastapi import Depends, FastAPI, HTTPException
-from typing_extensions import Annotated
-
-app = FastAPI()
-
-
-data = {
- "plumbus": {"description": "Freshly pickled plumbus", "owner": "Morty"},
- "portal-gun": {"description": "Gun to create portals", "owner": "Rick"},
-}
-
-
-class OwnerError(Exception):
- pass
-
-
-def get_username():
- try:
- yield "Rick"
- except OwnerError as e:
- raise HTTPException(status_code=400, detail=f"Owner error: {e}")
-
-
-@app.get("/items/{item_id}")
-def get_item(item_id: str, username: Annotated[str, Depends(get_username)]):
- if item_id not in data:
- raise HTTPException(status_code=404, detail="Item not found")
- item = data[item_id]
- if item["owner"] != username:
- raise OwnerError(username)
- return item
diff --git a/docs_src/dependencies/tutorial008b.py b/docs_src/dependencies/tutorial008b_py39.py
similarity index 100%
rename from docs_src/dependencies/tutorial008b.py
rename to docs_src/dependencies/tutorial008b_py39.py
diff --git a/docs_src/dependencies/tutorial008c_an.py b/docs_src/dependencies/tutorial008c_an.py
deleted file mode 100644
index 94f59f9aa6..0000000000
--- a/docs_src/dependencies/tutorial008c_an.py
+++ /dev/null
@@ -1,28 +0,0 @@
-from fastapi import Depends, FastAPI, HTTPException
-from typing_extensions import Annotated
-
-app = FastAPI()
-
-
-class InternalError(Exception):
- pass
-
-
-def get_username():
- try:
- yield "Rick"
- except InternalError:
- print("Oops, we didn't raise again, Britney 😱")
-
-
-@app.get("/items/{item_id}")
-def get_item(item_id: str, username: Annotated[str, Depends(get_username)]):
- if item_id == "portal-gun":
- raise InternalError(
- f"The portal gun is too dangerous to be owned by {username}"
- )
- if item_id != "plumbus":
- raise HTTPException(
- status_code=404, detail="Item not found, there's only a plumbus here"
- )
- return item_id
diff --git a/docs_src/dependencies/tutorial008c.py b/docs_src/dependencies/tutorial008c_py39.py
similarity index 100%
rename from docs_src/dependencies/tutorial008c.py
rename to docs_src/dependencies/tutorial008c_py39.py
diff --git a/docs_src/dependencies/tutorial008d_an.py b/docs_src/dependencies/tutorial008d_an.py
deleted file mode 100644
index c354245744..0000000000
--- a/docs_src/dependencies/tutorial008d_an.py
+++ /dev/null
@@ -1,29 +0,0 @@
-from fastapi import Depends, FastAPI, HTTPException
-from typing_extensions import Annotated
-
-app = FastAPI()
-
-
-class InternalError(Exception):
- pass
-
-
-def get_username():
- try:
- yield "Rick"
- except InternalError:
- print("We don't swallow the internal error here, we raise again 😎")
- raise
-
-
-@app.get("/items/{item_id}")
-def get_item(item_id: str, username: Annotated[str, Depends(get_username)]):
- if item_id == "portal-gun":
- raise InternalError(
- f"The portal gun is too dangerous to be owned by {username}"
- )
- if item_id != "plumbus":
- raise HTTPException(
- status_code=404, detail="Item not found, there's only a plumbus here"
- )
- return item_id
diff --git a/docs_src/dependencies/tutorial008d.py b/docs_src/dependencies/tutorial008d_py39.py
similarity index 100%
rename from docs_src/dependencies/tutorial008d.py
rename to docs_src/dependencies/tutorial008d_py39.py
diff --git a/docs_src/dependencies/tutorial008e_an.py b/docs_src/dependencies/tutorial008e_an.py
deleted file mode 100644
index c8a0af2b3b..0000000000
--- a/docs_src/dependencies/tutorial008e_an.py
+++ /dev/null
@@ -1,16 +0,0 @@
-from fastapi import Depends, FastAPI
-from typing_extensions import Annotated
-
-app = FastAPI()
-
-
-def get_username():
- try:
- yield "Rick"
- finally:
- print("Cleanup up before response is sent")
-
-
-@app.get("/users/me")
-def get_user_me(username: Annotated[str, Depends(get_username, scope="function")]):
- return username
diff --git a/docs_src/dependencies/tutorial008e.py b/docs_src/dependencies/tutorial008e_py39.py
similarity index 100%
rename from docs_src/dependencies/tutorial008e.py
rename to docs_src/dependencies/tutorial008e_py39.py
diff --git a/docs_src/dependencies/tutorial009.py b/docs_src/dependencies/tutorial009.py
deleted file mode 100644
index 8472f642de..0000000000
--- a/docs_src/dependencies/tutorial009.py
+++ /dev/null
@@ -1,25 +0,0 @@
-from fastapi import Depends
-
-
-async def dependency_a():
- dep_a = generate_dep_a()
- try:
- yield dep_a
- finally:
- dep_a.close()
-
-
-async def dependency_b(dep_a=Depends(dependency_a)):
- dep_b = generate_dep_b()
- try:
- yield dep_b
- finally:
- dep_b.close(dep_a)
-
-
-async def dependency_c(dep_b=Depends(dependency_b)):
- dep_c = generate_dep_c()
- try:
- yield dep_c
- finally:
- dep_c.close(dep_b)
diff --git a/docs_src/dependencies/tutorial010.py b/docs_src/dependencies/tutorial010_py39.py
similarity index 100%
rename from docs_src/dependencies/tutorial010.py
rename to docs_src/dependencies/tutorial010_py39.py
diff --git a/docs_src/dependencies/tutorial011_an.py b/docs_src/dependencies/tutorial011_an.py
deleted file mode 100644
index 6c13d9033f..0000000000
--- a/docs_src/dependencies/tutorial011_an.py
+++ /dev/null
@@ -1,22 +0,0 @@
-from fastapi import Depends, FastAPI
-from typing_extensions import Annotated
-
-app = FastAPI()
-
-
-class FixedContentQueryChecker:
- def __init__(self, fixed_content: str):
- self.fixed_content = fixed_content
-
- def __call__(self, q: str = ""):
- if q:
- return self.fixed_content in q
- return False
-
-
-checker = FixedContentQueryChecker("bar")
-
-
-@app.get("/query-checker/")
-async def read_query_check(fixed_content_included: Annotated[bool, Depends(checker)]):
- return {"fixed_content_in_query": fixed_content_included}
diff --git a/docs_src/dependencies/tutorial011.py b/docs_src/dependencies/tutorial011_py39.py
similarity index 100%
rename from docs_src/dependencies/tutorial011.py
rename to docs_src/dependencies/tutorial011_py39.py
diff --git a/docs_src/dependencies/tutorial012_an.py b/docs_src/dependencies/tutorial012_an.py
deleted file mode 100644
index 7541e6bf41..0000000000
--- a/docs_src/dependencies/tutorial012_an.py
+++ /dev/null
@@ -1,26 +0,0 @@
-from fastapi import Depends, FastAPI, Header, HTTPException
-from typing_extensions import Annotated
-
-
-async def verify_token(x_token: Annotated[str, Header()]):
- if x_token != "fake-super-secret-token":
- raise HTTPException(status_code=400, detail="X-Token header invalid")
-
-
-async def verify_key(x_key: Annotated[str, Header()]):
- if x_key != "fake-super-secret-key":
- raise HTTPException(status_code=400, detail="X-Key header invalid")
- return x_key
-
-
-app = FastAPI(dependencies=[Depends(verify_token), Depends(verify_key)])
-
-
-@app.get("/items/")
-async def read_items():
- return [{"item": "Portal Gun"}, {"item": "Plumbus"}]
-
-
-@app.get("/users/")
-async def read_users():
- return [{"username": "Rick"}, {"username": "Morty"}]
diff --git a/docs_src/dependencies/tutorial012_an_py39.py b/docs_src/dependencies/tutorial012_an_py39.py
index 7541e6bf41..6503591fc3 100644
--- a/docs_src/dependencies/tutorial012_an_py39.py
+++ b/docs_src/dependencies/tutorial012_an_py39.py
@@ -1,5 +1,6 @@
+from typing import Annotated
+
from fastapi import Depends, FastAPI, Header, HTTPException
-from typing_extensions import Annotated
async def verify_token(x_token: Annotated[str, Header()]):
diff --git a/docs_src/dependencies/tutorial012.py b/docs_src/dependencies/tutorial012_py39.py
similarity index 100%
rename from docs_src/dependencies/tutorial012.py
rename to docs_src/dependencies/tutorial012_py39.py
diff --git a/docs_src/dependency_testing/__init__.py b/docs_src/dependency_testing/__init__.py
new file mode 100644
index 0000000000..e69de29bb2
diff --git a/docs_src/dependency_testing/tutorial001_an.py b/docs_src/dependency_testing/tutorial001_an.py
deleted file mode 100644
index 4c76a87ff5..0000000000
--- a/docs_src/dependency_testing/tutorial001_an.py
+++ /dev/null
@@ -1,60 +0,0 @@
-from typing import Union
-
-from fastapi import Depends, FastAPI
-from fastapi.testclient import TestClient
-from typing_extensions import Annotated
-
-app = FastAPI()
-
-
-async def common_parameters(
- q: Union[str, None] = None, skip: int = 0, limit: int = 100
-):
- return {"q": q, "skip": skip, "limit": limit}
-
-
-@app.get("/items/")
-async def read_items(commons: Annotated[dict, Depends(common_parameters)]):
- return {"message": "Hello Items!", "params": commons}
-
-
-@app.get("/users/")
-async def read_users(commons: Annotated[dict, Depends(common_parameters)]):
- return {"message": "Hello Users!", "params": commons}
-
-
-client = TestClient(app)
-
-
-async def override_dependency(q: Union[str, None] = None):
- return {"q": q, "skip": 5, "limit": 10}
-
-
-app.dependency_overrides[common_parameters] = override_dependency
-
-
-def test_override_in_items():
- response = client.get("/items/")
- assert response.status_code == 200
- assert response.json() == {
- "message": "Hello Items!",
- "params": {"q": None, "skip": 5, "limit": 10},
- }
-
-
-def test_override_in_items_with_q():
- response = client.get("/items/?q=foo")
- assert response.status_code == 200
- assert response.json() == {
- "message": "Hello Items!",
- "params": {"q": "foo", "skip": 5, "limit": 10},
- }
-
-
-def test_override_in_items_with_params():
- response = client.get("/items/?q=foo&skip=100&limit=200")
- assert response.status_code == 200
- assert response.json() == {
- "message": "Hello Items!",
- "params": {"q": "foo", "skip": 5, "limit": 10},
- }
diff --git a/docs_src/dependency_testing/tutorial001.py b/docs_src/dependency_testing/tutorial001_py39.py
similarity index 100%
rename from docs_src/dependency_testing/tutorial001.py
rename to docs_src/dependency_testing/tutorial001_py39.py
diff --git a/docs_src/encoder/__init__.py b/docs_src/encoder/__init__.py
new file mode 100644
index 0000000000..e69de29bb2
diff --git a/docs_src/encoder/tutorial001.py b/docs_src/encoder/tutorial001_py39.py
similarity index 100%
rename from docs_src/encoder/tutorial001.py
rename to docs_src/encoder/tutorial001_py39.py
diff --git a/docs_src/events/__init__.py b/docs_src/events/__init__.py
new file mode 100644
index 0000000000..e69de29bb2
diff --git a/docs_src/events/tutorial001.py b/docs_src/events/tutorial001_py39.py
similarity index 100%
rename from docs_src/events/tutorial001.py
rename to docs_src/events/tutorial001_py39.py
diff --git a/docs_src/events/tutorial002.py b/docs_src/events/tutorial002_py39.py
similarity index 100%
rename from docs_src/events/tutorial002.py
rename to docs_src/events/tutorial002_py39.py
diff --git a/docs_src/events/tutorial003.py b/docs_src/events/tutorial003_py39.py
similarity index 100%
rename from docs_src/events/tutorial003.py
rename to docs_src/events/tutorial003_py39.py
diff --git a/docs_src/extending_openapi/__init__.py b/docs_src/extending_openapi/__init__.py
new file mode 100644
index 0000000000..e69de29bb2
diff --git a/docs_src/extending_openapi/tutorial001.py b/docs_src/extending_openapi/tutorial001_py39.py
similarity index 100%
rename from docs_src/extending_openapi/tutorial001.py
rename to docs_src/extending_openapi/tutorial001_py39.py
diff --git a/docs_src/extra_data_types/__init__.py b/docs_src/extra_data_types/__init__.py
new file mode 100644
index 0000000000..e69de29bb2
diff --git a/docs_src/extra_data_types/tutorial001_an.py b/docs_src/extra_data_types/tutorial001_an.py
deleted file mode 100644
index 257d0c7c86..0000000000
--- a/docs_src/extra_data_types/tutorial001_an.py
+++ /dev/null
@@ -1,29 +0,0 @@
-from datetime import datetime, time, timedelta
-from typing import Union
-from uuid import UUID
-
-from fastapi import Body, FastAPI
-from typing_extensions import Annotated
-
-app = FastAPI()
-
-
-@app.put("/items/{item_id}")
-async def read_items(
- item_id: UUID,
- start_datetime: Annotated[datetime, Body()],
- end_datetime: Annotated[datetime, Body()],
- process_after: Annotated[timedelta, Body()],
- repeat_at: Annotated[Union[time, None], Body()] = None,
-):
- start_process = start_datetime + process_after
- duration = end_datetime - start_process
- return {
- "item_id": item_id,
- "start_datetime": start_datetime,
- "end_datetime": end_datetime,
- "process_after": process_after,
- "repeat_at": repeat_at,
- "start_process": start_process,
- "duration": duration,
- }
diff --git a/docs_src/extra_data_types/tutorial001.py b/docs_src/extra_data_types/tutorial001_py39.py
similarity index 100%
rename from docs_src/extra_data_types/tutorial001.py
rename to docs_src/extra_data_types/tutorial001_py39.py
diff --git a/docs_src/extra_models/__init__.py b/docs_src/extra_models/__init__.py
new file mode 100644
index 0000000000..e69de29bb2
diff --git a/docs_src/extra_models/tutorial001_py310.py b/docs_src/extra_models/tutorial001_py310.py
index 669386ae6e..cf39142e4a 100644
--- a/docs_src/extra_models/tutorial001_py310.py
+++ b/docs_src/extra_models/tutorial001_py310.py
@@ -30,7 +30,7 @@ def fake_password_hasher(raw_password: str):
def fake_save_user(user_in: UserIn):
hashed_password = fake_password_hasher(user_in.password)
- user_in_db = UserInDB(**user_in.dict(), hashed_password=hashed_password)
+ user_in_db = UserInDB(**user_in.model_dump(), hashed_password=hashed_password)
print("User saved! ..not really")
return user_in_db
diff --git a/docs_src/extra_models/tutorial001.py b/docs_src/extra_models/tutorial001_py39.py
similarity index 91%
rename from docs_src/extra_models/tutorial001.py
rename to docs_src/extra_models/tutorial001_py39.py
index 4be56cd2a7..327ffcdf09 100644
--- a/docs_src/extra_models/tutorial001.py
+++ b/docs_src/extra_models/tutorial001_py39.py
@@ -32,7 +32,7 @@ def fake_password_hasher(raw_password: str):
def fake_save_user(user_in: UserIn):
hashed_password = fake_password_hasher(user_in.password)
- user_in_db = UserInDB(**user_in.dict(), hashed_password=hashed_password)
+ user_in_db = UserInDB(**user_in.model_dump(), hashed_password=hashed_password)
print("User saved! ..not really")
return user_in_db
diff --git a/docs_src/extra_models/tutorial002_py310.py b/docs_src/extra_models/tutorial002_py310.py
index 5b8ed7de3d..e8a4f5f29b 100644
--- a/docs_src/extra_models/tutorial002_py310.py
+++ b/docs_src/extra_models/tutorial002_py310.py
@@ -28,7 +28,7 @@ def fake_password_hasher(raw_password: str):
def fake_save_user(user_in: UserIn):
hashed_password = fake_password_hasher(user_in.password)
- user_in_db = UserInDB(**user_in.dict(), hashed_password=hashed_password)
+ user_in_db = UserInDB(**user_in.model_dump(), hashed_password=hashed_password)
print("User saved! ..not really")
return user_in_db
diff --git a/docs_src/extra_models/tutorial002.py b/docs_src/extra_models/tutorial002_py39.py
similarity index 90%
rename from docs_src/extra_models/tutorial002.py
rename to docs_src/extra_models/tutorial002_py39.py
index 70fa16441d..6543796015 100644
--- a/docs_src/extra_models/tutorial002.py
+++ b/docs_src/extra_models/tutorial002_py39.py
@@ -30,7 +30,7 @@ def fake_password_hasher(raw_password: str):
def fake_save_user(user_in: UserIn):
hashed_password = fake_password_hasher(user_in.password)
- user_in_db = UserInDB(**user_in.dict(), hashed_password=hashed_password)
+ user_in_db = UserInDB(**user_in.model_dump(), hashed_password=hashed_password)
print("User saved! ..not really")
return user_in_db
diff --git a/docs_src/extra_models/tutorial003.py b/docs_src/extra_models/tutorial003_py39.py
similarity index 100%
rename from docs_src/extra_models/tutorial003.py
rename to docs_src/extra_models/tutorial003_py39.py
diff --git a/docs_src/extra_models/tutorial004.py b/docs_src/extra_models/tutorial004.py
deleted file mode 100644
index a8e0f7af5a..0000000000
--- a/docs_src/extra_models/tutorial004.py
+++ /dev/null
@@ -1,22 +0,0 @@
-from typing import List
-
-from fastapi import FastAPI
-from pydantic import BaseModel
-
-app = FastAPI()
-
-
-class Item(BaseModel):
- name: str
- description: str
-
-
-items = [
- {"name": "Foo", "description": "There comes my hero"},
- {"name": "Red", "description": "It's my aeroplane"},
-]
-
-
-@app.get("/items/", response_model=List[Item])
-async def read_items():
- return items
diff --git a/docs_src/extra_models/tutorial005.py b/docs_src/extra_models/tutorial005.py
deleted file mode 100644
index a81cbc2c58..0000000000
--- a/docs_src/extra_models/tutorial005.py
+++ /dev/null
@@ -1,10 +0,0 @@
-from typing import Dict
-
-from fastapi import FastAPI
-
-app = FastAPI()
-
-
-@app.get("/keyword-weights/", response_model=Dict[str, float])
-async def read_keyword_weights():
- return {"foo": 2.3, "bar": 3.4}
diff --git a/docs_src/first_steps/__init__.py b/docs_src/first_steps/__init__.py
new file mode 100644
index 0000000000..e69de29bb2
diff --git a/docs_src/first_steps/tutorial001.py b/docs_src/first_steps/tutorial001_py39.py
similarity index 100%
rename from docs_src/first_steps/tutorial001.py
rename to docs_src/first_steps/tutorial001_py39.py
diff --git a/docs_src/first_steps/tutorial002.py b/docs_src/first_steps/tutorial002.py
deleted file mode 100644
index ca7d48cff9..0000000000
--- a/docs_src/first_steps/tutorial002.py
+++ /dev/null
@@ -1,8 +0,0 @@
-from fastapi import FastAPI
-
-my_awesome_api = FastAPI()
-
-
-@my_awesome_api.get("/")
-async def root():
- return {"message": "Hello World"}
diff --git a/docs_src/first_steps/tutorial003.py b/docs_src/first_steps/tutorial003_py39.py
similarity index 100%
rename from docs_src/first_steps/tutorial003.py
rename to docs_src/first_steps/tutorial003_py39.py
diff --git a/docs_src/generate_clients/__init__.py b/docs_src/generate_clients/__init__.py
new file mode 100644
index 0000000000..e69de29bb2
diff --git a/docs_src/generate_clients/tutorial001.py b/docs_src/generate_clients/tutorial001.py
deleted file mode 100644
index 2d1f91bc6c..0000000000
--- a/docs_src/generate_clients/tutorial001.py
+++ /dev/null
@@ -1,28 +0,0 @@
-from typing import List
-
-from fastapi import FastAPI
-from pydantic import BaseModel
-
-app = FastAPI()
-
-
-class Item(BaseModel):
- name: str
- price: float
-
-
-class ResponseMessage(BaseModel):
- message: str
-
-
-@app.post("/items/", response_model=ResponseMessage)
-async def create_item(item: Item):
- return {"message": "item received"}
-
-
-@app.get("/items/", response_model=List[Item])
-async def get_items():
- return [
- {"name": "Plumbus", "price": 3},
- {"name": "Portal Gun", "price": 9001},
- ]
diff --git a/docs_src/generate_clients/tutorial002.py b/docs_src/generate_clients/tutorial002.py
deleted file mode 100644
index bd80449af9..0000000000
--- a/docs_src/generate_clients/tutorial002.py
+++ /dev/null
@@ -1,38 +0,0 @@
-from typing import List
-
-from fastapi import FastAPI
-from pydantic import BaseModel
-
-app = FastAPI()
-
-
-class Item(BaseModel):
- name: str
- price: float
-
-
-class ResponseMessage(BaseModel):
- message: str
-
-
-class User(BaseModel):
- username: str
- email: str
-
-
-@app.post("/items/", response_model=ResponseMessage, tags=["items"])
-async def create_item(item: Item):
- return {"message": "Item received"}
-
-
-@app.get("/items/", response_model=List[Item], tags=["items"])
-async def get_items():
- return [
- {"name": "Plumbus", "price": 3},
- {"name": "Portal Gun", "price": 9001},
- ]
-
-
-@app.post("/users/", response_model=ResponseMessage, tags=["users"])
-async def create_user(user: User):
- return {"message": "User received"}
diff --git a/docs_src/generate_clients/tutorial003.py b/docs_src/generate_clients/tutorial003.py
deleted file mode 100644
index 49eab73a1b..0000000000
--- a/docs_src/generate_clients/tutorial003.py
+++ /dev/null
@@ -1,44 +0,0 @@
-from typing import List
-
-from fastapi import FastAPI
-from fastapi.routing import APIRoute
-from pydantic import BaseModel
-
-
-def custom_generate_unique_id(route: APIRoute):
- return f"{route.tags[0]}-{route.name}"
-
-
-app = FastAPI(generate_unique_id_function=custom_generate_unique_id)
-
-
-class Item(BaseModel):
- name: str
- price: float
-
-
-class ResponseMessage(BaseModel):
- message: str
-
-
-class User(BaseModel):
- username: str
- email: str
-
-
-@app.post("/items/", response_model=ResponseMessage, tags=["items"])
-async def create_item(item: Item):
- return {"message": "Item received"}
-
-
-@app.get("/items/", response_model=List[Item], tags=["items"])
-async def get_items():
- return [
- {"name": "Plumbus", "price": 3},
- {"name": "Portal Gun", "price": 9001},
- ]
-
-
-@app.post("/users/", response_model=ResponseMessage, tags=["users"])
-async def create_user(user: User):
- return {"message": "User received"}
diff --git a/docs_src/generate_clients/tutorial004.py b/docs_src/generate_clients/tutorial004_py39.py
similarity index 100%
rename from docs_src/generate_clients/tutorial004.py
rename to docs_src/generate_clients/tutorial004_py39.py
diff --git a/docs_src/graphql_/__init__.py b/docs_src/graphql_/__init__.py
new file mode 100644
index 0000000000..e69de29bb2
diff --git a/docs_src/graphql/tutorial001.py b/docs_src/graphql_/tutorial001_py39.py
similarity index 100%
rename from docs_src/graphql/tutorial001.py
rename to docs_src/graphql_/tutorial001_py39.py
diff --git a/docs_src/handling_errors/__init__.py b/docs_src/handling_errors/__init__.py
new file mode 100644
index 0000000000..e69de29bb2
diff --git a/docs_src/handling_errors/tutorial001.py b/docs_src/handling_errors/tutorial001_py39.py
similarity index 100%
rename from docs_src/handling_errors/tutorial001.py
rename to docs_src/handling_errors/tutorial001_py39.py
diff --git a/docs_src/handling_errors/tutorial002.py b/docs_src/handling_errors/tutorial002_py39.py
similarity index 100%
rename from docs_src/handling_errors/tutorial002.py
rename to docs_src/handling_errors/tutorial002_py39.py
diff --git a/docs_src/handling_errors/tutorial003.py b/docs_src/handling_errors/tutorial003_py39.py
similarity index 100%
rename from docs_src/handling_errors/tutorial003.py
rename to docs_src/handling_errors/tutorial003_py39.py
diff --git a/docs_src/handling_errors/tutorial004.py b/docs_src/handling_errors/tutorial004_py39.py
similarity index 100%
rename from docs_src/handling_errors/tutorial004.py
rename to docs_src/handling_errors/tutorial004_py39.py
diff --git a/docs_src/handling_errors/tutorial005.py b/docs_src/handling_errors/tutorial005_py39.py
similarity index 100%
rename from docs_src/handling_errors/tutorial005.py
rename to docs_src/handling_errors/tutorial005_py39.py
diff --git a/docs_src/handling_errors/tutorial006.py b/docs_src/handling_errors/tutorial006_py39.py
similarity index 100%
rename from docs_src/handling_errors/tutorial006.py
rename to docs_src/handling_errors/tutorial006_py39.py
diff --git a/docs_src/header_param_models/__init__.py b/docs_src/header_param_models/__init__.py
new file mode 100644
index 0000000000..e69de29bb2
diff --git a/docs_src/header_param_models/tutorial001.py b/docs_src/header_param_models/tutorial001.py
deleted file mode 100644
index 4caaba87b9..0000000000
--- a/docs_src/header_param_models/tutorial001.py
+++ /dev/null
@@ -1,19 +0,0 @@
-from typing import List, Union
-
-from fastapi import FastAPI, Header
-from pydantic import BaseModel
-
-app = FastAPI()
-
-
-class CommonHeaders(BaseModel):
- host: str
- save_data: bool
- if_modified_since: Union[str, None] = None
- traceparent: Union[str, None] = None
- x_tag: List[str] = []
-
-
-@app.get("/items/")
-async def read_items(headers: CommonHeaders = Header()):
- return headers
diff --git a/docs_src/header_param_models/tutorial001_an.py b/docs_src/header_param_models/tutorial001_an.py
deleted file mode 100644
index b55c6b56b1..0000000000
--- a/docs_src/header_param_models/tutorial001_an.py
+++ /dev/null
@@ -1,20 +0,0 @@
-from typing import List, Union
-
-from fastapi import FastAPI, Header
-from pydantic import BaseModel
-from typing_extensions import Annotated
-
-app = FastAPI()
-
-
-class CommonHeaders(BaseModel):
- host: str
- save_data: bool
- if_modified_since: Union[str, None] = None
- traceparent: Union[str, None] = None
- x_tag: List[str] = []
-
-
-@app.get("/items/")
-async def read_items(headers: Annotated[CommonHeaders, Header()]):
- return headers
diff --git a/docs_src/header_param_models/tutorial002.py b/docs_src/header_param_models/tutorial002.py
deleted file mode 100644
index 3f9aac58d2..0000000000
--- a/docs_src/header_param_models/tutorial002.py
+++ /dev/null
@@ -1,21 +0,0 @@
-from typing import List, Union
-
-from fastapi import FastAPI, Header
-from pydantic import BaseModel
-
-app = FastAPI()
-
-
-class CommonHeaders(BaseModel):
- model_config = {"extra": "forbid"}
-
- host: str
- save_data: bool
- if_modified_since: Union[str, None] = None
- traceparent: Union[str, None] = None
- x_tag: List[str] = []
-
-
-@app.get("/items/")
-async def read_items(headers: CommonHeaders = Header()):
- return headers
diff --git a/docs_src/header_param_models/tutorial002_an.py b/docs_src/header_param_models/tutorial002_an.py
deleted file mode 100644
index 771135d770..0000000000
--- a/docs_src/header_param_models/tutorial002_an.py
+++ /dev/null
@@ -1,22 +0,0 @@
-from typing import List, Union
-
-from fastapi import FastAPI, Header
-from pydantic import BaseModel
-from typing_extensions import Annotated
-
-app = FastAPI()
-
-
-class CommonHeaders(BaseModel):
- model_config = {"extra": "forbid"}
-
- host: str
- save_data: bool
- if_modified_since: Union[str, None] = None
- traceparent: Union[str, None] = None
- x_tag: List[str] = []
-
-
-@app.get("/items/")
-async def read_items(headers: Annotated[CommonHeaders, Header()]):
- return headers
diff --git a/docs_src/header_param_models/tutorial002_pv1.py b/docs_src/header_param_models/tutorial002_pv1.py
deleted file mode 100644
index 7e56cd993b..0000000000
--- a/docs_src/header_param_models/tutorial002_pv1.py
+++ /dev/null
@@ -1,22 +0,0 @@
-from typing import List, Union
-
-from fastapi import FastAPI, Header
-from pydantic import BaseModel
-
-app = FastAPI()
-
-
-class CommonHeaders(BaseModel):
- class Config:
- extra = "forbid"
-
- host: str
- save_data: bool
- if_modified_since: Union[str, None] = None
- traceparent: Union[str, None] = None
- x_tag: List[str] = []
-
-
-@app.get("/items/")
-async def read_items(headers: CommonHeaders = Header()):
- return headers
diff --git a/docs_src/header_param_models/tutorial002_pv1_an.py b/docs_src/header_param_models/tutorial002_pv1_an.py
deleted file mode 100644
index 236778231a..0000000000
--- a/docs_src/header_param_models/tutorial002_pv1_an.py
+++ /dev/null
@@ -1,23 +0,0 @@
-from typing import List, Union
-
-from fastapi import FastAPI, Header
-from pydantic import BaseModel
-from typing_extensions import Annotated
-
-app = FastAPI()
-
-
-class CommonHeaders(BaseModel):
- class Config:
- extra = "forbid"
-
- host: str
- save_data: bool
- if_modified_since: Union[str, None] = None
- traceparent: Union[str, None] = None
- x_tag: List[str] = []
-
-
-@app.get("/items/")
-async def read_items(headers: Annotated[CommonHeaders, Header()]):
- return headers
diff --git a/docs_src/header_param_models/tutorial002_pv1_an_py310.py b/docs_src/header_param_models/tutorial002_pv1_an_py310.py
deleted file mode 100644
index e99e24ea55..0000000000
--- a/docs_src/header_param_models/tutorial002_pv1_an_py310.py
+++ /dev/null
@@ -1,22 +0,0 @@
-from typing import Annotated
-
-from fastapi import FastAPI, Header
-from pydantic import BaseModel
-
-app = FastAPI()
-
-
-class CommonHeaders(BaseModel):
- class Config:
- extra = "forbid"
-
- host: str
- save_data: bool
- if_modified_since: str | None = None
- traceparent: str | None = None
- x_tag: list[str] = []
-
-
-@app.get("/items/")
-async def read_items(headers: Annotated[CommonHeaders, Header()]):
- return headers
diff --git a/docs_src/header_param_models/tutorial002_pv1_an_py39.py b/docs_src/header_param_models/tutorial002_pv1_an_py39.py
deleted file mode 100644
index 18398b726c..0000000000
--- a/docs_src/header_param_models/tutorial002_pv1_an_py39.py
+++ /dev/null
@@ -1,22 +0,0 @@
-from typing import Annotated, Union
-
-from fastapi import FastAPI, Header
-from pydantic import BaseModel
-
-app = FastAPI()
-
-
-class CommonHeaders(BaseModel):
- class Config:
- extra = "forbid"
-
- host: str
- save_data: bool
- if_modified_since: Union[str, None] = None
- traceparent: Union[str, None] = None
- x_tag: list[str] = []
-
-
-@app.get("/items/")
-async def read_items(headers: Annotated[CommonHeaders, Header()]):
- return headers
diff --git a/docs_src/header_param_models/tutorial002_pv1_py310.py b/docs_src/header_param_models/tutorial002_pv1_py310.py
deleted file mode 100644
index 3dbff9d7bf..0000000000
--- a/docs_src/header_param_models/tutorial002_pv1_py310.py
+++ /dev/null
@@ -1,20 +0,0 @@
-from fastapi import FastAPI, Header
-from pydantic import BaseModel
-
-app = FastAPI()
-
-
-class CommonHeaders(BaseModel):
- class Config:
- extra = "forbid"
-
- host: str
- save_data: bool
- if_modified_since: str | None = None
- traceparent: str | None = None
- x_tag: list[str] = []
-
-
-@app.get("/items/")
-async def read_items(headers: CommonHeaders = Header()):
- return headers
diff --git a/docs_src/header_param_models/tutorial002_pv1_py39.py b/docs_src/header_param_models/tutorial002_pv1_py39.py
deleted file mode 100644
index 86e19be0d1..0000000000
--- a/docs_src/header_param_models/tutorial002_pv1_py39.py
+++ /dev/null
@@ -1,22 +0,0 @@
-from typing import Union
-
-from fastapi import FastAPI, Header
-from pydantic import BaseModel
-
-app = FastAPI()
-
-
-class CommonHeaders(BaseModel):
- class Config:
- extra = "forbid"
-
- host: str
- save_data: bool
- if_modified_since: Union[str, None] = None
- traceparent: Union[str, None] = None
- x_tag: list[str] = []
-
-
-@app.get("/items/")
-async def read_items(headers: CommonHeaders = Header()):
- return headers
diff --git a/docs_src/header_param_models/tutorial003.py b/docs_src/header_param_models/tutorial003.py
deleted file mode 100644
index dc2eb74bd1..0000000000
--- a/docs_src/header_param_models/tutorial003.py
+++ /dev/null
@@ -1,19 +0,0 @@
-from typing import List, Union
-
-from fastapi import FastAPI, Header
-from pydantic import BaseModel
-
-app = FastAPI()
-
-
-class CommonHeaders(BaseModel):
- host: str
- save_data: bool
- if_modified_since: Union[str, None] = None
- traceparent: Union[str, None] = None
- x_tag: List[str] = []
-
-
-@app.get("/items/")
-async def read_items(headers: CommonHeaders = Header(convert_underscores=False)):
- return headers
diff --git a/docs_src/header_param_models/tutorial003_an.py b/docs_src/header_param_models/tutorial003_an.py
deleted file mode 100644
index e3edb11891..0000000000
--- a/docs_src/header_param_models/tutorial003_an.py
+++ /dev/null
@@ -1,22 +0,0 @@
-from typing import List, Union
-
-from fastapi import FastAPI, Header
-from pydantic import BaseModel
-from typing_extensions import Annotated
-
-app = FastAPI()
-
-
-class CommonHeaders(BaseModel):
- host: str
- save_data: bool
- if_modified_since: Union[str, None] = None
- traceparent: Union[str, None] = None
- x_tag: List[str] = []
-
-
-@app.get("/items/")
-async def read_items(
- headers: Annotated[CommonHeaders, Header(convert_underscores=False)],
-):
- return headers
diff --git a/docs_src/header_params/__init__.py b/docs_src/header_params/__init__.py
new file mode 100644
index 0000000000..e69de29bb2
diff --git a/docs_src/header_params/tutorial001_an.py b/docs_src/header_params/tutorial001_an.py
deleted file mode 100644
index 816c000862..0000000000
--- a/docs_src/header_params/tutorial001_an.py
+++ /dev/null
@@ -1,11 +0,0 @@
-from typing import Union
-
-from fastapi import FastAPI, Header
-from typing_extensions import Annotated
-
-app = FastAPI()
-
-
-@app.get("/items/")
-async def read_items(user_agent: Annotated[Union[str, None], Header()] = None):
- return {"User-Agent": user_agent}
diff --git a/docs_src/header_params/tutorial001.py b/docs_src/header_params/tutorial001_py39.py
similarity index 100%
rename from docs_src/header_params/tutorial001.py
rename to docs_src/header_params/tutorial001_py39.py
diff --git a/docs_src/header_params/tutorial002_an.py b/docs_src/header_params/tutorial002_an.py
deleted file mode 100644
index 82fe49ba2b..0000000000
--- a/docs_src/header_params/tutorial002_an.py
+++ /dev/null
@@ -1,15 +0,0 @@
-from typing import Union
-
-from fastapi import FastAPI, Header
-from typing_extensions import Annotated
-
-app = FastAPI()
-
-
-@app.get("/items/")
-async def read_items(
- strange_header: Annotated[
- Union[str, None], Header(convert_underscores=False)
- ] = None,
-):
- return {"strange_header": strange_header}
diff --git a/docs_src/header_params/tutorial002.py b/docs_src/header_params/tutorial002_py39.py
similarity index 100%
rename from docs_src/header_params/tutorial002.py
rename to docs_src/header_params/tutorial002_py39.py
diff --git a/docs_src/header_params/tutorial003.py b/docs_src/header_params/tutorial003.py
deleted file mode 100644
index a61314aedb..0000000000
--- a/docs_src/header_params/tutorial003.py
+++ /dev/null
@@ -1,10 +0,0 @@
-from typing import List, Union
-
-from fastapi import FastAPI, Header
-
-app = FastAPI()
-
-
-@app.get("/items/")
-async def read_items(x_token: Union[List[str], None] = Header(default=None)):
- return {"X-Token values": x_token}
diff --git a/docs_src/header_params/tutorial003_an.py b/docs_src/header_params/tutorial003_an.py
deleted file mode 100644
index 5406fd1f88..0000000000
--- a/docs_src/header_params/tutorial003_an.py
+++ /dev/null
@@ -1,11 +0,0 @@
-from typing import List, Union
-
-from fastapi import FastAPI, Header
-from typing_extensions import Annotated
-
-app = FastAPI()
-
-
-@app.get("/items/")
-async def read_items(x_token: Annotated[Union[List[str], None], Header()] = None):
- return {"X-Token values": x_token}
diff --git a/docs_src/header_params/tutorial003_an_py39.py b/docs_src/header_params/tutorial003_an_py39.py
index c1dd499611..5aad89407e 100644
--- a/docs_src/header_params/tutorial003_an_py39.py
+++ b/docs_src/header_params/tutorial003_an_py39.py
@@ -1,4 +1,4 @@
-from typing import Annotated, List, Union
+from typing import Annotated, Union
from fastapi import FastAPI, Header
@@ -6,5 +6,5 @@ app = FastAPI()
@app.get("/items/")
-async def read_items(x_token: Annotated[Union[List[str], None], Header()] = None):
+async def read_items(x_token: Annotated[Union[list[str], None], Header()] = None):
return {"X-Token values": x_token}
diff --git a/docs_src/metadata/__init__.py b/docs_src/metadata/__init__.py
new file mode 100644
index 0000000000..e69de29bb2
diff --git a/docs_src/metadata/tutorial001_1.py b/docs_src/metadata/tutorial001_1_py39.py
similarity index 100%
rename from docs_src/metadata/tutorial001_1.py
rename to docs_src/metadata/tutorial001_1_py39.py
diff --git a/docs_src/metadata/tutorial001.py b/docs_src/metadata/tutorial001_py39.py
similarity index 100%
rename from docs_src/metadata/tutorial001.py
rename to docs_src/metadata/tutorial001_py39.py
diff --git a/docs_src/metadata/tutorial002.py b/docs_src/metadata/tutorial002_py39.py
similarity index 100%
rename from docs_src/metadata/tutorial002.py
rename to docs_src/metadata/tutorial002_py39.py
diff --git a/docs_src/metadata/tutorial003.py b/docs_src/metadata/tutorial003_py39.py
similarity index 100%
rename from docs_src/metadata/tutorial003.py
rename to docs_src/metadata/tutorial003_py39.py
diff --git a/docs_src/metadata/tutorial004.py b/docs_src/metadata/tutorial004_py39.py
similarity index 100%
rename from docs_src/metadata/tutorial004.py
rename to docs_src/metadata/tutorial004_py39.py
diff --git a/docs_src/middleware/__init__.py b/docs_src/middleware/__init__.py
new file mode 100644
index 0000000000..e69de29bb2
diff --git a/docs_src/middleware/tutorial001.py b/docs_src/middleware/tutorial001_py39.py
similarity index 100%
rename from docs_src/middleware/tutorial001.py
rename to docs_src/middleware/tutorial001_py39.py
diff --git a/docs_src/openapi_callbacks/__init__.py b/docs_src/openapi_callbacks/__init__.py
new file mode 100644
index 0000000000..e69de29bb2
diff --git a/docs_src/openapi_callbacks/tutorial001.py b/docs_src/openapi_callbacks/tutorial001_py39.py
similarity index 100%
rename from docs_src/openapi_callbacks/tutorial001.py
rename to docs_src/openapi_callbacks/tutorial001_py39.py
diff --git a/docs_src/openapi_webhooks/__init__.py b/docs_src/openapi_webhooks/__init__.py
new file mode 100644
index 0000000000..e69de29bb2
diff --git a/docs_src/openapi_webhooks/tutorial001.py b/docs_src/openapi_webhooks/tutorial001_py39.py
similarity index 100%
rename from docs_src/openapi_webhooks/tutorial001.py
rename to docs_src/openapi_webhooks/tutorial001_py39.py
diff --git a/docs_src/path_operation_advanced_configuration/__init__.py b/docs_src/path_operation_advanced_configuration/__init__.py
new file mode 100644
index 0000000000..e69de29bb2
diff --git a/docs_src/path_operation_advanced_configuration/tutorial001.py b/docs_src/path_operation_advanced_configuration/tutorial001_py39.py
similarity index 100%
rename from docs_src/path_operation_advanced_configuration/tutorial001.py
rename to docs_src/path_operation_advanced_configuration/tutorial001_py39.py
diff --git a/docs_src/path_operation_advanced_configuration/tutorial002.py b/docs_src/path_operation_advanced_configuration/tutorial002_py39.py
similarity index 100%
rename from docs_src/path_operation_advanced_configuration/tutorial002.py
rename to docs_src/path_operation_advanced_configuration/tutorial002_py39.py
diff --git a/docs_src/path_operation_advanced_configuration/tutorial003.py b/docs_src/path_operation_advanced_configuration/tutorial003_py39.py
similarity index 100%
rename from docs_src/path_operation_advanced_configuration/tutorial003.py
rename to docs_src/path_operation_advanced_configuration/tutorial003_py39.py
diff --git a/docs_src/path_operation_advanced_configuration/tutorial004.py b/docs_src/path_operation_advanced_configuration/tutorial004.py
deleted file mode 100644
index a3aad4ac40..0000000000
--- a/docs_src/path_operation_advanced_configuration/tutorial004.py
+++ /dev/null
@@ -1,30 +0,0 @@
-from typing import Set, Union
-
-from fastapi import FastAPI
-from pydantic import BaseModel
-
-app = FastAPI()
-
-
-class Item(BaseModel):
- name: str
- description: Union[str, None] = None
- price: float
- tax: Union[float, None] = None
- tags: Set[str] = set()
-
-
-@app.post("/items/", response_model=Item, summary="Create an item")
-async def create_item(item: Item):
- """
- Create an item with all the information:
-
- - **name**: each item must have a name
- - **description**: a long description
- - **price**: required
- - **tax**: if the item doesn't have tax, you can omit this
- - **tags**: a set of unique tag strings for this item
- \f
- :param item: User input.
- """
- return item
diff --git a/docs_src/path_operation_advanced_configuration/tutorial005.py b/docs_src/path_operation_advanced_configuration/tutorial005_py39.py
similarity index 100%
rename from docs_src/path_operation_advanced_configuration/tutorial005.py
rename to docs_src/path_operation_advanced_configuration/tutorial005_py39.py
diff --git a/docs_src/path_operation_advanced_configuration/tutorial006.py b/docs_src/path_operation_advanced_configuration/tutorial006_py39.py
similarity index 100%
rename from docs_src/path_operation_advanced_configuration/tutorial006.py
rename to docs_src/path_operation_advanced_configuration/tutorial006_py39.py
diff --git a/docs_src/path_operation_advanced_configuration/tutorial007.py b/docs_src/path_operation_advanced_configuration/tutorial007.py
deleted file mode 100644
index 54e2e9399e..0000000000
--- a/docs_src/path_operation_advanced_configuration/tutorial007.py
+++ /dev/null
@@ -1,34 +0,0 @@
-from typing import List
-
-import yaml
-from fastapi import FastAPI, HTTPException, Request
-from pydantic import BaseModel, ValidationError
-
-app = FastAPI()
-
-
-class Item(BaseModel):
- name: str
- tags: List[str]
-
-
-@app.post(
- "/items/",
- openapi_extra={
- "requestBody": {
- "content": {"application/x-yaml": {"schema": Item.model_json_schema()}},
- "required": True,
- },
- },
-)
-async def create_item(request: Request):
- raw_body = await request.body()
- try:
- data = yaml.safe_load(raw_body)
- except yaml.YAMLError:
- raise HTTPException(status_code=422, detail="Invalid YAML")
- try:
- item = Item.model_validate(data)
- except ValidationError as e:
- raise HTTPException(status_code=422, detail=e.errors(include_url=False))
- return item
diff --git a/docs_src/path_operation_advanced_configuration/tutorial007_pv1.py b/docs_src/path_operation_advanced_configuration/tutorial007_pv1.py
deleted file mode 100644
index d51752bb87..0000000000
--- a/docs_src/path_operation_advanced_configuration/tutorial007_pv1.py
+++ /dev/null
@@ -1,34 +0,0 @@
-from typing import List
-
-import yaml
-from fastapi import FastAPI, HTTPException, Request
-from pydantic import BaseModel, ValidationError
-
-app = FastAPI()
-
-
-class Item(BaseModel):
- name: str
- tags: List[str]
-
-
-@app.post(
- "/items/",
- openapi_extra={
- "requestBody": {
- "content": {"application/x-yaml": {"schema": Item.schema()}},
- "required": True,
- },
- },
-)
-async def create_item(request: Request):
- raw_body = await request.body()
- try:
- data = yaml.safe_load(raw_body)
- except yaml.YAMLError:
- raise HTTPException(status_code=422, detail="Invalid YAML")
- try:
- item = Item.parse_obj(data)
- except ValidationError as e:
- raise HTTPException(status_code=422, detail=e.errors())
- return item
diff --git a/docs_src/path_operation_advanced_configuration/tutorial007_pv1_py39.py b/docs_src/path_operation_advanced_configuration/tutorial007_pv1_py39.py
index 831966553f..849f648e12 100644
--- a/docs_src/path_operation_advanced_configuration/tutorial007_pv1_py39.py
+++ b/docs_src/path_operation_advanced_configuration/tutorial007_pv1_py39.py
@@ -1,6 +1,6 @@
import yaml
from fastapi import FastAPI, HTTPException, Request
-from pydantic import BaseModel, ValidationError
+from pydantic.v1 import BaseModel, ValidationError
app = FastAPI()
diff --git a/docs_src/path_operation_configuration/__init__.py b/docs_src/path_operation_configuration/__init__.py
new file mode 100644
index 0000000000..e69de29bb2
diff --git a/docs_src/path_operation_configuration/tutorial001.py b/docs_src/path_operation_configuration/tutorial001.py
deleted file mode 100644
index 83fd8377ab..0000000000
--- a/docs_src/path_operation_configuration/tutorial001.py
+++ /dev/null
@@ -1,19 +0,0 @@
-from typing import Set, Union
-
-from fastapi import FastAPI, status
-from pydantic import BaseModel
-
-app = FastAPI()
-
-
-class Item(BaseModel):
- name: str
- description: Union[str, None] = None
- price: float
- tax: Union[float, None] = None
- tags: Set[str] = set()
-
-
-@app.post("/items/", response_model=Item, status_code=status.HTTP_201_CREATED)
-async def create_item(item: Item):
- return item
diff --git a/docs_src/path_operation_configuration/tutorial002.py b/docs_src/path_operation_configuration/tutorial002.py
deleted file mode 100644
index 798b0c2311..0000000000
--- a/docs_src/path_operation_configuration/tutorial002.py
+++ /dev/null
@@ -1,29 +0,0 @@
-from typing import Set, Union
-
-from fastapi import FastAPI
-from pydantic import BaseModel
-
-app = FastAPI()
-
-
-class Item(BaseModel):
- name: str
- description: Union[str, None] = None
- price: float
- tax: Union[float, None] = None
- tags: Set[str] = set()
-
-
-@app.post("/items/", response_model=Item, tags=["items"])
-async def create_item(item: Item):
- return item
-
-
-@app.get("/items/", tags=["items"])
-async def read_items():
- return [{"name": "Foo", "price": 42}]
-
-
-@app.get("/users/", tags=["users"])
-async def read_users():
- return [{"username": "johndoe"}]
diff --git a/docs_src/path_operation_configuration/tutorial002b.py b/docs_src/path_operation_configuration/tutorial002b_py39.py
similarity index 100%
rename from docs_src/path_operation_configuration/tutorial002b.py
rename to docs_src/path_operation_configuration/tutorial002b_py39.py
diff --git a/docs_src/path_operation_configuration/tutorial003.py b/docs_src/path_operation_configuration/tutorial003.py
deleted file mode 100644
index 26bf7dabae..0000000000
--- a/docs_src/path_operation_configuration/tutorial003.py
+++ /dev/null
@@ -1,24 +0,0 @@
-from typing import Set, Union
-
-from fastapi import FastAPI
-from pydantic import BaseModel
-
-app = FastAPI()
-
-
-class Item(BaseModel):
- name: str
- description: Union[str, None] = None
- price: float
- tax: Union[float, None] = None
- tags: Set[str] = set()
-
-
-@app.post(
- "/items/",
- response_model=Item,
- summary="Create an item",
- description="Create an item with all the information, name, description, price, tax and a set of unique tags",
-)
-async def create_item(item: Item):
- return item
diff --git a/docs_src/path_operation_configuration/tutorial004.py b/docs_src/path_operation_configuration/tutorial004.py
deleted file mode 100644
index 8f865c58a6..0000000000
--- a/docs_src/path_operation_configuration/tutorial004.py
+++ /dev/null
@@ -1,28 +0,0 @@
-from typing import Set, Union
-
-from fastapi import FastAPI
-from pydantic import BaseModel
-
-app = FastAPI()
-
-
-class Item(BaseModel):
- name: str
- description: Union[str, None] = None
- price: float
- tax: Union[float, None] = None
- tags: Set[str] = set()
-
-
-@app.post("/items/", response_model=Item, summary="Create an item")
-async def create_item(item: Item):
- """
- Create an item with all the information:
-
- - **name**: each item must have a name
- - **description**: a long description
- - **price**: required
- - **tax**: if the item doesn't have tax, you can omit this
- - **tags**: a set of unique tag strings for this item
- """
- return item
diff --git a/docs_src/path_operation_configuration/tutorial005.py b/docs_src/path_operation_configuration/tutorial005.py
deleted file mode 100644
index 2c1be4a34b..0000000000
--- a/docs_src/path_operation_configuration/tutorial005.py
+++ /dev/null
@@ -1,33 +0,0 @@
-from typing import Set, Union
-
-from fastapi import FastAPI
-from pydantic import BaseModel
-
-app = FastAPI()
-
-
-class Item(BaseModel):
- name: str
- description: Union[str, None] = None
- price: float
- tax: Union[float, None] = None
- tags: Set[str] = set()
-
-
-@app.post(
- "/items/",
- response_model=Item,
- summary="Create an item",
- response_description="The created item",
-)
-async def create_item(item: Item):
- """
- Create an item with all the information:
-
- - **name**: each item must have a name
- - **description**: a long description
- - **price**: required
- - **tax**: if the item doesn't have tax, you can omit this
- - **tags**: a set of unique tag strings for this item
- """
- return item
diff --git a/docs_src/path_operation_configuration/tutorial006.py b/docs_src/path_operation_configuration/tutorial006_py39.py
similarity index 100%
rename from docs_src/path_operation_configuration/tutorial006.py
rename to docs_src/path_operation_configuration/tutorial006_py39.py
diff --git a/docs_src/path_params/__init__.py b/docs_src/path_params/__init__.py
new file mode 100644
index 0000000000..e69de29bb2
diff --git a/docs_src/path_params/tutorial001.py b/docs_src/path_params/tutorial001_py39.py
similarity index 100%
rename from docs_src/path_params/tutorial001.py
rename to docs_src/path_params/tutorial001_py39.py
diff --git a/docs_src/path_params/tutorial002.py b/docs_src/path_params/tutorial002_py39.py
similarity index 100%
rename from docs_src/path_params/tutorial002.py
rename to docs_src/path_params/tutorial002_py39.py
diff --git a/docs_src/path_params/tutorial003.py b/docs_src/path_params/tutorial003_py39.py
similarity index 100%
rename from docs_src/path_params/tutorial003.py
rename to docs_src/path_params/tutorial003_py39.py
diff --git a/docs_src/path_params/tutorial003b.py b/docs_src/path_params/tutorial003b_py39.py
similarity index 100%
rename from docs_src/path_params/tutorial003b.py
rename to docs_src/path_params/tutorial003b_py39.py
diff --git a/docs_src/path_params/tutorial004.py b/docs_src/path_params/tutorial004_py39.py
similarity index 100%
rename from docs_src/path_params/tutorial004.py
rename to docs_src/path_params/tutorial004_py39.py
diff --git a/docs_src/path_params/tutorial005.py b/docs_src/path_params/tutorial005_py39.py
similarity index 100%
rename from docs_src/path_params/tutorial005.py
rename to docs_src/path_params/tutorial005_py39.py
diff --git a/docs_src/path_params_numeric_validations/__init__.py b/docs_src/path_params_numeric_validations/__init__.py
new file mode 100644
index 0000000000..e69de29bb2
diff --git a/docs_src/path_params_numeric_validations/tutorial001_an.py b/docs_src/path_params_numeric_validations/tutorial001_an.py
deleted file mode 100644
index 621be7b045..0000000000
--- a/docs_src/path_params_numeric_validations/tutorial001_an.py
+++ /dev/null
@@ -1,17 +0,0 @@
-from typing import Union
-
-from fastapi import FastAPI, Path, Query
-from typing_extensions import Annotated
-
-app = FastAPI()
-
-
-@app.get("/items/{item_id}")
-async def read_items(
- item_id: Annotated[int, Path(title="The ID of the item to get")],
- q: Annotated[Union[str, None], Query(alias="item-query")] = None,
-):
- results = {"item_id": item_id}
- if q:
- results.update({"q": q})
- return results
diff --git a/docs_src/path_params_numeric_validations/tutorial001.py b/docs_src/path_params_numeric_validations/tutorial001_py39.py
similarity index 100%
rename from docs_src/path_params_numeric_validations/tutorial001.py
rename to docs_src/path_params_numeric_validations/tutorial001_py39.py
diff --git a/docs_src/path_params_numeric_validations/tutorial002_an.py b/docs_src/path_params_numeric_validations/tutorial002_an.py
deleted file mode 100644
index 322f8cf0bb..0000000000
--- a/docs_src/path_params_numeric_validations/tutorial002_an.py
+++ /dev/null
@@ -1,14 +0,0 @@
-from fastapi import FastAPI, Path
-from typing_extensions import Annotated
-
-app = FastAPI()
-
-
-@app.get("/items/{item_id}")
-async def read_items(
- q: str, item_id: Annotated[int, Path(title="The ID of the item to get")]
-):
- results = {"item_id": item_id}
- if q:
- results.update({"q": q})
- return results
diff --git a/docs_src/path_params_numeric_validations/tutorial002.py b/docs_src/path_params_numeric_validations/tutorial002_py39.py
similarity index 100%
rename from docs_src/path_params_numeric_validations/tutorial002.py
rename to docs_src/path_params_numeric_validations/tutorial002_py39.py
diff --git a/docs_src/path_params_numeric_validations/tutorial003_an.py b/docs_src/path_params_numeric_validations/tutorial003_an.py
deleted file mode 100644
index d0fa8b3db9..0000000000
--- a/docs_src/path_params_numeric_validations/tutorial003_an.py
+++ /dev/null
@@ -1,14 +0,0 @@
-from fastapi import FastAPI, Path
-from typing_extensions import Annotated
-
-app = FastAPI()
-
-
-@app.get("/items/{item_id}")
-async def read_items(
- item_id: Annotated[int, Path(title="The ID of the item to get")], q: str
-):
- results = {"item_id": item_id}
- if q:
- results.update({"q": q})
- return results
diff --git a/docs_src/path_params_numeric_validations/tutorial003.py b/docs_src/path_params_numeric_validations/tutorial003_py39.py
similarity index 100%
rename from docs_src/path_params_numeric_validations/tutorial003.py
rename to docs_src/path_params_numeric_validations/tutorial003_py39.py
diff --git a/docs_src/path_params_numeric_validations/tutorial004_an.py b/docs_src/path_params_numeric_validations/tutorial004_an.py
deleted file mode 100644
index ffc50f6c5b..0000000000
--- a/docs_src/path_params_numeric_validations/tutorial004_an.py
+++ /dev/null
@@ -1,14 +0,0 @@
-from fastapi import FastAPI, Path
-from typing_extensions import Annotated
-
-app = FastAPI()
-
-
-@app.get("/items/{item_id}")
-async def read_items(
- item_id: Annotated[int, Path(title="The ID of the item to get", ge=1)], q: str
-):
- results = {"item_id": item_id}
- if q:
- results.update({"q": q})
- return results
diff --git a/docs_src/path_params_numeric_validations/tutorial004.py b/docs_src/path_params_numeric_validations/tutorial004_py39.py
similarity index 100%
rename from docs_src/path_params_numeric_validations/tutorial004.py
rename to docs_src/path_params_numeric_validations/tutorial004_py39.py
diff --git a/docs_src/path_params_numeric_validations/tutorial005_an.py b/docs_src/path_params_numeric_validations/tutorial005_an.py
deleted file mode 100644
index 433c69129f..0000000000
--- a/docs_src/path_params_numeric_validations/tutorial005_an.py
+++ /dev/null
@@ -1,15 +0,0 @@
-from fastapi import FastAPI, Path
-from typing_extensions import Annotated
-
-app = FastAPI()
-
-
-@app.get("/items/{item_id}")
-async def read_items(
- item_id: Annotated[int, Path(title="The ID of the item to get", gt=0, le=1000)],
- q: str,
-):
- results = {"item_id": item_id}
- if q:
- results.update({"q": q})
- return results
diff --git a/docs_src/path_params_numeric_validations/tutorial005.py b/docs_src/path_params_numeric_validations/tutorial005_py39.py
similarity index 100%
rename from docs_src/path_params_numeric_validations/tutorial005.py
rename to docs_src/path_params_numeric_validations/tutorial005_py39.py
diff --git a/docs_src/path_params_numeric_validations/tutorial006_an.py b/docs_src/path_params_numeric_validations/tutorial006_an.py
deleted file mode 100644
index ac47325732..0000000000
--- a/docs_src/path_params_numeric_validations/tutorial006_an.py
+++ /dev/null
@@ -1,19 +0,0 @@
-from fastapi import FastAPI, Path, Query
-from typing_extensions import Annotated
-
-app = FastAPI()
-
-
-@app.get("/items/{item_id}")
-async def read_items(
- *,
- item_id: Annotated[int, Path(title="The ID of the item to get", ge=0, le=1000)],
- q: str,
- size: Annotated[float, Query(gt=0, lt=10.5)],
-):
- results = {"item_id": item_id}
- if q:
- results.update({"q": q})
- if size:
- results.update({"size": size})
- return results
diff --git a/docs_src/path_params_numeric_validations/tutorial006.py b/docs_src/path_params_numeric_validations/tutorial006_py39.py
similarity index 100%
rename from docs_src/path_params_numeric_validations/tutorial006.py
rename to docs_src/path_params_numeric_validations/tutorial006_py39.py
diff --git a/docs_src/pydantic_v1_in_v2/__init__.py b/docs_src/pydantic_v1_in_v2/__init__.py
new file mode 100644
index 0000000000..e69de29bb2
diff --git a/docs_src/pydantic_v1_in_v2/tutorial001_an.py b/docs_src/pydantic_v1_in_v2/tutorial001_an_py39.py
similarity index 100%
rename from docs_src/pydantic_v1_in_v2/tutorial001_an.py
rename to docs_src/pydantic_v1_in_v2/tutorial001_an_py39.py
diff --git a/docs_src/pydantic_v1_in_v2/tutorial002_an.py b/docs_src/pydantic_v1_in_v2/tutorial002_an_py39.py
similarity index 100%
rename from docs_src/pydantic_v1_in_v2/tutorial002_an.py
rename to docs_src/pydantic_v1_in_v2/tutorial002_an_py39.py
diff --git a/docs_src/pydantic_v1_in_v2/tutorial003_an.py b/docs_src/pydantic_v1_in_v2/tutorial003_an_py39.py
similarity index 100%
rename from docs_src/pydantic_v1_in_v2/tutorial003_an.py
rename to docs_src/pydantic_v1_in_v2/tutorial003_an_py39.py
diff --git a/docs_src/pydantic_v1_in_v2/tutorial004_an.py b/docs_src/pydantic_v1_in_v2/tutorial004_an.py
deleted file mode 100644
index cca8a9ea80..0000000000
--- a/docs_src/pydantic_v1_in_v2/tutorial004_an.py
+++ /dev/null
@@ -1,20 +0,0 @@
-from typing import Union
-
-from fastapi import FastAPI
-from fastapi.temp_pydantic_v1_params import Body
-from pydantic.v1 import BaseModel
-from typing_extensions import Annotated
-
-
-class Item(BaseModel):
- name: str
- description: Union[str, None] = None
- size: float
-
-
-app = FastAPI()
-
-
-@app.post("/items/")
-async def create_item(item: Annotated[Item, Body(embed=True)]) -> Item:
- return item
diff --git a/docs_src/python_types/__init__.py b/docs_src/python_types/__init__.py
new file mode 100644
index 0000000000..e69de29bb2
diff --git a/docs_src/python_types/tutorial001.py b/docs_src/python_types/tutorial001_py39.py
similarity index 100%
rename from docs_src/python_types/tutorial001.py
rename to docs_src/python_types/tutorial001_py39.py
diff --git a/docs_src/python_types/tutorial002.py b/docs_src/python_types/tutorial002_py39.py
similarity index 100%
rename from docs_src/python_types/tutorial002.py
rename to docs_src/python_types/tutorial002_py39.py
diff --git a/docs_src/python_types/tutorial003.py b/docs_src/python_types/tutorial003_py39.py
similarity index 100%
rename from docs_src/python_types/tutorial003.py
rename to docs_src/python_types/tutorial003_py39.py
diff --git a/docs_src/python_types/tutorial004.py b/docs_src/python_types/tutorial004_py39.py
similarity index 100%
rename from docs_src/python_types/tutorial004.py
rename to docs_src/python_types/tutorial004_py39.py
diff --git a/docs_src/python_types/tutorial005.py b/docs_src/python_types/tutorial005_py39.py
similarity index 59%
rename from docs_src/python_types/tutorial005.py
rename to docs_src/python_types/tutorial005_py39.py
index 08ab44a941..6c8edb0ec4 100644
--- a/docs_src/python_types/tutorial005.py
+++ b/docs_src/python_types/tutorial005_py39.py
@@ -1,2 +1,2 @@
def get_items(item_a: str, item_b: int, item_c: float, item_d: bool, item_e: bytes):
- return item_a, item_b, item_c, item_d, item_d, item_e
+ return item_a, item_b, item_c, item_d, item_e
diff --git a/docs_src/python_types/tutorial006.py b/docs_src/python_types/tutorial006.py
deleted file mode 100644
index 87394ecb0c..0000000000
--- a/docs_src/python_types/tutorial006.py
+++ /dev/null
@@ -1,6 +0,0 @@
-from typing import List
-
-
-def process_items(items: List[str]):
- for item in items:
- print(item)
diff --git a/docs_src/python_types/tutorial007.py b/docs_src/python_types/tutorial007.py
deleted file mode 100644
index 5b13f15494..0000000000
--- a/docs_src/python_types/tutorial007.py
+++ /dev/null
@@ -1,5 +0,0 @@
-from typing import Set, Tuple
-
-
-def process_items(items_t: Tuple[int, int, str], items_s: Set[bytes]):
- return items_t, items_s
diff --git a/docs_src/python_types/tutorial008.py b/docs_src/python_types/tutorial008.py
deleted file mode 100644
index 9fb1043bb8..0000000000
--- a/docs_src/python_types/tutorial008.py
+++ /dev/null
@@ -1,7 +0,0 @@
-from typing import Dict
-
-
-def process_items(prices: Dict[str, float]):
- for item_name, item_price in prices.items():
- print(item_name)
- print(item_price)
diff --git a/docs_src/python_types/tutorial008b.py b/docs_src/python_types/tutorial008b_py39.py
similarity index 100%
rename from docs_src/python_types/tutorial008b.py
rename to docs_src/python_types/tutorial008b_py39.py
diff --git a/docs_src/python_types/tutorial009.py b/docs_src/python_types/tutorial009_py39.py
similarity index 100%
rename from docs_src/python_types/tutorial009.py
rename to docs_src/python_types/tutorial009_py39.py
diff --git a/docs_src/python_types/tutorial009b.py b/docs_src/python_types/tutorial009b_py39.py
similarity index 100%
rename from docs_src/python_types/tutorial009b.py
rename to docs_src/python_types/tutorial009b_py39.py
diff --git a/docs_src/python_types/tutorial009c.py b/docs_src/python_types/tutorial009c_py39.py
similarity index 100%
rename from docs_src/python_types/tutorial009c.py
rename to docs_src/python_types/tutorial009c_py39.py
diff --git a/docs_src/python_types/tutorial010.py b/docs_src/python_types/tutorial010_py39.py
similarity index 100%
rename from docs_src/python_types/tutorial010.py
rename to docs_src/python_types/tutorial010_py39.py
diff --git a/docs_src/python_types/tutorial011.py b/docs_src/python_types/tutorial011.py
deleted file mode 100644
index 297a84db68..0000000000
--- a/docs_src/python_types/tutorial011.py
+++ /dev/null
@@ -1,23 +0,0 @@
-from datetime import datetime
-from typing import List, Union
-
-from pydantic import BaseModel
-
-
-class User(BaseModel):
- id: int
- name: str = "John Doe"
- signup_ts: Union[datetime, None] = None
- friends: List[int] = []
-
-
-external_data = {
- "id": "123",
- "signup_ts": "2017-06-01 12:22",
- "friends": [1, "2", b"3"],
-}
-user = User(**external_data)
-print(user)
-# > User id=123 name='John Doe' signup_ts=datetime.datetime(2017, 6, 1, 12, 22) friends=[1, 2, 3]
-print(user.id)
-# > 123
diff --git a/docs_src/python_types/tutorial012.py b/docs_src/python_types/tutorial012_py39.py
similarity index 100%
rename from docs_src/python_types/tutorial012.py
rename to docs_src/python_types/tutorial012_py39.py
diff --git a/docs_src/python_types/tutorial013.py b/docs_src/python_types/tutorial013.py
deleted file mode 100644
index 0ec7735199..0000000000
--- a/docs_src/python_types/tutorial013.py
+++ /dev/null
@@ -1,5 +0,0 @@
-from typing_extensions import Annotated
-
-
-def say_hello(name: Annotated[str, "this is just metadata"]) -> str:
- return f"Hello {name}"
diff --git a/docs_src/query_param_models/__init__.py b/docs_src/query_param_models/__init__.py
new file mode 100644
index 0000000000..e69de29bb2
diff --git a/docs_src/query_param_models/tutorial001.py b/docs_src/query_param_models/tutorial001.py
deleted file mode 100644
index 0c0ab315e8..0000000000
--- a/docs_src/query_param_models/tutorial001.py
+++ /dev/null
@@ -1,19 +0,0 @@
-from typing import List
-
-from fastapi import FastAPI, Query
-from pydantic import BaseModel, Field
-from typing_extensions import Literal
-
-app = FastAPI()
-
-
-class FilterParams(BaseModel):
- limit: int = Field(100, gt=0, le=100)
- offset: int = Field(0, ge=0)
- order_by: Literal["created_at", "updated_at"] = "created_at"
- tags: List[str] = []
-
-
-@app.get("/items/")
-async def read_items(filter_query: FilterParams = Query()):
- return filter_query
diff --git a/docs_src/query_param_models/tutorial001_an.py b/docs_src/query_param_models/tutorial001_an.py
deleted file mode 100644
index 28375057c1..0000000000
--- a/docs_src/query_param_models/tutorial001_an.py
+++ /dev/null
@@ -1,19 +0,0 @@
-from typing import List
-
-from fastapi import FastAPI, Query
-from pydantic import BaseModel, Field
-from typing_extensions import Annotated, Literal
-
-app = FastAPI()
-
-
-class FilterParams(BaseModel):
- limit: int = Field(100, gt=0, le=100)
- offset: int = Field(0, ge=0)
- order_by: Literal["created_at", "updated_at"] = "created_at"
- tags: List[str] = []
-
-
-@app.get("/items/")
-async def read_items(filter_query: Annotated[FilterParams, Query()]):
- return filter_query
diff --git a/docs_src/query_param_models/tutorial001_an_py39.py b/docs_src/query_param_models/tutorial001_an_py39.py
index ba690d3e3f..71427acae1 100644
--- a/docs_src/query_param_models/tutorial001_an_py39.py
+++ b/docs_src/query_param_models/tutorial001_an_py39.py
@@ -1,6 +1,7 @@
+from typing import Annotated, Literal
+
from fastapi import FastAPI, Query
from pydantic import BaseModel, Field
-from typing_extensions import Annotated, Literal
app = FastAPI()
diff --git a/docs_src/query_param_models/tutorial001_py39.py b/docs_src/query_param_models/tutorial001_py39.py
index 54b52a054c..3ebf9f4d70 100644
--- a/docs_src/query_param_models/tutorial001_py39.py
+++ b/docs_src/query_param_models/tutorial001_py39.py
@@ -1,6 +1,7 @@
+from typing import Literal
+
from fastapi import FastAPI, Query
from pydantic import BaseModel, Field
-from typing_extensions import Literal
app = FastAPI()
diff --git a/docs_src/query_param_models/tutorial002.py b/docs_src/query_param_models/tutorial002.py
deleted file mode 100644
index 1633bc4644..0000000000
--- a/docs_src/query_param_models/tutorial002.py
+++ /dev/null
@@ -1,21 +0,0 @@
-from typing import List
-
-from fastapi import FastAPI, Query
-from pydantic import BaseModel, Field
-from typing_extensions import Literal
-
-app = FastAPI()
-
-
-class FilterParams(BaseModel):
- model_config = {"extra": "forbid"}
-
- limit: int = Field(100, gt=0, le=100)
- offset: int = Field(0, ge=0)
- order_by: Literal["created_at", "updated_at"] = "created_at"
- tags: List[str] = []
-
-
-@app.get("/items/")
-async def read_items(filter_query: FilterParams = Query()):
- return filter_query
diff --git a/docs_src/query_param_models/tutorial002_an.py b/docs_src/query_param_models/tutorial002_an.py
deleted file mode 100644
index 69705d4b4b..0000000000
--- a/docs_src/query_param_models/tutorial002_an.py
+++ /dev/null
@@ -1,21 +0,0 @@
-from typing import List
-
-from fastapi import FastAPI, Query
-from pydantic import BaseModel, Field
-from typing_extensions import Annotated, Literal
-
-app = FastAPI()
-
-
-class FilterParams(BaseModel):
- model_config = {"extra": "forbid"}
-
- limit: int = Field(100, gt=0, le=100)
- offset: int = Field(0, ge=0)
- order_by: Literal["created_at", "updated_at"] = "created_at"
- tags: List[str] = []
-
-
-@app.get("/items/")
-async def read_items(filter_query: Annotated[FilterParams, Query()]):
- return filter_query
diff --git a/docs_src/query_param_models/tutorial002_an_py39.py b/docs_src/query_param_models/tutorial002_an_py39.py
index 2d4c1a62b5..9759565023 100644
--- a/docs_src/query_param_models/tutorial002_an_py39.py
+++ b/docs_src/query_param_models/tutorial002_an_py39.py
@@ -1,6 +1,7 @@
+from typing import Annotated, Literal
+
from fastapi import FastAPI, Query
from pydantic import BaseModel, Field
-from typing_extensions import Annotated, Literal
app = FastAPI()
diff --git a/docs_src/query_param_models/tutorial002_pv1.py b/docs_src/query_param_models/tutorial002_pv1.py
deleted file mode 100644
index 71ccd961d3..0000000000
--- a/docs_src/query_param_models/tutorial002_pv1.py
+++ /dev/null
@@ -1,22 +0,0 @@
-from typing import List
-
-from fastapi import FastAPI, Query
-from pydantic import BaseModel, Field
-from typing_extensions import Literal
-
-app = FastAPI()
-
-
-class FilterParams(BaseModel):
- class Config:
- extra = "forbid"
-
- limit: int = Field(100, gt=0, le=100)
- offset: int = Field(0, ge=0)
- order_by: Literal["created_at", "updated_at"] = "created_at"
- tags: List[str] = []
-
-
-@app.get("/items/")
-async def read_items(filter_query: FilterParams = Query()):
- return filter_query
diff --git a/docs_src/query_param_models/tutorial002_pv1_an.py b/docs_src/query_param_models/tutorial002_pv1_an.py
deleted file mode 100644
index 1dd29157a4..0000000000
--- a/docs_src/query_param_models/tutorial002_pv1_an.py
+++ /dev/null
@@ -1,22 +0,0 @@
-from typing import List
-
-from fastapi import FastAPI, Query
-from pydantic import BaseModel, Field
-from typing_extensions import Annotated, Literal
-
-app = FastAPI()
-
-
-class FilterParams(BaseModel):
- class Config:
- extra = "forbid"
-
- limit: int = Field(100, gt=0, le=100)
- offset: int = Field(0, ge=0)
- order_by: Literal["created_at", "updated_at"] = "created_at"
- tags: List[str] = []
-
-
-@app.get("/items/")
-async def read_items(filter_query: Annotated[FilterParams, Query()]):
- return filter_query
diff --git a/docs_src/query_param_models/tutorial002_pv1_an_py310.py b/docs_src/query_param_models/tutorial002_pv1_an_py310.py
deleted file mode 100644
index d635aae88f..0000000000
--- a/docs_src/query_param_models/tutorial002_pv1_an_py310.py
+++ /dev/null
@@ -1,21 +0,0 @@
-from typing import Annotated, Literal
-
-from fastapi import FastAPI, Query
-from pydantic import BaseModel, Field
-
-app = FastAPI()
-
-
-class FilterParams(BaseModel):
- class Config:
- extra = "forbid"
-
- limit: int = Field(100, gt=0, le=100)
- offset: int = Field(0, ge=0)
- order_by: Literal["created_at", "updated_at"] = "created_at"
- tags: list[str] = []
-
-
-@app.get("/items/")
-async def read_items(filter_query: Annotated[FilterParams, Query()]):
- return filter_query
diff --git a/docs_src/query_param_models/tutorial002_pv1_an_py39.py b/docs_src/query_param_models/tutorial002_pv1_an_py39.py
deleted file mode 100644
index 494fef11fc..0000000000
--- a/docs_src/query_param_models/tutorial002_pv1_an_py39.py
+++ /dev/null
@@ -1,20 +0,0 @@
-from fastapi import FastAPI, Query
-from pydantic import BaseModel, Field
-from typing_extensions import Annotated, Literal
-
-app = FastAPI()
-
-
-class FilterParams(BaseModel):
- class Config:
- extra = "forbid"
-
- limit: int = Field(100, gt=0, le=100)
- offset: int = Field(0, ge=0)
- order_by: Literal["created_at", "updated_at"] = "created_at"
- tags: list[str] = []
-
-
-@app.get("/items/")
-async def read_items(filter_query: Annotated[FilterParams, Query()]):
- return filter_query
diff --git a/docs_src/query_param_models/tutorial002_pv1_py310.py b/docs_src/query_param_models/tutorial002_pv1_py310.py
deleted file mode 100644
index 9ffdeefc06..0000000000
--- a/docs_src/query_param_models/tutorial002_pv1_py310.py
+++ /dev/null
@@ -1,21 +0,0 @@
-from typing import Literal
-
-from fastapi import FastAPI, Query
-from pydantic import BaseModel, Field
-
-app = FastAPI()
-
-
-class FilterParams(BaseModel):
- class Config:
- extra = "forbid"
-
- limit: int = Field(100, gt=0, le=100)
- offset: int = Field(0, ge=0)
- order_by: Literal["created_at", "updated_at"] = "created_at"
- tags: list[str] = []
-
-
-@app.get("/items/")
-async def read_items(filter_query: FilterParams = Query()):
- return filter_query
diff --git a/docs_src/query_param_models/tutorial002_pv1_py39.py b/docs_src/query_param_models/tutorial002_pv1_py39.py
deleted file mode 100644
index 7fa456a791..0000000000
--- a/docs_src/query_param_models/tutorial002_pv1_py39.py
+++ /dev/null
@@ -1,20 +0,0 @@
-from fastapi import FastAPI, Query
-from pydantic import BaseModel, Field
-from typing_extensions import Literal
-
-app = FastAPI()
-
-
-class FilterParams(BaseModel):
- class Config:
- extra = "forbid"
-
- limit: int = Field(100, gt=0, le=100)
- offset: int = Field(0, ge=0)
- order_by: Literal["created_at", "updated_at"] = "created_at"
- tags: list[str] = []
-
-
-@app.get("/items/")
-async def read_items(filter_query: FilterParams = Query()):
- return filter_query
diff --git a/docs_src/query_param_models/tutorial002_py39.py b/docs_src/query_param_models/tutorial002_py39.py
index f9bba028c2..6ec4184991 100644
--- a/docs_src/query_param_models/tutorial002_py39.py
+++ b/docs_src/query_param_models/tutorial002_py39.py
@@ -1,6 +1,7 @@
+from typing import Literal
+
from fastapi import FastAPI, Query
from pydantic import BaseModel, Field
-from typing_extensions import Literal
app = FastAPI()
diff --git a/docs_src/query_params/__init__.py b/docs_src/query_params/__init__.py
new file mode 100644
index 0000000000..e69de29bb2
diff --git a/docs_src/query_params/tutorial001.py b/docs_src/query_params/tutorial001_py39.py
similarity index 100%
rename from docs_src/query_params/tutorial001.py
rename to docs_src/query_params/tutorial001_py39.py
diff --git a/docs_src/query_params/tutorial002.py b/docs_src/query_params/tutorial002_py39.py
similarity index 100%
rename from docs_src/query_params/tutorial002.py
rename to docs_src/query_params/tutorial002_py39.py
diff --git a/docs_src/query_params/tutorial003.py b/docs_src/query_params/tutorial003_py39.py
similarity index 100%
rename from docs_src/query_params/tutorial003.py
rename to docs_src/query_params/tutorial003_py39.py
diff --git a/docs_src/query_params/tutorial004.py b/docs_src/query_params/tutorial004_py39.py
similarity index 100%
rename from docs_src/query_params/tutorial004.py
rename to docs_src/query_params/tutorial004_py39.py
diff --git a/docs_src/query_params/tutorial005.py b/docs_src/query_params/tutorial005_py39.py
similarity index 100%
rename from docs_src/query_params/tutorial005.py
rename to docs_src/query_params/tutorial005_py39.py
diff --git a/docs_src/query_params/tutorial006.py b/docs_src/query_params/tutorial006_py39.py
similarity index 100%
rename from docs_src/query_params/tutorial006.py
rename to docs_src/query_params/tutorial006_py39.py
diff --git a/docs_src/query_params/tutorial006b.py b/docs_src/query_params/tutorial006b.py
deleted file mode 100644
index f0dbfe08fe..0000000000
--- a/docs_src/query_params/tutorial006b.py
+++ /dev/null
@@ -1,13 +0,0 @@
-from typing import Union
-
-from fastapi import FastAPI
-
-app = FastAPI()
-
-
-@app.get("/items/{item_id}")
-async def read_user_item(
- item_id: str, needy: str, skip: int = 0, limit: Union[int, None] = None
-):
- item = {"item_id": item_id, "needy": needy, "skip": skip, "limit": limit}
- return item
diff --git a/docs_src/query_params_str_validations/__init__.py b/docs_src/query_params_str_validations/__init__.py
new file mode 100644
index 0000000000..e69de29bb2
diff --git a/docs_src/query_params_str_validations/tutorial001.py b/docs_src/query_params_str_validations/tutorial001_py39.py
similarity index 100%
rename from docs_src/query_params_str_validations/tutorial001.py
rename to docs_src/query_params_str_validations/tutorial001_py39.py
diff --git a/docs_src/query_params_str_validations/tutorial002_an.py b/docs_src/query_params_str_validations/tutorial002_an_py39.py
similarity index 81%
rename from docs_src/query_params_str_validations/tutorial002_an.py
rename to docs_src/query_params_str_validations/tutorial002_an_py39.py
index cb1b38940c..2d8fc97985 100644
--- a/docs_src/query_params_str_validations/tutorial002_an.py
+++ b/docs_src/query_params_str_validations/tutorial002_an_py39.py
@@ -1,7 +1,6 @@
-from typing import Union
+from typing import Annotated, Union
from fastapi import FastAPI, Query
-from typing_extensions import Annotated
app = FastAPI()
diff --git a/docs_src/query_params_str_validations/tutorial002.py b/docs_src/query_params_str_validations/tutorial002_py39.py
similarity index 100%
rename from docs_src/query_params_str_validations/tutorial002.py
rename to docs_src/query_params_str_validations/tutorial002_py39.py
diff --git a/docs_src/query_params_str_validations/tutorial003_an.py b/docs_src/query_params_str_validations/tutorial003_an.py
deleted file mode 100644
index 0dd14086cf..0000000000
--- a/docs_src/query_params_str_validations/tutorial003_an.py
+++ /dev/null
@@ -1,16 +0,0 @@
-from typing import Union
-
-from fastapi import FastAPI, Query
-from typing_extensions import Annotated
-
-app = FastAPI()
-
-
-@app.get("/items/")
-async def read_items(
- q: Annotated[Union[str, None], Query(min_length=3, max_length=50)] = None,
-):
- results = {"items": [{"item_id": "Foo"}, {"item_id": "Bar"}]}
- if q:
- results.update({"q": q})
- return results
diff --git a/docs_src/query_params_str_validations/tutorial003.py b/docs_src/query_params_str_validations/tutorial003_py39.py
similarity index 100%
rename from docs_src/query_params_str_validations/tutorial003.py
rename to docs_src/query_params_str_validations/tutorial003_py39.py
diff --git a/docs_src/query_params_str_validations/tutorial004_an.py b/docs_src/query_params_str_validations/tutorial004_an.py
deleted file mode 100644
index c75d45d63e..0000000000
--- a/docs_src/query_params_str_validations/tutorial004_an.py
+++ /dev/null
@@ -1,18 +0,0 @@
-from typing import Union
-
-from fastapi import FastAPI, Query
-from typing_extensions import Annotated
-
-app = FastAPI()
-
-
-@app.get("/items/")
-async def read_items(
- q: Annotated[
- Union[str, None], Query(min_length=3, max_length=50, pattern="^fixedquery$")
- ] = None,
-):
- results = {"items": [{"item_id": "Foo"}, {"item_id": "Bar"}]}
- if q:
- results.update({"q": q})
- return results
diff --git a/docs_src/query_params_str_validations/tutorial004.py b/docs_src/query_params_str_validations/tutorial004_py39.py
similarity index 100%
rename from docs_src/query_params_str_validations/tutorial004.py
rename to docs_src/query_params_str_validations/tutorial004_py39.py
diff --git a/docs_src/query_params_str_validations/tutorial005_an.py b/docs_src/query_params_str_validations/tutorial005_an.py
deleted file mode 100644
index 452d4d38d7..0000000000
--- a/docs_src/query_params_str_validations/tutorial005_an.py
+++ /dev/null
@@ -1,12 +0,0 @@
-from fastapi import FastAPI, Query
-from typing_extensions import Annotated
-
-app = FastAPI()
-
-
-@app.get("/items/")
-async def read_items(q: Annotated[str, Query(min_length=3)] = "fixedquery"):
- results = {"items": [{"item_id": "Foo"}, {"item_id": "Bar"}]}
- if q:
- results.update({"q": q})
- return results
diff --git a/docs_src/query_params_str_validations/tutorial005.py b/docs_src/query_params_str_validations/tutorial005_py39.py
similarity index 100%
rename from docs_src/query_params_str_validations/tutorial005.py
rename to docs_src/query_params_str_validations/tutorial005_py39.py
diff --git a/docs_src/query_params_str_validations/tutorial006_an.py b/docs_src/query_params_str_validations/tutorial006_an.py
deleted file mode 100644
index 559480d2bf..0000000000
--- a/docs_src/query_params_str_validations/tutorial006_an.py
+++ /dev/null
@@ -1,12 +0,0 @@
-from fastapi import FastAPI, Query
-from typing_extensions import Annotated
-
-app = FastAPI()
-
-
-@app.get("/items/")
-async def read_items(q: Annotated[str, Query(min_length=3)]):
- results = {"items": [{"item_id": "Foo"}, {"item_id": "Bar"}]}
- if q:
- results.update({"q": q})
- return results
diff --git a/docs_src/query_params_str_validations/tutorial006.py b/docs_src/query_params_str_validations/tutorial006_py39.py
similarity index 100%
rename from docs_src/query_params_str_validations/tutorial006.py
rename to docs_src/query_params_str_validations/tutorial006_py39.py
diff --git a/docs_src/query_params_str_validations/tutorial006c_an.py b/docs_src/query_params_str_validations/tutorial006c_an.py
deleted file mode 100644
index 55c4f4adca..0000000000
--- a/docs_src/query_params_str_validations/tutorial006c_an.py
+++ /dev/null
@@ -1,14 +0,0 @@
-from typing import Union
-
-from fastapi import FastAPI, Query
-from typing_extensions import Annotated
-
-app = FastAPI()
-
-
-@app.get("/items/")
-async def read_items(q: Annotated[Union[str, None], Query(min_length=3)]):
- results = {"items": [{"item_id": "Foo"}, {"item_id": "Bar"}]}
- if q:
- results.update({"q": q})
- return results
diff --git a/docs_src/query_params_str_validations/tutorial006c.py b/docs_src/query_params_str_validations/tutorial006c_py39.py
similarity index 100%
rename from docs_src/query_params_str_validations/tutorial006c.py
rename to docs_src/query_params_str_validations/tutorial006c_py39.py
diff --git a/docs_src/query_params_str_validations/tutorial007_an.py b/docs_src/query_params_str_validations/tutorial007_an.py
deleted file mode 100644
index 4b3c8de4b9..0000000000
--- a/docs_src/query_params_str_validations/tutorial007_an.py
+++ /dev/null
@@ -1,16 +0,0 @@
-from typing import Union
-
-from fastapi import FastAPI, Query
-from typing_extensions import Annotated
-
-app = FastAPI()
-
-
-@app.get("/items/")
-async def read_items(
- q: Annotated[Union[str, None], Query(title="Query string", min_length=3)] = None,
-):
- results = {"items": [{"item_id": "Foo"}, {"item_id": "Bar"}]}
- if q:
- results.update({"q": q})
- return results
diff --git a/docs_src/query_params_str_validations/tutorial007.py b/docs_src/query_params_str_validations/tutorial007_py39.py
similarity index 100%
rename from docs_src/query_params_str_validations/tutorial007.py
rename to docs_src/query_params_str_validations/tutorial007_py39.py
diff --git a/docs_src/query_params_str_validations/tutorial008_an.py b/docs_src/query_params_str_validations/tutorial008_an.py
deleted file mode 100644
index 01606a9203..0000000000
--- a/docs_src/query_params_str_validations/tutorial008_an.py
+++ /dev/null
@@ -1,23 +0,0 @@
-from typing import Union
-
-from fastapi import FastAPI, Query
-from typing_extensions import Annotated
-
-app = FastAPI()
-
-
-@app.get("/items/")
-async def read_items(
- q: Annotated[
- Union[str, None],
- Query(
- title="Query string",
- description="Query string for the items to search in the database that have a good match",
- min_length=3,
- ),
- ] = None,
-):
- results = {"items": [{"item_id": "Foo"}, {"item_id": "Bar"}]}
- if q:
- results.update({"q": q})
- return results
diff --git a/docs_src/query_params_str_validations/tutorial008.py b/docs_src/query_params_str_validations/tutorial008_py39.py
similarity index 100%
rename from docs_src/query_params_str_validations/tutorial008.py
rename to docs_src/query_params_str_validations/tutorial008_py39.py
diff --git a/docs_src/query_params_str_validations/tutorial009_an.py b/docs_src/query_params_str_validations/tutorial009_an.py
deleted file mode 100644
index 2894e2d51a..0000000000
--- a/docs_src/query_params_str_validations/tutorial009_an.py
+++ /dev/null
@@ -1,14 +0,0 @@
-from typing import Union
-
-from fastapi import FastAPI, Query
-from typing_extensions import Annotated
-
-app = FastAPI()
-
-
-@app.get("/items/")
-async def read_items(q: Annotated[Union[str, None], Query(alias="item-query")] = None):
- results = {"items": [{"item_id": "Foo"}, {"item_id": "Bar"}]}
- if q:
- results.update({"q": q})
- return results
diff --git a/docs_src/query_params_str_validations/tutorial009.py b/docs_src/query_params_str_validations/tutorial009_py39.py
similarity index 100%
rename from docs_src/query_params_str_validations/tutorial009.py
rename to docs_src/query_params_str_validations/tutorial009_py39.py
diff --git a/docs_src/query_params_str_validations/tutorial010_an.py b/docs_src/query_params_str_validations/tutorial010_an.py
deleted file mode 100644
index ed343230f4..0000000000
--- a/docs_src/query_params_str_validations/tutorial010_an.py
+++ /dev/null
@@ -1,27 +0,0 @@
-from typing import Union
-
-from fastapi import FastAPI, Query
-from typing_extensions import Annotated
-
-app = FastAPI()
-
-
-@app.get("/items/")
-async def read_items(
- q: Annotated[
- Union[str, None],
- Query(
- alias="item-query",
- title="Query string",
- description="Query string for the items to search in the database that have a good match",
- min_length=3,
- max_length=50,
- pattern="^fixedquery$",
- deprecated=True,
- ),
- ] = None,
-):
- results = {"items": [{"item_id": "Foo"}, {"item_id": "Bar"}]}
- if q:
- results.update({"q": q})
- return results
diff --git a/docs_src/query_params_str_validations/tutorial010.py b/docs_src/query_params_str_validations/tutorial010_py39.py
similarity index 100%
rename from docs_src/query_params_str_validations/tutorial010.py
rename to docs_src/query_params_str_validations/tutorial010_py39.py
diff --git a/docs_src/query_params_str_validations/tutorial011.py b/docs_src/query_params_str_validations/tutorial011.py
deleted file mode 100644
index 65bbce781a..0000000000
--- a/docs_src/query_params_str_validations/tutorial011.py
+++ /dev/null
@@ -1,11 +0,0 @@
-from typing import List, Union
-
-from fastapi import FastAPI, Query
-
-app = FastAPI()
-
-
-@app.get("/items/")
-async def read_items(q: Union[List[str], None] = Query(default=None)):
- query_items = {"q": q}
- return query_items
diff --git a/docs_src/query_params_str_validations/tutorial011_an.py b/docs_src/query_params_str_validations/tutorial011_an.py
deleted file mode 100644
index 8ed699337d..0000000000
--- a/docs_src/query_params_str_validations/tutorial011_an.py
+++ /dev/null
@@ -1,12 +0,0 @@
-from typing import List, Union
-
-from fastapi import FastAPI, Query
-from typing_extensions import Annotated
-
-app = FastAPI()
-
-
-@app.get("/items/")
-async def read_items(q: Annotated[Union[List[str], None], Query()] = None):
- query_items = {"q": q}
- return query_items
diff --git a/docs_src/query_params_str_validations/tutorial012.py b/docs_src/query_params_str_validations/tutorial012.py
deleted file mode 100644
index e77d56974d..0000000000
--- a/docs_src/query_params_str_validations/tutorial012.py
+++ /dev/null
@@ -1,11 +0,0 @@
-from typing import List
-
-from fastapi import FastAPI, Query
-
-app = FastAPI()
-
-
-@app.get("/items/")
-async def read_items(q: List[str] = Query(default=["foo", "bar"])):
- query_items = {"q": q}
- return query_items
diff --git a/docs_src/query_params_str_validations/tutorial012_an.py b/docs_src/query_params_str_validations/tutorial012_an.py
deleted file mode 100644
index 261af250a1..0000000000
--- a/docs_src/query_params_str_validations/tutorial012_an.py
+++ /dev/null
@@ -1,12 +0,0 @@
-from typing import List
-
-from fastapi import FastAPI, Query
-from typing_extensions import Annotated
-
-app = FastAPI()
-
-
-@app.get("/items/")
-async def read_items(q: Annotated[List[str], Query()] = ["foo", "bar"]):
- query_items = {"q": q}
- return query_items
diff --git a/docs_src/query_params_str_validations/tutorial013_an.py b/docs_src/query_params_str_validations/tutorial013_an.py
deleted file mode 100644
index f12a250559..0000000000
--- a/docs_src/query_params_str_validations/tutorial013_an.py
+++ /dev/null
@@ -1,10 +0,0 @@
-from fastapi import FastAPI, Query
-from typing_extensions import Annotated
-
-app = FastAPI()
-
-
-@app.get("/items/")
-async def read_items(q: Annotated[list, Query()] = []):
- query_items = {"q": q}
- return query_items
diff --git a/docs_src/query_params_str_validations/tutorial013.py b/docs_src/query_params_str_validations/tutorial013_py39.py
similarity index 100%
rename from docs_src/query_params_str_validations/tutorial013.py
rename to docs_src/query_params_str_validations/tutorial013_py39.py
diff --git a/docs_src/query_params_str_validations/tutorial014_an.py b/docs_src/query_params_str_validations/tutorial014_an.py
deleted file mode 100644
index 2eaa585407..0000000000
--- a/docs_src/query_params_str_validations/tutorial014_an.py
+++ /dev/null
@@ -1,16 +0,0 @@
-from typing import Union
-
-from fastapi import FastAPI, Query
-from typing_extensions import Annotated
-
-app = FastAPI()
-
-
-@app.get("/items/")
-async def read_items(
- hidden_query: Annotated[Union[str, None], Query(include_in_schema=False)] = None,
-):
- if hidden_query:
- return {"hidden_query": hidden_query}
- else:
- return {"hidden_query": "Not found"}
diff --git a/docs_src/query_params_str_validations/tutorial014.py b/docs_src/query_params_str_validations/tutorial014_py39.py
similarity index 100%
rename from docs_src/query_params_str_validations/tutorial014.py
rename to docs_src/query_params_str_validations/tutorial014_py39.py
diff --git a/docs_src/query_params_str_validations/tutorial015_an.py b/docs_src/query_params_str_validations/tutorial015_an.py
deleted file mode 100644
index f2ec6db123..0000000000
--- a/docs_src/query_params_str_validations/tutorial015_an.py
+++ /dev/null
@@ -1,31 +0,0 @@
-import random
-from typing import Union
-
-from fastapi import FastAPI
-from pydantic import AfterValidator
-from typing_extensions import Annotated
-
-app = FastAPI()
-
-data = {
- "isbn-9781529046137": "The Hitchhiker's Guide to the Galaxy",
- "imdb-tt0371724": "The Hitchhiker's Guide to the Galaxy",
- "isbn-9781439512982": "Isaac Asimov: The Complete Stories, Vol. 2",
-}
-
-
-def check_valid_id(id: str):
- if not id.startswith(("isbn-", "imdb-")):
- raise ValueError('Invalid ID format, it must start with "isbn-" or "imdb-"')
- return id
-
-
-@app.get("/items/")
-async def read_items(
- id: Annotated[Union[str, None], AfterValidator(check_valid_id)] = None,
-):
- if id:
- item = data.get(id)
- else:
- id, item = random.choice(list(data.items()))
- return {"id": id, "name": item}
diff --git a/docs_src/request_files/__init__.py b/docs_src/request_files/__init__.py
new file mode 100644
index 0000000000..e69de29bb2
diff --git a/docs_src/request_files/tutorial001_02_an.py b/docs_src/request_files/tutorial001_02_an.py
deleted file mode 100644
index 5007fef159..0000000000
--- a/docs_src/request_files/tutorial001_02_an.py
+++ /dev/null
@@ -1,22 +0,0 @@
-from typing import Union
-
-from fastapi import FastAPI, File, UploadFile
-from typing_extensions import Annotated
-
-app = FastAPI()
-
-
-@app.post("/files/")
-async def create_file(file: Annotated[Union[bytes, None], File()] = None):
- if not file:
- return {"message": "No file sent"}
- else:
- return {"file_size": len(file)}
-
-
-@app.post("/uploadfile/")
-async def create_upload_file(file: Union[UploadFile, None] = None):
- if not file:
- return {"message": "No upload file sent"}
- else:
- return {"filename": file.filename}
diff --git a/docs_src/request_files/tutorial001_02.py b/docs_src/request_files/tutorial001_02_py39.py
similarity index 100%
rename from docs_src/request_files/tutorial001_02.py
rename to docs_src/request_files/tutorial001_02_py39.py
diff --git a/docs_src/request_files/tutorial001_03_an.py b/docs_src/request_files/tutorial001_03_an.py
deleted file mode 100644
index 8a6b0a2455..0000000000
--- a/docs_src/request_files/tutorial001_03_an.py
+++ /dev/null
@@ -1,16 +0,0 @@
-from fastapi import FastAPI, File, UploadFile
-from typing_extensions import Annotated
-
-app = FastAPI()
-
-
-@app.post("/files/")
-async def create_file(file: Annotated[bytes, File(description="A file read as bytes")]):
- return {"file_size": len(file)}
-
-
-@app.post("/uploadfile/")
-async def create_upload_file(
- file: Annotated[UploadFile, File(description="A file read as UploadFile")],
-):
- return {"filename": file.filename}
diff --git a/docs_src/request_files/tutorial001_03.py b/docs_src/request_files/tutorial001_03_py39.py
similarity index 100%
rename from docs_src/request_files/tutorial001_03.py
rename to docs_src/request_files/tutorial001_03_py39.py
diff --git a/docs_src/request_files/tutorial001_an.py b/docs_src/request_files/tutorial001_an.py
deleted file mode 100644
index ca2f76d5c6..0000000000
--- a/docs_src/request_files/tutorial001_an.py
+++ /dev/null
@@ -1,14 +0,0 @@
-from fastapi import FastAPI, File, UploadFile
-from typing_extensions import Annotated
-
-app = FastAPI()
-
-
-@app.post("/files/")
-async def create_file(file: Annotated[bytes, File()]):
- return {"file_size": len(file)}
-
-
-@app.post("/uploadfile/")
-async def create_upload_file(file: UploadFile):
- return {"filename": file.filename}
diff --git a/docs_src/request_files/tutorial001.py b/docs_src/request_files/tutorial001_py39.py
similarity index 100%
rename from docs_src/request_files/tutorial001.py
rename to docs_src/request_files/tutorial001_py39.py
diff --git a/docs_src/request_files/tutorial002.py b/docs_src/request_files/tutorial002.py
deleted file mode 100644
index b4d0acc68f..0000000000
--- a/docs_src/request_files/tutorial002.py
+++ /dev/null
@@ -1,33 +0,0 @@
-from typing import List
-
-from fastapi import FastAPI, File, UploadFile
-from fastapi.responses import HTMLResponse
-
-app = FastAPI()
-
-
-@app.post("/files/")
-async def create_files(files: List[bytes] = File()):
- return {"file_sizes": [len(file) for file in files]}
-
-
-@app.post("/uploadfiles/")
-async def create_upload_files(files: List[UploadFile]):
- return {"filenames": [file.filename for file in files]}
-
-
-@app.get("/")
-async def main():
- content = """
-
-
-
-
- """
- return HTMLResponse(content=content)
diff --git a/docs_src/request_files/tutorial002_an.py b/docs_src/request_files/tutorial002_an.py
deleted file mode 100644
index eaa90da2b6..0000000000
--- a/docs_src/request_files/tutorial002_an.py
+++ /dev/null
@@ -1,34 +0,0 @@
-from typing import List
-
-from fastapi import FastAPI, File, UploadFile
-from fastapi.responses import HTMLResponse
-from typing_extensions import Annotated
-
-app = FastAPI()
-
-
-@app.post("/files/")
-async def create_files(files: Annotated[List[bytes], File()]):
- return {"file_sizes": [len(file) for file in files]}
-
-
-@app.post("/uploadfiles/")
-async def create_upload_files(files: List[UploadFile]):
- return {"filenames": [file.filename for file in files]}
-
-
-@app.get("/")
-async def main():
- content = """
-
-
-
-
- """
- return HTMLResponse(content=content)
diff --git a/docs_src/request_files/tutorial003.py b/docs_src/request_files/tutorial003.py
deleted file mode 100644
index e3f805f605..0000000000
--- a/docs_src/request_files/tutorial003.py
+++ /dev/null
@@ -1,37 +0,0 @@
-from typing import List
-
-from fastapi import FastAPI, File, UploadFile
-from fastapi.responses import HTMLResponse
-
-app = FastAPI()
-
-
-@app.post("/files/")
-async def create_files(
- files: List[bytes] = File(description="Multiple files as bytes"),
-):
- return {"file_sizes": [len(file) for file in files]}
-
-
-@app.post("/uploadfiles/")
-async def create_upload_files(
- files: List[UploadFile] = File(description="Multiple files as UploadFile"),
-):
- return {"filenames": [file.filename for file in files]}
-
-
-@app.get("/")
-async def main():
- content = """
-
-
-
-
- """
- return HTMLResponse(content=content)
diff --git a/docs_src/request_files/tutorial003_an.py b/docs_src/request_files/tutorial003_an.py
deleted file mode 100644
index 2238e3c94b..0000000000
--- a/docs_src/request_files/tutorial003_an.py
+++ /dev/null
@@ -1,40 +0,0 @@
-from typing import List
-
-from fastapi import FastAPI, File, UploadFile
-from fastapi.responses import HTMLResponse
-from typing_extensions import Annotated
-
-app = FastAPI()
-
-
-@app.post("/files/")
-async def create_files(
- files: Annotated[List[bytes], File(description="Multiple files as bytes")],
-):
- return {"file_sizes": [len(file) for file in files]}
-
-
-@app.post("/uploadfiles/")
-async def create_upload_files(
- files: Annotated[
- List[UploadFile], File(description="Multiple files as UploadFile")
- ],
-):
- return {"filenames": [file.filename for file in files]}
-
-
-@app.get("/")
-async def main():
- content = """
-
-
-
-
- """
- return HTMLResponse(content=content)
diff --git a/docs_src/request_form_models/__init__.py b/docs_src/request_form_models/__init__.py
new file mode 100644
index 0000000000..e69de29bb2
diff --git a/docs_src/request_form_models/tutorial001_an.py b/docs_src/request_form_models/tutorial001_an.py
deleted file mode 100644
index 30483d4455..0000000000
--- a/docs_src/request_form_models/tutorial001_an.py
+++ /dev/null
@@ -1,15 +0,0 @@
-from fastapi import FastAPI, Form
-from pydantic import BaseModel
-from typing_extensions import Annotated
-
-app = FastAPI()
-
-
-class FormData(BaseModel):
- username: str
- password: str
-
-
-@app.post("/login/")
-async def login(data: Annotated[FormData, Form()]):
- return data
diff --git a/docs_src/request_form_models/tutorial001.py b/docs_src/request_form_models/tutorial001_py39.py
similarity index 100%
rename from docs_src/request_form_models/tutorial001.py
rename to docs_src/request_form_models/tutorial001_py39.py
diff --git a/docs_src/request_form_models/tutorial002_an.py b/docs_src/request_form_models/tutorial002_an.py
deleted file mode 100644
index bcb0227959..0000000000
--- a/docs_src/request_form_models/tutorial002_an.py
+++ /dev/null
@@ -1,16 +0,0 @@
-from fastapi import FastAPI, Form
-from pydantic import BaseModel
-from typing_extensions import Annotated
-
-app = FastAPI()
-
-
-class FormData(BaseModel):
- username: str
- password: str
- model_config = {"extra": "forbid"}
-
-
-@app.post("/login/")
-async def login(data: Annotated[FormData, Form()]):
- return data
diff --git a/docs_src/request_form_models/tutorial002_pv1.py b/docs_src/request_form_models/tutorial002_pv1.py
deleted file mode 100644
index d5f7db2a67..0000000000
--- a/docs_src/request_form_models/tutorial002_pv1.py
+++ /dev/null
@@ -1,17 +0,0 @@
-from fastapi import FastAPI, Form
-from pydantic import BaseModel
-
-app = FastAPI()
-
-
-class FormData(BaseModel):
- username: str
- password: str
-
- class Config:
- extra = "forbid"
-
-
-@app.post("/login/")
-async def login(data: FormData = Form()):
- return data
diff --git a/docs_src/request_form_models/tutorial002_pv1_an.py b/docs_src/request_form_models/tutorial002_pv1_an.py
deleted file mode 100644
index fe9dbc344b..0000000000
--- a/docs_src/request_form_models/tutorial002_pv1_an.py
+++ /dev/null
@@ -1,18 +0,0 @@
-from fastapi import FastAPI, Form
-from pydantic import BaseModel
-from typing_extensions import Annotated
-
-app = FastAPI()
-
-
-class FormData(BaseModel):
- username: str
- password: str
-
- class Config:
- extra = "forbid"
-
-
-@app.post("/login/")
-async def login(data: Annotated[FormData, Form()]):
- return data
diff --git a/docs_src/request_form_models/tutorial002_pv1_an_py39.py b/docs_src/request_form_models/tutorial002_pv1_an_py39.py
deleted file mode 100644
index 942d5d4118..0000000000
--- a/docs_src/request_form_models/tutorial002_pv1_an_py39.py
+++ /dev/null
@@ -1,19 +0,0 @@
-from typing import Annotated
-
-from fastapi import FastAPI, Form
-from pydantic import BaseModel
-
-app = FastAPI()
-
-
-class FormData(BaseModel):
- username: str
- password: str
-
- class Config:
- extra = "forbid"
-
-
-@app.post("/login/")
-async def login(data: Annotated[FormData, Form()]):
- return data
diff --git a/docs_src/request_form_models/tutorial002.py b/docs_src/request_form_models/tutorial002_py39.py
similarity index 100%
rename from docs_src/request_form_models/tutorial002.py
rename to docs_src/request_form_models/tutorial002_py39.py
diff --git a/docs_src/request_forms/__init__.py b/docs_src/request_forms/__init__.py
new file mode 100644
index 0000000000..e69de29bb2
diff --git a/docs_src/request_forms/tutorial001_an.py b/docs_src/request_forms/tutorial001_an.py
deleted file mode 100644
index 677fbf2db8..0000000000
--- a/docs_src/request_forms/tutorial001_an.py
+++ /dev/null
@@ -1,9 +0,0 @@
-from fastapi import FastAPI, Form
-from typing_extensions import Annotated
-
-app = FastAPI()
-
-
-@app.post("/login/")
-async def login(username: Annotated[str, Form()], password: Annotated[str, Form()]):
- return {"username": username}
diff --git a/docs_src/request_forms/tutorial001.py b/docs_src/request_forms/tutorial001_py39.py
similarity index 100%
rename from docs_src/request_forms/tutorial001.py
rename to docs_src/request_forms/tutorial001_py39.py
diff --git a/docs_src/request_forms_and_files/__init__.py b/docs_src/request_forms_and_files/__init__.py
new file mode 100644
index 0000000000..e69de29bb2
diff --git a/docs_src/request_forms_and_files/tutorial001_an.py b/docs_src/request_forms_and_files/tutorial001_an.py
deleted file mode 100644
index 0ea285ac87..0000000000
--- a/docs_src/request_forms_and_files/tutorial001_an.py
+++ /dev/null
@@ -1,17 +0,0 @@
-from fastapi import FastAPI, File, Form, UploadFile
-from typing_extensions import Annotated
-
-app = FastAPI()
-
-
-@app.post("/files/")
-async def create_file(
- file: Annotated[bytes, File()],
- fileb: Annotated[UploadFile, File()],
- token: Annotated[str, Form()],
-):
- return {
- "file_size": len(file),
- "token": token,
- "fileb_content_type": fileb.content_type,
- }
diff --git a/docs_src/request_forms_and_files/tutorial001.py b/docs_src/request_forms_and_files/tutorial001_py39.py
similarity index 100%
rename from docs_src/request_forms_and_files/tutorial001.py
rename to docs_src/request_forms_and_files/tutorial001_py39.py
diff --git a/docs_src/response_change_status_code/__init__.py b/docs_src/response_change_status_code/__init__.py
new file mode 100644
index 0000000000..e69de29bb2
diff --git a/docs_src/response_change_status_code/tutorial001.py b/docs_src/response_change_status_code/tutorial001_py39.py
similarity index 100%
rename from docs_src/response_change_status_code/tutorial001.py
rename to docs_src/response_change_status_code/tutorial001_py39.py
diff --git a/docs_src/response_cookies/__init__.py b/docs_src/response_cookies/__init__.py
new file mode 100644
index 0000000000..e69de29bb2
diff --git a/docs_src/response_cookies/tutorial001.py b/docs_src/response_cookies/tutorial001_py39.py
similarity index 100%
rename from docs_src/response_cookies/tutorial001.py
rename to docs_src/response_cookies/tutorial001_py39.py
diff --git a/docs_src/response_cookies/tutorial002.py b/docs_src/response_cookies/tutorial002_py39.py
similarity index 100%
rename from docs_src/response_cookies/tutorial002.py
rename to docs_src/response_cookies/tutorial002_py39.py
diff --git a/docs_src/response_directly/__init__.py b/docs_src/response_directly/__init__.py
new file mode 100644
index 0000000000..e69de29bb2
diff --git a/docs_src/response_directly/tutorial001.py b/docs_src/response_directly/tutorial001_py39.py
similarity index 100%
rename from docs_src/response_directly/tutorial001.py
rename to docs_src/response_directly/tutorial001_py39.py
diff --git a/docs_src/response_directly/tutorial002.py b/docs_src/response_directly/tutorial002_py39.py
similarity index 100%
rename from docs_src/response_directly/tutorial002.py
rename to docs_src/response_directly/tutorial002_py39.py
diff --git a/docs_src/response_headers/__init__.py b/docs_src/response_headers/__init__.py
new file mode 100644
index 0000000000..e69de29bb2
diff --git a/docs_src/response_headers/tutorial001.py b/docs_src/response_headers/tutorial001_py39.py
similarity index 100%
rename from docs_src/response_headers/tutorial001.py
rename to docs_src/response_headers/tutorial001_py39.py
diff --git a/docs_src/response_headers/tutorial002.py b/docs_src/response_headers/tutorial002_py39.py
similarity index 100%
rename from docs_src/response_headers/tutorial002.py
rename to docs_src/response_headers/tutorial002_py39.py
diff --git a/docs_src/response_model/__init__.py b/docs_src/response_model/__init__.py
new file mode 100644
index 0000000000..e69de29bb2
diff --git a/docs_src/response_model/tutorial001.py b/docs_src/response_model/tutorial001.py
deleted file mode 100644
index fd1c902a52..0000000000
--- a/docs_src/response_model/tutorial001.py
+++ /dev/null
@@ -1,27 +0,0 @@
-from typing import Any, List, Union
-
-from fastapi import FastAPI
-from pydantic import BaseModel
-
-app = FastAPI()
-
-
-class Item(BaseModel):
- name: str
- description: Union[str, None] = None
- price: float
- tax: Union[float, None] = None
- tags: List[str] = []
-
-
-@app.post("/items/", response_model=Item)
-async def create_item(item: Item) -> Any:
- return item
-
-
-@app.get("/items/", response_model=List[Item])
-async def read_items() -> Any:
- return [
- {"name": "Portal Gun", "price": 42.0},
- {"name": "Plumbus", "price": 32.0},
- ]
diff --git a/docs_src/response_model/tutorial001_01.py b/docs_src/response_model/tutorial001_01.py
deleted file mode 100644
index 98d30d540f..0000000000
--- a/docs_src/response_model/tutorial001_01.py
+++ /dev/null
@@ -1,27 +0,0 @@
-from typing import List, Union
-
-from fastapi import FastAPI
-from pydantic import BaseModel
-
-app = FastAPI()
-
-
-class Item(BaseModel):
- name: str
- description: Union[str, None] = None
- price: float
- tax: Union[float, None] = None
- tags: List[str] = []
-
-
-@app.post("/items/")
-async def create_item(item: Item) -> Item:
- return item
-
-
-@app.get("/items/")
-async def read_items() -> List[Item]:
- return [
- Item(name="Portal Gun", price=42.0),
- Item(name="Plumbus", price=32.0),
- ]
diff --git a/docs_src/response_model/tutorial002.py b/docs_src/response_model/tutorial002_py39.py
similarity index 100%
rename from docs_src/response_model/tutorial002.py
rename to docs_src/response_model/tutorial002_py39.py
diff --git a/docs_src/response_model/tutorial003_01.py b/docs_src/response_model/tutorial003_01_py39.py
similarity index 100%
rename from docs_src/response_model/tutorial003_01.py
rename to docs_src/response_model/tutorial003_01_py39.py
diff --git a/docs_src/response_model/tutorial003_02.py b/docs_src/response_model/tutorial003_02_py39.py
similarity index 100%
rename from docs_src/response_model/tutorial003_02.py
rename to docs_src/response_model/tutorial003_02_py39.py
diff --git a/docs_src/response_model/tutorial003_03.py b/docs_src/response_model/tutorial003_03_py39.py
similarity index 100%
rename from docs_src/response_model/tutorial003_03.py
rename to docs_src/response_model/tutorial003_03_py39.py
diff --git a/docs_src/response_model/tutorial003_04.py b/docs_src/response_model/tutorial003_04_py39.py
similarity index 100%
rename from docs_src/response_model/tutorial003_04.py
rename to docs_src/response_model/tutorial003_04_py39.py
diff --git a/docs_src/response_model/tutorial003_05.py b/docs_src/response_model/tutorial003_05_py39.py
similarity index 100%
rename from docs_src/response_model/tutorial003_05.py
rename to docs_src/response_model/tutorial003_05_py39.py
diff --git a/docs_src/response_model/tutorial003.py b/docs_src/response_model/tutorial003_py39.py
similarity index 100%
rename from docs_src/response_model/tutorial003.py
rename to docs_src/response_model/tutorial003_py39.py
diff --git a/docs_src/response_model/tutorial004.py b/docs_src/response_model/tutorial004.py
deleted file mode 100644
index 10b48039ae..0000000000
--- a/docs_src/response_model/tutorial004.py
+++ /dev/null
@@ -1,26 +0,0 @@
-from typing import List, Union
-
-from fastapi import FastAPI
-from pydantic import BaseModel
-
-app = FastAPI()
-
-
-class Item(BaseModel):
- name: str
- description: Union[str, None] = None
- price: float
- tax: float = 10.5
- tags: List[str] = []
-
-
-items = {
- "foo": {"name": "Foo", "price": 50.2},
- "bar": {"name": "Bar", "description": "The bartenders", "price": 62, "tax": 20.2},
- "baz": {"name": "Baz", "description": None, "price": 50.2, "tax": 10.5, "tags": []},
-}
-
-
-@app.get("/items/{item_id}", response_model=Item, response_model_exclude_unset=True)
-async def read_item(item_id: str):
- return items[item_id]
diff --git a/docs_src/response_model/tutorial005.py b/docs_src/response_model/tutorial005_py39.py
similarity index 100%
rename from docs_src/response_model/tutorial005.py
rename to docs_src/response_model/tutorial005_py39.py
diff --git a/docs_src/response_model/tutorial006.py b/docs_src/response_model/tutorial006_py39.py
similarity index 100%
rename from docs_src/response_model/tutorial006.py
rename to docs_src/response_model/tutorial006_py39.py
diff --git a/docs_src/response_status_code/__init__.py b/docs_src/response_status_code/__init__.py
new file mode 100644
index 0000000000..e69de29bb2
diff --git a/docs_src/response_status_code/tutorial001.py b/docs_src/response_status_code/tutorial001_py39.py
similarity index 100%
rename from docs_src/response_status_code/tutorial001.py
rename to docs_src/response_status_code/tutorial001_py39.py
diff --git a/docs_src/response_status_code/tutorial002.py b/docs_src/response_status_code/tutorial002_py39.py
similarity index 100%
rename from docs_src/response_status_code/tutorial002.py
rename to docs_src/response_status_code/tutorial002_py39.py
diff --git a/docs_src/schema_extra_example/__init__.py b/docs_src/schema_extra_example/__init__.py
new file mode 100644
index 0000000000..e69de29bb2
diff --git a/docs_src/schema_extra_example/tutorial001_pv1_py310.py b/docs_src/schema_extra_example/tutorial001_pv1_py310.py
index ec83f1112f..b13b8a8c2c 100644
--- a/docs_src/schema_extra_example/tutorial001_pv1_py310.py
+++ b/docs_src/schema_extra_example/tutorial001_pv1_py310.py
@@ -1,5 +1,5 @@
from fastapi import FastAPI
-from pydantic import BaseModel
+from pydantic.v1 import BaseModel
app = FastAPI()
diff --git a/docs_src/schema_extra_example/tutorial001_pv1.py b/docs_src/schema_extra_example/tutorial001_pv1_py39.py
similarity index 94%
rename from docs_src/schema_extra_example/tutorial001_pv1.py
rename to docs_src/schema_extra_example/tutorial001_pv1_py39.py
index 6ab96ff859..3240b35d6d 100644
--- a/docs_src/schema_extra_example/tutorial001_pv1.py
+++ b/docs_src/schema_extra_example/tutorial001_pv1_py39.py
@@ -1,7 +1,7 @@
from typing import Union
from fastapi import FastAPI
-from pydantic import BaseModel
+from pydantic.v1 import BaseModel
app = FastAPI()
diff --git a/docs_src/schema_extra_example/tutorial001.py b/docs_src/schema_extra_example/tutorial001_py39.py
similarity index 100%
rename from docs_src/schema_extra_example/tutorial001.py
rename to docs_src/schema_extra_example/tutorial001_py39.py
diff --git a/docs_src/schema_extra_example/tutorial002.py b/docs_src/schema_extra_example/tutorial002_py39.py
similarity index 100%
rename from docs_src/schema_extra_example/tutorial002.py
rename to docs_src/schema_extra_example/tutorial002_py39.py
diff --git a/docs_src/schema_extra_example/tutorial003_an.py b/docs_src/schema_extra_example/tutorial003_an.py
deleted file mode 100644
index 23675aba14..0000000000
--- a/docs_src/schema_extra_example/tutorial003_an.py
+++ /dev/null
@@ -1,35 +0,0 @@
-from typing import Union
-
-from fastapi import Body, FastAPI
-from pydantic import BaseModel
-from typing_extensions import Annotated
-
-app = FastAPI()
-
-
-class Item(BaseModel):
- name: str
- description: Union[str, None] = None
- price: float
- tax: Union[float, None] = None
-
-
-@app.put("/items/{item_id}")
-async def update_item(
- item_id: int,
- item: Annotated[
- Item,
- Body(
- examples=[
- {
- "name": "Foo",
- "description": "A very nice Item",
- "price": 35.4,
- "tax": 3.2,
- }
- ],
- ),
- ],
-):
- results = {"item_id": item_id, "item": item}
- return results
diff --git a/docs_src/schema_extra_example/tutorial003.py b/docs_src/schema_extra_example/tutorial003_py39.py
similarity index 100%
rename from docs_src/schema_extra_example/tutorial003.py
rename to docs_src/schema_extra_example/tutorial003_py39.py
diff --git a/docs_src/schema_extra_example/tutorial004_an.py b/docs_src/schema_extra_example/tutorial004_an.py
deleted file mode 100644
index e817302a22..0000000000
--- a/docs_src/schema_extra_example/tutorial004_an.py
+++ /dev/null
@@ -1,44 +0,0 @@
-from typing import Union
-
-from fastapi import Body, FastAPI
-from pydantic import BaseModel
-from typing_extensions import Annotated
-
-app = FastAPI()
-
-
-class Item(BaseModel):
- name: str
- description: Union[str, None] = None
- price: float
- tax: Union[float, None] = None
-
-
-@app.put("/items/{item_id}")
-async def update_item(
- *,
- item_id: int,
- item: Annotated[
- Item,
- Body(
- examples=[
- {
- "name": "Foo",
- "description": "A very nice Item",
- "price": 35.4,
- "tax": 3.2,
- },
- {
- "name": "Bar",
- "price": "35.4",
- },
- {
- "name": "Baz",
- "price": "thirty five point four",
- },
- ],
- ),
- ],
-):
- results = {"item_id": item_id, "item": item}
- return results
diff --git a/docs_src/schema_extra_example/tutorial004.py b/docs_src/schema_extra_example/tutorial004_py39.py
similarity index 100%
rename from docs_src/schema_extra_example/tutorial004.py
rename to docs_src/schema_extra_example/tutorial004_py39.py
diff --git a/docs_src/schema_extra_example/tutorial005_an.py b/docs_src/schema_extra_example/tutorial005_an.py
deleted file mode 100644
index 4b2d9c662b..0000000000
--- a/docs_src/schema_extra_example/tutorial005_an.py
+++ /dev/null
@@ -1,55 +0,0 @@
-from typing import Union
-
-from fastapi import Body, FastAPI
-from pydantic import BaseModel
-from typing_extensions import Annotated
-
-app = FastAPI()
-
-
-class Item(BaseModel):
- name: str
- description: Union[str, None] = None
- price: float
- tax: Union[float, None] = None
-
-
-@app.put("/items/{item_id}")
-async def update_item(
- *,
- item_id: int,
- item: Annotated[
- Item,
- Body(
- openapi_examples={
- "normal": {
- "summary": "A normal example",
- "description": "A **normal** item works correctly.",
- "value": {
- "name": "Foo",
- "description": "A very nice Item",
- "price": 35.4,
- "tax": 3.2,
- },
- },
- "converted": {
- "summary": "An example with converted data",
- "description": "FastAPI can convert price `strings` to actual `numbers` automatically",
- "value": {
- "name": "Bar",
- "price": "35.4",
- },
- },
- "invalid": {
- "summary": "Invalid data is rejected with an error",
- "value": {
- "name": "Baz",
- "price": "thirty five point four",
- },
- },
- },
- ),
- ],
-):
- results = {"item_id": item_id, "item": item}
- return results
diff --git a/docs_src/schema_extra_example/tutorial005.py b/docs_src/schema_extra_example/tutorial005_py39.py
similarity index 100%
rename from docs_src/schema_extra_example/tutorial005.py
rename to docs_src/schema_extra_example/tutorial005_py39.py
diff --git a/docs_src/security/__init__.py b/docs_src/security/__init__.py
new file mode 100644
index 0000000000..e69de29bb2
diff --git a/docs_src/security/tutorial001_an.py b/docs_src/security/tutorial001_an.py
deleted file mode 100644
index dac915b7ca..0000000000
--- a/docs_src/security/tutorial001_an.py
+++ /dev/null
@@ -1,12 +0,0 @@
-from fastapi import Depends, FastAPI
-from fastapi.security import OAuth2PasswordBearer
-from typing_extensions import Annotated
-
-app = FastAPI()
-
-oauth2_scheme = OAuth2PasswordBearer(tokenUrl="token")
-
-
-@app.get("/items/")
-async def read_items(token: Annotated[str, Depends(oauth2_scheme)]):
- return {"token": token}
diff --git a/docs_src/security/tutorial001.py b/docs_src/security/tutorial001_py39.py
similarity index 100%
rename from docs_src/security/tutorial001.py
rename to docs_src/security/tutorial001_py39.py
diff --git a/docs_src/security/tutorial002_an.py b/docs_src/security/tutorial002_an.py
deleted file mode 100644
index 291b3bf530..0000000000
--- a/docs_src/security/tutorial002_an.py
+++ /dev/null
@@ -1,33 +0,0 @@
-from typing import Union
-
-from fastapi import Depends, FastAPI
-from fastapi.security import OAuth2PasswordBearer
-from pydantic import BaseModel
-from typing_extensions import Annotated
-
-app = FastAPI()
-
-oauth2_scheme = OAuth2PasswordBearer(tokenUrl="token")
-
-
-class User(BaseModel):
- username: str
- email: Union[str, None] = None
- full_name: Union[str, None] = None
- disabled: Union[bool, None] = None
-
-
-def fake_decode_token(token):
- return User(
- username=token + "fakedecoded", email="john@example.com", full_name="John Doe"
- )
-
-
-async def get_current_user(token: Annotated[str, Depends(oauth2_scheme)]):
- user = fake_decode_token(token)
- return user
-
-
-@app.get("/users/me")
-async def read_users_me(current_user: Annotated[User, Depends(get_current_user)]):
- return current_user
diff --git a/docs_src/security/tutorial002.py b/docs_src/security/tutorial002_py39.py
similarity index 100%
rename from docs_src/security/tutorial002.py
rename to docs_src/security/tutorial002_py39.py
diff --git a/docs_src/security/tutorial003_an.py b/docs_src/security/tutorial003_an.py
deleted file mode 100644
index 1b7056a209..0000000000
--- a/docs_src/security/tutorial003_an.py
+++ /dev/null
@@ -1,95 +0,0 @@
-from typing import Union
-
-from fastapi import Depends, FastAPI, HTTPException, status
-from fastapi.security import OAuth2PasswordBearer, OAuth2PasswordRequestForm
-from pydantic import BaseModel
-from typing_extensions import Annotated
-
-fake_users_db = {
- "johndoe": {
- "username": "johndoe",
- "full_name": "John Doe",
- "email": "johndoe@example.com",
- "hashed_password": "fakehashedsecret",
- "disabled": False,
- },
- "alice": {
- "username": "alice",
- "full_name": "Alice Wonderson",
- "email": "alice@example.com",
- "hashed_password": "fakehashedsecret2",
- "disabled": True,
- },
-}
-
-app = FastAPI()
-
-
-def fake_hash_password(password: str):
- return "fakehashed" + password
-
-
-oauth2_scheme = OAuth2PasswordBearer(tokenUrl="token")
-
-
-class User(BaseModel):
- username: str
- email: Union[str, None] = None
- full_name: Union[str, None] = None
- disabled: Union[bool, None] = None
-
-
-class UserInDB(User):
- hashed_password: str
-
-
-def get_user(db, username: str):
- if username in db:
- user_dict = db[username]
- return UserInDB(**user_dict)
-
-
-def fake_decode_token(token):
- # This doesn't provide any security at all
- # Check the next version
- user = get_user(fake_users_db, token)
- return user
-
-
-async def get_current_user(token: Annotated[str, Depends(oauth2_scheme)]):
- user = fake_decode_token(token)
- if not user:
- raise HTTPException(
- status_code=status.HTTP_401_UNAUTHORIZED,
- detail="Not authenticated",
- headers={"WWW-Authenticate": "Bearer"},
- )
- return user
-
-
-async def get_current_active_user(
- current_user: Annotated[User, Depends(get_current_user)],
-):
- if current_user.disabled:
- raise HTTPException(status_code=400, detail="Inactive user")
- return current_user
-
-
-@app.post("/token")
-async def login(form_data: Annotated[OAuth2PasswordRequestForm, Depends()]):
- user_dict = fake_users_db.get(form_data.username)
- if not user_dict:
- raise HTTPException(status_code=400, detail="Incorrect username or password")
- user = UserInDB(**user_dict)
- hashed_password = fake_hash_password(form_data.password)
- if not hashed_password == user.hashed_password:
- raise HTTPException(status_code=400, detail="Incorrect username or password")
-
- return {"access_token": user.username, "token_type": "bearer"}
-
-
-@app.get("/users/me")
-async def read_users_me(
- current_user: Annotated[User, Depends(get_current_active_user)],
-):
- return current_user
diff --git a/docs_src/security/tutorial003.py b/docs_src/security/tutorial003_py39.py
similarity index 100%
rename from docs_src/security/tutorial003.py
rename to docs_src/security/tutorial003_py39.py
diff --git a/docs_src/security/tutorial004_an.py b/docs_src/security/tutorial004_an.py
deleted file mode 100644
index 018234e300..0000000000
--- a/docs_src/security/tutorial004_an.py
+++ /dev/null
@@ -1,148 +0,0 @@
-from datetime import datetime, timedelta, timezone
-from typing import Union
-
-import jwt
-from fastapi import Depends, FastAPI, HTTPException, status
-from fastapi.security import OAuth2PasswordBearer, OAuth2PasswordRequestForm
-from jwt.exceptions import InvalidTokenError
-from pwdlib import PasswordHash
-from pydantic import BaseModel
-from typing_extensions import Annotated
-
-# to get a string like this run:
-# openssl rand -hex 32
-SECRET_KEY = "09d25e094faa6ca2556c818166b7a9563b93f7099f6f0f4caa6cf63b88e8d3e7"
-ALGORITHM = "HS256"
-ACCESS_TOKEN_EXPIRE_MINUTES = 30
-
-
-fake_users_db = {
- "johndoe": {
- "username": "johndoe",
- "full_name": "John Doe",
- "email": "johndoe@example.com",
- "hashed_password": "$argon2id$v=19$m=65536,t=3,p=4$wagCPXjifgvUFBzq4hqe3w$CYaIb8sB+wtD+Vu/P4uod1+Qof8h+1g7bbDlBID48Rc",
- "disabled": False,
- }
-}
-
-
-class Token(BaseModel):
- access_token: str
- token_type: str
-
-
-class TokenData(BaseModel):
- username: Union[str, None] = None
-
-
-class User(BaseModel):
- username: str
- email: Union[str, None] = None
- full_name: Union[str, None] = None
- disabled: Union[bool, None] = None
-
-
-class UserInDB(User):
- hashed_password: str
-
-
-password_hash = PasswordHash.recommended()
-
-oauth2_scheme = OAuth2PasswordBearer(tokenUrl="token")
-
-app = FastAPI()
-
-
-def verify_password(plain_password, hashed_password):
- return password_hash.verify(plain_password, hashed_password)
-
-
-def get_password_hash(password):
- return password_hash.hash(password)
-
-
-def get_user(db, username: str):
- if username in db:
- user_dict = db[username]
- return UserInDB(**user_dict)
-
-
-def authenticate_user(fake_db, username: str, password: str):
- user = get_user(fake_db, username)
- if not user:
- return False
- if not verify_password(password, user.hashed_password):
- return False
- return user
-
-
-def create_access_token(data: dict, expires_delta: Union[timedelta, None] = None):
- to_encode = data.copy()
- if expires_delta:
- expire = datetime.now(timezone.utc) + expires_delta
- else:
- expire = datetime.now(timezone.utc) + timedelta(minutes=15)
- to_encode.update({"exp": expire})
- encoded_jwt = jwt.encode(to_encode, SECRET_KEY, algorithm=ALGORITHM)
- return encoded_jwt
-
-
-async def get_current_user(token: Annotated[str, Depends(oauth2_scheme)]):
- credentials_exception = HTTPException(
- status_code=status.HTTP_401_UNAUTHORIZED,
- detail="Could not validate credentials",
- headers={"WWW-Authenticate": "Bearer"},
- )
- try:
- payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM])
- username = payload.get("sub")
- if username is None:
- raise credentials_exception
- token_data = TokenData(username=username)
- except InvalidTokenError:
- raise credentials_exception
- user = get_user(fake_users_db, username=token_data.username)
- if user is None:
- raise credentials_exception
- return user
-
-
-async def get_current_active_user(
- current_user: Annotated[User, Depends(get_current_user)],
-):
- if current_user.disabled:
- raise HTTPException(status_code=400, detail="Inactive user")
- return current_user
-
-
-@app.post("/token")
-async def login_for_access_token(
- form_data: Annotated[OAuth2PasswordRequestForm, Depends()],
-) -> Token:
- user = authenticate_user(fake_users_db, form_data.username, form_data.password)
- if not user:
- raise HTTPException(
- status_code=status.HTTP_401_UNAUTHORIZED,
- detail="Incorrect username or password",
- headers={"WWW-Authenticate": "Bearer"},
- )
- access_token_expires = timedelta(minutes=ACCESS_TOKEN_EXPIRE_MINUTES)
- access_token = create_access_token(
- data={"sub": user.username}, expires_delta=access_token_expires
- )
- return Token(access_token=access_token, token_type="bearer")
-
-
-@app.get("/users/me/", response_model=User)
-async def read_users_me(
- current_user: Annotated[User, Depends(get_current_active_user)],
-):
- return current_user
-
-
-@app.get("/users/me/items/")
-async def read_own_items(
- current_user: Annotated[User, Depends(get_current_active_user)],
-):
- return [{"item_id": "Foo", "owner": current_user.username}]
diff --git a/docs_src/security/tutorial004.py b/docs_src/security/tutorial004_py39.py
similarity index 100%
rename from docs_src/security/tutorial004.py
rename to docs_src/security/tutorial004_py39.py
diff --git a/docs_src/security/tutorial005.py b/docs_src/security/tutorial005.py
deleted file mode 100644
index fdd73bcd8a..0000000000
--- a/docs_src/security/tutorial005.py
+++ /dev/null
@@ -1,177 +0,0 @@
-from datetime import datetime, timedelta, timezone
-from typing import List, Union
-
-import jwt
-from fastapi import Depends, FastAPI, HTTPException, Security, status
-from fastapi.security import (
- OAuth2PasswordBearer,
- OAuth2PasswordRequestForm,
- SecurityScopes,
-)
-from jwt.exceptions import InvalidTokenError
-from pwdlib import PasswordHash
-from pydantic import BaseModel, ValidationError
-
-# to get a string like this run:
-# openssl rand -hex 32
-SECRET_KEY = "09d25e094faa6ca2556c818166b7a9563b93f7099f6f0f4caa6cf63b88e8d3e7"
-ALGORITHM = "HS256"
-ACCESS_TOKEN_EXPIRE_MINUTES = 30
-
-
-fake_users_db = {
- "johndoe": {
- "username": "johndoe",
- "full_name": "John Doe",
- "email": "johndoe@example.com",
- "hashed_password": "$argon2id$v=19$m=65536,t=3,p=4$wagCPXjifgvUFBzq4hqe3w$CYaIb8sB+wtD+Vu/P4uod1+Qof8h+1g7bbDlBID48Rc",
- "disabled": False,
- },
- "alice": {
- "username": "alice",
- "full_name": "Alice Chains",
- "email": "alicechains@example.com",
- "hashed_password": "$argon2id$v=19$m=65536,t=3,p=4$g2/AV1zwopqUntPKJavBFw$BwpRGDCyUHLvHICnwijyX8ROGoiUPwNKZ7915MeYfCE",
- "disabled": True,
- },
-}
-
-
-class Token(BaseModel):
- access_token: str
- token_type: str
-
-
-class TokenData(BaseModel):
- username: Union[str, None] = None
- scopes: List[str] = []
-
-
-class User(BaseModel):
- username: str
- email: Union[str, None] = None
- full_name: Union[str, None] = None
- disabled: Union[bool, None] = None
-
-
-class UserInDB(User):
- hashed_password: str
-
-
-password_hash = PasswordHash.recommended()
-
-oauth2_scheme = OAuth2PasswordBearer(
- tokenUrl="token",
- scopes={"me": "Read information about the current user.", "items": "Read items."},
-)
-
-app = FastAPI()
-
-
-def verify_password(plain_password, hashed_password):
- return password_hash.verify(plain_password, hashed_password)
-
-
-def get_password_hash(password):
- return password_hash.hash(password)
-
-
-def get_user(db, username: str):
- if username in db:
- user_dict = db[username]
- return UserInDB(**user_dict)
-
-
-def authenticate_user(fake_db, username: str, password: str):
- user = get_user(fake_db, username)
- if not user:
- return False
- if not verify_password(password, user.hashed_password):
- return False
- return user
-
-
-def create_access_token(data: dict, expires_delta: Union[timedelta, None] = None):
- to_encode = data.copy()
- if expires_delta:
- expire = datetime.now(timezone.utc) + expires_delta
- else:
- expire = datetime.now(timezone.utc) + timedelta(minutes=15)
- to_encode.update({"exp": expire})
- encoded_jwt = jwt.encode(to_encode, SECRET_KEY, algorithm=ALGORITHM)
- return encoded_jwt
-
-
-async def get_current_user(
- security_scopes: SecurityScopes, token: str = Depends(oauth2_scheme)
-):
- if security_scopes.scopes:
- authenticate_value = f'Bearer scope="{security_scopes.scope_str}"'
- else:
- authenticate_value = "Bearer"
- credentials_exception = HTTPException(
- status_code=status.HTTP_401_UNAUTHORIZED,
- detail="Could not validate credentials",
- headers={"WWW-Authenticate": authenticate_value},
- )
- try:
- payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM])
- username: str = payload.get("sub")
- if username is None:
- raise credentials_exception
- scope: str = payload.get("scope", "")
- token_scopes = scope.split(" ")
- token_data = TokenData(scopes=token_scopes, username=username)
- except (InvalidTokenError, ValidationError):
- raise credentials_exception
- user = get_user(fake_users_db, username=token_data.username)
- if user is None:
- raise credentials_exception
- for scope in security_scopes.scopes:
- if scope not in token_data.scopes:
- raise HTTPException(
- status_code=status.HTTP_401_UNAUTHORIZED,
- detail="Not enough permissions",
- headers={"WWW-Authenticate": authenticate_value},
- )
- return user
-
-
-async def get_current_active_user(
- current_user: User = Security(get_current_user, scopes=["me"]),
-):
- if current_user.disabled:
- raise HTTPException(status_code=400, detail="Inactive user")
- return current_user
-
-
-@app.post("/token")
-async def login_for_access_token(
- form_data: OAuth2PasswordRequestForm = Depends(),
-) -> Token:
- user = authenticate_user(fake_users_db, form_data.username, form_data.password)
- if not user:
- raise HTTPException(status_code=400, detail="Incorrect username or password")
- access_token_expires = timedelta(minutes=ACCESS_TOKEN_EXPIRE_MINUTES)
- access_token = create_access_token(
- data={"sub": user.username, "scope": " ".join(form_data.scopes)},
- expires_delta=access_token_expires,
- )
- return Token(access_token=access_token, token_type="bearer")
-
-
-@app.get("/users/me/", response_model=User)
-async def read_users_me(current_user: User = Depends(get_current_active_user)):
- return current_user
-
-
-@app.get("/users/me/items/")
-async def read_own_items(
- current_user: User = Security(get_current_active_user, scopes=["items"]),
-):
- return [{"item_id": "Foo", "owner": current_user.username}]
-
-
-@app.get("/status/")
-async def read_system_status(current_user: User = Depends(get_current_user)):
- return {"status": "ok"}
diff --git a/docs_src/security/tutorial005_an.py b/docs_src/security/tutorial005_an.py
deleted file mode 100644
index e1d7b4f62a..0000000000
--- a/docs_src/security/tutorial005_an.py
+++ /dev/null
@@ -1,180 +0,0 @@
-from datetime import datetime, timedelta, timezone
-from typing import List, Union
-
-import jwt
-from fastapi import Depends, FastAPI, HTTPException, Security, status
-from fastapi.security import (
- OAuth2PasswordBearer,
- OAuth2PasswordRequestForm,
- SecurityScopes,
-)
-from jwt.exceptions import InvalidTokenError
-from pwdlib import PasswordHash
-from pydantic import BaseModel, ValidationError
-from typing_extensions import Annotated
-
-# to get a string like this run:
-# openssl rand -hex 32
-SECRET_KEY = "09d25e094faa6ca2556c818166b7a9563b93f7099f6f0f4caa6cf63b88e8d3e7"
-ALGORITHM = "HS256"
-ACCESS_TOKEN_EXPIRE_MINUTES = 30
-
-
-fake_users_db = {
- "johndoe": {
- "username": "johndoe",
- "full_name": "John Doe",
- "email": "johndoe@example.com",
- "hashed_password": "$argon2id$v=19$m=65536,t=3,p=4$wagCPXjifgvUFBzq4hqe3w$CYaIb8sB+wtD+Vu/P4uod1+Qof8h+1g7bbDlBID48Rc",
- "disabled": False,
- },
- "alice": {
- "username": "alice",
- "full_name": "Alice Chains",
- "email": "alicechains@example.com",
- "hashed_password": "$argon2id$v=19$m=65536,t=3,p=4$g2/AV1zwopqUntPKJavBFw$BwpRGDCyUHLvHICnwijyX8ROGoiUPwNKZ7915MeYfCE",
- "disabled": True,
- },
-}
-
-
-class Token(BaseModel):
- access_token: str
- token_type: str
-
-
-class TokenData(BaseModel):
- username: Union[str, None] = None
- scopes: List[str] = []
-
-
-class User(BaseModel):
- username: str
- email: Union[str, None] = None
- full_name: Union[str, None] = None
- disabled: Union[bool, None] = None
-
-
-class UserInDB(User):
- hashed_password: str
-
-
-password_hash = PasswordHash.recommended()
-
-oauth2_scheme = OAuth2PasswordBearer(
- tokenUrl="token",
- scopes={"me": "Read information about the current user.", "items": "Read items."},
-)
-
-app = FastAPI()
-
-
-def verify_password(plain_password, hashed_password):
- return password_hash.verify(plain_password, hashed_password)
-
-
-def get_password_hash(password):
- return password_hash.hash(password)
-
-
-def get_user(db, username: str):
- if username in db:
- user_dict = db[username]
- return UserInDB(**user_dict)
-
-
-def authenticate_user(fake_db, username: str, password: str):
- user = get_user(fake_db, username)
- if not user:
- return False
- if not verify_password(password, user.hashed_password):
- return False
- return user
-
-
-def create_access_token(data: dict, expires_delta: Union[timedelta, None] = None):
- to_encode = data.copy()
- if expires_delta:
- expire = datetime.now(timezone.utc) + expires_delta
- else:
- expire = datetime.now(timezone.utc) + timedelta(minutes=15)
- to_encode.update({"exp": expire})
- encoded_jwt = jwt.encode(to_encode, SECRET_KEY, algorithm=ALGORITHM)
- return encoded_jwt
-
-
-async def get_current_user(
- security_scopes: SecurityScopes, token: Annotated[str, Depends(oauth2_scheme)]
-):
- if security_scopes.scopes:
- authenticate_value = f'Bearer scope="{security_scopes.scope_str}"'
- else:
- authenticate_value = "Bearer"
- credentials_exception = HTTPException(
- status_code=status.HTTP_401_UNAUTHORIZED,
- detail="Could not validate credentials",
- headers={"WWW-Authenticate": authenticate_value},
- )
- try:
- payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM])
- username = payload.get("sub")
- if username is None:
- raise credentials_exception
- scope: str = payload.get("scope", "")
- token_scopes = scope.split(" ")
- token_data = TokenData(scopes=token_scopes, username=username)
- except (InvalidTokenError, ValidationError):
- raise credentials_exception
- user = get_user(fake_users_db, username=token_data.username)
- if user is None:
- raise credentials_exception
- for scope in security_scopes.scopes:
- if scope not in token_data.scopes:
- raise HTTPException(
- status_code=status.HTTP_401_UNAUTHORIZED,
- detail="Not enough permissions",
- headers={"WWW-Authenticate": authenticate_value},
- )
- return user
-
-
-async def get_current_active_user(
- current_user: Annotated[User, Security(get_current_user, scopes=["me"])],
-):
- if current_user.disabled:
- raise HTTPException(status_code=400, detail="Inactive user")
- return current_user
-
-
-@app.post("/token")
-async def login_for_access_token(
- form_data: Annotated[OAuth2PasswordRequestForm, Depends()],
-) -> Token:
- user = authenticate_user(fake_users_db, form_data.username, form_data.password)
- if not user:
- raise HTTPException(status_code=400, detail="Incorrect username or password")
- access_token_expires = timedelta(minutes=ACCESS_TOKEN_EXPIRE_MINUTES)
- access_token = create_access_token(
- data={"sub": user.username, "scope": " ".join(form_data.scopes)},
- expires_delta=access_token_expires,
- )
- return Token(access_token=access_token, token_type="bearer")
-
-
-@app.get("/users/me/", response_model=User)
-async def read_users_me(
- current_user: Annotated[User, Depends(get_current_active_user)],
-):
- return current_user
-
-
-@app.get("/users/me/items/")
-async def read_own_items(
- current_user: Annotated[User, Security(get_current_active_user, scopes=["items"])],
-):
- return [{"item_id": "Foo", "owner": current_user.username}]
-
-
-@app.get("/status/")
-async def read_system_status(current_user: Annotated[User, Depends(get_current_user)]):
- return {"status": "ok"}
diff --git a/docs_src/security/tutorial006_an.py b/docs_src/security/tutorial006_an.py
deleted file mode 100644
index 985e4b2ad2..0000000000
--- a/docs_src/security/tutorial006_an.py
+++ /dev/null
@@ -1,12 +0,0 @@
-from fastapi import Depends, FastAPI
-from fastapi.security import HTTPBasic, HTTPBasicCredentials
-from typing_extensions import Annotated
-
-app = FastAPI()
-
-security = HTTPBasic()
-
-
-@app.get("/users/me")
-def read_current_user(credentials: Annotated[HTTPBasicCredentials, Depends(security)]):
- return {"username": credentials.username, "password": credentials.password}
diff --git a/docs_src/security/tutorial006.py b/docs_src/security/tutorial006_py39.py
similarity index 100%
rename from docs_src/security/tutorial006.py
rename to docs_src/security/tutorial006_py39.py
diff --git a/docs_src/security/tutorial007_an.py b/docs_src/security/tutorial007_an.py
deleted file mode 100644
index 0d211dfde5..0000000000
--- a/docs_src/security/tutorial007_an.py
+++ /dev/null
@@ -1,36 +0,0 @@
-import secrets
-
-from fastapi import Depends, FastAPI, HTTPException, status
-from fastapi.security import HTTPBasic, HTTPBasicCredentials
-from typing_extensions import Annotated
-
-app = FastAPI()
-
-security = HTTPBasic()
-
-
-def get_current_username(
- credentials: Annotated[HTTPBasicCredentials, Depends(security)],
-):
- current_username_bytes = credentials.username.encode("utf8")
- correct_username_bytes = b"stanleyjobson"
- is_correct_username = secrets.compare_digest(
- current_username_bytes, correct_username_bytes
- )
- current_password_bytes = credentials.password.encode("utf8")
- correct_password_bytes = b"swordfish"
- is_correct_password = secrets.compare_digest(
- current_password_bytes, correct_password_bytes
- )
- if not (is_correct_username and is_correct_password):
- raise HTTPException(
- status_code=status.HTTP_401_UNAUTHORIZED,
- detail="Incorrect username or password",
- headers={"WWW-Authenticate": "Basic"},
- )
- return credentials.username
-
-
-@app.get("/users/me")
-def read_current_user(username: Annotated[str, Depends(get_current_username)]):
- return {"username": username}
diff --git a/docs_src/security/tutorial007.py b/docs_src/security/tutorial007_py39.py
similarity index 100%
rename from docs_src/security/tutorial007.py
rename to docs_src/security/tutorial007_py39.py
diff --git a/docs_src/separate_openapi_schemas/__init__.py b/docs_src/separate_openapi_schemas/__init__.py
new file mode 100644
index 0000000000..e69de29bb2
diff --git a/docs_src/separate_openapi_schemas/tutorial001.py b/docs_src/separate_openapi_schemas/tutorial001.py
deleted file mode 100644
index 415eef8e28..0000000000
--- a/docs_src/separate_openapi_schemas/tutorial001.py
+++ /dev/null
@@ -1,28 +0,0 @@
-from typing import List, Union
-
-from fastapi import FastAPI
-from pydantic import BaseModel
-
-
-class Item(BaseModel):
- name: str
- description: Union[str, None] = None
-
-
-app = FastAPI()
-
-
-@app.post("/items/")
-def create_item(item: Item):
- return item
-
-
-@app.get("/items/")
-def read_items() -> List[Item]:
- return [
- Item(
- name="Portal Gun",
- description="Device to travel through the multi-rick-verse",
- ),
- Item(name="Plumbus"),
- ]
diff --git a/docs_src/separate_openapi_schemas/tutorial002.py b/docs_src/separate_openapi_schemas/tutorial002.py
deleted file mode 100644
index 7df93783b9..0000000000
--- a/docs_src/separate_openapi_schemas/tutorial002.py
+++ /dev/null
@@ -1,28 +0,0 @@
-from typing import List, Union
-
-from fastapi import FastAPI
-from pydantic import BaseModel
-
-
-class Item(BaseModel):
- name: str
- description: Union[str, None] = None
-
-
-app = FastAPI(separate_input_output_schemas=False)
-
-
-@app.post("/items/")
-def create_item(item: Item):
- return item
-
-
-@app.get("/items/")
-def read_items() -> List[Item]:
- return [
- Item(
- name="Portal Gun",
- description="Device to travel through the multi-rick-verse",
- ),
- Item(name="Plumbus"),
- ]
diff --git a/docs_src/settings/__init__.py b/docs_src/settings/__init__.py
new file mode 100644
index 0000000000..e69de29bb2
diff --git a/docs_src/settings/app01_py39/__init__.py b/docs_src/settings/app01_py39/__init__.py
new file mode 100644
index 0000000000..e69de29bb2
diff --git a/docs_src/settings/app01/config.py b/docs_src/settings/app01_py39/config.py
similarity index 100%
rename from docs_src/settings/app01/config.py
rename to docs_src/settings/app01_py39/config.py
diff --git a/docs_src/settings/app01/main.py b/docs_src/settings/app01_py39/main.py
similarity index 100%
rename from docs_src/settings/app01/main.py
rename to docs_src/settings/app01_py39/main.py
diff --git a/docs_src/settings/app02_an/config.py b/docs_src/settings/app02_an/config.py
deleted file mode 100644
index e17b5035dc..0000000000
--- a/docs_src/settings/app02_an/config.py
+++ /dev/null
@@ -1,7 +0,0 @@
-from pydantic_settings import BaseSettings
-
-
-class Settings(BaseSettings):
- app_name: str = "Awesome API"
- admin_email: str
- items_per_user: int = 50
diff --git a/docs_src/settings/app02_an/main.py b/docs_src/settings/app02_an/main.py
deleted file mode 100644
index 3a578cc338..0000000000
--- a/docs_src/settings/app02_an/main.py
+++ /dev/null
@@ -1,22 +0,0 @@
-from functools import lru_cache
-
-from fastapi import Depends, FastAPI
-from typing_extensions import Annotated
-
-from .config import Settings
-
-app = FastAPI()
-
-
-@lru_cache
-def get_settings():
- return Settings()
-
-
-@app.get("/info")
-async def info(settings: Annotated[Settings, Depends(get_settings)]):
- return {
- "app_name": settings.app_name,
- "admin_email": settings.admin_email,
- "items_per_user": settings.items_per_user,
- }
diff --git a/docs_src/settings/app02_an/test_main.py b/docs_src/settings/app02_an/test_main.py
deleted file mode 100644
index 7a04d7e8ee..0000000000
--- a/docs_src/settings/app02_an/test_main.py
+++ /dev/null
@@ -1,23 +0,0 @@
-from fastapi.testclient import TestClient
-
-from .config import Settings
-from .main import app, get_settings
-
-client = TestClient(app)
-
-
-def get_settings_override():
- return Settings(admin_email="testing_admin@example.com")
-
-
-app.dependency_overrides[get_settings] = get_settings_override
-
-
-def test_app():
- response = client.get("/info")
- data = response.json()
- assert data == {
- "app_name": "Awesome API",
- "admin_email": "testing_admin@example.com",
- "items_per_user": 50,
- }
diff --git a/docs_src/settings/app02_py39/__init__.py b/docs_src/settings/app02_py39/__init__.py
new file mode 100644
index 0000000000..e69de29bb2
diff --git a/docs_src/settings/app02/config.py b/docs_src/settings/app02_py39/config.py
similarity index 100%
rename from docs_src/settings/app02/config.py
rename to docs_src/settings/app02_py39/config.py
diff --git a/docs_src/settings/app02/main.py b/docs_src/settings/app02_py39/main.py
similarity index 100%
rename from docs_src/settings/app02/main.py
rename to docs_src/settings/app02_py39/main.py
diff --git a/docs_src/settings/app02/test_main.py b/docs_src/settings/app02_py39/test_main.py
similarity index 100%
rename from docs_src/settings/app02/test_main.py
rename to docs_src/settings/app02_py39/test_main.py
diff --git a/docs_src/settings/app03_an/config.py b/docs_src/settings/app03_an/config.py
deleted file mode 100644
index 08f8f88c28..0000000000
--- a/docs_src/settings/app03_an/config.py
+++ /dev/null
@@ -1,9 +0,0 @@
-from pydantic_settings import BaseSettings, SettingsConfigDict
-
-
-class Settings(BaseSettings):
- app_name: str = "Awesome API"
- admin_email: str
- items_per_user: int = 50
-
- model_config = SettingsConfigDict(env_file=".env")
diff --git a/docs_src/settings/app03_an/config_pv1.py b/docs_src/settings/app03_an/config_pv1.py
deleted file mode 100644
index e1c3ee3006..0000000000
--- a/docs_src/settings/app03_an/config_pv1.py
+++ /dev/null
@@ -1,10 +0,0 @@
-from pydantic import BaseSettings
-
-
-class Settings(BaseSettings):
- app_name: str = "Awesome API"
- admin_email: str
- items_per_user: int = 50
-
- class Config:
- env_file = ".env"
diff --git a/docs_src/settings/app03_an/main.py b/docs_src/settings/app03_an/main.py
deleted file mode 100644
index 62f3476396..0000000000
--- a/docs_src/settings/app03_an/main.py
+++ /dev/null
@@ -1,22 +0,0 @@
-from functools import lru_cache
-
-from fastapi import Depends, FastAPI
-from typing_extensions import Annotated
-
-from . import config
-
-app = FastAPI()
-
-
-@lru_cache
-def get_settings():
- return config.Settings()
-
-
-@app.get("/info")
-async def info(settings: Annotated[config.Settings, Depends(get_settings)]):
- return {
- "app_name": settings.app_name,
- "admin_email": settings.admin_email,
- "items_per_user": settings.items_per_user,
- }
diff --git a/docs_src/settings/app03_an_py39/config_pv1.py b/docs_src/settings/app03_an_py39/config_pv1.py
index e1c3ee3006..7ae66ef77c 100644
--- a/docs_src/settings/app03_an_py39/config_pv1.py
+++ b/docs_src/settings/app03_an_py39/config_pv1.py
@@ -1,4 +1,4 @@
-from pydantic import BaseSettings
+from pydantic.v1 import BaseSettings
class Settings(BaseSettings):
diff --git a/docs_src/settings/app03_py39/__init__.py b/docs_src/settings/app03_py39/__init__.py
new file mode 100644
index 0000000000..e69de29bb2
diff --git a/docs_src/settings/app03/config.py b/docs_src/settings/app03_py39/config.py
similarity index 100%
rename from docs_src/settings/app03/config.py
rename to docs_src/settings/app03_py39/config.py
diff --git a/docs_src/settings/app03/config_pv1.py b/docs_src/settings/app03_py39/config_pv1.py
similarity index 81%
rename from docs_src/settings/app03/config_pv1.py
rename to docs_src/settings/app03_py39/config_pv1.py
index e1c3ee3006..7ae66ef77c 100644
--- a/docs_src/settings/app03/config_pv1.py
+++ b/docs_src/settings/app03_py39/config_pv1.py
@@ -1,4 +1,4 @@
-from pydantic import BaseSettings
+from pydantic.v1 import BaseSettings
class Settings(BaseSettings):
diff --git a/docs_src/settings/app03/main.py b/docs_src/settings/app03_py39/main.py
similarity index 100%
rename from docs_src/settings/app03/main.py
rename to docs_src/settings/app03_py39/main.py
diff --git a/docs_src/settings/tutorial001_pv1.py b/docs_src/settings/tutorial001_pv1_py39.py
similarity index 91%
rename from docs_src/settings/tutorial001_pv1.py
rename to docs_src/settings/tutorial001_pv1_py39.py
index 0cfd1b6632..20ad2bbf62 100644
--- a/docs_src/settings/tutorial001_pv1.py
+++ b/docs_src/settings/tutorial001_pv1_py39.py
@@ -1,5 +1,5 @@
from fastapi import FastAPI
-from pydantic import BaseSettings
+from pydantic.v1 import BaseSettings
class Settings(BaseSettings):
diff --git a/docs_src/settings/tutorial001.py b/docs_src/settings/tutorial001_py39.py
similarity index 100%
rename from docs_src/settings/tutorial001.py
rename to docs_src/settings/tutorial001_py39.py
diff --git a/docs_src/sql_databases/tutorial001.py b/docs_src/sql_databases/tutorial001.py
deleted file mode 100644
index be86ec0eeb..0000000000
--- a/docs_src/sql_databases/tutorial001.py
+++ /dev/null
@@ -1,71 +0,0 @@
-from typing import List, Union
-
-from fastapi import Depends, FastAPI, HTTPException, Query
-from sqlmodel import Field, Session, SQLModel, create_engine, select
-
-
-class Hero(SQLModel, table=True):
- id: Union[int, None] = Field(default=None, primary_key=True)
- name: str = Field(index=True)
- age: Union[int, None] = Field(default=None, index=True)
- secret_name: str
-
-
-sqlite_file_name = "database.db"
-sqlite_url = f"sqlite:///{sqlite_file_name}"
-
-connect_args = {"check_same_thread": False}
-engine = create_engine(sqlite_url, connect_args=connect_args)
-
-
-def create_db_and_tables():
- SQLModel.metadata.create_all(engine)
-
-
-def get_session():
- with Session(engine) as session:
- yield session
-
-
-app = FastAPI()
-
-
-@app.on_event("startup")
-def on_startup():
- create_db_and_tables()
-
-
-@app.post("/heroes/")
-def create_hero(hero: Hero, session: Session = Depends(get_session)) -> Hero:
- session.add(hero)
- session.commit()
- session.refresh(hero)
- return hero
-
-
-@app.get("/heroes/")
-def read_heroes(
- session: Session = Depends(get_session),
- offset: int = 0,
- limit: int = Query(default=100, le=100),
-) -> List[Hero]:
- heroes = session.exec(select(Hero).offset(offset).limit(limit)).all()
- return heroes
-
-
-@app.get("/heroes/{hero_id}")
-def read_hero(hero_id: int, session: Session = Depends(get_session)) -> Hero:
- hero = session.get(Hero, hero_id)
- if not hero:
- raise HTTPException(status_code=404, detail="Hero not found")
- return hero
-
-
-@app.delete("/heroes/{hero_id}")
-def delete_hero(hero_id: int, session: Session = Depends(get_session)):
- hero = session.get(Hero, hero_id)
- if not hero:
- raise HTTPException(status_code=404, detail="Hero not found")
- session.delete(hero)
- session.commit()
- return {"ok": True}
diff --git a/docs_src/sql_databases/tutorial001_an.py b/docs_src/sql_databases/tutorial001_an.py
deleted file mode 100644
index 8c000d31c7..0000000000
--- a/docs_src/sql_databases/tutorial001_an.py
+++ /dev/null
@@ -1,74 +0,0 @@
-from typing import List, Union
-
-from fastapi import Depends, FastAPI, HTTPException, Query
-from sqlmodel import Field, Session, SQLModel, create_engine, select
-from typing_extensions import Annotated
-
-
-class Hero(SQLModel, table=True):
- id: Union[int, None] = Field(default=None, primary_key=True)
- name: str = Field(index=True)
- age: Union[int, None] = Field(default=None, index=True)
- secret_name: str
-
-
-sqlite_file_name = "database.db"
-sqlite_url = f"sqlite:///{sqlite_file_name}"
-
-connect_args = {"check_same_thread": False}
-engine = create_engine(sqlite_url, connect_args=connect_args)
-
-
-def create_db_and_tables():
- SQLModel.metadata.create_all(engine)
-
-
-def get_session():
- with Session(engine) as session:
- yield session
-
-
-SessionDep = Annotated[Session, Depends(get_session)]
-
-app = FastAPI()
-
-
-@app.on_event("startup")
-def on_startup():
- create_db_and_tables()
-
-
-@app.post("/heroes/")
-def create_hero(hero: Hero, session: SessionDep) -> Hero:
- session.add(hero)
- session.commit()
- session.refresh(hero)
- return hero
-
-
-@app.get("/heroes/")
-def read_heroes(
- session: SessionDep,
- offset: int = 0,
- limit: Annotated[int, Query(le=100)] = 100,
-) -> List[Hero]:
- heroes = session.exec(select(Hero).offset(offset).limit(limit)).all()
- return heroes
-
-
-@app.get("/heroes/{hero_id}")
-def read_hero(hero_id: int, session: SessionDep) -> Hero:
- hero = session.get(Hero, hero_id)
- if not hero:
- raise HTTPException(status_code=404, detail="Hero not found")
- return hero
-
-
-@app.delete("/heroes/{hero_id}")
-def delete_hero(hero_id: int, session: SessionDep):
- hero = session.get(Hero, hero_id)
- if not hero:
- raise HTTPException(status_code=404, detail="Hero not found")
- session.delete(hero)
- session.commit()
- return {"ok": True}
diff --git a/docs_src/sql_databases/tutorial002.py b/docs_src/sql_databases/tutorial002.py
deleted file mode 100644
index 4350d19c61..0000000000
--- a/docs_src/sql_databases/tutorial002.py
+++ /dev/null
@@ -1,104 +0,0 @@
-from typing import List, Union
-
-from fastapi import Depends, FastAPI, HTTPException, Query
-from sqlmodel import Field, Session, SQLModel, create_engine, select
-
-
-class HeroBase(SQLModel):
- name: str = Field(index=True)
- age: Union[int, None] = Field(default=None, index=True)
-
-
-class Hero(HeroBase, table=True):
- id: Union[int, None] = Field(default=None, primary_key=True)
- secret_name: str
-
-
-class HeroPublic(HeroBase):
- id: int
-
-
-class HeroCreate(HeroBase):
- secret_name: str
-
-
-class HeroUpdate(HeroBase):
- name: Union[str, None] = None
- age: Union[int, None] = None
- secret_name: Union[str, None] = None
-
-
-sqlite_file_name = "database.db"
-sqlite_url = f"sqlite:///{sqlite_file_name}"
-
-connect_args = {"check_same_thread": False}
-engine = create_engine(sqlite_url, connect_args=connect_args)
-
-
-def create_db_and_tables():
- SQLModel.metadata.create_all(engine)
-
-
-def get_session():
- with Session(engine) as session:
- yield session
-
-
-app = FastAPI()
-
-
-@app.on_event("startup")
-def on_startup():
- create_db_and_tables()
-
-
-@app.post("/heroes/", response_model=HeroPublic)
-def create_hero(hero: HeroCreate, session: Session = Depends(get_session)):
- db_hero = Hero.model_validate(hero)
- session.add(db_hero)
- session.commit()
- session.refresh(db_hero)
- return db_hero
-
-
-@app.get("/heroes/", response_model=List[HeroPublic])
-def read_heroes(
- session: Session = Depends(get_session),
- offset: int = 0,
- limit: int = Query(default=100, le=100),
-):
- heroes = session.exec(select(Hero).offset(offset).limit(limit)).all()
- return heroes
-
-
-@app.get("/heroes/{hero_id}", response_model=HeroPublic)
-def read_hero(hero_id: int, session: Session = Depends(get_session)):
- hero = session.get(Hero, hero_id)
- if not hero:
- raise HTTPException(status_code=404, detail="Hero not found")
- return hero
-
-
-@app.patch("/heroes/{hero_id}", response_model=HeroPublic)
-def update_hero(
- hero_id: int, hero: HeroUpdate, session: Session = Depends(get_session)
-):
- hero_db = session.get(Hero, hero_id)
- if not hero_db:
- raise HTTPException(status_code=404, detail="Hero not found")
- hero_data = hero.model_dump(exclude_unset=True)
- hero_db.sqlmodel_update(hero_data)
- session.add(hero_db)
- session.commit()
- session.refresh(hero_db)
- return hero_db
-
-
-@app.delete("/heroes/{hero_id}")
-def delete_hero(hero_id: int, session: Session = Depends(get_session)):
- hero = session.get(Hero, hero_id)
- if not hero:
- raise HTTPException(status_code=404, detail="Hero not found")
- session.delete(hero)
- session.commit()
- return {"ok": True}
diff --git a/docs_src/sql_databases/tutorial002_an.py b/docs_src/sql_databases/tutorial002_an.py
deleted file mode 100644
index 15e3d7c3a5..0000000000
--- a/docs_src/sql_databases/tutorial002_an.py
+++ /dev/null
@@ -1,104 +0,0 @@
-from typing import List, Union
-
-from fastapi import Depends, FastAPI, HTTPException, Query
-from sqlmodel import Field, Session, SQLModel, create_engine, select
-from typing_extensions import Annotated
-
-
-class HeroBase(SQLModel):
- name: str = Field(index=True)
- age: Union[int, None] = Field(default=None, index=True)
-
-
-class Hero(HeroBase, table=True):
- id: Union[int, None] = Field(default=None, primary_key=True)
- secret_name: str
-
-
-class HeroPublic(HeroBase):
- id: int
-
-
-class HeroCreate(HeroBase):
- secret_name: str
-
-
-class HeroUpdate(HeroBase):
- name: Union[str, None] = None
- age: Union[int, None] = None
- secret_name: Union[str, None] = None
-
-
-sqlite_file_name = "database.db"
-sqlite_url = f"sqlite:///{sqlite_file_name}"
-
-connect_args = {"check_same_thread": False}
-engine = create_engine(sqlite_url, connect_args=connect_args)
-
-
-def create_db_and_tables():
- SQLModel.metadata.create_all(engine)
-
-
-def get_session():
- with Session(engine) as session:
- yield session
-
-
-SessionDep = Annotated[Session, Depends(get_session)]
-app = FastAPI()
-
-
-@app.on_event("startup")
-def on_startup():
- create_db_and_tables()
-
-
-@app.post("/heroes/", response_model=HeroPublic)
-def create_hero(hero: HeroCreate, session: SessionDep):
- db_hero = Hero.model_validate(hero)
- session.add(db_hero)
- session.commit()
- session.refresh(db_hero)
- return db_hero
-
-
-@app.get("/heroes/", response_model=List[HeroPublic])
-def read_heroes(
- session: SessionDep,
- offset: int = 0,
- limit: Annotated[int, Query(le=100)] = 100,
-):
- heroes = session.exec(select(Hero).offset(offset).limit(limit)).all()
- return heroes
-
-
-@app.get("/heroes/{hero_id}", response_model=HeroPublic)
-def read_hero(hero_id: int, session: SessionDep):
- hero = session.get(Hero, hero_id)
- if not hero:
- raise HTTPException(status_code=404, detail="Hero not found")
- return hero
-
-
-@app.patch("/heroes/{hero_id}", response_model=HeroPublic)
-def update_hero(hero_id: int, hero: HeroUpdate, session: SessionDep):
- hero_db = session.get(Hero, hero_id)
- if not hero_db:
- raise HTTPException(status_code=404, detail="Hero not found")
- hero_data = hero.model_dump(exclude_unset=True)
- hero_db.sqlmodel_update(hero_data)
- session.add(hero_db)
- session.commit()
- session.refresh(hero_db)
- return hero_db
-
-
-@app.delete("/heroes/{hero_id}")
-def delete_hero(hero_id: int, session: SessionDep):
- hero = session.get(Hero, hero_id)
- if not hero:
- raise HTTPException(status_code=404, detail="Hero not found")
- session.delete(hero)
- session.commit()
- return {"ok": True}
diff --git a/docs_src/static_files/__init__.py b/docs_src/static_files/__init__.py
new file mode 100644
index 0000000000..e69de29bb2
diff --git a/docs_src/static_files/tutorial001.py b/docs_src/static_files/tutorial001_py39.py
similarity index 100%
rename from docs_src/static_files/tutorial001.py
rename to docs_src/static_files/tutorial001_py39.py
diff --git a/docs_src/sub_applications/__init__.py b/docs_src/sub_applications/__init__.py
new file mode 100644
index 0000000000..e69de29bb2
diff --git a/docs_src/sub_applications/tutorial001.py b/docs_src/sub_applications/tutorial001_py39.py
similarity index 100%
rename from docs_src/sub_applications/tutorial001.py
rename to docs_src/sub_applications/tutorial001_py39.py
diff --git a/docs_src/templates/__init__.py b/docs_src/templates/__init__.py
new file mode 100644
index 0000000000..e69de29bb2
diff --git a/docs_src/templates/static/__init__.py b/docs_src/templates/static/__init__.py
new file mode 100644
index 0000000000..e69de29bb2
diff --git a/docs_src/templates/templates/__init__.py b/docs_src/templates/templates/__init__.py
new file mode 100644
index 0000000000..e69de29bb2
diff --git a/docs_src/templates/tutorial001.py b/docs_src/templates/tutorial001_py39.py
similarity index 100%
rename from docs_src/templates/tutorial001.py
rename to docs_src/templates/tutorial001_py39.py
diff --git a/docs_src/using_request_directly/__init__.py b/docs_src/using_request_directly/__init__.py
new file mode 100644
index 0000000000..e69de29bb2
diff --git a/docs_src/using_request_directly/tutorial001.py b/docs_src/using_request_directly/tutorial001_py39.py
similarity index 100%
rename from docs_src/using_request_directly/tutorial001.py
rename to docs_src/using_request_directly/tutorial001_py39.py
diff --git a/docs_src/websockets/tutorial001.py b/docs_src/websockets/tutorial001_py39.py
similarity index 100%
rename from docs_src/websockets/tutorial001.py
rename to docs_src/websockets/tutorial001_py39.py
diff --git a/docs_src/websockets/tutorial002_an.py b/docs_src/websockets/tutorial002_an.py
deleted file mode 100644
index c838fbd306..0000000000
--- a/docs_src/websockets/tutorial002_an.py
+++ /dev/null
@@ -1,93 +0,0 @@
-from typing import Union
-
-from fastapi import (
- Cookie,
- Depends,
- FastAPI,
- Query,
- WebSocket,
- WebSocketException,
- status,
-)
-from fastapi.responses import HTMLResponse
-from typing_extensions import Annotated
-
-app = FastAPI()
-
-html = """
-
-
-
- Chat
-
-
- WebSocket Chat
-
-
-
-
-
-"""
-
-
-@app.get("/")
-async def get():
- return HTMLResponse(html)
-
-
-async def get_cookie_or_token(
- websocket: WebSocket,
- session: Annotated[Union[str, None], Cookie()] = None,
- token: Annotated[Union[str, None], Query()] = None,
-):
- if session is None and token is None:
- raise WebSocketException(code=status.WS_1008_POLICY_VIOLATION)
- return session or token
-
-
-@app.websocket("/items/{item_id}/ws")
-async def websocket_endpoint(
- *,
- websocket: WebSocket,
- item_id: str,
- q: Union[int, None] = None,
- cookie_or_token: Annotated[str, Depends(get_cookie_or_token)],
-):
- await websocket.accept()
- while True:
- data = await websocket.receive_text()
- await websocket.send_text(
- f"Session cookie or query token value is: {cookie_or_token}"
- )
- if q is not None:
- await websocket.send_text(f"Query parameter q is: {q}")
- await websocket.send_text(f"Message text was: {data}, for item ID: {item_id}")
diff --git a/docs_src/websockets/tutorial002.py b/docs_src/websockets/tutorial002_py39.py
similarity index 100%
rename from docs_src/websockets/tutorial002.py
rename to docs_src/websockets/tutorial002_py39.py
diff --git a/docs_src/websockets/tutorial003.py b/docs_src/websockets/tutorial003.py
deleted file mode 100644
index d561633a8d..0000000000
--- a/docs_src/websockets/tutorial003.py
+++ /dev/null
@@ -1,83 +0,0 @@
-from typing import List
-
-from fastapi import FastAPI, WebSocket, WebSocketDisconnect
-from fastapi.responses import HTMLResponse
-
-app = FastAPI()
-
-html = """
-
-
-
- Chat
-
-
- WebSocket Chat
- Your ID:
-
-
-
-
-
-"""
-
-
-class ConnectionManager:
- def __init__(self):
- self.active_connections: List[WebSocket] = []
-
- async def connect(self, websocket: WebSocket):
- await websocket.accept()
- self.active_connections.append(websocket)
-
- def disconnect(self, websocket: WebSocket):
- self.active_connections.remove(websocket)
-
- async def send_personal_message(self, message: str, websocket: WebSocket):
- await websocket.send_text(message)
-
- async def broadcast(self, message: str):
- for connection in self.active_connections:
- await connection.send_text(message)
-
-
-manager = ConnectionManager()
-
-
-@app.get("/")
-async def get():
- return HTMLResponse(html)
-
-
-@app.websocket("/ws/{client_id}")
-async def websocket_endpoint(websocket: WebSocket, client_id: int):
- await manager.connect(websocket)
- try:
- while True:
- data = await websocket.receive_text()
- await manager.send_personal_message(f"You wrote: {data}", websocket)
- await manager.broadcast(f"Client #{client_id} says: {data}")
- except WebSocketDisconnect:
- manager.disconnect(websocket)
- await manager.broadcast(f"Client #{client_id} left the chat")
diff --git a/docs_src/wsgi/__init__.py b/docs_src/wsgi/__init__.py
new file mode 100644
index 0000000000..e69de29bb2
diff --git a/docs_src/wsgi/tutorial001.py b/docs_src/wsgi/tutorial001_py39.py
similarity index 100%
rename from docs_src/wsgi/tutorial001.py
rename to docs_src/wsgi/tutorial001_py39.py
diff --git a/fastapi/__init__.py b/fastapi/__init__.py
index e02969c55f..6133787b06 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.124.4"
+__version__ = "0.128.0"
from starlette import status as status
diff --git a/fastapi/_compat/__init__.py b/fastapi/_compat/__init__.py
index 0aadd68de2..3dfaf9b712 100644
--- a/fastapi/_compat/__init__.py
+++ b/fastapi/_compat/__init__.py
@@ -1,44 +1,9 @@
-from .main import BaseConfig as BaseConfig
-from .main import PydanticSchemaGenerationError as PydanticSchemaGenerationError
-from .main import RequiredParam as RequiredParam
-from .main import Undefined as Undefined
-from .main import UndefinedType as UndefinedType
-from .main import Url as Url
-from .main import Validator as Validator
-from .main import _get_model_config as _get_model_config
-from .main import _is_error_wrapper as _is_error_wrapper
-from .main import _is_model_class as _is_model_class
-from .main import _is_model_field as _is_model_field
-from .main import _is_undefined as _is_undefined
-from .main import _model_dump as _model_dump
-from .main import _model_rebuild as _model_rebuild
-from .main import copy_field_info as copy_field_info
-from .main import create_body_model as create_body_model
-from .main import evaluate_forwardref as evaluate_forwardref
-from .main import get_annotation_from_field_info as get_annotation_from_field_info
-from .main import get_cached_model_fields as get_cached_model_fields
-from .main import get_compat_model_name_map as get_compat_model_name_map
-from .main import get_definitions as get_definitions
-from .main import get_missing_field_error as get_missing_field_error
-from .main import get_schema_from_model_field as get_schema_from_model_field
-from .main import is_bytes_field as is_bytes_field
-from .main import is_bytes_sequence_field as is_bytes_sequence_field
-from .main import is_scalar_field as is_scalar_field
-from .main import is_scalar_sequence_field as is_scalar_sequence_field
-from .main import is_sequence_field as is_sequence_field
-from .main import serialize_sequence_value as serialize_sequence_value
-from .main import (
- with_info_plain_validator_function as with_info_plain_validator_function,
-)
-from .may_v1 import CoreSchema as CoreSchema
-from .may_v1 import GetJsonSchemaHandler as GetJsonSchemaHandler
-from .may_v1 import JsonSchemaValue as JsonSchemaValue
-from .may_v1 import _normalize_errors as _normalize_errors
-from .model_field import ModelField as ModelField
from .shared import PYDANTIC_V2 as PYDANTIC_V2
from .shared import PYDANTIC_VERSION_MINOR_TUPLE as PYDANTIC_VERSION_MINOR_TUPLE
from .shared import annotation_is_pydantic_v1 as annotation_is_pydantic_v1
from .shared import field_annotation_is_scalar as field_annotation_is_scalar
+from .shared import is_pydantic_v1_model_class as is_pydantic_v1_model_class
+from .shared import is_pydantic_v1_model_instance as is_pydantic_v1_model_instance
from .shared import (
is_uploadfile_or_nonable_uploadfile_annotation as is_uploadfile_or_nonable_uploadfile_annotation,
)
@@ -48,3 +13,29 @@ from .shared import (
from .shared import lenient_issubclass as lenient_issubclass
from .shared import sequence_types as sequence_types
from .shared import value_is_sequence as value_is_sequence
+from .v2 import BaseConfig as BaseConfig
+from .v2 import ModelField as ModelField
+from .v2 import PydanticSchemaGenerationError as PydanticSchemaGenerationError
+from .v2 import RequiredParam as RequiredParam
+from .v2 import Undefined as Undefined
+from .v2 import UndefinedType as UndefinedType
+from .v2 import Url as Url
+from .v2 import Validator as Validator
+from .v2 import _regenerate_error_with_loc as _regenerate_error_with_loc
+from .v2 import copy_field_info as copy_field_info
+from .v2 import create_body_model as create_body_model
+from .v2 import evaluate_forwardref as evaluate_forwardref
+from .v2 import get_cached_model_fields as get_cached_model_fields
+from .v2 import get_compat_model_name_map as get_compat_model_name_map
+from .v2 import get_definitions as get_definitions
+from .v2 import get_missing_field_error as get_missing_field_error
+from .v2 import get_schema_from_model_field as get_schema_from_model_field
+from .v2 import is_bytes_field as is_bytes_field
+from .v2 import is_bytes_sequence_field as is_bytes_sequence_field
+from .v2 import is_scalar_field as is_scalar_field
+from .v2 import is_scalar_sequence_field as is_scalar_sequence_field
+from .v2 import is_sequence_field as is_sequence_field
+from .v2 import serialize_sequence_value as serialize_sequence_value
+from .v2 import (
+ with_info_plain_validator_function as with_info_plain_validator_function,
+)
diff --git a/fastapi/_compat/main.py b/fastapi/_compat/main.py
deleted file mode 100644
index e5275950e8..0000000000
--- a/fastapi/_compat/main.py
+++ /dev/null
@@ -1,362 +0,0 @@
-import sys
-from functools import lru_cache
-from typing import (
- Any,
- Dict,
- List,
- Sequence,
- Tuple,
- Type,
-)
-
-from fastapi._compat import may_v1
-from fastapi._compat.shared import PYDANTIC_V2, lenient_issubclass
-from fastapi.types import ModelNameMap
-from pydantic import BaseModel
-from typing_extensions import Literal
-
-from .model_field import ModelField
-
-if PYDANTIC_V2:
- from .v2 import BaseConfig as BaseConfig
- from .v2 import FieldInfo as FieldInfo
- from .v2 import PydanticSchemaGenerationError as PydanticSchemaGenerationError
- from .v2 import RequiredParam as RequiredParam
- from .v2 import Undefined as Undefined
- from .v2 import UndefinedType as UndefinedType
- from .v2 import Url as Url
- from .v2 import Validator as Validator
- from .v2 import evaluate_forwardref as evaluate_forwardref
- from .v2 import get_missing_field_error as get_missing_field_error
- from .v2 import (
- with_info_plain_validator_function as with_info_plain_validator_function,
- )
-else:
- from .v1 import BaseConfig as BaseConfig # type: ignore[assignment]
- from .v1 import FieldInfo as FieldInfo
- from .v1 import ( # type: ignore[assignment]
- PydanticSchemaGenerationError as PydanticSchemaGenerationError,
- )
- from .v1 import RequiredParam as RequiredParam
- from .v1 import Undefined as Undefined
- from .v1 import UndefinedType as UndefinedType
- from .v1 import Url as Url # type: ignore[assignment]
- from .v1 import Validator as Validator
- from .v1 import evaluate_forwardref as evaluate_forwardref
- from .v1 import get_missing_field_error as get_missing_field_error
- from .v1 import ( # type: ignore[assignment]
- with_info_plain_validator_function as with_info_plain_validator_function,
- )
-
-
-@lru_cache
-def get_cached_model_fields(model: Type[BaseModel]) -> List[ModelField]:
- if lenient_issubclass(model, may_v1.BaseModel):
- from fastapi._compat import v1
-
- return v1.get_model_fields(model)
- else:
- from . import v2
-
- return v2.get_model_fields(model) # type: ignore[return-value]
-
-
-def _is_undefined(value: object) -> bool:
- if isinstance(value, may_v1.UndefinedType):
- return True
- elif PYDANTIC_V2:
- from . import v2
-
- return isinstance(value, v2.UndefinedType)
- return False
-
-
-def _get_model_config(model: BaseModel) -> Any:
- if isinstance(model, may_v1.BaseModel):
- from fastapi._compat import v1
-
- return v1._get_model_config(model)
- elif PYDANTIC_V2:
- from . import v2
-
- return v2._get_model_config(model)
-
-
-def _model_dump(
- model: BaseModel, mode: Literal["json", "python"] = "json", **kwargs: Any
-) -> Any:
- if isinstance(model, may_v1.BaseModel):
- from fastapi._compat import v1
-
- return v1._model_dump(model, mode=mode, **kwargs)
- elif PYDANTIC_V2:
- from . import v2
-
- return v2._model_dump(model, mode=mode, **kwargs)
-
-
-def _is_error_wrapper(exc: Exception) -> bool:
- if isinstance(exc, may_v1.ErrorWrapper):
- return True
- elif PYDANTIC_V2:
- from . import v2
-
- return isinstance(exc, v2.ErrorWrapper)
- return False
-
-
-def copy_field_info(*, field_info: FieldInfo, annotation: Any) -> FieldInfo:
- if isinstance(field_info, may_v1.FieldInfo):
- from fastapi._compat import v1
-
- return v1.copy_field_info(field_info=field_info, annotation=annotation)
- else:
- assert PYDANTIC_V2
- from . import v2
-
- return v2.copy_field_info(field_info=field_info, annotation=annotation)
-
-
-def create_body_model(
- *, fields: Sequence[ModelField], model_name: str
-) -> Type[BaseModel]:
- if fields and isinstance(fields[0], may_v1.ModelField):
- from fastapi._compat import v1
-
- return v1.create_body_model(fields=fields, model_name=model_name)
- else:
- assert PYDANTIC_V2
- from . import v2
-
- return v2.create_body_model(fields=fields, model_name=model_name) # type: ignore[arg-type]
-
-
-def get_annotation_from_field_info(
- annotation: Any, field_info: FieldInfo, field_name: str
-) -> Any:
- if isinstance(field_info, may_v1.FieldInfo):
- from fastapi._compat import v1
-
- return v1.get_annotation_from_field_info(
- annotation=annotation, field_info=field_info, field_name=field_name
- )
- else:
- assert PYDANTIC_V2
- from . import v2
-
- return v2.get_annotation_from_field_info(
- annotation=annotation, field_info=field_info, field_name=field_name
- )
-
-
-def is_bytes_field(field: ModelField) -> bool:
- if isinstance(field, may_v1.ModelField):
- from fastapi._compat import v1
-
- return v1.is_bytes_field(field)
- else:
- assert PYDANTIC_V2
- from . import v2
-
- return v2.is_bytes_field(field) # type: ignore[arg-type]
-
-
-def is_bytes_sequence_field(field: ModelField) -> bool:
- if isinstance(field, may_v1.ModelField):
- from fastapi._compat import v1
-
- return v1.is_bytes_sequence_field(field)
- else:
- assert PYDANTIC_V2
- from . import v2
-
- return v2.is_bytes_sequence_field(field) # type: ignore[arg-type]
-
-
-def is_scalar_field(field: ModelField) -> bool:
- if isinstance(field, may_v1.ModelField):
- from fastapi._compat import v1
-
- return v1.is_scalar_field(field)
- else:
- assert PYDANTIC_V2
- from . import v2
-
- return v2.is_scalar_field(field) # type: ignore[arg-type]
-
-
-def is_scalar_sequence_field(field: ModelField) -> bool:
- if isinstance(field, may_v1.ModelField):
- from fastapi._compat import v1
-
- return v1.is_scalar_sequence_field(field)
- else:
- assert PYDANTIC_V2
- from . import v2
-
- return v2.is_scalar_sequence_field(field) # type: ignore[arg-type]
-
-
-def is_sequence_field(field: ModelField) -> bool:
- if isinstance(field, may_v1.ModelField):
- from fastapi._compat import v1
-
- return v1.is_sequence_field(field)
- else:
- assert PYDANTIC_V2
- from . import v2
-
- return v2.is_sequence_field(field) # type: ignore[arg-type]
-
-
-def serialize_sequence_value(*, field: ModelField, value: Any) -> Sequence[Any]:
- if isinstance(field, may_v1.ModelField):
- from fastapi._compat import v1
-
- return v1.serialize_sequence_value(field=field, value=value)
- else:
- assert PYDANTIC_V2
- from . import v2
-
- return v2.serialize_sequence_value(field=field, value=value) # type: ignore[arg-type]
-
-
-def _model_rebuild(model: Type[BaseModel]) -> None:
- if lenient_issubclass(model, may_v1.BaseModel):
- from fastapi._compat import v1
-
- v1._model_rebuild(model)
- elif PYDANTIC_V2:
- from . import v2
-
- v2._model_rebuild(model)
-
-
-def get_compat_model_name_map(fields: List[ModelField]) -> ModelNameMap:
- v1_model_fields = [
- field for field in fields if isinstance(field, may_v1.ModelField)
- ]
- if v1_model_fields:
- from fastapi._compat import v1
-
- v1_flat_models = v1.get_flat_models_from_fields(
- v1_model_fields, known_models=set()
- )
- all_flat_models = v1_flat_models
- else:
- all_flat_models = set()
- if PYDANTIC_V2:
- from . import v2
-
- v2_model_fields = [
- field for field in fields if isinstance(field, v2.ModelField)
- ]
- v2_flat_models = v2.get_flat_models_from_fields(
- v2_model_fields, known_models=set()
- )
- all_flat_models = all_flat_models.union(v2_flat_models)
-
- model_name_map = v2.get_model_name_map(all_flat_models)
- return model_name_map
- from fastapi._compat import v1
-
- model_name_map = v1.get_model_name_map(all_flat_models)
- return model_name_map
-
-
-def get_definitions(
- *,
- fields: List[ModelField],
- model_name_map: ModelNameMap,
- separate_input_output_schemas: bool = True,
-) -> Tuple[
- Dict[
- Tuple[ModelField, Literal["validation", "serialization"]],
- may_v1.JsonSchemaValue,
- ],
- Dict[str, Dict[str, Any]],
-]:
- if sys.version_info < (3, 14):
- v1_fields = [field for field in fields if isinstance(field, may_v1.ModelField)]
- v1_field_maps, v1_definitions = may_v1.get_definitions(
- fields=v1_fields,
- model_name_map=model_name_map,
- separate_input_output_schemas=separate_input_output_schemas,
- )
- if not PYDANTIC_V2:
- return v1_field_maps, v1_definitions
- else:
- from . import v2
-
- v2_fields = [field for field in fields if isinstance(field, v2.ModelField)]
- v2_field_maps, v2_definitions = v2.get_definitions(
- fields=v2_fields,
- model_name_map=model_name_map,
- separate_input_output_schemas=separate_input_output_schemas,
- )
- all_definitions = {**v1_definitions, **v2_definitions}
- all_field_maps = {**v1_field_maps, **v2_field_maps}
- return all_field_maps, all_definitions
-
- # Pydantic v1 is not supported since Python 3.14
- else:
- from . import v2
-
- v2_fields = [field for field in fields if isinstance(field, v2.ModelField)]
- v2_field_maps, v2_definitions = v2.get_definitions(
- fields=v2_fields,
- model_name_map=model_name_map,
- separate_input_output_schemas=separate_input_output_schemas,
- )
- return v2_field_maps, v2_definitions
-
-
-def get_schema_from_model_field(
- *,
- field: ModelField,
- model_name_map: ModelNameMap,
- field_mapping: Dict[
- Tuple[ModelField, Literal["validation", "serialization"]],
- may_v1.JsonSchemaValue,
- ],
- separate_input_output_schemas: bool = True,
-) -> Dict[str, Any]:
- if isinstance(field, may_v1.ModelField):
- from fastapi._compat import v1
-
- return v1.get_schema_from_model_field(
- field=field,
- model_name_map=model_name_map,
- field_mapping=field_mapping,
- separate_input_output_schemas=separate_input_output_schemas,
- )
- else:
- assert PYDANTIC_V2
- from . import v2
-
- return v2.get_schema_from_model_field(
- field=field, # type: ignore[arg-type]
- model_name_map=model_name_map,
- field_mapping=field_mapping, # type: ignore[arg-type]
- separate_input_output_schemas=separate_input_output_schemas,
- )
-
-
-def _is_model_field(value: Any) -> bool:
- if isinstance(value, may_v1.ModelField):
- return True
- elif PYDANTIC_V2:
- from . import v2
-
- return isinstance(value, v2.ModelField)
- return False
-
-
-def _is_model_class(value: Any) -> bool:
- if lenient_issubclass(value, may_v1.BaseModel):
- return True
- elif PYDANTIC_V2:
- from . import v2
-
- return lenient_issubclass(value, v2.BaseModel) # type: ignore[attr-defined]
- return False
diff --git a/fastapi/_compat/may_v1.py b/fastapi/_compat/may_v1.py
deleted file mode 100644
index beea4d167f..0000000000
--- a/fastapi/_compat/may_v1.py
+++ /dev/null
@@ -1,123 +0,0 @@
-import sys
-from typing import Any, Dict, List, Literal, Sequence, Tuple, Type, Union
-
-from fastapi.types import ModelNameMap
-
-if sys.version_info >= (3, 14):
-
- class AnyUrl:
- pass
-
- class BaseConfig:
- pass
-
- class BaseModel:
- pass
-
- class Color:
- pass
-
- class CoreSchema:
- pass
-
- class ErrorWrapper:
- pass
-
- class FieldInfo:
- pass
-
- class GetJsonSchemaHandler:
- pass
-
- class JsonSchemaValue:
- pass
-
- class ModelField:
- pass
-
- class NameEmail:
- pass
-
- class RequiredParam:
- pass
-
- class SecretBytes:
- pass
-
- class SecretStr:
- pass
-
- class Undefined:
- pass
-
- class UndefinedType:
- pass
-
- class Url:
- pass
-
- from .v2 import ValidationError, create_model
-
- def get_definitions(
- *,
- fields: List[ModelField],
- model_name_map: ModelNameMap,
- separate_input_output_schemas: bool = True,
- ) -> Tuple[
- Dict[
- Tuple[ModelField, Literal["validation", "serialization"]], JsonSchemaValue
- ],
- Dict[str, Dict[str, Any]],
- ]:
- return {}, {} # pragma: no cover
-
-
-else:
- from .v1 import AnyUrl as AnyUrl
- from .v1 import BaseConfig as BaseConfig
- from .v1 import BaseModel as BaseModel
- from .v1 import Color as Color
- from .v1 import CoreSchema as CoreSchema
- from .v1 import ErrorWrapper as ErrorWrapper
- from .v1 import FieldInfo as FieldInfo
- from .v1 import GetJsonSchemaHandler as GetJsonSchemaHandler
- from .v1 import JsonSchemaValue as JsonSchemaValue
- from .v1 import ModelField as ModelField
- from .v1 import NameEmail as NameEmail
- from .v1 import RequiredParam as RequiredParam
- from .v1 import SecretBytes as SecretBytes
- from .v1 import SecretStr as SecretStr
- from .v1 import Undefined as Undefined
- from .v1 import UndefinedType as UndefinedType
- from .v1 import Url as Url
- from .v1 import ValidationError, create_model
- from .v1 import get_definitions as get_definitions
-
-
-RequestErrorModel: Type[BaseModel] = create_model("Request")
-
-
-def _normalize_errors(errors: Sequence[Any]) -> List[Dict[str, Any]]:
- use_errors: List[Any] = []
- for error in errors:
- if isinstance(error, ErrorWrapper):
- new_errors = ValidationError( # type: ignore[call-arg]
- errors=[error], model=RequestErrorModel
- ).errors()
- use_errors.extend(new_errors)
- elif isinstance(error, list):
- use_errors.extend(_normalize_errors(error))
- else:
- use_errors.append(error)
- return use_errors
-
-
-def _regenerate_error_with_loc(
- *, errors: Sequence[Any], loc_prefix: Tuple[Union[str, int], ...]
-) -> List[Dict[str, Any]]:
- updated_loc_errors: List[Any] = [
- {**err, "loc": loc_prefix + err.get("loc", ())}
- for err in _normalize_errors(errors)
- ]
-
- return updated_loc_errors
diff --git a/fastapi/_compat/model_field.py b/fastapi/_compat/model_field.py
deleted file mode 100644
index fa2008c5e0..0000000000
--- a/fastapi/_compat/model_field.py
+++ /dev/null
@@ -1,53 +0,0 @@
-from typing import (
- Any,
- Dict,
- List,
- Tuple,
- Union,
-)
-
-from fastapi.types import IncEx
-from pydantic.fields import FieldInfo
-from typing_extensions import Literal, Protocol
-
-
-class ModelField(Protocol):
- field_info: "FieldInfo"
- name: str
- mode: Literal["validation", "serialization"] = "validation"
- _version: Literal["v1", "v2"] = "v1"
-
- @property
- def alias(self) -> str: ...
-
- @property
- def required(self) -> bool: ...
-
- @property
- def default(self) -> Any: ...
-
- @property
- def type_(self) -> Any: ...
-
- def get_default(self) -> Any: ...
-
- def validate(
- self,
- value: Any,
- values: Dict[str, Any] = {}, # noqa: B006
- *,
- loc: Tuple[Union[int, str], ...] = (),
- ) -> Tuple[Any, Union[List[Dict[str, Any]], None]]: ...
-
- def serialize(
- self,
- value: Any,
- *,
- mode: Literal["json", "python"] = "json",
- include: Union[IncEx, None] = None,
- exclude: Union[IncEx, None] = None,
- by_alias: bool = True,
- exclude_unset: bool = False,
- exclude_defaults: bool = False,
- exclude_none: bool = False,
- ) -> Any: ...
diff --git a/fastapi/_compat/shared.py b/fastapi/_compat/shared.py
index cabf482283..419b58f7f2 100644
--- a/fastapi/_compat/shared.py
+++ b/fastapi/_compat/shared.py
@@ -1,36 +1,24 @@
import sys
import types
import typing
+import warnings
from collections import deque
+from collections.abc import Mapping, Sequence
from dataclasses import is_dataclass
from typing import (
+ Annotated,
Any,
- Deque,
- FrozenSet,
- List,
- Mapping,
- Sequence,
- Set,
- Tuple,
- Type,
Union,
)
-from fastapi._compat import may_v1
from fastapi.types import UnionType
from pydantic import BaseModel
from pydantic.version import VERSION as PYDANTIC_VERSION
from starlette.datastructures import UploadFile
-from typing_extensions import Annotated, get_args, get_origin
+from typing_extensions import get_args, get_origin
# Copy from Pydantic v2, compatible with v1
-if sys.version_info < (3, 9):
- # Pydantic no longer supports Python 3.8, this might be incorrect, but the code
- # this is used for is also never reached in this codebase, as it's a copy of
- # Pydantic's lenient_issubclass, just for compatibility with v1
- # TODO: remove when dropping support for Python 3.8
- WithArgsTypes: Tuple[Any, ...] = ()
-elif sys.version_info < (3, 10):
+if sys.version_info < (3, 10):
WithArgsTypes: tuple[Any, ...] = (typing._GenericAlias, types.GenericAlias) # type: ignore[attr-defined]
else:
WithArgsTypes: tuple[Any, ...] = (
@@ -45,26 +33,21 @@ PYDANTIC_V2 = PYDANTIC_VERSION_MINOR_TUPLE[0] == 2
sequence_annotation_to_type = {
Sequence: list,
- List: list,
list: list,
- Tuple: tuple,
tuple: tuple,
- Set: set,
set: set,
- FrozenSet: frozenset,
frozenset: frozenset,
- Deque: deque,
deque: deque,
}
sequence_types = tuple(sequence_annotation_to_type.keys())
-Url: Type[Any]
+Url: type[Any]
# Copy of Pydantic v2, compatible with v1
def lenient_issubclass(
- cls: Any, class_or_tuple: Union[Type[Any], Tuple[Type[Any], ...], None]
+ cls: Any, class_or_tuple: Union[type[Any], tuple[type[Any], ...], None]
) -> bool:
try:
return isinstance(cls, type) and issubclass(cls, class_or_tuple) # type: ignore[arg-type]
@@ -74,13 +57,13 @@ def lenient_issubclass(
raise # pragma: no cover
-def _annotation_is_sequence(annotation: Union[Type[Any], None]) -> bool:
+def _annotation_is_sequence(annotation: Union[type[Any], None]) -> bool:
if lenient_issubclass(annotation, (str, bytes)):
return False
- return lenient_issubclass(annotation, sequence_types) # type: ignore[arg-type]
+ return lenient_issubclass(annotation, sequence_types)
-def field_annotation_is_sequence(annotation: Union[Type[Any], None]) -> bool:
+def field_annotation_is_sequence(annotation: Union[type[Any], None]) -> bool:
origin = get_origin(annotation)
if origin is Union or origin is UnionType:
for arg in get_args(annotation):
@@ -93,20 +76,18 @@ def field_annotation_is_sequence(annotation: Union[Type[Any], None]) -> bool:
def value_is_sequence(value: Any) -> bool:
- return isinstance(value, sequence_types) and not isinstance(value, (str, bytes)) # type: ignore[arg-type]
+ return isinstance(value, sequence_types) and not isinstance(value, (str, bytes))
-def _annotation_is_complex(annotation: Union[Type[Any], None]) -> bool:
+def _annotation_is_complex(annotation: Union[type[Any], None]) -> bool:
return (
- lenient_issubclass(
- annotation, (BaseModel, may_v1.BaseModel, Mapping, UploadFile)
- )
+ lenient_issubclass(annotation, (BaseModel, Mapping, UploadFile))
or _annotation_is_sequence(annotation)
or is_dataclass(annotation)
)
-def field_annotation_is_complex(annotation: Union[Type[Any], None]) -> bool:
+def field_annotation_is_complex(annotation: Union[type[Any], None]) -> bool:
origin = get_origin(annotation)
if origin is Union or origin is UnionType:
return any(field_annotation_is_complex(arg) for arg in get_args(annotation))
@@ -127,7 +108,7 @@ def field_annotation_is_scalar(annotation: Any) -> bool:
return annotation is Ellipsis or not field_annotation_is_complex(annotation)
-def field_annotation_is_scalar_sequence(annotation: Union[Type[Any], None]) -> bool:
+def field_annotation_is_scalar_sequence(annotation: Union[type[Any], None]) -> bool:
origin = get_origin(annotation)
if origin is Union or origin is UnionType:
at_least_one_scalar_sequence = False
@@ -196,13 +177,27 @@ def is_uploadfile_sequence_annotation(annotation: Any) -> bool:
)
+def is_pydantic_v1_model_instance(obj: Any) -> bool:
+ with warnings.catch_warnings():
+ warnings.simplefilter("ignore", UserWarning)
+ from pydantic import v1
+ return isinstance(obj, v1.BaseModel)
+
+
+def is_pydantic_v1_model_class(cls: Any) -> bool:
+ with warnings.catch_warnings():
+ warnings.simplefilter("ignore", UserWarning)
+ from pydantic import v1
+ return lenient_issubclass(cls, v1.BaseModel)
+
+
def annotation_is_pydantic_v1(annotation: Any) -> bool:
- if lenient_issubclass(annotation, may_v1.BaseModel):
+ if is_pydantic_v1_model_class(annotation):
return True
origin = get_origin(annotation)
if origin is Union or origin is UnionType:
for arg in get_args(annotation):
- if lenient_issubclass(arg, may_v1.BaseModel):
+ if is_pydantic_v1_model_class(arg):
return True
if field_annotation_is_sequence(annotation):
for sub_annotation in get_args(annotation):
diff --git a/fastapi/_compat/v1.py b/fastapi/_compat/v1.py
deleted file mode 100644
index e17ce8beaf..0000000000
--- a/fastapi/_compat/v1.py
+++ /dev/null
@@ -1,312 +0,0 @@
-from copy import copy
-from dataclasses import dataclass, is_dataclass
-from enum import Enum
-from typing import (
- Any,
- Callable,
- Dict,
- List,
- Sequence,
- Set,
- Tuple,
- Type,
- Union,
-)
-
-from fastapi._compat import shared
-from fastapi.openapi.constants import REF_PREFIX as REF_PREFIX
-from fastapi.types import ModelNameMap
-from pydantic.version import VERSION as PYDANTIC_VERSION
-from typing_extensions import Literal
-
-PYDANTIC_VERSION_MINOR_TUPLE = tuple(int(x) for x in PYDANTIC_VERSION.split(".")[:2])
-PYDANTIC_V2 = PYDANTIC_VERSION_MINOR_TUPLE[0] == 2
-# Keeping old "Required" functionality from Pydantic V1, without
-# shadowing typing.Required.
-RequiredParam: Any = Ellipsis
-
-if not PYDANTIC_V2:
- from pydantic import BaseConfig as BaseConfig
- from pydantic import BaseModel as BaseModel
- from pydantic import ValidationError as ValidationError
- from pydantic import create_model as create_model
- from pydantic.class_validators import Validator as Validator
- from pydantic.color import Color as Color
- from pydantic.error_wrappers import ErrorWrapper as ErrorWrapper
- from pydantic.errors import MissingError
- from pydantic.fields import ( # type: ignore[attr-defined]
- SHAPE_FROZENSET,
- SHAPE_LIST,
- SHAPE_SEQUENCE,
- SHAPE_SET,
- SHAPE_SINGLETON,
- SHAPE_TUPLE,
- SHAPE_TUPLE_ELLIPSIS,
- )
- from pydantic.fields import FieldInfo as FieldInfo
- from pydantic.fields import ModelField as ModelField # type: ignore[attr-defined]
- from pydantic.fields import Undefined as Undefined # type: ignore[attr-defined]
- from pydantic.fields import ( # type: ignore[attr-defined]
- UndefinedType as UndefinedType,
- )
- from pydantic.networks import AnyUrl as AnyUrl
- from pydantic.networks import NameEmail as NameEmail
- from pydantic.schema import TypeModelSet as TypeModelSet
- from pydantic.schema import (
- field_schema,
- model_process_schema,
- )
- from pydantic.schema import (
- get_annotation_from_field_info as get_annotation_from_field_info,
- )
- from pydantic.schema import get_flat_models_from_field as get_flat_models_from_field
- from pydantic.schema import (
- get_flat_models_from_fields as get_flat_models_from_fields,
- )
- from pydantic.schema import get_model_name_map as get_model_name_map
- from pydantic.types import SecretBytes as SecretBytes
- from pydantic.types import SecretStr as SecretStr
- from pydantic.typing import evaluate_forwardref as evaluate_forwardref
- from pydantic.utils import lenient_issubclass as lenient_issubclass
-
-
-else:
- from pydantic.v1 import BaseConfig as BaseConfig # type: ignore[assignment]
- from pydantic.v1 import BaseModel as BaseModel # type: ignore[assignment]
- from pydantic.v1 import ( # type: ignore[assignment]
- ValidationError as ValidationError,
- )
- from pydantic.v1 import create_model as create_model # type: ignore[no-redef]
- from pydantic.v1.class_validators import Validator as Validator
- from pydantic.v1.color import Color as Color # type: ignore[assignment]
- from pydantic.v1.error_wrappers import ErrorWrapper as ErrorWrapper
- from pydantic.v1.errors import MissingError
- from pydantic.v1.fields import (
- SHAPE_FROZENSET,
- SHAPE_LIST,
- SHAPE_SEQUENCE,
- SHAPE_SET,
- SHAPE_SINGLETON,
- SHAPE_TUPLE,
- SHAPE_TUPLE_ELLIPSIS,
- )
- from pydantic.v1.fields import FieldInfo as FieldInfo # type: ignore[assignment]
- from pydantic.v1.fields import ModelField as ModelField
- from pydantic.v1.fields import Undefined as Undefined
- from pydantic.v1.fields import UndefinedType as UndefinedType
- from pydantic.v1.networks import AnyUrl as AnyUrl
- from pydantic.v1.networks import ( # type: ignore[assignment]
- NameEmail as NameEmail,
- )
- from pydantic.v1.schema import TypeModelSet as TypeModelSet
- from pydantic.v1.schema import (
- field_schema,
- model_process_schema,
- )
- from pydantic.v1.schema import (
- get_annotation_from_field_info as get_annotation_from_field_info,
- )
- from pydantic.v1.schema import (
- get_flat_models_from_field as get_flat_models_from_field,
- )
- from pydantic.v1.schema import (
- get_flat_models_from_fields as get_flat_models_from_fields,
- )
- from pydantic.v1.schema import get_model_name_map as get_model_name_map
- from pydantic.v1.types import ( # type: ignore[assignment]
- SecretBytes as SecretBytes,
- )
- from pydantic.v1.types import ( # type: ignore[assignment]
- SecretStr as SecretStr,
- )
- from pydantic.v1.typing import evaluate_forwardref as evaluate_forwardref
- from pydantic.v1.utils import lenient_issubclass as lenient_issubclass
-
-
-GetJsonSchemaHandler = Any
-JsonSchemaValue = Dict[str, Any]
-CoreSchema = Any
-Url = AnyUrl
-
-sequence_shapes = {
- SHAPE_LIST,
- SHAPE_SET,
- SHAPE_FROZENSET,
- SHAPE_TUPLE,
- SHAPE_SEQUENCE,
- SHAPE_TUPLE_ELLIPSIS,
-}
-sequence_shape_to_type = {
- SHAPE_LIST: list,
- SHAPE_SET: set,
- SHAPE_TUPLE: tuple,
- SHAPE_SEQUENCE: list,
- SHAPE_TUPLE_ELLIPSIS: list,
-}
-
-
-@dataclass
-class GenerateJsonSchema:
- ref_template: str
-
-
-class PydanticSchemaGenerationError(Exception):
- pass
-
-
-RequestErrorModel: Type[BaseModel] = create_model("Request")
-
-
-def with_info_plain_validator_function(
- function: Callable[..., Any],
- *,
- ref: Union[str, None] = None,
- metadata: Any = None,
- serialization: Any = None,
-) -> Any:
- return {}
-
-
-def get_model_definitions(
- *,
- flat_models: Set[Union[Type[BaseModel], Type[Enum]]],
- model_name_map: Dict[Union[Type[BaseModel], Type[Enum]], str],
-) -> Dict[str, Any]:
- definitions: Dict[str, Dict[str, Any]] = {}
- for model in flat_models:
- m_schema, m_definitions, m_nested_models = model_process_schema(
- model, model_name_map=model_name_map, ref_prefix=REF_PREFIX
- )
- definitions.update(m_definitions)
- model_name = model_name_map[model]
- definitions[model_name] = m_schema
- for m_schema in definitions.values():
- if "description" in m_schema:
- m_schema["description"] = m_schema["description"].split("\f")[0]
- return definitions
-
-
-def is_pv1_scalar_field(field: ModelField) -> bool:
- from fastapi import params
-
- field_info = field.field_info
- if not (
- field.shape == SHAPE_SINGLETON
- and not lenient_issubclass(field.type_, BaseModel)
- and not lenient_issubclass(field.type_, dict)
- and not shared.field_annotation_is_sequence(field.type_)
- and not is_dataclass(field.type_)
- and not isinstance(field_info, params.Body)
- ):
- return False
- if field.sub_fields:
- if not all(is_pv1_scalar_field(f) for f in field.sub_fields):
- return False
- return True
-
-
-def is_pv1_scalar_sequence_field(field: ModelField) -> bool:
- if (field.shape in sequence_shapes) and not lenient_issubclass(
- field.type_, BaseModel
- ):
- if field.sub_fields is not None:
- for sub_field in field.sub_fields:
- if not is_pv1_scalar_field(sub_field):
- return False
- return True
- if shared._annotation_is_sequence(field.type_):
- return True
- return False
-
-
-def _model_rebuild(model: Type[BaseModel]) -> None:
- model.update_forward_refs()
-
-
-def _model_dump(
- model: BaseModel, mode: Literal["json", "python"] = "json", **kwargs: Any
-) -> Any:
- return model.dict(**kwargs)
-
-
-def _get_model_config(model: BaseModel) -> Any:
- return model.__config__ # type: ignore[attr-defined]
-
-
-def get_schema_from_model_field(
- *,
- field: ModelField,
- model_name_map: ModelNameMap,
- field_mapping: Dict[
- Tuple[ModelField, Literal["validation", "serialization"]], JsonSchemaValue
- ],
- separate_input_output_schemas: bool = True,
-) -> Dict[str, Any]:
- return field_schema( # type: ignore[no-any-return]
- field, model_name_map=model_name_map, ref_prefix=REF_PREFIX
- )[0]
-
-
-# def get_compat_model_name_map(fields: List[ModelField]) -> ModelNameMap:
-# models = get_flat_models_from_fields(fields, known_models=set())
-# return get_model_name_map(models) # type: ignore[no-any-return]
-
-
-def get_definitions(
- *,
- fields: List[ModelField],
- model_name_map: ModelNameMap,
- separate_input_output_schemas: bool = True,
-) -> Tuple[
- Dict[Tuple[ModelField, Literal["validation", "serialization"]], JsonSchemaValue],
- Dict[str, Dict[str, Any]],
-]:
- models = get_flat_models_from_fields(fields, known_models=set())
- return {}, get_model_definitions(flat_models=models, model_name_map=model_name_map)
-
-
-def is_scalar_field(field: ModelField) -> bool:
- return is_pv1_scalar_field(field)
-
-
-def is_sequence_field(field: ModelField) -> bool:
- return field.shape in sequence_shapes or shared._annotation_is_sequence(field.type_)
-
-
-def is_scalar_sequence_field(field: ModelField) -> bool:
- return is_pv1_scalar_sequence_field(field)
-
-
-def is_bytes_field(field: ModelField) -> bool:
- return lenient_issubclass(field.type_, bytes) # type: ignore[no-any-return]
-
-
-def is_bytes_sequence_field(field: ModelField) -> bool:
- return field.shape in sequence_shapes and lenient_issubclass(field.type_, bytes)
-
-
-def copy_field_info(*, field_info: FieldInfo, annotation: Any) -> FieldInfo:
- return copy(field_info)
-
-
-def serialize_sequence_value(*, field: ModelField, value: Any) -> Sequence[Any]:
- return sequence_shape_to_type[field.shape](value) # type: ignore[no-any-return]
-
-
-def get_missing_field_error(loc: Tuple[str, ...]) -> Dict[str, Any]:
- missing_field_error = ErrorWrapper(MissingError(), loc=loc)
- new_error = ValidationError([missing_field_error], RequestErrorModel)
- return new_error.errors()[0] # type: ignore[return-value]
-
-
-def create_body_model(
- *, fields: Sequence[ModelField], model_name: str
-) -> Type[BaseModel]:
- BodyModel = create_model(model_name)
- for f in fields:
- BodyModel.__fields__[f.name] = f # type: ignore[index]
- return BodyModel
-
-
-def get_model_fields(model: Type[BaseModel]) -> List[ModelField]:
- return list(model.__fields__.values()) # type: ignore[attr-defined]
diff --git a/fastapi/_compat/v2.py b/fastapi/_compat/v2.py
index a17d625568..25b6814536 100644
--- a/fastapi/_compat/v2.py
+++ b/fastapi/_compat/v2.py
@@ -1,21 +1,18 @@
import re
import warnings
+from collections.abc import Sequence
from copy import copy, deepcopy
from dataclasses import dataclass, is_dataclass
from enum import Enum
+from functools import lru_cache
from typing import (
+ Annotated,
Any,
- Dict,
- List,
- Sequence,
- Set,
- Tuple,
- Type,
Union,
cast,
)
-from fastapi._compat import may_v1, shared
+from fastapi._compat import shared
from fastapi.openapi.constants import REF_TEMPLATE
from fastapi.types import IncEx, ModelNameMap, UnionType
from pydantic import BaseModel, ConfigDict, Field, TypeAdapter, create_model
@@ -33,7 +30,7 @@ from pydantic.json_schema import JsonSchemaValue as JsonSchemaValue
from pydantic_core import CoreSchema as CoreSchema
from pydantic_core import PydanticUndefined, PydanticUndefinedType
from pydantic_core import Url as Url
-from typing_extensions import Annotated, Literal, get_args, get_origin
+from typing_extensions import Literal, get_args, get_origin
try:
from pydantic_core.core_schema import (
@@ -77,7 +74,7 @@ _Attrs = {
# TODO: remove when dropping support for Pydantic < v2.12.3
-def asdict(field_info: FieldInfo) -> Dict[str, Any]:
+def asdict(field_info: FieldInfo) -> dict[str, Any]:
attributes = {}
for attr in _Attrs:
value = getattr(field_info, attr, Undefined)
@@ -169,17 +166,17 @@ class ModelField:
def validate(
self,
value: Any,
- values: Dict[str, Any] = {}, # noqa: B006
+ values: dict[str, Any] = {}, # noqa: B006
*,
- loc: Tuple[Union[int, str], ...] = (),
- ) -> Tuple[Any, Union[List[Dict[str, Any]], None]]:
+ loc: tuple[Union[int, str], ...] = (),
+ ) -> tuple[Any, Union[list[dict[str, Any]], None]]:
try:
return (
self._type_adapter.validate_python(value, from_attributes=True),
None,
)
except ValidationError as exc:
- return None, may_v1._regenerate_error_with_loc(
+ return None, _regenerate_error_with_loc(
errors=exc.errors(include_url=False), loc_prefix=loc
)
@@ -214,26 +211,6 @@ class ModelField:
return id(self)
-def get_annotation_from_field_info(
- annotation: Any, field_info: FieldInfo, field_name: str
-) -> Any:
- return annotation
-
-
-def _model_rebuild(model: Type[BaseModel]) -> None:
- model.model_rebuild()
-
-
-def _model_dump(
- model: BaseModel, mode: Literal["json", "python"] = "json", **kwargs: Any
-) -> Any:
- return model.model_dump(mode=mode, **kwargs)
-
-
-def _get_model_config(model: BaseModel) -> Any:
- return model.model_config
-
-
def _has_computed_fields(field: ModelField) -> bool:
computed_fields = field._type_adapter.core_schema.get("schema", {}).get(
"computed_fields", []
@@ -245,11 +222,11 @@ def get_schema_from_model_field(
*,
field: ModelField,
model_name_map: ModelNameMap,
- field_mapping: Dict[
- Tuple[ModelField, Literal["validation", "serialization"]], JsonSchemaValue
+ field_mapping: dict[
+ tuple[ModelField, Literal["validation", "serialization"]], JsonSchemaValue
],
separate_input_output_schemas: bool = True,
-) -> Dict[str, Any]:
+) -> dict[str, Any]:
override_mode: Union[Literal["validation"], None] = (
None
if (separate_input_output_schemas or _has_computed_fields(field))
@@ -277,9 +254,9 @@ def get_definitions(
fields: Sequence[ModelField],
model_name_map: ModelNameMap,
separate_input_output_schemas: bool = True,
-) -> Tuple[
- Dict[Tuple[ModelField, Literal["validation", "serialization"]], JsonSchemaValue],
- Dict[str, Dict[str, Any]],
+) -> tuple[
+ dict[tuple[ModelField, Literal["validation", "serialization"]], JsonSchemaValue],
+ dict[str, dict[str, Any]],
]:
schema_generator = GenerateJsonSchema(ref_template=REF_TEMPLATE)
validation_fields = [field for field in fields if field.mode == "validation"]
@@ -324,7 +301,7 @@ def get_definitions(
for field in list(fields) + list(unique_flat_model_fields)
]
field_mapping, definitions = schema_generator.generate_definitions(inputs=inputs)
- for item_def in cast(Dict[str, Dict[str, Any]], definitions).values():
+ for item_def in cast(dict[str, dict[str, Any]], definitions).values():
if "description" in item_def:
item_description = cast(str, item_def["description"]).split("\f")[0]
item_def["description"] = item_description
@@ -338,9 +315,9 @@ def get_definitions(
def _replace_refs(
*,
- schema: Dict[str, Any],
- old_name_to_new_name_map: Dict[str, str],
-) -> Dict[str, Any]:
+ schema: dict[str, Any],
+ old_name_to_new_name_map: dict[str, str],
+) -> dict[str, Any]:
new_schema = deepcopy(schema)
for key, value in new_schema.items():
if key == "$ref":
@@ -375,13 +352,13 @@ def _replace_refs(
def _remap_definitions_and_field_mappings(
*,
model_name_map: ModelNameMap,
- definitions: Dict[str, Any],
- field_mapping: Dict[
- Tuple[ModelField, Literal["validation", "serialization"]], JsonSchemaValue
+ definitions: dict[str, Any],
+ field_mapping: dict[
+ tuple[ModelField, Literal["validation", "serialization"]], JsonSchemaValue
],
-) -> Tuple[
- Dict[Tuple[ModelField, Literal["validation", "serialization"]], JsonSchemaValue],
- Dict[str, Any],
+) -> tuple[
+ dict[tuple[ModelField, Literal["validation", "serialization"]], JsonSchemaValue],
+ dict[str, Any],
]:
old_name_to_new_name_map = {}
for field_key, schema in field_mapping.items():
@@ -394,8 +371,8 @@ def _remap_definitions_and_field_mappings(
continue
old_name_to_new_name_map[old_name] = new_name
- new_field_mapping: Dict[
- Tuple[ModelField, Literal["validation", "serialization"]], JsonSchemaValue
+ new_field_mapping: dict[
+ tuple[ModelField, Literal["validation", "serialization"]], JsonSchemaValue
] = {}
for field_key, schema in field_mapping.items():
new_schema = _replace_refs(
@@ -461,10 +438,10 @@ def serialize_sequence_value(*, field: ModelField, value: Any) -> Sequence[Any]:
origin_type = get_origin(union_arg) or union_arg
break
assert issubclass(origin_type, shared.sequence_types) # type: ignore[arg-type]
- return shared.sequence_annotation_to_type[origin_type](value) # type: ignore[no-any-return]
+ return shared.sequence_annotation_to_type[origin_type](value) # type: ignore[no-any-return,index]
-def get_missing_field_error(loc: Tuple[str, ...]) -> Dict[str, Any]:
+def get_missing_field_error(loc: tuple[str, ...]) -> dict[str, Any]:
error = ValidationError.from_exception_data(
"Field required", [{"type": "missing", "loc": loc, "input": {}}]
).errors(include_url=False)[0]
@@ -474,14 +451,14 @@ def get_missing_field_error(loc: Tuple[str, ...]) -> Dict[str, Any]:
def create_body_model(
*, fields: Sequence[ModelField], model_name: str
-) -> Type[BaseModel]:
+) -> type[BaseModel]:
field_params = {f.name: (f.field_info.annotation, f.field_info) for f in fields}
- BodyModel: Type[BaseModel] = create_model(model_name, **field_params) # type: ignore[call-overload]
+ BodyModel: type[BaseModel] = create_model(model_name, **field_params) # type: ignore[call-overload]
return BodyModel
-def get_model_fields(model: Type[BaseModel]) -> List[ModelField]:
- model_fields: List[ModelField] = []
+def get_model_fields(model: type[BaseModel]) -> list[ModelField]:
+ model_fields: list[ModelField] = []
for name, field_info in model.model_fields.items():
type_ = field_info.annotation
if lenient_issubclass(type_, (BaseModel, dict)) or is_dataclass(type_):
@@ -498,37 +475,43 @@ def get_model_fields(model: Type[BaseModel]) -> List[ModelField]:
return model_fields
+@lru_cache
+def get_cached_model_fields(model: type[BaseModel]) -> list[ModelField]:
+ return get_model_fields(model) # type: ignore[return-value]
+
+
# Duplicate of several schema functions from Pydantic v1 to make them compatible with
# Pydantic v2 and allow mixing the models
-TypeModelOrEnum = Union[Type["BaseModel"], Type[Enum]]
-TypeModelSet = Set[TypeModelOrEnum]
+TypeModelOrEnum = Union[type["BaseModel"], type[Enum]]
+TypeModelSet = set[TypeModelOrEnum]
def normalize_name(name: str) -> str:
return re.sub(r"[^a-zA-Z0-9.\-_]", "_", name)
-def get_model_name_map(unique_models: TypeModelSet) -> Dict[TypeModelOrEnum, str]:
+def get_model_name_map(unique_models: TypeModelSet) -> dict[TypeModelOrEnum, str]:
name_model_map = {}
- conflicting_names: Set[str] = set()
for model in unique_models:
model_name = normalize_name(model.__name__)
- if model_name in conflicting_names:
- model_name = get_long_model_name(model)
- name_model_map[model_name] = model
- elif model_name in name_model_map:
- conflicting_names.add(model_name)
- conflicting_model = name_model_map.pop(model_name)
- name_model_map[get_long_model_name(conflicting_model)] = conflicting_model
- name_model_map[get_long_model_name(model)] = model
- else:
- name_model_map[model_name] = model
+ name_model_map[model_name] = model
return {v: k for k, v in name_model_map.items()}
+def get_compat_model_name_map(fields: list[ModelField]) -> ModelNameMap:
+ all_flat_models = set()
+
+ v2_model_fields = [field for field in fields if isinstance(field, ModelField)]
+ v2_flat_models = get_flat_models_from_fields(v2_model_fields, known_models=set())
+ all_flat_models = all_flat_models.union(v2_flat_models) # type: ignore[arg-type]
+
+ model_name_map = get_model_name_map(all_flat_models) # type: ignore[arg-type]
+ return model_name_map
+
+
def get_flat_models_from_model(
- model: Type["BaseModel"], known_models: Union[TypeModelSet, None] = None
+ model: type["BaseModel"], known_models: Union[TypeModelSet, None] = None
) -> TypeModelSet:
known_models = known_models or set()
fields = get_model_fields(model)
@@ -575,5 +558,11 @@ def get_flat_models_from_fields(
return known_models
-def get_long_model_name(model: TypeModelOrEnum) -> str:
- return f"{model.__module__}__{model.__qualname__}".replace(".", "__")
+def _regenerate_error_with_loc(
+ *, errors: Sequence[Any], loc_prefix: tuple[Union[str, int], ...]
+) -> list[dict[str, Any]]:
+ updated_loc_errors: list[Any] = [
+ {**err, "loc": loc_prefix + err.get("loc", ())} for err in errors
+ ]
+
+ return updated_loc_errors
diff --git a/fastapi/applications.py b/fastapi/applications.py
index 02193312b9..54175cb3b0 100644
--- a/fastapi/applications.py
+++ b/fastapi/applications.py
@@ -1,14 +1,10 @@
+from collections.abc import Awaitable, Coroutine, Sequence
from enum import Enum
from typing import (
+ Annotated,
Any,
- Awaitable,
Callable,
- Coroutine,
- Dict,
- List,
Optional,
- Sequence,
- Type,
TypeVar,
Union,
)
@@ -44,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, ExceptionHandler, Lifespan, Receive, Scope, Send
-from typing_extensions import Annotated, deprecated
+from typing_extensions import deprecated
AppType = TypeVar("AppType", bound="FastAPI")
@@ -81,7 +77,7 @@ class FastAPI(Starlette):
),
] = False,
routes: Annotated[
- Optional[List[BaseRoute]],
+ Optional[list[BaseRoute]],
Doc(
"""
**Note**: you probably shouldn't use this parameter, it is inherited
@@ -230,7 +226,7 @@ class FastAPI(Starlette):
),
] = "/openapi.json",
openapi_tags: Annotated[
- Optional[List[Dict[str, Any]]],
+ Optional[list[dict[str, Any]]],
Doc(
"""
A list of tags used by OpenAPI, these are the same `tags` you can set
@@ -290,7 +286,7 @@ class FastAPI(Starlette):
),
] = None,
servers: Annotated[
- Optional[List[Dict[str, Union[str, Any]]]],
+ Optional[list[dict[str, Union[str, Any]]]],
Doc(
"""
A `list` of `dict`s with connectivity information to a target server.
@@ -361,7 +357,7 @@ class FastAPI(Starlette):
),
] = None,
default_response_class: Annotated[
- Type[Response],
+ type[Response],
Doc(
"""
The default response class to be used.
@@ -467,7 +463,7 @@ class FastAPI(Starlette):
),
] = "/docs/oauth2-redirect",
swagger_ui_init_oauth: Annotated[
- Optional[Dict[str, Any]],
+ Optional[dict[str, Any]],
Doc(
"""
OAuth2 configuration for the Swagger UI, by default shown at `/docs`.
@@ -493,8 +489,8 @@ class FastAPI(Starlette):
] = None,
exception_handlers: Annotated[
Optional[
- Dict[
- Union[int, Type[Exception]],
+ dict[
+ Union[int, type[Exception]],
Callable[[Request, Any], Coroutine[Any, Any, Response]],
]
],
@@ -567,7 +563,7 @@ class FastAPI(Starlette):
),
] = None,
contact: Annotated[
- Optional[Dict[str, Union[str, Any]]],
+ Optional[dict[str, Union[str, Any]]],
Doc(
"""
A dictionary with the contact information for the exposed API.
@@ -600,7 +596,7 @@ class FastAPI(Starlette):
),
] = None,
license_info: Annotated[
- Optional[Dict[str, Union[str, Any]]],
+ Optional[dict[str, Union[str, Any]]],
Doc(
"""
A dictionary with the license information for the exposed API.
@@ -689,7 +685,7 @@ class FastAPI(Starlette):
),
] = True,
responses: Annotated[
- Optional[Dict[Union[int, str], Dict[str, Any]]],
+ Optional[dict[Union[int, str], dict[str, Any]]],
Doc(
"""
Additional responses to be shown in OpenAPI.
@@ -705,7 +701,7 @@ class FastAPI(Starlette):
),
] = None,
callbacks: Annotated[
- Optional[List[BaseRoute]],
+ Optional[list[BaseRoute]],
Doc(
"""
OpenAPI callbacks that should apply to all *path operations*.
@@ -762,7 +758,7 @@ class FastAPI(Starlette):
),
] = True,
swagger_ui_parameters: Annotated[
- Optional[Dict[str, Any]],
+ Optional[dict[str, Any]],
Doc(
"""
Parameters to configure Swagger UI, the autogenerated interactive API
@@ -820,7 +816,7 @@ class FastAPI(Starlette):
),
] = True,
openapi_external_docs: Annotated[
- Optional[Dict[str, Any]],
+ Optional[dict[str, Any]],
Doc(
"""
This field allows you to provide additional external documentation links.
@@ -906,7 +902,7 @@ class FastAPI(Starlette):
"""
),
] = "3.1.0"
- self.openapi_schema: Optional[Dict[str, Any]] = None
+ self.openapi_schema: Optional[dict[str, Any]] = None
if self.openapi_url:
assert self.title, "A title must be provided for OpenAPI, e.g.: 'My API'"
assert self.version, "A version must be provided for OpenAPI, e.g.: '2.1.0'"
@@ -949,7 +945,7 @@ class FastAPI(Starlette):
),
] = State()
self.dependency_overrides: Annotated[
- Dict[Callable[..., Any], Callable[..., Any]],
+ dict[Callable[..., Any], Callable[..., Any]],
Doc(
"""
A dictionary with overrides for the dependencies.
@@ -980,7 +976,7 @@ class FastAPI(Starlette):
responses=responses,
generate_unique_id_function=generate_unique_id_function,
)
- self.exception_handlers: Dict[
+ self.exception_handlers: dict[
Any, Callable[[Request, Any], Union[Response, Awaitable[Response]]]
] = {} if exception_handlers is None else dict(exception_handlers)
self.exception_handlers.setdefault(HTTPException, http_exception_handler)
@@ -993,7 +989,7 @@ class FastAPI(Starlette):
websocket_request_validation_exception_handler, # type: ignore
)
- self.user_middleware: List[Middleware] = (
+ self.user_middleware: list[Middleware] = (
[] if middleware is None else list(middleware)
)
self.middleware_stack: Union[ASGIApp, None] = None
@@ -1047,7 +1043,7 @@ class FastAPI(Starlette):
app = cls(app, *args, **kwargs)
return app
- def openapi(self) -> Dict[str, Any]:
+ def openapi(self) -> dict[str, Any]:
"""
Generate the OpenAPI schema of the application. This is called by FastAPI
internally.
@@ -1145,14 +1141,14 @@ class FastAPI(Starlette):
*,
response_model: Any = Default(None),
status_code: Optional[int] = None,
- tags: Optional[List[Union[str, Enum]]] = None,
+ tags: Optional[list[Union[str, Enum]]] = None,
dependencies: Optional[Sequence[Depends]] = None,
summary: Optional[str] = None,
description: Optional[str] = None,
response_description: str = "Successful Response",
- responses: Optional[Dict[Union[int, str], Dict[str, Any]]] = None,
+ responses: Optional[dict[Union[int, str], dict[str, Any]]] = None,
deprecated: Optional[bool] = None,
- methods: Optional[List[str]] = None,
+ methods: Optional[list[str]] = None,
operation_id: Optional[str] = None,
response_model_include: Optional[IncEx] = None,
response_model_exclude: Optional[IncEx] = None,
@@ -1161,11 +1157,11 @@ class FastAPI(Starlette):
response_model_exclude_defaults: bool = False,
response_model_exclude_none: bool = False,
include_in_schema: bool = True,
- response_class: Union[Type[Response], DefaultPlaceholder] = Default(
+ response_class: Union[type[Response], DefaultPlaceholder] = Default(
JSONResponse
),
name: Optional[str] = None,
- openapi_extra: Optional[Dict[str, Any]] = None,
+ openapi_extra: Optional[dict[str, Any]] = None,
generate_unique_id_function: Callable[[routing.APIRoute], str] = Default(
generate_unique_id
),
@@ -1203,14 +1199,14 @@ class FastAPI(Starlette):
*,
response_model: Any = Default(None),
status_code: Optional[int] = None,
- tags: Optional[List[Union[str, Enum]]] = None,
+ tags: Optional[list[Union[str, Enum]]] = None,
dependencies: Optional[Sequence[Depends]] = None,
summary: Optional[str] = None,
description: Optional[str] = None,
response_description: str = "Successful Response",
- responses: Optional[Dict[Union[int, str], Dict[str, Any]]] = None,
+ responses: Optional[dict[Union[int, str], dict[str, Any]]] = None,
deprecated: Optional[bool] = None,
- methods: Optional[List[str]] = None,
+ methods: Optional[list[str]] = None,
operation_id: Optional[str] = None,
response_model_include: Optional[IncEx] = None,
response_model_exclude: Optional[IncEx] = None,
@@ -1219,9 +1215,9 @@ class FastAPI(Starlette):
response_model_exclude_defaults: bool = False,
response_model_exclude_none: bool = False,
include_in_schema: bool = True,
- response_class: Type[Response] = Default(JSONResponse),
+ response_class: type[Response] = Default(JSONResponse),
name: Optional[str] = None,
- openapi_extra: Optional[Dict[str, Any]] = None,
+ openapi_extra: Optional[dict[str, Any]] = None,
generate_unique_id_function: Callable[[routing.APIRoute], str] = Default(
generate_unique_id
),
@@ -1343,7 +1339,7 @@ class FastAPI(Starlette):
*,
prefix: Annotated[str, Doc("An optional path prefix for the router.")] = "",
tags: Annotated[
- Optional[List[Union[str, Enum]]],
+ Optional[list[Union[str, Enum]]],
Doc(
"""
A list of tags to be applied to all the *path operations* in this
@@ -1385,7 +1381,7 @@ class FastAPI(Starlette):
),
] = None,
responses: Annotated[
- Optional[Dict[Union[int, str], Dict[str, Any]]],
+ Optional[dict[Union[int, str], dict[str, Any]]],
Doc(
"""
Additional responses to be shown in OpenAPI.
@@ -1452,7 +1448,7 @@ class FastAPI(Starlette):
),
] = True,
default_response_class: Annotated[
- Type[Response],
+ type[Response],
Doc(
"""
Default response class to be used for the *path operations* in this
@@ -1480,7 +1476,7 @@ class FastAPI(Starlette):
),
] = Default(JSONResponse),
callbacks: Annotated[
- Optional[List[BaseRoute]],
+ Optional[list[BaseRoute]],
Doc(
"""
List of *path operations* that will be used as OpenAPI callbacks.
@@ -1603,7 +1599,7 @@ class FastAPI(Starlette):
),
] = None,
tags: Annotated[
- Optional[List[Union[str, Enum]]],
+ Optional[list[Union[str, Enum]]],
Doc(
"""
A list of tags to be applied to the *path operation*.
@@ -1669,7 +1665,7 @@ class FastAPI(Starlette):
),
] = "Successful Response",
responses: Annotated[
- Optional[Dict[Union[int, str], Dict[str, Any]]],
+ Optional[dict[Union[int, str], dict[str, Any]]],
Doc(
"""
Additional responses that could be returned by this *path operation*.
@@ -1810,7 +1806,7 @@ class FastAPI(Starlette):
),
] = True,
response_class: Annotated[
- Type[Response],
+ type[Response],
Doc(
"""
Response class to be used for this *path operation*.
@@ -1831,7 +1827,7 @@ class FastAPI(Starlette):
),
] = None,
callbacks: Annotated[
- Optional[List[BaseRoute]],
+ Optional[list[BaseRoute]],
Doc(
"""
List of *path operations* that will be used as OpenAPI callbacks.
@@ -1847,7 +1843,7 @@ class FastAPI(Starlette):
),
] = None,
openapi_extra: Annotated[
- Optional[Dict[str, Any]],
+ Optional[dict[str, Any]],
Doc(
"""
Extra metadata to be included in the OpenAPI schema for this *path
@@ -1976,7 +1972,7 @@ class FastAPI(Starlette):
),
] = None,
tags: Annotated[
- Optional[List[Union[str, Enum]]],
+ Optional[list[Union[str, Enum]]],
Doc(
"""
A list of tags to be applied to the *path operation*.
@@ -2042,7 +2038,7 @@ class FastAPI(Starlette):
),
] = "Successful Response",
responses: Annotated[
- Optional[Dict[Union[int, str], Dict[str, Any]]],
+ Optional[dict[Union[int, str], dict[str, Any]]],
Doc(
"""
Additional responses that could be returned by this *path operation*.
@@ -2183,7 +2179,7 @@ class FastAPI(Starlette):
),
] = True,
response_class: Annotated[
- Type[Response],
+ type[Response],
Doc(
"""
Response class to be used for this *path operation*.
@@ -2204,7 +2200,7 @@ class FastAPI(Starlette):
),
] = None,
callbacks: Annotated[
- Optional[List[BaseRoute]],
+ Optional[list[BaseRoute]],
Doc(
"""
List of *path operations* that will be used as OpenAPI callbacks.
@@ -2220,7 +2216,7 @@ class FastAPI(Starlette):
),
] = None,
openapi_extra: Annotated[
- Optional[Dict[str, Any]],
+ Optional[dict[str, Any]],
Doc(
"""
Extra metadata to be included in the OpenAPI schema for this *path
@@ -2354,7 +2350,7 @@ class FastAPI(Starlette):
),
] = None,
tags: Annotated[
- Optional[List[Union[str, Enum]]],
+ Optional[list[Union[str, Enum]]],
Doc(
"""
A list of tags to be applied to the *path operation*.
@@ -2420,7 +2416,7 @@ class FastAPI(Starlette):
),
] = "Successful Response",
responses: Annotated[
- Optional[Dict[Union[int, str], Dict[str, Any]]],
+ Optional[dict[Union[int, str], dict[str, Any]]],
Doc(
"""
Additional responses that could be returned by this *path operation*.
@@ -2561,7 +2557,7 @@ class FastAPI(Starlette):
),
] = True,
response_class: Annotated[
- Type[Response],
+ type[Response],
Doc(
"""
Response class to be used for this *path operation*.
@@ -2582,7 +2578,7 @@ class FastAPI(Starlette):
),
] = None,
callbacks: Annotated[
- Optional[List[BaseRoute]],
+ Optional[list[BaseRoute]],
Doc(
"""
List of *path operations* that will be used as OpenAPI callbacks.
@@ -2598,7 +2594,7 @@ class FastAPI(Starlette):
),
] = None,
openapi_extra: Annotated[
- Optional[Dict[str, Any]],
+ Optional[dict[str, Any]],
Doc(
"""
Extra metadata to be included in the OpenAPI schema for this *path
@@ -2732,7 +2728,7 @@ class FastAPI(Starlette):
),
] = None,
tags: Annotated[
- Optional[List[Union[str, Enum]]],
+ Optional[list[Union[str, Enum]]],
Doc(
"""
A list of tags to be applied to the *path operation*.
@@ -2798,7 +2794,7 @@ class FastAPI(Starlette):
),
] = "Successful Response",
responses: Annotated[
- Optional[Dict[Union[int, str], Dict[str, Any]]],
+ Optional[dict[Union[int, str], dict[str, Any]]],
Doc(
"""
Additional responses that could be returned by this *path operation*.
@@ -2939,7 +2935,7 @@ class FastAPI(Starlette):
),
] = True,
response_class: Annotated[
- Type[Response],
+ type[Response],
Doc(
"""
Response class to be used for this *path operation*.
@@ -2960,7 +2956,7 @@ class FastAPI(Starlette):
),
] = None,
callbacks: Annotated[
- Optional[List[BaseRoute]],
+ Optional[list[BaseRoute]],
Doc(
"""
List of *path operations* that will be used as OpenAPI callbacks.
@@ -2976,7 +2972,7 @@ class FastAPI(Starlette):
),
] = None,
openapi_extra: Annotated[
- Optional[Dict[str, Any]],
+ Optional[dict[str, Any]],
Doc(
"""
Extra metadata to be included in the OpenAPI schema for this *path
@@ -3105,7 +3101,7 @@ class FastAPI(Starlette):
),
] = None,
tags: Annotated[
- Optional[List[Union[str, Enum]]],
+ Optional[list[Union[str, Enum]]],
Doc(
"""
A list of tags to be applied to the *path operation*.
@@ -3171,7 +3167,7 @@ class FastAPI(Starlette):
),
] = "Successful Response",
responses: Annotated[
- Optional[Dict[Union[int, str], Dict[str, Any]]],
+ Optional[dict[Union[int, str], dict[str, Any]]],
Doc(
"""
Additional responses that could be returned by this *path operation*.
@@ -3312,7 +3308,7 @@ class FastAPI(Starlette):
),
] = True,
response_class: Annotated[
- Type[Response],
+ type[Response],
Doc(
"""
Response class to be used for this *path operation*.
@@ -3333,7 +3329,7 @@ class FastAPI(Starlette):
),
] = None,
callbacks: Annotated[
- Optional[List[BaseRoute]],
+ Optional[list[BaseRoute]],
Doc(
"""
List of *path operations* that will be used as OpenAPI callbacks.
@@ -3349,7 +3345,7 @@ class FastAPI(Starlette):
),
] = None,
openapi_extra: Annotated[
- Optional[Dict[str, Any]],
+ Optional[dict[str, Any]],
Doc(
"""
Extra metadata to be included in the OpenAPI schema for this *path
@@ -3478,7 +3474,7 @@ class FastAPI(Starlette):
),
] = None,
tags: Annotated[
- Optional[List[Union[str, Enum]]],
+ Optional[list[Union[str, Enum]]],
Doc(
"""
A list of tags to be applied to the *path operation*.
@@ -3544,7 +3540,7 @@ class FastAPI(Starlette):
),
] = "Successful Response",
responses: Annotated[
- Optional[Dict[Union[int, str], Dict[str, Any]]],
+ Optional[dict[Union[int, str], dict[str, Any]]],
Doc(
"""
Additional responses that could be returned by this *path operation*.
@@ -3685,7 +3681,7 @@ class FastAPI(Starlette):
),
] = True,
response_class: Annotated[
- Type[Response],
+ type[Response],
Doc(
"""
Response class to be used for this *path operation*.
@@ -3706,7 +3702,7 @@ class FastAPI(Starlette):
),
] = None,
callbacks: Annotated[
- Optional[List[BaseRoute]],
+ Optional[list[BaseRoute]],
Doc(
"""
List of *path operations* that will be used as OpenAPI callbacks.
@@ -3722,7 +3718,7 @@ class FastAPI(Starlette):
),
] = None,
openapi_extra: Annotated[
- Optional[Dict[str, Any]],
+ Optional[dict[str, Any]],
Doc(
"""
Extra metadata to be included in the OpenAPI schema for this *path
@@ -3851,7 +3847,7 @@ class FastAPI(Starlette):
),
] = None,
tags: Annotated[
- Optional[List[Union[str, Enum]]],
+ Optional[list[Union[str, Enum]]],
Doc(
"""
A list of tags to be applied to the *path operation*.
@@ -3917,7 +3913,7 @@ class FastAPI(Starlette):
),
] = "Successful Response",
responses: Annotated[
- Optional[Dict[Union[int, str], Dict[str, Any]]],
+ Optional[dict[Union[int, str], dict[str, Any]]],
Doc(
"""
Additional responses that could be returned by this *path operation*.
@@ -4058,7 +4054,7 @@ class FastAPI(Starlette):
),
] = True,
response_class: Annotated[
- Type[Response],
+ type[Response],
Doc(
"""
Response class to be used for this *path operation*.
@@ -4079,7 +4075,7 @@ class FastAPI(Starlette):
),
] = None,
callbacks: Annotated[
- Optional[List[BaseRoute]],
+ Optional[list[BaseRoute]],
Doc(
"""
List of *path operations* that will be used as OpenAPI callbacks.
@@ -4095,7 +4091,7 @@ class FastAPI(Starlette):
),
] = None,
openapi_extra: Annotated[
- Optional[Dict[str, Any]],
+ Optional[dict[str, Any]],
Doc(
"""
Extra metadata to be included in the OpenAPI schema for this *path
@@ -4229,7 +4225,7 @@ class FastAPI(Starlette):
),
] = None,
tags: Annotated[
- Optional[List[Union[str, Enum]]],
+ Optional[list[Union[str, Enum]]],
Doc(
"""
A list of tags to be applied to the *path operation*.
@@ -4295,7 +4291,7 @@ class FastAPI(Starlette):
),
] = "Successful Response",
responses: Annotated[
- Optional[Dict[Union[int, str], Dict[str, Any]]],
+ Optional[dict[Union[int, str], dict[str, Any]]],
Doc(
"""
Additional responses that could be returned by this *path operation*.
@@ -4436,7 +4432,7 @@ class FastAPI(Starlette):
),
] = True,
response_class: Annotated[
- Type[Response],
+ type[Response],
Doc(
"""
Response class to be used for this *path operation*.
@@ -4457,7 +4453,7 @@ class FastAPI(Starlette):
),
] = None,
callbacks: Annotated[
- Optional[List[BaseRoute]],
+ Optional[list[BaseRoute]],
Doc(
"""
List of *path operations* that will be used as OpenAPI callbacks.
@@ -4473,7 +4469,7 @@ class FastAPI(Starlette):
),
] = None,
openapi_extra: Annotated[
- Optional[Dict[str, Any]],
+ Optional[dict[str, Any]],
Doc(
"""
Extra metadata to be included in the OpenAPI schema for this *path
@@ -4628,7 +4624,7 @@ class FastAPI(Starlette):
def exception_handler(
self,
exc_class_or_status_code: Annotated[
- Union[int, Type[Exception]],
+ Union[int, type[Exception]],
Doc(
"""
The Exception class this would handle, or a status code.
diff --git a/fastapi/background.py b/fastapi/background.py
index 6d4a30d442..20803ba670 100644
--- a/fastapi/background.py
+++ b/fastapi/background.py
@@ -1,8 +1,8 @@
-from typing import Any, Callable
+from typing import Annotated, Any, Callable
from annotated_doc import Doc
from starlette.background import BackgroundTasks as StarletteBackgroundTasks
-from typing_extensions import Annotated, ParamSpec
+from typing_extensions import ParamSpec
P = ParamSpec("P")
diff --git a/fastapi/concurrency.py b/fastapi/concurrency.py
index 3202c70789..76a5a2eb12 100644
--- a/fastapi/concurrency.py
+++ b/fastapi/concurrency.py
@@ -1,5 +1,7 @@
+from collections.abc import AsyncGenerator
+from contextlib import AbstractContextManager
from contextlib import asynccontextmanager as asynccontextmanager
-from typing import AsyncGenerator, ContextManager, TypeVar
+from typing import TypeVar
import anyio.to_thread
from anyio import CapacityLimiter
@@ -14,7 +16,7 @@ _T = TypeVar("_T")
@asynccontextmanager
async def contextmanager_in_threadpool(
- cm: ContextManager[_T],
+ cm: AbstractContextManager[_T],
) -> AsyncGenerator[_T, None]:
# blocking __exit__ from running waiting on a free thread
# can create race conditions/deadlocks if the context manager itself
diff --git a/fastapi/datastructures.py b/fastapi/datastructures.py
index 8ad9aa11a6..2bf5fdb262 100644
--- a/fastapi/datastructures.py
+++ b/fastapi/datastructures.py
@@ -1,21 +1,16 @@
+from collections.abc import Mapping
from typing import (
+ Annotated,
Any,
BinaryIO,
Callable,
- Dict,
- Iterable,
Optional,
- Type,
TypeVar,
cast,
)
from annotated_doc import Doc
-from fastapi._compat import (
- CoreSchema,
- GetJsonSchemaHandler,
- JsonSchemaValue,
-)
+from pydantic import GetJsonSchemaHandler
from starlette.datastructures import URL as URL # noqa: F401
from starlette.datastructures import Address as Address # noqa: F401
from starlette.datastructures import FormData as FormData # noqa: F401
@@ -23,7 +18,6 @@ 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
class UploadFile(StarletteUploadFile):
@@ -137,37 +131,22 @@ class UploadFile(StarletteUploadFile):
"""
return await super().close()
- @classmethod
- def __get_validators__(cls: Type["UploadFile"]) -> Iterable[Callable[..., Any]]:
- yield cls.validate
-
- @classmethod
- def validate(cls: Type["UploadFile"], v: Any) -> Any:
- if not isinstance(v, StarletteUploadFile):
- raise ValueError(f"Expected UploadFile, received: {type(v)}")
- return v
-
@classmethod
def _validate(cls, __input_value: Any, _: Any) -> "UploadFile":
if not isinstance(__input_value, StarletteUploadFile):
raise ValueError(f"Expected UploadFile, received: {type(__input_value)}")
return cast(UploadFile, __input_value)
- # TODO: remove when deprecating Pydantic v1
- @classmethod
- def __modify_schema__(cls, field_schema: Dict[str, Any]) -> None:
- field_schema.update({"type": "string", "format": "binary"})
-
@classmethod
def __get_pydantic_json_schema__(
- cls, core_schema: CoreSchema, handler: GetJsonSchemaHandler
- ) -> JsonSchemaValue:
+ cls, core_schema: Mapping[str, Any], handler: GetJsonSchemaHandler
+ ) -> dict[str, Any]:
return {"type": "string", "format": "binary"}
@classmethod
def __get_pydantic_core_schema__(
- cls, source: Type[Any], handler: Callable[[Any], CoreSchema]
- ) -> CoreSchema:
+ cls, source: type[Any], handler: Callable[[Any], Mapping[str, Any]]
+ ) -> Mapping[str, Any]:
from ._compat.v2 import with_info_plain_validator_function
return with_info_plain_validator_function(cls._validate)
diff --git a/fastapi/dependencies/models.py b/fastapi/dependencies/models.py
index 6c4bf18b37..58392326d6 100644
--- a/fastapi/dependencies/models.py
+++ b/fastapi/dependencies/models.py
@@ -2,7 +2,7 @@ import inspect
import sys
from dataclasses import dataclass, field
from functools import cached_property, partial
-from typing import Any, Callable, List, Optional, Union
+from typing import Any, Callable, Optional, Union
from fastapi._compat import ModelField
from fastapi.security.base import SecurityBase
@@ -30,12 +30,12 @@ def _impartial(func: Callable[..., Any]) -> Callable[..., Any]:
@dataclass
class Dependant:
- path_params: List[ModelField] = field(default_factory=list)
- query_params: List[ModelField] = field(default_factory=list)
- header_params: List[ModelField] = field(default_factory=list)
- cookie_params: List[ModelField] = field(default_factory=list)
- body_params: List[ModelField] = field(default_factory=list)
- dependencies: List["Dependant"] = field(default_factory=list)
+ path_params: list[ModelField] = field(default_factory=list)
+ query_params: list[ModelField] = field(default_factory=list)
+ header_params: list[ModelField] = field(default_factory=list)
+ cookie_params: list[ModelField] = field(default_factory=list)
+ body_params: list[ModelField] = field(default_factory=list)
+ dependencies: list["Dependant"] = field(default_factory=list)
name: Optional[str] = None
call: Optional[Callable[..., Any]] = None
request_param_name: Optional[str] = None
@@ -44,14 +44,14 @@ class Dependant:
response_param_name: Optional[str] = None
background_tasks_param_name: Optional[str] = None
security_scopes_param_name: Optional[str] = None
- own_oauth_scopes: Optional[List[str]] = None
- parent_oauth_scopes: Optional[List[str]] = None
+ own_oauth_scopes: Optional[list[str]] = None
+ parent_oauth_scopes: Optional[list[str]] = None
use_cache: bool = True
path: Optional[str] = None
scope: Union[Literal["function", "request"], None] = None
@cached_property
- def oauth_scopes(self) -> List[str]:
+ def oauth_scopes(self) -> list[str]:
scopes = self.parent_oauth_scopes.copy() if self.parent_oauth_scopes else []
# This doesn't use a set to preserve order, just in case
for scope in self.own_oauth_scopes or []:
@@ -98,7 +98,7 @@ class Dependant:
return unwrapped
@cached_property
- def _security_dependencies(self) -> List["Dependant"]:
+ def _security_dependencies(self) -> list["Dependant"]:
security_deps = [dep for dep in self.dependencies if dep._is_security_scheme]
return security_deps
diff --git a/fastapi/dependencies/utils.py b/fastapi/dependencies/utils.py
index cc7e55b4b0..45e1ff3ed1 100644
--- a/fastapi/dependencies/utils.py
+++ b/fastapi/dependencies/utils.py
@@ -1,21 +1,16 @@
import dataclasses
import inspect
import sys
+from collections.abc import Coroutine, Mapping, Sequence
from contextlib import AsyncExitStack, contextmanager
from copy import copy, deepcopy
from dataclasses import dataclass
from typing import (
+ Annotated,
Any,
Callable,
- Coroutine,
- Dict,
ForwardRef,
- List,
- Mapping,
Optional,
- Sequence,
- Tuple,
- Type,
Union,
cast,
)
@@ -23,17 +18,14 @@ from typing import (
import anyio
from fastapi import params
from fastapi._compat import (
- PYDANTIC_V2,
ModelField,
RequiredParam,
Undefined,
- _is_error_wrapper,
- _is_model_class,
+ _regenerate_error_with_loc,
copy_field_info,
create_body_model,
evaluate_forwardref,
field_annotation_is_scalar,
- get_annotation_from_field_info,
get_cached_model_fields,
get_missing_field_error,
is_bytes_field,
@@ -44,12 +36,10 @@ from fastapi._compat import (
is_uploadfile_or_nonable_uploadfile_annotation,
is_uploadfile_sequence_annotation,
lenient_issubclass,
- may_v1,
sequence_types,
serialize_sequence_value,
value_is_sequence,
)
-from fastapi._compat.shared import annotation_is_pydantic_v1
from fastapi.background import BackgroundTasks
from fastapi.concurrency import (
asynccontextmanager,
@@ -75,9 +65,7 @@ from starlette.datastructures import (
from starlette.requests import HTTPConnection, Request
from starlette.responses import Response
from starlette.websockets import WebSocket
-from typing_extensions import Annotated, Literal, get_args, get_origin
-
-from .. import temp_pydantic_v1_params
+from typing_extensions import Literal, get_args, get_origin
multipart_not_installed_error = (
'Form data requires "python-multipart" to be installed. \n'
@@ -125,7 +113,7 @@ def get_parameterless_sub_dependant(*, depends: params.Depends, path: str) -> De
assert callable(depends.dependency), (
"A parameter-less dependency must have a callable dependency"
)
- own_oauth_scopes: List[str] = []
+ own_oauth_scopes: list[str] = []
if isinstance(depends, params.Security) and depends.scopes:
own_oauth_scopes.extend(depends.scopes)
return get_dependant(
@@ -140,8 +128,8 @@ def get_flat_dependant(
dependant: Dependant,
*,
skip_repeats: bool = False,
- visited: Optional[List[DependencyCacheKey]] = None,
- parent_oauth_scopes: Optional[List[str]] = None,
+ visited: Optional[list[DependencyCacheKey]] = None,
+ parent_oauth_scopes: Optional[list[str]] = None,
) -> Dependant:
if visited is None:
visited = []
@@ -190,17 +178,17 @@ def get_flat_dependant(
return flat_dependant
-def _get_flat_fields_from_params(fields: List[ModelField]) -> List[ModelField]:
+def _get_flat_fields_from_params(fields: list[ModelField]) -> list[ModelField]:
if not fields:
return fields
first_field = fields[0]
- if len(fields) == 1 and _is_model_class(first_field.type_):
+ if len(fields) == 1 and lenient_issubclass(first_field.type_, BaseModel):
fields_to_extract = get_cached_model_fields(first_field.type_)
return fields_to_extract
return fields
-def get_flat_params(dependant: Dependant) -> List[ModelField]:
+def get_flat_params(dependant: Dependant) -> list[ModelField]:
flat_dependant = get_flat_dependant(dependant, skip_repeats=True)
path_params = _get_flat_fields_from_params(flat_dependant.path_params)
query_params = _get_flat_fields_from_params(flat_dependant.query_params)
@@ -239,7 +227,7 @@ def get_typed_signature(call: Callable[..., Any]) -> inspect.Signature:
return typed_signature
-def get_typed_annotation(annotation: Any, globalns: Dict[str, Any]) -> Any:
+def get_typed_annotation(annotation: Any, globalns: dict[str, Any]) -> Any:
if isinstance(annotation, str):
annotation = ForwardRef(annotation)
annotation = evaluate_forwardref(annotation, globalns, globalns)
@@ -265,8 +253,8 @@ def get_dependant(
path: str,
call: Callable[..., Any],
name: Optional[str] = None,
- own_oauth_scopes: Optional[List[str]] = None,
- parent_oauth_scopes: Optional[List[str]] = None,
+ own_oauth_scopes: Optional[list[str]] = None,
+ parent_oauth_scopes: Optional[list[str]] = None,
use_cache: bool = True,
scope: Union[Literal["function", "request"], None] = None,
) -> Dependant:
@@ -303,7 +291,7 @@ def get_dependant(
f'The dependency "{dependant.call.__name__}" has a scope of '
'"request", it cannot depend on dependencies with scope "function".'
)
- sub_own_oauth_scopes: List[str] = []
+ sub_own_oauth_scopes: list[str] = []
if isinstance(param_details.depends, params.Security):
if param_details.depends.scopes:
sub_own_oauth_scopes = list(param_details.depends.scopes)
@@ -328,9 +316,7 @@ def get_dependant(
)
continue
assert param_details.field is not None
- if isinstance(
- param_details.field.field_info, (params.Body, temp_pydantic_v1_params.Body)
- ):
+ if isinstance(param_details.field.field_info, params.Body):
dependant.body_params.append(param_details.field)
else:
add_param_to_fields(field=param_details.field, dependant=dependant)
@@ -389,7 +375,7 @@ def analyze_param(
fastapi_annotations = [
arg
for arg in annotated_args[1:]
- if isinstance(arg, (FieldInfo, may_v1.FieldInfo, params.Depends))
+ if isinstance(arg, (FieldInfo, params.Depends))
]
fastapi_specific_annotations = [
arg
@@ -398,29 +384,27 @@ def analyze_param(
arg,
(
params.Param,
- temp_pydantic_v1_params.Param,
params.Body,
- temp_pydantic_v1_params.Body,
params.Depends,
),
)
]
if fastapi_specific_annotations:
- fastapi_annotation: Union[
- FieldInfo, may_v1.FieldInfo, params.Depends, None
- ] = fastapi_specific_annotations[-1]
+ fastapi_annotation: Union[FieldInfo, params.Depends, None] = (
+ fastapi_specific_annotations[-1]
+ )
else:
fastapi_annotation = None
# Set default for Annotated FieldInfo
- if isinstance(fastapi_annotation, (FieldInfo, may_v1.FieldInfo)):
+ if isinstance(fastapi_annotation, FieldInfo):
# Copy `field_info` because we mutate `field_info.default` below.
field_info = copy_field_info(
- field_info=fastapi_annotation, annotation=use_annotation
+ field_info=fastapi_annotation, # type: ignore[arg-type]
+ annotation=use_annotation,
)
- assert field_info.default in {
- Undefined,
- may_v1.Undefined,
- } or field_info.default in {RequiredParam, may_v1.RequiredParam}, (
+ assert (
+ field_info.default == Undefined or field_info.default == RequiredParam
+ ), (
f"`{field_info.__class__.__name__}` default value cannot be set in"
f" `Annotated` for {param_name!r}. Set the default value with `=` instead."
)
@@ -444,15 +428,14 @@ def analyze_param(
)
depends = value
# Get FieldInfo from default value
- elif isinstance(value, (FieldInfo, may_v1.FieldInfo)):
+ elif isinstance(value, FieldInfo):
assert field_info is None, (
"Cannot specify FastAPI annotations in `Annotated` and default value"
f" together for {param_name!r}"
)
- field_info = value
- if PYDANTIC_V2:
- if isinstance(field_info, FieldInfo):
- field_info.annotation = type_annotation
+ field_info = value # type: ignore[assignment]
+ if isinstance(field_info, FieldInfo):
+ field_info.annotation = type_annotation
# Get Depends from type annotation
if depends is not None and depends.dependency is None:
@@ -489,14 +472,7 @@ def analyze_param(
) or is_uploadfile_sequence_annotation(type_annotation):
field_info = params.File(annotation=use_annotation, default=default_value)
elif not field_annotation_is_scalar(annotation=type_annotation):
- if annotation_is_pydantic_v1(use_annotation):
- field_info = temp_pydantic_v1_params.Body(
- annotation=use_annotation, default=default_value
- )
- else:
- field_info = params.Body(
- annotation=use_annotation, default=default_value
- )
+ field_info = params.Body(annotation=use_annotation, default=default_value)
else:
field_info = params.Query(annotation=use_annotation, default=default_value)
@@ -505,23 +481,17 @@ def analyze_param(
if field_info is not None:
# Handle field_info.in_
if is_path_param:
- assert isinstance(
- field_info, (params.Path, temp_pydantic_v1_params.Path)
- ), (
+ assert isinstance(field_info, params.Path), (
f"Cannot use `{field_info.__class__.__name__}` for path param"
f" {param_name!r}"
)
elif (
- isinstance(field_info, (params.Param, temp_pydantic_v1_params.Param))
+ isinstance(field_info, params.Param)
and getattr(field_info, "in_", None) is None
):
field_info.in_ = params.ParamTypes.query
- use_annotation_from_field_info = get_annotation_from_field_info(
- use_annotation,
- field_info,
- param_name,
- )
- if isinstance(field_info, (params.Form, temp_pydantic_v1_params.Form)):
+ use_annotation_from_field_info = use_annotation
+ if isinstance(field_info, params.Form):
ensure_multipart_is_installed()
if not field_info.alias and getattr(field_info, "convert_underscores", None):
alias = param_name.replace("_", "-")
@@ -533,20 +503,19 @@ def analyze_param(
type_=use_annotation_from_field_info,
default=field_info.default,
alias=alias,
- required=field_info.default
- in (RequiredParam, may_v1.RequiredParam, Undefined),
+ required=field_info.default in (RequiredParam, Undefined),
field_info=field_info,
)
if is_path_param:
assert is_scalar_field(field=field), (
"Path params must be of one of the supported types"
)
- elif isinstance(field_info, (params.Query, temp_pydantic_v1_params.Query)):
+ elif isinstance(field_info, params.Query):
assert (
is_scalar_field(field)
or is_scalar_sequence_field(field)
or (
- _is_model_class(field.type_)
+ lenient_issubclass(field.type_, BaseModel)
# For Pydantic v1
and getattr(field, "shape", 1) == 1
)
@@ -572,7 +541,7 @@ def add_param_to_fields(*, field: ModelField, dependant: Dependant) -> None:
async def _solve_generator(
- *, dependant: Dependant, stack: AsyncExitStack, sub_values: Dict[str, Any]
+ *, dependant: Dependant, stack: AsyncExitStack, sub_values: dict[str, Any]
) -> Any:
assert dependant.call
if dependant.is_async_gen_callable:
@@ -584,22 +553,22 @@ async def _solve_generator(
@dataclass
class SolvedDependency:
- values: Dict[str, Any]
- errors: List[Any]
+ values: dict[str, Any]
+ errors: list[Any]
background_tasks: Optional[StarletteBackgroundTasks]
response: Response
- dependency_cache: Dict[DependencyCacheKey, Any]
+ dependency_cache: dict[DependencyCacheKey, Any]
async def solve_dependencies(
*,
request: Union[Request, WebSocket],
dependant: Dependant,
- body: Optional[Union[Dict[str, Any], FormData]] = None,
+ body: Optional[Union[dict[str, Any], FormData]] = None,
background_tasks: Optional[StarletteBackgroundTasks] = None,
response: Optional[Response] = None,
dependency_overrides_provider: Optional[Any] = None,
- dependency_cache: Optional[Dict[DependencyCacheKey, Any]] = None,
+ dependency_cache: Optional[dict[DependencyCacheKey, Any]] = None,
# TODO: remove this parameter later, no longer used, not removing it yet as some
# people might be monkey patching this function (although that's not supported)
async_exit_stack: AsyncExitStack,
@@ -613,8 +582,8 @@ async def solve_dependencies(
assert isinstance(function_astack, AsyncExitStack), (
"fastapi_function_astack not found in request scope"
)
- values: Dict[str, Any] = {}
- errors: List[Any] = []
+ values: dict[str, Any] = {}
+ errors: list[Any] = []
if response is None:
response = Response()
del response.headers["content-length"]
@@ -732,18 +701,16 @@ async def solve_dependencies(
def _validate_value_with_model_field(
- *, field: ModelField, value: Any, values: Dict[str, Any], loc: Tuple[str, ...]
-) -> Tuple[Any, List[Any]]:
+ *, field: ModelField, value: Any, values: dict[str, Any], loc: tuple[str, ...]
+) -> tuple[Any, list[Any]]:
if value is None:
if field.required:
return None, [get_missing_field_error(loc=loc)]
else:
return deepcopy(field.default), []
v_, errors_ = field.validate(value, values, loc=loc)
- if _is_error_wrapper(errors_): # type: ignore[arg-type]
- return None, [errors_]
- elif isinstance(errors_, list):
- new_errors = may_v1._regenerate_error_with_loc(errors=errors_, loc_prefix=())
+ if isinstance(errors_, list):
+ new_errors = _regenerate_error_with_loc(errors=errors_, loc_prefix=())
return None, new_errors
else:
return v_, []
@@ -760,7 +727,7 @@ def _get_multidict_value(
if (
value is None
or (
- isinstance(field.field_info, (params.Form, temp_pydantic_v1_params.Form))
+ isinstance(field.field_info, params.Form)
and isinstance(value, str) # For type checks
and value == ""
)
@@ -776,9 +743,9 @@ def _get_multidict_value(
def request_params_to_args(
fields: Sequence[ModelField],
received_params: Union[Mapping[str, Any], QueryParams, Headers],
-) -> Tuple[Dict[str, Any], List[Any]]:
- values: Dict[str, Any] = {}
- errors: List[Dict[str, Any]] = []
+) -> tuple[dict[str, Any], list[Any]]:
+ values: dict[str, Any] = {}
+ errors: list[dict[str, Any]] = []
if not fields:
return values, errors
@@ -796,7 +763,7 @@ def request_params_to_args(
first_field.field_info, "convert_underscores", True
)
- params_to_process: Dict[str, Any] = {}
+ params_to_process: dict[str, Any] = {}
processed_keys = set()
@@ -830,10 +797,10 @@ def request_params_to_args(
if single_not_embedded_field:
field_info = first_field.field_info
- assert isinstance(field_info, (params.Param, temp_pydantic_v1_params.Param)), (
+ assert isinstance(field_info, params.Param), (
"Params must be subclasses of Param"
)
- loc: Tuple[str, ...] = (field_info.in_.value,)
+ loc: tuple[str, ...] = (field_info.in_.value,)
v_, errors_ = _validate_value_with_model_field(
field=first_field, value=params_to_process, values=values, loc=loc
)
@@ -842,7 +809,7 @@ def request_params_to_args(
for field in fields:
value = _get_multidict_value(field, received_params)
field_info = field.field_info
- assert isinstance(field_info, (params.Param, temp_pydantic_v1_params.Param)), (
+ assert isinstance(field_info, params.Param), (
"Params must be subclasses of Param"
)
loc = (field_info.in_.value, get_validation_alias(field))
@@ -869,13 +836,13 @@ def is_union_of_base_models(field_type: Any) -> bool:
union_args = get_args(field_type)
for arg in union_args:
- if not _is_model_class(arg):
+ if not lenient_issubclass(arg, BaseModel):
return False
return True
-def _should_embed_body_fields(fields: List[ModelField]) -> bool:
+def _should_embed_body_fields(fields: list[ModelField]) -> bool:
if not fields:
return False
# More than one dependency could have the same field, it would show up as multiple
@@ -891,8 +858,8 @@ def _should_embed_body_fields(fields: List[ModelField]) -> bool:
# If it's a Form (or File) field, it has to be a BaseModel (or a union of BaseModels) to be top level
# otherwise it has to be embedded, so that the key value pair can be extracted
if (
- isinstance(first_field.field_info, (params.Form, temp_pydantic_v1_params.Form))
- and not _is_model_class(first_field.type_)
+ isinstance(first_field.field_info, params.Form)
+ and not lenient_issubclass(first_field.type_, BaseModel)
and not is_union_of_base_models(first_field.type_)
):
return True
@@ -900,28 +867,28 @@ def _should_embed_body_fields(fields: List[ModelField]) -> bool:
async def _extract_form_body(
- body_fields: List[ModelField],
+ body_fields: list[ModelField],
received_body: FormData,
-) -> Dict[str, Any]:
+) -> dict[str, Any]:
values = {}
for field in body_fields:
value = _get_multidict_value(field, received_body)
field_info = field.field_info
if (
- isinstance(field_info, (params.File, temp_pydantic_v1_params.File))
+ isinstance(field_info, params.File)
and is_bytes_field(field)
and isinstance(value, UploadFile)
):
value = await value.read()
elif (
is_bytes_sequence_field(field)
- and isinstance(field_info, (params.File, temp_pydantic_v1_params.File))
+ and isinstance(field_info, params.File)
and value_is_sequence(value)
):
# For types
- assert isinstance(value, sequence_types) # type: ignore[arg-type]
- results: List[Union[bytes, str]] = []
+ assert isinstance(value, sequence_types)
+ results: list[Union[bytes, str]] = []
async def process_fn(
fn: Callable[[], Coroutine[Any, Any, Any]],
@@ -947,22 +914,22 @@ async def _extract_form_body(
async def request_body_to_args(
- body_fields: List[ModelField],
- received_body: Optional[Union[Dict[str, Any], FormData]],
+ body_fields: list[ModelField],
+ received_body: Optional[Union[dict[str, Any], FormData]],
embed_body_fields: bool,
-) -> Tuple[Dict[str, Any], List[Dict[str, Any]]]:
- values: Dict[str, Any] = {}
- errors: List[Dict[str, Any]] = []
+) -> tuple[dict[str, Any], list[dict[str, Any]]]:
+ values: dict[str, Any] = {}
+ errors: list[dict[str, Any]] = []
assert body_fields, "request_body_to_args() should be called with fields"
single_not_embedded_field = len(body_fields) == 1 and not embed_body_fields
first_field = body_fields[0]
body_to_process = received_body
- fields_to_extract: List[ModelField] = body_fields
+ fields_to_extract: list[ModelField] = body_fields
if (
single_not_embedded_field
- and _is_model_class(first_field.type_)
+ and lenient_issubclass(first_field.type_, BaseModel)
and isinstance(received_body, FormData)
):
fields_to_extract = get_cached_model_fields(first_field.type_)
@@ -971,7 +938,7 @@ async def request_body_to_args(
body_to_process = await _extract_form_body(fields_to_extract, received_body)
if single_not_embedded_field:
- loc: Tuple[str, ...] = ("body",)
+ loc: tuple[str, ...] = ("body",)
v_, errors_ = _validate_value_with_model_field(
field=first_field, value=body_to_process, values=values, loc=loc
)
@@ -1019,36 +986,23 @@ def get_body_field(
fields=flat_dependant.body_params, model_name=model_name
)
required = any(True for f in flat_dependant.body_params if f.required)
- BodyFieldInfo_kwargs: Dict[str, Any] = {
+ BodyFieldInfo_kwargs: dict[str, Any] = {
"annotation": BodyModel,
"alias": "body",
}
if not required:
BodyFieldInfo_kwargs["default"] = None
if any(isinstance(f.field_info, params.File) for f in flat_dependant.body_params):
- BodyFieldInfo: Type[params.Body] = params.File
- elif any(
- isinstance(f.field_info, temp_pydantic_v1_params.File)
- for f in flat_dependant.body_params
- ):
- BodyFieldInfo: Type[temp_pydantic_v1_params.Body] = temp_pydantic_v1_params.File # type: ignore[no-redef]
+ BodyFieldInfo: type[params.Body] = params.File
elif any(isinstance(f.field_info, params.Form) for f in flat_dependant.body_params):
BodyFieldInfo = params.Form
- elif any(
- isinstance(f.field_info, temp_pydantic_v1_params.Form)
- for f in flat_dependant.body_params
- ):
- BodyFieldInfo = temp_pydantic_v1_params.Form # type: ignore[assignment]
else:
- if annotation_is_pydantic_v1(BodyModel):
- BodyFieldInfo = temp_pydantic_v1_params.Body # type: ignore[assignment]
- else:
- BodyFieldInfo = params.Body
+ BodyFieldInfo = params.Body
body_param_media_types = [
f.field_info.media_type
for f in flat_dependant.body_params
- if isinstance(f.field_info, (params.Body, temp_pydantic_v1_params.Body))
+ if isinstance(f.field_info, params.Body)
]
if len(set(body_param_media_types)) == 1:
BodyFieldInfo_kwargs["media_type"] = body_param_media_types[0]
diff --git a/fastapi/encoders.py b/fastapi/encoders.py
index 7939510895..e8610c983b 100644
--- a/fastapi/encoders.py
+++ b/fastapi/encoders.py
@@ -14,19 +14,22 @@ from ipaddress import (
from pathlib import Path, PurePath
from re import Pattern
from types import GeneratorType
-from typing import Any, Callable, Dict, List, Optional, Tuple, Type, Union
+from typing import Annotated, Any, Callable, Optional, Union
from uuid import UUID
from annotated_doc import Doc
-from fastapi._compat import may_v1
+from fastapi.exceptions import PydanticV1NotSupportedError
from fastapi.types import IncEx
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
+from pydantic_core import PydanticUndefinedType
-from ._compat import Url, _is_undefined, _model_dump
+from ._compat import (
+ Url,
+ is_pydantic_v1_model_instance,
+)
# Taken from Pydantic v1 as is
@@ -61,10 +64,9 @@ def decimal_encoder(dec_value: Decimal) -> Union[int, float]:
return float(dec_value)
-ENCODERS_BY_TYPE: Dict[Type[Any], Callable[[Any], Any]] = {
+ENCODERS_BY_TYPE: dict[type[Any], Callable[[Any], Any]] = {
bytes: lambda o: o.decode(),
Color: str,
- may_v1.Color: str,
datetime.date: isoformat,
datetime.datetime: isoformat,
datetime.time: isoformat,
@@ -81,26 +83,21 @@ ENCODERS_BY_TYPE: Dict[Type[Any], Callable[[Any], Any]] = {
IPv6Interface: str,
IPv6Network: str,
NameEmail: str,
- may_v1.NameEmail: str,
Path: str,
Pattern: lambda o: o.pattern,
SecretBytes: str,
- may_v1.SecretBytes: str,
SecretStr: str,
- may_v1.SecretStr: str,
set: list,
UUID: str,
Url: str,
- may_v1.Url: str,
AnyUrl: str,
- may_v1.AnyUrl: str,
}
def generate_encoders_by_class_tuples(
- type_encoder_map: Dict[Any, Callable[[Any], Any]],
-) -> Dict[Callable[[Any], Any], Tuple[Any, ...]]:
- encoders_by_class_tuples: Dict[Callable[[Any], Any], Tuple[Any, ...]] = defaultdict(
+ type_encoder_map: dict[Any, Callable[[Any], Any]],
+) -> dict[Callable[[Any], Any], tuple[Any, ...]]:
+ encoders_by_class_tuples: dict[Callable[[Any], Any], tuple[Any, ...]] = defaultdict(
tuple
)
for type_, encoder in type_encoder_map.items():
@@ -180,7 +177,7 @@ def jsonable_encoder(
),
] = False,
custom_encoder: Annotated[
- Optional[Dict[Any, Callable[[Any], Any]]],
+ Optional[dict[Any, Callable[[Any], Any]]],
Doc(
"""
Pydantic's `custom_encoder` parameter, passed to Pydantic models to define
@@ -225,15 +222,8 @@ def jsonable_encoder(
include = set(include)
if exclude is not None and not isinstance(exclude, (set, dict)):
exclude = set(exclude)
- if isinstance(obj, (BaseModel, may_v1.BaseModel)):
- # TODO: remove when deprecating Pydantic v1
- encoders: Dict[Any, Any] = {}
- if isinstance(obj, may_v1.BaseModel):
- encoders = getattr(obj.__config__, "json_encoders", {}) # type: ignore[attr-defined]
- if custom_encoder:
- encoders = {**encoders, **custom_encoder}
- obj_dict = _model_dump(
- obj,
+ if isinstance(obj, BaseModel):
+ obj_dict = obj.model_dump(
mode="json",
include=include,
exclude=exclude,
@@ -242,14 +232,10 @@ def jsonable_encoder(
exclude_none=exclude_none,
exclude_defaults=exclude_defaults,
)
- if "__root__" in obj_dict:
- obj_dict = obj_dict["__root__"]
return jsonable_encoder(
obj_dict,
exclude_none=exclude_none,
exclude_defaults=exclude_defaults,
- # TODO: remove when deprecating Pydantic v1
- custom_encoder=encoders,
sqlalchemy_safe=sqlalchemy_safe,
)
if dataclasses.is_dataclass(obj):
@@ -272,7 +258,7 @@ def jsonable_encoder(
return str(obj)
if isinstance(obj, (str, int, float, type(None))):
return obj
- if _is_undefined(obj):
+ if isinstance(obj, PydanticUndefinedType):
return None
if isinstance(obj, dict):
encoded_dict = {}
@@ -332,11 +318,15 @@ def jsonable_encoder(
for encoder, classes_tuple in encoders_by_class_tuples.items():
if isinstance(obj, classes_tuple):
return encoder(obj)
-
+ if is_pydantic_v1_model_instance(obj):
+ raise PydanticV1NotSupportedError(
+ "pydantic.v1 models are no longer supported by FastAPI."
+ f" Please update the model {obj!r}."
+ )
try:
data = dict(obj)
except Exception as e:
- errors: List[Exception] = []
+ errors: list[Exception] = []
errors.append(e)
try:
data = vars(obj)
diff --git a/fastapi/exceptions.py b/fastapi/exceptions.py
index a46e823506..1a3abd80c2 100644
--- a/fastapi/exceptions.py
+++ b/fastapi/exceptions.py
@@ -1,10 +1,10 @@
-from typing import Any, Dict, Optional, Sequence, Type, TypedDict, Union
+from collections.abc import Sequence
+from typing import Annotated, Any, Optional, TypedDict, Union
from annotated_doc import Doc
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
class EndpointContext(TypedDict, total=False):
@@ -62,7 +62,7 @@ class HTTPException(StarletteHTTPException):
),
] = None,
headers: Annotated[
- Optional[Dict[str, str]],
+ Optional[dict[str, str]],
Doc(
"""
Any headers to send to the client in the response.
@@ -144,8 +144,8 @@ class WebSocketException(StarletteWebSocketException):
super().__init__(code=code, reason=reason)
-RequestErrorModel: Type[BaseModel] = create_model("Request")
-WebSocketErrorModel: Type[BaseModel] = create_model("WebSocket")
+RequestErrorModel: type[BaseModel] = create_model("Request")
+WebSocketErrorModel: type[BaseModel] = create_model("WebSocket")
class FastAPIError(RuntimeError):
@@ -231,3 +231,16 @@ class ResponseValidationError(ValidationException):
) -> None:
super().__init__(errors, endpoint_ctx=endpoint_ctx)
self.body = body
+
+
+class PydanticV1NotSupportedError(FastAPIError):
+ """
+ A pydantic.v1 model is used, which is no longer supported.
+ """
+
+
+class FastAPIDeprecationWarning(UserWarning):
+ """
+ A custom deprecation warning as DeprecationWarning is ignored
+ Ref: https://sethmlarson.dev/deprecations-via-warnings-dont-work-for-python-libraries
+ """
diff --git a/fastapi/openapi/docs.py b/fastapi/openapi/docs.py
index 74b23a3706..82380f85d9 100644
--- a/fastapi/openapi/docs.py
+++ b/fastapi/openapi/docs.py
@@ -1,13 +1,12 @@
import json
-from typing import Any, Dict, Optional
+from typing import Annotated, Any, Optional
from annotated_doc import Doc
from fastapi.encoders import jsonable_encoder
from starlette.responses import HTMLResponse
-from typing_extensions import Annotated
swagger_ui_default_parameters: Annotated[
- Dict[str, Any],
+ dict[str, Any],
Doc(
"""
Default configurations for Swagger UI.
@@ -82,7 +81,7 @@ def get_swagger_ui_html(
),
] = None,
init_oauth: Annotated[
- Optional[Dict[str, Any]],
+ Optional[dict[str, Any]],
Doc(
"""
A dictionary with Swagger UI OAuth2 initialization configurations.
@@ -90,7 +89,7 @@ def get_swagger_ui_html(
),
] = None,
swagger_ui_parameters: Annotated[
- Optional[Dict[str, Any]],
+ Optional[dict[str, Any]],
Doc(
"""
Configuration parameters for Swagger UI.
diff --git a/fastapi/openapi/models.py b/fastapi/openapi/models.py
index 81d276aed6..ac6a6d52c3 100644
--- a/fastapi/openapi/models.py
+++ b/fastapi/openapi/models.py
@@ -1,17 +1,16 @@
+from collections.abc import Iterable, Mapping
from enum import Enum
-from typing import Any, Callable, Dict, Iterable, List, Optional, Set, Type, Union
+from typing import Annotated, Any, Callable, Optional, Union
-from fastapi._compat import (
- PYDANTIC_V2,
- CoreSchema,
- GetJsonSchemaHandler,
- JsonSchemaValue,
- _model_rebuild,
- with_info_plain_validator_function,
-)
+from fastapi._compat import with_info_plain_validator_function
from fastapi.logger import logger
-from pydantic import AnyUrl, BaseModel, Field
-from typing_extensions import Annotated, Literal, TypedDict
+from pydantic import (
+ AnyUrl,
+ BaseModel,
+ Field,
+ GetJsonSchemaHandler,
+)
+from typing_extensions import Literal, TypedDict
from typing_extensions import deprecated as typing_deprecated
try:
@@ -44,25 +43,19 @@ except ImportError: # pragma: no cover
@classmethod
def __get_pydantic_json_schema__(
- cls, core_schema: CoreSchema, handler: GetJsonSchemaHandler
- ) -> JsonSchemaValue:
+ cls, core_schema: Mapping[str, Any], handler: GetJsonSchemaHandler
+ ) -> dict[str, Any]:
return {"type": "string", "format": "email"}
@classmethod
def __get_pydantic_core_schema__(
- cls, source: Type[Any], handler: Callable[[Any], CoreSchema]
- ) -> CoreSchema:
+ cls, source: type[Any], handler: Callable[[Any], Mapping[str, Any]]
+ ) -> Mapping[str, Any]:
return with_info_plain_validator_function(cls._validate)
class BaseModelWithConfig(BaseModel):
- if PYDANTIC_V2:
- model_config = {"extra": "allow"}
-
- else:
-
- class Config:
- extra = "allow"
+ model_config = {"extra": "allow"}
class Contact(BaseModelWithConfig):
@@ -88,7 +81,7 @@ class Info(BaseModelWithConfig):
class ServerVariable(BaseModelWithConfig):
- enum: Annotated[Optional[List[str]], Field(min_length=1)] = None
+ enum: Annotated[Optional[list[str]], Field(min_length=1)] = None
default: str
description: Optional[str] = None
@@ -96,7 +89,7 @@ class ServerVariable(BaseModelWithConfig):
class Server(BaseModelWithConfig):
url: Union[AnyUrl, str]
description: Optional[str] = None
- variables: Optional[Dict[str, ServerVariable]] = None
+ variables: Optional[dict[str, ServerVariable]] = None
class Reference(BaseModel):
@@ -105,7 +98,7 @@ class Reference(BaseModel):
class Discriminator(BaseModel):
propertyName: str
- mapping: Optional[Dict[str, str]] = None
+ mapping: Optional[dict[str, str]] = None
class XML(BaseModelWithConfig):
@@ -137,34 +130,34 @@ class Schema(BaseModelWithConfig):
dynamicAnchor: Optional[str] = Field(default=None, alias="$dynamicAnchor")
ref: Optional[str] = Field(default=None, alias="$ref")
dynamicRef: Optional[str] = Field(default=None, alias="$dynamicRef")
- defs: Optional[Dict[str, "SchemaOrBool"]] = Field(default=None, alias="$defs")
+ defs: Optional[dict[str, "SchemaOrBool"]] = Field(default=None, alias="$defs")
comment: Optional[str] = Field(default=None, alias="$comment")
# Ref: JSON Schema 2020-12: https://json-schema.org/draft/2020-12/json-schema-core.html#name-a-vocabulary-for-applying-s
# A Vocabulary for Applying Subschemas
- allOf: Optional[List["SchemaOrBool"]] = None
- anyOf: Optional[List["SchemaOrBool"]] = None
- oneOf: Optional[List["SchemaOrBool"]] = None
+ allOf: Optional[list["SchemaOrBool"]] = None
+ anyOf: Optional[list["SchemaOrBool"]] = None
+ oneOf: Optional[list["SchemaOrBool"]] = None
not_: Optional["SchemaOrBool"] = Field(default=None, alias="not")
if_: Optional["SchemaOrBool"] = Field(default=None, alias="if")
then: Optional["SchemaOrBool"] = None
else_: Optional["SchemaOrBool"] = Field(default=None, alias="else")
- dependentSchemas: Optional[Dict[str, "SchemaOrBool"]] = None
- prefixItems: Optional[List["SchemaOrBool"]] = None
+ dependentSchemas: Optional[dict[str, "SchemaOrBool"]] = None
+ prefixItems: Optional[list["SchemaOrBool"]] = None
# TODO: uncomment and remove below when deprecating Pydantic v1
# It generates a list of schemas for tuples, before prefixItems was available
# items: Optional["SchemaOrBool"] = None
- items: Optional[Union["SchemaOrBool", List["SchemaOrBool"]]] = None
+ items: Optional[Union["SchemaOrBool", list["SchemaOrBool"]]] = None
contains: Optional["SchemaOrBool"] = None
- properties: Optional[Dict[str, "SchemaOrBool"]] = None
- patternProperties: Optional[Dict[str, "SchemaOrBool"]] = None
+ properties: Optional[dict[str, "SchemaOrBool"]] = None
+ patternProperties: Optional[dict[str, "SchemaOrBool"]] = None
additionalProperties: Optional["SchemaOrBool"] = None
propertyNames: Optional["SchemaOrBool"] = None
unevaluatedItems: Optional["SchemaOrBool"] = None
unevaluatedProperties: Optional["SchemaOrBool"] = None
# Ref: JSON Schema Validation 2020-12: https://json-schema.org/draft/2020-12/json-schema-validation.html#name-a-vocabulary-for-structural
# A Vocabulary for Structural Validation
- type: Optional[Union[SchemaType, List[SchemaType]]] = None
- enum: Optional[List[Any]] = None
+ type: Optional[Union[SchemaType, list[SchemaType]]] = None
+ enum: Optional[list[Any]] = None
const: Optional[Any] = None
multipleOf: Optional[float] = Field(default=None, gt=0)
maximum: Optional[float] = None
@@ -181,8 +174,8 @@ class Schema(BaseModelWithConfig):
minContains: Optional[int] = Field(default=None, ge=0)
maxProperties: Optional[int] = Field(default=None, ge=0)
minProperties: Optional[int] = Field(default=None, ge=0)
- required: Optional[List[str]] = None
- dependentRequired: Optional[Dict[str, Set[str]]] = None
+ required: Optional[list[str]] = None
+ dependentRequired: Optional[dict[str, set[str]]] = None
# Ref: JSON Schema Validation 2020-12: https://json-schema.org/draft/2020-12/json-schema-validation.html#name-vocabularies-for-semantic-c
# Vocabularies for Semantic Content With "format"
format: Optional[str] = None
@@ -199,7 +192,7 @@ class Schema(BaseModelWithConfig):
deprecated: Optional[bool] = None
readOnly: Optional[bool] = None
writeOnly: Optional[bool] = None
- examples: Optional[List[Any]] = None
+ examples: Optional[list[Any]] = None
# Ref: OpenAPI 3.1.0: https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#schema-object
# Schema Object
discriminator: Optional[Discriminator] = None
@@ -225,13 +218,7 @@ class Example(TypedDict, total=False):
value: Optional[Any]
externalValue: Optional[AnyUrl]
- if PYDANTIC_V2: # type: ignore [misc]
- __pydantic_config__ = {"extra": "allow"}
-
- else:
-
- class Config:
- extra = "allow"
+ __pydantic_config__ = {"extra": "allow"} # type: ignore[misc]
class ParameterInType(Enum):
@@ -243,7 +230,7 @@ class ParameterInType(Enum):
class Encoding(BaseModelWithConfig):
contentType: Optional[str] = None
- headers: Optional[Dict[str, Union["Header", Reference]]] = None
+ headers: Optional[dict[str, Union["Header", Reference]]] = None
style: Optional[str] = None
explode: Optional[bool] = None
allowReserved: Optional[bool] = None
@@ -252,8 +239,8 @@ class Encoding(BaseModelWithConfig):
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
+ examples: Optional[dict[str, Union[Example, Reference]]] = None
+ encoding: Optional[dict[str, Encoding]] = None
class ParameterBase(BaseModelWithConfig):
@@ -266,9 +253,9 @@ class ParameterBase(BaseModelWithConfig):
allowReserved: Optional[bool] = None
schema_: Optional[Union[Schema, Reference]] = Field(default=None, alias="schema")
example: Optional[Any] = None
- examples: Optional[Dict[str, Union[Example, Reference]]] = None
+ examples: Optional[dict[str, Union[Example, Reference]]] = None
# Serialization rules for more complex scenarios
- content: Optional[Dict[str, MediaType]] = None
+ content: Optional[dict[str, MediaType]] = None
class Parameter(ParameterBase):
@@ -282,14 +269,14 @@ class Header(ParameterBase):
class RequestBody(BaseModelWithConfig):
description: Optional[str] = None
- content: Dict[str, MediaType]
+ content: dict[str, MediaType]
required: Optional[bool] = None
class Link(BaseModelWithConfig):
operationRef: Optional[str] = None
operationId: Optional[str] = None
- parameters: Optional[Dict[str, Union[Any, str]]] = None
+ parameters: Optional[dict[str, Union[Any, str]]] = None
requestBody: Optional[Union[Any, str]] = None
description: Optional[str] = None
server: Optional[Server] = None
@@ -297,25 +284,25 @@ class Link(BaseModelWithConfig):
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
+ headers: Optional[dict[str, Union[Header, Reference]]] = None
+ content: Optional[dict[str, MediaType]] = None
+ links: Optional[dict[str, Union[Link, Reference]]] = None
class Operation(BaseModelWithConfig):
- tags: Optional[List[str]] = None
+ tags: Optional[list[str]] = None
summary: Optional[str] = None
description: Optional[str] = None
externalDocs: Optional[ExternalDocumentation] = None
operationId: Optional[str] = None
- parameters: Optional[List[Union[Parameter, Reference]]] = None
+ parameters: Optional[list[Union[Parameter, Reference]]] = None
requestBody: Optional[Union[RequestBody, Reference]] = None
# Using Any for Specification Extensions
- responses: Optional[Dict[str, Union[Response, Any]]] = None
- callbacks: Optional[Dict[str, Union[Dict[str, "PathItem"], Reference]]] = None
+ responses: Optional[dict[str, Union[Response, Any]]] = None
+ callbacks: Optional[dict[str, Union[dict[str, "PathItem"], Reference]]] = None
deprecated: Optional[bool] = None
- security: Optional[List[Dict[str, List[str]]]] = None
- servers: Optional[List[Server]] = None
+ security: Optional[list[dict[str, list[str]]]] = None
+ servers: Optional[list[Server]] = None
class PathItem(BaseModelWithConfig):
@@ -330,8 +317,8 @@ class PathItem(BaseModelWithConfig):
head: Optional[Operation] = None
patch: Optional[Operation] = None
trace: Optional[Operation] = None
- servers: Optional[List[Server]] = None
- parameters: Optional[List[Union[Parameter, Reference]]] = None
+ servers: Optional[list[Server]] = None
+ parameters: Optional[list[Union[Parameter, Reference]]] = None
class SecuritySchemeType(Enum):
@@ -370,7 +357,7 @@ class HTTPBearer(HTTPBase):
class OAuthFlow(BaseModelWithConfig):
refreshUrl: Optional[str] = None
- scopes: Dict[str, str] = {}
+ scopes: dict[str, str] = {}
class OAuthFlowImplicit(OAuthFlow):
@@ -413,17 +400,17 @@ SecurityScheme = Union[APIKey, HTTPBase, OAuth2, OpenIdConnect, HTTPBearer]
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
- examples: Optional[Dict[str, Union[Example, Reference]]] = None
- requestBodies: Optional[Dict[str, Union[RequestBody, Reference]]] = None
- headers: Optional[Dict[str, Union[Header, Reference]]] = None
- securitySchemes: Optional[Dict[str, Union[SecurityScheme, Reference]]] = None
- links: Optional[Dict[str, Union[Link, Reference]]] = None
+ schemas: Optional[dict[str, Union[Schema, Reference]]] = None
+ responses: Optional[dict[str, Union[Response, Reference]]] = None
+ parameters: Optional[dict[str, Union[Parameter, Reference]]] = None
+ examples: Optional[dict[str, Union[Example, Reference]]] = None
+ requestBodies: Optional[dict[str, Union[RequestBody, Reference]]] = None
+ headers: Optional[dict[str, Union[Header, Reference]]] = None
+ securitySchemes: Optional[dict[str, Union[SecurityScheme, Reference]]] = None
+ links: Optional[dict[str, Union[Link, Reference]]] = None
# Using Any for Specification Extensions
- callbacks: Optional[Dict[str, Union[Dict[str, PathItem], Reference, Any]]] = None
- pathItems: Optional[Dict[str, Union[PathItem, Reference]]] = None
+ callbacks: Optional[dict[str, Union[dict[str, PathItem], Reference, Any]]] = None
+ pathItems: Optional[dict[str, Union[PathItem, Reference]]] = None
class Tag(BaseModelWithConfig):
@@ -436,16 +423,16 @@ class OpenAPI(BaseModelWithConfig):
openapi: str
info: Info
jsonSchemaDialect: Optional[str] = None
- servers: Optional[List[Server]] = None
+ servers: Optional[list[Server]] = None
# Using Any for Specification Extensions
- paths: Optional[Dict[str, Union[PathItem, Any]]] = None
- webhooks: Optional[Dict[str, Union[PathItem, Reference]]] = None
+ paths: Optional[dict[str, Union[PathItem, Any]]] = None
+ webhooks: Optional[dict[str, Union[PathItem, Reference]]] = None
components: Optional[Components] = None
- security: Optional[List[Dict[str, List[str]]]] = None
- tags: Optional[List[Tag]] = None
+ security: Optional[list[dict[str, list[str]]]] = None
+ tags: Optional[list[Tag]] = None
externalDocs: Optional[ExternalDocumentation] = None
-_model_rebuild(Schema)
-_model_rebuild(Operation)
-_model_rebuild(Encoding)
+Schema.model_rebuild()
+Operation.model_rebuild()
+Encoding.model_rebuild()
diff --git a/fastapi/openapi/utils.py b/fastapi/openapi/utils.py
index 9fe2044f26..75ff261025 100644
--- a/fastapi/openapi/utils.py
+++ b/fastapi/openapi/utils.py
@@ -1,11 +1,11 @@
import http.client
import inspect
import warnings
-from typing import Any, Dict, List, Optional, Sequence, Set, Tuple, Type, Union, cast
+from collections.abc import Sequence
+from typing import Any, Optional, Union, cast
from fastapi import routing
from fastapi._compat import (
- JsonSchemaValue,
ModelField,
Undefined,
get_compat_model_name_map,
@@ -22,6 +22,7 @@ from fastapi.dependencies.utils import (
get_validation_alias,
)
from fastapi.encoders import jsonable_encoder
+from fastapi.exceptions import FastAPIDeprecationWarning
from fastapi.openapi.constants import METHODS_WITH_BODY, REF_PREFIX
from fastapi.openapi.models import OpenAPI
from fastapi.params import Body, ParamTypes
@@ -37,8 +38,6 @@ from starlette.responses import JSONResponse
from starlette.routing import BaseRoute
from typing_extensions import Literal
-from .._compat import _is_model_field
-
validation_error_definition = {
"title": "ValidationError",
"type": "object",
@@ -66,7 +65,7 @@ validation_error_response_definition = {
},
}
-status_code_ranges: Dict[str, str] = {
+status_code_ranges: dict[str, str] = {
"1XX": "Information",
"2XX": "Success",
"3XX": "Redirection",
@@ -78,10 +77,10 @@ status_code_ranges: Dict[str, str] = {
def get_openapi_security_definitions(
flat_dependant: Dependant,
-) -> Tuple[Dict[str, Any], List[Dict[str, Any]]]:
+) -> tuple[dict[str, Any], list[dict[str, Any]]]:
security_definitions = {}
# Use a dict to merge scopes for same security scheme
- operation_security_dict: Dict[str, List[str]] = {}
+ operation_security_dict: dict[str, list[str]] = {}
for security_dependency in flat_dependant._security_dependencies:
security_definition = jsonable_encoder(
security_dependency._security_scheme.model,
@@ -106,11 +105,11 @@ def _get_openapi_operation_parameters(
*,
dependant: Dependant,
model_name_map: ModelNameMap,
- field_mapping: Dict[
- Tuple[ModelField, Literal["validation", "serialization"]], JsonSchemaValue
+ field_mapping: dict[
+ tuple[ModelField, Literal["validation", "serialization"]], dict[str, Any]
],
separate_input_output_schemas: bool = True,
-) -> List[Dict[str, Any]]:
+) -> list[dict[str, Any]]:
parameters = []
flat_dependant = get_flat_dependant(dependant, skip_repeats=True)
path_params = _get_flat_fields_from_params(flat_dependant.path_params)
@@ -179,14 +178,14 @@ def get_openapi_operation_request_body(
*,
body_field: Optional[ModelField],
model_name_map: ModelNameMap,
- field_mapping: Dict[
- Tuple[ModelField, Literal["validation", "serialization"]], JsonSchemaValue
+ field_mapping: dict[
+ tuple[ModelField, Literal["validation", "serialization"]], dict[str, Any]
],
separate_input_output_schemas: bool = True,
-) -> Optional[Dict[str, Any]]:
+) -> Optional[dict[str, Any]]:
if not body_field:
return None
- assert _is_model_field(body_field)
+ assert isinstance(body_field, ModelField)
body_schema = get_schema_from_model_field(
field=body_field,
model_name_map=model_name_map,
@@ -196,10 +195,10 @@ def get_openapi_operation_request_body(
field_info = cast(Body, body_field.field_info)
request_media_type = field_info.media_type
required = body_field.required
- request_body_oai: Dict[str, Any] = {}
+ request_body_oai: dict[str, Any] = {}
if required:
request_body_oai["required"] = required
- request_media_content: Dict[str, Any] = {"schema": body_schema}
+ request_media_content: dict[str, Any] = {"schema": body_schema}
if field_info.openapi_examples:
request_media_content["examples"] = jsonable_encoder(
field_info.openapi_examples
@@ -214,9 +213,9 @@ def generate_operation_id(
*, route: routing.APIRoute, method: str
) -> str: # pragma: nocover
warnings.warn(
- "fastapi.openapi.utils.generate_operation_id() was deprecated, "
+ message="fastapi.openapi.utils.generate_operation_id() was deprecated, "
"it is not used internally, and will be removed soon",
- DeprecationWarning,
+ category=FastAPIDeprecationWarning,
stacklevel=2,
)
if route.operation_id:
@@ -232,9 +231,9 @@ def generate_operation_summary(*, route: routing.APIRoute, method: str) -> str:
def get_openapi_operation_metadata(
- *, route: routing.APIRoute, method: str, operation_ids: Set[str]
-) -> Dict[str, Any]:
- operation: Dict[str, Any] = {}
+ *, route: routing.APIRoute, method: str, operation_ids: set[str]
+) -> dict[str, Any]:
+ operation: dict[str, Any] = {}
if route.tags:
operation["tags"] = route.tags
operation["summary"] = generate_operation_summary(route=route, method=method)
@@ -260,19 +259,19 @@ def get_openapi_operation_metadata(
def get_openapi_path(
*,
route: routing.APIRoute,
- operation_ids: Set[str],
+ operation_ids: set[str],
model_name_map: ModelNameMap,
- field_mapping: Dict[
- Tuple[ModelField, Literal["validation", "serialization"]], JsonSchemaValue
+ field_mapping: dict[
+ tuple[ModelField, Literal["validation", "serialization"]], dict[str, Any]
],
separate_input_output_schemas: bool = True,
-) -> Tuple[Dict[str, Any], Dict[str, Any], Dict[str, Any]]:
+) -> tuple[dict[str, Any], dict[str, Any], dict[str, Any]]:
path = {}
- security_schemes: Dict[str, Any] = {}
- definitions: Dict[str, Any] = {}
+ security_schemes: dict[str, Any] = {}
+ definitions: dict[str, Any] = {}
assert route.methods is not None, "Methods must be a list"
if isinstance(route.response_class, DefaultPlaceholder):
- current_response_class: Type[Response] = route.response_class.value
+ current_response_class: type[Response] = route.response_class.value
else:
current_response_class = route.response_class
assert current_response_class, "A response class is needed to generate OpenAPI"
@@ -282,7 +281,7 @@ def get_openapi_path(
operation = get_openapi_operation_metadata(
route=route, method=method, operation_ids=operation_ids
)
- parameters: List[Dict[str, Any]] = []
+ parameters: list[dict[str, Any]] = []
flat_dependant = get_flat_dependant(route.dependant, skip_repeats=True)
security_definitions, operation_security = get_openapi_security_definitions(
flat_dependant=flat_dependant
@@ -390,7 +389,7 @@ def get_openapi_path(
"An additional response must be a dict"
)
field = route.response_fields.get(additional_status_code)
- additional_field_schema: Optional[Dict[str, Any]] = None
+ additional_field_schema: Optional[dict[str, Any]] = None
if field:
additional_field_schema = get_schema_from_model_field(
field=field,
@@ -445,17 +444,17 @@ def get_openapi_path(
def get_fields_from_routes(
routes: Sequence[BaseRoute],
-) -> List[ModelField]:
- body_fields_from_routes: List[ModelField] = []
- responses_from_routes: List[ModelField] = []
- request_fields_from_routes: List[ModelField] = []
- callback_flat_models: List[ModelField] = []
+) -> list[ModelField]:
+ body_fields_from_routes: list[ModelField] = []
+ responses_from_routes: list[ModelField] = []
+ request_fields_from_routes: list[ModelField] = []
+ callback_flat_models: list[ModelField] = []
for route in routes:
if getattr(route, "include_in_schema", None) and isinstance(
route, routing.APIRoute
):
if route.body_field:
- assert _is_model_field(route.body_field), (
+ assert isinstance(route.body_field, ModelField), (
"A request body must be a Pydantic Field"
)
body_fields_from_routes.append(route.body_field)
@@ -483,15 +482,15 @@ def get_openapi(
description: Optional[str] = None,
routes: Sequence[BaseRoute],
webhooks: Optional[Sequence[BaseRoute]] = None,
- tags: Optional[List[Dict[str, Any]]] = None,
- servers: Optional[List[Dict[str, Union[str, Any]]]] = None,
+ tags: Optional[list[dict[str, Any]]] = None,
+ servers: Optional[list[dict[str, Union[str, Any]]]] = None,
terms_of_service: Optional[str] = None,
- contact: Optional[Dict[str, Union[str, Any]]] = None,
- license_info: Optional[Dict[str, Union[str, Any]]] = None,
+ contact: Optional[dict[str, Union[str, Any]]] = None,
+ license_info: Optional[dict[str, Union[str, Any]]] = None,
separate_input_output_schemas: bool = True,
- external_docs: Optional[Dict[str, Any]] = None,
-) -> Dict[str, Any]:
- info: Dict[str, Any] = {"title": title, "version": version}
+ external_docs: Optional[dict[str, Any]] = None,
+) -> dict[str, Any]:
+ info: dict[str, Any] = {"title": title, "version": version}
if summary:
info["summary"] = summary
if description:
@@ -502,13 +501,13 @@ def get_openapi(
info["contact"] = contact
if license_info:
info["license"] = license_info
- output: Dict[str, Any] = {"openapi": openapi_version, "info": info}
+ output: dict[str, Any] = {"openapi": openapi_version, "info": info}
if servers:
output["servers"] = servers
- components: Dict[str, Dict[str, Any]] = {}
- paths: Dict[str, Dict[str, Any]] = {}
- webhook_paths: Dict[str, Dict[str, Any]] = {}
- operation_ids: Set[str] = set()
+ components: dict[str, dict[str, Any]] = {}
+ paths: dict[str, dict[str, Any]] = {}
+ webhook_paths: dict[str, dict[str, Any]] = {}
+ operation_ids: set[str] = set()
all_fields = get_fields_from_routes(list(routes or []) + list(webhooks or []))
model_name_map = get_compat_model_name_map(all_fields)
field_mapping, definitions = get_definitions(
diff --git a/fastapi/param_functions.py b/fastapi/param_functions.py
index e32f755933..0834fd741a 100644
--- a/fastapi/param_functions.py
+++ b/fastapi/param_functions.py
@@ -1,10 +1,12 @@
-from typing import Any, Callable, Dict, List, Optional, Sequence, Union
+from collections.abc import Sequence
+from typing import Annotated, Any, Callable, Optional, Union
from annotated_doc import Doc
from fastapi import params
from fastapi._compat import Undefined
from fastapi.openapi.models import Example
-from typing_extensions import Annotated, Literal, deprecated
+from pydantic import AliasChoices, AliasPath
+from typing_extensions import Literal, deprecated
_Unset: Any = Undefined
@@ -53,10 +55,8 @@ def Path( # noqa: N802
"""
),
] = _Unset,
- # TODO: update when deprecating Pydantic v1, import these types
- # validation_alias: str | AliasPath | AliasChoices | None
validation_alias: Annotated[
- Union[str, None],
+ Union[str, AliasPath, AliasChoices, None],
Doc(
"""
'Whitelist' validation step. The parameter field will be the single one
@@ -209,7 +209,7 @@ def Path( # noqa: N802
),
] = _Unset,
examples: Annotated[
- Optional[List[Any]],
+ Optional[list[Any]],
Doc(
"""
Example values for this field.
@@ -224,7 +224,7 @@ def Path( # noqa: N802
),
] = _Unset,
openapi_examples: Annotated[
- Optional[Dict[str, Example]],
+ Optional[dict[str, Example]],
Doc(
"""
OpenAPI-specific examples.
@@ -262,7 +262,7 @@ def Path( # noqa: N802
),
] = True,
json_schema_extra: Annotated[
- Union[Dict[str, Any], None],
+ Union[dict[str, Any], None],
Doc(
"""
Any additional JSON schema data.
@@ -378,10 +378,8 @@ def Query( # noqa: N802
"""
),
] = _Unset,
- # TODO: update when deprecating Pydantic v1, import these types
- # validation_alias: str | AliasPath | AliasChoices | None
validation_alias: Annotated[
- Union[str, None],
+ Union[str, AliasPath, AliasChoices, None],
Doc(
"""
'Whitelist' validation step. The parameter field will be the single one
@@ -534,7 +532,7 @@ def Query( # noqa: N802
),
] = _Unset,
examples: Annotated[
- Optional[List[Any]],
+ Optional[list[Any]],
Doc(
"""
Example values for this field.
@@ -549,7 +547,7 @@ def Query( # noqa: N802
),
] = _Unset,
openapi_examples: Annotated[
- Optional[Dict[str, Example]],
+ Optional[dict[str, Example]],
Doc(
"""
OpenAPI-specific examples.
@@ -587,7 +585,7 @@ def Query( # noqa: N802
),
] = True,
json_schema_extra: Annotated[
- Union[Dict[str, Any], None],
+ Union[dict[str, Any], None],
Doc(
"""
Any additional JSON schema data.
@@ -682,10 +680,8 @@ def Header( # noqa: N802
"""
),
] = _Unset,
- # TODO: update when deprecating Pydantic v1, import these types
- # validation_alias: str | AliasPath | AliasChoices | None
validation_alias: Annotated[
- Union[str, None],
+ Union[str, AliasPath, AliasChoices, None],
Doc(
"""
'Whitelist' validation step. The parameter field will be the single one
@@ -849,7 +845,7 @@ def Header( # noqa: N802
),
] = _Unset,
examples: Annotated[
- Optional[List[Any]],
+ Optional[list[Any]],
Doc(
"""
Example values for this field.
@@ -864,7 +860,7 @@ def Header( # noqa: N802
),
] = _Unset,
openapi_examples: Annotated[
- Optional[Dict[str, Example]],
+ Optional[dict[str, Example]],
Doc(
"""
OpenAPI-specific examples.
@@ -902,7 +898,7 @@ def Header( # noqa: N802
),
] = True,
json_schema_extra: Annotated[
- Union[Dict[str, Any], None],
+ Union[dict[str, Any], None],
Doc(
"""
Any additional JSON schema data.
@@ -998,10 +994,8 @@ def Cookie( # noqa: N802
"""
),
] = _Unset,
- # TODO: update when deprecating Pydantic v1, import these types
- # validation_alias: str | AliasPath | AliasChoices | None
validation_alias: Annotated[
- Union[str, None],
+ Union[str, AliasPath, AliasChoices, None],
Doc(
"""
'Whitelist' validation step. The parameter field will be the single one
@@ -1154,7 +1148,7 @@ def Cookie( # noqa: N802
),
] = _Unset,
examples: Annotated[
- Optional[List[Any]],
+ Optional[list[Any]],
Doc(
"""
Example values for this field.
@@ -1169,7 +1163,7 @@ def Cookie( # noqa: N802
),
] = _Unset,
openapi_examples: Annotated[
- Optional[Dict[str, Example]],
+ Optional[dict[str, Example]],
Doc(
"""
OpenAPI-specific examples.
@@ -1207,7 +1201,7 @@ def Cookie( # noqa: N802
),
] = True,
json_schema_extra: Annotated[
- Union[Dict[str, Any], None],
+ Union[dict[str, Any], None],
Doc(
"""
Any additional JSON schema data.
@@ -1325,10 +1319,8 @@ def Body( # noqa: N802
"""
),
] = _Unset,
- # TODO: update when deprecating Pydantic v1, import these types
- # validation_alias: str | AliasPath | AliasChoices | None
validation_alias: Annotated[
- Union[str, None],
+ Union[str, AliasPath, AliasChoices, None],
Doc(
"""
'Whitelist' validation step. The parameter field will be the single one
@@ -1481,7 +1473,7 @@ def Body( # noqa: N802
),
] = _Unset,
examples: Annotated[
- Optional[List[Any]],
+ Optional[list[Any]],
Doc(
"""
Example values for this field.
@@ -1496,7 +1488,7 @@ def Body( # noqa: N802
),
] = _Unset,
openapi_examples: Annotated[
- Optional[Dict[str, Example]],
+ Optional[dict[str, Example]],
Doc(
"""
OpenAPI-specific examples.
@@ -1534,7 +1526,7 @@ def Body( # noqa: N802
),
] = True,
json_schema_extra: Annotated[
- Union[Dict[str, Any], None],
+ Union[dict[str, Any], None],
Doc(
"""
Any additional JSON schema data.
@@ -1640,10 +1632,8 @@ def Form( # noqa: N802
"""
),
] = _Unset,
- # TODO: update when deprecating Pydantic v1, import these types
- # validation_alias: str | AliasPath | AliasChoices | None
validation_alias: Annotated[
- Union[str, None],
+ Union[str, AliasPath, AliasChoices, None],
Doc(
"""
'Whitelist' validation step. The parameter field will be the single one
@@ -1796,7 +1786,7 @@ def Form( # noqa: N802
),
] = _Unset,
examples: Annotated[
- Optional[List[Any]],
+ Optional[list[Any]],
Doc(
"""
Example values for this field.
@@ -1811,7 +1801,7 @@ def Form( # noqa: N802
),
] = _Unset,
openapi_examples: Annotated[
- Optional[Dict[str, Example]],
+ Optional[dict[str, Example]],
Doc(
"""
OpenAPI-specific examples.
@@ -1849,7 +1839,7 @@ def Form( # noqa: N802
),
] = True,
json_schema_extra: Annotated[
- Union[Dict[str, Any], None],
+ Union[dict[str, Any], None],
Doc(
"""
Any additional JSON schema data.
@@ -1954,10 +1944,8 @@ def File( # noqa: N802
"""
),
] = _Unset,
- # TODO: update when deprecating Pydantic v1, import these types
- # validation_alias: str | AliasPath | AliasChoices | None
validation_alias: Annotated[
- Union[str, None],
+ Union[str, AliasPath, AliasChoices, None],
Doc(
"""
'Whitelist' validation step. The parameter field will be the single one
@@ -2110,7 +2098,7 @@ def File( # noqa: N802
),
] = _Unset,
examples: Annotated[
- Optional[List[Any]],
+ Optional[list[Any]],
Doc(
"""
Example values for this field.
@@ -2125,7 +2113,7 @@ def File( # noqa: N802
),
] = _Unset,
openapi_examples: Annotated[
- Optional[Dict[str, Example]],
+ Optional[dict[str, Example]],
Doc(
"""
OpenAPI-specific examples.
@@ -2163,7 +2151,7 @@ def File( # noqa: N802
),
] = True,
json_schema_extra: Annotated[
- Union[Dict[str, Any], None],
+ Union[dict[str, Any], None],
Doc(
"""
Any additional JSON schema data.
diff --git a/fastapi/params.py b/fastapi/params.py
index b6d0f08e31..72e797f833 100644
--- a/fastapi/params.py
+++ b/fastapi/params.py
@@ -1,15 +1,16 @@
import warnings
+from collections.abc import Sequence
from dataclasses import dataclass
from enum import Enum
-from typing import Any, Callable, Dict, List, Optional, Sequence, Union
+from typing import Annotated, Any, Callable, Optional, Union
+from fastapi.exceptions import FastAPIDeprecationWarning
from fastapi.openapi.models import Example
+from pydantic import AliasChoices, AliasPath
from pydantic.fields import FieldInfo
-from typing_extensions import Annotated, Literal, deprecated
+from typing_extensions import Literal, deprecated
from ._compat import (
- PYDANTIC_V2,
- PYDANTIC_VERSION_MINOR_TUPLE,
Undefined,
)
@@ -34,9 +35,7 @@ class Param(FieldInfo): # type: ignore[misc]
annotation: Optional[Any] = None,
alias: Optional[str] = None,
alias_priority: Union[int, None] = _Unset,
- # TODO: update when deprecating Pydantic v1, import these types
- # validation_alias: str | AliasPath | AliasChoices | None
- validation_alias: Union[str, None] = None,
+ validation_alias: Union[str, AliasPath, AliasChoices, None] = None,
serialization_alias: Union[str, None] = None,
title: Optional[str] = None,
description: Optional[str] = None,
@@ -59,7 +58,7 @@ class Param(FieldInfo): # type: ignore[misc]
allow_inf_nan: Union[bool, None] = _Unset,
max_digits: Union[int, None] = _Unset,
decimal_places: Union[int, None] = _Unset,
- examples: Optional[List[Any]] = None,
+ examples: Optional[list[Any]] = None,
example: Annotated[
Optional[Any],
deprecated(
@@ -67,16 +66,16 @@ class Param(FieldInfo): # type: ignore[misc]
"although still supported. Use examples instead."
),
] = _Unset,
- openapi_examples: Optional[Dict[str, Example]] = None,
+ openapi_examples: Optional[dict[str, Example]] = None,
deprecated: Union[deprecated, str, bool, None] = None,
include_in_schema: bool = True,
- json_schema_extra: Union[Dict[str, Any], None] = None,
+ json_schema_extra: Union[dict[str, Any], None] = None,
**extra: Any,
):
if example is not _Unset:
warnings.warn(
"`example` has been deprecated, please use `examples` instead",
- category=DeprecationWarning,
+ category=FastAPIDeprecationWarning,
stacklevel=4,
)
self.example = example
@@ -106,33 +105,28 @@ class Param(FieldInfo): # type: ignore[misc]
if regex is not None:
warnings.warn(
"`regex` has been deprecated, please use `pattern` instead",
- category=DeprecationWarning,
+ category=FastAPIDeprecationWarning,
stacklevel=4,
)
current_json_schema_extra = json_schema_extra or extra
- if PYDANTIC_VERSION_MINOR_TUPLE < (2, 7):
- self.deprecated = deprecated
- else:
- kwargs["deprecated"] = deprecated
- if PYDANTIC_V2:
- if serialization_alias in (_Unset, None) and isinstance(alias, str):
- serialization_alias = alias
- if validation_alias in (_Unset, None):
- validation_alias = alias
- kwargs.update(
- {
- "annotation": annotation,
- "alias_priority": alias_priority,
- "validation_alias": validation_alias,
- "serialization_alias": serialization_alias,
- "strict": strict,
- "json_schema_extra": current_json_schema_extra,
- }
- )
- kwargs["pattern"] = pattern or regex
- else:
- kwargs["regex"] = pattern or regex
- kwargs.update(**current_json_schema_extra)
+ kwargs["deprecated"] = deprecated
+
+ if serialization_alias in (_Unset, None) and isinstance(alias, str):
+ serialization_alias = alias
+ if validation_alias in (_Unset, None):
+ validation_alias = alias
+ kwargs.update(
+ {
+ "annotation": annotation,
+ "alias_priority": alias_priority,
+ "validation_alias": validation_alias,
+ "serialization_alias": serialization_alias,
+ "strict": strict,
+ "json_schema_extra": current_json_schema_extra,
+ }
+ )
+ kwargs["pattern"] = pattern or regex
+
use_kwargs = {k: v for k, v in kwargs.items() if v is not _Unset}
super().__init__(**use_kwargs)
@@ -152,9 +146,7 @@ class Path(Param): # type: ignore[misc]
annotation: Optional[Any] = None,
alias: Optional[str] = None,
alias_priority: Union[int, None] = _Unset,
- # TODO: update when deprecating Pydantic v1, import these types
- # validation_alias: str | AliasPath | AliasChoices | None
- validation_alias: Union[str, None] = None,
+ validation_alias: Union[str, AliasPath, AliasChoices, None] = None,
serialization_alias: Union[str, None] = None,
title: Optional[str] = None,
description: Optional[str] = None,
@@ -177,7 +169,7 @@ class Path(Param): # type: ignore[misc]
allow_inf_nan: Union[bool, None] = _Unset,
max_digits: Union[int, None] = _Unset,
decimal_places: Union[int, None] = _Unset,
- examples: Optional[List[Any]] = None,
+ examples: Optional[list[Any]] = None,
example: Annotated[
Optional[Any],
deprecated(
@@ -185,10 +177,10 @@ class Path(Param): # type: ignore[misc]
"although still supported. Use examples instead."
),
] = _Unset,
- openapi_examples: Optional[Dict[str, Example]] = None,
+ openapi_examples: Optional[dict[str, Example]] = None,
deprecated: Union[deprecated, str, bool, None] = None,
include_in_schema: bool = True,
- json_schema_extra: Union[Dict[str, Any], None] = None,
+ json_schema_extra: Union[dict[str, Any], None] = None,
**extra: Any,
):
assert default is ..., "Path parameters cannot have a default value"
@@ -238,9 +230,7 @@ class Query(Param): # type: ignore[misc]
annotation: Optional[Any] = None,
alias: Optional[str] = None,
alias_priority: Union[int, None] = _Unset,
- # TODO: update when deprecating Pydantic v1, import these types
- # validation_alias: str | AliasPath | AliasChoices | None
- validation_alias: Union[str, None] = None,
+ validation_alias: Union[str, AliasPath, AliasChoices, None] = None,
serialization_alias: Union[str, None] = None,
title: Optional[str] = None,
description: Optional[str] = None,
@@ -263,7 +253,7 @@ class Query(Param): # type: ignore[misc]
allow_inf_nan: Union[bool, None] = _Unset,
max_digits: Union[int, None] = _Unset,
decimal_places: Union[int, None] = _Unset,
- examples: Optional[List[Any]] = None,
+ examples: Optional[list[Any]] = None,
example: Annotated[
Optional[Any],
deprecated(
@@ -271,10 +261,10 @@ class Query(Param): # type: ignore[misc]
"although still supported. Use examples instead."
),
] = _Unset,
- openapi_examples: Optional[Dict[str, Example]] = None,
+ openapi_examples: Optional[dict[str, Example]] = None,
deprecated: Union[deprecated, str, bool, None] = None,
include_in_schema: bool = True,
- json_schema_extra: Union[Dict[str, Any], None] = None,
+ json_schema_extra: Union[dict[str, Any], None] = None,
**extra: Any,
):
super().__init__(
@@ -322,9 +312,7 @@ class Header(Param): # type: ignore[misc]
annotation: Optional[Any] = None,
alias: Optional[str] = None,
alias_priority: Union[int, None] = _Unset,
- # TODO: update when deprecating Pydantic v1, import these types
- # validation_alias: str | AliasPath | AliasChoices | None
- validation_alias: Union[str, None] = None,
+ validation_alias: Union[str, AliasPath, AliasChoices, None] = None,
serialization_alias: Union[str, None] = None,
convert_underscores: bool = True,
title: Optional[str] = None,
@@ -348,7 +336,7 @@ class Header(Param): # type: ignore[misc]
allow_inf_nan: Union[bool, None] = _Unset,
max_digits: Union[int, None] = _Unset,
decimal_places: Union[int, None] = _Unset,
- examples: Optional[List[Any]] = None,
+ examples: Optional[list[Any]] = None,
example: Annotated[
Optional[Any],
deprecated(
@@ -356,10 +344,10 @@ class Header(Param): # type: ignore[misc]
"although still supported. Use examples instead."
),
] = _Unset,
- openapi_examples: Optional[Dict[str, Example]] = None,
+ openapi_examples: Optional[dict[str, Example]] = None,
deprecated: Union[deprecated, str, bool, None] = None,
include_in_schema: bool = True,
- json_schema_extra: Union[Dict[str, Any], None] = None,
+ json_schema_extra: Union[dict[str, Any], None] = None,
**extra: Any,
):
self.convert_underscores = convert_underscores
@@ -408,9 +396,7 @@ class Cookie(Param): # type: ignore[misc]
annotation: Optional[Any] = None,
alias: Optional[str] = None,
alias_priority: Union[int, None] = _Unset,
- # TODO: update when deprecating Pydantic v1, import these types
- # validation_alias: str | AliasPath | AliasChoices | None
- validation_alias: Union[str, None] = None,
+ validation_alias: Union[str, AliasPath, AliasChoices, None] = None,
serialization_alias: Union[str, None] = None,
title: Optional[str] = None,
description: Optional[str] = None,
@@ -433,7 +419,7 @@ class Cookie(Param): # type: ignore[misc]
allow_inf_nan: Union[bool, None] = _Unset,
max_digits: Union[int, None] = _Unset,
decimal_places: Union[int, None] = _Unset,
- examples: Optional[List[Any]] = None,
+ examples: Optional[list[Any]] = None,
example: Annotated[
Optional[Any],
deprecated(
@@ -441,10 +427,10 @@ class Cookie(Param): # type: ignore[misc]
"although still supported. Use examples instead."
),
] = _Unset,
- openapi_examples: Optional[Dict[str, Example]] = None,
+ openapi_examples: Optional[dict[str, Example]] = None,
deprecated: Union[deprecated, str, bool, None] = None,
include_in_schema: bool = True,
- json_schema_extra: Union[Dict[str, Any], None] = None,
+ json_schema_extra: Union[dict[str, Any], None] = None,
**extra: Any,
):
super().__init__(
@@ -492,9 +478,7 @@ class Body(FieldInfo): # type: ignore[misc]
media_type: str = "application/json",
alias: Optional[str] = None,
alias_priority: Union[int, None] = _Unset,
- # TODO: update when deprecating Pydantic v1, import these types
- # validation_alias: str | AliasPath | AliasChoices | None
- validation_alias: Union[str, None] = None,
+ validation_alias: Union[str, AliasPath, AliasChoices, None] = None,
serialization_alias: Union[str, None] = None,
title: Optional[str] = None,
description: Optional[str] = None,
@@ -517,7 +501,7 @@ class Body(FieldInfo): # type: ignore[misc]
allow_inf_nan: Union[bool, None] = _Unset,
max_digits: Union[int, None] = _Unset,
decimal_places: Union[int, None] = _Unset,
- examples: Optional[List[Any]] = None,
+ examples: Optional[list[Any]] = None,
example: Annotated[
Optional[Any],
deprecated(
@@ -525,10 +509,10 @@ class Body(FieldInfo): # type: ignore[misc]
"although still supported. Use examples instead."
),
] = _Unset,
- openapi_examples: Optional[Dict[str, Example]] = None,
+ openapi_examples: Optional[dict[str, Example]] = None,
deprecated: Union[deprecated, str, bool, None] = None,
include_in_schema: bool = True,
- json_schema_extra: Union[Dict[str, Any], None] = None,
+ json_schema_extra: Union[dict[str, Any], None] = None,
**extra: Any,
):
self.embed = embed
@@ -536,7 +520,7 @@ class Body(FieldInfo): # type: ignore[misc]
if example is not _Unset:
warnings.warn(
"`example` has been deprecated, please use `examples` instead",
- category=DeprecationWarning,
+ category=FastAPIDeprecationWarning,
stacklevel=4,
)
self.example = example
@@ -566,33 +550,26 @@ class Body(FieldInfo): # type: ignore[misc]
if regex is not None:
warnings.warn(
"`regex` has been deprecated, please use `pattern` instead",
- category=DeprecationWarning,
+ category=FastAPIDeprecationWarning,
stacklevel=4,
)
current_json_schema_extra = json_schema_extra or extra
- if PYDANTIC_VERSION_MINOR_TUPLE < (2, 7):
- self.deprecated = deprecated
- else:
- kwargs["deprecated"] = deprecated
- if PYDANTIC_V2:
- if serialization_alias in (_Unset, None) and isinstance(alias, str):
- serialization_alias = alias
- if validation_alias in (_Unset, None):
- validation_alias = alias
- kwargs.update(
- {
- "annotation": annotation,
- "alias_priority": alias_priority,
- "validation_alias": validation_alias,
- "serialization_alias": serialization_alias,
- "strict": strict,
- "json_schema_extra": current_json_schema_extra,
- }
- )
- kwargs["pattern"] = pattern or regex
- else:
- kwargs["regex"] = pattern or regex
- kwargs.update(**current_json_schema_extra)
+ kwargs["deprecated"] = deprecated
+ if serialization_alias in (_Unset, None) and isinstance(alias, str):
+ serialization_alias = alias
+ if validation_alias in (_Unset, None):
+ validation_alias = alias
+ kwargs.update(
+ {
+ "annotation": annotation,
+ "alias_priority": alias_priority,
+ "validation_alias": validation_alias,
+ "serialization_alias": serialization_alias,
+ "strict": strict,
+ "json_schema_extra": current_json_schema_extra,
+ }
+ )
+ kwargs["pattern"] = pattern or regex
use_kwargs = {k: v for k, v in kwargs.items() if v is not _Unset}
@@ -612,9 +589,7 @@ class Form(Body): # type: ignore[misc]
media_type: str = "application/x-www-form-urlencoded",
alias: Optional[str] = None,
alias_priority: Union[int, None] = _Unset,
- # TODO: update when deprecating Pydantic v1, import these types
- # validation_alias: str | AliasPath | AliasChoices | None
- validation_alias: Union[str, None] = None,
+ validation_alias: Union[str, AliasPath, AliasChoices, None] = None,
serialization_alias: Union[str, None] = None,
title: Optional[str] = None,
description: Optional[str] = None,
@@ -637,7 +612,7 @@ class Form(Body): # type: ignore[misc]
allow_inf_nan: Union[bool, None] = _Unset,
max_digits: Union[int, None] = _Unset,
decimal_places: Union[int, None] = _Unset,
- examples: Optional[List[Any]] = None,
+ examples: Optional[list[Any]] = None,
example: Annotated[
Optional[Any],
deprecated(
@@ -645,10 +620,10 @@ class Form(Body): # type: ignore[misc]
"although still supported. Use examples instead."
),
] = _Unset,
- openapi_examples: Optional[Dict[str, Example]] = None,
+ openapi_examples: Optional[dict[str, Example]] = None,
deprecated: Union[deprecated, str, bool, None] = None,
include_in_schema: bool = True,
- json_schema_extra: Union[Dict[str, Any], None] = None,
+ json_schema_extra: Union[dict[str, Any], None] = None,
**extra: Any,
):
super().__init__(
@@ -696,9 +671,7 @@ class File(Form): # type: ignore[misc]
media_type: str = "multipart/form-data",
alias: Optional[str] = None,
alias_priority: Union[int, None] = _Unset,
- # TODO: update when deprecating Pydantic v1, import these types
- # validation_alias: str | AliasPath | AliasChoices | None
- validation_alias: Union[str, None] = None,
+ validation_alias: Union[str, AliasPath, AliasChoices, None] = None,
serialization_alias: Union[str, None] = None,
title: Optional[str] = None,
description: Optional[str] = None,
@@ -721,7 +694,7 @@ class File(Form): # type: ignore[misc]
allow_inf_nan: Union[bool, None] = _Unset,
max_digits: Union[int, None] = _Unset,
decimal_places: Union[int, None] = _Unset,
- examples: Optional[List[Any]] = None,
+ examples: Optional[list[Any]] = None,
example: Annotated[
Optional[Any],
deprecated(
@@ -729,10 +702,10 @@ class File(Form): # type: ignore[misc]
"although still supported. Use examples instead."
),
] = _Unset,
- openapi_examples: Optional[Dict[str, Example]] = None,
+ openapi_examples: Optional[dict[str, Example]] = None,
deprecated: Union[deprecated, str, bool, None] = None,
include_in_schema: bool = True,
- json_schema_extra: Union[Dict[str, Any], None] = None,
+ json_schema_extra: Union[dict[str, Any], None] = None,
**extra: Any,
):
super().__init__(
diff --git a/fastapi/routing.py b/fastapi/routing.py
index 9be2b44bc1..9ca2f46732 100644
--- a/fastapi/routing.py
+++ b/fastapi/routing.py
@@ -1,36 +1,31 @@
-import dataclasses
import email.message
import functools
import inspect
import json
+from collections.abc import (
+ AsyncIterator,
+ Awaitable,
+ Collection,
+ Coroutine,
+ Mapping,
+ Sequence,
+)
from contextlib import AsyncExitStack, asynccontextmanager
from enum import Enum, IntEnum
from typing import (
+ Annotated,
Any,
- AsyncIterator,
- Awaitable,
Callable,
- Collection,
- Coroutine,
- Dict,
- List,
- Mapping,
Optional,
- Sequence,
- Set,
- Tuple,
- Type,
Union,
)
from annotated_doc import Doc
-from fastapi import params, temp_pydantic_v1_params
+from fastapi import params
from fastapi._compat import (
ModelField,
Undefined,
- _get_model_config,
- _model_dump,
- _normalize_errors,
+ annotation_is_pydantic_v1,
lenient_issubclass,
)
from fastapi.datastructures import Default, DefaultPlaceholder
@@ -48,6 +43,7 @@ from fastapi.encoders import jsonable_encoder
from fastapi.exceptions import (
EndpointContext,
FastAPIError,
+ PydanticV1NotSupportedError,
RequestValidationError,
ResponseValidationError,
WebSocketRequestValidationError,
@@ -60,7 +56,6 @@ from fastapi.utils import (
get_value_or_default,
is_body_allowed_for_status_code,
)
-from pydantic import BaseModel
from starlette import routing
from starlette._exception_handler import wrap_app_handling_exceptions
from starlette._utils import is_async_callable
@@ -77,7 +72,7 @@ from starlette.routing import (
from starlette.routing import Mount as Mount # noqa
from starlette.types import AppType, ASGIApp, Lifespan, Receive, Scope, Send
from starlette.websockets import WebSocket
-from typing_extensions import Annotated, deprecated
+from typing_extensions import deprecated
# Copy of starlette.routing.request_response modified to include the
@@ -148,54 +143,6 @@ def websocket_session(
return app
-def _prepare_response_content(
- res: Any,
- *,
- exclude_unset: bool,
- exclude_defaults: bool = False,
- exclude_none: bool = False,
-) -> Any:
- if isinstance(res, BaseModel):
- read_with_orm_mode = getattr(_get_model_config(res), "read_with_orm_mode", None)
- if read_with_orm_mode:
- # Let from_orm extract the data from this model instead of converting
- # it now to a dict.
- # Otherwise, there's no way to extract lazy data that requires attribute
- # access instead of dict iteration, e.g. lazy relationships.
- return res
- return _model_dump(
- res,
- by_alias=True,
- exclude_unset=exclude_unset,
- exclude_defaults=exclude_defaults,
- exclude_none=exclude_none,
- )
- elif isinstance(res, list):
- return [
- _prepare_response_content(
- item,
- exclude_unset=exclude_unset,
- exclude_defaults=exclude_defaults,
- exclude_none=exclude_none,
- )
- for item in res
- ]
- elif isinstance(res, dict):
- return {
- k: _prepare_response_content(
- v,
- exclude_unset=exclude_unset,
- exclude_defaults=exclude_defaults,
- exclude_none=exclude_none,
- )
- for k, v in res.items()
- }
- elif dataclasses.is_dataclass(res):
- assert not isinstance(res, type)
- return dataclasses.asdict(res)
- return res
-
-
def _merge_lifespan_context(
original_context: Lifespan[Any], nested_context: Lifespan[Any]
) -> Lifespan[Any]:
@@ -214,7 +161,7 @@ def _merge_lifespan_context(
# Cache for endpoint context to avoid re-extracting on every request
-_endpoint_context_cache: Dict[int, EndpointContext] = {}
+_endpoint_context_cache: dict[int, EndpointContext] = {}
def _extract_endpoint_context(func: Any) -> EndpointContext:
@@ -255,14 +202,6 @@ async def serialize_response(
) -> Any:
if field:
errors = []
- if not hasattr(field, "serialize"):
- # pydantic v1
- response_content = _prepare_response_content(
- response_content,
- exclude_unset=exclude_unset,
- exclude_defaults=exclude_defaults,
- exclude_none=exclude_none,
- )
if is_coroutine:
value, errors_ = field.validate(response_content, {}, loc=("response",))
else:
@@ -271,28 +210,15 @@ async def serialize_response(
)
if isinstance(errors_, list):
errors.extend(errors_)
- elif errors_:
- errors.append(errors_)
if errors:
ctx = endpoint_ctx or EndpointContext()
raise ResponseValidationError(
- errors=_normalize_errors(errors),
+ errors=errors,
body=response_content,
endpoint_ctx=ctx,
)
- if hasattr(field, "serialize"):
- return field.serialize(
- value,
- include=include,
- exclude=exclude,
- by_alias=by_alias,
- exclude_unset=exclude_unset,
- exclude_defaults=exclude_defaults,
- exclude_none=exclude_none,
- )
-
- return jsonable_encoder(
+ return field.serialize(
value,
include=include,
exclude=exclude,
@@ -301,12 +227,13 @@ async def serialize_response(
exclude_defaults=exclude_defaults,
exclude_none=exclude_none,
)
+
else:
return jsonable_encoder(response_content)
async def run_endpoint_function(
- *, dependant: Dependant, values: Dict[str, Any], is_coroutine: bool
+ *, dependant: Dependant, values: dict[str, Any], is_coroutine: bool
) -> Any:
# Only called by get_request_handler. Has been split into its own function to
# facilitate profiling endpoints, since inner functions are harder to profile.
@@ -322,7 +249,7 @@ def get_request_handler(
dependant: Dependant,
body_field: Optional[ModelField] = None,
status_code: Optional[int] = None,
- response_class: Union[Type[Response], DefaultPlaceholder] = Default(JSONResponse),
+ response_class: Union[type[Response], DefaultPlaceholder] = Default(JSONResponse),
response_field: Optional[ModelField] = None,
response_model_include: Optional[IncEx] = None,
response_model_exclude: Optional[IncEx] = None,
@@ -335,11 +262,9 @@ def get_request_handler(
) -> Callable[[Request], Coroutine[Any, Any, Response]]:
assert dependant.call is not None, "dependant.call must be a function"
is_coroutine = dependant.is_coroutine_callable
- is_body_form = body_field and isinstance(
- body_field.field_info, (params.Form, temp_pydantic_v1_params.Form)
- )
+ is_body_form = body_field and isinstance(body_field.field_info, params.Form)
if isinstance(response_class, DefaultPlaceholder):
- actual_response_class: Type[Response] = response_class.value
+ actual_response_class: type[Response] = response_class.value
else:
actual_response_class = response_class
@@ -412,7 +337,7 @@ def get_request_handler(
raise http_error from e
# Solve dependencies and run path operation function, auto-closing dependencies
- errors: List[Any] = []
+ errors: list[Any] = []
async_exit_stack = request.scope.get("fastapi_inner_astack")
assert isinstance(async_exit_stack, AsyncExitStack), (
"fastapi_inner_astack not found in request scope"
@@ -437,7 +362,7 @@ def get_request_handler(
raw_response.background = solved_result.background_tasks
response = raw_response
else:
- response_args: Dict[str, Any] = {
+ response_args: dict[str, Any] = {
"background": solved_result.background_tasks
}
# If status_code was set, use it, otherwise use the default from the
@@ -467,7 +392,7 @@ def get_request_handler(
response.headers.raw.extend(solved_result.response.headers.raw)
if errors:
validation_error = RequestValidationError(
- _normalize_errors(errors), body=body, endpoint_ctx=endpoint_ctx
+ errors, body=body, endpoint_ctx=endpoint_ctx
)
raise validation_error
@@ -506,7 +431,7 @@ def get_websocket_app(
)
if solved_result.errors:
raise WebSocketRequestValidationError(
- _normalize_errors(solved_result.errors),
+ solved_result.errors,
endpoint_ctx=endpoint_ctx,
)
assert dependant.call is not None, "dependant.call must be a function"
@@ -550,7 +475,7 @@ class APIWebSocketRoute(routing.WebSocketRoute):
)
)
- def matches(self, scope: Scope) -> Tuple[Match, Scope]:
+ def matches(self, scope: Scope) -> tuple[Match, Scope]:
match, child_scope = super().matches(scope)
if match != Match.NONE:
child_scope["route"] = self
@@ -565,15 +490,15 @@ class APIRoute(routing.Route):
*,
response_model: Any = Default(None),
status_code: Optional[int] = None,
- tags: Optional[List[Union[str, Enum]]] = None,
+ tags: Optional[list[Union[str, Enum]]] = None,
dependencies: Optional[Sequence[params.Depends]] = None,
summary: Optional[str] = None,
description: Optional[str] = None,
response_description: str = "Successful Response",
- responses: Optional[Dict[Union[int, str], Dict[str, Any]]] = None,
+ responses: Optional[dict[Union[int, str], dict[str, Any]]] = None,
deprecated: Optional[bool] = None,
name: Optional[str] = None,
- methods: Optional[Union[Set[str], List[str]]] = None,
+ methods: Optional[Union[set[str], list[str]]] = None,
operation_id: Optional[str] = None,
response_model_include: Optional[IncEx] = None,
response_model_exclude: Optional[IncEx] = None,
@@ -582,12 +507,12 @@ class APIRoute(routing.Route):
response_model_exclude_defaults: bool = False,
response_model_exclude_none: bool = False,
include_in_schema: bool = True,
- response_class: Union[Type[Response], DefaultPlaceholder] = Default(
+ response_class: Union[type[Response], DefaultPlaceholder] = Default(
JSONResponse
),
dependency_overrides_provider: Optional[Any] = None,
- callbacks: Optional[List[BaseRoute]] = None,
- openapi_extra: Optional[Dict[str, Any]] = None,
+ callbacks: Optional[list[BaseRoute]] = None,
+ openapi_extra: Optional[dict[str, Any]] = None,
generate_unique_id_function: Union[
Callable[["APIRoute"], str], DefaultPlaceholder
] = Default(generate_unique_id),
@@ -623,7 +548,7 @@ class APIRoute(routing.Route):
self.path_regex, self.path_format, self.param_convertors = compile_path(path)
if methods is None:
methods = ["GET"]
- self.methods: Set[str] = {method.upper() for method in methods}
+ self.methods: set[str] = {method.upper() for method in methods}
if isinstance(generate_unique_id_function, DefaultPlaceholder):
current_generate_unique_id: Callable[[APIRoute], str] = (
generate_unique_id_function.value
@@ -640,6 +565,11 @@ class APIRoute(routing.Route):
f"Status code {status_code} must not have a response body"
)
response_name = "Response_" + self.unique_id
+ if annotation_is_pydantic_v1(self.response_model):
+ raise PydanticV1NotSupportedError(
+ "pydantic.v1 models are no longer supported by FastAPI."
+ f" Please update the response model {self.response_model!r}."
+ )
self.response_field = create_model_field(
name=response_name,
type_=self.response_model,
@@ -673,12 +603,17 @@ class APIRoute(routing.Route):
f"Status code {additional_status_code} must not have a response body"
)
response_name = f"Response_{additional_status_code}_{self.unique_id}"
+ if annotation_is_pydantic_v1(model):
+ raise PydanticV1NotSupportedError(
+ "pydantic.v1 models are no longer supported by FastAPI."
+ f" In responses={{}}, please update {model}."
+ )
response_field = create_model_field(
name=response_name, type_=model, mode="serialization"
)
response_fields[additional_status_code] = response_field
if response_fields:
- self.response_fields: Dict[Union[int, str], ModelField] = response_fields
+ self.response_fields: dict[Union[int, str], ModelField] = response_fields
else:
self.response_fields = {}
@@ -719,7 +654,7 @@ class APIRoute(routing.Route):
embed_body_fields=self._embed_body_fields,
)
- def matches(self, scope: Scope) -> Tuple[Match, Scope]:
+ def matches(self, scope: Scope) -> tuple[Match, Scope]:
match, child_scope = super().matches(scope)
if match != Match.NONE:
child_scope["route"] = self
@@ -758,7 +693,7 @@ class APIRouter(routing.Router):
*,
prefix: Annotated[str, Doc("An optional path prefix for the router.")] = "",
tags: Annotated[
- Optional[List[Union[str, Enum]]],
+ Optional[list[Union[str, Enum]]],
Doc(
"""
A list of tags to be applied to all the *path operations* in this
@@ -784,7 +719,7 @@ class APIRouter(routing.Router):
),
] = None,
default_response_class: Annotated[
- Type[Response],
+ type[Response],
Doc(
"""
The default response class to be used.
@@ -795,7 +730,7 @@ class APIRouter(routing.Router):
),
] = Default(JSONResponse),
responses: Annotated[
- Optional[Dict[Union[int, str], Dict[str, Any]]],
+ Optional[dict[Union[int, str], dict[str, Any]]],
Doc(
"""
Additional responses to be shown in OpenAPI.
@@ -811,7 +746,7 @@ class APIRouter(routing.Router):
),
] = None,
callbacks: Annotated[
- Optional[List[BaseRoute]],
+ Optional[list[BaseRoute]],
Doc(
"""
OpenAPI callbacks that should apply to all *path operations* in this
@@ -825,7 +760,7 @@ class APIRouter(routing.Router):
),
] = None,
routes: Annotated[
- Optional[List[BaseRoute]],
+ Optional[list[BaseRoute]],
Doc(
"""
**Note**: you probably shouldn't use this parameter, it is inherited
@@ -876,7 +811,7 @@ class APIRouter(routing.Router):
),
] = None,
route_class: Annotated[
- Type[APIRoute],
+ type[APIRoute],
Doc(
"""
Custom route (*path operation*) class to be used by this router.
@@ -982,7 +917,7 @@ class APIRouter(routing.Router):
"A path prefix must not end with '/', as the routes will start with '/'"
)
self.prefix = prefix
- self.tags: List[Union[str, Enum]] = tags or []
+ self.tags: list[Union[str, Enum]] = tags or []
self.dependencies = list(dependencies or [])
self.deprecated = deprecated
self.include_in_schema = include_in_schema
@@ -1019,14 +954,14 @@ class APIRouter(routing.Router):
*,
response_model: Any = Default(None),
status_code: Optional[int] = None,
- tags: Optional[List[Union[str, Enum]]] = None,
+ tags: Optional[list[Union[str, Enum]]] = None,
dependencies: Optional[Sequence[params.Depends]] = None,
summary: Optional[str] = None,
description: Optional[str] = None,
response_description: str = "Successful Response",
- responses: Optional[Dict[Union[int, str], Dict[str, Any]]] = None,
+ responses: Optional[dict[Union[int, str], dict[str, Any]]] = None,
deprecated: Optional[bool] = None,
- methods: Optional[Union[Set[str], List[str]]] = None,
+ methods: Optional[Union[set[str], list[str]]] = None,
operation_id: Optional[str] = None,
response_model_include: Optional[IncEx] = None,
response_model_exclude: Optional[IncEx] = None,
@@ -1035,13 +970,13 @@ class APIRouter(routing.Router):
response_model_exclude_defaults: bool = False,
response_model_exclude_none: bool = False,
include_in_schema: bool = True,
- response_class: Union[Type[Response], DefaultPlaceholder] = Default(
+ response_class: Union[type[Response], DefaultPlaceholder] = Default(
JSONResponse
),
name: Optional[str] = None,
- route_class_override: Optional[Type[APIRoute]] = None,
- callbacks: Optional[List[BaseRoute]] = None,
- openapi_extra: Optional[Dict[str, Any]] = None,
+ route_class_override: Optional[type[APIRoute]] = None,
+ callbacks: Optional[list[BaseRoute]] = None,
+ openapi_extra: Optional[dict[str, Any]] = None,
generate_unique_id_function: Union[
Callable[[APIRoute], str], DefaultPlaceholder
] = Default(generate_unique_id),
@@ -1100,14 +1035,14 @@ class APIRouter(routing.Router):
*,
response_model: Any = Default(None),
status_code: Optional[int] = None,
- tags: Optional[List[Union[str, Enum]]] = None,
+ tags: Optional[list[Union[str, Enum]]] = None,
dependencies: Optional[Sequence[params.Depends]] = None,
summary: Optional[str] = None,
description: Optional[str] = None,
response_description: str = "Successful Response",
- responses: Optional[Dict[Union[int, str], Dict[str, Any]]] = None,
+ responses: Optional[dict[Union[int, str], dict[str, Any]]] = None,
deprecated: Optional[bool] = None,
- methods: Optional[List[str]] = None,
+ methods: Optional[list[str]] = None,
operation_id: Optional[str] = None,
response_model_include: Optional[IncEx] = None,
response_model_exclude: Optional[IncEx] = None,
@@ -1116,10 +1051,10 @@ class APIRouter(routing.Router):
response_model_exclude_defaults: bool = False,
response_model_exclude_none: bool = False,
include_in_schema: bool = True,
- response_class: Type[Response] = Default(JSONResponse),
+ response_class: type[Response] = Default(JSONResponse),
name: Optional[str] = None,
- callbacks: Optional[List[BaseRoute]] = None,
- openapi_extra: Optional[Dict[str, Any]] = None,
+ callbacks: Optional[list[BaseRoute]] = None,
+ openapi_extra: Optional[dict[str, Any]] = None,
generate_unique_id_function: Callable[[APIRoute], str] = Default(
generate_unique_id
),
@@ -1259,7 +1194,7 @@ class APIRouter(routing.Router):
*,
prefix: Annotated[str, Doc("An optional path prefix for the router.")] = "",
tags: Annotated[
- Optional[List[Union[str, Enum]]],
+ Optional[list[Union[str, Enum]]],
Doc(
"""
A list of tags to be applied to all the *path operations* in this
@@ -1285,7 +1220,7 @@ class APIRouter(routing.Router):
),
] = None,
default_response_class: Annotated[
- Type[Response],
+ type[Response],
Doc(
"""
The default response class to be used.
@@ -1296,7 +1231,7 @@ class APIRouter(routing.Router):
),
] = Default(JSONResponse),
responses: Annotated[
- Optional[Dict[Union[int, str], Dict[str, Any]]],
+ Optional[dict[Union[int, str], dict[str, Any]]],
Doc(
"""
Additional responses to be shown in OpenAPI.
@@ -1312,7 +1247,7 @@ class APIRouter(routing.Router):
),
] = None,
callbacks: Annotated[
- Optional[List[BaseRoute]],
+ Optional[list[BaseRoute]],
Doc(
"""
OpenAPI callbacks that should apply to all *path operations* in this
@@ -1417,7 +1352,7 @@ class APIRouter(routing.Router):
current_tags.extend(tags)
if route.tags:
current_tags.extend(route.tags)
- current_dependencies: List[params.Depends] = []
+ current_dependencies: list[params.Depends] = []
if dependencies:
current_dependencies.extend(dependencies)
if route.dependencies:
@@ -1558,7 +1493,7 @@ class APIRouter(routing.Router):
),
] = None,
tags: Annotated[
- Optional[List[Union[str, Enum]]],
+ Optional[list[Union[str, Enum]]],
Doc(
"""
A list of tags to be applied to the *path operation*.
@@ -1624,7 +1559,7 @@ class APIRouter(routing.Router):
),
] = "Successful Response",
responses: Annotated[
- Optional[Dict[Union[int, str], Dict[str, Any]]],
+ Optional[dict[Union[int, str], dict[str, Any]]],
Doc(
"""
Additional responses that could be returned by this *path operation*.
@@ -1765,7 +1700,7 @@ class APIRouter(routing.Router):
),
] = True,
response_class: Annotated[
- Type[Response],
+ type[Response],
Doc(
"""
Response class to be used for this *path operation*.
@@ -1786,7 +1721,7 @@ class APIRouter(routing.Router):
),
] = None,
callbacks: Annotated[
- Optional[List[BaseRoute]],
+ Optional[list[BaseRoute]],
Doc(
"""
List of *path operations* that will be used as OpenAPI callbacks.
@@ -1802,7 +1737,7 @@ class APIRouter(routing.Router):
),
] = None,
openapi_extra: Annotated[
- Optional[Dict[str, Any]],
+ Optional[dict[str, Any]],
Doc(
"""
Extra metadata to be included in the OpenAPI schema for this *path
@@ -1935,7 +1870,7 @@ class APIRouter(routing.Router):
),
] = None,
tags: Annotated[
- Optional[List[Union[str, Enum]]],
+ Optional[list[Union[str, Enum]]],
Doc(
"""
A list of tags to be applied to the *path operation*.
@@ -2001,7 +1936,7 @@ class APIRouter(routing.Router):
),
] = "Successful Response",
responses: Annotated[
- Optional[Dict[Union[int, str], Dict[str, Any]]],
+ Optional[dict[Union[int, str], dict[str, Any]]],
Doc(
"""
Additional responses that could be returned by this *path operation*.
@@ -2142,7 +2077,7 @@ class APIRouter(routing.Router):
),
] = True,
response_class: Annotated[
- Type[Response],
+ type[Response],
Doc(
"""
Response class to be used for this *path operation*.
@@ -2163,7 +2098,7 @@ class APIRouter(routing.Router):
),
] = None,
callbacks: Annotated[
- Optional[List[BaseRoute]],
+ Optional[list[BaseRoute]],
Doc(
"""
List of *path operations* that will be used as OpenAPI callbacks.
@@ -2179,7 +2114,7 @@ class APIRouter(routing.Router):
),
] = None,
openapi_extra: Annotated[
- Optional[Dict[str, Any]],
+ Optional[dict[str, Any]],
Doc(
"""
Extra metadata to be included in the OpenAPI schema for this *path
@@ -2317,7 +2252,7 @@ class APIRouter(routing.Router):
),
] = None,
tags: Annotated[
- Optional[List[Union[str, Enum]]],
+ Optional[list[Union[str, Enum]]],
Doc(
"""
A list of tags to be applied to the *path operation*.
@@ -2383,7 +2318,7 @@ class APIRouter(routing.Router):
),
] = "Successful Response",
responses: Annotated[
- Optional[Dict[Union[int, str], Dict[str, Any]]],
+ Optional[dict[Union[int, str], dict[str, Any]]],
Doc(
"""
Additional responses that could be returned by this *path operation*.
@@ -2524,7 +2459,7 @@ class APIRouter(routing.Router):
),
] = True,
response_class: Annotated[
- Type[Response],
+ type[Response],
Doc(
"""
Response class to be used for this *path operation*.
@@ -2545,7 +2480,7 @@ class APIRouter(routing.Router):
),
] = None,
callbacks: Annotated[
- Optional[List[BaseRoute]],
+ Optional[list[BaseRoute]],
Doc(
"""
List of *path operations* that will be used as OpenAPI callbacks.
@@ -2561,7 +2496,7 @@ class APIRouter(routing.Router):
),
] = None,
openapi_extra: Annotated[
- Optional[Dict[str, Any]],
+ Optional[dict[str, Any]],
Doc(
"""
Extra metadata to be included in the OpenAPI schema for this *path
@@ -2699,7 +2634,7 @@ class APIRouter(routing.Router):
),
] = None,
tags: Annotated[
- Optional[List[Union[str, Enum]]],
+ Optional[list[Union[str, Enum]]],
Doc(
"""
A list of tags to be applied to the *path operation*.
@@ -2765,7 +2700,7 @@ class APIRouter(routing.Router):
),
] = "Successful Response",
responses: Annotated[
- Optional[Dict[Union[int, str], Dict[str, Any]]],
+ Optional[dict[Union[int, str], dict[str, Any]]],
Doc(
"""
Additional responses that could be returned by this *path operation*.
@@ -2906,7 +2841,7 @@ class APIRouter(routing.Router):
),
] = True,
response_class: Annotated[
- Type[Response],
+ type[Response],
Doc(
"""
Response class to be used for this *path operation*.
@@ -2927,7 +2862,7 @@ class APIRouter(routing.Router):
),
] = None,
callbacks: Annotated[
- Optional[List[BaseRoute]],
+ Optional[list[BaseRoute]],
Doc(
"""
List of *path operations* that will be used as OpenAPI callbacks.
@@ -2943,7 +2878,7 @@ class APIRouter(routing.Router):
),
] = None,
openapi_extra: Annotated[
- Optional[Dict[str, Any]],
+ Optional[dict[str, Any]],
Doc(
"""
Extra metadata to be included in the OpenAPI schema for this *path
@@ -3076,7 +3011,7 @@ class APIRouter(routing.Router):
),
] = None,
tags: Annotated[
- Optional[List[Union[str, Enum]]],
+ Optional[list[Union[str, Enum]]],
Doc(
"""
A list of tags to be applied to the *path operation*.
@@ -3142,7 +3077,7 @@ class APIRouter(routing.Router):
),
] = "Successful Response",
responses: Annotated[
- Optional[Dict[Union[int, str], Dict[str, Any]]],
+ Optional[dict[Union[int, str], dict[str, Any]]],
Doc(
"""
Additional responses that could be returned by this *path operation*.
@@ -3283,7 +3218,7 @@ class APIRouter(routing.Router):
),
] = True,
response_class: Annotated[
- Type[Response],
+ type[Response],
Doc(
"""
Response class to be used for this *path operation*.
@@ -3304,7 +3239,7 @@ class APIRouter(routing.Router):
),
] = None,
callbacks: Annotated[
- Optional[List[BaseRoute]],
+ Optional[list[BaseRoute]],
Doc(
"""
List of *path operations* that will be used as OpenAPI callbacks.
@@ -3320,7 +3255,7 @@ class APIRouter(routing.Router):
),
] = None,
openapi_extra: Annotated[
- Optional[Dict[str, Any]],
+ Optional[dict[str, Any]],
Doc(
"""
Extra metadata to be included in the OpenAPI schema for this *path
@@ -3453,7 +3388,7 @@ class APIRouter(routing.Router):
),
] = None,
tags: Annotated[
- Optional[List[Union[str, Enum]]],
+ Optional[list[Union[str, Enum]]],
Doc(
"""
A list of tags to be applied to the *path operation*.
@@ -3519,7 +3454,7 @@ class APIRouter(routing.Router):
),
] = "Successful Response",
responses: Annotated[
- Optional[Dict[Union[int, str], Dict[str, Any]]],
+ Optional[dict[Union[int, str], dict[str, Any]]],
Doc(
"""
Additional responses that could be returned by this *path operation*.
@@ -3660,7 +3595,7 @@ class APIRouter(routing.Router):
),
] = True,
response_class: Annotated[
- Type[Response],
+ type[Response],
Doc(
"""
Response class to be used for this *path operation*.
@@ -3681,7 +3616,7 @@ class APIRouter(routing.Router):
),
] = None,
callbacks: Annotated[
- Optional[List[BaseRoute]],
+ Optional[list[BaseRoute]],
Doc(
"""
List of *path operations* that will be used as OpenAPI callbacks.
@@ -3697,7 +3632,7 @@ class APIRouter(routing.Router):
),
] = None,
openapi_extra: Annotated[
- Optional[Dict[str, Any]],
+ Optional[dict[str, Any]],
Doc(
"""
Extra metadata to be included in the OpenAPI schema for this *path
@@ -3835,7 +3770,7 @@ class APIRouter(routing.Router):
),
] = None,
tags: Annotated[
- Optional[List[Union[str, Enum]]],
+ Optional[list[Union[str, Enum]]],
Doc(
"""
A list of tags to be applied to the *path operation*.
@@ -3901,7 +3836,7 @@ class APIRouter(routing.Router):
),
] = "Successful Response",
responses: Annotated[
- Optional[Dict[Union[int, str], Dict[str, Any]]],
+ Optional[dict[Union[int, str], dict[str, Any]]],
Doc(
"""
Additional responses that could be returned by this *path operation*.
@@ -4042,7 +3977,7 @@ class APIRouter(routing.Router):
),
] = True,
response_class: Annotated[
- Type[Response],
+ type[Response],
Doc(
"""
Response class to be used for this *path operation*.
@@ -4063,7 +3998,7 @@ class APIRouter(routing.Router):
),
] = None,
callbacks: Annotated[
- Optional[List[BaseRoute]],
+ Optional[list[BaseRoute]],
Doc(
"""
List of *path operations* that will be used as OpenAPI callbacks.
@@ -4079,7 +4014,7 @@ class APIRouter(routing.Router):
),
] = None,
openapi_extra: Annotated[
- Optional[Dict[str, Any]],
+ Optional[dict[str, Any]],
Doc(
"""
Extra metadata to be included in the OpenAPI schema for this *path
@@ -4217,7 +4152,7 @@ class APIRouter(routing.Router):
),
] = None,
tags: Annotated[
- Optional[List[Union[str, Enum]]],
+ Optional[list[Union[str, Enum]]],
Doc(
"""
A list of tags to be applied to the *path operation*.
@@ -4283,7 +4218,7 @@ class APIRouter(routing.Router):
),
] = "Successful Response",
responses: Annotated[
- Optional[Dict[Union[int, str], Dict[str, Any]]],
+ Optional[dict[Union[int, str], dict[str, Any]]],
Doc(
"""
Additional responses that could be returned by this *path operation*.
@@ -4424,7 +4359,7 @@ class APIRouter(routing.Router):
),
] = True,
response_class: Annotated[
- Type[Response],
+ type[Response],
Doc(
"""
Response class to be used for this *path operation*.
@@ -4445,7 +4380,7 @@ class APIRouter(routing.Router):
),
] = None,
callbacks: Annotated[
- Optional[List[BaseRoute]],
+ Optional[list[BaseRoute]],
Doc(
"""
List of *path operations* that will be used as OpenAPI callbacks.
@@ -4461,7 +4396,7 @@ class APIRouter(routing.Router):
),
] = None,
openapi_extra: Annotated[
- Optional[Dict[str, Any]],
+ Optional[dict[str, Any]],
Doc(
"""
Extra metadata to be included in the OpenAPI schema for this *path
diff --git a/fastapi/security/api_key.py b/fastapi/security/api_key.py
index f64370e3e5..9da5e24834 100644
--- a/fastapi/security/api_key.py
+++ b/fastapi/security/api_key.py
@@ -1,4 +1,4 @@
-from typing import Optional, Union
+from typing import Annotated, Optional, Union
from annotated_doc import Doc
from fastapi.openapi.models import APIKey, APIKeyIn
@@ -6,7 +6,6 @@ from fastapi.security.base import SecurityBase
from starlette.exceptions import HTTPException
from starlette.requests import HTTPConnection
from starlette.status import HTTP_401_UNAUTHORIZED
-from typing_extensions import Annotated
class APIKeyBase(SecurityBase):
diff --git a/fastapi/security/http.py b/fastapi/security/http.py
index a6de1ba2ba..04ada9aeb6 100644
--- a/fastapi/security/http.py
+++ b/fastapi/security/http.py
@@ -1,6 +1,6 @@
import binascii
from base64 import b64decode
-from typing import Dict, Optional
+from typing import Annotated, Optional
from annotated_doc import Doc
from fastapi.exceptions import HTTPException
@@ -11,7 +11,6 @@ from fastapi.security.utils import get_authorization_scheme_param
from pydantic import BaseModel
from starlette.requests import HTTPConnection
from starlette.status import HTTP_401_UNAUTHORIZED
-from typing_extensions import Annotated
class HTTPBasicCredentials(BaseModel):
@@ -82,7 +81,7 @@ class HTTPBase(SecurityBase):
self.scheme_name = scheme_name or self.__class__.__name__
self.auto_error = auto_error
- def make_authenticate_headers(self) -> Dict[str, str]:
+ def make_authenticate_headers(self) -> dict[str, str]:
return {"WWW-Authenticate": f"{self.model.scheme.title()}"}
def make_not_authenticated_error(self) -> HTTPException:
@@ -197,7 +196,7 @@ class HTTPBasic(HTTPBase):
self.realm = realm
self.auto_error = auto_error
- def make_authenticate_headers(self) -> Dict[str, str]:
+ def make_authenticate_headers(self) -> dict[str, str]:
if self.realm:
return {"WWW-Authenticate": f'Basic realm="{self.realm}"'}
return {"WWW-Authenticate": "Basic"}
diff --git a/fastapi/security/oauth2.py b/fastapi/security/oauth2.py
index 7d666d320e..e8c2da6566 100644
--- a/fastapi/security/oauth2.py
+++ b/fastapi/security/oauth2.py
@@ -1,4 +1,4 @@
-from typing import Any, Dict, List, Optional, Union, cast
+from typing import Annotated, Any, Optional, Union, cast
from annotated_doc import Doc
from fastapi.exceptions import HTTPException
@@ -10,9 +10,6 @@ from fastapi.security.utils import get_authorization_scheme_param
from starlette.requests import HTTPConnection
from starlette.status import HTTP_401_UNAUTHORIZED
-# TODO: import from typing when deprecating Python 3.9
-from typing_extensions import Annotated
-
class OAuth2PasswordRequestForm:
"""
@@ -323,7 +320,7 @@ class OAuth2(SecurityBase):
self,
*,
flows: Annotated[
- Union[OAuthFlowsModel, Dict[str, Dict[str, Any]]],
+ Union[OAuthFlowsModel, dict[str, dict[str, Any]]],
Doc(
"""
The dictionary of OAuth2 flows.
@@ -440,7 +437,7 @@ class OAuth2PasswordBearer(OAuth2):
),
] = None,
scopes: Annotated[
- Optional[Dict[str, str]],
+ Optional[dict[str, str]],
Doc(
"""
The OAuth2 scopes that would be required by the *path operations* that
@@ -553,7 +550,7 @@ class OAuth2AuthorizationCodeBearer(OAuth2):
),
] = None,
scopes: Annotated[
- Optional[Dict[str, str]],
+ Optional[dict[str, str]],
Doc(
"""
The OAuth2 scopes that would be required by the *path operations* that
@@ -639,7 +636,7 @@ class SecurityScopes:
def __init__(
self,
scopes: Annotated[
- Optional[List[str]],
+ Optional[list[str]],
Doc(
"""
This will be filled by FastAPI.
@@ -648,7 +645,7 @@ class SecurityScopes:
] = None,
):
self.scopes: Annotated[
- List[str],
+ list[str],
Doc(
"""
The list of all the scopes required by dependencies.
diff --git a/fastapi/security/open_id_connect_url.py b/fastapi/security/open_id_connect_url.py
index 4fdd7a89c7..ba4598ddab 100644
--- a/fastapi/security/open_id_connect_url.py
+++ b/fastapi/security/open_id_connect_url.py
@@ -1,4 +1,4 @@
-from typing import Optional
+from typing import Annotated, Optional
from annotated_doc import Doc
from fastapi.openapi.models import OpenIdConnect as OpenIdConnectModel
@@ -6,7 +6,6 @@ from fastapi.security.base import SecurityBase
from starlette.exceptions import HTTPException
from starlette.requests import HTTPConnection
from starlette.status import HTTP_401_UNAUTHORIZED
-from typing_extensions import Annotated
class OpenIdConnect(SecurityBase):
diff --git a/fastapi/security/utils.py b/fastapi/security/utils.py
index fa7a450b74..002e68b445 100644
--- a/fastapi/security/utils.py
+++ b/fastapi/security/utils.py
@@ -1,9 +1,9 @@
-from typing import Optional, Tuple
+from typing import Optional
def get_authorization_scheme_param(
authorization_header_value: Optional[str],
-) -> Tuple[str, str]:
+) -> tuple[str, str]:
if not authorization_header_value:
return "", ""
scheme, _, param = authorization_header_value.partition(" ")
diff --git a/fastapi/temp_pydantic_v1_params.py b/fastapi/temp_pydantic_v1_params.py
deleted file mode 100644
index e41d712308..0000000000
--- a/fastapi/temp_pydantic_v1_params.py
+++ /dev/null
@@ -1,724 +0,0 @@
-import warnings
-from typing import Any, Callable, Dict, List, Optional, Union
-
-from fastapi.openapi.models import Example
-from fastapi.params import ParamTypes
-from typing_extensions import Annotated, deprecated
-
-from ._compat.may_v1 import FieldInfo, Undefined
-from ._compat.shared import PYDANTIC_VERSION_MINOR_TUPLE
-
-_Unset: Any = Undefined
-
-
-class Param(FieldInfo): # type: ignore[misc]
- in_: ParamTypes
-
- def __init__(
- self,
- default: Any = Undefined,
- *,
- default_factory: Union[Callable[[], Any], None] = _Unset,
- annotation: Optional[Any] = None,
- alias: Optional[str] = None,
- alias_priority: Union[int, None] = _Unset,
- # TODO: update when deprecating Pydantic v1, import these types
- # validation_alias: str | AliasPath | AliasChoices | None
- validation_alias: Union[str, None] = None,
- serialization_alias: Union[str, None] = None,
- title: Optional[str] = None,
- description: Optional[str] = None,
- gt: Optional[float] = None,
- ge: Optional[float] = None,
- lt: Optional[float] = None,
- le: Optional[float] = None,
- min_length: Optional[int] = None,
- max_length: Optional[int] = None,
- pattern: Optional[str] = None,
- regex: Annotated[
- Optional[str],
- deprecated(
- "Deprecated in FastAPI 0.100.0 and Pydantic v2, use `pattern` instead."
- ),
- ] = None,
- discriminator: Union[str, None] = None,
- strict: Union[bool, None] = _Unset,
- multiple_of: Union[float, None] = _Unset,
- allow_inf_nan: Union[bool, None] = _Unset,
- max_digits: Union[int, None] = _Unset,
- decimal_places: Union[int, None] = _Unset,
- examples: Optional[List[Any]] = None,
- example: Annotated[
- Optional[Any],
- deprecated(
- "Deprecated in OpenAPI 3.1.0 that now uses JSON Schema 2020-12, "
- "although still supported. Use examples instead."
- ),
- ] = _Unset,
- openapi_examples: Optional[Dict[str, Example]] = None,
- deprecated: Union[deprecated, str, bool, None] = None,
- include_in_schema: bool = True,
- json_schema_extra: Union[Dict[str, Any], None] = None,
- **extra: Any,
- ):
- if example is not _Unset:
- warnings.warn(
- "`example` has been deprecated, please use `examples` instead",
- category=DeprecationWarning,
- stacklevel=4,
- )
- self.example = example
- self.include_in_schema = include_in_schema
- self.openapi_examples = openapi_examples
- kwargs = dict(
- default=default,
- default_factory=default_factory,
- alias=alias,
- title=title,
- description=description,
- gt=gt,
- ge=ge,
- lt=lt,
- le=le,
- min_length=min_length,
- max_length=max_length,
- discriminator=discriminator,
- multiple_of=multiple_of,
- allow_inf_nan=allow_inf_nan,
- max_digits=max_digits,
- decimal_places=decimal_places,
- **extra,
- )
- if examples is not None:
- kwargs["examples"] = examples
- if regex is not None:
- warnings.warn(
- "`regex` has been deprecated, please use `pattern` instead",
- category=DeprecationWarning,
- stacklevel=4,
- )
- current_json_schema_extra = json_schema_extra or extra
- if PYDANTIC_VERSION_MINOR_TUPLE < (2, 7):
- self.deprecated = deprecated
- else:
- kwargs["deprecated"] = deprecated
- kwargs["regex"] = pattern or regex
- kwargs.update(**current_json_schema_extra)
- use_kwargs = {k: v for k, v in kwargs.items() if v is not _Unset}
-
- super().__init__(**use_kwargs)
-
- def __repr__(self) -> str:
- return f"{self.__class__.__name__}({self.default})"
-
-
-class Path(Param): # type: ignore[misc]
- in_ = ParamTypes.path
-
- def __init__(
- self,
- default: Any = ...,
- *,
- default_factory: Union[Callable[[], Any], None] = _Unset,
- annotation: Optional[Any] = None,
- alias: Optional[str] = None,
- alias_priority: Union[int, None] = _Unset,
- # TODO: update when deprecating Pydantic v1, import these types
- # validation_alias: str | AliasPath | AliasChoices | None
- validation_alias: Union[str, None] = None,
- serialization_alias: Union[str, None] = None,
- title: Optional[str] = None,
- description: Optional[str] = None,
- gt: Optional[float] = None,
- ge: Optional[float] = None,
- lt: Optional[float] = None,
- le: Optional[float] = None,
- min_length: Optional[int] = None,
- max_length: Optional[int] = None,
- pattern: Optional[str] = None,
- regex: Annotated[
- Optional[str],
- deprecated(
- "Deprecated in FastAPI 0.100.0 and Pydantic v2, use `pattern` instead."
- ),
- ] = None,
- discriminator: Union[str, None] = None,
- strict: Union[bool, None] = _Unset,
- multiple_of: Union[float, None] = _Unset,
- allow_inf_nan: Union[bool, None] = _Unset,
- max_digits: Union[int, None] = _Unset,
- decimal_places: Union[int, None] = _Unset,
- examples: Optional[List[Any]] = None,
- example: Annotated[
- Optional[Any],
- deprecated(
- "Deprecated in OpenAPI 3.1.0 that now uses JSON Schema 2020-12, "
- "although still supported. Use examples instead."
- ),
- ] = _Unset,
- openapi_examples: Optional[Dict[str, Example]] = None,
- deprecated: Union[deprecated, str, bool, None] = None,
- include_in_schema: bool = True,
- json_schema_extra: Union[Dict[str, Any], None] = None,
- **extra: Any,
- ):
- assert default is ..., "Path parameters cannot have a default value"
- self.in_ = self.in_
- super().__init__(
- default=default,
- default_factory=default_factory,
- annotation=annotation,
- alias=alias,
- alias_priority=alias_priority,
- validation_alias=validation_alias,
- serialization_alias=serialization_alias,
- title=title,
- description=description,
- gt=gt,
- ge=ge,
- lt=lt,
- le=le,
- min_length=min_length,
- max_length=max_length,
- pattern=pattern,
- regex=regex,
- discriminator=discriminator,
- strict=strict,
- multiple_of=multiple_of,
- allow_inf_nan=allow_inf_nan,
- max_digits=max_digits,
- decimal_places=decimal_places,
- deprecated=deprecated,
- example=example,
- examples=examples,
- openapi_examples=openapi_examples,
- include_in_schema=include_in_schema,
- json_schema_extra=json_schema_extra,
- **extra,
- )
-
-
-class Query(Param): # type: ignore[misc]
- in_ = ParamTypes.query
-
- def __init__(
- self,
- default: Any = Undefined,
- *,
- default_factory: Union[Callable[[], Any], None] = _Unset,
- annotation: Optional[Any] = None,
- alias: Optional[str] = None,
- alias_priority: Union[int, None] = _Unset,
- # TODO: update when deprecating Pydantic v1, import these types
- # validation_alias: str | AliasPath | AliasChoices | None
- validation_alias: Union[str, None] = None,
- serialization_alias: Union[str, None] = None,
- title: Optional[str] = None,
- description: Optional[str] = None,
- gt: Optional[float] = None,
- ge: Optional[float] = None,
- lt: Optional[float] = None,
- le: Optional[float] = None,
- min_length: Optional[int] = None,
- max_length: Optional[int] = None,
- pattern: Optional[str] = None,
- regex: Annotated[
- Optional[str],
- deprecated(
- "Deprecated in FastAPI 0.100.0 and Pydantic v2, use `pattern` instead."
- ),
- ] = None,
- discriminator: Union[str, None] = None,
- strict: Union[bool, None] = _Unset,
- multiple_of: Union[float, None] = _Unset,
- allow_inf_nan: Union[bool, None] = _Unset,
- max_digits: Union[int, None] = _Unset,
- decimal_places: Union[int, None] = _Unset,
- examples: Optional[List[Any]] = None,
- example: Annotated[
- Optional[Any],
- deprecated(
- "Deprecated in OpenAPI 3.1.0 that now uses JSON Schema 2020-12, "
- "although still supported. Use examples instead."
- ),
- ] = _Unset,
- openapi_examples: Optional[Dict[str, Example]] = None,
- deprecated: Union[deprecated, str, bool, None] = None,
- include_in_schema: bool = True,
- json_schema_extra: Union[Dict[str, Any], None] = None,
- **extra: Any,
- ):
- super().__init__(
- default=default,
- default_factory=default_factory,
- annotation=annotation,
- alias=alias,
- alias_priority=alias_priority,
- validation_alias=validation_alias,
- serialization_alias=serialization_alias,
- title=title,
- description=description,
- gt=gt,
- ge=ge,
- lt=lt,
- le=le,
- min_length=min_length,
- max_length=max_length,
- pattern=pattern,
- regex=regex,
- discriminator=discriminator,
- strict=strict,
- multiple_of=multiple_of,
- allow_inf_nan=allow_inf_nan,
- max_digits=max_digits,
- decimal_places=decimal_places,
- deprecated=deprecated,
- example=example,
- examples=examples,
- openapi_examples=openapi_examples,
- include_in_schema=include_in_schema,
- json_schema_extra=json_schema_extra,
- **extra,
- )
-
-
-class Header(Param): # type: ignore[misc]
- in_ = ParamTypes.header
-
- def __init__(
- self,
- default: Any = Undefined,
- *,
- default_factory: Union[Callable[[], Any], None] = _Unset,
- annotation: Optional[Any] = None,
- alias: Optional[str] = None,
- alias_priority: Union[int, None] = _Unset,
- # TODO: update when deprecating Pydantic v1, import these types
- # validation_alias: str | AliasPath | AliasChoices | None
- validation_alias: Union[str, None] = None,
- serialization_alias: Union[str, None] = None,
- convert_underscores: bool = True,
- title: Optional[str] = None,
- description: Optional[str] = None,
- gt: Optional[float] = None,
- ge: Optional[float] = None,
- lt: Optional[float] = None,
- le: Optional[float] = None,
- min_length: Optional[int] = None,
- max_length: Optional[int] = None,
- pattern: Optional[str] = None,
- regex: Annotated[
- Optional[str],
- deprecated(
- "Deprecated in FastAPI 0.100.0 and Pydantic v2, use `pattern` instead."
- ),
- ] = None,
- discriminator: Union[str, None] = None,
- strict: Union[bool, None] = _Unset,
- multiple_of: Union[float, None] = _Unset,
- allow_inf_nan: Union[bool, None] = _Unset,
- max_digits: Union[int, None] = _Unset,
- decimal_places: Union[int, None] = _Unset,
- examples: Optional[List[Any]] = None,
- example: Annotated[
- Optional[Any],
- deprecated(
- "Deprecated in OpenAPI 3.1.0 that now uses JSON Schema 2020-12, "
- "although still supported. Use examples instead."
- ),
- ] = _Unset,
- openapi_examples: Optional[Dict[str, Example]] = None,
- deprecated: Union[deprecated, str, bool, None] = None,
- include_in_schema: bool = True,
- json_schema_extra: Union[Dict[str, Any], None] = None,
- **extra: Any,
- ):
- self.convert_underscores = convert_underscores
- super().__init__(
- default=default,
- default_factory=default_factory,
- annotation=annotation,
- alias=alias,
- alias_priority=alias_priority,
- validation_alias=validation_alias,
- serialization_alias=serialization_alias,
- title=title,
- description=description,
- gt=gt,
- ge=ge,
- lt=lt,
- le=le,
- min_length=min_length,
- max_length=max_length,
- pattern=pattern,
- regex=regex,
- discriminator=discriminator,
- strict=strict,
- multiple_of=multiple_of,
- allow_inf_nan=allow_inf_nan,
- max_digits=max_digits,
- decimal_places=decimal_places,
- deprecated=deprecated,
- example=example,
- examples=examples,
- openapi_examples=openapi_examples,
- include_in_schema=include_in_schema,
- json_schema_extra=json_schema_extra,
- **extra,
- )
-
-
-class Cookie(Param): # type: ignore[misc]
- in_ = ParamTypes.cookie
-
- def __init__(
- self,
- default: Any = Undefined,
- *,
- default_factory: Union[Callable[[], Any], None] = _Unset,
- annotation: Optional[Any] = None,
- alias: Optional[str] = None,
- alias_priority: Union[int, None] = _Unset,
- # TODO: update when deprecating Pydantic v1, import these types
- # validation_alias: str | AliasPath | AliasChoices | None
- validation_alias: Union[str, None] = None,
- serialization_alias: Union[str, None] = None,
- title: Optional[str] = None,
- description: Optional[str] = None,
- gt: Optional[float] = None,
- ge: Optional[float] = None,
- lt: Optional[float] = None,
- le: Optional[float] = None,
- min_length: Optional[int] = None,
- max_length: Optional[int] = None,
- pattern: Optional[str] = None,
- regex: Annotated[
- Optional[str],
- deprecated(
- "Deprecated in FastAPI 0.100.0 and Pydantic v2, use `pattern` instead."
- ),
- ] = None,
- discriminator: Union[str, None] = None,
- strict: Union[bool, None] = _Unset,
- multiple_of: Union[float, None] = _Unset,
- allow_inf_nan: Union[bool, None] = _Unset,
- max_digits: Union[int, None] = _Unset,
- decimal_places: Union[int, None] = _Unset,
- examples: Optional[List[Any]] = None,
- example: Annotated[
- Optional[Any],
- deprecated(
- "Deprecated in OpenAPI 3.1.0 that now uses JSON Schema 2020-12, "
- "although still supported. Use examples instead."
- ),
- ] = _Unset,
- openapi_examples: Optional[Dict[str, Example]] = None,
- deprecated: Union[deprecated, str, bool, None] = None,
- include_in_schema: bool = True,
- json_schema_extra: Union[Dict[str, Any], None] = None,
- **extra: Any,
- ):
- super().__init__(
- default=default,
- default_factory=default_factory,
- annotation=annotation,
- alias=alias,
- alias_priority=alias_priority,
- validation_alias=validation_alias,
- serialization_alias=serialization_alias,
- title=title,
- description=description,
- gt=gt,
- ge=ge,
- lt=lt,
- le=le,
- min_length=min_length,
- max_length=max_length,
- pattern=pattern,
- regex=regex,
- discriminator=discriminator,
- strict=strict,
- multiple_of=multiple_of,
- allow_inf_nan=allow_inf_nan,
- max_digits=max_digits,
- decimal_places=decimal_places,
- deprecated=deprecated,
- example=example,
- examples=examples,
- openapi_examples=openapi_examples,
- include_in_schema=include_in_schema,
- json_schema_extra=json_schema_extra,
- **extra,
- )
-
-
-class Body(FieldInfo): # type: ignore[misc]
- def __init__(
- self,
- default: Any = Undefined,
- *,
- default_factory: Union[Callable[[], Any], None] = _Unset,
- annotation: Optional[Any] = None,
- embed: Union[bool, None] = None,
- media_type: str = "application/json",
- alias: Optional[str] = None,
- alias_priority: Union[int, None] = _Unset,
- # TODO: update when deprecating Pydantic v1, import these types
- # validation_alias: str | AliasPath | AliasChoices | None
- validation_alias: Union[str, None] = None,
- serialization_alias: Union[str, None] = None,
- title: Optional[str] = None,
- description: Optional[str] = None,
- gt: Optional[float] = None,
- ge: Optional[float] = None,
- lt: Optional[float] = None,
- le: Optional[float] = None,
- min_length: Optional[int] = None,
- max_length: Optional[int] = None,
- pattern: Optional[str] = None,
- regex: Annotated[
- Optional[str],
- deprecated(
- "Deprecated in FastAPI 0.100.0 and Pydantic v2, use `pattern` instead."
- ),
- ] = None,
- discriminator: Union[str, None] = None,
- strict: Union[bool, None] = _Unset,
- multiple_of: Union[float, None] = _Unset,
- allow_inf_nan: Union[bool, None] = _Unset,
- max_digits: Union[int, None] = _Unset,
- decimal_places: Union[int, None] = _Unset,
- examples: Optional[List[Any]] = None,
- example: Annotated[
- Optional[Any],
- deprecated(
- "Deprecated in OpenAPI 3.1.0 that now uses JSON Schema 2020-12, "
- "although still supported. Use examples instead."
- ),
- ] = _Unset,
- openapi_examples: Optional[Dict[str, Example]] = None,
- deprecated: 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
- if example is not _Unset:
- warnings.warn(
- "`example` has been deprecated, please use `examples` instead",
- category=DeprecationWarning,
- stacklevel=4,
- )
- self.example = example
- self.include_in_schema = include_in_schema
- self.openapi_examples = openapi_examples
- kwargs = dict(
- default=default,
- default_factory=default_factory,
- alias=alias,
- title=title,
- description=description,
- gt=gt,
- ge=ge,
- lt=lt,
- le=le,
- min_length=min_length,
- max_length=max_length,
- discriminator=discriminator,
- multiple_of=multiple_of,
- allow_inf_nan=allow_inf_nan,
- max_digits=max_digits,
- decimal_places=decimal_places,
- **extra,
- )
- if examples is not None:
- kwargs["examples"] = examples
- if regex is not None:
- warnings.warn(
- "`regex` has been deprecated, please use `pattern` instead",
- category=DeprecationWarning,
- stacklevel=4,
- )
- current_json_schema_extra = json_schema_extra or extra
- if PYDANTIC_VERSION_MINOR_TUPLE < (2, 7):
- self.deprecated = deprecated
- else:
- kwargs["deprecated"] = deprecated
- kwargs["regex"] = pattern or regex
- kwargs.update(**current_json_schema_extra)
-
- use_kwargs = {k: v for k, v in kwargs.items() if v is not _Unset}
-
- super().__init__(**use_kwargs)
-
- def __repr__(self) -> str:
- return f"{self.__class__.__name__}({self.default})"
-
-
-class Form(Body): # type: ignore[misc]
- def __init__(
- self,
- default: Any = Undefined,
- *,
- default_factory: Union[Callable[[], Any], None] = _Unset,
- annotation: Optional[Any] = None,
- media_type: str = "application/x-www-form-urlencoded",
- alias: Optional[str] = None,
- alias_priority: Union[int, None] = _Unset,
- # TODO: update when deprecating Pydantic v1, import these types
- # validation_alias: str | AliasPath | AliasChoices | None
- validation_alias: Union[str, None] = None,
- serialization_alias: Union[str, None] = None,
- title: Optional[str] = None,
- description: Optional[str] = None,
- gt: Optional[float] = None,
- ge: Optional[float] = None,
- lt: Optional[float] = None,
- le: Optional[float] = None,
- min_length: Optional[int] = None,
- max_length: Optional[int] = None,
- pattern: Optional[str] = None,
- regex: Annotated[
- Optional[str],
- deprecated(
- "Deprecated in FastAPI 0.100.0 and Pydantic v2, use `pattern` instead."
- ),
- ] = None,
- discriminator: Union[str, None] = None,
- strict: Union[bool, None] = _Unset,
- multiple_of: Union[float, None] = _Unset,
- allow_inf_nan: Union[bool, None] = _Unset,
- max_digits: Union[int, None] = _Unset,
- decimal_places: Union[int, None] = _Unset,
- examples: Optional[List[Any]] = None,
- example: Annotated[
- Optional[Any],
- deprecated(
- "Deprecated in OpenAPI 3.1.0 that now uses JSON Schema 2020-12, "
- "although still supported. Use examples instead."
- ),
- ] = _Unset,
- openapi_examples: Optional[Dict[str, Example]] = None,
- deprecated: Union[deprecated, str, bool, None] = None,
- include_in_schema: bool = True,
- json_schema_extra: Union[Dict[str, Any], None] = None,
- **extra: Any,
- ):
- super().__init__(
- default=default,
- default_factory=default_factory,
- annotation=annotation,
- media_type=media_type,
- alias=alias,
- alias_priority=alias_priority,
- validation_alias=validation_alias,
- serialization_alias=serialization_alias,
- title=title,
- description=description,
- gt=gt,
- ge=ge,
- lt=lt,
- le=le,
- min_length=min_length,
- max_length=max_length,
- pattern=pattern,
- regex=regex,
- discriminator=discriminator,
- strict=strict,
- multiple_of=multiple_of,
- allow_inf_nan=allow_inf_nan,
- max_digits=max_digits,
- decimal_places=decimal_places,
- deprecated=deprecated,
- example=example,
- examples=examples,
- openapi_examples=openapi_examples,
- include_in_schema=include_in_schema,
- json_schema_extra=json_schema_extra,
- **extra,
- )
-
-
-class File(Form): # type: ignore[misc]
- def __init__(
- self,
- default: Any = Undefined,
- *,
- default_factory: Union[Callable[[], Any], None] = _Unset,
- annotation: Optional[Any] = None,
- media_type: str = "multipart/form-data",
- alias: Optional[str] = None,
- alias_priority: Union[int, None] = _Unset,
- # TODO: update when deprecating Pydantic v1, import these types
- # validation_alias: str | AliasPath | AliasChoices | None
- validation_alias: Union[str, None] = None,
- serialization_alias: Union[str, None] = None,
- title: Optional[str] = None,
- description: Optional[str] = None,
- gt: Optional[float] = None,
- ge: Optional[float] = None,
- lt: Optional[float] = None,
- le: Optional[float] = None,
- min_length: Optional[int] = None,
- max_length: Optional[int] = None,
- pattern: Optional[str] = None,
- regex: Annotated[
- Optional[str],
- deprecated(
- "Deprecated in FastAPI 0.100.0 and Pydantic v2, use `pattern` instead."
- ),
- ] = None,
- discriminator: Union[str, None] = None,
- strict: Union[bool, None] = _Unset,
- multiple_of: Union[float, None] = _Unset,
- allow_inf_nan: Union[bool, None] = _Unset,
- max_digits: Union[int, None] = _Unset,
- decimal_places: Union[int, None] = _Unset,
- examples: Optional[List[Any]] = None,
- example: Annotated[
- Optional[Any],
- deprecated(
- "Deprecated in OpenAPI 3.1.0 that now uses JSON Schema 2020-12, "
- "although still supported. Use examples instead."
- ),
- ] = _Unset,
- openapi_examples: Optional[Dict[str, Example]] = None,
- deprecated: Union[deprecated, str, bool, None] = None,
- include_in_schema: bool = True,
- json_schema_extra: Union[Dict[str, Any], None] = None,
- **extra: Any,
- ):
- super().__init__(
- default=default,
- default_factory=default_factory,
- annotation=annotation,
- media_type=media_type,
- alias=alias,
- alias_priority=alias_priority,
- validation_alias=validation_alias,
- serialization_alias=serialization_alias,
- title=title,
- description=description,
- gt=gt,
- ge=ge,
- lt=lt,
- le=le,
- min_length=min_length,
- max_length=max_length,
- pattern=pattern,
- regex=regex,
- discriminator=discriminator,
- strict=strict,
- multiple_of=multiple_of,
- allow_inf_nan=allow_inf_nan,
- max_digits=max_digits,
- decimal_places=decimal_places,
- deprecated=deprecated,
- example=example,
- examples=examples,
- openapi_examples=openapi_examples,
- include_in_schema=include_in_schema,
- json_schema_extra=json_schema_extra,
- **extra,
- )
diff --git a/fastapi/types.py b/fastapi/types.py
index 3f4e81a7cc..d3e980cb43 100644
--- a/fastapi/types.py
+++ b/fastapi/types.py
@@ -1,11 +1,11 @@
import types
from enum import Enum
-from typing import Any, Callable, Dict, Optional, Set, Tuple, Type, TypeVar, Union
+from typing import Any, Callable, Optional, TypeVar, Union
from pydantic import BaseModel
DecoratedCallable = TypeVar("DecoratedCallable", bound=Callable[..., Any])
UnionType = getattr(types, "UnionType", Union)
-ModelNameMap = Dict[Union[Type[BaseModel], Type[Enum]], str]
-IncEx = Union[Set[int], Set[str], Dict[int, Any], Dict[str, Any]]
-DependencyCacheKey = Tuple[Optional[Callable[..., Any]], Tuple[str, ...], str]
+ModelNameMap = dict[Union[type[BaseModel], type[Enum]], str]
+IncEx = Union[set[int], set[str], dict[int, Any], dict[str, Any]]
+DependencyCacheKey = tuple[Optional[Callable[..., Any]], tuple[str, ...], str]
diff --git a/fastapi/utils.py b/fastapi/utils.py
index b3b89ed2b4..78fdcbb5b4 100644
--- a/fastapi/utils.py
+++ b/fastapi/utils.py
@@ -1,22 +1,16 @@
import re
import warnings
-from dataclasses import is_dataclass
+from collections.abc import MutableMapping
from typing import (
TYPE_CHECKING,
Any,
- Dict,
- MutableMapping,
Optional,
- Set,
- Type,
Union,
- cast,
)
from weakref import WeakKeyDictionary
import fastapi
from fastapi._compat import (
- PYDANTIC_V2,
BaseConfig,
ModelField,
PydanticSchemaGenerationError,
@@ -24,19 +18,20 @@ from fastapi._compat import (
UndefinedType,
Validator,
annotation_is_pydantic_v1,
- lenient_issubclass,
- may_v1,
)
from fastapi.datastructures import DefaultPlaceholder, DefaultType
+from fastapi.exceptions import FastAPIDeprecationWarning, PydanticV1NotSupportedError
from pydantic import BaseModel
from pydantic.fields import FieldInfo
from typing_extensions import Literal
+from ._compat import v2
+
if TYPE_CHECKING: # pragma: nocover
from .routing import APIRoute
# Cache for `create_cloned_field`
-_CLONED_TYPES_CACHE: MutableMapping[Type[BaseModel], Type[BaseModel]] = (
+_CLONED_TYPES_CACHE: MutableMapping[type[BaseModel], type[BaseModel]] = (
WeakKeyDictionary()
)
@@ -58,7 +53,7 @@ def is_body_allowed_for_status_code(status_code: Union[int, str, None]) -> bool:
return not (current_status_code < 200 or current_status_code in {204, 205, 304})
-def get_path_param_names(path: str) -> Set[str]:
+def get_path_param_names(path: str) -> set[str]:
return set(re.findall("{(.*?)}", path))
@@ -76,63 +71,27 @@ _invalid_args_message = (
def create_model_field(
name: str,
type_: Any,
- class_validators: Optional[Dict[str, Validator]] = None,
+ class_validators: Optional[dict[str, Validator]] = None,
default: Optional[Any] = Undefined,
required: Union[bool, UndefinedType] = Undefined,
- model_config: Union[Type[BaseConfig], None] = None,
+ model_config: Union[type[BaseConfig], None] = None,
field_info: Optional[FieldInfo] = None,
alias: Optional[str] = None,
mode: Literal["validation", "serialization"] = "validation",
version: Literal["1", "auto"] = "auto",
) -> ModelField:
+ if annotation_is_pydantic_v1(type_):
+ raise PydanticV1NotSupportedError(
+ "pydantic.v1 models are no longer supported by FastAPI."
+ f" Please update the response model {type_!r}."
+ )
class_validators = class_validators or {}
- v1_model_config = may_v1.BaseConfig
- v1_field_info = field_info or may_v1.FieldInfo()
- v1_kwargs = {
- "name": name,
- "field_info": v1_field_info,
- "type_": type_,
- "class_validators": class_validators,
- "default": default,
- "required": required,
- "model_config": v1_model_config,
- "alias": alias,
- }
-
- if (
- annotation_is_pydantic_v1(type_)
- or isinstance(field_info, may_v1.FieldInfo)
- or version == "1"
- ):
- from fastapi._compat import v1
-
- try:
- return v1.ModelField(**v1_kwargs) # type: ignore[no-any-return]
- except RuntimeError:
- raise fastapi.exceptions.FastAPIError(
- _invalid_args_message.format(type_=type_)
- ) from None
- elif PYDANTIC_V2:
- from ._compat import v2
-
- field_info = field_info or FieldInfo(
- annotation=type_, default=default, alias=alias
- )
- kwargs = {"mode": mode, "name": name, "field_info": field_info}
- try:
- return v2.ModelField(**kwargs) # type: ignore[return-value,arg-type]
- except PydanticSchemaGenerationError:
- raise fastapi.exceptions.FastAPIError(
- _invalid_args_message.format(type_=type_)
- ) from None
- # Pydantic v2 is not installed, but it's not a Pydantic v1 ModelField, it could be
- # a Pydantic v1 type, like a constrained int
- from fastapi._compat import v1
-
+ field_info = field_info or FieldInfo(annotation=type_, default=default, alias=alias)
+ kwargs = {"mode": mode, "name": name, "field_info": field_info}
try:
- return v1.ModelField(**v1_kwargs) # type: ignore[no-any-return]
- except RuntimeError:
+ return v2.ModelField(**kwargs) # type: ignore[return-value,arg-type]
+ except PydanticSchemaGenerationError:
raise fastapi.exceptions.FastAPIError(
_invalid_args_message.format(type_=type_)
) from None
@@ -141,73 +100,18 @@ def create_model_field(
def create_cloned_field(
field: ModelField,
*,
- cloned_types: Optional[MutableMapping[Type[BaseModel], Type[BaseModel]]] = None,
+ cloned_types: Optional[MutableMapping[type[BaseModel], type[BaseModel]]] = None,
) -> ModelField:
- if PYDANTIC_V2:
- from ._compat import v2
-
- if isinstance(field, v2.ModelField):
- return field
-
- from fastapi._compat import v1
-
- # cloned_types caches already cloned types to support recursive models and improve
- # performance by avoiding unnecessary cloning
- if cloned_types is None:
- cloned_types = _CLONED_TYPES_CACHE
-
- original_type = field.type_
- if is_dataclass(original_type) and hasattr(original_type, "__pydantic_model__"):
- original_type = original_type.__pydantic_model__
- use_type = original_type
- if lenient_issubclass(original_type, v1.BaseModel):
- original_type = cast(Type[v1.BaseModel], original_type)
- use_type = cloned_types.get(original_type)
- if use_type is None:
- use_type = v1.create_model(original_type.__name__, __base__=original_type)
- cloned_types[original_type] = use_type
- for f in original_type.__fields__.values():
- use_type.__fields__[f.name] = create_cloned_field(
- f,
- cloned_types=cloned_types,
- )
- new_field = create_model_field(name=field.name, type_=use_type, version="1")
- new_field.has_alias = field.has_alias # type: ignore[attr-defined]
- new_field.alias = field.alias # type: ignore[misc]
- new_field.class_validators = field.class_validators # type: ignore[attr-defined]
- new_field.default = field.default # type: ignore[misc]
- new_field.default_factory = field.default_factory # type: ignore[attr-defined]
- new_field.required = field.required # type: ignore[misc]
- new_field.model_config = field.model_config # type: ignore[attr-defined]
- new_field.field_info = field.field_info
- new_field.allow_none = field.allow_none # type: ignore[attr-defined]
- new_field.validate_always = field.validate_always # type: ignore[attr-defined]
- if field.sub_fields: # type: ignore[attr-defined]
- new_field.sub_fields = [ # type: ignore[attr-defined]
- create_cloned_field(sub_field, cloned_types=cloned_types)
- for sub_field in field.sub_fields # type: ignore[attr-defined]
- ]
- if field.key_field: # type: ignore[attr-defined]
- new_field.key_field = create_cloned_field( # type: ignore[attr-defined]
- field.key_field, # type: ignore[attr-defined]
- cloned_types=cloned_types,
- )
- new_field.validators = field.validators # type: ignore[attr-defined]
- new_field.pre_validators = field.pre_validators # type: ignore[attr-defined]
- new_field.post_validators = field.post_validators # type: ignore[attr-defined]
- new_field.parse_json = field.parse_json # type: ignore[attr-defined]
- new_field.shape = field.shape # type: ignore[attr-defined]
- new_field.populate_validators() # type: ignore[attr-defined]
- return new_field
+ return field
def generate_operation_id_for_path(
*, name: str, path: str, method: str
) -> str: # pragma: nocover
warnings.warn(
- "fastapi.utils.generate_operation_id_for_path() was deprecated, "
+ message="fastapi.utils.generate_operation_id_for_path() was deprecated, "
"it is not used internally, and will be removed soon",
- DeprecationWarning,
+ category=FastAPIDeprecationWarning,
stacklevel=2,
)
operation_id = f"{name}{path}"
@@ -224,7 +128,7 @@ def generate_unique_id(route: "APIRoute") -> str:
return operation_id
-def deep_dict_update(main_dict: Dict[Any, Any], update_dict: Dict[Any, Any]) -> None:
+def deep_dict_update(main_dict: dict[Any, Any], update_dict: dict[Any, Any]) -> None:
for key, value in update_dict.items():
if (
key in main_dict
diff --git a/pdm_build.py b/pdm_build.py
index c83222b336..a0eb88eebb 100644
--- a/pdm_build.py
+++ b/pdm_build.py
@@ -1,5 +1,5 @@
import os
-from typing import Any, Dict
+from typing import Any
from pdm.backend.hooks import Context
@@ -9,12 +9,12 @@ TIANGOLO_BUILD_PACKAGE = os.getenv("TIANGOLO_BUILD_PACKAGE", "fastapi")
def pdm_build_initialize(context: Context) -> None:
metadata = context.config.metadata
# Get custom config for the current package, from the env var
- config: Dict[str, Any] = context.config.data["tool"]["tiangolo"][
+ config: dict[str, Any] = context.config.data["tool"]["tiangolo"][
"_internal-slim-build"
]["packages"].get(TIANGOLO_BUILD_PACKAGE)
if not config:
return
- project_config: Dict[str, Any] = config["project"]
+ project_config: dict[str, Any] = config["project"]
# Override main [project] configs with custom configs for this package
for key, value in project_config.items():
metadata[key] = value
diff --git a/pyproject.toml b/pyproject.toml
index ef4440b1b4..9c2c35a9f5 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -9,7 +9,7 @@ description = "FastAPI framework, high performance, easy to learn, fast to code,
readme = "README.md"
license = "MIT"
license-files = ["LICENSE"]
-requires-python = ">=3.8"
+requires-python = ">=3.9"
authors = [
{ name = "Sebastián Ramírez", email = "tiangolo@gmail.com" },
]
@@ -30,11 +30,9 @@ classifiers = [
"Framework :: AsyncIO",
"Framework :: FastAPI",
"Framework :: Pydantic",
- "Framework :: Pydantic :: 1",
"Framework :: Pydantic :: 2",
"Intended Audience :: Developers",
"Programming Language :: Python :: 3 :: Only",
- "Programming Language :: Python :: 3.8",
"Programming Language :: Python :: 3.9",
"Programming Language :: Python :: 3.10",
"Programming Language :: Python :: 3.11",
@@ -46,7 +44,7 @@ classifiers = [
]
dependencies = [
"starlette>=0.40.0,<0.51.0",
- "pydantic>=1.7.4,!=1.8,!=1.8.1,!=2.0.0,!=2.0.1,!=2.1.0,<3.0.0",
+ "pydantic>=2.7.0",
"typing-extensions>=4.8.0",
"annotated-doc>=0.0.2",
]
@@ -72,11 +70,10 @@ standard = [
"email-validator >=2.0.0",
# Uvicorn with uvloop
"uvicorn[standard] >=0.12.0",
- # TODO: this should be part of some pydantic optional extra dependencies
# # Settings management
- # "pydantic-settings >=2.0.0",
+ "pydantic-settings >=2.0.0",
# # Extra Pydantic data types
- # "pydantic-extra-types >=2.0.0",
+ "pydantic-extra-types >=2.0.0",
]
standard-no-fastapi-cloud-cli = [
@@ -91,11 +88,10 @@ standard-no-fastapi-cloud-cli = [
"email-validator >=2.0.0",
# Uvicorn with uvloop
"uvicorn[standard] >=0.12.0",
- # TODO: this should be part of some pydantic optional extra dependencies
# # Settings management
- # "pydantic-settings >=2.0.0",
+ "pydantic-settings >=2.0.0",
# # Extra Pydantic data types
- # "pydantic-extra-types >=2.0.0",
+ "pydantic-extra-types >=2.0.0",
]
all = [
@@ -184,8 +180,6 @@ filterwarnings = [
# Ref: https://github.com/python-trio/trio/pull/3054
# Remove once there's a new version of Trio
'ignore:The `hash` argument is deprecated*:DeprecationWarning:trio',
- # Ignore flaky coverage / pytest warning about SQLite connection, only applies to Python 3.13 and Pydantic v1
- 'ignore:Exception ignored in. =1.1.2,<4.0.0
+strawberry-graphql >=0.200.0,< 1.0.0
anyio[trio] >=3.2.1,<5.0.0
PyJWT==2.9.0
pyyaml >=5.3.1,<7.0.0
pwdlib[argon2] >=0.2.1
inline-snapshot>=0.21.1
+pytest-codspeed==4.2.0
# types
types-ujson ==5.10.0.20240515
types-orjson ==3.6.2
diff --git a/requirements.txt b/requirements.txt
index 1cff1a5a9b..3bbab64a42 100644
--- a/requirements.txt
+++ b/requirements.txt
@@ -2,6 +2,6 @@
-r requirements-tests.txt
-r requirements-docs.txt
-r requirements-translations.txt
-pre-commit >=4.5.0,<5.0.0
+prek==0.2.22
# For generating screenshots
playwright
diff --git a/scripts/docs.py b/scripts/docs.py
index b35bb3627f..fbde1eca4f 100644
--- a/scripts/docs.py
+++ b/scripts/docs.py
@@ -8,7 +8,7 @@ from html.parser import HTMLParser
from http.server import HTTPServer, SimpleHTTPRequestHandler
from multiprocessing import Pool
from pathlib import Path
-from typing import Any, Dict, List, Optional, Union
+from typing import Any, Optional, Union
import mkdocs.utils
import typer
@@ -19,7 +19,13 @@ from slugify import slugify as py_slugify
logging.basicConfig(level=logging.INFO)
-SUPPORTED_LANGS = {"en", "de", "es", "pt", "ru"}
+SUPPORTED_LANGS = {
+ "en",
+ "de",
+ "es",
+ "pt",
+ "ru",
+}
app = typer.Typer()
@@ -82,11 +88,11 @@ def slugify(text: str) -> str:
)
-def get_en_config() -> Dict[str, Any]:
+def get_en_config() -> dict[str, Any]:
return mkdocs.utils.yaml_load(en_config_path.read_text(encoding="utf-8"))
-def get_lang_paths() -> List[Path]:
+def get_lang_paths() -> list[Path]:
return sorted(docs_path.iterdir())
@@ -232,27 +238,15 @@ def generate_readme() -> None:
"""
Generate README.md content from main index.md
"""
- typer.echo("Generating README")
readme_path = Path("README.md")
+ old_content = readme_path.read_text()
new_content = generate_readme_content()
- readme_path.write_text(new_content, encoding="utf-8")
-
-
-@app.command()
-def verify_readme() -> None:
- """
- Verify README.md content from main index.md
- """
- typer.echo("Verifying README")
- readme_path = Path("README.md")
- generated_content = generate_readme_content()
- readme_content = readme_path.read_text("utf-8")
- if generated_content != readme_content:
- typer.secho(
- "README.md outdated from the latest index.md", color=typer.colors.RED
- )
- raise typer.Abort()
- typer.echo("Valid README ✅")
+ if new_content != old_content:
+ print("README.md outdated from the latest index.md")
+ print("Updating README.md")
+ readme_path.write_text(new_content, encoding="utf-8")
+ raise typer.Exit(1)
+ print("README.md is up to date ✅")
@app.command()
@@ -280,7 +274,17 @@ def update_languages() -> None:
"""
Update the mkdocs.yml file Languages section including all the available languages.
"""
- update_config()
+ old_config = get_en_config()
+ updated_config = get_updated_config_content()
+ if old_config != updated_config:
+ print("docs/en/mkdocs.yml outdated")
+ print("Updating docs/en/mkdocs.yml")
+ en_config_path.write_text(
+ yaml.dump(updated_config, sort_keys=False, width=200, allow_unicode=True),
+ encoding="utf-8",
+ )
+ raise typer.Exit(1)
+ print("docs/en/mkdocs.yml is up to date ✅")
@app.command()
@@ -334,14 +338,14 @@ def live(
)
-def get_updated_config_content() -> Dict[str, Any]:
+def get_updated_config_content() -> dict[str, Any]:
config = get_en_config()
languages = [{"en": "/"}]
- new_alternate: List[Dict[str, str]] = []
+ new_alternate: list[dict[str, str]] = []
# Language names sourced from https://quickref.me/iso-639-1
# Contributors may wish to update or change these, e.g. to fix capitalization.
language_names_path = Path(__file__).parent / "../docs/language_names.yml"
- local_language_names: Dict[str, str] = mkdocs.utils.yaml_load(
+ local_language_names: dict[str, str] = mkdocs.utils.yaml_load(
language_names_path.read_text(encoding="utf-8")
)
for lang_path in get_lang_paths():
@@ -367,39 +371,12 @@ def get_updated_config_content() -> Dict[str, Any]:
return config
-def update_config() -> None:
- config = get_updated_config_content()
- en_config_path.write_text(
- yaml.dump(config, sort_keys=False, width=200, allow_unicode=True),
- encoding="utf-8",
- )
-
-
@app.command()
-def verify_config() -> None:
+def ensure_non_translated() -> None:
"""
- Verify main mkdocs.yml content to make sure it uses the latest language names.
+ Ensure there are no files in the non translatable pages.
"""
- typer.echo("Verifying mkdocs.yml")
- config = get_en_config()
- updated_config = get_updated_config_content()
- if config != updated_config:
- typer.secho(
- "docs/en/mkdocs.yml outdated from docs/language_names.yml, "
- "update language_names.yml and run "
- "python ./scripts/docs.py update-languages",
- color=typer.colors.RED,
- )
- raise typer.Abort()
- typer.echo("Valid mkdocs.yml ✅")
-
-
-@app.command()
-def verify_non_translated() -> None:
- """
- Verify there are no files in the non translatable pages.
- """
- print("Verifying non translated pages")
+ print("Ensuring no non translated pages")
lang_paths = get_lang_paths()
error_paths = []
for lang in lang_paths:
@@ -410,20 +387,17 @@ def verify_non_translated() -> None:
if non_translatable_path.exists():
error_paths.append(non_translatable_path)
if error_paths:
- print("Non-translated pages found, remove them:")
+ print("Non-translated pages found, removing them:")
for error_path in error_paths:
print(error_path)
- raise typer.Abort()
+ if error_path.is_file():
+ error_path.unlink()
+ else:
+ shutil.rmtree(error_path)
+ raise typer.Exit(1)
print("No non-translated pages found ✅")
-@app.command()
-def verify_docs():
- verify_readme()
- verify_config()
- verify_non_translated()
-
-
@app.command()
def langs_json():
langs = []
@@ -530,7 +504,7 @@ def add_permalinks_page(path: Path, update_existing: bool = False):
@app.command()
-def add_permalinks_pages(pages: List[Path], update_existing: bool = False) -> None:
+def add_permalinks_pages(pages: list[Path], update_existing: bool = False) -> None:
"""
Add or update header permalinks in specific pages of En docs.
"""
diff --git a/scripts/general-llm-prompt.md b/scripts/general-llm-prompt.md
new file mode 100644
index 0000000000..d45ab8eb07
--- /dev/null
+++ b/scripts/general-llm-prompt.md
@@ -0,0 +1,528 @@
+### Your task
+
+Translate an English original content to a target language.
+
+The original content is written in Markdown, write the translation in Markdown as well.
+
+The original content will be surrounded by triple percentage signs (%%%). Do not include the triple percentage signs in the translation.
+
+### Technical terms in English
+
+For technical terms in English that don't have a common translation term, use the original term in English.
+
+### Content of code snippets
+
+Do not translate the content of code snippets, keep the original in English. For example, `list`, `dict`, keep them as is.
+
+### Content of code blocks
+
+Do not translate the content of code blocks, except for comments in the language which the code block uses.
+
+Examples:
+
+Source (English) - The code block is a bash code example with one comment:
+
+```bash
+# Print greeting
+echo "Hello, World!"
+```
+
+Result (German):
+
+```bash
+# Gruß ausgeben
+echo "Hello, World!"
+```
+
+Source (English) - The code block is a console example containing HTML tags. No comments, so nothing to change here:
+
+```console
+$ fastapi run main.py
+ FastAPI Starting server
+ Searching for package file structure
+```
+
+Result (German):
+
+```console
+$ fastapi run main.py
+ FastAPI Starting server
+ Searching for package file structure
+```
+
+Source (English) - The code block is a console example containing 5 comments:
+
+
+```console
+// Go to the home directory
+$ cd
+// Create a directory for all your code projects
+$ mkdir code
+// Enter into that code directory
+$ cd code
+// Create a directory for this project
+$ mkdir awesome-project
+// Enter into that project directory
+$ cd awesome-project
+```
+
+Result (German):
+
+```console
+// Gehe zum Home-Verzeichnis
+$ cd
+// Erstelle ein Verzeichnis für alle Ihre Code-Projekte
+$ mkdir code
+// Gehe in dieses Code-Verzeichnis
+$ cd code
+// Erstelle ein Verzeichnis für dieses Projekt
+$ mkdir awesome-project
+// Gehe in dieses Projektverzeichnis
+$ cd awesome-project
+```
+
+If there is an existing translation and its Mermaid diagram is in sync with the Mermaid diagram in the English source, except a few translated words, then use the Mermaid diagram of the existing translation. The human editor of the translation translated these words in the Mermaid diagram. Keep these translations, do not revert them back to the English source.
+
+Example:
+
+Source (English):
+
+```mermaid
+flowchart LR
+ subgraph global[global env]
+ harry-1[harry v1]
+ end
+ subgraph stone-project[philosophers-stone project]
+ stone(philosophers-stone) -->|requires| harry-1
+ end
+```
+
+Existing translation (German) - has three translations:
+
+```mermaid
+flowchart LR
+ subgraph global[globale Umgebung]
+ harry-1[harry v1]
+ end
+ subgraph stone-project[philosophers-stone-Projekt]
+ stone(philosophers-stone) -->|benötigt| harry-1
+ end
+```
+
+Result (German) - you change nothing:
+
+```mermaid
+flowchart LR
+ subgraph global[globale Umgebung]
+ harry-1[harry v1]
+ end
+ subgraph stone-project[philosophers-stone-Projekt]
+ stone(philosophers-stone) -->|benötigt| harry-1
+ end
+```
+
+### Special blocks
+
+There are special blocks of notes, tips and others that look like:
+
+/// note
+Here goes a note
+///
+
+To translate it, keep the same line and add the translation after a vertical bar.
+
+For example, if you were translating to Spanish, you would write:
+
+/// note | Nota
+
+Some examples in Spanish:
+
+Source (English):
+
+/// tip
+
+Result (Spanish):
+
+/// tip | Consejo
+
+Source (English):
+
+/// details | Preview
+
+Result (Spanish):
+
+/// details | Vista previa
+
+### Tab blocks
+
+There are special blocks surrounded by four slashes (////). They mark text, which will be rendered as part of a tab in the final document. The scheme is:
+
+//// tab | {tab title}
+{tab content, may span many lines}
+////
+
+Keep everything before the vertical bar (|) as is, including the vertical bar. Translate the tab title. Translate the tab content, applying the rules you know. Keep the four block closing slashes as is.
+
+Examples:
+
+Source (English):
+
+//// tab | Python 3.8+ non-Annotated
+Hello
+////
+
+Result (German):
+
+//// tab | Python 3.8+ nicht annotiert
+Hallo
+////
+
+Source (English) - Here there is nothing to translate in the tab title:
+
+//// tab | Linux, macOS, Windows Bash
+Hello again
+////
+
+Result (German):
+
+//// tab | Linux, macOS, Windows Bash
+Hallo wieder
+////
+
+### Headings
+
+Every Markdown heading in the English text (all levels) ends with a part inside curly brackets. This part denotes the hash of this heading, which is used in links to this heading. In translations, translate the heading, but do not translate this hash part, so that links do not break.
+
+Examples of how to translate a heading:
+
+Source (English):
+
+```
+## Alternative API docs { #alternative-api-docs }
+```
+
+Result (Spanish):
+
+```
+## Documentación de la API alternativa { #alternative-api-docs }
+```
+
+Source (English):
+
+```
+### Example { #example }
+```
+
+Result (German):
+
+```
+### Beispiel { #example }
+```
+
+### Links
+
+Use the following rules for links (apply both to Markdown-style links ([text](url)) and to HTML-style text tags):
+
+- For relative URLs, only translate the link text. Do not translate the URL or its parts.
+
+Example:
+
+Source (English):
+
+```
+[One of the fastest Python frameworks available](#performance)
+```
+
+Result (German):
+
+```
+[Eines der schnellsten verfügbaren Python-Frameworks](#performance)
+```
+
+- For absolute URLs which DO NOT start EXACTLY with https://fastapi.tiangolo.com, only translate the link text and leave the URL unchanged.
+
+Example:
+
+Source (English):
+
+```
+SQLModel docs
+```
+
+Result (German):
+
+```
+SQLModel-Dokumentation
+```
+
+- For absolute URLs which DO start EXACTLY with https://fastapi.tiangolo.com, only translate the link text and change the URL by adding the language code (https://fastapi.tiangolo.com/{language_code}[rest part of the url]).
+
+Example:
+
+Source (English):
+
+```
+Documentation
+```
+
+Result (Spanish):
+
+```
+Documentación
+```
+
+- Do not add language codes for URLs that point to static assets (e.g., images, CSS, JavaScript).
+
+Example:
+
+Source (English):
+
+```
+Something
+```
+
+Result (Spanish):
+
+```
+Algo
+```
+
+- For internal links, only translate link text.
+
+Example:
+
+Source (English):
+
+```
+[Create Pull Requests](help-fastapi.md#create-a-pull-request){.internal-link target=_blank}
+```
+
+Result (German):
+
+```
+[Pull Requests erzeugen](help-fastapi.md#create-a-pull-request){.internal-link target=_blank}
+```
+
+- Do not translate anchor fragments in links (the part after `#`), as they must remain the same to work correctly.
+
+- If an existing translation has a link with an anchor fragment different to the anchor fragment in the English source, then this is an error. Fix this by using the anchor fragment of the English source.
+
+Example:
+
+Source (English):
+
+```
+[Body - Multiple Parameters: Singular values in body](body-multiple-params.md#singular-values-in-body){.internal-link target=_blank}
+```
+
+Existing wrong translation (German) - notice the wrongly translated anchor fragment:
+
+```
+[Body - Mehrere Parameter: Einfache Werte im Body](body-multiple-params.md#einzelne-werte-im-body){.internal-link target=_blank}.
+```
+
+Result (German) - you fix the anchor fragment:
+
+```
+[Body - Mehrere Parameter: Einfache Werte im Body](body-multiple-params.md#singular-values-in-body){.internal-link target=_blank}.
+```
+
+- Do not add anchor fragments at will, even if this makes sense. If the English source has no anchor, don't add one.
+
+Example:
+
+Source (English):
+
+```
+Create a [virtual environment](../virtual-environments.md){.internal-link target=_blank}
+```
+
+Wrong translation in German - Anchor added to the URL.
+
+```
+Erstelle eine [virtuelle Umgebung](../virtual-environments.md#create-a-virtual-environment){.internal-link target=_blank}
+```
+
+Good translation (German) - URL stays like in the English source.
+
+```
+Erstelle eine [Virtuelle Umgebung](../virtual-environments.md){.internal-link target=_blank}
+```
+
+### HTML abbr elements
+
+Translate HTML abbr elements (`text`) as follows:
+
+- If the text surrounded by the abbr element is an abbreviation (the text may be surrounded by further HTML or Markdown markup or quotes, for example text or `text` or "text", ignore that further markup when deciding if the text is an abbreviation), and if the description (the text inside the title attribute) contains the full phrase for this abbreviation, then append a dash (-) to the full phrase, followed by the translation of the full phrase.
+
+Conversion scheme:
+
+Source (English):
+
+```
+{abbreviation}
+```
+
+Result:
+
+```
+{abbreviation}
+```
+
+Examples:
+
+Source (English):
+
+```
+IoT
+CPU
+TL;DR:
+```
+
+Result (German):
+
+```
+IoT
+CPU
+TL;DR:
+```
+
+- If the language to which you translate mostly uses the letters of the ASCII char set (for example Spanish, French, German, but not Russian, Chinese) and if the translation of the full phrase is identical to, or starts with the same letters as the original full phrase, then only give the translation of the full phrase.
+
+Conversion scheme:
+
+Source (English):
+
+```
+{abbreviation}
+```
+
+Result:
+
+```
+{abbreviation}
+```
+
+Examples:
+
+Source (English):
+
+```
+JWT
+Enum
+ASGI
+```
+
+Result (German):
+
+```
+JWT
+Enum
+ASGI
+```
+
+- If the description is not a full phrase for an abbreviation which the abbr element surrounds, but some other information, then just translate the description.
+
+Conversion scheme:
+
+Source (English):
+
+```
+{text}
+```
+
+Result:
+
+```
+{translation of text}
+```
+
+Examples:
+
+ Source (English):
+
+```
+path
+linter
+parsing
+0.95.0
+at the time of writing this
+```
+
+Result (German):
+
+```
+Pfad
+Linter
+Parsen
+0.95.0
+zum Zeitpunkt als das hier geschrieben wurde
+```
+
+- If the text surrounded by the abbr element is an abbreviation and the description contains both the full phrase for that abbreviation, and other information, separated by a colon (`:`), then append a dash (`-`) and the translation of the full phrase to the original full phrase and translate the other information.
+
+Conversion scheme:
+
+Source (English):
+
+```
+{abbreviation}
+```
+
+Result:
+
+```
+{abbreviation}
+```
+
+Examples:
+
+Source (English):
+
+```
+I/O
+CDN
+IDE
+```
+
+Result (German):
+
+```
+I/O
+CDN
+IDE
+```
+
+- You can leave the original full phrase away, if the translated full phrase is identical or starts with the same letters as the original full phrase.
+
+Conversion scheme:
+
+Source (English):
+
+```
+{abbreviation}
+```
+
+Result:
+
+```
+{abbreviation}
+```
+
+Example:
+
+Source (English):
+
+```
+ORM
+```
+
+Result (German):
+
+```
+ORM
+```
+
+- If there is an existing translation, and it has ADDITIONAL abbr elements in a sentence, and these additional abbr elements do not exist in the related sentence in the English text, then KEEP those additional abbr elements in the translation. Do not remove them. Except when you remove the whole sentence from the translation, because the whole sentence was removed from the English text, then also remove the abbr element. The reasoning for this rule is, that such additional abbr elements are manually added by the human editor of the translation, in order to translate or explain an English word to the human readers of the translation. These additional abbr elements would not make sense in the English text, but they do make sense in the translation. So keep them in the translation, even though they are not part of the English text. This rule only applies to abbr elements.
+
+- Apply above rules also when there is an existing translation! Make sure that all title attributes in abbr elements get properly translated or updated, using the schemes given above. However, leave the ADDITIONAL abbr's described above alone. Do not change their formatting or content.
diff --git a/scripts/mkdocs_hooks.py b/scripts/mkdocs_hooks.py
index 09cfa99e38..4b781270a2 100644
--- a/scripts/mkdocs_hooks.py
+++ b/scripts/mkdocs_hooks.py
@@ -1,6 +1,6 @@
from functools import lru_cache
from pathlib import Path
-from typing import Any, List, Union
+from typing import Any, Union
import material
from mkdocs.config.defaults import MkDocsConfig
@@ -27,7 +27,7 @@ def get_missing_translation_content(docs_dir: str) -> str:
@lru_cache
-def get_mkdocs_material_langs() -> List[str]:
+def get_mkdocs_material_langs() -> list[str]:
material_path = Path(material.__file__).parent
material_langs_path = material_path / "templates" / "partials" / "languages"
langs = [file.stem for file in material_langs_path.glob("*.html")]
@@ -65,7 +65,7 @@ def resolve_file(*, item: str, files: Files, config: MkDocsConfig) -> None:
)
-def resolve_files(*, items: List[Any], files: Files, config: MkDocsConfig) -> None:
+def resolve_files(*, items: list[Any], files: Files, config: MkDocsConfig) -> None:
for item in items:
if isinstance(item, str):
resolve_file(item=item, files=files, config=config)
@@ -94,9 +94,9 @@ def on_files(files: Files, *, config: MkDocsConfig) -> Files:
def generate_renamed_section_items(
- items: List[Union[Page, Section, Link]], *, config: MkDocsConfig
-) -> List[Union[Page, Section, Link]]:
- new_items: List[Union[Page, Section, Link]] = []
+ items: list[Union[Page, Section, Link]], *, config: MkDocsConfig
+) -> list[Union[Page, Section, Link]]:
+ new_items: list[Union[Page, Section, Link]] = []
for item in items:
if isinstance(item, Section):
new_title = item.title
diff --git a/scripts/notify_translations.py b/scripts/notify_translations.py
index c300624db2..2ca740a607 100644
--- a/scripts/notify_translations.py
+++ b/scripts/notify_translations.py
@@ -3,7 +3,7 @@ import random
import sys
import time
from pathlib import Path
-from typing import Any, Dict, List, Union, cast
+from typing import Any, Union, cast
import httpx
from github import Github
@@ -120,7 +120,7 @@ class CommentsEdge(BaseModel):
class Comments(BaseModel):
- edges: List[CommentsEdge]
+ edges: list[CommentsEdge]
class CommentsDiscussion(BaseModel):
@@ -149,7 +149,7 @@ class AllDiscussionsLabelsEdge(BaseModel):
class AllDiscussionsDiscussionLabels(BaseModel):
- edges: List[AllDiscussionsLabelsEdge]
+ edges: list[AllDiscussionsLabelsEdge]
class AllDiscussionsDiscussionNode(BaseModel):
@@ -160,7 +160,7 @@ class AllDiscussionsDiscussionNode(BaseModel):
class AllDiscussionsDiscussions(BaseModel):
- nodes: List[AllDiscussionsDiscussionNode]
+ nodes: list[AllDiscussionsDiscussionNode]
class AllDiscussionsRepository(BaseModel):
@@ -205,7 +205,7 @@ def get_graphql_response(
discussion_id: Union[str, None] = None,
comment_id: Union[str, None] = None,
body: Union[str, None] = None,
-) -> Dict[str, Any]:
+) -> dict[str, Any]:
headers = {"Authorization": f"token {settings.github_token.get_secret_value()}"}
variables = {
"after": after,
@@ -233,12 +233,12 @@ def get_graphql_response(
logging.error(data["errors"])
logging.error(response.text)
raise RuntimeError(response.text)
- return cast(Dict[str, Any], data)
+ return cast(dict[str, Any], data)
def get_graphql_translation_discussions(
*, settings: Settings
-) -> List[AllDiscussionsDiscussionNode]:
+) -> list[AllDiscussionsDiscussionNode]:
data = get_graphql_response(
settings=settings,
query=all_discussions_query,
@@ -250,7 +250,7 @@ def get_graphql_translation_discussions(
def get_graphql_translation_discussion_comments_edges(
*, settings: Settings, discussion_number: int, after: Union[str, None] = None
-) -> List[CommentsEdge]:
+) -> list[CommentsEdge]:
data = get_graphql_response(
settings=settings,
query=translation_discussion_query,
@@ -264,7 +264,7 @@ def get_graphql_translation_discussion_comments_edges(
def get_graphql_translation_discussion_comments(
*, settings: Settings, discussion_number: int
) -> list[Comment]:
- comment_nodes: List[Comment] = []
+ comment_nodes: list[Comment] = []
discussion_edges = get_graphql_translation_discussion_comments_edges(
settings=settings, discussion_number=discussion_number
)
@@ -348,7 +348,7 @@ def main() -> None:
# Generate translation map, lang ID to discussion
discussions = get_graphql_translation_discussions(settings=settings)
- lang_to_discussion_map: Dict[str, AllDiscussionsDiscussionNode] = {}
+ lang_to_discussion_map: dict[str, AllDiscussionsDiscussionNode] = {}
for discussion in discussions:
for edge in discussion.labels.edges:
label = edge.node.name
diff --git a/scripts/people.py b/scripts/people.py
index 65e009944c..207ab46493 100644
--- a/scripts/people.py
+++ b/scripts/people.py
@@ -3,9 +3,10 @@ import secrets
import subprocess
import time
from collections import Counter
+from collections.abc import Container
from datetime import datetime, timedelta, timezone
from pathlib import Path
-from typing import Any, Container, Union
+from typing import Any, Union
import httpx
import yaml
diff --git a/scripts/translate.py b/scripts/translate.py
index 764bc704ea..ffecfde07b 100644
--- a/scripts/translate.py
+++ b/scripts/translate.py
@@ -25,650 +25,8 @@ non_translated_sections = (
"contributing.md",
)
-
-general_prompt = """
-### About literal text in this prompt
-
-1) In the following instructions (after I say: `The above rules are in effect now`) the two characters `«` and `»` will be used to surround LITERAL TEXT, which is text or characters you shall interpret literally. The `«` and the `»` are not part of the literal text, they are the meta characters denoting it.
-
-2) Furthermore, text surrounded by `«««` and `»»»` is a BLOCK OF LITERAL TEXT which spans multiple lines. To get its content, dedent all lines of the block until the `«««` and `»»»` are at column zero, then remove the newline (`\n`) after the `«««` and the newline before the `»»»`. The `«««` and the `»»»` are not part of the literal text block, they are the meta characters denoting it.
-
-3) If you see backticks or any other quotes inside literal text – inside `«` and `»` – or inside blocks of literal text – inside `«««` and `»»»` – then interpret them as literal characters, do NOT interpret them as meta characters.
-
-The above rules are in effect now.
-
-
-### Definitions of terms used in this prompt
-
-"backtick"
-
- The character «`»
- Unicode U+0060 (GRAVE ACCENT)
-
-"single backtick"
-
- A single backtick – «`»
-
-"triple backticks"
-
- Three backticks in a row – «```»
-
-"neutral double quote"
-
- The character «"»
- Unicode U+0022 (QUOTATION MARK)
-
-"neutral single quote"
-
- The character «'»
- Unicode U+0027 (APOSTROPHE)
-
-"English double typographic quotes"
-
- The characters «“» and «”»
- Unicode U+201C (LEFT DOUBLE QUOTATION MARK) and Unicode U+201D (RIGHT DOUBLE QUOTATION MARK)
-
-"English single typographic quotes"
-
- The characters «‘» and «’»
- Unicode U+2018 (LEFT SINGLE QUOTATION MARK) and Unicode U+2019 (RIGHT SINGLE QUOTATION MARK)
-
-"code snippet"
-
- Also called "inline code". Text in a Markdown document which is surrounded by single backticks. A paragraph in a Markdown document can have a more than one code snippet.
-
- Example:
-
- «««
- `i am a code snippet`
- »»»
-
- Example:
-
- «««
- `first code snippet` `second code snippet` `third code snippet`
- »»»
-
-"code block"
-
- Text in a Markdown document which is surrounded by triple backticks. Spreads multiple lines.
-
- Example:
-
- «««
- ```
- Hello
- World
- ```
- »»»
-
- Example:
-
- «««
- ```python
- print("hello World")
- ```
- »»»
-
-"HTML element"
-
- a HTML opening tag – e.g. «» – and a HTML closing tag – e.g. «
» – surrounding text or other HTML elements.
-
-
-### Your task
-
-Translate an English text – the original content – to a target language.
-
-The original content is written in Markdown, write the translation in Markdown as well.
-
-The original content will be surrounded by triple percentage signs («%%%»). Do not include the triple percentage signs in the translation.
-
-
-### Technical terms in English
-
-For technical terms in English that don't have a common translation term, use the original term in English.
-
-
-### Content of code snippets
-
-Do not translate the content of code snippets, keep the original in English. For example, «`list`», «`dict`», keep them as is.
-
-
-### Content of code blocks
-
-Do not translate the content of code blocks, except for comments in the language which the code block uses.
-
-Examples:
-
- Source (English) – The code block is a bash code example with one comment:
-
- «««
- ```bash
- # Print greeting
- echo "Hello, World!"
- ```
- »»»
-
- Result (German):
-
- «««
- ```bash
- # Gruß ausgeben
- echo "Hello, World!"
- ```
- »»»
-
- Source (English) – The code block is a console example containing HTML tags. No comments, so nothing to change here:
-
- «««
- ```console
- $ fastapi run main.py
- FastAPI Starting server
- Searching for package file structure
- ```
- »»»
-
- Result (German):
-
- «««
- ```console
- $ fastapi run main.py
- FastAPI Starting server
- Searching for package file structure
- ```
- »»»
-
- Source (English) – The code block is a console example containing 5 comments:
-
- «««
- ```console
- // Go to the home directory
- $ cd
- // Create a directory for all your code projects
- $ mkdir code
- // Enter into that code directory
- $ cd code
- // Create a directory for this project
- $ mkdir awesome-project
- // Enter into that project directory
- $ cd awesome-project
- ```
- »»»
-
- Result (German):
-
- «««
- ```console
- // Gehe zum Home-Verzeichnis
- $ cd
- // Erstelle ein Verzeichnis für alle Ihre Code-Projekte
- $ mkdir code
- // Gehe in dieses Code-Verzeichnis
- $ cd code
- // Erstelle ein Verzeichnis für dieses Projekt
- $ mkdir awesome-project
- // Gehe in dieses Projektverzeichnis
- $ cd awesome-project
- ```
- »»»
-
-If there is an existing translation and its Mermaid diagram is in sync with the Mermaid diagram in the English source, except a few translated words, then use the Mermaid diagram of the existing translation. The human editor of the translation translated these words in the Mermaid diagram. Keep these translations, do not revert them back to the English source.
-
-Example:
-
- Source (English):
-
- «««
- ```mermaid
- flowchart LR
- subgraph global[global env]
- harry-1[harry v1]
- end
- subgraph stone-project[philosophers-stone project]
- stone(philosophers-stone) -->|requires| harry-1
- end
- ```
- »»»
-
- Existing translation (German) – has three translations:
-
- «««
- ```mermaid
- flowchart LR
- subgraph global[globale Umgebung]
- harry-1[harry v1]
- end
- subgraph stone-project[philosophers-stone-Projekt]
- stone(philosophers-stone) -->|benötigt| harry-1
- end
- ```
- »»»
-
- Result (German) – you change nothing:
-
- «««
- ```mermaid
- flowchart LR
- subgraph global[globale Umgebung]
- harry-1[harry v1]
- end
- subgraph stone-project[philosophers-stone-Projekt]
- stone(philosophers-stone) -->|benötigt| harry-1
- end
- ```
- »»»
-
-
-### Special blocks
-
-There are special blocks of notes, tips and others that look like:
-
- «««
- /// note
- »»»
-
-To translate it, keep the same line and add the translation after a vertical bar.
-
-For example, if you were translating to Spanish, you would write:
-
- «««
- /// note | Nota
- »»»
-
-Some examples in Spanish:
-
- Source:
-
- «««
- /// tip
- »»»
-
- Result:
-
- «««
- /// tip | Consejo
- »»»
-
- Source:
-
- «««
- /// details | Preview
- »»»
-
- Result:
-
- «««
- /// details | Vista previa
- »»»
-
-
-### Tab blocks
-
-There are special blocks surrounded by four slashes («////»). They mark text, which will be rendered as part of a tab in the final document. The scheme is:
-
- //// tab | {tab title}
- {tab content, may span many lines}
- ////
-
-Keep everything before the vertical bar («|») as is, including the vertical bar. Translate the tab title. Translate the tab content, applying the rules you know. Keep the four block closing slashes as is.
-
-Examples:
-
- Source (English):
-
- «««
- //// tab | Python 3.8+ non-Annotated
- Hello
- ////
- »»»
-
- Result (German):
-
- «««
- //// tab | Python 3.8+ nicht annotiert
- Hallo
- ////
- »»»
-
- Source (English) – Here there is nothing to translate in the tab title:
-
- «««
- //// tab | Linux, macOS, Windows Bash
- Hello again
- ////
- »»»
-
- Result (German):
-
- «««
- //// tab | Linux, macOS, Windows Bash
- Hallo wieder
- ////
- »»»
-
-
-### Headings
-
-Every Markdown heading in the English text (all levels) ends with a part inside curly brackets. This part denotes the hash of this heading, which is used in links to this heading. In translations, translate the heading, but do not translate this hash part, so that links do not break.
-
-Examples of how to translate a heading:
-
- Source (English):
-
- «««
- ## Alternative API docs { #alternative-api-docs }
- »»»
-
- Result (Spanish):
-
- «««
- ## Documentación de la API alternativa { #alternative-api-docs }
- »»»
-
- Source (English):
-
- «««
- ### Example { #example }
- »»»
-
- Result (German):
-
- «««
- ### Beispiel { #example }
- »»»
-
-
-### Links
-
-Use the following rules for links (apply both to Markdown-style links ([text](url)) and to HTML-style tags):
-
-1) For relative URLs, only translate link text. Do not translate the URL or its parts
-
-Example:
-
- Source (English):
-
- «««
- [One of the fastest Python frameworks available](#performance)
- »»»
-
- Result (German):
-
- «««
- [Eines der schnellsten verfügbaren Python-Frameworks](#performance)
- »»»
-
-2) For absolute URLs which DO NOT start EXACTLY with «https://fastapi.tiangolo.com», only translate link text and leave the URL unchanged.
-
-Example:
-
- Source (English):
-
- «««
- SQLModel docs
- »»»
-
- Result (German):
-
- «««
- SQLModel-Dokumentation
- »»»
-
-3) For absolute URLs which DO start EXACTLY with «https://fastapi.tiangolo.com», only translate link text and change the URL by adding language code («https://fastapi.tiangolo.com/{language_code}[rest part of the url]»).
-
-Example:
-
- Source (English):
-
- «««
- Documentation
- »»»
-
- Result (Spanish):
-
- «««
- Documentación
- »»»
-
-3.1) Do not add language codes for URLs that point to static assets (e.g., images, CSS, JavaScript).
-
-Example:
-
- Source (English):
-
- «««
- Something
- »»»
-
- Result (Spanish):
-
- «««
- Algo
- »»»
-
-4) For internal links, only translate link text.
-
-Example:
-
- Source (English):
-
- «««
- [Create Pull Requests](help-fastapi.md#create-a-pull-request){.internal-link target=_blank}
- »»»
-
- Result (German):
-
- «««
- [Pull Requests erzeugen](help-fastapi.md#create-a-pull-request){.internal-link target=_blank}
- »»»
-
-5) Do not translate anchor fragments in links (the part after «#»), as they must remain the same to work correctly.
-
-5.1) If an existing translation has a link with an anchor fragment different to the anchor fragment in the English source, then this is an error. Fix this by using the anchor fragment of the English source.
-
-Example:
-
- Source (English):
-
- «««
- [Body - Multiple Parameters: Singular values in body](body-multiple-params.md#singular-values-in-body){.internal-link target=_blank}
- »»»
-
- Existing wrong translation (German) – notice the wrongly translated anchor fragment:
-
- «««
- [Body – Mehrere Parameter: Einfache Werte im Body](body-multiple-params.md#einzelne-werte-im-body){.internal-link target=_blank}.
- »»»
-
- Result (German) – you fix the anchor fragment:
-
- «««
- [Body – Mehrere Parameter: Einfache Werte im Body](body-multiple-params.md#singular-values-in-body){.internal-link target=_blank}.
- »»»
-
-5.2) Do not add anchor fragments at will, even if this makes sense. If the English source has no anchor, don't add one.
-
-Example:
-
- Source (English):
-
- «««
- Create a [virtual environment](../virtual-environments.md){.internal-link target=_blank}
- »»»
-
- Wrong translation (German) – Anchor added to the URL.
-
- «««
- Erstelle eine [virtuelle Umgebung](../virtual-environments.md#create-a-virtual-environment){.internal-link target=_blank}
- »»»
-
- Good translation (German) – URL stays like in the English source.
-
- «««
- Erstelle eine [Virtuelle Umgebung](../virtual-environments.md){.internal-link target=_blank}
- »»»
-
-
-### HTML abbr elements
-
-Translate HTML abbr elements («text») as follows:
-
-1) If the text surrounded by the abbr element is an abbreviation (the text may be surrounded by further HTML or Markdown markup or quotes, for example «text» or «`text`» or «"text"», ignore that further markup when deciding if the text is an abbreviation), and if the description (the text inside the title attribute) contains the full phrase for this abbreviation, then append a dash («–») to the full phrase, followed by the translation of the full phrase.
-
-Conversion scheme:
-
- Source (English):
-
- {abbreviation}
-
- Result:
-
- {abbreviation}
-
-Examples:
-
- Source (English):
-
- «««
- IoT
- CPU
- TL;DR:
- »»»
-
- Result (German):
-
- «««
- IoT
- CPU
- TL;DR:
- »»»
-
-1.1) If the language to which you translate mostly uses the letters of the ASCII char set (for example Spanish, French, German, but not Russian, Chinese) and if the translation of the full phrase is identical to, or starts with the same letters as the original full phrase, then only give the translation of the full phrase.
-
-Conversion scheme:
-
- Source (English):
-
- {abbreviation}
-
- Result:
-
- {abbreviation}
-
-Examples:
-
- Source (English):
-
- «««
- JWT
- Enum
- ASGI
- »»»
-
- Result (German):
-
- «««
- JWT
- Enum
- ASGI
- »»»
-
-2) If the description is not a full phrase for an abbreviation which the abbr element surrounds, but some other information, then just translate the description.
-
-Conversion scheme:
-
- Source (English):
-
- {text}
-
- Result:
-
- {translation of text}
-
-Examples:
-
- Source (English):
-
- «««
- path
- linter
- parsing
- 0.95.0
- at the time of writing this
- »»»
-
- Result (German):
-
- «««
- Pfad
- Linter
- Parsen
- 0.95.0
- zum Zeitpunkt als das hier geschrieben wurde
- »»»
-
-
-3) If the text surrounded by the abbr element is an abbreviation and the description contains both the full phrase for that abbreviation, and other information, separated by a colon («:»), then append a dash («–») and the translation of the full phrase to the original full phrase and translate the other information.
-
-Conversion scheme:
-
- Source (English):
-
- {abbreviation}
-
- Result:
-
- {abbreviation}
-
-Examples:
-
- Source (English):
-
- «««
- I/O
- CDN
- IDE
- »»»
-
- Result (German):
-
- «««
- I/O
- CDN
- IDE
- »»»
-
-3.1) Like in rule 2.1, you can leave the original full phrase away, if the translated full phrase is identical or starts with the same letters as the original full phrase.
-
-Conversion scheme:
-
- Source (English):
-
- {abbreviation}
-
- Result:
-
- {abbreviation}
-
-Example:
-
- Source (English):
-
- «««
- ORM
- »»»
-
- Result (German):
-
- «««
- ORM
- »»»
-
-4) If there is an existing translation, and it has ADDITIONAL abbr elements in a sentence, and these additional abbr elements do not exist in the related sentence in the English text, then KEEP those additional abbr elements in the translation. Do not remove them. Except when you remove the whole sentence from the translation, because the whole sentence was removed from the English text, then also remove the abbr element. The reasoning for this rule is, that such additional abbr elements are manually added by the human editor of the translation, in order to translate or explain an English word to the human readers of the translation. These additional abbr elements would not make sense in the English text, but they do make sense in the translation. So keep them in the translation, even though they are not part of the English text. This rule only applies to abbr elements.
-
-5) Apply above rules also when there is an existing translation! Make sure that all title attributes in abbr elements get properly translated or updated, using the schemes given above. However, leave the ADDITIONAL abbr's from rule 4 alone. Do not change their formatting or content.
-
-"""
+general_prompt_path = Path(__file__).absolute().parent / "llm-general-prompt.md"
+general_prompt = general_prompt_path.read_text(encoding="utf-8")
app = typer.Typer()
@@ -727,7 +85,7 @@ def translate_page(
print(f"Found existing translation: {out_path}")
old_translation = out_path.read_text(encoding="utf-8")
print(f"Translating {en_path} to {language} ({language_name})")
- agent = Agent("openai:gpt-5")
+ agent = Agent("openai:gpt-5.2")
prompt_segments = [
general_prompt,
@@ -1036,9 +394,13 @@ def make_pr(
print("Creating PR")
g = Github(github_token)
gh_repo = g.get_repo(github_repository)
- pr = gh_repo.create_pull(
- title=message, body=message, base="master", head=branch_name
+ body = (
+ message
+ + "\n\nThis PR was created automatically using LLMs."
+ + f"\n\nIt uses the prompt file https://github.com/fastapi/fastapi/blob/master/docs/{language}/llm-prompt.md."
+ + "\n\nIn most cases, it's better to make PRs updating that file so that the LLM can do a better job generating the translations than suggesting changes in this PR."
)
+ pr = gh_repo.create_pull(title=message, body=body, base="master", head=branch_name)
print(f"Created PR: {pr.number}")
print("Finished")
diff --git a/tests/benchmarks/__init__.py b/tests/benchmarks/__init__.py
new file mode 100644
index 0000000000..e69de29bb2
diff --git a/tests/benchmarks/test_general_performance.py b/tests/benchmarks/test_general_performance.py
new file mode 100644
index 0000000000..87add6d174
--- /dev/null
+++ b/tests/benchmarks/test_general_performance.py
@@ -0,0 +1,399 @@
+import json
+import sys
+from collections.abc import Iterator
+from typing import Annotated, Any
+
+import pytest
+from fastapi import Depends, FastAPI
+from fastapi.testclient import TestClient
+from pydantic import BaseModel
+
+if "--codspeed" not in sys.argv:
+ pytest.skip(
+ "Benchmark tests are skipped by default; run with --codspeed.",
+ allow_module_level=True,
+ )
+
+LARGE_ITEMS: list[dict[str, Any]] = [
+ {
+ "id": i,
+ "name": f"item-{i}",
+ "values": list(range(25)),
+ "meta": {
+ "active": True,
+ "group": i % 10,
+ "tag": f"t{i % 5}",
+ },
+ }
+ for i in range(300)
+]
+
+LARGE_METADATA: dict[str, Any] = {
+ "source": "benchmark",
+ "version": 1,
+ "flags": {"a": True, "b": False, "c": True},
+ "notes": ["x" * 50, "y" * 50, "z" * 50],
+}
+
+LARGE_PAYLOAD: dict[str, Any] = {"items": LARGE_ITEMS, "metadata": LARGE_METADATA}
+
+
+def dep_a():
+ return 40
+
+
+def dep_b(a: Annotated[int, Depends(dep_a)]):
+ return a + 2
+
+
+class ItemIn(BaseModel):
+ name: str
+ value: int
+
+
+class ItemOut(BaseModel):
+ name: str
+ value: int
+ dep: int
+
+
+class LargeIn(BaseModel):
+ items: list[dict[str, Any]]
+ metadata: dict[str, Any]
+
+
+class LargeOut(BaseModel):
+ items: list[dict[str, Any]]
+ metadata: dict[str, Any]
+
+
+app = FastAPI()
+
+
+@app.post("/sync/validated", response_model=ItemOut)
+def sync_validated(item: ItemIn, dep: Annotated[int, Depends(dep_b)]):
+ return ItemOut(name=item.name, value=item.value, dep=dep)
+
+
+@app.get("/sync/dict-no-response-model")
+def sync_dict_no_response_model():
+ return {"name": "foo", "value": 123}
+
+
+@app.get("/sync/dict-with-response-model", response_model=ItemOut)
+def sync_dict_with_response_model(
+ dep: Annotated[int, Depends(dep_b)],
+):
+ return {"name": "foo", "value": 123, "dep": dep}
+
+
+@app.get("/sync/model-no-response-model")
+def sync_model_no_response_model(dep: Annotated[int, Depends(dep_b)]):
+ return ItemOut(name="foo", value=123, dep=dep)
+
+
+@app.get("/sync/model-with-response-model", response_model=ItemOut)
+def sync_model_with_response_model(dep: Annotated[int, Depends(dep_b)]):
+ return ItemOut(name="foo", value=123, dep=dep)
+
+
+@app.post("/async/validated", response_model=ItemOut)
+async def async_validated(
+ item: ItemIn,
+ dep: Annotated[int, Depends(dep_b)],
+):
+ return ItemOut(name=item.name, value=item.value, dep=dep)
+
+
+@app.post("/sync/large-receive")
+def sync_large_receive(payload: LargeIn):
+ return {"received": len(payload.items)}
+
+
+@app.post("/async/large-receive")
+async def async_large_receive(payload: LargeIn):
+ return {"received": len(payload.items)}
+
+
+@app.get("/sync/large-dict-no-response-model")
+def sync_large_dict_no_response_model():
+ return LARGE_PAYLOAD
+
+
+@app.get("/sync/large-dict-with-response-model", response_model=LargeOut)
+def sync_large_dict_with_response_model():
+ return LARGE_PAYLOAD
+
+
+@app.get("/sync/large-model-no-response-model")
+def sync_large_model_no_response_model():
+ return LargeOut(items=LARGE_ITEMS, metadata=LARGE_METADATA)
+
+
+@app.get("/sync/large-model-with-response-model", response_model=LargeOut)
+def sync_large_model_with_response_model():
+ return LargeOut(items=LARGE_ITEMS, metadata=LARGE_METADATA)
+
+
+@app.get("/async/large-dict-no-response-model")
+async def async_large_dict_no_response_model():
+ return LARGE_PAYLOAD
+
+
+@app.get("/async/large-dict-with-response-model", response_model=LargeOut)
+async def async_large_dict_with_response_model():
+ return LARGE_PAYLOAD
+
+
+@app.get("/async/large-model-no-response-model")
+async def async_large_model_no_response_model():
+ return LargeOut(items=LARGE_ITEMS, metadata=LARGE_METADATA)
+
+
+@app.get("/async/large-model-with-response-model", response_model=LargeOut)
+async def async_large_model_with_response_model():
+ return LargeOut(items=LARGE_ITEMS, metadata=LARGE_METADATA)
+
+
+@app.get("/async/dict-no-response-model")
+async def async_dict_no_response_model():
+ return {"name": "foo", "value": 123}
+
+
+@app.get("/async/dict-with-response-model", response_model=ItemOut)
+async def async_dict_with_response_model(
+ dep: Annotated[int, Depends(dep_b)],
+):
+ return {"name": "foo", "value": 123, "dep": dep}
+
+
+@app.get("/async/model-no-response-model")
+async def async_model_no_response_model(
+ dep: Annotated[int, Depends(dep_b)],
+):
+ return ItemOut(name="foo", value=123, dep=dep)
+
+
+@app.get("/async/model-with-response-model", response_model=ItemOut)
+async def async_model_with_response_model(
+ dep: Annotated[int, Depends(dep_b)],
+):
+ return ItemOut(name="foo", value=123, dep=dep)
+
+
+@pytest.fixture(scope="module")
+def client() -> Iterator[TestClient]:
+ with TestClient(app) as client:
+ yield client
+
+
+def _bench_get(benchmark, client: TestClient, path: str) -> tuple[int, bytes]:
+ warmup = client.get(path)
+ assert warmup.status_code == 200
+
+ def do_request() -> tuple[int, bytes]:
+ response = client.get(path)
+ return response.status_code, response.content
+
+ return benchmark(do_request)
+
+
+def _bench_post_json(
+ benchmark, client: TestClient, path: str, json: dict[str, Any]
+) -> tuple[int, bytes]:
+ warmup = client.post(path, json=json)
+ assert warmup.status_code == 200
+
+ def do_request() -> tuple[int, bytes]:
+ response = client.post(path, json=json)
+ return response.status_code, response.content
+
+ return benchmark(do_request)
+
+
+def test_sync_receiving_validated_pydantic_model(benchmark, client: TestClient) -> None:
+ status_code, body = _bench_post_json(
+ benchmark,
+ client,
+ "/sync/validated",
+ json={"name": "foo", "value": 123},
+ )
+ assert status_code == 200
+ assert body == b'{"name":"foo","value":123,"dep":42}'
+
+
+def test_sync_return_dict_without_response_model(benchmark, client: TestClient) -> None:
+ status_code, body = _bench_get(benchmark, client, "/sync/dict-no-response-model")
+ assert status_code == 200
+ assert body == b'{"name":"foo","value":123}'
+
+
+def test_sync_return_dict_with_response_model(benchmark, client: TestClient) -> None:
+ status_code, body = _bench_get(benchmark, client, "/sync/dict-with-response-model")
+ assert status_code == 200
+ assert body == b'{"name":"foo","value":123,"dep":42}'
+
+
+def test_sync_return_model_without_response_model(
+ benchmark, client: TestClient
+) -> None:
+ status_code, body = _bench_get(benchmark, client, "/sync/model-no-response-model")
+ assert status_code == 200
+ assert body == b'{"name":"foo","value":123,"dep":42}'
+
+
+def test_sync_return_model_with_response_model(benchmark, client: TestClient) -> None:
+ status_code, body = _bench_get(benchmark, client, "/sync/model-with-response-model")
+ assert status_code == 200
+ assert body == b'{"name":"foo","value":123,"dep":42}'
+
+
+def test_async_receiving_validated_pydantic_model(
+ benchmark, client: TestClient
+) -> None:
+ status_code, body = _bench_post_json(
+ benchmark, client, "/async/validated", json={"name": "foo", "value": 123}
+ )
+ assert status_code == 200
+ assert body == b'{"name":"foo","value":123,"dep":42}'
+
+
+def test_async_return_dict_without_response_model(
+ benchmark, client: TestClient
+) -> None:
+ status_code, body = _bench_get(benchmark, client, "/async/dict-no-response-model")
+ assert status_code == 200
+ assert body == b'{"name":"foo","value":123}'
+
+
+def test_async_return_dict_with_response_model(benchmark, client: TestClient) -> None:
+ status_code, body = _bench_get(benchmark, client, "/async/dict-with-response-model")
+ assert status_code == 200
+ assert body == b'{"name":"foo","value":123,"dep":42}'
+
+
+def test_async_return_model_without_response_model(
+ benchmark, client: TestClient
+) -> None:
+ status_code, body = _bench_get(benchmark, client, "/async/model-no-response-model")
+ assert status_code == 200
+ assert body == b'{"name":"foo","value":123,"dep":42}'
+
+
+def test_async_return_model_with_response_model(benchmark, client: TestClient) -> None:
+ status_code, body = _bench_get(
+ benchmark, client, "/async/model-with-response-model"
+ )
+ assert status_code == 200
+ assert body == b'{"name":"foo","value":123,"dep":42}'
+
+
+def test_sync_receiving_large_payload(benchmark, client: TestClient) -> None:
+ status_code, body = _bench_post_json(
+ benchmark,
+ client,
+ "/sync/large-receive",
+ json=LARGE_PAYLOAD,
+ )
+ assert status_code == 200
+ assert body == b'{"received":300}'
+
+
+def test_async_receiving_large_payload(benchmark, client: TestClient) -> None:
+ status_code, body = _bench_post_json(
+ benchmark,
+ client,
+ "/async/large-receive",
+ json=LARGE_PAYLOAD,
+ )
+ assert status_code == 200
+ assert body == b'{"received":300}'
+
+
+def _expected_large_payload_json_bytes() -> bytes:
+ return json.dumps(
+ LARGE_PAYLOAD,
+ ensure_ascii=False,
+ allow_nan=False,
+ separators=(",", ":"),
+ ).encode("utf-8")
+
+
+def test_sync_return_large_dict_without_response_model(
+ benchmark, client: TestClient
+) -> None:
+ status_code, body = _bench_get(
+ benchmark, client, "/sync/large-dict-no-response-model"
+ )
+ assert status_code == 200
+ assert body == _expected_large_payload_json_bytes()
+
+
+def test_sync_return_large_dict_with_response_model(
+ benchmark, client: TestClient
+) -> None:
+ status_code, body = _bench_get(
+ benchmark, client, "/sync/large-dict-with-response-model"
+ )
+ assert status_code == 200
+ assert body == _expected_large_payload_json_bytes()
+
+
+def test_sync_return_large_model_without_response_model(
+ benchmark, client: TestClient
+) -> None:
+ status_code, body = _bench_get(
+ benchmark, client, "/sync/large-model-no-response-model"
+ )
+ assert status_code == 200
+ assert body == _expected_large_payload_json_bytes()
+
+
+def test_sync_return_large_model_with_response_model(
+ benchmark, client: TestClient
+) -> None:
+ status_code, body = _bench_get(
+ benchmark, client, "/sync/large-model-with-response-model"
+ )
+ assert status_code == 200
+ assert body == _expected_large_payload_json_bytes()
+
+
+def test_async_return_large_dict_without_response_model(
+ benchmark, client: TestClient
+) -> None:
+ status_code, body = _bench_get(
+ benchmark, client, "/async/large-dict-no-response-model"
+ )
+ assert status_code == 200
+ assert body == _expected_large_payload_json_bytes()
+
+
+def test_async_return_large_dict_with_response_model(
+ benchmark, client: TestClient
+) -> None:
+ status_code, body = _bench_get(
+ benchmark, client, "/async/large-dict-with-response-model"
+ )
+ assert status_code == 200
+ assert body == _expected_large_payload_json_bytes()
+
+
+def test_async_return_large_model_without_response_model(
+ benchmark, client: TestClient
+) -> None:
+ status_code, body = _bench_get(
+ benchmark, client, "/async/large-model-no-response-model"
+ )
+ assert status_code == 200
+ assert body == _expected_large_payload_json_bytes()
+
+
+def test_async_return_large_model_with_response_model(
+ benchmark, client: TestClient
+) -> None:
+ status_code, body = _bench_get(
+ benchmark, client, "/async/large-model-with-response-model"
+ )
+ assert status_code == 200
+ assert body == _expected_large_payload_json_bytes()
diff --git a/tests/main.py b/tests/main.py
index 2f1d617115..7edb16c615 100644
--- a/tests/main.py
+++ b/tests/main.py
@@ -1,5 +1,5 @@
import http
-from typing import FrozenSet, List, Optional
+from typing import Optional
from fastapi import FastAPI, Path, Query
@@ -195,15 +195,15 @@ def get_enum_status_code():
@app.get("/query/frozenset")
-def get_query_type_frozenset(query: FrozenSet[int] = Query(...)):
+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]:
+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]:
+def get_query_list_default(device_ids: list[int] = Query(default=[])) -> list[int]:
return device_ids
diff --git a/tests/test_additional_properties.py b/tests/test_additional_properties.py
index be14d10edc..2622366400 100644
--- a/tests/test_additional_properties.py
+++ b/tests/test_additional_properties.py
@@ -1,5 +1,3 @@
-from typing import Dict
-
from fastapi import FastAPI
from fastapi.testclient import TestClient
from pydantic import BaseModel
@@ -8,7 +6,7 @@ app = FastAPI()
class Items(BaseModel):
- items: Dict[str, int]
+ items: dict[str, int]
@app.post("/foo")
diff --git a/tests/test_additional_properties_bool.py b/tests/test_additional_properties_bool.py
index de59e48ce7..063297a3f2 100644
--- a/tests/test_additional_properties_bool.py
+++ b/tests/test_additional_properties_bool.py
@@ -1,19 +1,12 @@
from typing import Union
-from dirty_equals import IsDict
from fastapi import FastAPI
-from fastapi._compat import PYDANTIC_V2
from fastapi.testclient import TestClient
from pydantic import BaseModel, ConfigDict
class FooBaseModel(BaseModel):
- if PYDANTIC_V2:
- model_config = ConfigDict(extra="forbid")
- else:
-
- class Config:
- extra = "forbid"
+ model_config = ConfigDict(extra="forbid")
class Foo(FooBaseModel):
@@ -58,19 +51,13 @@ def test_openapi_schema():
"requestBody": {
"content": {
"application/json": {
- "schema": IsDict(
- {
- "anyOf": [
- {"$ref": "#/components/schemas/Foo"},
- {"type": "null"},
- ],
- "title": "Foo",
- }
- )
- | IsDict(
- # TODO: remove when deprecating Pydantic v1
- {"$ref": "#/components/schemas/Foo"}
- )
+ "schema": {
+ "anyOf": [
+ {"$ref": "#/components/schemas/Foo"},
+ {"type": "null"},
+ ],
+ "title": "Foo",
+ }
}
}
},
diff --git a/tests/test_additional_responses_custom_model_in_callback.py b/tests/test_additional_responses_custom_model_in_callback.py
index 2ad5754551..376d7714ed 100644
--- a/tests/test_additional_responses_custom_model_in_callback.py
+++ b/tests/test_additional_responses_custom_model_in_callback.py
@@ -1,6 +1,6 @@
-from dirty_equals import IsDict
from fastapi import APIRouter, FastAPI
from fastapi.testclient import TestClient
+from inline_snapshot import snapshot
from pydantic import BaseModel, HttpUrl
from starlette.responses import JSONResponse
@@ -32,121 +32,114 @@ client = TestClient(app)
def test_openapi_schema():
response = client.get("/openapi.json")
assert response.status_code == 200, response.text
- assert response.json() == {
- "openapi": "3.1.0",
- "info": {"title": "FastAPI", "version": "0.1.0"},
- "paths": {
- "/": {
- "post": {
- "summary": "Main Route",
- "operationId": "main_route__post",
- "parameters": [
- {
- "required": True,
- "schema": IsDict(
- {
- "title": "Callback Url",
- "minLength": 1,
- "type": "string",
- "format": "uri",
- }
- )
- # TODO: remove when deprecating Pydantic v1
- | IsDict(
- {
+ assert response.json() == snapshot(
+ {
+ "openapi": "3.1.0",
+ "info": {"title": "FastAPI", "version": "0.1.0"},
+ "paths": {
+ "/": {
+ "post": {
+ "summary": "Main Route",
+ "operationId": "main_route__post",
+ "parameters": [
+ {
+ "required": True,
+ "schema": {
"title": "Callback Url",
"maxLength": 2083,
"minLength": 1,
"type": "string",
"format": "uri",
- }
- ),
- "name": "callback_url",
- "in": "query",
- }
- ],
- "responses": {
- "200": {
- "description": "Successful Response",
- "content": {"application/json": {"schema": {}}},
+ },
+ "name": "callback_url",
+ "in": "query",
+ }
+ ],
+ "responses": {
+ "200": {
+ "description": "Successful Response",
+ "content": {"application/json": {"schema": {}}},
+ },
+ "422": {
+ "description": "Validation Error",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/HTTPValidationError"
+ }
+ }
+ },
+ },
},
- "422": {
- "description": "Validation Error",
- "content": {
- "application/json": {
- "schema": {
- "$ref": "#/components/schemas/HTTPValidationError"
+ "callbacks": {
+ "callback_route": {
+ "{$callback_url}/callback/": {
+ "get": {
+ "summary": "Callback Route",
+ "operationId": "callback_route__callback_url__callback__get",
+ "responses": {
+ "400": {
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/CustomModel"
+ }
+ }
+ },
+ "description": "Bad Request",
+ },
+ "200": {
+ "description": "Successful Response",
+ "content": {
+ "application/json": {"schema": {}}
+ },
+ },
+ },
}
}
- },
+ }
+ },
+ }
+ }
+ },
+ "components": {
+ "schemas": {
+ "CustomModel": {
+ "title": "CustomModel",
+ "required": ["a"],
+ "type": "object",
+ "properties": {"a": {"title": "A", "type": "integer"}},
+ },
+ "HTTPValidationError": {
+ "title": "HTTPValidationError",
+ "type": "object",
+ "properties": {
+ "detail": {
+ "title": "Detail",
+ "type": "array",
+ "items": {
+ "$ref": "#/components/schemas/ValidationError"
+ },
+ }
},
},
- "callbacks": {
- "callback_route": {
- "{$callback_url}/callback/": {
- "get": {
- "summary": "Callback Route",
- "operationId": "callback_route__callback_url__callback__get",
- "responses": {
- "400": {
- "content": {
- "application/json": {
- "schema": {
- "$ref": "#/components/schemas/CustomModel"
- }
- }
- },
- "description": "Bad Request",
- },
- "200": {
- "description": "Successful Response",
- "content": {
- "application/json": {"schema": {}}
- },
- },
- },
- }
- }
- }
+ "ValidationError": {
+ "title": "ValidationError",
+ "required": ["loc", "msg", "type"],
+ "type": "object",
+ "properties": {
+ "loc": {
+ "title": "Location",
+ "type": "array",
+ "items": {
+ "anyOf": [{"type": "string"}, {"type": "integer"}]
+ },
+ },
+ "msg": {"title": "Message", "type": "string"},
+ "type": {"title": "Error Type", "type": "string"},
+ },
},
}
- }
- },
- "components": {
- "schemas": {
- "CustomModel": {
- "title": "CustomModel",
- "required": ["a"],
- "type": "object",
- "properties": {"a": {"title": "A", "type": "integer"}},
- },
- "HTTPValidationError": {
- "title": "HTTPValidationError",
- "type": "object",
- "properties": {
- "detail": {
- "title": "Detail",
- "type": "array",
- "items": {"$ref": "#/components/schemas/ValidationError"},
- }
- },
- },
- "ValidationError": {
- "title": "ValidationError",
- "required": ["loc", "msg", "type"],
- "type": "object",
- "properties": {
- "loc": {
- "title": "Location",
- "type": "array",
- "items": {
- "anyOf": [{"type": "string"}, {"type": "integer"}]
- },
- },
- "msg": {"title": "Message", "type": "string"},
- "type": {"title": "Error Type", "type": "string"},
- },
- },
- }
- },
- }
+ },
+ }
+ )
diff --git a/tests/test_additional_responses_custom_validationerror.py b/tests/test_additional_responses_custom_validationerror.py
index 9fec5c96d4..8724e5ecb8 100644
--- a/tests/test_additional_responses_custom_validationerror.py
+++ b/tests/test_additional_responses_custom_validationerror.py
@@ -1,5 +1,3 @@
-import typing
-
from fastapi import FastAPI
from fastapi.responses import JSONResponse
from fastapi.testclient import TestClient
@@ -18,7 +16,7 @@ class Error(BaseModel):
class JsonApiError(BaseModel):
- errors: typing.List[Error]
+ errors: list[Error]
@app.get(
diff --git a/tests/test_additional_responses_response_class.py b/tests/test_additional_responses_response_class.py
index 68753561c9..fecc3ee16b 100644
--- a/tests/test_additional_responses_response_class.py
+++ b/tests/test_additional_responses_response_class.py
@@ -1,5 +1,3 @@
-import typing
-
from fastapi import FastAPI
from fastapi.responses import JSONResponse
from fastapi.testclient import TestClient
@@ -18,7 +16,7 @@ class Error(BaseModel):
class JsonApiError(BaseModel):
- errors: typing.List[Error]
+ errors: list[Error]
@app.get(
diff --git a/tests/test_allow_inf_nan_in_enforcing.py b/tests/test_allow_inf_nan_in_enforcing.py
index 9e855fdf81..083a024af0 100644
--- a/tests/test_allow_inf_nan_in_enforcing.py
+++ b/tests/test_allow_inf_nan_in_enforcing.py
@@ -1,7 +1,8 @@
+from typing import Annotated
+
import pytest
from fastapi import Body, FastAPI, Query
from fastapi.testclient import TestClient
-from typing_extensions import Annotated
app = FastAPI()
diff --git a/tests/test_ambiguous_params.py b/tests/test_ambiguous_params.py
index 8a31442eb0..44d49b7818 100644
--- a/tests/test_ambiguous_params.py
+++ b/tests/test_ambiguous_params.py
@@ -1,9 +1,9 @@
+from typing import Annotated
+
import pytest
from fastapi import Depends, FastAPI, Path
from fastapi.param_functions import Query
from fastapi.testclient import TestClient
-from fastapi.utils import PYDANTIC_V2
-from typing_extensions import Annotated
app = FastAPI()
@@ -70,6 +70,5 @@ def test_multiple_annotations():
response = client.get("/multi-query", params={"foo": "123"})
assert response.status_code == 422
- if PYDANTIC_V2:
- response = client.get("/multi-query", params={"foo": "1"})
- assert response.status_code == 422
+ response = client.get("/multi-query", params={"foo": "1"})
+ assert response.status_code == 422
diff --git a/tests/test_annotated.py b/tests/test_annotated.py
index 473d33e52c..39f6f83b29 100644
--- a/tests/test_annotated.py
+++ b/tests/test_annotated.py
@@ -1,8 +1,8 @@
+from typing import Annotated
+
import pytest
-from dirty_equals import IsDict
from fastapi import APIRouter, FastAPI, Query
from fastapi.testclient import TestClient
-from typing_extensions import Annotated
app = FastAPI()
@@ -31,44 +31,23 @@ client = TestClient(app)
foo_is_missing = {
"detail": [
- IsDict(
- {
- "loc": ["query", "foo"],
- "msg": "Field required",
- "type": "missing",
- "input": None,
- }
- )
- # TODO: remove when deprecating Pydantic v1
- | IsDict(
- {
- "loc": ["query", "foo"],
- "msg": "field required",
- "type": "value_error.missing",
- }
- )
+ {
+ "loc": ["query", "foo"],
+ "msg": "Field required",
+ "type": "missing",
+ "input": None,
+ }
]
}
foo_is_short = {
"detail": [
- IsDict(
- {
- "ctx": {"min_length": 1},
- "loc": ["query", "foo"],
- "msg": "String should have at least 1 character",
- "type": "string_too_short",
- "input": "",
- }
- )
- # TODO: remove when deprecating Pydantic v1
- | IsDict(
- {
- "ctx": {"limit_value": 1},
- "loc": ["query", "foo"],
- "msg": "ensure this value has at least 1 characters",
- "type": "value_error.any_str.min_length",
- }
- )
+ {
+ "ctx": {"min_length": 1},
+ "loc": ["query", "foo"],
+ "msg": "String should have at least 1 character",
+ "type": "string_too_short",
+ "input": "",
+ }
]
}
diff --git a/tests/test_application.py b/tests/test_application.py
index 8f1b0a18d3..001586ff78 100644
--- a/tests/test_application.py
+++ b/tests/test_application.py
@@ -1,5 +1,4 @@
import pytest
-from dirty_equals import IsDict
from fastapi.testclient import TestClient
from .main import app
@@ -274,14 +273,10 @@ def test_openapi_schema():
"name": "item_id",
"in": "path",
"required": True,
- "schema": IsDict(
- {
- "anyOf": [{"type": "string"}, {"type": "null"}],
- "title": "Item Id",
- }
- )
- # TODO: remove when deprecating Pydantic v1
- | IsDict({"title": "Item Id", "type": "string"}),
+ "schema": {
+ "anyOf": [{"type": "string"}, {"type": "null"}],
+ "title": "Item Id",
+ },
}
],
}
@@ -984,14 +979,10 @@ def test_openapi_schema():
"name": "query",
"in": "query",
"required": False,
- "schema": IsDict(
- {
- "anyOf": [{"type": "integer"}, {"type": "null"}],
- "title": "Query",
- }
- )
- # TODO: remove when deprecating Pydantic v1
- | IsDict({"title": "Query", "type": "integer"}),
+ "schema": {
+ "anyOf": [{"type": "integer"}, {"type": "null"}],
+ "title": "Query",
+ },
}
],
}
diff --git a/tests/test_arbitrary_types.py b/tests/test_arbitrary_types.py
index e5fa95ef22..481acc3bfc 100644
--- a/tests/test_arbitrary_types.py
+++ b/tests/test_arbitrary_types.py
@@ -1,12 +1,9 @@
-from typing import List
+from typing import Annotated
import pytest
from fastapi import FastAPI
from fastapi.testclient import TestClient
from inline_snapshot import snapshot
-from typing_extensions import Annotated
-
-from .utils import needs_pydanticv2
@pytest.fixture(name="client")
@@ -25,7 +22,7 @@ def get_client():
FakeNumpyArrayPydantic = Annotated[
FakeNumpyArray,
- WithJsonSchema(TypeAdapter(List[float]).json_schema()),
+ WithJsonSchema(TypeAdapter(list[float]).json_schema()),
PlainSerializer(lambda v: v.data),
]
@@ -43,13 +40,11 @@ def get_client():
return client
-@needs_pydanticv2
def test_get(client: TestClient):
response = client.get("/")
assert response.json() == {"custom_field": [1.0, 2.0, 3.0]}
-@needs_pydanticv2
def test_typeadapter():
# This test is only to confirm that Pydantic alone is working as expected
from pydantic import (
@@ -66,7 +61,7 @@ def test_typeadapter():
FakeNumpyArrayPydantic = Annotated[
FakeNumpyArray,
- WithJsonSchema(TypeAdapter(List[float]).json_schema()),
+ WithJsonSchema(TypeAdapter(list[float]).json_schema()),
PlainSerializer(lambda v: v.data),
]
@@ -94,7 +89,6 @@ def test_typeadapter():
)
-@needs_pydanticv2
def test_openapi_schema(client: TestClient):
response = client.get("openapi.json")
assert response.json() == snapshot(
diff --git a/tests/test_compat.py b/tests/test_compat.py
index 26537c5ab7..0b5600f8f5 100644
--- a/tests/test_compat.py
+++ b/tests/test_compat.py
@@ -1,23 +1,18 @@
-from typing import Any, Dict, List, Union
+from typing import Union
from fastapi import FastAPI, UploadFile
from fastapi._compat import (
Undefined,
- _get_model_config,
- get_cached_model_fields,
- is_scalar_field,
is_uploadfile_sequence_annotation,
- may_v1,
)
from fastapi._compat.shared import is_bytes_sequence_annotation
from fastapi.testclient import TestClient
from pydantic import BaseModel, ConfigDict
from pydantic.fields import FieldInfo
-from .utils import needs_py310, needs_py_lt_314, needs_pydanticv2
+from .utils import needs_py310
-@needs_pydanticv2
def test_model_field_default_required():
from fastapi._compat import v2
@@ -27,41 +22,11 @@ def test_model_field_default_required():
assert field.default is Undefined
-@needs_py_lt_314
-def test_v1_plain_validator_function():
- from fastapi._compat import v1
-
- # For coverage
- def func(v): # pragma: no cover
- return v
-
- result = v1.with_info_plain_validator_function(func)
- assert result == {}
-
-
-def test_is_model_field():
- # For coverage
- from fastapi._compat import _is_model_field
-
- assert not _is_model_field(str)
-
-
-@needs_pydanticv2
-def test_get_model_config():
- # For coverage in Pydantic v2
- class Foo(BaseModel):
- model_config = ConfigDict(from_attributes=True)
-
- foo = Foo()
- config = _get_model_config(foo)
- assert config == {"from_attributes": True}
-
-
def test_complex():
app = FastAPI()
@app.post("/")
- def foo(foo: Union[str, List[int]]):
+ def foo(foo: Union[str, list[int]]):
return foo
client = TestClient(app)
@@ -75,7 +40,6 @@ def test_complex():
assert response2.json() == [1, 2]
-@needs_pydanticv2
def test_propagates_pydantic2_model_config():
app = FastAPI()
@@ -95,7 +59,7 @@ def test_propagates_pydantic2_model_config():
embedded_model: EmbeddedModel = EmbeddedModel()
@app.post("/")
- def foo(req: Model) -> Dict[str, Union[str, None]]:
+ def foo(req: Model) -> dict[str, Union[str, None]]:
return {
"value": req.value or None,
"embedded_value": req.embedded_model.value or None,
@@ -125,7 +89,7 @@ def test_is_bytes_sequence_annotation_union():
# TODO: in theory this would allow declaring types that could be lists of bytes
# to be read from files and other types, but I'm not even sure it's a good idea
# to support it as a first class "feature"
- assert is_bytes_sequence_annotation(Union[List[str], List[bytes]])
+ assert is_bytes_sequence_annotation(Union[list[str], list[bytes]])
def test_is_uploadfile_sequence_annotation():
@@ -133,22 +97,20 @@ def test_is_uploadfile_sequence_annotation():
# TODO: in theory this would allow declaring types that could be lists of UploadFile
# and other types, but I'm not even sure it's a good idea to support it as a first
# class "feature"
- assert is_uploadfile_sequence_annotation(Union[List[str], List[UploadFile]])
+ assert is_uploadfile_sequence_annotation(Union[list[str], list[UploadFile]])
-@needs_pydanticv2
def test_serialize_sequence_value_with_optional_list():
"""Test that serialize_sequence_value handles optional lists correctly."""
from fastapi._compat import v2
- field_info = FieldInfo(annotation=Union[List[str], None])
+ field_info = FieldInfo(annotation=Union[list[str], None])
field = v2.ModelField(name="items", field_info=field_info)
result = v2.serialize_sequence_value(field=field, value=["a", "b", "c"])
assert result == ["a", "b", "c"]
assert isinstance(result, list)
-@needs_pydanticv2
@needs_py310
def test_serialize_sequence_value_with_optional_list_pipe_union():
"""Test that serialize_sequence_value handles optional lists correctly (with new syntax)."""
@@ -161,43 +123,12 @@ def test_serialize_sequence_value_with_optional_list_pipe_union():
assert isinstance(result, list)
-@needs_pydanticv2
def test_serialize_sequence_value_with_none_first_in_union():
"""Test that serialize_sequence_value handles Union[None, List[...]] correctly."""
from fastapi._compat import v2
- field_info = FieldInfo(annotation=Union[None, List[str]])
+ field_info = FieldInfo(annotation=Union[None, list[str]])
field = v2.ModelField(name="items", field_info=field_info)
result = v2.serialize_sequence_value(field=field, value=["x", "y"])
assert result == ["x", "y"]
assert isinstance(result, list)
-
-
-@needs_py_lt_314
-def test_is_pv1_scalar_field():
- from fastapi._compat import v1
-
- # For coverage
- class Model(v1.BaseModel):
- foo: Union[str, Dict[str, Any]]
-
- fields = v1.get_model_fields(Model)
- assert not is_scalar_field(fields[0])
-
-
-@needs_py_lt_314
-def test_get_model_fields_cached():
- from fastapi._compat import v1
-
- class Model(may_v1.BaseModel):
- foo: str
-
- non_cached_fields = v1.get_model_fields(Model)
- non_cached_fields2 = v1.get_model_fields(Model)
- cached_fields = get_cached_model_fields(Model)
- cached_fields2 = get_cached_model_fields(Model)
- for f1, f2 in zip(cached_fields, cached_fields2):
- assert f1 is f2
-
- assert non_cached_fields is not non_cached_fields2
- assert cached_fields is cached_fields2
diff --git a/tests/test_compat_params_v1.py b/tests/test_compat_params_v1.py
deleted file mode 100644
index 7064761cb5..0000000000
--- a/tests/test_compat_params_v1.py
+++ /dev/null
@@ -1,1122 +0,0 @@
-import sys
-from typing import List, Optional
-
-import pytest
-
-from tests.utils import pydantic_snapshot, skip_module_if_py_gte_314
-
-if sys.version_info >= (3, 14):
- skip_module_if_py_gte_314()
-
-from fastapi import FastAPI
-from fastapi._compat.v1 import BaseModel
-from fastapi.temp_pydantic_v1_params import (
- Body,
- Cookie,
- File,
- Form,
- Header,
- Path,
- Query,
-)
-from fastapi.testclient import TestClient
-from inline_snapshot import snapshot
-from typing_extensions import Annotated
-
-
-class Item(BaseModel):
- name: str
- price: float
- description: Optional[str] = None
-
-
-app = FastAPI()
-
-
-@app.get("/items/{item_id}")
-def get_item_with_path(
- item_id: Annotated[int, Path(title="The ID of the item", ge=1, le=1000)],
-):
- return {"item_id": item_id}
-
-
-@app.get("/items/")
-def get_items_with_query(
- q: Annotated[
- Optional[str], Query(min_length=3, max_length=50, pattern="^[a-zA-Z0-9 ]+$")
- ] = None,
- skip: Annotated[int, Query(ge=0)] = 0,
- limit: Annotated[int, Query(ge=1, le=100, examples=[5])] = 10,
-):
- return {"q": q, "skip": skip, "limit": limit}
-
-
-@app.get("/users/")
-def get_user_with_header(
- x_custom: Annotated[Optional[str], Header()] = None,
- x_token: Annotated[Optional[str], Header(convert_underscores=True)] = None,
-):
- return {"x_custom": x_custom, "x_token": x_token}
-
-
-@app.get("/cookies/")
-def get_cookies(
- session_id: Annotated[Optional[str], Cookie()] = None,
- tracking_id: Annotated[Optional[str], Cookie(min_length=10)] = None,
-):
- return {"session_id": session_id, "tracking_id": tracking_id}
-
-
-@app.post("/items/")
-def create_item(
- item: Annotated[
- Item,
- Body(examples=[{"name": "Foo", "price": 35.4, "description": "The Foo item"}]),
- ],
-):
- return {"item": item}
-
-
-@app.post("/items-embed/")
-def create_item_embed(
- item: Annotated[Item, Body(embed=True)],
-):
- return {"item": item}
-
-
-@app.put("/items/{item_id}")
-def update_item(
- item_id: Annotated[int, Path(ge=1)],
- item: Annotated[Item, Body()],
- importance: Annotated[int, Body(gt=0, le=10)],
-):
- return {"item": item, "importance": importance}
-
-
-@app.post("/form-data/")
-def submit_form(
- username: Annotated[str, Form(min_length=3, max_length=50)],
- password: Annotated[str, Form(min_length=8)],
- email: Annotated[Optional[str], Form()] = None,
-):
- return {"username": username, "password": password, "email": email}
-
-
-@app.post("/upload/")
-def upload_file(
- file: Annotated[bytes, File()],
- description: Annotated[Optional[str], Form()] = None,
-):
- return {"file_size": len(file), "description": description}
-
-
-@app.post("/upload-multiple/")
-def upload_multiple_files(
- files: Annotated[List[bytes], File()],
- note: Annotated[str, Form()] = "",
-):
- return {
- "file_count": len(files),
- "total_size": sum(len(f) for f in files),
- "note": note,
- }
-
-
-client = TestClient(app)
-
-
-# Path parameter tests
-def test_path_param_valid():
- response = client.get("/items/50")
- assert response.status_code == 200
- assert response.json() == {"item_id": 50}
-
-
-def test_path_param_too_large():
- response = client.get("/items/1001")
- assert response.status_code == 422
- error = response.json()["detail"][0]
- assert error["loc"] == ["path", "item_id"]
-
-
-def test_path_param_too_small():
- response = client.get("/items/0")
- assert response.status_code == 422
- error = response.json()["detail"][0]
- assert error["loc"] == ["path", "item_id"]
-
-
-# Query parameter tests
-def test_query_params_valid():
- response = client.get("/items/?q=test search&skip=5&limit=20")
- assert response.status_code == 200
- assert response.json() == {"q": "test search", "skip": 5, "limit": 20}
-
-
-def test_query_params_defaults():
- response = client.get("/items/")
- assert response.status_code == 200
- assert response.json() == {"q": None, "skip": 0, "limit": 10}
-
-
-def test_query_param_too_short():
- response = client.get("/items/?q=ab")
- assert response.status_code == 422
- error = response.json()["detail"][0]
- assert error["loc"] == ["query", "q"]
-
-
-def test_query_param_invalid_pattern():
- response = client.get("/items/?q=test@#$")
- assert response.status_code == 422
- error = response.json()["detail"][0]
- assert error["loc"] == ["query", "q"]
-
-
-def test_query_param_limit_too_large():
- response = client.get("/items/?limit=101")
- assert response.status_code == 422
- error = response.json()["detail"][0]
- assert error["loc"] == ["query", "limit"]
-
-
-# Header parameter tests
-def test_header_params():
- response = client.get(
- "/users/",
- headers={"X-Custom": "Plumbus", "X-Token": "secret-token"},
- )
- assert response.status_code == 200
- assert response.json() == {
- "x_custom": "Plumbus",
- "x_token": "secret-token",
- }
-
-
-def test_header_underscore_conversion():
- response = client.get(
- "/users/",
- headers={"x-token": "secret-token-with-dash"},
- )
- assert response.status_code == 200
- assert response.json()["x_token"] == "secret-token-with-dash"
-
-
-def test_header_params_none():
- response = client.get("/users/")
- assert response.status_code == 200
- assert response.json() == {"x_custom": None, "x_token": None}
-
-
-# Cookie parameter tests
-def test_cookie_params():
- with TestClient(app) as client:
- client.cookies.set("session_id", "abc123")
- client.cookies.set("tracking_id", "1234567890abcdef")
- response = client.get("/cookies/")
- assert response.status_code == 200
- assert response.json() == {
- "session_id": "abc123",
- "tracking_id": "1234567890abcdef",
- }
-
-
-def test_cookie_tracking_id_too_short():
- with TestClient(app) as client:
- client.cookies.set("tracking_id", "short")
- response = client.get("/cookies/")
- assert response.status_code == 422
- assert response.json() == snapshot(
- {
- "detail": [
- {
- "loc": ["cookie", "tracking_id"],
- "msg": "ensure this value has at least 10 characters",
- "type": "value_error.any_str.min_length",
- "ctx": {"limit_value": 10},
- }
- ]
- }
- )
-
-
-def test_cookie_params_none():
- response = client.get("/cookies/")
- assert response.status_code == 200
- assert response.json() == {"session_id": None, "tracking_id": None}
-
-
-# Body parameter tests
-def test_body_param():
- response = client.post(
- "/items/",
- json={"name": "Test Item", "price": 29.99, "description": "A test item"},
- )
- assert response.status_code == 200
- assert response.json() == {
- "item": {
- "name": "Test Item",
- "price": 29.99,
- "description": "A test item",
- }
- }
-
-
-def test_body_param_minimal():
- response = client.post(
- "/items/",
- json={"name": "Minimal", "price": 9.99},
- )
- assert response.status_code == 200
- assert response.json() == {
- "item": {"name": "Minimal", "price": 9.99, "description": None}
- }
-
-
-def test_body_param_missing_required():
- response = client.post(
- "/items/",
- json={"name": "Incomplete"},
- )
- assert response.status_code == 422
- error = response.json()["detail"][0]
- assert error["loc"] == ["body", "price"]
-
-
-def test_body_embed():
- response = client.post(
- "/items-embed/",
- json={"item": {"name": "Embedded", "price": 15.0}},
- )
- assert response.status_code == 200
- assert response.json() == {
- "item": {"name": "Embedded", "price": 15.0, "description": None}
- }
-
-
-def test_body_embed_wrong_structure():
- response = client.post(
- "/items-embed/",
- json={"name": "Not Embedded", "price": 15.0},
- )
- assert response.status_code == 422
-
-
-# Multiple body parameters test
-def test_multiple_body_params():
- response = client.put(
- "/items/5",
- json={
- "item": {"name": "Updated Item", "price": 49.99},
- "importance": 8,
- },
- )
- assert response.status_code == 200
- assert response.json() == snapshot(
- {
- "item": {"name": "Updated Item", "price": 49.99, "description": None},
- "importance": 8,
- }
- )
-
-
-def test_multiple_body_params_importance_too_large():
- response = client.put(
- "/items/5",
- json={
- "item": {"name": "Item", "price": 10.0},
- "importance": 11,
- },
- )
- assert response.status_code == 422
- assert response.json() == snapshot(
- {
- "detail": [
- {
- "loc": ["body", "importance"],
- "msg": "ensure this value is less than or equal to 10",
- "type": "value_error.number.not_le",
- "ctx": {"limit_value": 10},
- }
- ]
- }
- )
-
-
-def test_multiple_body_params_importance_too_small():
- response = client.put(
- "/items/5",
- json={
- "item": {"name": "Item", "price": 10.0},
- "importance": 0,
- },
- )
- assert response.status_code == 422
- assert response.json() == snapshot(
- {
- "detail": [
- {
- "loc": ["body", "importance"],
- "msg": "ensure this value is greater than 0",
- "type": "value_error.number.not_gt",
- "ctx": {"limit_value": 0},
- }
- ]
- }
- )
-
-
-# Form parameter tests
-def test_form_data_valid():
- response = client.post(
- "/form-data/",
- data={
- "username": "testuser",
- "password": "password123",
- "email": "test@example.com",
- },
- )
- assert response.status_code == 200, response.text
- assert response.json() == {
- "username": "testuser",
- "password": "password123",
- "email": "test@example.com",
- }
-
-
-def test_form_data_optional_field():
- response = client.post(
- "/form-data/",
- data={"username": "testuser", "password": "password123"},
- )
- assert response.status_code == 200
- assert response.json() == {
- "username": "testuser",
- "password": "password123",
- "email": None,
- }
-
-
-def test_form_data_username_too_short():
- response = client.post(
- "/form-data/",
- data={"username": "ab", "password": "password123"},
- )
- assert response.status_code == 422
- assert response.json() == snapshot(
- {
- "detail": [
- {
- "loc": ["body", "username"],
- "msg": "ensure this value has at least 3 characters",
- "type": "value_error.any_str.min_length",
- "ctx": {"limit_value": 3},
- }
- ]
- }
- )
-
-
-def test_form_data_password_too_short():
- response = client.post(
- "/form-data/",
- data={"username": "testuser", "password": "short"},
- )
- assert response.status_code == 422
- assert response.json() == snapshot(
- {
- "detail": [
- {
- "loc": ["body", "password"],
- "msg": "ensure this value has at least 8 characters",
- "type": "value_error.any_str.min_length",
- "ctx": {"limit_value": 8},
- }
- ]
- }
- )
-
-
-# File upload tests
-def test_upload_file():
- response = client.post(
- "/upload/",
- files={"file": ("test.txt", b"Hello, World!", "text/plain")},
- data={"description": "A test file"},
- )
- assert response.status_code == 200
- assert response.json() == {
- "file_size": 13,
- "description": "A test file",
- }
-
-
-def test_upload_file_without_description():
- response = client.post(
- "/upload/",
- files={"file": ("test.txt", b"Hello!", "text/plain")},
- )
- assert response.status_code == 200
- assert response.json() == {
- "file_size": 6,
- "description": None,
- }
-
-
-def test_upload_multiple_files():
- response = client.post(
- "/upload-multiple/",
- files=[
- ("files", ("file1.txt", b"Content 1", "text/plain")),
- ("files", ("file2.txt", b"Content 2", "text/plain")),
- ("files", ("file3.txt", b"Content 3", "text/plain")),
- ],
- data={"note": "Multiple files uploaded"},
- )
- assert response.status_code == 200
- assert response.json() == {
- "file_count": 3,
- "total_size": 27,
- "note": "Multiple files uploaded",
- }
-
-
-def test_upload_multiple_files_empty_note():
- response = client.post(
- "/upload-multiple/",
- files=[
- ("files", ("file1.txt", b"Test", "text/plain")),
- ],
- )
- assert response.status_code == 200
- assert response.json()["file_count"] == 1
- assert response.json()["note"] == ""
-
-
-# __repr__ tests
-def test_query_repr():
- query_param = Query(default=None, min_length=3)
- assert repr(query_param) == "Query(None)"
-
-
-def test_body_repr():
- body_param = Body(default=None)
- assert repr(body_param) == "Body(None)"
-
-
-# Deprecation warning tests for regex parameter
-def test_query_regex_deprecation_warning():
- with pytest.warns(DeprecationWarning, match="`regex` has been deprecated"):
- Query(regex="^test$")
-
-
-def test_body_regex_deprecation_warning():
- with pytest.warns(DeprecationWarning, match="`regex` has been deprecated"):
- Body(regex="^test$")
-
-
-# Deprecation warning tests for example parameter
-def test_query_example_deprecation_warning():
- with pytest.warns(DeprecationWarning, match="`example` has been deprecated"):
- Query(example="test example")
-
-
-def test_body_example_deprecation_warning():
- with pytest.warns(DeprecationWarning, match="`example` has been deprecated"):
- Body(example={"test": "example"})
-
-
-def test_openapi_schema():
- response = client.get("/openapi.json")
- assert response.status_code == 200, response.text
- assert response.json() == snapshot(
- {
- "openapi": "3.1.0",
- "info": {"title": "FastAPI", "version": "0.1.0"},
- "paths": {
- "/items/{item_id}": {
- "get": {
- "summary": "Get Item With Path",
- "operationId": "get_item_with_path_items__item_id__get",
- "parameters": [
- {
- "name": "item_id",
- "in": "path",
- "required": True,
- "schema": {
- "title": "The ID of the item",
- "minimum": 1,
- "maximum": 1000,
- "type": "integer",
- },
- }
- ],
- "responses": {
- "200": {
- "description": "Successful Response",
- "content": {"application/json": {"schema": {}}},
- },
- "422": {
- "description": "Validation Error",
- "content": {
- "application/json": {
- "schema": {
- "$ref": "#/components/schemas/HTTPValidationError"
- }
- }
- },
- },
- },
- },
- "put": {
- "summary": "Update Item",
- "operationId": "update_item_items__item_id__put",
- "parameters": [
- {
- "name": "item_id",
- "in": "path",
- "required": True,
- "schema": {
- "title": "Item Id",
- "minimum": 1,
- "type": "integer",
- },
- }
- ],
- "requestBody": {
- "required": True,
- "content": {
- "application/json": {
- "schema": pydantic_snapshot(
- v1=snapshot(
- {
- "$ref": "#/components/schemas/Body_update_item_items__item_id__put"
- }
- ),
- v2=snapshot(
- {
- "title": "Body",
- "allOf": [
- {
- "$ref": "#/components/schemas/Body_update_item_items__item_id__put"
- }
- ],
- }
- ),
- ),
- }
- },
- },
- "responses": {
- "200": {
- "description": "Successful Response",
- "content": {"application/json": {"schema": {}}},
- },
- "422": {
- "description": "Validation Error",
- "content": {
- "application/json": {
- "schema": {
- "$ref": "#/components/schemas/HTTPValidationError"
- }
- }
- },
- },
- },
- },
- },
- "/items/": {
- "get": {
- "summary": "Get Items With Query",
- "operationId": "get_items_with_query_items__get",
- "parameters": [
- {
- "name": "q",
- "in": "query",
- "required": False,
- "schema": {
- "title": "Q",
- "maxLength": 50,
- "minLength": 3,
- "pattern": "^[a-zA-Z0-9 ]+$",
- "type": "string",
- },
- },
- {
- "name": "skip",
- "in": "query",
- "required": False,
- "schema": {
- "title": "Skip",
- "default": 0,
- "minimum": 0,
- "type": "integer",
- },
- },
- {
- "name": "limit",
- "in": "query",
- "required": False,
- "schema": {
- "title": "Limit",
- "default": 10,
- "minimum": 1,
- "maximum": 100,
- "examples": [5],
- "type": "integer",
- },
- },
- ],
- "responses": {
- "200": {
- "description": "Successful Response",
- "content": {"application/json": {"schema": {}}},
- },
- "422": {
- "description": "Validation Error",
- "content": {
- "application/json": {
- "schema": {
- "$ref": "#/components/schemas/HTTPValidationError"
- }
- }
- },
- },
- },
- },
- "post": {
- "summary": "Create Item",
- "operationId": "create_item_items__post",
- "requestBody": {
- "required": True,
- "content": {
- "application/json": {
- "schema": {
- "title": "Item",
- "examples": [
- {
- "name": "Foo",
- "price": 35.4,
- "description": "The Foo item",
- }
- ],
- "allOf": [
- {"$ref": "#/components/schemas/Item"}
- ],
- }
- }
- },
- },
- "responses": {
- "200": {
- "description": "Successful Response",
- "content": {"application/json": {"schema": {}}},
- },
- "422": {
- "description": "Validation Error",
- "content": {
- "application/json": {
- "schema": {
- "$ref": "#/components/schemas/HTTPValidationError"
- }
- }
- },
- },
- },
- },
- },
- "/users/": {
- "get": {
- "summary": "Get User With Header",
- "operationId": "get_user_with_header_users__get",
- "parameters": [
- {
- "name": "x-custom",
- "in": "header",
- "required": False,
- "schema": {"title": "X-Custom", "type": "string"},
- },
- {
- "name": "x-token",
- "in": "header",
- "required": False,
- "schema": {"title": "X-Token", "type": "string"},
- },
- ],
- "responses": {
- "200": {
- "description": "Successful Response",
- "content": {"application/json": {"schema": {}}},
- },
- "422": {
- "description": "Validation Error",
- "content": {
- "application/json": {
- "schema": {
- "$ref": "#/components/schemas/HTTPValidationError"
- }
- }
- },
- },
- },
- }
- },
- "/cookies/": {
- "get": {
- "summary": "Get Cookies",
- "operationId": "get_cookies_cookies__get",
- "parameters": [
- {
- "name": "session_id",
- "in": "cookie",
- "required": False,
- "schema": {"title": "Session Id", "type": "string"},
- },
- {
- "name": "tracking_id",
- "in": "cookie",
- "required": False,
- "schema": {
- "title": "Tracking Id",
- "minLength": 10,
- "type": "string",
- },
- },
- ],
- "responses": {
- "200": {
- "description": "Successful Response",
- "content": {"application/json": {"schema": {}}},
- },
- "422": {
- "description": "Validation Error",
- "content": {
- "application/json": {
- "schema": {
- "$ref": "#/components/schemas/HTTPValidationError"
- }
- }
- },
- },
- },
- }
- },
- "/items-embed/": {
- "post": {
- "summary": "Create Item Embed",
- "operationId": "create_item_embed_items_embed__post",
- "requestBody": {
- "content": {
- "application/json": {
- "schema": pydantic_snapshot(
- v1=snapshot(
- {
- "$ref": "#/components/schemas/Body_create_item_embed_items_embed__post"
- }
- ),
- v2=snapshot(
- {
- "allOf": [
- {
- "$ref": "#/components/schemas/Body_create_item_embed_items_embed__post"
- }
- ],
- "title": "Body",
- }
- ),
- ),
- }
- },
- "required": True,
- },
- "responses": {
- "200": {
- "description": "Successful Response",
- "content": {"application/json": {"schema": {}}},
- },
- "422": {
- "description": "Validation Error",
- "content": {
- "application/json": {
- "schema": {
- "$ref": "#/components/schemas/HTTPValidationError"
- }
- }
- },
- },
- },
- }
- },
- "/form-data/": {
- "post": {
- "summary": "Submit Form",
- "operationId": "submit_form_form_data__post",
- "requestBody": {
- "content": {
- "application/x-www-form-urlencoded": {
- "schema": pydantic_snapshot(
- v1=snapshot(
- {
- "$ref": "#/components/schemas/Body_submit_form_form_data__post"
- }
- ),
- v2=snapshot(
- {
- "allOf": [
- {
- "$ref": "#/components/schemas/Body_submit_form_form_data__post"
- }
- ],
- "title": "Body",
- }
- ),
- ),
- }
- },
- "required": True,
- },
- "responses": {
- "200": {
- "description": "Successful Response",
- "content": {"application/json": {"schema": {}}},
- },
- "422": {
- "description": "Validation Error",
- "content": {
- "application/json": {
- "schema": {
- "$ref": "#/components/schemas/HTTPValidationError"
- }
- }
- },
- },
- },
- }
- },
- "/upload/": {
- "post": {
- "summary": "Upload File",
- "operationId": "upload_file_upload__post",
- "requestBody": {
- "content": {
- "multipart/form-data": {
- "schema": pydantic_snapshot(
- v1=snapshot(
- {
- "$ref": "#/components/schemas/Body_upload_file_upload__post"
- }
- ),
- v2=snapshot(
- {
- "allOf": [
- {
- "$ref": "#/components/schemas/Body_upload_file_upload__post"
- }
- ],
- "title": "Body",
- }
- ),
- ),
- }
- },
- "required": True,
- },
- "responses": {
- "200": {
- "description": "Successful Response",
- "content": {"application/json": {"schema": {}}},
- },
- "422": {
- "description": "Validation Error",
- "content": {
- "application/json": {
- "schema": {
- "$ref": "#/components/schemas/HTTPValidationError"
- }
- }
- },
- },
- },
- }
- },
- "/upload-multiple/": {
- "post": {
- "summary": "Upload Multiple Files",
- "operationId": "upload_multiple_files_upload_multiple__post",
- "requestBody": {
- "content": {
- "multipart/form-data": {
- "schema": pydantic_snapshot(
- v1=snapshot(
- {
- "$ref": "#/components/schemas/Body_upload_multiple_files_upload_multiple__post"
- }
- ),
- v2=snapshot(
- {
- "allOf": [
- {
- "$ref": "#/components/schemas/Body_upload_multiple_files_upload_multiple__post"
- }
- ],
- "title": "Body",
- }
- ),
- ),
- }
- },
- "required": True,
- },
- "responses": {
- "200": {
- "description": "Successful Response",
- "content": {"application/json": {"schema": {}}},
- },
- "422": {
- "description": "Validation Error",
- "content": {
- "application/json": {
- "schema": {
- "$ref": "#/components/schemas/HTTPValidationError"
- }
- }
- },
- },
- },
- }
- },
- },
- "components": {
- "schemas": {
- "Body_create_item_embed_items_embed__post": {
- "properties": pydantic_snapshot(
- v1=snapshot(
- {"item": {"$ref": "#/components/schemas/Item"}}
- ),
- v2=snapshot(
- {
- "item": {
- "allOf": [
- {"$ref": "#/components/schemas/Item"}
- ],
- "title": "Item",
- }
- }
- ),
- ),
- "type": "object",
- "required": ["item"],
- "title": "Body_create_item_embed_items_embed__post",
- },
- "Body_submit_form_form_data__post": {
- "properties": {
- "username": {
- "type": "string",
- "maxLength": 50,
- "minLength": 3,
- "title": "Username",
- },
- "password": {
- "type": "string",
- "minLength": 8,
- "title": "Password",
- },
- "email": {"type": "string", "title": "Email"},
- },
- "type": "object",
- "required": ["username", "password"],
- "title": "Body_submit_form_form_data__post",
- },
- "Body_update_item_items__item_id__put": {
- "properties": {
- "item": pydantic_snapshot(
- v1=snapshot({"$ref": "#/components/schemas/Item"}),
- v2=snapshot(
- {
- "allOf": [
- {"$ref": "#/components/schemas/Item"}
- ],
- "title": "Item",
- }
- ),
- ),
- "importance": {
- "type": "integer",
- "maximum": 10.0,
- "exclusiveMinimum": 0.0,
- "title": "Importance",
- },
- },
- "type": "object",
- "required": ["item", "importance"],
- "title": "Body_update_item_items__item_id__put",
- },
- "Body_upload_file_upload__post": {
- "properties": {
- "file": {
- "type": "string",
- "format": "binary",
- "title": "File",
- },
- "description": {"type": "string", "title": "Description"},
- },
- "type": "object",
- "required": ["file"],
- "title": "Body_upload_file_upload__post",
- },
- "Body_upload_multiple_files_upload_multiple__post": {
- "properties": {
- "files": {
- "items": {"type": "string", "format": "binary"},
- "type": "array",
- "title": "Files",
- },
- "note": {"type": "string", "title": "Note", "default": ""},
- },
- "type": "object",
- "required": ["files"],
- "title": "Body_upload_multiple_files_upload_multiple__post",
- },
- "HTTPValidationError": {
- "properties": {
- "detail": {
- "items": {
- "$ref": "#/components/schemas/ValidationError"
- },
- "type": "array",
- "title": "Detail",
- }
- },
- "type": "object",
- "title": "HTTPValidationError",
- },
- "Item": {
- "properties": {
- "name": {"type": "string", "title": "Name"},
- "price": {"type": "number", "title": "Price"},
- "description": {"type": "string", "title": "Description"},
- },
- "type": "object",
- "required": ["name", "price"],
- "title": "Item",
- },
- "ValidationError": {
- "properties": {
- "loc": {
- "items": {
- "anyOf": [{"type": "string"}, {"type": "integer"}]
- },
- "type": "array",
- "title": "Location",
- },
- "msg": {"type": "string", "title": "Message"},
- "type": {"type": "string", "title": "Error Type"},
- },
- "type": "object",
- "required": ["loc", "msg", "type"],
- "title": "ValidationError",
- },
- }
- },
- }
- )
diff --git a/tests/test_computed_fields.py b/tests/test_computed_fields.py
index f2e42999b3..e7f969f7cf 100644
--- a/tests/test_computed_fields.py
+++ b/tests/test_computed_fields.py
@@ -2,8 +2,6 @@ import pytest
from fastapi import FastAPI
from fastapi.testclient import TestClient
-from .utils import needs_pydanticv2
-
@pytest.fixture(name="client")
def get_client(request):
@@ -35,7 +33,6 @@ def get_client(request):
@pytest.mark.parametrize("client", [True, False], indirect=True)
@pytest.mark.parametrize("path", ["/", "/responses"])
-@needs_pydanticv2
def test_get(client: TestClient, path: str):
response = client.get(path)
assert response.status_code == 200, response.text
@@ -43,7 +40,6 @@ def test_get(client: TestClient, path: str):
@pytest.mark.parametrize("client", [True, False], indirect=True)
-@needs_pydanticv2
def test_openapi_schema(client: TestClient):
response = client.get("/openapi.json")
assert response.status_code == 200, response.text
diff --git a/tests/test_custom_schema_fields.py b/tests/test_custom_schema_fields.py
index d890291b19..60b795e9ba 100644
--- a/tests/test_custom_schema_fields.py
+++ b/tests/test_custom_schema_fields.py
@@ -1,13 +1,8 @@
-from typing import Optional
+from typing import Annotated, Optional
from fastapi import FastAPI
-from fastapi._compat import PYDANTIC_V2
from fastapi.testclient import TestClient
-from pydantic import BaseModel
-from typing_extensions import Annotated
-
-if PYDANTIC_V2:
- from pydantic import WithJsonSchema
+from pydantic import BaseModel, WithJsonSchema
app = FastAPI()
@@ -15,23 +10,15 @@ app = FastAPI()
class Item(BaseModel):
name: str
- if PYDANTIC_V2:
- description: Annotated[
- Optional[str], WithJsonSchema({"type": ["string", "null"]})
- ] = None
+ description: Annotated[
+ Optional[str], WithJsonSchema({"type": ["string", "null"]})
+ ] = None
- model_config = {
- "json_schema_extra": {
- "x-something-internal": {"level": 4},
- }
+ model_config = {
+ "json_schema_extra": {
+ "x-something-internal": {"level": 4},
}
- else:
- description: Optional[str] = None # type: ignore[no-redef]
-
- class Config:
- schema_extra = {
- "x-something-internal": {"level": 4},
- }
+ }
@app.get("/foo", response_model=Item)
@@ -56,7 +43,7 @@ item_schema = {
},
"description": {
"title": "Description",
- "type": ["string", "null"] if PYDANTIC_V2 else "string",
+ "type": ["string", "null"],
},
},
}
diff --git a/tests/test_datastructures.py b/tests/test_datastructures.py
index 7e57d525ce..29a70cae0c 100644
--- a/tests/test_datastructures.py
+++ b/tests/test_datastructures.py
@@ -1,6 +1,5 @@
import io
from pathlib import Path
-from typing import List
import pytest
from fastapi import FastAPI, UploadFile
@@ -8,12 +7,6 @@ from fastapi.datastructures import Default
from fastapi.testclient import TestClient
-# TODO: remove when deprecating Pydantic v1
-def test_upload_file_invalid():
- with pytest.raises(ValueError):
- UploadFile.validate("not a Starlette UploadFile")
-
-
def test_upload_file_invalid_pydantic_v2():
with pytest.raises(ValueError):
UploadFile._validate("not a Starlette UploadFile", {})
@@ -38,7 +31,7 @@ def test_upload_file_is_closed(tmp_path: Path):
path.write_bytes(b"")
app = FastAPI()
- testing_file_store: List[UploadFile] = []
+ testing_file_store: list[UploadFile] = []
@app.post("/uploadfile/")
def create_upload_file(file: UploadFile):
diff --git a/tests/test_datetime_custom_encoder.py b/tests/test_datetime_custom_encoder.py
index 3aa77c0b1d..f154ede029 100644
--- a/tests/test_datetime_custom_encoder.py
+++ b/tests/test_datetime_custom_encoder.py
@@ -4,10 +4,7 @@ from fastapi import FastAPI
from fastapi.testclient import TestClient
from pydantic import BaseModel
-from .utils import needs_pydanticv1, needs_pydanticv2
-
-@needs_pydanticv2
def test_pydanticv2():
from pydantic import field_serializer
@@ -29,29 +26,3 @@ def test_pydanticv2():
with client:
response = client.get("/model")
assert response.json() == {"dt_field": "2019-01-01T08:00:00+00:00"}
-
-
-# TODO: remove when deprecating Pydantic v1
-@needs_pydanticv1
-def test_pydanticv1():
- class ModelWithDatetimeField(BaseModel):
- dt_field: datetime
-
- class Config:
- json_encoders = {
- datetime: lambda dt: dt.replace(
- microsecond=0, tzinfo=timezone.utc
- ).isoformat()
- }
-
- app = FastAPI()
- model = ModelWithDatetimeField(dt_field=datetime(2019, 1, 1, 8))
-
- @app.get("/model", response_model=ModelWithDatetimeField)
- def get_model():
- return model
-
- client = TestClient(app)
- with client:
- response = client.get("/model")
- assert response.json() == {"dt_field": "2019-01-01T08:00:00+00:00"}
diff --git a/tests/test_dependency_after_yield_raise.py b/tests/test_dependency_after_yield_raise.py
index b560dc36f9..b561402772 100644
--- a/tests/test_dependency_after_yield_raise.py
+++ b/tests/test_dependency_after_yield_raise.py
@@ -1,9 +1,8 @@
-from typing import Any
+from typing import Annotated, Any
import pytest
from fastapi import Depends, FastAPI, HTTPException
from fastapi.testclient import TestClient
-from typing_extensions import Annotated
class CustomError(Exception):
diff --git a/tests/test_dependency_after_yield_streaming.py b/tests/test_dependency_after_yield_streaming.py
index 7e1c8822b8..cbadff8f87 100644
--- a/tests/test_dependency_after_yield_streaming.py
+++ b/tests/test_dependency_after_yield_streaming.py
@@ -1,11 +1,11 @@
+from collections.abc import Generator
from contextlib import contextmanager
-from typing import Any, Generator
+from typing import Annotated, Any
import pytest
from fastapi import Depends, FastAPI
from fastapi.responses import StreamingResponse
from fastapi.testclient import TestClient
-from typing_extensions import Annotated
class Session:
diff --git a/tests/test_dependency_after_yield_websockets.py b/tests/test_dependency_after_yield_websockets.py
index 7c323c338b..0fdf697b6c 100644
--- a/tests/test_dependency_after_yield_websockets.py
+++ b/tests/test_dependency_after_yield_websockets.py
@@ -1,10 +1,10 @@
+from collections.abc import Generator
from contextlib import contextmanager
-from typing import Any, Generator
+from typing import Annotated, Any
import pytest
from fastapi import Depends, FastAPI, WebSocket
from fastapi.testclient import TestClient
-from typing_extensions import Annotated
class Session:
diff --git a/tests/test_dependency_class.py b/tests/test_dependency_class.py
index 75241b467a..95ff3e9d95 100644
--- a/tests/test_dependency_class.py
+++ b/tests/test_dependency_class.py
@@ -1,4 +1,4 @@
-from typing import AsyncGenerator, Generator
+from collections.abc import AsyncGenerator, Generator
import pytest
from fastapi import Depends, FastAPI
diff --git a/tests/test_dependency_contextmanager.py b/tests/test_dependency_contextmanager.py
index 02c10458cb..5a89934741 100644
--- a/tests/test_dependency_contextmanager.py
+++ b/tests/test_dependency_contextmanager.py
@@ -1,5 +1,4 @@
import json
-from typing import Dict
import pytest
from fastapi import BackgroundTasks, Depends, FastAPI
@@ -37,19 +36,19 @@ class OtherDependencyError(Exception):
pass
-async def asyncgen_state(state: Dict[str, str] = Depends(get_state)):
+async def asyncgen_state(state: dict[str, str] = Depends(get_state)):
state["/async"] = "asyncgen started"
yield state["/async"]
state["/async"] = "asyncgen completed"
-def generator_state(state: Dict[str, str] = Depends(get_state)):
+def generator_state(state: dict[str, str] = Depends(get_state)):
state["/sync"] = "generator started"
yield state["/sync"]
state["/sync"] = "generator completed"
-async def asyncgen_state_try(state: Dict[str, str] = Depends(get_state)):
+async def asyncgen_state_try(state: dict[str, str] = Depends(get_state)):
state["/async_raise"] = "asyncgen raise started"
try:
yield state["/async_raise"]
@@ -60,7 +59,7 @@ async def asyncgen_state_try(state: Dict[str, str] = Depends(get_state)):
state["/async_raise"] = "asyncgen raise finalized"
-def generator_state_try(state: Dict[str, str] = Depends(get_state)):
+def generator_state_try(state: dict[str, str] = Depends(get_state)):
state["/sync_raise"] = "generator raise started"
try:
yield state["/sync_raise"]
diff --git a/tests/test_dependency_contextvars.py b/tests/test_dependency_contextvars.py
index 076802df84..0c2e5594b6 100644
--- a/tests/test_dependency_contextvars.py
+++ b/tests/test_dependency_contextvars.py
@@ -1,10 +1,11 @@
+from collections.abc import Awaitable
from contextvars import ContextVar
-from typing import Any, Awaitable, Callable, Dict, Optional
+from typing import Any, Callable, Optional
from fastapi import Depends, FastAPI, Request, Response
from fastapi.testclient import TestClient
-legacy_request_state_context_var: ContextVar[Optional[Dict[str, Any]]] = ContextVar(
+legacy_request_state_context_var: ContextVar[Optional[dict[str, Any]]] = ContextVar(
"legacy_request_state_context_var", default=None
)
diff --git a/tests/test_dependency_duplicates.py b/tests/test_dependency_duplicates.py
index 8e8d07c2d6..a8658e03bb 100644
--- a/tests/test_dependency_duplicates.py
+++ b/tests/test_dependency_duplicates.py
@@ -1,6 +1,3 @@
-from typing import List
-
-from dirty_equals import IsDict
from fastapi import Depends, FastAPI
from fastapi.testclient import TestClient
from pydantic import BaseModel
@@ -40,7 +37,7 @@ async def no_duplicates(item: Item, item2: Item = Depends(dependency)):
@app.post("/with-duplicates-sub")
async def no_duplicates_sub(
- item: Item, sub_items: List[Item] = Depends(sub_duplicate_dependency)
+ item: Item, sub_items: list[Item] = Depends(sub_duplicate_dependency)
):
return [item, sub_items]
@@ -48,29 +45,16 @@ async def no_duplicates_sub(
def test_no_duplicates_invalid():
response = client.post("/no-duplicates", json={"item": {"data": "myitem"}})
assert response.status_code == 422, response.text
- assert response.json() == IsDict(
- {
- "detail": [
- {
- "type": "missing",
- "loc": ["body", "item2"],
- "msg": "Field required",
- "input": None,
- }
- ]
- }
- ) | IsDict(
- # TODO: remove when deprecating Pydantic v1
- {
- "detail": [
- {
- "loc": ["body", "item2"],
- "msg": "field required",
- "type": "value_error.missing",
- }
- ]
- }
- )
+ assert response.json() == {
+ "detail": [
+ {
+ "type": "missing",
+ "loc": ["body", "item2"],
+ "msg": "Field required",
+ "input": None,
+ }
+ ]
+ }
def test_no_duplicates():
diff --git a/tests/test_dependency_overrides.py b/tests/test_dependency_overrides.py
index 154937fa0b..e25db624d8 100644
--- a/tests/test_dependency_overrides.py
+++ b/tests/test_dependency_overrides.py
@@ -1,7 +1,6 @@
from typing import Optional
import pytest
-from dirty_equals import IsDict
from fastapi import APIRouter, Depends, FastAPI
from fastapi.testclient import TestClient
@@ -54,29 +53,16 @@ async def overrider_dependency_with_sub(msg: dict = Depends(overrider_sub_depend
def test_main_depends():
response = client.get("/main-depends/")
assert response.status_code == 422
- assert response.json() == IsDict(
- {
- "detail": [
- {
- "type": "missing",
- "loc": ["query", "q"],
- "msg": "Field required",
- "input": None,
- }
- ]
- }
- ) | IsDict(
- # TODO: remove when deprecating Pydantic v1
- {
- "detail": [
- {
- "loc": ["query", "q"],
- "msg": "field required",
- "type": "value_error.missing",
- }
- ]
- }
- )
+ assert response.json() == {
+ "detail": [
+ {
+ "type": "missing",
+ "loc": ["query", "q"],
+ "msg": "Field required",
+ "input": None,
+ }
+ ]
+ }
def test_main_depends_q_foo():
@@ -100,29 +86,16 @@ def test_main_depends_q_foo_skip_100_limit_200():
def test_decorator_depends():
response = client.get("/decorator-depends/")
assert response.status_code == 422
- assert response.json() == IsDict(
- {
- "detail": [
- {
- "type": "missing",
- "loc": ["query", "q"],
- "msg": "Field required",
- "input": None,
- }
- ]
- }
- ) | IsDict(
- # TODO: remove when deprecating Pydantic v1
- {
- "detail": [
- {
- "loc": ["query", "q"],
- "msg": "field required",
- "type": "value_error.missing",
- }
- ]
- }
- )
+ assert response.json() == {
+ "detail": [
+ {
+ "type": "missing",
+ "loc": ["query", "q"],
+ "msg": "Field required",
+ "input": None,
+ }
+ ]
+ }
def test_decorator_depends_q_foo():
@@ -140,29 +113,16 @@ def test_decorator_depends_q_foo_skip_100_limit_200():
def test_router_depends():
response = client.get("/router-depends/")
assert response.status_code == 422
- assert response.json() == IsDict(
- {
- "detail": [
- {
- "type": "missing",
- "loc": ["query", "q"],
- "msg": "Field required",
- "input": None,
- }
- ]
- }
- ) | IsDict(
- # TODO: remove when deprecating Pydantic v1
- {
- "detail": [
- {
- "loc": ["query", "q"],
- "msg": "field required",
- "type": "value_error.missing",
- }
- ]
- }
- )
+ assert response.json() == {
+ "detail": [
+ {
+ "type": "missing",
+ "loc": ["query", "q"],
+ "msg": "Field required",
+ "input": None,
+ }
+ ]
+ }
def test_router_depends_q_foo():
@@ -186,29 +146,16 @@ def test_router_depends_q_foo_skip_100_limit_200():
def test_router_decorator_depends():
response = client.get("/router-decorator-depends/")
assert response.status_code == 422
- assert response.json() == IsDict(
- {
- "detail": [
- {
- "type": "missing",
- "loc": ["query", "q"],
- "msg": "Field required",
- "input": None,
- }
- ]
- }
- ) | IsDict(
- # TODO remove when deprecating Pydantic v1
- {
- "detail": [
- {
- "loc": ["query", "q"],
- "msg": "field required",
- "type": "value_error.missing",
- }
- ]
- }
- )
+ assert response.json() == {
+ "detail": [
+ {
+ "type": "missing",
+ "loc": ["query", "q"],
+ "msg": "Field required",
+ "input": None,
+ }
+ ]
+ }
def test_router_decorator_depends_q_foo():
@@ -272,29 +219,17 @@ def test_override_with_sub_main_depends():
app.dependency_overrides[common_parameters] = overrider_dependency_with_sub
response = client.get("/main-depends/")
assert response.status_code == 422
- assert response.json() == IsDict(
- {
- "detail": [
- {
- "type": "missing",
- "loc": ["query", "k"],
- "msg": "Field required",
- "input": None,
- }
- ]
- }
- ) | IsDict(
- # TODO: remove when deprecating Pydantic v1
- {
- "detail": [
- {
- "loc": ["query", "k"],
- "msg": "field required",
- "type": "value_error.missing",
- }
- ]
- }
- )
+ assert response.json() == {
+ "detail": [
+ {
+ "type": "missing",
+ "loc": ["query", "k"],
+ "msg": "Field required",
+ "input": None,
+ }
+ ]
+ }
+
app.dependency_overrides = {}
@@ -302,29 +237,17 @@ def test_override_with_sub__main_depends_q_foo():
app.dependency_overrides[common_parameters] = overrider_dependency_with_sub
response = client.get("/main-depends/?q=foo")
assert response.status_code == 422
- assert response.json() == IsDict(
- {
- "detail": [
- {
- "type": "missing",
- "loc": ["query", "k"],
- "msg": "Field required",
- "input": None,
- }
- ]
- }
- ) | IsDict(
- # TODO: remove when deprecating Pydantic v1
- {
- "detail": [
- {
- "loc": ["query", "k"],
- "msg": "field required",
- "type": "value_error.missing",
- }
- ]
- }
- )
+ assert response.json() == {
+ "detail": [
+ {
+ "type": "missing",
+ "loc": ["query", "k"],
+ "msg": "Field required",
+ "input": None,
+ }
+ ]
+ }
+
app.dependency_overrides = {}
@@ -340,29 +263,17 @@ def test_override_with_sub_decorator_depends():
app.dependency_overrides[common_parameters] = overrider_dependency_with_sub
response = client.get("/decorator-depends/")
assert response.status_code == 422
- assert response.json() == IsDict(
- {
- "detail": [
- {
- "type": "missing",
- "loc": ["query", "k"],
- "msg": "Field required",
- "input": None,
- }
- ]
- }
- ) | IsDict(
- # TODO: remove when deprecating Pydantic v1
- {
- "detail": [
- {
- "loc": ["query", "k"],
- "msg": "field required",
- "type": "value_error.missing",
- }
- ]
- }
- )
+ assert response.json() == {
+ "detail": [
+ {
+ "type": "missing",
+ "loc": ["query", "k"],
+ "msg": "Field required",
+ "input": None,
+ }
+ ]
+ }
+
app.dependency_overrides = {}
@@ -370,29 +281,17 @@ def test_override_with_sub_decorator_depends_q_foo():
app.dependency_overrides[common_parameters] = overrider_dependency_with_sub
response = client.get("/decorator-depends/?q=foo")
assert response.status_code == 422
- assert response.json() == IsDict(
- {
- "detail": [
- {
- "type": "missing",
- "loc": ["query", "k"],
- "msg": "Field required",
- "input": None,
- }
- ]
- }
- ) | IsDict(
- # TODO: remove when deprecating Pydantic v1
- {
- "detail": [
- {
- "loc": ["query", "k"],
- "msg": "field required",
- "type": "value_error.missing",
- }
- ]
- }
- )
+ assert response.json() == {
+ "detail": [
+ {
+ "type": "missing",
+ "loc": ["query", "k"],
+ "msg": "Field required",
+ "input": None,
+ }
+ ]
+ }
+
app.dependency_overrides = {}
@@ -408,29 +307,17 @@ def test_override_with_sub_router_depends():
app.dependency_overrides[common_parameters] = overrider_dependency_with_sub
response = client.get("/router-depends/")
assert response.status_code == 422
- assert response.json() == IsDict(
- {
- "detail": [
- {
- "type": "missing",
- "loc": ["query", "k"],
- "msg": "Field required",
- "input": None,
- }
- ]
- }
- ) | IsDict(
- # TODO remove when deprecating Pydantic v1
- {
- "detail": [
- {
- "loc": ["query", "k"],
- "msg": "field required",
- "type": "value_error.missing",
- }
- ]
- }
- )
+ assert response.json() == {
+ "detail": [
+ {
+ "type": "missing",
+ "loc": ["query", "k"],
+ "msg": "Field required",
+ "input": None,
+ }
+ ]
+ }
+
app.dependency_overrides = {}
@@ -438,29 +325,17 @@ def test_override_with_sub_router_depends_q_foo():
app.dependency_overrides[common_parameters] = overrider_dependency_with_sub
response = client.get("/router-depends/?q=foo")
assert response.status_code == 422
- assert response.json() == IsDict(
- {
- "detail": [
- {
- "type": "missing",
- "loc": ["query", "k"],
- "msg": "Field required",
- "input": None,
- }
- ]
- }
- ) | IsDict(
- # TODO remove when deprecating Pydantic v1
- {
- "detail": [
- {
- "loc": ["query", "k"],
- "msg": "field required",
- "type": "value_error.missing",
- }
- ]
- }
- )
+ assert response.json() == {
+ "detail": [
+ {
+ "type": "missing",
+ "loc": ["query", "k"],
+ "msg": "Field required",
+ "input": None,
+ }
+ ]
+ }
+
app.dependency_overrides = {}
@@ -476,29 +351,17 @@ def test_override_with_sub_router_decorator_depends():
app.dependency_overrides[common_parameters] = overrider_dependency_with_sub
response = client.get("/router-decorator-depends/")
assert response.status_code == 422
- assert response.json() == IsDict(
- {
- "detail": [
- {
- "type": "missing",
- "loc": ["query", "k"],
- "msg": "Field required",
- "input": None,
- }
- ]
- }
- ) | IsDict(
- # TODO remove when deprecating Pydantic v1
- {
- "detail": [
- {
- "loc": ["query", "k"],
- "msg": "field required",
- "type": "value_error.missing",
- }
- ]
- }
- )
+ assert response.json() == {
+ "detail": [
+ {
+ "type": "missing",
+ "loc": ["query", "k"],
+ "msg": "Field required",
+ "input": None,
+ }
+ ]
+ }
+
app.dependency_overrides = {}
@@ -506,29 +369,17 @@ def test_override_with_sub_router_decorator_depends_q_foo():
app.dependency_overrides[common_parameters] = overrider_dependency_with_sub
response = client.get("/router-decorator-depends/?q=foo")
assert response.status_code == 422
- assert response.json() == IsDict(
- {
- "detail": [
- {
- "type": "missing",
- "loc": ["query", "k"],
- "msg": "Field required",
- "input": None,
- }
- ]
- }
- ) | IsDict(
- # TODO remove when deprecating Pydantic v1
- {
- "detail": [
- {
- "loc": ["query", "k"],
- "msg": "field required",
- "type": "value_error.missing",
- }
- ]
- }
- )
+ assert response.json() == {
+ "detail": [
+ {
+ "type": "missing",
+ "loc": ["query", "k"],
+ "msg": "Field required",
+ "input": None,
+ }
+ ]
+ }
+
app.dependency_overrides = {}
diff --git a/tests/test_dependency_paramless.py b/tests/test_dependency_paramless.py
index 9c3cc3878b..1774196fe4 100644
--- a/tests/test_dependency_paramless.py
+++ b/tests/test_dependency_paramless.py
@@ -1,4 +1,4 @@
-from typing import Union
+from typing import Annotated, Union
from fastapi import FastAPI, HTTPException, Security
from fastapi.security import (
@@ -6,7 +6,6 @@ from fastapi.security import (
SecurityScopes,
)
from fastapi.testclient import TestClient
-from typing_extensions import Annotated
app = FastAPI()
diff --git a/tests/test_dependency_partial.py b/tests/test_dependency_partial.py
index 61a76236f8..05a3cffa5a 100644
--- a/tests/test_dependency_partial.py
+++ b/tests/test_dependency_partial.py
@@ -1,10 +1,10 @@
+from collections.abc import AsyncGenerator, Generator
from functools import partial
-from typing import AsyncGenerator, Generator
+from typing import Annotated
import pytest
from fastapi import Depends, FastAPI
from fastapi.testclient import TestClient
-from typing_extensions import Annotated
app = FastAPI()
diff --git a/tests/test_dependency_security_overrides.py b/tests/test_dependency_security_overrides.py
index b89d82db43..14b65c7770 100644
--- a/tests/test_dependency_security_overrides.py
+++ b/tests/test_dependency_security_overrides.py
@@ -1,5 +1,3 @@
-from typing import List, Tuple
-
from fastapi import Depends, FastAPI, Security
from fastapi.security import SecurityScopes
from fastapi.testclient import TestClient
@@ -25,8 +23,8 @@ def get_data_override():
@app.get("/user")
def read_user(
- user_data: Tuple[str, List[str]] = Security(get_user, scopes=["foo", "bar"]),
- data: List[int] = Depends(get_data),
+ user_data: tuple[str, list[str]] = Security(get_user, scopes=["foo", "bar"]),
+ data: list[int] = Depends(get_data),
):
return {"user": user_data[0], "scopes": user_data[1], "data": data}
diff --git a/tests/test_dependency_wrapped.py b/tests/test_dependency_wrapped.py
index 08356712d6..a4044112a2 100644
--- a/tests/test_dependency_wrapped.py
+++ b/tests/test_dependency_wrapped.py
@@ -1,7 +1,7 @@
import inspect
import sys
+from collections.abc import AsyncGenerator, Generator
from functools import wraps
-from typing import AsyncGenerator, Generator
import pytest
from fastapi import Depends, FastAPI
diff --git a/tests/test_dependency_yield_scope.py b/tests/test_dependency_yield_scope.py
index d87164fe80..f3fc3cc94f 100644
--- a/tests/test_dependency_yield_scope.py
+++ b/tests/test_dependency_yield_scope.py
@@ -1,12 +1,11 @@
import json
-from typing import Any, Tuple
+from typing import Annotated, Any
import pytest
from fastapi import APIRouter, Depends, FastAPI, HTTPException
from fastapi.exceptions import FastAPIError
from fastapi.responses import StreamingResponse
from fastapi.testclient import TestClient
-from typing_extensions import Annotated
class Session:
@@ -43,7 +42,7 @@ def get_named_session(session: SessionRequestDep, session_b: SessionDefaultDep)
named_session.open = False
-NamedSessionsDep = Annotated[Tuple[NamedSession, Session], Depends(get_named_session)]
+NamedSessionsDep = Annotated[tuple[NamedSession, Session], Depends(get_named_session)]
def get_named_func_session(session: SessionFuncDep) -> Any:
@@ -58,14 +57,14 @@ def get_named_regular_func_session(session: SessionFuncDep) -> Any:
BrokenSessionsDep = Annotated[
- Tuple[NamedSession, Session], Depends(get_named_func_session)
+ tuple[NamedSession, Session], Depends(get_named_func_session)
]
NamedSessionsFuncDep = Annotated[
- Tuple[NamedSession, Session], Depends(get_named_func_session, scope="function")
+ tuple[NamedSession, Session], Depends(get_named_func_session, scope="function")
]
RegularSessionsDep = Annotated[
- Tuple[NamedSession, Session], Depends(get_named_regular_func_session)
+ tuple[NamedSession, Session], Depends(get_named_regular_func_session)
]
app = FastAPI()
diff --git a/tests/test_dependency_yield_scope_websockets.py b/tests/test_dependency_yield_scope_websockets.py
index 52a30ae7a7..dbe35e576c 100644
--- a/tests/test_dependency_yield_scope_websockets.py
+++ b/tests/test_dependency_yield_scope_websockets.py
@@ -1,13 +1,12 @@
from contextvars import ContextVar
-from typing import Any, Dict, Tuple
+from typing import Annotated, Any
import pytest
from fastapi import Depends, FastAPI, WebSocket
from fastapi.exceptions import FastAPIError
from fastapi.testclient import TestClient
-from typing_extensions import Annotated
-global_context: ContextVar[Dict[str, Any]] = ContextVar("global_context", default={}) # noqa: B039
+global_context: ContextVar[dict[str, Any]] = ContextVar("global_context", default={}) # noqa: B039
class Session:
@@ -43,7 +42,7 @@ def get_named_session(session: SessionRequestDep, session_b: SessionDefaultDep)
global_state["named_session_closed"] = True
-NamedSessionsDep = Annotated[Tuple[NamedSession, Session], Depends(get_named_session)]
+NamedSessionsDep = Annotated[tuple[NamedSession, Session], Depends(get_named_session)]
def get_named_func_session(session: SessionFuncDep) -> Any:
@@ -60,14 +59,14 @@ def get_named_regular_func_session(session: SessionFuncDep) -> Any:
BrokenSessionsDep = Annotated[
- Tuple[NamedSession, Session], Depends(get_named_func_session)
+ tuple[NamedSession, Session], Depends(get_named_func_session)
]
NamedSessionsFuncDep = Annotated[
- Tuple[NamedSession, Session], Depends(get_named_func_session, scope="function")
+ tuple[NamedSession, Session], Depends(get_named_func_session, scope="function")
]
RegularSessionsDep = Annotated[
- Tuple[NamedSession, Session], Depends(get_named_regular_func_session)
+ tuple[NamedSession, Session], Depends(get_named_regular_func_session)
]
app = FastAPI()
diff --git a/tests/test_extra_routes.py b/tests/test_extra_routes.py
index bd16fe9254..45734ec28a 100644
--- a/tests/test_extra_routes.py
+++ b/tests/test_extra_routes.py
@@ -1,6 +1,5 @@
from typing import Optional
-from dirty_equals import IsDict
from fastapi import FastAPI
from fastapi.responses import JSONResponse
from fastapi.testclient import TestClient
@@ -328,14 +327,10 @@ def test_openapi_schema():
"type": "object",
"properties": {
"name": {"title": "Name", "type": "string"},
- "price": IsDict(
- {
- "title": "Price",
- "anyOf": [{"type": "number"}, {"type": "null"}],
- }
- )
- # TODO: remove when deprecating Pydantic v1
- | IsDict({"title": "Price", "type": "number"}),
+ "price": {
+ "title": "Price",
+ "anyOf": [{"type": "number"}, {"type": "null"}],
+ },
},
},
"ValidationError": {
diff --git a/tests/test_file_and_form_order_issue_9116.py b/tests/test_file_and_form_order_issue_9116.py
index cb9a31d314..75290b60cd 100644
--- a/tests/test_file_and_form_order_issue_9116.py
+++ b/tests/test_file_and_form_order_issue_9116.py
@@ -4,12 +4,11 @@ See https://github.com/tiangolo/fastapi/discussions/9116
"""
from pathlib import Path
-from typing import List
+from typing import Annotated
import pytest
from fastapi import FastAPI, File, Form
from fastapi.testclient import TestClient
-from typing_extensions import Annotated
app = FastAPI()
@@ -32,7 +31,7 @@ def file_after_form(
@app.post("/file_list_before_form")
def file_list_before_form(
- files: Annotated[List[bytes], File()],
+ files: Annotated[list[bytes], File()],
city: Annotated[str, Form()],
):
return {"file_contents": files, "city": city}
@@ -41,7 +40,7 @@ def file_list_before_form(
@app.post("/file_list_after_form")
def file_list_after_form(
city: Annotated[str, Form()],
- files: Annotated[List[bytes], File()],
+ files: Annotated[list[bytes], File()],
):
return {"file_contents": files, "city": city}
diff --git a/tests/test_filter_pydantic_sub_model/app_pv1.py b/tests/test_filter_pydantic_sub_model/app_pv1.py
deleted file mode 100644
index 657e8c5d12..0000000000
--- a/tests/test_filter_pydantic_sub_model/app_pv1.py
+++ /dev/null
@@ -1,35 +0,0 @@
-from typing import Optional
-
-from fastapi import Depends, FastAPI
-from pydantic import BaseModel, validator
-
-app = FastAPI()
-
-
-class ModelB(BaseModel):
- username: str
-
-
-class ModelC(ModelB):
- password: str
-
-
-class ModelA(BaseModel):
- name: str
- description: Optional[str] = None
- model_b: ModelB
-
- @validator("name")
- def lower_username(cls, name: str, values):
- if not name.endswith("A"):
- raise ValueError("name must end in A")
- return name
-
-
-async def get_model_c() -> ModelC:
- return ModelC(username="test-user", password="test-password")
-
-
-@app.get("/model/{name}", response_model=ModelA)
-async def get_model_a(name: str, model_c=Depends(get_model_c)):
- return {"name": name, "description": "model-a-desc", "model_b": model_c}
diff --git a/tests/test_filter_pydantic_sub_model_pv2.py b/tests/test_filter_pydantic_sub_model_pv2.py
index 2e2c26ddcb..fc5876410d 100644
--- a/tests/test_filter_pydantic_sub_model_pv2.py
+++ b/tests/test_filter_pydantic_sub_model_pv2.py
@@ -1,12 +1,11 @@
from typing import Optional
import pytest
-from dirty_equals import HasRepr, IsDict, IsOneOf
+from dirty_equals import HasRepr
from fastapi import Depends, FastAPI
from fastapi.exceptions import ResponseValidationError
from fastapi.testclient import TestClient
-
-from .utils import needs_pydanticv2
+from inline_snapshot import snapshot
@pytest.fixture(name="client")
@@ -25,6 +24,7 @@ def get_client():
name: str
description: Optional[str] = None
foo: ModelB
+ tags: dict[str, str] = {}
@field_validator("name")
def lower_username(cls, name: str, info: ValidationInfo):
@@ -37,13 +37,17 @@ def get_client():
@app.get("/model/{name}", response_model=ModelA)
async def get_model_a(name: str, model_c=Depends(get_model_c)):
- return {"name": name, "description": "model-a-desc", "foo": model_c}
+ return {
+ "name": name,
+ "description": "model-a-desc",
+ "foo": model_c,
+ "tags": {"key1": "value1", "key2": "value2"},
+ }
client = TestClient(app)
return client
-@needs_pydanticv2
def test_filter_sub_model(client: TestClient):
response = client.get("/model/modelA")
assert response.status_code == 200, response.text
@@ -51,134 +55,128 @@ def test_filter_sub_model(client: TestClient):
"name": "modelA",
"description": "model-a-desc",
"foo": {"username": "test-user"},
+ "tags": {"key1": "value1", "key2": "value2"},
}
-@needs_pydanticv2
def test_validator_is_cloned(client: TestClient):
with pytest.raises(ResponseValidationError) as err:
client.get("/model/modelX")
assert err.value.errors() == [
- IsDict(
- {
- "type": "value_error",
- "loc": ("response", "name"),
- "msg": "Value error, name must end in A",
- "input": "modelX",
- "ctx": {"error": HasRepr("ValueError('name must end in A')")},
- }
- )
- | IsDict(
- # TODO remove when deprecating Pydantic v1
- {
- "loc": ("response", "name"),
- "msg": "name must end in A",
- "type": "value_error",
- }
- )
+ {
+ "type": "value_error",
+ "loc": ("response", "name"),
+ "msg": "Value error, name must end in A",
+ "input": "modelX",
+ "ctx": {"error": HasRepr("ValueError('name must end in A')")},
+ }
]
-@needs_pydanticv2
def test_openapi_schema(client: TestClient):
response = client.get("/openapi.json")
assert response.status_code == 200, response.text
- assert response.json() == {
- "openapi": "3.1.0",
- "info": {"title": "FastAPI", "version": "0.1.0"},
- "paths": {
- "/model/{name}": {
- "get": {
- "summary": "Get Model A",
- "operationId": "get_model_a_model__name__get",
- "parameters": [
- {
- "required": True,
- "schema": {"title": "Name", "type": "string"},
- "name": "name",
- "in": "path",
- }
- ],
- "responses": {
- "200": {
- "description": "Successful Response",
- "content": {
- "application/json": {
- "schema": {"$ref": "#/components/schemas/ModelA"}
- }
+ assert response.json() == snapshot(
+ {
+ "openapi": "3.1.0",
+ "info": {"title": "FastAPI", "version": "0.1.0"},
+ "paths": {
+ "/model/{name}": {
+ "get": {
+ "summary": "Get Model A",
+ "operationId": "get_model_a_model__name__get",
+ "parameters": [
+ {
+ "required": True,
+ "schema": {"title": "Name", "type": "string"},
+ "name": "name",
+ "in": "path",
+ }
+ ],
+ "responses": {
+ "200": {
+ "description": "Successful Response",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/ModelA"
+ }
+ }
+ },
+ },
+ "422": {
+ "description": "Validation Error",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/HTTPValidationError"
+ }
+ }
+ },
},
},
- "422": {
- "description": "Validation Error",
- "content": {
- "application/json": {
- "schema": {
- "$ref": "#/components/schemas/HTTPValidationError"
- }
- }
+ }
+ }
+ },
+ "components": {
+ "schemas": {
+ "HTTPValidationError": {
+ "title": "HTTPValidationError",
+ "type": "object",
+ "properties": {
+ "detail": {
+ "title": "Detail",
+ "type": "array",
+ "items": {
+ "$ref": "#/components/schemas/ValidationError"
+ },
+ }
+ },
+ },
+ "ModelA": {
+ "title": "ModelA",
+ "required": ["name", "foo"],
+ "type": "object",
+ "properties": {
+ "name": {"title": "Name", "type": "string"},
+ "description": {
+ "title": "Description",
+ "anyOf": [{"type": "string"}, {"type": "null"}],
},
+ "foo": {"$ref": "#/components/schemas/ModelB"},
+ "tags": {
+ "additionalProperties": {"type": "string"},
+ "type": "object",
+ "title": "Tags",
+ "default": {},
+ },
+ },
+ },
+ "ModelB": {
+ "title": "ModelB",
+ "required": ["username"],
+ "type": "object",
+ "properties": {
+ "username": {"title": "Username", "type": "string"}
+ },
+ },
+ "ValidationError": {
+ "title": "ValidationError",
+ "required": ["loc", "msg", "type"],
+ "type": "object",
+ "properties": {
+ "loc": {
+ "title": "Location",
+ "type": "array",
+ "items": {
+ "anyOf": [{"type": "string"}, {"type": "integer"}]
+ },
+ },
+ "msg": {"title": "Message", "type": "string"},
+ "type": {"title": "Error Type", "type": "string"},
},
},
}
- }
- },
- "components": {
- "schemas": {
- "HTTPValidationError": {
- "title": "HTTPValidationError",
- "type": "object",
- "properties": {
- "detail": {
- "title": "Detail",
- "type": "array",
- "items": {"$ref": "#/components/schemas/ValidationError"},
- }
- },
- },
- "ModelA": {
- "title": "ModelA",
- "required": IsOneOf(
- ["name", "description", "foo"],
- # TODO remove when deprecating Pydantic v1
- ["name", "foo"],
- ),
- "type": "object",
- "properties": {
- "name": {"title": "Name", "type": "string"},
- "description": IsDict(
- {
- "title": "Description",
- "anyOf": [{"type": "string"}, {"type": "null"}],
- }
- )
- |
- # TODO remove when deprecating Pydantic v1
- IsDict({"title": "Description", "type": "string"}),
- "foo": {"$ref": "#/components/schemas/ModelB"},
- },
- },
- "ModelB": {
- "title": "ModelB",
- "required": ["username"],
- "type": "object",
- "properties": {"username": {"title": "Username", "type": "string"}},
- },
- "ValidationError": {
- "title": "ValidationError",
- "required": ["loc", "msg", "type"],
- "type": "object",
- "properties": {
- "loc": {
- "title": "Location",
- "type": "array",
- "items": {
- "anyOf": [{"type": "string"}, {"type": "integer"}]
- },
- },
- "msg": {"title": "Message", "type": "string"},
- "type": {"title": "Error Type", "type": "string"},
- },
- },
- }
- },
- }
+ },
+ }
+ )
diff --git a/tests/test_form_default.py b/tests/test_form_default.py
index 2a12049d1a..0b3eb8f2e2 100644
--- a/tests/test_form_default.py
+++ b/tests/test_form_default.py
@@ -1,8 +1,7 @@
-from typing import Optional
+from typing import Annotated, Optional
from fastapi import FastAPI, File, Form
from starlette.testclient import TestClient
-from typing_extensions import Annotated
app = FastAPI()
diff --git a/tests/test_forms_single_model.py b/tests/test_forms_single_model.py
index 1db63f0214..7d03d29572 100644
--- a/tests/test_forms_single_model.py
+++ b/tests/test_forms_single_model.py
@@ -1,11 +1,8 @@
-from typing import List, Optional
+from typing import Annotated, Optional
-from dirty_equals import IsDict
from fastapi import FastAPI, Form
-from fastapi._compat import PYDANTIC_V2
from fastapi.testclient import TestClient
from pydantic import BaseModel, Field
-from typing_extensions import Annotated
app = FastAPI()
@@ -14,19 +11,14 @@ class FormModel(BaseModel):
username: str
lastname: str
age: Optional[int] = None
- tags: List[str] = ["foo", "bar"]
+ tags: list[str] = ["foo", "bar"]
alias_with: str = Field(alias="with", default="nothing")
class FormModelExtraAllow(BaseModel):
param: str
- if PYDANTIC_V2:
- model_config = {"extra": "allow"}
- else:
-
- class Config:
- extra = "allow"
+ model_config = {"extra": "allow"}
@app.post("/form/")
@@ -86,68 +78,37 @@ def test_invalid_data():
},
)
assert response.status_code == 422, response.text
- assert response.json() == IsDict(
- {
- "detail": [
- {
- "type": "int_parsing",
- "loc": ["body", "age"],
- "msg": "Input should be a valid integer, unable to parse string as an integer",
- "input": "seventy",
- }
- ]
- }
- ) | IsDict(
- # TODO: remove when deprecating Pydantic v1
- {
- "detail": [
- {
- "loc": ["body", "age"],
- "msg": "value is not a valid integer",
- "type": "type_error.integer",
- }
- ]
- }
- )
+ assert response.json() == {
+ "detail": [
+ {
+ "type": "int_parsing",
+ "loc": ["body", "age"],
+ "msg": "Input should be a valid integer, unable to parse string as an integer",
+ "input": "seventy",
+ }
+ ]
+ }
def test_no_data():
response = client.post("/form/")
assert response.status_code == 422, response.text
- assert response.json() == IsDict(
- {
- "detail": [
- {
- "type": "missing",
- "loc": ["body", "username"],
- "msg": "Field required",
- "input": {"tags": ["foo", "bar"], "with": "nothing"},
- },
- {
- "type": "missing",
- "loc": ["body", "lastname"],
- "msg": "Field required",
- "input": {"tags": ["foo", "bar"], "with": "nothing"},
- },
- ]
- }
- ) | IsDict(
- # TODO: remove when deprecating Pydantic v1
- {
- "detail": [
- {
- "loc": ["body", "username"],
- "msg": "field required",
- "type": "value_error.missing",
- },
- {
- "loc": ["body", "lastname"],
- "msg": "field required",
- "type": "value_error.missing",
- },
- ]
- }
- )
+ assert response.json() == {
+ "detail": [
+ {
+ "type": "missing",
+ "loc": ["body", "username"],
+ "msg": "Field required",
+ "input": {"tags": ["foo", "bar"], "with": "nothing"},
+ },
+ {
+ "type": "missing",
+ "loc": ["body", "lastname"],
+ "msg": "Field required",
+ "input": {"tags": ["foo", "bar"], "with": "nothing"},
+ },
+ ]
+ }
def test_extra_param_single():
diff --git a/tests/test_forms_single_param.py b/tests/test_forms_single_param.py
index 3bb951441f..67f054b34e 100644
--- a/tests/test_forms_single_param.py
+++ b/tests/test_forms_single_param.py
@@ -1,6 +1,7 @@
+from typing import Annotated
+
from fastapi import FastAPI, Form
from fastapi.testclient import TestClient
-from typing_extensions import Annotated
app = FastAPI()
diff --git a/tests/test_generate_unique_id_function.py b/tests/test_generate_unique_id_function.py
index 5aeec66367..62ebfbc964 100644
--- a/tests/test_generate_unique_id_function.py
+++ b/tests/test_generate_unique_id_function.py
@@ -1,5 +1,4 @@
import warnings
-from typing import List
from fastapi import APIRouter, FastAPI
from fastapi.routing import APIRoute
@@ -33,12 +32,12 @@ def test_top_level_generate_unique_id():
app = FastAPI(generate_unique_id_function=custom_generate_unique_id)
router = APIRouter()
- @app.post("/", response_model=List[Item], responses={404: {"model": List[Message]}})
+ @app.post("/", response_model=list[Item], responses={404: {"model": list[Message]}})
def post_root(item1: Item, item2: Item):
return item1, item2 # pragma: nocover
@router.post(
- "/router", response_model=List[Item], responses={404: {"model": List[Message]}}
+ "/router", response_model=list[Item], responses={404: {"model": list[Message]}}
)
def post_router(item1: Item, item2: Item):
return item1, item2 # pragma: nocover
@@ -234,12 +233,12 @@ def test_router_overrides_generate_unique_id():
app = FastAPI(generate_unique_id_function=custom_generate_unique_id)
router = APIRouter(generate_unique_id_function=custom_generate_unique_id2)
- @app.post("/", response_model=List[Item], responses={404: {"model": List[Message]}})
+ @app.post("/", response_model=list[Item], responses={404: {"model": list[Message]}})
def post_root(item1: Item, item2: Item):
return item1, item2 # pragma: nocover
@router.post(
- "/router", response_model=List[Item], responses={404: {"model": List[Message]}}
+ "/router", response_model=list[Item], responses={404: {"model": list[Message]}}
)
def post_router(item1: Item, item2: Item):
return item1, item2 # pragma: nocover
@@ -435,12 +434,12 @@ def test_router_include_overrides_generate_unique_id():
app = FastAPI(generate_unique_id_function=custom_generate_unique_id)
router = APIRouter(generate_unique_id_function=custom_generate_unique_id2)
- @app.post("/", response_model=List[Item], responses={404: {"model": List[Message]}})
+ @app.post("/", response_model=list[Item], responses={404: {"model": list[Message]}})
def post_root(item1: Item, item2: Item):
return item1, item2 # pragma: nocover
@router.post(
- "/router", response_model=List[Item], responses={404: {"model": List[Message]}}
+ "/router", response_model=list[Item], responses={404: {"model": list[Message]}}
)
def post_router(item1: Item, item2: Item):
return item1, item2 # pragma: nocover
@@ -637,20 +636,20 @@ def test_subrouter_top_level_include_overrides_generate_unique_id():
router = APIRouter()
sub_router = APIRouter(generate_unique_id_function=custom_generate_unique_id2)
- @app.post("/", response_model=List[Item], responses={404: {"model": List[Message]}})
+ @app.post("/", response_model=list[Item], responses={404: {"model": list[Message]}})
def post_root(item1: Item, item2: Item):
return item1, item2 # pragma: nocover
@router.post(
- "/router", response_model=List[Item], responses={404: {"model": List[Message]}}
+ "/router", response_model=list[Item], responses={404: {"model": list[Message]}}
)
def post_router(item1: Item, item2: Item):
return item1, item2 # pragma: nocover
@sub_router.post(
"/subrouter",
- response_model=List[Item],
- responses={404: {"model": List[Message]}},
+ response_model=list[Item],
+ responses={404: {"model": list[Message]}},
)
def post_subrouter(item1: Item, item2: Item):
return item1, item2 # pragma: nocover
@@ -910,14 +909,14 @@ def test_router_path_operation_overrides_generate_unique_id():
app = FastAPI(generate_unique_id_function=custom_generate_unique_id)
router = APIRouter(generate_unique_id_function=custom_generate_unique_id2)
- @app.post("/", response_model=List[Item], responses={404: {"model": List[Message]}})
+ @app.post("/", response_model=list[Item], responses={404: {"model": list[Message]}})
def post_root(item1: Item, item2: Item):
return item1, item2 # pragma: nocover
@router.post(
"/router",
- response_model=List[Item],
- responses={404: {"model": List[Message]}},
+ response_model=list[Item],
+ responses={404: {"model": list[Message]}},
generate_unique_id_function=custom_generate_unique_id3,
)
def post_router(item1: Item, item2: Item):
@@ -1116,8 +1115,8 @@ def test_app_path_operation_overrides_generate_unique_id():
@app.post(
"/",
- response_model=List[Item],
- responses={404: {"model": List[Message]}},
+ response_model=list[Item],
+ responses={404: {"model": list[Message]}},
generate_unique_id_function=custom_generate_unique_id3,
)
def post_root(item1: Item, item2: Item):
@@ -1125,8 +1124,8 @@ def test_app_path_operation_overrides_generate_unique_id():
@router.post(
"/router",
- response_model=List[Item],
- responses={404: {"model": List[Message]}},
+ response_model=list[Item],
+ responses={404: {"model": list[Message]}},
)
def post_router(item1: Item, item2: Item):
return item1, item2 # pragma: nocover
@@ -1324,8 +1323,8 @@ def test_callback_override_generate_unique_id():
@callback_router.post(
"/post-callback",
- response_model=List[Item],
- responses={404: {"model": List[Message]}},
+ response_model=list[Item],
+ responses={404: {"model": list[Message]}},
generate_unique_id_function=custom_generate_unique_id3,
)
def post_callback(item1: Item, item2: Item):
@@ -1333,8 +1332,8 @@ def test_callback_override_generate_unique_id():
@app.post(
"/",
- response_model=List[Item],
- responses={404: {"model": List[Message]}},
+ response_model=list[Item],
+ responses={404: {"model": list[Message]}},
generate_unique_id_function=custom_generate_unique_id3,
callbacks=callback_router.routes,
)
@@ -1343,8 +1342,8 @@ def test_callback_override_generate_unique_id():
@app.post(
"/tocallback",
- response_model=List[Item],
- responses={404: {"model": List[Message]}},
+ response_model=list[Item],
+ responses={404: {"model": list[Message]}},
)
def post_with_callback(item1: Item, item2: Item):
return item1, item2 # pragma: nocover
diff --git a/tests/test_generic_parameterless_depends.py b/tests/test_generic_parameterless_depends.py
index 5aa35320c9..93b72ad243 100644
--- a/tests/test_generic_parameterless_depends.py
+++ b/tests/test_generic_parameterless_depends.py
@@ -1,8 +1,7 @@
-from typing import TypeVar
+from typing import Annotated, TypeVar
from fastapi import Depends, FastAPI
from fastapi.testclient import TestClient
-from typing_extensions import Annotated
app = FastAPI()
diff --git a/tests/test_get_model_definitions_formfeed_escape.py b/tests/test_get_model_definitions_formfeed_escape.py
index 6601585ef0..eb7939b69a 100644
--- a/tests/test_get_model_definitions_formfeed_escape.py
+++ b/tests/test_get_model_definitions_formfeed_escape.py
@@ -1,180 +1,158 @@
-from typing import Any, Iterator, Set, Type
-
-import fastapi._compat
-import fastapi.openapi.utils
-import pydantic.schema
import pytest
from fastapi import FastAPI
-from pydantic import BaseModel
-from starlette.testclient import TestClient
-
-from .utils import needs_pydanticv1
+from fastapi.testclient import TestClient
+from inline_snapshot import snapshot
-class Address(BaseModel):
- """
- This is a public description of an Address
- \f
- You can't see this part of the docstring, it's private!
- """
+@pytest.fixture(name="client")
+def client_fixture() -> TestClient:
+ from pydantic import BaseModel
- line_1: str
- city: str
- state_province: str
+ class Address(BaseModel):
+ """
+ This is a public description of an Address
+ \f
+ You can't see this part of the docstring, it's private!
+ """
+
+ line_1: str
+ city: str
+ state_province: str
+
+ class Facility(BaseModel):
+ id: str
+ address: Address
+
+ app = FastAPI()
+
+ @app.get("/facilities/{facility_id}")
+ def get_facility(facility_id: str) -> Facility:
+ return Facility(
+ id=facility_id,
+ address=Address(line_1="123 Main St", city="Anytown", state_province="CA"),
+ )
+
+ client = TestClient(app)
+ return client
-class Facility(BaseModel):
- id: str
- address: Address
+def test_get(client: TestClient):
+ response = client.get("/facilities/42")
+ assert response.status_code == 200, response.text
+ assert response.json() == {
+ "id": "42",
+ "address": {
+ "line_1": "123 Main St",
+ "city": "Anytown",
+ "state_province": "CA",
+ },
+ }
-app = FastAPI()
-
-client = TestClient(app)
-
-
-@app.get("/facilities/{facility_id}")
-def get_facility(facility_id: str) -> Facility: ...
-
-
-openapi_schema = {
- "components": {
- "schemas": {
- "Address": {
- # NOTE: the description of this model shows only the public-facing text, before the `\f` in docstring
- "description": "This is a public description of an Address\n",
- "properties": {
- "city": {"title": "City", "type": "string"},
- "line_1": {"title": "Line 1", "type": "string"},
- "state_province": {"title": "State Province", "type": "string"},
- },
- "required": ["line_1", "city", "state_province"],
- "title": "Address",
- "type": "object",
- },
- "Facility": {
- "properties": {
- "address": {"$ref": "#/components/schemas/Address"},
- "id": {"title": "Id", "type": "string"},
- },
- "required": ["id", "address"],
- "title": "Facility",
- "type": "object",
- },
- "HTTPValidationError": {
- "properties": {
- "detail": {
- "items": {"$ref": "#/components/schemas/ValidationError"},
- "title": "Detail",
- "type": "array",
- }
- },
- "title": "HTTPValidationError",
- "type": "object",
- },
- "ValidationError": {
- "properties": {
- "loc": {
- "items": {"anyOf": [{"type": "string"}, {"type": "integer"}]},
- "title": "Location",
- "type": "array",
- },
- "msg": {"title": "Message", "type": "string"},
- "type": {"title": "Error Type", "type": "string"},
- },
- "required": ["loc", "msg", "type"],
- "title": "ValidationError",
- "type": "object",
- },
- }
- },
- "info": {"title": "FastAPI", "version": "0.1.0"},
- "openapi": "3.1.0",
- "paths": {
- "/facilities/{facility_id}": {
- "get": {
- "operationId": "get_facility_facilities__facility_id__get",
- "parameters": [
- {
- "in": "path",
- "name": "facility_id",
- "required": True,
- "schema": {"title": "Facility Id", "type": "string"},
- }
- ],
- "responses": {
- "200": {
- "content": {
- "application/json": {
- "schema": {"$ref": "#/components/schemas/Facility"}
- }
- },
- "description": "Successful Response",
- },
- "422": {
- "content": {
- "application/json": {
- "schema": {
- "$ref": "#/components/schemas/HTTPValidationError"
- }
- }
- },
- "description": "Validation Error",
- },
- },
- "summary": "Get Facility",
- }
- }
- },
-}
-
-
-def test_openapi_schema():
+def test_openapi_schema(client: TestClient):
"""
Sanity check to ensure our app's openapi schema renders as we expect
"""
response = client.get("/openapi.json")
assert response.status_code == 200, response.text
- assert response.json() == openapi_schema
-
-
-class SortedTypeSet(set):
- """
- Set of Types whose `__iter__()` method yields results sorted by the type names
- """
-
- def __init__(self, seq: Set[Type[Any]], *, sort_reversed: bool):
- super().__init__(seq)
- self.sort_reversed = sort_reversed
-
- def __iter__(self) -> Iterator[Type[Any]]:
- members_sorted = sorted(
- super().__iter__(),
- key=lambda type_: type_.__name__,
- reverse=self.sort_reversed,
- )
- yield from members_sorted
-
-
-@needs_pydanticv1
-@pytest.mark.parametrize("sort_reversed", [True, False])
-def test_model_description_escaped_with_formfeed(sort_reversed: bool):
- """
- Regression test for bug fixed by https://github.com/fastapi/fastapi/pull/6039.
-
- Test `get_model_definitions` with models passed in different order.
- """
- from fastapi._compat import v1
-
- all_fields = fastapi.openapi.utils.get_fields_from_routes(app.routes)
-
- flat_models = v1.get_flat_models_from_fields(all_fields, known_models=set())
- model_name_map = pydantic.schema.get_model_name_map(flat_models)
-
- expected_address_description = "This is a public description of an Address\n"
-
- models = v1.get_model_definitions(
- flat_models=SortedTypeSet(flat_models, sort_reversed=sort_reversed),
- model_name_map=model_name_map,
+ assert response.json() == snapshot(
+ {
+ "components": {
+ "schemas": {
+ "Address": {
+ # NOTE: the description of this model shows only the public-facing text, before the `\f` in docstring
+ "description": "This is a public description of an Address\n",
+ "properties": {
+ "city": {"title": "City", "type": "string"},
+ "line_1": {"title": "Line 1", "type": "string"},
+ "state_province": {
+ "title": "State Province",
+ "type": "string",
+ },
+ },
+ "required": ["line_1", "city", "state_province"],
+ "title": "Address",
+ "type": "object",
+ },
+ "Facility": {
+ "properties": {
+ "address": {"$ref": "#/components/schemas/Address"},
+ "id": {"title": "Id", "type": "string"},
+ },
+ "required": ["id", "address"],
+ "title": "Facility",
+ "type": "object",
+ },
+ "HTTPValidationError": {
+ "properties": {
+ "detail": {
+ "items": {
+ "$ref": "#/components/schemas/ValidationError"
+ },
+ "title": "Detail",
+ "type": "array",
+ }
+ },
+ "title": "HTTPValidationError",
+ "type": "object",
+ },
+ "ValidationError": {
+ "properties": {
+ "loc": {
+ "items": {
+ "anyOf": [{"type": "string"}, {"type": "integer"}]
+ },
+ "title": "Location",
+ "type": "array",
+ },
+ "msg": {"title": "Message", "type": "string"},
+ "type": {"title": "Error Type", "type": "string"},
+ },
+ "required": ["loc", "msg", "type"],
+ "title": "ValidationError",
+ "type": "object",
+ },
+ }
+ },
+ "info": {"title": "FastAPI", "version": "0.1.0"},
+ "openapi": "3.1.0",
+ "paths": {
+ "/facilities/{facility_id}": {
+ "get": {
+ "operationId": "get_facility_facilities__facility_id__get",
+ "parameters": [
+ {
+ "in": "path",
+ "name": "facility_id",
+ "required": True,
+ "schema": {"title": "Facility Id", "type": "string"},
+ }
+ ],
+ "responses": {
+ "200": {
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/Facility"
+ }
+ }
+ },
+ "description": "Successful Response",
+ },
+ "422": {
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/HTTPValidationError"
+ }
+ }
+ },
+ "description": "Validation Error",
+ },
+ },
+ "summary": "Get Facility",
+ }
+ }
+ },
+ }
)
- assert models["Address"]["description"] == expected_address_description
diff --git a/tests/test_infer_param_optionality.py b/tests/test_infer_param_optionality.py
index e3d57bb428..147018996e 100644
--- a/tests/test_infer_param_optionality.py
+++ b/tests/test_infer_param_optionality.py
@@ -1,6 +1,5 @@
from typing import Optional
-from dirty_equals import IsDict
from fastapi import APIRouter, FastAPI
from fastapi.testclient import TestClient
@@ -163,16 +162,10 @@ def test_openapi_schema():
"required": False,
"name": "user_id",
"in": "query",
- "schema": IsDict(
- {
- "anyOf": [{"type": "string"}, {"type": "null"}],
- "title": "User Id",
- }
- )
- | IsDict(
- # TODO: remove when deprecating Pydantic v1
- {"title": "User Id", "type": "string"}
- ),
+ "schema": {
+ "anyOf": [{"type": "string"}, {"type": "null"}],
+ "title": "User Id",
+ },
}
],
"responses": {
@@ -208,16 +201,10 @@ def test_openapi_schema():
"required": False,
"name": "user_id",
"in": "query",
- "schema": IsDict(
- {
- "anyOf": [{"type": "string"}, {"type": "null"}],
- "title": "User Id",
- }
- )
- | IsDict(
- # TODO: remove when deprecating Pydantic v1
- {"title": "User Id", "type": "string"}
- ),
+ "schema": {
+ "anyOf": [{"type": "string"}, {"type": "null"}],
+ "title": "User Id",
+ },
},
],
"responses": {
@@ -247,16 +234,10 @@ def test_openapi_schema():
"required": True,
"name": "user_id",
"in": "path",
- "schema": IsDict(
- {
- "anyOf": [{"type": "string"}, {"type": "null"}],
- "title": "User Id",
- }
- )
- | IsDict(
- # TODO: remove when deprecating Pydantic v1
- {"title": "User Id", "type": "string"}
- ),
+ "schema": {
+ "anyOf": [{"type": "string"}, {"type": "null"}],
+ "title": "User Id",
+ },
}
],
"responses": {
@@ -292,16 +273,10 @@ def test_openapi_schema():
"required": True,
"name": "user_id",
"in": "path",
- "schema": IsDict(
- {
- "anyOf": [{"type": "string"}, {"type": "null"}],
- "title": "User Id",
- }
- )
- | IsDict(
- # TODO: remove when deprecating Pydantic v1
- {"title": "User Id", "type": "string"}
- ),
+ "schema": {
+ "anyOf": [{"type": "string"}, {"type": "null"}],
+ "title": "User Id",
+ },
},
],
"responses": {
diff --git a/tests/test_inherited_custom_class.py b/tests/test_inherited_custom_class.py
index fe9350f4ef..8cf8952f92 100644
--- a/tests/test_inherited_custom_class.py
+++ b/tests/test_inherited_custom_class.py
@@ -5,8 +5,6 @@ from fastapi import FastAPI
from fastapi.testclient import TestClient
from pydantic import BaseModel
-from .utils import needs_pydanticv1, needs_pydanticv2
-
class MyUuid:
def __init__(self, uuid_string: str):
@@ -26,7 +24,6 @@ class MyUuid:
raise TypeError("vars() argument must have __dict__ attribute")
-@needs_pydanticv2
def test_pydanticv2():
from pydantic import field_serializer
@@ -68,44 +65,3 @@ def test_pydanticv2():
assert response_pydantic.json() == {
"a_uuid": "b8799909-f914-42de-91bc-95c819218d01"
}
-
-
-# TODO: remove when deprecating Pydantic v1
-@needs_pydanticv1
-def test_pydanticv1():
- app = FastAPI()
-
- @app.get("/fast_uuid")
- def return_fast_uuid():
- asyncpg_uuid = MyUuid("a10ff360-3b1e-4984-a26f-d3ab460bdb51")
- assert isinstance(asyncpg_uuid, uuid.UUID)
- assert type(asyncpg_uuid) is not uuid.UUID
- with pytest.raises(TypeError):
- vars(asyncpg_uuid)
- return {"fast_uuid": asyncpg_uuid}
-
- class SomeCustomClass(BaseModel):
- class Config:
- arbitrary_types_allowed = True
- json_encoders = {uuid.UUID: str}
-
- a_uuid: MyUuid
-
- @app.get("/get_custom_class")
- def return_some_user():
- # Test that the fix also works for custom pydantic classes
- return SomeCustomClass(a_uuid=MyUuid("b8799909-f914-42de-91bc-95c819218d01"))
-
- client = TestClient(app)
-
- with client:
- response_simple = client.get("/fast_uuid")
- response_pydantic = client.get("/get_custom_class")
-
- assert response_simple.json() == {
- "fast_uuid": "a10ff360-3b1e-4984-a26f-d3ab460bdb51"
- }
-
- assert response_pydantic.json() == {
- "a_uuid": "b8799909-f914-42de-91bc-95c819218d01"
- }
diff --git a/tests/test_invalid_path_param.py b/tests/test_invalid_path_param.py
index d5fa53c1fc..35c00363da 100644
--- a/tests/test_invalid_path_param.py
+++ b/tests/test_invalid_path_param.py
@@ -1,5 +1,3 @@
-from typing import Dict, List, Tuple
-
import pytest
from fastapi import FastAPI
from pydantic import BaseModel
@@ -13,7 +11,7 @@ def test_invalid_sequence():
title: str
@app.get("/items/{id}")
- def read_items(id: List[Item]):
+ def read_items(id: list[Item]):
pass # pragma: no cover
@@ -25,7 +23,7 @@ def test_invalid_tuple():
title: str
@app.get("/items/{id}")
- def read_items(id: Tuple[Item, Item]):
+ def read_items(id: tuple[Item, Item]):
pass # pragma: no cover
@@ -37,7 +35,7 @@ def test_invalid_dict():
title: str
@app.get("/items/{id}")
- def read_items(id: Dict[str, Item]):
+ def read_items(id: dict[str, Item]):
pass # pragma: no cover
diff --git a/tests/test_invalid_sequence_param.py b/tests/test_invalid_sequence_param.py
index 475786adbf..2b8fd059e1 100644
--- a/tests/test_invalid_sequence_param.py
+++ b/tests/test_invalid_sequence_param.py
@@ -1,4 +1,4 @@
-from typing import Dict, List, Optional, Tuple
+from typing import Optional
import pytest
from fastapi import FastAPI, Query
@@ -13,7 +13,7 @@ def test_invalid_sequence():
title: str
@app.get("/items/")
- def read_items(q: List[Item] = Query(default=None)):
+ def read_items(q: list[Item] = Query(default=None)):
pass # pragma: no cover
@@ -25,7 +25,7 @@ def test_invalid_tuple():
title: str
@app.get("/items/")
- def read_items(q: Tuple[Item, Item] = Query(default=None)):
+ def read_items(q: tuple[Item, Item] = Query(default=None)):
pass # pragma: no cover
@@ -37,7 +37,7 @@ def test_invalid_dict():
title: str
@app.get("/items/")
- def read_items(q: Dict[str, Item] = Query(default=None)):
+ def read_items(q: dict[str, Item] = Query(default=None)):
pass # pragma: no cover
diff --git a/tests/test_jsonable_encoder.py b/tests/test_jsonable_encoder.py
index 3b6513e27b..4528dff440 100644
--- a/tests/test_jsonable_encoder.py
+++ b/tests/test_jsonable_encoder.py
@@ -1,3 +1,4 @@
+import warnings
from collections import deque
from dataclasses import dataclass
from datetime import datetime, timezone
@@ -5,15 +6,14 @@ from decimal import Decimal
from enum import Enum
from math import isinf, isnan
from pathlib import PurePath, PurePosixPath, PureWindowsPath
-from typing import Optional
+from typing import Optional, TypedDict
import pytest
-from fastapi._compat import PYDANTIC_V2, Undefined
+from fastapi._compat import Undefined
from fastapi.encoders import jsonable_encoder
+from fastapi.exceptions import PydanticV1NotSupportedError
from pydantic import BaseModel, Field, ValidationError
-from .utils import needs_pydanticv1, needs_pydanticv2
-
class Person:
def __init__(self, name: str):
@@ -59,12 +59,7 @@ class RoleEnum(Enum):
class ModelWithConfig(BaseModel):
role: Optional[RoleEnum] = None
- if PYDANTIC_V2:
- model_config = {"use_enum_values": True}
- else:
-
- class Config:
- use_enum_values = True
+ model_config = {"use_enum_values": True}
class ModelWithAlias(BaseModel):
@@ -89,6 +84,18 @@ def test_encode_dict():
}
+def test_encode_dict_include_exclude_list():
+ pet = {"name": "Firulais", "owner": {"name": "Foo"}}
+ assert jsonable_encoder(pet) == {"name": "Firulais", "owner": {"name": "Foo"}}
+ assert jsonable_encoder(pet, include=["name"]) == {"name": "Firulais"}
+ assert jsonable_encoder(pet, exclude=["owner"]) == {"name": "Firulais"}
+ assert jsonable_encoder(pet, include=[]) == {}
+ assert jsonable_encoder(pet, exclude=[]) == {
+ "name": "Firulais",
+ "owner": {"name": "Foo"},
+ }
+
+
def test_encode_class():
person = Person(name="Foo")
pet = Pet(owner=person, name="Firulais")
@@ -130,7 +137,6 @@ def test_encode_unsupported():
jsonable_encoder(unserializable)
-@needs_pydanticv2
def test_encode_custom_json_encoders_model_pydanticv2():
from pydantic import field_serializer
@@ -150,27 +156,17 @@ def test_encode_custom_json_encoders_model_pydanticv2():
assert jsonable_encoder(subclass_model) == {"dt_field": "2019-01-01T08:00:00+00:00"}
-# TODO: remove when deprecating Pydantic v1
-@needs_pydanticv1
-def test_encode_custom_json_encoders_model_pydanticv1():
- class ModelWithCustomEncoder(BaseModel):
- dt_field: datetime
+def test_json_encoder_error_with_pydanticv1():
+ with warnings.catch_warnings():
+ warnings.simplefilter("ignore", UserWarning)
+ from pydantic import v1
- class Config:
- json_encoders = {
- datetime: lambda dt: dt.replace(
- microsecond=0, tzinfo=timezone.utc
- ).isoformat()
- }
+ class ModelV1(v1.BaseModel):
+ name: str
- class ModelWithCustomEncoderSubclass(ModelWithCustomEncoder):
- class Config:
- pass
-
- model = ModelWithCustomEncoder(dt_field=datetime(2019, 1, 1, 8))
- assert jsonable_encoder(model) == {"dt_field": "2019-01-01T08:00:00+00:00"}
- subclass_model = ModelWithCustomEncoderSubclass(dt_field=datetime(2019, 1, 1, 8))
- assert jsonable_encoder(subclass_model) == {"dt_field": "2019-01-01T08:00:00+00:00"}
+ data = ModelV1(name="test")
+ with pytest.raises(PydanticV1NotSupportedError):
+ jsonable_encoder(data)
def test_encode_model_with_config():
@@ -206,23 +202,27 @@ def test_encode_model_with_default():
}
-@needs_pydanticv1
def test_custom_encoders():
class safe_datetime(datetime):
pass
- class MyModel(BaseModel):
+ class MyDict(TypedDict):
dt_field: safe_datetime
- instance = MyModel(dt_field=safe_datetime.now())
+ instance = MyDict(dt_field=safe_datetime.now())
encoded_instance = jsonable_encoder(
instance, custom_encoder={safe_datetime: lambda o: o.strftime("%H:%M:%S")}
)
- assert encoded_instance["dt_field"] == instance.dt_field.strftime("%H:%M:%S")
+ assert encoded_instance["dt_field"] == instance["dt_field"].strftime("%H:%M:%S")
+
+ encoded_instance = jsonable_encoder(
+ instance, custom_encoder={datetime: lambda o: o.strftime("%H:%M:%S")}
+ )
+ assert encoded_instance["dt_field"] == instance["dt_field"].strftime("%H:%M:%S")
encoded_instance2 = jsonable_encoder(instance)
- assert encoded_instance2["dt_field"] == instance.dt_field.isoformat()
+ assert encoded_instance2["dt_field"] == instance["dt_field"].isoformat()
def test_custom_enum_encoders():
@@ -244,12 +244,7 @@ def test_encode_model_with_pure_path():
class ModelWithPath(BaseModel):
path: PurePath
- if PYDANTIC_V2:
- model_config = {"arbitrary_types_allowed": True}
- else:
-
- class Config:
- arbitrary_types_allowed = True
+ model_config = {"arbitrary_types_allowed": True}
test_path = PurePath("/foo", "bar")
obj = ModelWithPath(path=test_path)
@@ -260,12 +255,7 @@ def test_encode_model_with_pure_posix_path():
class ModelWithPath(BaseModel):
path: PurePosixPath
- if PYDANTIC_V2:
- model_config = {"arbitrary_types_allowed": True}
- else:
-
- class Config:
- arbitrary_types_allowed = True
+ model_config = {"arbitrary_types_allowed": True}
obj = ModelWithPath(path=PurePosixPath("/foo", "bar"))
assert jsonable_encoder(obj) == {"path": "/foo/bar"}
@@ -275,45 +265,33 @@ def test_encode_model_with_pure_windows_path():
class ModelWithPath(BaseModel):
path: PureWindowsPath
- if PYDANTIC_V2:
- model_config = {"arbitrary_types_allowed": True}
- else:
-
- class Config:
- arbitrary_types_allowed = True
+ model_config = {"arbitrary_types_allowed": True}
obj = ModelWithPath(path=PureWindowsPath("/foo", "bar"))
assert jsonable_encoder(obj) == {"path": "\\foo\\bar"}
-@needs_pydanticv1
-def test_encode_root():
- class ModelWithRoot(BaseModel):
- __root__: str
+def test_encode_pure_path():
+ test_path = PurePath("/foo", "bar")
- model = ModelWithRoot(__root__="Foo")
- assert jsonable_encoder(model) == "Foo"
+ assert jsonable_encoder({"path": test_path}) == {"path": str(test_path)}
-@needs_pydanticv2
def test_decimal_encoder_float():
data = {"value": Decimal(1.23)}
assert jsonable_encoder(data) == {"value": 1.23}
-@needs_pydanticv2
def test_decimal_encoder_int():
data = {"value": Decimal(2)}
assert jsonable_encoder(data) == {"value": 2}
-@needs_pydanticv2
def test_decimal_encoder_nan():
data = {"value": Decimal("NaN")}
assert isnan(jsonable_encoder(data)["value"])
-@needs_pydanticv2
def test_decimal_encoder_infinity():
data = {"value": Decimal("Infinity")}
assert isinf(jsonable_encoder(data)["value"])
@@ -330,7 +308,6 @@ def test_encode_deque_encodes_child_models():
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 33304827a9..4418c77cb0 100644
--- a/tests/test_multi_body_errors.py
+++ b/tests/test_multi_body_errors.py
@@ -1,9 +1,9 @@
from decimal import Decimal
-from typing import List
-from dirty_equals import IsDict, IsOneOf
+from dirty_equals import IsOneOf
from fastapi import FastAPI
from fastapi.testclient import TestClient
+from inline_snapshot import snapshot
from pydantic import BaseModel, condecimal
app = FastAPI()
@@ -15,7 +15,7 @@ class Item(BaseModel):
@app.post("/items/")
-def save_item_no_body(item: List[Item]):
+def save_item_no_body(item: list[Item]):
return {"item": item}
@@ -25,109 +25,65 @@ client = TestClient(app)
def test_put_correct_body():
response = client.post("/items/", json=[{"name": "Foo", "age": 5}])
assert response.status_code == 200, response.text
- assert response.json() == {
- "item": [
- {
- "name": "Foo",
- "age": IsOneOf(
- 5,
- # TODO: remove when deprecating Pydantic v1
- "5",
- ),
- }
- ]
- }
+ assert response.json() == snapshot(
+ {
+ "item": [
+ {
+ "name": "Foo",
+ "age": "5",
+ }
+ ]
+ }
+ )
def test_jsonable_encoder_requiring_error():
response = client.post("/items/", json=[{"name": "Foo", "age": -1.0}])
assert response.status_code == 422, response.text
- assert response.json() == IsDict(
- {
- "detail": [
- {
- "type": "greater_than",
- "loc": ["body", 0, "age"],
- "msg": "Input should be greater than 0",
- "input": -1.0,
- "ctx": {"gt": 0},
- }
- ]
- }
- ) | IsDict(
- # TODO: remove when deprecating Pydantic v1
- {
- "detail": [
- {
- "ctx": {"limit_value": 0.0},
- "loc": ["body", 0, "age"],
- "msg": "ensure this value is greater than 0",
- "type": "value_error.number.not_gt",
- }
- ]
- }
- )
+ assert response.json() == {
+ "detail": [
+ {
+ "type": "greater_than",
+ "loc": ["body", 0, "age"],
+ "msg": "Input should be greater than 0",
+ "input": -1.0,
+ "ctx": {"gt": 0},
+ }
+ ]
+ }
def test_put_incorrect_body_multiple():
response = client.post("/items/", json=[{"age": "five"}, {"age": "six"}])
assert response.status_code == 422, response.text
- assert response.json() == IsDict(
- {
- "detail": [
- {
- "type": "missing",
- "loc": ["body", 0, "name"],
- "msg": "Field required",
- "input": {"age": "five"},
- },
- {
- "type": "decimal_parsing",
- "loc": ["body", 0, "age"],
- "msg": "Input should be a valid decimal",
- "input": "five",
- },
- {
- "type": "missing",
- "loc": ["body", 1, "name"],
- "msg": "Field required",
- "input": {"age": "six"},
- },
- {
- "type": "decimal_parsing",
- "loc": ["body", 1, "age"],
- "msg": "Input should be a valid decimal",
- "input": "six",
- },
- ]
- }
- ) | IsDict(
- # TODO: remove when deprecating Pydantic v1
- {
- "detail": [
- {
- "loc": ["body", 0, "name"],
- "msg": "field required",
- "type": "value_error.missing",
- },
- {
- "loc": ["body", 0, "age"],
- "msg": "value is not a valid decimal",
- "type": "type_error.decimal",
- },
- {
- "loc": ["body", 1, "name"],
- "msg": "field required",
- "type": "value_error.missing",
- },
- {
- "loc": ["body", 1, "age"],
- "msg": "value is not a valid decimal",
- "type": "type_error.decimal",
- },
- ]
- }
- )
+ assert response.json() == {
+ "detail": [
+ {
+ "type": "missing",
+ "loc": ["body", 0, "name"],
+ "msg": "Field required",
+ "input": {"age": "five"},
+ },
+ {
+ "type": "decimal_parsing",
+ "loc": ["body", 0, "age"],
+ "msg": "Input should be a valid decimal",
+ "input": "five",
+ },
+ {
+ "type": "missing",
+ "loc": ["body", 1, "name"],
+ "msg": "Field required",
+ "input": {"age": "six"},
+ },
+ {
+ "type": "decimal_parsing",
+ "loc": ["body", 1, "age"],
+ "msg": "Input should be a valid decimal",
+ "input": "six",
+ },
+ ]
+ }
def test_openapi_schema():
@@ -180,31 +136,21 @@ def test_openapi_schema():
"type": "object",
"properties": {
"name": {"title": "Name", "type": "string"},
- "age": IsDict(
- {
- "title": "Age",
- "anyOf": [
- {"exclusiveMinimum": 0.0, "type": "number"},
- IsOneOf(
- # pydantic < 2.12.0
- {"type": "string"},
- # pydantic >= 2.12.0
- {
- "type": "string",
- "pattern": r"^(?!^[-+.]*$)[+-]?0*\d*\.?\d*$",
- },
- ),
- ],
- }
- )
- | IsDict(
- # TODO: remove when deprecating Pydantic v1
- {
- "title": "Age",
- "exclusiveMinimum": 0.0,
- "type": "number",
- }
- ),
+ "age": {
+ "title": "Age",
+ "anyOf": [
+ {"exclusiveMinimum": 0.0, "type": "number"},
+ IsOneOf(
+ # pydantic < 2.12.0
+ {"type": "string"},
+ # pydantic >= 2.12.0
+ {
+ "type": "string",
+ "pattern": r"^(?!^[-+.]*$)[+-]?0*\d*\.?\d*$",
+ },
+ ),
+ ],
+ },
},
},
"ValidationError": {
diff --git a/tests/test_multi_query_errors.py b/tests/test_multi_query_errors.py
index 8162d986c5..5df51ba185 100644
--- a/tests/test_multi_query_errors.py
+++ b/tests/test_multi_query_errors.py
@@ -1,6 +1,3 @@
-from typing import List
-
-from dirty_equals import IsDict
from fastapi import FastAPI, Query
from fastapi.testclient import TestClient
@@ -8,7 +5,7 @@ app = FastAPI()
@app.get("/items/")
-def read_items(q: List[int] = Query(default=None)):
+def read_items(q: list[int] = Query(default=None)):
return {"q": q}
@@ -24,40 +21,22 @@ def test_multi_query():
def test_multi_query_incorrect():
response = client.get("/items/?q=five&q=six")
assert response.status_code == 422, response.text
- assert response.json() == IsDict(
- {
- "detail": [
- {
- "type": "int_parsing",
- "loc": ["query", "q", 0],
- "msg": "Input should be a valid integer, unable to parse string as an integer",
- "input": "five",
- },
- {
- "type": "int_parsing",
- "loc": ["query", "q", 1],
- "msg": "Input should be a valid integer, unable to parse string as an integer",
- "input": "six",
- },
- ]
- }
- ) | IsDict(
- # TODO: remove when deprecating Pydantic v1
- {
- "detail": [
- {
- "loc": ["query", "q", 0],
- "msg": "value is not a valid integer",
- "type": "type_error.integer",
- },
- {
- "loc": ["query", "q", 1],
- "msg": "value is not a valid integer",
- "type": "type_error.integer",
- },
- ]
- }
- )
+ assert response.json() == {
+ "detail": [
+ {
+ "type": "int_parsing",
+ "loc": ["query", "q", 0],
+ "msg": "Input should be a valid integer, unable to parse string as an integer",
+ "input": "five",
+ },
+ {
+ "type": "int_parsing",
+ "loc": ["query", "q", 1],
+ "msg": "Input should be a valid integer, unable to parse string as an integer",
+ "input": "six",
+ },
+ ]
+ }
def test_openapi_schema():
diff --git a/tests/test_no_schema_split.py b/tests/test_no_schema_split.py
index b0b5958c1b..131a3755e7 100644
--- a/tests/test_no_schema_split.py
+++ b/tests/test_no_schema_split.py
@@ -3,15 +3,12 @@
# Made an issue in:
# https://github.com/fastapi/fastapi/issues/14247
from enum import Enum
-from typing import List
from fastapi import FastAPI
from fastapi.testclient import TestClient
from inline_snapshot import snapshot
from pydantic import BaseModel, Field
-from tests.utils import pydantic_snapshot
-
class MessageEventType(str, Enum):
alpha = "alpha"
@@ -25,7 +22,7 @@ class MessageEvent(BaseModel):
class MessageOutput(BaseModel):
body: str = ""
- events: List[MessageEvent] = []
+ events: list[MessageEvent] = []
class Message(BaseModel):
@@ -127,47 +124,21 @@ def test_openapi_schema():
},
"MessageEvent": {
"properties": {
- "event_type": pydantic_snapshot(
- v2=snapshot(
- {
- "$ref": "#/components/schemas/MessageEventType",
- "default": "alpha",
- }
- ),
- v1=snapshot(
- {
- "allOf": [
- {
- "$ref": "#/components/schemas/MessageEventType"
- }
- ],
- "default": "alpha",
- }
- ),
- ),
+ "event_type": {
+ "$ref": "#/components/schemas/MessageEventType",
+ "default": "alpha",
+ },
"output": {"type": "string", "title": "Output"},
},
"type": "object",
"required": ["output"],
"title": "MessageEvent",
},
- "MessageEventType": pydantic_snapshot(
- v2=snapshot(
- {
- "type": "string",
- "enum": ["alpha", "beta"],
- "title": "MessageEventType",
- }
- ),
- v1=snapshot(
- {
- "type": "string",
- "enum": ["alpha", "beta"],
- "title": "MessageEventType",
- "description": "An enumeration.",
- }
- ),
- ),
+ "MessageEventType": {
+ "type": "string",
+ "enum": ["alpha", "beta"],
+ "title": "MessageEventType",
+ },
"MessageOutput": {
"properties": {
"body": {"type": "string", "title": "Body", "default": ""},
diff --git a/tests/test_openapi_examples.py b/tests/test_openapi_examples.py
index b3f83ae237..bd0d55452e 100644
--- a/tests/test_openapi_examples.py
+++ b/tests/test_openapi_examples.py
@@ -1,6 +1,5 @@
from typing import Union
-from dirty_equals import IsDict
from fastapi import Body, Cookie, FastAPI, Header, Path, Query
from fastapi.testclient import TestClient
from pydantic import BaseModel
@@ -155,26 +154,12 @@ def test_openapi_schema():
"requestBody": {
"content": {
"application/json": {
- "schema": IsDict(
- {
- "$ref": "#/components/schemas/Item",
- "examples": [
- {"data": "Data in Body examples, example1"}
- ],
- }
- )
- | IsDict(
- {
- # TODO: remove when deprecating Pydantic v1
- "allOf": [
- {"$ref": "#/components/schemas/Item"}
- ],
- "title": "Item",
- "examples": [
- {"data": "Data in Body examples, example1"}
- ],
- }
- ),
+ "schema": {
+ "$ref": "#/components/schemas/Item",
+ "examples": [
+ {"data": "Data in Body examples, example1"}
+ ],
+ },
"examples": {
"Example One": {
"summary": "Example One Summary",
@@ -265,27 +250,14 @@ def test_openapi_schema():
"name": "data",
"in": "query",
"required": False,
- "schema": IsDict(
- {
- "anyOf": [{"type": "string"}, {"type": "null"}],
- "examples": [
- "json_schema_query1",
- "json_schema_query2",
- ],
- "title": "Data",
- }
- )
- | IsDict(
- # TODO: remove when deprecating Pydantic v1
- {
- "examples": [
- "json_schema_query1",
- "json_schema_query2",
- ],
- "type": "string",
- "title": "Data",
- }
- ),
+ "schema": {
+ "anyOf": [{"type": "string"}, {"type": "null"}],
+ "examples": [
+ "json_schema_query1",
+ "json_schema_query2",
+ ],
+ "title": "Data",
+ },
"examples": {
"Query One": {
"summary": "Query One Summary",
@@ -323,27 +295,14 @@ def test_openapi_schema():
"name": "data",
"in": "header",
"required": False,
- "schema": IsDict(
- {
- "anyOf": [{"type": "string"}, {"type": "null"}],
- "examples": [
- "json_schema_header1",
- "json_schema_header2",
- ],
- "title": "Data",
- }
- )
- | IsDict(
- # TODO: remove when deprecating Pydantic v1
- {
- "type": "string",
- "examples": [
- "json_schema_header1",
- "json_schema_header2",
- ],
- "title": "Data",
- }
- ),
+ "schema": {
+ "anyOf": [{"type": "string"}, {"type": "null"}],
+ "examples": [
+ "json_schema_header1",
+ "json_schema_header2",
+ ],
+ "title": "Data",
+ },
"examples": {
"Header One": {
"summary": "Header One Summary",
@@ -381,27 +340,14 @@ def test_openapi_schema():
"name": "data",
"in": "cookie",
"required": False,
- "schema": IsDict(
- {
- "anyOf": [{"type": "string"}, {"type": "null"}],
- "examples": [
- "json_schema_cookie1",
- "json_schema_cookie2",
- ],
- "title": "Data",
- }
- )
- | IsDict(
- # TODO: remove when deprecating Pydantic v1
- {
- "type": "string",
- "examples": [
- "json_schema_cookie1",
- "json_schema_cookie2",
- ],
- "title": "Data",
- }
- ),
+ "schema": {
+ "anyOf": [{"type": "string"}, {"type": "null"}],
+ "examples": [
+ "json_schema_cookie1",
+ "json_schema_cookie2",
+ ],
+ "title": "Data",
+ },
"examples": {
"Cookie One": {
"summary": "Cookie One Summary",
diff --git a/tests/test_openapi_query_parameter_extension.py b/tests/test_openapi_query_parameter_extension.py
index dc7147c712..084cb695d4 100644
--- a/tests/test_openapi_query_parameter_extension.py
+++ b/tests/test_openapi_query_parameter_extension.py
@@ -1,6 +1,5 @@
from typing import Optional
-from dirty_equals import IsDict
from fastapi import FastAPI
from fastapi.testclient import TestClient
@@ -53,21 +52,11 @@ def test_openapi():
"parameters": [
{
"required": False,
- "schema": IsDict(
- {
- "anyOf": [{"type": "integer"}, {"type": "null"}],
- "default": 50,
- "title": "Standard Query Param",
- }
- )
- | IsDict(
- # TODO: remove when deprecating Pydantic v1
- {
- "title": "Standard Query Param",
- "type": "integer",
- "default": 50,
- }
- ),
+ "schema": {
+ "anyOf": [{"type": "integer"}, {"type": "null"}],
+ "default": 50,
+ "title": "Standard Query Param",
+ },
"name": "standard_query_param",
"in": "query",
},
diff --git a/tests/test_openapi_schema_type.py b/tests/test_openapi_schema_type.py
index a45ea20c8c..98d9787455 100644
--- a/tests/test_openapi_schema_type.py
+++ b/tests/test_openapi_schema_type.py
@@ -1,4 +1,4 @@
-from typing import List, Optional, Union
+from typing import Optional, Union
import pytest
from fastapi.openapi.models import Schema, SchemaType
@@ -13,7 +13,7 @@ from fastapi.openapi.models import Schema, SchemaType
],
)
def test_allowed_schema_type(
- type_value: Optional[Union[SchemaType, List[SchemaType]]],
+ type_value: Optional[Union[SchemaType, list[SchemaType]]],
) -> None:
"""Test that Schema accepts SchemaType, List[SchemaType] and None for type field."""
schema = Schema(type=type_value)
diff --git a/tests/test_openapi_separate_input_output_schemas.py b/tests/test_openapi_separate_input_output_schemas.py
index c9a05418bf..1891f0bde0 100644
--- a/tests/test_openapi_separate_input_output_schemas.py
+++ b/tests/test_openapi_separate_input_output_schemas.py
@@ -1,39 +1,32 @@
-from typing import List, Optional
+from typing import Optional
from fastapi import FastAPI
from fastapi.testclient import TestClient
from inline_snapshot import snapshot
-from pydantic import BaseModel
-
-from .utils import PYDANTIC_V2, needs_pydanticv2
+from pydantic import BaseModel, computed_field
class SubItem(BaseModel):
subname: str
sub_description: Optional[str] = None
- tags: List[str] = []
- if PYDANTIC_V2:
- model_config = {"json_schema_serialization_defaults_required": True}
+ tags: list[str] = []
+ model_config = {"json_schema_serialization_defaults_required": True}
class Item(BaseModel):
name: str
description: Optional[str] = None
sub: Optional[SubItem] = None
- if PYDANTIC_V2:
- model_config = {"json_schema_serialization_defaults_required": True}
+ model_config = {"json_schema_serialization_defaults_required": True}
-if PYDANTIC_V2:
- from pydantic import computed_field
+class WithComputedField(BaseModel):
+ name: str
- class WithComputedField(BaseModel):
- name: str
-
- @computed_field
- @property
- def computed_field(self) -> str:
- return f"computed {self.name}"
+ @computed_field
+ @property
+ def computed_field(self) -> str:
+ return f"computed {self.name}"
def get_app_client(separate_input_output_schemas: bool = True) -> TestClient:
@@ -44,11 +37,11 @@ def get_app_client(separate_input_output_schemas: bool = True) -> TestClient:
return item
@app.post("/items-list/")
- def create_item_list(item: List[Item]):
+ def create_item_list(item: list[Item]):
return item
@app.get("/items/")
- def read_items() -> List[Item]:
+ def read_items() -> list[Item]:
return [
Item(
name="Portal Gun",
@@ -58,13 +51,11 @@ def get_app_client(separate_input_output_schemas: bool = True) -> TestClient:
Item(name="Plumbus"),
]
- if PYDANTIC_V2:
-
- @app.post("/with-computed-field/")
- def create_with_computed_field(
- with_computed_field: WithComputedField,
- ) -> WithComputedField:
- return with_computed_field
+ @app.post("/with-computed-field/")
+ def create_with_computed_field(
+ with_computed_field: WithComputedField,
+ ) -> WithComputedField:
+ return with_computed_field
client = TestClient(app)
return client
@@ -151,7 +142,6 @@ def test_read_items():
)
-@needs_pydanticv2
def test_with_computed_field():
client = get_app_client()
client_no = get_app_client(separate_input_output_schemas=False)
@@ -168,7 +158,6 @@ def test_with_computed_field():
)
-@needs_pydanticv2
def test_openapi_schema():
client = get_app_client()
response = client.get("/openapi.json")
@@ -449,7 +438,6 @@ def test_openapi_schema():
)
-@needs_pydanticv2
def test_openapi_schema_no_separate():
client = get_app_client(separate_input_output_schemas=False)
response = client.get("/openapi.json")
diff --git a/tests/test_openapi_servers.py b/tests/test_openapi_servers.py
index 8697c8438b..33079e4b1d 100644
--- a/tests/test_openapi_servers.py
+++ b/tests/test_openapi_servers.py
@@ -1,6 +1,6 @@
-from dirty_equals import IsOneOf
from fastapi import FastAPI
from fastapi.testclient import TestClient
+from inline_snapshot import snapshot
app = FastAPI(
servers=[
@@ -30,39 +30,31 @@ def test_app():
def test_openapi_schema():
response = client.get("/openapi.json")
assert response.status_code == 200, response.text
- assert response.json() == {
- "openapi": "3.1.0",
- "info": {"title": "FastAPI", "version": "0.1.0"},
- "servers": [
- {"url": "/", "description": "Default, relative server"},
- {
- "url": IsOneOf(
- "http://staging.localhost.tiangolo.com:8000/",
- # TODO: remove when deprecating Pydantic v1
- "http://staging.localhost.tiangolo.com:8000",
- ),
- "description": "Staging but actually localhost still",
- },
- {
- "url": IsOneOf(
- "https://prod.example.com/",
- # TODO: remove when deprecating Pydantic v1
- "https://prod.example.com",
- )
- },
- ],
- "paths": {
- "/foo": {
- "get": {
- "summary": "Foo",
- "operationId": "foo_foo_get",
- "responses": {
- "200": {
- "description": "Successful Response",
- "content": {"application/json": {"schema": {}}},
- }
- },
+ assert response.json() == snapshot(
+ {
+ "openapi": "3.1.0",
+ "info": {"title": "FastAPI", "version": "0.1.0"},
+ "servers": [
+ {"url": "/", "description": "Default, relative server"},
+ {
+ "url": "http://staging.localhost.tiangolo.com:8000",
+ "description": "Staging but actually localhost still",
+ },
+ {"url": "https://prod.example.com"},
+ ],
+ "paths": {
+ "/foo": {
+ "get": {
+ "summary": "Foo",
+ "operationId": "foo_foo_get",
+ "responses": {
+ "200": {
+ "description": "Successful Response",
+ "content": {"application/json": {"schema": {}}},
+ }
+ },
+ }
}
- }
- },
- }
+ },
+ }
+ )
diff --git a/tests/test_optional_file_list.py b/tests/test_optional_file_list.py
index 0228900cf6..6860258643 100644
--- a/tests/test_optional_file_list.py
+++ b/tests/test_optional_file_list.py
@@ -1,4 +1,4 @@
-from typing import List, Optional
+from typing import Optional
from fastapi import FastAPI, File
from fastapi.testclient import TestClient
@@ -7,7 +7,7 @@ app = FastAPI()
@app.post("/files")
-async def upload_files(files: Optional[List[bytes]] = File(None)):
+async def upload_files(files: Optional[list[bytes]] = File(None)):
if files is None:
return {"files_count": 0}
return {"files_count": len(files), "sizes": [len(f) for f in files]}
diff --git a/tests/test_params_repr.py b/tests/test_params_repr.py
index baa172497d..670e4f5ddf 100644
--- a/tests/test_params_repr.py
+++ b/tests/test_params_repr.py
@@ -1,9 +1,8 @@
-from typing import Any, List
+from typing import Any
-from dirty_equals import IsOneOf
from fastapi.params import Body, Cookie, Header, Param, Path, Query
-test_data: List[Any] = ["teststr", None, ..., 1, []]
+test_data: list[Any] = ["teststr", None, ..., 1, []]
def get_user():
@@ -19,11 +18,7 @@ def test_param_repr_none():
def test_param_repr_ellipsis():
- assert repr(Param(...)) == IsOneOf(
- "Param(PydanticUndefined)",
- # TODO: remove when deprecating Pydantic v1
- "Param(Ellipsis)",
- )
+ assert repr(Param(...)) == "Param(PydanticUndefined)"
def test_param_repr_number():
@@ -35,16 +30,8 @@ def test_param_repr_list():
def test_path_repr():
- assert repr(Path()) == IsOneOf(
- "Path(PydanticUndefined)",
- # TODO: remove when deprecating Pydantic v1
- "Path(Ellipsis)",
- )
- assert repr(Path(...)) == IsOneOf(
- "Path(PydanticUndefined)",
- # TODO: remove when deprecating Pydantic v1
- "Path(Ellipsis)",
- )
+ assert repr(Path()) == "Path(PydanticUndefined)"
+ assert repr(Path(...)) == "Path(PydanticUndefined)"
def test_query_repr_str():
@@ -56,11 +43,7 @@ def test_query_repr_none():
def test_query_repr_ellipsis():
- assert repr(Query(...)) == IsOneOf(
- "Query(PydanticUndefined)",
- # TODO: remove when deprecating Pydantic v1
- "Query(Ellipsis)",
- )
+ assert repr(Query(...)) == "Query(PydanticUndefined)"
def test_query_repr_number():
@@ -80,11 +63,7 @@ def test_header_repr_none():
def test_header_repr_ellipsis():
- assert repr(Header(...)) == IsOneOf(
- "Header(PydanticUndefined)",
- # TODO: remove when deprecating Pydantic v1
- "Header(Ellipsis)",
- )
+ assert repr(Header(...)) == "Header(PydanticUndefined)"
def test_header_repr_number():
@@ -104,11 +83,7 @@ def test_cookie_repr_none():
def test_cookie_repr_ellipsis():
- assert repr(Cookie(...)) == IsOneOf(
- "Cookie(PydanticUndefined)",
- # TODO: remove when deprecating Pydantic v1
- "Cookie(Ellipsis)",
- )
+ assert repr(Cookie(...)) == "Cookie(PydanticUndefined)"
def test_cookie_repr_number():
@@ -128,11 +103,7 @@ def test_body_repr_none():
def test_body_repr_ellipsis():
- assert repr(Body(...)) == IsOneOf(
- "Body(PydanticUndefined)",
- # TODO: remove when deprecating Pydantic v1
- "Body(Ellipsis)",
- )
+ assert repr(Body(...)) == "Body(PydanticUndefined)"
def test_body_repr_number():
diff --git a/tests/test_path.py b/tests/test_path.py
index 09c1f13fb1..47051b927c 100644
--- a/tests/test_path.py
+++ b/tests/test_path.py
@@ -1,4 +1,3 @@
-from dirty_equals import IsDict
from fastapi.testclient import TestClient
from .main import app
@@ -45,57 +44,31 @@ def test_path_str_True():
def test_path_int_foobar():
response = client.get("/path/int/foobar")
assert response.status_code == 422
- assert response.json() == IsDict(
- {
- "detail": [
- {
- "type": "int_parsing",
- "loc": ["path", "item_id"],
- "msg": "Input should be a valid integer, unable to parse string as an integer",
- "input": "foobar",
- }
- ]
- }
- ) | IsDict(
- # TODO: remove when deprecating Pydantic v1
- {
- "detail": [
- {
- "loc": ["path", "item_id"],
- "msg": "value is not a valid integer",
- "type": "type_error.integer",
- }
- ]
- }
- )
+ assert response.json() == {
+ "detail": [
+ {
+ "type": "int_parsing",
+ "loc": ["path", "item_id"],
+ "msg": "Input should be a valid integer, unable to parse string as an integer",
+ "input": "foobar",
+ }
+ ]
+ }
def test_path_int_True():
response = client.get("/path/int/True")
assert response.status_code == 422
- assert response.json() == IsDict(
- {
- "detail": [
- {
- "type": "int_parsing",
- "loc": ["path", "item_id"],
- "msg": "Input should be a valid integer, unable to parse string as an integer",
- "input": "True",
- }
- ]
- }
- ) | IsDict(
- # TODO: remove when deprecating Pydantic v1
- {
- "detail": [
- {
- "loc": ["path", "item_id"],
- "msg": "value is not a valid integer",
- "type": "type_error.integer",
- }
- ]
- }
- )
+ assert response.json() == {
+ "detail": [
+ {
+ "type": "int_parsing",
+ "loc": ["path", "item_id"],
+ "msg": "Input should be a valid integer, unable to parse string as an integer",
+ "input": "True",
+ }
+ ]
+ }
def test_path_int_42():
@@ -107,85 +80,46 @@ def test_path_int_42():
def test_path_int_42_5():
response = client.get("/path/int/42.5")
assert response.status_code == 422
- assert response.json() == IsDict(
- {
- "detail": [
- {
- "type": "int_parsing",
- "loc": ["path", "item_id"],
- "msg": "Input should be a valid integer, unable to parse string as an integer",
- "input": "42.5",
- }
- ]
- }
- ) | IsDict(
- # TODO: remove when deprecating Pydantic v1
- {
- "detail": [
- {
- "loc": ["path", "item_id"],
- "msg": "value is not a valid integer",
- "type": "type_error.integer",
- }
- ]
- }
- )
+ assert response.json() == {
+ "detail": [
+ {
+ "type": "int_parsing",
+ "loc": ["path", "item_id"],
+ "msg": "Input should be a valid integer, unable to parse string as an integer",
+ "input": "42.5",
+ }
+ ]
+ }
def test_path_float_foobar():
response = client.get("/path/float/foobar")
assert response.status_code == 422
- assert response.json() == IsDict(
- {
- "detail": [
- {
- "type": "float_parsing",
- "loc": ["path", "item_id"],
- "msg": "Input should be a valid number, unable to parse string as a number",
- "input": "foobar",
- }
- ]
- }
- ) | IsDict(
- # TODO: remove when deprecating Pydantic v1
- {
- "detail": [
- {
- "loc": ["path", "item_id"],
- "msg": "value is not a valid float",
- "type": "type_error.float",
- }
- ]
- }
- )
+ assert response.json() == {
+ "detail": [
+ {
+ "type": "float_parsing",
+ "loc": ["path", "item_id"],
+ "msg": "Input should be a valid number, unable to parse string as a number",
+ "input": "foobar",
+ }
+ ]
+ }
def test_path_float_True():
response = client.get("/path/float/True")
assert response.status_code == 422
- assert response.json() == IsDict(
- {
- "detail": [
- {
- "type": "float_parsing",
- "loc": ["path", "item_id"],
- "msg": "Input should be a valid number, unable to parse string as a number",
- "input": "True",
- }
- ]
- }
- ) | IsDict(
- # TODO: remove when deprecating Pydantic v1
- {
- "detail": [
- {
- "loc": ["path", "item_id"],
- "msg": "value is not a valid float",
- "type": "type_error.float",
- }
- ]
- }
- )
+ assert response.json() == {
+ "detail": [
+ {
+ "type": "float_parsing",
+ "loc": ["path", "item_id"],
+ "msg": "Input should be a valid number, unable to parse string as a number",
+ "input": "True",
+ }
+ ]
+ }
def test_path_float_42():
@@ -203,29 +137,16 @@ def test_path_float_42_5():
def test_path_bool_foobar():
response = client.get("/path/bool/foobar")
assert response.status_code == 422
- assert response.json() == IsDict(
- {
- "detail": [
- {
- "type": "bool_parsing",
- "loc": ["path", "item_id"],
- "msg": "Input should be a valid boolean, unable to interpret input",
- "input": "foobar",
- }
- ]
- }
- ) | IsDict(
- # TODO: remove when deprecating Pydantic v1
- {
- "detail": [
- {
- "loc": ["path", "item_id"],
- "msg": "value could not be parsed to a boolean",
- "type": "type_error.bool",
- }
- ]
- }
- )
+ assert response.json() == {
+ "detail": [
+ {
+ "type": "bool_parsing",
+ "loc": ["path", "item_id"],
+ "msg": "Input should be a valid boolean, unable to interpret input",
+ "input": "foobar",
+ }
+ ]
+ }
def test_path_bool_True():
@@ -237,57 +158,31 @@ def test_path_bool_True():
def test_path_bool_42():
response = client.get("/path/bool/42")
assert response.status_code == 422
- assert response.json() == IsDict(
- {
- "detail": [
- {
- "type": "bool_parsing",
- "loc": ["path", "item_id"],
- "msg": "Input should be a valid boolean, unable to interpret input",
- "input": "42",
- }
- ]
- }
- ) | IsDict(
- # TODO: remove when deprecating Pydantic v1
- {
- "detail": [
- {
- "loc": ["path", "item_id"],
- "msg": "value could not be parsed to a boolean",
- "type": "type_error.bool",
- }
- ]
- }
- )
+ assert response.json() == {
+ "detail": [
+ {
+ "type": "bool_parsing",
+ "loc": ["path", "item_id"],
+ "msg": "Input should be a valid boolean, unable to interpret input",
+ "input": "42",
+ }
+ ]
+ }
def test_path_bool_42_5():
response = client.get("/path/bool/42.5")
assert response.status_code == 422
- assert response.json() == IsDict(
- {
- "detail": [
- {
- "type": "bool_parsing",
- "loc": ["path", "item_id"],
- "msg": "Input should be a valid boolean, unable to interpret input",
- "input": "42.5",
- }
- ]
- }
- ) | IsDict(
- # TODO: remove when deprecating Pydantic v1
- {
- "detail": [
- {
- "loc": ["path", "item_id"],
- "msg": "value could not be parsed to a boolean",
- "type": "type_error.bool",
- }
- ]
- }
- )
+ assert response.json() == {
+ "detail": [
+ {
+ "type": "bool_parsing",
+ "loc": ["path", "item_id"],
+ "msg": "Input should be a valid boolean, unable to interpret input",
+ "input": "42.5",
+ }
+ ]
+ }
def test_path_bool_1():
@@ -335,31 +230,17 @@ def test_path_param_minlength_foo():
def test_path_param_minlength_fo():
response = client.get("/path/param-minlength/fo")
assert response.status_code == 422
- assert response.json() == IsDict(
- {
- "detail": [
- {
- "type": "string_too_short",
- "loc": ["path", "item_id"],
- "msg": "String should have at least 3 characters",
- "input": "fo",
- "ctx": {"min_length": 3},
- }
- ]
- }
- ) | IsDict(
- # TODO: remove when deprecating Pydantic v1
- {
- "detail": [
- {
- "loc": ["path", "item_id"],
- "msg": "ensure this value has at least 3 characters",
- "type": "value_error.any_str.min_length",
- "ctx": {"limit_value": 3},
- }
- ]
- }
- )
+ assert response.json() == {
+ "detail": [
+ {
+ "type": "string_too_short",
+ "loc": ["path", "item_id"],
+ "msg": "String should have at least 3 characters",
+ "input": "fo",
+ "ctx": {"min_length": 3},
+ }
+ ]
+ }
def test_path_param_maxlength_foo():
@@ -371,31 +252,17 @@ def test_path_param_maxlength_foo():
def test_path_param_maxlength_foobar():
response = client.get("/path/param-maxlength/foobar")
assert response.status_code == 422
- assert response.json() == IsDict(
- {
- "detail": [
- {
- "type": "string_too_long",
- "loc": ["path", "item_id"],
- "msg": "String should have at most 3 characters",
- "input": "foobar",
- "ctx": {"max_length": 3},
- }
- ]
- }
- ) | IsDict(
- # TODO: remove when deprecating Pydantic v1
- {
- "detail": [
- {
- "loc": ["path", "item_id"],
- "msg": "ensure this value has at most 3 characters",
- "type": "value_error.any_str.max_length",
- "ctx": {"limit_value": 3},
- }
- ]
- }
- )
+ assert response.json() == {
+ "detail": [
+ {
+ "type": "string_too_long",
+ "loc": ["path", "item_id"],
+ "msg": "String should have at most 3 characters",
+ "input": "foobar",
+ "ctx": {"max_length": 3},
+ }
+ ]
+ }
def test_path_param_min_maxlength_foo():
@@ -407,60 +274,33 @@ def test_path_param_min_maxlength_foo():
def test_path_param_min_maxlength_foobar():
response = client.get("/path/param-min_maxlength/foobar")
assert response.status_code == 422
- assert response.json() == IsDict(
- {
- "detail": [
- {
- "type": "string_too_long",
- "loc": ["path", "item_id"],
- "msg": "String should have at most 3 characters",
- "input": "foobar",
- "ctx": {"max_length": 3},
- }
- ]
- }
- ) | IsDict(
- # TODO: remove when deprecating Pydantic v1
- {
- "detail": [
- {
- "loc": ["path", "item_id"],
- "msg": "ensure this value has at most 3 characters",
- "type": "value_error.any_str.max_length",
- "ctx": {"limit_value": 3},
- }
- ]
- }
- )
+ assert response.json() == {
+ "detail": [
+ {
+ "type": "string_too_long",
+ "loc": ["path", "item_id"],
+ "msg": "String should have at most 3 characters",
+ "input": "foobar",
+ "ctx": {"max_length": 3},
+ }
+ ]
+ }
def test_path_param_min_maxlength_f():
response = client.get("/path/param-min_maxlength/f")
assert response.status_code == 422
- assert response.json() == IsDict(
- {
- "detail": [
- {
- "type": "string_too_short",
- "loc": ["path", "item_id"],
- "msg": "String should have at least 2 characters",
- "input": "f",
- "ctx": {"min_length": 2},
- }
- ]
- }
- ) | IsDict(
- {
- "detail": [
- {
- "loc": ["path", "item_id"],
- "msg": "ensure this value has at least 2 characters",
- "type": "value_error.any_str.min_length",
- "ctx": {"limit_value": 2},
- }
- ]
- }
- )
+ assert response.json() == {
+ "detail": [
+ {
+ "type": "string_too_short",
+ "loc": ["path", "item_id"],
+ "msg": "String should have at least 2 characters",
+ "input": "f",
+ "ctx": {"min_length": 2},
+ }
+ ]
+ }
def test_path_param_gt_42():
@@ -472,31 +312,17 @@ def test_path_param_gt_42():
def test_path_param_gt_2():
response = client.get("/path/param-gt/2")
assert response.status_code == 422
- assert response.json() == IsDict(
- {
- "detail": [
- {
- "type": "greater_than",
- "loc": ["path", "item_id"],
- "msg": "Input should be greater than 3",
- "input": "2",
- "ctx": {"gt": 3.0},
- }
- ]
- }
- ) | IsDict(
- # TODO: remove when deprecating Pydantic v1
- {
- "detail": [
- {
- "loc": ["path", "item_id"],
- "msg": "ensure this value is greater than 3",
- "type": "value_error.number.not_gt",
- "ctx": {"limit_value": 3},
- }
- ]
- }
- )
+ assert response.json() == {
+ "detail": [
+ {
+ "type": "greater_than",
+ "loc": ["path", "item_id"],
+ "msg": "Input should be greater than 3",
+ "input": "2",
+ "ctx": {"gt": 3.0},
+ }
+ ]
+ }
def test_path_param_gt0_0_05():
@@ -508,31 +334,17 @@ def test_path_param_gt0_0_05():
def test_path_param_gt0_0():
response = client.get("/path/param-gt0/0")
assert response.status_code == 422
- assert response.json() == IsDict(
- {
- "detail": [
- {
- "type": "greater_than",
- "loc": ["path", "item_id"],
- "msg": "Input should be greater than 0",
- "input": "0",
- "ctx": {"gt": 0.0},
- }
- ]
- }
- ) | IsDict(
- # TODO: remove when deprecating Pydantic v1
- {
- "detail": [
- {
- "loc": ["path", "item_id"],
- "msg": "ensure this value is greater than 0",
- "type": "value_error.number.not_gt",
- "ctx": {"limit_value": 0},
- }
- ]
- }
- )
+ assert response.json() == {
+ "detail": [
+ {
+ "type": "greater_than",
+ "loc": ["path", "item_id"],
+ "msg": "Input should be greater than 0",
+ "input": "0",
+ "ctx": {"gt": 0.0},
+ }
+ ]
+ }
def test_path_param_ge_42():
@@ -550,61 +362,33 @@ def test_path_param_ge_3():
def test_path_param_ge_2():
response = client.get("/path/param-ge/2")
assert response.status_code == 422
- assert response.json() == IsDict(
- {
- "detail": [
- {
- "type": "greater_than_equal",
- "loc": ["path", "item_id"],
- "msg": "Input should be greater than or equal to 3",
- "input": "2",
- "ctx": {"ge": 3.0},
- }
- ]
- }
- ) | IsDict(
- # TODO: remove when deprecating Pydantic v1
- {
- "detail": [
- {
- "loc": ["path", "item_id"],
- "msg": "ensure this value is greater than or equal to 3",
- "type": "value_error.number.not_ge",
- "ctx": {"limit_value": 3},
- }
- ]
- }
- )
+ assert response.json() == {
+ "detail": [
+ {
+ "type": "greater_than_equal",
+ "loc": ["path", "item_id"],
+ "msg": "Input should be greater than or equal to 3",
+ "input": "2",
+ "ctx": {"ge": 3.0},
+ }
+ ]
+ }
def test_path_param_lt_42():
response = client.get("/path/param-lt/42")
assert response.status_code == 422
- assert response.json() == IsDict(
- {
- "detail": [
- {
- "type": "less_than",
- "loc": ["path", "item_id"],
- "msg": "Input should be less than 3",
- "input": "42",
- "ctx": {"lt": 3.0},
- }
- ]
- }
- ) | IsDict(
- # TODO: remove when deprecating Pydantic v1
- {
- "detail": [
- {
- "loc": ["path", "item_id"],
- "msg": "ensure this value is less than 3",
- "type": "value_error.number.not_lt",
- "ctx": {"limit_value": 3},
- }
- ]
- }
- )
+ assert response.json() == {
+ "detail": [
+ {
+ "type": "less_than",
+ "loc": ["path", "item_id"],
+ "msg": "Input should be less than 3",
+ "input": "42",
+ "ctx": {"lt": 3.0},
+ }
+ ]
+ }
def test_path_param_lt_2():
@@ -622,61 +406,33 @@ def test_path_param_lt0__1():
def test_path_param_lt0_0():
response = client.get("/path/param-lt0/0")
assert response.status_code == 422
- assert response.json() == IsDict(
- {
- "detail": [
- {
- "type": "less_than",
- "loc": ["path", "item_id"],
- "msg": "Input should be less than 0",
- "input": "0",
- "ctx": {"lt": 0.0},
- }
- ]
- }
- ) | IsDict(
- # TODO: remove when deprecating Pydantic v1
- {
- "detail": [
- {
- "loc": ["path", "item_id"],
- "msg": "ensure this value is less than 0",
- "type": "value_error.number.not_lt",
- "ctx": {"limit_value": 0},
- }
- ]
- }
- )
+ assert response.json() == {
+ "detail": [
+ {
+ "type": "less_than",
+ "loc": ["path", "item_id"],
+ "msg": "Input should be less than 0",
+ "input": "0",
+ "ctx": {"lt": 0.0},
+ }
+ ]
+ }
def test_path_param_le_42():
response = client.get("/path/param-le/42")
assert response.status_code == 422
- assert response.json() == IsDict(
- {
- "detail": [
- {
- "type": "less_than_equal",
- "loc": ["path", "item_id"],
- "msg": "Input should be less than or equal to 3",
- "input": "42",
- "ctx": {"le": 3.0},
- }
- ]
- }
- ) | IsDict(
- # TODO: remove when deprecating Pydantic v1
- {
- "detail": [
- {
- "loc": ["path", "item_id"],
- "msg": "ensure this value is less than or equal to 3",
- "type": "value_error.number.not_le",
- "ctx": {"limit_value": 3},
- }
- ]
- }
- )
+ assert response.json() == {
+ "detail": [
+ {
+ "type": "less_than_equal",
+ "loc": ["path", "item_id"],
+ "msg": "Input should be less than or equal to 3",
+ "input": "42",
+ "ctx": {"le": 3.0},
+ }
+ ]
+ }
def test_path_param_le_3():
@@ -700,61 +456,33 @@ def test_path_param_lt_gt_2():
def test_path_param_lt_gt_4():
response = client.get("/path/param-lt-gt/4")
assert response.status_code == 422
- assert response.json() == IsDict(
- {
- "detail": [
- {
- "type": "less_than",
- "loc": ["path", "item_id"],
- "msg": "Input should be less than 3",
- "input": "4",
- "ctx": {"lt": 3.0},
- }
- ]
- }
- ) | IsDict(
- # TODO: remove when deprecating Pydantic v1
- {
- "detail": [
- {
- "loc": ["path", "item_id"],
- "msg": "ensure this value is less than 3",
- "type": "value_error.number.not_lt",
- "ctx": {"limit_value": 3},
- }
- ]
- }
- )
+ assert response.json() == {
+ "detail": [
+ {
+ "type": "less_than",
+ "loc": ["path", "item_id"],
+ "msg": "Input should be less than 3",
+ "input": "4",
+ "ctx": {"lt": 3.0},
+ }
+ ]
+ }
def test_path_param_lt_gt_0():
response = client.get("/path/param-lt-gt/0")
assert response.status_code == 422
- assert response.json() == IsDict(
- {
- "detail": [
- {
- "type": "greater_than",
- "loc": ["path", "item_id"],
- "msg": "Input should be greater than 1",
- "input": "0",
- "ctx": {"gt": 1.0},
- }
- ]
- }
- ) | IsDict(
- # TODO: remove when deprecating Pydantic v1
- {
- "detail": [
- {
- "loc": ["path", "item_id"],
- "msg": "ensure this value is greater than 1",
- "type": "value_error.number.not_gt",
- "ctx": {"limit_value": 1},
- }
- ]
- }
- )
+ assert response.json() == {
+ "detail": [
+ {
+ "type": "greater_than",
+ "loc": ["path", "item_id"],
+ "msg": "Input should be greater than 1",
+ "input": "0",
+ "ctx": {"gt": 1.0},
+ }
+ ]
+ }
def test_path_param_le_ge_2():
@@ -777,31 +505,17 @@ def test_path_param_le_ge_3():
def test_path_param_le_ge_4():
response = client.get("/path/param-le-ge/4")
assert response.status_code == 422
- assert response.json() == IsDict(
- {
- "detail": [
- {
- "type": "less_than_equal",
- "loc": ["path", "item_id"],
- "msg": "Input should be less than or equal to 3",
- "input": "4",
- "ctx": {"le": 3.0},
- }
- ]
- }
- ) | IsDict(
- # TODO: remove when deprecating Pydantic v1
- {
- "detail": [
- {
- "loc": ["path", "item_id"],
- "msg": "ensure this value is less than or equal to 3",
- "type": "value_error.number.not_le",
- "ctx": {"limit_value": 3},
- }
- ]
- }
- )
+ assert response.json() == {
+ "detail": [
+ {
+ "type": "less_than_equal",
+ "loc": ["path", "item_id"],
+ "msg": "Input should be less than or equal to 3",
+ "input": "4",
+ "ctx": {"le": 3.0},
+ }
+ ]
+ }
def test_path_param_lt_int_2():
@@ -813,59 +527,32 @@ def test_path_param_lt_int_2():
def test_path_param_lt_int_42():
response = client.get("/path/param-lt-int/42")
assert response.status_code == 422
- assert response.json() == IsDict(
- {
- "detail": [
- {
- "type": "less_than",
- "loc": ["path", "item_id"],
- "msg": "Input should be less than 3",
- "input": "42",
- "ctx": {"lt": 3},
- }
- ]
- }
- ) | IsDict(
- # TODO: remove when deprecating Pydantic v1
- {
- "detail": [
- {
- "loc": ["path", "item_id"],
- "msg": "ensure this value is less than 3",
- "type": "value_error.number.not_lt",
- "ctx": {"limit_value": 3},
- }
- ]
- }
- )
+ assert response.json() == {
+ "detail": [
+ {
+ "type": "less_than",
+ "loc": ["path", "item_id"],
+ "msg": "Input should be less than 3",
+ "input": "42",
+ "ctx": {"lt": 3},
+ }
+ ]
+ }
def test_path_param_lt_int_2_7():
response = client.get("/path/param-lt-int/2.7")
assert response.status_code == 422
- assert response.json() == IsDict(
- {
- "detail": [
- {
- "type": "int_parsing",
- "loc": ["path", "item_id"],
- "msg": "Input should be a valid integer, unable to parse string as an integer",
- "input": "2.7",
- }
- ]
- }
- ) | IsDict(
- # TODO: remove when deprecating Pydantic v1
- {
- "detail": [
- {
- "loc": ["path", "item_id"],
- "msg": "value is not a valid integer",
- "type": "type_error.integer",
- }
- ]
- }
- )
+ assert response.json() == {
+ "detail": [
+ {
+ "type": "int_parsing",
+ "loc": ["path", "item_id"],
+ "msg": "Input should be a valid integer, unable to parse string as an integer",
+ "input": "2.7",
+ }
+ ]
+ }
def test_path_param_gt_int_42():
@@ -877,89 +564,48 @@ def test_path_param_gt_int_42():
def test_path_param_gt_int_2():
response = client.get("/path/param-gt-int/2")
assert response.status_code == 422
- assert response.json() == IsDict(
- {
- "detail": [
- {
- "type": "greater_than",
- "loc": ["path", "item_id"],
- "msg": "Input should be greater than 3",
- "input": "2",
- "ctx": {"gt": 3},
- }
- ]
- }
- ) | IsDict(
- # TODO: remove when deprecating Pydantic v1
- {
- "detail": [
- {
- "loc": ["path", "item_id"],
- "msg": "ensure this value is greater than 3",
- "type": "value_error.number.not_gt",
- "ctx": {"limit_value": 3},
- }
- ]
- }
- )
+ assert response.json() == {
+ "detail": [
+ {
+ "type": "greater_than",
+ "loc": ["path", "item_id"],
+ "msg": "Input should be greater than 3",
+ "input": "2",
+ "ctx": {"gt": 3},
+ }
+ ]
+ }
def test_path_param_gt_int_2_7():
response = client.get("/path/param-gt-int/2.7")
assert response.status_code == 422
- assert response.json() == IsDict(
- {
- "detail": [
- {
- "type": "int_parsing",
- "loc": ["path", "item_id"],
- "msg": "Input should be a valid integer, unable to parse string as an integer",
- "input": "2.7",
- }
- ]
- }
- ) | IsDict(
- # TODO: remove when deprecating Pydantic v1
- {
- "detail": [
- {
- "loc": ["path", "item_id"],
- "msg": "value is not a valid integer",
- "type": "type_error.integer",
- }
- ]
- }
- )
+ assert response.json() == {
+ "detail": [
+ {
+ "type": "int_parsing",
+ "loc": ["path", "item_id"],
+ "msg": "Input should be a valid integer, unable to parse string as an integer",
+ "input": "2.7",
+ }
+ ]
+ }
def test_path_param_le_int_42():
response = client.get("/path/param-le-int/42")
assert response.status_code == 422
- assert response.json() == IsDict(
- {
- "detail": [
- {
- "type": "less_than_equal",
- "loc": ["path", "item_id"],
- "msg": "Input should be less than or equal to 3",
- "input": "42",
- "ctx": {"le": 3},
- }
- ]
- }
- ) | IsDict(
- # TODO: remove when deprecating Pydantic v1
- {
- "detail": [
- {
- "loc": ["path", "item_id"],
- "msg": "ensure this value is less than or equal to 3",
- "type": "value_error.number.not_le",
- "ctx": {"limit_value": 3},
- }
- ]
- }
- )
+ assert response.json() == {
+ "detail": [
+ {
+ "type": "less_than_equal",
+ "loc": ["path", "item_id"],
+ "msg": "Input should be less than or equal to 3",
+ "input": "42",
+ "ctx": {"le": 3},
+ }
+ ]
+ }
def test_path_param_le_int_3():
@@ -977,29 +623,16 @@ def test_path_param_le_int_2():
def test_path_param_le_int_2_7():
response = client.get("/path/param-le-int/2.7")
assert response.status_code == 422
- assert response.json() == IsDict(
- {
- "detail": [
- {
- "type": "int_parsing",
- "loc": ["path", "item_id"],
- "msg": "Input should be a valid integer, unable to parse string as an integer",
- "input": "2.7",
- }
- ]
- }
- ) | IsDict(
- # TODO: remove when deprecating Pydantic v1
- {
- "detail": [
- {
- "loc": ["path", "item_id"],
- "msg": "value is not a valid integer",
- "type": "type_error.integer",
- }
- ]
- }
- )
+ assert response.json() == {
+ "detail": [
+ {
+ "type": "int_parsing",
+ "loc": ["path", "item_id"],
+ "msg": "Input should be a valid integer, unable to parse string as an integer",
+ "input": "2.7",
+ }
+ ]
+ }
def test_path_param_ge_int_42():
@@ -1017,59 +650,32 @@ def test_path_param_ge_int_3():
def test_path_param_ge_int_2():
response = client.get("/path/param-ge-int/2")
assert response.status_code == 422
- assert response.json() == IsDict(
- {
- "detail": [
- {
- "type": "greater_than_equal",
- "loc": ["path", "item_id"],
- "msg": "Input should be greater than or equal to 3",
- "input": "2",
- "ctx": {"ge": 3},
- }
- ]
- }
- ) | IsDict(
- # TODO: remove when deprecating Pydantic v1
- {
- "detail": [
- {
- "loc": ["path", "item_id"],
- "msg": "ensure this value is greater than or equal to 3",
- "type": "value_error.number.not_ge",
- "ctx": {"limit_value": 3},
- }
- ]
- }
- )
+ assert response.json() == {
+ "detail": [
+ {
+ "type": "greater_than_equal",
+ "loc": ["path", "item_id"],
+ "msg": "Input should be greater than or equal to 3",
+ "input": "2",
+ "ctx": {"ge": 3},
+ }
+ ]
+ }
def test_path_param_ge_int_2_7():
response = client.get("/path/param-ge-int/2.7")
assert response.status_code == 422
- assert response.json() == IsDict(
- {
- "detail": [
- {
- "type": "int_parsing",
- "loc": ["path", "item_id"],
- "msg": "Input should be a valid integer, unable to parse string as an integer",
- "input": "2.7",
- }
- ]
- }
- ) | IsDict(
- # TODO: remove when deprecating Pydantic v1
- {
- "detail": [
- {
- "loc": ["path", "item_id"],
- "msg": "value is not a valid integer",
- "type": "type_error.integer",
- }
- ]
- }
- )
+ assert response.json() == {
+ "detail": [
+ {
+ "type": "int_parsing",
+ "loc": ["path", "item_id"],
+ "msg": "Input should be a valid integer, unable to parse string as an integer",
+ "input": "2.7",
+ }
+ ]
+ }
def test_path_param_lt_gt_int_2():
@@ -1081,89 +687,48 @@ def test_path_param_lt_gt_int_2():
def test_path_param_lt_gt_int_4():
response = client.get("/path/param-lt-gt-int/4")
assert response.status_code == 422
- assert response.json() == IsDict(
- {
- "detail": [
- {
- "type": "less_than",
- "loc": ["path", "item_id"],
- "msg": "Input should be less than 3",
- "input": "4",
- "ctx": {"lt": 3},
- }
- ]
- }
- ) | IsDict(
- # TODO: remove when deprecating Pydantic v1
- {
- "detail": [
- {
- "loc": ["path", "item_id"],
- "msg": "ensure this value is less than 3",
- "type": "value_error.number.not_lt",
- "ctx": {"limit_value": 3},
- }
- ]
- }
- )
+ assert response.json() == {
+ "detail": [
+ {
+ "type": "less_than",
+ "loc": ["path", "item_id"],
+ "msg": "Input should be less than 3",
+ "input": "4",
+ "ctx": {"lt": 3},
+ }
+ ]
+ }
def test_path_param_lt_gt_int_0():
response = client.get("/path/param-lt-gt-int/0")
assert response.status_code == 422
- assert response.json() == IsDict(
- {
- "detail": [
- {
- "type": "greater_than",
- "loc": ["path", "item_id"],
- "msg": "Input should be greater than 1",
- "input": "0",
- "ctx": {"gt": 1},
- }
- ]
- }
- ) | IsDict(
- # TODO: remove when deprecating Pydantic v1
- {
- "detail": [
- {
- "loc": ["path", "item_id"],
- "msg": "ensure this value is greater than 1",
- "type": "value_error.number.not_gt",
- "ctx": {"limit_value": 1},
- }
- ]
- }
- )
+ assert response.json() == {
+ "detail": [
+ {
+ "type": "greater_than",
+ "loc": ["path", "item_id"],
+ "msg": "Input should be greater than 1",
+ "input": "0",
+ "ctx": {"gt": 1},
+ }
+ ]
+ }
def test_path_param_lt_gt_int_2_7():
response = client.get("/path/param-lt-gt-int/2.7")
assert response.status_code == 422
- assert response.json() == IsDict(
- {
- "detail": [
- {
- "type": "int_parsing",
- "loc": ["path", "item_id"],
- "msg": "Input should be a valid integer, unable to parse string as an integer",
- "input": "2.7",
- }
- ]
- }
- ) | IsDict(
- # TODO: remove when deprecating Pydantic v1
- {
- "detail": [
- {
- "loc": ["path", "item_id"],
- "msg": "value is not a valid integer",
- "type": "type_error.integer",
- }
- ]
- }
- )
+ assert response.json() == {
+ "detail": [
+ {
+ "type": "int_parsing",
+ "loc": ["path", "item_id"],
+ "msg": "Input should be a valid integer, unable to parse string as an integer",
+ "input": "2.7",
+ }
+ ]
+ }
def test_path_param_le_ge_int_2():
@@ -1187,56 +752,29 @@ def test_path_param_le_ge_int_3():
def test_path_param_le_ge_int_4():
response = client.get("/path/param-le-ge-int/4")
assert response.status_code == 422
- assert response.json() == IsDict(
- {
- "detail": [
- {
- "type": "less_than_equal",
- "loc": ["path", "item_id"],
- "msg": "Input should be less than or equal to 3",
- "input": "4",
- "ctx": {"le": 3},
- }
- ]
- }
- ) | IsDict(
- # TODO: remove when deprecating Pydantic v1
- {
- "detail": [
- {
- "loc": ["path", "item_id"],
- "msg": "ensure this value is less than or equal to 3",
- "type": "value_error.number.not_le",
- "ctx": {"limit_value": 3},
- }
- ]
- }
- )
+ assert response.json() == {
+ "detail": [
+ {
+ "type": "less_than_equal",
+ "loc": ["path", "item_id"],
+ "msg": "Input should be less than or equal to 3",
+ "input": "4",
+ "ctx": {"le": 3},
+ }
+ ]
+ }
def test_path_param_le_ge_int_2_7():
response = client.get("/path/param-le-ge-int/2.7")
assert response.status_code == 422
- assert response.json() == IsDict(
- {
- "detail": [
- {
- "type": "int_parsing",
- "loc": ["path", "item_id"],
- "msg": "Input should be a valid integer, unable to parse string as an integer",
- "input": "2.7",
- }
- ]
- }
- ) | IsDict(
- # TODO: remove when deprecating Pydantic v1
- {
- "detail": [
- {
- "loc": ["path", "item_id"],
- "msg": "value is not a valid integer",
- "type": "type_error.integer",
- }
- ]
- }
- )
+ assert response.json() == {
+ "detail": [
+ {
+ "type": "int_parsing",
+ "loc": ["path", "item_id"],
+ "msg": "Input should be a valid integer, unable to parse string as an integer",
+ "input": "2.7",
+ }
+ ]
+ }
diff --git a/tests/test_pydantic_v1_error.py b/tests/test_pydantic_v1_error.py
new file mode 100644
index 0000000000..13229a3137
--- /dev/null
+++ b/tests/test_pydantic_v1_error.py
@@ -0,0 +1,97 @@
+import sys
+import warnings
+from typing import Union
+
+import pytest
+
+from tests.utils import skip_module_if_py_gte_314
+
+if sys.version_info >= (3, 14):
+ skip_module_if_py_gte_314()
+
+from fastapi import FastAPI
+from fastapi.exceptions import PydanticV1NotSupportedError
+
+with warnings.catch_warnings():
+ warnings.simplefilter("ignore", UserWarning)
+ from pydantic.v1 import BaseModel
+
+
+def test_raises_pydantic_v1_model_in_endpoint_param() -> None:
+ class ParamModelV1(BaseModel):
+ name: str
+
+ app = FastAPI()
+
+ with pytest.raises(PydanticV1NotSupportedError):
+
+ @app.post("/param")
+ def endpoint(data: ParamModelV1): # pragma: no cover
+ return data
+
+
+def test_raises_pydantic_v1_model_in_return_type() -> None:
+ class ReturnModelV1(BaseModel):
+ name: str
+
+ app = FastAPI()
+
+ with pytest.raises(PydanticV1NotSupportedError):
+
+ @app.get("/return")
+ def endpoint() -> ReturnModelV1: # pragma: no cover
+ return ReturnModelV1(name="test")
+
+
+def test_raises_pydantic_v1_model_in_response_model() -> None:
+ class ResponseModelV1(BaseModel):
+ name: str
+
+ app = FastAPI()
+
+ with pytest.raises(PydanticV1NotSupportedError):
+
+ @app.get("/response-model", response_model=ResponseModelV1)
+ def endpoint(): # pragma: no cover
+ return {"name": "test"}
+
+
+def test_raises_pydantic_v1_model_in_additional_responses_model() -> None:
+ class ErrorModelV1(BaseModel):
+ detail: str
+
+ app = FastAPI()
+
+ with pytest.raises(PydanticV1NotSupportedError):
+
+ @app.get(
+ "/responses", response_model=None, responses={400: {"model": ErrorModelV1}}
+ )
+ def endpoint(): # pragma: no cover
+ return {"ok": True}
+
+
+def test_raises_pydantic_v1_model_in_union() -> None:
+ class ModelV1A(BaseModel):
+ name: str
+
+ app = FastAPI()
+
+ with pytest.raises(PydanticV1NotSupportedError):
+
+ @app.post("/union")
+ def endpoint(data: Union[dict, ModelV1A]): # pragma: no cover
+ return data
+
+
+def test_raises_pydantic_v1_model_in_sequence() -> None:
+ class ModelV1A(BaseModel):
+ name: str
+
+ app = FastAPI()
+
+ with pytest.raises(PydanticV1NotSupportedError):
+
+ @app.post("/sequence")
+ def endpoint(data: list[ModelV1A]): # pragma: no cover
+ return data
diff --git a/tests/test_pydantic_v1_v2_01.py b/tests/test_pydantic_v1_v2_01.py
deleted file mode 100644
index 769e5fab62..0000000000
--- a/tests/test_pydantic_v1_v2_01.py
+++ /dev/null
@@ -1,475 +0,0 @@
-import sys
-from typing import Any, List, Union
-
-from tests.utils import pydantic_snapshot, skip_module_if_py_gte_314
-
-if sys.version_info >= (3, 14):
- skip_module_if_py_gte_314()
-
-from fastapi import FastAPI
-from fastapi._compat.v1 import BaseModel
-from fastapi.testclient import TestClient
-from inline_snapshot import snapshot
-
-
-class SubItem(BaseModel):
- name: str
-
-
-class Item(BaseModel):
- title: str
- size: int
- description: Union[str, None] = None
- sub: SubItem
- multi: List[SubItem] = []
-
-
-app = FastAPI()
-
-
-@app.post("/simple-model")
-def handle_simple_model(data: SubItem) -> SubItem:
- return data
-
-
-@app.post("/simple-model-filter", response_model=SubItem)
-def handle_simple_model_filter(data: SubItem) -> Any:
- extended_data = data.dict()
- extended_data.update({"secret_price": 42})
- return extended_data
-
-
-@app.post("/item")
-def handle_item(data: Item) -> Item:
- return data
-
-
-@app.post("/item-filter", response_model=Item)
-def handle_item_filter(data: Item) -> Any:
- extended_data = data.dict()
- extended_data.update({"secret_data": "classified", "internal_id": 12345})
- extended_data["sub"].update({"internal_id": 67890})
- return extended_data
-
-
-client = TestClient(app)
-
-
-def test_old_simple_model():
- response = client.post(
- "/simple-model",
- json={"name": "Foo"},
- )
- assert response.status_code == 200, response.text
- assert response.json() == {"name": "Foo"}
-
-
-def test_old_simple_model_validation_error():
- response = client.post(
- "/simple-model",
- json={"wrong_name": "Foo"},
- )
- assert response.status_code == 422, response.text
- assert response.json() == snapshot(
- {
- "detail": [
- {
- "loc": ["body", "name"],
- "msg": "field required",
- "type": "value_error.missing",
- }
- ]
- }
- )
-
-
-def test_old_simple_model_filter():
- response = client.post(
- "/simple-model-filter",
- json={"name": "Foo"},
- )
- assert response.status_code == 200, response.text
- assert response.json() == {"name": "Foo"}
-
-
-def test_item_model():
- response = client.post(
- "/item",
- json={
- "title": "Test Item",
- "size": 100,
- "description": "This is a test item",
- "sub": {"name": "SubItem1"},
- "multi": [{"name": "Multi1"}, {"name": "Multi2"}],
- },
- )
- assert response.status_code == 200, response.text
- assert response.json() == {
- "title": "Test Item",
- "size": 100,
- "description": "This is a test item",
- "sub": {"name": "SubItem1"},
- "multi": [{"name": "Multi1"}, {"name": "Multi2"}],
- }
-
-
-def test_item_model_minimal():
- response = client.post(
- "/item",
- json={"title": "Minimal Item", "size": 50, "sub": {"name": "SubMin"}},
- )
- assert response.status_code == 200, response.text
- assert response.json() == {
- "title": "Minimal Item",
- "size": 50,
- "description": None,
- "sub": {"name": "SubMin"},
- "multi": [],
- }
-
-
-def test_item_model_validation_errors():
- response = client.post(
- "/item",
- json={"title": "Missing fields"},
- )
- assert response.status_code == 422, response.text
- error_detail = response.json()["detail"]
- assert len(error_detail) == 2
- assert {
- "loc": ["body", "size"],
- "msg": "field required",
- "type": "value_error.missing",
- } in error_detail
- assert {
- "loc": ["body", "sub"],
- "msg": "field required",
- "type": "value_error.missing",
- } in error_detail
-
-
-def test_item_model_nested_validation_error():
- response = client.post(
- "/item",
- json={"title": "Test Item", "size": 100, "sub": {"wrong_field": "test"}},
- )
- assert response.status_code == 422, response.text
- assert response.json() == snapshot(
- {
- "detail": [
- {
- "loc": ["body", "sub", "name"],
- "msg": "field required",
- "type": "value_error.missing",
- }
- ]
- }
- )
-
-
-def test_item_model_invalid_type():
- response = client.post(
- "/item",
- json={"title": "Test Item", "size": "not_a_number", "sub": {"name": "SubItem"}},
- )
- assert response.status_code == 422, response.text
- assert response.json() == snapshot(
- {
- "detail": [
- {
- "loc": ["body", "size"],
- "msg": "value is not a valid integer",
- "type": "type_error.integer",
- }
- ]
- }
- )
-
-
-def test_item_filter():
- response = client.post(
- "/item-filter",
- json={
- "title": "Filtered Item",
- "size": 200,
- "description": "Test filtering",
- "sub": {"name": "SubFiltered"},
- "multi": [],
- },
- )
- assert response.status_code == 200, response.text
- result = response.json()
- assert result == {
- "title": "Filtered Item",
- "size": 200,
- "description": "Test filtering",
- "sub": {"name": "SubFiltered"},
- "multi": [],
- }
- assert "secret_data" not in result
- assert "internal_id" not in result
-
-
-def test_openapi_schema():
- response = client.get("/openapi.json")
- assert response.status_code == 200, response.text
- assert response.json() == snapshot(
- {
- "openapi": "3.1.0",
- "info": {"title": "FastAPI", "version": "0.1.0"},
- "paths": {
- "/simple-model": {
- "post": {
- "summary": "Handle Simple Model",
- "operationId": "handle_simple_model_simple_model_post",
- "requestBody": {
- "content": {
- "application/json": {
- "schema": pydantic_snapshot(
- v2=snapshot(
- {
- "allOf": [
- {
- "$ref": "#/components/schemas/SubItem"
- }
- ],
- "title": "Data",
- }
- ),
- v1=snapshot(
- {"$ref": "#/components/schemas/SubItem"}
- ),
- )
- }
- },
- "required": True,
- },
- "responses": {
- "200": {
- "description": "Successful Response",
- "content": {
- "application/json": {
- "schema": {
- "$ref": "#/components/schemas/SubItem"
- }
- }
- },
- },
- "422": {
- "description": "Validation Error",
- "content": {
- "application/json": {
- "schema": {
- "$ref": "#/components/schemas/HTTPValidationError"
- }
- }
- },
- },
- },
- }
- },
- "/simple-model-filter": {
- "post": {
- "summary": "Handle Simple Model Filter",
- "operationId": "handle_simple_model_filter_simple_model_filter_post",
- "requestBody": {
- "content": {
- "application/json": {
- "schema": pydantic_snapshot(
- v2=snapshot(
- {
- "allOf": [
- {
- "$ref": "#/components/schemas/SubItem"
- }
- ],
- "title": "Data",
- }
- ),
- v1=snapshot(
- {"$ref": "#/components/schemas/SubItem"}
- ),
- )
- }
- },
- "required": True,
- },
- "responses": {
- "200": {
- "description": "Successful Response",
- "content": {
- "application/json": {
- "schema": {
- "$ref": "#/components/schemas/SubItem"
- }
- }
- },
- },
- "422": {
- "description": "Validation Error",
- "content": {
- "application/json": {
- "schema": {
- "$ref": "#/components/schemas/HTTPValidationError"
- }
- }
- },
- },
- },
- }
- },
- "/item": {
- "post": {
- "summary": "Handle Item",
- "operationId": "handle_item_item_post",
- "requestBody": {
- "content": {
- "application/json": {
- "schema": pydantic_snapshot(
- v2=snapshot(
- {
- "allOf": [
- {
- "$ref": "#/components/schemas/Item"
- }
- ],
- "title": "Data",
- }
- ),
- v1=snapshot(
- {"$ref": "#/components/schemas/Item"}
- ),
- )
- }
- },
- "required": True,
- },
- "responses": {
- "200": {
- "description": "Successful Response",
- "content": {
- "application/json": {
- "schema": {"$ref": "#/components/schemas/Item"}
- }
- },
- },
- "422": {
- "description": "Validation Error",
- "content": {
- "application/json": {
- "schema": {
- "$ref": "#/components/schemas/HTTPValidationError"
- }
- }
- },
- },
- },
- }
- },
- "/item-filter": {
- "post": {
- "summary": "Handle Item Filter",
- "operationId": "handle_item_filter_item_filter_post",
- "requestBody": {
- "content": {
- "application/json": {
- "schema": pydantic_snapshot(
- v2=snapshot(
- {
- "allOf": [
- {
- "$ref": "#/components/schemas/Item"
- }
- ],
- "title": "Data",
- }
- ),
- v1=snapshot(
- {"$ref": "#/components/schemas/Item"}
- ),
- )
- }
- },
- "required": True,
- },
- "responses": {
- "200": {
- "description": "Successful Response",
- "content": {
- "application/json": {
- "schema": {"$ref": "#/components/schemas/Item"}
- }
- },
- },
- "422": {
- "description": "Validation Error",
- "content": {
- "application/json": {
- "schema": {
- "$ref": "#/components/schemas/HTTPValidationError"
- }
- }
- },
- },
- },
- }
- },
- },
- "components": {
- "schemas": {
- "HTTPValidationError": {
- "properties": {
- "detail": {
- "items": {
- "$ref": "#/components/schemas/ValidationError"
- },
- "type": "array",
- "title": "Detail",
- }
- },
- "type": "object",
- "title": "HTTPValidationError",
- },
- "Item": {
- "properties": {
- "title": {"type": "string", "title": "Title"},
- "size": {"type": "integer", "title": "Size"},
- "description": {"type": "string", "title": "Description"},
- "sub": {"$ref": "#/components/schemas/SubItem"},
- "multi": {
- "items": {"$ref": "#/components/schemas/SubItem"},
- "type": "array",
- "title": "Multi",
- "default": [],
- },
- },
- "type": "object",
- "required": ["title", "size", "sub"],
- "title": "Item",
- },
- "SubItem": {
- "properties": {"name": {"type": "string", "title": "Name"}},
- "type": "object",
- "required": ["name"],
- "title": "SubItem",
- },
- "ValidationError": {
- "properties": {
- "loc": {
- "items": {
- "anyOf": [{"type": "string"}, {"type": "integer"}]
- },
- "type": "array",
- "title": "Location",
- },
- "msg": {"type": "string", "title": "Message"},
- "type": {"type": "string", "title": "Error Type"},
- },
- "type": "object",
- "required": ["loc", "msg", "type"],
- "title": "ValidationError",
- },
- }
- },
- }
- )
diff --git a/tests/test_pydantic_v1_v2_list.py b/tests/test_pydantic_v1_v2_list.py
deleted file mode 100644
index 64f3dd3446..0000000000
--- a/tests/test_pydantic_v1_v2_list.py
+++ /dev/null
@@ -1,701 +0,0 @@
-import sys
-from typing import Any, List, Union
-
-from tests.utils import pydantic_snapshot, skip_module_if_py_gte_314
-
-if sys.version_info >= (3, 14):
- skip_module_if_py_gte_314()
-
-from fastapi import FastAPI
-from fastapi._compat.v1 import BaseModel
-from fastapi.testclient import TestClient
-from inline_snapshot import snapshot
-
-
-class SubItem(BaseModel):
- name: str
-
-
-class Item(BaseModel):
- title: str
- size: int
- description: Union[str, None] = None
- sub: SubItem
- multi: List[SubItem] = []
-
-
-app = FastAPI()
-
-
-@app.post("/item")
-def handle_item(data: Item) -> List[Item]:
- return [data, data]
-
-
-@app.post("/item-filter", response_model=List[Item])
-def handle_item_filter(data: Item) -> Any:
- extended_data = data.dict()
- extended_data.update({"secret_data": "classified", "internal_id": 12345})
- extended_data["sub"].update({"internal_id": 67890})
- return [extended_data, extended_data]
-
-
-@app.post("/item-list")
-def handle_item_list(data: List[Item]) -> Item:
- if data:
- return data[0]
- return Item(title="", size=0, sub=SubItem(name=""))
-
-
-@app.post("/item-list-filter", response_model=Item)
-def handle_item_list_filter(data: List[Item]) -> Any:
- if data:
- extended_data = data[0].dict()
- extended_data.update({"secret_data": "classified", "internal_id": 12345})
- extended_data["sub"].update({"internal_id": 67890})
- return extended_data
- return Item(title="", size=0, sub=SubItem(name=""))
-
-
-@app.post("/item-list-to-list")
-def handle_item_list_to_list(data: List[Item]) -> List[Item]:
- return data
-
-
-@app.post("/item-list-to-list-filter", response_model=List[Item])
-def handle_item_list_to_list_filter(data: List[Item]) -> Any:
- if data:
- extended_data = data[0].dict()
- extended_data.update({"secret_data": "classified", "internal_id": 12345})
- extended_data["sub"].update({"internal_id": 67890})
- return [extended_data, extended_data]
- return []
-
-
-client = TestClient(app)
-
-
-def test_item_to_list():
- response = client.post(
- "/item",
- json={
- "title": "Test Item",
- "size": 100,
- "description": "This is a test item",
- "sub": {"name": "SubItem1"},
- "multi": [{"name": "Multi1"}, {"name": "Multi2"}],
- },
- )
- assert response.status_code == 200, response.text
- result = response.json()
- assert isinstance(result, list)
- assert len(result) == 2
- for item in result:
- assert item == {
- "title": "Test Item",
- "size": 100,
- "description": "This is a test item",
- "sub": {"name": "SubItem1"},
- "multi": [{"name": "Multi1"}, {"name": "Multi2"}],
- }
-
-
-def test_item_to_list_filter():
- response = client.post(
- "/item-filter",
- json={
- "title": "Filtered Item",
- "size": 200,
- "description": "Test filtering",
- "sub": {"name": "SubFiltered"},
- "multi": [],
- },
- )
- assert response.status_code == 200, response.text
- result = response.json()
- assert isinstance(result, list)
- assert len(result) == 2
- for item in result:
- assert item == {
- "title": "Filtered Item",
- "size": 200,
- "description": "Test filtering",
- "sub": {"name": "SubFiltered"},
- "multi": [],
- }
- # Verify secret fields are filtered out
- assert "secret_data" not in item
- assert "internal_id" not in item
- assert "internal_id" not in item["sub"]
-
-
-def test_list_to_item():
- response = client.post(
- "/item-list",
- json=[
- {"title": "First Item", "size": 50, "sub": {"name": "First Sub"}},
- {"title": "Second Item", "size": 75, "sub": {"name": "Second Sub"}},
- ],
- )
- assert response.status_code == 200, response.text
- assert response.json() == {
- "title": "First Item",
- "size": 50,
- "description": None,
- "sub": {"name": "First Sub"},
- "multi": [],
- }
-
-
-def test_list_to_item_empty():
- response = client.post(
- "/item-list",
- json=[],
- )
- assert response.status_code == 200, response.text
- assert response.json() == {
- "title": "",
- "size": 0,
- "description": None,
- "sub": {"name": ""},
- "multi": [],
- }
-
-
-def test_list_to_item_filter():
- response = client.post(
- "/item-list-filter",
- json=[
- {
- "title": "First Item",
- "size": 100,
- "sub": {"name": "First Sub"},
- "multi": [{"name": "Multi1"}],
- },
- {"title": "Second Item", "size": 200, "sub": {"name": "Second Sub"}},
- ],
- )
- assert response.status_code == 200, response.text
- result = response.json()
- assert result == {
- "title": "First Item",
- "size": 100,
- "description": None,
- "sub": {"name": "First Sub"},
- "multi": [{"name": "Multi1"}],
- }
- # Verify secret fields are filtered out
- assert "secret_data" not in result
- assert "internal_id" not in result
-
-
-def test_list_to_item_filter_no_data():
- response = client.post("/item-list-filter", json=[])
- assert response.status_code == 200, response.text
- assert response.json() == {
- "title": "",
- "size": 0,
- "description": None,
- "sub": {"name": ""},
- "multi": [],
- }
-
-
-def test_list_to_list():
- input_items = [
- {"title": "Item 1", "size": 10, "sub": {"name": "Sub1"}},
- {
- "title": "Item 2",
- "size": 20,
- "description": "Second item",
- "sub": {"name": "Sub2"},
- "multi": [{"name": "M1"}, {"name": "M2"}],
- },
- {"title": "Item 3", "size": 30, "sub": {"name": "Sub3"}},
- ]
- response = client.post(
- "/item-list-to-list",
- json=input_items,
- )
- assert response.status_code == 200, response.text
- result = response.json()
- assert isinstance(result, list)
- assert len(result) == 3
- assert result[0] == {
- "title": "Item 1",
- "size": 10,
- "description": None,
- "sub": {"name": "Sub1"},
- "multi": [],
- }
- assert result[1] == {
- "title": "Item 2",
- "size": 20,
- "description": "Second item",
- "sub": {"name": "Sub2"},
- "multi": [{"name": "M1"}, {"name": "M2"}],
- }
- assert result[2] == {
- "title": "Item 3",
- "size": 30,
- "description": None,
- "sub": {"name": "Sub3"},
- "multi": [],
- }
-
-
-def test_list_to_list_filter():
- response = client.post(
- "/item-list-to-list-filter",
- json=[{"title": "Item 1", "size": 100, "sub": {"name": "Sub1"}}],
- )
- assert response.status_code == 200, response.text
- result = response.json()
- assert isinstance(result, list)
- assert len(result) == 2
- for item in result:
- assert item == {
- "title": "Item 1",
- "size": 100,
- "description": None,
- "sub": {"name": "Sub1"},
- "multi": [],
- }
- # Verify secret fields are filtered out
- assert "secret_data" not in item
- assert "internal_id" not in item
-
-
-def test_list_to_list_filter_no_data():
- response = client.post(
- "/item-list-to-list-filter",
- json=[],
- )
- assert response.status_code == 200, response.text
- assert response.json() == []
-
-
-def test_list_validation_error():
- response = client.post(
- "/item-list",
- json=[
- {"title": "Valid Item", "size": 100, "sub": {"name": "Sub1"}},
- {
- "title": "Invalid Item"
- # Missing required fields: size and sub
- },
- ],
- )
- assert response.status_code == 422, response.text
- error_detail = response.json()["detail"]
- assert len(error_detail) == 2
- assert {
- "loc": ["body", 1, "size"],
- "msg": "field required",
- "type": "value_error.missing",
- } in error_detail
- assert {
- "loc": ["body", 1, "sub"],
- "msg": "field required",
- "type": "value_error.missing",
- } in error_detail
-
-
-def test_list_nested_validation_error():
- response = client.post(
- "/item-list",
- json=[
- {"title": "Item with bad sub", "size": 100, "sub": {"wrong_field": "value"}}
- ],
- )
- assert response.status_code == 422, response.text
- assert response.json() == snapshot(
- {
- "detail": [
- {
- "loc": ["body", 0, "sub", "name"],
- "msg": "field required",
- "type": "value_error.missing",
- }
- ]
- }
- )
-
-
-def test_list_type_validation_error():
- response = client.post(
- "/item-list",
- json=[{"title": "Item", "size": "not_a_number", "sub": {"name": "Sub"}}],
- )
- assert response.status_code == 422, response.text
- assert response.json() == snapshot(
- {
- "detail": [
- {
- "loc": ["body", 0, "size"],
- "msg": "value is not a valid integer",
- "type": "type_error.integer",
- }
- ]
- }
- )
-
-
-def test_invalid_list_structure():
- response = client.post(
- "/item-list",
- json={"title": "Not a list", "size": 100, "sub": {"name": "Sub"}},
- )
- assert response.status_code == 422, response.text
- assert response.json() == snapshot(
- {
- "detail": [
- {
- "loc": ["body"],
- "msg": "value is not a valid list",
- "type": "type_error.list",
- }
- ]
- }
- )
-
-
-def test_openapi_schema():
- response = client.get("/openapi.json")
- assert response.status_code == 200, response.text
- assert response.json() == snapshot(
- {
- "openapi": "3.1.0",
- "info": {"title": "FastAPI", "version": "0.1.0"},
- "paths": {
- "/item": {
- "post": {
- "summary": "Handle Item",
- "operationId": "handle_item_item_post",
- "requestBody": {
- "content": {
- "application/json": {
- "schema": pydantic_snapshot(
- v2=snapshot(
- {
- "allOf": [
- {
- "$ref": "#/components/schemas/Item"
- }
- ],
- "title": "Data",
- }
- ),
- v1=snapshot(
- {"$ref": "#/components/schemas/Item"}
- ),
- )
- }
- },
- "required": True,
- },
- "responses": {
- "200": {
- "description": "Successful Response",
- "content": {
- "application/json": {
- "schema": {
- "items": {
- "$ref": "#/components/schemas/Item"
- },
- "type": "array",
- "title": "Response Handle Item Item Post",
- }
- }
- },
- },
- "422": {
- "description": "Validation Error",
- "content": {
- "application/json": {
- "schema": {
- "$ref": "#/components/schemas/HTTPValidationError"
- }
- }
- },
- },
- },
- }
- },
- "/item-filter": {
- "post": {
- "summary": "Handle Item Filter",
- "operationId": "handle_item_filter_item_filter_post",
- "requestBody": {
- "content": {
- "application/json": {
- "schema": pydantic_snapshot(
- v2=snapshot(
- {
- "allOf": [
- {
- "$ref": "#/components/schemas/Item"
- }
- ],
- "title": "Data",
- }
- ),
- v1=snapshot(
- {"$ref": "#/components/schemas/Item"}
- ),
- )
- }
- },
- "required": True,
- },
- "responses": {
- "200": {
- "description": "Successful Response",
- "content": {
- "application/json": {
- "schema": {
- "items": {
- "$ref": "#/components/schemas/Item"
- },
- "type": "array",
- "title": "Response Handle Item Filter Item Filter Post",
- }
- }
- },
- },
- "422": {
- "description": "Validation Error",
- "content": {
- "application/json": {
- "schema": {
- "$ref": "#/components/schemas/HTTPValidationError"
- }
- }
- },
- },
- },
- }
- },
- "/item-list": {
- "post": {
- "summary": "Handle Item List",
- "operationId": "handle_item_list_item_list_post",
- "requestBody": {
- "content": {
- "application/json": {
- "schema": {
- "items": {"$ref": "#/components/schemas/Item"},
- "type": "array",
- "title": "Data",
- }
- }
- },
- "required": True,
- },
- "responses": {
- "200": {
- "description": "Successful Response",
- "content": {
- "application/json": {
- "schema": {"$ref": "#/components/schemas/Item"}
- }
- },
- },
- "422": {
- "description": "Validation Error",
- "content": {
- "application/json": {
- "schema": {
- "$ref": "#/components/schemas/HTTPValidationError"
- }
- }
- },
- },
- },
- }
- },
- "/item-list-filter": {
- "post": {
- "summary": "Handle Item List Filter",
- "operationId": "handle_item_list_filter_item_list_filter_post",
- "requestBody": {
- "content": {
- "application/json": {
- "schema": {
- "items": {"$ref": "#/components/schemas/Item"},
- "type": "array",
- "title": "Data",
- }
- }
- },
- "required": True,
- },
- "responses": {
- "200": {
- "description": "Successful Response",
- "content": {
- "application/json": {
- "schema": {"$ref": "#/components/schemas/Item"}
- }
- },
- },
- "422": {
- "description": "Validation Error",
- "content": {
- "application/json": {
- "schema": {
- "$ref": "#/components/schemas/HTTPValidationError"
- }
- }
- },
- },
- },
- }
- },
- "/item-list-to-list": {
- "post": {
- "summary": "Handle Item List To List",
- "operationId": "handle_item_list_to_list_item_list_to_list_post",
- "requestBody": {
- "content": {
- "application/json": {
- "schema": {
- "items": {"$ref": "#/components/schemas/Item"},
- "type": "array",
- "title": "Data",
- }
- }
- },
- "required": True,
- },
- "responses": {
- "200": {
- "description": "Successful Response",
- "content": {
- "application/json": {
- "schema": {
- "items": {
- "$ref": "#/components/schemas/Item"
- },
- "type": "array",
- "title": "Response Handle Item List To List Item List To List Post",
- }
- }
- },
- },
- "422": {
- "description": "Validation Error",
- "content": {
- "application/json": {
- "schema": {
- "$ref": "#/components/schemas/HTTPValidationError"
- }
- }
- },
- },
- },
- }
- },
- "/item-list-to-list-filter": {
- "post": {
- "summary": "Handle Item List To List Filter",
- "operationId": "handle_item_list_to_list_filter_item_list_to_list_filter_post",
- "requestBody": {
- "content": {
- "application/json": {
- "schema": {
- "items": {"$ref": "#/components/schemas/Item"},
- "type": "array",
- "title": "Data",
- }
- }
- },
- "required": True,
- },
- "responses": {
- "200": {
- "description": "Successful Response",
- "content": {
- "application/json": {
- "schema": {
- "items": {
- "$ref": "#/components/schemas/Item"
- },
- "type": "array",
- "title": "Response Handle Item List To List Filter Item List To List Filter Post",
- }
- }
- },
- },
- "422": {
- "description": "Validation Error",
- "content": {
- "application/json": {
- "schema": {
- "$ref": "#/components/schemas/HTTPValidationError"
- }
- }
- },
- },
- },
- }
- },
- },
- "components": {
- "schemas": {
- "HTTPValidationError": {
- "properties": {
- "detail": {
- "items": {
- "$ref": "#/components/schemas/ValidationError"
- },
- "type": "array",
- "title": "Detail",
- }
- },
- "type": "object",
- "title": "HTTPValidationError",
- },
- "Item": {
- "properties": {
- "title": {"type": "string", "title": "Title"},
- "size": {"type": "integer", "title": "Size"},
- "description": {"type": "string", "title": "Description"},
- "sub": {"$ref": "#/components/schemas/SubItem"},
- "multi": {
- "items": {"$ref": "#/components/schemas/SubItem"},
- "type": "array",
- "title": "Multi",
- "default": [],
- },
- },
- "type": "object",
- "required": ["title", "size", "sub"],
- "title": "Item",
- },
- "SubItem": {
- "properties": {"name": {"type": "string", "title": "Name"}},
- "type": "object",
- "required": ["name"],
- "title": "SubItem",
- },
- "ValidationError": {
- "properties": {
- "loc": {
- "items": {
- "anyOf": [{"type": "string"}, {"type": "integer"}]
- },
- "type": "array",
- "title": "Location",
- },
- "msg": {"type": "string", "title": "Message"},
- "type": {"type": "string", "title": "Error Type"},
- },
- "type": "object",
- "required": ["loc", "msg", "type"],
- "title": "ValidationError",
- },
- }
- },
- }
- )
diff --git a/tests/test_pydantic_v1_v2_mixed.py b/tests/test_pydantic_v1_v2_mixed.py
deleted file mode 100644
index 54d408827f..0000000000
--- a/tests/test_pydantic_v1_v2_mixed.py
+++ /dev/null
@@ -1,1499 +0,0 @@
-import sys
-from typing import Any, List, Union
-
-from tests.utils import pydantic_snapshot, skip_module_if_py_gte_314
-
-if sys.version_info >= (3, 14):
- skip_module_if_py_gte_314()
-
-from fastapi import FastAPI
-from fastapi._compat.v1 import BaseModel
-from fastapi.testclient import TestClient
-from inline_snapshot import snapshot
-from pydantic import BaseModel as NewBaseModel
-
-
-class SubItem(BaseModel):
- name: str
-
-
-class Item(BaseModel):
- title: str
- size: int
- description: Union[str, None] = None
- sub: SubItem
- multi: List[SubItem] = []
-
-
-class NewSubItem(NewBaseModel):
- new_sub_name: str
-
-
-class NewItem(NewBaseModel):
- new_title: str
- new_size: int
- new_description: Union[str, None] = None
- new_sub: NewSubItem
- new_multi: List[NewSubItem] = []
-
-
-app = FastAPI()
-
-
-@app.post("/v1-to-v2/item")
-def handle_v1_item_to_v2(data: Item) -> NewItem:
- return NewItem(
- new_title=data.title,
- new_size=data.size,
- new_description=data.description,
- new_sub=NewSubItem(new_sub_name=data.sub.name),
- new_multi=[NewSubItem(new_sub_name=s.name) for s in data.multi],
- )
-
-
-@app.post("/v1-to-v2/item-filter", response_model=NewItem)
-def handle_v1_item_to_v2_filter(data: Item) -> Any:
- result = {
- "new_title": data.title,
- "new_size": data.size,
- "new_description": data.description,
- "new_sub": {"new_sub_name": data.sub.name, "new_sub_secret": "sub_hidden"},
- "new_multi": [
- {"new_sub_name": s.name, "new_sub_secret": "sub_hidden"} for s in data.multi
- ],
- "secret": "hidden_v1_to_v2",
- }
- return result
-
-
-@app.post("/v2-to-v1/item")
-def handle_v2_item_to_v1(data: NewItem) -> Item:
- return Item(
- title=data.new_title,
- size=data.new_size,
- description=data.new_description,
- sub=SubItem(name=data.new_sub.new_sub_name),
- multi=[SubItem(name=s.new_sub_name) for s in data.new_multi],
- )
-
-
-@app.post("/v2-to-v1/item-filter", response_model=Item)
-def handle_v2_item_to_v1_filter(data: NewItem) -> Any:
- result = {
- "title": data.new_title,
- "size": data.new_size,
- "description": data.new_description,
- "sub": {"name": data.new_sub.new_sub_name, "sub_secret": "sub_hidden"},
- "multi": [
- {"name": s.new_sub_name, "sub_secret": "sub_hidden"} for s in data.new_multi
- ],
- "secret": "hidden_v2_to_v1",
- }
- return result
-
-
-@app.post("/v1-to-v2/item-to-list")
-def handle_v1_item_to_v2_list(data: Item) -> List[NewItem]:
- converted = NewItem(
- new_title=data.title,
- new_size=data.size,
- new_description=data.description,
- new_sub=NewSubItem(new_sub_name=data.sub.name),
- new_multi=[NewSubItem(new_sub_name=s.name) for s in data.multi],
- )
- return [converted, converted]
-
-
-@app.post("/v1-to-v2/list-to-list")
-def handle_v1_list_to_v2_list(data: List[Item]) -> List[NewItem]:
- result = []
- for item in data:
- result.append(
- NewItem(
- new_title=item.title,
- new_size=item.size,
- new_description=item.description,
- new_sub=NewSubItem(new_sub_name=item.sub.name),
- new_multi=[NewSubItem(new_sub_name=s.name) for s in item.multi],
- )
- )
- return result
-
-
-@app.post("/v1-to-v2/list-to-list-filter", response_model=List[NewItem])
-def handle_v1_list_to_v2_list_filter(data: List[Item]) -> Any:
- result = []
- for item in data:
- converted = {
- "new_title": item.title,
- "new_size": item.size,
- "new_description": item.description,
- "new_sub": {"new_sub_name": item.sub.name, "new_sub_secret": "sub_hidden"},
- "new_multi": [
- {"new_sub_name": s.name, "new_sub_secret": "sub_hidden"}
- for s in item.multi
- ],
- "secret": "hidden_v2_to_v1",
- }
- result.append(converted)
- return result
-
-
-@app.post("/v1-to-v2/list-to-item")
-def handle_v1_list_to_v2_item(data: List[Item]) -> NewItem:
- if data:
- item = data[0]
- return NewItem(
- new_title=item.title,
- new_size=item.size,
- new_description=item.description,
- new_sub=NewSubItem(new_sub_name=item.sub.name),
- new_multi=[NewSubItem(new_sub_name=s.name) for s in item.multi],
- )
- return NewItem(new_title="", new_size=0, new_sub=NewSubItem(new_sub_name=""))
-
-
-@app.post("/v2-to-v1/item-to-list")
-def handle_v2_item_to_v1_list(data: NewItem) -> List[Item]:
- converted = Item(
- title=data.new_title,
- size=data.new_size,
- description=data.new_description,
- sub=SubItem(name=data.new_sub.new_sub_name),
- multi=[SubItem(name=s.new_sub_name) for s in data.new_multi],
- )
- return [converted, converted]
-
-
-@app.post("/v2-to-v1/list-to-list")
-def handle_v2_list_to_v1_list(data: List[NewItem]) -> List[Item]:
- result = []
- for item in data:
- result.append(
- Item(
- title=item.new_title,
- size=item.new_size,
- description=item.new_description,
- sub=SubItem(name=item.new_sub.new_sub_name),
- multi=[SubItem(name=s.new_sub_name) for s in item.new_multi],
- )
- )
- return result
-
-
-@app.post("/v2-to-v1/list-to-list-filter", response_model=List[Item])
-def handle_v2_list_to_v1_list_filter(data: List[NewItem]) -> Any:
- result = []
- for item in data:
- converted = {
- "title": item.new_title,
- "size": item.new_size,
- "description": item.new_description,
- "sub": {"name": item.new_sub.new_sub_name, "sub_secret": "sub_hidden"},
- "multi": [
- {"name": s.new_sub_name, "sub_secret": "sub_hidden"}
- for s in item.new_multi
- ],
- "secret": "hidden_v2_to_v1",
- }
- result.append(converted)
- return result
-
-
-@app.post("/v2-to-v1/list-to-item")
-def handle_v2_list_to_v1_item(data: List[NewItem]) -> Item:
- if data:
- item = data[0]
- return Item(
- title=item.new_title,
- size=item.new_size,
- description=item.new_description,
- sub=SubItem(name=item.new_sub.new_sub_name),
- multi=[SubItem(name=s.new_sub_name) for s in item.new_multi],
- )
- return Item(title="", size=0, sub=SubItem(name=""))
-
-
-client = TestClient(app)
-
-
-def test_v1_to_v2_item():
- response = client.post(
- "/v1-to-v2/item",
- json={
- "title": "Old Item",
- "size": 100,
- "description": "V1 description",
- "sub": {"name": "V1 Sub"},
- "multi": [{"name": "M1"}, {"name": "M2"}],
- },
- )
- assert response.status_code == 200, response.text
- assert response.json() == {
- "new_title": "Old Item",
- "new_size": 100,
- "new_description": "V1 description",
- "new_sub": {"new_sub_name": "V1 Sub"},
- "new_multi": [{"new_sub_name": "M1"}, {"new_sub_name": "M2"}],
- }
-
-
-def test_v1_to_v2_item_minimal():
- response = client.post(
- "/v1-to-v2/item",
- json={"title": "Minimal", "size": 50, "sub": {"name": "MinSub"}},
- )
- assert response.status_code == 200, response.text
- assert response.json() == {
- "new_title": "Minimal",
- "new_size": 50,
- "new_description": None,
- "new_sub": {"new_sub_name": "MinSub"},
- "new_multi": [],
- }
-
-
-def test_v1_to_v2_item_filter():
- response = client.post(
- "/v1-to-v2/item-filter",
- json={
- "title": "Filtered Item",
- "size": 50,
- "sub": {"name": "Sub"},
- "multi": [{"name": "Multi1"}],
- },
- )
- assert response.status_code == 200, response.text
- result = response.json()
- assert result == snapshot(
- {
- "new_title": "Filtered Item",
- "new_size": 50,
- "new_description": None,
- "new_sub": {"new_sub_name": "Sub"},
- "new_multi": [{"new_sub_name": "Multi1"}],
- }
- )
- # Verify secret fields are filtered out
- assert "secret" not in result
- assert "new_sub_secret" not in result["new_sub"]
- assert "new_sub_secret" not in result["new_multi"][0]
-
-
-def test_v2_to_v1_item():
- response = client.post(
- "/v2-to-v1/item",
- json={
- "new_title": "New Item",
- "new_size": 200,
- "new_description": "V2 description",
- "new_sub": {"new_sub_name": "V2 Sub"},
- "new_multi": [{"new_sub_name": "N1"}, {"new_sub_name": "N2"}],
- },
- )
- assert response.status_code == 200, response.text
- assert response.json() == {
- "title": "New Item",
- "size": 200,
- "description": "V2 description",
- "sub": {"name": "V2 Sub"},
- "multi": [{"name": "N1"}, {"name": "N2"}],
- }
-
-
-def test_v2_to_v1_item_minimal():
- response = client.post(
- "/v2-to-v1/item",
- json={
- "new_title": "MinimalNew",
- "new_size": 75,
- "new_sub": {"new_sub_name": "MinNewSub"},
- },
- )
- assert response.status_code == 200, response.text
- assert response.json() == {
- "title": "MinimalNew",
- "size": 75,
- "description": None,
- "sub": {"name": "MinNewSub"},
- "multi": [],
- }
-
-
-def test_v2_to_v1_item_filter():
- response = client.post(
- "/v2-to-v1/item-filter",
- json={
- "new_title": "Filtered New",
- "new_size": 75,
- "new_sub": {"new_sub_name": "NewSub"},
- "new_multi": [],
- },
- )
- assert response.status_code == 200, response.text
- result = response.json()
- assert result == snapshot(
- {
- "title": "Filtered New",
- "size": 75,
- "description": None,
- "sub": {"name": "NewSub"},
- "multi": [],
- }
- )
- # Verify secret fields are filtered out
- assert "secret" not in result
- assert "sub_secret" not in result["sub"]
-
-
-def test_v1_item_to_v2_list():
- response = client.post(
- "/v1-to-v2/item-to-list",
- json={
- "title": "Single to List",
- "size": 150,
- "description": "Convert to list",
- "sub": {"name": "Sub1"},
- "multi": [],
- },
- )
- assert response.status_code == 200, response.text
- result = response.json()
- assert result == [
- {
- "new_title": "Single to List",
- "new_size": 150,
- "new_description": "Convert to list",
- "new_sub": {"new_sub_name": "Sub1"},
- "new_multi": [],
- },
- {
- "new_title": "Single to List",
- "new_size": 150,
- "new_description": "Convert to list",
- "new_sub": {"new_sub_name": "Sub1"},
- "new_multi": [],
- },
- ]
-
-
-def test_v1_list_to_v2_list():
- response = client.post(
- "/v1-to-v2/list-to-list",
- json=[
- {"title": "Item1", "size": 10, "sub": {"name": "Sub1"}},
- {
- "title": "Item2",
- "size": 20,
- "description": "Second item",
- "sub": {"name": "Sub2"},
- "multi": [{"name": "M1"}, {"name": "M2"}],
- },
- {"title": "Item3", "size": 30, "sub": {"name": "Sub3"}},
- ],
- )
- assert response.status_code == 200, response.text
- assert response.json() == [
- {
- "new_title": "Item1",
- "new_size": 10,
- "new_description": None,
- "new_sub": {"new_sub_name": "Sub1"},
- "new_multi": [],
- },
- {
- "new_title": "Item2",
- "new_size": 20,
- "new_description": "Second item",
- "new_sub": {"new_sub_name": "Sub2"},
- "new_multi": [{"new_sub_name": "M1"}, {"new_sub_name": "M2"}],
- },
- {
- "new_title": "Item3",
- "new_size": 30,
- "new_description": None,
- "new_sub": {"new_sub_name": "Sub3"},
- "new_multi": [],
- },
- ]
-
-
-def test_v1_list_to_v2_list_filter():
- response = client.post(
- "/v1-to-v2/list-to-list-filter",
- json=[{"title": "FilterMe", "size": 30, "sub": {"name": "SubF"}}],
- )
- assert response.status_code == 200, response.text
- result = response.json()
- assert result == snapshot(
- [
- {
- "new_title": "FilterMe",
- "new_size": 30,
- "new_description": None,
- "new_sub": {"new_sub_name": "SubF"},
- "new_multi": [],
- }
- ]
- )
- # Verify secret fields are filtered out
- assert "secret" not in result[0]
- assert "new_sub_secret" not in result[0]["new_sub"]
-
-
-def test_v1_list_to_v2_item():
- response = client.post(
- "/v1-to-v2/list-to-item",
- json=[
- {"title": "First", "size": 100, "sub": {"name": "FirstSub"}},
- {"title": "Second", "size": 200, "sub": {"name": "SecondSub"}},
- ],
- )
- assert response.status_code == 200, response.text
- assert response.json() == {
- "new_title": "First",
- "new_size": 100,
- "new_description": None,
- "new_sub": {"new_sub_name": "FirstSub"},
- "new_multi": [],
- }
-
-
-def test_v1_list_to_v2_item_empty():
- response = client.post("/v1-to-v2/list-to-item", json=[])
- assert response.status_code == 200, response.text
- assert response.json() == {
- "new_title": "",
- "new_size": 0,
- "new_description": None,
- "new_sub": {"new_sub_name": ""},
- "new_multi": [],
- }
-
-
-def test_v2_item_to_v1_list():
- response = client.post(
- "/v2-to-v1/item-to-list",
- json={
- "new_title": "Single New",
- "new_size": 250,
- "new_description": "New to list",
- "new_sub": {"new_sub_name": "NewSub"},
- "new_multi": [],
- },
- )
- assert response.status_code == 200, response.text
- assert response.json() == [
- {
- "title": "Single New",
- "size": 250,
- "description": "New to list",
- "sub": {"name": "NewSub"},
- "multi": [],
- },
- {
- "title": "Single New",
- "size": 250,
- "description": "New to list",
- "sub": {"name": "NewSub"},
- "multi": [],
- },
- ]
-
-
-def test_v2_list_to_v1_list():
- response = client.post(
- "/v2-to-v1/list-to-list",
- json=[
- {"new_title": "New1", "new_size": 15, "new_sub": {"new_sub_name": "NS1"}},
- {
- "new_title": "New2",
- "new_size": 25,
- "new_description": "Second new",
- "new_sub": {"new_sub_name": "NS2"},
- "new_multi": [{"new_sub_name": "NM1"}],
- },
- ],
- )
- assert response.status_code == 200, response.text
- assert response.json() == [
- {
- "title": "New1",
- "size": 15,
- "description": None,
- "sub": {"name": "NS1"},
- "multi": [],
- },
- {
- "title": "New2",
- "size": 25,
- "description": "Second new",
- "sub": {"name": "NS2"},
- "multi": [{"name": "NM1"}],
- },
- ]
-
-
-def test_v2_list_to_v1_list_filter():
- response = client.post(
- "/v2-to-v1/list-to-list-filter",
- json=[
- {
- "new_title": "FilterNew",
- "new_size": 35,
- "new_sub": {"new_sub_name": "NSF"},
- }
- ],
- )
- assert response.status_code == 200, response.text
- result = response.json()
- assert result == snapshot(
- [
- {
- "title": "FilterNew",
- "size": 35,
- "description": None,
- "sub": {"name": "NSF"},
- "multi": [],
- }
- ]
- )
- # Verify secret fields are filtered out
- assert "secret" not in result[0]
- assert "sub_secret" not in result[0]["sub"]
-
-
-def test_v2_list_to_v1_item():
- response = client.post(
- "/v2-to-v1/list-to-item",
- json=[
- {
- "new_title": "FirstNew",
- "new_size": 300,
- "new_sub": {"new_sub_name": "FNS"},
- },
- {
- "new_title": "SecondNew",
- "new_size": 400,
- "new_sub": {"new_sub_name": "SNS"},
- },
- ],
- )
- assert response.status_code == 200, response.text
- assert response.json() == {
- "title": "FirstNew",
- "size": 300,
- "description": None,
- "sub": {"name": "FNS"},
- "multi": [],
- }
-
-
-def test_v2_list_to_v1_item_empty():
- response = client.post("/v2-to-v1/list-to-item", json=[])
- assert response.status_code == 200, response.text
- assert response.json() == {
- "title": "",
- "size": 0,
- "description": None,
- "sub": {"name": ""},
- "multi": [],
- }
-
-
-def test_v1_to_v2_validation_error():
- response = client.post("/v1-to-v2/item", json={"title": "Missing fields"})
- assert response.status_code == 422, response.text
- assert response.json() == snapshot(
- {
- "detail": [
- {
- "loc": ["body", "size"],
- "msg": "field required",
- "type": "value_error.missing",
- },
- {
- "loc": ["body", "sub"],
- "msg": "field required",
- "type": "value_error.missing",
- },
- ]
- }
- )
-
-
-def test_v1_to_v2_nested_validation_error():
- response = client.post(
- "/v1-to-v2/item",
- json={"title": "Bad sub", "size": 100, "sub": {"wrong_field": "value"}},
- )
- assert response.status_code == 422, response.text
- assert response.json() == snapshot(
- {
- "detail": [
- {
- "loc": ["body", "sub", "name"],
- "msg": "field required",
- "type": "value_error.missing",
- }
- ]
- }
- )
-
-
-def test_v1_to_v2_type_validation_error():
- response = client.post(
- "/v1-to-v2/item",
- json={"title": "Bad type", "size": "not_a_number", "sub": {"name": "Sub"}},
- )
- assert response.status_code == 422, response.text
- assert response.json() == snapshot(
- {
- "detail": [
- {
- "loc": ["body", "size"],
- "msg": "value is not a valid integer",
- "type": "type_error.integer",
- }
- ]
- }
- )
-
-
-def test_v2_to_v1_validation_error():
- response = client.post(
- "/v2-to-v1/item",
- json={"new_title": "Missing fields"},
- )
- assert response.status_code == 422, response.text
- assert response.json() == snapshot(
- {
- "detail": pydantic_snapshot(
- v2=snapshot(
- [
- {
- "type": "missing",
- "loc": ["body", "new_size"],
- "msg": "Field required",
- "input": {"new_title": "Missing fields"},
- },
- {
- "type": "missing",
- "loc": ["body", "new_sub"],
- "msg": "Field required",
- "input": {"new_title": "Missing fields"},
- },
- ]
- ),
- v1=snapshot(
- [
- {
- "loc": ["body", "new_size"],
- "msg": "field required",
- "type": "value_error.missing",
- },
- {
- "loc": ["body", "new_sub"],
- "msg": "field required",
- "type": "value_error.missing",
- },
- ]
- ),
- )
- }
- )
-
-
-def test_v2_to_v1_nested_validation_error():
- response = client.post(
- "/v2-to-v1/item",
- json={
- "new_title": "Bad sub",
- "new_size": 200,
- "new_sub": {"wrong_field": "value"},
- },
- )
- assert response.status_code == 422, response.text
- assert response.json() == snapshot(
- {
- "detail": [
- pydantic_snapshot(
- v2=snapshot(
- {
- "type": "missing",
- "loc": ["body", "new_sub", "new_sub_name"],
- "msg": "Field required",
- "input": {"wrong_field": "value"},
- }
- ),
- v1=snapshot(
- {
- "loc": ["body", "new_sub", "new_sub_name"],
- "msg": "field required",
- "type": "value_error.missing",
- }
- ),
- )
- ]
- }
- )
-
-
-def test_v1_list_validation_error():
- response = client.post(
- "/v1-to-v2/list-to-list",
- json=[
- {"title": "Valid", "size": 10, "sub": {"name": "S"}},
- {"title": "Invalid"},
- ],
- )
- assert response.status_code == 422, response.text
- assert response.json() == snapshot(
- {
- "detail": [
- {
- "loc": ["body", 1, "size"],
- "msg": "field required",
- "type": "value_error.missing",
- },
- {
- "loc": ["body", 1, "sub"],
- "msg": "field required",
- "type": "value_error.missing",
- },
- ]
- }
- )
-
-
-def test_v2_list_validation_error():
- response = client.post(
- "/v2-to-v1/list-to-list",
- json=[
- {"new_title": "Valid", "new_size": 10, "new_sub": {"new_sub_name": "NS"}},
- {"new_title": "Invalid"},
- ],
- )
- assert response.status_code == 422, response.text
- assert response.json() == snapshot(
- {
- "detail": pydantic_snapshot(
- v2=snapshot(
- [
- {
- "type": "missing",
- "loc": ["body", 1, "new_size"],
- "msg": "Field required",
- "input": {"new_title": "Invalid"},
- },
- {
- "type": "missing",
- "loc": ["body", 1, "new_sub"],
- "msg": "Field required",
- "input": {"new_title": "Invalid"},
- },
- ]
- ),
- v1=snapshot(
- [
- {
- "loc": ["body", 1, "new_size"],
- "msg": "field required",
- "type": "value_error.missing",
- },
- {
- "loc": ["body", 1, "new_sub"],
- "msg": "field required",
- "type": "value_error.missing",
- },
- ]
- ),
- )
- }
- )
-
-
-def test_invalid_list_structure_v1():
- response = client.post(
- "/v1-to-v2/list-to-list",
- json={"title": "Not a list", "size": 100, "sub": {"name": "Sub"}},
- )
- assert response.status_code == 422, response.text
- assert response.json() == snapshot(
- {
- "detail": [
- {
- "loc": ["body"],
- "msg": "value is not a valid list",
- "type": "type_error.list",
- }
- ]
- }
- )
-
-
-def test_invalid_list_structure_v2():
- response = client.post(
- "/v2-to-v1/list-to-list",
- json={
- "new_title": "Not a list",
- "new_size": 100,
- "new_sub": {"new_sub_name": "Sub"},
- },
- )
- assert response.status_code == 422, response.text
- assert response.json() == snapshot(
- {
- "detail": pydantic_snapshot(
- v2=snapshot(
- [
- {
- "type": "list_type",
- "loc": ["body"],
- "msg": "Input should be a valid list",
- "input": {
- "new_title": "Not a list",
- "new_size": 100,
- "new_sub": {"new_sub_name": "Sub"},
- },
- }
- ]
- ),
- v1=snapshot(
- [
- {
- "loc": ["body"],
- "msg": "value is not a valid list",
- "type": "type_error.list",
- }
- ]
- ),
- )
- }
- )
-
-
-def test_openapi_schema():
- response = client.get("/openapi.json")
- assert response.status_code == 200, response.text
- assert response.json() == snapshot(
- {
- "openapi": "3.1.0",
- "info": {"title": "FastAPI", "version": "0.1.0"},
- "paths": {
- "/v1-to-v2/item": {
- "post": {
- "summary": "Handle V1 Item To V2",
- "operationId": "handle_v1_item_to_v2_v1_to_v2_item_post",
- "requestBody": {
- "content": {
- "application/json": {
- "schema": pydantic_snapshot(
- v2=snapshot(
- {
- "allOf": [
- {
- "$ref": "#/components/schemas/Item"
- }
- ],
- "title": "Data",
- }
- ),
- v1=snapshot(
- {"$ref": "#/components/schemas/Item"}
- ),
- )
- }
- },
- "required": True,
- },
- "responses": {
- "200": {
- "description": "Successful Response",
- "content": {
- "application/json": {
- "schema": {
- "$ref": "#/components/schemas/NewItem"
- }
- }
- },
- },
- "422": {
- "description": "Validation Error",
- "content": {
- "application/json": {
- "schema": {
- "$ref": "#/components/schemas/HTTPValidationError"
- }
- }
- },
- },
- },
- }
- },
- "/v1-to-v2/item-filter": {
- "post": {
- "summary": "Handle V1 Item To V2 Filter",
- "operationId": "handle_v1_item_to_v2_filter_v1_to_v2_item_filter_post",
- "requestBody": {
- "content": {
- "application/json": {
- "schema": pydantic_snapshot(
- v2=snapshot(
- {
- "allOf": [
- {
- "$ref": "#/components/schemas/Item"
- }
- ],
- "title": "Data",
- }
- ),
- v1=snapshot(
- {"$ref": "#/components/schemas/Item"}
- ),
- )
- }
- },
- "required": True,
- },
- "responses": {
- "200": {
- "description": "Successful Response",
- "content": {
- "application/json": {
- "schema": {
- "$ref": "#/components/schemas/NewItem"
- }
- }
- },
- },
- "422": {
- "description": "Validation Error",
- "content": {
- "application/json": {
- "schema": {
- "$ref": "#/components/schemas/HTTPValidationError"
- }
- }
- },
- },
- },
- }
- },
- "/v2-to-v1/item": {
- "post": {
- "summary": "Handle V2 Item To V1",
- "operationId": "handle_v2_item_to_v1_v2_to_v1_item_post",
- "requestBody": {
- "content": {
- "application/json": {
- "schema": {"$ref": "#/components/schemas/NewItem"}
- }
- },
- "required": True,
- },
- "responses": {
- "200": {
- "description": "Successful Response",
- "content": {
- "application/json": {
- "schema": {"$ref": "#/components/schemas/Item"}
- }
- },
- },
- "422": {
- "description": "Validation Error",
- "content": {
- "application/json": {
- "schema": {
- "$ref": "#/components/schemas/HTTPValidationError"
- }
- }
- },
- },
- },
- }
- },
- "/v2-to-v1/item-filter": {
- "post": {
- "summary": "Handle V2 Item To V1 Filter",
- "operationId": "handle_v2_item_to_v1_filter_v2_to_v1_item_filter_post",
- "requestBody": {
- "content": {
- "application/json": {
- "schema": {"$ref": "#/components/schemas/NewItem"}
- }
- },
- "required": True,
- },
- "responses": {
- "200": {
- "description": "Successful Response",
- "content": {
- "application/json": {
- "schema": {"$ref": "#/components/schemas/Item"}
- }
- },
- },
- "422": {
- "description": "Validation Error",
- "content": {
- "application/json": {
- "schema": {
- "$ref": "#/components/schemas/HTTPValidationError"
- }
- }
- },
- },
- },
- }
- },
- "/v1-to-v2/item-to-list": {
- "post": {
- "summary": "Handle V1 Item To V2 List",
- "operationId": "handle_v1_item_to_v2_list_v1_to_v2_item_to_list_post",
- "requestBody": {
- "content": {
- "application/json": {
- "schema": pydantic_snapshot(
- v2=snapshot(
- {
- "allOf": [
- {
- "$ref": "#/components/schemas/Item"
- }
- ],
- "title": "Data",
- }
- ),
- v1=snapshot(
- {"$ref": "#/components/schemas/Item"}
- ),
- )
- }
- },
- "required": True,
- },
- "responses": {
- "200": {
- "description": "Successful Response",
- "content": {
- "application/json": {
- "schema": {
- "items": {
- "$ref": "#/components/schemas/NewItem"
- },
- "type": "array",
- "title": "Response Handle V1 Item To V2 List V1 To V2 Item To List Post",
- }
- }
- },
- },
- "422": {
- "description": "Validation Error",
- "content": {
- "application/json": {
- "schema": {
- "$ref": "#/components/schemas/HTTPValidationError"
- }
- }
- },
- },
- },
- }
- },
- "/v1-to-v2/list-to-list": {
- "post": {
- "summary": "Handle V1 List To V2 List",
- "operationId": "handle_v1_list_to_v2_list_v1_to_v2_list_to_list_post",
- "requestBody": {
- "content": {
- "application/json": {
- "schema": {
- "items": {"$ref": "#/components/schemas/Item"},
- "type": "array",
- "title": "Data",
- }
- }
- },
- "required": True,
- },
- "responses": {
- "200": {
- "description": "Successful Response",
- "content": {
- "application/json": {
- "schema": {
- "items": {
- "$ref": "#/components/schemas/NewItem"
- },
- "type": "array",
- "title": "Response Handle V1 List To V2 List V1 To V2 List To List Post",
- }
- }
- },
- },
- "422": {
- "description": "Validation Error",
- "content": {
- "application/json": {
- "schema": {
- "$ref": "#/components/schemas/HTTPValidationError"
- }
- }
- },
- },
- },
- }
- },
- "/v1-to-v2/list-to-list-filter": {
- "post": {
- "summary": "Handle V1 List To V2 List Filter",
- "operationId": "handle_v1_list_to_v2_list_filter_v1_to_v2_list_to_list_filter_post",
- "requestBody": {
- "content": {
- "application/json": {
- "schema": {
- "items": {"$ref": "#/components/schemas/Item"},
- "type": "array",
- "title": "Data",
- }
- }
- },
- "required": True,
- },
- "responses": {
- "200": {
- "description": "Successful Response",
- "content": {
- "application/json": {
- "schema": {
- "items": {
- "$ref": "#/components/schemas/NewItem"
- },
- "type": "array",
- "title": "Response Handle V1 List To V2 List Filter V1 To V2 List To List Filter Post",
- }
- }
- },
- },
- "422": {
- "description": "Validation Error",
- "content": {
- "application/json": {
- "schema": {
- "$ref": "#/components/schemas/HTTPValidationError"
- }
- }
- },
- },
- },
- }
- },
- "/v1-to-v2/list-to-item": {
- "post": {
- "summary": "Handle V1 List To V2 Item",
- "operationId": "handle_v1_list_to_v2_item_v1_to_v2_list_to_item_post",
- "requestBody": {
- "content": {
- "application/json": {
- "schema": {
- "items": {"$ref": "#/components/schemas/Item"},
- "type": "array",
- "title": "Data",
- }
- }
- },
- "required": True,
- },
- "responses": {
- "200": {
- "description": "Successful Response",
- "content": {
- "application/json": {
- "schema": {
- "$ref": "#/components/schemas/NewItem"
- }
- }
- },
- },
- "422": {
- "description": "Validation Error",
- "content": {
- "application/json": {
- "schema": {
- "$ref": "#/components/schemas/HTTPValidationError"
- }
- }
- },
- },
- },
- }
- },
- "/v2-to-v1/item-to-list": {
- "post": {
- "summary": "Handle V2 Item To V1 List",
- "operationId": "handle_v2_item_to_v1_list_v2_to_v1_item_to_list_post",
- "requestBody": {
- "content": {
- "application/json": {
- "schema": {"$ref": "#/components/schemas/NewItem"}
- }
- },
- "required": True,
- },
- "responses": {
- "200": {
- "description": "Successful Response",
- "content": {
- "application/json": {
- "schema": {
- "items": {
- "$ref": "#/components/schemas/Item"
- },
- "type": "array",
- "title": "Response Handle V2 Item To V1 List V2 To V1 Item To List Post",
- }
- }
- },
- },
- "422": {
- "description": "Validation Error",
- "content": {
- "application/json": {
- "schema": {
- "$ref": "#/components/schemas/HTTPValidationError"
- }
- }
- },
- },
- },
- }
- },
- "/v2-to-v1/list-to-list": {
- "post": {
- "summary": "Handle V2 List To V1 List",
- "operationId": "handle_v2_list_to_v1_list_v2_to_v1_list_to_list_post",
- "requestBody": {
- "content": {
- "application/json": {
- "schema": {
- "items": {
- "$ref": "#/components/schemas/NewItem"
- },
- "type": "array",
- "title": "Data",
- }
- }
- },
- "required": True,
- },
- "responses": {
- "200": {
- "description": "Successful Response",
- "content": {
- "application/json": {
- "schema": {
- "items": {
- "$ref": "#/components/schemas/Item"
- },
- "type": "array",
- "title": "Response Handle V2 List To V1 List V2 To V1 List To List Post",
- }
- }
- },
- },
- "422": {
- "description": "Validation Error",
- "content": {
- "application/json": {
- "schema": {
- "$ref": "#/components/schemas/HTTPValidationError"
- }
- }
- },
- },
- },
- }
- },
- "/v2-to-v1/list-to-list-filter": {
- "post": {
- "summary": "Handle V2 List To V1 List Filter",
- "operationId": "handle_v2_list_to_v1_list_filter_v2_to_v1_list_to_list_filter_post",
- "requestBody": {
- "content": {
- "application/json": {
- "schema": {
- "items": {
- "$ref": "#/components/schemas/NewItem"
- },
- "type": "array",
- "title": "Data",
- }
- }
- },
- "required": True,
- },
- "responses": {
- "200": {
- "description": "Successful Response",
- "content": {
- "application/json": {
- "schema": {
- "items": {
- "$ref": "#/components/schemas/Item"
- },
- "type": "array",
- "title": "Response Handle V2 List To V1 List Filter V2 To V1 List To List Filter Post",
- }
- }
- },
- },
- "422": {
- "description": "Validation Error",
- "content": {
- "application/json": {
- "schema": {
- "$ref": "#/components/schemas/HTTPValidationError"
- }
- }
- },
- },
- },
- }
- },
- "/v2-to-v1/list-to-item": {
- "post": {
- "summary": "Handle V2 List To V1 Item",
- "operationId": "handle_v2_list_to_v1_item_v2_to_v1_list_to_item_post",
- "requestBody": {
- "content": {
- "application/json": {
- "schema": {
- "items": {
- "$ref": "#/components/schemas/NewItem"
- },
- "type": "array",
- "title": "Data",
- }
- }
- },
- "required": True,
- },
- "responses": {
- "200": {
- "description": "Successful Response",
- "content": {
- "application/json": {
- "schema": {"$ref": "#/components/schemas/Item"}
- }
- },
- },
- "422": {
- "description": "Validation Error",
- "content": {
- "application/json": {
- "schema": {
- "$ref": "#/components/schemas/HTTPValidationError"
- }
- }
- },
- },
- },
- }
- },
- },
- "components": {
- "schemas": {
- "HTTPValidationError": {
- "properties": {
- "detail": {
- "items": {
- "$ref": "#/components/schemas/ValidationError"
- },
- "type": "array",
- "title": "Detail",
- }
- },
- "type": "object",
- "title": "HTTPValidationError",
- },
- "Item": {
- "properties": {
- "title": {"type": "string", "title": "Title"},
- "size": {"type": "integer", "title": "Size"},
- "description": {"type": "string", "title": "Description"},
- "sub": {"$ref": "#/components/schemas/SubItem"},
- "multi": {
- "items": {"$ref": "#/components/schemas/SubItem"},
- "type": "array",
- "title": "Multi",
- "default": [],
- },
- },
- "type": "object",
- "required": ["title", "size", "sub"],
- "title": "Item",
- },
- "NewItem": {
- "properties": {
- "new_title": {"type": "string", "title": "New Title"},
- "new_size": {"type": "integer", "title": "New Size"},
- "new_description": pydantic_snapshot(
- v2=snapshot(
- {
- "anyOf": [{"type": "string"}, {"type": "null"}],
- "title": "New Description",
- }
- ),
- v1=snapshot(
- {"type": "string", "title": "New Description"}
- ),
- ),
- "new_sub": {"$ref": "#/components/schemas/NewSubItem"},
- "new_multi": {
- "items": {"$ref": "#/components/schemas/NewSubItem"},
- "type": "array",
- "title": "New Multi",
- "default": [],
- },
- },
- "type": "object",
- "required": ["new_title", "new_size", "new_sub"],
- "title": "NewItem",
- },
- "NewSubItem": {
- "properties": {
- "new_sub_name": {"type": "string", "title": "New Sub Name"}
- },
- "type": "object",
- "required": ["new_sub_name"],
- "title": "NewSubItem",
- },
- "SubItem": {
- "properties": {"name": {"type": "string", "title": "Name"}},
- "type": "object",
- "required": ["name"],
- "title": "SubItem",
- },
- "ValidationError": {
- "properties": {
- "loc": {
- "items": {
- "anyOf": [{"type": "string"}, {"type": "integer"}]
- },
- "type": "array",
- "title": "Location",
- },
- "msg": {"type": "string", "title": "Message"},
- "type": {"type": "string", "title": "Error Type"},
- },
- "type": "object",
- "required": ["loc", "msg", "type"],
- "title": "ValidationError",
- },
- }
- },
- }
- )
diff --git a/tests/test_pydantic_v1_v2_multifile/main.py b/tests/test_pydantic_v1_v2_multifile/main.py
deleted file mode 100644
index 8985cb7b4c..0000000000
--- a/tests/test_pydantic_v1_v2_multifile/main.py
+++ /dev/null
@@ -1,142 +0,0 @@
-from typing import List
-
-from fastapi import FastAPI
-
-from . import modelsv1, modelsv2, modelsv2b
-
-app = FastAPI()
-
-
-@app.post("/v1-to-v2/item")
-def handle_v1_item_to_v2(data: modelsv1.Item) -> modelsv2.Item:
- return modelsv2.Item(
- new_title=data.title,
- new_size=data.size,
- new_description=data.description,
- new_sub=modelsv2.SubItem(new_sub_name=data.sub.name),
- new_multi=[modelsv2.SubItem(new_sub_name=s.name) for s in data.multi],
- )
-
-
-@app.post("/v2-to-v1/item")
-def handle_v2_item_to_v1(data: modelsv2.Item) -> modelsv1.Item:
- return modelsv1.Item(
- title=data.new_title,
- size=data.new_size,
- description=data.new_description,
- sub=modelsv1.SubItem(name=data.new_sub.new_sub_name),
- multi=[modelsv1.SubItem(name=s.new_sub_name) for s in data.new_multi],
- )
-
-
-@app.post("/v1-to-v2/item-to-list")
-def handle_v1_item_to_v2_list(data: modelsv1.Item) -> List[modelsv2.Item]:
- converted = modelsv2.Item(
- new_title=data.title,
- new_size=data.size,
- new_description=data.description,
- new_sub=modelsv2.SubItem(new_sub_name=data.sub.name),
- new_multi=[modelsv2.SubItem(new_sub_name=s.name) for s in data.multi],
- )
- return [converted, converted]
-
-
-@app.post("/v1-to-v2/list-to-list")
-def handle_v1_list_to_v2_list(data: List[modelsv1.Item]) -> List[modelsv2.Item]:
- result = []
- for item in data:
- result.append(
- modelsv2.Item(
- new_title=item.title,
- new_size=item.size,
- new_description=item.description,
- new_sub=modelsv2.SubItem(new_sub_name=item.sub.name),
- new_multi=[modelsv2.SubItem(new_sub_name=s.name) for s in item.multi],
- )
- )
- return result
-
-
-@app.post("/v1-to-v2/list-to-item")
-def handle_v1_list_to_v2_item(data: List[modelsv1.Item]) -> modelsv2.Item:
- if data:
- item = data[0]
- return modelsv2.Item(
- new_title=item.title,
- new_size=item.size,
- new_description=item.description,
- new_sub=modelsv2.SubItem(new_sub_name=item.sub.name),
- new_multi=[modelsv2.SubItem(new_sub_name=s.name) for s in item.multi],
- )
- return modelsv2.Item(
- new_title="", new_size=0, new_sub=modelsv2.SubItem(new_sub_name="")
- )
-
-
-@app.post("/v2-to-v1/item-to-list")
-def handle_v2_item_to_v1_list(data: modelsv2.Item) -> List[modelsv1.Item]:
- converted = modelsv1.Item(
- title=data.new_title,
- size=data.new_size,
- description=data.new_description,
- sub=modelsv1.SubItem(name=data.new_sub.new_sub_name),
- multi=[modelsv1.SubItem(name=s.new_sub_name) for s in data.new_multi],
- )
- return [converted, converted]
-
-
-@app.post("/v2-to-v1/list-to-list")
-def handle_v2_list_to_v1_list(data: List[modelsv2.Item]) -> List[modelsv1.Item]:
- result = []
- for item in data:
- result.append(
- modelsv1.Item(
- title=item.new_title,
- size=item.new_size,
- description=item.new_description,
- sub=modelsv1.SubItem(name=item.new_sub.new_sub_name),
- multi=[modelsv1.SubItem(name=s.new_sub_name) for s in item.new_multi],
- )
- )
- return result
-
-
-@app.post("/v2-to-v1/list-to-item")
-def handle_v2_list_to_v1_item(data: List[modelsv2.Item]) -> modelsv1.Item:
- if data:
- item = data[0]
- return modelsv1.Item(
- title=item.new_title,
- size=item.new_size,
- description=item.new_description,
- sub=modelsv1.SubItem(name=item.new_sub.new_sub_name),
- multi=[modelsv1.SubItem(name=s.new_sub_name) for s in item.new_multi],
- )
- return modelsv1.Item(title="", size=0, sub=modelsv1.SubItem(name=""))
-
-
-@app.post("/v2-to-v1/same-name")
-def handle_v2_same_name_to_v1(
- item1: modelsv2.Item, item2: modelsv2b.Item
-) -> modelsv1.Item:
- return modelsv1.Item(
- title=item1.new_title,
- size=item2.dup_size,
- description=item1.new_description,
- sub=modelsv1.SubItem(name=item1.new_sub.new_sub_name),
- multi=[modelsv1.SubItem(name=s.dup_sub_name) for s in item2.dup_multi],
- )
-
-
-@app.post("/v2-to-v1/list-of-items-to-list-of-items")
-def handle_v2_items_in_list_to_v1_item_in_list(
- data1: List[modelsv2.ItemInList], data2: List[modelsv2b.ItemInList]
-) -> List[modelsv1.ItemInList]:
- result = []
- item1 = data1[0]
- item2 = data2[0]
- result = [
- modelsv1.ItemInList(name1=item1.name2),
- modelsv1.ItemInList(name1=item2.dup_name2),
- ]
- return result
diff --git a/tests/test_pydantic_v1_v2_multifile/modelsv1.py b/tests/test_pydantic_v1_v2_multifile/modelsv1.py
deleted file mode 100644
index 889291a1a7..0000000000
--- a/tests/test_pydantic_v1_v2_multifile/modelsv1.py
+++ /dev/null
@@ -1,19 +0,0 @@
-from typing import List, Union
-
-from fastapi._compat.v1 import BaseModel
-
-
-class SubItem(BaseModel):
- name: str
-
-
-class Item(BaseModel):
- title: str
- size: int
- description: Union[str, None] = None
- sub: SubItem
- multi: List[SubItem] = []
-
-
-class ItemInList(BaseModel):
- name1: str
diff --git a/tests/test_pydantic_v1_v2_multifile/modelsv2.py b/tests/test_pydantic_v1_v2_multifile/modelsv2.py
deleted file mode 100644
index 2c8c6ea356..0000000000
--- a/tests/test_pydantic_v1_v2_multifile/modelsv2.py
+++ /dev/null
@@ -1,19 +0,0 @@
-from typing import List, Union
-
-from pydantic import BaseModel
-
-
-class SubItem(BaseModel):
- new_sub_name: str
-
-
-class Item(BaseModel):
- new_title: str
- new_size: int
- new_description: Union[str, None] = None
- new_sub: SubItem
- new_multi: List[SubItem] = []
-
-
-class ItemInList(BaseModel):
- name2: str
diff --git a/tests/test_pydantic_v1_v2_multifile/modelsv2b.py b/tests/test_pydantic_v1_v2_multifile/modelsv2b.py
deleted file mode 100644
index dc0c06c669..0000000000
--- a/tests/test_pydantic_v1_v2_multifile/modelsv2b.py
+++ /dev/null
@@ -1,19 +0,0 @@
-from typing import List, Union
-
-from pydantic import BaseModel
-
-
-class SubItem(BaseModel):
- dup_sub_name: str
-
-
-class Item(BaseModel):
- dup_title: str
- dup_size: int
- dup_description: Union[str, None] = None
- dup_sub: SubItem
- dup_multi: List[SubItem] = []
-
-
-class ItemInList(BaseModel):
- dup_name2: str
diff --git a/tests/test_pydantic_v1_v2_multifile/test_multifile.py b/tests/test_pydantic_v1_v2_multifile/test_multifile.py
deleted file mode 100644
index e66d102fb3..0000000000
--- a/tests/test_pydantic_v1_v2_multifile/test_multifile.py
+++ /dev/null
@@ -1,1226 +0,0 @@
-import sys
-
-from tests.utils import pydantic_snapshot, skip_module_if_py_gte_314
-
-if sys.version_info >= (3, 14):
- skip_module_if_py_gte_314()
-
-from fastapi.testclient import TestClient
-from inline_snapshot import snapshot
-
-from .main import app
-
-client = TestClient(app)
-
-
-def test_v1_to_v2_item():
- response = client.post(
- "/v1-to-v2/item",
- json={"title": "Test", "size": 10, "sub": {"name": "SubTest"}},
- )
- assert response.status_code == 200
- assert response.json() == {
- "new_title": "Test",
- "new_size": 10,
- "new_description": None,
- "new_sub": {"new_sub_name": "SubTest"},
- "new_multi": [],
- }
-
-
-def test_v2_to_v1_item():
- response = client.post(
- "/v2-to-v1/item",
- json={
- "new_title": "NewTest",
- "new_size": 20,
- "new_sub": {"new_sub_name": "NewSubTest"},
- },
- )
- assert response.status_code == 200
- assert response.json() == {
- "title": "NewTest",
- "size": 20,
- "description": None,
- "sub": {"name": "NewSubTest"},
- "multi": [],
- }
-
-
-def test_v1_to_v2_item_to_list():
- response = client.post(
- "/v1-to-v2/item-to-list",
- json={"title": "ListTest", "size": 30, "sub": {"name": "SubListTest"}},
- )
- assert response.status_code == 200
- assert response.json() == [
- {
- "new_title": "ListTest",
- "new_size": 30,
- "new_description": None,
- "new_sub": {"new_sub_name": "SubListTest"},
- "new_multi": [],
- },
- {
- "new_title": "ListTest",
- "new_size": 30,
- "new_description": None,
- "new_sub": {"new_sub_name": "SubListTest"},
- "new_multi": [],
- },
- ]
-
-
-def test_v1_to_v2_list_to_list():
- response = client.post(
- "/v1-to-v2/list-to-list",
- json=[
- {"title": "Item1", "size": 40, "sub": {"name": "Sub1"}},
- {"title": "Item2", "size": 50, "sub": {"name": "Sub2"}},
- ],
- )
- assert response.status_code == 200
- assert response.json() == [
- {
- "new_title": "Item1",
- "new_size": 40,
- "new_description": None,
- "new_sub": {"new_sub_name": "Sub1"},
- "new_multi": [],
- },
- {
- "new_title": "Item2",
- "new_size": 50,
- "new_description": None,
- "new_sub": {"new_sub_name": "Sub2"},
- "new_multi": [],
- },
- ]
-
-
-def test_v1_to_v2_list_to_item():
- response = client.post(
- "/v1-to-v2/list-to-item",
- json=[
- {"title": "FirstItem", "size": 60, "sub": {"name": "FirstSub"}},
- {"title": "SecondItem", "size": 70, "sub": {"name": "SecondSub"}},
- ],
- )
- assert response.status_code == 200
- assert response.json() == {
- "new_title": "FirstItem",
- "new_size": 60,
- "new_description": None,
- "new_sub": {"new_sub_name": "FirstSub"},
- "new_multi": [],
- }
-
-
-def test_v2_to_v1_item_to_list():
- response = client.post(
- "/v2-to-v1/item-to-list",
- json={
- "new_title": "ListNew",
- "new_size": 80,
- "new_sub": {"new_sub_name": "SubListNew"},
- },
- )
- assert response.status_code == 200
- assert response.json() == [
- {
- "title": "ListNew",
- "size": 80,
- "description": None,
- "sub": {"name": "SubListNew"},
- "multi": [],
- },
- {
- "title": "ListNew",
- "size": 80,
- "description": None,
- "sub": {"name": "SubListNew"},
- "multi": [],
- },
- ]
-
-
-def test_v2_to_v1_list_to_list():
- response = client.post(
- "/v2-to-v1/list-to-list",
- json=[
- {
- "new_title": "New1",
- "new_size": 90,
- "new_sub": {"new_sub_name": "NewSub1"},
- },
- {
- "new_title": "New2",
- "new_size": 100,
- "new_sub": {"new_sub_name": "NewSub2"},
- },
- ],
- )
- assert response.status_code == 200
- assert response.json() == [
- {
- "title": "New1",
- "size": 90,
- "description": None,
- "sub": {"name": "NewSub1"},
- "multi": [],
- },
- {
- "title": "New2",
- "size": 100,
- "description": None,
- "sub": {"name": "NewSub2"},
- "multi": [],
- },
- ]
-
-
-def test_v2_to_v1_list_to_item():
- response = client.post(
- "/v2-to-v1/list-to-item",
- json=[
- {
- "new_title": "FirstNew",
- "new_size": 110,
- "new_sub": {"new_sub_name": "FirstNewSub"},
- },
- {
- "new_title": "SecondNew",
- "new_size": 120,
- "new_sub": {"new_sub_name": "SecondNewSub"},
- },
- ],
- )
- assert response.status_code == 200
- assert response.json() == {
- "title": "FirstNew",
- "size": 110,
- "description": None,
- "sub": {"name": "FirstNewSub"},
- "multi": [],
- }
-
-
-def test_v1_to_v2_list_to_item_empty():
- response = client.post("/v1-to-v2/list-to-item", json=[])
- assert response.status_code == 200
- assert response.json() == {
- "new_title": "",
- "new_size": 0,
- "new_description": None,
- "new_sub": {"new_sub_name": ""},
- "new_multi": [],
- }
-
-
-def test_v2_to_v1_list_to_item_empty():
- response = client.post("/v2-to-v1/list-to-item", json=[])
- assert response.status_code == 200
- assert response.json() == {
- "title": "",
- "size": 0,
- "description": None,
- "sub": {"name": ""},
- "multi": [],
- }
-
-
-def test_v2_same_name_to_v1():
- response = client.post(
- "/v2-to-v1/same-name",
- json={
- "item1": {
- "new_title": "Title1",
- "new_size": 100,
- "new_description": "Description1",
- "new_sub": {"new_sub_name": "Sub1"},
- "new_multi": [{"new_sub_name": "Multi1"}],
- },
- "item2": {
- "dup_title": "Title2",
- "dup_size": 200,
- "dup_description": "Description2",
- "dup_sub": {"dup_sub_name": "Sub2"},
- "dup_multi": [
- {"dup_sub_name": "Multi2a"},
- {"dup_sub_name": "Multi2b"},
- ],
- },
- },
- )
- assert response.status_code == 200
- assert response.json() == {
- "title": "Title1",
- "size": 200,
- "description": "Description1",
- "sub": {"name": "Sub1"},
- "multi": [{"name": "Multi2a"}, {"name": "Multi2b"}],
- }
-
-
-def test_v2_items_in_list_to_v1_item_in_list():
- response = client.post(
- "/v2-to-v1/list-of-items-to-list-of-items",
- json={
- "data1": [{"name2": "Item1"}, {"name2": "Item2"}],
- "data2": [{"dup_name2": "Item3"}, {"dup_name2": "Item4"}],
- },
- )
- assert response.status_code == 200, response.text
- assert response.json() == [
- {"name1": "Item1"},
- {"name1": "Item3"},
- ]
-
-
-def test_openapi_schema():
- response = client.get("/openapi.json")
- assert response.status_code == 200
- assert response.json() == snapshot(
- {
- "openapi": "3.1.0",
- "info": {"title": "FastAPI", "version": "0.1.0"},
- "paths": {
- "/v1-to-v2/item": {
- "post": {
- "summary": "Handle V1 Item To V2",
- "operationId": "handle_v1_item_to_v2_v1_to_v2_item_post",
- "requestBody": {
- "content": {
- "application/json": {
- "schema": pydantic_snapshot(
- v2=snapshot(
- {
- "allOf": [
- {
- "$ref": "#/components/schemas/tests__test_pydantic_v1_v2_multifile__modelsv1__Item"
- }
- ],
- "title": "Data",
- }
- ),
- v1=snapshot(
- {
- "$ref": "#/components/schemas/tests__test_pydantic_v1_v2_multifile__modelsv1__Item"
- }
- ),
- )
- }
- },
- "required": True,
- },
- "responses": {
- "200": {
- "description": "Successful Response",
- "content": {
- "application/json": {
- "schema": {
- "$ref": "#/components/schemas/tests__test_pydantic_v1_v2_multifile__modelsv2__Item"
- }
- }
- },
- },
- "422": {
- "description": "Validation Error",
- "content": {
- "application/json": {
- "schema": {
- "$ref": "#/components/schemas/HTTPValidationError"
- }
- }
- },
- },
- },
- }
- },
- "/v2-to-v1/item": {
- "post": {
- "summary": "Handle V2 Item To V1",
- "operationId": "handle_v2_item_to_v1_v2_to_v1_item_post",
- "requestBody": {
- "content": {
- "application/json": {
- "schema": pydantic_snapshot(
- v2=snapshot(
- {
- "$ref": "#/components/schemas/tests__test_pydantic_v1_v2_multifile__modelsv2__Item-Input"
- }
- ),
- v1=snapshot(
- {
- "$ref": "#/components/schemas/tests__test_pydantic_v1_v2_multifile__modelsv2__Item"
- }
- ),
- ),
- }
- },
- "required": True,
- },
- "responses": {
- "200": {
- "description": "Successful Response",
- "content": {
- "application/json": {
- "schema": {
- "$ref": "#/components/schemas/tests__test_pydantic_v1_v2_multifile__modelsv1__Item"
- }
- }
- },
- },
- "422": {
- "description": "Validation Error",
- "content": {
- "application/json": {
- "schema": {
- "$ref": "#/components/schemas/HTTPValidationError"
- }
- }
- },
- },
- },
- }
- },
- "/v1-to-v2/item-to-list": {
- "post": {
- "summary": "Handle V1 Item To V2 List",
- "operationId": "handle_v1_item_to_v2_list_v1_to_v2_item_to_list_post",
- "requestBody": {
- "content": {
- "application/json": {
- "schema": pydantic_snapshot(
- v2=snapshot(
- {
- "allOf": [
- {
- "$ref": "#/components/schemas/tests__test_pydantic_v1_v2_multifile__modelsv1__Item"
- }
- ],
- "title": "Data",
- }
- ),
- v1=snapshot(
- {
- "$ref": "#/components/schemas/tests__test_pydantic_v1_v2_multifile__modelsv1__Item"
- }
- ),
- )
- }
- },
- "required": True,
- },
- "responses": {
- "200": {
- "description": "Successful Response",
- "content": {
- "application/json": {
- "schema": {
- "items": {
- "$ref": "#/components/schemas/tests__test_pydantic_v1_v2_multifile__modelsv2__Item"
- },
- "type": "array",
- "title": "Response Handle V1 Item To V2 List V1 To V2 Item To List Post",
- }
- }
- },
- },
- "422": {
- "description": "Validation Error",
- "content": {
- "application/json": {
- "schema": {
- "$ref": "#/components/schemas/HTTPValidationError"
- }
- }
- },
- },
- },
- }
- },
- "/v1-to-v2/list-to-list": {
- "post": {
- "summary": "Handle V1 List To V2 List",
- "operationId": "handle_v1_list_to_v2_list_v1_to_v2_list_to_list_post",
- "requestBody": {
- "content": {
- "application/json": {
- "schema": {
- "items": {
- "$ref": "#/components/schemas/tests__test_pydantic_v1_v2_multifile__modelsv1__Item"
- },
- "type": "array",
- "title": "Data",
- }
- }
- },
- "required": True,
- },
- "responses": {
- "200": {
- "description": "Successful Response",
- "content": {
- "application/json": {
- "schema": {
- "items": {
- "$ref": "#/components/schemas/tests__test_pydantic_v1_v2_multifile__modelsv2__Item"
- },
- "type": "array",
- "title": "Response Handle V1 List To V2 List V1 To V2 List To List Post",
- }
- }
- },
- },
- "422": {
- "description": "Validation Error",
- "content": {
- "application/json": {
- "schema": {
- "$ref": "#/components/schemas/HTTPValidationError"
- }
- }
- },
- },
- },
- }
- },
- "/v1-to-v2/list-to-item": {
- "post": {
- "summary": "Handle V1 List To V2 Item",
- "operationId": "handle_v1_list_to_v2_item_v1_to_v2_list_to_item_post",
- "requestBody": {
- "content": {
- "application/json": {
- "schema": {
- "items": {
- "$ref": "#/components/schemas/tests__test_pydantic_v1_v2_multifile__modelsv1__Item"
- },
- "type": "array",
- "title": "Data",
- }
- }
- },
- "required": True,
- },
- "responses": {
- "200": {
- "description": "Successful Response",
- "content": {
- "application/json": {
- "schema": {
- "$ref": "#/components/schemas/tests__test_pydantic_v1_v2_multifile__modelsv2__Item"
- }
- }
- },
- },
- "422": {
- "description": "Validation Error",
- "content": {
- "application/json": {
- "schema": {
- "$ref": "#/components/schemas/HTTPValidationError"
- }
- }
- },
- },
- },
- }
- },
- "/v2-to-v1/item-to-list": {
- "post": {
- "summary": "Handle V2 Item To V1 List",
- "operationId": "handle_v2_item_to_v1_list_v2_to_v1_item_to_list_post",
- "requestBody": {
- "content": {
- "application/json": {
- "schema": pydantic_snapshot(
- v2=snapshot(
- {
- "$ref": "#/components/schemas/tests__test_pydantic_v1_v2_multifile__modelsv2__Item-Input"
- }
- ),
- v1=snapshot(
- {
- "$ref": "#/components/schemas/tests__test_pydantic_v1_v2_multifile__modelsv2__Item"
- }
- ),
- ),
- }
- },
- "required": True,
- },
- "responses": {
- "200": {
- "description": "Successful Response",
- "content": {
- "application/json": {
- "schema": {
- "items": {
- "$ref": "#/components/schemas/tests__test_pydantic_v1_v2_multifile__modelsv1__Item"
- },
- "type": "array",
- "title": "Response Handle V2 Item To V1 List V2 To V1 Item To List Post",
- }
- }
- },
- },
- "422": {
- "description": "Validation Error",
- "content": {
- "application/json": {
- "schema": {
- "$ref": "#/components/schemas/HTTPValidationError"
- }
- }
- },
- },
- },
- }
- },
- "/v2-to-v1/list-to-list": {
- "post": {
- "summary": "Handle V2 List To V1 List",
- "operationId": "handle_v2_list_to_v1_list_v2_to_v1_list_to_list_post",
- "requestBody": {
- "content": {
- "application/json": {
- "schema": {
- "items": pydantic_snapshot(
- v2=snapshot(
- {
- "$ref": "#/components/schemas/tests__test_pydantic_v1_v2_multifile__modelsv2__Item-Input"
- }
- ),
- v1=snapshot(
- {
- "$ref": "#/components/schemas/tests__test_pydantic_v1_v2_multifile__modelsv2__Item"
- }
- ),
- ),
- "type": "array",
- "title": "Data",
- }
- }
- },
- "required": True,
- },
- "responses": {
- "200": {
- "description": "Successful Response",
- "content": {
- "application/json": {
- "schema": {
- "items": {
- "$ref": "#/components/schemas/tests__test_pydantic_v1_v2_multifile__modelsv1__Item"
- },
- "type": "array",
- "title": "Response Handle V2 List To V1 List V2 To V1 List To List Post",
- }
- }
- },
- },
- "422": {
- "description": "Validation Error",
- "content": {
- "application/json": {
- "schema": {
- "$ref": "#/components/schemas/HTTPValidationError"
- }
- }
- },
- },
- },
- }
- },
- "/v2-to-v1/list-to-item": {
- "post": {
- "summary": "Handle V2 List To V1 Item",
- "operationId": "handle_v2_list_to_v1_item_v2_to_v1_list_to_item_post",
- "requestBody": {
- "content": {
- "application/json": {
- "schema": {
- "items": pydantic_snapshot(
- v2=snapshot(
- {
- "$ref": "#/components/schemas/tests__test_pydantic_v1_v2_multifile__modelsv2__Item-Input"
- }
- ),
- v1=snapshot(
- {
- "$ref": "#/components/schemas/tests__test_pydantic_v1_v2_multifile__modelsv2__Item"
- }
- ),
- ),
- "type": "array",
- "title": "Data",
- }
- }
- },
- "required": True,
- },
- "responses": {
- "200": {
- "description": "Successful Response",
- "content": {
- "application/json": {
- "schema": {
- "$ref": "#/components/schemas/tests__test_pydantic_v1_v2_multifile__modelsv1__Item"
- }
- }
- },
- },
- "422": {
- "description": "Validation Error",
- "content": {
- "application/json": {
- "schema": {
- "$ref": "#/components/schemas/HTTPValidationError"
- }
- }
- },
- },
- },
- }
- },
- "/v2-to-v1/same-name": {
- "post": {
- "summary": "Handle V2 Same Name To V1",
- "operationId": "handle_v2_same_name_to_v1_v2_to_v1_same_name_post",
- "requestBody": {
- "content": {
- "application/json": {
- "schema": {
- "$ref": "#/components/schemas/Body_handle_v2_same_name_to_v1_v2_to_v1_same_name_post"
- }
- }
- },
- "required": True,
- },
- "responses": {
- "200": {
- "description": "Successful Response",
- "content": {
- "application/json": {
- "schema": {
- "$ref": "#/components/schemas/tests__test_pydantic_v1_v2_multifile__modelsv1__Item"
- }
- }
- },
- },
- "422": {
- "description": "Validation Error",
- "content": {
- "application/json": {
- "schema": {
- "$ref": "#/components/schemas/HTTPValidationError"
- }
- }
- },
- },
- },
- }
- },
- "/v2-to-v1/list-of-items-to-list-of-items": {
- "post": {
- "summary": "Handle V2 Items In List To V1 Item In List",
- "operationId": "handle_v2_items_in_list_to_v1_item_in_list_v2_to_v1_list_of_items_to_list_of_items_post",
- "requestBody": {
- "content": {
- "application/json": {
- "schema": {
- "$ref": "#/components/schemas/Body_handle_v2_items_in_list_to_v1_item_in_list_v2_to_v1_list_of_items_to_list_of_items_post"
- }
- }
- },
- "required": True,
- },
- "responses": {
- "200": {
- "description": "Successful Response",
- "content": {
- "application/json": {
- "schema": {
- "items": {
- "$ref": "#/components/schemas/tests__test_pydantic_v1_v2_multifile__modelsv1__ItemInList"
- },
- "type": "array",
- "title": "Response Handle V2 Items In List To V1 Item In List V2 To V1 List Of Items To List Of Items Post",
- }
- }
- },
- },
- "422": {
- "description": "Validation Error",
- "content": {
- "application/json": {
- "schema": {
- "$ref": "#/components/schemas/HTTPValidationError"
- }
- }
- },
- },
- },
- }
- },
- },
- "components": {
- "schemas": pydantic_snapshot(
- v1=snapshot(
- {
- "Body_handle_v2_items_in_list_to_v1_item_in_list_v2_to_v1_list_of_items_to_list_of_items_post": {
- "properties": {
- "data1": {
- "items": {
- "$ref": "#/components/schemas/tests__test_pydantic_v1_v2_multifile__modelsv2__ItemInList"
- },
- "type": "array",
- "title": "Data1",
- },
- "data2": {
- "items": {
- "$ref": "#/components/schemas/tests__test_pydantic_v1_v2_multifile__modelsv2b__ItemInList"
- },
- "type": "array",
- "title": "Data2",
- },
- },
- "type": "object",
- "required": ["data1", "data2"],
- "title": "Body_handle_v2_items_in_list_to_v1_item_in_list_v2_to_v1_list_of_items_to_list_of_items_post",
- },
- "Body_handle_v2_same_name_to_v1_v2_to_v1_same_name_post": {
- "properties": {
- "item1": {
- "$ref": "#/components/schemas/tests__test_pydantic_v1_v2_multifile__modelsv2__Item"
- },
- "item2": {
- "$ref": "#/components/schemas/tests__test_pydantic_v1_v2_multifile__modelsv2b__Item"
- },
- },
- "type": "object",
- "required": ["item1", "item2"],
- "title": "Body_handle_v2_same_name_to_v1_v2_to_v1_same_name_post",
- },
- "HTTPValidationError": {
- "properties": {
- "detail": {
- "items": {
- "$ref": "#/components/schemas/ValidationError"
- },
- "type": "array",
- "title": "Detail",
- }
- },
- "type": "object",
- "title": "HTTPValidationError",
- },
- "ValidationError": {
- "properties": {
- "loc": {
- "items": {
- "anyOf": [
- {"type": "string"},
- {"type": "integer"},
- ]
- },
- "type": "array",
- "title": "Location",
- },
- "msg": {"type": "string", "title": "Message"},
- "type": {"type": "string", "title": "Error Type"},
- },
- "type": "object",
- "required": ["loc", "msg", "type"],
- "title": "ValidationError",
- },
- "tests__test_pydantic_v1_v2_multifile__modelsv1__Item": {
- "properties": {
- "title": {"type": "string", "title": "Title"},
- "size": {"type": "integer", "title": "Size"},
- "description": {
- "type": "string",
- "title": "Description",
- },
- "sub": {
- "$ref": "#/components/schemas/tests__test_pydantic_v1_v2_multifile__modelsv1__SubItem"
- },
- "multi": {
- "items": {
- "$ref": "#/components/schemas/tests__test_pydantic_v1_v2_multifile__modelsv1__SubItem"
- },
- "type": "array",
- "title": "Multi",
- "default": [],
- },
- },
- "type": "object",
- "required": ["title", "size", "sub"],
- "title": "Item",
- },
- "tests__test_pydantic_v1_v2_multifile__modelsv1__ItemInList": {
- "properties": {
- "name1": {"type": "string", "title": "Name1"}
- },
- "type": "object",
- "required": ["name1"],
- "title": "ItemInList",
- },
- "tests__test_pydantic_v1_v2_multifile__modelsv1__SubItem": {
- "properties": {
- "name": {"type": "string", "title": "Name"}
- },
- "type": "object",
- "required": ["name"],
- "title": "SubItem",
- },
- "tests__test_pydantic_v1_v2_multifile__modelsv2__Item": {
- "properties": {
- "new_title": {
- "type": "string",
- "title": "New Title",
- },
- "new_size": {
- "type": "integer",
- "title": "New Size",
- },
- "new_description": {
- "type": "string",
- "title": "New Description",
- },
- "new_sub": {
- "$ref": "#/components/schemas/tests__test_pydantic_v1_v2_multifile__modelsv2__SubItem"
- },
- "new_multi": {
- "items": {
- "$ref": "#/components/schemas/tests__test_pydantic_v1_v2_multifile__modelsv2__SubItem"
- },
- "type": "array",
- "title": "New Multi",
- "default": [],
- },
- },
- "type": "object",
- "required": ["new_title", "new_size", "new_sub"],
- "title": "Item",
- },
- "tests__test_pydantic_v1_v2_multifile__modelsv2__ItemInList": {
- "properties": {
- "name2": {"type": "string", "title": "Name2"}
- },
- "type": "object",
- "required": ["name2"],
- "title": "ItemInList",
- },
- "tests__test_pydantic_v1_v2_multifile__modelsv2__SubItem": {
- "properties": {
- "new_sub_name": {
- "type": "string",
- "title": "New Sub Name",
- }
- },
- "type": "object",
- "required": ["new_sub_name"],
- "title": "SubItem",
- },
- "tests__test_pydantic_v1_v2_multifile__modelsv2b__Item": {
- "properties": {
- "dup_title": {
- "type": "string",
- "title": "Dup Title",
- },
- "dup_size": {
- "type": "integer",
- "title": "Dup Size",
- },
- "dup_description": {
- "type": "string",
- "title": "Dup Description",
- },
- "dup_sub": {
- "$ref": "#/components/schemas/tests__test_pydantic_v1_v2_multifile__modelsv2b__SubItem"
- },
- "dup_multi": {
- "items": {
- "$ref": "#/components/schemas/tests__test_pydantic_v1_v2_multifile__modelsv2b__SubItem"
- },
- "type": "array",
- "title": "Dup Multi",
- "default": [],
- },
- },
- "type": "object",
- "required": ["dup_title", "dup_size", "dup_sub"],
- "title": "Item",
- },
- "tests__test_pydantic_v1_v2_multifile__modelsv2b__ItemInList": {
- "properties": {
- "dup_name2": {
- "type": "string",
- "title": "Dup Name2",
- }
- },
- "type": "object",
- "required": ["dup_name2"],
- "title": "ItemInList",
- },
- "tests__test_pydantic_v1_v2_multifile__modelsv2b__SubItem": {
- "properties": {
- "dup_sub_name": {
- "type": "string",
- "title": "Dup Sub Name",
- }
- },
- "type": "object",
- "required": ["dup_sub_name"],
- "title": "SubItem",
- },
- }
- ),
- v2=snapshot(
- {
- "Body_handle_v2_items_in_list_to_v1_item_in_list_v2_to_v1_list_of_items_to_list_of_items_post": {
- "properties": {
- "data1": {
- "items": {
- "$ref": "#/components/schemas/tests__test_pydantic_v1_v2_multifile__modelsv2__ItemInList"
- },
- "type": "array",
- "title": "Data1",
- },
- "data2": {
- "items": {
- "$ref": "#/components/schemas/tests__test_pydantic_v1_v2_multifile__modelsv2b__ItemInList"
- },
- "type": "array",
- "title": "Data2",
- },
- },
- "type": "object",
- "required": ["data1", "data2"],
- "title": "Body_handle_v2_items_in_list_to_v1_item_in_list_v2_to_v1_list_of_items_to_list_of_items_post",
- },
- "Body_handle_v2_same_name_to_v1_v2_to_v1_same_name_post": {
- "properties": {
- "item1": {
- "$ref": "#/components/schemas/tests__test_pydantic_v1_v2_multifile__modelsv2__Item-Input"
- },
- "item2": {
- "$ref": "#/components/schemas/tests__test_pydantic_v1_v2_multifile__modelsv2b__Item"
- },
- },
- "type": "object",
- "required": ["item1", "item2"],
- "title": "Body_handle_v2_same_name_to_v1_v2_to_v1_same_name_post",
- },
- "HTTPValidationError": {
- "properties": {
- "detail": {
- "items": {
- "$ref": "#/components/schemas/ValidationError"
- },
- "type": "array",
- "title": "Detail",
- }
- },
- "type": "object",
- "title": "HTTPValidationError",
- },
- "ValidationError": {
- "properties": {
- "loc": {
- "items": {
- "anyOf": [
- {"type": "string"},
- {"type": "integer"},
- ]
- },
- "type": "array",
- "title": "Location",
- },
- "msg": {"type": "string", "title": "Message"},
- "type": {"type": "string", "title": "Error Type"},
- },
- "type": "object",
- "required": ["loc", "msg", "type"],
- "title": "ValidationError",
- },
- "tests__test_pydantic_v1_v2_multifile__modelsv1__Item": {
- "properties": {
- "title": {"type": "string", "title": "Title"},
- "size": {"type": "integer", "title": "Size"},
- "description": {
- "type": "string",
- "title": "Description",
- },
- "sub": {
- "$ref": "#/components/schemas/tests__test_pydantic_v1_v2_multifile__modelsv1__SubItem"
- },
- "multi": {
- "items": {
- "$ref": "#/components/schemas/tests__test_pydantic_v1_v2_multifile__modelsv1__SubItem"
- },
- "type": "array",
- "title": "Multi",
- "default": [],
- },
- },
- "type": "object",
- "required": ["title", "size", "sub"],
- "title": "Item",
- },
- "tests__test_pydantic_v1_v2_multifile__modelsv1__ItemInList": {
- "properties": {
- "name1": {"type": "string", "title": "Name1"}
- },
- "type": "object",
- "required": ["name1"],
- "title": "ItemInList",
- },
- "tests__test_pydantic_v1_v2_multifile__modelsv1__SubItem": {
- "properties": {
- "name": {"type": "string", "title": "Name"}
- },
- "type": "object",
- "required": ["name"],
- "title": "SubItem",
- },
- "tests__test_pydantic_v1_v2_multifile__modelsv2__Item": {
- "properties": {
- "new_title": {
- "type": "string",
- "title": "New Title",
- },
- "new_size": {
- "type": "integer",
- "title": "New Size",
- },
- "new_description": {
- "anyOf": [{"type": "string"}, {"type": "null"}],
- "title": "New Description",
- },
- "new_sub": {
- "$ref": "#/components/schemas/tests__test_pydantic_v1_v2_multifile__modelsv2__SubItem"
- },
- "new_multi": {
- "items": {
- "$ref": "#/components/schemas/tests__test_pydantic_v1_v2_multifile__modelsv2__SubItem"
- },
- "type": "array",
- "title": "New Multi",
- "default": [],
- },
- },
- "type": "object",
- "required": ["new_title", "new_size", "new_sub"],
- "title": "Item",
- },
- "tests__test_pydantic_v1_v2_multifile__modelsv2__Item-Input": {
- "properties": {
- "new_title": {
- "type": "string",
- "title": "New Title",
- },
- "new_size": {
- "type": "integer",
- "title": "New Size",
- },
- "new_description": {
- "anyOf": [{"type": "string"}, {"type": "null"}],
- "title": "New Description",
- },
- "new_sub": {
- "$ref": "#/components/schemas/tests__test_pydantic_v1_v2_multifile__modelsv2__SubItem"
- },
- "new_multi": {
- "items": {
- "$ref": "#/components/schemas/tests__test_pydantic_v1_v2_multifile__modelsv2__SubItem"
- },
- "type": "array",
- "title": "New Multi",
- "default": [],
- },
- },
- "type": "object",
- "required": ["new_title", "new_size", "new_sub"],
- "title": "Item",
- },
- "tests__test_pydantic_v1_v2_multifile__modelsv2__ItemInList": {
- "properties": {
- "name2": {"type": "string", "title": "Name2"}
- },
- "type": "object",
- "required": ["name2"],
- "title": "ItemInList",
- },
- "tests__test_pydantic_v1_v2_multifile__modelsv2__SubItem": {
- "properties": {
- "new_sub_name": {
- "type": "string",
- "title": "New Sub Name",
- }
- },
- "type": "object",
- "required": ["new_sub_name"],
- "title": "SubItem",
- },
- "tests__test_pydantic_v1_v2_multifile__modelsv2b__Item": {
- "properties": {
- "dup_title": {
- "type": "string",
- "title": "Dup Title",
- },
- "dup_size": {
- "type": "integer",
- "title": "Dup Size",
- },
- "dup_description": {
- "anyOf": [{"type": "string"}, {"type": "null"}],
- "title": "Dup Description",
- },
- "dup_sub": {
- "$ref": "#/components/schemas/tests__test_pydantic_v1_v2_multifile__modelsv2b__SubItem"
- },
- "dup_multi": {
- "items": {
- "$ref": "#/components/schemas/tests__test_pydantic_v1_v2_multifile__modelsv2b__SubItem"
- },
- "type": "array",
- "title": "Dup Multi",
- "default": [],
- },
- },
- "type": "object",
- "required": ["dup_title", "dup_size", "dup_sub"],
- "title": "Item",
- },
- "tests__test_pydantic_v1_v2_multifile__modelsv2b__ItemInList": {
- "properties": {
- "dup_name2": {
- "type": "string",
- "title": "Dup Name2",
- }
- },
- "type": "object",
- "required": ["dup_name2"],
- "title": "ItemInList",
- },
- "tests__test_pydantic_v1_v2_multifile__modelsv2b__SubItem": {
- "properties": {
- "dup_sub_name": {
- "type": "string",
- "title": "Dup Sub Name",
- }
- },
- "type": "object",
- "required": ["dup_sub_name"],
- "title": "SubItem",
- },
- }
- ),
- ),
- },
- }
- )
diff --git a/tests/test_pydantic_v1_v2_noneable.py b/tests/test_pydantic_v1_v2_noneable.py
deleted file mode 100644
index d2d6f6635b..0000000000
--- a/tests/test_pydantic_v1_v2_noneable.py
+++ /dev/null
@@ -1,766 +0,0 @@
-import sys
-from typing import Any, List, Union
-
-from tests.utils import pydantic_snapshot, skip_module_if_py_gte_314
-
-if sys.version_info >= (3, 14):
- skip_module_if_py_gte_314()
-
-from fastapi import FastAPI
-from fastapi._compat.v1 import BaseModel
-from fastapi.testclient import TestClient
-from inline_snapshot import snapshot
-from pydantic import BaseModel as NewBaseModel
-
-
-class SubItem(BaseModel):
- name: str
-
-
-class Item(BaseModel):
- title: str
- size: int
- description: Union[str, None] = None
- sub: SubItem
- multi: List[SubItem] = []
-
-
-class NewSubItem(NewBaseModel):
- new_sub_name: str
-
-
-class NewItem(NewBaseModel):
- new_title: str
- new_size: int
- new_description: Union[str, None] = None
- new_sub: NewSubItem
- new_multi: List[NewSubItem] = []
-
-
-app = FastAPI()
-
-
-@app.post("/v1-to-v2/")
-def handle_v1_item_to_v2(data: Item) -> Union[NewItem, None]:
- if data.size < 0:
- return None
- return NewItem(
- new_title=data.title,
- new_size=data.size,
- new_description=data.description,
- new_sub=NewSubItem(new_sub_name=data.sub.name),
- new_multi=[NewSubItem(new_sub_name=s.name) for s in data.multi],
- )
-
-
-@app.post("/v1-to-v2/item-filter", response_model=Union[NewItem, None])
-def handle_v1_item_to_v2_filter(data: Item) -> Any:
- if data.size < 0:
- return None
- result = {
- "new_title": data.title,
- "new_size": data.size,
- "new_description": data.description,
- "new_sub": {"new_sub_name": data.sub.name, "new_sub_secret": "sub_hidden"},
- "new_multi": [
- {"new_sub_name": s.name, "new_sub_secret": "sub_hidden"} for s in data.multi
- ],
- "secret": "hidden_v1_to_v2",
- }
- return result
-
-
-@app.post("/v2-to-v1/item")
-def handle_v2_item_to_v1(data: NewItem) -> Union[Item, None]:
- if data.new_size < 0:
- return None
- return Item(
- title=data.new_title,
- size=data.new_size,
- description=data.new_description,
- sub=SubItem(name=data.new_sub.new_sub_name),
- multi=[SubItem(name=s.new_sub_name) for s in data.new_multi],
- )
-
-
-@app.post("/v2-to-v1/item-filter", response_model=Union[Item, None])
-def handle_v2_item_to_v1_filter(data: NewItem) -> Any:
- if data.new_size < 0:
- return None
- result = {
- "title": data.new_title,
- "size": data.new_size,
- "description": data.new_description,
- "sub": {"name": data.new_sub.new_sub_name, "sub_secret": "sub_hidden"},
- "multi": [
- {"name": s.new_sub_name, "sub_secret": "sub_hidden"} for s in data.new_multi
- ],
- "secret": "hidden_v2_to_v1",
- }
- return result
-
-
-client = TestClient(app)
-
-
-def test_v1_to_v2_item_success():
- response = client.post(
- "/v1-to-v2/",
- json={
- "title": "Old Item",
- "size": 100,
- "description": "V1 description",
- "sub": {"name": "V1 Sub"},
- "multi": [{"name": "M1"}, {"name": "M2"}],
- },
- )
- assert response.status_code == 200, response.text
- assert response.json() == {
- "new_title": "Old Item",
- "new_size": 100,
- "new_description": "V1 description",
- "new_sub": {"new_sub_name": "V1 Sub"},
- "new_multi": [{"new_sub_name": "M1"}, {"new_sub_name": "M2"}],
- }
-
-
-def test_v1_to_v2_item_returns_none():
- response = client.post(
- "/v1-to-v2/",
- json={"title": "Invalid Item", "size": -10, "sub": {"name": "Sub"}},
- )
- assert response.status_code == 200, response.text
- assert response.json() is None
-
-
-def test_v1_to_v2_item_minimal():
- response = client.post(
- "/v1-to-v2/", json={"title": "Minimal", "size": 50, "sub": {"name": "MinSub"}}
- )
- assert response.status_code == 200, response.text
- assert response.json() == {
- "new_title": "Minimal",
- "new_size": 50,
- "new_description": None,
- "new_sub": {"new_sub_name": "MinSub"},
- "new_multi": [],
- }
-
-
-def test_v1_to_v2_item_filter_success():
- response = client.post(
- "/v1-to-v2/item-filter",
- json={
- "title": "Filtered Item",
- "size": 50,
- "sub": {"name": "Sub"},
- "multi": [{"name": "Multi1"}],
- },
- )
- assert response.status_code == 200, response.text
- result = response.json()
- assert result["new_title"] == "Filtered Item"
- assert result["new_size"] == 50
- assert result["new_sub"]["new_sub_name"] == "Sub"
- assert result["new_multi"][0]["new_sub_name"] == "Multi1"
- # Verify secret fields are filtered out
- assert "secret" not in result
- assert "new_sub_secret" not in result["new_sub"]
- assert "new_sub_secret" not in result["new_multi"][0]
-
-
-def test_v1_to_v2_item_filter_returns_none():
- response = client.post(
- "/v1-to-v2/item-filter",
- json={"title": "Invalid", "size": -1, "sub": {"name": "Sub"}},
- )
- assert response.status_code == 200, response.text
- assert response.json() is None
-
-
-def test_v2_to_v1_item_success():
- response = client.post(
- "/v2-to-v1/item",
- json={
- "new_title": "New Item",
- "new_size": 200,
- "new_description": "V2 description",
- "new_sub": {"new_sub_name": "V2 Sub"},
- "new_multi": [{"new_sub_name": "N1"}, {"new_sub_name": "N2"}],
- },
- )
- assert response.status_code == 200, response.text
- assert response.json() == {
- "title": "New Item",
- "size": 200,
- "description": "V2 description",
- "sub": {"name": "V2 Sub"},
- "multi": [{"name": "N1"}, {"name": "N2"}],
- }
-
-
-def test_v2_to_v1_item_returns_none():
- response = client.post(
- "/v2-to-v1/item",
- json={
- "new_title": "Invalid New",
- "new_size": -5,
- "new_sub": {"new_sub_name": "NewSub"},
- },
- )
- assert response.status_code == 200, response.text
- assert response.json() is None
-
-
-def test_v2_to_v1_item_minimal():
- response = client.post(
- "/v2-to-v1/item",
- json={
- "new_title": "MinimalNew",
- "new_size": 75,
- "new_sub": {"new_sub_name": "MinNewSub"},
- },
- )
- assert response.status_code == 200, response.text
- assert response.json() == {
- "title": "MinimalNew",
- "size": 75,
- "description": None,
- "sub": {"name": "MinNewSub"},
- "multi": [],
- }
-
-
-def test_v2_to_v1_item_filter_success():
- response = client.post(
- "/v2-to-v1/item-filter",
- json={
- "new_title": "Filtered New",
- "new_size": 75,
- "new_sub": {"new_sub_name": "NewSub"},
- "new_multi": [],
- },
- )
- assert response.status_code == 200, response.text
- result = response.json()
- assert result["title"] == "Filtered New"
- assert result["size"] == 75
- assert result["sub"]["name"] == "NewSub"
- # Verify secret fields are filtered out
- assert "secret" not in result
- assert "sub_secret" not in result["sub"]
-
-
-def test_v2_to_v1_item_filter_returns_none():
- response = client.post(
- "/v2-to-v1/item-filter",
- json={
- "new_title": "Invalid Filtered",
- "new_size": -100,
- "new_sub": {"new_sub_name": "Sub"},
- },
- )
- assert response.status_code == 200, response.text
- assert response.json() is None
-
-
-def test_v1_to_v2_validation_error():
- response = client.post("/v1-to-v2/", json={"title": "Missing fields"})
- assert response.status_code == 422, response.text
- assert response.json() == snapshot(
- {
- "detail": [
- {
- "loc": ["body", "size"],
- "msg": "field required",
- "type": "value_error.missing",
- },
- {
- "loc": ["body", "sub"],
- "msg": "field required",
- "type": "value_error.missing",
- },
- ]
- }
- )
-
-
-def test_v1_to_v2_nested_validation_error():
- response = client.post(
- "/v1-to-v2/",
- json={"title": "Bad sub", "size": 100, "sub": {"wrong_field": "value"}},
- )
- assert response.status_code == 422, response.text
- error_detail = response.json()["detail"]
- assert len(error_detail) == 1
- assert error_detail[0]["loc"] == ["body", "sub", "name"]
-
-
-def test_v1_to_v2_type_validation_error():
- response = client.post(
- "/v1-to-v2/",
- json={"title": "Bad type", "size": "not_a_number", "sub": {"name": "Sub"}},
- )
- assert response.status_code == 422, response.text
- error_detail = response.json()["detail"]
- assert len(error_detail) == 1
- assert error_detail[0]["loc"] == ["body", "size"]
-
-
-def test_v2_to_v1_validation_error():
- response = client.post("/v2-to-v1/item", json={"new_title": "Missing fields"})
- assert response.status_code == 422, response.text
- assert response.json() == snapshot(
- {
- "detail": pydantic_snapshot(
- v2=snapshot(
- [
- {
- "type": "missing",
- "loc": ["body", "new_size"],
- "msg": "Field required",
- "input": {"new_title": "Missing fields"},
- },
- {
- "type": "missing",
- "loc": ["body", "new_sub"],
- "msg": "Field required",
- "input": {"new_title": "Missing fields"},
- },
- ]
- ),
- v1=snapshot(
- [
- {
- "loc": ["body", "new_size"],
- "msg": "field required",
- "type": "value_error.missing",
- },
- {
- "loc": ["body", "new_sub"],
- "msg": "field required",
- "type": "value_error.missing",
- },
- ]
- ),
- )
- }
- )
-
-
-def test_v2_to_v1_nested_validation_error():
- response = client.post(
- "/v2-to-v1/item",
- json={
- "new_title": "Bad sub",
- "new_size": 200,
- "new_sub": {"wrong_field": "value"},
- },
- )
- assert response.status_code == 422, response.text
- assert response.json() == snapshot(
- {
- "detail": [
- pydantic_snapshot(
- v2=snapshot(
- {
- "type": "missing",
- "loc": ["body", "new_sub", "new_sub_name"],
- "msg": "Field required",
- "input": {"wrong_field": "value"},
- }
- ),
- v1=snapshot(
- {
- "loc": ["body", "new_sub", "new_sub_name"],
- "msg": "field required",
- "type": "value_error.missing",
- }
- ),
- )
- ]
- }
- )
-
-
-def test_v2_to_v1_type_validation_error():
- response = client.post(
- "/v2-to-v1/item",
- json={
- "new_title": "Bad type",
- "new_size": "not_a_number",
- "new_sub": {"new_sub_name": "Sub"},
- },
- )
- assert response.status_code == 422, response.text
- assert response.json() == snapshot(
- {
- "detail": [
- pydantic_snapshot(
- v2=snapshot(
- {
- "type": "int_parsing",
- "loc": ["body", "new_size"],
- "msg": "Input should be a valid integer, unable to parse string as an integer",
- "input": "not_a_number",
- }
- ),
- v1=snapshot(
- {
- "loc": ["body", "new_size"],
- "msg": "value is not a valid integer",
- "type": "type_error.integer",
- }
- ),
- )
- ]
- }
- )
-
-
-def test_v1_to_v2_with_multi_items():
- response = client.post(
- "/v1-to-v2/",
- json={
- "title": "Complex Item",
- "size": 300,
- "description": "Item with multiple sub-items",
- "sub": {"name": "Main Sub"},
- "multi": [{"name": "Sub1"}, {"name": "Sub2"}, {"name": "Sub3"}],
- },
- )
- assert response.status_code == 200, response.text
- assert response.json() == snapshot(
- {
- "new_title": "Complex Item",
- "new_size": 300,
- "new_description": "Item with multiple sub-items",
- "new_sub": {"new_sub_name": "Main Sub"},
- "new_multi": [
- {"new_sub_name": "Sub1"},
- {"new_sub_name": "Sub2"},
- {"new_sub_name": "Sub3"},
- ],
- }
- )
-
-
-def test_v2_to_v1_with_multi_items():
- response = client.post(
- "/v2-to-v1/item",
- json={
- "new_title": "Complex New Item",
- "new_size": 400,
- "new_description": "New item with multiple sub-items",
- "new_sub": {"new_sub_name": "Main New Sub"},
- "new_multi": [{"new_sub_name": "NewSub1"}, {"new_sub_name": "NewSub2"}],
- },
- )
- assert response.status_code == 200, response.text
- assert response.json() == snapshot(
- {
- "title": "Complex New Item",
- "size": 400,
- "description": "New item with multiple sub-items",
- "sub": {"name": "Main New Sub"},
- "multi": [{"name": "NewSub1"}, {"name": "NewSub2"}],
- }
- )
-
-
-def test_openapi_schema():
- response = client.get("/openapi.json")
- assert response.status_code == 200, response.text
- assert response.json() == snapshot(
- {
- "openapi": "3.1.0",
- "info": {"title": "FastAPI", "version": "0.1.0"},
- "paths": {
- "/v1-to-v2/": {
- "post": {
- "summary": "Handle V1 Item To V2",
- "operationId": "handle_v1_item_to_v2_v1_to_v2__post",
- "requestBody": {
- "content": {
- "application/json": {
- "schema": pydantic_snapshot(
- v2=snapshot(
- {
- "allOf": [
- {
- "$ref": "#/components/schemas/Item"
- }
- ],
- "title": "Data",
- }
- ),
- v1=snapshot(
- {"$ref": "#/components/schemas/Item"}
- ),
- )
- }
- },
- "required": True,
- },
- "responses": {
- "200": {
- "description": "Successful Response",
- "content": {
- "application/json": {
- "schema": pydantic_snapshot(
- v2=snapshot(
- {
- "anyOf": [
- {
- "$ref": "#/components/schemas/NewItem"
- },
- {"type": "null"},
- ],
- "title": "Response Handle V1 Item To V2 V1 To V2 Post",
- }
- ),
- v1=snapshot(
- {"$ref": "#/components/schemas/NewItem"}
- ),
- )
- }
- },
- },
- "422": {
- "description": "Validation Error",
- "content": {
- "application/json": {
- "schema": {
- "$ref": "#/components/schemas/HTTPValidationError"
- }
- }
- },
- },
- },
- }
- },
- "/v1-to-v2/item-filter": {
- "post": {
- "summary": "Handle V1 Item To V2 Filter",
- "operationId": "handle_v1_item_to_v2_filter_v1_to_v2_item_filter_post",
- "requestBody": {
- "content": {
- "application/json": {
- "schema": pydantic_snapshot(
- v2=snapshot(
- {
- "allOf": [
- {
- "$ref": "#/components/schemas/Item"
- }
- ],
- "title": "Data",
- }
- ),
- v1=snapshot(
- {"$ref": "#/components/schemas/Item"}
- ),
- )
- }
- },
- "required": True,
- },
- "responses": {
- "200": {
- "description": "Successful Response",
- "content": {
- "application/json": {
- "schema": pydantic_snapshot(
- v2=snapshot(
- {
- "anyOf": [
- {
- "$ref": "#/components/schemas/NewItem"
- },
- {"type": "null"},
- ],
- "title": "Response Handle V1 Item To V2 Filter V1 To V2 Item Filter Post",
- }
- ),
- v1=snapshot(
- {"$ref": "#/components/schemas/NewItem"}
- ),
- )
- }
- },
- },
- "422": {
- "description": "Validation Error",
- "content": {
- "application/json": {
- "schema": {
- "$ref": "#/components/schemas/HTTPValidationError"
- }
- }
- },
- },
- },
- }
- },
- "/v2-to-v1/item": {
- "post": {
- "summary": "Handle V2 Item To V1",
- "operationId": "handle_v2_item_to_v1_v2_to_v1_item_post",
- "requestBody": {
- "content": {
- "application/json": {
- "schema": {"$ref": "#/components/schemas/NewItem"}
- }
- },
- "required": True,
- },
- "responses": {
- "200": {
- "description": "Successful Response",
- "content": {
- "application/json": {
- "schema": {"$ref": "#/components/schemas/Item"}
- }
- },
- },
- "422": {
- "description": "Validation Error",
- "content": {
- "application/json": {
- "schema": {
- "$ref": "#/components/schemas/HTTPValidationError"
- }
- }
- },
- },
- },
- }
- },
- "/v2-to-v1/item-filter": {
- "post": {
- "summary": "Handle V2 Item To V1 Filter",
- "operationId": "handle_v2_item_to_v1_filter_v2_to_v1_item_filter_post",
- "requestBody": {
- "content": {
- "application/json": {
- "schema": {"$ref": "#/components/schemas/NewItem"}
- }
- },
- "required": True,
- },
- "responses": {
- "200": {
- "description": "Successful Response",
- "content": {
- "application/json": {
- "schema": {"$ref": "#/components/schemas/Item"}
- }
- },
- },
- "422": {
- "description": "Validation Error",
- "content": {
- "application/json": {
- "schema": {
- "$ref": "#/components/schemas/HTTPValidationError"
- }
- }
- },
- },
- },
- }
- },
- },
- "components": {
- "schemas": {
- "HTTPValidationError": {
- "properties": {
- "detail": {
- "items": {
- "$ref": "#/components/schemas/ValidationError"
- },
- "type": "array",
- "title": "Detail",
- }
- },
- "type": "object",
- "title": "HTTPValidationError",
- },
- "Item": {
- "properties": {
- "title": {"type": "string", "title": "Title"},
- "size": {"type": "integer", "title": "Size"},
- "description": {"type": "string", "title": "Description"},
- "sub": {"$ref": "#/components/schemas/SubItem"},
- "multi": {
- "items": {"$ref": "#/components/schemas/SubItem"},
- "type": "array",
- "title": "Multi",
- "default": [],
- },
- },
- "type": "object",
- "required": ["title", "size", "sub"],
- "title": "Item",
- },
- "NewItem": {
- "properties": {
- "new_title": {"type": "string", "title": "New Title"},
- "new_size": {"type": "integer", "title": "New Size"},
- "new_description": pydantic_snapshot(
- v2=snapshot(
- {
- "anyOf": [{"type": "string"}, {"type": "null"}],
- "title": "New Description",
- }
- ),
- v1=snapshot(
- {"type": "string", "title": "New Description"}
- ),
- ),
- "new_sub": {"$ref": "#/components/schemas/NewSubItem"},
- "new_multi": {
- "items": {"$ref": "#/components/schemas/NewSubItem"},
- "type": "array",
- "title": "New Multi",
- "default": [],
- },
- },
- "type": "object",
- "required": ["new_title", "new_size", "new_sub"],
- "title": "NewItem",
- },
- "NewSubItem": {
- "properties": {
- "new_sub_name": {"type": "string", "title": "New Sub Name"}
- },
- "type": "object",
- "required": ["new_sub_name"],
- "title": "NewSubItem",
- },
- "SubItem": {
- "properties": {"name": {"type": "string", "title": "Name"}},
- "type": "object",
- "required": ["name"],
- "title": "SubItem",
- },
- "ValidationError": {
- "properties": {
- "loc": {
- "items": {
- "anyOf": [{"type": "string"}, {"type": "integer"}]
- },
- "type": "array",
- "title": "Location",
- },
- "msg": {"type": "string", "title": "Message"},
- "type": {"type": "string", "title": "Error Type"},
- },
- "type": "object",
- "required": ["loc", "msg", "type"],
- "title": "ValidationError",
- },
- }
- },
- }
- )
diff --git a/tests/test_pydanticv2_dataclasses_uuid_stringified_annotations.py b/tests/test_pydanticv2_dataclasses_uuid_stringified_annotations.py
index c9f94563bb..b72b0518a1 100644
--- a/tests/test_pydanticv2_dataclasses_uuid_stringified_annotations.py
+++ b/tests/test_pydanticv2_dataclasses_uuid_stringified_annotations.py
@@ -2,7 +2,7 @@ from __future__ import annotations
import uuid
from dataclasses import dataclass, field
-from typing import List, Union
+from typing import Union
from dirty_equals import IsUUID
from fastapi import FastAPI
@@ -15,7 +15,7 @@ class Item:
id: uuid.UUID
name: str
price: float
- tags: List[str] = field(default_factory=list)
+ tags: list[str] = field(default_factory=list)
description: Union[str, None] = None
tax: Union[float, None] = None
diff --git a/tests/test_query.py b/tests/test_query.py
index 57f551d2ab..c25960caca 100644
--- a/tests/test_query.py
+++ b/tests/test_query.py
@@ -1,4 +1,3 @@
-from dirty_equals import IsDict
from fastapi.testclient import TestClient
from .main import app
@@ -9,29 +8,16 @@ client = TestClient(app)
def test_query():
response = client.get("/query")
assert response.status_code == 422
- assert response.json() == IsDict(
- {
- "detail": [
- {
- "type": "missing",
- "loc": ["query", "query"],
- "msg": "Field required",
- "input": None,
- }
- ]
- }
- ) | IsDict(
- # TODO: remove when deprecating Pydantic v1
- {
- "detail": [
- {
- "loc": ["query", "query"],
- "msg": "field required",
- "type": "value_error.missing",
- }
- ]
- }
- )
+ assert response.json() == {
+ "detail": [
+ {
+ "type": "missing",
+ "loc": ["query", "query"],
+ "msg": "Field required",
+ "input": None,
+ }
+ ]
+ }
def test_query_query_baz():
@@ -43,29 +29,16 @@ def test_query_query_baz():
def test_query_not_declared_baz():
response = client.get("/query?not_declared=baz")
assert response.status_code == 422
- assert response.json() == IsDict(
- {
- "detail": [
- {
- "type": "missing",
- "loc": ["query", "query"],
- "msg": "Field required",
- "input": None,
- }
- ]
- }
- ) | IsDict(
- # TODO: remove when deprecating Pydantic v1
- {
- "detail": [
- {
- "loc": ["query", "query"],
- "msg": "field required",
- "type": "value_error.missing",
- }
- ]
- }
- )
+ assert response.json() == {
+ "detail": [
+ {
+ "type": "missing",
+ "loc": ["query", "query"],
+ "msg": "Field required",
+ "input": None,
+ }
+ ]
+ }
def test_query_optional():
@@ -89,29 +62,16 @@ def test_query_optional_not_declared_baz():
def test_query_int():
response = client.get("/query/int")
assert response.status_code == 422
- assert response.json() == IsDict(
- {
- "detail": [
- {
- "type": "missing",
- "loc": ["query", "query"],
- "msg": "Field required",
- "input": None,
- }
- ]
- }
- ) | IsDict(
- # TODO: remove when deprecating Pydantic v1
- {
- "detail": [
- {
- "loc": ["query", "query"],
- "msg": "field required",
- "type": "value_error.missing",
- }
- ]
- }
- )
+ assert response.json() == {
+ "detail": [
+ {
+ "type": "missing",
+ "loc": ["query", "query"],
+ "msg": "Field required",
+ "input": None,
+ }
+ ]
+ }
def test_query_int_query_42():
@@ -123,85 +83,46 @@ def test_query_int_query_42():
def test_query_int_query_42_5():
response = client.get("/query/int?query=42.5")
assert response.status_code == 422
- assert response.json() == IsDict(
- {
- "detail": [
- {
- "type": "int_parsing",
- "loc": ["query", "query"],
- "msg": "Input should be a valid integer, unable to parse string as an integer",
- "input": "42.5",
- }
- ]
- }
- ) | IsDict(
- # TODO: remove when deprecating Pydantic v1
- {
- "detail": [
- {
- "loc": ["query", "query"],
- "msg": "value is not a valid integer",
- "type": "type_error.integer",
- }
- ]
- }
- )
+ assert response.json() == {
+ "detail": [
+ {
+ "type": "int_parsing",
+ "loc": ["query", "query"],
+ "msg": "Input should be a valid integer, unable to parse string as an integer",
+ "input": "42.5",
+ }
+ ]
+ }
def test_query_int_query_baz():
response = client.get("/query/int?query=baz")
assert response.status_code == 422
- assert response.json() == IsDict(
- {
- "detail": [
- {
- "type": "int_parsing",
- "loc": ["query", "query"],
- "msg": "Input should be a valid integer, unable to parse string as an integer",
- "input": "baz",
- }
- ]
- }
- ) | IsDict(
- # TODO: remove when deprecating Pydantic v1
- {
- "detail": [
- {
- "loc": ["query", "query"],
- "msg": "value is not a valid integer",
- "type": "type_error.integer",
- }
- ]
- }
- )
+ assert response.json() == {
+ "detail": [
+ {
+ "type": "int_parsing",
+ "loc": ["query", "query"],
+ "msg": "Input should be a valid integer, unable to parse string as an integer",
+ "input": "baz",
+ }
+ ]
+ }
def test_query_int_not_declared_baz():
response = client.get("/query/int?not_declared=baz")
assert response.status_code == 422
- assert response.json() == IsDict(
- {
- "detail": [
- {
- "type": "missing",
- "loc": ["query", "query"],
- "msg": "Field required",
- "input": None,
- }
- ]
- }
- ) | IsDict(
- # TODO: remove when deprecating Pydantic v1
- {
- "detail": [
- {
- "loc": ["query", "query"],
- "msg": "field required",
- "type": "value_error.missing",
- }
- ]
- }
- )
+ assert response.json() == {
+ "detail": [
+ {
+ "type": "missing",
+ "loc": ["query", "query"],
+ "msg": "Field required",
+ "input": None,
+ }
+ ]
+ }
def test_query_int_optional():
@@ -219,29 +140,16 @@ def test_query_int_optional_query_50():
def test_query_int_optional_query_foo():
response = client.get("/query/int/optional?query=foo")
assert response.status_code == 422
- assert response.json() == IsDict(
- {
- "detail": [
- {
- "type": "int_parsing",
- "loc": ["query", "query"],
- "msg": "Input should be a valid integer, unable to parse string as an integer",
- "input": "foo",
- }
- ]
- }
- ) | IsDict(
- # TODO: remove when deprecating Pydantic v1
- {
- "detail": [
- {
- "loc": ["query", "query"],
- "msg": "value is not a valid integer",
- "type": "type_error.integer",
- }
- ]
- }
- )
+ assert response.json() == {
+ "detail": [
+ {
+ "type": "int_parsing",
+ "loc": ["query", "query"],
+ "msg": "Input should be a valid integer, unable to parse string as an integer",
+ "input": "foo",
+ }
+ ]
+ }
def test_query_int_default():
@@ -259,29 +167,16 @@ def test_query_int_default_query_50():
def test_query_int_default_query_foo():
response = client.get("/query/int/default?query=foo")
assert response.status_code == 422
- assert response.json() == IsDict(
- {
- "detail": [
- {
- "type": "int_parsing",
- "loc": ["query", "query"],
- "msg": "Input should be a valid integer, unable to parse string as an integer",
- "input": "foo",
- }
- ]
- }
- ) | IsDict(
- # TODO: remove when deprecating Pydantic v1
- {
- "detail": [
- {
- "loc": ["query", "query"],
- "msg": "value is not a valid integer",
- "type": "type_error.integer",
- }
- ]
- }
- )
+ assert response.json() == {
+ "detail": [
+ {
+ "type": "int_parsing",
+ "loc": ["query", "query"],
+ "msg": "Input should be a valid integer, unable to parse string as an integer",
+ "input": "foo",
+ }
+ ]
+ }
def test_query_param():
@@ -299,29 +194,16 @@ def test_query_param_query_50():
def test_query_param_required():
response = client.get("/query/param-required")
assert response.status_code == 422
- assert response.json() == IsDict(
- {
- "detail": [
- {
- "type": "missing",
- "loc": ["query", "query"],
- "msg": "Field required",
- "input": None,
- }
- ]
- }
- ) | IsDict(
- # TODO: remove when deprecating Pydantic v1
- {
- "detail": [
- {
- "loc": ["query", "query"],
- "msg": "field required",
- "type": "value_error.missing",
- }
- ]
- }
- )
+ assert response.json() == {
+ "detail": [
+ {
+ "type": "missing",
+ "loc": ["query", "query"],
+ "msg": "Field required",
+ "input": None,
+ }
+ ]
+ }
def test_query_param_required_query_50():
@@ -333,29 +215,16 @@ def test_query_param_required_query_50():
def test_query_param_required_int():
response = client.get("/query/param-required/int")
assert response.status_code == 422
- assert response.json() == IsDict(
- {
- "detail": [
- {
- "type": "missing",
- "loc": ["query", "query"],
- "msg": "Field required",
- "input": None,
- }
- ]
- }
- ) | IsDict(
- # TODO: remove when deprecating Pydantic v1
- {
- "detail": [
- {
- "loc": ["query", "query"],
- "msg": "field required",
- "type": "value_error.missing",
- }
- ]
- }
- )
+ assert response.json() == {
+ "detail": [
+ {
+ "type": "missing",
+ "loc": ["query", "query"],
+ "msg": "Field required",
+ "input": None,
+ }
+ ]
+ }
def test_query_param_required_int_query_50():
@@ -367,29 +236,16 @@ def test_query_param_required_int_query_50():
def test_query_param_required_int_query_foo():
response = client.get("/query/param-required/int?query=foo")
assert response.status_code == 422
- assert response.json() == IsDict(
- {
- "detail": [
- {
- "type": "int_parsing",
- "loc": ["query", "query"],
- "msg": "Input should be a valid integer, unable to parse string as an integer",
- "input": "foo",
- }
- ]
- }
- ) | IsDict(
- # TODO: remove when deprecating Pydantic v1
- {
- "detail": [
- {
- "loc": ["query", "query"],
- "msg": "value is not a valid integer",
- "type": "type_error.integer",
- }
- ]
- }
- )
+ assert response.json() == {
+ "detail": [
+ {
+ "type": "int_parsing",
+ "loc": ["query", "query"],
+ "msg": "Input should be a valid integer, unable to parse string as an integer",
+ "input": "foo",
+ }
+ ]
+ }
def test_query_frozenset_query_1_query_1_query_2():
diff --git a/tests/test_query_cookie_header_model_extra_params.py b/tests/test_query_cookie_header_model_extra_params.py
index f4ebefb3f3..d361e1e533 100644
--- a/tests/test_query_cookie_header_model_extra_params.py
+++ b/tests/test_query_cookie_header_model_extra_params.py
@@ -1,5 +1,4 @@
from fastapi import Cookie, FastAPI, Header, Query
-from fastapi._compat import PYDANTIC_V2
from fastapi.testclient import TestClient
from pydantic import BaseModel
@@ -9,12 +8,7 @@ app = FastAPI()
class Model(BaseModel):
param: str
- if PYDANTIC_V2:
- model_config = {"extra": "allow"}
- else:
-
- class Config:
- extra = "allow"
+ model_config = {"extra": "allow"}
@app.get("/query")
diff --git a/tests/test_read_with_orm_mode.py b/tests/test_read_with_orm_mode.py
index b359874439..cd7389252a 100644
--- a/tests/test_read_with_orm_mode.py
+++ b/tests/test_read_with_orm_mode.py
@@ -4,10 +4,7 @@ from fastapi import FastAPI
from fastapi.testclient import TestClient
from pydantic import BaseModel, ConfigDict
-from .utils import needs_pydanticv1, needs_pydanticv2
-
-@needs_pydanticv2
def test_read_with_orm_mode() -> None:
class PersonBase(BaseModel):
name: str
@@ -44,45 +41,3 @@ def test_read_with_orm_mode() -> None:
assert data["name"] == person_data["name"]
assert data["lastname"] == person_data["lastname"]
assert data["full_name"] == person_data["name"] + " " + person_data["lastname"]
-
-
-@needs_pydanticv1
-def test_read_with_orm_mode_pv1() -> None:
- class PersonBase(BaseModel):
- name: str
- lastname: str
-
- class Person(PersonBase):
- @property
- def full_name(self) -> str:
- return f"{self.name} {self.lastname}"
-
- class Config:
- orm_mode = True
- read_with_orm_mode = True
-
- class PersonCreate(PersonBase):
- pass
-
- class PersonRead(PersonBase):
- full_name: str
-
- class Config:
- orm_mode = True
-
- app = FastAPI()
-
- @app.post("/people/", response_model=PersonRead)
- def create_person(person: PersonCreate) -> Any:
- db_person = Person.from_orm(person)
- return db_person
-
- client = TestClient(app)
-
- person_data = {"name": "Dive", "lastname": "Wilson"}
- response = client.post("/people/", json=person_data)
- data = response.json()
- assert response.status_code == 200, response.text
- assert data["name"] == person_data["name"]
- assert data["lastname"] == person_data["lastname"]
- assert data["full_name"] == person_data["name"] + " " + person_data["lastname"]
diff --git a/tests/test_regex_deprecated_body.py b/tests/test_regex_deprecated_body.py
index 74654ff3ce..5b4daa450f 100644
--- a/tests/test_regex_deprecated_body.py
+++ b/tests/test_regex_deprecated_body.py
@@ -1,15 +1,17 @@
+from typing import Annotated
+
import pytest
-from dirty_equals import IsDict
from fastapi import FastAPI, Form
+from fastapi.exceptions import FastAPIDeprecationWarning
from fastapi.testclient import TestClient
-from typing_extensions import Annotated
+from inline_snapshot import snapshot
from .utils import needs_py310
def get_client():
app = FastAPI()
- with pytest.warns(DeprecationWarning):
+ with pytest.warns(FastAPIDeprecationWarning):
@app.post("/items/")
async def read_items(
@@ -45,31 +47,17 @@ def test_query_nonregexquery():
client = get_client()
response = client.post("/items/", data={"q": "nonregexquery"})
assert response.status_code == 422
- assert response.json() == IsDict(
- {
- "detail": [
- {
- "type": "string_pattern_mismatch",
- "loc": ["body", "q"],
- "msg": "String should match pattern '^fixedquery$'",
- "input": "nonregexquery",
- "ctx": {"pattern": "^fixedquery$"},
- }
- ]
- }
- ) | IsDict(
- # TODO: remove when deprecating Pydantic v1
- {
- "detail": [
- {
- "ctx": {"pattern": "^fixedquery$"},
- "loc": ["body", "q"],
- "msg": 'string does not match regex "^fixedquery$"',
- "type": "value_error.str.regex",
- }
- ]
- }
- )
+ assert response.json() == {
+ "detail": [
+ {
+ "type": "string_pattern_mismatch",
+ "loc": ["body", "q"],
+ "msg": "String should match pattern '^fixedquery$'",
+ "input": "nonregexquery",
+ "ctx": {"pattern": "^fixedquery$"},
+ }
+ ]
+ }
@needs_py310
@@ -77,104 +65,88 @@ def test_openapi_schema():
client = get_client()
response = client.get("/openapi.json")
assert response.status_code == 200, response.text
- # insert_assert(response.json())
- assert response.json() == {
- "openapi": "3.1.0",
- "info": {"title": "FastAPI", "version": "0.1.0"},
- "paths": {
- "/items/": {
- "post": {
- "summary": "Read Items",
- "operationId": "read_items_items__post",
- "requestBody": {
- "content": {
- "application/x-www-form-urlencoded": {
- "schema": IsDict(
- {
- "allOf": [
- {
- "$ref": "#/components/schemas/Body_read_items_items__post"
- }
- ],
- "title": "Body",
- }
- )
- | IsDict(
- # TODO: remove when deprecating Pydantic v1
- {
+ assert response.json() == snapshot(
+ {
+ "openapi": "3.1.0",
+ "info": {"title": "FastAPI", "version": "0.1.0"},
+ "paths": {
+ "/items/": {
+ "post": {
+ "summary": "Read Items",
+ "operationId": "read_items_items__post",
+ "requestBody": {
+ "content": {
+ "application/x-www-form-urlencoded": {
+ "schema": {
"$ref": "#/components/schemas/Body_read_items_items__post"
}
- )
- }
- }
- },
- "responses": {
- "200": {
- "description": "Successful Response",
- "content": {"application/json": {"schema": {}}},
- },
- "422": {
- "description": "Validation Error",
- "content": {
- "application/json": {
- "schema": {
- "$ref": "#/components/schemas/HTTPValidationError"
- }
}
+ }
+ },
+ "responses": {
+ "200": {
+ "description": "Successful Response",
+ "content": {"application/json": {"schema": {}}},
+ },
+ "422": {
+ "description": "Validation Error",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/HTTPValidationError"
+ }
+ }
+ },
},
},
- },
+ }
}
- }
- },
- "components": {
- "schemas": {
- "Body_read_items_items__post": {
- "properties": {
- "q": IsDict(
- {
+ },
+ "components": {
+ "schemas": {
+ "Body_read_items_items__post": {
+ "properties": {
+ "q": {
"anyOf": [
{"type": "string", "pattern": "^fixedquery$"},
{"type": "null"},
],
"title": "Q",
}
- )
- | IsDict(
- # TODO: remove when deprecating Pydantic v1
- {"type": "string", "pattern": "^fixedquery$", "title": "Q"}
- )
- },
- "type": "object",
- "title": "Body_read_items_items__post",
- },
- "HTTPValidationError": {
- "properties": {
- "detail": {
- "items": {"$ref": "#/components/schemas/ValidationError"},
- "type": "array",
- "title": "Detail",
- }
- },
- "type": "object",
- "title": "HTTPValidationError",
- },
- "ValidationError": {
- "properties": {
- "loc": {
- "items": {
- "anyOf": [{"type": "string"}, {"type": "integer"}]
- },
- "type": "array",
- "title": "Location",
},
- "msg": {"type": "string", "title": "Message"},
- "type": {"type": "string", "title": "Error Type"},
+ "type": "object",
+ "title": "Body_read_items_items__post",
},
- "type": "object",
- "required": ["loc", "msg", "type"],
- "title": "ValidationError",
- },
- }
- },
- }
+ "HTTPValidationError": {
+ "properties": {
+ "detail": {
+ "items": {
+ "$ref": "#/components/schemas/ValidationError"
+ },
+ "type": "array",
+ "title": "Detail",
+ }
+ },
+ "type": "object",
+ "title": "HTTPValidationError",
+ },
+ "ValidationError": {
+ "properties": {
+ "loc": {
+ "items": {
+ "anyOf": [{"type": "string"}, {"type": "integer"}]
+ },
+ "type": "array",
+ "title": "Location",
+ },
+ "msg": {"type": "string", "title": "Message"},
+ "type": {"type": "string", "title": "Error Type"},
+ },
+ "type": "object",
+ "required": ["loc", "msg", "type"],
+ "title": "ValidationError",
+ },
+ }
+ },
+ }
+ )
diff --git a/tests/test_regex_deprecated_params.py b/tests/test_regex_deprecated_params.py
index 2ce64c6862..d6eaa45fb1 100644
--- a/tests/test_regex_deprecated_params.py
+++ b/tests/test_regex_deprecated_params.py
@@ -1,15 +1,16 @@
+from typing import Annotated
+
import pytest
-from dirty_equals import IsDict
from fastapi import FastAPI, Query
+from fastapi.exceptions import FastAPIDeprecationWarning
from fastapi.testclient import TestClient
-from typing_extensions import Annotated
from .utils import needs_py310
def get_client():
app = FastAPI()
- with pytest.warns(DeprecationWarning):
+ with pytest.warns(FastAPIDeprecationWarning):
@app.get("/items/")
async def read_items(
@@ -45,31 +46,17 @@ def test_query_params_str_validations_item_query_nonregexquery():
client = get_client()
response = client.get("/items/", params={"q": "nonregexquery"})
assert response.status_code == 422
- assert response.json() == IsDict(
- {
- "detail": [
- {
- "type": "string_pattern_mismatch",
- "loc": ["query", "q"],
- "msg": "String should match pattern '^fixedquery$'",
- "input": "nonregexquery",
- "ctx": {"pattern": "^fixedquery$"},
- }
- ]
- }
- ) | IsDict(
- # TODO: remove when deprecating Pydantic v1
- {
- "detail": [
- {
- "ctx": {"pattern": "^fixedquery$"},
- "loc": ["query", "q"],
- "msg": 'string does not match regex "^fixedquery$"',
- "type": "value_error.str.regex",
- }
- ]
- }
- )
+ assert response.json() == {
+ "detail": [
+ {
+ "type": "string_pattern_mismatch",
+ "loc": ["query", "q"],
+ "msg": "String should match pattern '^fixedquery$'",
+ "input": "nonregexquery",
+ "ctx": {"pattern": "^fixedquery$"},
+ }
+ ]
+ }
@needs_py310
@@ -91,23 +78,13 @@ def test_openapi_schema():
"name": "q",
"in": "query",
"required": False,
- "schema": IsDict(
- {
- "anyOf": [
- {"type": "string", "pattern": "^fixedquery$"},
- {"type": "null"},
- ],
- "title": "Q",
- }
- )
- | IsDict(
- # TODO: remove when deprecating Pydantic v1
- {
- "type": "string",
- "pattern": "^fixedquery$",
- "title": "Q",
- }
- ),
+ "schema": {
+ "anyOf": [
+ {"type": "string", "pattern": "^fixedquery$"},
+ {"type": "null"},
+ ],
+ "title": "Q",
+ },
}
],
"responses": {
diff --git a/tests/test_request_body_parameters_media_type.py b/tests/test_request_body_parameters_media_type.py
index 8c72fee54a..d1bff9ddf4 100644
--- a/tests/test_request_body_parameters_media_type.py
+++ b/tests/test_request_body_parameters_media_type.py
@@ -1,5 +1,3 @@
-import typing
-
from fastapi import Body, FastAPI
from fastapi.testclient import TestClient
from pydantic import BaseModel
@@ -28,7 +26,7 @@ async def create_product(data: Product = Body(media_type=media_type, embed=True)
@app.post("/shops")
async def create_shop(
data: Shop = Body(media_type=media_type),
- included: typing.List[Product] = Body(default=[], media_type=media_type),
+ included: list[Product] = Body(default=[], media_type=media_type),
):
pass # pragma: no cover
diff --git a/tests/test_request_param_model_by_alias.py b/tests/test_request_param_model_by_alias.py
index a6f759f23b..c29130d7a6 100644
--- a/tests/test_request_param_model_by_alias.py
+++ b/tests/test_request_param_model_by_alias.py
@@ -1,6 +1,5 @@
from dirty_equals import IsPartialDict
from fastapi import Cookie, FastAPI, Header, Query
-from fastapi._compat import PYDANTIC_V2
from fastapi.testclient import TestClient
from pydantic import BaseModel, Field
@@ -53,8 +52,7 @@ def test_query_model_with_alias_by_name():
response = client.get("/query", params={"param": "value"})
assert response.status_code == 422, response.text
details = response.json()
- if PYDANTIC_V2:
- assert details["detail"][0]["input"] == {"param": "value"}
+ assert details["detail"][0]["input"] == {"param": "value"}
def test_header_model_with_alias_by_name():
@@ -62,8 +60,7 @@ def test_header_model_with_alias_by_name():
response = client.get("/header", headers={"param": "value"})
assert response.status_code == 422, response.text
details = response.json()
- if PYDANTIC_V2:
- assert details["detail"][0]["input"] == IsPartialDict({"param": "value"})
+ assert details["detail"][0]["input"] == IsPartialDict({"param": "value"})
def test_cookie_model_with_alias_by_name():
@@ -72,5 +69,4 @@ def test_cookie_model_with_alias_by_name():
response = client.get("/cookie")
assert response.status_code == 422, response.text
details = response.json()
- if PYDANTIC_V2:
- assert details["detail"][0]["input"] == {"param": "value"}
+ assert details["detail"][0]["input"] == {"param": "value"}
diff --git a/tests/test_request_params/test_body/test_list.py b/tests/test_request_params/test_body/test_list.py
index 18a2a2f308..970e6a6607 100644
--- a/tests/test_request_params/test_body/test_list.py
+++ b/tests/test_request_params/test_body/test_list.py
@@ -1,13 +1,10 @@
-from typing import List, Union
+from typing import Annotated, Union
import pytest
-from dirty_equals import IsDict, IsOneOf, IsPartialDict
+from dirty_equals import IsOneOf, IsPartialDict
from fastapi import Body, FastAPI
from fastapi.testclient import TestClient
from pydantic import BaseModel, Field
-from typing_extensions import Annotated
-
-from tests.utils import needs_pydanticv2
from .utils import get_body_model_name
@@ -18,12 +15,12 @@ app = FastAPI()
@app.post("/required-list-str", operation_id="required_list_str")
-async def read_required_list_str(p: Annotated[List[str], Body(embed=True)]):
+async def read_required_list_str(p: Annotated[list[str], Body(embed=True)]):
return {"p": p}
class BodyModelRequiredListStr(BaseModel):
- p: List[str]
+ p: list[str]
@app.post("/model-required-list-str", operation_id="model_required_list_str")
@@ -62,28 +59,16 @@ def test_required_list_str_missing(path: str, json: Union[dict, None]):
client = TestClient(app)
response = client.post(path, json=json)
assert response.status_code == 422
- assert response.json() == IsDict(
- {
- "detail": [
- {
- "type": "missing",
- "loc": IsOneOf(["body", "p"], ["body"]),
- "msg": "Field required",
- "input": IsOneOf(None, {}),
- }
- ]
- }
- ) | IsDict(
- {
- "detail": [
- {
- "loc": IsOneOf(["body", "p"], ["body"]),
- "msg": "field required",
- "type": "value_error.missing",
- }
- ]
- }
- )
+ assert response.json() == {
+ "detail": [
+ {
+ "type": "missing",
+ "loc": IsOneOf(["body", "p"], ["body"]),
+ "msg": "Field required",
+ "input": IsOneOf(None, {}),
+ }
+ ]
+ }
@pytest.mark.parametrize(
@@ -103,13 +88,13 @@ def test_required_list_str(path: str):
@app.post("/required-list-alias", operation_id="required_list_alias")
async def read_required_list_alias(
- p: Annotated[List[str], Body(embed=True, alias="p_alias")],
+ p: Annotated[list[str], Body(embed=True, alias="p_alias")],
):
return {"p": p}
class BodyModelRequiredListAlias(BaseModel):
- p: List[str] = Field(alias="p_alias")
+ p: list[str] = Field(alias="p_alias")
@app.post("/model-required-list-alias", operation_id="model_required_list_alias")
@@ -151,29 +136,16 @@ def test_required_list_alias_missing(path: str, json: Union[dict, None]):
client = TestClient(app)
response = client.post(path, json=json)
assert response.status_code == 422
- assert response.json() == IsDict(
- {
- "detail": [
- {
- "type": "missing",
- "loc": IsOneOf(["body", "p_alias"], ["body"]),
- "msg": "Field required",
- "input": IsOneOf(None, {}),
- }
- ]
- }
- ) | IsDict(
- # TODO: remove when deprecating Pydantic v1
- {
- "detail": [
- {
- "loc": IsOneOf(["body", "p_alias"], ["body"]),
- "msg": "field required",
- "type": "value_error.missing",
- }
- ]
- }
- )
+ assert response.json() == {
+ "detail": [
+ {
+ "type": "missing",
+ "loc": IsOneOf(["body", "p_alias"], ["body"]),
+ "msg": "Field required",
+ "input": IsOneOf(None, {}),
+ }
+ ]
+ }
@pytest.mark.parametrize(
@@ -184,29 +156,16 @@ def test_required_list_alias_by_name(path: str):
client = TestClient(app)
response = client.post(path, json={"p": ["hello", "world"]})
assert response.status_code == 422
- assert response.json() == IsDict(
- {
- "detail": [
- {
- "type": "missing",
- "loc": ["body", "p_alias"],
- "msg": "Field required",
- "input": IsOneOf(None, {"p": ["hello", "world"]}),
- }
- ]
- }
- ) | IsDict(
- # TODO: remove when deprecating Pydantic v1
- {
- "detail": [
- {
- "loc": ["body", "p_alias"],
- "msg": "field required",
- "type": "value_error.missing",
- }
- ]
- }
- )
+ assert response.json() == {
+ "detail": [
+ {
+ "type": "missing",
+ "loc": ["body", "p_alias"],
+ "msg": "Field required",
+ "input": IsOneOf(None, {"p": ["hello", "world"]}),
+ }
+ ]
+ }
@pytest.mark.parametrize(
@@ -228,13 +187,13 @@ def test_required_list_alias_by_alias(path: str):
"/required-list-validation-alias", operation_id="required_list_validation_alias"
)
def read_required_list_validation_alias(
- p: Annotated[List[str], Body(embed=True, validation_alias="p_val_alias")],
+ p: Annotated[list[str], Body(embed=True, validation_alias="p_val_alias")],
):
return {"p": p}
class BodyModelRequiredListValidationAlias(BaseModel):
- p: List[str] = Field(validation_alias="p_val_alias")
+ p: list[str] = Field(validation_alias="p_val_alias")
@app.post(
@@ -247,7 +206,6 @@ async def read_model_required_list_validation_alias(
return {"p": p.p}
-@needs_pydanticv2
@pytest.mark.parametrize(
"path",
["/required-list-validation-alias", "/model-required-list-validation-alias"],
@@ -270,7 +228,6 @@ def test_required_list_validation_alias_schema(path: str):
}
-@needs_pydanticv2
@pytest.mark.parametrize("json", [None, {}])
@pytest.mark.parametrize(
"path",
@@ -295,7 +252,6 @@ def test_required_list_validation_alias_missing(path: str, json: Union[dict, Non
}
-@needs_pydanticv2
@pytest.mark.parametrize(
"path",
[
@@ -320,7 +276,6 @@ def test_required_list_validation_alias_by_name(path: str):
}
-@needs_pydanticv2
@pytest.mark.parametrize(
"path",
[
@@ -345,14 +300,14 @@ def test_required_list_validation_alias_by_validation_alias(path: str):
)
def read_required_list_alias_and_validation_alias(
p: Annotated[
- List[str], Body(embed=True, alias="p_alias", validation_alias="p_val_alias")
+ list[str], Body(embed=True, alias="p_alias", validation_alias="p_val_alias")
],
):
return {"p": p}
class BodyModelRequiredListAliasAndValidationAlias(BaseModel):
- p: List[str] = Field(alias="p_alias", validation_alias="p_val_alias")
+ p: list[str] = Field(alias="p_alias", validation_alias="p_val_alias")
@app.post(
@@ -365,7 +320,6 @@ def read_model_required_list_alias_and_validation_alias(
return {"p": p.p}
-@needs_pydanticv2
@pytest.mark.parametrize(
"path",
[
@@ -391,7 +345,6 @@ def test_required_list_alias_and_validation_alias_schema(path: str):
}
-@needs_pydanticv2
@pytest.mark.parametrize("json", [None, {}])
@pytest.mark.parametrize(
"path",
@@ -416,7 +369,6 @@ def test_required_list_alias_and_validation_alias_missing(path: str, json):
}
-@needs_pydanticv2
@pytest.mark.parametrize(
"path",
[
@@ -443,7 +395,6 @@ def test_required_list_alias_and_validation_alias_by_name(path: str):
}
-@needs_pydanticv2
@pytest.mark.parametrize(
"path",
[
@@ -468,7 +419,6 @@ def test_required_list_alias_and_validation_alias_by_alias(path: str):
}
-@needs_pydanticv2
@pytest.mark.parametrize(
"path",
[
diff --git a/tests/test_request_params/test_body/test_optional_list.py b/tests/test_request_params/test_body/test_optional_list.py
index e2ecdc7f43..ba8ba9092e 100644
--- a/tests/test_request_params/test_body/test_optional_list.py
+++ b/tests/test_request_params/test_body/test_optional_list.py
@@ -1,13 +1,9 @@
-from typing import List, Optional
+from typing import Annotated, Optional
import pytest
-from dirty_equals import IsDict
from fastapi import Body, FastAPI
from fastapi.testclient import TestClient
from pydantic import BaseModel, Field
-from typing_extensions import Annotated
-
-from tests.utils import needs_pydanticv2
from .utils import get_body_model_name
@@ -19,13 +15,13 @@ app = FastAPI()
@app.post("/optional-list-str", operation_id="optional_list_str")
async def read_optional_list_str(
- p: Annotated[Optional[List[str]], Body(embed=True)] = None,
+ p: Annotated[Optional[list[str]], Body(embed=True)] = None,
):
return {"p": p}
class BodyModelOptionalListStr(BaseModel):
- p: Optional[List[str]] = None
+ p: Optional[list[str]] = None
@app.post("/model-optional-list-str", operation_id="model_optional_list_str")
@@ -41,30 +37,19 @@ def test_optional_list_str_schema(path: str):
openapi = app.openapi()
body_model_name = get_body_model_name(openapi, path)
- assert app.openapi()["components"]["schemas"][body_model_name] == IsDict(
- {
- "properties": {
- "p": {
- "anyOf": [
- {"items": {"type": "string"}, "type": "array"},
- {"type": "null"},
- ],
- "title": "P",
- },
+ assert app.openapi()["components"]["schemas"][body_model_name] == {
+ "properties": {
+ "p": {
+ "anyOf": [
+ {"items": {"type": "string"}, "type": "array"},
+ {"type": "null"},
+ ],
+ "title": "P",
},
- "title": body_model_name,
- "type": "object",
- }
- ) | IsDict(
- # TODO: remove when deprecating Pydantic v1
- {
- "properties": {
- "p": {"items": {"type": "string"}, "type": "array", "title": "P"},
- },
- "title": body_model_name,
- "type": "object",
- }
- )
+ },
+ "title": body_model_name,
+ "type": "object",
+ }
def test_optional_list_str_missing():
@@ -78,29 +63,16 @@ def test_model_optional_list_str_missing():
client = TestClient(app)
response = client.post("/model-optional-list-str")
assert response.status_code == 422, response.text
- assert response.json() == IsDict(
- {
- "detail": [
- {
- "input": None,
- "loc": ["body"],
- "msg": "Field required",
- "type": "missing",
- },
- ],
- }
- ) | IsDict(
- {
- # TODO: remove when deprecating Pydantic v1
- "detail": [
- {
- "loc": ["body"],
- "msg": "field required",
- "type": "value_error.missing",
- },
- ],
- }
- )
+ assert response.json() == {
+ "detail": [
+ {
+ "input": None,
+ "loc": ["body"],
+ "msg": "Field required",
+ "type": "missing",
+ },
+ ],
+ }
@pytest.mark.parametrize(
@@ -131,13 +103,13 @@ def test_optional_list_str(path: str):
@app.post("/optional-list-alias", operation_id="optional_list_alias")
async def read_optional_list_alias(
- p: Annotated[Optional[List[str]], Body(embed=True, alias="p_alias")] = None,
+ p: Annotated[Optional[list[str]], Body(embed=True, alias="p_alias")] = None,
):
return {"p": p}
class BodyModelOptionalListAlias(BaseModel):
- p: Optional[List[str]] = Field(None, alias="p_alias")
+ p: Optional[list[str]] = Field(None, alias="p_alias")
@app.post("/model-optional-list-alias", operation_id="model_optional_list_alias")
@@ -156,34 +128,19 @@ def test_optional_list_str_alias_schema(path: str):
openapi = app.openapi()
body_model_name = get_body_model_name(openapi, path)
- assert app.openapi()["components"]["schemas"][body_model_name] == IsDict(
- {
- "properties": {
- "p_alias": {
- "anyOf": [
- {"items": {"type": "string"}, "type": "array"},
- {"type": "null"},
- ],
- "title": "P Alias",
- },
+ assert app.openapi()["components"]["schemas"][body_model_name] == {
+ "properties": {
+ "p_alias": {
+ "anyOf": [
+ {"items": {"type": "string"}, "type": "array"},
+ {"type": "null"},
+ ],
+ "title": "P Alias",
},
- "title": body_model_name,
- "type": "object",
- }
- ) | IsDict(
- # TODO: remove when deprecating Pydantic v1
- {
- "properties": {
- "p_alias": {
- "items": {"type": "string"},
- "type": "array",
- "title": "P Alias",
- },
- },
- "title": body_model_name,
- "type": "object",
- }
- )
+ },
+ "title": body_model_name,
+ "type": "object",
+ }
def test_optional_list_alias_missing():
@@ -197,29 +154,16 @@ def test_model_optional_list_alias_missing():
client = TestClient(app)
response = client.post("/model-optional-list-alias")
assert response.status_code == 422, response.text
- assert response.json() == IsDict(
- {
- "detail": [
- {
- "input": None,
- "loc": ["body"],
- "msg": "Field required",
- "type": "missing",
- },
- ],
- }
- ) | IsDict(
- {
- # TODO: remove when deprecating Pydantic v1
- "detail": [
- {
- "loc": ["body"],
- "msg": "field required",
- "type": "value_error.missing",
- },
- ],
- }
- )
+ assert response.json() == {
+ "detail": [
+ {
+ "input": None,
+ "loc": ["body"],
+ "msg": "Field required",
+ "type": "missing",
+ },
+ ],
+ }
@pytest.mark.parametrize(
@@ -264,14 +208,14 @@ def test_optional_list_alias_by_alias(path: str):
)
def read_optional_list_validation_alias(
p: Annotated[
- Optional[List[str]], Body(embed=True, validation_alias="p_val_alias")
+ Optional[list[str]], Body(embed=True, validation_alias="p_val_alias")
] = None,
):
return {"p": p}
class BodyModelOptionalListValidationAlias(BaseModel):
- p: Optional[List[str]] = Field(None, validation_alias="p_val_alias")
+ p: Optional[list[str]] = Field(None, validation_alias="p_val_alias")
@app.post(
@@ -284,7 +228,6 @@ def read_model_optional_list_validation_alias(
return {"p": p.p}
-@needs_pydanticv2
@pytest.mark.parametrize(
"path",
["/optional-list-validation-alias", "/model-optional-list-validation-alias"],
@@ -293,34 +236,19 @@ def test_optional_list_validation_alias_schema(path: str):
openapi = app.openapi()
body_model_name = get_body_model_name(openapi, path)
- assert app.openapi()["components"]["schemas"][body_model_name] == IsDict(
- {
- "properties": {
- "p_val_alias": {
- "anyOf": [
- {"items": {"type": "string"}, "type": "array"},
- {"type": "null"},
- ],
- "title": "P Val Alias",
- },
+ assert app.openapi()["components"]["schemas"][body_model_name] == {
+ "properties": {
+ "p_val_alias": {
+ "anyOf": [
+ {"items": {"type": "string"}, "type": "array"},
+ {"type": "null"},
+ ],
+ "title": "P Val Alias",
},
- "title": body_model_name,
- "type": "object",
- }
- ) | IsDict(
- # TODO: remove when deprecating Pydantic v1
- {
- "properties": {
- "p_val_alias": {
- "items": {"type": "string"},
- "type": "array",
- "title": "P Val Alias",
- },
- },
- "title": body_model_name,
- "type": "object",
- }
- )
+ },
+ "title": body_model_name,
+ "type": "object",
+ }
def test_optional_list_validation_alias_missing():
@@ -334,29 +262,16 @@ def test_model_optional_list_validation_alias_missing():
client = TestClient(app)
response = client.post("/model-optional-list-validation-alias")
assert response.status_code == 422, response.text
- assert response.json() == IsDict(
- {
- "detail": [
- {
- "input": None,
- "loc": ["body"],
- "msg": "Field required",
- "type": "missing",
- },
- ],
- }
- ) | IsDict(
- {
- # TODO: remove when deprecating Pydantic v1
- "detail": [
- {
- "loc": ["body"],
- "msg": "field required",
- "type": "value_error.missing",
- },
- ],
- }
- )
+ assert response.json() == {
+ "detail": [
+ {
+ "input": None,
+ "loc": ["body"],
+ "msg": "Field required",
+ "type": "missing",
+ },
+ ],
+ }
@pytest.mark.parametrize(
@@ -370,7 +285,6 @@ def test_optional_list_validation_alias_missing_empty_dict(path: str):
assert response.json() == {"p": None}
-@needs_pydanticv2
@pytest.mark.parametrize(
"path",
[
@@ -385,7 +299,6 @@ def test_optional_list_validation_alias_by_name(path: str):
assert response.json() == {"p": None}
-@needs_pydanticv2
@pytest.mark.parametrize(
"path",
[
@@ -410,7 +323,7 @@ def test_optional_list_validation_alias_by_validation_alias(path: str):
)
def read_optional_list_alias_and_validation_alias(
p: Annotated[
- Optional[List[str]],
+ Optional[list[str]],
Body(embed=True, alias="p_alias", validation_alias="p_val_alias"),
] = None,
):
@@ -418,7 +331,7 @@ def read_optional_list_alias_and_validation_alias(
class BodyModelOptionalListAliasAndValidationAlias(BaseModel):
- p: Optional[List[str]] = Field(
+ p: Optional[list[str]] = Field(
None, alias="p_alias", validation_alias="p_val_alias"
)
@@ -433,7 +346,6 @@ def read_model_optional_list_alias_and_validation_alias(
return {"p": p.p}
-@needs_pydanticv2
@pytest.mark.parametrize(
"path",
[
@@ -445,34 +357,19 @@ def test_optional_list_alias_and_validation_alias_schema(path: str):
openapi = app.openapi()
body_model_name = get_body_model_name(openapi, path)
- assert app.openapi()["components"]["schemas"][body_model_name] == IsDict(
- {
- "properties": {
- "p_val_alias": {
- "anyOf": [
- {"items": {"type": "string"}, "type": "array"},
- {"type": "null"},
- ],
- "title": "P Val Alias",
- },
+ assert app.openapi()["components"]["schemas"][body_model_name] == {
+ "properties": {
+ "p_val_alias": {
+ "anyOf": [
+ {"items": {"type": "string"}, "type": "array"},
+ {"type": "null"},
+ ],
+ "title": "P Val Alias",
},
- "title": body_model_name,
- "type": "object",
- }
- ) | IsDict(
- # TODO: remove when deprecating Pydantic v1
- {
- "properties": {
- "p_val_alias": {
- "items": {"type": "string"},
- "type": "array",
- "title": "P Val Alias",
- },
- },
- "title": body_model_name,
- "type": "object",
- }
- )
+ },
+ "title": body_model_name,
+ "type": "object",
+ }
def test_optional_list_alias_and_validation_alias_missing():
@@ -486,29 +383,16 @@ def test_model_optional_list_alias_and_validation_alias_missing():
client = TestClient(app)
response = client.post("/model-optional-list-alias-and-validation-alias")
assert response.status_code == 422, response.text
- assert response.json() == IsDict(
- {
- "detail": [
- {
- "input": None,
- "loc": ["body"],
- "msg": "Field required",
- "type": "missing",
- },
- ],
- }
- ) | IsDict(
- {
- # TODO: remove when deprecating Pydantic v1
- "detail": [
- {
- "loc": ["body"],
- "msg": "field required",
- "type": "value_error.missing",
- },
- ],
- }
- )
+ assert response.json() == {
+ "detail": [
+ {
+ "input": None,
+ "loc": ["body"],
+ "msg": "Field required",
+ "type": "missing",
+ },
+ ],
+ }
@pytest.mark.parametrize(
@@ -525,7 +409,6 @@ def test_optional_list_alias_and_validation_alias_missing_empty_dict(path: str):
assert response.json() == {"p": None}
-@needs_pydanticv2
@pytest.mark.parametrize(
"path",
[
@@ -540,7 +423,6 @@ def test_optional_list_alias_and_validation_alias_by_name(path: str):
assert response.json() == {"p": None}
-@needs_pydanticv2
@pytest.mark.parametrize(
"path",
[
@@ -555,7 +437,6 @@ def test_optional_list_alias_and_validation_alias_by_alias(path: str):
assert response.json() == {"p": None}
-@needs_pydanticv2
@pytest.mark.parametrize(
"path",
[
diff --git a/tests/test_request_params/test_body/test_optional_str.py b/tests/test_request_params/test_body/test_optional_str.py
index a49f5a3675..b9c18034da 100644
--- a/tests/test_request_params/test_body/test_optional_str.py
+++ b/tests/test_request_params/test_body/test_optional_str.py
@@ -1,13 +1,9 @@
-from typing import Optional
+from typing import Annotated, Optional
import pytest
-from dirty_equals import IsDict
from fastapi import Body, FastAPI
from fastapi.testclient import TestClient
from pydantic import BaseModel, Field
-from typing_extensions import Annotated
-
-from tests.utils import needs_pydanticv2
from .utils import get_body_model_name
@@ -39,27 +35,16 @@ def test_optional_str_schema(path: str):
openapi = app.openapi()
body_model_name = get_body_model_name(openapi, path)
- assert app.openapi()["components"]["schemas"][body_model_name] == IsDict(
- {
- "properties": {
- "p": {
- "anyOf": [{"type": "string"}, {"type": "null"}],
- "title": "P",
- },
+ assert app.openapi()["components"]["schemas"][body_model_name] == {
+ "properties": {
+ "p": {
+ "anyOf": [{"type": "string"}, {"type": "null"}],
+ "title": "P",
},
- "title": body_model_name,
- "type": "object",
- }
- ) | IsDict(
- # TODO: remove when deprecating Pydantic v1
- {
- "properties": {
- "p": {"type": "string", "title": "P"},
- },
- "title": body_model_name,
- "type": "object",
- }
- )
+ },
+ "title": body_model_name,
+ "type": "object",
+ }
def test_optional_str_missing():
@@ -73,29 +58,16 @@ def test_model_optional_str_missing():
client = TestClient(app)
response = client.post("/model-optional-str")
assert response.status_code == 422, response.text
- assert response.json() == IsDict(
- {
- "detail": [
- {
- "input": None,
- "loc": ["body"],
- "msg": "Field required",
- "type": "missing",
- },
- ],
- }
- ) | IsDict(
- {
- # TODO: remove when deprecating Pydantic v1
- "detail": [
- {
- "loc": ["body"],
- "msg": "field required",
- "type": "value_error.missing",
- },
- ],
- }
- )
+ assert response.json() == {
+ "detail": [
+ {
+ "input": None,
+ "loc": ["body"],
+ "msg": "Field required",
+ "type": "missing",
+ },
+ ],
+ }
@pytest.mark.parametrize(
@@ -151,27 +123,16 @@ def test_optional_str_alias_schema(path: str):
openapi = app.openapi()
body_model_name = get_body_model_name(openapi, path)
- assert app.openapi()["components"]["schemas"][body_model_name] == IsDict(
- {
- "properties": {
- "p_alias": {
- "anyOf": [{"type": "string"}, {"type": "null"}],
- "title": "P Alias",
- },
+ assert app.openapi()["components"]["schemas"][body_model_name] == {
+ "properties": {
+ "p_alias": {
+ "anyOf": [{"type": "string"}, {"type": "null"}],
+ "title": "P Alias",
},
- "title": body_model_name,
- "type": "object",
- }
- ) | IsDict(
- # TODO: remove when deprecating Pydantic v1
- {
- "properties": {
- "p_alias": {"type": "string", "title": "P Alias"},
- },
- "title": body_model_name,
- "type": "object",
- }
- )
+ },
+ "title": body_model_name,
+ "type": "object",
+ }
def test_optional_alias_missing():
@@ -185,29 +146,16 @@ def test_model_optional_alias_missing():
client = TestClient(app)
response = client.post("/model-optional-alias")
assert response.status_code == 422, response.text
- assert response.json() == IsDict(
- {
- "detail": [
- {
- "input": None,
- "loc": ["body"],
- "msg": "Field required",
- "type": "missing",
- },
- ],
- }
- ) | IsDict(
- {
- # TODO: remove when deprecating Pydantic v1
- "detail": [
- {
- "loc": ["body"],
- "msg": "field required",
- "type": "value_error.missing",
- },
- ],
- }
- )
+ assert response.json() == {
+ "detail": [
+ {
+ "input": None,
+ "loc": ["body"],
+ "msg": "Field required",
+ "type": "missing",
+ },
+ ],
+ }
@pytest.mark.parametrize(
@@ -269,7 +217,6 @@ def read_model_optional_validation_alias(
return {"p": p.p}
-@needs_pydanticv2
@pytest.mark.parametrize(
"path",
["/optional-validation-alias", "/model-optional-validation-alias"],
@@ -278,30 +225,18 @@ def test_optional_validation_alias_schema(path: str):
openapi = app.openapi()
body_model_name = get_body_model_name(openapi, path)
- assert app.openapi()["components"]["schemas"][body_model_name] == IsDict(
- {
- "properties": {
- "p_val_alias": {
- "anyOf": [{"type": "string"}, {"type": "null"}],
- "title": "P Val Alias",
- },
+ assert app.openapi()["components"]["schemas"][body_model_name] == {
+ "properties": {
+ "p_val_alias": {
+ "anyOf": [{"type": "string"}, {"type": "null"}],
+ "title": "P Val Alias",
},
- "title": body_model_name,
- "type": "object",
- }
- ) | IsDict(
- # TODO: remove when deprecating Pydantic v1
- {
- "properties": {
- "p_val_alias": {"type": "string", "title": "P Val Alias"},
- },
- "title": body_model_name,
- "type": "object",
- }
- )
+ },
+ "title": body_model_name,
+ "type": "object",
+ }
-@needs_pydanticv2
def test_optional_validation_alias_missing():
client = TestClient(app)
response = client.post("/optional-validation-alias")
@@ -309,37 +244,22 @@ def test_optional_validation_alias_missing():
assert response.json() == {"p": None}
-@needs_pydanticv2
def test_model_optional_validation_alias_missing():
client = TestClient(app)
response = client.post("/model-optional-validation-alias")
assert response.status_code == 422, response.text
- assert response.json() == IsDict(
- {
- "detail": [
- {
- "input": None,
- "loc": ["body"],
- "msg": "Field required",
- "type": "missing",
- },
- ],
- }
- ) | IsDict(
- {
- # TODO: remove when deprecating Pydantic v1
- "detail": [
- {
- "loc": ["body"],
- "msg": "field required",
- "type": "value_error.missing",
- },
- ],
- }
- )
+ assert response.json() == {
+ "detail": [
+ {
+ "input": None,
+ "loc": ["body"],
+ "msg": "Field required",
+ "type": "missing",
+ },
+ ],
+ }
-@needs_pydanticv2
@pytest.mark.parametrize(
"path",
["/optional-validation-alias", "/model-optional-validation-alias"],
@@ -351,7 +271,6 @@ def test_model_optional_validation_alias_missing_empty_dict(path: str):
assert response.json() == {"p": None}
-@needs_pydanticv2
@pytest.mark.parametrize(
"path",
[
@@ -366,7 +285,6 @@ def test_optional_validation_alias_by_name(path: str):
assert response.json() == {"p": None}
-@needs_pydanticv2
@pytest.mark.parametrize(
"path",
[
@@ -411,7 +329,6 @@ def read_model_optional_alias_and_validation_alias(
return {"p": p.p}
-@needs_pydanticv2
@pytest.mark.parametrize(
"path",
[
@@ -423,30 +340,18 @@ def test_optional_alias_and_validation_alias_schema(path: str):
openapi = app.openapi()
body_model_name = get_body_model_name(openapi, path)
- assert app.openapi()["components"]["schemas"][body_model_name] == IsDict(
- {
- "properties": {
- "p_val_alias": {
- "anyOf": [{"type": "string"}, {"type": "null"}],
- "title": "P Val Alias",
- },
+ assert app.openapi()["components"]["schemas"][body_model_name] == {
+ "properties": {
+ "p_val_alias": {
+ "anyOf": [{"type": "string"}, {"type": "null"}],
+ "title": "P Val Alias",
},
- "title": body_model_name,
- "type": "object",
- }
- ) | IsDict(
- # TODO: remove when deprecating Pydantic v1
- {
- "properties": {
- "p_val_alias": {"type": "string", "title": "P Val Alias"},
- },
- "title": body_model_name,
- "type": "object",
- }
- )
+ },
+ "title": body_model_name,
+ "type": "object",
+ }
-@needs_pydanticv2
def test_optional_alias_and_validation_alias_missing():
client = TestClient(app)
response = client.post("/optional-alias-and-validation-alias")
@@ -454,37 +359,22 @@ def test_optional_alias_and_validation_alias_missing():
assert response.json() == {"p": None}
-@needs_pydanticv2
def test_model_optional_alias_and_validation_alias_missing():
client = TestClient(app)
response = client.post("/model-optional-alias-and-validation-alias")
assert response.status_code == 422, response.text
- assert response.json() == IsDict(
- {
- "detail": [
- {
- "input": None,
- "loc": ["body"],
- "msg": "Field required",
- "type": "missing",
- },
- ],
- }
- ) | IsDict(
- {
- # TODO: remove when deprecating Pydantic v1
- "detail": [
- {
- "loc": ["body"],
- "msg": "field required",
- "type": "value_error.missing",
- },
- ],
- }
- )
+ assert response.json() == {
+ "detail": [
+ {
+ "input": None,
+ "loc": ["body"],
+ "msg": "Field required",
+ "type": "missing",
+ },
+ ],
+ }
-@needs_pydanticv2
@pytest.mark.parametrize(
"path",
[
@@ -499,7 +389,6 @@ def test_model_optional_alias_and_validation_alias_missing_empty_dict(path: str)
assert response.json() == {"p": None}
-@needs_pydanticv2
@pytest.mark.parametrize(
"path",
[
@@ -514,7 +403,6 @@ def test_optional_alias_and_validation_alias_by_name(path: str):
assert response.json() == {"p": None}
-@needs_pydanticv2
@pytest.mark.parametrize(
"path",
[
@@ -529,7 +417,6 @@ def test_optional_alias_and_validation_alias_by_alias(path: str):
assert response.json() == {"p": None}
-@needs_pydanticv2
@pytest.mark.parametrize(
"path",
[
diff --git a/tests/test_request_params/test_body/test_required_str.py b/tests/test_request_params/test_body/test_required_str.py
index 18c660cad2..5b434fa1db 100644
--- a/tests/test_request_params/test_body/test_required_str.py
+++ b/tests/test_request_params/test_body/test_required_str.py
@@ -1,13 +1,10 @@
-from typing import Any, Dict, Union
+from typing import Annotated, Any, Union
import pytest
-from dirty_equals import IsDict, IsOneOf
+from dirty_equals import IsOneOf
from fastapi import Body, FastAPI
from fastapi.testclient import TestClient
from pydantic import BaseModel, Field
-from typing_extensions import Annotated
-
-from tests.utils import needs_pydanticv2
from .utils import get_body_model_name
@@ -54,33 +51,20 @@ def test_required_str_schema(path: str):
"path",
["/required-str", "/model-required-str"],
)
-def test_required_str_missing(path: str, json: Union[Dict[str, Any], None]):
+def test_required_str_missing(path: str, json: Union[dict[str, Any], None]):
client = TestClient(app)
response = client.post(path, json=json)
assert response.status_code == 422
- assert response.json() == IsDict(
- {
- "detail": [
- {
- "type": "missing",
- "loc": IsOneOf(["body"], ["body", "p"]),
- "msg": "Field required",
- "input": IsOneOf(None, {}),
- }
- ]
- }
- ) | IsDict(
- # TODO: remove when deprecating Pydantic v1
- {
- "detail": [
- {
- "loc": IsOneOf(["body"], ["body", "p"]),
- "msg": "field required",
- "type": "value_error.missing",
- }
- ]
- }
- )
+ assert response.json() == {
+ "detail": [
+ {
+ "type": "missing",
+ "loc": IsOneOf(["body"], ["body", "p"]),
+ "msg": "Field required",
+ "input": IsOneOf(None, {}),
+ }
+ ]
+ }
@pytest.mark.parametrize(
@@ -140,33 +124,20 @@ def test_required_str_alias_schema(path: str):
"path",
["/required-alias", "/model-required-alias"],
)
-def test_required_alias_missing(path: str, json: Union[Dict[str, Any], None]):
+def test_required_alias_missing(path: str, json: Union[dict[str, Any], None]):
client = TestClient(app)
response = client.post(path, json=json)
assert response.status_code == 422
- assert response.json() == IsDict(
- {
- "detail": [
- {
- "type": "missing",
- "loc": IsOneOf(["body", "p_alias"], ["body"]),
- "msg": "Field required",
- "input": IsOneOf(None, {}),
- }
- ]
- }
- ) | IsDict(
- # TODO: remove when deprecating Pydantic v1
- {
- "detail": [
- {
- "loc": IsOneOf(["body", "p_alias"], ["body"]),
- "msg": "field required",
- "type": "value_error.missing",
- }
- ]
- }
- )
+ assert response.json() == {
+ "detail": [
+ {
+ "type": "missing",
+ "loc": IsOneOf(["body", "p_alias"], ["body"]),
+ "msg": "Field required",
+ "input": IsOneOf(None, {}),
+ }
+ ]
+ }
@pytest.mark.parametrize(
@@ -177,29 +148,16 @@ def test_required_alias_by_name(path: str):
client = TestClient(app)
response = client.post(path, json={"p": "hello"})
assert response.status_code == 422
- assert response.json() == IsDict(
- {
- "detail": [
- {
- "type": "missing",
- "loc": ["body", "p_alias"],
- "msg": "Field required",
- "input": IsOneOf(None, {"p": "hello"}),
- }
- ]
- }
- ) | IsDict(
- # TODO: remove when deprecating Pydantic v1
- {
- "detail": [
- {
- "loc": IsOneOf(["body", "p_alias"], ["body"]),
- "msg": "field required",
- "type": "value_error.missing",
- }
- ]
- }
- )
+ assert response.json() == {
+ "detail": [
+ {
+ "type": "missing",
+ "loc": ["body", "p_alias"],
+ "msg": "Field required",
+ "input": IsOneOf(None, {"p": "hello"}),
+ }
+ ]
+ }
@pytest.mark.parametrize(
@@ -237,7 +195,6 @@ def read_model_required_validation_alias(
return {"p": p.p}
-@needs_pydanticv2
@pytest.mark.parametrize(
"path",
["/required-validation-alias", "/model-required-validation-alias"],
@@ -256,7 +213,6 @@ def test_required_validation_alias_schema(path: str):
}
-@needs_pydanticv2
@pytest.mark.parametrize("json", [None, {}])
@pytest.mark.parametrize(
"path",
@@ -266,7 +222,7 @@ def test_required_validation_alias_schema(path: str):
],
)
def test_required_validation_alias_missing(
- path: str, json: Union[Dict[str, Any], None]
+ path: str, json: Union[dict[str, Any], None]
):
client = TestClient(app)
response = client.post(path, json=json)
@@ -283,7 +239,6 @@ def test_required_validation_alias_missing(
}
-@needs_pydanticv2
@pytest.mark.parametrize(
"path",
[
@@ -308,7 +263,6 @@ def test_required_validation_alias_by_name(path: str):
}
-@needs_pydanticv2
@pytest.mark.parametrize(
"path",
[
@@ -354,7 +308,6 @@ def read_model_required_alias_and_validation_alias(
return {"p": p.p}
-@needs_pydanticv2
@pytest.mark.parametrize(
"path",
[
@@ -376,7 +329,6 @@ def test_required_alias_and_validation_alias_schema(path: str):
}
-@needs_pydanticv2
@pytest.mark.parametrize("json", [None, {}])
@pytest.mark.parametrize(
"path",
@@ -386,7 +338,7 @@ def test_required_alias_and_validation_alias_schema(path: str):
],
)
def test_required_alias_and_validation_alias_missing(
- path: str, json: Union[Dict[str, Any], None]
+ path: str, json: Union[dict[str, Any], None]
):
client = TestClient(app)
response = client.post(path, json=json)
@@ -403,7 +355,6 @@ def test_required_alias_and_validation_alias_missing(
}
-@needs_pydanticv2
@pytest.mark.parametrize(
"path",
[
@@ -431,7 +382,6 @@ def test_required_alias_and_validation_alias_by_name(path: str):
}
-@needs_pydanticv2
@pytest.mark.parametrize(
"path",
[
@@ -456,7 +406,6 @@ def test_required_alias_and_validation_alias_by_alias(path: str):
}
-@needs_pydanticv2
@pytest.mark.parametrize(
"path",
[
diff --git a/tests/test_request_params/test_body/utils.py b/tests/test_request_params/test_body/utils.py
index 5151a82d36..bf07394f90 100644
--- a/tests/test_request_params/test_body/utils.py
+++ b/tests/test_request_params/test_body/utils.py
@@ -1,7 +1,7 @@
-from typing import Any, Dict
+from typing import Any
-def get_body_model_name(openapi: Dict[str, Any], path: str) -> str:
+def get_body_model_name(openapi: dict[str, Any], path: str) -> str:
body = openapi["paths"][path]["post"]["requestBody"]
body_schema = body["content"]["application/json"]["schema"]
return body_schema.get("$ref", "").split("/")[-1]
diff --git a/tests/test_request_params/test_cookie/test_optional_str.py b/tests/test_request_params/test_cookie/test_optional_str.py
index 1eec45689d..6f381c8b86 100644
--- a/tests/test_request_params/test_cookie/test_optional_str.py
+++ b/tests/test_request_params/test_cookie/test_optional_str.py
@@ -1,13 +1,9 @@
-from typing import Optional
+from typing import Annotated, Optional
import pytest
-from dirty_equals import IsDict
from fastapi import Cookie, FastAPI
from fastapi.testclient import TestClient
from pydantic import BaseModel, Field
-from typing_extensions import Annotated
-
-from tests.utils import needs_pydanticv2
app = FastAPI()
@@ -35,26 +31,15 @@ async def read_model_optional_str(p: Annotated[CookieModelOptionalStr, Cookie()]
)
def test_optional_str_schema(path: str):
assert app.openapi()["paths"][path]["get"]["parameters"] == [
- IsDict(
- {
- "required": False,
- "schema": {
- "anyOf": [{"type": "string"}, {"type": "null"}],
- "title": "P",
- },
- "name": "p",
- "in": "cookie",
- }
- )
- | IsDict(
- # TODO: remove when deprecating Pydantic v1
- {
- "required": False,
- "schema": {"title": "P", "type": "string"},
- "name": "p",
- "in": "cookie",
- }
- )
+ {
+ "required": False,
+ "schema": {
+ "anyOf": [{"type": "string"}, {"type": "null"}],
+ "title": "P",
+ },
+ "name": "p",
+ "in": "cookie",
+ }
]
@@ -107,26 +92,15 @@ async def read_model_optional_alias(p: Annotated[CookieModelOptionalAlias, Cooki
)
def test_optional_str_alias_schema(path: str):
assert app.openapi()["paths"][path]["get"]["parameters"] == [
- IsDict(
- {
- "required": False,
- "schema": {
- "anyOf": [{"type": "string"}, {"type": "null"}],
- "title": "P Alias",
- },
- "name": "p_alias",
- "in": "cookie",
- }
- )
- | IsDict(
- # TODO: remove when deprecating Pydantic v1
- {
- "required": False,
- "schema": {"title": "P Alias", "type": "string"},
- "name": "p_alias",
- "in": "cookie",
- }
- )
+ {
+ "required": False,
+ "schema": {
+ "anyOf": [{"type": "string"}, {"type": "null"}],
+ "title": "P Alias",
+ },
+ "name": "p_alias",
+ "in": "cookie",
+ }
]
@@ -190,7 +164,6 @@ def read_model_optional_validation_alias(
return {"p": p.p}
-@needs_pydanticv2
@pytest.mark.parametrize(
"path",
["/optional-validation-alias", "/model-optional-validation-alias"],
@@ -209,7 +182,6 @@ def test_optional_validation_alias_schema(path: str):
]
-@needs_pydanticv2
@pytest.mark.parametrize(
"path",
["/optional-validation-alias", "/model-optional-validation-alias"],
@@ -221,7 +193,6 @@ def test_optional_validation_alias_missing(path: str):
assert response.json() == {"p": None}
-@needs_pydanticv2
@pytest.mark.parametrize(
"path",
[
@@ -237,7 +208,6 @@ def test_optional_validation_alias_by_name(path: str):
assert response.json() == {"p": None}
-@needs_pydanticv2
@pytest.mark.parametrize(
"path",
[
@@ -277,7 +247,6 @@ def read_model_optional_alias_and_validation_alias(
return {"p": p.p}
-@needs_pydanticv2
@pytest.mark.parametrize(
"path",
[
@@ -299,7 +268,6 @@ def test_optional_alias_and_validation_alias_schema(path: str):
]
-@needs_pydanticv2
@pytest.mark.parametrize(
"path",
[
@@ -314,7 +282,6 @@ def test_optional_alias_and_validation_alias_missing(path: str):
assert response.json() == {"p": None}
-@needs_pydanticv2
@pytest.mark.parametrize(
"path",
[
@@ -330,7 +297,6 @@ def test_optional_alias_and_validation_alias_by_name(path: str):
assert response.json() == {"p": None}
-@needs_pydanticv2
@pytest.mark.parametrize(
"path",
[
@@ -346,7 +312,6 @@ def test_optional_alias_and_validation_alias_by_alias(path: str):
assert response.json() == {"p": None}
-@needs_pydanticv2
@pytest.mark.parametrize(
"path",
[
diff --git a/tests/test_request_params/test_cookie/test_required_str.py b/tests/test_request_params/test_cookie/test_required_str.py
index 6d0fa2ef29..3e877b3e3d 100644
--- a/tests/test_request_params/test_cookie/test_required_str.py
+++ b/tests/test_request_params/test_cookie/test_required_str.py
@@ -1,11 +1,10 @@
+from typing import Annotated
+
import pytest
-from dirty_equals import IsDict, IsOneOf
+from dirty_equals import IsOneOf
from fastapi import Cookie, FastAPI
from fastapi.testclient import TestClient
from pydantic import BaseModel, Field
-from typing_extensions import Annotated
-
-from tests.utils import needs_pydanticv2
app = FastAPI()
@@ -50,29 +49,16 @@ def test_required_str_missing(path: str):
client = TestClient(app)
response = client.get(path)
assert response.status_code == 422
- assert response.json() == IsDict(
- {
- "detail": [
- {
- "type": "missing",
- "loc": ["cookie", "p"],
- "msg": "Field required",
- "input": IsOneOf(None, {}),
- }
- ]
- }
- ) | IsDict(
- # TODO: remove when deprecating Pydantic v1
- {
- "detail": [
- {
- "loc": ["cookie", "p"],
- "msg": "field required",
- "type": "value_error.missing",
- }
- ]
- }
- )
+ assert response.json() == {
+ "detail": [
+ {
+ "type": "missing",
+ "loc": ["cookie", "p"],
+ "msg": "Field required",
+ "input": IsOneOf(None, {}),
+ }
+ ]
+ }
@pytest.mark.parametrize(
@@ -128,29 +114,16 @@ def test_required_alias_missing(path: str):
client = TestClient(app)
response = client.get(path)
assert response.status_code == 422
- assert response.json() == IsDict(
- {
- "detail": [
- {
- "type": "missing",
- "loc": ["cookie", "p_alias"],
- "msg": "Field required",
- "input": IsOneOf(None, {}),
- }
- ]
- }
- ) | IsDict(
- # TODO: remove when deprecating Pydantic v1
- {
- "detail": [
- {
- "loc": ["cookie", "p_alias"],
- "msg": "field required",
- "type": "value_error.missing",
- }
- ]
- }
- )
+ assert response.json() == {
+ "detail": [
+ {
+ "type": "missing",
+ "loc": ["cookie", "p_alias"],
+ "msg": "Field required",
+ "input": IsOneOf(None, {}),
+ }
+ ]
+ }
@pytest.mark.parametrize(
@@ -165,32 +138,19 @@ def test_required_alias_by_name(path: str):
client.cookies.set("p", "hello")
response = client.get(path)
assert response.status_code == 422
- assert response.json() == IsDict(
- {
- "detail": [
- {
- "type": "missing",
- "loc": ["cookie", "p_alias"],
- "msg": "Field required",
- "input": IsOneOf(
- None,
- {"p": "hello"},
- ),
- }
- ]
- }
- ) | IsDict(
- # TODO: remove when deprecating Pydantic v1
- {
- "detail": [
- {
- "loc": ["cookie", "p_alias"],
- "msg": "field required",
- "type": "value_error.missing",
- }
- ]
- }
- )
+ assert response.json() == {
+ "detail": [
+ {
+ "type": "missing",
+ "loc": ["cookie", "p_alias"],
+ "msg": "Field required",
+ "input": IsOneOf(
+ None,
+ {"p": "hello"},
+ ),
+ }
+ ]
+ }
@pytest.mark.parametrize(
@@ -230,7 +190,6 @@ def read_model_required_validation_alias(
return {"p": p.p}
-@needs_pydanticv2
@pytest.mark.parametrize(
"path",
["/required-validation-alias", "/model-required-validation-alias"],
@@ -246,7 +205,6 @@ def test_required_validation_alias_schema(path: str):
]
-@needs_pydanticv2
@pytest.mark.parametrize(
"path",
[
@@ -273,7 +231,6 @@ def test_required_validation_alias_missing(path: str):
}
-@needs_pydanticv2
@pytest.mark.parametrize(
"path",
[
@@ -299,7 +256,6 @@ def test_required_validation_alias_by_name(path: str):
}
-@needs_pydanticv2
@pytest.mark.parametrize(
"path",
[
@@ -338,7 +294,6 @@ def read_model_required_alias_and_validation_alias(
return {"p": p.p}
-@needs_pydanticv2
@pytest.mark.parametrize(
"path",
[
@@ -357,7 +312,6 @@ def test_required_alias_and_validation_alias_schema(path: str):
]
-@needs_pydanticv2
@pytest.mark.parametrize(
"path",
[
@@ -384,7 +338,6 @@ def test_required_alias_and_validation_alias_missing(path: str):
}
-@needs_pydanticv2
@pytest.mark.parametrize(
"path",
[
@@ -416,7 +369,6 @@ def test_required_alias_and_validation_alias_by_name(path: str):
}
-@needs_pydanticv2
@pytest.mark.parametrize(
"path",
[
@@ -445,7 +397,6 @@ def test_required_alias_and_validation_alias_by_alias(path: str):
}
-@needs_pydanticv2
@pytest.mark.parametrize(
"path",
[
diff --git a/tests/test_request_params/test_file/test_list.py b/tests/test_request_params/test_file/test_list.py
index 94a33967f3..68280fcf32 100644
--- a/tests/test_request_params/test_file/test_list.py
+++ b/tests/test_request_params/test_file/test_list.py
@@ -1,12 +1,8 @@
-from typing import List
+from typing import Annotated
import pytest
-from dirty_equals import IsDict
from fastapi import FastAPI, File, UploadFile
from fastapi.testclient import TestClient
-from typing_extensions import Annotated
-
-from tests.utils import needs_pydanticv2
from .utils import get_body_model_name
@@ -17,12 +13,12 @@ app = FastAPI()
@app.post("/list-bytes", operation_id="list_bytes")
-async def read_list_bytes(p: Annotated[List[bytes], File()]):
+async def read_list_bytes(p: Annotated[list[bytes], File()]):
return {"file_size": [len(file) for file in p]}
@app.post("/list-uploadfile", operation_id="list_uploadfile")
-async def read_list_uploadfile(p: Annotated[List[UploadFile], File()]):
+async def read_list_uploadfile(p: Annotated[list[UploadFile], File()]):
return {"file_size": [file.size for file in p]}
@@ -39,27 +35,11 @@ def test_list_schema(path: str):
assert app.openapi()["components"]["schemas"][body_model_name] == {
"properties": {
- "p": (
- IsDict(
- {
- "anyOf": [
- {
- "type": "array",
- "items": {"type": "string", "format": "binary"},
- },
- {"type": "null"},
- ],
- "title": "P",
- },
- )
- | IsDict(
- {
- "type": "array",
- "items": {"type": "string", "format": "binary"},
- "title": "P",
- },
- )
- )
+ "p": {
+ "type": "array",
+ "items": {"type": "string", "format": "binary"},
+ "title": "P",
+ },
},
"required": ["p"],
"title": body_model_name,
@@ -78,29 +58,16 @@ def test_list_missing(path: str):
client = TestClient(app)
response = client.post(path)
assert response.status_code == 422
- assert response.json() == IsDict(
- {
- "detail": [
- {
- "type": "missing",
- "loc": ["body", "p"],
- "msg": "Field required",
- "input": None,
- }
- ]
- }
- ) | IsDict(
- # TODO: remove when deprecating Pydantic v1
- {
- "detail": [
- {
- "loc": ["body", "p"],
- "msg": "field required",
- "type": "value_error.missing",
- }
- ]
- }
- )
+ assert response.json() == {
+ "detail": [
+ {
+ "type": "missing",
+ "loc": ["body", "p"],
+ "msg": "Field required",
+ "input": None,
+ }
+ ]
+ }
@pytest.mark.parametrize(
@@ -122,13 +89,13 @@ def test_list(path: str):
@app.post("/list-bytes-alias", operation_id="list_bytes_alias")
-async def read_list_bytes_alias(p: Annotated[List[bytes], File(alias="p_alias")]):
+async def read_list_bytes_alias(p: Annotated[list[bytes], File(alias="p_alias")]):
return {"file_size": [len(file) for file in p]}
@app.post("/list-uploadfile-alias", operation_id="list_uploadfile_alias")
async def read_list_uploadfile_alias(
- p: Annotated[List[UploadFile], File(alias="p_alias")],
+ p: Annotated[list[UploadFile], File(alias="p_alias")],
):
return {"file_size": [file.size for file in p]}
@@ -146,27 +113,11 @@ def test_list_alias_schema(path: str):
assert app.openapi()["components"]["schemas"][body_model_name] == {
"properties": {
- "p_alias": (
- IsDict(
- {
- "anyOf": [
- {
- "type": "array",
- "items": {"type": "string", "format": "binary"},
- },
- {"type": "null"},
- ],
- "title": "P Alias",
- },
- )
- | IsDict(
- {
- "type": "array",
- "items": {"type": "string", "format": "binary"},
- "title": "P Alias",
- },
- )
- )
+ "p_alias": {
+ "type": "array",
+ "items": {"type": "string", "format": "binary"},
+ "title": "P Alias",
+ },
},
"required": ["p_alias"],
"title": body_model_name,
@@ -185,29 +136,16 @@ def test_list_alias_missing(path: str):
client = TestClient(app)
response = client.post(path)
assert response.status_code == 422
- assert response.json() == IsDict(
- {
- "detail": [
- {
- "type": "missing",
- "loc": ["body", "p_alias"],
- "msg": "Field required",
- "input": None,
- }
- ]
- }
- ) | IsDict(
- # TODO: remove when deprecating Pydantic v1
- {
- "detail": [
- {
- "loc": ["body", "p_alias"],
- "msg": "field required",
- "type": "value_error.missing",
- }
- ]
- }
- )
+ assert response.json() == {
+ "detail": [
+ {
+ "type": "missing",
+ "loc": ["body", "p_alias"],
+ "msg": "Field required",
+ "input": None,
+ }
+ ]
+ }
@pytest.mark.parametrize(
@@ -221,29 +159,16 @@ def test_list_alias_by_name(path: str):
client = TestClient(app)
response = client.post(path, files=[("p", b"hello"), ("p", b"world")])
assert response.status_code == 422
- assert response.json() == IsDict(
- {
- "detail": [
- {
- "type": "missing",
- "loc": ["body", "p_alias"],
- "msg": "Field required",
- "input": None,
- }
- ]
- }
- ) | IsDict(
- # TODO: remove when deprecating Pydantic v1
- {
- "detail": [
- {
- "loc": ["body", "p_alias"],
- "msg": "field required",
- "type": "value_error.missing",
- }
- ]
- }
- )
+ assert response.json() == {
+ "detail": [
+ {
+ "type": "missing",
+ "loc": ["body", "p_alias"],
+ "msg": "Field required",
+ "input": None,
+ }
+ ]
+ }
@pytest.mark.parametrize(
@@ -266,7 +191,7 @@ def test_list_alias_by_alias(path: str):
@app.post("/list-bytes-validation-alias", operation_id="list_bytes_validation_alias")
def read_list_bytes_validation_alias(
- p: Annotated[List[bytes], File(validation_alias="p_val_alias")],
+ p: Annotated[list[bytes], File(validation_alias="p_val_alias")],
):
return {"file_size": [len(file) for file in p]}
@@ -276,12 +201,11 @@ def read_list_bytes_validation_alias(
operation_id="list_uploadfile_validation_alias",
)
def read_list_uploadfile_validation_alias(
- p: Annotated[List[UploadFile], File(validation_alias="p_val_alias")],
+ p: Annotated[list[UploadFile], File(validation_alias="p_val_alias")],
):
return {"file_size": [file.size for file in p]}
-@needs_pydanticv2
@pytest.mark.parametrize(
"path",
[
@@ -295,27 +219,11 @@ def test_list_validation_alias_schema(path: str):
assert app.openapi()["components"]["schemas"][body_model_name] == {
"properties": {
- "p_val_alias": (
- IsDict(
- {
- "anyOf": [
- {
- "type": "array",
- "items": {"type": "string", "format": "binary"},
- },
- {"type": "null"},
- ],
- "title": "P Val Alias",
- },
- )
- | IsDict(
- {
- "type": "array",
- "items": {"type": "string", "format": "binary"},
- "title": "P Val Alias",
- },
- )
- )
+ "p_val_alias": {
+ "type": "array",
+ "items": {"type": "string", "format": "binary"},
+ "title": "P Val Alias",
+ },
},
"required": ["p_val_alias"],
"title": body_model_name,
@@ -323,7 +231,6 @@ def test_list_validation_alias_schema(path: str):
}
-@needs_pydanticv2
@pytest.mark.parametrize(
"path",
[
@@ -350,7 +257,6 @@ def test_list_validation_alias_missing(path: str):
}
-@needs_pydanticv2
@pytest.mark.parametrize(
"path",
[
@@ -375,7 +281,6 @@ def test_list_validation_alias_by_name(path: str):
}
-@needs_pydanticv2
@pytest.mark.parametrize(
"path",
[
@@ -401,7 +306,7 @@ def test_list_validation_alias_by_validation_alias(path: str):
operation_id="list_bytes_alias_and_validation_alias",
)
def read_list_bytes_alias_and_validation_alias(
- p: Annotated[List[bytes], File(alias="p_alias", validation_alias="p_val_alias")],
+ p: Annotated[list[bytes], File(alias="p_alias", validation_alias="p_val_alias")],
):
return {"file_size": [len(file) for file in p]}
@@ -412,13 +317,12 @@ def read_list_bytes_alias_and_validation_alias(
)
def read_list_uploadfile_alias_and_validation_alias(
p: Annotated[
- List[UploadFile], File(alias="p_alias", validation_alias="p_val_alias")
+ list[UploadFile], File(alias="p_alias", validation_alias="p_val_alias")
],
):
return {"file_size": [file.size for file in p]}
-@needs_pydanticv2
@pytest.mark.parametrize(
"path",
[
@@ -432,27 +336,11 @@ def test_list_alias_and_validation_alias_schema(path: str):
assert app.openapi()["components"]["schemas"][body_model_name] == {
"properties": {
- "p_val_alias": (
- IsDict(
- {
- "anyOf": [
- {
- "type": "array",
- "items": {"type": "string", "format": "binary"},
- },
- {"type": "null"},
- ],
- "title": "P Val Alias",
- },
- )
- | IsDict(
- {
- "type": "array",
- "items": {"type": "string", "format": "binary"},
- "title": "P Val Alias",
- },
- )
- )
+ "p_val_alias": {
+ "type": "array",
+ "items": {"type": "string", "format": "binary"},
+ "title": "P Val Alias",
+ },
},
"required": ["p_val_alias"],
"title": body_model_name,
@@ -460,7 +348,6 @@ def test_list_alias_and_validation_alias_schema(path: str):
}
-@needs_pydanticv2
@pytest.mark.parametrize(
"path",
[
@@ -487,7 +374,6 @@ def test_list_alias_and_validation_alias_missing(path: str):
}
-@needs_pydanticv2
@pytest.mark.parametrize(
"path",
[
@@ -515,7 +401,6 @@ def test_list_alias_and_validation_alias_by_name(path: str):
}
-@needs_pydanticv2
@pytest.mark.parametrize(
"path",
[
@@ -540,7 +425,6 @@ def test_list_alias_and_validation_alias_by_alias(path: str):
}
-@needs_pydanticv2
@pytest.mark.parametrize(
"path",
[
diff --git a/tests/test_request_params/test_file/test_optional.py b/tests/test_request_params/test_file/test_optional.py
index 2c1ca9530e..45ef7bdec4 100644
--- a/tests/test_request_params/test_file/test_optional.py
+++ b/tests/test_request_params/test_file/test_optional.py
@@ -1,12 +1,8 @@
-from typing import Optional
+from typing import Annotated, Optional
import pytest
-from dirty_equals import IsDict
from fastapi import FastAPI, File, UploadFile
from fastapi.testclient import TestClient
-from typing_extensions import Annotated
-
-from tests.utils import needs_pydanticv2
from .utils import get_body_model_name
@@ -39,21 +35,13 @@ def test_optional_schema(path: str):
assert app.openapi()["components"]["schemas"][body_model_name] == {
"properties": {
- "p": (
- IsDict(
- {
- "anyOf": [
- {"type": "string", "format": "binary"},
- {"type": "null"},
- ],
- "title": "P",
- }
- )
- | IsDict(
- # TODO: remove when deprecating Pydantic v1
- {"title": "P", "type": "string", "format": "binary"}
- )
- ),
+ "p": {
+ "anyOf": [
+ {"type": "string", "format": "binary"},
+ {"type": "null"},
+ ],
+ "title": "P",
+ }
},
"title": body_model_name,
"type": "object",
@@ -119,21 +107,13 @@ def test_optional_alias_schema(path: str):
assert app.openapi()["components"]["schemas"][body_model_name] == {
"properties": {
- "p_alias": (
- IsDict(
- {
- "anyOf": [
- {"type": "string", "format": "binary"},
- {"type": "null"},
- ],
- "title": "P Alias",
- }
- )
- | IsDict(
- # TODO: remove when deprecating Pydantic v1
- {"title": "P Alias", "type": "string", "format": "binary"}
- )
- ),
+ "p_alias": {
+ "anyOf": [
+ {"type": "string", "format": "binary"},
+ {"type": "null"},
+ ],
+ "title": "P Alias",
+ }
},
"title": body_model_name,
"type": "object",
@@ -205,7 +185,6 @@ def read_optional_uploadfile_validation_alias(
return {"file_size": p.size if p else None}
-@needs_pydanticv2
@pytest.mark.parametrize(
"path",
[
@@ -219,28 +198,19 @@ def test_optional_validation_alias_schema(path: str):
assert app.openapi()["components"]["schemas"][body_model_name] == {
"properties": {
- "p_val_alias": (
- IsDict(
- {
- "anyOf": [
- {"type": "string", "format": "binary"},
- {"type": "null"},
- ],
- "title": "P Val Alias",
- }
- )
- | IsDict(
- # TODO: remove when deprecating Pydantic v1
- {"title": "P Val Alias", "type": "string", "format": "binary"}
- )
- ),
+ "p_val_alias": {
+ "anyOf": [
+ {"type": "string", "format": "binary"},
+ {"type": "null"},
+ ],
+ "title": "P Val Alias",
+ }
},
"title": body_model_name,
"type": "object",
}
-@needs_pydanticv2
@pytest.mark.parametrize(
"path",
[
@@ -255,7 +225,6 @@ def test_optional_validation_alias_missing(path: str):
assert response.json() == {"file_size": None}
-@needs_pydanticv2
@pytest.mark.parametrize(
"path",
[
@@ -270,7 +239,6 @@ def test_optional_validation_alias_by_name(path: str):
assert response.json() == {"file_size": None}
-@needs_pydanticv2
@pytest.mark.parametrize(
"path",
[
@@ -313,7 +281,6 @@ def read_optional_uploadfile_alias_and_validation_alias(
return {"file_size": p.size if p else None}
-@needs_pydanticv2
@pytest.mark.parametrize(
"path",
[
@@ -327,28 +294,19 @@ def test_optional_alias_and_validation_alias_schema(path: str):
assert app.openapi()["components"]["schemas"][body_model_name] == {
"properties": {
- "p_val_alias": (
- IsDict(
- {
- "anyOf": [
- {"type": "string", "format": "binary"},
- {"type": "null"},
- ],
- "title": "P Val Alias",
- }
- )
- | IsDict(
- # TODO: remove when deprecating Pydantic v1
- {"title": "P Val Alias", "type": "string", "format": "binary"}
- )
- ),
+ "p_val_alias": {
+ "anyOf": [
+ {"type": "string", "format": "binary"},
+ {"type": "null"},
+ ],
+ "title": "P Val Alias",
+ }
},
"title": body_model_name,
"type": "object",
}
-@needs_pydanticv2
@pytest.mark.parametrize(
"path",
[
@@ -363,7 +321,6 @@ def test_optional_alias_and_validation_alias_missing(path: str):
assert response.json() == {"file_size": None}
-@needs_pydanticv2
@pytest.mark.parametrize(
"path",
[
@@ -378,7 +335,6 @@ def test_optional_alias_and_validation_alias_by_name(path: str):
assert response.json() == {"file_size": None}
-@needs_pydanticv2
@pytest.mark.parametrize(
"path",
[
@@ -393,7 +349,6 @@ def test_optional_alias_and_validation_alias_by_alias(path: str):
assert response.json() == {"file_size": None}
-@needs_pydanticv2
@pytest.mark.parametrize(
"path",
[
diff --git a/tests/test_request_params/test_file/test_optional_list.py b/tests/test_request_params/test_file/test_optional_list.py
index 20e36501f8..162fbe08ae 100644
--- a/tests/test_request_params/test_file/test_optional_list.py
+++ b/tests/test_request_params/test_file/test_optional_list.py
@@ -1,12 +1,8 @@
-from typing import List, Optional
+from typing import Annotated, Optional
import pytest
-from dirty_equals import IsDict
from fastapi import FastAPI, File, UploadFile
from fastapi.testclient import TestClient
-from typing_extensions import Annotated
-
-from tests.utils import needs_pydanticv2
from .utils import get_body_model_name
@@ -17,13 +13,13 @@ app = FastAPI()
@app.post("/optional-list-bytes")
-async def read_optional_list_bytes(p: Annotated[Optional[List[bytes]], File()] = None):
+async def read_optional_list_bytes(p: Annotated[Optional[list[bytes]], File()] = None):
return {"file_size": [len(file) for file in p] if p else None}
@app.post("/optional-list-uploadfile")
async def read_optional_list_uploadfile(
- p: Annotated[Optional[List[UploadFile]], File()] = None,
+ p: Annotated[Optional[list[UploadFile]], File()] = None,
):
return {"file_size": [file.size for file in p] if p else None}
@@ -41,28 +37,16 @@ def test_optional_list_schema(path: str):
assert app.openapi()["components"]["schemas"][body_model_name] == {
"properties": {
- "p": (
- IsDict(
+ "p": {
+ "anyOf": [
{
- "anyOf": [
- {
- "type": "array",
- "items": {"type": "string", "format": "binary"},
- },
- {"type": "null"},
- ],
- "title": "P",
- }
- )
- | IsDict(
- # TODO: remove when deprecating Pydantic v1
- {
- "title": "P",
"type": "array",
"items": {"type": "string", "format": "binary"},
},
- )
- ),
+ {"type": "null"},
+ ],
+ "title": "P",
+ }
},
"title": body_model_name,
"type": "object",
@@ -103,14 +87,14 @@ def test_optional_list(path: str):
@app.post("/optional-list-bytes-alias")
async def read_optional_list_bytes_alias(
- p: Annotated[Optional[List[bytes]], File(alias="p_alias")] = None,
+ p: Annotated[Optional[list[bytes]], File(alias="p_alias")] = None,
):
return {"file_size": [len(file) for file in p] if p else None}
@app.post("/optional-list-uploadfile-alias")
async def read_optional_list_uploadfile_alias(
- p: Annotated[Optional[List[UploadFile]], File(alias="p_alias")] = None,
+ p: Annotated[Optional[list[UploadFile]], File(alias="p_alias")] = None,
):
return {"file_size": [file.size for file in p] if p else None}
@@ -128,28 +112,16 @@ def test_optional_list_alias_schema(path: str):
assert app.openapi()["components"]["schemas"][body_model_name] == {
"properties": {
- "p_alias": (
- IsDict(
+ "p_alias": {
+ "anyOf": [
{
- "anyOf": [
- {
- "type": "array",
- "items": {"type": "string", "format": "binary"},
- },
- {"type": "null"},
- ],
- "title": "P Alias",
- }
- )
- | IsDict(
- # TODO: remove when deprecating Pydantic v1
- {
- "title": "P Alias",
"type": "array",
"items": {"type": "string", "format": "binary"},
- }
- )
- ),
+ },
+ {"type": "null"},
+ ],
+ "title": "P Alias",
+ }
},
"title": body_model_name,
"type": "object",
@@ -204,7 +176,7 @@ def test_optional_list_alias_by_alias(path: str):
@app.post("/optional-list-bytes-validation-alias")
def read_optional_list_bytes_validation_alias(
- p: Annotated[Optional[List[bytes]], File(validation_alias="p_val_alias")] = None,
+ p: Annotated[Optional[list[bytes]], File(validation_alias="p_val_alias")] = None,
):
return {"file_size": [len(file) for file in p] if p else None}
@@ -212,13 +184,12 @@ def read_optional_list_bytes_validation_alias(
@app.post("/optional-list-uploadfile-validation-alias")
def read_optional_list_uploadfile_validation_alias(
p: Annotated[
- Optional[List[UploadFile]], File(validation_alias="p_val_alias")
+ Optional[list[UploadFile]], File(validation_alias="p_val_alias")
] = None,
):
return {"file_size": [file.size for file in p] if p else None}
-@needs_pydanticv2
@pytest.mark.parametrize(
"path",
[
@@ -232,35 +203,22 @@ def test_optional_validation_alias_schema(path: str):
assert app.openapi()["components"]["schemas"][body_model_name] == {
"properties": {
- "p_val_alias": (
- IsDict(
+ "p_val_alias": {
+ "anyOf": [
{
- "anyOf": [
- {
- "type": "array",
- "items": {"type": "string", "format": "binary"},
- },
- {"type": "null"},
- ],
- "title": "P Val Alias",
- }
- )
- | IsDict(
- # TODO: remove when deprecating Pydantic v1
- {
- "title": "P Val Alias",
"type": "array",
"items": {"type": "string", "format": "binary"},
- }
- )
- ),
+ },
+ {"type": "null"},
+ ],
+ "title": "P Val Alias",
+ }
},
"title": body_model_name,
"type": "object",
}
-@needs_pydanticv2
@pytest.mark.parametrize(
"path",
[
@@ -275,7 +233,6 @@ def test_optional_validation_alias_missing(path: str):
assert response.json() == {"file_size": None}
-@needs_pydanticv2
@pytest.mark.parametrize(
"path",
[
@@ -290,7 +247,6 @@ def test_optional_validation_alias_by_name(path: str):
assert response.json() == {"file_size": None}
-@needs_pydanticv2
@pytest.mark.parametrize(
"path",
[
@@ -314,7 +270,7 @@ def test_optional_validation_alias_by_validation_alias(path: str):
@app.post("/optional-list-bytes-alias-and-validation-alias")
def read_optional_list_bytes_alias_and_validation_alias(
p: Annotated[
- Optional[List[bytes]], File(alias="p_alias", validation_alias="p_val_alias")
+ Optional[list[bytes]], File(alias="p_alias", validation_alias="p_val_alias")
] = None,
):
return {"file_size": [len(file) for file in p] if p else None}
@@ -323,14 +279,13 @@ def read_optional_list_bytes_alias_and_validation_alias(
@app.post("/optional-list-uploadfile-alias-and-validation-alias")
def read_optional_list_uploadfile_alias_and_validation_alias(
p: Annotated[
- Optional[List[UploadFile]],
+ Optional[list[UploadFile]],
File(alias="p_alias", validation_alias="p_val_alias"),
] = None,
):
return {"file_size": [file.size for file in p] if p else None}
-@needs_pydanticv2
@pytest.mark.parametrize(
"path",
[
@@ -344,35 +299,22 @@ def test_optional_list_alias_and_validation_alias_schema(path: str):
assert app.openapi()["components"]["schemas"][body_model_name] == {
"properties": {
- "p_val_alias": (
- IsDict(
+ "p_val_alias": {
+ "anyOf": [
{
- "anyOf": [
- {
- "type": "array",
- "items": {"type": "string", "format": "binary"},
- },
- {"type": "null"},
- ],
- "title": "P Val Alias",
- }
- )
- | IsDict(
- # TODO: remove when deprecating Pydantic v1
- {
- "title": "P Val Alias",
"type": "array",
"items": {"type": "string", "format": "binary"},
- }
- )
- ),
+ },
+ {"type": "null"},
+ ],
+ "title": "P Val Alias",
+ }
},
"title": body_model_name,
"type": "object",
}
-@needs_pydanticv2
@pytest.mark.parametrize(
"path",
[
@@ -387,7 +329,6 @@ def test_optional_list_alias_and_validation_alias_missing(path: str):
assert response.json() == {"file_size": None}
-@needs_pydanticv2
@pytest.mark.parametrize(
"path",
[
@@ -402,7 +343,6 @@ def test_optional_list_alias_and_validation_alias_by_name(path: str):
assert response.json() == {"file_size": None}
-@needs_pydanticv2
@pytest.mark.parametrize(
"path",
[
@@ -417,7 +357,6 @@ def test_optional_list_alias_and_validation_alias_by_alias(path: str):
assert response.json() == {"file_size": None}
-@needs_pydanticv2
@pytest.mark.parametrize(
"path",
[
diff --git a/tests/test_request_params/test_file/test_required.py b/tests/test_request_params/test_file/test_required.py
index f041ac1ccf..a0f9d23a6b 100644
--- a/tests/test_request_params/test_file/test_required.py
+++ b/tests/test_request_params/test_file/test_required.py
@@ -1,10 +1,8 @@
+from typing import Annotated
+
import pytest
-from dirty_equals import IsDict
from fastapi import FastAPI, File, UploadFile
from fastapi.testclient import TestClient
-from typing_extensions import Annotated
-
-from tests.utils import needs_pydanticv2
from .utils import get_body_model_name
@@ -56,29 +54,16 @@ def test_required_missing(path: str):
client = TestClient(app)
response = client.post(path)
assert response.status_code == 422
- assert response.json() == IsDict(
- {
- "detail": [
- {
- "type": "missing",
- "loc": ["body", "p"],
- "msg": "Field required",
- "input": None,
- }
- ]
- }
- ) | IsDict(
- # TODO: remove when deprecating Pydantic v1
- {
- "detail": [
- {
- "loc": ["body", "p"],
- "msg": "field required",
- "type": "value_error.missing",
- }
- ]
- }
- )
+ assert response.json() == {
+ "detail": [
+ {
+ "type": "missing",
+ "loc": ["body", "p"],
+ "msg": "Field required",
+ "input": None,
+ }
+ ]
+ }
@pytest.mark.parametrize(
@@ -143,29 +128,16 @@ def test_required_alias_missing(path: str):
client = TestClient(app)
response = client.post(path)
assert response.status_code == 422
- assert response.json() == IsDict(
- {
- "detail": [
- {
- "type": "missing",
- "loc": ["body", "p_alias"],
- "msg": "Field required",
- "input": None,
- }
- ]
- }
- ) | IsDict(
- # TODO: remove when deprecating Pydantic v1
- {
- "detail": [
- {
- "loc": ["body", "p_alias"],
- "msg": "field required",
- "type": "value_error.missing",
- }
- ]
- }
- )
+ assert response.json() == {
+ "detail": [
+ {
+ "type": "missing",
+ "loc": ["body", "p_alias"],
+ "msg": "Field required",
+ "input": None,
+ }
+ ]
+ }
@pytest.mark.parametrize(
@@ -179,29 +151,16 @@ def test_required_alias_by_name(path: str):
client = TestClient(app)
response = client.post(path, files=[("p", b"hello")])
assert response.status_code == 422
- assert response.json() == IsDict(
- {
- "detail": [
- {
- "type": "missing",
- "loc": ["body", "p_alias"],
- "msg": "Field required",
- "input": None,
- }
- ]
- }
- ) | IsDict(
- # TODO: remove when deprecating Pydantic v1
- {
- "detail": [
- {
- "loc": ["body", "p_alias"],
- "msg": "field required",
- "type": "value_error.missing",
- }
- ]
- }
- )
+ assert response.json() == {
+ "detail": [
+ {
+ "type": "missing",
+ "loc": ["body", "p_alias"],
+ "msg": "Field required",
+ "input": None,
+ }
+ ]
+ }
@pytest.mark.parametrize(
@@ -241,7 +200,6 @@ def read_required_uploadfile_validation_alias(
return {"file_size": p.size}
-@needs_pydanticv2
@pytest.mark.parametrize(
"path",
[
@@ -267,7 +225,6 @@ def test_required_validation_alias_schema(path: str):
}
-@needs_pydanticv2
@pytest.mark.parametrize(
"path",
[
@@ -294,7 +251,6 @@ def test_required_validation_alias_missing(path: str):
}
-@needs_pydanticv2
@pytest.mark.parametrize(
"path",
[
@@ -319,7 +275,6 @@ def test_required_validation_alias_by_name(path: str):
}
-@needs_pydanticv2
@pytest.mark.parametrize(
"path",
[
@@ -358,7 +313,6 @@ def read_required_uploadfile_alias_and_validation_alias(
return {"file_size": p.size}
-@needs_pydanticv2
@pytest.mark.parametrize(
"path",
[
@@ -384,7 +338,6 @@ def test_required_alias_and_validation_alias_schema(path: str):
}
-@needs_pydanticv2
@pytest.mark.parametrize(
"path",
[
@@ -411,7 +364,6 @@ def test_required_alias_and_validation_alias_missing(path: str):
}
-@needs_pydanticv2
@pytest.mark.parametrize(
"path",
[
@@ -439,7 +391,6 @@ def test_required_alias_and_validation_alias_by_name(path: str):
}
-@needs_pydanticv2
@pytest.mark.parametrize(
"path",
[
@@ -464,7 +415,6 @@ def test_required_alias_and_validation_alias_by_alias(path: str):
}
-@needs_pydanticv2
@pytest.mark.parametrize(
"path",
[
diff --git a/tests/test_request_params/test_file/utils.py b/tests/test_request_params/test_file/utils.py
index e33f64385f..e2a97ccd9b 100644
--- a/tests/test_request_params/test_file/utils.py
+++ b/tests/test_request_params/test_file/utils.py
@@ -1,7 +1,7 @@
-from typing import Any, Dict
+from typing import Any
-def get_body_model_name(openapi: Dict[str, Any], path: str) -> str:
+def get_body_model_name(openapi: dict[str, Any], path: str) -> str:
body = openapi["paths"][path]["post"]["requestBody"]
body_schema = body["content"]["multipart/form-data"]["schema"]
return body_schema.get("$ref", "").split("/")[-1]
diff --git a/tests/test_request_params/test_form/test_list.py b/tests/test_request_params/test_form/test_list.py
index 69a1b6a380..abe781c945 100644
--- a/tests/test_request_params/test_form/test_list.py
+++ b/tests/test_request_params/test_form/test_list.py
@@ -1,13 +1,10 @@
-from typing import List
+from typing import Annotated
import pytest
-from dirty_equals import IsDict, IsOneOf, IsPartialDict
+from dirty_equals import IsOneOf, IsPartialDict
from fastapi import FastAPI, Form
from fastapi.testclient import TestClient
from pydantic import BaseModel, Field
-from typing_extensions import Annotated
-
-from tests.utils import needs_pydanticv2
from .utils import get_body_model_name
@@ -18,12 +15,12 @@ app = FastAPI()
@app.post("/required-list-str", operation_id="required_list_str")
-async def read_required_list_str(p: Annotated[List[str], Form()]):
+async def read_required_list_str(p: Annotated[list[str], Form()]):
return {"p": p}
class FormModelRequiredListStr(BaseModel):
- p: List[str]
+ p: list[str]
@app.post("/model-required-list-str", operation_id="model_required_list_str")
@@ -61,28 +58,16 @@ def test_required_list_str_missing(path: str):
client = TestClient(app)
response = client.post(path)
assert response.status_code == 422
- assert response.json() == IsDict(
- {
- "detail": [
- {
- "type": "missing",
- "loc": ["body", "p"],
- "msg": "Field required",
- "input": IsOneOf(None, {}),
- }
- ]
- }
- ) | IsDict(
- {
- "detail": [
- {
- "loc": ["body", "p"],
- "msg": "field required",
- "type": "value_error.missing",
- }
- ]
- }
- )
+ assert response.json() == {
+ "detail": [
+ {
+ "type": "missing",
+ "loc": ["body", "p"],
+ "msg": "Field required",
+ "input": IsOneOf(None, {}),
+ }
+ ]
+ }
@pytest.mark.parametrize(
@@ -101,12 +86,12 @@ def test_required_list_str(path: str):
@app.post("/required-list-alias", operation_id="required_list_alias")
-async def read_required_list_alias(p: Annotated[List[str], Form(alias="p_alias")]):
+async def read_required_list_alias(p: Annotated[list[str], Form(alias="p_alias")]):
return {"p": p}
class FormModelRequiredListAlias(BaseModel):
- p: List[str] = Field(alias="p_alias")
+ p: list[str] = Field(alias="p_alias")
@app.post("/model-required-list-alias", operation_id="model_required_list_alias")
@@ -149,29 +134,16 @@ def test_required_list_alias_missing(path: str):
client = TestClient(app)
response = client.post(path)
assert response.status_code == 422
- assert response.json() == IsDict(
- {
- "detail": [
- {
- "type": "missing",
- "loc": ["body", "p_alias"],
- "msg": "Field required",
- "input": IsOneOf(None, {}),
- }
- ]
- }
- ) | IsDict(
- # TODO: remove when deprecating Pydantic v1
- {
- "detail": [
- {
- "loc": ["body", "p_alias"],
- "msg": "field required",
- "type": "value_error.missing",
- }
- ]
- }
- )
+ assert response.json() == {
+ "detail": [
+ {
+ "type": "missing",
+ "loc": ["body", "p_alias"],
+ "msg": "Field required",
+ "input": IsOneOf(None, {}),
+ }
+ ]
+ }
@pytest.mark.parametrize(
@@ -185,29 +157,16 @@ def test_required_list_alias_by_name(path: str):
client = TestClient(app)
response = client.post(path, data={"p": ["hello", "world"]})
assert response.status_code == 422
- assert response.json() == IsDict(
- {
- "detail": [
- {
- "type": "missing",
- "loc": ["body", "p_alias"],
- "msg": "Field required",
- "input": IsOneOf(None, {"p": ["hello", "world"]}),
- }
- ]
- }
- ) | IsDict(
- # TODO: remove when deprecating Pydantic v1
- {
- "detail": [
- {
- "loc": ["body", "p_alias"],
- "msg": "field required",
- "type": "value_error.missing",
- }
- ]
- }
- )
+ assert response.json() == {
+ "detail": [
+ {
+ "type": "missing",
+ "loc": ["body", "p_alias"],
+ "msg": "Field required",
+ "input": IsOneOf(None, {"p": ["hello", "world"]}),
+ }
+ ]
+ }
@pytest.mark.parametrize(
@@ -229,13 +188,13 @@ def test_required_list_alias_by_alias(path: str):
"/required-list-validation-alias", operation_id="required_list_validation_alias"
)
def read_required_list_validation_alias(
- p: Annotated[List[str], Form(validation_alias="p_val_alias")],
+ p: Annotated[list[str], Form(validation_alias="p_val_alias")],
):
return {"p": p}
class FormModelRequiredListValidationAlias(BaseModel):
- p: List[str] = Field(validation_alias="p_val_alias")
+ p: list[str] = Field(validation_alias="p_val_alias")
@app.post(
@@ -248,7 +207,6 @@ async def read_model_required_list_validation_alias(
return {"p": p.p}
-@needs_pydanticv2
@pytest.mark.parametrize(
"path",
["/required-list-validation-alias", "/model-required-list-validation-alias"],
@@ -271,7 +229,6 @@ def test_required_list_validation_alias_schema(path: str):
}
-@needs_pydanticv2
@pytest.mark.parametrize(
"path",
[
@@ -298,7 +255,6 @@ def test_required_list_validation_alias_missing(path: str):
}
-@needs_pydanticv2
@pytest.mark.parametrize(
"path",
[
@@ -323,7 +279,6 @@ def test_required_list_validation_alias_by_name(path: str):
}
-@needs_pydanticv2
@pytest.mark.parametrize(
"path",
["/required-list-validation-alias", "/model-required-list-validation-alias"],
@@ -345,13 +300,13 @@ def test_required_list_validation_alias_by_validation_alias(path: str):
operation_id="required_list_alias_and_validation_alias",
)
def read_required_list_alias_and_validation_alias(
- p: Annotated[List[str], Form(alias="p_alias", validation_alias="p_val_alias")],
+ p: Annotated[list[str], Form(alias="p_alias", validation_alias="p_val_alias")],
):
return {"p": p}
class FormModelRequiredListAliasAndValidationAlias(BaseModel):
- p: List[str] = Field(alias="p_alias", validation_alias="p_val_alias")
+ p: list[str] = Field(alias="p_alias", validation_alias="p_val_alias")
@app.post(
@@ -364,7 +319,6 @@ def read_model_required_list_alias_and_validation_alias(
return {"p": p.p}
-@needs_pydanticv2
@pytest.mark.parametrize(
"path",
[
@@ -390,7 +344,6 @@ def test_required_list_alias_and_validation_alias_schema(path: str):
}
-@needs_pydanticv2
@pytest.mark.parametrize(
"path",
[
@@ -417,7 +370,6 @@ def test_required_list_alias_and_validation_alias_missing(path: str):
}
-@needs_pydanticv2
@pytest.mark.parametrize(
"path",
[
@@ -447,7 +399,6 @@ def test_required_list_alias_and_validation_alias_by_name(path: str):
}
-@needs_pydanticv2
@pytest.mark.parametrize(
"path",
[
@@ -471,7 +422,6 @@ def test_required_list_alias_and_validation_alias_by_alias(path: str):
}
-@needs_pydanticv2
@pytest.mark.parametrize(
"path",
[
diff --git a/tests/test_request_params/test_form/test_optional_list.py b/tests/test_request_params/test_form/test_optional_list.py
index 1f779a7ed9..6d1957a18c 100644
--- a/tests/test_request_params/test_form/test_optional_list.py
+++ b/tests/test_request_params/test_form/test_optional_list.py
@@ -1,13 +1,9 @@
-from typing import List, Optional
+from typing import Annotated, Optional
import pytest
-from dirty_equals import IsDict
from fastapi import FastAPI, Form
from fastapi.testclient import TestClient
from pydantic import BaseModel, Field
-from typing_extensions import Annotated
-
-from tests.utils import needs_pydanticv2
from .utils import get_body_model_name
@@ -19,13 +15,13 @@ app = FastAPI()
@app.post("/optional-list-str", operation_id="optional_list_str")
async def read_optional_list_str(
- p: Annotated[Optional[List[str]], Form()] = None,
+ p: Annotated[Optional[list[str]], Form()] = None,
):
return {"p": p}
class FormModelOptionalListStr(BaseModel):
- p: Optional[List[str]] = None
+ p: Optional[list[str]] = None
@app.post("/model-optional-list-str", operation_id="model_optional_list_str")
@@ -41,30 +37,19 @@ def test_optional_list_str_schema(path: str):
openapi = app.openapi()
body_model_name = get_body_model_name(openapi, path)
- assert app.openapi()["components"]["schemas"][body_model_name] == IsDict(
- {
- "properties": {
- "p": {
- "anyOf": [
- {"items": {"type": "string"}, "type": "array"},
- {"type": "null"},
- ],
- "title": "P",
- },
+ assert app.openapi()["components"]["schemas"][body_model_name] == {
+ "properties": {
+ "p": {
+ "anyOf": [
+ {"items": {"type": "string"}, "type": "array"},
+ {"type": "null"},
+ ],
+ "title": "P",
},
- "title": body_model_name,
- "type": "object",
- }
- ) | IsDict(
- # TODO: remove when deprecating Pydantic v1
- {
- "properties": {
- "p": {"items": {"type": "string"}, "type": "array", "title": "P"},
- },
- "title": body_model_name,
- "type": "object",
- }
- )
+ },
+ "title": body_model_name,
+ "type": "object",
+ }
@pytest.mark.parametrize(
@@ -95,13 +80,13 @@ def test_optional_list_str(path: str):
@app.post("/optional-list-alias", operation_id="optional_list_alias")
async def read_optional_list_alias(
- p: Annotated[Optional[List[str]], Form(alias="p_alias")] = None,
+ p: Annotated[Optional[list[str]], Form(alias="p_alias")] = None,
):
return {"p": p}
class FormModelOptionalListAlias(BaseModel):
- p: Optional[List[str]] = Field(None, alias="p_alias")
+ p: Optional[list[str]] = Field(None, alias="p_alias")
@app.post("/model-optional-list-alias", operation_id="model_optional_list_alias")
@@ -122,34 +107,19 @@ def test_optional_list_str_alias_schema(path: str):
openapi = app.openapi()
body_model_name = get_body_model_name(openapi, path)
- assert app.openapi()["components"]["schemas"][body_model_name] == IsDict(
- {
- "properties": {
- "p_alias": {
- "anyOf": [
- {"items": {"type": "string"}, "type": "array"},
- {"type": "null"},
- ],
- "title": "P Alias",
- },
+ assert app.openapi()["components"]["schemas"][body_model_name] == {
+ "properties": {
+ "p_alias": {
+ "anyOf": [
+ {"items": {"type": "string"}, "type": "array"},
+ {"type": "null"},
+ ],
+ "title": "P Alias",
},
- "title": body_model_name,
- "type": "object",
- }
- ) | IsDict(
- # TODO: remove when deprecating Pydantic v1
- {
- "properties": {
- "p_alias": {
- "items": {"type": "string"},
- "type": "array",
- "title": "P Alias",
- },
- },
- "title": body_model_name,
- "type": "object",
- }
- )
+ },
+ "title": body_model_name,
+ "type": "object",
+ }
@pytest.mark.parametrize(
@@ -193,13 +163,13 @@ def test_optional_list_alias_by_alias(path: str):
"/optional-list-validation-alias", operation_id="optional_list_validation_alias"
)
def read_optional_list_validation_alias(
- p: Annotated[Optional[List[str]], Form(validation_alias="p_val_alias")] = None,
+ p: Annotated[Optional[list[str]], Form(validation_alias="p_val_alias")] = None,
):
return {"p": p}
class FormModelOptionalListValidationAlias(BaseModel):
- p: Optional[List[str]] = Field(None, validation_alias="p_val_alias")
+ p: Optional[list[str]] = Field(None, validation_alias="p_val_alias")
@app.post(
@@ -212,7 +182,6 @@ def read_model_optional_list_validation_alias(
return {"p": p.p}
-@needs_pydanticv2
@pytest.mark.parametrize(
"path",
["/optional-list-validation-alias", "/model-optional-list-validation-alias"],
@@ -221,37 +190,21 @@ def test_optional_list_validation_alias_schema(path: str):
openapi = app.openapi()
body_model_name = get_body_model_name(openapi, path)
- assert app.openapi()["components"]["schemas"][body_model_name] == IsDict(
- {
- "properties": {
- "p_val_alias": {
- "anyOf": [
- {"items": {"type": "string"}, "type": "array"},
- {"type": "null"},
- ],
- "title": "P Val Alias",
- },
+ assert app.openapi()["components"]["schemas"][body_model_name] == {
+ "properties": {
+ "p_val_alias": {
+ "anyOf": [
+ {"items": {"type": "string"}, "type": "array"},
+ {"type": "null"},
+ ],
+ "title": "P Val Alias",
},
- "title": body_model_name,
- "type": "object",
- }
- ) | IsDict(
- # TODO: remove when deprecating Pydantic v1
- {
- "properties": {
- "p_val_alias": {
- "items": {"type": "string"},
- "type": "array",
- "title": "P Val Alias",
- },
- },
- "title": body_model_name,
- "type": "object",
- }
- )
+ },
+ "title": body_model_name,
+ "type": "object",
+ }
-@needs_pydanticv2
@pytest.mark.parametrize(
"path",
["/optional-list-validation-alias", "/model-optional-list-validation-alias"],
@@ -263,7 +216,6 @@ def test_optional_list_validation_alias_missing(path: str):
assert response.json() == {"p": None}
-@needs_pydanticv2
@pytest.mark.parametrize(
"path",
[
@@ -278,7 +230,6 @@ def test_optional_list_validation_alias_by_name(path: str):
assert response.json() == {"p": None}
-@needs_pydanticv2
@pytest.mark.parametrize(
"path",
["/optional-list-validation-alias", "/model-optional-list-validation-alias"],
@@ -300,14 +251,14 @@ def test_optional_list_validation_alias_by_validation_alias(path: str):
)
def read_optional_list_alias_and_validation_alias(
p: Annotated[
- Optional[List[str]], Form(alias="p_alias", validation_alias="p_val_alias")
+ Optional[list[str]], Form(alias="p_alias", validation_alias="p_val_alias")
] = None,
):
return {"p": p}
class FormModelOptionalListAliasAndValidationAlias(BaseModel):
- p: Optional[List[str]] = Field(
+ p: Optional[list[str]] = Field(
None, alias="p_alias", validation_alias="p_val_alias"
)
@@ -322,7 +273,6 @@ def read_model_optional_list_alias_and_validation_alias(
return {"p": p.p}
-@needs_pydanticv2
@pytest.mark.parametrize(
"path",
[
@@ -334,37 +284,21 @@ def test_optional_list_alias_and_validation_alias_schema(path: str):
openapi = app.openapi()
body_model_name = get_body_model_name(openapi, path)
- assert app.openapi()["components"]["schemas"][body_model_name] == IsDict(
- {
- "properties": {
- "p_val_alias": {
- "anyOf": [
- {"items": {"type": "string"}, "type": "array"},
- {"type": "null"},
- ],
- "title": "P Val Alias",
- },
+ assert app.openapi()["components"]["schemas"][body_model_name] == {
+ "properties": {
+ "p_val_alias": {
+ "anyOf": [
+ {"items": {"type": "string"}, "type": "array"},
+ {"type": "null"},
+ ],
+ "title": "P Val Alias",
},
- "title": body_model_name,
- "type": "object",
- }
- ) | IsDict(
- # TODO: remove when deprecating Pydantic v1
- {
- "properties": {
- "p_val_alias": {
- "items": {"type": "string"},
- "type": "array",
- "title": "P Val Alias",
- },
- },
- "title": body_model_name,
- "type": "object",
- }
- )
+ },
+ "title": body_model_name,
+ "type": "object",
+ }
-@needs_pydanticv2
@pytest.mark.parametrize(
"path",
[
@@ -379,7 +313,6 @@ def test_optional_list_alias_and_validation_alias_missing(path: str):
assert response.json() == {"p": None}
-@needs_pydanticv2
@pytest.mark.parametrize(
"path",
[
@@ -394,7 +327,6 @@ def test_optional_list_alias_and_validation_alias_by_name(path: str):
assert response.json() == {"p": None}
-@needs_pydanticv2
@pytest.mark.parametrize(
"path",
[
@@ -409,7 +341,6 @@ def test_optional_list_alias_and_validation_alias_by_alias(path: str):
assert response.json() == {"p": None}
-@needs_pydanticv2
@pytest.mark.parametrize(
"path",
[
diff --git a/tests/test_request_params/test_form/test_optional_str.py b/tests/test_request_params/test_form/test_optional_str.py
index 9698659452..810e83caa3 100644
--- a/tests/test_request_params/test_form/test_optional_str.py
+++ b/tests/test_request_params/test_form/test_optional_str.py
@@ -1,13 +1,9 @@
-from typing import Optional
+from typing import Annotated, Optional
import pytest
-from dirty_equals import IsDict
from fastapi import FastAPI, Form
from fastapi.testclient import TestClient
from pydantic import BaseModel, Field
-from typing_extensions import Annotated
-
-from tests.utils import needs_pydanticv2
from .utils import get_body_model_name
@@ -39,27 +35,16 @@ def test_optional_str_schema(path: str):
openapi = app.openapi()
body_model_name = get_body_model_name(openapi, path)
- assert app.openapi()["components"]["schemas"][body_model_name] == IsDict(
- {
- "properties": {
- "p": {
- "anyOf": [{"type": "string"}, {"type": "null"}],
- "title": "P",
- },
+ assert app.openapi()["components"]["schemas"][body_model_name] == {
+ "properties": {
+ "p": {
+ "anyOf": [{"type": "string"}, {"type": "null"}],
+ "title": "P",
},
- "title": body_model_name,
- "type": "object",
- }
- ) | IsDict(
- # TODO: remove when deprecating Pydantic v1
- {
- "properties": {
- "p": {"type": "string", "title": "P"},
- },
- "title": body_model_name,
- "type": "object",
- }
- )
+ },
+ "title": body_model_name,
+ "type": "object",
+ }
@pytest.mark.parametrize(
@@ -115,27 +100,16 @@ def test_optional_str_alias_schema(path: str):
openapi = app.openapi()
body_model_name = get_body_model_name(openapi, path)
- assert app.openapi()["components"]["schemas"][body_model_name] == IsDict(
- {
- "properties": {
- "p_alias": {
- "anyOf": [{"type": "string"}, {"type": "null"}],
- "title": "P Alias",
- },
+ assert app.openapi()["components"]["schemas"][body_model_name] == {
+ "properties": {
+ "p_alias": {
+ "anyOf": [{"type": "string"}, {"type": "null"}],
+ "title": "P Alias",
},
- "title": body_model_name,
- "type": "object",
- }
- ) | IsDict(
- # TODO: remove when deprecating Pydantic v1
- {
- "properties": {
- "p_alias": {"type": "string", "title": "P Alias"},
- },
- "title": body_model_name,
- "type": "object",
- }
- )
+ },
+ "title": body_model_name,
+ "type": "object",
+ }
@pytest.mark.parametrize(
@@ -195,7 +169,6 @@ def read_model_optional_validation_alias(
return {"p": p.p}
-@needs_pydanticv2
@pytest.mark.parametrize(
"path",
["/optional-validation-alias", "/model-optional-validation-alias"],
@@ -204,30 +177,18 @@ def test_optional_validation_alias_schema(path: str):
openapi = app.openapi()
body_model_name = get_body_model_name(openapi, path)
- assert app.openapi()["components"]["schemas"][body_model_name] == IsDict(
- {
- "properties": {
- "p_val_alias": {
- "anyOf": [{"type": "string"}, {"type": "null"}],
- "title": "P Val Alias",
- },
+ assert app.openapi()["components"]["schemas"][body_model_name] == {
+ "properties": {
+ "p_val_alias": {
+ "anyOf": [{"type": "string"}, {"type": "null"}],
+ "title": "P Val Alias",
},
- "title": body_model_name,
- "type": "object",
- }
- ) | IsDict(
- # TODO: remove when deprecating Pydantic v1
- {
- "properties": {
- "p_val_alias": {"type": "string", "title": "P Val Alias"},
- },
- "title": body_model_name,
- "type": "object",
- }
- )
+ },
+ "title": body_model_name,
+ "type": "object",
+ }
-@needs_pydanticv2
@pytest.mark.parametrize(
"path",
["/optional-validation-alias", "/model-optional-validation-alias"],
@@ -239,7 +200,6 @@ def test_optional_validation_alias_missing(path: str):
assert response.json() == {"p": None}
-@needs_pydanticv2
@pytest.mark.parametrize(
"path",
[
@@ -254,7 +214,6 @@ def test_optional_validation_alias_by_name(path: str):
assert response.json() == {"p": None}
-@needs_pydanticv2
@pytest.mark.parametrize(
"path",
[
@@ -299,7 +258,6 @@ def read_model_optional_alias_and_validation_alias(
return {"p": p.p}
-@needs_pydanticv2
@pytest.mark.parametrize(
"path",
[
@@ -311,30 +269,18 @@ def test_optional_alias_and_validation_alias_schema(path: str):
openapi = app.openapi()
body_model_name = get_body_model_name(openapi, path)
- assert app.openapi()["components"]["schemas"][body_model_name] == IsDict(
- {
- "properties": {
- "p_val_alias": {
- "anyOf": [{"type": "string"}, {"type": "null"}],
- "title": "P Val Alias",
- },
+ assert app.openapi()["components"]["schemas"][body_model_name] == {
+ "properties": {
+ "p_val_alias": {
+ "anyOf": [{"type": "string"}, {"type": "null"}],
+ "title": "P Val Alias",
},
- "title": body_model_name,
- "type": "object",
- }
- ) | IsDict(
- # TODO: remove when deprecating Pydantic v1
- {
- "properties": {
- "p_val_alias": {"type": "string", "title": "P Val Alias"},
- },
- "title": body_model_name,
- "type": "object",
- }
- )
+ },
+ "title": body_model_name,
+ "type": "object",
+ }
-@needs_pydanticv2
@pytest.mark.parametrize(
"path",
[
@@ -349,7 +295,6 @@ def test_optional_alias_and_validation_alias_missing(path: str):
assert response.json() == {"p": None}
-@needs_pydanticv2
@pytest.mark.parametrize(
"path",
[
@@ -364,7 +309,6 @@ def test_optional_alias_and_validation_alias_by_name(path: str):
assert response.json() == {"p": None}
-@needs_pydanticv2
@pytest.mark.parametrize(
"path",
[
@@ -379,7 +323,6 @@ def test_optional_alias_and_validation_alias_by_alias(path: str):
assert response.json() == {"p": None}
-@needs_pydanticv2
@pytest.mark.parametrize(
"path",
[
diff --git a/tests/test_request_params/test_form/test_required_str.py b/tests/test_request_params/test_form/test_required_str.py
index c901e7b445..7c9523b308 100644
--- a/tests/test_request_params/test_form/test_required_str.py
+++ b/tests/test_request_params/test_form/test_required_str.py
@@ -1,11 +1,10 @@
+from typing import Annotated
+
import pytest
-from dirty_equals import IsDict, IsOneOf
+from dirty_equals import IsOneOf
from fastapi import FastAPI, Form
from fastapi.testclient import TestClient
from pydantic import BaseModel, Field
-from typing_extensions import Annotated
-
-from tests.utils import needs_pydanticv2
from .utils import get_body_model_name
@@ -55,29 +54,16 @@ def test_required_str_missing(path: str):
client = TestClient(app)
response = client.post(path)
assert response.status_code == 422
- assert response.json() == IsDict(
- {
- "detail": [
- {
- "type": "missing",
- "loc": ["body", "p"],
- "msg": "Field required",
- "input": IsOneOf(None, {}),
- }
- ]
- }
- ) | IsDict(
- # TODO: remove when deprecating Pydantic v1
- {
- "detail": [
- {
- "loc": ["body", "p"],
- "msg": "field required",
- "type": "value_error.missing",
- }
- ]
- }
- )
+ assert response.json() == {
+ "detail": [
+ {
+ "type": "missing",
+ "loc": ["body", "p"],
+ "msg": "Field required",
+ "input": IsOneOf(None, {}),
+ }
+ ]
+ }
@pytest.mark.parametrize(
@@ -138,29 +124,16 @@ def test_required_alias_missing(path: str):
client = TestClient(app)
response = client.post(path)
assert response.status_code == 422
- assert response.json() == IsDict(
- {
- "detail": [
- {
- "type": "missing",
- "loc": ["body", "p_alias"],
- "msg": "Field required",
- "input": IsOneOf(None, {}),
- }
- ]
- }
- ) | IsDict(
- # TODO: remove when deprecating Pydantic v1
- {
- "detail": [
- {
- "loc": ["body", "p_alias"],
- "msg": "field required",
- "type": "value_error.missing",
- }
- ]
- }
- )
+ assert response.json() == {
+ "detail": [
+ {
+ "type": "missing",
+ "loc": ["body", "p_alias"],
+ "msg": "Field required",
+ "input": IsOneOf(None, {}),
+ }
+ ]
+ }
@pytest.mark.parametrize(
@@ -171,29 +144,16 @@ def test_required_alias_by_name(path: str):
client = TestClient(app)
response = client.post(path, data={"p": "hello"})
assert response.status_code == 422
- assert response.json() == IsDict(
- {
- "detail": [
- {
- "type": "missing",
- "loc": ["body", "p_alias"],
- "msg": "Field required",
- "input": IsOneOf(None, {"p": "hello"}),
- }
- ]
- }
- ) | IsDict(
- # TODO: remove when deprecating Pydantic v1
- {
- "detail": [
- {
- "loc": ["body", "p_alias"],
- "msg": "field required",
- "type": "value_error.missing",
- }
- ]
- }
- )
+ assert response.json() == {
+ "detail": [
+ {
+ "type": "missing",
+ "loc": ["body", "p_alias"],
+ "msg": "Field required",
+ "input": IsOneOf(None, {"p": "hello"}),
+ }
+ ]
+ }
@pytest.mark.parametrize(
@@ -231,7 +191,6 @@ def read_model_required_validation_alias(
return {"p": p.p}
-@needs_pydanticv2
@pytest.mark.parametrize(
"path",
["/required-validation-alias", "/model-required-validation-alias"],
@@ -250,7 +209,6 @@ def test_required_validation_alias_schema(path: str):
}
-@needs_pydanticv2
@pytest.mark.parametrize(
"path",
[
@@ -277,7 +235,6 @@ def test_required_validation_alias_missing(path: str):
}
-@needs_pydanticv2
@pytest.mark.parametrize(
"path",
[
@@ -302,7 +259,6 @@ def test_required_validation_alias_by_name(path: str):
}
-@needs_pydanticv2
@pytest.mark.parametrize(
"path",
[
@@ -346,7 +302,6 @@ def read_model_required_alias_and_validation_alias(
return {"p": p.p}
-@needs_pydanticv2
@pytest.mark.parametrize(
"path",
[
@@ -368,7 +323,6 @@ def test_required_alias_and_validation_alias_schema(path: str):
}
-@needs_pydanticv2
@pytest.mark.parametrize(
"path",
[
@@ -395,7 +349,6 @@ def test_required_alias_and_validation_alias_missing(path: str):
}
-@needs_pydanticv2
@pytest.mark.parametrize(
"path",
[
@@ -423,7 +376,6 @@ def test_required_alias_and_validation_alias_by_name(path: str):
}
-@needs_pydanticv2
@pytest.mark.parametrize(
"path",
[
@@ -448,7 +400,6 @@ def test_required_alias_and_validation_alias_by_alias(path: str):
}
-@needs_pydanticv2
@pytest.mark.parametrize(
"path",
[
diff --git a/tests/test_request_params/test_form/utils.py b/tests/test_request_params/test_form/utils.py
index d200650dfd..9132173111 100644
--- a/tests/test_request_params/test_form/utils.py
+++ b/tests/test_request_params/test_form/utils.py
@@ -1,7 +1,7 @@
-from typing import Any, Dict
+from typing import Any
-def get_body_model_name(openapi: Dict[str, Any], path: str) -> str:
+def get_body_model_name(openapi: dict[str, Any], path: str) -> str:
body = openapi["paths"][path]["post"]["requestBody"]
body_schema = body["content"]["application/x-www-form-urlencoded"]["schema"]
return body_schema.get("$ref", "").split("/")[-1]
diff --git a/tests/test_request_params/test_header/test_list.py b/tests/test_request_params/test_header/test_list.py
index 4a5f4bb647..489a6b3e7d 100644
--- a/tests/test_request_params/test_header/test_list.py
+++ b/tests/test_request_params/test_header/test_list.py
@@ -1,13 +1,10 @@
-from typing import List
+from typing import Annotated
import pytest
-from dirty_equals import AnyThing, IsDict, IsOneOf, IsPartialDict
+from dirty_equals import AnyThing, IsOneOf, IsPartialDict
from fastapi import FastAPI, Header
from fastapi.testclient import TestClient
from pydantic import BaseModel, Field
-from typing_extensions import Annotated
-
-from tests.utils import needs_pydanticv2
app = FastAPI()
@@ -16,12 +13,12 @@ app = FastAPI()
@app.get("/required-list-str")
-async def read_required_list_str(p: Annotated[List[str], Header()]):
+async def read_required_list_str(p: Annotated[list[str], Header()]):
return {"p": p}
class HeaderModelRequiredListStr(BaseModel):
- p: List[str]
+ p: list[str]
@app.get("/model-required-list-str")
@@ -56,28 +53,16 @@ def test_required_list_str_missing(path: str):
client = TestClient(app)
response = client.get(path)
assert response.status_code == 422
- assert response.json() == IsDict(
- {
- "detail": [
- {
- "type": "missing",
- "loc": ["header", "p"],
- "msg": "Field required",
- "input": AnyThing,
- }
- ]
- }
- ) | IsDict(
- {
- "detail": [
- {
- "loc": ["header", "p"],
- "msg": "field required",
- "type": "value_error.missing",
- }
- ]
- }
- )
+ assert response.json() == {
+ "detail": [
+ {
+ "type": "missing",
+ "loc": ["header", "p"],
+ "msg": "Field required",
+ "input": AnyThing,
+ }
+ ]
+ }
@pytest.mark.parametrize(
@@ -96,12 +81,12 @@ def test_required_list_str(path: str):
@app.get("/required-list-alias")
-async def read_required_list_alias(p: Annotated[List[str], Header(alias="p_alias")]):
+async def read_required_list_alias(p: Annotated[list[str], Header(alias="p_alias")]):
return {"p": p}
class HeaderModelRequiredListAlias(BaseModel):
- p: List[str] = Field(alias="p_alias")
+ p: list[str] = Field(alias="p_alias")
@app.get("/model-required-list-alias")
@@ -138,29 +123,16 @@ def test_required_list_alias_missing(path: str):
client = TestClient(app)
response = client.get(path)
assert response.status_code == 422
- assert response.json() == IsDict(
- {
- "detail": [
- {
- "type": "missing",
- "loc": ["header", "p_alias"],
- "msg": "Field required",
- "input": AnyThing,
- }
- ]
- }
- ) | IsDict(
- # TODO: remove when deprecating Pydantic v1
- {
- "detail": [
- {
- "loc": ["header", "p_alias"],
- "msg": "field required",
- "type": "value_error.missing",
- }
- ]
- }
- )
+ assert response.json() == {
+ "detail": [
+ {
+ "type": "missing",
+ "loc": ["header", "p_alias"],
+ "msg": "Field required",
+ "input": AnyThing,
+ }
+ ]
+ }
@pytest.mark.parametrize(
@@ -174,29 +146,16 @@ def test_required_list_alias_by_name(path: str):
client = TestClient(app)
response = client.get(path, headers=[("p", "hello"), ("p", "world")])
assert response.status_code == 422
- assert response.json() == IsDict(
- {
- "detail": [
- {
- "type": "missing",
- "loc": ["header", "p_alias"],
- "msg": "Field required",
- "input": IsOneOf(None, IsPartialDict({"p": ["hello", "world"]})),
- }
- ]
- }
- ) | IsDict(
- # TODO: remove when deprecating Pydantic v1
- {
- "detail": [
- {
- "loc": ["header", "p_alias"],
- "msg": "field required",
- "type": "value_error.missing",
- }
- ]
- }
- )
+ assert response.json() == {
+ "detail": [
+ {
+ "type": "missing",
+ "loc": ["header", "p_alias"],
+ "msg": "Field required",
+ "input": IsOneOf(None, IsPartialDict({"p": ["hello", "world"]})),
+ }
+ ]
+ }
@pytest.mark.parametrize(
@@ -219,13 +178,13 @@ def test_required_list_alias_by_alias(path: str):
@app.get("/required-list-validation-alias")
def read_required_list_validation_alias(
- p: Annotated[List[str], Header(validation_alias="p_val_alias")],
+ p: Annotated[list[str], Header(validation_alias="p_val_alias")],
):
return {"p": p}
class HeaderModelRequiredListValidationAlias(BaseModel):
- p: List[str] = Field(validation_alias="p_val_alias")
+ p: list[str] = Field(validation_alias="p_val_alias")
@app.get("/model-required-list-validation-alias")
@@ -235,7 +194,6 @@ async def read_model_required_list_validation_alias(
return {"p": p.p}
-@needs_pydanticv2
@pytest.mark.parametrize(
"path",
["/required-list-validation-alias", "/model-required-list-validation-alias"],
@@ -255,7 +213,6 @@ def test_required_list_validation_alias_schema(path: str):
]
-@needs_pydanticv2
@pytest.mark.parametrize(
"path",
[
@@ -282,7 +239,6 @@ def test_required_list_validation_alias_missing(path: str):
}
-@needs_pydanticv2
@pytest.mark.parametrize(
"path",
[
@@ -307,7 +263,6 @@ def test_required_list_validation_alias_by_name(path: str):
}
-@needs_pydanticv2
@pytest.mark.parametrize(
"path",
["/required-list-validation-alias", "/model-required-list-validation-alias"],
@@ -328,13 +283,13 @@ def test_required_list_validation_alias_by_validation_alias(path: str):
@app.get("/required-list-alias-and-validation-alias")
def read_required_list_alias_and_validation_alias(
- p: Annotated[List[str], Header(alias="p_alias", validation_alias="p_val_alias")],
+ p: Annotated[list[str], Header(alias="p_alias", validation_alias="p_val_alias")],
):
return {"p": p}
class HeaderModelRequiredListAliasAndValidationAlias(BaseModel):
- p: List[str] = Field(alias="p_alias", validation_alias="p_val_alias")
+ p: list[str] = Field(alias="p_alias", validation_alias="p_val_alias")
@app.get("/model-required-list-alias-and-validation-alias")
@@ -344,7 +299,6 @@ def read_model_required_list_alias_and_validation_alias(
return {"p": p.p}
-@needs_pydanticv2
@pytest.mark.parametrize(
"path",
[
@@ -367,7 +321,6 @@ def test_required_list_alias_and_validation_alias_schema(path: str):
]
-@needs_pydanticv2
@pytest.mark.parametrize(
"path",
[
@@ -394,7 +347,6 @@ def test_required_list_alias_and_validation_alias_missing(path: str):
}
-@needs_pydanticv2
@pytest.mark.parametrize(
"path",
[
@@ -424,7 +376,6 @@ def test_required_list_alias_and_validation_alias_by_name(path: str):
}
-@needs_pydanticv2
@pytest.mark.parametrize(
"path",
[
@@ -451,7 +402,6 @@ def test_required_list_alias_and_validation_alias_by_alias(path: str):
}
-@needs_pydanticv2
@pytest.mark.parametrize(
"path",
[
diff --git a/tests/test_request_params/test_header/test_optional_list.py b/tests/test_request_params/test_header/test_optional_list.py
index e81025c02b..5dd4ea9ade 100644
--- a/tests/test_request_params/test_header/test_optional_list.py
+++ b/tests/test_request_params/test_header/test_optional_list.py
@@ -1,13 +1,9 @@
-from typing import List, Optional
+from typing import Annotated, Optional
import pytest
-from dirty_equals import IsDict
from fastapi import FastAPI, Header
from fastapi.testclient import TestClient
from pydantic import BaseModel, Field
-from typing_extensions import Annotated
-
-from tests.utils import needs_pydanticv2
app = FastAPI()
@@ -17,13 +13,13 @@ app = FastAPI()
@app.get("/optional-list-str")
async def read_optional_list_str(
- p: Annotated[Optional[List[str]], Header()] = None,
+ p: Annotated[Optional[list[str]], Header()] = None,
):
return {"p": p}
class HeaderModelOptionalListStr(BaseModel):
- p: Optional[List[str]] = None
+ p: Optional[list[str]] = None
@app.get("/model-optional-list-str")
@@ -39,29 +35,18 @@ async def read_model_optional_list_str(
)
def test_optional_list_str_schema(path: str):
assert app.openapi()["paths"][path]["get"]["parameters"] == [
- IsDict(
- {
- "required": False,
- "schema": {
- "anyOf": [
- {"items": {"type": "string"}, "type": "array"},
- {"type": "null"},
- ],
- "title": "P",
- },
- "name": "p",
- "in": "header",
- }
- )
- | IsDict(
- # TODO: remove when deprecating Pydantic v1
- {
- "required": False,
- "schema": {"items": {"type": "string"}, "type": "array", "title": "P"},
- "name": "p",
- "in": "header",
- }
- )
+ {
+ "required": False,
+ "schema": {
+ "anyOf": [
+ {"items": {"type": "string"}, "type": "array"},
+ {"type": "null"},
+ ],
+ "title": "P",
+ },
+ "name": "p",
+ "in": "header",
+ }
]
@@ -93,13 +78,13 @@ def test_optional_list_str(path: str):
@app.get("/optional-list-alias")
async def read_optional_list_alias(
- p: Annotated[Optional[List[str]], Header(alias="p_alias")] = None,
+ p: Annotated[Optional[list[str]], Header(alias="p_alias")] = None,
):
return {"p": p}
class HeaderModelOptionalListAlias(BaseModel):
- p: Optional[List[str]] = Field(None, alias="p_alias")
+ p: Optional[list[str]] = Field(None, alias="p_alias")
@app.get("/model-optional-list-alias")
@@ -115,33 +100,18 @@ async def read_model_optional_list_alias(
)
def test_optional_list_str_alias_schema(path: str):
assert app.openapi()["paths"][path]["get"]["parameters"] == [
- IsDict(
- {
- "required": False,
- "schema": {
- "anyOf": [
- {"items": {"type": "string"}, "type": "array"},
- {"type": "null"},
- ],
- "title": "P Alias",
- },
- "name": "p_alias",
- "in": "header",
- }
- )
- | IsDict(
- # TODO: remove when deprecating Pydantic v1
- {
- "required": False,
- "schema": {
- "items": {"type": "string"},
- "type": "array",
- "title": "P Alias",
- },
- "name": "p_alias",
- "in": "header",
- }
- )
+ {
+ "required": False,
+ "schema": {
+ "anyOf": [
+ {"items": {"type": "string"}, "type": "array"},
+ {"type": "null"},
+ ],
+ "title": "P Alias",
+ },
+ "name": "p_alias",
+ "in": "header",
+ }
]
@@ -187,13 +157,13 @@ def test_optional_list_alias_by_alias(path: str):
@app.get("/optional-list-validation-alias")
def read_optional_list_validation_alias(
- p: Annotated[Optional[List[str]], Header(validation_alias="p_val_alias")] = None,
+ p: Annotated[Optional[list[str]], Header(validation_alias="p_val_alias")] = None,
):
return {"p": p}
class HeaderModelOptionalListValidationAlias(BaseModel):
- p: Optional[List[str]] = Field(None, validation_alias="p_val_alias")
+ p: Optional[list[str]] = Field(None, validation_alias="p_val_alias")
@app.get("/model-optional-list-validation-alias")
@@ -203,7 +173,6 @@ def read_model_optional_list_validation_alias(
return {"p": p.p}
-@needs_pydanticv2
@pytest.mark.parametrize(
"path",
["/optional-list-validation-alias", "/model-optional-list-validation-alias"],
@@ -225,7 +194,6 @@ def test_optional_list_validation_alias_schema(path: str):
]
-@needs_pydanticv2
@pytest.mark.parametrize(
"path",
["/optional-list-validation-alias", "/model-optional-list-validation-alias"],
@@ -237,7 +205,6 @@ def test_optional_list_validation_alias_missing(path: str):
assert response.json() == {"p": None}
-@needs_pydanticv2
@pytest.mark.parametrize(
"path",
[
@@ -252,7 +219,6 @@ def test_optional_list_validation_alias_by_name(path: str):
assert response.json() == {"p": None}
-@needs_pydanticv2
@pytest.mark.parametrize(
"path",
["/optional-list-validation-alias", "/model-optional-list-validation-alias"],
@@ -273,14 +239,14 @@ def test_optional_list_validation_alias_by_validation_alias(path: str):
@app.get("/optional-list-alias-and-validation-alias")
def read_optional_list_alias_and_validation_alias(
p: Annotated[
- Optional[List[str]], Header(alias="p_alias", validation_alias="p_val_alias")
+ Optional[list[str]], Header(alias="p_alias", validation_alias="p_val_alias")
] = None,
):
return {"p": p}
class HeaderModelOptionalListAliasAndValidationAlias(BaseModel):
- p: Optional[List[str]] = Field(
+ p: Optional[list[str]] = Field(
None, alias="p_alias", validation_alias="p_val_alias"
)
@@ -292,7 +258,6 @@ def read_model_optional_list_alias_and_validation_alias(
return {"p": p.p}
-@needs_pydanticv2
@pytest.mark.parametrize(
"path",
[
@@ -317,7 +282,6 @@ def test_optional_list_alias_and_validation_alias_schema(path: str):
]
-@needs_pydanticv2
@pytest.mark.parametrize(
"path",
[
@@ -332,7 +296,6 @@ def test_optional_list_alias_and_validation_alias_missing(path: str):
assert response.json() == {"p": None}
-@needs_pydanticv2
@pytest.mark.parametrize(
"path",
[
@@ -347,7 +310,6 @@ def test_optional_list_alias_and_validation_alias_by_name(path: str):
assert response.json() == {"p": None}
-@needs_pydanticv2
@pytest.mark.parametrize(
"path",
[
@@ -362,7 +324,6 @@ def test_optional_list_alias_and_validation_alias_by_alias(path: str):
assert response.json() == {"p": None}
-@needs_pydanticv2
@pytest.mark.parametrize(
"path",
[
diff --git a/tests/test_request_params/test_header/test_optional_str.py b/tests/test_request_params/test_header/test_optional_str.py
index 5ae9f26701..0bd0eddc1b 100644
--- a/tests/test_request_params/test_header/test_optional_str.py
+++ b/tests/test_request_params/test_header/test_optional_str.py
@@ -1,13 +1,9 @@
-from typing import Optional
+from typing import Annotated, Optional
import pytest
-from dirty_equals import IsDict
from fastapi import FastAPI, Header
from fastapi.testclient import TestClient
from pydantic import BaseModel, Field
-from typing_extensions import Annotated
-
-from tests.utils import needs_pydanticv2
app = FastAPI()
@@ -35,26 +31,15 @@ async def read_model_optional_str(p: Annotated[HeaderModelOptionalStr, Header()]
)
def test_optional_str_schema(path: str):
assert app.openapi()["paths"][path]["get"]["parameters"] == [
- IsDict(
- {
- "required": False,
- "schema": {
- "anyOf": [{"type": "string"}, {"type": "null"}],
- "title": "P",
- },
- "name": "p",
- "in": "header",
- }
- )
- | IsDict(
- # TODO: remove when deprecating Pydantic v1
- {
- "required": False,
- "schema": {"title": "P", "type": "string"},
- "name": "p",
- "in": "header",
- }
- )
+ {
+ "required": False,
+ "schema": {
+ "anyOf": [{"type": "string"}, {"type": "null"}],
+ "title": "P",
+ },
+ "name": "p",
+ "in": "header",
+ }
]
@@ -106,26 +91,15 @@ async def read_model_optional_alias(p: Annotated[HeaderModelOptionalAlias, Heade
)
def test_optional_str_alias_schema(path: str):
assert app.openapi()["paths"][path]["get"]["parameters"] == [
- IsDict(
- {
- "required": False,
- "schema": {
- "anyOf": [{"type": "string"}, {"type": "null"}],
- "title": "P Alias",
- },
- "name": "p_alias",
- "in": "header",
- }
- )
- | IsDict(
- # TODO: remove when deprecating Pydantic v1
- {
- "required": False,
- "schema": {"title": "P Alias", "type": "string"},
- "name": "p_alias",
- "in": "header",
- }
- )
+ {
+ "required": False,
+ "schema": {
+ "anyOf": [{"type": "string"}, {"type": "null"}],
+ "title": "P Alias",
+ },
+ "name": "p_alias",
+ "in": "header",
+ }
]
@@ -187,7 +161,6 @@ def read_model_optional_validation_alias(
return {"p": p.p}
-@needs_pydanticv2
@pytest.mark.parametrize(
"path",
["/optional-validation-alias", "/model-optional-validation-alias"],
@@ -206,7 +179,6 @@ def test_optional_validation_alias_schema(path: str):
]
-@needs_pydanticv2
@pytest.mark.parametrize(
"path",
["/optional-validation-alias", "/model-optional-validation-alias"],
@@ -218,7 +190,6 @@ def test_optional_validation_alias_missing(path: str):
assert response.json() == {"p": None}
-@needs_pydanticv2
@pytest.mark.parametrize(
"path",
[
@@ -233,7 +204,6 @@ def test_optional_validation_alias_by_name(path: str):
assert response.json() == {"p": None}
-@needs_pydanticv2
@pytest.mark.parametrize(
"path",
[
@@ -272,7 +242,6 @@ def read_model_optional_alias_and_validation_alias(
return {"p": p.p}
-@needs_pydanticv2
@pytest.mark.parametrize(
"path",
[
@@ -294,7 +263,6 @@ def test_optional_alias_and_validation_alias_schema(path: str):
]
-@needs_pydanticv2
@pytest.mark.parametrize(
"path",
[
@@ -309,7 +277,6 @@ def test_optional_alias_and_validation_alias_missing(path: str):
assert response.json() == {"p": None}
-@needs_pydanticv2
@pytest.mark.parametrize(
"path",
[
@@ -324,7 +291,6 @@ def test_optional_alias_and_validation_alias_by_name(path: str):
assert response.json() == {"p": None}
-@needs_pydanticv2
@pytest.mark.parametrize(
"path",
[
@@ -339,7 +305,6 @@ def test_optional_alias_and_validation_alias_by_alias(path: str):
assert response.json() == {"p": None}
-@needs_pydanticv2
@pytest.mark.parametrize(
"path",
[
diff --git a/tests/test_request_params/test_header/test_required_str.py b/tests/test_request_params/test_header/test_required_str.py
index d57c66919d..20dd296570 100644
--- a/tests/test_request_params/test_header/test_required_str.py
+++ b/tests/test_request_params/test_header/test_required_str.py
@@ -1,11 +1,10 @@
+from typing import Annotated
+
import pytest
-from dirty_equals import AnyThing, IsDict, IsOneOf, IsPartialDict
+from dirty_equals import AnyThing, IsOneOf, IsPartialDict
from fastapi import FastAPI, Header
from fastapi.testclient import TestClient
from pydantic import BaseModel, Field
-from typing_extensions import Annotated
-
-from tests.utils import needs_pydanticv2
app = FastAPI()
@@ -50,29 +49,16 @@ def test_required_str_missing(path: str):
client = TestClient(app)
response = client.get(path)
assert response.status_code == 422
- assert response.json() == IsDict(
- {
- "detail": [
- {
- "type": "missing",
- "loc": ["header", "p"],
- "msg": "Field required",
- "input": AnyThing,
- }
- ]
- }
- ) | IsDict(
- # TODO: remove when deprecating Pydantic v1
- {
- "detail": [
- {
- "loc": ["header", "p"],
- "msg": "field required",
- "type": "value_error.missing",
- }
- ]
- }
- )
+ assert response.json() == {
+ "detail": [
+ {
+ "type": "missing",
+ "loc": ["header", "p"],
+ "msg": "Field required",
+ "input": AnyThing,
+ }
+ ]
+ }
@pytest.mark.parametrize(
@@ -127,29 +113,16 @@ def test_required_alias_missing(path: str):
client = TestClient(app)
response = client.get(path)
assert response.status_code == 422
- assert response.json() == IsDict(
- {
- "detail": [
- {
- "type": "missing",
- "loc": ["header", "p_alias"],
- "msg": "Field required",
- "input": AnyThing,
- }
- ]
- }
- ) | IsDict(
- # TODO: remove when deprecating Pydantic v1
- {
- "detail": [
- {
- "loc": ["header", "p_alias"],
- "msg": "field required",
- "type": "value_error.missing",
- }
- ]
- }
- )
+ assert response.json() == {
+ "detail": [
+ {
+ "type": "missing",
+ "loc": ["header", "p_alias"],
+ "msg": "Field required",
+ "input": AnyThing,
+ }
+ ]
+ }
@pytest.mark.parametrize(
@@ -163,29 +136,16 @@ def test_required_alias_by_name(path: str):
client = TestClient(app)
response = client.get(path, headers={"p": "hello"})
assert response.status_code == 422
- assert response.json() == IsDict(
- {
- "detail": [
- {
- "type": "missing",
- "loc": ["header", "p_alias"],
- "msg": "Field required",
- "input": IsOneOf(None, IsPartialDict({"p": "hello"})),
- }
- ]
- }
- ) | IsDict(
- # TODO: remove when deprecating Pydantic v1
- {
- "detail": [
- {
- "loc": ["header", "p_alias"],
- "msg": "field required",
- "type": "value_error.missing",
- }
- ]
- }
- )
+ assert response.json() == {
+ "detail": [
+ {
+ "type": "missing",
+ "loc": ["header", "p_alias"],
+ "msg": "Field required",
+ "input": IsOneOf(None, IsPartialDict({"p": "hello"})),
+ }
+ ]
+ }
@pytest.mark.parametrize(
@@ -224,7 +184,6 @@ def read_model_required_validation_alias(
return {"p": p.p}
-@needs_pydanticv2
@pytest.mark.parametrize(
"path",
["/required-validation-alias", "/model-required-validation-alias"],
@@ -240,7 +199,6 @@ def test_required_validation_alias_schema(path: str):
]
-@needs_pydanticv2
@pytest.mark.parametrize(
"path",
[
@@ -267,7 +225,6 @@ def test_required_validation_alias_missing(path: str):
}
-@needs_pydanticv2
@pytest.mark.parametrize(
"path",
[
@@ -292,7 +249,6 @@ def test_required_validation_alias_by_name(path: str):
}
-@needs_pydanticv2
@pytest.mark.parametrize(
"path",
[
@@ -330,7 +286,6 @@ def read_model_required_alias_and_validation_alias(
return {"p": p.p}
-@needs_pydanticv2
@pytest.mark.parametrize(
"path",
[
@@ -349,7 +304,6 @@ def test_required_alias_and_validation_alias_schema(path: str):
]
-@needs_pydanticv2
@pytest.mark.parametrize(
"path",
[
@@ -376,7 +330,6 @@ def test_required_alias_and_validation_alias_missing(path: str):
}
-@needs_pydanticv2
@pytest.mark.parametrize(
"path",
[
@@ -407,7 +360,6 @@ def test_required_alias_and_validation_alias_by_name(path: str):
}
-@needs_pydanticv2
@pytest.mark.parametrize(
"path",
[
@@ -435,7 +387,6 @@ def test_required_alias_and_validation_alias_by_alias(path: str):
}
-@needs_pydanticv2
@pytest.mark.parametrize(
"path",
[
diff --git a/tests/test_request_params/test_path/test_required_str.py b/tests/test_request_params/test_path/test_required_str.py
index 6417199674..b2d63667e2 100644
--- a/tests/test_request_params/test_path/test_required_str.py
+++ b/tests/test_request_params/test_path/test_required_str.py
@@ -1,9 +1,8 @@
+from typing import Annotated
+
import pytest
from fastapi import FastAPI, Path
from fastapi.testclient import TestClient
-from typing_extensions import Annotated
-
-from tests.utils import needs_pydanticv2
app = FastAPI()
@@ -44,14 +43,12 @@ def read_required_alias_and_validation_alias(
"p_val_alias",
"P Val Alias",
id="required-validation-alias",
- marks=needs_pydanticv2,
),
pytest.param(
"/required-alias-and-validation-alias/{p_val_alias}",
"p_val_alias",
"P Val Alias",
id="required-alias-and-validation-alias",
- marks=needs_pydanticv2,
),
],
)
@@ -74,12 +71,10 @@ def test_schema(path: str, expected_name: str, expected_title: str):
pytest.param(
"/required-validation-alias",
id="required-validation-alias",
- marks=needs_pydanticv2,
),
pytest.param(
"/required-alias-and-validation-alias",
id="required-alias-and-validation-alias",
- marks=needs_pydanticv2,
),
],
)
diff --git a/tests/test_request_params/test_query/test_list.py b/tests/test_request_params/test_query/test_list.py
index 71cbca51fb..e933da214d 100644
--- a/tests/test_request_params/test_query/test_list.py
+++ b/tests/test_request_params/test_query/test_list.py
@@ -1,13 +1,10 @@
-from typing import List
+from typing import Annotated
import pytest
-from dirty_equals import IsDict, IsOneOf
+from dirty_equals import IsOneOf
from fastapi import FastAPI, Query
from fastapi.testclient import TestClient
from pydantic import BaseModel, Field
-from typing_extensions import Annotated
-
-from tests.utils import needs_pydanticv2
app = FastAPI()
@@ -16,12 +13,12 @@ app = FastAPI()
@app.get("/required-list-str")
-async def read_required_list_str(p: Annotated[List[str], Query()]):
+async def read_required_list_str(p: Annotated[list[str], Query()]):
return {"p": p}
class QueryModelRequiredListStr(BaseModel):
- p: List[str]
+ p: list[str]
@app.get("/model-required-list-str")
@@ -56,28 +53,16 @@ def test_required_list_str_missing(path: str):
client = TestClient(app)
response = client.get(path)
assert response.status_code == 422
- assert response.json() == IsDict(
- {
- "detail": [
- {
- "type": "missing",
- "loc": ["query", "p"],
- "msg": "Field required",
- "input": IsOneOf(None, {}),
- }
- ]
- }
- ) | IsDict(
- {
- "detail": [
- {
- "loc": ["query", "p"],
- "msg": "field required",
- "type": "value_error.missing",
- }
- ]
- }
- )
+ assert response.json() == {
+ "detail": [
+ {
+ "type": "missing",
+ "loc": ["query", "p"],
+ "msg": "Field required",
+ "input": IsOneOf(None, {}),
+ }
+ ]
+ }
@pytest.mark.parametrize(
@@ -96,12 +81,12 @@ def test_required_list_str(path: str):
@app.get("/required-list-alias")
-async def read_required_list_alias(p: Annotated[List[str], Query(alias="p_alias")]):
+async def read_required_list_alias(p: Annotated[list[str], Query(alias="p_alias")]):
return {"p": p}
class QueryModelRequiredListAlias(BaseModel):
- p: List[str] = Field(alias="p_alias")
+ p: list[str] = Field(alias="p_alias")
@app.get("/model-required-list-alias")
@@ -138,29 +123,16 @@ def test_required_list_alias_missing(path: str):
client = TestClient(app)
response = client.get(path)
assert response.status_code == 422
- assert response.json() == IsDict(
- {
- "detail": [
- {
- "type": "missing",
- "loc": ["query", "p_alias"],
- "msg": "Field required",
- "input": IsOneOf(None, {}),
- }
- ]
- }
- ) | IsDict(
- # TODO: remove when deprecating Pydantic v1
- {
- "detail": [
- {
- "loc": ["query", "p_alias"],
- "msg": "field required",
- "type": "value_error.missing",
- }
- ]
- }
- )
+ assert response.json() == {
+ "detail": [
+ {
+ "type": "missing",
+ "loc": ["query", "p_alias"],
+ "msg": "Field required",
+ "input": IsOneOf(None, {}),
+ }
+ ]
+ }
@pytest.mark.parametrize(
@@ -174,29 +146,16 @@ def test_required_list_alias_by_name(path: str):
client = TestClient(app)
response = client.get(f"{path}?p=hello&p=world")
assert response.status_code == 422
- assert response.json() == IsDict(
- {
- "detail": [
- {
- "type": "missing",
- "loc": ["query", "p_alias"],
- "msg": "Field required",
- "input": IsOneOf(None, {"p": ["hello", "world"]}),
- }
- ]
- }
- ) | IsDict(
- # TODO: remove when deprecating Pydantic v1
- {
- "detail": [
- {
- "loc": ["query", "p_alias"],
- "msg": "field required",
- "type": "value_error.missing",
- }
- ]
- }
- )
+ assert response.json() == {
+ "detail": [
+ {
+ "type": "missing",
+ "loc": ["query", "p_alias"],
+ "msg": "Field required",
+ "input": IsOneOf(None, {"p": ["hello", "world"]}),
+ }
+ ]
+ }
@pytest.mark.parametrize(
@@ -219,13 +178,13 @@ def test_required_list_alias_by_alias(path: str):
@app.get("/required-list-validation-alias")
def read_required_list_validation_alias(
- p: Annotated[List[str], Query(validation_alias="p_val_alias")],
+ p: Annotated[list[str], Query(validation_alias="p_val_alias")],
):
return {"p": p}
class QueryModelRequiredListValidationAlias(BaseModel):
- p: List[str] = Field(validation_alias="p_val_alias")
+ p: list[str] = Field(validation_alias="p_val_alias")
@app.get("/model-required-list-validation-alias")
@@ -235,7 +194,6 @@ async def read_model_required_list_validation_alias(
return {"p": p.p}
-@needs_pydanticv2
@pytest.mark.parametrize(
"path",
["/required-list-validation-alias", "/model-required-list-validation-alias"],
@@ -255,7 +213,6 @@ def test_required_list_validation_alias_schema(path: str):
]
-@needs_pydanticv2
@pytest.mark.parametrize(
"path",
[
@@ -282,7 +239,6 @@ def test_required_list_validation_alias_missing(path: str):
}
-@needs_pydanticv2
@pytest.mark.parametrize(
"path",
[
@@ -307,7 +263,6 @@ def test_required_list_validation_alias_by_name(path: str):
}
-@needs_pydanticv2
@pytest.mark.parametrize(
"path",
["/required-list-validation-alias", "/model-required-list-validation-alias"],
@@ -326,13 +281,13 @@ def test_required_list_validation_alias_by_validation_alias(path: str):
@app.get("/required-list-alias-and-validation-alias")
def read_required_list_alias_and_validation_alias(
- p: Annotated[List[str], Query(alias="p_alias", validation_alias="p_val_alias")],
+ p: Annotated[list[str], Query(alias="p_alias", validation_alias="p_val_alias")],
):
return {"p": p}
class QueryModelRequiredListAliasAndValidationAlias(BaseModel):
- p: List[str] = Field(alias="p_alias", validation_alias="p_val_alias")
+ p: list[str] = Field(alias="p_alias", validation_alias="p_val_alias")
@app.get("/model-required-list-alias-and-validation-alias")
@@ -342,7 +297,6 @@ def read_model_required_list_alias_and_validation_alias(
return {"p": p.p}
-@needs_pydanticv2
@pytest.mark.parametrize(
"path",
[
@@ -365,7 +319,6 @@ def test_required_list_alias_and_validation_alias_schema(path: str):
]
-@needs_pydanticv2
@pytest.mark.parametrize(
"path",
[
@@ -392,7 +345,6 @@ def test_required_list_alias_and_validation_alias_missing(path: str):
}
-@needs_pydanticv2
@pytest.mark.parametrize(
"path",
[
@@ -427,7 +379,6 @@ def test_required_list_alias_and_validation_alias_by_name(path: str):
}
-@needs_pydanticv2
@pytest.mark.parametrize(
"path",
[
@@ -454,7 +405,6 @@ def test_required_list_alias_and_validation_alias_by_alias(path: str):
}
-@needs_pydanticv2
@pytest.mark.parametrize(
"path",
[
diff --git a/tests/test_request_params/test_query/test_optional_list.py b/tests/test_request_params/test_query/test_optional_list.py
index 5609213364..351e03a713 100644
--- a/tests/test_request_params/test_query/test_optional_list.py
+++ b/tests/test_request_params/test_query/test_optional_list.py
@@ -1,13 +1,9 @@
-from typing import List, Optional
+from typing import Annotated, Optional
import pytest
-from dirty_equals import IsDict
from fastapi import FastAPI, Query
from fastapi.testclient import TestClient
from pydantic import BaseModel, Field
-from typing_extensions import Annotated
-
-from tests.utils import needs_pydanticv2
app = FastAPI()
@@ -17,13 +13,13 @@ app = FastAPI()
@app.get("/optional-list-str")
async def read_optional_list_str(
- p: Annotated[Optional[List[str]], Query()] = None,
+ p: Annotated[Optional[list[str]], Query()] = None,
):
return {"p": p}
class QueryModelOptionalListStr(BaseModel):
- p: Optional[List[str]] = None
+ p: Optional[list[str]] = None
@app.get("/model-optional-list-str")
@@ -39,29 +35,18 @@ async def read_model_optional_list_str(
)
def test_optional_list_str_schema(path: str):
assert app.openapi()["paths"][path]["get"]["parameters"] == [
- IsDict(
- {
- "required": False,
- "schema": {
- "anyOf": [
- {"items": {"type": "string"}, "type": "array"},
- {"type": "null"},
- ],
- "title": "P",
- },
- "name": "p",
- "in": "query",
- }
- )
- | IsDict(
- # TODO: remove when deprecating Pydantic v1
- {
- "required": False,
- "schema": {"items": {"type": "string"}, "type": "array", "title": "P"},
- "name": "p",
- "in": "query",
- }
- )
+ {
+ "required": False,
+ "schema": {
+ "anyOf": [
+ {"items": {"type": "string"}, "type": "array"},
+ {"type": "null"},
+ ],
+ "title": "P",
+ },
+ "name": "p",
+ "in": "query",
+ }
]
@@ -93,13 +78,13 @@ def test_optional_list_str(path: str):
@app.get("/optional-list-alias")
async def read_optional_list_alias(
- p: Annotated[Optional[List[str]], Query(alias="p_alias")] = None,
+ p: Annotated[Optional[list[str]], Query(alias="p_alias")] = None,
):
return {"p": p}
class QueryModelOptionalListAlias(BaseModel):
- p: Optional[List[str]] = Field(None, alias="p_alias")
+ p: Optional[list[str]] = Field(None, alias="p_alias")
@app.get("/model-optional-list-alias")
@@ -115,33 +100,18 @@ async def read_model_optional_list_alias(
)
def test_optional_list_str_alias_schema(path: str):
assert app.openapi()["paths"][path]["get"]["parameters"] == [
- IsDict(
- {
- "required": False,
- "schema": {
- "anyOf": [
- {"items": {"type": "string"}, "type": "array"},
- {"type": "null"},
- ],
- "title": "P Alias",
- },
- "name": "p_alias",
- "in": "query",
- }
- )
- | IsDict(
- # TODO: remove when deprecating Pydantic v1
- {
- "required": False,
- "schema": {
- "items": {"type": "string"},
- "type": "array",
- "title": "P Alias",
- },
- "name": "p_alias",
- "in": "query",
- }
- )
+ {
+ "required": False,
+ "schema": {
+ "anyOf": [
+ {"items": {"type": "string"}, "type": "array"},
+ {"type": "null"},
+ ],
+ "title": "P Alias",
+ },
+ "name": "p_alias",
+ "in": "query",
+ }
]
@@ -187,13 +157,13 @@ def test_optional_list_alias_by_alias(path: str):
@app.get("/optional-list-validation-alias")
def read_optional_list_validation_alias(
- p: Annotated[Optional[List[str]], Query(validation_alias="p_val_alias")] = None,
+ p: Annotated[Optional[list[str]], Query(validation_alias="p_val_alias")] = None,
):
return {"p": p}
class QueryModelOptionalListValidationAlias(BaseModel):
- p: Optional[List[str]] = Field(None, validation_alias="p_val_alias")
+ p: Optional[list[str]] = Field(None, validation_alias="p_val_alias")
@app.get("/model-optional-list-validation-alias")
@@ -203,7 +173,6 @@ def read_model_optional_list_validation_alias(
return {"p": p.p}
-@needs_pydanticv2
@pytest.mark.parametrize(
"path",
["/optional-list-validation-alias", "/model-optional-list-validation-alias"],
@@ -225,7 +194,6 @@ def test_optional_list_validation_alias_schema(path: str):
]
-@needs_pydanticv2
@pytest.mark.parametrize(
"path",
["/optional-list-validation-alias", "/model-optional-list-validation-alias"],
@@ -237,7 +205,6 @@ def test_optional_list_validation_alias_missing(path: str):
assert response.json() == {"p": None}
-@needs_pydanticv2
@pytest.mark.parametrize(
"path",
[
@@ -252,7 +219,6 @@ def test_optional_list_validation_alias_by_name(path: str):
assert response.json() == {"p": None}
-@needs_pydanticv2
@pytest.mark.parametrize(
"path",
["/optional-list-validation-alias", "/model-optional-list-validation-alias"],
@@ -271,14 +237,14 @@ def test_optional_list_validation_alias_by_validation_alias(path: str):
@app.get("/optional-list-alias-and-validation-alias")
def read_optional_list_alias_and_validation_alias(
p: Annotated[
- Optional[List[str]], Query(alias="p_alias", validation_alias="p_val_alias")
+ Optional[list[str]], Query(alias="p_alias", validation_alias="p_val_alias")
] = None,
):
return {"p": p}
class QueryModelOptionalListAliasAndValidationAlias(BaseModel):
- p: Optional[List[str]] = Field(
+ p: Optional[list[str]] = Field(
None, alias="p_alias", validation_alias="p_val_alias"
)
@@ -290,7 +256,6 @@ def read_model_optional_list_alias_and_validation_alias(
return {"p": p.p}
-@needs_pydanticv2
@pytest.mark.parametrize(
"path",
[
@@ -315,7 +280,6 @@ def test_optional_list_alias_and_validation_alias_schema(path: str):
]
-@needs_pydanticv2
@pytest.mark.parametrize(
"path",
[
@@ -330,7 +294,6 @@ def test_optional_list_alias_and_validation_alias_missing(path: str):
assert response.json() == {"p": None}
-@needs_pydanticv2
@pytest.mark.parametrize(
"path",
[
@@ -345,7 +308,6 @@ def test_optional_list_alias_and_validation_alias_by_name(path: str):
assert response.json() == {"p": None}
-@needs_pydanticv2
@pytest.mark.parametrize(
"path",
[
@@ -360,7 +322,6 @@ def test_optional_list_alias_and_validation_alias_by_alias(path: str):
assert response.json() == {"p": None}
-@needs_pydanticv2
@pytest.mark.parametrize(
"path",
[
diff --git a/tests/test_request_params/test_query/test_optional_str.py b/tests/test_request_params/test_query/test_optional_str.py
index 25e4ea42e6..12e1b465a7 100644
--- a/tests/test_request_params/test_query/test_optional_str.py
+++ b/tests/test_request_params/test_query/test_optional_str.py
@@ -1,13 +1,9 @@
-from typing import Optional
+from typing import Annotated, Optional
import pytest
-from dirty_equals import IsDict
from fastapi import FastAPI, Query
from fastapi.testclient import TestClient
from pydantic import BaseModel, Field
-from typing_extensions import Annotated
-
-from tests.utils import needs_pydanticv2
app = FastAPI()
@@ -35,26 +31,15 @@ async def read_model_optional_str(p: Annotated[QueryModelOptionalStr, Query()]):
)
def test_optional_str_schema(path: str):
assert app.openapi()["paths"][path]["get"]["parameters"] == [
- IsDict(
- {
- "required": False,
- "schema": {
- "anyOf": [{"type": "string"}, {"type": "null"}],
- "title": "P",
- },
- "name": "p",
- "in": "query",
- }
- )
- | IsDict(
- # TODO: remove when deprecating Pydantic v1
- {
- "required": False,
- "schema": {"title": "P", "type": "string"},
- "name": "p",
- "in": "query",
- }
- )
+ {
+ "required": False,
+ "schema": {
+ "anyOf": [{"type": "string"}, {"type": "null"}],
+ "title": "P",
+ },
+ "name": "p",
+ "in": "query",
+ }
]
@@ -106,26 +91,15 @@ async def read_model_optional_alias(p: Annotated[QueryModelOptionalAlias, Query(
)
def test_optional_str_alias_schema(path: str):
assert app.openapi()["paths"][path]["get"]["parameters"] == [
- IsDict(
- {
- "required": False,
- "schema": {
- "anyOf": [{"type": "string"}, {"type": "null"}],
- "title": "P Alias",
- },
- "name": "p_alias",
- "in": "query",
- }
- )
- | IsDict(
- # TODO: remove when deprecating Pydantic v1
- {
- "required": False,
- "schema": {"title": "P Alias", "type": "string"},
- "name": "p_alias",
- "in": "query",
- }
- )
+ {
+ "required": False,
+ "schema": {
+ "anyOf": [{"type": "string"}, {"type": "null"}],
+ "title": "P Alias",
+ },
+ "name": "p_alias",
+ "in": "query",
+ }
]
@@ -187,7 +161,6 @@ def read_model_optional_validation_alias(
return {"p": p.p}
-@needs_pydanticv2
@pytest.mark.parametrize(
"path",
["/optional-validation-alias", "/model-optional-validation-alias"],
@@ -206,7 +179,6 @@ def test_optional_validation_alias_schema(path: str):
]
-@needs_pydanticv2
@pytest.mark.parametrize(
"path",
["/optional-validation-alias", "/model-optional-validation-alias"],
@@ -218,7 +190,6 @@ def test_optional_validation_alias_missing(path: str):
assert response.json() == {"p": None}
-@needs_pydanticv2
@pytest.mark.parametrize(
"path",
[
@@ -233,7 +204,6 @@ def test_optional_validation_alias_by_name(path: str):
assert response.json() == {"p": None}
-@needs_pydanticv2
@pytest.mark.parametrize(
"path",
[
@@ -272,7 +242,6 @@ def read_model_optional_alias_and_validation_alias(
return {"p": p.p}
-@needs_pydanticv2
@pytest.mark.parametrize(
"path",
[
@@ -294,7 +263,6 @@ def test_optional_alias_and_validation_alias_schema(path: str):
]
-@needs_pydanticv2
@pytest.mark.parametrize(
"path",
[
@@ -309,7 +277,6 @@ def test_optional_alias_and_validation_alias_missing(path: str):
assert response.json() == {"p": None}
-@needs_pydanticv2
@pytest.mark.parametrize(
"path",
[
@@ -324,7 +291,6 @@ def test_optional_alias_and_validation_alias_by_name(path: str):
assert response.json() == {"p": None}
-@needs_pydanticv2
@pytest.mark.parametrize(
"path",
[
@@ -339,7 +305,6 @@ def test_optional_alias_and_validation_alias_by_alias(path: str):
assert response.json() == {"p": None}
-@needs_pydanticv2
@pytest.mark.parametrize(
"path",
[
diff --git a/tests/test_request_params/test_query/test_required_str.py b/tests/test_request_params/test_query/test_required_str.py
index aa0731e2c6..9e7b961453 100644
--- a/tests/test_request_params/test_query/test_required_str.py
+++ b/tests/test_request_params/test_query/test_required_str.py
@@ -1,11 +1,10 @@
+from typing import Annotated
+
import pytest
-from dirty_equals import IsDict, IsOneOf
+from dirty_equals import IsOneOf
from fastapi import FastAPI, Query
from fastapi.testclient import TestClient
from pydantic import BaseModel, Field
-from typing_extensions import Annotated
-
-from tests.utils import needs_pydanticv2
app = FastAPI()
@@ -50,29 +49,16 @@ def test_required_str_missing(path: str):
client = TestClient(app)
response = client.get(path)
assert response.status_code == 422
- assert response.json() == IsDict(
- {
- "detail": [
- {
- "type": "missing",
- "loc": ["query", "p"],
- "msg": "Field required",
- "input": IsOneOf(None, {}),
- }
- ]
- }
- ) | IsDict(
- # TODO: remove when deprecating Pydantic v1
- {
- "detail": [
- {
- "loc": ["query", "p"],
- "msg": "field required",
- "type": "value_error.missing",
- }
- ]
- }
- )
+ assert response.json() == {
+ "detail": [
+ {
+ "type": "missing",
+ "loc": ["query", "p"],
+ "msg": "Field required",
+ "input": IsOneOf(None, {}),
+ }
+ ]
+ }
@pytest.mark.parametrize(
@@ -127,29 +113,16 @@ def test_required_alias_missing(path: str):
client = TestClient(app)
response = client.get(path)
assert response.status_code == 422
- assert response.json() == IsDict(
- {
- "detail": [
- {
- "type": "missing",
- "loc": ["query", "p_alias"],
- "msg": "Field required",
- "input": IsOneOf(None, {}),
- }
- ]
- }
- ) | IsDict(
- # TODO: remove when deprecating Pydantic v1
- {
- "detail": [
- {
- "loc": ["query", "p_alias"],
- "msg": "field required",
- "type": "value_error.missing",
- }
- ]
- }
- )
+ assert response.json() == {
+ "detail": [
+ {
+ "type": "missing",
+ "loc": ["query", "p_alias"],
+ "msg": "Field required",
+ "input": IsOneOf(None, {}),
+ }
+ ]
+ }
@pytest.mark.parametrize(
@@ -163,32 +136,19 @@ def test_required_alias_by_name(path: str):
client = TestClient(app)
response = client.get(f"{path}?p=hello")
assert response.status_code == 422
- assert response.json() == IsDict(
- {
- "detail": [
- {
- "type": "missing",
- "loc": ["query", "p_alias"],
- "msg": "Field required",
- "input": IsOneOf(
- None,
- {"p": "hello"},
- ),
- }
- ]
- }
- ) | IsDict(
- # TODO: remove when deprecating Pydantic v1
- {
- "detail": [
- {
- "loc": ["query", "p_alias"],
- "msg": "field required",
- "type": "value_error.missing",
- }
- ]
- }
- )
+ assert response.json() == {
+ "detail": [
+ {
+ "type": "missing",
+ "loc": ["query", "p_alias"],
+ "msg": "Field required",
+ "input": IsOneOf(
+ None,
+ {"p": "hello"},
+ ),
+ }
+ ]
+ }
@pytest.mark.parametrize(
@@ -227,7 +187,6 @@ def read_model_required_validation_alias(
return {"p": p.p}
-@needs_pydanticv2
@pytest.mark.parametrize(
"path",
["/required-validation-alias", "/model-required-validation-alias"],
@@ -243,7 +202,6 @@ def test_required_validation_alias_schema(path: str):
]
-@needs_pydanticv2
@pytest.mark.parametrize(
"path",
[
@@ -270,7 +228,6 @@ def test_required_validation_alias_missing(path: str):
}
-@needs_pydanticv2
@pytest.mark.parametrize(
"path",
[
@@ -295,7 +252,6 @@ def test_required_validation_alias_by_name(path: str):
}
-@needs_pydanticv2
@pytest.mark.parametrize(
"path",
[
@@ -333,7 +289,6 @@ def read_model_required_alias_and_validation_alias(
return {"p": p.p}
-@needs_pydanticv2
@pytest.mark.parametrize(
"path",
[
@@ -352,7 +307,6 @@ def test_required_alias_and_validation_alias_schema(path: str):
]
-@needs_pydanticv2
@pytest.mark.parametrize(
"path",
[
@@ -379,7 +333,6 @@ def test_required_alias_and_validation_alias_missing(path: str):
}
-@needs_pydanticv2
@pytest.mark.parametrize(
"path",
[
@@ -410,7 +363,6 @@ def test_required_alias_and_validation_alias_by_name(path: str):
}
-@needs_pydanticv2
@pytest.mark.parametrize(
"path",
[
@@ -438,7 +390,6 @@ def test_required_alias_and_validation_alias_by_alias(path: str):
}
-@needs_pydanticv2
@pytest.mark.parametrize(
"path",
[
diff --git a/tests/test_response_by_alias.py b/tests/test_response_by_alias.py
index e162cd39b5..807d2600b9 100644
--- a/tests/test_response_by_alias.py
+++ b/tests/test_response_by_alias.py
@@ -1,7 +1,4 @@
-from typing import List
-
from fastapi import FastAPI
-from fastapi._compat import PYDANTIC_V2
from fastapi.testclient import TestClient
from pydantic import BaseModel, ConfigDict, Field
@@ -15,24 +12,14 @@ class Model(BaseModel):
class ModelNoAlias(BaseModel):
name: str
- if PYDANTIC_V2:
- model_config = ConfigDict(
- json_schema_extra={
- "description": (
- "response_model_by_alias=False is basically a quick hack, to support "
- "proper OpenAPI use another model with the correct field names"
- )
- }
- )
- else:
-
- class Config:
- schema_extra = {
- "description": (
- "response_model_by_alias=False is basically a quick hack, to support "
- "proper OpenAPI use another model with the correct field names"
- )
- }
+ model_config = ConfigDict(
+ json_schema_extra={
+ "description": (
+ "response_model_by_alias=False is basically a quick hack, to support "
+ "proper OpenAPI use another model with the correct field names"
+ )
+ }
+ )
@app.get("/dict", response_model=Model, response_model_by_alias=False)
@@ -45,7 +32,7 @@ def read_model():
return Model(alias="Foo")
-@app.get("/list", response_model=List[Model], response_model_by_alias=False)
+@app.get("/list", response_model=list[Model], response_model_by_alias=False)
def read_list():
return [{"alias": "Foo"}, {"alias": "Bar"}]
@@ -60,7 +47,7 @@ def by_alias_model():
return Model(alias="Foo")
-@app.get("/by-alias/list", response_model=List[Model])
+@app.get("/by-alias/list", response_model=list[Model])
def by_alias_list():
return [{"alias": "Foo"}, {"alias": "Bar"}]
@@ -75,7 +62,7 @@ def no_alias_model():
return ModelNoAlias(name="Foo")
-@app.get("/no-alias/list", response_model=List[ModelNoAlias])
+@app.get("/no-alias/list", response_model=list[ModelNoAlias])
def no_alias_list():
return [{"name": "Foo"}, {"name": "Bar"}]
diff --git a/tests/test_response_class_no_mediatype.py b/tests/test_response_class_no_mediatype.py
index 706929ac36..4dc164bf92 100644
--- a/tests/test_response_class_no_mediatype.py
+++ b/tests/test_response_class_no_mediatype.py
@@ -1,5 +1,3 @@
-import typing
-
from fastapi import FastAPI, Response
from fastapi.responses import JSONResponse
from fastapi.testclient import TestClient
@@ -18,7 +16,7 @@ class Error(BaseModel):
class JsonApiError(BaseModel):
- errors: typing.List[Error]
+ errors: list[Error]
@app.get(
diff --git a/tests/test_response_code_no_body.py b/tests/test_response_code_no_body.py
index 3ca8708f12..70456a7462 100644
--- a/tests/test_response_code_no_body.py
+++ b/tests/test_response_code_no_body.py
@@ -1,5 +1,3 @@
-import typing
-
from fastapi import FastAPI
from fastapi.responses import JSONResponse
from fastapi.testclient import TestClient
@@ -18,7 +16,7 @@ class Error(BaseModel):
class JsonApiError(BaseModel):
- errors: typing.List[Error]
+ errors: list[Error]
@app.get(
diff --git a/tests/test_response_model_as_return_annotation.py b/tests/test_response_model_as_return_annotation.py
index 1745c69b60..58fba89f1a 100644
--- a/tests/test_response_model_as_return_annotation.py
+++ b/tests/test_response_model_as_return_annotation.py
@@ -1,4 +1,4 @@
-from typing import List, Union
+from typing import Union
import pytest
from fastapi import FastAPI
@@ -7,8 +7,6 @@ from fastapi.responses import JSONResponse, Response
from fastapi.testclient import TestClient
from pydantic import BaseModel
-from tests.utils import needs_pydanticv1
-
class BaseUser(BaseModel):
name: str
@@ -191,7 +189,7 @@ def response_model_filtering_model_annotation_submodel_return_submodel() -> DBUs
return DBUser(name="John", surname="Doe", password_hash="secret")
-@app.get("/response_model_list_of_model-no_annotation", response_model=List[User])
+@app.get("/response_model_list_of_model-no_annotation", response_model=list[User])
def response_model_list_of_model_no_annotation():
return [
DBUser(name="John", surname="Doe", password_hash="secret"),
@@ -200,7 +198,7 @@ def response_model_list_of_model_no_annotation():
@app.get("/no_response_model-annotation_list_of_model")
-def no_response_model_annotation_list_of_model() -> List[User]:
+def no_response_model_annotation_list_of_model() -> list[User]:
return [
DBUser(name="John", surname="Doe", password_hash="secret"),
DBUser(name="Jane", surname="Does", password_hash="secret2"),
@@ -208,7 +206,7 @@ def no_response_model_annotation_list_of_model() -> List[User]:
@app.get("/no_response_model-annotation_forward_ref_list_of_model")
-def no_response_model_annotation_forward_ref_list_of_model() -> "List[User]":
+def no_response_model_annotation_forward_ref_list_of_model() -> "list[User]":
return [
DBUser(name="John", surname="Doe", password_hash="secret"),
DBUser(name="Jane", surname="Does", password_hash="secret2"),
@@ -511,26 +509,6 @@ def test_invalid_response_model_field():
assert "parameter response_model=None" in e.value.args[0]
-# TODO: remove when dropping Pydantic v1 support
-@needs_pydanticv1
-def test_invalid_response_model_field_pv1():
- from fastapi._compat import v1
-
- app = FastAPI()
-
- class Model(v1.BaseModel):
- foo: str
-
- with pytest.raises(FastAPIError) as e:
-
- @app.get("/")
- def read_root() -> Union[Response, Model, None]:
- return Response(content="Foo") # pragma: no cover
-
- assert "valid Pydantic field type" in e.value.args[0]
- assert "parameter response_model=None" in e.value.args[0]
-
-
def test_openapi_schema():
response = client.get("/openapi.json")
assert response.status_code == 200, response.text
diff --git a/tests/test_response_model_data_filter.py b/tests/test_response_model_data_filter.py
index a3e0f95f04..358697d6df 100644
--- a/tests/test_response_model_data_filter.py
+++ b/tests/test_response_model_data_filter.py
@@ -1,5 +1,3 @@
-from typing import List
-
from fastapi import FastAPI
from fastapi.testclient import TestClient
from pydantic import BaseModel
@@ -44,7 +42,7 @@ async def read_pet(pet_id: int):
return pet
-@app.get("/pets/", response_model=List[PetOut])
+@app.get("/pets/", response_model=list[PetOut])
async def read_pets():
user = UserDB(
email="johndoe@example.com",
diff --git a/tests/test_response_model_data_filter_no_inheritance.py b/tests/test_response_model_data_filter_no_inheritance.py
index 64003a8417..c0c2f3a9dc 100644
--- a/tests/test_response_model_data_filter_no_inheritance.py
+++ b/tests/test_response_model_data_filter_no_inheritance.py
@@ -1,5 +1,3 @@
-from typing import List
-
from fastapi import FastAPI
from fastapi.testclient import TestClient
from pydantic import BaseModel
@@ -46,7 +44,7 @@ async def read_pet(pet_id: int):
return pet
-@app.get("/pets/", response_model=List[PetOut])
+@app.get("/pets/", response_model=list[PetOut])
async def read_pets():
user = UserDB(
email="johndoe@example.com",
diff --git a/tests/test_response_model_invalid.py b/tests/test_response_model_invalid.py
index 88b55a436d..f884b5c74a 100644
--- a/tests/test_response_model_invalid.py
+++ b/tests/test_response_model_invalid.py
@@ -1,5 +1,3 @@
-from typing import List
-
import pytest
from fastapi import FastAPI
from fastapi.exceptions import FastAPIError
@@ -22,7 +20,7 @@ def test_invalid_response_model_sub_type_raises():
with pytest.raises(FastAPIError):
app = FastAPI()
- @app.get("/", response_model=List[NonPydanticModel])
+ @app.get("/", response_model=list[NonPydanticModel])
def read_root():
pass # pragma: nocover
@@ -40,6 +38,6 @@ def test_invalid_response_model_sub_type_in_responses_raises():
with pytest.raises(FastAPIError):
app = FastAPI()
- @app.get("/", responses={"500": {"model": List[NonPydanticModel]}})
+ @app.get("/", responses={"500": {"model": list[NonPydanticModel]}})
def read_root():
pass # pragma: nocover
diff --git a/tests/test_response_model_sub_types.py b/tests/test_response_model_sub_types.py
index 660bcee1bb..8036bcb07d 100644
--- a/tests/test_response_model_sub_types.py
+++ b/tests/test_response_model_sub_types.py
@@ -1,5 +1,3 @@
-from typing import List
-
from fastapi import FastAPI
from fastapi.testclient import TestClient
from pydantic import BaseModel
@@ -17,7 +15,7 @@ def valid1():
pass
-@app.get("/valid2", responses={"500": {"model": List[int]}})
+@app.get("/valid2", responses={"500": {"model": list[int]}})
def valid2():
pass
@@ -27,7 +25,7 @@ def valid3():
pass
-@app.get("/valid4", responses={"500": {"model": List[Model]}})
+@app.get("/valid4", responses={"500": {"model": list[Model]}})
def valid4():
pass
diff --git a/tests/test_router_events.py b/tests/test_router_events.py
index dd7ff3314b..9df299cdaa 100644
--- a/tests/test_router_events.py
+++ b/tests/test_router_events.py
@@ -1,5 +1,6 @@
+from collections.abc import AsyncGenerator
from contextlib import asynccontextmanager
-from typing import AsyncGenerator, Dict, Union
+from typing import Union
import pytest
from fastapi import APIRouter, FastAPI, Request
@@ -28,7 +29,7 @@ def test_router_events(state: State) -> None:
app = FastAPI()
@app.get("/")
- def main() -> Dict[str, str]:
+ def main() -> dict[str, str]:
return {"message": "Hello World"}
@app.on_event("startup")
@@ -96,7 +97,7 @@ def test_app_lifespan_state(state: State) -> None:
app = FastAPI(lifespan=lifespan)
@app.get("/")
- def main() -> Dict[str, str]:
+ def main() -> dict[str, str]:
return {"message": "Hello World"}
assert state.app_startup is False
@@ -113,19 +114,19 @@ def test_app_lifespan_state(state: State) -> None:
def test_router_nested_lifespan_state(state: State) -> None:
@asynccontextmanager
- async def lifespan(app: FastAPI) -> AsyncGenerator[Dict[str, bool], None]:
+ async def lifespan(app: FastAPI) -> AsyncGenerator[dict[str, bool], None]:
state.app_startup = True
yield {"app": True}
state.app_shutdown = True
@asynccontextmanager
- async def router_lifespan(app: FastAPI) -> AsyncGenerator[Dict[str, bool], None]:
+ async def router_lifespan(app: FastAPI) -> AsyncGenerator[dict[str, bool], None]:
state.router_startup = True
yield {"router": True}
state.router_shutdown = True
@asynccontextmanager
- async def subrouter_lifespan(app: FastAPI) -> AsyncGenerator[Dict[str, bool], None]:
+ async def subrouter_lifespan(app: FastAPI) -> AsyncGenerator[dict[str, bool], None]:
state.sub_router_startup = True
yield {"sub_router": True}
state.sub_router_shutdown = True
@@ -139,7 +140,7 @@ def test_router_nested_lifespan_state(state: State) -> None:
app.include_router(router)
@app.get("/")
- def main(request: Request) -> Dict[str, str]:
+ def main(request: Request) -> dict[str, str]:
assert request.state.app
assert request.state.router
assert request.state.sub_router
@@ -175,7 +176,7 @@ def test_router_nested_lifespan_state_overriding_by_parent() -> None:
@asynccontextmanager
async def lifespan(
app: FastAPI,
- ) -> AsyncGenerator[Dict[str, Union[str, bool]], None]:
+ ) -> AsyncGenerator[dict[str, Union[str, bool]], None]:
yield {
"app_specific": True,
"overridden": "app",
@@ -184,7 +185,7 @@ def test_router_nested_lifespan_state_overriding_by_parent() -> None:
@asynccontextmanager
async def router_lifespan(
app: FastAPI,
- ) -> AsyncGenerator[Dict[str, Union[str, bool]], None]:
+ ) -> AsyncGenerator[dict[str, Union[str, bool]], None]:
yield {
"router_specific": True,
"overridden": "router", # should override parent
@@ -225,7 +226,7 @@ def test_merged_mixed_state_lifespans() -> None:
yield
@asynccontextmanager
- async def router_lifespan(app: FastAPI) -> AsyncGenerator[Dict[str, bool], None]:
+ async def router_lifespan(app: FastAPI) -> AsyncGenerator[dict[str, bool], None]:
yield {"router": True}
@asynccontextmanager
diff --git a/tests/test_schema_compat_pydantic_v2.py b/tests/test_schema_compat_pydantic_v2.py
index 39626c0eca..737687f256 100644
--- a/tests/test_schema_compat_pydantic_v2.py
+++ b/tests/test_schema_compat_pydantic_v2.py
@@ -4,7 +4,7 @@ from fastapi.testclient import TestClient
from inline_snapshot import snapshot
from pydantic import BaseModel
-from tests.utils import needs_py310, needs_pydanticv2
+from tests.utils import needs_py310
@pytest.fixture(name="client")
@@ -32,14 +32,12 @@ def get_client():
@needs_py310
-@needs_pydanticv2
def test_get(client: TestClient):
response = client.get("/users")
assert response.json() == {"username": "alice", "role": "admin"}
@needs_py310
-@needs_pydanticv2
def test_openapi_schema(client: TestClient):
response = client.get("openapi.json")
assert response.json() == snapshot(
diff --git a/tests/test_schema_extra_examples.py b/tests/test_schema_extra_examples.py
index b313f47e90..ac8999c90a 100644
--- a/tests/test_schema_extra_examples.py
+++ b/tests/test_schema_extra_examples.py
@@ -1,9 +1,8 @@
from typing import Union
import pytest
-from dirty_equals import IsDict
from fastapi import Body, Cookie, FastAPI, Header, Path, Query
-from fastapi._compat import PYDANTIC_V2
+from fastapi.exceptions import FastAPIDeprecationWarning
from fastapi.testclient import TestClient
from pydantic import BaseModel, ConfigDict
@@ -14,20 +13,15 @@ def create_app():
class Item(BaseModel):
data: str
- if PYDANTIC_V2:
- model_config = ConfigDict(
- json_schema_extra={"example": {"data": "Data in schema_extra"}}
- )
- else:
-
- class Config:
- schema_extra = {"example": {"data": "Data in schema_extra"}}
+ model_config = ConfigDict(
+ json_schema_extra={"example": {"data": "Data in schema_extra"}}
+ )
@app.post("/schema_extra/")
def schema_extra(item: Item):
return item
- with pytest.warns(DeprecationWarning):
+ with pytest.warns(FastAPIDeprecationWarning):
@app.post("/example/")
def example(item: Item = Body(example={"data": "Data in Body example"})):
@@ -44,7 +38,7 @@ def create_app():
):
return item
- with pytest.warns(DeprecationWarning):
+ with pytest.warns(FastAPIDeprecationWarning):
@app.post("/example_examples/")
def example_examples(
@@ -89,7 +83,7 @@ def create_app():
# ):
# return lastname
- with pytest.warns(DeprecationWarning):
+ with pytest.warns(FastAPIDeprecationWarning):
@app.get("/path_example/{item_id}")
def path_example(
@@ -107,7 +101,7 @@ def create_app():
):
return item_id
- with pytest.warns(DeprecationWarning):
+ with pytest.warns(FastAPIDeprecationWarning):
@app.get("/path_example_examples/{item_id}")
def path_example_examples(
@@ -118,7 +112,7 @@ def create_app():
):
return item_id
- with pytest.warns(DeprecationWarning):
+ with pytest.warns(FastAPIDeprecationWarning):
@app.get("/query_example/")
def query_example(
@@ -138,7 +132,7 @@ def create_app():
):
return data
- with pytest.warns(DeprecationWarning):
+ with pytest.warns(FastAPIDeprecationWarning):
@app.get("/query_example_examples/")
def query_example_examples(
@@ -150,7 +144,7 @@ def create_app():
):
return data
- with pytest.warns(DeprecationWarning):
+ with pytest.warns(FastAPIDeprecationWarning):
@app.get("/header_example/")
def header_example(
@@ -173,7 +167,7 @@ def create_app():
):
return data
- with pytest.warns(DeprecationWarning):
+ with pytest.warns(FastAPIDeprecationWarning):
@app.get("/header_example_examples/")
def header_example_examples(
@@ -185,7 +179,7 @@ def create_app():
):
return data
- with pytest.warns(DeprecationWarning):
+ with pytest.warns(FastAPIDeprecationWarning):
@app.get("/cookie_example/")
def cookie_example(
@@ -205,7 +199,7 @@ def create_app():
):
return data
- with pytest.warns(DeprecationWarning):
+ with pytest.warns(FastAPIDeprecationWarning):
@app.get("/cookie_example_examples/")
def cookie_example_examples(
@@ -341,28 +335,13 @@ def test_openapi_schema():
"requestBody": {
"content": {
"application/json": {
- "schema": IsDict(
- {
- "$ref": "#/components/schemas/Item",
- "examples": [
- {"data": "Data in Body examples, example1"},
- {"data": "Data in Body examples, example2"},
- ],
- }
- )
- | IsDict(
- # TODO: remove this when deprecating Pydantic v1
- {
- "allOf": [
- {"$ref": "#/components/schemas/Item"}
- ],
- "title": "Item",
- "examples": [
- {"data": "Data in Body examples, example1"},
- {"data": "Data in Body examples, example2"},
- ],
- }
- )
+ "schema": {
+ "$ref": "#/components/schemas/Item",
+ "examples": [
+ {"data": "Data in Body examples, example1"},
+ {"data": "Data in Body examples, example2"},
+ ],
+ }
}
},
"required": True,
@@ -392,28 +371,13 @@ def test_openapi_schema():
"requestBody": {
"content": {
"application/json": {
- "schema": IsDict(
- {
- "$ref": "#/components/schemas/Item",
- "examples": [
- {"data": "examples example_examples 1"},
- {"data": "examples example_examples 2"},
- ],
- }
- )
- | IsDict(
- # TODO: remove this when deprecating Pydantic v1
- {
- "allOf": [
- {"$ref": "#/components/schemas/Item"}
- ],
- "title": "Item",
- "examples": [
- {"data": "examples example_examples 1"},
- {"data": "examples example_examples 2"},
- ],
- },
- ),
+ "schema": {
+ "$ref": "#/components/schemas/Item",
+ "examples": [
+ {"data": "examples example_examples 1"},
+ {"data": "examples example_examples 2"},
+ ],
+ },
"example": {"data": "Overridden example"},
}
},
@@ -544,16 +508,10 @@ def test_openapi_schema():
"parameters": [
{
"required": False,
- "schema": IsDict(
- {
- "anyOf": [{"type": "string"}, {"type": "null"}],
- "title": "Data",
- }
- )
- | IsDict(
- # TODO: Remove this when deprecating Pydantic v1
- {"title": "Data", "type": "string"}
- ),
+ "schema": {
+ "anyOf": [{"type": "string"}, {"type": "null"}],
+ "title": "Data",
+ },
"example": "query1",
"name": "data",
"in": "query",
@@ -584,21 +542,11 @@ def test_openapi_schema():
"parameters": [
{
"required": False,
- "schema": IsDict(
- {
- "anyOf": [{"type": "string"}, {"type": "null"}],
- "title": "Data",
- "examples": ["query1", "query2"],
- }
- )
- | IsDict(
- # TODO: Remove this when deprecating Pydantic v1
- {
- "type": "string",
- "title": "Data",
- "examples": ["query1", "query2"],
- }
- ),
+ "schema": {
+ "anyOf": [{"type": "string"}, {"type": "null"}],
+ "title": "Data",
+ "examples": ["query1", "query2"],
+ },
"name": "data",
"in": "query",
}
@@ -628,21 +576,11 @@ def test_openapi_schema():
"parameters": [
{
"required": False,
- "schema": IsDict(
- {
- "anyOf": [{"type": "string"}, {"type": "null"}],
- "title": "Data",
- "examples": ["query1", "query2"],
- }
- )
- | IsDict(
- # TODO: Remove this when deprecating Pydantic v1
- {
- "type": "string",
- "title": "Data",
- "examples": ["query1", "query2"],
- }
- ),
+ "schema": {
+ "anyOf": [{"type": "string"}, {"type": "null"}],
+ "title": "Data",
+ "examples": ["query1", "query2"],
+ },
"example": "query_overridden",
"name": "data",
"in": "query",
@@ -673,16 +611,10 @@ def test_openapi_schema():
"parameters": [
{
"required": False,
- "schema": IsDict(
- {
- "anyOf": [{"type": "string"}, {"type": "null"}],
- "title": "Data",
- }
- )
- | IsDict(
- # TODO: Remove this when deprecating Pydantic v1
- {"title": "Data", "type": "string"}
- ),
+ "schema": {
+ "anyOf": [{"type": "string"}, {"type": "null"}],
+ "title": "Data",
+ },
"example": "header1",
"name": "data",
"in": "header",
@@ -713,21 +645,11 @@ def test_openapi_schema():
"parameters": [
{
"required": False,
- "schema": IsDict(
- {
- "anyOf": [{"type": "string"}, {"type": "null"}],
- "title": "Data",
- "examples": ["header1", "header2"],
- }
- )
- | IsDict(
- # TODO: Remove this when deprecating Pydantic v1
- {
- "type": "string",
- "title": "Data",
- "examples": ["header1", "header2"],
- }
- ),
+ "schema": {
+ "anyOf": [{"type": "string"}, {"type": "null"}],
+ "title": "Data",
+ "examples": ["header1", "header2"],
+ },
"name": "data",
"in": "header",
}
@@ -757,21 +679,11 @@ def test_openapi_schema():
"parameters": [
{
"required": False,
- "schema": IsDict(
- {
- "anyOf": [{"type": "string"}, {"type": "null"}],
- "title": "Data",
- "examples": ["header1", "header2"],
- }
- )
- | IsDict(
- # TODO: Remove this when deprecating Pydantic v1
- {
- "title": "Data",
- "type": "string",
- "examples": ["header1", "header2"],
- }
- ),
+ "schema": {
+ "anyOf": [{"type": "string"}, {"type": "null"}],
+ "title": "Data",
+ "examples": ["header1", "header2"],
+ },
"example": "header_overridden",
"name": "data",
"in": "header",
@@ -802,16 +714,10 @@ def test_openapi_schema():
"parameters": [
{
"required": False,
- "schema": IsDict(
- {
- "anyOf": [{"type": "string"}, {"type": "null"}],
- "title": "Data",
- }
- )
- | IsDict(
- # TODO: Remove this when deprecating Pydantic v1
- {"title": "Data", "type": "string"}
- ),
+ "schema": {
+ "anyOf": [{"type": "string"}, {"type": "null"}],
+ "title": "Data",
+ },
"example": "cookie1",
"name": "data",
"in": "cookie",
@@ -842,21 +748,11 @@ def test_openapi_schema():
"parameters": [
{
"required": False,
- "schema": IsDict(
- {
- "anyOf": [{"type": "string"}, {"type": "null"}],
- "title": "Data",
- "examples": ["cookie1", "cookie2"],
- }
- )
- | IsDict(
- # TODO: Remove this when deprecating Pydantic v1
- {
- "title": "Data",
- "type": "string",
- "examples": ["cookie1", "cookie2"],
- }
- ),
+ "schema": {
+ "anyOf": [{"type": "string"}, {"type": "null"}],
+ "title": "Data",
+ "examples": ["cookie1", "cookie2"],
+ },
"name": "data",
"in": "cookie",
}
@@ -886,21 +782,11 @@ def test_openapi_schema():
"parameters": [
{
"required": False,
- "schema": IsDict(
- {
- "anyOf": [{"type": "string"}, {"type": "null"}],
- "title": "Data",
- "examples": ["cookie1", "cookie2"],
- }
- )
- | IsDict(
- # TODO: Remove this when deprecating Pydantic v1
- {
- "title": "Data",
- "type": "string",
- "examples": ["cookie1", "cookie2"],
- }
- ),
+ "schema": {
+ "anyOf": [{"type": "string"}, {"type": "null"}],
+ "title": "Data",
+ "examples": ["cookie1", "cookie2"],
+ },
"example": "cookie_overridden",
"name": "data",
"in": "cookie",
diff --git a/tests/test_schema_ref_pydantic_v2.py b/tests/test_schema_ref_pydantic_v2.py
index 119b76a529..69cb82a356 100644
--- a/tests/test_schema_ref_pydantic_v2.py
+++ b/tests/test_schema_ref_pydantic_v2.py
@@ -6,8 +6,6 @@ from fastapi.testclient import TestClient
from inline_snapshot import snapshot
from pydantic import BaseModel, ConfigDict, Field
-from tests.utils import needs_pydanticv2
-
@pytest.fixture(name="client")
def get_client():
@@ -25,13 +23,11 @@ def get_client():
return client
-@needs_pydanticv2
def test_get(client: TestClient):
response = client.get("/")
assert response.json() == {"$ref": "some-ref"}
-@needs_pydanticv2
def test_openapi_schema(client: TestClient):
response = client.get("openapi.json")
assert response.json() == snapshot(
diff --git a/tests/test_security_oauth2.py b/tests/test_security_oauth2.py
index 804e4152db..7ad9369956 100644
--- a/tests/test_security_oauth2.py
+++ b/tests/test_security_oauth2.py
@@ -1,5 +1,4 @@
import pytest
-from dirty_equals import IsDict
from fastapi import Depends, FastAPI, Security
from fastapi.security import OAuth2, OAuth2PasswordRequestFormStrict
from fastapi.testclient import TestClient
@@ -64,79 +63,43 @@ def test_security_oauth2_password_bearer_no_header():
def test_strict_login_no_data():
response = client.post("/login")
assert response.status_code == 422
- assert response.json() == IsDict(
- {
- "detail": [
- {
- "type": "missing",
- "loc": ["body", "grant_type"],
- "msg": "Field required",
- "input": None,
- },
- {
- "type": "missing",
- "loc": ["body", "username"],
- "msg": "Field required",
- "input": None,
- },
- {
- "type": "missing",
- "loc": ["body", "password"],
- "msg": "Field required",
- "input": None,
- },
- ]
- }
- ) | IsDict(
- # TODO: remove when deprecating Pydantic v1
- {
- "detail": [
- {
- "loc": ["body", "grant_type"],
- "msg": "field required",
- "type": "value_error.missing",
- },
- {
- "loc": ["body", "username"],
- "msg": "field required",
- "type": "value_error.missing",
- },
- {
- "loc": ["body", "password"],
- "msg": "field required",
- "type": "value_error.missing",
- },
- ]
- }
- )
+ assert response.json() == {
+ "detail": [
+ {
+ "type": "missing",
+ "loc": ["body", "grant_type"],
+ "msg": "Field required",
+ "input": None,
+ },
+ {
+ "type": "missing",
+ "loc": ["body", "username"],
+ "msg": "Field required",
+ "input": None,
+ },
+ {
+ "type": "missing",
+ "loc": ["body", "password"],
+ "msg": "Field required",
+ "input": None,
+ },
+ ]
+ }
def test_strict_login_no_grant_type():
response = client.post("/login", data={"username": "johndoe", "password": "secret"})
assert response.status_code == 422
- assert response.json() == IsDict(
- {
- "detail": [
- {
- "type": "missing",
- "loc": ["body", "grant_type"],
- "msg": "Field required",
- "input": None,
- }
- ]
- }
- ) | IsDict(
- # TODO: remove when deprecating Pydantic v1
- {
- "detail": [
- {
- "loc": ["body", "grant_type"],
- "msg": "field required",
- "type": "value_error.missing",
- }
- ]
- }
- )
+ assert response.json() == {
+ "detail": [
+ {
+ "type": "missing",
+ "loc": ["body", "grant_type"],
+ "msg": "Field required",
+ "input": None,
+ }
+ ]
+ }
@pytest.mark.parametrize(
@@ -153,31 +116,17 @@ def test_strict_login_incorrect_grant_type(grant_type: str):
data={"username": "johndoe", "password": "secret", "grant_type": grant_type},
)
assert response.status_code == 422
- assert response.json() == IsDict(
- {
- "detail": [
- {
- "type": "string_pattern_mismatch",
- "loc": ["body", "grant_type"],
- "msg": "String should match pattern '^password$'",
- "input": grant_type,
- "ctx": {"pattern": "^password$"},
- }
- ]
- }
- ) | IsDict(
- # TODO: remove when deprecating Pydantic v1
- {
- "detail": [
- {
- "loc": ["body", "grant_type"],
- "msg": 'string does not match regex "^password$"',
- "type": "value_error.str.regex",
- "ctx": {"pattern": "^password$"},
- }
- ]
- }
- )
+ assert response.json() == {
+ "detail": [
+ {
+ "type": "string_pattern_mismatch",
+ "loc": ["body", "grant_type"],
+ "msg": "String should match pattern '^password$'",
+ "input": grant_type,
+ "ctx": {"pattern": "^password$"},
+ }
+ ]
+ }
def test_strict_login_correct_grant_type():
@@ -264,26 +213,14 @@ def test_openapi_schema():
"username": {"title": "Username", "type": "string"},
"password": {"title": "Password", "type": "string"},
"scope": {"title": "Scope", "type": "string", "default": ""},
- "client_id": IsDict(
- {
- "title": "Client Id",
- "anyOf": [{"type": "string"}, {"type": "null"}],
- }
- )
- | IsDict(
- # TODO: remove when deprecating Pydantic v1
- {"title": "Client Id", "type": "string"}
- ),
- "client_secret": IsDict(
- {
- "title": "Client Secret",
- "anyOf": [{"type": "string"}, {"type": "null"}],
- }
- )
- | IsDict(
- # TODO: remove when deprecating Pydantic v1
- {"title": "Client Secret", "type": "string"}
- ),
+ "client_id": {
+ "title": "Client Id",
+ "anyOf": [{"type": "string"}, {"type": "null"}],
+ },
+ "client_secret": {
+ "title": "Client Secret",
+ "anyOf": [{"type": "string"}, {"type": "null"}],
+ },
},
},
"ValidationError": {
diff --git a/tests/test_security_oauth2_authorization_code_bearer_scopes_openapi.py b/tests/test_security_oauth2_authorization_code_bearer_scopes_openapi.py
index d41f1dc1f0..583007c8b7 100644
--- a/tests/test_security_oauth2_authorization_code_bearer_scopes_openapi.py
+++ b/tests/test_security_oauth2_authorization_code_bearer_scopes_openapi.py
@@ -1,12 +1,11 @@
# Ref: https://github.com/fastapi/fastapi/issues/14454
-from typing import Optional
+from typing import Annotated, Optional
from fastapi import APIRouter, Depends, FastAPI, Security
from fastapi.security import OAuth2AuthorizationCodeBearer
from fastapi.testclient import TestClient
from inline_snapshot import snapshot
-from typing_extensions import Annotated
oauth2_scheme = OAuth2AuthorizationCodeBearer(
authorizationUrl="authorize",
diff --git a/tests/test_security_oauth2_authorization_code_bearer_scopes_openapi_simple.py b/tests/test_security_oauth2_authorization_code_bearer_scopes_openapi_simple.py
index ff866d4fc9..1c21369d33 100644
--- a/tests/test_security_oauth2_authorization_code_bearer_scopes_openapi_simple.py
+++ b/tests/test_security_oauth2_authorization_code_bearer_scopes_openapi_simple.py
@@ -1,10 +1,11 @@
# Ref: https://github.com/fastapi/fastapi/issues/14454
+from typing import Annotated
+
from fastapi import Depends, FastAPI, Security
from fastapi.security import OAuth2AuthorizationCodeBearer
from fastapi.testclient import TestClient
from inline_snapshot import snapshot
-from typing_extensions import Annotated
oauth2_scheme = OAuth2AuthorizationCodeBearer(
authorizationUrl="api/oauth/authorize",
diff --git a/tests/test_security_oauth2_optional.py b/tests/test_security_oauth2_optional.py
index 046ac57637..57c16058af 100644
--- a/tests/test_security_oauth2_optional.py
+++ b/tests/test_security_oauth2_optional.py
@@ -1,7 +1,6 @@
from typing import Optional
import pytest
-from dirty_equals import IsDict
from fastapi import Depends, FastAPI, Security
from fastapi.security import OAuth2, OAuth2PasswordRequestFormStrict
from fastapi.testclient import TestClient
@@ -67,79 +66,43 @@ def test_security_oauth2_password_bearer_no_header():
def test_strict_login_no_data():
response = client.post("/login")
assert response.status_code == 422
- assert response.json() == IsDict(
- {
- "detail": [
- {
- "type": "missing",
- "loc": ["body", "grant_type"],
- "msg": "Field required",
- "input": None,
- },
- {
- "type": "missing",
- "loc": ["body", "username"],
- "msg": "Field required",
- "input": None,
- },
- {
- "type": "missing",
- "loc": ["body", "password"],
- "msg": "Field required",
- "input": None,
- },
- ]
- }
- ) | IsDict(
- # TODO: remove when deprecating Pydantic v1
- {
- "detail": [
- {
- "loc": ["body", "grant_type"],
- "msg": "field required",
- "type": "value_error.missing",
- },
- {
- "loc": ["body", "username"],
- "msg": "field required",
- "type": "value_error.missing",
- },
- {
- "loc": ["body", "password"],
- "msg": "field required",
- "type": "value_error.missing",
- },
- ]
- }
- )
+ assert response.json() == {
+ "detail": [
+ {
+ "type": "missing",
+ "loc": ["body", "grant_type"],
+ "msg": "Field required",
+ "input": None,
+ },
+ {
+ "type": "missing",
+ "loc": ["body", "username"],
+ "msg": "Field required",
+ "input": None,
+ },
+ {
+ "type": "missing",
+ "loc": ["body", "password"],
+ "msg": "Field required",
+ "input": None,
+ },
+ ]
+ }
def test_strict_login_no_grant_type():
response = client.post("/login", data={"username": "johndoe", "password": "secret"})
assert response.status_code == 422
- assert response.json() == IsDict(
- {
- "detail": [
- {
- "type": "missing",
- "loc": ["body", "grant_type"],
- "msg": "Field required",
- "input": None,
- }
- ]
- }
- ) | IsDict(
- # TODO: remove when deprecating Pydantic v1
- {
- "detail": [
- {
- "loc": ["body", "grant_type"],
- "msg": "field required",
- "type": "value_error.missing",
- }
- ]
- }
- )
+ assert response.json() == {
+ "detail": [
+ {
+ "type": "missing",
+ "loc": ["body", "grant_type"],
+ "msg": "Field required",
+ "input": None,
+ }
+ ]
+ }
@pytest.mark.parametrize(
@@ -156,31 +119,17 @@ def test_strict_login_incorrect_grant_type(grant_type: str):
data={"username": "johndoe", "password": "secret", "grant_type": grant_type},
)
assert response.status_code == 422
- assert response.json() == IsDict(
- {
- "detail": [
- {
- "type": "string_pattern_mismatch",
- "loc": ["body", "grant_type"],
- "msg": "String should match pattern '^password$'",
- "input": grant_type,
- "ctx": {"pattern": "^password$"},
- }
- ]
- }
- ) | IsDict(
- # TODO: remove when deprecating Pydantic v1
- {
- "detail": [
- {
- "loc": ["body", "grant_type"],
- "msg": 'string does not match regex "^password$"',
- "type": "value_error.str.regex",
- "ctx": {"pattern": "^password$"},
- }
- ]
- }
- )
+ assert response.json() == {
+ "detail": [
+ {
+ "type": "string_pattern_mismatch",
+ "loc": ["body", "grant_type"],
+ "msg": "String should match pattern '^password$'",
+ "input": grant_type,
+ "ctx": {"pattern": "^password$"},
+ }
+ ]
+ }
def test_strict_login_correct_data():
@@ -267,26 +216,14 @@ def test_openapi_schema():
"username": {"title": "Username", "type": "string"},
"password": {"title": "Password", "type": "string"},
"scope": {"title": "Scope", "type": "string", "default": ""},
- "client_id": IsDict(
- {
- "title": "Client Id",
- "anyOf": [{"type": "string"}, {"type": "null"}],
- }
- )
- | IsDict(
- # TODO: remove when deprecating Pydantic v1
- {"title": "Client Id", "type": "string"}
- ),
- "client_secret": IsDict(
- {
- "title": "Client Secret",
- "anyOf": [{"type": "string"}, {"type": "null"}],
- }
- )
- | IsDict(
- # TODO: remove when deprecating Pydantic v1
- {"title": "Client Secret", "type": "string"}
- ),
+ "client_id": {
+ "title": "Client Id",
+ "anyOf": [{"type": "string"}, {"type": "null"}],
+ },
+ "client_secret": {
+ "title": "Client Secret",
+ "anyOf": [{"type": "string"}, {"type": "null"}],
+ },
},
},
"ValidationError": {
diff --git a/tests/test_security_oauth2_optional_description.py b/tests/test_security_oauth2_optional_description.py
index 629cddca2f..60c6c242e0 100644
--- a/tests/test_security_oauth2_optional_description.py
+++ b/tests/test_security_oauth2_optional_description.py
@@ -1,7 +1,6 @@
from typing import Optional
import pytest
-from dirty_equals import IsDict
from fastapi import Depends, FastAPI, Security
from fastapi.security import OAuth2, OAuth2PasswordRequestFormStrict
from fastapi.testclient import TestClient
@@ -68,79 +67,43 @@ def test_security_oauth2_password_bearer_no_header():
def test_strict_login_None():
response = client.post("/login", data=None)
assert response.status_code == 422
- assert response.json() == IsDict(
- {
- "detail": [
- {
- "type": "missing",
- "loc": ["body", "grant_type"],
- "msg": "Field required",
- "input": None,
- },
- {
- "type": "missing",
- "loc": ["body", "username"],
- "msg": "Field required",
- "input": None,
- },
- {
- "type": "missing",
- "loc": ["body", "password"],
- "msg": "Field required",
- "input": None,
- },
- ]
- }
- ) | IsDict(
- # TODO: remove when deprecating Pydantic v1
- {
- "detail": [
- {
- "loc": ["body", "grant_type"],
- "msg": "field required",
- "type": "value_error.missing",
- },
- {
- "loc": ["body", "username"],
- "msg": "field required",
- "type": "value_error.missing",
- },
- {
- "loc": ["body", "password"],
- "msg": "field required",
- "type": "value_error.missing",
- },
- ]
- }
- )
+ assert response.json() == {
+ "detail": [
+ {
+ "type": "missing",
+ "loc": ["body", "grant_type"],
+ "msg": "Field required",
+ "input": None,
+ },
+ {
+ "type": "missing",
+ "loc": ["body", "username"],
+ "msg": "Field required",
+ "input": None,
+ },
+ {
+ "type": "missing",
+ "loc": ["body", "password"],
+ "msg": "Field required",
+ "input": None,
+ },
+ ]
+ }
def test_strict_login_no_grant_type():
response = client.post("/login", data={"username": "johndoe", "password": "secret"})
assert response.status_code == 422
- assert response.json() == IsDict(
- {
- "detail": [
- {
- "type": "missing",
- "loc": ["body", "grant_type"],
- "msg": "Field required",
- "input": None,
- }
- ]
- }
- ) | IsDict(
- # TODO: remove when deprecating Pydantic v1
- {
- "detail": [
- {
- "loc": ["body", "grant_type"],
- "msg": "field required",
- "type": "value_error.missing",
- }
- ]
- }
- )
+ assert response.json() == {
+ "detail": [
+ {
+ "type": "missing",
+ "loc": ["body", "grant_type"],
+ "msg": "Field required",
+ "input": None,
+ }
+ ]
+ }
@pytest.mark.parametrize(
@@ -157,31 +120,17 @@ def test_strict_login_incorrect_grant_type(grant_type: str):
data={"username": "johndoe", "password": "secret", "grant_type": grant_type},
)
assert response.status_code == 422
- assert response.json() == IsDict(
- {
- "detail": [
- {
- "type": "string_pattern_mismatch",
- "loc": ["body", "grant_type"],
- "msg": "String should match pattern '^password$'",
- "input": grant_type,
- "ctx": {"pattern": "^password$"},
- }
- ]
- }
- ) | IsDict(
- # TODO: remove when deprecating Pydantic v1
- {
- "detail": [
- {
- "loc": ["body", "grant_type"],
- "msg": 'string does not match regex "^password$"',
- "type": "value_error.str.regex",
- "ctx": {"pattern": "^password$"},
- }
- ]
- }
- )
+ assert response.json() == {
+ "detail": [
+ {
+ "type": "string_pattern_mismatch",
+ "loc": ["body", "grant_type"],
+ "msg": "String should match pattern '^password$'",
+ "input": grant_type,
+ "ctx": {"pattern": "^password$"},
+ }
+ ]
+ }
def test_strict_login_correct_correct_grant_type():
@@ -268,26 +217,14 @@ def test_openapi_schema():
"username": {"title": "Username", "type": "string"},
"password": {"title": "Password", "type": "string"},
"scope": {"title": "Scope", "type": "string", "default": ""},
- "client_id": IsDict(
- {
- "title": "Client Id",
- "anyOf": [{"type": "string"}, {"type": "null"}],
- }
- )
- | IsDict(
- # TODO: remove when deprecating Pydantic v1
- {"title": "Client Id", "type": "string"}
- ),
- "client_secret": IsDict(
- {
- "title": "Client Secret",
- "anyOf": [{"type": "string"}, {"type": "null"}],
- }
- )
- | IsDict(
- # TODO: remove when deprecating Pydantic v1
- {"title": "Client Secret", "type": "string"}
- ),
+ "client_id": {
+ "title": "Client Id",
+ "anyOf": [{"type": "string"}, {"type": "null"}],
+ },
+ "client_secret": {
+ "title": "Client Secret",
+ "anyOf": [{"type": "string"}, {"type": "null"}],
+ },
},
},
"ValidationError": {
diff --git a/tests/test_security_scopes.py b/tests/test_security_scopes.py
index 248fd2bcc2..fccb026fe2 100644
--- a/tests/test_security_scopes.py
+++ b/tests/test_security_scopes.py
@@ -1,9 +1,8 @@
-from typing import Dict
+from typing import Annotated
import pytest
from fastapi import Depends, FastAPI, Security
from fastapi.testclient import TestClient
-from typing_extensions import Annotated
@pytest.fixture(name="call_counter")
@@ -12,7 +11,7 @@ def call_counter_fixture():
@pytest.fixture(name="app")
-def app_fixture(call_counter: Dict[str, int]):
+def app_fixture(call_counter: dict[str, int]):
def get_db():
call_counter["count"] += 1
return f"db_{call_counter['count']}"
@@ -38,7 +37,7 @@ def client_fixture(app: FastAPI):
def test_security_scopes_dependency_called_once(
- client: TestClient, call_counter: Dict[str, int]
+ client: TestClient, call_counter: dict[str, int]
):
response = client.get("/")
diff --git a/tests/test_security_scopes_dont_propagate.py b/tests/test_security_scopes_dont_propagate.py
index 2bbcc749d3..c306ed0590 100644
--- a/tests/test_security_scopes_dont_propagate.py
+++ b/tests/test_security_scopes_dont_propagate.py
@@ -1,11 +1,10 @@
# Ref: https://github.com/tiangolo/fastapi/issues/5623
-from typing import Any, Dict, List
+from typing import Annotated, Any
from fastapi import FastAPI, Security
from fastapi.security import SecurityScopes
from fastapi.testclient import TestClient
-from typing_extensions import Annotated
async def security1(scopes: SecurityScopes):
@@ -17,8 +16,8 @@ async def security2(scopes: SecurityScopes):
async def dep3(
- dep1: Annotated[List[str], Security(security1, scopes=["scope1"])],
- dep2: Annotated[List[str], Security(security2, scopes=["scope2"])],
+ dep1: Annotated[list[str], Security(security1, scopes=["scope1"])],
+ dep2: Annotated[list[str], Security(security2, scopes=["scope2"])],
):
return {"dep1": dep1, "dep2": dep2}
@@ -28,7 +27,7 @@ app = FastAPI()
@app.get("/scopes")
def get_scopes(
- dep3: Annotated[Dict[str, Any], Security(dep3, scopes=["scope3"])],
+ dep3: Annotated[dict[str, Any], Security(dep3, scopes=["scope3"])],
):
return dep3
diff --git a/tests/test_security_scopes_sub_dependency.py b/tests/test_security_scopes_sub_dependency.py
index 9cc668d8e7..2c64d5f3d5 100644
--- a/tests/test_security_scopes_sub_dependency.py
+++ b/tests/test_security_scopes_sub_dependency.py
@@ -1,12 +1,12 @@
# Ref: https://github.com/fastapi/fastapi/discussions/6024#discussioncomment-8541913
-from typing import Dict
+
+from typing import Annotated
import pytest
from fastapi import Depends, FastAPI, Security
from fastapi.security import SecurityScopes
from fastapi.testclient import TestClient
-from typing_extensions import Annotated
@pytest.fixture(name="call_counts")
@@ -20,7 +20,7 @@ def call_counts_fixture():
@pytest.fixture(name="app")
-def app_fixture(call_counts: Dict[str, int]):
+def app_fixture(call_counts: dict[str, int]):
def get_db_session():
call_counts["get_db_session"] += 1
return f"db_session_{call_counts['get_db_session']}"
@@ -75,7 +75,7 @@ def client_fixture(app: FastAPI):
def test_security_scopes_sub_dependency_caching(
- client: TestClient, call_counts: Dict[str, int]
+ client: TestClient, call_counts: dict[str, int]
):
response = client.get("/")
diff --git a/tests/test_serialize_response.py b/tests/test_serialize_response.py
index d823e5e04a..14f88dd931 100644
--- a/tests/test_serialize_response.py
+++ b/tests/test_serialize_response.py
@@ -1,4 +1,4 @@
-from typing import List, Optional
+from typing import Optional
from fastapi import FastAPI
from fastapi.testclient import TestClient
@@ -10,7 +10,7 @@ app = FastAPI()
class Item(BaseModel):
name: str
price: Optional[float] = None
- owner_ids: Optional[List[int]] = None
+ owner_ids: Optional[list[int]] = None
@app.get("/items/valid", response_model=Item)
@@ -23,7 +23,7 @@ def get_coerce():
return {"name": "coerce", "price": "1.0"}
-@app.get("/items/validlist", response_model=List[Item])
+@app.get("/items/validlist", response_model=list[Item])
def get_validlist():
return [
{"name": "foo"},
diff --git a/tests/test_serialize_response_dataclass.py b/tests/test_serialize_response_dataclass.py
index 1e3bf3b28b..ee695368b8 100644
--- a/tests/test_serialize_response_dataclass.py
+++ b/tests/test_serialize_response_dataclass.py
@@ -1,6 +1,6 @@
from dataclasses import dataclass
from datetime import datetime
-from typing import List, Optional
+from typing import Optional
from fastapi import FastAPI
from fastapi.testclient import TestClient
@@ -13,7 +13,7 @@ class Item:
name: str
date: datetime
price: Optional[float] = None
- owner_ids: Optional[List[int]] = None
+ owner_ids: Optional[list[int]] = None
@app.get("/items/valid", response_model=Item)
@@ -33,7 +33,7 @@ def get_coerce():
return {"name": "coerce", "date": datetime(2021, 7, 26).isoformat(), "price": "1.0"}
-@app.get("/items/validlist", response_model=List[Item])
+@app.get("/items/validlist", response_model=list[Item])
def get_validlist():
return [
{"name": "foo", "date": datetime(2021, 7, 26)},
@@ -47,7 +47,7 @@ def get_validlist():
]
-@app.get("/items/objectlist", response_model=List[Item])
+@app.get("/items/objectlist", response_model=list[Item])
def get_objectlist():
return [
Item(name="foo", date=datetime(2021, 7, 26)),
diff --git a/tests/test_serialize_response_model.py b/tests/test_serialize_response_model.py
index 3bb46b2e9b..79c90c9c29 100644
--- a/tests/test_serialize_response_model.py
+++ b/tests/test_serialize_response_model.py
@@ -1,4 +1,4 @@
-from typing import Dict, List, Optional
+from typing import Optional
from fastapi import FastAPI
from pydantic import BaseModel, Field
@@ -10,7 +10,7 @@ app = FastAPI()
class Item(BaseModel):
name: str = Field(alias="aliased_name")
price: Optional[float] = None
- owner_ids: Optional[List[int]] = None
+ owner_ids: Optional[list[int]] = None
@app.get("/items/valid", response_model=Item)
@@ -23,7 +23,7 @@ def get_coerce():
return Item(aliased_name="coerce", price="1.0")
-@app.get("/items/validlist", response_model=List[Item])
+@app.get("/items/validlist", response_model=list[Item])
def get_validlist():
return [
Item(aliased_name="foo"),
@@ -32,7 +32,7 @@ def get_validlist():
]
-@app.get("/items/validdict", response_model=Dict[str, Item])
+@app.get("/items/validdict", response_model=dict[str, Item])
def get_validdict():
return {
"k1": Item(aliased_name="foo"),
@@ -59,7 +59,7 @@ def get_coerce_exclude_unset():
@app.get(
"/items/validlist-exclude-unset",
- response_model=List[Item],
+ response_model=list[Item],
response_model_exclude_unset=True,
)
def get_validlist_exclude_unset():
@@ -72,7 +72,7 @@ def get_validlist_exclude_unset():
@app.get(
"/items/validdict-exclude-unset",
- response_model=Dict[str, Item],
+ response_model=dict[str, Item],
response_model_exclude_unset=True,
)
def get_validdict_exclude_unset():
diff --git a/tests/test_stringified_annotation_dependency.py b/tests/test_stringified_annotation_dependency.py
index 89bb884b5c..ce88074957 100644
--- a/tests/test_stringified_annotation_dependency.py
+++ b/tests/test_stringified_annotation_dependency.py
@@ -1,12 +1,11 @@
from __future__ import annotations
-from typing import TYPE_CHECKING
+from typing import TYPE_CHECKING, Annotated
import pytest
from fastapi import Depends, FastAPI
from fastapi.testclient import TestClient
from inline_snapshot import snapshot
-from typing_extensions import Annotated
if TYPE_CHECKING: # pragma: no cover
from collections.abc import AsyncGenerator
diff --git a/tests/test_stringified_annotations_simple.py b/tests/test_stringified_annotations_simple.py
index 9bd6d09d63..6e037fb21f 100644
--- a/tests/test_stringified_annotations_simple.py
+++ b/tests/test_stringified_annotations_simple.py
@@ -1,8 +1,9 @@
from __future__ import annotations
+from typing import Annotated
+
from fastapi import Depends, FastAPI, Request
from fastapi.testclient import TestClient
-from typing_extensions import Annotated
from .utils import needs_py310
diff --git a/tests/test_sub_callbacks.py b/tests/test_sub_callbacks.py
index ed7f4efe8a..cc7e5f5c6a 100644
--- a/tests/test_sub_callbacks.py
+++ b/tests/test_sub_callbacks.py
@@ -1,6 +1,5 @@
from typing import Optional
-from dirty_equals import IsDict
from fastapi import APIRouter, FastAPI
from fastapi.testclient import TestClient
from pydantic import BaseModel, HttpUrl
@@ -99,30 +98,18 @@ def test_openapi_schema():
"parameters": [
{
"required": False,
- "schema": IsDict(
- {
- "title": "Callback Url",
- "anyOf": [
- {
- "type": "string",
- "format": "uri",
- "minLength": 1,
- "maxLength": 2083,
- },
- {"type": "null"},
- ],
- }
- )
- | IsDict(
- # TODO: remove when deprecating Pydantic v1
- {
- "title": "Callback Url",
- "maxLength": 2083,
- "minLength": 1,
- "type": "string",
- "format": "uri",
- }
- ),
+ "schema": {
+ "title": "Callback Url",
+ "anyOf": [
+ {
+ "type": "string",
+ "format": "uri",
+ "minLength": 1,
+ "maxLength": 2083,
+ },
+ {"type": "null"},
+ ],
+ },
"name": "callback_url",
"in": "query",
}
@@ -262,16 +249,10 @@ def test_openapi_schema():
"type": "object",
"properties": {
"id": {"title": "Id", "type": "string"},
- "title": IsDict(
- {
- "title": "Title",
- "anyOf": [{"type": "string"}, {"type": "null"}],
- }
- )
- | IsDict(
- # TODO: remove when deprecating Pydantic v1
- {"title": "Title", "type": "string"}
- ),
+ "title": {
+ "title": "Title",
+ "anyOf": [{"type": "string"}, {"type": "null"}],
+ },
"customer": {"title": "Customer", "type": "string"},
"total": {"title": "Total", "type": "number"},
},
diff --git a/tests/test_tuples.py b/tests/test_tuples.py
index ca33d2580c..d3c89045b4 100644
--- a/tests/test_tuples.py
+++ b/tests/test_tuples.py
@@ -1,6 +1,3 @@
-from typing import List, Tuple
-
-from dirty_equals import IsDict
from fastapi import FastAPI, Form
from fastapi.testclient import TestClient
from pydantic import BaseModel
@@ -9,7 +6,7 @@ app = FastAPI()
class ItemGroup(BaseModel):
- items: List[Tuple[str, str]]
+ items: list[tuple[str, str]]
class Coordinate(BaseModel):
@@ -23,12 +20,12 @@ def post_model_with_tuple(item_group: ItemGroup):
@app.post("/tuple-of-models/")
-def post_tuple_of_models(square: Tuple[Coordinate, Coordinate]):
+def post_tuple_of_models(square: tuple[Coordinate, Coordinate]):
return square
@app.post("/tuple-form/")
-def hello(values: Tuple[int, int] = Form()):
+def hello(values: tuple[int, int] = Form()):
return values
@@ -127,31 +124,16 @@ def test_openapi_schema():
"requestBody": {
"content": {
"application/json": {
- "schema": IsDict(
- {
- "title": "Square",
- "maxItems": 2,
- "minItems": 2,
- "type": "array",
- "prefixItems": [
- {"$ref": "#/components/schemas/Coordinate"},
- {"$ref": "#/components/schemas/Coordinate"},
- ],
- }
- )
- | IsDict(
- # TODO: remove when deprecating Pydantic v1
- {
- "title": "Square",
- "maxItems": 2,
- "minItems": 2,
- "type": "array",
- "items": [
- {"$ref": "#/components/schemas/Coordinate"},
- {"$ref": "#/components/schemas/Coordinate"},
- ],
- }
- )
+ "schema": {
+ "title": "Square",
+ "maxItems": 2,
+ "minItems": 2,
+ "type": "array",
+ "prefixItems": [
+ {"$ref": "#/components/schemas/Coordinate"},
+ {"$ref": "#/components/schemas/Coordinate"},
+ ],
+ }
}
},
"required": True,
@@ -214,28 +196,16 @@ def test_openapi_schema():
"required": ["values"],
"type": "object",
"properties": {
- "values": IsDict(
- {
- "title": "Values",
- "maxItems": 2,
- "minItems": 2,
- "type": "array",
- "prefixItems": [
- {"type": "integer"},
- {"type": "integer"},
- ],
- }
- )
- | IsDict(
- # TODO: remove when deprecating Pydantic v1
- {
- "title": "Values",
- "maxItems": 2,
- "minItems": 2,
- "type": "array",
- "items": [{"type": "integer"}, {"type": "integer"}],
- }
- )
+ "values": {
+ "title": "Values",
+ "maxItems": 2,
+ "minItems": 2,
+ "type": "array",
+ "prefixItems": [
+ {"type": "integer"},
+ {"type": "integer"},
+ ],
+ }
},
},
"Coordinate": {
@@ -266,26 +236,15 @@ def test_openapi_schema():
"items": {
"title": "Items",
"type": "array",
- "items": IsDict(
- {
- "maxItems": 2,
- "minItems": 2,
- "type": "array",
- "prefixItems": [
- {"type": "string"},
- {"type": "string"},
- ],
- }
- )
- | IsDict(
- # TODO: remove when deprecating Pydantic v1
- {
- "maxItems": 2,
- "minItems": 2,
- "type": "array",
- "items": [{"type": "string"}, {"type": "string"}],
- }
- ),
+ "items": {
+ "maxItems": 2,
+ "minItems": 2,
+ "type": "array",
+ "prefixItems": [
+ {"type": "string"},
+ {"type": "string"},
+ ],
+ },
}
},
},
diff --git a/tests/test_tutorial/test_additional_responses/test_tutorial001.py b/tests/test_tutorial/test_additional_responses/test_tutorial001.py
index 3afeaff840..1a18db75ce 100644
--- a/tests/test_tutorial/test_additional_responses/test_tutorial001.py
+++ b/tests/test_tutorial/test_additional_responses/test_tutorial001.py
@@ -1,6 +1,6 @@
from fastapi.testclient import TestClient
-from docs_src.additional_responses.tutorial001 import app
+from docs_src.additional_responses.tutorial001_py39 import app
client = TestClient(app)
diff --git a/tests/test_tutorial/test_additional_responses/test_tutorial002.py b/tests/test_tutorial/test_additional_responses/test_tutorial002.py
index 91d6ff101f..8208605956 100644
--- a/tests/test_tutorial/test_additional_responses/test_tutorial002.py
+++ b/tests/test_tutorial/test_additional_responses/test_tutorial002.py
@@ -3,7 +3,6 @@ import os
import shutil
import pytest
-from dirty_equals import IsDict
from fastapi.testclient import TestClient
from tests.utils import needs_py310
@@ -12,7 +11,7 @@ from tests.utils import needs_py310
@pytest.fixture(
name="client",
params=[
- pytest.param("tutorial002"),
+ pytest.param("tutorial002_py39"),
pytest.param("tutorial002_py310", marks=needs_py310),
],
)
@@ -80,16 +79,10 @@ def test_openapi_schema(client: TestClient):
},
{
"required": False,
- "schema": IsDict(
- {
- "anyOf": [{"type": "boolean"}, {"type": "null"}],
- "title": "Img",
- }
- )
- | IsDict(
- # TODO: remove when deprecating Pydantic v1
- {"title": "Img", "type": "boolean"}
- ),
+ "schema": {
+ "anyOf": [{"type": "boolean"}, {"type": "null"}],
+ "title": "Img",
+ },
"name": "img",
"in": "query",
},
diff --git a/tests/test_tutorial/test_additional_responses/test_tutorial003.py b/tests/test_tutorial/test_additional_responses/test_tutorial003.py
index bd34d2938c..90dc4e371e 100644
--- a/tests/test_tutorial/test_additional_responses/test_tutorial003.py
+++ b/tests/test_tutorial/test_additional_responses/test_tutorial003.py
@@ -1,6 +1,6 @@
from fastapi.testclient import TestClient
-from docs_src.additional_responses.tutorial003 import app
+from docs_src.additional_responses.tutorial003_py39 import app
client = TestClient(app)
diff --git a/tests/test_tutorial/test_additional_responses/test_tutorial004.py b/tests/test_tutorial/test_additional_responses/test_tutorial004.py
index 2d9491467e..c6abf5e466 100644
--- a/tests/test_tutorial/test_additional_responses/test_tutorial004.py
+++ b/tests/test_tutorial/test_additional_responses/test_tutorial004.py
@@ -3,7 +3,6 @@ import os
import shutil
import pytest
-from dirty_equals import IsDict
from fastapi.testclient import TestClient
from tests.utils import needs_py310
@@ -12,7 +11,7 @@ from tests.utils import needs_py310
@pytest.fixture(
name="client",
params=[
- pytest.param("tutorial004"),
+ pytest.param("tutorial004_py39"),
pytest.param("tutorial004_py310", marks=needs_py310),
],
)
@@ -83,16 +82,10 @@ def test_openapi_schema(client: TestClient):
},
{
"required": False,
- "schema": IsDict(
- {
- "anyOf": [{"type": "boolean"}, {"type": "null"}],
- "title": "Img",
- }
- )
- | IsDict(
- # TODO: remove when deprecating Pydantic v1
- {"title": "Img", "type": "boolean"}
- ),
+ "schema": {
+ "anyOf": [{"type": "boolean"}, {"type": "null"}],
+ "title": "Img",
+ },
"name": "img",
"in": "query",
},
diff --git a/tests/test_tutorial/test_additional_status_codes/test_tutorial001.py b/tests/test_tutorial/test_additional_status_codes/test_tutorial001.py
index b304f70153..bced1f6dfe 100644
--- a/tests/test_tutorial/test_additional_status_codes/test_tutorial001.py
+++ b/tests/test_tutorial/test_additional_status_codes/test_tutorial001.py
@@ -3,16 +3,15 @@ import importlib
import pytest
from fastapi.testclient import TestClient
-from ...utils import needs_py39, needs_py310
+from ...utils import needs_py310
@pytest.fixture(
name="client",
params=[
- "tutorial001",
+ "tutorial001_py39",
pytest.param("tutorial001_py310", marks=needs_py310),
- "tutorial001_an",
- pytest.param("tutorial001_an_py39", marks=needs_py39),
+ "tutorial001_an_py39",
pytest.param("tutorial001_an_py310", marks=needs_py310),
],
)
diff --git a/tests/test_tutorial/test_advanced_middleware/test_tutorial001.py b/tests/test_tutorial/test_advanced_middleware/test_tutorial001.py
index 157fa5caf1..f17391956e 100644
--- a/tests/test_tutorial/test_advanced_middleware/test_tutorial001.py
+++ b/tests/test_tutorial/test_advanced_middleware/test_tutorial001.py
@@ -1,6 +1,6 @@
from fastapi.testclient import TestClient
-from docs_src.advanced_middleware.tutorial001 import app
+from docs_src.advanced_middleware.tutorial001_py39 import app
def test_middleware():
diff --git a/tests/test_tutorial/test_advanced_middleware/test_tutorial002.py b/tests/test_tutorial/test_advanced_middleware/test_tutorial002.py
index 79be52f4db..bae915406e 100644
--- a/tests/test_tutorial/test_advanced_middleware/test_tutorial002.py
+++ b/tests/test_tutorial/test_advanced_middleware/test_tutorial002.py
@@ -1,6 +1,6 @@
from fastapi.testclient import TestClient
-from docs_src.advanced_middleware.tutorial002 import app
+from docs_src.advanced_middleware.tutorial002_py39 import app
def test_middleware():
diff --git a/tests/test_tutorial/test_advanced_middleware/test_tutorial003.py b/tests/test_tutorial/test_advanced_middleware/test_tutorial003.py
index 04a922ff7b..66697997c8 100644
--- a/tests/test_tutorial/test_advanced_middleware/test_tutorial003.py
+++ b/tests/test_tutorial/test_advanced_middleware/test_tutorial003.py
@@ -1,7 +1,7 @@
from fastapi.responses import PlainTextResponse
from fastapi.testclient import TestClient
-from docs_src.advanced_middleware.tutorial003 import app
+from docs_src.advanced_middleware.tutorial003_py39 import app
@app.get("/large")
diff --git a/tests/test_tutorial/test_async_tests/test_main.py b/tests/test_tutorial/test_async_tests/test_main_a.py
similarity index 58%
rename from tests/test_tutorial/test_async_tests/test_main.py
rename to tests/test_tutorial/test_async_tests/test_main_a.py
index 1f5d7186cc..f29acaa9a0 100644
--- a/tests/test_tutorial/test_async_tests/test_main.py
+++ b/tests/test_tutorial/test_async_tests/test_main_a.py
@@ -1,6 +1,6 @@
import pytest
-from docs_src.async_tests.test_main import test_root
+from docs_src.async_tests.app_a_py39.test_main import test_root
@pytest.mark.anyio
diff --git a/tests/test_tutorial/test_authentication_error_status_code/test_tutorial001.py b/tests/test_tutorial/test_authentication_error_status_code/test_tutorial001.py
index bbd7bff30f..6f58116313 100644
--- a/tests/test_tutorial/test_authentication_error_status_code/test_tutorial001.py
+++ b/tests/test_tutorial/test_authentication_error_status_code/test_tutorial001.py
@@ -4,14 +4,11 @@ import pytest
from fastapi.testclient import TestClient
from inline_snapshot import snapshot
-from ...utils import needs_py39
-
@pytest.fixture(
name="client",
params=[
- "tutorial001_an",
- pytest.param("tutorial001_an_py39", marks=needs_py39),
+ "tutorial001_an_py39",
],
)
def get_client(request: pytest.FixtureRequest):
diff --git a/tests/test_tutorial/test_background_tasks/test_tutorial001.py b/tests/test_tutorial/test_background_tasks/test_tutorial001.py
index 0602cd8aa4..c0ad27a6f5 100644
--- a/tests/test_tutorial/test_background_tasks/test_tutorial001.py
+++ b/tests/test_tutorial/test_background_tasks/test_tutorial001.py
@@ -3,7 +3,7 @@ from pathlib import Path
from fastapi.testclient import TestClient
-from docs_src.background_tasks.tutorial001 import app
+from docs_src.background_tasks.tutorial001_py39 import app
client = TestClient(app)
diff --git a/tests/test_tutorial/test_background_tasks/test_tutorial002.py b/tests/test_tutorial/test_background_tasks/test_tutorial002.py
index d5ef51ee2b..288a1c244e 100644
--- a/tests/test_tutorial/test_background_tasks/test_tutorial002.py
+++ b/tests/test_tutorial/test_background_tasks/test_tutorial002.py
@@ -5,16 +5,15 @@ from pathlib import Path
import pytest
from fastapi.testclient import TestClient
-from ...utils import needs_py39, needs_py310
+from ...utils import needs_py310
@pytest.fixture(
name="client",
params=[
- "tutorial002",
+ "tutorial002_py39",
pytest.param("tutorial002_py310", marks=needs_py310),
- "tutorial002_an",
- pytest.param("tutorial002_an_py39", marks=needs_py39),
+ "tutorial002_an_py39",
pytest.param("tutorial002_an_py310", marks=needs_py310),
],
)
diff --git a/tests/test_tutorial/test_behind_a_proxy/test_tutorial001.py b/tests/test_tutorial/test_behind_a_proxy/test_tutorial001.py
index a070f850f7..00574b5b0f 100644
--- a/tests/test_tutorial/test_behind_a_proxy/test_tutorial001.py
+++ b/tests/test_tutorial/test_behind_a_proxy/test_tutorial001.py
@@ -1,6 +1,6 @@
from fastapi.testclient import TestClient
-from docs_src.behind_a_proxy.tutorial001 import app
+from docs_src.behind_a_proxy.tutorial001_py39 import app
client = TestClient(app, root_path="/api/v1")
diff --git a/tests/test_tutorial/test_behind_a_proxy/test_tutorial001_01.py b/tests/test_tutorial/test_behind_a_proxy/test_tutorial001_01.py
index f13046e018..da4acb28cc 100644
--- a/tests/test_tutorial/test_behind_a_proxy/test_tutorial001_01.py
+++ b/tests/test_tutorial/test_behind_a_proxy/test_tutorial001_01.py
@@ -1,6 +1,6 @@
from fastapi.testclient import TestClient
-from docs_src.behind_a_proxy.tutorial001_01 import app
+from docs_src.behind_a_proxy.tutorial001_01_py39 import app
client = TestClient(
app,
diff --git a/tests/test_tutorial/test_behind_a_proxy/test_tutorial002.py b/tests/test_tutorial/test_behind_a_proxy/test_tutorial002.py
index ce791e2157..1a49c0dfeb 100644
--- a/tests/test_tutorial/test_behind_a_proxy/test_tutorial002.py
+++ b/tests/test_tutorial/test_behind_a_proxy/test_tutorial002.py
@@ -1,6 +1,6 @@
from fastapi.testclient import TestClient
-from docs_src.behind_a_proxy.tutorial002 import app
+from docs_src.behind_a_proxy.tutorial002_py39 import app
client = TestClient(app)
diff --git a/tests/test_tutorial/test_behind_a_proxy/test_tutorial003.py b/tests/test_tutorial/test_behind_a_proxy/test_tutorial003.py
index ec17b41790..a164bb80b5 100644
--- a/tests/test_tutorial/test_behind_a_proxy/test_tutorial003.py
+++ b/tests/test_tutorial/test_behind_a_proxy/test_tutorial003.py
@@ -1,7 +1,7 @@
-from dirty_equals import IsOneOf
from fastapi.testclient import TestClient
+from inline_snapshot import snapshot
-from docs_src.behind_a_proxy.tutorial003 import app
+from docs_src.behind_a_proxy.tutorial003_py39 import app
client = TestClient(app)
@@ -15,40 +15,34 @@ def test_main():
def test_openapi_schema():
response = client.get("/openapi.json")
assert response.status_code == 200
- assert response.json() == {
- "openapi": "3.1.0",
- "info": {"title": "FastAPI", "version": "0.1.0"},
- "servers": [
- {"url": "/api/v1"},
- {
- "url": IsOneOf(
- "https://stag.example.com/",
- # TODO: remove when deprecating Pydantic v1
- "https://stag.example.com",
- ),
- "description": "Staging environment",
- },
- {
- "url": IsOneOf(
- "https://prod.example.com/",
- # TODO: remove when deprecating Pydantic v1
- "https://prod.example.com",
- ),
- "description": "Production environment",
- },
- ],
- "paths": {
- "/app": {
- "get": {
- "summary": "Read Main",
- "operationId": "read_main_app_get",
- "responses": {
- "200": {
- "description": "Successful Response",
- "content": {"application/json": {"schema": {}}},
- }
- },
+ assert response.json() == snapshot(
+ {
+ "openapi": "3.1.0",
+ "info": {"title": "FastAPI", "version": "0.1.0"},
+ "servers": [
+ {"url": "/api/v1"},
+ {
+ "url": "https://stag.example.com",
+ "description": "Staging environment",
+ },
+ {
+ "url": "https://prod.example.com",
+ "description": "Production environment",
+ },
+ ],
+ "paths": {
+ "/app": {
+ "get": {
+ "summary": "Read Main",
+ "operationId": "read_main_app_get",
+ "responses": {
+ "200": {
+ "description": "Successful Response",
+ "content": {"application/json": {"schema": {}}},
+ }
+ },
+ }
}
- }
- },
- }
+ },
+ }
+ )
diff --git a/tests/test_tutorial/test_behind_a_proxy/test_tutorial004.py b/tests/test_tutorial/test_behind_a_proxy/test_tutorial004.py
index 2f8eb46995..01bba9fedd 100644
--- a/tests/test_tutorial/test_behind_a_proxy/test_tutorial004.py
+++ b/tests/test_tutorial/test_behind_a_proxy/test_tutorial004.py
@@ -1,7 +1,7 @@
-from dirty_equals import IsOneOf
from fastapi.testclient import TestClient
+from inline_snapshot import snapshot
-from docs_src.behind_a_proxy.tutorial004 import app
+from docs_src.behind_a_proxy.tutorial004_py39 import app
client = TestClient(app)
@@ -15,39 +15,33 @@ def test_main():
def test_openapi_schema():
response = client.get("/openapi.json")
assert response.status_code == 200
- assert response.json() == {
- "openapi": "3.1.0",
- "info": {"title": "FastAPI", "version": "0.1.0"},
- "servers": [
- {
- "url": IsOneOf(
- "https://stag.example.com/",
- # TODO: remove when deprecating Pydantic v1
- "https://stag.example.com",
- ),
- "description": "Staging environment",
- },
- {
- "url": IsOneOf(
- "https://prod.example.com/",
- # TODO: remove when deprecating Pydantic v1
- "https://prod.example.com",
- ),
- "description": "Production environment",
- },
- ],
- "paths": {
- "/app": {
- "get": {
- "summary": "Read Main",
- "operationId": "read_main_app_get",
- "responses": {
- "200": {
- "description": "Successful Response",
- "content": {"application/json": {"schema": {}}},
- }
- },
+ assert response.json() == snapshot(
+ {
+ "openapi": "3.1.0",
+ "info": {"title": "FastAPI", "version": "0.1.0"},
+ "servers": [
+ {
+ "url": "https://stag.example.com",
+ "description": "Staging environment",
+ },
+ {
+ "url": "https://prod.example.com",
+ "description": "Production environment",
+ },
+ ],
+ "paths": {
+ "/app": {
+ "get": {
+ "summary": "Read Main",
+ "operationId": "read_main_app_get",
+ "responses": {
+ "200": {
+ "description": "Successful Response",
+ "content": {"application/json": {"schema": {}}},
+ }
+ },
+ }
}
- }
- },
- }
+ },
+ }
+ )
diff --git a/tests/test_tutorial/test_bigger_applications/test_main.py b/tests/test_tutorial/test_bigger_applications/test_main.py
index fe40fad7d0..f5e243b95a 100644
--- a/tests/test_tutorial/test_bigger_applications/test_main.py
+++ b/tests/test_tutorial/test_bigger_applications/test_main.py
@@ -1,18 +1,14 @@
import importlib
import pytest
-from dirty_equals import IsDict
from fastapi.testclient import TestClient
-from ...utils import needs_py39
-
@pytest.fixture(
name="client",
params=[
- "app_an.main",
- pytest.param("app_an_py39.main", marks=needs_py39),
- "app.main",
+ "app_py39.main",
+ "app_an_py39.main",
],
)
def get_client(request: pytest.FixtureRequest):
@@ -31,29 +27,16 @@ def test_users_token_jessica(client: TestClient):
def test_users_with_no_token(client: TestClient):
response = client.get("/users")
assert response.status_code == 422
- assert response.json() == IsDict(
- {
- "detail": [
- {
- "type": "missing",
- "loc": ["query", "token"],
- "msg": "Field required",
- "input": None,
- }
- ]
- }
- ) | IsDict(
- # TODO: remove when deprecating Pydantic v1
- {
- "detail": [
- {
- "loc": ["query", "token"],
- "msg": "field required",
- "type": "value_error.missing",
- },
- ]
- }
- )
+ assert response.json() == {
+ "detail": [
+ {
+ "type": "missing",
+ "loc": ["query", "token"],
+ "msg": "Field required",
+ "input": None,
+ }
+ ]
+ }
def test_users_foo_token_jessica(client: TestClient):
@@ -65,29 +48,16 @@ def test_users_foo_token_jessica(client: TestClient):
def test_users_foo_with_no_token(client: TestClient):
response = client.get("/users/foo")
assert response.status_code == 422
- assert response.json() == IsDict(
- {
- "detail": [
- {
- "type": "missing",
- "loc": ["query", "token"],
- "msg": "Field required",
- "input": None,
- }
- ]
- }
- ) | IsDict(
- # TODO: remove when deprecating Pydantic v1
- {
- "detail": [
- {
- "loc": ["query", "token"],
- "msg": "field required",
- "type": "value_error.missing",
- },
- ]
- }
- )
+ assert response.json() == {
+ "detail": [
+ {
+ "type": "missing",
+ "loc": ["query", "token"],
+ "msg": "Field required",
+ "input": None,
+ }
+ ]
+ }
def test_users_me_token_jessica(client: TestClient):
@@ -99,29 +69,16 @@ def test_users_me_token_jessica(client: TestClient):
def test_users_me_with_no_token(client: TestClient):
response = client.get("/users/me")
assert response.status_code == 422
- assert response.json() == IsDict(
- {
- "detail": [
- {
- "type": "missing",
- "loc": ["query", "token"],
- "msg": "Field required",
- "input": None,
- }
- ]
- }
- ) | IsDict(
- # TODO: remove when deprecating Pydantic v1
- {
- "detail": [
- {
- "loc": ["query", "token"],
- "msg": "field required",
- "type": "value_error.missing",
- },
- ]
- }
- )
+ assert response.json() == {
+ "detail": [
+ {
+ "type": "missing",
+ "loc": ["query", "token"],
+ "msg": "Field required",
+ "input": None,
+ }
+ ]
+ }
def test_users_token_monica_with_no_jessica(client: TestClient):
@@ -144,29 +101,16 @@ def test_items_token_jessica(client: TestClient):
def test_items_with_no_token_jessica(client: TestClient):
response = client.get("/items", headers={"X-Token": "fake-super-secret-token"})
assert response.status_code == 422
- assert response.json() == IsDict(
- {
- "detail": [
- {
- "type": "missing",
- "loc": ["query", "token"],
- "msg": "Field required",
- "input": None,
- }
- ]
- }
- ) | IsDict(
- # TODO: remove when deprecating Pydantic v1
- {
- "detail": [
- {
- "loc": ["query", "token"],
- "msg": "field required",
- "type": "value_error.missing",
- },
- ]
- }
- )
+ assert response.json() == {
+ "detail": [
+ {
+ "type": "missing",
+ "loc": ["query", "token"],
+ "msg": "Field required",
+ "input": None,
+ }
+ ]
+ }
def test_items_plumbus_token_jessica(client: TestClient):
@@ -190,29 +134,16 @@ def test_items_plumbus_with_no_token(client: TestClient):
"/items/plumbus", headers={"X-Token": "fake-super-secret-token"}
)
assert response.status_code == 422
- assert response.json() == IsDict(
- {
- "detail": [
- {
- "type": "missing",
- "loc": ["query", "token"],
- "msg": "Field required",
- "input": None,
- }
- ]
- }
- ) | IsDict(
- # TODO: remove when deprecating Pydantic v1
- {
- "detail": [
- {
- "loc": ["query", "token"],
- "msg": "field required",
- "type": "value_error.missing",
- },
- ]
- }
- )
+ assert response.json() == {
+ "detail": [
+ {
+ "type": "missing",
+ "loc": ["query", "token"],
+ "msg": "Field required",
+ "input": None,
+ }
+ ]
+ }
def test_items_with_invalid_token(client: TestClient):
@@ -230,57 +161,31 @@ def test_items_bar_with_invalid_token(client: TestClient):
def test_items_with_missing_x_token_header(client: TestClient):
response = client.get("/items?token=jessica")
assert response.status_code == 422
- assert response.json() == IsDict(
- {
- "detail": [
- {
- "type": "missing",
- "loc": ["header", "x-token"],
- "msg": "Field required",
- "input": None,
- }
- ]
- }
- ) | IsDict(
- # TODO: remove when deprecating Pydantic v1
- {
- "detail": [
- {
- "loc": ["header", "x-token"],
- "msg": "field required",
- "type": "value_error.missing",
- }
- ]
- }
- )
+ assert response.json() == {
+ "detail": [
+ {
+ "type": "missing",
+ "loc": ["header", "x-token"],
+ "msg": "Field required",
+ "input": None,
+ }
+ ]
+ }
def test_items_plumbus_with_missing_x_token_header(client: TestClient):
response = client.get("/items/plumbus?token=jessica")
assert response.status_code == 422
- assert response.json() == IsDict(
- {
- "detail": [
- {
- "type": "missing",
- "loc": ["header", "x-token"],
- "msg": "Field required",
- "input": None,
- }
- ]
- }
- ) | IsDict(
- # TODO: remove when deprecating Pydantic v1
- {
- "detail": [
- {
- "loc": ["header", "x-token"],
- "msg": "field required",
- "type": "value_error.missing",
- }
- ]
- }
- )
+ assert response.json() == {
+ "detail": [
+ {
+ "type": "missing",
+ "loc": ["header", "x-token"],
+ "msg": "Field required",
+ "input": None,
+ }
+ ]
+ }
def test_root_token_jessica(client: TestClient):
@@ -292,68 +197,37 @@ def test_root_token_jessica(client: TestClient):
def test_root_with_no_token(client: TestClient):
response = client.get("/")
assert response.status_code == 422
- assert response.json() == IsDict(
- {
- "detail": [
- {
- "type": "missing",
- "loc": ["query", "token"],
- "msg": "Field required",
- "input": None,
- }
- ]
- }
- ) | IsDict(
- # TODO: remove when deprecating Pydantic v1
- {
- "detail": [
- {
- "loc": ["query", "token"],
- "msg": "field required",
- "type": "value_error.missing",
- },
- ]
- }
- )
+ assert response.json() == {
+ "detail": [
+ {
+ "type": "missing",
+ "loc": ["query", "token"],
+ "msg": "Field required",
+ "input": None,
+ }
+ ]
+ }
def test_put_no_header(client: TestClient):
response = client.put("/items/foo")
assert response.status_code == 422, response.text
- assert response.json() == IsDict(
- {
- "detail": [
- {
- "type": "missing",
- "loc": ["query", "token"],
- "msg": "Field required",
- "input": None,
- },
- {
- "type": "missing",
- "loc": ["header", "x-token"],
- "msg": "Field required",
- "input": None,
- },
- ]
- }
- ) | IsDict(
- # TODO: remove when deprecating Pydantic v1
- {
- "detail": [
- {
- "loc": ["query", "token"],
- "msg": "field required",
- "type": "value_error.missing",
- },
- {
- "loc": ["header", "x-token"],
- "msg": "field required",
- "type": "value_error.missing",
- },
- ]
- }
- )
+ assert response.json() == {
+ "detail": [
+ {
+ "type": "missing",
+ "loc": ["query", "token"],
+ "msg": "Field required",
+ "input": None,
+ },
+ {
+ "type": "missing",
+ "loc": ["header", "x-token"],
+ "msg": "Field required",
+ "input": None,
+ },
+ ]
+ }
def test_put_invalid_header(client: TestClient):
diff --git a/tests/test_tutorial/test_body/test_tutorial001.py b/tests/test_tutorial/test_body/test_tutorial001.py
index f8b5aee8d2..5a7cae1603 100644
--- a/tests/test_tutorial/test_body/test_tutorial001.py
+++ b/tests/test_tutorial/test_body/test_tutorial001.py
@@ -2,7 +2,6 @@ import importlib
from unittest.mock import patch
import pytest
-from dirty_equals import IsDict
from fastapi.testclient import TestClient
from ...utils import needs_py310
@@ -11,7 +10,7 @@ from ...utils import needs_py310
@pytest.fixture(
name="client",
params=[
- "tutorial001",
+ "tutorial001_py39",
pytest.param("tutorial001_py310", marks=needs_py310),
],
)
@@ -74,124 +73,67 @@ def test_post_with_str_float_description_tax(client: TestClient):
def test_post_with_only_name(client: TestClient):
response = client.post("/items/", json={"name": "Foo"})
assert response.status_code == 422
- assert response.json() == IsDict(
- {
- "detail": [
- {
- "type": "missing",
- "loc": ["body", "price"],
- "msg": "Field required",
- "input": {"name": "Foo"},
- }
- ]
- }
- ) | IsDict(
- # TODO: remove when deprecating Pydantic v1
- {
- "detail": [
- {
- "loc": ["body", "price"],
- "msg": "field required",
- "type": "value_error.missing",
- }
- ]
- }
- )
+ assert response.json() == {
+ "detail": [
+ {
+ "type": "missing",
+ "loc": ["body", "price"],
+ "msg": "Field required",
+ "input": {"name": "Foo"},
+ }
+ ]
+ }
def test_post_with_only_name_price(client: TestClient):
response = client.post("/items/", json={"name": "Foo", "price": "twenty"})
assert response.status_code == 422
- assert response.json() == IsDict(
- {
- "detail": [
- {
- "type": "float_parsing",
- "loc": ["body", "price"],
- "msg": "Input should be a valid number, unable to parse string as a number",
- "input": "twenty",
- }
- ]
- }
- ) | IsDict(
- # TODO: remove when deprecating Pydantic v1
- {
- "detail": [
- {
- "loc": ["body", "price"],
- "msg": "value is not a valid float",
- "type": "type_error.float",
- }
- ]
- }
- )
+ assert response.json() == {
+ "detail": [
+ {
+ "type": "float_parsing",
+ "loc": ["body", "price"],
+ "msg": "Input should be a valid number, unable to parse string as a number",
+ "input": "twenty",
+ }
+ ]
+ }
def test_post_with_no_data(client: TestClient):
response = client.post("/items/", json={})
assert response.status_code == 422
- assert response.json() == IsDict(
- {
- "detail": [
- {
- "type": "missing",
- "loc": ["body", "name"],
- "msg": "Field required",
- "input": {},
- },
- {
- "type": "missing",
- "loc": ["body", "price"],
- "msg": "Field required",
- "input": {},
- },
- ]
- }
- ) | IsDict(
- # TODO: remove when deprecating Pydantic v1
- {
- "detail": [
- {
- "loc": ["body", "name"],
- "msg": "field required",
- "type": "value_error.missing",
- },
- {
- "loc": ["body", "price"],
- "msg": "field required",
- "type": "value_error.missing",
- },
- ]
- }
- )
+ assert response.json() == {
+ "detail": [
+ {
+ "type": "missing",
+ "loc": ["body", "name"],
+ "msg": "Field required",
+ "input": {},
+ },
+ {
+ "type": "missing",
+ "loc": ["body", "price"],
+ "msg": "Field required",
+ "input": {},
+ },
+ ]
+ }
def test_post_with_none(client: TestClient):
response = client.post("/items/", json=None)
assert response.status_code == 422
- assert response.json() == IsDict(
- {
- "detail": [
- {
- "type": "missing",
- "loc": ["body"],
- "msg": "Field required",
- "input": None,
- }
- ]
- }
- ) | IsDict(
- # TODO: remove when deprecating Pydantic v1
- {
- "detail": [
- {
- "loc": ["body"],
- "msg": "field required",
- "type": "value_error.missing",
- }
- ]
- }
- )
+ assert response.json() == {
+ "detail": [
+ {
+ "type": "missing",
+ "loc": ["body"],
+ "msg": "Field required",
+ "input": None,
+ }
+ ]
+ }
def test_post_broken_body(client: TestClient):
@@ -201,67 +143,32 @@ def test_post_broken_body(client: TestClient):
content="{some broken json}",
)
assert response.status_code == 422, response.text
- assert response.json() == IsDict(
- {
- "detail": [
- {
- "type": "json_invalid",
- "loc": ["body", 1],
- "msg": "JSON decode error",
- "input": {},
- "ctx": {
- "error": "Expecting property name enclosed in double quotes"
- },
- }
- ]
- }
- ) | IsDict(
- # TODO: remove when deprecating Pydantic v1
- {
- "detail": [
- {
- "loc": ["body", 1],
- "msg": "Expecting property name enclosed in double quotes: line 1 column 2 (char 1)",
- "type": "value_error.jsondecode",
- "ctx": {
- "msg": "Expecting property name enclosed in double quotes",
- "doc": "{some broken json}",
- "pos": 1,
- "lineno": 1,
- "colno": 2,
- },
- }
- ]
- }
- )
+ assert response.json() == {
+ "detail": [
+ {
+ "type": "json_invalid",
+ "loc": ["body", 1],
+ "msg": "JSON decode error",
+ "input": {},
+ "ctx": {"error": "Expecting property name enclosed in double quotes"},
+ }
+ ]
+ }
def test_post_form_for_json(client: TestClient):
response = client.post("/items/", data={"name": "Foo", "price": 50.5})
assert response.status_code == 422, response.text
- assert response.json() == IsDict(
- {
- "detail": [
- {
- "type": "model_attributes_type",
- "loc": ["body"],
- "msg": "Input should be a valid dictionary or object to extract fields from",
- "input": "name=Foo&price=50.5",
- }
- ]
- }
- ) | IsDict(
- # TODO: remove when deprecating Pydantic v1
- {
- "detail": [
- {
- "loc": ["body"],
- "msg": "value is not a valid dict",
- "type": "type_error.dict",
- }
- ]
- }
- )
+ assert response.json() == {
+ "detail": [
+ {
+ "type": "model_attributes_type",
+ "loc": ["body"],
+ "msg": "Input should be a valid dictionary or object to extract fields from",
+ "input": "name=Foo&price=50.5",
+ }
+ ]
+ }
def test_explicit_content_type(client: TestClient):
@@ -302,84 +209,46 @@ def test_wrong_headers(client: TestClient):
"/items/", content=data, headers={"Content-Type": "text/plain"}
)
assert response.status_code == 422, response.text
- assert response.json() == IsDict(
- {
- "detail": [
- {
- "type": "model_attributes_type",
- "loc": ["body"],
- "msg": "Input should be a valid dictionary or object to extract fields from",
- "input": '{"name": "Foo", "price": 50.5}',
- }
- ]
- }
- ) | IsDict(
- # TODO: remove when deprecating Pydantic v1
- {
- "detail": [
- {
- "loc": ["body"],
- "msg": "value is not a valid dict",
- "type": "type_error.dict",
- }
- ]
- }
- )
+ assert response.json() == {
+ "detail": [
+ {
+ "type": "model_attributes_type",
+ "loc": ["body"],
+ "msg": "Input should be a valid dictionary or object to extract fields from",
+ "input": '{"name": "Foo", "price": 50.5}',
+ }
+ ]
+ }
response = client.post(
"/items/", content=data, headers={"Content-Type": "application/geo+json-seq"}
)
assert response.status_code == 422, response.text
- assert response.json() == IsDict(
- {
- "detail": [
- {
- "type": "model_attributes_type",
- "loc": ["body"],
- "msg": "Input should be a valid dictionary or object to extract fields from",
- "input": '{"name": "Foo", "price": 50.5}',
- }
- ]
- }
- ) | IsDict(
- # TODO: remove when deprecating Pydantic v1
- {
- "detail": [
- {
- "loc": ["body"],
- "msg": "value is not a valid dict",
- "type": "type_error.dict",
- }
- ]
- }
- )
+ assert response.json() == {
+ "detail": [
+ {
+ "type": "model_attributes_type",
+ "loc": ["body"],
+ "msg": "Input should be a valid dictionary or object to extract fields from",
+ "input": '{"name": "Foo", "price": 50.5}',
+ }
+ ]
+ }
+
response = client.post(
"/items/", content=data, headers={"Content-Type": "application/not-really-json"}
)
assert response.status_code == 422, response.text
- assert response.json() == IsDict(
- {
- "detail": [
- {
- "type": "model_attributes_type",
- "loc": ["body"],
- "msg": "Input should be a valid dictionary or object to extract fields from",
- "input": '{"name": "Foo", "price": 50.5}',
- }
- ]
- }
- ) | IsDict(
- # TODO: remove when deprecating Pydantic v1
- {
- "detail": [
- {
- "loc": ["body"],
- "msg": "value is not a valid dict",
- "type": "type_error.dict",
- }
- ]
- }
- )
+ assert response.json() == {
+ "detail": [
+ {
+ "type": "model_attributes_type",
+ "loc": ["body"],
+ "msg": "Input should be a valid dictionary or object to extract fields from",
+ "input": '{"name": "Foo", "price": 50.5}',
+ }
+ ]
+ }
def test_other_exceptions(client: TestClient):
@@ -435,26 +304,14 @@ def test_openapi_schema(client: TestClient):
"properties": {
"name": {"title": "Name", "type": "string"},
"price": {"title": "Price", "type": "number"},
- "description": IsDict(
- {
- "title": "Description",
- "anyOf": [{"type": "string"}, {"type": "null"}],
- }
- )
- | IsDict(
- # TODO: remove when deprecating Pydantic v1
- {"title": "Description", "type": "string"}
- ),
- "tax": IsDict(
- {
- "title": "Tax",
- "anyOf": [{"type": "number"}, {"type": "null"}],
- }
- )
- | IsDict(
- # TODO: remove when deprecating Pydantic v1
- {"title": "Tax", "type": "number"}
- ),
+ "description": {
+ "title": "Description",
+ "anyOf": [{"type": "string"}, {"type": "null"}],
+ },
+ "tax": {
+ "title": "Tax",
+ "anyOf": [{"type": "number"}, {"type": "null"}],
+ },
},
},
"ValidationError": {
diff --git a/tests/test_tutorial/test_body/test_tutorial002.py b/tests/test_tutorial/test_body/test_tutorial002.py
new file mode 100644
index 0000000000..b6d51d5235
--- /dev/null
+++ b/tests/test_tutorial/test_body/test_tutorial002.py
@@ -0,0 +1,161 @@
+import importlib
+from typing import Union
+
+import pytest
+from fastapi.testclient import TestClient
+
+from ...utils import needs_py310
+
+
+@pytest.fixture(
+ name="client",
+ params=[
+ pytest.param("tutorial002_py39"),
+ pytest.param("tutorial002_py310", marks=needs_py310),
+ ],
+)
+def get_client(request: pytest.FixtureRequest):
+ mod = importlib.import_module(f"docs_src.body.{request.param}")
+
+ client = TestClient(mod.app)
+ return client
+
+
+@pytest.mark.parametrize("price", ["50.5", 50.5])
+def test_post_with_tax(client: TestClient, price: Union[str, float]):
+ response = client.post(
+ "/items/",
+ json={"name": "Foo", "price": price, "description": "Some Foo", "tax": 0.3},
+ )
+ assert response.status_code == 200
+ assert response.json() == {
+ "name": "Foo",
+ "price": 50.5,
+ "description": "Some Foo",
+ "tax": 0.3,
+ "price_with_tax": 50.8,
+ }
+
+
+@pytest.mark.parametrize("price", ["50.5", 50.5])
+def test_post_without_tax(client: TestClient, price: Union[str, float]):
+ response = client.post(
+ "/items/", json={"name": "Foo", "price": price, "description": "Some Foo"}
+ )
+ assert response.status_code == 200
+ assert response.json() == {
+ "name": "Foo",
+ "price": 50.5,
+ "description": "Some Foo",
+ "tax": None,
+ }
+
+
+def test_post_with_no_data(client: TestClient):
+ response = client.post("/items/", json={})
+ assert response.status_code == 422
+ assert response.json() == {
+ "detail": [
+ {
+ "type": "missing",
+ "loc": ["body", "name"],
+ "msg": "Field required",
+ "input": {},
+ },
+ {
+ "type": "missing",
+ "loc": ["body", "price"],
+ "msg": "Field required",
+ "input": {},
+ },
+ ]
+ }
+
+
+def test_openapi_schema(client: TestClient):
+ response = client.get("/openapi.json")
+ assert response.status_code == 200, response.text
+ assert response.json() == {
+ "openapi": "3.1.0",
+ "info": {"title": "FastAPI", "version": "0.1.0"},
+ "paths": {
+ "/items/": {
+ "post": {
+ "responses": {
+ "200": {
+ "description": "Successful Response",
+ "content": {"application/json": {"schema": {}}},
+ },
+ "422": {
+ "description": "Validation Error",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/HTTPValidationError"
+ }
+ }
+ },
+ },
+ },
+ "summary": "Create Item",
+ "operationId": "create_item_items__post",
+ "requestBody": {
+ "content": {
+ "application/json": {
+ "schema": {"$ref": "#/components/schemas/Item"}
+ }
+ },
+ "required": True,
+ },
+ }
+ }
+ },
+ "components": {
+ "schemas": {
+ "Item": {
+ "title": "Item",
+ "required": ["name", "price"],
+ "type": "object",
+ "properties": {
+ "name": {"title": "Name", "type": "string"},
+ "price": {"title": "Price", "type": "number"},
+ "description": {
+ "title": "Description",
+ "anyOf": [{"type": "string"}, {"type": "null"}],
+ },
+ "tax": {
+ "title": "Tax",
+ "anyOf": [{"type": "number"}, {"type": "null"}],
+ },
+ },
+ },
+ "ValidationError": {
+ "title": "ValidationError",
+ "required": ["loc", "msg", "type"],
+ "type": "object",
+ "properties": {
+ "loc": {
+ "title": "Location",
+ "type": "array",
+ "items": {
+ "anyOf": [{"type": "string"}, {"type": "integer"}]
+ },
+ },
+ "msg": {"title": "Message", "type": "string"},
+ "type": {"title": "Error Type", "type": "string"},
+ },
+ },
+ "HTTPValidationError": {
+ "title": "HTTPValidationError",
+ "type": "object",
+ "properties": {
+ "detail": {
+ "title": "Detail",
+ "type": "array",
+ "items": {"$ref": "#/components/schemas/ValidationError"},
+ }
+ },
+ },
+ }
+ },
+ }
diff --git a/tests/test_tutorial/test_body/test_tutorial003.py b/tests/test_tutorial/test_body/test_tutorial003.py
new file mode 100644
index 0000000000..227a125e78
--- /dev/null
+++ b/tests/test_tutorial/test_body/test_tutorial003.py
@@ -0,0 +1,171 @@
+import importlib
+
+import pytest
+from fastapi.testclient import TestClient
+
+from ...utils import needs_py310
+
+
+@pytest.fixture(
+ name="client",
+ params=[
+ pytest.param("tutorial003_py39"),
+ pytest.param("tutorial003_py310", marks=needs_py310),
+ ],
+)
+def get_client(request: pytest.FixtureRequest):
+ mod = importlib.import_module(f"docs_src.body.{request.param}")
+
+ client = TestClient(mod.app)
+ return client
+
+
+def test_put_all(client: TestClient):
+ response = client.put(
+ "/items/123",
+ json={"name": "Foo", "price": 50.1, "description": "Some Foo", "tax": 0.3},
+ )
+ assert response.status_code == 200
+ assert response.json() == {
+ "item_id": 123,
+ "name": "Foo",
+ "price": 50.1,
+ "description": "Some Foo",
+ "tax": 0.3,
+ }
+
+
+def test_put_only_required(client: TestClient):
+ response = client.put(
+ "/items/123",
+ json={"name": "Foo", "price": 50.1},
+ )
+ assert response.status_code == 200
+ assert response.json() == {
+ "item_id": 123,
+ "name": "Foo",
+ "price": 50.1,
+ "description": None,
+ "tax": None,
+ }
+
+
+def test_put_with_no_data(client: TestClient):
+ response = client.put("/items/123", json={})
+ assert response.status_code == 422
+ assert response.json() == {
+ "detail": [
+ {
+ "type": "missing",
+ "loc": ["body", "name"],
+ "msg": "Field required",
+ "input": {},
+ },
+ {
+ "type": "missing",
+ "loc": ["body", "price"],
+ "msg": "Field required",
+ "input": {},
+ },
+ ]
+ }
+
+
+def test_openapi_schema(client: TestClient):
+ response = client.get("/openapi.json")
+ assert response.status_code == 200, response.text
+ assert response.json() == {
+ "openapi": "3.1.0",
+ "info": {"title": "FastAPI", "version": "0.1.0"},
+ "paths": {
+ "/items/{item_id}": {
+ "put": {
+ "parameters": [
+ {
+ "in": "path",
+ "name": "item_id",
+ "required": True,
+ "schema": {
+ "title": "Item Id",
+ "type": "integer",
+ },
+ },
+ ],
+ "responses": {
+ "200": {
+ "description": "Successful Response",
+ "content": {"application/json": {"schema": {}}},
+ },
+ "422": {
+ "description": "Validation Error",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/HTTPValidationError"
+ }
+ }
+ },
+ },
+ },
+ "summary": "Update Item",
+ "operationId": "update_item_items__item_id__put",
+ "requestBody": {
+ "content": {
+ "application/json": {
+ "schema": {"$ref": "#/components/schemas/Item"}
+ }
+ },
+ "required": True,
+ },
+ }
+ }
+ },
+ "components": {
+ "schemas": {
+ "Item": {
+ "title": "Item",
+ "required": ["name", "price"],
+ "type": "object",
+ "properties": {
+ "name": {"title": "Name", "type": "string"},
+ "price": {"title": "Price", "type": "number"},
+ "description": {
+ "title": "Description",
+ "anyOf": [{"type": "string"}, {"type": "null"}],
+ },
+ "tax": {
+ "title": "Tax",
+ "anyOf": [{"type": "number"}, {"type": "null"}],
+ },
+ },
+ },
+ "ValidationError": {
+ "title": "ValidationError",
+ "required": ["loc", "msg", "type"],
+ "type": "object",
+ "properties": {
+ "loc": {
+ "title": "Location",
+ "type": "array",
+ "items": {
+ "anyOf": [{"type": "string"}, {"type": "integer"}]
+ },
+ },
+ "msg": {"title": "Message", "type": "string"},
+ "type": {"title": "Error Type", "type": "string"},
+ },
+ },
+ "HTTPValidationError": {
+ "title": "HTTPValidationError",
+ "type": "object",
+ "properties": {
+ "detail": {
+ "title": "Detail",
+ "type": "array",
+ "items": {"$ref": "#/components/schemas/ValidationError"},
+ }
+ },
+ },
+ }
+ },
+ }
diff --git a/tests/test_tutorial/test_body/test_tutorial004.py b/tests/test_tutorial/test_body/test_tutorial004.py
new file mode 100644
index 0000000000..10212843ee
--- /dev/null
+++ b/tests/test_tutorial/test_body/test_tutorial004.py
@@ -0,0 +1,182 @@
+import importlib
+
+import pytest
+from fastapi.testclient import TestClient
+
+from ...utils import needs_py310
+
+
+@pytest.fixture(
+ name="client",
+ params=[
+ pytest.param("tutorial004_py39"),
+ pytest.param("tutorial004_py310", marks=needs_py310),
+ ],
+)
+def get_client(request: pytest.FixtureRequest):
+ mod = importlib.import_module(f"docs_src.body.{request.param}")
+
+ client = TestClient(mod.app)
+ return client
+
+
+def test_put_all(client: TestClient):
+ response = client.put(
+ "/items/123",
+ json={"name": "Foo", "price": 50.1, "description": "Some Foo", "tax": 0.3},
+ params={"q": "somequery"},
+ )
+ assert response.status_code == 200
+ assert response.json() == {
+ "item_id": 123,
+ "name": "Foo",
+ "price": 50.1,
+ "description": "Some Foo",
+ "tax": 0.3,
+ "q": "somequery",
+ }
+
+
+def test_put_only_required(client: TestClient):
+ response = client.put(
+ "/items/123",
+ json={"name": "Foo", "price": 50.1},
+ )
+ assert response.status_code == 200
+ assert response.json() == {
+ "item_id": 123,
+ "name": "Foo",
+ "price": 50.1,
+ "description": None,
+ "tax": None,
+ }
+
+
+def test_put_with_no_data(client: TestClient):
+ response = client.put("/items/123", json={})
+ assert response.status_code == 422
+ assert response.json() == {
+ "detail": [
+ {
+ "type": "missing",
+ "loc": ["body", "name"],
+ "msg": "Field required",
+ "input": {},
+ },
+ {
+ "type": "missing",
+ "loc": ["body", "price"],
+ "msg": "Field required",
+ "input": {},
+ },
+ ]
+ }
+
+
+def test_openapi_schema(client: TestClient):
+ response = client.get("/openapi.json")
+ assert response.status_code == 200, response.text
+ assert response.json() == {
+ "openapi": "3.1.0",
+ "info": {"title": "FastAPI", "version": "0.1.0"},
+ "paths": {
+ "/items/{item_id}": {
+ "put": {
+ "parameters": [
+ {
+ "in": "path",
+ "name": "item_id",
+ "required": True,
+ "schema": {
+ "title": "Item Id",
+ "type": "integer",
+ },
+ },
+ {
+ "required": False,
+ "schema": {
+ "anyOf": [{"type": "string"}, {"type": "null"}],
+ "title": "Q",
+ },
+ "name": "q",
+ "in": "query",
+ },
+ ],
+ "responses": {
+ "200": {
+ "description": "Successful Response",
+ "content": {"application/json": {"schema": {}}},
+ },
+ "422": {
+ "description": "Validation Error",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/HTTPValidationError"
+ }
+ }
+ },
+ },
+ },
+ "summary": "Update Item",
+ "operationId": "update_item_items__item_id__put",
+ "requestBody": {
+ "content": {
+ "application/json": {
+ "schema": {"$ref": "#/components/schemas/Item"}
+ }
+ },
+ "required": True,
+ },
+ }
+ }
+ },
+ "components": {
+ "schemas": {
+ "Item": {
+ "title": "Item",
+ "required": ["name", "price"],
+ "type": "object",
+ "properties": {
+ "name": {"title": "Name", "type": "string"},
+ "price": {"title": "Price", "type": "number"},
+ "description": {
+ "title": "Description",
+ "anyOf": [{"type": "string"}, {"type": "null"}],
+ },
+ "tax": {
+ "title": "Tax",
+ "anyOf": [{"type": "number"}, {"type": "null"}],
+ },
+ },
+ },
+ "ValidationError": {
+ "title": "ValidationError",
+ "required": ["loc", "msg", "type"],
+ "type": "object",
+ "properties": {
+ "loc": {
+ "title": "Location",
+ "type": "array",
+ "items": {
+ "anyOf": [{"type": "string"}, {"type": "integer"}]
+ },
+ },
+ "msg": {"title": "Message", "type": "string"},
+ "type": {"title": "Error Type", "type": "string"},
+ },
+ },
+ "HTTPValidationError": {
+ "title": "HTTPValidationError",
+ "type": "object",
+ "properties": {
+ "detail": {
+ "title": "Detail",
+ "type": "array",
+ "items": {"$ref": "#/components/schemas/ValidationError"},
+ }
+ },
+ },
+ }
+ },
+ }
diff --git a/tests/test_tutorial/test_body_fields/test_tutorial001.py b/tests/test_tutorial/test_body_fields/test_tutorial001.py
index fb68f28689..0ecadbb660 100644
--- a/tests/test_tutorial/test_body_fields/test_tutorial001.py
+++ b/tests/test_tutorial/test_body_fields/test_tutorial001.py
@@ -1,19 +1,17 @@
import importlib
import pytest
-from dirty_equals import IsDict
from fastapi.testclient import TestClient
-from ...utils import needs_py39, needs_py310
+from ...utils import needs_py310
@pytest.fixture(
name="client",
params=[
- "tutorial001",
+ "tutorial001_py39",
pytest.param("tutorial001_py310", marks=needs_py310),
- "tutorial001_an",
- pytest.param("tutorial001_an_py39", marks=needs_py39),
+ "tutorial001_an_py39",
pytest.param("tutorial001_an_py310", marks=needs_py310),
],
)
@@ -60,31 +58,17 @@ def test_items_6(client: TestClient):
def test_invalid_price(client: TestClient):
response = client.put("/items/5", json={"item": {"name": "Foo", "price": -3.0}})
assert response.status_code == 422
- assert response.json() == IsDict(
- {
- "detail": [
- {
- "type": "greater_than",
- "loc": ["body", "item", "price"],
- "msg": "Input should be greater than 0",
- "input": -3.0,
- "ctx": {"gt": 0.0},
- }
- ]
- }
- ) | IsDict(
- # TODO: remove when deprecating Pydantic v1
- {
- "detail": [
- {
- "ctx": {"limit_value": 0},
- "loc": ["body", "item", "price"],
- "msg": "ensure this value is greater than 0",
- "type": "value_error.number.not_gt",
- }
- ]
- }
- )
+ assert response.json() == {
+ "detail": [
+ {
+ "type": "greater_than",
+ "loc": ["body", "item", "price"],
+ "msg": "Input should be greater than 0",
+ "input": -3.0,
+ "ctx": {"gt": 0.0},
+ }
+ ]
+ }
def test_openapi_schema(client: TestClient):
@@ -143,39 +127,23 @@ def test_openapi_schema(client: TestClient):
"type": "object",
"properties": {
"name": {"title": "Name", "type": "string"},
- "description": IsDict(
- {
- "title": "The description of the item",
- "anyOf": [
- {"maxLength": 300, "type": "string"},
- {"type": "null"},
- ],
- }
- )
- | IsDict(
- # TODO: remove when deprecating Pydantic v1
- {
- "title": "The description of the item",
- "maxLength": 300,
- "type": "string",
- }
- ),
+ "description": {
+ "title": "The description of the item",
+ "anyOf": [
+ {"maxLength": 300, "type": "string"},
+ {"type": "null"},
+ ],
+ },
"price": {
"title": "Price",
"exclusiveMinimum": 0.0,
"type": "number",
"description": "The price must be greater than zero",
},
- "tax": IsDict(
- {
- "title": "Tax",
- "anyOf": [{"type": "number"}, {"type": "null"}],
- }
- )
- | IsDict(
- # TODO: remove when deprecating Pydantic v1
- {"title": "Tax", "type": "number"}
- ),
+ "tax": {
+ "title": "Tax",
+ "anyOf": [{"type": "number"}, {"type": "null"}],
+ },
},
},
"Body_update_item_items__item_id__put": {
diff --git a/tests/test_tutorial/test_body_multiple_params/test_tutorial001.py b/tests/test_tutorial/test_body_multiple_params/test_tutorial001.py
index 1424055952..63c9c16d62 100644
--- a/tests/test_tutorial/test_body_multiple_params/test_tutorial001.py
+++ b/tests/test_tutorial/test_body_multiple_params/test_tutorial001.py
@@ -1,19 +1,17 @@
import importlib
import pytest
-from dirty_equals import IsDict
from fastapi.testclient import TestClient
-from ...utils import needs_py39, needs_py310
+from ...utils import needs_py310
@pytest.fixture(
name="client",
params=[
- "tutorial001",
+ "tutorial001_py39",
pytest.param("tutorial001_py310", marks=needs_py310),
- "tutorial001_an",
- pytest.param("tutorial001_an_py39", marks=needs_py39),
+ "tutorial001_an_py39",
pytest.param("tutorial001_an_py310", marks=needs_py310),
],
)
@@ -54,29 +52,16 @@ def test_post_no_body(client: TestClient):
def test_post_id_foo(client: TestClient):
response = client.put("/items/foo", json=None)
assert response.status_code == 422
- assert response.json() == IsDict(
- {
- "detail": [
- {
- "type": "int_parsing",
- "loc": ["path", "item_id"],
- "msg": "Input should be a valid integer, unable to parse string as an integer",
- "input": "foo",
- }
- ]
- }
- ) | IsDict(
- # TODO: remove when deprecating Pydantic v1
- {
- "detail": [
- {
- "loc": ["path", "item_id"],
- "msg": "value is not a valid integer",
- "type": "type_error.integer",
- }
- ]
- }
- )
+ assert response.json() == {
+ "detail": [
+ {
+ "type": "int_parsing",
+ "loc": ["path", "item_id"],
+ "msg": "Input should be a valid integer, unable to parse string as an integer",
+ "input": "foo",
+ }
+ ]
+ }
def test_openapi_schema(client: TestClient):
@@ -120,16 +105,10 @@ def test_openapi_schema(client: TestClient):
},
{
"required": False,
- "schema": IsDict(
- {
- "anyOf": [{"type": "string"}, {"type": "null"}],
- "title": "Q",
- }
- )
- | IsDict(
- # TODO: remove when deprecating Pydantic v1
- {"title": "Q", "type": "string"}
- ),
+ "schema": {
+ "anyOf": [{"type": "string"}, {"type": "null"}],
+ "title": "Q",
+ },
"name": "q",
"in": "query",
},
@@ -137,19 +116,13 @@ def test_openapi_schema(client: TestClient):
"requestBody": {
"content": {
"application/json": {
- "schema": IsDict(
- {
- "anyOf": [
- {"$ref": "#/components/schemas/Item"},
- {"type": "null"},
- ],
- "title": "Item",
- }
- )
- | IsDict(
- # TODO: remove when deprecating Pydantic v1
- {"$ref": "#/components/schemas/Item"}
- )
+ "schema": {
+ "anyOf": [
+ {"$ref": "#/components/schemas/Item"},
+ {"type": "null"},
+ ],
+ "title": "Item",
+ }
}
}
},
@@ -164,27 +137,15 @@ def test_openapi_schema(client: TestClient):
"type": "object",
"properties": {
"name": {"title": "Name", "type": "string"},
- "description": IsDict(
- {
- "title": "Description",
- "anyOf": [{"type": "string"}, {"type": "null"}],
- }
- )
- | IsDict(
- # TODO: remove when deprecating Pydantic v1
- {"title": "Description", "type": "string"}
- ),
+ "description": {
+ "title": "Description",
+ "anyOf": [{"type": "string"}, {"type": "null"}],
+ },
"price": {"title": "Price", "type": "number"},
- "tax": IsDict(
- {
- "title": "Tax",
- "anyOf": [{"type": "number"}, {"type": "null"}],
- }
- )
- | IsDict(
- # TODO: remove when deprecating Pydantic v1
- {"title": "Tax", "type": "number"}
- ),
+ "tax": {
+ "title": "Tax",
+ "anyOf": [{"type": "number"}, {"type": "null"}],
+ },
},
},
"ValidationError": {
diff --git a/tests/test_tutorial/test_body_multiple_params/test_tutorial002.py b/tests/test_tutorial/test_body_multiple_params/test_tutorial002.py
new file mode 100644
index 0000000000..e98d5860fe
--- /dev/null
+++ b/tests/test_tutorial/test_body_multiple_params/test_tutorial002.py
@@ -0,0 +1,361 @@
+import importlib
+
+import pytest
+from fastapi.testclient import TestClient
+
+from ...utils import needs_py310
+
+
+@pytest.fixture(
+ name="client",
+ params=[
+ pytest.param("tutorial002_py39"),
+ pytest.param("tutorial002_py310", marks=needs_py310),
+ ],
+)
+def get_client(request: pytest.FixtureRequest):
+ mod = importlib.import_module(f"docs_src.body_multiple_params.{request.param}")
+
+ client = TestClient(mod.app)
+ return client
+
+
+def test_post_all(client: TestClient):
+ response = client.put(
+ "/items/5",
+ json={
+ "item": {
+ "name": "Foo",
+ "price": 50.5,
+ "description": "Some Foo",
+ "tax": 0.1,
+ },
+ "user": {"username": "johndoe", "full_name": "John Doe"},
+ },
+ )
+ assert response.status_code == 200
+ assert response.json() == {
+ "item_id": 5,
+ "item": {
+ "name": "Foo",
+ "price": 50.5,
+ "description": "Some Foo",
+ "tax": 0.1,
+ },
+ "user": {"username": "johndoe", "full_name": "John Doe"},
+ }
+
+
+def test_post_required(client: TestClient):
+ response = client.put(
+ "/items/5",
+ json={
+ "item": {"name": "Foo", "price": 50.5},
+ "user": {"username": "johndoe"},
+ },
+ )
+ assert response.status_code == 200
+ assert response.json() == {
+ "item_id": 5,
+ "item": {
+ "name": "Foo",
+ "price": 50.5,
+ "description": None,
+ "tax": None,
+ },
+ "user": {"username": "johndoe", "full_name": None},
+ }
+
+
+def test_post_no_body(client: TestClient):
+ response = client.put("/items/5", json=None)
+ assert response.status_code == 422
+ assert response.json() == {
+ "detail": [
+ {
+ "input": None,
+ "loc": [
+ "body",
+ "item",
+ ],
+ "msg": "Field required",
+ "type": "missing",
+ },
+ {
+ "input": None,
+ "loc": [
+ "body",
+ "user",
+ ],
+ "msg": "Field required",
+ "type": "missing",
+ },
+ ],
+ }
+
+
+def test_post_no_item(client: TestClient):
+ response = client.put("/items/5", json={"user": {"username": "johndoe"}})
+ assert response.status_code == 422
+ assert response.json() == {
+ "detail": [
+ {
+ "input": None,
+ "loc": [
+ "body",
+ "item",
+ ],
+ "msg": "Field required",
+ "type": "missing",
+ },
+ ],
+ }
+
+
+def test_post_no_user(client: TestClient):
+ response = client.put("/items/5", json={"item": {"name": "Foo", "price": 50.5}})
+ assert response.status_code == 422
+ assert response.json() == {
+ "detail": [
+ {
+ "input": None,
+ "loc": [
+ "body",
+ "user",
+ ],
+ "msg": "Field required",
+ "type": "missing",
+ },
+ ],
+ }
+
+
+def test_post_missing_required_field_in_item(client: TestClient):
+ response = client.put(
+ "/items/5", json={"item": {"name": "Foo"}, "user": {"username": "johndoe"}}
+ )
+ assert response.status_code == 422
+ assert response.json() == {
+ "detail": [
+ {
+ "input": {"name": "Foo"},
+ "loc": [
+ "body",
+ "item",
+ "price",
+ ],
+ "msg": "Field required",
+ "type": "missing",
+ },
+ ],
+ }
+
+
+def test_post_missing_required_field_in_user(client: TestClient):
+ response = client.put(
+ "/items/5",
+ json={"item": {"name": "Foo", "price": 50.5}, "user": {"ful_name": "John Doe"}},
+ )
+ assert response.status_code == 422
+ assert response.json() == {
+ "detail": [
+ {
+ "input": {"ful_name": "John Doe"},
+ "loc": [
+ "body",
+ "user",
+ "username",
+ ],
+ "msg": "Field required",
+ "type": "missing",
+ },
+ ],
+ }
+
+
+def test_post_id_foo(client: TestClient):
+ response = client.put(
+ "/items/foo",
+ json={
+ "item": {"name": "Foo", "price": 50.5},
+ "user": {"username": "johndoe"},
+ },
+ )
+ assert response.status_code == 422
+ assert response.json() == {
+ "detail": [
+ {
+ "type": "int_parsing",
+ "loc": ["path", "item_id"],
+ "msg": "Input should be a valid integer, unable to parse string as an integer",
+ "input": "foo",
+ }
+ ]
+ }
+
+
+def test_openapi_schema(client: TestClient):
+ 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": {
+ "/items/{item_id}": {
+ "put": {
+ "operationId": "update_item_items__item_id__put",
+ "parameters": [
+ {
+ "in": "path",
+ "name": "item_id",
+ "required": True,
+ "schema": {
+ "title": "Item Id",
+ "type": "integer",
+ },
+ },
+ ],
+ "requestBody": {
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/Body_update_item_items__item_id__put",
+ },
+ },
+ },
+ "required": True,
+ },
+ "responses": {
+ "200": {
+ "content": {
+ "application/json": {
+ "schema": {},
+ },
+ },
+ "description": "Successful Response",
+ },
+ "422": {
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/HTTPValidationError",
+ },
+ },
+ },
+ "description": "Validation Error",
+ },
+ },
+ "summary": "Update Item",
+ },
+ },
+ },
+ "components": {
+ "schemas": {
+ "Body_update_item_items__item_id__put": {
+ "properties": {
+ "item": {
+ "$ref": "#/components/schemas/Item",
+ },
+ "user": {
+ "$ref": "#/components/schemas/User",
+ },
+ },
+ "required": [
+ "item",
+ "user",
+ ],
+ "title": "Body_update_item_items__item_id__put",
+ "type": "object",
+ },
+ "HTTPValidationError": {
+ "properties": {
+ "detail": {
+ "items": {
+ "$ref": "#/components/schemas/ValidationError",
+ },
+ "title": "Detail",
+ "type": "array",
+ },
+ },
+ "title": "HTTPValidationError",
+ "type": "object",
+ },
+ "Item": {
+ "properties": {
+ "name": {
+ "title": "Name",
+ "type": "string",
+ },
+ "description": {
+ "title": "Description",
+ "anyOf": [{"type": "string"}, {"type": "null"}],
+ },
+ "price": {"title": "Price", "type": "number"},
+ "tax": {
+ "title": "Tax",
+ "anyOf": [{"type": "number"}, {"type": "null"}],
+ },
+ },
+ "required": [
+ "name",
+ "price",
+ ],
+ "title": "Item",
+ "type": "object",
+ },
+ "User": {
+ "properties": {
+ "username": {
+ "title": "Username",
+ "type": "string",
+ },
+ "full_name": {
+ "title": "Full Name",
+ "anyOf": [{"type": "string"}, {"type": "null"}],
+ },
+ },
+ "required": [
+ "username",
+ ],
+ "title": "User",
+ "type": "object",
+ },
+ "ValidationError": {
+ "properties": {
+ "loc": {
+ "items": {
+ "anyOf": [
+ {
+ "type": "string",
+ },
+ {
+ "type": "integer",
+ },
+ ],
+ },
+ "title": "Location",
+ "type": "array",
+ },
+ "msg": {
+ "title": "Message",
+ "type": "string",
+ },
+ "type": {
+ "title": "Error Type",
+ "type": "string",
+ },
+ },
+ "required": [
+ "loc",
+ "msg",
+ "type",
+ ],
+ "title": "ValidationError",
+ "type": "object",
+ },
+ },
+ },
+ }
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 d18ceae486..76b7ff7099 100644
--- a/tests/test_tutorial/test_body_multiple_params/test_tutorial003.py
+++ b/tests/test_tutorial/test_body_multiple_params/test_tutorial003.py
@@ -1,19 +1,17 @@
import importlib
import pytest
-from dirty_equals import IsDict
from fastapi.testclient import TestClient
-from ...utils import needs_py39, needs_py310
+from ...utils import needs_py310
@pytest.fixture(
name="client",
params=[
- "tutorial003",
+ "tutorial003_py39",
pytest.param("tutorial003_py310", marks=needs_py310),
- "tutorial003_an",
- pytest.param("tutorial003_an_py39", marks=needs_py39),
+ "tutorial003_an_py39",
pytest.param("tutorial003_an_py310", marks=needs_py310),
],
)
@@ -50,101 +48,55 @@ def test_post_body_valid(client: TestClient):
def test_post_body_no_data(client: TestClient):
response = client.put("/items/5", json=None)
assert response.status_code == 422
- assert response.json() == IsDict(
- {
- "detail": [
- {
- "type": "missing",
- "loc": ["body", "item"],
- "msg": "Field required",
- "input": None,
- },
- {
- "type": "missing",
- "loc": ["body", "user"],
- "msg": "Field required",
- "input": None,
- },
- {
- "type": "missing",
- "loc": ["body", "importance"],
- "msg": "Field required",
- "input": None,
- },
- ]
- }
- ) | IsDict(
- # TODO: remove when deprecating Pydantic v1
- {
- "detail": [
- {
- "loc": ["body", "item"],
- "msg": "field required",
- "type": "value_error.missing",
- },
- {
- "loc": ["body", "user"],
- "msg": "field required",
- "type": "value_error.missing",
- },
- {
- "loc": ["body", "importance"],
- "msg": "field required",
- "type": "value_error.missing",
- },
- ]
- }
- )
+ assert response.json() == {
+ "detail": [
+ {
+ "type": "missing",
+ "loc": ["body", "item"],
+ "msg": "Field required",
+ "input": None,
+ },
+ {
+ "type": "missing",
+ "loc": ["body", "user"],
+ "msg": "Field required",
+ "input": None,
+ },
+ {
+ "type": "missing",
+ "loc": ["body", "importance"],
+ "msg": "Field required",
+ "input": None,
+ },
+ ]
+ }
def test_post_body_empty_list(client: TestClient):
response = client.put("/items/5", json=[])
assert response.status_code == 422
- assert response.json() == IsDict(
- {
- "detail": [
- {
- "type": "missing",
- "loc": ["body", "item"],
- "msg": "Field required",
- "input": None,
- },
- {
- "type": "missing",
- "loc": ["body", "user"],
- "msg": "Field required",
- "input": None,
- },
- {
- "type": "missing",
- "loc": ["body", "importance"],
- "msg": "Field required",
- "input": None,
- },
- ]
- }
- ) | IsDict(
- # TODO: remove when deprecating Pydantic v1
- {
- "detail": [
- {
- "loc": ["body", "item"],
- "msg": "field required",
- "type": "value_error.missing",
- },
- {
- "loc": ["body", "user"],
- "msg": "field required",
- "type": "value_error.missing",
- },
- {
- "loc": ["body", "importance"],
- "msg": "field required",
- "type": "value_error.missing",
- },
- ]
- }
- )
+ assert response.json() == {
+ "detail": [
+ {
+ "type": "missing",
+ "loc": ["body", "item"],
+ "msg": "Field required",
+ "input": None,
+ },
+ {
+ "type": "missing",
+ "loc": ["body", "user"],
+ "msg": "Field required",
+ "input": None,
+ },
+ {
+ "type": "missing",
+ "loc": ["body", "importance"],
+ "msg": "Field required",
+ "input": None,
+ },
+ ]
+ }
def test_openapi_schema(client: TestClient):
@@ -203,27 +155,15 @@ def test_openapi_schema(client: TestClient):
"type": "object",
"properties": {
"name": {"title": "Name", "type": "string"},
- "description": IsDict(
- {
- "title": "Description",
- "anyOf": [{"type": "string"}, {"type": "null"}],
- }
- )
- | IsDict(
- # TODO: remove when deprecating Pydantic v1
- {"title": "Description", "type": "string"}
- ),
+ "description": {
+ "title": "Description",
+ "anyOf": [{"type": "string"}, {"type": "null"}],
+ },
"price": {"title": "Price", "type": "number"},
- "tax": IsDict(
- {
- "title": "Tax",
- "anyOf": [{"type": "number"}, {"type": "null"}],
- }
- )
- | IsDict(
- # TODO: remove when deprecating Pydantic v1
- {"title": "Tax", "type": "number"}
- ),
+ "tax": {
+ "title": "Tax",
+ "anyOf": [{"type": "number"}, {"type": "null"}],
+ },
},
},
"User": {
@@ -232,16 +172,10 @@ def test_openapi_schema(client: TestClient):
"type": "object",
"properties": {
"username": {"title": "Username", "type": "string"},
- "full_name": IsDict(
- {
- "title": "Full Name",
- "anyOf": [{"type": "string"}, {"type": "null"}],
- }
- )
- | IsDict(
- # TODO: remove when deprecating Pydantic v1
- {"title": "Full Name", "type": "string"}
- ),
+ "full_name": {
+ "title": "Full Name",
+ "anyOf": [{"type": "string"}, {"type": "null"}],
+ },
},
},
"Body_update_item_items__item_id__put": {
diff --git a/tests/test_tutorial/test_body_multiple_params/test_tutorial004.py b/tests/test_tutorial/test_body_multiple_params/test_tutorial004.py
new file mode 100644
index 0000000000..979c054cd0
--- /dev/null
+++ b/tests/test_tutorial/test_body_multiple_params/test_tutorial004.py
@@ -0,0 +1,290 @@
+import importlib
+
+import pytest
+from fastapi.testclient import TestClient
+
+from ...utils import needs_py310
+
+
+@pytest.fixture(
+ name="client",
+ params=[
+ pytest.param("tutorial004_py39"),
+ pytest.param("tutorial004_py310", marks=needs_py310),
+ pytest.param("tutorial004_an_py39"),
+ pytest.param("tutorial004_an_py310", marks=needs_py310),
+ ],
+)
+def get_client(request: pytest.FixtureRequest):
+ mod = importlib.import_module(f"docs_src.body_multiple_params.{request.param}")
+
+ client = TestClient(mod.app)
+ return client
+
+
+def test_put_all(client: TestClient):
+ response = client.put(
+ "/items/5",
+ json={
+ "importance": 2,
+ "item": {"name": "Foo", "price": 50.5},
+ "user": {"username": "Dave"},
+ },
+ params={"q": "somequery"},
+ )
+ assert response.status_code == 200
+ assert response.json() == {
+ "item_id": 5,
+ "importance": 2,
+ "item": {
+ "name": "Foo",
+ "price": 50.5,
+ "description": None,
+ "tax": None,
+ },
+ "user": {"username": "Dave", "full_name": None},
+ "q": "somequery",
+ }
+
+
+def test_put_only_required(client: TestClient):
+ response = client.put(
+ "/items/5",
+ json={
+ "importance": 2,
+ "item": {"name": "Foo", "price": 50.5},
+ "user": {"username": "Dave"},
+ },
+ )
+ assert response.status_code == 200
+ assert response.json() == {
+ "item_id": 5,
+ "importance": 2,
+ "item": {
+ "name": "Foo",
+ "price": 50.5,
+ "description": None,
+ "tax": None,
+ },
+ "user": {"username": "Dave", "full_name": None},
+ }
+
+
+def test_put_missing_body(client: TestClient):
+ response = client.put("/items/5")
+ assert response.status_code == 422
+ assert response.json() == {
+ "detail": [
+ {
+ "input": None,
+ "loc": [
+ "body",
+ "item",
+ ],
+ "msg": "Field required",
+ "type": "missing",
+ },
+ {
+ "input": None,
+ "loc": [
+ "body",
+ "user",
+ ],
+ "msg": "Field required",
+ "type": "missing",
+ },
+ {
+ "input": None,
+ "loc": [
+ "body",
+ "importance",
+ ],
+ "msg": "Field required",
+ "type": "missing",
+ },
+ ],
+ }
+
+
+def test_put_empty_body(client: TestClient):
+ response = client.put("/items/5", json={})
+ assert response.status_code == 422
+ assert response.json() == {
+ "detail": [
+ {
+ "type": "missing",
+ "loc": ["body", "item"],
+ "msg": "Field required",
+ "input": None,
+ },
+ {
+ "type": "missing",
+ "loc": ["body", "user"],
+ "msg": "Field required",
+ "input": None,
+ },
+ {
+ "type": "missing",
+ "loc": ["body", "importance"],
+ "msg": "Field required",
+ "input": None,
+ },
+ ]
+ }
+
+
+def test_put_invalid_importance(client: TestClient):
+ response = client.put(
+ "/items/5",
+ json={
+ "importance": 0,
+ "item": {"name": "Foo", "price": 50.5},
+ "user": {"username": "Dave"},
+ },
+ )
+ assert response.status_code == 422
+ assert response.json() == {
+ "detail": [
+ {
+ "loc": ["body", "importance"],
+ "msg": "Input should be greater than 0",
+ "type": "greater_than",
+ "input": 0,
+ "ctx": {"gt": 0},
+ },
+ ],
+ }
+
+
+def test_openapi_schema(client: TestClient):
+ response = client.get("/openapi.json")
+ assert response.status_code == 200, response.text
+ assert response.json() == {
+ "openapi": "3.1.0",
+ "info": {"title": "FastAPI", "version": "0.1.0"},
+ "paths": {
+ "/items/{item_id}": {
+ "put": {
+ "responses": {
+ "200": {
+ "description": "Successful Response",
+ "content": {"application/json": {"schema": {}}},
+ },
+ "422": {
+ "description": "Validation Error",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/HTTPValidationError"
+ }
+ }
+ },
+ },
+ },
+ "summary": "Update Item",
+ "operationId": "update_item_items__item_id__put",
+ "parameters": [
+ {
+ "required": True,
+ "schema": {"title": "Item Id", "type": "integer"},
+ "name": "item_id",
+ "in": "path",
+ },
+ {
+ "required": False,
+ "schema": {
+ "anyOf": [{"type": "string"}, {"type": "null"}],
+ "title": "Q",
+ },
+ "name": "q",
+ "in": "query",
+ },
+ ],
+ "requestBody": {
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/Body_update_item_items__item_id__put"
+ }
+ }
+ },
+ "required": True,
+ },
+ }
+ }
+ },
+ "components": {
+ "schemas": {
+ "Item": {
+ "title": "Item",
+ "required": ["name", "price"],
+ "type": "object",
+ "properties": {
+ "name": {"title": "Name", "type": "string"},
+ "description": {
+ "title": "Description",
+ "anyOf": [{"type": "string"}, {"type": "null"}],
+ },
+ "price": {"title": "Price", "type": "number"},
+ "tax": {
+ "title": "Tax",
+ "anyOf": [{"type": "number"}, {"type": "null"}],
+ },
+ },
+ },
+ "User": {
+ "title": "User",
+ "required": ["username"],
+ "type": "object",
+ "properties": {
+ "username": {"title": "Username", "type": "string"},
+ "full_name": {
+ "title": "Full Name",
+ "anyOf": [{"type": "string"}, {"type": "null"}],
+ },
+ },
+ },
+ "Body_update_item_items__item_id__put": {
+ "title": "Body_update_item_items__item_id__put",
+ "required": ["item", "user", "importance"],
+ "type": "object",
+ "properties": {
+ "item": {"$ref": "#/components/schemas/Item"},
+ "user": {"$ref": "#/components/schemas/User"},
+ "importance": {
+ "title": "Importance",
+ "type": "integer",
+ "exclusiveMinimum": 0.0,
+ },
+ },
+ },
+ "ValidationError": {
+ "title": "ValidationError",
+ "required": ["loc", "msg", "type"],
+ "type": "object",
+ "properties": {
+ "loc": {
+ "title": "Location",
+ "type": "array",
+ "items": {
+ "anyOf": [{"type": "string"}, {"type": "integer"}]
+ },
+ },
+ "msg": {"title": "Message", "type": "string"},
+ "type": {"title": "Error Type", "type": "string"},
+ },
+ },
+ "HTTPValidationError": {
+ "title": "HTTPValidationError",
+ "type": "object",
+ "properties": {
+ "detail": {
+ "title": "Detail",
+ "type": "array",
+ "items": {"$ref": "#/components/schemas/ValidationError"},
+ }
+ },
+ },
+ }
+ },
+ }
diff --git a/tests/test_tutorial/test_body_multiple_params/test_tutorial005.py b/tests/test_tutorial/test_body_multiple_params/test_tutorial005.py
new file mode 100644
index 0000000000..d47aa1b4f9
--- /dev/null
+++ b/tests/test_tutorial/test_body_multiple_params/test_tutorial005.py
@@ -0,0 +1,272 @@
+import importlib
+
+import pytest
+from fastapi.testclient import TestClient
+
+from ...utils import needs_py310
+
+
+@pytest.fixture(
+ name="client",
+ params=[
+ pytest.param("tutorial005_py39"),
+ pytest.param("tutorial005_py310", marks=needs_py310),
+ pytest.param("tutorial005_an_py39"),
+ pytest.param("tutorial005_an_py310", marks=needs_py310),
+ ],
+)
+def get_client(request: pytest.FixtureRequest):
+ mod = importlib.import_module(f"docs_src.body_multiple_params.{request.param}")
+
+ client = TestClient(mod.app)
+ return client
+
+
+def test_post_all(client: TestClient):
+ response = client.put(
+ "/items/5",
+ json={
+ "item": {
+ "name": "Foo",
+ "price": 50.5,
+ "description": "Some Foo",
+ "tax": 0.1,
+ },
+ },
+ )
+ assert response.status_code == 200
+ assert response.json() == {
+ "item_id": 5,
+ "item": {
+ "name": "Foo",
+ "price": 50.5,
+ "description": "Some Foo",
+ "tax": 0.1,
+ },
+ }
+
+
+def test_post_required(client: TestClient):
+ response = client.put(
+ "/items/5",
+ json={
+ "item": {"name": "Foo", "price": 50.5},
+ },
+ )
+ assert response.status_code == 200
+ assert response.json() == {
+ "item_id": 5,
+ "item": {
+ "name": "Foo",
+ "price": 50.5,
+ "description": None,
+ "tax": None,
+ },
+ }
+
+
+def test_post_no_body(client: TestClient):
+ response = client.put("/items/5", json=None)
+ assert response.status_code == 422
+ assert response.json() == {
+ "detail": [
+ {
+ "input": None,
+ "loc": [
+ "body",
+ "item",
+ ],
+ "msg": "Field required",
+ "type": "missing",
+ },
+ ],
+ }
+
+
+def test_post_like_not_embeded(client: TestClient):
+ response = client.put(
+ "/items/5",
+ json={
+ "name": "Foo",
+ "price": 50.5,
+ },
+ )
+ assert response.status_code == 422
+ assert response.json() == {
+ "detail": [
+ {
+ "input": None,
+ "loc": [
+ "body",
+ "item",
+ ],
+ "msg": "Field required",
+ "type": "missing",
+ },
+ ],
+ }
+
+
+def test_post_missing_required_field_in_item(client: TestClient):
+ response = client.put(
+ "/items/5", json={"item": {"name": "Foo"}, "user": {"username": "johndoe"}}
+ )
+ assert response.status_code == 422
+ assert response.json() == {
+ "detail": [
+ {
+ "input": {"name": "Foo"},
+ "loc": [
+ "body",
+ "item",
+ "price",
+ ],
+ "msg": "Field required",
+ "type": "missing",
+ },
+ ],
+ }
+
+
+def test_openapi_schema(client: TestClient):
+ 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": {
+ "/items/{item_id}": {
+ "put": {
+ "operationId": "update_item_items__item_id__put",
+ "parameters": [
+ {
+ "in": "path",
+ "name": "item_id",
+ "required": True,
+ "schema": {
+ "title": "Item Id",
+ "type": "integer",
+ },
+ },
+ ],
+ "requestBody": {
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/Body_update_item_items__item_id__put",
+ },
+ },
+ },
+ "required": True,
+ },
+ "responses": {
+ "200": {
+ "content": {
+ "application/json": {
+ "schema": {},
+ },
+ },
+ "description": "Successful Response",
+ },
+ "422": {
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/HTTPValidationError",
+ },
+ },
+ },
+ "description": "Validation Error",
+ },
+ },
+ "summary": "Update Item",
+ },
+ },
+ },
+ "components": {
+ "schemas": {
+ "Body_update_item_items__item_id__put": {
+ "properties": {
+ "item": {
+ "$ref": "#/components/schemas/Item",
+ },
+ },
+ "required": ["item"],
+ "title": "Body_update_item_items__item_id__put",
+ "type": "object",
+ },
+ "HTTPValidationError": {
+ "properties": {
+ "detail": {
+ "items": {
+ "$ref": "#/components/schemas/ValidationError",
+ },
+ "title": "Detail",
+ "type": "array",
+ },
+ },
+ "title": "HTTPValidationError",
+ "type": "object",
+ },
+ "Item": {
+ "properties": {
+ "name": {
+ "title": "Name",
+ "type": "string",
+ },
+ "description": {
+ "title": "Description",
+ "anyOf": [{"type": "string"}, {"type": "null"}],
+ },
+ "price": {"title": "Price", "type": "number"},
+ "tax": {
+ "title": "Tax",
+ "anyOf": [{"type": "number"}, {"type": "null"}],
+ },
+ },
+ "required": [
+ "name",
+ "price",
+ ],
+ "title": "Item",
+ "type": "object",
+ },
+ "ValidationError": {
+ "properties": {
+ "loc": {
+ "items": {
+ "anyOf": [
+ {
+ "type": "string",
+ },
+ {
+ "type": "integer",
+ },
+ ],
+ },
+ "title": "Location",
+ "type": "array",
+ },
+ "msg": {
+ "title": "Message",
+ "type": "string",
+ },
+ "type": {
+ "title": "Error Type",
+ "type": "string",
+ },
+ },
+ "required": [
+ "loc",
+ "msg",
+ "type",
+ ],
+ "title": "ValidationError",
+ "type": "object",
+ },
+ },
+ },
+ }
diff --git a/tests/test_tutorial/test_body_nested_models/test_tutorial001_tutorial002_tutorial003.py b/tests/test_tutorial/test_body_nested_models/test_tutorial001_tutorial002_tutorial003.py
new file mode 100644
index 0000000000..d452929c38
--- /dev/null
+++ b/tests/test_tutorial/test_body_nested_models/test_tutorial001_tutorial002_tutorial003.py
@@ -0,0 +1,251 @@
+import importlib
+
+import pytest
+from dirty_equals import IsList
+from fastapi.testclient import TestClient
+
+from ...utils import needs_py310
+
+UNTYPED_LIST_SCHEMA = {"type": "array", "items": {}}
+
+LIST_OF_STR_SCHEMA = {"type": "array", "items": {"type": "string"}}
+
+SET_OF_STR_SCHEMA = {"type": "array", "items": {"type": "string"}, "uniqueItems": True}
+
+
+@pytest.fixture(
+ name="mod_name",
+ params=[
+ pytest.param("tutorial001_py39"),
+ pytest.param("tutorial001_py310", marks=needs_py310),
+ pytest.param("tutorial002_py39"),
+ pytest.param("tutorial002_py310", marks=needs_py310),
+ pytest.param("tutorial003_py39"),
+ pytest.param("tutorial003_py310", marks=needs_py310),
+ ],
+)
+def get_mod_name(request: pytest.FixtureRequest):
+ return request.param
+
+
+@pytest.fixture(name="client")
+def get_client(mod_name: str):
+ mod = importlib.import_module(f"docs_src.body_nested_models.{mod_name}")
+
+ client = TestClient(mod.app)
+ return client
+
+
+def test_put_all(client: TestClient, mod_name: str):
+ if mod_name.startswith("tutorial003"):
+ tags_expected = IsList("foo", "bar", check_order=False)
+ else:
+ tags_expected = ["foo", "bar", "foo"]
+
+ response = client.put(
+ "/items/123",
+ json={
+ "name": "Foo",
+ "description": "A very nice Item",
+ "price": 35.4,
+ "tax": 3.2,
+ "tags": ["foo", "bar", "foo"],
+ },
+ )
+ assert response.status_code == 200, response.text
+ assert response.json() == {
+ "item_id": 123,
+ "item": {
+ "name": "Foo",
+ "description": "A very nice Item",
+ "price": 35.4,
+ "tax": 3.2,
+ "tags": tags_expected,
+ },
+ }
+
+
+def test_put_only_required(client: TestClient):
+ response = client.put(
+ "/items/5",
+ json={"name": "Foo", "price": 35.4},
+ )
+ assert response.status_code == 200, response.text
+ assert response.json() == {
+ "item_id": 5,
+ "item": {
+ "name": "Foo",
+ "description": None,
+ "price": 35.4,
+ "tax": None,
+ "tags": [],
+ },
+ }
+
+
+def test_put_empty_body(client: TestClient):
+ response = client.put(
+ "/items/5",
+ json={},
+ )
+ assert response.status_code == 422, response.text
+ assert response.json() == {
+ "detail": [
+ {
+ "loc": ["body", "name"],
+ "input": {},
+ "msg": "Field required",
+ "type": "missing",
+ },
+ {
+ "loc": ["body", "price"],
+ "input": {},
+ "msg": "Field required",
+ "type": "missing",
+ },
+ ]
+ }
+
+
+def test_put_missing_required(client: TestClient):
+ response = client.put(
+ "/items/5",
+ json={"description": "A very nice Item"},
+ )
+ assert response.status_code == 422, response.text
+ assert response.json() == {
+ "detail": [
+ {
+ "loc": ["body", "name"],
+ "input": {"description": "A very nice Item"},
+ "msg": "Field required",
+ "type": "missing",
+ },
+ {
+ "loc": ["body", "price"],
+ "input": {"description": "A very nice Item"},
+ "msg": "Field required",
+ "type": "missing",
+ },
+ ]
+ }
+
+
+def test_openapi_schema(client: TestClient, mod_name: str):
+ tags_schema = {"default": [], "title": "Tags"}
+ if mod_name.startswith("tutorial001"):
+ tags_schema.update(UNTYPED_LIST_SCHEMA)
+ elif mod_name.startswith("tutorial002"):
+ tags_schema.update(LIST_OF_STR_SCHEMA)
+ elif mod_name.startswith("tutorial003"):
+ tags_schema.update(SET_OF_STR_SCHEMA)
+
+ response = client.get("/openapi.json")
+ assert response.status_code == 200, response.text
+ assert response.json() == {
+ "openapi": "3.1.0",
+ "info": {"title": "FastAPI", "version": "0.1.0"},
+ "paths": {
+ "/items/{item_id}": {
+ "put": {
+ "parameters": [
+ {
+ "in": "path",
+ "name": "item_id",
+ "required": True,
+ "schema": {
+ "title": "Item Id",
+ "type": "integer",
+ },
+ },
+ ],
+ "responses": {
+ "200": {
+ "description": "Successful Response",
+ "content": {"application/json": {"schema": {}}},
+ },
+ "422": {
+ "description": "Validation Error",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/HTTPValidationError"
+ }
+ }
+ },
+ },
+ },
+ "summary": "Update Item",
+ "operationId": "update_item_items__item_id__put",
+ "requestBody": {
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/Item",
+ }
+ }
+ },
+ "required": True,
+ },
+ }
+ }
+ },
+ "components": {
+ "schemas": {
+ "Item": {
+ "properties": {
+ "name": {
+ "title": "Name",
+ "type": "string",
+ },
+ "description": {
+ "title": "Description",
+ "anyOf": [{"type": "string"}, {"type": "null"}],
+ },
+ "price": {
+ "title": "Price",
+ "type": "number",
+ },
+ "tax": {
+ "title": "Tax",
+ "anyOf": [{"type": "number"}, {"type": "null"}],
+ },
+ "tags": tags_schema,
+ },
+ "required": [
+ "name",
+ "price",
+ ],
+ "title": "Item",
+ "type": "object",
+ },
+ "ValidationError": {
+ "title": "ValidationError",
+ "required": ["loc", "msg", "type"],
+ "type": "object",
+ "properties": {
+ "loc": {
+ "title": "Location",
+ "type": "array",
+ "items": {
+ "anyOf": [{"type": "string"}, {"type": "integer"}]
+ },
+ },
+ "msg": {"title": "Message", "type": "string"},
+ "type": {"title": "Error Type", "type": "string"},
+ },
+ },
+ "HTTPValidationError": {
+ "title": "HTTPValidationError",
+ "type": "object",
+ "properties": {
+ "detail": {
+ "title": "Detail",
+ "type": "array",
+ "items": {"$ref": "#/components/schemas/ValidationError"},
+ }
+ },
+ },
+ }
+ },
+ }
diff --git a/tests/test_tutorial/test_body_nested_models/test_tutorial004.py b/tests/test_tutorial/test_body_nested_models/test_tutorial004.py
new file mode 100644
index 0000000000..ff9596943d
--- /dev/null
+++ b/tests/test_tutorial/test_body_nested_models/test_tutorial004.py
@@ -0,0 +1,275 @@
+import importlib
+
+import pytest
+from dirty_equals import IsList
+from fastapi.testclient import TestClient
+
+from ...utils import needs_py310
+
+
+@pytest.fixture(
+ name="client",
+ params=[
+ pytest.param("tutorial004_py39"),
+ pytest.param("tutorial004_py310", marks=needs_py310),
+ ],
+)
+def get_client(request: pytest.FixtureRequest):
+ mod = importlib.import_module(f"docs_src.body_nested_models.{request.param}")
+
+ client = TestClient(mod.app)
+ return client
+
+
+def test_put_all(client: TestClient):
+ response = client.put(
+ "/items/123",
+ json={
+ "name": "Foo",
+ "description": "A very nice Item",
+ "price": 35.4,
+ "tax": 3.2,
+ "tags": ["foo", "bar", "foo"],
+ "image": {"url": "http://example.com/image.png", "name": "example image"},
+ },
+ )
+ assert response.status_code == 200, response.text
+ assert response.json() == {
+ "item_id": 123,
+ "item": {
+ "name": "Foo",
+ "description": "A very nice Item",
+ "price": 35.4,
+ "tax": 3.2,
+ "tags": IsList("foo", "bar", check_order=False),
+ "image": {"url": "http://example.com/image.png", "name": "example image"},
+ },
+ }
+
+
+def test_put_only_required(client: TestClient):
+ response = client.put(
+ "/items/5",
+ json={"name": "Foo", "price": 35.4},
+ )
+ assert response.status_code == 200, response.text
+ assert response.json() == {
+ "item_id": 5,
+ "item": {
+ "name": "Foo",
+ "description": None,
+ "price": 35.4,
+ "tax": None,
+ "tags": [],
+ "image": None,
+ },
+ }
+
+
+def test_put_empty_body(client: TestClient):
+ response = client.put(
+ "/items/5",
+ json={},
+ )
+ assert response.status_code == 422, response.text
+ assert response.json() == {
+ "detail": [
+ {
+ "loc": ["body", "name"],
+ "input": {},
+ "msg": "Field required",
+ "type": "missing",
+ },
+ {
+ "loc": ["body", "price"],
+ "input": {},
+ "msg": "Field required",
+ "type": "missing",
+ },
+ ]
+ }
+
+
+def test_put_missing_required_in_item(client: TestClient):
+ response = client.put(
+ "/items/5",
+ json={"description": "A very nice Item"},
+ )
+ assert response.status_code == 422, response.text
+ assert response.json() == {
+ "detail": [
+ {
+ "loc": ["body", "name"],
+ "input": {"description": "A very nice Item"},
+ "msg": "Field required",
+ "type": "missing",
+ },
+ {
+ "loc": ["body", "price"],
+ "input": {"description": "A very nice Item"},
+ "msg": "Field required",
+ "type": "missing",
+ },
+ ]
+ }
+
+
+def test_put_missing_required_in_image(client: TestClient):
+ response = client.put(
+ "/items/5",
+ json={
+ "name": "Foo",
+ "price": 35.4,
+ "image": {"url": "http://example.com/image.png"},
+ },
+ )
+ assert response.status_code == 422, response.text
+ assert response.json() == {
+ "detail": [
+ {
+ "loc": ["body", "image", "name"],
+ "input": {"url": "http://example.com/image.png"},
+ "msg": "Field required",
+ "type": "missing",
+ },
+ ]
+ }
+
+
+def test_openapi_schema(client: TestClient):
+ response = client.get("/openapi.json")
+ assert response.status_code == 200, response.text
+ assert response.json() == {
+ "openapi": "3.1.0",
+ "info": {"title": "FastAPI", "version": "0.1.0"},
+ "paths": {
+ "/items/{item_id}": {
+ "put": {
+ "parameters": [
+ {
+ "in": "path",
+ "name": "item_id",
+ "required": True,
+ "schema": {
+ "title": "Item Id",
+ "type": "integer",
+ },
+ },
+ ],
+ "responses": {
+ "200": {
+ "description": "Successful Response",
+ "content": {"application/json": {"schema": {}}},
+ },
+ "422": {
+ "description": "Validation Error",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/HTTPValidationError"
+ }
+ }
+ },
+ },
+ },
+ "summary": "Update Item",
+ "operationId": "update_item_items__item_id__put",
+ "requestBody": {
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/Item",
+ }
+ }
+ },
+ "required": True,
+ },
+ }
+ }
+ },
+ "components": {
+ "schemas": {
+ "Image": {
+ "properties": {
+ "url": {
+ "title": "Url",
+ "type": "string",
+ },
+ "name": {
+ "title": "Name",
+ "type": "string",
+ },
+ },
+ "required": ["url", "name"],
+ "title": "Image",
+ "type": "object",
+ },
+ "Item": {
+ "properties": {
+ "name": {
+ "title": "Name",
+ "type": "string",
+ },
+ "description": {
+ "title": "Description",
+ "anyOf": [{"type": "string"}, {"type": "null"}],
+ },
+ "price": {
+ "title": "Price",
+ "type": "number",
+ },
+ "tax": {
+ "title": "Tax",
+ "anyOf": [{"type": "number"}, {"type": "null"}],
+ },
+ "tags": {
+ "title": "Tags",
+ "default": [],
+ "type": "array",
+ "items": {"type": "string"},
+ "uniqueItems": True,
+ },
+ "image": {
+ "anyOf": [
+ {"$ref": "#/components/schemas/Image"},
+ {"type": "null"},
+ ],
+ },
+ },
+ "required": [
+ "name",
+ "price",
+ ],
+ "title": "Item",
+ "type": "object",
+ },
+ "ValidationError": {
+ "title": "ValidationError",
+ "required": ["loc", "msg", "type"],
+ "type": "object",
+ "properties": {
+ "loc": {
+ "title": "Location",
+ "type": "array",
+ "items": {
+ "anyOf": [{"type": "string"}, {"type": "integer"}]
+ },
+ },
+ "msg": {"title": "Message", "type": "string"},
+ "type": {"title": "Error Type", "type": "string"},
+ },
+ },
+ "HTTPValidationError": {
+ "title": "HTTPValidationError",
+ "type": "object",
+ "properties": {
+ "detail": {
+ "title": "Detail",
+ "type": "array",
+ "items": {"$ref": "#/components/schemas/ValidationError"},
+ }
+ },
+ },
+ }
+ },
+ }
diff --git a/tests/test_tutorial/test_body_nested_models/test_tutorial005.py b/tests/test_tutorial/test_body_nested_models/test_tutorial005.py
new file mode 100644
index 0000000000..9a07a904e6
--- /dev/null
+++ b/tests/test_tutorial/test_body_nested_models/test_tutorial005.py
@@ -0,0 +1,301 @@
+import importlib
+
+import pytest
+from dirty_equals import IsList
+from fastapi.testclient import TestClient
+
+from ...utils import needs_py310
+
+
+@pytest.fixture(
+ name="client",
+ params=[
+ pytest.param("tutorial005_py39"),
+ pytest.param("tutorial005_py310", marks=needs_py310),
+ ],
+)
+def get_client(request: pytest.FixtureRequest):
+ mod = importlib.import_module(f"docs_src.body_nested_models.{request.param}")
+
+ client = TestClient(mod.app)
+ return client
+
+
+def test_put_all(client: TestClient):
+ response = client.put(
+ "/items/123",
+ json={
+ "name": "Foo",
+ "description": "A very nice Item",
+ "price": 35.4,
+ "tax": 3.2,
+ "tags": ["foo", "bar", "foo"],
+ "image": {"url": "http://example.com/image.png", "name": "example image"},
+ },
+ )
+ assert response.status_code == 200, response.text
+ assert response.json() == {
+ "item_id": 123,
+ "item": {
+ "name": "Foo",
+ "description": "A very nice Item",
+ "price": 35.4,
+ "tax": 3.2,
+ "tags": IsList("foo", "bar", check_order=False),
+ "image": {"url": "http://example.com/image.png", "name": "example image"},
+ },
+ }
+
+
+def test_put_only_required(client: TestClient):
+ response = client.put(
+ "/items/5",
+ json={"name": "Foo", "price": 35.4},
+ )
+ assert response.status_code == 200, response.text
+ assert response.json() == {
+ "item_id": 5,
+ "item": {
+ "name": "Foo",
+ "description": None,
+ "price": 35.4,
+ "tax": None,
+ "tags": [],
+ "image": None,
+ },
+ }
+
+
+def test_put_empty_body(client: TestClient):
+ response = client.put(
+ "/items/5",
+ json={},
+ )
+ assert response.status_code == 422, response.text
+ assert response.json() == {
+ "detail": [
+ {
+ "loc": ["body", "name"],
+ "input": {},
+ "msg": "Field required",
+ "type": "missing",
+ },
+ {
+ "loc": ["body", "price"],
+ "input": {},
+ "msg": "Field required",
+ "type": "missing",
+ },
+ ]
+ }
+
+
+def test_put_missing_required_in_item(client: TestClient):
+ response = client.put(
+ "/items/5",
+ json={"description": "A very nice Item"},
+ )
+ assert response.status_code == 422, response.text
+ assert response.json() == {
+ "detail": [
+ {
+ "loc": ["body", "name"],
+ "input": {"description": "A very nice Item"},
+ "msg": "Field required",
+ "type": "missing",
+ },
+ {
+ "loc": ["body", "price"],
+ "input": {"description": "A very nice Item"},
+ "msg": "Field required",
+ "type": "missing",
+ },
+ ]
+ }
+
+
+def test_put_missing_required_in_image(client: TestClient):
+ response = client.put(
+ "/items/5",
+ json={
+ "name": "Foo",
+ "price": 35.4,
+ "image": {"url": "http://example.com/image.png"},
+ },
+ )
+ assert response.status_code == 422, response.text
+ assert response.json() == {
+ "detail": [
+ {
+ "loc": ["body", "image", "name"],
+ "input": {"url": "http://example.com/image.png"},
+ "msg": "Field required",
+ "type": "missing",
+ },
+ ]
+ }
+
+
+def test_put_wrong_url(client: TestClient):
+ response = client.put(
+ "/items/5",
+ json={
+ "name": "Foo",
+ "price": 35.4,
+ "image": {"url": "not a valid url", "name": "example image"},
+ },
+ )
+ assert response.status_code == 422, response.text
+ assert response.json() == {
+ "detail": [
+ {
+ "loc": ["body", "image", "url"],
+ "input": "not a valid url",
+ "msg": "Input should be a valid URL, relative URL without a base",
+ "type": "url_parsing",
+ "ctx": {"error": "relative URL without a base"},
+ },
+ ]
+ }
+
+
+def test_openapi_schema(client: TestClient):
+ response = client.get("/openapi.json")
+ assert response.status_code == 200, response.text
+ assert response.json() == {
+ "openapi": "3.1.0",
+ "info": {"title": "FastAPI", "version": "0.1.0"},
+ "paths": {
+ "/items/{item_id}": {
+ "put": {
+ "parameters": [
+ {
+ "in": "path",
+ "name": "item_id",
+ "required": True,
+ "schema": {
+ "title": "Item Id",
+ "type": "integer",
+ },
+ },
+ ],
+ "responses": {
+ "200": {
+ "description": "Successful Response",
+ "content": {"application/json": {"schema": {}}},
+ },
+ "422": {
+ "description": "Validation Error",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/HTTPValidationError"
+ }
+ }
+ },
+ },
+ },
+ "summary": "Update Item",
+ "operationId": "update_item_items__item_id__put",
+ "requestBody": {
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/Item",
+ }
+ }
+ },
+ "required": True,
+ },
+ }
+ }
+ },
+ "components": {
+ "schemas": {
+ "Image": {
+ "properties": {
+ "url": {
+ "title": "Url",
+ "type": "string",
+ "format": "uri",
+ "maxLength": 2083,
+ "minLength": 1,
+ },
+ "name": {
+ "title": "Name",
+ "type": "string",
+ },
+ },
+ "required": ["url", "name"],
+ "title": "Image",
+ "type": "object",
+ },
+ "Item": {
+ "properties": {
+ "name": {
+ "title": "Name",
+ "type": "string",
+ },
+ "description": {
+ "title": "Description",
+ "anyOf": [{"type": "string"}, {"type": "null"}],
+ },
+ "price": {
+ "title": "Price",
+ "type": "number",
+ },
+ "tax": {
+ "title": "Tax",
+ "anyOf": [{"type": "number"}, {"type": "null"}],
+ },
+ "tags": {
+ "title": "Tags",
+ "default": [],
+ "type": "array",
+ "items": {"type": "string"},
+ "uniqueItems": True,
+ },
+ "image": {
+ "anyOf": [
+ {"$ref": "#/components/schemas/Image"},
+ {"type": "null"},
+ ],
+ },
+ },
+ "required": [
+ "name",
+ "price",
+ ],
+ "title": "Item",
+ "type": "object",
+ },
+ "ValidationError": {
+ "title": "ValidationError",
+ "required": ["loc", "msg", "type"],
+ "type": "object",
+ "properties": {
+ "loc": {
+ "title": "Location",
+ "type": "array",
+ "items": {
+ "anyOf": [{"type": "string"}, {"type": "integer"}]
+ },
+ },
+ "msg": {"title": "Message", "type": "string"},
+ "type": {"title": "Error Type", "type": "string"},
+ },
+ },
+ "HTTPValidationError": {
+ "title": "HTTPValidationError",
+ "type": "object",
+ "properties": {
+ "detail": {
+ "title": "Detail",
+ "type": "array",
+ "items": {"$ref": "#/components/schemas/ValidationError"},
+ }
+ },
+ },
+ }
+ },
+ }
diff --git a/tests/test_tutorial/test_body_nested_models/test_tutorial006.py b/tests/test_tutorial/test_body_nested_models/test_tutorial006.py
new file mode 100644
index 0000000000..088177cb95
--- /dev/null
+++ b/tests/test_tutorial/test_body_nested_models/test_tutorial006.py
@@ -0,0 +1,269 @@
+import importlib
+
+import pytest
+from dirty_equals import IsList
+from fastapi.testclient import TestClient
+
+from ...utils import needs_py310
+
+
+@pytest.fixture(
+ name="client",
+ params=[
+ pytest.param("tutorial006_py39"),
+ pytest.param("tutorial006_py310", marks=needs_py310),
+ ],
+)
+def get_client(request: pytest.FixtureRequest):
+ mod = importlib.import_module(f"docs_src.body_nested_models.{request.param}")
+
+ client = TestClient(mod.app)
+ return client
+
+
+def test_put_all(client: TestClient):
+ response = client.put(
+ "/items/123",
+ json={
+ "name": "Foo",
+ "description": "A very nice Item",
+ "price": 35.4,
+ "tax": 3.2,
+ "tags": ["foo", "bar", "foo"],
+ "images": [
+ {"url": "http://example.com/image.png", "name": "example image"}
+ ],
+ },
+ )
+ assert response.status_code == 200, response.text
+ assert response.json() == {
+ "item_id": 123,
+ "item": {
+ "name": "Foo",
+ "description": "A very nice Item",
+ "price": 35.4,
+ "tax": 3.2,
+ "tags": IsList("foo", "bar", check_order=False),
+ "images": [
+ {"url": "http://example.com/image.png", "name": "example image"}
+ ],
+ },
+ }
+
+
+def test_put_only_required(client: TestClient):
+ response = client.put(
+ "/items/5",
+ json={"name": "Foo", "price": 35.4},
+ )
+ assert response.status_code == 200, response.text
+ assert response.json() == {
+ "item_id": 5,
+ "item": {
+ "name": "Foo",
+ "description": None,
+ "price": 35.4,
+ "tax": None,
+ "tags": [],
+ "images": None,
+ },
+ }
+
+
+def test_put_empty_body(client: TestClient):
+ response = client.put(
+ "/items/5",
+ json={},
+ )
+ assert response.status_code == 422, response.text
+ assert response.json() == {
+ "detail": [
+ {
+ "loc": ["body", "name"],
+ "input": {},
+ "msg": "Field required",
+ "type": "missing",
+ },
+ {
+ "loc": ["body", "price"],
+ "input": {},
+ "msg": "Field required",
+ "type": "missing",
+ },
+ ]
+ }
+
+
+def test_put_images_not_list(client: TestClient):
+ response = client.put(
+ "/items/5",
+ json={
+ "name": "Foo",
+ "price": 35.4,
+ "images": {"url": "http://example.com/image.png", "name": "example image"},
+ },
+ )
+ assert response.status_code == 422, response.text
+ assert response.json() == {
+ "detail": [
+ {
+ "loc": ["body", "images"],
+ "input": {
+ "url": "http://example.com/image.png",
+ "name": "example image",
+ },
+ "msg": "Input should be a valid list",
+ "type": "list_type",
+ },
+ ]
+ }
+
+
+def test_openapi_schema(client: TestClient):
+ response = client.get("/openapi.json")
+ assert response.status_code == 200, response.text
+ assert response.json() == {
+ "openapi": "3.1.0",
+ "info": {"title": "FastAPI", "version": "0.1.0"},
+ "paths": {
+ "/items/{item_id}": {
+ "put": {
+ "parameters": [
+ {
+ "in": "path",
+ "name": "item_id",
+ "required": True,
+ "schema": {
+ "title": "Item Id",
+ "type": "integer",
+ },
+ },
+ ],
+ "responses": {
+ "200": {
+ "description": "Successful Response",
+ "content": {"application/json": {"schema": {}}},
+ },
+ "422": {
+ "description": "Validation Error",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/HTTPValidationError"
+ }
+ }
+ },
+ },
+ },
+ "summary": "Update Item",
+ "operationId": "update_item_items__item_id__put",
+ "requestBody": {
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/Item",
+ }
+ }
+ },
+ "required": True,
+ },
+ }
+ }
+ },
+ "components": {
+ "schemas": {
+ "Image": {
+ "properties": {
+ "url": {
+ "title": "Url",
+ "type": "string",
+ "format": "uri",
+ "maxLength": 2083,
+ "minLength": 1,
+ },
+ "name": {
+ "title": "Name",
+ "type": "string",
+ },
+ },
+ "required": ["url", "name"],
+ "title": "Image",
+ "type": "object",
+ },
+ "Item": {
+ "properties": {
+ "name": {
+ "title": "Name",
+ "type": "string",
+ },
+ "description": {
+ "title": "Description",
+ "anyOf": [{"type": "string"}, {"type": "null"}],
+ },
+ "price": {
+ "title": "Price",
+ "type": "number",
+ },
+ "tax": {
+ "title": "Tax",
+ "anyOf": [{"type": "number"}, {"type": "null"}],
+ },
+ "tags": {
+ "title": "Tags",
+ "default": [],
+ "type": "array",
+ "items": {"type": "string"},
+ "uniqueItems": True,
+ },
+ "images": {
+ "anyOf": [
+ {
+ "items": {
+ "$ref": "#/components/schemas/Image",
+ },
+ "type": "array",
+ },
+ {
+ "type": "null",
+ },
+ ],
+ "title": "Images",
+ },
+ },
+ "required": [
+ "name",
+ "price",
+ ],
+ "title": "Item",
+ "type": "object",
+ },
+ "ValidationError": {
+ "title": "ValidationError",
+ "required": ["loc", "msg", "type"],
+ "type": "object",
+ "properties": {
+ "loc": {
+ "title": "Location",
+ "type": "array",
+ "items": {
+ "anyOf": [{"type": "string"}, {"type": "integer"}]
+ },
+ },
+ "msg": {"title": "Message", "type": "string"},
+ "type": {"title": "Error Type", "type": "string"},
+ },
+ },
+ "HTTPValidationError": {
+ "title": "HTTPValidationError",
+ "type": "object",
+ "properties": {
+ "detail": {
+ "title": "Detail",
+ "type": "array",
+ "items": {"$ref": "#/components/schemas/ValidationError"},
+ }
+ },
+ },
+ }
+ },
+ }
diff --git a/tests/test_tutorial/test_body_nested_models/test_tutorial007.py b/tests/test_tutorial/test_body_nested_models/test_tutorial007.py
new file mode 100644
index 0000000000..a302819505
--- /dev/null
+++ b/tests/test_tutorial/test_body_nested_models/test_tutorial007.py
@@ -0,0 +1,344 @@
+import importlib
+
+import pytest
+from fastapi.testclient import TestClient
+
+from ...utils import needs_py310
+
+
+@pytest.fixture(
+ name="client",
+ params=[
+ pytest.param("tutorial007_py39"),
+ pytest.param("tutorial007_py310", marks=needs_py310),
+ ],
+)
+def get_client(request: pytest.FixtureRequest):
+ mod = importlib.import_module(f"docs_src.body_nested_models.{request.param}")
+
+ client = TestClient(mod.app)
+ return client
+
+
+def test_post_all(client: TestClient):
+ data = {
+ "name": "Special Offer",
+ "description": "This is a special offer",
+ "price": 38.6,
+ "items": [
+ {
+ "name": "Foo",
+ "description": "A very nice Item",
+ "price": 35.4,
+ "tax": 3.2,
+ "tags": ["foo"],
+ "images": [
+ {
+ "url": "http://example.com/image.png",
+ "name": "example image",
+ }
+ ],
+ }
+ ],
+ }
+
+ response = client.post(
+ "/offers/",
+ json=data,
+ )
+ assert response.status_code == 200, response.text
+ assert response.json() == data
+
+
+def test_put_only_required(client: TestClient):
+ response = client.post(
+ "/offers/",
+ json={
+ "name": "Special Offer",
+ "price": 38.6,
+ "items": [
+ {
+ "name": "Foo",
+ "price": 35.4,
+ "images": [
+ {
+ "url": "http://example.com/image.png",
+ "name": "example image",
+ }
+ ],
+ }
+ ],
+ },
+ )
+ assert response.status_code == 200, response.text
+ assert response.json() == {
+ "name": "Special Offer",
+ "description": None,
+ "price": 38.6,
+ "items": [
+ {
+ "name": "Foo",
+ "description": None,
+ "price": 35.4,
+ "tax": None,
+ "tags": [],
+ "images": [
+ {
+ "url": "http://example.com/image.png",
+ "name": "example image",
+ }
+ ],
+ }
+ ],
+ }
+
+
+def test_put_empty_body(client: TestClient):
+ response = client.post(
+ "/offers/",
+ json={},
+ )
+ assert response.status_code == 422, response.text
+ assert response.json() == {
+ "detail": [
+ {
+ "loc": ["body", "name"],
+ "input": {},
+ "msg": "Field required",
+ "type": "missing",
+ },
+ {
+ "loc": ["body", "price"],
+ "input": {},
+ "msg": "Field required",
+ "type": "missing",
+ },
+ {
+ "loc": ["body", "items"],
+ "input": {},
+ "msg": "Field required",
+ "type": "missing",
+ },
+ ]
+ }
+
+
+def test_put_missing_required_in_items(client: TestClient):
+ response = client.post(
+ "/offers/",
+ json={
+ "name": "Special Offer",
+ "price": 38.6,
+ "items": [{}],
+ },
+ )
+ assert response.status_code == 422, response.text
+ assert response.json() == {
+ "detail": [
+ {
+ "loc": ["body", "items", 0, "name"],
+ "input": {},
+ "msg": "Field required",
+ "type": "missing",
+ },
+ {
+ "loc": ["body", "items", 0, "price"],
+ "input": {},
+ "msg": "Field required",
+ "type": "missing",
+ },
+ ]
+ }
+
+
+def test_put_missing_required_in_images(client: TestClient):
+ response = client.post(
+ "/offers/",
+ json={
+ "name": "Special Offer",
+ "price": 38.6,
+ "items": [
+ {"name": "Foo", "price": 35.4, "images": [{}]},
+ ],
+ },
+ )
+ assert response.status_code == 422, response.text
+ assert response.json() == {
+ "detail": [
+ {
+ "loc": ["body", "items", 0, "images", 0, "url"],
+ "input": {},
+ "msg": "Field required",
+ "type": "missing",
+ },
+ {
+ "loc": ["body", "items", 0, "images", 0, "name"],
+ "input": {},
+ "msg": "Field required",
+ "type": "missing",
+ },
+ ]
+ }
+
+
+def test_openapi_schema(client: TestClient):
+ response = client.get("/openapi.json")
+ assert response.status_code == 200, response.text
+ assert response.json() == {
+ "openapi": "3.1.0",
+ "info": {"title": "FastAPI", "version": "0.1.0"},
+ "paths": {
+ "/offers/": {
+ "post": {
+ "responses": {
+ "200": {
+ "description": "Successful Response",
+ "content": {"application/json": {"schema": {}}},
+ },
+ "422": {
+ "description": "Validation Error",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/HTTPValidationError"
+ }
+ }
+ },
+ },
+ },
+ "summary": "Create Offer",
+ "operationId": "create_offer_offers__post",
+ "requestBody": {
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/Offer",
+ }
+ }
+ },
+ "required": True,
+ },
+ }
+ }
+ },
+ "components": {
+ "schemas": {
+ "Image": {
+ "properties": {
+ "url": {
+ "title": "Url",
+ "type": "string",
+ "format": "uri",
+ "maxLength": 2083,
+ "minLength": 1,
+ },
+ "name": {
+ "title": "Name",
+ "type": "string",
+ },
+ },
+ "required": ["url", "name"],
+ "title": "Image",
+ "type": "object",
+ },
+ "Item": {
+ "properties": {
+ "name": {
+ "title": "Name",
+ "type": "string",
+ },
+ "description": {
+ "title": "Description",
+ "anyOf": [{"type": "string"}, {"type": "null"}],
+ },
+ "price": {
+ "title": "Price",
+ "type": "number",
+ },
+ "tax": {
+ "title": "Tax",
+ "anyOf": [{"type": "number"}, {"type": "null"}],
+ },
+ "tags": {
+ "title": "Tags",
+ "default": [],
+ "type": "array",
+ "items": {"type": "string"},
+ "uniqueItems": True,
+ },
+ "images": {
+ "anyOf": [
+ {
+ "items": {
+ "$ref": "#/components/schemas/Image",
+ },
+ "type": "array",
+ },
+ {
+ "type": "null",
+ },
+ ],
+ "title": "Images",
+ },
+ },
+ "required": [
+ "name",
+ "price",
+ ],
+ "title": "Item",
+ "type": "object",
+ },
+ "Offer": {
+ "properties": {
+ "name": {
+ "title": "Name",
+ "type": "string",
+ },
+ "description": {
+ "title": "Description",
+ "anyOf": [{"type": "string"}, {"type": "null"}],
+ },
+ "price": {
+ "title": "Price",
+ "type": "number",
+ },
+ "items": {
+ "title": "Items",
+ "type": "array",
+ "items": {"$ref": "#/components/schemas/Item"},
+ },
+ },
+ "required": ["name", "price", "items"],
+ "title": "Offer",
+ "type": "object",
+ },
+ "ValidationError": {
+ "title": "ValidationError",
+ "required": ["loc", "msg", "type"],
+ "type": "object",
+ "properties": {
+ "loc": {
+ "title": "Location",
+ "type": "array",
+ "items": {
+ "anyOf": [{"type": "string"}, {"type": "integer"}]
+ },
+ },
+ "msg": {"title": "Message", "type": "string"},
+ "type": {"title": "Error Type", "type": "string"},
+ },
+ },
+ "HTTPValidationError": {
+ "title": "HTTPValidationError",
+ "type": "object",
+ "properties": {
+ "detail": {
+ "title": "Detail",
+ "type": "array",
+ "items": {"$ref": "#/components/schemas/ValidationError"},
+ }
+ },
+ },
+ }
+ },
+ }
diff --git a/tests/test_tutorial/test_body_nested_models/test_tutorial008.py b/tests/test_tutorial/test_body_nested_models/test_tutorial008.py
new file mode 100644
index 0000000000..32eb8ee75c
--- /dev/null
+++ b/tests/test_tutorial/test_body_nested_models/test_tutorial008.py
@@ -0,0 +1,157 @@
+import importlib
+
+import pytest
+from fastapi.testclient import TestClient
+
+
+@pytest.fixture(
+ name="client",
+ params=[
+ pytest.param("tutorial008_py39"),
+ ],
+)
+def get_client(request: pytest.FixtureRequest):
+ mod = importlib.import_module(f"docs_src.body_nested_models.{request.param}")
+
+ client = TestClient(mod.app)
+ return client
+
+
+def test_post_body(client: TestClient):
+ data = [
+ {"url": "http://example.com/", "name": "Example"},
+ {"url": "http://fastapi.tiangolo.com/", "name": "FastAPI"},
+ ]
+ response = client.post("/images/multiple", json=data)
+ assert response.status_code == 200, response.text
+ assert response.json() == data
+
+
+def test_post_invalid_list_item(client: TestClient):
+ data = [{"url": "not a valid url", "name": "Example"}]
+ response = client.post("/images/multiple", json=data)
+ assert response.status_code == 422, response.text
+ assert response.json() == {
+ "detail": [
+ {
+ "loc": ["body", 0, "url"],
+ "input": "not a valid url",
+ "msg": "Input should be a valid URL, relative URL without a base",
+ "type": "url_parsing",
+ "ctx": {"error": "relative URL without a base"},
+ },
+ ]
+ }
+
+
+def test_post_not_a_list(client: TestClient):
+ data = {"url": "http://example.com/", "name": "Example"}
+ response = client.post("/images/multiple", json=data)
+ assert response.status_code == 422, response.text
+ assert response.json() == {
+ "detail": [
+ {
+ "loc": ["body"],
+ "input": {
+ "name": "Example",
+ "url": "http://example.com/",
+ },
+ "msg": "Input should be a valid list",
+ "type": "list_type",
+ }
+ ]
+ }
+
+
+def test_openapi_schema(client: TestClient):
+ response = client.get("/openapi.json")
+ assert response.status_code == 200, response.text
+ assert response.json() == {
+ "openapi": "3.1.0",
+ "info": {"title": "FastAPI", "version": "0.1.0"},
+ "paths": {
+ "/images/multiple/": {
+ "post": {
+ "responses": {
+ "200": {
+ "description": "Successful Response",
+ "content": {"application/json": {"schema": {}}},
+ },
+ "422": {
+ "description": "Validation Error",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/HTTPValidationError"
+ }
+ }
+ },
+ },
+ },
+ "summary": "Create Multiple Images",
+ "operationId": "create_multiple_images_images_multiple__post",
+ "requestBody": {
+ "content": {
+ "application/json": {
+ "schema": {
+ "title": "Images",
+ "type": "array",
+ "items": {"$ref": "#/components/schemas/Image"},
+ }
+ }
+ },
+ "required": True,
+ },
+ }
+ }
+ },
+ "components": {
+ "schemas": {
+ "Image": {
+ "properties": {
+ "url": {
+ "title": "Url",
+ "type": "string",
+ "format": "uri",
+ "maxLength": 2083,
+ "minLength": 1,
+ },
+ "name": {
+ "title": "Name",
+ "type": "string",
+ },
+ },
+ "required": ["url", "name"],
+ "title": "Image",
+ "type": "object",
+ },
+ "ValidationError": {
+ "title": "ValidationError",
+ "required": ["loc", "msg", "type"],
+ "type": "object",
+ "properties": {
+ "loc": {
+ "title": "Location",
+ "type": "array",
+ "items": {
+ "anyOf": [{"type": "string"}, {"type": "integer"}]
+ },
+ },
+ "msg": {"title": "Message", "type": "string"},
+ "type": {"title": "Error Type", "type": "string"},
+ },
+ },
+ "HTTPValidationError": {
+ "title": "HTTPValidationError",
+ "type": "object",
+ "properties": {
+ "detail": {
+ "title": "Detail",
+ "type": "array",
+ "items": {"$ref": "#/components/schemas/ValidationError"},
+ }
+ },
+ },
+ }
+ },
+ }
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 38ba3c8875..f2e56d40fb 100644
--- a/tests/test_tutorial/test_body_nested_models/test_tutorial009.py
+++ b/tests/test_tutorial/test_body_nested_models/test_tutorial009.py
@@ -1,17 +1,13 @@
import importlib
import pytest
-from dirty_equals import IsDict
from fastapi.testclient import TestClient
-from ...utils import needs_py39
-
@pytest.fixture(
name="client",
params=[
- "tutorial009",
- pytest.param("tutorial009_py39", marks=needs_py39),
+ "tutorial009_py39",
],
)
def get_client(request: pytest.FixtureRequest):
@@ -32,29 +28,16 @@ def test_post_invalid_body(client: TestClient):
data = {"foo": 2.2, "3": 3.3}
response = client.post("/index-weights/", json=data)
assert response.status_code == 422, response.text
- assert response.json() == IsDict(
- {
- "detail": [
- {
- "type": "int_parsing",
- "loc": ["body", "foo", "[key]"],
- "msg": "Input should be a valid integer, unable to parse string as an integer",
- "input": "foo",
- }
- ]
- }
- ) | IsDict(
- # TODO: remove when deprecating Pydantic v1
- {
- "detail": [
- {
- "loc": ["body", "__key__"],
- "msg": "value is not a valid integer",
- "type": "type_error.integer",
- }
- ]
- }
- )
+ assert response.json() == {
+ "detail": [
+ {
+ "type": "int_parsing",
+ "loc": ["body", "foo", "[key]"],
+ "msg": "Input should be a valid integer, unable to parse string as an integer",
+ "input": "foo",
+ }
+ ]
+ }
def test_openapi_schema(client: TestClient):
diff --git a/tests/test_tutorial/test_body_updates/test_tutorial001.py b/tests/test_tutorial/test_body_updates/test_tutorial001.py
index f874dc9bd6..0401eb7d0d 100644
--- a/tests/test_tutorial/test_body_updates/test_tutorial001.py
+++ b/tests/test_tutorial/test_body_updates/test_tutorial001.py
@@ -3,15 +3,14 @@ import importlib
import pytest
from fastapi.testclient import TestClient
-from ...utils import needs_py39, needs_py310, needs_pydanticv1, needs_pydanticv2
+from ...utils import needs_py310
@pytest.fixture(
name="client",
params=[
- "tutorial001",
+ "tutorial001_py39",
pytest.param("tutorial001_py310", marks=needs_py310),
- pytest.param("tutorial001_py39", marks=needs_py39),
],
)
def get_client(request: pytest.FixtureRequest):
@@ -46,7 +45,6 @@ def test_put(client: TestClient):
}
-@needs_pydanticv2
def test_openapi_schema(client: TestClient):
response = client.get("/openapi.json")
assert response.status_code == 200, response.text
@@ -186,137 +184,3 @@ def test_openapi_schema(client: TestClient):
}
},
}
-
-
-# TODO: remove when deprecating Pydantic v1
-@needs_pydanticv1
-def test_openapi_schema_pv1(client: TestClient):
- response = client.get("/openapi.json")
- assert response.status_code == 200, response.text
- assert response.json() == {
- "openapi": "3.1.0",
- "info": {"title": "FastAPI", "version": "0.1.0"},
- "paths": {
- "/items/{item_id}": {
- "get": {
- "responses": {
- "200": {
- "description": "Successful Response",
- "content": {
- "application/json": {
- "schema": {"$ref": "#/components/schemas/Item"}
- }
- },
- },
- "422": {
- "description": "Validation Error",
- "content": {
- "application/json": {
- "schema": {
- "$ref": "#/components/schemas/HTTPValidationError"
- }
- }
- },
- },
- },
- "summary": "Read Item",
- "operationId": "read_item_items__item_id__get",
- "parameters": [
- {
- "required": True,
- "schema": {"title": "Item Id", "type": "string"},
- "name": "item_id",
- "in": "path",
- }
- ],
- },
- "put": {
- "responses": {
- "200": {
- "description": "Successful Response",
- "content": {
- "application/json": {
- "schema": {"$ref": "#/components/schemas/Item"}
- }
- },
- },
- "422": {
- "description": "Validation Error",
- "content": {
- "application/json": {
- "schema": {
- "$ref": "#/components/schemas/HTTPValidationError"
- }
- }
- },
- },
- },
- "summary": "Update Item",
- "operationId": "update_item_items__item_id__put",
- "parameters": [
- {
- "required": True,
- "schema": {"title": "Item Id", "type": "string"},
- "name": "item_id",
- "in": "path",
- }
- ],
- "requestBody": {
- "content": {
- "application/json": {
- "schema": {"$ref": "#/components/schemas/Item"}
- }
- },
- "required": True,
- },
- },
- }
- },
- "components": {
- "schemas": {
- "Item": {
- "title": "Item",
- "type": "object",
- "properties": {
- "name": {"title": "Name", "type": "string"},
- "description": {"title": "Description", "type": "string"},
- "price": {"title": "Price", "type": "number"},
- "tax": {"title": "Tax", "type": "number", "default": 10.5},
- "tags": {
- "title": "Tags",
- "type": "array",
- "items": {"type": "string"},
- "default": [],
- },
- },
- },
- "ValidationError": {
- "title": "ValidationError",
- "required": ["loc", "msg", "type"],
- "type": "object",
- "properties": {
- "loc": {
- "title": "Location",
- "type": "array",
- "items": {
- "anyOf": [{"type": "string"}, {"type": "integer"}]
- },
- },
- "msg": {"title": "Message", "type": "string"},
- "type": {"title": "Error Type", "type": "string"},
- },
- },
- "HTTPValidationError": {
- "title": "HTTPValidationError",
- "type": "object",
- "properties": {
- "detail": {
- "title": "Detail",
- "type": "array",
- "items": {"$ref": "#/components/schemas/ValidationError"},
- }
- },
- },
- }
- },
- }
diff --git a/tests/test_tutorial/test_body_updates/test_tutorial002.py b/tests/test_tutorial/test_body_updates/test_tutorial002.py
new file mode 100644
index 0000000000..466e6af8fd
--- /dev/null
+++ b/tests/test_tutorial/test_body_updates/test_tutorial002.py
@@ -0,0 +1,207 @@
+import importlib
+
+import pytest
+from fastapi.testclient import TestClient
+
+from ...utils import needs_py310
+
+
+@pytest.fixture(
+ name="client",
+ params=[
+ pytest.param("tutorial002_py39"),
+ pytest.param("tutorial002_py310", marks=needs_py310),
+ ],
+)
+def get_client(request: pytest.FixtureRequest):
+ mod = importlib.import_module(f"docs_src.body_updates.{request.param}")
+
+ client = TestClient(mod.app)
+ return client
+
+
+def test_get(client: TestClient):
+ response = client.get("/items/baz")
+ assert response.status_code == 200, response.text
+ assert response.json() == {
+ "name": "Baz",
+ "description": None,
+ "price": 50.2,
+ "tax": 10.5,
+ "tags": [],
+ }
+
+
+def test_patch_all(client: TestClient):
+ response = client.patch(
+ "/items/foo",
+ json={
+ "name": "Fooz",
+ "description": "Item description",
+ "price": 3,
+ "tax": 10.5,
+ "tags": ["tag1", "tag2"],
+ },
+ )
+ assert response.json() == {
+ "name": "Fooz",
+ "description": "Item description",
+ "price": 3,
+ "tax": 10.5,
+ "tags": ["tag1", "tag2"],
+ }
+
+
+def test_patch_name(client: TestClient):
+ response = client.patch(
+ "/items/bar",
+ json={"name": "Barz"},
+ )
+ assert response.json() == {
+ "name": "Barz",
+ "description": "The bartenders",
+ "price": 62,
+ "tax": 20.2,
+ "tags": [],
+ }
+
+
+def test_openapi_schema(client: TestClient):
+ response = client.get("/openapi.json")
+ assert response.status_code == 200, response.text
+ assert response.json() == {
+ "openapi": "3.1.0",
+ "info": {"title": "FastAPI", "version": "0.1.0"},
+ "paths": {
+ "/items/{item_id}": {
+ "get": {
+ "responses": {
+ "200": {
+ "description": "Successful Response",
+ "content": {
+ "application/json": {
+ "schema": {"$ref": "#/components/schemas/Item"}
+ }
+ },
+ },
+ "422": {
+ "description": "Validation Error",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/HTTPValidationError"
+ }
+ }
+ },
+ },
+ },
+ "summary": "Read Item",
+ "operationId": "read_item_items__item_id__get",
+ "parameters": [
+ {
+ "required": True,
+ "schema": {"title": "Item Id", "type": "string"},
+ "name": "item_id",
+ "in": "path",
+ }
+ ],
+ },
+ "patch": {
+ "responses": {
+ "200": {
+ "description": "Successful Response",
+ "content": {
+ "application/json": {
+ "schema": {"$ref": "#/components/schemas/Item"}
+ }
+ },
+ },
+ "422": {
+ "description": "Validation Error",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/HTTPValidationError"
+ }
+ }
+ },
+ },
+ },
+ "summary": "Update Item",
+ "operationId": "update_item_items__item_id__patch",
+ "parameters": [
+ {
+ "required": True,
+ "schema": {"title": "Item Id", "type": "string"},
+ "name": "item_id",
+ "in": "path",
+ }
+ ],
+ "requestBody": {
+ "content": {
+ "application/json": {
+ "schema": {"$ref": "#/components/schemas/Item"}
+ }
+ },
+ "required": True,
+ },
+ },
+ }
+ },
+ "components": {
+ "schemas": {
+ "Item": {
+ "type": "object",
+ "title": "Item",
+ "properties": {
+ "name": {
+ "anyOf": [{"type": "string"}, {"type": "null"}],
+ "title": "Name",
+ },
+ "description": {
+ "anyOf": [{"type": "string"}, {"type": "null"}],
+ "title": "Description",
+ },
+ "price": {
+ "anyOf": [{"type": "number"}, {"type": "null"}],
+ "title": "Price",
+ },
+ "tax": {"title": "Tax", "type": "number", "default": 10.5},
+ "tags": {
+ "title": "Tags",
+ "type": "array",
+ "items": {"type": "string"},
+ "default": [],
+ },
+ },
+ },
+ "ValidationError": {
+ "title": "ValidationError",
+ "required": ["loc", "msg", "type"],
+ "type": "object",
+ "properties": {
+ "loc": {
+ "title": "Location",
+ "type": "array",
+ "items": {
+ "anyOf": [{"type": "string"}, {"type": "integer"}]
+ },
+ },
+ "msg": {"title": "Message", "type": "string"},
+ "type": {"title": "Error Type", "type": "string"},
+ },
+ },
+ "HTTPValidationError": {
+ "title": "HTTPValidationError",
+ "type": "object",
+ "properties": {
+ "detail": {
+ "title": "Detail",
+ "type": "array",
+ "items": {"$ref": "#/components/schemas/ValidationError"},
+ }
+ },
+ },
+ }
+ },
+ }
diff --git a/tests/test_tutorial/test_conditional_openapi/test_tutorial001.py b/tests/test_tutorial/test_conditional_openapi/test_tutorial001.py
index b098f259c2..ddc282d85e 100644
--- a/tests/test_tutorial/test_conditional_openapi/test_tutorial001.py
+++ b/tests/test_tutorial/test_conditional_openapi/test_tutorial001.py
@@ -2,19 +2,16 @@ import importlib
from fastapi.testclient import TestClient
-from ...utils import needs_pydanticv2
-
def get_client() -> TestClient:
- from docs_src.conditional_openapi import tutorial001
+ from docs_src.conditional_openapi import tutorial001_py39
- importlib.reload(tutorial001)
+ importlib.reload(tutorial001_py39)
- client = TestClient(tutorial001.app)
+ client = TestClient(tutorial001_py39.app)
return client
-@needs_pydanticv2
def test_disable_openapi(monkeypatch):
monkeypatch.setenv("OPENAPI_URL", "")
# Load the client after setting the env var
@@ -27,7 +24,6 @@ def test_disable_openapi(monkeypatch):
assert response.status_code == 404, response.text
-@needs_pydanticv2
def test_root():
client = get_client()
response = client.get("/")
@@ -35,7 +31,6 @@ def test_root():
assert response.json() == {"message": "Hello World"}
-@needs_pydanticv2
def test_default_openapi():
client = get_client()
response = client.get("/docs")
diff --git a/tests/test_tutorial/test_configure_swagger_ui/test_tutorial001.py b/tests/test_tutorial/test_configure_swagger_ui/test_tutorial001.py
index a04dba2197..1fa9419a76 100644
--- a/tests/test_tutorial/test_configure_swagger_ui/test_tutorial001.py
+++ b/tests/test_tutorial/test_configure_swagger_ui/test_tutorial001.py
@@ -1,6 +1,6 @@
from fastapi.testclient import TestClient
-from docs_src.configure_swagger_ui.tutorial001 import app
+from docs_src.configure_swagger_ui.tutorial001_py39 import app
client = TestClient(app)
diff --git a/tests/test_tutorial/test_configure_swagger_ui/test_tutorial002.py b/tests/test_tutorial/test_configure_swagger_ui/test_tutorial002.py
index ea56b6f21c..c218cc858c 100644
--- a/tests/test_tutorial/test_configure_swagger_ui/test_tutorial002.py
+++ b/tests/test_tutorial/test_configure_swagger_ui/test_tutorial002.py
@@ -1,6 +1,6 @@
from fastapi.testclient import TestClient
-from docs_src.configure_swagger_ui.tutorial002 import app
+from docs_src.configure_swagger_ui.tutorial002_py39 import app
client = TestClient(app)
diff --git a/tests/test_tutorial/test_configure_swagger_ui/test_tutorial003.py b/tests/test_tutorial/test_configure_swagger_ui/test_tutorial003.py
index 926bbb14f0..8b73685499 100644
--- a/tests/test_tutorial/test_configure_swagger_ui/test_tutorial003.py
+++ b/tests/test_tutorial/test_configure_swagger_ui/test_tutorial003.py
@@ -1,6 +1,6 @@
from fastapi.testclient import TestClient
-from docs_src.configure_swagger_ui.tutorial003 import app
+from docs_src.configure_swagger_ui.tutorial003_py39 import app
client = TestClient(app)
diff --git a/tests/test_tutorial/test_cookie_param_models/test_tutorial001.py b/tests/test_tutorial/test_cookie_param_models/test_tutorial001.py
index 60643185a4..ac8e7bdae1 100644
--- a/tests/test_tutorial/test_cookie_param_models/test_tutorial001.py
+++ b/tests/test_tutorial/test_cookie_param_models/test_tutorial001.py
@@ -1,20 +1,18 @@
import importlib
import pytest
-from dirty_equals import IsDict
from fastapi.testclient import TestClient
from inline_snapshot import snapshot
-from tests.utils import needs_py39, needs_py310
+from tests.utils import needs_py310
@pytest.fixture(
name="client",
params=[
- "tutorial001",
+ "tutorial001_py39",
pytest.param("tutorial001_py310", marks=needs_py310),
- "tutorial001_an",
- pytest.param("tutorial001_an_py39", marks=needs_py39),
+ "tutorial001_an_py39",
pytest.param("tutorial001_an_py310", marks=needs_py310),
],
)
@@ -55,30 +53,16 @@ def test_cookie_param_model_invalid(client: TestClient):
response = client.get("/items/")
assert response.status_code == 422
assert response.json() == snapshot(
- IsDict(
- {
- "detail": [
- {
- "type": "missing",
- "loc": ["cookie", "session_id"],
- "msg": "Field required",
- "input": {},
- }
- ]
- }
- )
- | IsDict(
- # TODO: remove when deprecating Pydantic v1
- {
- "detail": [
- {
- "type": "value_error.missing",
- "loc": ["cookie", "session_id"],
- "msg": "field required",
- }
- ]
- }
- )
+ {
+ "detail": [
+ {
+ "type": "missing",
+ "loc": ["cookie", "session_id"],
+ "msg": "Field required",
+ "input": {},
+ }
+ ]
+ }
)
@@ -116,37 +100,19 @@ def test_openapi_schema(client: TestClient):
"name": "fatebook_tracker",
"in": "cookie",
"required": False,
- "schema": IsDict(
- {
- "anyOf": [{"type": "string"}, {"type": "null"}],
- "title": "Fatebook Tracker",
- }
- )
- | IsDict(
- # TODO: remove when deprecating Pydantic v1
- {
- "type": "string",
- "title": "Fatebook Tracker",
- }
- ),
+ "schema": {
+ "anyOf": [{"type": "string"}, {"type": "null"}],
+ "title": "Fatebook Tracker",
+ },
},
{
"name": "googall_tracker",
"in": "cookie",
"required": False,
- "schema": IsDict(
- {
- "anyOf": [{"type": "string"}, {"type": "null"}],
- "title": "Googall Tracker",
- }
- )
- | IsDict(
- # TODO: remove when deprecating Pydantic v1
- {
- "type": "string",
- "title": "Googall Tracker",
- }
- ),
+ "schema": {
+ "anyOf": [{"type": "string"}, {"type": "null"}],
+ "title": "Googall Tracker",
+ },
},
],
"responses": {
diff --git a/tests/test_tutorial/test_cookie_param_models/test_tutorial002.py b/tests/test_tutorial/test_cookie_param_models/test_tutorial002.py
index cef6f66309..d7c3d15f1b 100644
--- a/tests/test_tutorial/test_cookie_param_models/test_tutorial002.py
+++ b/tests/test_tutorial/test_cookie_param_models/test_tutorial002.py
@@ -1,32 +1,19 @@
import importlib
import pytest
-from dirty_equals import IsDict
from fastapi.testclient import TestClient
from inline_snapshot import snapshot
-from tests.utils import (
- needs_py39,
- needs_py310,
- needs_pydanticv1,
- needs_pydanticv2,
- pydantic_snapshot,
-)
+from tests.utils import needs_py310
@pytest.fixture(
name="client",
params=[
- pytest.param("tutorial002", marks=needs_pydanticv2),
- pytest.param("tutorial002_py310", marks=[needs_py310, needs_pydanticv2]),
- pytest.param("tutorial002_an", marks=needs_pydanticv2),
- pytest.param("tutorial002_an_py39", marks=[needs_py39, needs_pydanticv2]),
- pytest.param("tutorial002_an_py310", marks=[needs_py310, needs_pydanticv2]),
- pytest.param("tutorial002_pv1", marks=[needs_pydanticv1, needs_pydanticv1]),
- pytest.param("tutorial002_pv1_py310", marks=[needs_py310, needs_pydanticv1]),
- pytest.param("tutorial002_pv1_an", marks=[needs_pydanticv1]),
- pytest.param("tutorial002_pv1_an_py39", marks=[needs_py39, needs_pydanticv1]),
- pytest.param("tutorial002_pv1_an_py310", marks=[needs_py310, needs_pydanticv1]),
+ pytest.param("tutorial002_py39"),
+ pytest.param("tutorial002_py310", marks=[needs_py310]),
+ pytest.param("tutorial002_an_py39"),
+ pytest.param("tutorial002_an_py310", marks=[needs_py310]),
],
)
def get_client(request: pytest.FixtureRequest):
@@ -65,31 +52,16 @@ def test_cookie_param_model_defaults(client: TestClient):
def test_cookie_param_model_invalid(client: TestClient):
response = client.get("/items/")
assert response.status_code == 422
- assert response.json() == pydantic_snapshot(
- v2=snapshot(
+ assert response.json() == {
+ "detail": [
{
- "detail": [
- {
- "type": "missing",
- "loc": ["cookie", "session_id"],
- "msg": "Field required",
- "input": {},
- }
- ]
+ "type": "missing",
+ "loc": ["cookie", "session_id"],
+ "msg": "Field required",
+ "input": {},
}
- ),
- v1=snapshot(
- {
- "detail": [
- {
- "type": "value_error.missing",
- "loc": ["cookie", "session_id"],
- "msg": "field required",
- }
- ]
- }
- ),
- )
+ ]
+ }
def test_cookie_param_model_extra(client: TestClient):
@@ -99,30 +71,16 @@ def test_cookie_param_model_extra(client: TestClient):
response = c.get("/items/")
assert response.status_code == 422
assert response.json() == snapshot(
- IsDict(
- {
- "detail": [
- {
- "type": "extra_forbidden",
- "loc": ["cookie", "extra"],
- "msg": "Extra inputs are not permitted",
- "input": "track-me-here-too",
- }
- ]
- }
- )
- | IsDict(
- # TODO: remove when deprecating Pydantic v1
- {
- "detail": [
- {
- "type": "value_error.extra",
- "loc": ["cookie", "extra"],
- "msg": "extra fields not permitted",
- }
- ]
- }
- )
+ {
+ "detail": [
+ {
+ "type": "extra_forbidden",
+ "loc": ["cookie", "extra"],
+ "msg": "Extra inputs are not permitted",
+ "input": "track-me-here-too",
+ }
+ ]
+ }
)
@@ -149,42 +107,22 @@ def test_openapi_schema(client: TestClient):
"name": "fatebook_tracker",
"in": "cookie",
"required": False,
- "schema": pydantic_snapshot(
- v2=snapshot(
- {
- "anyOf": [
- {"type": "string"},
- {"type": "null"},
- ],
- "title": "Fatebook Tracker",
- }
- ),
- v1=snapshot(
- # TODO: remove when deprecating Pydantic v1
- {
- "type": "string",
- "title": "Fatebook Tracker",
- }
- ),
- ),
+ "schema": {
+ "anyOf": [
+ {"type": "string"},
+ {"type": "null"},
+ ],
+ "title": "Fatebook Tracker",
+ },
},
{
"name": "googall_tracker",
"in": "cookie",
"required": False,
- "schema": IsDict(
- {
- "anyOf": [{"type": "string"}, {"type": "null"}],
- "title": "Googall Tracker",
- }
- )
- | IsDict(
- # TODO: remove when deprecating Pydantic v1
- {
- "type": "string",
- "title": "Googall Tracker",
- }
- ),
+ "schema": {
+ "anyOf": [{"type": "string"}, {"type": "null"}],
+ "title": "Googall Tracker",
+ },
},
],
"responses": {
diff --git a/tests/test_tutorial/test_cookie_params/test_tutorial001.py b/tests/test_tutorial/test_cookie_params/test_tutorial001.py
index 90e8dfd37c..9b47cbc67a 100644
--- a/tests/test_tutorial/test_cookie_params/test_tutorial001.py
+++ b/tests/test_tutorial/test_cookie_params/test_tutorial001.py
@@ -2,19 +2,17 @@ import importlib
from types import ModuleType
import pytest
-from dirty_equals import IsDict
from fastapi.testclient import TestClient
-from ...utils import needs_py39, needs_py310
+from ...utils import needs_py310
@pytest.fixture(
name="mod",
params=[
- "tutorial001",
+ "tutorial001_py39",
pytest.param("tutorial001_py310", marks=needs_py310),
- "tutorial001_an",
- pytest.param("tutorial001_an_py39", marks=needs_py39),
+ "tutorial001_an_py39",
pytest.param("tutorial001_an_py310", marks=needs_py310),
],
)
@@ -76,16 +74,10 @@ def test_openapi_schema(mod: ModuleType):
"parameters": [
{
"required": False,
- "schema": IsDict(
- {
- "anyOf": [{"type": "string"}, {"type": "null"}],
- "title": "Ads Id",
- }
- )
- | IsDict(
- # TODO: remove when deprecating Pydantic v1
- {"title": "Ads Id", "type": "string"}
- ),
+ "schema": {
+ "anyOf": [{"type": "string"}, {"type": "null"}],
+ "title": "Ads Id",
+ },
"name": "ads_id",
"in": "cookie",
}
diff --git a/tests/test_tutorial/test_cors/test_tutorial001.py b/tests/test_tutorial/test_cors/test_tutorial001.py
index f62c9df4f9..6a733693ae 100644
--- a/tests/test_tutorial/test_cors/test_tutorial001.py
+++ b/tests/test_tutorial/test_cors/test_tutorial001.py
@@ -1,6 +1,6 @@
from fastapi.testclient import TestClient
-from docs_src.cors.tutorial001 import app
+from docs_src.cors.tutorial001_py39 import app
def test_cors():
diff --git a/tests/test_tutorial/test_custom_docs_ui/test_tutorial001.py b/tests/test_tutorial/test_custom_docs_ui/test_tutorial001.py
index cb8e8c2248..1816e5d975 100644
--- a/tests/test_tutorial/test_custom_docs_ui/test_tutorial001.py
+++ b/tests/test_tutorial/test_custom_docs_ui/test_tutorial001.py
@@ -10,7 +10,7 @@ def client():
static_dir: Path = Path(os.getcwd()) / "static"
print(static_dir)
static_dir.mkdir(exist_ok=True)
- from docs_src.custom_docs_ui.tutorial001 import app
+ from docs_src.custom_docs_ui.tutorial001_py39 import app
with TestClient(app) as client:
yield client
diff --git a/tests/test_tutorial/test_custom_docs_ui/test_tutorial002.py b/tests/test_tutorial/test_custom_docs_ui/test_tutorial002.py
index 712618807c..e8b7eb7aa3 100644
--- a/tests/test_tutorial/test_custom_docs_ui/test_tutorial002.py
+++ b/tests/test_tutorial/test_custom_docs_ui/test_tutorial002.py
@@ -10,7 +10,7 @@ def client():
static_dir: Path = Path(os.getcwd()) / "static"
print(static_dir)
static_dir.mkdir(exist_ok=True)
- from docs_src.custom_docs_ui.tutorial002 import app
+ from docs_src.custom_docs_ui.tutorial002_py39 import app
with TestClient(app) as client:
yield client
diff --git a/tests/test_tutorial/test_custom_request_and_route/test_tutorial001.py b/tests/test_tutorial/test_custom_request_and_route/test_tutorial001.py
index f9fd0d1af8..b4ea537846 100644
--- a/tests/test_tutorial/test_custom_request_and_route/test_tutorial001.py
+++ b/tests/test_tutorial/test_custom_request_and_route/test_tutorial001.py
@@ -6,17 +6,15 @@ import pytest
from fastapi import Request
from fastapi.testclient import TestClient
-from tests.utils import needs_py39, needs_py310
+from tests.utils import needs_py310
@pytest.fixture(
name="client",
params=[
- pytest.param("tutorial001"),
- pytest.param("tutorial001_py39", marks=needs_py39),
+ pytest.param("tutorial001_py39"),
pytest.param("tutorial001_py310", marks=needs_py310),
- pytest.param("tutorial001_an"),
- pytest.param("tutorial001_an_py39", marks=needs_py39),
+ pytest.param("tutorial001_an_py39"),
pytest.param("tutorial001_an_py310", marks=needs_py310),
],
)
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 c35752ed13..a9c7ae638b 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,20 +1,18 @@
import importlib
import pytest
-from dirty_equals import IsDict, IsOneOf
+from dirty_equals import IsOneOf
from fastapi.testclient import TestClient
-from tests.utils import needs_py39, needs_py310
+from tests.utils import needs_py310
@pytest.fixture(
name="client",
params=[
- pytest.param("tutorial002"),
- pytest.param("tutorial002_py39", marks=needs_py39),
+ pytest.param("tutorial002_py39"),
pytest.param("tutorial002_py310", marks=needs_py310),
- pytest.param("tutorial002_an"),
- pytest.param("tutorial002_an_py39", marks=needs_py39),
+ pytest.param("tutorial002_an_py39"),
pytest.param("tutorial002_an_py310", marks=needs_py310),
],
)
@@ -32,34 +30,17 @@ def test_endpoint_works(client: TestClient):
def test_exception_handler_body_access(client: TestClient):
response = client.post("/", json={"numbers": [1, 2, 3]})
- assert response.json() == IsDict(
- {
- "detail": {
- "errors": [
- {
- "type": "list_type",
- "loc": ["body"],
- "msg": "Input should be a valid list",
- "input": {"numbers": [1, 2, 3]},
- }
- ],
- # httpx 0.28.0 switches to compact JSON https://github.com/encode/httpx/issues/3363
- "body": IsOneOf('{"numbers": [1, 2, 3]}', '{"numbers":[1,2,3]}'),
- }
+ assert response.json() == {
+ "detail": {
+ "errors": [
+ {
+ "type": "list_type",
+ "loc": ["body"],
+ "msg": "Input should be a valid list",
+ "input": {"numbers": [1, 2, 3]},
+ }
+ ],
+ # httpx 0.28.0 switches to compact JSON https://github.com/encode/httpx/issues/3363
+ "body": IsOneOf('{"numbers": [1, 2, 3]}', '{"numbers":[1,2,3]}'),
}
- ) | IsDict(
- # TODO: remove when deprecating Pydantic v1
- {
- "detail": {
- # httpx 0.28.0 switches to compact JSON https://github.com/encode/httpx/issues/3363
- "body": IsOneOf('{"numbers": [1, 2, 3]}', '{"numbers":[1,2,3]}'),
- "errors": [
- {
- "loc": ["body"],
- "msg": "value is not a valid list",
- "type": "type_error.list",
- }
- ],
- }
- }
- )
+ }
diff --git a/tests/test_tutorial/test_custom_request_and_route/test_tutorial003.py b/tests/test_tutorial/test_custom_request_and_route/test_tutorial003.py
index 9e895b2daf..6cad7bd3f0 100644
--- a/tests/test_tutorial/test_custom_request_and_route/test_tutorial003.py
+++ b/tests/test_tutorial/test_custom_request_and_route/test_tutorial003.py
@@ -9,7 +9,7 @@ from tests.utils import needs_py310
@pytest.fixture(
name="client",
params=[
- pytest.param("tutorial003"),
+ pytest.param("tutorial003_py39"),
pytest.param("tutorial003_py310", marks=needs_py310),
],
)
diff --git a/tests/test_tutorial/test_custom_response/test_tutorial001.py b/tests/test_tutorial/test_custom_response/test_tutorial001.py
index fc83624673..f1d2accef2 100644
--- a/tests/test_tutorial/test_custom_response/test_tutorial001.py
+++ b/tests/test_tutorial/test_custom_response/test_tutorial001.py
@@ -1,17 +1,29 @@
+import importlib
+
+import pytest
from fastapi.testclient import TestClient
-from docs_src.custom_response.tutorial001 import app
-client = TestClient(app)
+@pytest.fixture(
+ name="client",
+ params=[
+ pytest.param("tutorial001_py39"),
+ pytest.param("tutorial010_py39"),
+ ],
+)
+def get_client(request: pytest.FixtureRequest):
+ mod = importlib.import_module(f"docs_src.custom_response.{request.param}")
+ client = TestClient(mod.app)
+ return client
-def test_get_custom_response():
+def test_get_custom_response(client: TestClient):
response = client.get("/items/")
assert response.status_code == 200, response.text
assert response.json() == [{"item_id": "Foo"}]
-def test_openapi_schema():
+def test_openapi_schema(client: TestClient):
response = client.get("/openapi.json")
assert response.status_code == 200, response.text
assert response.json() == {
diff --git a/tests/test_tutorial/test_custom_response/test_tutorial001b.py b/tests/test_tutorial/test_custom_response/test_tutorial001b.py
index 91e5c501e3..3337f47d5f 100644
--- a/tests/test_tutorial/test_custom_response/test_tutorial001b.py
+++ b/tests/test_tutorial/test_custom_response/test_tutorial001b.py
@@ -1,6 +1,6 @@
from fastapi.testclient import TestClient
-from docs_src.custom_response.tutorial001b import app
+from docs_src.custom_response.tutorial001b_py39 import app
client = TestClient(app)
diff --git a/tests/test_tutorial/test_custom_response/test_tutorial002_tutorial003_tutorial004.py b/tests/test_tutorial/test_custom_response/test_tutorial002_tutorial003_tutorial004.py
new file mode 100644
index 0000000000..22e2e02540
--- /dev/null
+++ b/tests/test_tutorial/test_custom_response/test_tutorial002_tutorial003_tutorial004.py
@@ -0,0 +1,68 @@
+import importlib
+
+import pytest
+from fastapi.testclient import TestClient
+
+
+@pytest.fixture(
+ name="mod_name",
+ params=[
+ pytest.param("tutorial002_py39"),
+ pytest.param("tutorial003_py39"),
+ pytest.param("tutorial004_py39"),
+ ],
+)
+def get_mod_name(request: pytest.FixtureRequest) -> str:
+ return request.param
+
+
+@pytest.fixture(name="client")
+def get_client(mod_name: str) -> TestClient:
+ mod = importlib.import_module(f"docs_src.custom_response.{mod_name}")
+ return TestClient(mod.app)
+
+
+html_contents = """
+
+
+ Some HTML in here
+
+
+ Look ma! HTML!
+
+
+ """
+
+
+def test_get_custom_response(client: TestClient):
+ response = client.get("/items/")
+ assert response.status_code == 200, response.text
+ assert response.text == html_contents
+
+
+def test_openapi_schema(client: TestClient, mod_name: str):
+ if mod_name.startswith("tutorial003"):
+ response_content = {"application/json": {"schema": {}}}
+ else:
+ response_content = {"text/html": {"schema": {"type": "string"}}}
+
+ response = client.get("/openapi.json")
+ assert response.status_code == 200, response.text
+ assert response.json() == {
+ "openapi": "3.1.0",
+ "info": {"title": "FastAPI", "version": "0.1.0"},
+ "paths": {
+ "/items/": {
+ "get": {
+ "responses": {
+ "200": {
+ "description": "Successful Response",
+ "content": response_content,
+ }
+ },
+ "summary": "Read Items",
+ "operationId": "read_items_items__get",
+ }
+ }
+ },
+ }
diff --git a/tests/test_tutorial/test_custom_response/test_tutorial005.py b/tests/test_tutorial/test_custom_response/test_tutorial005.py
index 889bf3e929..fea105c28e 100644
--- a/tests/test_tutorial/test_custom_response/test_tutorial005.py
+++ b/tests/test_tutorial/test_custom_response/test_tutorial005.py
@@ -1,6 +1,6 @@
from fastapi.testclient import TestClient
-from docs_src.custom_response.tutorial005 import app
+from docs_src.custom_response.tutorial005_py39 import app
client = TestClient(app)
diff --git a/tests/test_tutorial/test_custom_response/test_tutorial006.py b/tests/test_tutorial/test_custom_response/test_tutorial006.py
index 2d0a2cd3f6..e9e6ca1086 100644
--- a/tests/test_tutorial/test_custom_response/test_tutorial006.py
+++ b/tests/test_tutorial/test_custom_response/test_tutorial006.py
@@ -1,6 +1,6 @@
from fastapi.testclient import TestClient
-from docs_src.custom_response.tutorial006 import app
+from docs_src.custom_response.tutorial006_py39 import app
client = TestClient(app)
diff --git a/tests/test_tutorial/test_custom_response/test_tutorial006b.py b/tests/test_tutorial/test_custom_response/test_tutorial006b.py
index 1739fd4570..7ca727d2cd 100644
--- a/tests/test_tutorial/test_custom_response/test_tutorial006b.py
+++ b/tests/test_tutorial/test_custom_response/test_tutorial006b.py
@@ -1,6 +1,6 @@
from fastapi.testclient import TestClient
-from docs_src.custom_response.tutorial006b import app
+from docs_src.custom_response.tutorial006b_py39 import app
client = TestClient(app)
diff --git a/tests/test_tutorial/test_custom_response/test_tutorial006c.py b/tests/test_tutorial/test_custom_response/test_tutorial006c.py
index 2675f2a93c..e3f76c8403 100644
--- a/tests/test_tutorial/test_custom_response/test_tutorial006c.py
+++ b/tests/test_tutorial/test_custom_response/test_tutorial006c.py
@@ -1,6 +1,6 @@
from fastapi.testclient import TestClient
-from docs_src.custom_response.tutorial006c import app
+from docs_src.custom_response.tutorial006c_py39 import app
client = TestClient(app)
diff --git a/tests/test_tutorial/test_custom_response/test_tutorial007.py b/tests/test_tutorial/test_custom_response/test_tutorial007.py
index 4ede820b94..a62476ec14 100644
--- a/tests/test_tutorial/test_custom_response/test_tutorial007.py
+++ b/tests/test_tutorial/test_custom_response/test_tutorial007.py
@@ -1,6 +1,6 @@
from fastapi.testclient import TestClient
-from docs_src.custom_response.tutorial007 import app
+from docs_src.custom_response.tutorial007_py39 import app
client = TestClient(app)
diff --git a/tests/test_tutorial/test_custom_response/test_tutorial008.py b/tests/test_tutorial/test_custom_response/test_tutorial008.py
index 10d88a5948..d9fe61f539 100644
--- a/tests/test_tutorial/test_custom_response/test_tutorial008.py
+++ b/tests/test_tutorial/test_custom_response/test_tutorial008.py
@@ -2,15 +2,15 @@ from pathlib import Path
from fastapi.testclient import TestClient
-from docs_src.custom_response import tutorial008
-from docs_src.custom_response.tutorial008 import app
+from docs_src.custom_response import tutorial008_py39
+from docs_src.custom_response.tutorial008_py39 import app
client = TestClient(app)
def test_get(tmp_path: Path):
file_path: Path = tmp_path / "large-video-file.mp4"
- tutorial008.some_file_path = str(file_path)
+ tutorial008_py39.some_file_path = str(file_path)
test_content = b"Fake video bytes"
file_path.write_bytes(test_content)
response = client.get("/")
diff --git a/tests/test_tutorial/test_custom_response/test_tutorial009.py b/tests/test_tutorial/test_custom_response/test_tutorial009.py
index ac20f89e67..cb6a514be6 100644
--- a/tests/test_tutorial/test_custom_response/test_tutorial009.py
+++ b/tests/test_tutorial/test_custom_response/test_tutorial009.py
@@ -2,15 +2,15 @@ from pathlib import Path
from fastapi.testclient import TestClient
-from docs_src.custom_response import tutorial009
-from docs_src.custom_response.tutorial009 import app
+from docs_src.custom_response import tutorial009_py39
+from docs_src.custom_response.tutorial009_py39 import app
client = TestClient(app)
def test_get(tmp_path: Path):
file_path: Path = tmp_path / "large-video-file.mp4"
- tutorial009.some_file_path = str(file_path)
+ tutorial009_py39.some_file_path = str(file_path)
test_content = b"Fake video bytes"
file_path.write_bytes(test_content)
response = client.get("/")
diff --git a/tests/test_tutorial/test_custom_response/test_tutorial009b.py b/tests/test_tutorial/test_custom_response/test_tutorial009b.py
index 4f56e2f3fe..9918bdb1ac 100644
--- a/tests/test_tutorial/test_custom_response/test_tutorial009b.py
+++ b/tests/test_tutorial/test_custom_response/test_tutorial009b.py
@@ -2,15 +2,15 @@ from pathlib import Path
from fastapi.testclient import TestClient
-from docs_src.custom_response import tutorial009b
-from docs_src.custom_response.tutorial009b import app
+from docs_src.custom_response import tutorial009b_py39
+from docs_src.custom_response.tutorial009b_py39 import app
client = TestClient(app)
def test_get(tmp_path: Path):
file_path: Path = tmp_path / "large-video-file.mp4"
- tutorial009b.some_file_path = str(file_path)
+ tutorial009b_py39.some_file_path = str(file_path)
test_content = b"Fake video bytes"
file_path.write_bytes(test_content)
response = client.get("/")
diff --git a/tests/test_tutorial/test_custom_response/test_tutorial009c.py b/tests/test_tutorial/test_custom_response/test_tutorial009c.py
index 23c711abe9..efc3a6b4a0 100644
--- a/tests/test_tutorial/test_custom_response/test_tutorial009c.py
+++ b/tests/test_tutorial/test_custom_response/test_tutorial009c.py
@@ -1,6 +1,6 @@
from fastapi.testclient import TestClient
-from docs_src.custom_response.tutorial009c import app
+from docs_src.custom_response.tutorial009c_py39 import app
client = TestClient(app)
diff --git a/tests/test_tutorial/test_dataclasses/test_tutorial001.py b/tests/test_tutorial/test_dataclasses/test_tutorial001.py
index b36dee7684..4683062f59 100644
--- a/tests/test_tutorial/test_dataclasses/test_tutorial001.py
+++ b/tests/test_tutorial/test_dataclasses/test_tutorial001.py
@@ -1,7 +1,6 @@
import importlib
import pytest
-from dirty_equals import IsDict
from fastapi.testclient import TestClient
from tests.utils import needs_py310
@@ -10,12 +9,12 @@ from tests.utils import needs_py310
@pytest.fixture(
name="client",
params=[
- pytest.param("tutorial001"),
+ pytest.param("tutorial001_py39"),
pytest.param("tutorial001_py310", marks=needs_py310),
],
)
def get_client(request: pytest.FixtureRequest):
- mod = importlib.import_module(f"docs_src.dataclasses.{request.param}")
+ mod = importlib.import_module(f"docs_src.dataclasses_.{request.param}")
client = TestClient(mod.app)
client.headers.clear()
@@ -36,29 +35,16 @@ def test_post_item(client: TestClient):
def test_post_invalid_item(client: TestClient):
response = client.post("/items/", json={"name": "Foo", "price": "invalid price"})
assert response.status_code == 422
- assert response.json() == IsDict(
- {
- "detail": [
- {
- "type": "float_parsing",
- "loc": ["body", "price"],
- "msg": "Input should be a valid number, unable to parse string as a number",
- "input": "invalid price",
- }
- ]
- }
- ) | IsDict(
- # TODO: remove when deprecating Pydantic v1
- {
- "detail": [
- {
- "loc": ["body", "price"],
- "msg": "value is not a valid float",
- "type": "type_error.float",
- }
- ]
- }
- )
+ assert response.json() == {
+ "detail": [
+ {
+ "type": "float_parsing",
+ "loc": ["body", "price"],
+ "msg": "Input should be a valid number, unable to parse string as a number",
+ "input": "invalid price",
+ }
+ ]
+ }
def test_openapi_schema(client: TestClient):
@@ -119,26 +105,14 @@ def test_openapi_schema(client: TestClient):
"properties": {
"name": {"title": "Name", "type": "string"},
"price": {"title": "Price", "type": "number"},
- "description": IsDict(
- {
- "title": "Description",
- "anyOf": [{"type": "string"}, {"type": "null"}],
- }
- )
- | IsDict(
- # TODO: remove when deprecating Pydantic v1
- {"title": "Description", "type": "string"}
- ),
- "tax": IsDict(
- {
- "title": "Tax",
- "anyOf": [{"type": "number"}, {"type": "null"}],
- }
- )
- | IsDict(
- # TODO: remove when deprecating Pydantic v1
- {"title": "Tax", "type": "number"}
- ),
+ "description": {
+ "title": "Description",
+ "anyOf": [{"type": "string"}, {"type": "null"}],
+ },
+ "tax": {
+ "title": "Tax",
+ "anyOf": [{"type": "number"}, {"type": "null"}],
+ },
},
},
"ValidationError": {
diff --git a/tests/test_tutorial/test_dataclasses/test_tutorial002.py b/tests/test_tutorial/test_dataclasses/test_tutorial002.py
index baaea45d8f..210d743bb8 100644
--- a/tests/test_tutorial/test_dataclasses/test_tutorial002.py
+++ b/tests/test_tutorial/test_dataclasses/test_tutorial002.py
@@ -1,22 +1,21 @@
import importlib
import pytest
-from dirty_equals import IsDict, IsOneOf
from fastapi.testclient import TestClient
+from inline_snapshot import snapshot
-from tests.utils import needs_py39, needs_py310
+from tests.utils import needs_py310
@pytest.fixture(
name="client",
params=[
- pytest.param("tutorial002"),
- pytest.param("tutorial002_py39", marks=needs_py39),
+ pytest.param("tutorial002_py39"),
pytest.param("tutorial002_py310", marks=needs_py310),
],
)
def get_client(request: pytest.FixtureRequest):
- mod = importlib.import_module(f"docs_src.dataclasses.{request.param}")
+ mod = importlib.import_module(f"docs_src.dataclasses_.{request.param}")
client = TestClient(mod.app)
client.headers.clear()
@@ -38,77 +37,53 @@ def test_get_item(client: TestClient):
def test_openapi_schema(client: TestClient):
response = client.get("/openapi.json")
assert response.status_code == 200
- assert response.json() == {
- "openapi": "3.1.0",
- "info": {"title": "FastAPI", "version": "0.1.0"},
- "paths": {
- "/items/next": {
- "get": {
- "summary": "Read Next Item",
- "operationId": "read_next_item_items_next_get",
- "responses": {
- "200": {
- "description": "Successful Response",
- "content": {
- "application/json": {
- "schema": {"$ref": "#/components/schemas/Item"}
- }
- },
- }
- },
+ assert response.json() == snapshot(
+ {
+ "openapi": "3.1.0",
+ "info": {"title": "FastAPI", "version": "0.1.0"},
+ "paths": {
+ "/items/next": {
+ "get": {
+ "summary": "Read Next Item",
+ "operationId": "read_next_item_items_next_get",
+ "responses": {
+ "200": {
+ "description": "Successful Response",
+ "content": {
+ "application/json": {
+ "schema": {"$ref": "#/components/schemas/Item"}
+ }
+ },
+ }
+ },
+ }
}
- }
- },
- "components": {
- "schemas": {
- "Item": {
- "title": "Item",
- "required": IsOneOf(
- ["name", "price", "tags", "description", "tax"],
- # TODO: remove when deprecating Pydantic v1
- ["name", "price"],
- ),
- "type": "object",
- "properties": {
- "name": {"title": "Name", "type": "string"},
- "price": {"title": "Price", "type": "number"},
- "tags": IsDict(
- {
+ },
+ "components": {
+ "schemas": {
+ "Item": {
+ "title": "Item",
+ "required": ["name", "price"],
+ "type": "object",
+ "properties": {
+ "name": {"title": "Name", "type": "string"},
+ "price": {"title": "Price", "type": "number"},
+ "tags": {
"title": "Tags",
"type": "array",
"items": {"type": "string"},
- }
- )
- | IsDict(
- # TODO: remove when deprecating Pydantic v1
- {
- "title": "Tags",
- "type": "array",
- "items": {"type": "string"},
- }
- ),
- "description": IsDict(
- {
+ },
+ "description": {
"title": "Description",
"anyOf": [{"type": "string"}, {"type": "null"}],
- }
- )
- | IsDict(
- # TODO: remove when deprecating Pydantic v1
- {"title": "Description", "type": "string"}
- ),
- "tax": IsDict(
- {
+ },
+ "tax": {
"title": "Tax",
"anyOf": [{"type": "number"}, {"type": "null"}],
- }
- )
- | IsDict(
- # TODO: remove when deprecating Pydantic v1
- {"title": "Tax", "type": "number"}
- ),
- },
+ },
+ },
+ }
}
- }
- },
- }
+ },
+ }
+ )
diff --git a/tests/test_tutorial/test_dataclasses/test_tutorial003.py b/tests/test_tutorial/test_dataclasses/test_tutorial003.py
index 5728d2b6b3..a6a9fc1c7e 100644
--- a/tests/test_tutorial/test_dataclasses/test_tutorial003.py
+++ b/tests/test_tutorial/test_dataclasses/test_tutorial003.py
@@ -3,19 +3,18 @@ import importlib
import pytest
from fastapi.testclient import TestClient
-from ...utils import needs_py39, needs_py310, needs_pydanticv1, needs_pydanticv2
+from ...utils import needs_py310
@pytest.fixture(
name="client",
params=[
- pytest.param("tutorial003"),
- pytest.param("tutorial003_py39", marks=needs_py39),
+ pytest.param("tutorial003_py39"),
pytest.param("tutorial003_py310", marks=needs_py310),
],
)
def get_client(request: pytest.FixtureRequest):
- mod = importlib.import_module(f"docs_src.dataclasses.{request.param}")
+ mod = importlib.import_module(f"docs_src.dataclasses_.{request.param}")
client = TestClient(mod.app)
client.headers.clear()
@@ -68,7 +67,6 @@ def test_get_authors(client: TestClient):
]
-@needs_pydanticv2
def test_openapi_schema(client: TestClient):
response = client.get("/openapi.json")
assert response.status_code == 200
@@ -202,137 +200,3 @@ def test_openapi_schema(client: TestClient):
}
},
}
-
-
-# TODO: remove when deprecating Pydantic v1
-@needs_pydanticv1
-def test_openapi_schema_pv1(client: TestClient):
- response = client.get("/openapi.json")
- assert response.status_code == 200
- assert response.json() == {
- "openapi": "3.1.0",
- "info": {"title": "FastAPI", "version": "0.1.0"},
- "paths": {
- "/authors/{author_id}/items/": {
- "post": {
- "summary": "Create Author Items",
- "operationId": "create_author_items_authors__author_id__items__post",
- "parameters": [
- {
- "required": True,
- "schema": {"title": "Author Id", "type": "string"},
- "name": "author_id",
- "in": "path",
- }
- ],
- "requestBody": {
- "content": {
- "application/json": {
- "schema": {
- "title": "Items",
- "type": "array",
- "items": {"$ref": "#/components/schemas/Item"},
- }
- }
- },
- "required": True,
- },
- "responses": {
- "200": {
- "description": "Successful Response",
- "content": {
- "application/json": {
- "schema": {"$ref": "#/components/schemas/Author"}
- }
- },
- },
- "422": {
- "description": "Validation Error",
- "content": {
- "application/json": {
- "schema": {
- "$ref": "#/components/schemas/HTTPValidationError"
- }
- }
- },
- },
- },
- }
- },
- "/authors/": {
- "get": {
- "summary": "Get Authors",
- "operationId": "get_authors_authors__get",
- "responses": {
- "200": {
- "description": "Successful Response",
- "content": {
- "application/json": {
- "schema": {
- "title": "Response Get Authors Authors Get",
- "type": "array",
- "items": {
- "$ref": "#/components/schemas/Author"
- },
- }
- }
- },
- }
- },
- }
- },
- },
- "components": {
- "schemas": {
- "Author": {
- "title": "Author",
- "required": ["name"],
- "type": "object",
- "properties": {
- "name": {"title": "Name", "type": "string"},
- "items": {
- "title": "Items",
- "type": "array",
- "items": {"$ref": "#/components/schemas/Item"},
- },
- },
- },
- "HTTPValidationError": {
- "title": "HTTPValidationError",
- "type": "object",
- "properties": {
- "detail": {
- "title": "Detail",
- "type": "array",
- "items": {"$ref": "#/components/schemas/ValidationError"},
- }
- },
- },
- "Item": {
- "title": "Item",
- "required": ["name"],
- "type": "object",
- "properties": {
- "name": {"title": "Name", "type": "string"},
- "description": {"title": "Description", "type": "string"},
- },
- },
- "ValidationError": {
- "title": "ValidationError",
- "required": ["loc", "msg", "type"],
- "type": "object",
- "properties": {
- "loc": {
- "title": "Location",
- "type": "array",
- "items": {
- "anyOf": [{"type": "string"}, {"type": "integer"}]
- },
- },
- "msg": {"title": "Message", "type": "string"},
- "type": {"title": "Error Type", "type": "string"},
- },
- },
- }
- },
- }
diff --git a/tests/test_tutorial/test_debugging/__init__.py b/tests/test_tutorial/test_debugging/__init__.py
new file mode 100644
index 0000000000..e69de29bb2
diff --git a/tests/test_tutorial/test_debugging/test_tutorial001.py b/tests/test_tutorial/test_debugging/test_tutorial001.py
new file mode 100644
index 0000000000..cf62c3b194
--- /dev/null
+++ b/tests/test_tutorial/test_debugging/test_tutorial001.py
@@ -0,0 +1,64 @@
+import importlib
+import runpy
+import sys
+import unittest
+
+import pytest
+from fastapi.testclient import TestClient
+
+MOD_NAME = "docs_src.debugging.tutorial001_py39"
+
+
+@pytest.fixture(name="client")
+def get_client():
+ mod = importlib.import_module(MOD_NAME)
+ client = TestClient(mod.app)
+ return client
+
+
+def test_uvicorn_run_is_not_called_on_import():
+ if sys.modules.get(MOD_NAME):
+ del sys.modules[MOD_NAME] # pragma: no cover
+ with unittest.mock.patch("uvicorn.run") as uvicorn_run_mock:
+ importlib.import_module(MOD_NAME)
+ uvicorn_run_mock.assert_not_called()
+
+
+def test_get_root(client: TestClient):
+ response = client.get("/")
+ assert response.status_code == 200
+ assert response.json() == {"hello world": "ba"}
+
+
+def test_uvicorn_run_called_when_run_as_main(): # Just for coverage
+ if sys.modules.get(MOD_NAME):
+ del sys.modules[MOD_NAME]
+ with unittest.mock.patch("uvicorn.run") as uvicorn_run_mock:
+ runpy.run_module(MOD_NAME, run_name="__main__")
+
+ uvicorn_run_mock.assert_called_once_with(
+ unittest.mock.ANY, host="0.0.0.0", port=8000
+ )
+
+
+def test_openapi_schema(client: TestClient):
+ response = client.get("/openapi.json")
+ assert response.status_code == 200
+ assert response.json() == {
+ "openapi": "3.1.0",
+ "info": {"title": "FastAPI", "version": "0.1.0"},
+ "paths": {
+ "/": {
+ "get": {
+ "summary": "Root",
+ "operationId": "root__get",
+ "responses": {
+ "200": {
+ "description": "Successful Response",
+ "content": {"application/json": {"schema": {}}},
+ },
+ },
+ }
+ }
+ },
+ }
diff --git a/tests/test_tutorial/test_dependencies/test_tutorial001.py b/tests/test_tutorial/test_dependencies/test_tutorial001_tutorial001_02.py
similarity index 84%
rename from tests/test_tutorial/test_dependencies/test_tutorial001.py
rename to tests/test_tutorial/test_dependencies/test_tutorial001_tutorial001_02.py
index ed9944912e..50d7c4108c 100644
--- a/tests/test_tutorial/test_dependencies/test_tutorial001.py
+++ b/tests/test_tutorial/test_dependencies/test_tutorial001_tutorial001_02.py
@@ -1,20 +1,20 @@
import importlib
import pytest
-from dirty_equals import IsDict
from fastapi.testclient import TestClient
-from ...utils import needs_py39, needs_py310
+from ...utils import needs_py310
@pytest.fixture(
name="client",
params=[
- "tutorial001",
+ pytest.param("tutorial001_py39"),
pytest.param("tutorial001_py310", marks=needs_py310),
- "tutorial001_an",
- pytest.param("tutorial001_an_py39", marks=needs_py39),
+ pytest.param("tutorial001_an_py39"),
pytest.param("tutorial001_an_py310", marks=needs_py310),
+ pytest.param("tutorial001_02_an_py39"),
+ pytest.param("tutorial001_02_an_py310", marks=needs_py310),
],
)
def get_client(request: pytest.FixtureRequest):
@@ -70,16 +70,10 @@ def test_openapi_schema(client: TestClient):
"parameters": [
{
"required": False,
- "schema": IsDict(
- {
- "anyOf": [{"type": "string"}, {"type": "null"}],
- "title": "Q",
- }
- )
- | IsDict(
- # TODO: remove when deprecating Pydantic v1
- {"title": "Q", "type": "string"}
- ),
+ "schema": {
+ "anyOf": [{"type": "string"}, {"type": "null"}],
+ "title": "Q",
+ },
"name": "q",
"in": "query",
},
@@ -129,16 +123,10 @@ def test_openapi_schema(client: TestClient):
"parameters": [
{
"required": False,
- "schema": IsDict(
- {
- "anyOf": [{"type": "string"}, {"type": "null"}],
- "title": "Q",
- }
- )
- | IsDict(
- # TODO: remove when deprecating Pydantic v1
- {"title": "Q", "type": "string"}
- ),
+ "schema": {
+ "anyOf": [{"type": "string"}, {"type": "null"}],
+ "title": "Q",
+ },
"name": "q",
"in": "query",
},
diff --git a/tests/test_tutorial/test_dependencies/test_tutorial004.py b/tests/test_tutorial/test_dependencies/test_tutorial002_tutorial003_tutorial004.py
similarity index 87%
rename from tests/test_tutorial/test_dependencies/test_tutorial004.py
rename to tests/test_tutorial/test_dependencies/test_tutorial002_tutorial003_tutorial004.py
index 8221c83d44..f09d6f268d 100644
--- a/tests/test_tutorial/test_dependencies/test_tutorial004.py
+++ b/tests/test_tutorial/test_dependencies/test_tutorial002_tutorial003_tutorial004.py
@@ -1,19 +1,25 @@
import importlib
import pytest
-from dirty_equals import IsDict
from fastapi.testclient import TestClient
-from ...utils import needs_py39, needs_py310
+from ...utils import needs_py310
@pytest.fixture(
name="client",
params=[
- "tutorial004",
+ pytest.param("tutorial002_py39"),
+ pytest.param("tutorial002_py310", marks=needs_py310),
+ pytest.param("tutorial002_an_py39"),
+ pytest.param("tutorial002_an_py310", marks=needs_py310),
+ pytest.param("tutorial003_py39"),
+ pytest.param("tutorial003_py310", marks=needs_py310),
+ pytest.param("tutorial003_an_py39"),
+ pytest.param("tutorial003_an_py310", marks=needs_py310),
+ pytest.param("tutorial004_py39"),
pytest.param("tutorial004_py310", marks=needs_py310),
- "tutorial004_an",
- pytest.param("tutorial004_an_py39", marks=needs_py39),
+ pytest.param("tutorial004_an_py39"),
pytest.param("tutorial004_an_py310", marks=needs_py310),
],
)
@@ -108,16 +114,10 @@ def test_openapi_schema(client: TestClient):
"parameters": [
{
"required": False,
- "schema": IsDict(
- {
- "anyOf": [{"type": "string"}, {"type": "null"}],
- "title": "Q",
- }
- )
- | IsDict(
- # TODO: remove when deprecating Pydantic v1
- {"title": "Q", "type": "string"}
- ),
+ "schema": {
+ "anyOf": [{"type": "string"}, {"type": "null"}],
+ "title": "Q",
+ },
"name": "q",
"in": "query",
},
diff --git a/tests/test_tutorial/test_dependencies/test_tutorial005.py b/tests/test_tutorial/test_dependencies/test_tutorial005.py
new file mode 100644
index 0000000000..a914936ba1
--- /dev/null
+++ b/tests/test_tutorial/test_dependencies/test_tutorial005.py
@@ -0,0 +1,139 @@
+import importlib
+
+import pytest
+from fastapi.testclient import TestClient
+
+from ...utils import needs_py310
+
+
+@pytest.fixture(
+ name="client",
+ params=[
+ pytest.param("tutorial005_py39"),
+ pytest.param("tutorial005_py310", marks=needs_py310),
+ pytest.param("tutorial005_an_py39"),
+ pytest.param("tutorial005_an_py310", marks=needs_py310),
+ ],
+)
+def get_client(request: pytest.FixtureRequest):
+ mod = importlib.import_module(f"docs_src.dependencies.{request.param}")
+
+ client = TestClient(mod.app)
+ return client
+
+
+@pytest.mark.parametrize(
+ "path,cookie,expected_status,expected_response",
+ [
+ (
+ "/items",
+ "from_cookie",
+ 200,
+ {"q_or_cookie": "from_cookie"},
+ ),
+ (
+ "/items?q=foo",
+ "from_cookie",
+ 200,
+ {"q_or_cookie": "foo"},
+ ),
+ (
+ "/items",
+ None,
+ 200,
+ {"q_or_cookie": None},
+ ),
+ ],
+)
+def test_get(path, cookie, expected_status, expected_response, client: TestClient):
+ if cookie is not None:
+ client.cookies.set("last_query", cookie)
+ else:
+ client.cookies.clear()
+ response = client.get(path)
+ assert response.status_code == expected_status
+ assert response.json() == expected_response
+
+
+def test_openapi_schema(client: TestClient):
+ response = client.get("/openapi.json")
+ assert response.status_code == 200, response.text
+ assert response.json() == {
+ "openapi": "3.1.0",
+ "info": {"title": "FastAPI", "version": "0.1.0"},
+ "paths": {
+ "/items/": {
+ "get": {
+ "responses": {
+ "200": {
+ "description": "Successful Response",
+ "content": {"application/json": {"schema": {}}},
+ },
+ "422": {
+ "description": "Validation Error",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/HTTPValidationError"
+ }
+ }
+ },
+ },
+ },
+ "summary": "Read Query",
+ "operationId": "read_query_items__get",
+ "parameters": [
+ {
+ "required": False,
+ "schema": {
+ "anyOf": [{"type": "string"}, {"type": "null"}],
+ "title": "Q",
+ },
+ "name": "q",
+ "in": "query",
+ },
+ {
+ "required": False,
+ "schema": {
+ "anyOf": [{"type": "string"}, {"type": "null"}],
+ "title": "Last Query",
+ },
+ "name": "last_query",
+ "in": "cookie",
+ },
+ ],
+ }
+ }
+ },
+ "components": {
+ "schemas": {
+ "ValidationError": {
+ "title": "ValidationError",
+ "required": ["loc", "msg", "type"],
+ "type": "object",
+ "properties": {
+ "loc": {
+ "title": "Location",
+ "type": "array",
+ "items": {
+ "anyOf": [{"type": "string"}, {"type": "integer"}]
+ },
+ },
+ "msg": {"title": "Message", "type": "string"},
+ "type": {"title": "Error Type", "type": "string"},
+ },
+ },
+ "HTTPValidationError": {
+ "title": "HTTPValidationError",
+ "type": "object",
+ "properties": {
+ "detail": {
+ "title": "Detail",
+ "type": "array",
+ "items": {"$ref": "#/components/schemas/ValidationError"},
+ }
+ },
+ },
+ }
+ },
+ }
diff --git a/tests/test_tutorial/test_dependencies/test_tutorial006.py b/tests/test_tutorial/test_dependencies/test_tutorial006.py
index 4530762f76..59202df3bf 100644
--- a/tests/test_tutorial/test_dependencies/test_tutorial006.py
+++ b/tests/test_tutorial/test_dependencies/test_tutorial006.py
@@ -1,18 +1,14 @@
import importlib
import pytest
-from dirty_equals import IsDict
from fastapi.testclient import TestClient
-from ...utils import needs_py39
-
@pytest.fixture(
name="client",
params=[
- "tutorial006",
- "tutorial006_an",
- pytest.param("tutorial006_an_py39", marks=needs_py39),
+ pytest.param("tutorial006_py39"),
+ pytest.param("tutorial006_an_py39"),
],
)
def get_client(request: pytest.FixtureRequest):
@@ -25,40 +21,22 @@ def get_client(request: pytest.FixtureRequest):
def test_get_no_headers(client: TestClient):
response = client.get("/items/")
assert response.status_code == 422, response.text
- assert response.json() == IsDict(
- {
- "detail": [
- {
- "type": "missing",
- "loc": ["header", "x-token"],
- "msg": "Field required",
- "input": None,
- },
- {
- "type": "missing",
- "loc": ["header", "x-key"],
- "msg": "Field required",
- "input": None,
- },
- ]
- }
- ) | IsDict(
- # TODO: remove when deprecating Pydantic v1
- {
- "detail": [
- {
- "loc": ["header", "x-token"],
- "msg": "field required",
- "type": "value_error.missing",
- },
- {
- "loc": ["header", "x-key"],
- "msg": "field required",
- "type": "value_error.missing",
- },
- ]
- }
- )
+ assert response.json() == {
+ "detail": [
+ {
+ "type": "missing",
+ "loc": ["header", "x-token"],
+ "msg": "Field required",
+ "input": None,
+ },
+ {
+ "type": "missing",
+ "loc": ["header", "x-key"],
+ "msg": "Field required",
+ "input": None,
+ },
+ ]
+ }
def test_get_invalid_one_header(client: TestClient):
diff --git a/tests/test_tutorial/test_dependencies/test_tutorial007.py b/tests/test_tutorial/test_dependencies/test_tutorial007.py
new file mode 100644
index 0000000000..3e188abcf6
--- /dev/null
+++ b/tests/test_tutorial/test_dependencies/test_tutorial007.py
@@ -0,0 +1,24 @@
+import asyncio
+from contextlib import asynccontextmanager
+from unittest.mock import Mock, patch
+
+from docs_src.dependencies.tutorial007_py39 import get_db
+
+
+def test_get_db(): # Just for coverage
+ async def test_async_gen():
+ cm = asynccontextmanager(get_db)
+ async with cm() as db_session:
+ return db_session
+
+ dbsession_moock = Mock()
+
+ with patch(
+ "docs_src.dependencies.tutorial007_py39.DBSession",
+ return_value=dbsession_moock,
+ create=True,
+ ):
+ value = asyncio.run(test_async_gen())
+
+ assert value is dbsession_moock
+ dbsession_moock.close.assert_called_once()
diff --git a/tests/test_tutorial/test_dependencies/test_tutorial008.py b/tests/test_tutorial/test_dependencies/test_tutorial008.py
new file mode 100644
index 0000000000..9d7377ebe4
--- /dev/null
+++ b/tests/test_tutorial/test_dependencies/test_tutorial008.py
@@ -0,0 +1,58 @@
+import importlib
+from types import ModuleType
+from typing import Annotated, Any
+from unittest.mock import Mock, patch
+
+import pytest
+from fastapi import Depends, FastAPI
+from fastapi.testclient import TestClient
+
+
+@pytest.fixture(
+ name="module",
+ params=[
+ "tutorial008_py39",
+ # Fails with `NameError: name 'DepA' is not defined`
+ pytest.param("tutorial008_an_py39", marks=pytest.mark.xfail),
+ ],
+)
+def get_module(request: pytest.FixtureRequest):
+ mod_name = f"docs_src.dependencies.{request.param}"
+ mod = importlib.import_module(mod_name)
+ return mod
+
+
+def test_get_db(module: ModuleType):
+ app = FastAPI()
+
+ @app.get("/")
+ def read_root(c: Annotated[Any, Depends(module.dependency_c)]):
+ return {"c": str(c)}
+
+ client = TestClient(app)
+
+ a_mock = Mock()
+ b_mock = Mock()
+ c_mock = Mock()
+
+ with (
+ patch(
+ f"{module.__name__}.generate_dep_a",
+ return_value=a_mock,
+ create=True,
+ ),
+ patch(
+ f"{module.__name__}.generate_dep_b",
+ return_value=b_mock,
+ create=True,
+ ),
+ patch(
+ f"{module.__name__}.generate_dep_c",
+ return_value=c_mock,
+ create=True,
+ ),
+ ):
+ response = client.get("/")
+
+ assert response.status_code == 200
+ assert response.json() == {"c": str(c_mock)}
diff --git a/tests/test_tutorial/test_dependencies/test_tutorial008b.py b/tests/test_tutorial/test_dependencies/test_tutorial008b.py
index 4d70922657..91e00b3705 100644
--- a/tests/test_tutorial/test_dependencies/test_tutorial008b.py
+++ b/tests/test_tutorial/test_dependencies/test_tutorial008b.py
@@ -3,15 +3,12 @@ import importlib
import pytest
from fastapi.testclient import TestClient
-from ...utils import needs_py39
-
@pytest.fixture(
name="client",
params=[
- "tutorial008b",
- "tutorial008b_an",
- pytest.param("tutorial008b_an_py39", marks=needs_py39),
+ pytest.param("tutorial008b_py39"),
+ pytest.param("tutorial008b_an_py39"),
],
)
def get_client(request: pytest.FixtureRequest):
diff --git a/tests/test_tutorial/test_dependencies/test_tutorial008c.py b/tests/test_tutorial/test_dependencies/test_tutorial008c.py
index 369b0a221d..aede6f8d25 100644
--- a/tests/test_tutorial/test_dependencies/test_tutorial008c.py
+++ b/tests/test_tutorial/test_dependencies/test_tutorial008c.py
@@ -5,15 +5,12 @@ import pytest
from fastapi.exceptions import FastAPIError
from fastapi.testclient import TestClient
-from ...utils import needs_py39
-
@pytest.fixture(
name="mod",
params=[
- "tutorial008c",
- "tutorial008c_an",
- pytest.param("tutorial008c_an_py39", marks=needs_py39),
+ pytest.param("tutorial008c_py39"),
+ pytest.param("tutorial008c_an_py39"),
],
)
def get_mod(request: pytest.FixtureRequest):
diff --git a/tests/test_tutorial/test_dependencies/test_tutorial008d.py b/tests/test_tutorial/test_dependencies/test_tutorial008d.py
index bc99bb3835..5477f8b953 100644
--- a/tests/test_tutorial/test_dependencies/test_tutorial008d.py
+++ b/tests/test_tutorial/test_dependencies/test_tutorial008d.py
@@ -4,15 +4,12 @@ from types import ModuleType
import pytest
from fastapi.testclient import TestClient
-from ...utils import needs_py39
-
@pytest.fixture(
name="mod",
params=[
- "tutorial008d",
- "tutorial008d_an",
- pytest.param("tutorial008d_an_py39", marks=needs_py39),
+ pytest.param("tutorial008d_py39"),
+ pytest.param("tutorial008d_an_py39"),
],
)
def get_mod(request: pytest.FixtureRequest):
diff --git a/tests/test_tutorial/test_dependencies/test_tutorial008e.py b/tests/test_tutorial/test_dependencies/test_tutorial008e.py
index 1ae9ab2cd1..c433157ea1 100644
--- a/tests/test_tutorial/test_dependencies/test_tutorial008e.py
+++ b/tests/test_tutorial/test_dependencies/test_tutorial008e.py
@@ -3,15 +3,12 @@ import importlib
import pytest
from fastapi.testclient import TestClient
-from ...utils import needs_py39
-
@pytest.fixture(
name="client",
params=[
- "tutorial008e",
- "tutorial008e_an",
- pytest.param("tutorial008e_an_py39", marks=needs_py39),
+ pytest.param("tutorial008e_py39"),
+ pytest.param("tutorial008e_an_py39"),
],
)
def get_client(request: pytest.FixtureRequest):
diff --git a/tests/test_tutorial/test_dependencies/test_tutorial010.py b/tests/test_tutorial/test_dependencies/test_tutorial010.py
new file mode 100644
index 0000000000..6d3815ada2
--- /dev/null
+++ b/tests/test_tutorial/test_dependencies/test_tutorial010.py
@@ -0,0 +1,29 @@
+from typing import Annotated, Any
+from unittest.mock import Mock, patch
+
+from fastapi import Depends, FastAPI
+from fastapi.testclient import TestClient
+
+from docs_src.dependencies.tutorial010_py39 import get_db
+
+
+def test_get_db():
+ app = FastAPI()
+
+ @app.get("/")
+ def read_root(c: Annotated[Any, Depends(get_db)]):
+ return {"c": str(c)}
+
+ client = TestClient(app)
+
+ dbsession_mock = Mock()
+
+ with patch(
+ "docs_src.dependencies.tutorial010_py39.DBSession",
+ return_value=dbsession_mock,
+ create=True,
+ ):
+ response = client.get("/")
+
+ assert response.status_code == 200
+ assert response.json() == {"c": str(dbsession_mock)}
diff --git a/tests/test_tutorial/test_dependencies/test_tutorial011.py b/tests/test_tutorial/test_dependencies/test_tutorial011.py
new file mode 100644
index 0000000000..4868254c0b
--- /dev/null
+++ b/tests/test_tutorial/test_dependencies/test_tutorial011.py
@@ -0,0 +1,120 @@
+import importlib
+
+import pytest
+from fastapi.testclient import TestClient
+
+
+@pytest.fixture(
+ name="client",
+ params=[
+ "tutorial011_py39",
+ pytest.param("tutorial011_an_py39"),
+ ],
+)
+def get_client(request: pytest.FixtureRequest):
+ mod = importlib.import_module(f"docs_src.dependencies.{request.param}")
+
+ client = TestClient(mod.app)
+ return client
+
+
+@pytest.mark.parametrize(
+ "path,expected_status,expected_response",
+ [
+ (
+ "/query-checker/",
+ 200,
+ {"fixed_content_in_query": False},
+ ),
+ (
+ "/query-checker/?q=qwerty",
+ 200,
+ {"fixed_content_in_query": False},
+ ),
+ (
+ "/query-checker/?q=foobar",
+ 200,
+ {"fixed_content_in_query": True},
+ ),
+ ],
+)
+def test_get(path, expected_status, expected_response, client: TestClient):
+ response = client.get(path)
+ assert response.status_code == expected_status
+ assert response.json() == expected_response
+
+
+def test_openapi_schema(client: TestClient):
+ response = client.get("/openapi.json")
+ assert response.status_code == 200, response.text
+ assert response.json() == {
+ "openapi": "3.1.0",
+ "info": {"title": "FastAPI", "version": "0.1.0"},
+ "paths": {
+ "/query-checker/": {
+ "get": {
+ "responses": {
+ "200": {
+ "description": "Successful Response",
+ "content": {"application/json": {"schema": {}}},
+ },
+ "422": {
+ "description": "Validation Error",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/HTTPValidationError"
+ }
+ }
+ },
+ },
+ },
+ "summary": "Read Query Check",
+ "operationId": "read_query_check_query_checker__get",
+ "parameters": [
+ {
+ "required": False,
+ "schema": {
+ "type": "string",
+ "default": "",
+ "title": "Q",
+ },
+ "name": "q",
+ "in": "query",
+ },
+ ],
+ }
+ }
+ },
+ "components": {
+ "schemas": {
+ "ValidationError": {
+ "title": "ValidationError",
+ "required": ["loc", "msg", "type"],
+ "type": "object",
+ "properties": {
+ "loc": {
+ "title": "Location",
+ "type": "array",
+ "items": {
+ "anyOf": [{"type": "string"}, {"type": "integer"}]
+ },
+ },
+ "msg": {"title": "Message", "type": "string"},
+ "type": {"title": "Error Type", "type": "string"},
+ },
+ },
+ "HTTPValidationError": {
+ "title": "HTTPValidationError",
+ "type": "object",
+ "properties": {
+ "detail": {
+ "title": "Detail",
+ "type": "array",
+ "items": {"$ref": "#/components/schemas/ValidationError"},
+ }
+ },
+ },
+ }
+ },
+ }
diff --git a/tests/test_tutorial/test_dependencies/test_tutorial012.py b/tests/test_tutorial/test_dependencies/test_tutorial012.py
index 0af17e9bc5..d5599ac73a 100644
--- a/tests/test_tutorial/test_dependencies/test_tutorial012.py
+++ b/tests/test_tutorial/test_dependencies/test_tutorial012.py
@@ -1,18 +1,14 @@
import importlib
import pytest
-from dirty_equals import IsDict
from fastapi.testclient import TestClient
-from ...utils import needs_py39
-
@pytest.fixture(
name="client",
params=[
- "tutorial012",
- "tutorial012_an",
- pytest.param("tutorial012_an_py39", marks=needs_py39),
+ pytest.param("tutorial012_py39"),
+ pytest.param("tutorial012_an_py39"),
],
)
def get_client(request: pytest.FixtureRequest):
@@ -25,79 +21,43 @@ def get_client(request: pytest.FixtureRequest):
def test_get_no_headers_items(client: TestClient):
response = client.get("/items/")
assert response.status_code == 422, response.text
- assert response.json() == IsDict(
- {
- "detail": [
- {
- "type": "missing",
- "loc": ["header", "x-token"],
- "msg": "Field required",
- "input": None,
- },
- {
- "type": "missing",
- "loc": ["header", "x-key"],
- "msg": "Field required",
- "input": None,
- },
- ]
- }
- ) | IsDict(
- # TODO: remove when deprecating Pydantic v1
- {
- "detail": [
- {
- "loc": ["header", "x-token"],
- "msg": "field required",
- "type": "value_error.missing",
- },
- {
- "loc": ["header", "x-key"],
- "msg": "field required",
- "type": "value_error.missing",
- },
- ]
- }
- )
+ assert response.json() == {
+ "detail": [
+ {
+ "type": "missing",
+ "loc": ["header", "x-token"],
+ "msg": "Field required",
+ "input": None,
+ },
+ {
+ "type": "missing",
+ "loc": ["header", "x-key"],
+ "msg": "Field required",
+ "input": None,
+ },
+ ]
+ }
def test_get_no_headers_users(client: TestClient):
response = client.get("/users/")
assert response.status_code == 422, response.text
- assert response.json() == IsDict(
- {
- "detail": [
- {
- "type": "missing",
- "loc": ["header", "x-token"],
- "msg": "Field required",
- "input": None,
- },
- {
- "type": "missing",
- "loc": ["header", "x-key"],
- "msg": "Field required",
- "input": None,
- },
- ]
- }
- ) | IsDict(
- # TODO: remove when deprecating Pydantic v1
- {
- "detail": [
- {
- "loc": ["header", "x-token"],
- "msg": "field required",
- "type": "value_error.missing",
- },
- {
- "loc": ["header", "x-key"],
- "msg": "field required",
- "type": "value_error.missing",
- },
- ]
- }
- )
+ assert response.json() == {
+ "detail": [
+ {
+ "type": "missing",
+ "loc": ["header", "x-token"],
+ "msg": "Field required",
+ "input": None,
+ },
+ {
+ "type": "missing",
+ "loc": ["header", "x-key"],
+ "msg": "Field required",
+ "input": None,
+ },
+ ]
+ }
def test_get_invalid_one_header_items(client: TestClient):
diff --git a/tests/test_tutorial/test_encoder/__init__.py b/tests/test_tutorial/test_encoder/__init__.py
new file mode 100644
index 0000000000..e69de29bb2
diff --git a/tests/test_tutorial/test_encoder/test_tutorial001.py b/tests/test_tutorial/test_encoder/test_tutorial001.py
new file mode 100644
index 0000000000..5c8ee054d8
--- /dev/null
+++ b/tests/test_tutorial/test_encoder/test_tutorial001.py
@@ -0,0 +1,208 @@
+import importlib
+from types import ModuleType
+
+import pytest
+from fastapi.testclient import TestClient
+
+from ...utils import needs_py310
+
+
+@pytest.fixture(
+ name="mod",
+ params=[
+ pytest.param("tutorial001_py39"),
+ pytest.param("tutorial001_py310", marks=needs_py310),
+ ],
+)
+def get_module(request: pytest.FixtureRequest):
+ module = importlib.import_module(f"docs_src.encoder.{request.param}")
+ return module
+
+
+@pytest.fixture(name="client")
+def get_client(mod: ModuleType):
+ client = TestClient(mod.app)
+ return client
+
+
+def test_put(client: TestClient, mod: ModuleType):
+ fake_db = mod.fake_db
+
+ response = client.put(
+ "/items/123",
+ json={
+ "title": "Foo",
+ "timestamp": "2023-01-01T12:00:00",
+ "description": "An optional description",
+ },
+ )
+ assert response.status_code == 200
+ assert "123" in fake_db
+ assert fake_db["123"] == {
+ "title": "Foo",
+ "timestamp": "2023-01-01T12:00:00",
+ "description": "An optional description",
+ }
+
+
+def test_put_invalid_data(client: TestClient, mod: ModuleType):
+ fake_db = mod.fake_db
+
+ response = client.put(
+ "/items/345",
+ json={
+ "title": "Foo",
+ "timestamp": "not a date",
+ },
+ )
+ assert response.status_code == 422
+ assert response.json() == {
+ "detail": [
+ {
+ "loc": ["body", "timestamp"],
+ "msg": "Input should be a valid datetime or date, invalid character in year",
+ "type": "datetime_from_date_parsing",
+ "input": "not a date",
+ "ctx": {"error": "invalid character in year"},
+ }
+ ]
+ }
+ assert "345" not in fake_db
+
+
+def test_openapi_schema(client: TestClient):
+ response = client.get("/openapi.json")
+ assert response.status_code == 200
+ assert response.json() == {
+ "openapi": "3.1.0",
+ "info": {"title": "FastAPI", "version": "0.1.0"},
+ "paths": {
+ "/items/{id}": {
+ "put": {
+ "operationId": "update_item_items__id__put",
+ "parameters": [
+ {
+ "in": "path",
+ "name": "id",
+ "required": True,
+ "schema": {
+ "title": "Id",
+ "type": "string",
+ },
+ },
+ ],
+ "requestBody": {
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/Item",
+ },
+ },
+ },
+ "required": True,
+ },
+ "responses": {
+ "200": {
+ "content": {
+ "application/json": {
+ "schema": {},
+ },
+ },
+ "description": "Successful Response",
+ },
+ "422": {
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/HTTPValidationError",
+ },
+ },
+ },
+ "description": "Validation Error",
+ },
+ },
+ "summary": "Update Item",
+ },
+ },
+ },
+ "components": {
+ "schemas": {
+ "HTTPValidationError": {
+ "properties": {
+ "detail": {
+ "items": {
+ "$ref": "#/components/schemas/ValidationError",
+ },
+ "title": "Detail",
+ "type": "array",
+ },
+ },
+ "title": "HTTPValidationError",
+ "type": "object",
+ },
+ "Item": {
+ "properties": {
+ "description": {
+ "anyOf": [
+ {
+ "type": "string",
+ },
+ {
+ "type": "null",
+ },
+ ],
+ "title": "Description",
+ },
+ "timestamp": {
+ "format": "date-time",
+ "title": "Timestamp",
+ "type": "string",
+ },
+ "title": {
+ "title": "Title",
+ "type": "string",
+ },
+ },
+ "required": [
+ "title",
+ "timestamp",
+ ],
+ "title": "Item",
+ "type": "object",
+ },
+ "ValidationError": {
+ "properties": {
+ "loc": {
+ "items": {
+ "anyOf": [
+ {
+ "type": "string",
+ },
+ {
+ "type": "integer",
+ },
+ ],
+ },
+ "title": "Location",
+ "type": "array",
+ },
+ "msg": {
+ "title": "Message",
+ "type": "string",
+ },
+ "type": {
+ "title": "Error Type",
+ "type": "string",
+ },
+ },
+ "required": [
+ "loc",
+ "msg",
+ "type",
+ ],
+ "title": "ValidationError",
+ "type": "object",
+ },
+ },
+ },
+ }
diff --git a/tests/test_tutorial/test_events/test_tutorial001.py b/tests/test_tutorial/test_events/test_tutorial001.py
index f65b92d127..5fe99d50df 100644
--- a/tests/test_tutorial/test_events/test_tutorial001.py
+++ b/tests/test_tutorial/test_events/test_tutorial001.py
@@ -6,7 +6,7 @@ from fastapi.testclient import TestClient
@pytest.fixture(name="app", scope="module")
def get_app():
with pytest.warns(DeprecationWarning):
- from docs_src.events.tutorial001 import app
+ from docs_src.events.tutorial001_py39 import app
yield app
diff --git a/tests/test_tutorial/test_events/test_tutorial002.py b/tests/test_tutorial/test_events/test_tutorial002.py
index 137294d737..0612899b55 100644
--- a/tests/test_tutorial/test_events/test_tutorial002.py
+++ b/tests/test_tutorial/test_events/test_tutorial002.py
@@ -6,7 +6,7 @@ from fastapi.testclient import TestClient
@pytest.fixture(name="app", scope="module")
def get_app():
with pytest.warns(DeprecationWarning):
- from docs_src.events.tutorial002 import app
+ from docs_src.events.tutorial002_py39 import app
yield app
diff --git a/tests/test_tutorial/test_events/test_tutorial003.py b/tests/test_tutorial/test_events/test_tutorial003.py
index 0ad1a1f8b2..38710edfea 100644
--- a/tests/test_tutorial/test_events/test_tutorial003.py
+++ b/tests/test_tutorial/test_events/test_tutorial003.py
@@ -1,6 +1,6 @@
from fastapi.testclient import TestClient
-from docs_src.events.tutorial003 import (
+from docs_src.events.tutorial003_py39 import (
app,
fake_answer_to_everything_ml_model,
ml_models,
diff --git a/tests/test_tutorial/test_extending_openapi/test_tutorial001.py b/tests/test_tutorial/test_extending_openapi/test_tutorial001.py
index a85a313501..83ecb300ee 100644
--- a/tests/test_tutorial/test_extending_openapi/test_tutorial001.py
+++ b/tests/test_tutorial/test_extending_openapi/test_tutorial001.py
@@ -1,6 +1,6 @@
from fastapi.testclient import TestClient
-from docs_src.extending_openapi.tutorial001 import app
+from docs_src.extending_openapi.tutorial001_py39 import app
client = TestClient(app)
diff --git a/tests/test_tutorial/test_extra_data_types/test_tutorial001.py b/tests/test_tutorial/test_extra_data_types/test_tutorial001.py
index b816c9cab5..5479e29252 100644
--- a/tests/test_tutorial/test_extra_data_types/test_tutorial001.py
+++ b/tests/test_tutorial/test_extra_data_types/test_tutorial001.py
@@ -1,19 +1,18 @@
import importlib
import pytest
-from dirty_equals import IsDict
from fastapi.testclient import TestClient
+from inline_snapshot import snapshot
-from ...utils import needs_py39, needs_py310
+from ...utils import needs_py310
@pytest.fixture(
name="client",
params=[
- "tutorial001",
+ pytest.param("tutorial001_py39"),
pytest.param("tutorial001_py310", marks=needs_py310),
- "tutorial001_an",
- pytest.param("tutorial001_an_py39", marks=needs_py39),
+ pytest.param("tutorial001_an_py39"),
pytest.param("tutorial001_an_py310", marks=needs_py310),
],
)
@@ -48,146 +47,117 @@ def test_extra_types(client: TestClient):
def test_openapi_schema(client: TestClient):
response = client.get("/openapi.json")
assert response.status_code == 200, response.text
- assert response.json() == {
- "openapi": "3.1.0",
- "info": {"title": "FastAPI", "version": "0.1.0"},
- "paths": {
- "/items/{item_id}": {
- "put": {
- "responses": {
- "200": {
- "description": "Successful Response",
- "content": {"application/json": {"schema": {}}},
+ assert response.json() == snapshot(
+ {
+ "openapi": "3.1.0",
+ "info": {"title": "FastAPI", "version": "0.1.0"},
+ "paths": {
+ "/items/{item_id}": {
+ "put": {
+ "responses": {
+ "200": {
+ "description": "Successful Response",
+ "content": {"application/json": {"schema": {}}},
+ },
+ "422": {
+ "description": "Validation Error",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/HTTPValidationError"
+ }
+ }
+ },
+ },
},
- "422": {
- "description": "Validation Error",
+ "summary": "Read Items",
+ "operationId": "read_items_items__item_id__put",
+ "parameters": [
+ {
+ "required": True,
+ "schema": {
+ "title": "Item Id",
+ "type": "string",
+ "format": "uuid",
+ },
+ "name": "item_id",
+ "in": "path",
+ }
+ ],
+ "requestBody": {
+ "required": True,
"content": {
"application/json": {
"schema": {
- "$ref": "#/components/schemas/HTTPValidationError"
+ "$ref": "#/components/schemas/Body_read_items_items__item_id__put"
}
}
},
},
- },
- "summary": "Read Items",
- "operationId": "read_items_items__item_id__put",
- "parameters": [
- {
- "required": True,
- "schema": {
- "title": "Item Id",
- "type": "string",
- "format": "uuid",
- },
- "name": "item_id",
- "in": "path",
- }
- ],
- "requestBody": {
- "required": True,
- "content": {
- "application/json": {
- "schema": IsDict(
- {
- "allOf": [
- {
- "$ref": "#/components/schemas/Body_read_items_items__item_id__put"
- }
- ],
- "title": "Body",
- }
- )
- | IsDict(
- # TODO: remove when deprecating Pydantic v1
- {
- "$ref": "#/components/schemas/Body_read_items_items__item_id__put"
- }
- )
- }
- },
- },
+ }
}
- }
- },
- "components": {
- "schemas": {
- "Body_read_items_items__item_id__put": {
- "title": "Body_read_items_items__item_id__put",
- "type": "object",
- "properties": {
- "start_datetime": {
- "title": "Start Datetime",
- "type": "string",
- "format": "date-time",
- },
- "end_datetime": {
- "title": "End Datetime",
- "type": "string",
- "format": "date-time",
- },
- "repeat_at": IsDict(
- {
+ },
+ "components": {
+ "schemas": {
+ "Body_read_items_items__item_id__put": {
+ "title": "Body_read_items_items__item_id__put",
+ "type": "object",
+ "properties": {
+ "start_datetime": {
+ "title": "Start Datetime",
+ "type": "string",
+ "format": "date-time",
+ },
+ "end_datetime": {
+ "title": "End Datetime",
+ "type": "string",
+ "format": "date-time",
+ },
+ "repeat_at": {
"title": "Repeat At",
"anyOf": [
{"type": "string", "format": "time"},
{"type": "null"},
],
- }
- )
- | IsDict(
- # TODO: remove when deprecating Pydantic v1
- {
- "title": "Repeat At",
- "type": "string",
- "format": "time",
- }
- ),
- "process_after": IsDict(
- {
+ },
+ "process_after": {
"title": "Process After",
"type": "string",
"format": "duration",
- }
- )
- | IsDict(
- # TODO: remove when deprecating Pydantic v1
- {
- "title": "Process After",
- "type": "number",
- "format": "time-delta",
- }
- ),
- },
- "required": ["start_datetime", "end_datetime", "process_after"],
- },
- "ValidationError": {
- "title": "ValidationError",
- "required": ["loc", "msg", "type"],
- "type": "object",
- "properties": {
- "loc": {
- "title": "Location",
- "type": "array",
- "items": {
- "anyOf": [{"type": "string"}, {"type": "integer"}]
},
},
- "msg": {"title": "Message", "type": "string"},
- "type": {"title": "Error Type", "type": "string"},
+ "required": ["start_datetime", "end_datetime", "process_after"],
},
- },
- "HTTPValidationError": {
- "title": "HTTPValidationError",
- "type": "object",
- "properties": {
- "detail": {
- "title": "Detail",
- "type": "array",
- "items": {"$ref": "#/components/schemas/ValidationError"},
- }
+ "ValidationError": {
+ "title": "ValidationError",
+ "required": ["loc", "msg", "type"],
+ "type": "object",
+ "properties": {
+ "loc": {
+ "title": "Location",
+ "type": "array",
+ "items": {
+ "anyOf": [{"type": "string"}, {"type": "integer"}]
+ },
+ },
+ "msg": {"title": "Message", "type": "string"},
+ "type": {"title": "Error Type", "type": "string"},
+ },
},
- },
- }
- },
- }
+ "HTTPValidationError": {
+ "title": "HTTPValidationError",
+ "type": "object",
+ "properties": {
+ "detail": {
+ "title": "Detail",
+ "type": "array",
+ "items": {
+ "$ref": "#/components/schemas/ValidationError"
+ },
+ }
+ },
+ },
+ }
+ },
+ }
+ )
diff --git a/tests/test_tutorial/test_extra_models/test_tutorial001_tutorial002.py b/tests/test_tutorial/test_extra_models/test_tutorial001_tutorial002.py
new file mode 100644
index 0000000000..3f2f508a11
--- /dev/null
+++ b/tests/test_tutorial/test_extra_models/test_tutorial001_tutorial002.py
@@ -0,0 +1,156 @@
+import importlib
+
+import pytest
+from dirty_equals import IsList
+from fastapi.testclient import TestClient
+
+from ...utils import needs_py310
+
+
+@pytest.fixture(
+ name="client",
+ params=[
+ pytest.param("tutorial001_py39"),
+ pytest.param("tutorial001_py310", marks=needs_py310),
+ pytest.param("tutorial002_py39"),
+ pytest.param("tutorial002_py310", marks=needs_py310),
+ ],
+)
+def get_client(request: pytest.FixtureRequest):
+ mod = importlib.import_module(f"docs_src.extra_models.{request.param}")
+
+ client = TestClient(mod.app)
+ return client
+
+
+def test_post(client: TestClient):
+ response = client.post(
+ "/user/",
+ json={
+ "username": "johndoe",
+ "password": "secret",
+ "email": "johndoe@example.com",
+ "full_name": "John Doe",
+ },
+ )
+ assert response.status_code == 200, response.text
+ assert response.json() == {
+ "username": "johndoe",
+ "email": "johndoe@example.com",
+ "full_name": "John Doe",
+ }
+
+
+def test_openapi_schema(client: TestClient):
+ response = client.get("/openapi.json")
+ assert response.status_code == 200, response.text
+ assert response.json() == {
+ "openapi": "3.1.0",
+ "info": {"title": "FastAPI", "version": "0.1.0"},
+ "paths": {
+ "/user/": {
+ "post": {
+ "responses": {
+ "200": {
+ "description": "Successful Response",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/UserOut",
+ }
+ }
+ },
+ },
+ "422": {
+ "description": "Validation Error",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/HTTPValidationError"
+ }
+ }
+ },
+ },
+ },
+ "summary": "Create User",
+ "operationId": "create_user_user__post",
+ "requestBody": {
+ "content": {
+ "application/json": {
+ "schema": {"$ref": "#/components/schemas/UserIn"}
+ }
+ },
+ "required": True,
+ },
+ }
+ }
+ },
+ "components": {
+ "schemas": {
+ "UserIn": {
+ "title": "UserIn",
+ "required": IsList(
+ "username", "password", "email", check_order=False
+ ),
+ "type": "object",
+ "properties": {
+ "username": {"title": "Username", "type": "string"},
+ "password": {"title": "Password", "type": "string"},
+ "email": {
+ "title": "Email",
+ "type": "string",
+ "format": "email",
+ },
+ "full_name": {
+ "title": "Full Name",
+ "anyOf": [{"type": "string"}, {"type": "null"}],
+ },
+ },
+ },
+ "UserOut": {
+ "title": "UserOut",
+ "required": ["username", "email"],
+ "type": "object",
+ "properties": {
+ "username": {"title": "Username", "type": "string"},
+ "email": {
+ "title": "Email",
+ "type": "string",
+ "format": "email",
+ },
+ "full_name": {
+ "title": "Full Name",
+ "anyOf": [{"type": "string"}, {"type": "null"}],
+ },
+ },
+ },
+ "ValidationError": {
+ "title": "ValidationError",
+ "required": ["loc", "msg", "type"],
+ "type": "object",
+ "properties": {
+ "loc": {
+ "title": "Location",
+ "type": "array",
+ "items": {
+ "anyOf": [{"type": "string"}, {"type": "integer"}]
+ },
+ },
+ "msg": {"title": "Message", "type": "string"},
+ "type": {"title": "Error Type", "type": "string"},
+ },
+ },
+ "HTTPValidationError": {
+ "title": "HTTPValidationError",
+ "type": "object",
+ "properties": {
+ "detail": {
+ "title": "Detail",
+ "type": "array",
+ "items": {"$ref": "#/components/schemas/ValidationError"},
+ }
+ },
+ },
+ }
+ },
+ }
diff --git a/tests/test_tutorial/test_extra_models/test_tutorial003.py b/tests/test_tutorial/test_extra_models/test_tutorial003.py
index 73aa299039..872af53830 100644
--- a/tests/test_tutorial/test_extra_models/test_tutorial003.py
+++ b/tests/test_tutorial/test_extra_models/test_tutorial003.py
@@ -1,8 +1,8 @@
import importlib
import pytest
-from dirty_equals import IsOneOf
from fastapi.testclient import TestClient
+from inline_snapshot import snapshot
from ...utils import needs_py310
@@ -10,7 +10,7 @@ from ...utils import needs_py310
@pytest.fixture(
name="client",
params=[
- "tutorial003",
+ pytest.param("tutorial003_py39"),
pytest.param("tutorial003_py310", marks=needs_py310),
],
)
@@ -43,107 +43,115 @@ def test_get_plane(client: TestClient):
def test_openapi_schema(client: TestClient):
response = client.get("/openapi.json")
assert response.status_code == 200, response.text
- assert response.json() == {
- "openapi": "3.1.0",
- "info": {"title": "FastAPI", "version": "0.1.0"},
- "paths": {
- "/items/{item_id}": {
- "get": {
- "responses": {
- "200": {
- "description": "Successful Response",
- "content": {
- "application/json": {
- "schema": {
- "title": "Response Read Item Items Item Id Get",
- "anyOf": [
- {"$ref": "#/components/schemas/PlaneItem"},
- {"$ref": "#/components/schemas/CarItem"},
- ],
+ assert response.json() == snapshot(
+ {
+ "openapi": "3.1.0",
+ "info": {"title": "FastAPI", "version": "0.1.0"},
+ "paths": {
+ "/items/{item_id}": {
+ "get": {
+ "responses": {
+ "200": {
+ "description": "Successful Response",
+ "content": {
+ "application/json": {
+ "schema": {
+ "title": "Response Read Item Items Item Id Get",
+ "anyOf": [
+ {
+ "$ref": "#/components/schemas/PlaneItem"
+ },
+ {
+ "$ref": "#/components/schemas/CarItem"
+ },
+ ],
+ }
}
- }
+ },
+ },
+ "422": {
+ "description": "Validation Error",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/HTTPValidationError"
+ }
+ }
+ },
},
},
- "422": {
- "description": "Validation Error",
- "content": {
- "application/json": {
- "schema": {
- "$ref": "#/components/schemas/HTTPValidationError"
- }
- }
- },
- },
- },
- "summary": "Read Item",
- "operationId": "read_item_items__item_id__get",
- "parameters": [
- {
- "required": True,
- "schema": {"title": "Item Id", "type": "string"},
- "name": "item_id",
- "in": "path",
- }
- ],
+ "summary": "Read Item",
+ "operationId": "read_item_items__item_id__get",
+ "parameters": [
+ {
+ "required": True,
+ "schema": {"title": "Item Id", "type": "string"},
+ "name": "item_id",
+ "in": "path",
+ }
+ ],
+ }
}
- }
- },
- "components": {
- "schemas": {
- "PlaneItem": {
- "title": "PlaneItem",
- "required": IsOneOf(
- ["description", "type", "size"],
- # TODO: remove when deprecating Pydantic v1
- ["description", "size"],
- ),
- "type": "object",
- "properties": {
- "description": {"title": "Description", "type": "string"},
- "type": {"title": "Type", "type": "string", "default": "plane"},
- "size": {"title": "Size", "type": "integer"},
+ },
+ "components": {
+ "schemas": {
+ "PlaneItem": {
+ "title": "PlaneItem",
+ "required": ["description", "size"],
+ "type": "object",
+ "properties": {
+ "description": {"title": "Description", "type": "string"},
+ "type": {
+ "title": "Type",
+ "type": "string",
+ "default": "plane",
+ },
+ "size": {"title": "Size", "type": "integer"},
+ },
},
- },
- "CarItem": {
- "title": "CarItem",
- "required": IsOneOf(
- ["description", "type"],
- # TODO: remove when deprecating Pydantic v1
- ["description"],
- ),
- "type": "object",
- "properties": {
- "description": {"title": "Description", "type": "string"},
- "type": {"title": "Type", "type": "string", "default": "car"},
- },
- },
- "ValidationError": {
- "title": "ValidationError",
- "required": ["loc", "msg", "type"],
- "type": "object",
- "properties": {
- "loc": {
- "title": "Location",
- "type": "array",
- "items": {
- "anyOf": [{"type": "string"}, {"type": "integer"}]
+ "CarItem": {
+ "title": "CarItem",
+ "required": ["description"],
+ "type": "object",
+ "properties": {
+ "description": {"title": "Description", "type": "string"},
+ "type": {
+ "title": "Type",
+ "type": "string",
+ "default": "car",
},
},
- "msg": {"title": "Message", "type": "string"},
- "type": {"title": "Error Type", "type": "string"},
},
- },
- "HTTPValidationError": {
- "title": "HTTPValidationError",
- "type": "object",
- "properties": {
- "detail": {
- "title": "Detail",
- "type": "array",
- "items": {"$ref": "#/components/schemas/ValidationError"},
- }
+ "ValidationError": {
+ "title": "ValidationError",
+ "required": ["loc", "msg", "type"],
+ "type": "object",
+ "properties": {
+ "loc": {
+ "title": "Location",
+ "type": "array",
+ "items": {
+ "anyOf": [{"type": "string"}, {"type": "integer"}]
+ },
+ },
+ "msg": {"title": "Message", "type": "string"},
+ "type": {"title": "Error Type", "type": "string"},
+ },
},
- },
- }
- },
- }
+ "HTTPValidationError": {
+ "title": "HTTPValidationError",
+ "type": "object",
+ "properties": {
+ "detail": {
+ "title": "Detail",
+ "type": "array",
+ "items": {
+ "$ref": "#/components/schemas/ValidationError"
+ },
+ }
+ },
+ },
+ }
+ },
+ }
+ )
diff --git a/tests/test_tutorial/test_extra_models/test_tutorial004.py b/tests/test_tutorial/test_extra_models/test_tutorial004.py
index 7628db30c7..073375ccc9 100644
--- a/tests/test_tutorial/test_extra_models/test_tutorial004.py
+++ b/tests/test_tutorial/test_extra_models/test_tutorial004.py
@@ -3,14 +3,11 @@ import importlib
import pytest
from fastapi.testclient import TestClient
-from ...utils import needs_py39
-
@pytest.fixture(
name="client",
params=[
- "tutorial004",
- pytest.param("tutorial004_py39", marks=needs_py39),
+ pytest.param("tutorial004_py39"),
],
)
def get_client(request: pytest.FixtureRequest):
diff --git a/tests/test_tutorial/test_extra_models/test_tutorial005.py b/tests/test_tutorial/test_extra_models/test_tutorial005.py
index 553e442385..8e52d8d4ba 100644
--- a/tests/test_tutorial/test_extra_models/test_tutorial005.py
+++ b/tests/test_tutorial/test_extra_models/test_tutorial005.py
@@ -3,14 +3,11 @@ import importlib
import pytest
from fastapi.testclient import TestClient
-from ...utils import needs_py39
-
@pytest.fixture(
name="client",
params=[
- "tutorial005",
- pytest.param("tutorial005_py39", marks=needs_py39),
+ pytest.param("tutorial005_py39"),
],
)
def get_client(request: pytest.FixtureRequest):
diff --git a/tests/test_tutorial/test_first_steps/test_tutorial001.py b/tests/test_tutorial/test_first_steps/test_tutorial001_tutorial002_tutorial003.py
similarity index 70%
rename from tests/test_tutorial/test_first_steps/test_tutorial001.py
rename to tests/test_tutorial/test_first_steps/test_tutorial001_tutorial002_tutorial003.py
index 6cc9fc2282..aa65218cde 100644
--- a/tests/test_tutorial/test_first_steps/test_tutorial001.py
+++ b/tests/test_tutorial/test_first_steps/test_tutorial001_tutorial002_tutorial003.py
@@ -1,9 +1,20 @@
+import importlib
+
import pytest
from fastapi.testclient import TestClient
-from docs_src.first_steps.tutorial001 import app
-client = TestClient(app)
+@pytest.fixture(
+ name="client",
+ params=[
+ "tutorial001_py39",
+ "tutorial003_py39",
+ ],
+)
+def get_client(request: pytest.FixtureRequest):
+ mod = importlib.import_module(f"docs_src.first_steps.{request.param}")
+ client = TestClient(mod.app)
+ return client
@pytest.mark.parametrize(
@@ -13,13 +24,13 @@ client = TestClient(app)
("/nonexistent", 404, {"detail": "Not Found"}),
],
)
-def test_get_path(path, expected_status, expected_response):
+def test_get_path(client: TestClient, path, expected_status, expected_response):
response = client.get(path)
assert response.status_code == expected_status
assert response.json() == expected_response
-def test_openapi_schema():
+def test_openapi_schema(client: TestClient):
response = client.get("/openapi.json")
assert response.status_code == 200
assert response.json() == {
diff --git a/tests/test_tutorial/test_generate_clients/test_tutorial001.py b/tests/test_tutorial/test_generate_clients/test_tutorial001.py
new file mode 100644
index 0000000000..bbb66b4516
--- /dev/null
+++ b/tests/test_tutorial/test_generate_clients/test_tutorial001.py
@@ -0,0 +1,142 @@
+import importlib
+
+import pytest
+from fastapi.testclient import TestClient
+
+
+@pytest.fixture(
+ name="client",
+ params=[
+ pytest.param("tutorial001_py39"),
+ ],
+)
+def get_client(request: pytest.FixtureRequest):
+ mod = importlib.import_module(f"docs_src.generate_clients.{request.param}")
+ client = TestClient(mod.app)
+ return client
+
+
+def test_post_items(client: TestClient):
+ response = client.post("/items/", json={"name": "Foo", "price": 5})
+ assert response.status_code == 200, response.text
+ assert response.json() == {"message": "item received"}
+
+
+def test_get_items(client: TestClient):
+ response = client.get("/items/")
+ assert response.status_code == 200, response.text
+ assert response.json() == [
+ {"name": "Plumbus", "price": 3},
+ {"name": "Portal Gun", "price": 9001},
+ ]
+
+
+def test_openapi_schema(client: TestClient):
+ response = client.get("/openapi.json")
+ assert response.status_code == 200, response.text
+ assert response.json() == {
+ "openapi": "3.1.0",
+ "info": {"title": "FastAPI", "version": "0.1.0"},
+ "paths": {
+ "/items/": {
+ "get": {
+ "summary": "Get Items",
+ "operationId": "get_items_items__get",
+ "responses": {
+ "200": {
+ "description": "Successful Response",
+ "content": {
+ "application/json": {
+ "schema": {
+ "title": "Response Get Items Items Get",
+ "type": "array",
+ "items": {"$ref": "#/components/schemas/Item"},
+ }
+ }
+ },
+ }
+ },
+ },
+ "post": {
+ "summary": "Create Item",
+ "operationId": "create_item_items__post",
+ "requestBody": {
+ "content": {
+ "application/json": {
+ "schema": {"$ref": "#/components/schemas/Item"}
+ }
+ },
+ "required": True,
+ },
+ "responses": {
+ "200": {
+ "description": "Successful Response",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/ResponseMessage"
+ }
+ }
+ },
+ },
+ "422": {
+ "description": "Validation Error",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/HTTPValidationError"
+ }
+ }
+ },
+ },
+ },
+ },
+ },
+ },
+ "components": {
+ "schemas": {
+ "HTTPValidationError": {
+ "title": "HTTPValidationError",
+ "type": "object",
+ "properties": {
+ "detail": {
+ "title": "Detail",
+ "type": "array",
+ "items": {"$ref": "#/components/schemas/ValidationError"},
+ }
+ },
+ },
+ "Item": {
+ "title": "Item",
+ "required": ["name", "price"],
+ "type": "object",
+ "properties": {
+ "name": {"title": "Name", "type": "string"},
+ "price": {"title": "Price", "type": "number"},
+ },
+ },
+ "ResponseMessage": {
+ "title": "ResponseMessage",
+ "required": ["message"],
+ "type": "object",
+ "properties": {"message": {"title": "Message", "type": "string"}},
+ },
+ "ValidationError": {
+ "title": "ValidationError",
+ "required": ["loc", "msg", "type"],
+ "type": "object",
+ "properties": {
+ "loc": {
+ "title": "Location",
+ "type": "array",
+ "items": {
+ "anyOf": [{"type": "string"}, {"type": "integer"}]
+ },
+ },
+ "msg": {"title": "Message", "type": "string"},
+ "type": {"title": "Error Type", "type": "string"},
+ },
+ },
+ }
+ },
+ }
diff --git a/tests/test_tutorial/test_generate_clients/test_tutorial002.py b/tests/test_tutorial/test_generate_clients/test_tutorial002.py
new file mode 100644
index 0000000000..ab8bc4c11c
--- /dev/null
+++ b/tests/test_tutorial/test_generate_clients/test_tutorial002.py
@@ -0,0 +1,187 @@
+from fastapi.testclient import TestClient
+
+from docs_src.generate_clients.tutorial002_py39 import app
+
+client = TestClient(app)
+
+
+def test_post_items():
+ response = client.post("/items/", json={"name": "Foo", "price": 5})
+ assert response.status_code == 200, response.text
+ assert response.json() == {"message": "Item received"}
+
+
+def test_post_users():
+ response = client.post(
+ "/users/", json={"username": "Foo", "email": "foo@example.com"}
+ )
+ assert response.status_code == 200, response.text
+ assert response.json() == {"message": "User received"}
+
+
+def test_get_items():
+ response = client.get("/items/")
+ assert response.status_code == 200, response.text
+ assert response.json() == [
+ {"name": "Plumbus", "price": 3},
+ {"name": "Portal Gun", "price": 9001},
+ ]
+
+
+def test_openapi_schema():
+ response = client.get("/openapi.json")
+ assert response.status_code == 200, response.text
+ assert response.json() == {
+ "openapi": "3.1.0",
+ "info": {"title": "FastAPI", "version": "0.1.0"},
+ "paths": {
+ "/items/": {
+ "get": {
+ "tags": ["items"],
+ "summary": "Get Items",
+ "operationId": "get_items_items__get",
+ "responses": {
+ "200": {
+ "description": "Successful Response",
+ "content": {
+ "application/json": {
+ "schema": {
+ "title": "Response Get Items Items Get",
+ "type": "array",
+ "items": {"$ref": "#/components/schemas/Item"},
+ }
+ }
+ },
+ }
+ },
+ },
+ "post": {
+ "tags": ["items"],
+ "summary": "Create Item",
+ "operationId": "create_item_items__post",
+ "requestBody": {
+ "content": {
+ "application/json": {
+ "schema": {"$ref": "#/components/schemas/Item"}
+ }
+ },
+ "required": True,
+ },
+ "responses": {
+ "200": {
+ "description": "Successful Response",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/ResponseMessage"
+ }
+ }
+ },
+ },
+ "422": {
+ "description": "Validation Error",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/HTTPValidationError"
+ }
+ }
+ },
+ },
+ },
+ },
+ },
+ "/users/": {
+ "post": {
+ "tags": ["users"],
+ "summary": "Create User",
+ "operationId": "create_user_users__post",
+ "requestBody": {
+ "content": {
+ "application/json": {
+ "schema": {"$ref": "#/components/schemas/User"}
+ }
+ },
+ "required": True,
+ },
+ "responses": {
+ "200": {
+ "description": "Successful Response",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/ResponseMessage"
+ }
+ }
+ },
+ },
+ "422": {
+ "description": "Validation Error",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/HTTPValidationError"
+ }
+ }
+ },
+ },
+ },
+ }
+ },
+ },
+ "components": {
+ "schemas": {
+ "HTTPValidationError": {
+ "title": "HTTPValidationError",
+ "type": "object",
+ "properties": {
+ "detail": {
+ "title": "Detail",
+ "type": "array",
+ "items": {"$ref": "#/components/schemas/ValidationError"},
+ }
+ },
+ },
+ "Item": {
+ "title": "Item",
+ "required": ["name", "price"],
+ "type": "object",
+ "properties": {
+ "name": {"title": "Name", "type": "string"},
+ "price": {"title": "Price", "type": "number"},
+ },
+ },
+ "ResponseMessage": {
+ "title": "ResponseMessage",
+ "required": ["message"],
+ "type": "object",
+ "properties": {"message": {"title": "Message", "type": "string"}},
+ },
+ "User": {
+ "title": "User",
+ "required": ["username", "email"],
+ "type": "object",
+ "properties": {
+ "username": {"title": "Username", "type": "string"},
+ "email": {"title": "Email", "type": "string"},
+ },
+ },
+ "ValidationError": {
+ "title": "ValidationError",
+ "required": ["loc", "msg", "type"],
+ "type": "object",
+ "properties": {
+ "loc": {
+ "title": "Location",
+ "type": "array",
+ "items": {
+ "anyOf": [{"type": "string"}, {"type": "integer"}]
+ },
+ },
+ "msg": {"title": "Message", "type": "string"},
+ "type": {"title": "Error Type", "type": "string"},
+ },
+ },
+ }
+ },
+ }
diff --git a/tests/test_tutorial/test_generate_clients/test_tutorial003.py b/tests/test_tutorial/test_generate_clients/test_tutorial003.py
index 1cd9678a1c..bac52e4fd6 100644
--- a/tests/test_tutorial/test_generate_clients/test_tutorial003.py
+++ b/tests/test_tutorial/test_generate_clients/test_tutorial003.py
@@ -1,6 +1,6 @@
from fastapi.testclient import TestClient
-from docs_src.generate_clients.tutorial003 import app
+from docs_src.generate_clients.tutorial003_py39 import app
client = TestClient(app)
diff --git a/tests/test_tutorial/test_generate_clients/test_tutorial004.py b/tests/test_tutorial/test_generate_clients/test_tutorial004.py
new file mode 100644
index 0000000000..e66f6d2a12
--- /dev/null
+++ b/tests/test_tutorial/test_generate_clients/test_tutorial004.py
@@ -0,0 +1,230 @@
+import importlib
+import json
+import pathlib
+from unittest.mock import patch
+
+from docs_src.generate_clients import tutorial003_py39
+
+
+def test_remove_tags(tmp_path: pathlib.Path):
+ tmp_file = tmp_path / "openapi.json"
+ openapi_json = tutorial003_py39.app.openapi()
+ tmp_file.write_text(json.dumps(openapi_json))
+
+ with patch("pathlib.Path", return_value=tmp_file):
+ importlib.import_module("docs_src.generate_clients.tutorial004_py39")
+
+ modified_openapi = json.loads(tmp_file.read_text())
+ assert modified_openapi == {
+ "components": {
+ "schemas": {
+ "HTTPValidationError": {
+ "properties": {
+ "detail": {
+ "items": {
+ "$ref": "#/components/schemas/ValidationError",
+ },
+ "title": "Detail",
+ "type": "array",
+ },
+ },
+ "title": "HTTPValidationError",
+ "type": "object",
+ },
+ "Item": {
+ "properties": {
+ "name": {
+ "title": "Name",
+ "type": "string",
+ },
+ "price": {
+ "title": "Price",
+ "type": "number",
+ },
+ },
+ "required": [
+ "name",
+ "price",
+ ],
+ "title": "Item",
+ "type": "object",
+ },
+ "ResponseMessage": {
+ "properties": {
+ "message": {
+ "title": "Message",
+ "type": "string",
+ },
+ },
+ "required": [
+ "message",
+ ],
+ "title": "ResponseMessage",
+ "type": "object",
+ },
+ "User": {
+ "properties": {
+ "email": {
+ "title": "Email",
+ "type": "string",
+ },
+ "username": {
+ "title": "Username",
+ "type": "string",
+ },
+ },
+ "required": [
+ "username",
+ "email",
+ ],
+ "title": "User",
+ "type": "object",
+ },
+ "ValidationError": {
+ "properties": {
+ "loc": {
+ "items": {
+ "anyOf": [
+ {
+ "type": "string",
+ },
+ {
+ "type": "integer",
+ },
+ ],
+ },
+ "title": "Location",
+ "type": "array",
+ },
+ "msg": {
+ "title": "Message",
+ "type": "string",
+ },
+ "type": {
+ "title": "Error Type",
+ "type": "string",
+ },
+ },
+ "required": [
+ "loc",
+ "msg",
+ "type",
+ ],
+ "title": "ValidationError",
+ "type": "object",
+ },
+ },
+ },
+ "info": {
+ "title": "FastAPI",
+ "version": "0.1.0",
+ },
+ "openapi": "3.1.0",
+ "paths": {
+ "/items/": {
+ "get": {
+ "operationId": "get_items",
+ "responses": {
+ "200": {
+ "content": {
+ "application/json": {
+ "schema": {
+ "items": {
+ "$ref": "#/components/schemas/Item",
+ },
+ "title": "Response Items-Get Items",
+ "type": "array",
+ },
+ },
+ },
+ "description": "Successful Response",
+ },
+ },
+ "summary": "Get Items",
+ "tags": [
+ "items",
+ ],
+ },
+ "post": {
+ "operationId": "create_item",
+ "requestBody": {
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/Item",
+ },
+ },
+ },
+ "required": True,
+ },
+ "responses": {
+ "200": {
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/ResponseMessage",
+ },
+ },
+ },
+ "description": "Successful Response",
+ },
+ "422": {
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/HTTPValidationError",
+ },
+ },
+ },
+ "description": "Validation Error",
+ },
+ },
+ "summary": "Create Item",
+ "tags": [
+ "items",
+ ],
+ },
+ },
+ "/users/": {
+ "post": {
+ "operationId": "create_user",
+ "requestBody": {
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/User",
+ },
+ },
+ },
+ "required": True,
+ },
+ "responses": {
+ "200": {
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/ResponseMessage",
+ },
+ },
+ },
+ "description": "Successful Response",
+ },
+ "422": {
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/HTTPValidationError",
+ },
+ },
+ },
+ "description": "Validation Error",
+ },
+ },
+ "summary": "Create User",
+ "tags": [
+ "users",
+ ],
+ },
+ },
+ },
+ }
diff --git a/tests/test_tutorial/test_graphql/__init__.py b/tests/test_tutorial/test_graphql/__init__.py
new file mode 100644
index 0000000000..e69de29bb2
diff --git a/tests/test_tutorial/test_graphql/test_tutorial001.py b/tests/test_tutorial/test_graphql/test_tutorial001.py
new file mode 100644
index 0000000000..9ba7147b55
--- /dev/null
+++ b/tests/test_tutorial/test_graphql/test_tutorial001.py
@@ -0,0 +1,70 @@
+import warnings
+
+import pytest
+from starlette.testclient import TestClient
+
+warnings.filterwarnings(
+ "ignore",
+ message=r"The 'lia' package has been renamed to 'cross_web'\..*",
+ category=DeprecationWarning,
+)
+
+from docs_src.graphql_.tutorial001_py39 import app # noqa: E402
+
+
+@pytest.fixture(name="client")
+def get_client() -> TestClient:
+ return TestClient(app)
+
+
+def test_query(client: TestClient):
+ response = client.post("/graphql", json={"query": "{ user { name, age } }"})
+ assert response.status_code == 200
+ assert response.json() == {"data": {"user": {"name": "Patrick", "age": 100}}}
+
+
+def test_openapi(client: TestClient):
+ response = client.get("/openapi.json")
+ assert response.status_code == 200
+ assert response.json() == {
+ "info": {
+ "title": "FastAPI",
+ "version": "0.1.0",
+ },
+ "openapi": "3.1.0",
+ "paths": {
+ "/graphql": {
+ "get": {
+ "operationId": "handle_http_get_graphql_get",
+ "responses": {
+ "200": {
+ "content": {
+ "application/json": {
+ "schema": {},
+ },
+ },
+ "description": "The GraphiQL integrated development environment.",
+ },
+ "404": {
+ "description": "Not found if GraphiQL or query via GET are not enabled.",
+ },
+ },
+ "summary": "Handle Http Get",
+ },
+ "post": {
+ "operationId": "handle_http_post_graphql_post",
+ "responses": {
+ "200": {
+ "content": {
+ "application/json": {
+ "schema": {},
+ },
+ },
+ "description": "Successful Response",
+ },
+ },
+ "summary": "Handle Http Post",
+ },
+ },
+ },
+ }
diff --git a/tests/test_tutorial/test_handling_errors/test_tutorial001.py b/tests/test_tutorial/test_handling_errors/test_tutorial001.py
index 8809c135bd..c01850fae6 100644
--- a/tests/test_tutorial/test_handling_errors/test_tutorial001.py
+++ b/tests/test_tutorial/test_handling_errors/test_tutorial001.py
@@ -1,6 +1,6 @@
from fastapi.testclient import TestClient
-from docs_src.handling_errors.tutorial001 import app
+from docs_src.handling_errors.tutorial001_py39 import app
client = TestClient(app)
diff --git a/tests/test_tutorial/test_handling_errors/test_tutorial002.py b/tests/test_tutorial/test_handling_errors/test_tutorial002.py
index efd86ebdec..09366a86fa 100644
--- a/tests/test_tutorial/test_handling_errors/test_tutorial002.py
+++ b/tests/test_tutorial/test_handling_errors/test_tutorial002.py
@@ -1,6 +1,6 @@
from fastapi.testclient import TestClient
-from docs_src.handling_errors.tutorial002 import app
+from docs_src.handling_errors.tutorial002_py39 import app
client = TestClient(app)
diff --git a/tests/test_tutorial/test_handling_errors/test_tutorial003.py b/tests/test_tutorial/test_handling_errors/test_tutorial003.py
index 4763f68f3f..51ac3e7b28 100644
--- a/tests/test_tutorial/test_handling_errors/test_tutorial003.py
+++ b/tests/test_tutorial/test_handling_errors/test_tutorial003.py
@@ -1,6 +1,6 @@
from fastapi.testclient import TestClient
-from docs_src.handling_errors.tutorial003 import app
+from docs_src.handling_errors.tutorial003_py39 import app
client = TestClient(app)
diff --git a/tests/test_tutorial/test_handling_errors/test_tutorial004.py b/tests/test_tutorial/test_handling_errors/test_tutorial004.py
index c04bf37245..376bc8266f 100644
--- a/tests/test_tutorial/test_handling_errors/test_tutorial004.py
+++ b/tests/test_tutorial/test_handling_errors/test_tutorial004.py
@@ -1,6 +1,6 @@
from fastapi.testclient import TestClient
-from docs_src.handling_errors.tutorial004 import app
+from docs_src.handling_errors.tutorial004_py39 import app
client = TestClient(app)
diff --git a/tests/test_tutorial/test_handling_errors/test_tutorial005.py b/tests/test_tutorial/test_handling_errors/test_tutorial005.py
index 581b2e4c75..7bd947f194 100644
--- a/tests/test_tutorial/test_handling_errors/test_tutorial005.py
+++ b/tests/test_tutorial/test_handling_errors/test_tutorial005.py
@@ -1,7 +1,6 @@
-from dirty_equals import IsDict
from fastapi.testclient import TestClient
-from docs_src.handling_errors.tutorial005 import app
+from docs_src.handling_errors.tutorial005_py39 import app
client = TestClient(app)
@@ -9,31 +8,17 @@ client = TestClient(app)
def test_post_validation_error():
response = client.post("/items/", json={"title": "towel", "size": "XL"})
assert response.status_code == 422, response.text
- assert response.json() == IsDict(
- {
- "detail": [
- {
- "type": "int_parsing",
- "loc": ["body", "size"],
- "msg": "Input should be a valid integer, unable to parse string as an integer",
- "input": "XL",
- }
- ],
- "body": {"title": "towel", "size": "XL"},
- }
- ) | IsDict(
- # TODO: remove when deprecating Pydantic v1
- {
- "detail": [
- {
- "loc": ["body", "size"],
- "msg": "value is not a valid integer",
- "type": "type_error.integer",
- }
- ],
- "body": {"title": "towel", "size": "XL"},
- }
- )
+ assert response.json() == {
+ "detail": [
+ {
+ "type": "int_parsing",
+ "loc": ["body", "size"],
+ "msg": "Input should be a valid integer, unable to parse string as an integer",
+ "input": "XL",
+ }
+ ],
+ "body": {"title": "towel", "size": "XL"},
+ }
def test_post():
diff --git a/tests/test_tutorial/test_handling_errors/test_tutorial006.py b/tests/test_tutorial/test_handling_errors/test_tutorial006.py
index 7d2f553aac..e95e53d5ed 100644
--- a/tests/test_tutorial/test_handling_errors/test_tutorial006.py
+++ b/tests/test_tutorial/test_handling_errors/test_tutorial006.py
@@ -1,7 +1,6 @@
-from dirty_equals import IsDict
from fastapi.testclient import TestClient
-from docs_src.handling_errors.tutorial006 import app
+from docs_src.handling_errors.tutorial006_py39 import app
client = TestClient(app)
@@ -9,29 +8,16 @@ client = TestClient(app)
def test_get_validation_error():
response = client.get("/items/foo")
assert response.status_code == 422, response.text
- assert response.json() == IsDict(
- {
- "detail": [
- {
- "type": "int_parsing",
- "loc": ["path", "item_id"],
- "msg": "Input should be a valid integer, unable to parse string as an integer",
- "input": "foo",
- }
- ]
- }
- ) | IsDict(
- # TODO: remove when deprecating Pydantic v1
- {
- "detail": [
- {
- "loc": ["path", "item_id"],
- "msg": "value is not a valid integer",
- "type": "type_error.integer",
- }
- ]
- }
- )
+ assert response.json() == {
+ "detail": [
+ {
+ "type": "int_parsing",
+ "loc": ["path", "item_id"],
+ "msg": "Input should be a valid integer, unable to parse string as an integer",
+ "input": "foo",
+ }
+ ]
+ }
def test_get_http_error():
diff --git a/tests/test_tutorial/test_header_param_models/test_tutorial001.py b/tests/test_tutorial/test_header_param_models/test_tutorial001.py
index bc876897b2..1fa8aee461 100644
--- a/tests/test_tutorial/test_header_param_models/test_tutorial001.py
+++ b/tests/test_tutorial/test_header_param_models/test_tutorial001.py
@@ -1,21 +1,18 @@
import importlib
import pytest
-from dirty_equals import IsDict
from fastapi.testclient import TestClient
from inline_snapshot import snapshot
-from tests.utils import needs_py39, needs_py310
+from tests.utils import needs_py310
@pytest.fixture(
name="client",
params=[
- "tutorial001",
- pytest.param("tutorial001_py39", marks=needs_py39),
+ pytest.param("tutorial001_py39"),
pytest.param("tutorial001_py310", marks=needs_py310),
- "tutorial001_an",
- pytest.param("tutorial001_an_py39", marks=needs_py39),
+ pytest.param("tutorial001_an_py39"),
pytest.param("tutorial001_an_py310", marks=needs_py310),
],
)
@@ -65,29 +62,19 @@ def test_header_param_model_invalid(client: TestClient):
assert response.json() == snapshot(
{
"detail": [
- IsDict(
- {
- "type": "missing",
- "loc": ["header", "save_data"],
- "msg": "Field required",
- "input": {
- "x_tag": [],
- "host": "testserver",
- "accept": "*/*",
- "accept-encoding": "gzip, deflate",
- "connection": "keep-alive",
- "user-agent": "testclient",
- },
- }
- )
- | IsDict(
- # TODO: remove when deprecating Pydantic v1
- {
- "type": "value_error.missing",
- "loc": ["header", "save_data"],
- "msg": "field required",
- }
- )
+ {
+ "type": "missing",
+ "loc": ["header", "save_data"],
+ "msg": "Field required",
+ "input": {
+ "x_tag": [],
+ "host": "testserver",
+ "accept": "*/*",
+ "accept-encoding": "gzip, deflate",
+ "connection": "keep-alive",
+ "user-agent": "testclient",
+ },
+ }
]
}
)
@@ -138,37 +125,19 @@ def test_openapi_schema(client: TestClient):
"name": "if-modified-since",
"in": "header",
"required": False,
- "schema": IsDict(
- {
- "anyOf": [{"type": "string"}, {"type": "null"}],
- "title": "If Modified Since",
- }
- )
- | IsDict(
- # TODO: remove when deprecating Pydantic v1
- {
- "type": "string",
- "title": "If Modified Since",
- }
- ),
+ "schema": {
+ "anyOf": [{"type": "string"}, {"type": "null"}],
+ "title": "If Modified Since",
+ },
},
{
"name": "traceparent",
"in": "header",
"required": False,
- "schema": IsDict(
- {
- "anyOf": [{"type": "string"}, {"type": "null"}],
- "title": "Traceparent",
- }
- )
- | IsDict(
- # TODO: remove when deprecating Pydantic v1
- {
- "type": "string",
- "title": "Traceparent",
- }
- ),
+ "schema": {
+ "anyOf": [{"type": "string"}, {"type": "null"}],
+ "title": "Traceparent",
+ },
},
{
"name": "x-tag",
diff --git a/tests/test_tutorial/test_header_param_models/test_tutorial002.py b/tests/test_tutorial/test_header_param_models/test_tutorial002.py
index 0615521c43..079a8f5402 100644
--- a/tests/test_tutorial/test_header_param_models/test_tutorial002.py
+++ b/tests/test_tutorial/test_header_param_models/test_tutorial002.py
@@ -1,26 +1,19 @@
import importlib
import pytest
-from dirty_equals import IsDict
from fastapi.testclient import TestClient
from inline_snapshot import snapshot
-from tests.utils import needs_py39, needs_py310, needs_pydanticv1, needs_pydanticv2
+from tests.utils import needs_py310
@pytest.fixture(
name="client",
params=[
- pytest.param("tutorial002", marks=needs_pydanticv2),
- pytest.param("tutorial002_py310", marks=[needs_py310, needs_pydanticv2]),
- pytest.param("tutorial002_an", marks=needs_pydanticv2),
- pytest.param("tutorial002_an_py39", marks=[needs_py39, needs_pydanticv2]),
- pytest.param("tutorial002_an_py310", marks=[needs_py310, needs_pydanticv2]),
- pytest.param("tutorial002_pv1", marks=[needs_pydanticv1, needs_pydanticv1]),
- pytest.param("tutorial002_pv1_py310", marks=[needs_py310, needs_pydanticv1]),
- pytest.param("tutorial002_pv1_an", marks=[needs_pydanticv1]),
- pytest.param("tutorial002_pv1_an_py39", marks=[needs_py39, needs_pydanticv1]),
- pytest.param("tutorial002_pv1_an_py310", marks=[needs_py310, needs_pydanticv1]),
+ pytest.param("tutorial002_py39"),
+ pytest.param("tutorial002_py310", marks=[needs_py310]),
+ pytest.param("tutorial002_an_py39"),
+ pytest.param("tutorial002_an_py310", marks=[needs_py310]),
],
)
def get_client(request: pytest.FixtureRequest):
@@ -70,22 +63,12 @@ def test_header_param_model_invalid(client: TestClient):
assert response.json() == snapshot(
{
"detail": [
- IsDict(
- {
- "type": "missing",
- "loc": ["header", "save_data"],
- "msg": "Field required",
- "input": {"x_tag": [], "host": "testserver"},
- }
- )
- | IsDict(
- # TODO: remove when deprecating Pydantic v1
- {
- "type": "value_error.missing",
- "loc": ["header", "save_data"],
- "msg": "field required",
- }
- )
+ {
+ "type": "missing",
+ "loc": ["header", "save_data"],
+ "msg": "Field required",
+ "input": {"x_tag": [], "host": "testserver"},
+ }
]
}
)
@@ -99,22 +82,12 @@ def test_header_param_model_extra(client: TestClient):
assert response.json() == snapshot(
{
"detail": [
- IsDict(
- {
- "type": "extra_forbidden",
- "loc": ["header", "tool"],
- "msg": "Extra inputs are not permitted",
- "input": "plumbus",
- }
- )
- | IsDict(
- # TODO: remove when deprecating Pydantic v1
- {
- "type": "value_error.extra",
- "loc": ["header", "tool"],
- "msg": "extra fields not permitted",
- }
- )
+ {
+ "type": "extra_forbidden",
+ "loc": ["header", "tool"],
+ "msg": "Extra inputs are not permitted",
+ "input": "plumbus",
+ }
]
}
)
@@ -149,37 +122,19 @@ def test_openapi_schema(client: TestClient):
"name": "if-modified-since",
"in": "header",
"required": False,
- "schema": IsDict(
- {
- "anyOf": [{"type": "string"}, {"type": "null"}],
- "title": "If Modified Since",
- }
- )
- | IsDict(
- # TODO: remove when deprecating Pydantic v1
- {
- "type": "string",
- "title": "If Modified Since",
- }
- ),
+ "schema": {
+ "anyOf": [{"type": "string"}, {"type": "null"}],
+ "title": "If Modified Since",
+ },
},
{
"name": "traceparent",
"in": "header",
"required": False,
- "schema": IsDict(
- {
- "anyOf": [{"type": "string"}, {"type": "null"}],
- "title": "Traceparent",
- }
- )
- | IsDict(
- # TODO: remove when deprecating Pydantic v1
- {
- "type": "string",
- "title": "Traceparent",
- }
- ),
+ "schema": {
+ "anyOf": [{"type": "string"}, {"type": "null"}],
+ "title": "Traceparent",
+ },
},
{
"name": "x-tag",
diff --git a/tests/test_tutorial/test_header_param_models/test_tutorial003.py b/tests/test_tutorial/test_header_param_models/test_tutorial003.py
index 554a48d2e8..4c89d80ee2 100644
--- a/tests/test_tutorial/test_header_param_models/test_tutorial003.py
+++ b/tests/test_tutorial/test_header_param_models/test_tutorial003.py
@@ -1,21 +1,18 @@
import importlib
import pytest
-from dirty_equals import IsDict
from fastapi.testclient import TestClient
from inline_snapshot import snapshot
-from tests.utils import needs_py39, needs_py310
+from tests.utils import needs_py310
@pytest.fixture(
name="client",
params=[
- "tutorial003",
- pytest.param("tutorial003_py39", marks=needs_py39),
+ pytest.param("tutorial003_py39"),
pytest.param("tutorial003_py310", marks=needs_py310),
- "tutorial003_an",
- pytest.param("tutorial003_an_py39", marks=needs_py39),
+ pytest.param("tutorial003_an_py39"),
pytest.param("tutorial003_an_py310", marks=needs_py310),
],
)
@@ -62,33 +59,23 @@ def test_header_param_model_no_underscore(client: TestClient):
assert response.json() == snapshot(
{
"detail": [
- IsDict(
- {
- "type": "missing",
- "loc": ["header", "save_data"],
- "msg": "Field required",
- "input": {
- "host": "testserver",
- "traceparent": "123",
- "x_tag": [],
- "accept": "*/*",
- "accept-encoding": "gzip, deflate",
- "connection": "keep-alive",
- "user-agent": "testclient",
- "save-data": "true",
- "if-modified-since": "yesterday",
- "x-tag": ["one", "two"],
- },
- }
- )
- | IsDict(
- # TODO: remove when deprecating Pydantic v1
- {
- "type": "value_error.missing",
- "loc": ["header", "save_data"],
- "msg": "field required",
- }
- )
+ {
+ "type": "missing",
+ "loc": ["header", "save_data"],
+ "msg": "Field required",
+ "input": {
+ "host": "testserver",
+ "traceparent": "123",
+ "x_tag": [],
+ "accept": "*/*",
+ "accept-encoding": "gzip, deflate",
+ "connection": "keep-alive",
+ "user-agent": "testclient",
+ "save-data": "true",
+ "if-modified-since": "yesterday",
+ "x-tag": ["one", "two"],
+ },
+ }
]
}
)
@@ -112,29 +99,19 @@ def test_header_param_model_invalid(client: TestClient):
assert response.json() == snapshot(
{
"detail": [
- IsDict(
- {
- "type": "missing",
- "loc": ["header", "save_data"],
- "msg": "Field required",
- "input": {
- "x_tag": [],
- "host": "testserver",
- "accept": "*/*",
- "accept-encoding": "gzip, deflate",
- "connection": "keep-alive",
- "user-agent": "testclient",
- },
- }
- )
- | IsDict(
- # TODO: remove when deprecating Pydantic v1
- {
- "type": "value_error.missing",
- "loc": ["header", "save_data"],
- "msg": "field required",
- }
- )
+ {
+ "type": "missing",
+ "loc": ["header", "save_data"],
+ "msg": "Field required",
+ "input": {
+ "x_tag": [],
+ "host": "testserver",
+ "accept": "*/*",
+ "accept-encoding": "gzip, deflate",
+ "connection": "keep-alive",
+ "user-agent": "testclient",
+ },
+ }
]
}
)
@@ -185,37 +162,19 @@ def test_openapi_schema(client: TestClient):
"name": "if_modified_since",
"in": "header",
"required": False,
- "schema": IsDict(
- {
- "anyOf": [{"type": "string"}, {"type": "null"}],
- "title": "If Modified Since",
- }
- )
- | IsDict(
- # TODO: remove when deprecating Pydantic v1
- {
- "type": "string",
- "title": "If Modified Since",
- }
- ),
+ "schema": {
+ "anyOf": [{"type": "string"}, {"type": "null"}],
+ "title": "If Modified Since",
+ },
},
{
"name": "traceparent",
"in": "header",
"required": False,
- "schema": IsDict(
- {
- "anyOf": [{"type": "string"}, {"type": "null"}],
- "title": "Traceparent",
- }
- )
- | IsDict(
- # TODO: remove when deprecating Pydantic v1
- {
- "type": "string",
- "title": "Traceparent",
- }
- ),
+ "schema": {
+ "anyOf": [{"type": "string"}, {"type": "null"}],
+ "title": "Traceparent",
+ },
},
{
"name": "x_tag",
diff --git a/tests/test_tutorial/test_header_params/test_tutorial001.py b/tests/test_tutorial/test_header_params/test_tutorial001.py
index d6f7fe6189..88591b8225 100644
--- a/tests/test_tutorial/test_header_params/test_tutorial001.py
+++ b/tests/test_tutorial/test_header_params/test_tutorial001.py
@@ -1,7 +1,6 @@
import importlib
import pytest
-from dirty_equals import IsDict
from fastapi.testclient import TestClient
from ...utils import needs_py310
@@ -10,9 +9,9 @@ from ...utils import needs_py310
@pytest.fixture(
name="client",
params=[
- "tutorial001",
+ pytest.param("tutorial001_py39"),
pytest.param("tutorial001_py310", marks=needs_py310),
- "tutorial001_an",
+ pytest.param("tutorial001_an_py39"),
pytest.param("tutorial001_an_py310", marks=needs_py310),
],
)
@@ -67,16 +66,10 @@ def test_openapi_schema(client: TestClient):
"parameters": [
{
"required": False,
- "schema": IsDict(
- {
- "anyOf": [{"type": "string"}, {"type": "null"}],
- "title": "User-Agent",
- }
- )
- | IsDict(
- # TODO: remove when deprecating Pydantic v1
- {"title": "User-Agent", "type": "string"}
- ),
+ "schema": {
+ "anyOf": [{"type": "string"}, {"type": "null"}],
+ "title": "User-Agent",
+ },
"name": "user-agent",
"in": "header",
}
diff --git a/tests/test_tutorial/test_header_params/test_tutorial002.py b/tests/test_tutorial/test_header_params/test_tutorial002.py
index 7158f8651b..229f96c1f8 100644
--- a/tests/test_tutorial/test_header_params/test_tutorial002.py
+++ b/tests/test_tutorial/test_header_params/test_tutorial002.py
@@ -1,19 +1,17 @@
import importlib
import pytest
-from dirty_equals import IsDict
from fastapi.testclient import TestClient
-from ...utils import needs_py39, needs_py310
+from ...utils import needs_py310
@pytest.fixture(
name="client",
params=[
- "tutorial002",
+ pytest.param("tutorial002_py39"),
pytest.param("tutorial002_py310", marks=needs_py310),
- "tutorial002_an",
- pytest.param("tutorial002_an_py39", marks=needs_py39),
+ pytest.param("tutorial002_an_py39"),
pytest.param("tutorial002_an_py310", marks=needs_py310),
],
)
@@ -79,16 +77,10 @@ def test_openapi_schema(client: TestClient):
"parameters": [
{
"required": False,
- "schema": IsDict(
- {
- "anyOf": [{"type": "string"}, {"type": "null"}],
- "title": "Strange Header",
- }
- )
- | IsDict(
- # TODO: remove when deprecating Pydantic v1
- {"title": "Strange Header", "type": "string"}
- ),
+ "schema": {
+ "anyOf": [{"type": "string"}, {"type": "null"}],
+ "title": "Strange Header",
+ },
"name": "strange_header",
"in": "header",
}
diff --git a/tests/test_tutorial/test_header_params/test_tutorial003.py b/tests/test_tutorial/test_header_params/test_tutorial003.py
index 473b961236..cf067ccf9e 100644
--- a/tests/test_tutorial/test_header_params/test_tutorial003.py
+++ b/tests/test_tutorial/test_header_params/test_tutorial003.py
@@ -1,19 +1,17 @@
import importlib
import pytest
-from dirty_equals import IsDict
from fastapi.testclient import TestClient
-from ...utils import needs_py39, needs_py310
+from ...utils import needs_py310
@pytest.fixture(
name="client",
params=[
- "tutorial003",
+ pytest.param("tutorial003_py39"),
pytest.param("tutorial003_py310", marks=needs_py310),
- "tutorial003_an",
- pytest.param("tutorial003_an_py39", marks=needs_py39),
+ pytest.param("tutorial003_an_py39"),
pytest.param("tutorial003_an_py310", marks=needs_py310),
],
)
@@ -57,23 +55,13 @@ def test_openapi_schema(client: TestClient):
"parameters": [
{
"required": False,
- "schema": IsDict(
- {
- "title": "X-Token",
- "anyOf": [
- {"type": "array", "items": {"type": "string"}},
- {"type": "null"},
- ],
- }
- )
- | IsDict(
- # TODO: remove when deprecating Pydantic v1
- {
- "title": "X-Token",
- "type": "array",
- "items": {"type": "string"},
- }
- ),
+ "schema": {
+ "title": "X-Token",
+ "anyOf": [
+ {"type": "array", "items": {"type": "string"}},
+ {"type": "null"},
+ ],
+ },
"name": "x-token",
"in": "header",
}
diff --git a/tests/test_tutorial/test_metadata/test_tutorial001.py b/tests/test_tutorial/test_metadata/test_tutorial001.py
index 04e8ff82b0..ead48577d0 100644
--- a/tests/test_tutorial/test_metadata/test_tutorial001.py
+++ b/tests/test_tutorial/test_metadata/test_tutorial001.py
@@ -1,6 +1,6 @@
from fastapi.testclient import TestClient
-from docs_src.metadata.tutorial001 import app
+from docs_src.metadata.tutorial001_py39 import app
client = TestClient(app)
diff --git a/tests/test_tutorial/test_metadata/test_tutorial001_1.py b/tests/test_tutorial/test_metadata/test_tutorial001_1.py
index 3efb1c4329..40878ccfd4 100644
--- a/tests/test_tutorial/test_metadata/test_tutorial001_1.py
+++ b/tests/test_tutorial/test_metadata/test_tutorial001_1.py
@@ -1,6 +1,6 @@
from fastapi.testclient import TestClient
-from docs_src.metadata.tutorial001_1 import app
+from docs_src.metadata.tutorial001_1_py39 import app
client = TestClient(app)
diff --git a/tests/test_tutorial/test_custom_response/test_tutorial004.py b/tests/test_tutorial/test_metadata/test_tutorial002.py
similarity index 61%
rename from tests/test_tutorial/test_custom_response/test_tutorial004.py
rename to tests/test_tutorial/test_metadata/test_tutorial002.py
index de60574f5e..e2814c88f9 100644
--- a/tests/test_tutorial/test_custom_response/test_tutorial004.py
+++ b/tests/test_tutorial/test_metadata/test_tutorial002.py
@@ -1,45 +1,41 @@
from fastapi.testclient import TestClient
-from docs_src.custom_response.tutorial004 import app
+from docs_src.metadata.tutorial002_py39 import app
client = TestClient(app)
-html_contents = """
-
-
- Some HTML in here
-
-
- Look ma! HTML!
-
-
- """
-
-
-def test_get_custom_response():
+def test_items():
response = client.get("/items/")
assert response.status_code == 200, response.text
- assert response.text == html_contents
+ assert response.json() == [{"name": "Foo"}]
+
+
+def test_get_openapi_json_default_url():
+ response = client.get("/openapi.json")
+ assert response.status_code == 404, response.text
def test_openapi_schema():
- response = client.get("/openapi.json")
+ response = client.get("/api/v1/openapi.json")
assert response.status_code == 200, response.text
assert response.json() == {
"openapi": "3.1.0",
- "info": {"title": "FastAPI", "version": "0.1.0"},
+ "info": {
+ "title": "FastAPI",
+ "version": "0.1.0",
+ },
"paths": {
"/items/": {
"get": {
+ "summary": "Read Items",
+ "operationId": "read_items_items__get",
"responses": {
"200": {
"description": "Successful Response",
- "content": {"text/html": {"schema": {"type": "string"}}},
+ "content": {"application/json": {"schema": {}}},
}
},
- "summary": "Read Items",
- "operationId": "read_items_items__get",
}
}
},
diff --git a/tests/test_tutorial/test_metadata/test_tutorial003.py b/tests/test_tutorial/test_metadata/test_tutorial003.py
new file mode 100644
index 0000000000..085c271cdb
--- /dev/null
+++ b/tests/test_tutorial/test_metadata/test_tutorial003.py
@@ -0,0 +1,53 @@
+from fastapi.testclient import TestClient
+
+from docs_src.metadata.tutorial003_py39 import app
+
+client = TestClient(app)
+
+
+def test_items():
+ response = client.get("/items/")
+ assert response.status_code == 200, response.text
+ assert response.json() == [{"name": "Foo"}]
+
+
+def test_openapi_schema():
+ response = client.get("/openapi.json")
+ assert response.status_code == 200, response.text
+ assert response.json() == {
+ "openapi": "3.1.0",
+ "info": {
+ "title": "FastAPI",
+ "version": "0.1.0",
+ },
+ "paths": {
+ "/items/": {
+ "get": {
+ "summary": "Read Items",
+ "operationId": "read_items_items__get",
+ "responses": {
+ "200": {
+ "description": "Successful Response",
+ "content": {"application/json": {"schema": {}}},
+ }
+ },
+ }
+ }
+ },
+ }
+
+
+def test_swagger_ui_default_url():
+ response = client.get("/docs")
+ assert response.status_code == 404, response.text
+
+
+def test_swagger_ui_custom_url():
+ response = client.get("/documentation")
+ assert response.status_code == 200, response.text
+ assert "FastAPI - Swagger UI" in response.text
+
+
+def test_redoc_ui_default_url():
+ response = client.get("/redoc")
+ assert response.status_code == 404, response.text
diff --git a/tests/test_tutorial/test_metadata/test_tutorial004.py b/tests/test_tutorial/test_metadata/test_tutorial004.py
index 5072203712..4ef93fd5e3 100644
--- a/tests/test_tutorial/test_metadata/test_tutorial004.py
+++ b/tests/test_tutorial/test_metadata/test_tutorial004.py
@@ -1,6 +1,6 @@
from fastapi.testclient import TestClient
-from docs_src.metadata.tutorial004 import app
+from docs_src.metadata.tutorial004_py39 import app
client = TestClient(app)
diff --git a/tests/test_tutorial/test_middleware/__init__.py b/tests/test_tutorial/test_middleware/__init__.py
new file mode 100644
index 0000000000..e69de29bb2
diff --git a/tests/test_tutorial/test_middleware/test_tutorial001.py b/tests/test_tutorial/test_middleware/test_tutorial001.py
new file mode 100644
index 0000000000..cbcfd4146f
--- /dev/null
+++ b/tests/test_tutorial/test_middleware/test_tutorial001.py
@@ -0,0 +1,24 @@
+from fastapi.testclient import TestClient
+
+from docs_src.middleware.tutorial001_py39 import app
+
+client = TestClient(app)
+
+
+def test_response_headers():
+ response = client.get("/openapi.json")
+ assert response.status_code == 200, response.text
+ assert "X-Process-Time" in response.headers
+
+
+def test_openapi_schema():
+ response = client.get("/openapi.json")
+ assert response.status_code == 200, response.text
+ assert response.json() == {
+ "openapi": "3.1.0",
+ "info": {
+ "title": "FastAPI",
+ "version": "0.1.0",
+ },
+ "paths": {},
+ }
diff --git a/tests/test_tutorial/test_openapi_callbacks/test_tutorial001.py b/tests/test_tutorial/test_openapi_callbacks/test_tutorial001.py
index 2df2b98893..6fde96cb5b 100644
--- a/tests/test_tutorial/test_openapi_callbacks/test_tutorial001.py
+++ b/tests/test_tutorial/test_openapi_callbacks/test_tutorial001.py
@@ -2,7 +2,6 @@ import importlib
from types import ModuleType
import pytest
-from dirty_equals import IsDict
from fastapi.testclient import TestClient
from tests.utils import needs_py310
@@ -11,7 +10,7 @@ from tests.utils import needs_py310
@pytest.fixture(
name="mod",
params=[
- pytest.param("tutorial001"),
+ pytest.param("tutorial001_py39"),
pytest.param("tutorial001_py310", marks=needs_py310),
],
)
@@ -55,30 +54,18 @@ def test_openapi_schema(client: TestClient):
"parameters": [
{
"required": False,
- "schema": IsDict(
- {
- "anyOf": [
- {
- "type": "string",
- "format": "uri",
- "minLength": 1,
- "maxLength": 2083,
- },
- {"type": "null"},
- ],
- "title": "Callback Url",
- }
- )
- | IsDict(
- # TODO: remove when deprecating Pydantic v1
- {
- "title": "Callback Url",
- "maxLength": 2083,
- "minLength": 1,
- "type": "string",
- "format": "uri",
- }
- ),
+ "schema": {
+ "anyOf": [
+ {
+ "type": "string",
+ "format": "uri",
+ "minLength": 1,
+ "maxLength": 2083,
+ },
+ {"type": "null"},
+ ],
+ "title": "Callback Url",
+ },
"name": "callback_url",
"in": "query",
}
@@ -171,16 +158,10 @@ def test_openapi_schema(client: TestClient):
"type": "object",
"properties": {
"id": {"title": "Id", "type": "string"},
- "title": IsDict(
- {
- "title": "Title",
- "anyOf": [{"type": "string"}, {"type": "null"}],
- }
- )
- | IsDict(
- # TODO: remove when deprecating Pydantic v1
- {"title": "Title", "type": "string"}
- ),
+ "title": {
+ "title": "Title",
+ "anyOf": [{"type": "string"}, {"type": "null"}],
+ },
"customer": {"title": "Customer", "type": "string"},
"total": {"title": "Total", "type": "number"},
},
diff --git a/tests/test_tutorial/test_openapi_webhooks/test_tutorial001.py b/tests/test_tutorial/test_openapi_webhooks/test_tutorial001.py
index dc67ec401d..27619489fa 100644
--- a/tests/test_tutorial/test_openapi_webhooks/test_tutorial001.py
+++ b/tests/test_tutorial/test_openapi_webhooks/test_tutorial001.py
@@ -1,6 +1,6 @@
from fastapi.testclient import TestClient
-from docs_src.openapi_webhooks.tutorial001 import app
+from docs_src.openapi_webhooks.tutorial001_py39 import app
client = TestClient(app)
diff --git a/tests/test_tutorial/test_path_operation_advanced_configurations/test_tutorial001.py b/tests/test_tutorial/test_path_operation_advanced_configurations/test_tutorial001.py
index 95542398e4..ee0b707108 100644
--- a/tests/test_tutorial/test_path_operation_advanced_configurations/test_tutorial001.py
+++ b/tests/test_tutorial/test_path_operation_advanced_configurations/test_tutorial001.py
@@ -1,6 +1,6 @@
from fastapi.testclient import TestClient
-from docs_src.path_operation_advanced_configuration.tutorial001 import app
+from docs_src.path_operation_advanced_configuration.tutorial001_py39 import app
client = TestClient(app)
diff --git a/tests/test_tutorial/test_path_operation_advanced_configurations/test_tutorial002.py b/tests/test_tutorial/test_path_operation_advanced_configurations/test_tutorial002.py
index d1388c3670..f6580d72e3 100644
--- a/tests/test_tutorial/test_path_operation_advanced_configurations/test_tutorial002.py
+++ b/tests/test_tutorial/test_path_operation_advanced_configurations/test_tutorial002.py
@@ -1,6 +1,6 @@
from fastapi.testclient import TestClient
-from docs_src.path_operation_advanced_configuration.tutorial002 import app
+from docs_src.path_operation_advanced_configuration.tutorial002_py39 import app
client = TestClient(app)
diff --git a/tests/test_tutorial/test_path_operation_advanced_configurations/test_tutorial003.py b/tests/test_tutorial/test_path_operation_advanced_configurations/test_tutorial003.py
index 313bb2a04a..104554fce3 100644
--- a/tests/test_tutorial/test_path_operation_advanced_configurations/test_tutorial003.py
+++ b/tests/test_tutorial/test_path_operation_advanced_configurations/test_tutorial003.py
@@ -1,6 +1,6 @@
from fastapi.testclient import TestClient
-from docs_src.path_operation_advanced_configuration.tutorial003 import app
+from docs_src.path_operation_advanced_configuration.tutorial003_py39 import app
client = TestClient(app)
diff --git a/tests/test_tutorial/test_path_operation_advanced_configurations/test_tutorial004.py b/tests/test_tutorial/test_path_operation_advanced_configurations/test_tutorial004.py
index da5782d189..a95540731d 100644
--- a/tests/test_tutorial/test_path_operation_advanced_configurations/test_tutorial004.py
+++ b/tests/test_tutorial/test_path_operation_advanced_configurations/test_tutorial004.py
@@ -3,14 +3,13 @@ import importlib
import pytest
from fastapi.testclient import TestClient
-from ...utils import needs_py39, needs_py310, needs_pydanticv1, needs_pydanticv2
+from ...utils import needs_py310
@pytest.fixture(
name="client",
params=[
- pytest.param("tutorial004"),
- pytest.param("tutorial004_py39", marks=needs_py39),
+ pytest.param("tutorial004_py39"),
pytest.param("tutorial004_py310", marks=needs_py310),
],
)
@@ -36,7 +35,6 @@ def test_query_params_str_validations(client: TestClient):
}
-@needs_pydanticv2
def test_openapi_schema(client: TestClient):
response = client.get("/openapi.json")
assert response.status_code == 200, response.text
@@ -136,100 +134,3 @@ def test_openapi_schema(client: TestClient):
}
},
}
-
-
-# TODO: remove when deprecating Pydantic v1
-@needs_pydanticv1
-def test_openapi_schema_pv1(client: TestClient):
- response = client.get("/openapi.json")
- assert response.status_code == 200, response.text
- assert response.json() == {
- "openapi": "3.1.0",
- "info": {"title": "FastAPI", "version": "0.1.0"},
- "paths": {
- "/items/": {
- "post": {
- "responses": {
- "200": {
- "description": "Successful Response",
- "content": {
- "application/json": {
- "schema": {"$ref": "#/components/schemas/Item"}
- }
- },
- },
- "422": {
- "description": "Validation Error",
- "content": {
- "application/json": {
- "schema": {
- "$ref": "#/components/schemas/HTTPValidationError"
- }
- }
- },
- },
- },
- "summary": "Create an item",
- "description": "Create an item with all the information:\n\n- **name**: each item must have a name\n- **description**: a long description\n- **price**: required\n- **tax**: if the item doesn't have tax, you can omit this\n- **tags**: a set of unique tag strings for this item",
- "operationId": "create_item_items__post",
- "requestBody": {
- "content": {
- "application/json": {
- "schema": {"$ref": "#/components/schemas/Item"}
- }
- },
- "required": True,
- },
- }
- }
- },
- "components": {
- "schemas": {
- "Item": {
- "title": "Item",
- "required": ["name", "price"],
- "type": "object",
- "properties": {
- "name": {"title": "Name", "type": "string"},
- "description": {"title": "Description", "type": "string"},
- "price": {"title": "Price", "type": "number"},
- "tax": {"title": "Tax", "type": "number"},
- "tags": {
- "title": "Tags",
- "uniqueItems": True,
- "type": "array",
- "items": {"type": "string"},
- "default": [],
- },
- },
- },
- "ValidationError": {
- "title": "ValidationError",
- "required": ["loc", "msg", "type"],
- "type": "object",
- "properties": {
- "loc": {
- "title": "Location",
- "type": "array",
- "items": {
- "anyOf": [{"type": "string"}, {"type": "integer"}]
- },
- },
- "msg": {"title": "Message", "type": "string"},
- "type": {"title": "Error Type", "type": "string"},
- },
- },
- "HTTPValidationError": {
- "title": "HTTPValidationError",
- "type": "object",
- "properties": {
- "detail": {
- "title": "Detail",
- "type": "array",
- "items": {"$ref": "#/components/schemas/ValidationError"},
- }
- },
- },
- }
- },
- }
diff --git a/tests/test_tutorial/test_path_operation_advanced_configurations/test_tutorial005.py b/tests/test_tutorial/test_path_operation_advanced_configurations/test_tutorial005.py
index 07e2d7d202..e2a71236ff 100644
--- a/tests/test_tutorial/test_path_operation_advanced_configurations/test_tutorial005.py
+++ b/tests/test_tutorial/test_path_operation_advanced_configurations/test_tutorial005.py
@@ -1,6 +1,6 @@
from fastapi.testclient import TestClient
-from docs_src.path_operation_advanced_configuration.tutorial005 import app
+from docs_src.path_operation_advanced_configuration.tutorial005_py39 import app
client = TestClient(app)
diff --git a/tests/test_tutorial/test_path_operation_advanced_configurations/test_tutorial006.py b/tests/test_tutorial/test_path_operation_advanced_configurations/test_tutorial006.py
index f92c59015e..9484f7f573 100644
--- a/tests/test_tutorial/test_path_operation_advanced_configurations/test_tutorial006.py
+++ b/tests/test_tutorial/test_path_operation_advanced_configurations/test_tutorial006.py
@@ -1,6 +1,6 @@
from fastapi.testclient import TestClient
-from docs_src.path_operation_advanced_configuration.tutorial006 import app
+from docs_src.path_operation_advanced_configuration.tutorial006_py39 import app
client = TestClient(app)
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 a90337a63d..d5f284e3bd 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
@@ -3,14 +3,11 @@ import importlib
import pytest
from fastapi.testclient import TestClient
-from ...utils import needs_py39, needs_pydanticv2
-
@pytest.fixture(
name="client",
params=[
- pytest.param("tutorial007"),
- pytest.param("tutorial007_py39", marks=needs_py39),
+ pytest.param("tutorial007_py39"),
],
)
def get_client(request: pytest.FixtureRequest):
@@ -22,7 +19,6 @@ def get_client(request: pytest.FixtureRequest):
return client
-@needs_pydanticv2
def test_post(client: TestClient):
yaml_data = """
name: Deadpoolio
@@ -39,7 +35,6 @@ def test_post(client: TestClient):
}
-@needs_pydanticv2
def test_post_broken_yaml(client: TestClient):
yaml_data = """
name: Deadpoolio
@@ -53,7 +48,6 @@ def test_post_broken_yaml(client: TestClient):
assert response.json() == {"detail": "Invalid YAML"}
-@needs_pydanticv2
def test_post_invalid(client: TestClient):
yaml_data = """
name: Deadpoolio
@@ -78,7 +72,6 @@ def test_post_invalid(client: TestClient):
}
-@needs_pydanticv2
def test_openapi_schema(client: TestClient):
response = client.get("/openapi.json")
assert response.status_code == 200, response.text
diff --git a/tests/test_tutorial/test_path_operation_advanced_configurations/test_tutorial007_pv1.py b/tests/test_tutorial/test_path_operation_advanced_configurations/test_tutorial007_pv1.py
deleted file mode 100644
index b38e4947cc..0000000000
--- a/tests/test_tutorial/test_path_operation_advanced_configurations/test_tutorial007_pv1.py
+++ /dev/null
@@ -1,116 +0,0 @@
-import importlib
-
-import pytest
-from fastapi.testclient import TestClient
-
-from ...utils import needs_py39, needs_pydanticv1
-
-
-@pytest.fixture(
- name="client",
- params=[
- pytest.param("tutorial007_pv1"),
- pytest.param("tutorial007_pv1_py39", marks=needs_py39),
- ],
-)
-def get_client(request: pytest.FixtureRequest):
- mod = importlib.import_module(
- f"docs_src.path_operation_advanced_configuration.{request.param}"
- )
-
- client = TestClient(mod.app)
- return client
-
-
-@needs_pydanticv1
-def test_post(client: TestClient):
- yaml_data = """
- name: Deadpoolio
- tags:
- - x-force
- - x-men
- - x-avengers
- """
- response = client.post("/items/", content=yaml_data)
- assert response.status_code == 200, response.text
- assert response.json() == {
- "name": "Deadpoolio",
- "tags": ["x-force", "x-men", "x-avengers"],
- }
-
-
-@needs_pydanticv1
-def test_post_broken_yaml(client: TestClient):
- yaml_data = """
- name: Deadpoolio
- tags:
- x - x-force
- x - x-men
- x - x-avengers
- """
- response = client.post("/items/", content=yaml_data)
- assert response.status_code == 422, response.text
- assert response.json() == {"detail": "Invalid YAML"}
-
-
-@needs_pydanticv1
-def test_post_invalid(client: TestClient):
- yaml_data = """
- name: Deadpoolio
- tags:
- - x-force
- - x-men
- - x-avengers
- - sneaky: object
- """
- response = client.post("/items/", content=yaml_data)
- assert response.status_code == 422, response.text
- assert response.json() == {
- "detail": [
- {"loc": ["tags", 3], "msg": "str type expected", "type": "type_error.str"}
- ]
- }
-
-
-@needs_pydanticv1
-def test_openapi_schema(client: TestClient):
- response = client.get("/openapi.json")
- assert response.status_code == 200, response.text
- assert response.json() == {
- "openapi": "3.1.0",
- "info": {"title": "FastAPI", "version": "0.1.0"},
- "paths": {
- "/items/": {
- "post": {
- "summary": "Create Item",
- "operationId": "create_item_items__post",
- "requestBody": {
- "content": {
- "application/x-yaml": {
- "schema": {
- "title": "Item",
- "required": ["name", "tags"],
- "type": "object",
- "properties": {
- "name": {"title": "Name", "type": "string"},
- "tags": {
- "title": "Tags",
- "type": "array",
- "items": {"type": "string"},
- },
- },
- }
- }
- },
- "required": True,
- },
- "responses": {
- "200": {
- "description": "Successful Response",
- "content": {"application/json": {"schema": {}}},
- }
- },
- }
- }
- },
- }
diff --git a/tests/test_tutorial/test_path_operation_configurations/test_tutorial001.py b/tests/test_tutorial/test_path_operation_configurations/test_tutorial001.py
new file mode 100644
index 0000000000..085d1f5e19
--- /dev/null
+++ b/tests/test_tutorial/test_path_operation_configurations/test_tutorial001.py
@@ -0,0 +1,186 @@
+import importlib
+
+import pytest
+from dirty_equals import IsList
+from fastapi.testclient import TestClient
+
+from ...utils import needs_py310
+
+
+@pytest.fixture(
+ name="client",
+ params=[
+ pytest.param("tutorial001_py39"),
+ pytest.param("tutorial001_py310", marks=needs_py310),
+ ],
+)
+def get_client(request: pytest.FixtureRequest) -> TestClient:
+ mod = importlib.import_module(
+ f"docs_src.path_operation_configuration.{request.param}"
+ )
+ return TestClient(mod.app)
+
+
+def test_post_items(client: TestClient):
+ response = client.post(
+ "/items/",
+ json={
+ "name": "Foo",
+ "description": "Item description",
+ "price": 42.0,
+ "tax": 3.2,
+ "tags": ["bar", "baz"],
+ },
+ )
+ assert response.status_code == 201, response.text
+ assert response.json() == {
+ "name": "Foo",
+ "description": "Item description",
+ "price": 42.0,
+ "tax": 3.2,
+ "tags": IsList("bar", "baz", check_order=False),
+ }
+
+
+def test_openapi_schema(client: TestClient):
+ response = client.get("/openapi.json")
+ assert response.status_code == 200, response.text
+ assert response.json() == {
+ "openapi": "3.1.0",
+ "info": {"title": "FastAPI", "version": "0.1.0"},
+ "paths": {
+ "/items/": {
+ "post": {
+ "summary": "Create Item",
+ "operationId": "create_item_items__post",
+ "requestBody": {
+ "content": {
+ "application/json": {
+ "schema": {"$ref": "#/components/schemas/Item"}
+ }
+ },
+ "required": True,
+ },
+ "responses": {
+ "201": {
+ "description": "Successful Response",
+ "content": {
+ "application/json": {
+ "schema": {"$ref": "#/components/schemas/Item"}
+ }
+ },
+ },
+ "422": {
+ "description": "Validation Error",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/HTTPValidationError"
+ }
+ }
+ },
+ },
+ },
+ },
+ },
+ },
+ "components": {
+ "schemas": {
+ "HTTPValidationError": {
+ "properties": {
+ "detail": {
+ "items": {
+ "$ref": "#/components/schemas/ValidationError",
+ },
+ "title": "Detail",
+ "type": "array",
+ },
+ },
+ "title": "HTTPValidationError",
+ "type": "object",
+ },
+ "Item": {
+ "properties": {
+ "description": {
+ "anyOf": [
+ {
+ "type": "string",
+ },
+ {
+ "type": "null",
+ },
+ ],
+ "title": "Description",
+ },
+ "name": {
+ "title": "Name",
+ "type": "string",
+ },
+ "price": {
+ "title": "Price",
+ "type": "number",
+ },
+ "tags": {
+ "default": [],
+ "items": {
+ "type": "string",
+ },
+ "title": "Tags",
+ "type": "array",
+ "uniqueItems": True,
+ },
+ "tax": {
+ "anyOf": [
+ {
+ "type": "number",
+ },
+ {
+ "type": "null",
+ },
+ ],
+ "title": "Tax",
+ },
+ },
+ "required": [
+ "name",
+ "price",
+ ],
+ "title": "Item",
+ "type": "object",
+ },
+ "ValidationError": {
+ "properties": {
+ "loc": {
+ "items": {
+ "anyOf": [
+ {
+ "type": "string",
+ },
+ {
+ "type": "integer",
+ },
+ ],
+ },
+ "title": "Location",
+ "type": "array",
+ },
+ "msg": {
+ "title": "Message",
+ "type": "string",
+ },
+ "type": {
+ "title": "Error Type",
+ "type": "string",
+ },
+ },
+ "required": [
+ "loc",
+ "msg",
+ "type",
+ ],
+ "title": "ValidationError",
+ "type": "object",
+ },
+ },
+ },
+ }
diff --git a/tests/test_tutorial/test_path_operation_configurations/test_tutorial002.py b/tests/test_tutorial/test_path_operation_configurations/test_tutorial002.py
new file mode 100644
index 0000000000..c7414d756a
--- /dev/null
+++ b/tests/test_tutorial/test_path_operation_configurations/test_tutorial002.py
@@ -0,0 +1,223 @@
+import importlib
+
+import pytest
+from dirty_equals import IsList
+from fastapi.testclient import TestClient
+
+from ...utils import needs_py310
+
+
+@pytest.fixture(
+ name="client",
+ params=[
+ pytest.param("tutorial002_py39"),
+ pytest.param("tutorial002_py310", marks=needs_py310),
+ ],
+)
+def get_client(request: pytest.FixtureRequest) -> TestClient:
+ mod = importlib.import_module(
+ f"docs_src.path_operation_configuration.{request.param}"
+ )
+ return TestClient(mod.app)
+
+
+def test_post_items(client: TestClient):
+ response = client.post(
+ "/items/",
+ json={
+ "name": "Foo",
+ "description": "Item description",
+ "price": 42.0,
+ "tax": 3.2,
+ "tags": ["bar", "baz"],
+ },
+ )
+ assert response.status_code == 200, response.text
+ assert response.json() == {
+ "name": "Foo",
+ "description": "Item description",
+ "price": 42.0,
+ "tax": 3.2,
+ "tags": IsList("bar", "baz", check_order=False),
+ }
+
+
+def test_get_items(client: TestClient):
+ response = client.get("/items/")
+ assert response.status_code == 200, response.text
+ assert response.json() == [{"name": "Foo", "price": 42}]
+
+
+def test_get_users(client: TestClient):
+ response = client.get("/users/")
+ assert response.status_code == 200, response.text
+ assert response.json() == [{"username": "johndoe"}]
+
+
+def test_openapi_schema(client: TestClient):
+ response = client.get("/openapi.json")
+ assert response.status_code == 200, response.text
+ assert response.json() == {
+ "openapi": "3.1.0",
+ "info": {"title": "FastAPI", "version": "0.1.0"},
+ "paths": {
+ "/items/": {
+ "get": {
+ "tags": ["items"],
+ "summary": "Read Items",
+ "operationId": "read_items_items__get",
+ "responses": {
+ "200": {
+ "description": "Successful Response",
+ "content": {"application/json": {"schema": {}}},
+ }
+ },
+ },
+ "post": {
+ "tags": ["items"],
+ "summary": "Create Item",
+ "operationId": "create_item_items__post",
+ "requestBody": {
+ "content": {
+ "application/json": {
+ "schema": {"$ref": "#/components/schemas/Item"}
+ }
+ },
+ "required": True,
+ },
+ "responses": {
+ "200": {
+ "description": "Successful Response",
+ "content": {
+ "application/json": {
+ "schema": {"$ref": "#/components/schemas/Item"}
+ }
+ },
+ },
+ "422": {
+ "description": "Validation Error",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/HTTPValidationError"
+ }
+ }
+ },
+ },
+ },
+ },
+ },
+ "/users/": {
+ "get": {
+ "tags": ["users"],
+ "summary": "Read Users",
+ "operationId": "read_users_users__get",
+ "responses": {
+ "200": {
+ "description": "Successful Response",
+ "content": {"application/json": {"schema": {}}},
+ }
+ },
+ }
+ },
+ },
+ "components": {
+ "schemas": {
+ "HTTPValidationError": {
+ "properties": {
+ "detail": {
+ "items": {
+ "$ref": "#/components/schemas/ValidationError",
+ },
+ "title": "Detail",
+ "type": "array",
+ },
+ },
+ "title": "HTTPValidationError",
+ "type": "object",
+ },
+ "Item": {
+ "properties": {
+ "description": {
+ "anyOf": [
+ {
+ "type": "string",
+ },
+ {
+ "type": "null",
+ },
+ ],
+ "title": "Description",
+ },
+ "name": {
+ "title": "Name",
+ "type": "string",
+ },
+ "price": {
+ "title": "Price",
+ "type": "number",
+ },
+ "tags": {
+ "default": [],
+ "items": {
+ "type": "string",
+ },
+ "title": "Tags",
+ "type": "array",
+ "uniqueItems": True,
+ },
+ "tax": {
+ "anyOf": [
+ {
+ "type": "number",
+ },
+ {
+ "type": "null",
+ },
+ ],
+ "title": "Tax",
+ },
+ },
+ "required": [
+ "name",
+ "price",
+ ],
+ "title": "Item",
+ "type": "object",
+ },
+ "ValidationError": {
+ "properties": {
+ "loc": {
+ "items": {
+ "anyOf": [
+ {
+ "type": "string",
+ },
+ {
+ "type": "integer",
+ },
+ ],
+ },
+ "title": "Location",
+ "type": "array",
+ },
+ "msg": {
+ "title": "Message",
+ "type": "string",
+ },
+ "type": {
+ "title": "Error Type",
+ "type": "string",
+ },
+ },
+ "required": [
+ "loc",
+ "msg",
+ "type",
+ ],
+ "title": "ValidationError",
+ "type": "object",
+ },
+ },
+ },
+ }
diff --git a/tests/test_tutorial/test_path_operation_configurations/test_tutorial002b.py b/tests/test_tutorial/test_path_operation_configurations/test_tutorial002b.py
index 58dec5769d..5a0193adfa 100644
--- a/tests/test_tutorial/test_path_operation_configurations/test_tutorial002b.py
+++ b/tests/test_tutorial/test_path_operation_configurations/test_tutorial002b.py
@@ -1,6 +1,6 @@
from fastapi.testclient import TestClient
-from docs_src.path_operation_configuration.tutorial002b import app
+from docs_src.path_operation_configuration.tutorial002b_py39 import app
client = TestClient(app)
diff --git a/tests/test_tutorial/test_path_operation_configurations/test_tutorial003_tutorial004.py b/tests/test_tutorial/test_path_operation_configurations/test_tutorial003_tutorial004.py
new file mode 100644
index 0000000000..791db24625
--- /dev/null
+++ b/tests/test_tutorial/test_path_operation_configurations/test_tutorial003_tutorial004.py
@@ -0,0 +1,208 @@
+import importlib
+from textwrap import dedent
+
+import pytest
+from dirty_equals import IsList
+from fastapi.testclient import TestClient
+
+from ...utils import needs_py310
+
+DESCRIPTIONS = {
+ "tutorial003": "Create an item with all the information, name, description, price, tax and a set of unique tags",
+ "tutorial004": dedent("""
+ Create an item with all the information:
+
+ - **name**: each item must have a name
+ - **description**: a long description
+ - **price**: required
+ - **tax**: if the item doesn't have tax, you can omit this
+ - **tags**: a set of unique tag strings for this item
+ """).strip(),
+}
+
+
+@pytest.fixture(
+ name="mod_name",
+ params=[
+ pytest.param("tutorial003_py39"),
+ pytest.param("tutorial003_py310", marks=needs_py310),
+ pytest.param("tutorial004_py39"),
+ pytest.param("tutorial004_py310", marks=needs_py310),
+ ],
+)
+def get_mod_name(request: pytest.FixtureRequest) -> str:
+ return request.param
+
+
+@pytest.fixture(name="client")
+def get_client(mod_name: str) -> TestClient:
+ mod = importlib.import_module(f"docs_src.path_operation_configuration.{mod_name}")
+ return TestClient(mod.app)
+
+
+def test_post_items(client: TestClient):
+ response = client.post(
+ "/items/",
+ json={
+ "name": "Foo",
+ "description": "Item description",
+ "price": 42.0,
+ "tax": 3.2,
+ "tags": ["bar", "baz"],
+ },
+ )
+ assert response.status_code == 200, response.text
+ assert response.json() == {
+ "name": "Foo",
+ "description": "Item description",
+ "price": 42.0,
+ "tax": 3.2,
+ "tags": IsList("bar", "baz", check_order=False),
+ }
+
+
+def test_openapi_schema(client: TestClient, mod_name: str):
+ mod_name = mod_name[:11]
+
+ response = client.get("/openapi.json")
+ assert response.status_code == 200, response.text
+ assert response.json() == {
+ "openapi": "3.1.0",
+ "info": {"title": "FastAPI", "version": "0.1.0"},
+ "paths": {
+ "/items/": {
+ "post": {
+ "summary": "Create an item",
+ "description": DESCRIPTIONS[mod_name],
+ "operationId": "create_item_items__post",
+ "requestBody": {
+ "content": {
+ "application/json": {
+ "schema": {"$ref": "#/components/schemas/Item"}
+ }
+ },
+ "required": True,
+ },
+ "responses": {
+ "200": {
+ "description": "Successful Response",
+ "content": {
+ "application/json": {
+ "schema": {"$ref": "#/components/schemas/Item"}
+ }
+ },
+ },
+ "422": {
+ "description": "Validation Error",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/HTTPValidationError"
+ }
+ }
+ },
+ },
+ },
+ },
+ },
+ },
+ "components": {
+ "schemas": {
+ "HTTPValidationError": {
+ "properties": {
+ "detail": {
+ "items": {
+ "$ref": "#/components/schemas/ValidationError",
+ },
+ "title": "Detail",
+ "type": "array",
+ },
+ },
+ "title": "HTTPValidationError",
+ "type": "object",
+ },
+ "Item": {
+ "properties": {
+ "description": {
+ "anyOf": [
+ {
+ "type": "string",
+ },
+ {
+ "type": "null",
+ },
+ ],
+ "title": "Description",
+ },
+ "name": {
+ "title": "Name",
+ "type": "string",
+ },
+ "price": {
+ "title": "Price",
+ "type": "number",
+ },
+ "tags": {
+ "default": [],
+ "items": {
+ "type": "string",
+ },
+ "title": "Tags",
+ "type": "array",
+ "uniqueItems": True,
+ },
+ "tax": {
+ "anyOf": [
+ {
+ "type": "number",
+ },
+ {
+ "type": "null",
+ },
+ ],
+ "title": "Tax",
+ },
+ },
+ "required": [
+ "name",
+ "price",
+ ],
+ "title": "Item",
+ "type": "object",
+ },
+ "ValidationError": {
+ "properties": {
+ "loc": {
+ "items": {
+ "anyOf": [
+ {
+ "type": "string",
+ },
+ {
+ "type": "integer",
+ },
+ ],
+ },
+ "title": "Location",
+ "type": "array",
+ },
+ "msg": {
+ "title": "Message",
+ "type": "string",
+ },
+ "type": {
+ "title": "Error Type",
+ "type": "string",
+ },
+ },
+ "required": [
+ "loc",
+ "msg",
+ "type",
+ ],
+ "title": "ValidationError",
+ "type": "object",
+ },
+ },
+ },
+ }
diff --git a/tests/test_tutorial/test_path_operation_configurations/test_tutorial005.py b/tests/test_tutorial/test_path_operation_configurations/test_tutorial005.py
index 0742f5d0e8..c5a3aec1d9 100644
--- a/tests/test_tutorial/test_path_operation_configurations/test_tutorial005.py
+++ b/tests/test_tutorial/test_path_operation_configurations/test_tutorial005.py
@@ -3,14 +3,13 @@ import importlib
import pytest
from fastapi.testclient import TestClient
-from ...utils import needs_py39, needs_py310, needs_pydanticv1, needs_pydanticv2
+from ...utils import needs_py310
@pytest.fixture(
name="client",
params=[
- "tutorial005",
- pytest.param("tutorial005_py39", marks=needs_py39),
+ pytest.param("tutorial005_py39"),
pytest.param("tutorial005_py310", marks=needs_py310),
],
)
@@ -35,7 +34,6 @@ def test_query_params_str_validations(client: TestClient):
}
-@needs_pydanticv2
def test_openapi_schema(client: TestClient):
response = client.get("/openapi.json")
assert response.status_code == 200, response.text
@@ -135,100 +133,3 @@ def test_openapi_schema(client: TestClient):
}
},
}
-
-
-# TODO: remove when deprecating Pydantic v1
-@needs_pydanticv1
-def test_openapi_schema_pv1(client: TestClient):
- response = client.get("/openapi.json")
- assert response.status_code == 200, response.text
- assert response.json() == {
- "openapi": "3.1.0",
- "info": {"title": "FastAPI", "version": "0.1.0"},
- "paths": {
- "/items/": {
- "post": {
- "responses": {
- "200": {
- "description": "The created item",
- "content": {
- "application/json": {
- "schema": {"$ref": "#/components/schemas/Item"}
- }
- },
- },
- "422": {
- "description": "Validation Error",
- "content": {
- "application/json": {
- "schema": {
- "$ref": "#/components/schemas/HTTPValidationError"
- }
- }
- },
- },
- },
- "summary": "Create an item",
- "description": "Create an item with all the information:\n\n- **name**: each item must have a name\n- **description**: a long description\n- **price**: required\n- **tax**: if the item doesn't have tax, you can omit this\n- **tags**: a set of unique tag strings for this item",
- "operationId": "create_item_items__post",
- "requestBody": {
- "content": {
- "application/json": {
- "schema": {"$ref": "#/components/schemas/Item"}
- }
- },
- "required": True,
- },
- }
- }
- },
- "components": {
- "schemas": {
- "Item": {
- "title": "Item",
- "required": ["name", "price"],
- "type": "object",
- "properties": {
- "name": {"title": "Name", "type": "string"},
- "description": {"title": "Description", "type": "string"},
- "price": {"title": "Price", "type": "number"},
- "tax": {"title": "Tax", "type": "number"},
- "tags": {
- "title": "Tags",
- "uniqueItems": True,
- "type": "array",
- "items": {"type": "string"},
- "default": [],
- },
- },
- },
- "ValidationError": {
- "title": "ValidationError",
- "required": ["loc", "msg", "type"],
- "type": "object",
- "properties": {
- "loc": {
- "title": "Location",
- "type": "array",
- "items": {
- "anyOf": [{"type": "string"}, {"type": "integer"}]
- },
- },
- "msg": {"title": "Message", "type": "string"},
- "type": {"title": "Error Type", "type": "string"},
- },
- },
- "HTTPValidationError": {
- "title": "HTTPValidationError",
- "type": "object",
- "properties": {
- "detail": {
- "title": "Detail",
- "type": "array",
- "items": {"$ref": "#/components/schemas/ValidationError"},
- }
- },
- },
- }
- },
- }
diff --git a/tests/test_tutorial/test_path_operation_configurations/test_tutorial006.py b/tests/test_tutorial/test_path_operation_configurations/test_tutorial006.py
index 91180d1097..5d9c55675f 100644
--- a/tests/test_tutorial/test_path_operation_configurations/test_tutorial006.py
+++ b/tests/test_tutorial/test_path_operation_configurations/test_tutorial006.py
@@ -1,7 +1,7 @@
import pytest
from fastapi.testclient import TestClient
-from docs_src.path_operation_configuration.tutorial006 import app
+from docs_src.path_operation_configuration.tutorial006_py39 import app
client = TestClient(app)
diff --git a/tests/test_tutorial/test_path_params/test_tutorial001.py b/tests/test_tutorial/test_path_params/test_tutorial001.py
new file mode 100644
index 0000000000..a898e386fb
--- /dev/null
+++ b/tests/test_tutorial/test_path_params/test_tutorial001.py
@@ -0,0 +1,116 @@
+import pytest
+from fastapi.testclient import TestClient
+
+from docs_src.path_params.tutorial001_py39 import app
+
+client = TestClient(app)
+
+
+@pytest.mark.parametrize(
+ ("item_id", "expected_response"),
+ [
+ (1, {"item_id": "1"}),
+ ("alice", {"item_id": "alice"}),
+ ],
+)
+def test_get_items(item_id, expected_response):
+ response = client.get(f"/items/{item_id}")
+ assert response.status_code == 200, response.text
+ assert response.json() == expected_response
+
+
+def test_openapi_schema():
+ response = client.get("/openapi.json")
+ assert response.status_code == 200, response.text
+ assert response.json() == {
+ "openapi": "3.1.0",
+ "info": {"title": "FastAPI", "version": "0.1.0"},
+ "paths": {
+ "/items/{item_id}": {
+ "get": {
+ "operationId": "read_item_items__item_id__get",
+ "parameters": [
+ {
+ "in": "path",
+ "name": "item_id",
+ "required": True,
+ "schema": {
+ "title": "Item Id",
+ },
+ },
+ ],
+ "responses": {
+ "200": {
+ "content": {
+ "application/json": {
+ "schema": {},
+ },
+ },
+ "description": "Successful Response",
+ },
+ "422": {
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/HTTPValidationError",
+ },
+ },
+ },
+ "description": "Validation Error",
+ },
+ },
+ "summary": "Read Item",
+ },
+ },
+ },
+ "components": {
+ "schemas": {
+ "HTTPValidationError": {
+ "properties": {
+ "detail": {
+ "items": {
+ "$ref": "#/components/schemas/ValidationError",
+ },
+ "title": "Detail",
+ "type": "array",
+ },
+ },
+ "title": "HTTPValidationError",
+ "type": "object",
+ },
+ "ValidationError": {
+ "properties": {
+ "loc": {
+ "items": {
+ "anyOf": [
+ {
+ "type": "string",
+ },
+ {
+ "type": "integer",
+ },
+ ],
+ },
+ "title": "Location",
+ "type": "array",
+ },
+ "msg": {
+ "title": "Message",
+ "type": "string",
+ },
+ "type": {
+ "title": "Error Type",
+ "type": "string",
+ },
+ },
+ "required": [
+ "loc",
+ "msg",
+ "type",
+ ],
+ "title": "ValidationError",
+ "type": "object",
+ },
+ },
+ },
+ }
diff --git a/tests/test_tutorial/test_path_params/test_tutorial002.py b/tests/test_tutorial/test_path_params/test_tutorial002.py
new file mode 100644
index 0000000000..0bfc9f807e
--- /dev/null
+++ b/tests/test_tutorial/test_path_params/test_tutorial002.py
@@ -0,0 +1,124 @@
+from fastapi.testclient import TestClient
+
+from docs_src.path_params.tutorial002_py39 import app
+
+client = TestClient(app)
+
+
+def test_get_items():
+ response = client.get("/items/1")
+ assert response.status_code == 200, response.text
+ assert response.json() == {"item_id": 1}
+
+
+def test_get_items_invalid_id():
+ response = client.get("/items/item1")
+ assert response.status_code == 422, response.text
+ assert response.json() == {
+ "detail": [
+ {
+ "input": "item1",
+ "loc": ["path", "item_id"],
+ "msg": "Input should be a valid integer, unable to parse string as an integer",
+ "type": "int_parsing",
+ }
+ ]
+ }
+
+
+def test_openapi_schema():
+ response = client.get("/openapi.json")
+ assert response.status_code == 200, response.text
+ assert response.json() == {
+ "openapi": "3.1.0",
+ "info": {"title": "FastAPI", "version": "0.1.0"},
+ "paths": {
+ "/items/{item_id}": {
+ "get": {
+ "operationId": "read_item_items__item_id__get",
+ "parameters": [
+ {
+ "in": "path",
+ "name": "item_id",
+ "required": True,
+ "schema": {
+ "title": "Item Id",
+ "type": "integer",
+ },
+ },
+ ],
+ "responses": {
+ "200": {
+ "content": {
+ "application/json": {
+ "schema": {},
+ },
+ },
+ "description": "Successful Response",
+ },
+ "422": {
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/HTTPValidationError",
+ },
+ },
+ },
+ "description": "Validation Error",
+ },
+ },
+ "summary": "Read Item",
+ },
+ },
+ },
+ "components": {
+ "schemas": {
+ "HTTPValidationError": {
+ "properties": {
+ "detail": {
+ "items": {
+ "$ref": "#/components/schemas/ValidationError",
+ },
+ "title": "Detail",
+ "type": "array",
+ },
+ },
+ "title": "HTTPValidationError",
+ "type": "object",
+ },
+ "ValidationError": {
+ "properties": {
+ "loc": {
+ "items": {
+ "anyOf": [
+ {
+ "type": "string",
+ },
+ {
+ "type": "integer",
+ },
+ ],
+ },
+ "title": "Location",
+ "type": "array",
+ },
+ "msg": {
+ "title": "Message",
+ "type": "string",
+ },
+ "type": {
+ "title": "Error Type",
+ "type": "string",
+ },
+ },
+ "required": [
+ "loc",
+ "msg",
+ "type",
+ ],
+ "title": "ValidationError",
+ "type": "object",
+ },
+ },
+ },
+ }
diff --git a/tests/test_tutorial/test_path_params/test_tutorial003.py b/tests/test_tutorial/test_path_params/test_tutorial003.py
new file mode 100644
index 0000000000..cd2c39ab06
--- /dev/null
+++ b/tests/test_tutorial/test_path_params/test_tutorial003.py
@@ -0,0 +1,133 @@
+import pytest
+from fastapi.testclient import TestClient
+
+from docs_src.path_params.tutorial003_py39 import app
+
+client = TestClient(app)
+
+
+@pytest.mark.parametrize(
+ ("user_id", "expected_response"),
+ [
+ ("me", {"user_id": "the current user"}),
+ ("alice", {"user_id": "alice"}),
+ ],
+)
+def test_get_users(user_id: str, expected_response: dict):
+ response = client.get(f"/users/{user_id}")
+ assert response.status_code == 200, response.text
+ assert response.json() == expected_response
+
+
+def test_openapi_schema():
+ response = client.get("/openapi.json")
+ assert response.status_code == 200, response.text
+ assert response.json() == {
+ "openapi": "3.1.0",
+ "info": {"title": "FastAPI", "version": "0.1.0"},
+ "paths": {
+ "/users/me": {
+ "get": {
+ "operationId": "read_user_me_users_me_get",
+ "responses": {
+ "200": {
+ "content": {
+ "application/json": {
+ "schema": {},
+ },
+ },
+ "description": "Successful Response",
+ },
+ },
+ "summary": "Read User Me",
+ },
+ },
+ "/users/{user_id}": {
+ "get": {
+ "operationId": "read_user_users__user_id__get",
+ "parameters": [
+ {
+ "in": "path",
+ "name": "user_id",
+ "required": True,
+ "schema": {
+ "title": "User Id",
+ "type": "string",
+ },
+ },
+ ],
+ "responses": {
+ "200": {
+ "content": {
+ "application/json": {
+ "schema": {},
+ },
+ },
+ "description": "Successful Response",
+ },
+ "422": {
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/HTTPValidationError",
+ },
+ },
+ },
+ "description": "Validation Error",
+ },
+ },
+ "summary": "Read User",
+ },
+ },
+ },
+ "components": {
+ "schemas": {
+ "HTTPValidationError": {
+ "properties": {
+ "detail": {
+ "items": {
+ "$ref": "#/components/schemas/ValidationError",
+ },
+ "title": "Detail",
+ "type": "array",
+ },
+ },
+ "title": "HTTPValidationError",
+ "type": "object",
+ },
+ "ValidationError": {
+ "properties": {
+ "loc": {
+ "items": {
+ "anyOf": [
+ {
+ "type": "string",
+ },
+ {
+ "type": "integer",
+ },
+ ],
+ },
+ "title": "Location",
+ "type": "array",
+ },
+ "msg": {
+ "title": "Message",
+ "type": "string",
+ },
+ "type": {
+ "title": "Error Type",
+ "type": "string",
+ },
+ },
+ "required": [
+ "loc",
+ "msg",
+ "type",
+ ],
+ "title": "ValidationError",
+ "type": "object",
+ },
+ },
+ },
+ }
diff --git a/tests/test_tutorial/test_path_params/test_tutorial003b.py b/tests/test_tutorial/test_path_params/test_tutorial003b.py
new file mode 100644
index 0000000000..8e4a26a1ca
--- /dev/null
+++ b/tests/test_tutorial/test_path_params/test_tutorial003b.py
@@ -0,0 +1,44 @@
+import asyncio
+
+from fastapi.testclient import TestClient
+
+from docs_src.path_params.tutorial003b_py39 import app, read_users2
+
+client = TestClient(app)
+
+
+def test_get_users():
+ response = client.get("/users")
+ assert response.status_code == 200, response.text
+ assert response.json() == ["Rick", "Morty"]
+
+
+def test_read_users2(): # Just for coverage
+ assert asyncio.run(read_users2()) == ["Bean", "Elfo"]
+
+
+def test_openapi_schema():
+ response = client.get("/openapi.json")
+ assert response.status_code == 200, response.text
+ assert response.json() == {
+ "openapi": "3.1.0",
+ "info": {"title": "FastAPI", "version": "0.1.0"},
+ "paths": {
+ "/users": {
+ "get": {
+ "operationId": "read_users2_users_get",
+ "responses": {
+ "200": {
+ "content": {
+ "application/json": {
+ "schema": {},
+ },
+ },
+ "description": "Successful Response",
+ },
+ },
+ "summary": "Read Users2",
+ },
+ },
+ },
+ }
diff --git a/tests/test_tutorial/test_path_params/test_tutorial004.py b/tests/test_tutorial/test_path_params/test_tutorial004.py
index acbeaca769..f7f233ccff 100644
--- a/tests/test_tutorial/test_path_params/test_tutorial004.py
+++ b/tests/test_tutorial/test_path_params/test_tutorial004.py
@@ -1,6 +1,6 @@
from fastapi.testclient import TestClient
-from docs_src.path_params.tutorial004 import app
+from docs_src.path_params.tutorial004_py39 import app
client = TestClient(app)
diff --git a/tests/test_tutorial/test_path_params/test_tutorial005.py b/tests/test_tutorial/test_path_params/test_tutorial005.py
index 2e4b0146be..86ccce7b6d 100644
--- a/tests/test_tutorial/test_path_params/test_tutorial005.py
+++ b/tests/test_tutorial/test_path_params/test_tutorial005.py
@@ -1,7 +1,6 @@
-from dirty_equals import IsDict
from fastapi.testclient import TestClient
-from docs_src.path_params.tutorial005 import app
+from docs_src.path_params.tutorial005_py39 import app
client = TestClient(app)
@@ -27,31 +26,17 @@ def test_get_enums_resnet():
def test_get_enums_invalid():
response = client.get("/models/foo")
assert response.status_code == 422
- assert response.json() == IsDict(
- {
- "detail": [
- {
- "type": "enum",
- "loc": ["path", "model_name"],
- "msg": "Input should be 'alexnet', 'resnet' or 'lenet'",
- "input": "foo",
- "ctx": {"expected": "'alexnet', 'resnet' or 'lenet'"},
- }
- ]
- }
- ) | IsDict(
- # TODO: remove when deprecating Pydantic v1
- {
- "detail": [
- {
- "ctx": {"enum_values": ["alexnet", "resnet", "lenet"]},
- "loc": ["path", "model_name"],
- "msg": "value is not a valid enumeration member; permitted: 'alexnet', 'resnet', 'lenet'",
- "type": "type_error.enum",
- }
- ]
- }
- )
+ assert response.json() == {
+ "detail": [
+ {
+ "type": "enum",
+ "loc": ["path", "model_name"],
+ "msg": "Input should be 'alexnet', 'resnet' or 'lenet'",
+ "input": "foo",
+ "ctx": {"expected": "'alexnet', 'resnet' or 'lenet'"},
+ }
+ ]
+ }
def test_openapi_schema():
@@ -106,22 +91,11 @@ def test_openapi_schema():
}
},
},
- "ModelName": IsDict(
- {
- "title": "ModelName",
- "enum": ["alexnet", "resnet", "lenet"],
- "type": "string",
- }
- )
- | IsDict(
- {
- # TODO: remove when deprecating Pydantic v1
- "title": "ModelName",
- "enum": ["alexnet", "resnet", "lenet"],
- "type": "string",
- "description": "An enumeration.",
- }
- ),
+ "ModelName": {
+ "title": "ModelName",
+ "enum": ["alexnet", "resnet", "lenet"],
+ "type": "string",
+ },
"ValidationError": {
"title": "ValidationError",
"required": ["loc", "msg", "type"],
diff --git a/tests/test_tutorial/test_path_params_numeric_validations/__init__.py b/tests/test_tutorial/test_path_params_numeric_validations/__init__.py
new file mode 100644
index 0000000000..e69de29bb2
diff --git a/tests/test_tutorial/test_path_params_numeric_validations/test_tutorial001.py b/tests/test_tutorial/test_path_params_numeric_validations/test_tutorial001.py
new file mode 100644
index 0000000000..f1e3041030
--- /dev/null
+++ b/tests/test_tutorial/test_path_params_numeric_validations/test_tutorial001.py
@@ -0,0 +1,164 @@
+import importlib
+
+import pytest
+from fastapi.testclient import TestClient
+
+from ...utils import needs_py310
+
+
+@pytest.fixture(
+ name="client",
+ params=[
+ pytest.param("tutorial001_py39"),
+ pytest.param("tutorial001_py310", marks=needs_py310),
+ pytest.param("tutorial001_an_py39"),
+ pytest.param("tutorial001_an_py310", marks=needs_py310),
+ ],
+)
+def get_client(request: pytest.FixtureRequest) -> TestClient:
+ mod = importlib.import_module(
+ f"docs_src.path_params_numeric_validations.{request.param}"
+ )
+ return TestClient(mod.app)
+
+
+@pytest.mark.parametrize(
+ "path,expected_response",
+ [
+ ("/items/42", {"item_id": 42}),
+ ("/items/123?item-query=somequery", {"item_id": 123, "q": "somequery"}),
+ ],
+)
+def test_read_items(client: TestClient, path, expected_response):
+ response = client.get(path)
+ assert response.status_code == 200, response.text
+ assert response.json() == expected_response
+
+
+def test_read_items_invalid_item_id(client: TestClient):
+ response = client.get("/items/invalid_id")
+ assert response.status_code == 422, response.text
+ assert response.json() == {
+ "detail": [
+ {
+ "loc": ["path", "item_id"],
+ "input": "invalid_id",
+ "msg": "Input should be a valid integer, unable to parse string as an integer",
+ "type": "int_parsing",
+ }
+ ]
+ }
+
+
+def test_openapi_schema(client: TestClient):
+ response = client.get("/openapi.json")
+ assert response.status_code == 200, response.text
+ assert response.json() == {
+ "openapi": "3.1.0",
+ "info": {"title": "FastAPI", "version": "0.1.0"},
+ "paths": {
+ "/items/{item_id}": {
+ "get": {
+ "summary": "Read Items",
+ "operationId": "read_items_items__item_id__get",
+ "parameters": [
+ {
+ "required": True,
+ "schema": {
+ "title": "The ID of the item to get",
+ "type": "integer",
+ },
+ "name": "item_id",
+ "in": "path",
+ },
+ {
+ "required": False,
+ "schema": {
+ "anyOf": [
+ {
+ "type": "string",
+ },
+ {
+ "type": "null",
+ },
+ ],
+ "title": "Item-Query",
+ },
+ "name": "item-query",
+ "in": "query",
+ },
+ ],
+ "responses": {
+ "200": {
+ "description": "Successful Response",
+ "content": {
+ "application/json": {
+ "schema": {},
+ }
+ },
+ },
+ "422": {
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/HTTPValidationError",
+ },
+ },
+ },
+ "description": "Validation Error",
+ },
+ },
+ }
+ }
+ },
+ "components": {
+ "schemas": {
+ "HTTPValidationError": {
+ "properties": {
+ "detail": {
+ "items": {
+ "$ref": "#/components/schemas/ValidationError",
+ },
+ "title": "Detail",
+ "type": "array",
+ },
+ },
+ "title": "HTTPValidationError",
+ "type": "object",
+ },
+ "ValidationError": {
+ "properties": {
+ "loc": {
+ "items": {
+ "anyOf": [
+ {
+ "type": "string",
+ },
+ {
+ "type": "integer",
+ },
+ ],
+ },
+ "title": "Location",
+ "type": "array",
+ },
+ "msg": {
+ "title": "Message",
+ "type": "string",
+ },
+ "type": {
+ "title": "Error Type",
+ "type": "string",
+ },
+ },
+ "required": [
+ "loc",
+ "msg",
+ "type",
+ ],
+ "title": "ValidationError",
+ "type": "object",
+ },
+ },
+ },
+ }
diff --git a/tests/test_tutorial/test_path_params_numeric_validations/test_tutorial002_tutorial003.py b/tests/test_tutorial/test_path_params_numeric_validations/test_tutorial002_tutorial003.py
new file mode 100644
index 0000000000..467c915dcd
--- /dev/null
+++ b/tests/test_tutorial/test_path_params_numeric_validations/test_tutorial002_tutorial003.py
@@ -0,0 +1,170 @@
+import importlib
+
+import pytest
+from fastapi.testclient import TestClient
+
+
+@pytest.fixture(
+ name="client",
+ params=[
+ pytest.param("tutorial002_py39"),
+ pytest.param("tutorial002_an_py39"),
+ pytest.param("tutorial003_py39"),
+ pytest.param("tutorial003_an_py39"),
+ ],
+)
+def get_client(request: pytest.FixtureRequest) -> TestClient:
+ mod = importlib.import_module(
+ f"docs_src.path_params_numeric_validations.{request.param}"
+ )
+ return TestClient(mod.app)
+
+
+@pytest.mark.parametrize(
+ "path,expected_response",
+ [
+ ("/items/42?q=", {"item_id": 42}),
+ ("/items/123?q=somequery", {"item_id": 123, "q": "somequery"}),
+ ],
+)
+def test_read_items(client: TestClient, path, expected_response):
+ response = client.get(path)
+ assert response.status_code == 200, response.text
+ assert response.json() == expected_response
+
+
+def test_read_items_invalid_item_id(client: TestClient):
+ response = client.get("/items/invalid_id?q=somequery")
+ assert response.status_code == 422, response.text
+ assert response.json() == {
+ "detail": [
+ {
+ "loc": ["path", "item_id"],
+ "input": "invalid_id",
+ "msg": "Input should be a valid integer, unable to parse string as an integer",
+ "type": "int_parsing",
+ }
+ ]
+ }
+
+
+def test_read_items_missing_q(client: TestClient):
+ response = client.get("/items/42")
+ assert response.status_code == 422, response.text
+ assert response.json() == {
+ "detail": [
+ {
+ "loc": ["query", "q"],
+ "input": None,
+ "msg": "Field required",
+ "type": "missing",
+ }
+ ]
+ }
+
+
+def test_openapi_schema(client: TestClient):
+ response = client.get("/openapi.json")
+ assert response.status_code == 200, response.text
+ assert response.json() == {
+ "openapi": "3.1.0",
+ "info": {"title": "FastAPI", "version": "0.1.0"},
+ "paths": {
+ "/items/{item_id}": {
+ "get": {
+ "summary": "Read Items",
+ "operationId": "read_items_items__item_id__get",
+ "parameters": [
+ {
+ "required": True,
+ "schema": {
+ "title": "The ID of the item to get",
+ "type": "integer",
+ },
+ "name": "item_id",
+ "in": "path",
+ },
+ {
+ "required": True,
+ "schema": {
+ "type": "string",
+ "title": "Q",
+ },
+ "name": "q",
+ "in": "query",
+ },
+ ],
+ "responses": {
+ "200": {
+ "description": "Successful Response",
+ "content": {
+ "application/json": {
+ "schema": {},
+ }
+ },
+ },
+ "422": {
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/HTTPValidationError",
+ },
+ },
+ },
+ "description": "Validation Error",
+ },
+ },
+ }
+ }
+ },
+ "components": {
+ "schemas": {
+ "HTTPValidationError": {
+ "properties": {
+ "detail": {
+ "items": {
+ "$ref": "#/components/schemas/ValidationError",
+ },
+ "title": "Detail",
+ "type": "array",
+ },
+ },
+ "title": "HTTPValidationError",
+ "type": "object",
+ },
+ "ValidationError": {
+ "properties": {
+ "loc": {
+ "items": {
+ "anyOf": [
+ {
+ "type": "string",
+ },
+ {
+ "type": "integer",
+ },
+ ],
+ },
+ "title": "Location",
+ "type": "array",
+ },
+ "msg": {
+ "title": "Message",
+ "type": "string",
+ },
+ "type": {
+ "title": "Error Type",
+ "type": "string",
+ },
+ },
+ "required": [
+ "loc",
+ "msg",
+ "type",
+ ],
+ "title": "ValidationError",
+ "type": "object",
+ },
+ },
+ },
+ }
diff --git a/tests/test_tutorial/test_path_params_numeric_validations/test_tutorial004.py b/tests/test_tutorial/test_path_params_numeric_validations/test_tutorial004.py
new file mode 100644
index 0000000000..d3593c984c
--- /dev/null
+++ b/tests/test_tutorial/test_path_params_numeric_validations/test_tutorial004.py
@@ -0,0 +1,185 @@
+import importlib
+
+import pytest
+from fastapi.testclient import TestClient
+
+
+@pytest.fixture(
+ name="client",
+ params=[
+ pytest.param("tutorial004_py39"),
+ pytest.param("tutorial004_an_py39"),
+ ],
+)
+def get_client(request: pytest.FixtureRequest) -> TestClient:
+ mod = importlib.import_module(
+ f"docs_src.path_params_numeric_validations.{request.param}"
+ )
+ return TestClient(mod.app)
+
+
+@pytest.mark.parametrize(
+ "path,expected_response",
+ [
+ ("/items/42?q=", {"item_id": 42}),
+ ("/items/1?q=somequery", {"item_id": 1, "q": "somequery"}),
+ ],
+)
+def test_read_items(client: TestClient, path, expected_response):
+ response = client.get(path)
+ assert response.status_code == 200, response.text
+ assert response.json() == expected_response
+
+
+def test_read_items_non_int_item_id(client: TestClient):
+ response = client.get("/items/invalid_id?q=somequery")
+ assert response.status_code == 422, response.text
+ assert response.json() == {
+ "detail": [
+ {
+ "loc": ["path", "item_id"],
+ "input": "invalid_id",
+ "msg": "Input should be a valid integer, unable to parse string as an integer",
+ "type": "int_parsing",
+ }
+ ]
+ }
+
+
+def test_read_items_item_id_less_than_one(client: TestClient):
+ response = client.get("/items/0?q=somequery")
+ assert response.status_code == 422, response.text
+ assert response.json() == {
+ "detail": [
+ {
+ "loc": ["path", "item_id"],
+ "input": "0",
+ "msg": "Input should be greater than or equal to 1",
+ "type": "greater_than_equal",
+ "ctx": {"ge": 1},
+ }
+ ]
+ }
+
+
+def test_read_items_missing_q(client: TestClient):
+ response = client.get("/items/42")
+ assert response.status_code == 422, response.text
+ assert response.json() == {
+ "detail": [
+ {
+ "loc": ["query", "q"],
+ "input": None,
+ "msg": "Field required",
+ "type": "missing",
+ }
+ ]
+ }
+
+
+def test_openapi_schema(client: TestClient):
+ response = client.get("/openapi.json")
+ assert response.status_code == 200, response.text
+ assert response.json() == {
+ "openapi": "3.1.0",
+ "info": {"title": "FastAPI", "version": "0.1.0"},
+ "paths": {
+ "/items/{item_id}": {
+ "get": {
+ "summary": "Read Items",
+ "operationId": "read_items_items__item_id__get",
+ "parameters": [
+ {
+ "required": True,
+ "schema": {
+ "title": "The ID of the item to get",
+ "type": "integer",
+ "minimum": 1,
+ },
+ "name": "item_id",
+ "in": "path",
+ },
+ {
+ "required": True,
+ "schema": {
+ "type": "string",
+ "title": "Q",
+ },
+ "name": "q",
+ "in": "query",
+ },
+ ],
+ "responses": {
+ "200": {
+ "description": "Successful Response",
+ "content": {
+ "application/json": {
+ "schema": {},
+ }
+ },
+ },
+ "422": {
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/HTTPValidationError",
+ },
+ },
+ },
+ "description": "Validation Error",
+ },
+ },
+ }
+ }
+ },
+ "components": {
+ "schemas": {
+ "HTTPValidationError": {
+ "properties": {
+ "detail": {
+ "items": {
+ "$ref": "#/components/schemas/ValidationError",
+ },
+ "title": "Detail",
+ "type": "array",
+ },
+ },
+ "title": "HTTPValidationError",
+ "type": "object",
+ },
+ "ValidationError": {
+ "properties": {
+ "loc": {
+ "items": {
+ "anyOf": [
+ {
+ "type": "string",
+ },
+ {
+ "type": "integer",
+ },
+ ],
+ },
+ "title": "Location",
+ "type": "array",
+ },
+ "msg": {
+ "title": "Message",
+ "type": "string",
+ },
+ "type": {
+ "title": "Error Type",
+ "type": "string",
+ },
+ },
+ "required": [
+ "loc",
+ "msg",
+ "type",
+ ],
+ "title": "ValidationError",
+ "type": "object",
+ },
+ },
+ },
+ }
diff --git a/tests/test_tutorial/test_path_params_numeric_validations/test_tutorial005.py b/tests/test_tutorial/test_path_params_numeric_validations/test_tutorial005.py
new file mode 100644
index 0000000000..296192593b
--- /dev/null
+++ b/tests/test_tutorial/test_path_params_numeric_validations/test_tutorial005.py
@@ -0,0 +1,202 @@
+import importlib
+
+import pytest
+from fastapi.testclient import TestClient
+
+
+@pytest.fixture(
+ name="client",
+ params=[
+ pytest.param("tutorial005_py39"),
+ pytest.param("tutorial005_an_py39"),
+ ],
+)
+def get_client(request: pytest.FixtureRequest) -> TestClient:
+ mod = importlib.import_module(
+ f"docs_src.path_params_numeric_validations.{request.param}"
+ )
+ return TestClient(mod.app)
+
+
+@pytest.mark.parametrize(
+ "path,expected_response",
+ [
+ ("/items/1?q=", {"item_id": 1}),
+ ("/items/1000?q=somequery", {"item_id": 1000, "q": "somequery"}),
+ ],
+)
+def test_read_items(client: TestClient, path, expected_response):
+ response = client.get(path)
+ assert response.status_code == 200, response.text
+ assert response.json() == expected_response
+
+
+def test_read_items_non_int_item_id(client: TestClient):
+ response = client.get("/items/invalid_id?q=somequery")
+ assert response.status_code == 422, response.text
+ assert response.json() == {
+ "detail": [
+ {
+ "loc": ["path", "item_id"],
+ "input": "invalid_id",
+ "msg": "Input should be a valid integer, unable to parse string as an integer",
+ "type": "int_parsing",
+ }
+ ]
+ }
+
+
+def test_read_items_item_id_less_than_one(client: TestClient):
+ response = client.get("/items/0?q=somequery")
+ assert response.status_code == 422, response.text
+ assert response.json() == {
+ "detail": [
+ {
+ "loc": ["path", "item_id"],
+ "input": "0",
+ "msg": "Input should be greater than 0",
+ "type": "greater_than",
+ "ctx": {"gt": 0},
+ }
+ ]
+ }
+
+
+def test_read_items_item_id_greater_than_one_thousand(client: TestClient):
+ response = client.get("/items/1001?q=somequery")
+ assert response.status_code == 422, response.text
+ assert response.json() == {
+ "detail": [
+ {
+ "loc": ["path", "item_id"],
+ "input": "1001",
+ "msg": "Input should be less than or equal to 1000",
+ "type": "less_than_equal",
+ "ctx": {"le": 1000},
+ }
+ ]
+ }
+
+
+def test_read_items_missing_q(client: TestClient):
+ response = client.get("/items/42")
+ assert response.status_code == 422, response.text
+ assert response.json() == {
+ "detail": [
+ {
+ "loc": ["query", "q"],
+ "input": None,
+ "msg": "Field required",
+ "type": "missing",
+ }
+ ]
+ }
+
+
+def test_openapi_schema(client: TestClient):
+ response = client.get("/openapi.json")
+ assert response.status_code == 200, response.text
+ assert response.json() == {
+ "openapi": "3.1.0",
+ "info": {"title": "FastAPI", "version": "0.1.0"},
+ "paths": {
+ "/items/{item_id}": {
+ "get": {
+ "summary": "Read Items",
+ "operationId": "read_items_items__item_id__get",
+ "parameters": [
+ {
+ "required": True,
+ "schema": {
+ "title": "The ID of the item to get",
+ "type": "integer",
+ "exclusiveMinimum": 0,
+ "maximum": 1000,
+ },
+ "name": "item_id",
+ "in": "path",
+ },
+ {
+ "required": True,
+ "schema": {
+ "type": "string",
+ "title": "Q",
+ },
+ "name": "q",
+ "in": "query",
+ },
+ ],
+ "responses": {
+ "200": {
+ "description": "Successful Response",
+ "content": {
+ "application/json": {
+ "schema": {},
+ }
+ },
+ },
+ "422": {
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/HTTPValidationError",
+ },
+ },
+ },
+ "description": "Validation Error",
+ },
+ },
+ }
+ }
+ },
+ "components": {
+ "schemas": {
+ "HTTPValidationError": {
+ "properties": {
+ "detail": {
+ "items": {
+ "$ref": "#/components/schemas/ValidationError",
+ },
+ "title": "Detail",
+ "type": "array",
+ },
+ },
+ "title": "HTTPValidationError",
+ "type": "object",
+ },
+ "ValidationError": {
+ "properties": {
+ "loc": {
+ "items": {
+ "anyOf": [
+ {
+ "type": "string",
+ },
+ {
+ "type": "integer",
+ },
+ ],
+ },
+ "title": "Location",
+ "type": "array",
+ },
+ "msg": {
+ "title": "Message",
+ "type": "string",
+ },
+ "type": {
+ "title": "Error Type",
+ "type": "string",
+ },
+ },
+ "required": [
+ "loc",
+ "msg",
+ "type",
+ ],
+ "title": "ValidationError",
+ "type": "object",
+ },
+ },
+ },
+ }
diff --git a/tests/test_tutorial/test_path_params_numeric_validations/test_tutorial006.py b/tests/test_tutorial/test_path_params_numeric_validations/test_tutorial006.py
new file mode 100644
index 0000000000..9dc7d7aac2
--- /dev/null
+++ b/tests/test_tutorial/test_path_params_numeric_validations/test_tutorial006.py
@@ -0,0 +1,221 @@
+import importlib
+
+import pytest
+from fastapi.testclient import TestClient
+
+
+@pytest.fixture(
+ name="client",
+ params=[
+ pytest.param("tutorial006_py39"),
+ pytest.param("tutorial006_an_py39"),
+ ],
+)
+def get_client(request: pytest.FixtureRequest) -> TestClient:
+ mod = importlib.import_module(
+ f"docs_src.path_params_numeric_validations.{request.param}"
+ )
+ return TestClient(mod.app)
+
+
+@pytest.mark.parametrize(
+ "path,expected_response",
+ [
+ (
+ "/items/0?q=&size=0.1",
+ {"item_id": 0, "size": 0.1},
+ ),
+ (
+ "/items/1000?q=somequery&size=10.4",
+ {"item_id": 1000, "q": "somequery", "size": 10.4},
+ ),
+ ],
+)
+def test_read_items(client: TestClient, path, expected_response):
+ response = client.get(path)
+ assert response.status_code == 200, response.text
+ assert response.json() == expected_response
+
+
+def test_read_items_item_id_less_than_zero(client: TestClient):
+ response = client.get("/items/-1?q=somequery&size=5")
+ assert response.status_code == 422, response.text
+ assert response.json() == {
+ "detail": [
+ {
+ "loc": ["path", "item_id"],
+ "input": "-1",
+ "msg": "Input should be greater than or equal to 0",
+ "type": "greater_than_equal",
+ "ctx": {"ge": 0},
+ }
+ ]
+ }
+
+
+def test_read_items_item_id_greater_than_one_thousand(client: TestClient):
+ response = client.get("/items/1001?q=somequery&size=5")
+ assert response.status_code == 422, response.text
+ assert response.json() == {
+ "detail": [
+ {
+ "loc": ["path", "item_id"],
+ "input": "1001",
+ "msg": "Input should be less than or equal to 1000",
+ "type": "less_than_equal",
+ "ctx": {"le": 1000},
+ }
+ ]
+ }
+
+
+def test_read_items_size_too_small(client: TestClient):
+ response = client.get("/items/1?q=somequery&size=0.0")
+ assert response.status_code == 422, response.text
+ assert response.json() == {
+ "detail": [
+ {
+ "loc": ["query", "size"],
+ "input": "0.0",
+ "msg": "Input should be greater than 0",
+ "type": "greater_than",
+ "ctx": {"gt": 0.0},
+ }
+ ]
+ }
+
+
+def test_read_items_size_too_large(client: TestClient):
+ response = client.get("/items/1?q=somequery&size=10.5")
+ assert response.status_code == 422, response.text
+ assert response.json() == {
+ "detail": [
+ {
+ "loc": ["query", "size"],
+ "input": "10.5",
+ "msg": "Input should be less than 10.5",
+ "type": "less_than",
+ "ctx": {"lt": 10.5},
+ }
+ ]
+ }
+
+
+def test_openapi_schema(client: TestClient):
+ response = client.get("/openapi.json")
+ assert response.status_code == 200, response.text
+ assert response.json() == {
+ "openapi": "3.1.0",
+ "info": {"title": "FastAPI", "version": "0.1.0"},
+ "paths": {
+ "/items/{item_id}": {
+ "get": {
+ "summary": "Read Items",
+ "operationId": "read_items_items__item_id__get",
+ "parameters": [
+ {
+ "required": True,
+ "schema": {
+ "title": "The ID of the item to get",
+ "type": "integer",
+ "minimum": 0,
+ "maximum": 1000,
+ },
+ "name": "item_id",
+ "in": "path",
+ },
+ {
+ "required": True,
+ "schema": {
+ "type": "string",
+ "title": "Q",
+ },
+ "name": "q",
+ "in": "query",
+ },
+ {
+ "in": "query",
+ "name": "size",
+ "required": True,
+ "schema": {
+ "exclusiveMaximum": 10.5,
+ "exclusiveMinimum": 0,
+ "title": "Size",
+ "type": "number",
+ },
+ },
+ ],
+ "responses": {
+ "200": {
+ "description": "Successful Response",
+ "content": {
+ "application/json": {
+ "schema": {},
+ }
+ },
+ },
+ "422": {
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/HTTPValidationError",
+ },
+ },
+ },
+ "description": "Validation Error",
+ },
+ },
+ }
+ }
+ },
+ "components": {
+ "schemas": {
+ "HTTPValidationError": {
+ "properties": {
+ "detail": {
+ "items": {
+ "$ref": "#/components/schemas/ValidationError",
+ },
+ "title": "Detail",
+ "type": "array",
+ },
+ },
+ "title": "HTTPValidationError",
+ "type": "object",
+ },
+ "ValidationError": {
+ "properties": {
+ "loc": {
+ "items": {
+ "anyOf": [
+ {
+ "type": "string",
+ },
+ {
+ "type": "integer",
+ },
+ ],
+ },
+ "title": "Location",
+ "type": "array",
+ },
+ "msg": {
+ "title": "Message",
+ "type": "string",
+ },
+ "type": {
+ "title": "Error Type",
+ "type": "string",
+ },
+ },
+ "required": [
+ "loc",
+ "msg",
+ "type",
+ ],
+ "title": "ValidationError",
+ "type": "object",
+ },
+ },
+ },
+ }
diff --git a/tests/test_tutorial/test_pydantic_v1_in_v2/test_tutorial001.py b/tests/test_tutorial/test_pydantic_v1_in_v2/test_tutorial001.py
deleted file mode 100644
index 3075a05f51..0000000000
--- a/tests/test_tutorial/test_pydantic_v1_in_v2/test_tutorial001.py
+++ /dev/null
@@ -1,37 +0,0 @@
-import sys
-from typing import Any
-
-import pytest
-from fastapi._compat import PYDANTIC_V2
-
-from tests.utils import skip_module_if_py_gte_314
-
-if sys.version_info >= (3, 14):
- skip_module_if_py_gte_314()
-
-
-if not PYDANTIC_V2:
- pytest.skip("This test is only for Pydantic v2", allow_module_level=True)
-
-import importlib
-
-import pytest
-
-from ...utils import needs_py310
-
-
-@pytest.fixture(
- name="mod",
- params=[
- "tutorial001_an",
- pytest.param("tutorial001_an_py310", marks=needs_py310),
- ],
-)
-def get_mod(request: pytest.FixtureRequest):
- mod = importlib.import_module(f"docs_src.pydantic_v1_in_v2.{request.param}")
- return mod
-
-
-def test_model(mod: Any):
- item = mod.Item(name="Foo", size=3.4)
- assert item.dict() == {"name": "Foo", "description": None, "size": 3.4}
diff --git a/tests/test_tutorial/test_pydantic_v1_in_v2/test_tutorial002.py b/tests/test_tutorial/test_pydantic_v1_in_v2/test_tutorial002.py
deleted file mode 100644
index a402c663d1..0000000000
--- a/tests/test_tutorial/test_pydantic_v1_in_v2/test_tutorial002.py
+++ /dev/null
@@ -1,140 +0,0 @@
-import sys
-
-import pytest
-from fastapi._compat import PYDANTIC_V2
-from inline_snapshot import snapshot
-
-from tests.utils import skip_module_if_py_gte_314
-
-if sys.version_info >= (3, 14):
- skip_module_if_py_gte_314()
-
-
-if not PYDANTIC_V2:
- pytest.skip("This test is only for Pydantic v2", allow_module_level=True)
-
-import importlib
-
-import pytest
-from fastapi.testclient import TestClient
-
-from ...utils import needs_py310
-
-
-@pytest.fixture(
- name="client",
- params=[
- "tutorial002_an",
- pytest.param("tutorial002_an_py310", marks=needs_py310),
- ],
-)
-def get_client(request: pytest.FixtureRequest):
- mod = importlib.import_module(f"docs_src.pydantic_v1_in_v2.{request.param}")
-
- c = TestClient(mod.app)
- return c
-
-
-def test_call(client: TestClient):
- response = client.post("/items/", json={"name": "Foo", "size": 3.4})
- assert response.status_code == 200, response.text
- assert response.json() == {
- "name": "Foo",
- "description": None,
- "size": 3.4,
- }
-
-
-def test_openapi_schema(client: TestClient):
- response = client.get("/openapi.json")
- assert response.status_code == 200, response.text
- assert response.json() == snapshot(
- {
- "openapi": "3.1.0",
- "info": {"title": "FastAPI", "version": "0.1.0"},
- "paths": {
- "/items/": {
- "post": {
- "summary": "Create Item",
- "operationId": "create_item_items__post",
- "requestBody": {
- "content": {
- "application/json": {
- "schema": {
- "allOf": [
- {"$ref": "#/components/schemas/Item"}
- ],
- "title": "Item",
- }
- }
- },
- "required": True,
- },
- "responses": {
- "200": {
- "description": "Successful Response",
- "content": {
- "application/json": {
- "schema": {"$ref": "#/components/schemas/Item"}
- }
- },
- },
- "422": {
- "description": "Validation Error",
- "content": {
- "application/json": {
- "schema": {
- "$ref": "#/components/schemas/HTTPValidationError"
- }
- }
- },
- },
- },
- }
- }
- },
- "components": {
- "schemas": {
- "HTTPValidationError": {
- "properties": {
- "detail": {
- "items": {
- "$ref": "#/components/schemas/ValidationError"
- },
- "type": "array",
- "title": "Detail",
- }
- },
- "type": "object",
- "title": "HTTPValidationError",
- },
- "Item": {
- "properties": {
- "name": {"type": "string", "title": "Name"},
- "description": {"type": "string", "title": "Description"},
- "size": {"type": "number", "title": "Size"},
- },
- "type": "object",
- "required": ["name", "size"],
- "title": "Item",
- },
- "ValidationError": {
- "properties": {
- "loc": {
- "items": {
- "anyOf": [{"type": "string"}, {"type": "integer"}]
- },
- "type": "array",
- "title": "Location",
- },
- "msg": {"type": "string", "title": "Message"},
- "type": {"type": "string", "title": "Error Type"},
- },
- "type": "object",
- "required": ["loc", "msg", "type"],
- "title": "ValidationError",
- },
- }
- },
- }
- )
diff --git a/tests/test_tutorial/test_pydantic_v1_in_v2/test_tutorial003.py b/tests/test_tutorial/test_pydantic_v1_in_v2/test_tutorial003.py
deleted file mode 100644
index 03155c9249..0000000000
--- a/tests/test_tutorial/test_pydantic_v1_in_v2/test_tutorial003.py
+++ /dev/null
@@ -1,154 +0,0 @@
-import sys
-
-import pytest
-from fastapi._compat import PYDANTIC_V2
-from inline_snapshot import snapshot
-
-from tests.utils import skip_module_if_py_gte_314
-
-if sys.version_info >= (3, 14):
- skip_module_if_py_gte_314()
-
-if not PYDANTIC_V2:
- pytest.skip("This test is only for Pydantic v2", allow_module_level=True)
-
-
-import importlib
-
-from fastapi.testclient import TestClient
-
-from ...utils import needs_py310
-
-
-@pytest.fixture(
- name="client",
- params=[
- "tutorial003_an",
- pytest.param("tutorial003_an_py310", marks=needs_py310),
- ],
-)
-def get_client(request: pytest.FixtureRequest):
- mod = importlib.import_module(f"docs_src.pydantic_v1_in_v2.{request.param}")
-
- c = TestClient(mod.app)
- return c
-
-
-def test_call(client: TestClient):
- response = client.post("/items/", json={"name": "Foo", "size": 3.4})
- assert response.status_code == 200, response.text
- assert response.json() == {
- "name": "Foo",
- "description": None,
- "size": 3.4,
- }
-
-
-def test_openapi_schema(client: TestClient):
- response = client.get("/openapi.json")
- assert response.status_code == 200, response.text
- assert response.json() == snapshot(
- {
- "openapi": "3.1.0",
- "info": {"title": "FastAPI", "version": "0.1.0"},
- "paths": {
- "/items/": {
- "post": {
- "summary": "Create Item",
- "operationId": "create_item_items__post",
- "requestBody": {
- "content": {
- "application/json": {
- "schema": {
- "allOf": [
- {"$ref": "#/components/schemas/Item"}
- ],
- "title": "Item",
- }
- }
- },
- "required": True,
- },
- "responses": {
- "200": {
- "description": "Successful Response",
- "content": {
- "application/json": {
- "schema": {
- "$ref": "#/components/schemas/ItemV2"
- }
- }
- },
- },
- "422": {
- "description": "Validation Error",
- "content": {
- "application/json": {
- "schema": {
- "$ref": "#/components/schemas/HTTPValidationError"
- }
- }
- },
- },
- },
- }
- }
- },
- "components": {
- "schemas": {
- "HTTPValidationError": {
- "properties": {
- "detail": {
- "items": {
- "$ref": "#/components/schemas/ValidationError"
- },
- "type": "array",
- "title": "Detail",
- }
- },
- "type": "object",
- "title": "HTTPValidationError",
- },
- "Item": {
- "properties": {
- "name": {"type": "string", "title": "Name"},
- "description": {"type": "string", "title": "Description"},
- "size": {"type": "number", "title": "Size"},
- },
- "type": "object",
- "required": ["name", "size"],
- "title": "Item",
- },
- "ItemV2": {
- "properties": {
- "name": {"type": "string", "title": "Name"},
- "description": {
- "anyOf": [{"type": "string"}, {"type": "null"}],
- "title": "Description",
- },
- "size": {"type": "number", "title": "Size"},
- },
- "type": "object",
- "required": ["name", "size"],
- "title": "ItemV2",
- },
- "ValidationError": {
- "properties": {
- "loc": {
- "items": {
- "anyOf": [{"type": "string"}, {"type": "integer"}]
- },
- "type": "array",
- "title": "Location",
- },
- "msg": {"type": "string", "title": "Message"},
- "type": {"type": "string", "title": "Error Type"},
- },
- "type": "object",
- "required": ["loc", "msg", "type"],
- "title": "ValidationError",
- },
- }
- },
- }
- )
diff --git a/tests/test_tutorial/test_pydantic_v1_in_v2/test_tutorial004.py b/tests/test_tutorial/test_pydantic_v1_in_v2/test_tutorial004.py
deleted file mode 100644
index d2e204ddaf..0000000000
--- a/tests/test_tutorial/test_pydantic_v1_in_v2/test_tutorial004.py
+++ /dev/null
@@ -1,153 +0,0 @@
-import sys
-
-import pytest
-from fastapi._compat import PYDANTIC_V2
-from inline_snapshot import snapshot
-
-from tests.utils import skip_module_if_py_gte_314
-
-if sys.version_info >= (3, 14):
- skip_module_if_py_gte_314()
-
-if not PYDANTIC_V2:
- pytest.skip("This test is only for Pydantic v2", allow_module_level=True)
-
-
-import importlib
-
-from fastapi.testclient import TestClient
-
-from ...utils import needs_py39, needs_py310
-
-
-@pytest.fixture(
- name="client",
- params=[
- "tutorial004_an",
- pytest.param("tutorial004_an_py39", marks=needs_py39),
- pytest.param("tutorial004_an_py310", marks=needs_py310),
- ],
-)
-def get_client(request: pytest.FixtureRequest):
- mod = importlib.import_module(f"docs_src.pydantic_v1_in_v2.{request.param}")
-
- c = TestClient(mod.app)
- return c
-
-
-def test_call(client: TestClient):
- response = client.post("/items/", json={"item": {"name": "Foo", "size": 3.4}})
- assert response.status_code == 200, response.text
- assert response.json() == {
- "name": "Foo",
- "description": None,
- "size": 3.4,
- }
-
-
-def test_openapi_schema(client: TestClient):
- response = client.get("/openapi.json")
- assert response.status_code == 200, response.text
- assert response.json() == snapshot(
- {
- "openapi": "3.1.0",
- "info": {"title": "FastAPI", "version": "0.1.0"},
- "paths": {
- "/items/": {
- "post": {
- "summary": "Create Item",
- "operationId": "create_item_items__post",
- "requestBody": {
- "content": {
- "application/json": {
- "schema": {
- "allOf": [
- {
- "$ref": "#/components/schemas/Body_create_item_items__post"
- }
- ],
- "title": "Body",
- }
- }
- },
- "required": True,
- },
- "responses": {
- "200": {
- "description": "Successful Response",
- "content": {
- "application/json": {
- "schema": {"$ref": "#/components/schemas/Item"}
- }
- },
- },
- "422": {
- "description": "Validation Error",
- "content": {
- "application/json": {
- "schema": {
- "$ref": "#/components/schemas/HTTPValidationError"
- }
- }
- },
- },
- },
- }
- }
- },
- "components": {
- "schemas": {
- "Body_create_item_items__post": {
- "properties": {
- "item": {
- "allOf": [{"$ref": "#/components/schemas/Item"}],
- "title": "Item",
- }
- },
- "type": "object",
- "required": ["item"],
- "title": "Body_create_item_items__post",
- },
- "HTTPValidationError": {
- "properties": {
- "detail": {
- "items": {
- "$ref": "#/components/schemas/ValidationError"
- },
- "type": "array",
- "title": "Detail",
- }
- },
- "type": "object",
- "title": "HTTPValidationError",
- },
- "Item": {
- "properties": {
- "name": {"type": "string", "title": "Name"},
- "description": {"type": "string", "title": "Description"},
- "size": {"type": "number", "title": "Size"},
- },
- "type": "object",
- "required": ["name", "size"],
- "title": "Item",
- },
- "ValidationError": {
- "properties": {
- "loc": {
- "items": {
- "anyOf": [{"type": "string"}, {"type": "integer"}]
- },
- "type": "array",
- "title": "Location",
- },
- "msg": {"type": "string", "title": "Message"},
- "type": {"type": "string", "title": "Error Type"},
- },
- "type": "object",
- "required": ["loc", "msg", "type"],
- "title": "ValidationError",
- },
- }
- },
- }
- )
diff --git a/tests/test_tutorial/test_python_types/__init__.py b/tests/test_tutorial/test_python_types/__init__.py
new file mode 100644
index 0000000000..e69de29bb2
diff --git a/tests/test_tutorial/test_python_types/test_tutorial001_tutorial002.py b/tests/test_tutorial/test_python_types/test_tutorial001_tutorial002.py
new file mode 100644
index 0000000000..ccb0968576
--- /dev/null
+++ b/tests/test_tutorial/test_python_types/test_tutorial001_tutorial002.py
@@ -0,0 +1,18 @@
+import runpy
+from unittest.mock import patch
+
+import pytest
+
+
+@pytest.mark.parametrize(
+ "module_name",
+ [
+ "tutorial001_py39",
+ "tutorial002_py39",
+ ],
+)
+def test_run_module(module_name: str):
+ with patch("builtins.print") as mock_print:
+ runpy.run_module(f"docs_src.python_types.{module_name}", run_name="__main__")
+
+ mock_print.assert_called_with("John Doe")
diff --git a/tests/test_tutorial/test_python_types/test_tutorial003.py b/tests/test_tutorial/test_python_types/test_tutorial003.py
new file mode 100644
index 0000000000..34d2649171
--- /dev/null
+++ b/tests/test_tutorial/test_python_types/test_tutorial003.py
@@ -0,0 +1,12 @@
+import pytest
+
+from docs_src.python_types.tutorial003_py39 import get_name_with_age
+
+
+def test_get_name_with_age_pass_int():
+ with pytest.raises(TypeError):
+ get_name_with_age("John", 30)
+
+
+def test_get_name_with_age_pass_str():
+ assert get_name_with_age("John", "30") == "John is this old: 30"
diff --git a/tests/test_tutorial/test_python_types/test_tutorial004.py b/tests/test_tutorial/test_python_types/test_tutorial004.py
new file mode 100644
index 0000000000..24af32883e
--- /dev/null
+++ b/tests/test_tutorial/test_python_types/test_tutorial004.py
@@ -0,0 +1,5 @@
+from docs_src.python_types.tutorial004_py39 import get_name_with_age
+
+
+def test_get_name_with_age_pass_int():
+ assert get_name_with_age("John", 30) == "John is this old: 30"
diff --git a/tests/test_tutorial/test_python_types/test_tutorial005.py b/tests/test_tutorial/test_python_types/test_tutorial005.py
new file mode 100644
index 0000000000..6d67ec4716
--- /dev/null
+++ b/tests/test_tutorial/test_python_types/test_tutorial005.py
@@ -0,0 +1,12 @@
+from docs_src.python_types.tutorial005_py39 import get_items
+
+
+def test_get_items():
+ res = get_items(
+ "item_a",
+ "item_b",
+ "item_c",
+ "item_d",
+ "item_e",
+ )
+ assert res == ("item_a", "item_b", "item_c", "item_d", "item_e")
diff --git a/tests/test_tutorial/test_python_types/test_tutorial006.py b/tests/test_tutorial/test_python_types/test_tutorial006.py
new file mode 100644
index 0000000000..50976926e7
--- /dev/null
+++ b/tests/test_tutorial/test_python_types/test_tutorial006.py
@@ -0,0 +1,16 @@
+from unittest.mock import patch
+
+from docs_src.python_types.tutorial006_py39 import process_items
+
+
+def test_process_items():
+ with patch("builtins.print") as mock_print:
+ process_items(["item_a", "item_b", "item_c"])
+
+ assert mock_print.call_count == 3
+ call_args = [arg.args for arg in mock_print.call_args_list]
+ assert call_args == [
+ ("item_a",),
+ ("item_b",),
+ ("item_c",),
+ ]
diff --git a/tests/test_tutorial/test_python_types/test_tutorial007.py b/tests/test_tutorial/test_python_types/test_tutorial007.py
new file mode 100644
index 0000000000..c045294652
--- /dev/null
+++ b/tests/test_tutorial/test_python_types/test_tutorial007.py
@@ -0,0 +1,8 @@
+from docs_src.python_types.tutorial007_py39 import process_items
+
+
+def test_process_items():
+ items_t = (1, 2, "foo")
+ items_s = {b"a", b"b", b"c"}
+
+ assert process_items(items_t, items_s) == (items_t, items_s)
diff --git a/tests/test_tutorial/test_python_types/test_tutorial008.py b/tests/test_tutorial/test_python_types/test_tutorial008.py
new file mode 100644
index 0000000000..33cf6cbfbc
--- /dev/null
+++ b/tests/test_tutorial/test_python_types/test_tutorial008.py
@@ -0,0 +1,17 @@
+from unittest.mock import patch
+
+from docs_src.python_types.tutorial008_py39 import process_items
+
+
+def test_process_items():
+ with patch("builtins.print") as mock_print:
+ process_items({"a": 1.0, "b": 2.5})
+
+ assert mock_print.call_count == 4
+ call_args = [arg.args for arg in mock_print.call_args_list]
+ assert call_args == [
+ ("a",),
+ (1.0,),
+ ("b",),
+ (2.5,),
+ ]
diff --git a/tests/test_tutorial/test_python_types/test_tutorial008b.py b/tests/test_tutorial/test_python_types/test_tutorial008b.py
new file mode 100644
index 0000000000..1ef0d4ea16
--- /dev/null
+++ b/tests/test_tutorial/test_python_types/test_tutorial008b.py
@@ -0,0 +1,27 @@
+import importlib
+from types import ModuleType
+from unittest.mock import patch
+
+import pytest
+
+from ...utils import needs_py310
+
+
+@pytest.fixture(
+ name="module",
+ params=[
+ pytest.param("tutorial008b_py39"),
+ pytest.param("tutorial008b_py310", marks=needs_py310),
+ ],
+)
+def get_module(request: pytest.FixtureRequest):
+ mod = importlib.import_module(f"docs_src.python_types.{request.param}")
+ return mod
+
+
+def test_process_items(module: ModuleType):
+ with patch("builtins.print") as mock_print:
+ module.process_item("a")
+
+ assert mock_print.call_count == 1
+ mock_print.assert_called_with("a")
diff --git a/tests/test_tutorial/test_python_types/test_tutorial009_tutorial009b.py b/tests/test_tutorial/test_python_types/test_tutorial009_tutorial009b.py
new file mode 100644
index 0000000000..34046c5c48
--- /dev/null
+++ b/tests/test_tutorial/test_python_types/test_tutorial009_tutorial009b.py
@@ -0,0 +1,33 @@
+import importlib
+from types import ModuleType
+from unittest.mock import patch
+
+import pytest
+
+from ...utils import needs_py310
+
+
+@pytest.fixture(
+ name="module",
+ params=[
+ pytest.param("tutorial009_py39"),
+ pytest.param("tutorial009_py310", marks=needs_py310),
+ pytest.param("tutorial009b_py39"),
+ ],
+)
+def get_module(request: pytest.FixtureRequest):
+ mod = importlib.import_module(f"docs_src.python_types.{request.param}")
+ return mod
+
+
+def test_say_hi(module: ModuleType):
+ with patch("builtins.print") as mock_print:
+ module.say_hi("FastAPI")
+ module.say_hi()
+
+ assert mock_print.call_count == 2
+ call_args = [arg.args for arg in mock_print.call_args_list]
+ assert call_args == [
+ ("Hey FastAPI!",),
+ ("Hello World",),
+ ]
diff --git a/tests/test_tutorial/test_python_types/test_tutorial009c.py b/tests/test_tutorial/test_python_types/test_tutorial009c.py
new file mode 100644
index 0000000000..7bd4049113
--- /dev/null
+++ b/tests/test_tutorial/test_python_types/test_tutorial009c.py
@@ -0,0 +1,33 @@
+import importlib
+import re
+from types import ModuleType
+from unittest.mock import patch
+
+import pytest
+
+from ...utils import needs_py310
+
+
+@pytest.fixture(
+ name="module",
+ params=[
+ pytest.param("tutorial009c_py39"),
+ pytest.param("tutorial009c_py310", marks=needs_py310),
+ ],
+)
+def get_module(request: pytest.FixtureRequest):
+ mod = importlib.import_module(f"docs_src.python_types.{request.param}")
+ return mod
+
+
+def test_say_hi(module: ModuleType):
+ with patch("builtins.print") as mock_print:
+ module.say_hi("FastAPI")
+
+ mock_print.assert_called_once_with("Hey FastAPI!")
+
+ with pytest.raises(
+ TypeError,
+ match=re.escape("say_hi() missing 1 required positional argument: 'name'"),
+ ):
+ module.say_hi()
diff --git a/tests/test_tutorial/test_python_types/test_tutorial010.py b/tests/test_tutorial/test_python_types/test_tutorial010.py
new file mode 100644
index 0000000000..9e4d2e36bf
--- /dev/null
+++ b/tests/test_tutorial/test_python_types/test_tutorial010.py
@@ -0,0 +1,5 @@
+from docs_src.python_types.tutorial010_py39 import Person, get_person_name
+
+
+def test_get_person_name():
+ assert get_person_name(Person("John Doe")) == "John Doe"
diff --git a/tests/test_tutorial/test_python_types/test_tutorial011.py b/tests/test_tutorial/test_python_types/test_tutorial011.py
new file mode 100644
index 0000000000..a05751b974
--- /dev/null
+++ b/tests/test_tutorial/test_python_types/test_tutorial011.py
@@ -0,0 +1,25 @@
+import runpy
+from unittest.mock import patch
+
+import pytest
+
+from ...utils import needs_py310
+
+
+@pytest.mark.parametrize(
+ "module_name",
+ [
+ pytest.param("tutorial011_py39"),
+ pytest.param("tutorial011_py310", marks=needs_py310),
+ ],
+)
+def test_run_module(module_name: str):
+ with patch("builtins.print") as mock_print:
+ runpy.run_module(f"docs_src.python_types.{module_name}", run_name="__main__")
+
+ assert mock_print.call_count == 2
+ call_args = [str(arg.args[0]) for arg in mock_print.call_args_list]
+ assert call_args == [
+ "id=123 name='John Doe' signup_ts=datetime.datetime(2017, 6, 1, 12, 22) friends=[1, 2, 3]",
+ "123",
+ ]
diff --git a/tests/test_tutorial/test_python_types/test_tutorial012.py b/tests/test_tutorial/test_python_types/test_tutorial012.py
new file mode 100644
index 0000000000..e578048204
--- /dev/null
+++ b/tests/test_tutorial/test_python_types/test_tutorial012.py
@@ -0,0 +1,7 @@
+from docs_src.python_types.tutorial012_py39 import User
+
+
+def test_user():
+ user = User(name="John Doe", age=30)
+ assert user.name == "John Doe"
+ assert user.age == 30
diff --git a/tests/test_tutorial/test_python_types/test_tutorial013.py b/tests/test_tutorial/test_python_types/test_tutorial013.py
new file mode 100644
index 0000000000..5602ef76f8
--- /dev/null
+++ b/tests/test_tutorial/test_python_types/test_tutorial013.py
@@ -0,0 +1,5 @@
+from docs_src.python_types.tutorial013_py39 import say_hello
+
+
+def test_say_hello():
+ assert say_hello("FastAPI") == "Hello FastAPI"
diff --git a/tests/test_tutorial/test_query_param_models/test_tutorial001.py b/tests/test_tutorial/test_query_param_models/test_tutorial001.py
index 5b7bc7b424..d3ce57121d 100644
--- a/tests/test_tutorial/test_query_param_models/test_tutorial001.py
+++ b/tests/test_tutorial/test_query_param_models/test_tutorial001.py
@@ -1,21 +1,18 @@
import importlib
import pytest
-from dirty_equals import IsDict
from fastapi.testclient import TestClient
from inline_snapshot import snapshot
-from tests.utils import needs_py39, needs_py310
+from tests.utils import needs_py310
@pytest.fixture(
name="client",
params=[
- "tutorial001",
- pytest.param("tutorial001_py39", marks=needs_py39),
+ pytest.param("tutorial001_py39"),
pytest.param("tutorial001_py310", marks=needs_py310),
- "tutorial001_an",
- pytest.param("tutorial001_an_py39", marks=needs_py39),
+ pytest.param("tutorial001_an_py39"),
pytest.param("tutorial001_an_py310", marks=needs_py310),
],
)
@@ -67,61 +64,31 @@ def test_query_param_model_invalid(client: TestClient):
)
assert response.status_code == 422
assert response.json() == snapshot(
- IsDict(
- {
- "detail": [
- {
- "type": "less_than_equal",
- "loc": ["query", "limit"],
- "msg": "Input should be less than or equal to 100",
- "input": "150",
- "ctx": {"le": 100},
- },
- {
- "type": "greater_than_equal",
- "loc": ["query", "offset"],
- "msg": "Input should be greater than or equal to 0",
- "input": "-1",
- "ctx": {"ge": 0},
- },
- {
- "type": "literal_error",
- "loc": ["query", "order_by"],
- "msg": "Input should be 'created_at' or 'updated_at'",
- "input": "invalid",
- "ctx": {"expected": "'created_at' or 'updated_at'"},
- },
- ]
- }
- )
- | IsDict(
- # TODO: remove when deprecating Pydantic v1
- {
- "detail": [
- {
- "type": "value_error.number.not_le",
- "loc": ["query", "limit"],
- "msg": "ensure this value is less than or equal to 100",
- "ctx": {"limit_value": 100},
- },
- {
- "type": "value_error.number.not_ge",
- "loc": ["query", "offset"],
- "msg": "ensure this value is greater than or equal to 0",
- "ctx": {"limit_value": 0},
- },
- {
- "type": "value_error.const",
- "loc": ["query", "order_by"],
- "msg": "unexpected value; permitted: 'created_at', 'updated_at'",
- "ctx": {
- "given": "invalid",
- "permitted": ["created_at", "updated_at"],
- },
- },
- ]
- }
- )
+ {
+ "detail": [
+ {
+ "type": "less_than_equal",
+ "loc": ["query", "limit"],
+ "msg": "Input should be less than or equal to 100",
+ "input": "150",
+ "ctx": {"le": 100},
+ },
+ {
+ "type": "greater_than_equal",
+ "loc": ["query", "offset"],
+ "msg": "Input should be greater than or equal to 0",
+ "input": "-1",
+ "ctx": {"ge": 0},
+ },
+ {
+ "type": "literal_error",
+ "loc": ["query", "order_by"],
+ "msg": "Input should be 'created_at' or 'updated_at'",
+ "input": "invalid",
+ "ctx": {"expected": "'created_at' or 'updated_at'"},
+ },
+ ]
+ }
)
diff --git a/tests/test_tutorial/test_query_param_models/test_tutorial002.py b/tests/test_tutorial/test_query_param_models/test_tutorial002.py
index 4432c9d8a3..96abce6ab9 100644
--- a/tests/test_tutorial/test_query_param_models/test_tutorial002.py
+++ b/tests/test_tutorial/test_query_param_models/test_tutorial002.py
@@ -1,28 +1,19 @@
import importlib
import pytest
-from dirty_equals import IsDict
from fastapi.testclient import TestClient
from inline_snapshot import snapshot
-from tests.utils import needs_py39, needs_py310, needs_pydanticv1, needs_pydanticv2
+from tests.utils import needs_py310
@pytest.fixture(
name="client",
params=[
- pytest.param("tutorial002", marks=needs_pydanticv2),
- pytest.param("tutorial002_py39", marks=[needs_py39, needs_pydanticv2]),
- pytest.param("tutorial002_py310", marks=[needs_py310, needs_pydanticv2]),
- pytest.param("tutorial002_an", marks=needs_pydanticv2),
- pytest.param("tutorial002_an_py39", marks=[needs_py39, needs_pydanticv2]),
- pytest.param("tutorial002_an_py310", marks=[needs_py310, needs_pydanticv2]),
- pytest.param("tutorial002_pv1", marks=[needs_pydanticv1, needs_pydanticv1]),
- pytest.param("tutorial002_pv1_py39", marks=[needs_py39, needs_pydanticv1]),
- pytest.param("tutorial002_pv1_py310", marks=[needs_py310, needs_pydanticv1]),
- pytest.param("tutorial002_pv1_an", marks=[needs_pydanticv1]),
- pytest.param("tutorial002_pv1_an_py39", marks=[needs_py39, needs_pydanticv1]),
- pytest.param("tutorial002_pv1_an_py310", marks=[needs_py310, needs_pydanticv1]),
+ pytest.param("tutorial002_py39"),
+ pytest.param("tutorial002_py310", marks=[needs_py310]),
+ pytest.param("tutorial002_an_py39"),
+ pytest.param("tutorial002_an_py310", marks=[needs_py310]),
],
)
def get_client(request: pytest.FixtureRequest):
@@ -73,61 +64,31 @@ def test_query_param_model_invalid(client: TestClient):
)
assert response.status_code == 422
assert response.json() == snapshot(
- IsDict(
- {
- "detail": [
- {
- "type": "less_than_equal",
- "loc": ["query", "limit"],
- "msg": "Input should be less than or equal to 100",
- "input": "150",
- "ctx": {"le": 100},
- },
- {
- "type": "greater_than_equal",
- "loc": ["query", "offset"],
- "msg": "Input should be greater than or equal to 0",
- "input": "-1",
- "ctx": {"ge": 0},
- },
- {
- "type": "literal_error",
- "loc": ["query", "order_by"],
- "msg": "Input should be 'created_at' or 'updated_at'",
- "input": "invalid",
- "ctx": {"expected": "'created_at' or 'updated_at'"},
- },
- ]
- }
- )
- | IsDict(
- # TODO: remove when deprecating Pydantic v1
- {
- "detail": [
- {
- "type": "value_error.number.not_le",
- "loc": ["query", "limit"],
- "msg": "ensure this value is less than or equal to 100",
- "ctx": {"limit_value": 100},
- },
- {
- "type": "value_error.number.not_ge",
- "loc": ["query", "offset"],
- "msg": "ensure this value is greater than or equal to 0",
- "ctx": {"limit_value": 0},
- },
- {
- "type": "value_error.const",
- "loc": ["query", "order_by"],
- "msg": "unexpected value; permitted: 'created_at', 'updated_at'",
- "ctx": {
- "given": "invalid",
- "permitted": ["created_at", "updated_at"],
- },
- },
- ]
- }
- )
+ {
+ "detail": [
+ {
+ "type": "less_than_equal",
+ "loc": ["query", "limit"],
+ "msg": "Input should be less than or equal to 100",
+ "input": "150",
+ "ctx": {"le": 100},
+ },
+ {
+ "type": "greater_than_equal",
+ "loc": ["query", "offset"],
+ "msg": "Input should be greater than or equal to 0",
+ "input": "-1",
+ "ctx": {"ge": 0},
+ },
+ {
+ "type": "literal_error",
+ "loc": ["query", "order_by"],
+ "msg": "Input should be 'created_at' or 'updated_at'",
+ "input": "invalid",
+ "ctx": {"expected": "'created_at' or 'updated_at'"},
+ },
+ ]
+ }
)
@@ -146,22 +107,12 @@ def test_query_param_model_extra(client: TestClient):
assert response.json() == snapshot(
{
"detail": [
- IsDict(
- {
- "type": "extra_forbidden",
- "loc": ["query", "tool"],
- "msg": "Extra inputs are not permitted",
- "input": "plumbus",
- }
- )
- | IsDict(
- # TODO: remove when deprecating Pydantic v1
- {
- "type": "value_error.extra",
- "loc": ["query", "tool"],
- "msg": "extra fields not permitted",
- }
- )
+ {
+ "type": "extra_forbidden",
+ "loc": ["query", "tool"],
+ "msg": "Extra inputs are not permitted",
+ "input": "plumbus",
+ }
]
}
)
diff --git a/tests/test_tutorial/test_query_params/test_tutorial001.py b/tests/test_tutorial/test_query_params/test_tutorial001.py
new file mode 100644
index 0000000000..4c92b57b8d
--- /dev/null
+++ b/tests/test_tutorial/test_query_params/test_tutorial001.py
@@ -0,0 +1,126 @@
+import importlib
+
+import pytest
+from fastapi.testclient import TestClient
+
+
+@pytest.fixture(
+ name="client",
+ params=[
+ pytest.param("tutorial001_py39"),
+ ],
+)
+def get_client(request: pytest.FixtureRequest):
+ mod = importlib.import_module(f"docs_src.query_params.{request.param}")
+
+ client = TestClient(mod.app)
+ return client
+
+
+@pytest.mark.parametrize(
+ ("path", "expected_json"),
+ [
+ (
+ "/items/",
+ [{"item_name": "Foo"}, {"item_name": "Bar"}, {"item_name": "Baz"}],
+ ),
+ (
+ "/items/?skip=1",
+ [{"item_name": "Bar"}, {"item_name": "Baz"}],
+ ),
+ (
+ "/items/?skip=1&limit=1",
+ [{"item_name": "Bar"}],
+ ),
+ ],
+)
+def test_read_user_item(client: TestClient, path, expected_json):
+ response = client.get(path)
+ assert response.status_code == 200
+ assert response.json() == expected_json
+
+
+def test_openapi_schema(client: TestClient):
+ response = client.get("/openapi.json")
+ assert response.status_code == 200
+ assert response.json() == {
+ "openapi": "3.1.0",
+ "info": {"title": "FastAPI", "version": "0.1.0"},
+ "paths": {
+ "/items/": {
+ "get": {
+ "summary": "Read Item",
+ "operationId": "read_item_items__get",
+ "parameters": [
+ {
+ "required": False,
+ "schema": {
+ "title": "Skip",
+ "type": "integer",
+ "default": 0,
+ },
+ "name": "skip",
+ "in": "query",
+ },
+ {
+ "required": False,
+ "schema": {
+ "title": "Limit",
+ "type": "integer",
+ "default": 10,
+ },
+ "name": "limit",
+ "in": "query",
+ },
+ ],
+ "responses": {
+ "200": {
+ "description": "Successful Response",
+ "content": {"application/json": {"schema": {}}},
+ },
+ "422": {
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/HTTPValidationError",
+ },
+ },
+ },
+ "description": "Validation Error",
+ },
+ },
+ }
+ }
+ },
+ "components": {
+ "schemas": {
+ "ValidationError": {
+ "title": "ValidationError",
+ "required": ["loc", "msg", "type"],
+ "type": "object",
+ "properties": {
+ "loc": {
+ "title": "Location",
+ "type": "array",
+ "items": {
+ "anyOf": [{"type": "string"}, {"type": "integer"}]
+ },
+ },
+ "msg": {"title": "Message", "type": "string"},
+ "type": {"title": "Error Type", "type": "string"},
+ },
+ },
+ "HTTPValidationError": {
+ "title": "HTTPValidationError",
+ "type": "object",
+ "properties": {
+ "detail": {
+ "title": "Detail",
+ "type": "array",
+ "items": {"$ref": "#/components/schemas/ValidationError"},
+ }
+ },
+ },
+ }
+ },
+ }
diff --git a/tests/test_tutorial/test_query_params/test_tutorial002.py b/tests/test_tutorial/test_query_params/test_tutorial002.py
new file mode 100644
index 0000000000..ae3ee7613d
--- /dev/null
+++ b/tests/test_tutorial/test_query_params/test_tutorial002.py
@@ -0,0 +1,127 @@
+import importlib
+
+import pytest
+from fastapi.testclient import TestClient
+
+from ...utils import needs_py310
+
+
+@pytest.fixture(
+ name="client",
+ params=[
+ pytest.param("tutorial002_py39"),
+ pytest.param("tutorial002_py310", marks=needs_py310),
+ ],
+)
+def get_client(request: pytest.FixtureRequest):
+ mod = importlib.import_module(f"docs_src.query_params.{request.param}")
+
+ client = TestClient(mod.app)
+ return client
+
+
+@pytest.mark.parametrize(
+ ("path", "expected_json"),
+ [
+ (
+ "/items/foo",
+ {"item_id": "foo"},
+ ),
+ (
+ "/items/bar?q=somequery",
+ {"item_id": "bar", "q": "somequery"},
+ ),
+ ],
+)
+def test_read_user_item(client: TestClient, path, expected_json):
+ response = client.get(path)
+ assert response.status_code == 200
+ assert response.json() == expected_json
+
+
+def test_openapi_schema(client: TestClient):
+ response = client.get("/openapi.json")
+ assert response.status_code == 200
+ assert response.json() == {
+ "openapi": "3.1.0",
+ "info": {"title": "FastAPI", "version": "0.1.0"},
+ "paths": {
+ "/items/{item_id}": {
+ "get": {
+ "summary": "Read Item",
+ "operationId": "read_item_items__item_id__get",
+ "parameters": [
+ {
+ "required": True,
+ "schema": {"title": "Item Id", "type": "string"},
+ "name": "item_id",
+ "in": "path",
+ },
+ {
+ "required": False,
+ "schema": {
+ "title": "Q",
+ "anyOf": [
+ {
+ "type": "string",
+ },
+ {
+ "type": "null",
+ },
+ ],
+ },
+ "name": "q",
+ "in": "query",
+ },
+ ],
+ "responses": {
+ "200": {
+ "description": "Successful Response",
+ "content": {"application/json": {"schema": {}}},
+ },
+ "422": {
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/HTTPValidationError",
+ },
+ },
+ },
+ "description": "Validation Error",
+ },
+ },
+ }
+ }
+ },
+ "components": {
+ "schemas": {
+ "ValidationError": {
+ "title": "ValidationError",
+ "required": ["loc", "msg", "type"],
+ "type": "object",
+ "properties": {
+ "loc": {
+ "title": "Location",
+ "type": "array",
+ "items": {
+ "anyOf": [{"type": "string"}, {"type": "integer"}]
+ },
+ },
+ "msg": {"title": "Message", "type": "string"},
+ "type": {"title": "Error Type", "type": "string"},
+ },
+ },
+ "HTTPValidationError": {
+ "title": "HTTPValidationError",
+ "type": "object",
+ "properties": {
+ "detail": {
+ "title": "Detail",
+ "type": "array",
+ "items": {"$ref": "#/components/schemas/ValidationError"},
+ }
+ },
+ },
+ }
+ },
+ }
diff --git a/tests/test_tutorial/test_query_params/test_tutorial003.py b/tests/test_tutorial/test_query_params/test_tutorial003.py
new file mode 100644
index 0000000000..c0b7e3b133
--- /dev/null
+++ b/tests/test_tutorial/test_query_params/test_tutorial003.py
@@ -0,0 +1,148 @@
+import importlib
+
+import pytest
+from fastapi.testclient import TestClient
+
+from ...utils import needs_py310
+
+
+@pytest.fixture(
+ name="client",
+ params=[
+ pytest.param("tutorial003_py39"),
+ pytest.param("tutorial003_py310", marks=needs_py310),
+ ],
+)
+def get_client(request: pytest.FixtureRequest):
+ mod = importlib.import_module(f"docs_src.query_params.{request.param}")
+
+ client = TestClient(mod.app)
+ return client
+
+
+@pytest.mark.parametrize(
+ ("path", "expected_json"),
+ [
+ (
+ "/items/foo",
+ {
+ "item_id": "foo",
+ "description": "This is an amazing item that has a long description",
+ },
+ ),
+ (
+ "/items/bar?q=somequery",
+ {
+ "item_id": "bar",
+ "q": "somequery",
+ "description": "This is an amazing item that has a long description",
+ },
+ ),
+ (
+ "/items/baz?short=true",
+ {"item_id": "baz"},
+ ),
+ ],
+)
+def test_read_user_item(client: TestClient, path, expected_json):
+ response = client.get(path)
+ assert response.status_code == 200
+ assert response.json() == expected_json
+
+
+def test_openapi_schema(client: TestClient):
+ response = client.get("/openapi.json")
+ assert response.status_code == 200
+ assert response.json() == {
+ "openapi": "3.1.0",
+ "info": {"title": "FastAPI", "version": "0.1.0"},
+ "paths": {
+ "/items/{item_id}": {
+ "get": {
+ "summary": "Read Item",
+ "operationId": "read_item_items__item_id__get",
+ "parameters": [
+ {
+ "required": True,
+ "schema": {"title": "Item Id", "type": "string"},
+ "name": "item_id",
+ "in": "path",
+ },
+ {
+ "required": False,
+ "schema": {
+ "title": "Q",
+ "anyOf": [
+ {
+ "type": "string",
+ },
+ {
+ "type": "null",
+ },
+ ],
+ },
+ "name": "q",
+ "in": "query",
+ },
+ {
+ "required": False,
+ "schema": {
+ "title": "Short",
+ "type": "boolean",
+ "default": False,
+ },
+ "name": "short",
+ "in": "query",
+ },
+ ],
+ "responses": {
+ "200": {
+ "description": "Successful Response",
+ "content": {"application/json": {"schema": {}}},
+ },
+ "422": {
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/HTTPValidationError",
+ },
+ },
+ },
+ "description": "Validation Error",
+ },
+ },
+ }
+ }
+ },
+ "components": {
+ "schemas": {
+ "ValidationError": {
+ "title": "ValidationError",
+ "required": ["loc", "msg", "type"],
+ "type": "object",
+ "properties": {
+ "loc": {
+ "title": "Location",
+ "type": "array",
+ "items": {
+ "anyOf": [{"type": "string"}, {"type": "integer"}]
+ },
+ },
+ "msg": {"title": "Message", "type": "string"},
+ "type": {"title": "Error Type", "type": "string"},
+ },
+ },
+ "HTTPValidationError": {
+ "title": "HTTPValidationError",
+ "type": "object",
+ "properties": {
+ "detail": {
+ "title": "Detail",
+ "type": "array",
+ "items": {"$ref": "#/components/schemas/ValidationError"},
+ }
+ },
+ },
+ }
+ },
+ }
diff --git a/tests/test_tutorial/test_query_params/test_tutorial004.py b/tests/test_tutorial/test_query_params/test_tutorial004.py
new file mode 100644
index 0000000000..9be18b74df
--- /dev/null
+++ b/tests/test_tutorial/test_query_params/test_tutorial004.py
@@ -0,0 +1,156 @@
+import importlib
+
+import pytest
+from fastapi.testclient import TestClient
+
+from ...utils import needs_py310
+
+
+@pytest.fixture(
+ name="client",
+ params=[
+ pytest.param("tutorial004_py39"),
+ pytest.param("tutorial004_py310", marks=needs_py310),
+ ],
+)
+def get_client(request: pytest.FixtureRequest):
+ mod = importlib.import_module(f"docs_src.query_params.{request.param}")
+
+ client = TestClient(mod.app)
+ return client
+
+
+@pytest.mark.parametrize(
+ ("path", "expected_json"),
+ [
+ (
+ "/users/123/items/foo",
+ {
+ "item_id": "foo",
+ "owner_id": 123,
+ "description": "This is an amazing item that has a long description",
+ },
+ ),
+ (
+ "/users/1/items/bar?q=somequery",
+ {
+ "item_id": "bar",
+ "owner_id": 1,
+ "q": "somequery",
+ "description": "This is an amazing item that has a long description",
+ },
+ ),
+ (
+ "/users/42/items/baz?short=true",
+ {"item_id": "baz", "owner_id": 42},
+ ),
+ ],
+)
+def test_read_user_item(client: TestClient, path, expected_json):
+ response = client.get(path)
+ assert response.status_code == 200
+ assert response.json() == expected_json
+
+
+def test_openapi_schema(client: TestClient):
+ response = client.get("/openapi.json")
+ assert response.status_code == 200
+ assert response.json() == {
+ "openapi": "3.1.0",
+ "info": {"title": "FastAPI", "version": "0.1.0"},
+ "paths": {
+ "/users/{user_id}/items/{item_id}": {
+ "get": {
+ "summary": "Read User Item",
+ "operationId": "read_user_item_users__user_id__items__item_id__get",
+ "parameters": [
+ {
+ "required": True,
+ "schema": {"title": "User Id", "type": "integer"},
+ "name": "user_id",
+ "in": "path",
+ },
+ {
+ "required": True,
+ "schema": {"title": "Item Id", "type": "string"},
+ "name": "item_id",
+ "in": "path",
+ },
+ {
+ "required": False,
+ "schema": {
+ "title": "Q",
+ "anyOf": [
+ {
+ "type": "string",
+ },
+ {
+ "type": "null",
+ },
+ ],
+ },
+ "name": "q",
+ "in": "query",
+ },
+ {
+ "required": False,
+ "schema": {
+ "title": "Short",
+ "type": "boolean",
+ "default": False,
+ },
+ "name": "short",
+ "in": "query",
+ },
+ ],
+ "responses": {
+ "200": {
+ "description": "Successful Response",
+ "content": {"application/json": {"schema": {}}},
+ },
+ "422": {
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/HTTPValidationError",
+ },
+ },
+ },
+ "description": "Validation Error",
+ },
+ },
+ }
+ }
+ },
+ "components": {
+ "schemas": {
+ "ValidationError": {
+ "title": "ValidationError",
+ "required": ["loc", "msg", "type"],
+ "type": "object",
+ "properties": {
+ "loc": {
+ "title": "Location",
+ "type": "array",
+ "items": {
+ "anyOf": [{"type": "string"}, {"type": "integer"}]
+ },
+ },
+ "msg": {"title": "Message", "type": "string"},
+ "type": {"title": "Error Type", "type": "string"},
+ },
+ },
+ "HTTPValidationError": {
+ "title": "HTTPValidationError",
+ "type": "object",
+ "properties": {
+ "detail": {
+ "title": "Detail",
+ "type": "array",
+ "items": {"$ref": "#/components/schemas/ValidationError"},
+ }
+ },
+ },
+ }
+ },
+ }
diff --git a/tests/test_tutorial/test_query_params/test_tutorial005.py b/tests/test_tutorial/test_query_params/test_tutorial005.py
index 05ae85b451..1030781472 100644
--- a/tests/test_tutorial/test_query_params/test_tutorial005.py
+++ b/tests/test_tutorial/test_query_params/test_tutorial005.py
@@ -1,7 +1,6 @@
-from dirty_equals import IsDict
from fastapi.testclient import TestClient
-from docs_src.query_params.tutorial005 import app
+from docs_src.query_params.tutorial005_py39 import app
client = TestClient(app)
@@ -15,29 +14,16 @@ def test_foo_needy_very():
def test_foo_no_needy():
response = client.get("/items/foo")
assert response.status_code == 422
- assert response.json() == IsDict(
- {
- "detail": [
- {
- "type": "missing",
- "loc": ["query", "needy"],
- "msg": "Field required",
- "input": None,
- }
- ]
- }
- ) | IsDict(
- # TODO: remove when deprecating Pydantic v1
- {
- "detail": [
- {
- "loc": ["query", "needy"],
- "msg": "field required",
- "type": "value_error.missing",
- }
- ]
- }
- )
+ assert response.json() == {
+ "detail": [
+ {
+ "type": "missing",
+ "loc": ["query", "needy"],
+ "msg": "Field required",
+ "input": None,
+ }
+ ]
+ }
def test_openapi_schema():
diff --git a/tests/test_tutorial/test_query_params/test_tutorial006.py b/tests/test_tutorial/test_query_params/test_tutorial006.py
index a0b5ef4943..157322c7e3 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 importlib
import pytest
-from dirty_equals import IsDict
from fastapi.testclient import TestClient
from ...utils import needs_py310
@@ -10,7 +9,7 @@ from ...utils import needs_py310
@pytest.fixture(
name="client",
params=[
- "tutorial006",
+ pytest.param("tutorial006_py39"),
pytest.param("tutorial006_py310", marks=needs_py310),
],
)
@@ -35,51 +34,28 @@ def test_foo_needy_very(client: TestClient):
def test_foo_no_needy(client: TestClient):
response = client.get("/items/foo?skip=a&limit=b")
assert response.status_code == 422
- assert response.json() == IsDict(
- {
- "detail": [
- {
- "type": "missing",
- "loc": ["query", "needy"],
- "msg": "Field required",
- "input": None,
- },
- {
- "type": "int_parsing",
- "loc": ["query", "skip"],
- "msg": "Input should be a valid integer, unable to parse string as an integer",
- "input": "a",
- },
- {
- "type": "int_parsing",
- "loc": ["query", "limit"],
- "msg": "Input should be a valid integer, unable to parse string as an integer",
- "input": "b",
- },
- ]
- }
- ) | IsDict(
- # TODO: remove when deprecating Pydantic v1
- {
- "detail": [
- {
- "loc": ["query", "needy"],
- "msg": "field required",
- "type": "value_error.missing",
- },
- {
- "loc": ["query", "skip"],
- "msg": "value is not a valid integer",
- "type": "type_error.integer",
- },
- {
- "loc": ["query", "limit"],
- "msg": "value is not a valid integer",
- "type": "type_error.integer",
- },
- ]
- }
- )
+ assert response.json() == {
+ "detail": [
+ {
+ "type": "missing",
+ "loc": ["query", "needy"],
+ "msg": "Field required",
+ "input": None,
+ },
+ {
+ "type": "int_parsing",
+ "loc": ["query", "skip"],
+ "msg": "Input should be a valid integer, unable to parse string as an integer",
+ "input": "a",
+ },
+ {
+ "type": "int_parsing",
+ "loc": ["query", "limit"],
+ "msg": "Input should be a valid integer, unable to parse string as an integer",
+ "input": "b",
+ },
+ ]
+ }
def test_openapi_schema(client: TestClient):
@@ -134,16 +110,10 @@ def test_openapi_schema(client: TestClient):
},
{
"required": False,
- "schema": IsDict(
- {
- "anyOf": [{"type": "integer"}, {"type": "null"}],
- "title": "Limit",
- }
- )
- | IsDict(
- # TODO: remove when deprecating Pydantic v1
- {"title": "Limit", "type": "integer"}
- ),
+ "schema": {
+ "anyOf": [{"type": "integer"}, {"type": "null"}],
+ "title": "Limit",
+ },
"name": "limit",
"in": "query",
},
diff --git a/tests/test_tutorial/test_query_params_str_validations/test_tutorial001.py b/tests/test_tutorial/test_query_params_str_validations/test_tutorial001.py
new file mode 100644
index 0000000000..f1af7e08c1
--- /dev/null
+++ b/tests/test_tutorial/test_query_params_str_validations/test_tutorial001.py
@@ -0,0 +1,121 @@
+import importlib
+
+import pytest
+from fastapi.testclient import TestClient
+
+from ...utils import needs_py310
+
+
+@pytest.fixture(
+ name="client",
+ params=[
+ pytest.param("tutorial001_py39"),
+ pytest.param("tutorial001_py310", marks=needs_py310),
+ ],
+)
+def get_client(request: pytest.FixtureRequest):
+ mod = importlib.import_module(
+ f"docs_src.query_params_str_validations.{request.param}"
+ )
+
+ client = TestClient(mod.app)
+ return client
+
+
+def test_query_params_str_validations_no_query(client: TestClient):
+ response = client.get("/items/")
+ assert response.status_code == 200
+ assert response.json() == {"items": [{"item_id": "Foo"}, {"item_id": "Bar"}]}
+
+
+def test_query_params_str_validations_q_empty_str(client: TestClient):
+ response = client.get("/items/", params={"q": ""})
+ assert response.status_code == 200
+ assert response.json() == {"items": [{"item_id": "Foo"}, {"item_id": "Bar"}]}
+
+
+def test_query_params_str_validations_q_query(client: TestClient):
+ response = client.get("/items/", params={"q": "query"})
+ assert response.status_code == 200
+ assert response.json() == {
+ "items": [{"item_id": "Foo"}, {"item_id": "Bar"}],
+ "q": "query",
+ }
+
+
+def test_openapi_schema(client: TestClient):
+ response = client.get("/openapi.json")
+ assert response.status_code == 200, response.text
+ assert response.json() == {
+ "openapi": "3.1.0",
+ "info": {"title": "FastAPI", "version": "0.1.0"},
+ "paths": {
+ "/items/": {
+ "get": {
+ "responses": {
+ "200": {
+ "description": "Successful Response",
+ "content": {"application/json": {"schema": {}}},
+ },
+ "422": {
+ "description": "Validation Error",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/HTTPValidationError"
+ }
+ }
+ },
+ },
+ },
+ "summary": "Read Items",
+ "operationId": "read_items_items__get",
+ "parameters": [
+ {
+ "required": False,
+ "schema": {
+ "anyOf": [
+ {"type": "string"},
+ {"type": "null"},
+ ],
+ "title": "Q",
+ },
+ "name": "q",
+ "in": "query",
+ }
+ ],
+ }
+ }
+ },
+ "components": {
+ "schemas": {
+ "ValidationError": {
+ "title": "ValidationError",
+ "required": ["loc", "msg", "type"],
+ "type": "object",
+ "properties": {
+ "loc": {
+ "title": "Location",
+ "type": "array",
+ "items": {
+ "anyOf": [{"type": "string"}, {"type": "integer"}]
+ },
+ },
+ "msg": {"title": "Message", "type": "string"},
+ "type": {"title": "Error Type", "type": "string"},
+ },
+ },
+ "HTTPValidationError": {
+ "title": "HTTPValidationError",
+ "type": "object",
+ "properties": {
+ "detail": {
+ "title": "Detail",
+ "type": "array",
+ "items": {"$ref": "#/components/schemas/ValidationError"},
+ }
+ },
+ },
+ }
+ },
+ }
diff --git a/tests/test_tutorial/test_query_params_str_validations/test_tutorial002.py b/tests/test_tutorial/test_query_params_str_validations/test_tutorial002.py
new file mode 100644
index 0000000000..62018b80b5
--- /dev/null
+++ b/tests/test_tutorial/test_query_params_str_validations/test_tutorial002.py
@@ -0,0 +1,142 @@
+import importlib
+
+import pytest
+from fastapi.testclient import TestClient
+
+from ...utils import needs_py310
+
+
+@pytest.fixture(
+ name="client",
+ params=[
+ pytest.param("tutorial002_py39"),
+ pytest.param("tutorial002_py310", marks=needs_py310),
+ pytest.param("tutorial002_an_py39"),
+ pytest.param("tutorial002_an_py310", marks=needs_py310),
+ ],
+)
+def get_client(request: pytest.FixtureRequest):
+ mod = importlib.import_module(
+ f"docs_src.query_params_str_validations.{request.param}"
+ )
+
+ client = TestClient(mod.app)
+ return client
+
+
+def test_query_params_str_validations_no_query(client: TestClient):
+ response = client.get("/items/")
+ assert response.status_code == 200
+ assert response.json() == {"items": [{"item_id": "Foo"}, {"item_id": "Bar"}]}
+
+
+def test_query_params_str_validations_q_empty_str(client: TestClient):
+ response = client.get("/items/", params={"q": ""})
+ assert response.status_code == 200
+ assert response.json() == {"items": [{"item_id": "Foo"}, {"item_id": "Bar"}]}
+
+
+def test_query_params_str_validations_q_query(client: TestClient):
+ response = client.get("/items/", params={"q": "query"})
+ assert response.status_code == 200
+ assert response.json() == {
+ "items": [{"item_id": "Foo"}, {"item_id": "Bar"}],
+ "q": "query",
+ }
+
+
+def test_query_params_str_validations_q_too_long(client: TestClient):
+ response = client.get("/items/", params={"q": "q" * 51})
+ assert response.status_code == 422
+ assert response.json() == {
+ "detail": [
+ {
+ "type": "string_too_long",
+ "loc": ["query", "q"],
+ "msg": "String should have at most 50 characters",
+ "input": "q" * 51,
+ "ctx": {"max_length": 50},
+ }
+ ]
+ }
+
+
+def test_openapi_schema(client: TestClient):
+ response = client.get("/openapi.json")
+ assert response.status_code == 200, response.text
+ assert response.json() == {
+ "openapi": "3.1.0",
+ "info": {"title": "FastAPI", "version": "0.1.0"},
+ "paths": {
+ "/items/": {
+ "get": {
+ "responses": {
+ "200": {
+ "description": "Successful Response",
+ "content": {"application/json": {"schema": {}}},
+ },
+ "422": {
+ "description": "Validation Error",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/HTTPValidationError"
+ }
+ }
+ },
+ },
+ },
+ "summary": "Read Items",
+ "operationId": "read_items_items__get",
+ "parameters": [
+ {
+ "required": False,
+ "schema": {
+ "anyOf": [
+ {
+ "type": "string",
+ "maxLength": 50,
+ },
+ {"type": "null"},
+ ],
+ "title": "Q",
+ },
+ "name": "q",
+ "in": "query",
+ }
+ ],
+ }
+ }
+ },
+ "components": {
+ "schemas": {
+ "ValidationError": {
+ "title": "ValidationError",
+ "required": ["loc", "msg", "type"],
+ "type": "object",
+ "properties": {
+ "loc": {
+ "title": "Location",
+ "type": "array",
+ "items": {
+ "anyOf": [{"type": "string"}, {"type": "integer"}]
+ },
+ },
+ "msg": {"title": "Message", "type": "string"},
+ "type": {"title": "Error Type", "type": "string"},
+ },
+ },
+ "HTTPValidationError": {
+ "title": "HTTPValidationError",
+ "type": "object",
+ "properties": {
+ "detail": {
+ "title": "Detail",
+ "type": "array",
+ "items": {"$ref": "#/components/schemas/ValidationError"},
+ }
+ },
+ },
+ }
+ },
+ }
diff --git a/tests/test_tutorial/test_query_params_str_validations/test_tutorial003.py b/tests/test_tutorial/test_query_params_str_validations/test_tutorial003.py
new file mode 100644
index 0000000000..a4ad7a63ba
--- /dev/null
+++ b/tests/test_tutorial/test_query_params_str_validations/test_tutorial003.py
@@ -0,0 +1,153 @@
+import importlib
+
+import pytest
+from fastapi.testclient import TestClient
+
+from ...utils import needs_py310
+
+
+@pytest.fixture(
+ name="client",
+ params=[
+ pytest.param("tutorial003_py39"),
+ pytest.param("tutorial003_py310", marks=needs_py310),
+ pytest.param("tutorial003_an_py39"),
+ pytest.param("tutorial003_an_py310", marks=needs_py310),
+ ],
+)
+def get_client(request: pytest.FixtureRequest):
+ mod = importlib.import_module(
+ f"docs_src.query_params_str_validations.{request.param}"
+ )
+
+ client = TestClient(mod.app)
+ return client
+
+
+def test_query_params_str_validations_no_query(client: TestClient):
+ response = client.get("/items/")
+ assert response.status_code == 200
+ assert response.json() == {"items": [{"item_id": "Foo"}, {"item_id": "Bar"}]}
+
+
+def test_query_params_str_validations_q_query(client: TestClient):
+ response = client.get("/items/", params={"q": "query"})
+ assert response.status_code == 200
+ assert response.json() == {
+ "items": [{"item_id": "Foo"}, {"item_id": "Bar"}],
+ "q": "query",
+ }
+
+
+def test_query_params_str_validations_q_too_short(client: TestClient):
+ response = client.get("/items/", params={"q": "qu"})
+ assert response.status_code == 422
+ assert response.json() == {
+ "detail": [
+ {
+ "type": "string_too_short",
+ "loc": ["query", "q"],
+ "msg": "String should have at least 3 characters",
+ "input": "qu",
+ "ctx": {"min_length": 3},
+ }
+ ]
+ }
+
+
+def test_query_params_str_validations_q_too_long(client: TestClient):
+ response = client.get("/items/", params={"q": "q" * 51})
+ assert response.status_code == 422
+ assert response.json() == {
+ "detail": [
+ {
+ "type": "string_too_long",
+ "loc": ["query", "q"],
+ "msg": "String should have at most 50 characters",
+ "input": "q" * 51,
+ "ctx": {"max_length": 50},
+ }
+ ]
+ }
+
+
+def test_openapi_schema(client: TestClient):
+ response = client.get("/openapi.json")
+ assert response.status_code == 200, response.text
+ assert response.json() == {
+ "openapi": "3.1.0",
+ "info": {"title": "FastAPI", "version": "0.1.0"},
+ "paths": {
+ "/items/": {
+ "get": {
+ "responses": {
+ "200": {
+ "description": "Successful Response",
+ "content": {"application/json": {"schema": {}}},
+ },
+ "422": {
+ "description": "Validation Error",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/HTTPValidationError"
+ }
+ }
+ },
+ },
+ },
+ "summary": "Read Items",
+ "operationId": "read_items_items__get",
+ "parameters": [
+ {
+ "required": False,
+ "schema": {
+ "anyOf": [
+ {
+ "type": "string",
+ "minLength": 3,
+ "maxLength": 50,
+ },
+ {"type": "null"},
+ ],
+ "title": "Q",
+ },
+ "name": "q",
+ "in": "query",
+ }
+ ],
+ }
+ }
+ },
+ "components": {
+ "schemas": {
+ "ValidationError": {
+ "title": "ValidationError",
+ "required": ["loc", "msg", "type"],
+ "type": "object",
+ "properties": {
+ "loc": {
+ "title": "Location",
+ "type": "array",
+ "items": {
+ "anyOf": [{"type": "string"}, {"type": "integer"}]
+ },
+ },
+ "msg": {"title": "Message", "type": "string"},
+ "type": {"title": "Error Type", "type": "string"},
+ },
+ },
+ "HTTPValidationError": {
+ "title": "HTTPValidationError",
+ "type": "object",
+ "properties": {
+ "detail": {
+ "title": "Detail",
+ "type": "array",
+ "items": {"$ref": "#/components/schemas/ValidationError"},
+ }
+ },
+ },
+ }
+ },
+ }
diff --git a/tests/test_tutorial/test_query_params_str_validations/test_tutorial004.py b/tests/test_tutorial/test_query_params_str_validations/test_tutorial004.py
new file mode 100644
index 0000000000..585989a827
--- /dev/null
+++ b/tests/test_tutorial/test_query_params_str_validations/test_tutorial004.py
@@ -0,0 +1,147 @@
+import importlib
+
+import pytest
+from fastapi.testclient import TestClient
+
+from ...utils import needs_py310
+
+
+@pytest.fixture(
+ name="client",
+ params=[
+ pytest.param("tutorial004_py39"),
+ pytest.param("tutorial004_py310", marks=needs_py310),
+ pytest.param("tutorial004_an_py39"),
+ pytest.param("tutorial004_an_py310", marks=needs_py310),
+ pytest.param(
+ "tutorial004_regex_an_py310",
+ marks=(
+ needs_py310,
+ pytest.mark.filterwarnings(
+ "ignore:`regex` has been deprecated, please use `pattern` instead:fastapi.exceptions.FastAPIDeprecationWarning"
+ ),
+ ),
+ ),
+ ],
+)
+def get_client(request: pytest.FixtureRequest):
+ mod = importlib.import_module(
+ f"docs_src.query_params_str_validations.{request.param}"
+ )
+
+ client = TestClient(mod.app)
+ return client
+
+
+def test_query_params_str_validations_no_query(client: TestClient):
+ response = client.get("/items/")
+ assert response.status_code == 200
+ assert response.json() == {"items": [{"item_id": "Foo"}, {"item_id": "Bar"}]}
+
+
+def test_query_params_str_validations_q_fixedquery(client: TestClient):
+ response = client.get("/items/", params={"q": "fixedquery"})
+ assert response.status_code == 200
+ assert response.json() == {
+ "items": [{"item_id": "Foo"}, {"item_id": "Bar"}],
+ "q": "fixedquery",
+ }
+
+
+def test_query_params_str_validations_q_nonregexquery(client: TestClient):
+ response = client.get("/items/", params={"q": "nonregexquery"})
+ assert response.status_code == 422
+ assert response.json() == {
+ "detail": [
+ {
+ "type": "string_pattern_mismatch",
+ "loc": ["query", "q"],
+ "msg": "String should match pattern '^fixedquery$'",
+ "input": "nonregexquery",
+ "ctx": {"pattern": "^fixedquery$"},
+ }
+ ]
+ }
+
+
+def test_openapi_schema(client: TestClient):
+ response = client.get("/openapi.json")
+ assert response.status_code == 200, response.text
+ assert response.json() == {
+ "openapi": "3.1.0",
+ "info": {"title": "FastAPI", "version": "0.1.0"},
+ "paths": {
+ "/items/": {
+ "get": {
+ "responses": {
+ "200": {
+ "description": "Successful Response",
+ "content": {"application/json": {"schema": {}}},
+ },
+ "422": {
+ "description": "Validation Error",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/HTTPValidationError"
+ }
+ }
+ },
+ },
+ },
+ "summary": "Read Items",
+ "operationId": "read_items_items__get",
+ "parameters": [
+ {
+ "required": False,
+ "schema": {
+ "anyOf": [
+ {
+ "type": "string",
+ "minLength": 3,
+ "maxLength": 50,
+ "pattern": "^fixedquery$",
+ },
+ {"type": "null"},
+ ],
+ "title": "Q",
+ },
+ "name": "q",
+ "in": "query",
+ }
+ ],
+ }
+ }
+ },
+ "components": {
+ "schemas": {
+ "ValidationError": {
+ "title": "ValidationError",
+ "required": ["loc", "msg", "type"],
+ "type": "object",
+ "properties": {
+ "loc": {
+ "title": "Location",
+ "type": "array",
+ "items": {
+ "anyOf": [{"type": "string"}, {"type": "integer"}]
+ },
+ },
+ "msg": {"title": "Message", "type": "string"},
+ "type": {"title": "Error Type", "type": "string"},
+ },
+ },
+ "HTTPValidationError": {
+ "title": "HTTPValidationError",
+ "type": "object",
+ "properties": {
+ "detail": {
+ "title": "Detail",
+ "type": "array",
+ "items": {"$ref": "#/components/schemas/ValidationError"},
+ }
+ },
+ },
+ }
+ },
+ }
diff --git a/tests/test_tutorial/test_query_params_str_validations/test_tutorial005.py b/tests/test_tutorial/test_query_params_str_validations/test_tutorial005.py
new file mode 100644
index 0000000000..52462fe33b
--- /dev/null
+++ b/tests/test_tutorial/test_query_params_str_validations/test_tutorial005.py
@@ -0,0 +1,131 @@
+import importlib
+
+import pytest
+from fastapi.testclient import TestClient
+
+
+@pytest.fixture(
+ name="client",
+ params=[
+ pytest.param("tutorial005_py39"),
+ pytest.param("tutorial005_an_py39"),
+ ],
+)
+def get_client(request: pytest.FixtureRequest):
+ mod = importlib.import_module(
+ f"docs_src.query_params_str_validations.{request.param}"
+ )
+
+ client = TestClient(mod.app)
+ return client
+
+
+def test_query_params_str_validations_no_query(client: TestClient):
+ response = client.get("/items/")
+ assert response.status_code == 200
+ assert response.json() == {
+ "items": [{"item_id": "Foo"}, {"item_id": "Bar"}],
+ "q": "fixedquery",
+ }
+
+
+def test_query_params_str_validations_q_query(client: TestClient):
+ response = client.get("/items/", params={"q": "query"})
+ assert response.status_code == 200
+ assert response.json() == {
+ "items": [{"item_id": "Foo"}, {"item_id": "Bar"}],
+ "q": "query",
+ }
+
+
+def test_query_params_str_validations_q_short(client: TestClient):
+ response = client.get("/items/", params={"q": "fa"})
+ assert response.status_code == 422
+ assert response.json() == {
+ "detail": [
+ {
+ "type": "string_too_short",
+ "loc": ["query", "q"],
+ "msg": "String should have at least 3 characters",
+ "input": "fa",
+ "ctx": {"min_length": 3},
+ }
+ ]
+ }
+
+
+def test_openapi_schema(client: TestClient):
+ response = client.get("/openapi.json")
+ assert response.status_code == 200, response.text
+ assert response.json() == {
+ "openapi": "3.1.0",
+ "info": {"title": "FastAPI", "version": "0.1.0"},
+ "paths": {
+ "/items/": {
+ "get": {
+ "responses": {
+ "200": {
+ "description": "Successful Response",
+ "content": {"application/json": {"schema": {}}},
+ },
+ "422": {
+ "description": "Validation Error",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/HTTPValidationError"
+ }
+ }
+ },
+ },
+ },
+ "summary": "Read Items",
+ "operationId": "read_items_items__get",
+ "parameters": [
+ {
+ "required": False,
+ "schema": {
+ "type": "string",
+ "default": "fixedquery",
+ "minLength": 3,
+ "title": "Q",
+ },
+ "name": "q",
+ "in": "query",
+ }
+ ],
+ }
+ }
+ },
+ "components": {
+ "schemas": {
+ "ValidationError": {
+ "title": "ValidationError",
+ "required": ["loc", "msg", "type"],
+ "type": "object",
+ "properties": {
+ "loc": {
+ "title": "Location",
+ "type": "array",
+ "items": {
+ "anyOf": [{"type": "string"}, {"type": "integer"}]
+ },
+ },
+ "msg": {"title": "Message", "type": "string"},
+ "type": {"title": "Error Type", "type": "string"},
+ },
+ },
+ "HTTPValidationError": {
+ "title": "HTTPValidationError",
+ "type": "object",
+ "properties": {
+ "detail": {
+ "title": "Detail",
+ "type": "array",
+ "items": {"$ref": "#/components/schemas/ValidationError"},
+ }
+ },
+ },
+ }
+ },
+ }
diff --git a/tests/test_tutorial/test_query_params_str_validations/test_tutorial006.py b/tests/test_tutorial/test_query_params_str_validations/test_tutorial006.py
new file mode 100644
index 0000000000..640cedce19
--- /dev/null
+++ b/tests/test_tutorial/test_query_params_str_validations/test_tutorial006.py
@@ -0,0 +1,136 @@
+import importlib
+
+import pytest
+from fastapi.testclient import TestClient
+
+
+@pytest.fixture(
+ name="client",
+ params=[
+ pytest.param("tutorial006_py39"),
+ pytest.param("tutorial006_an_py39"),
+ ],
+)
+def get_client(request: pytest.FixtureRequest):
+ mod = importlib.import_module(
+ f"docs_src.query_params_str_validations.{request.param}"
+ )
+
+ client = TestClient(mod.app)
+ return client
+
+
+def test_query_params_str_validations_no_query(client: TestClient):
+ response = client.get("/items/")
+ assert response.status_code == 422
+ assert response.json() == {
+ "detail": [
+ {
+ "type": "missing",
+ "loc": ["query", "q"],
+ "msg": "Field required",
+ "input": None,
+ }
+ ]
+ }
+
+
+def test_query_params_str_validations_q_fixedquery(client: TestClient):
+ response = client.get("/items/", params={"q": "fixedquery"})
+ assert response.status_code == 200
+ assert response.json() == {
+ "items": [{"item_id": "Foo"}, {"item_id": "Bar"}],
+ "q": "fixedquery",
+ }
+
+
+def test_query_params_str_validations_q_fixedquery_too_short(client: TestClient):
+ response = client.get("/items/", params={"q": "fa"})
+ assert response.status_code == 422
+ assert response.json() == {
+ "detail": [
+ {
+ "type": "string_too_short",
+ "loc": ["query", "q"],
+ "msg": "String should have at least 3 characters",
+ "input": "fa",
+ "ctx": {"min_length": 3},
+ }
+ ]
+ }
+
+
+def test_openapi_schema(client: TestClient):
+ response = client.get("/openapi.json")
+ assert response.status_code == 200, response.text
+ assert response.json() == {
+ "openapi": "3.1.0",
+ "info": {"title": "FastAPI", "version": "0.1.0"},
+ "paths": {
+ "/items/": {
+ "get": {
+ "responses": {
+ "200": {
+ "description": "Successful Response",
+ "content": {"application/json": {"schema": {}}},
+ },
+ "422": {
+ "description": "Validation Error",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/HTTPValidationError"
+ }
+ }
+ },
+ },
+ },
+ "summary": "Read Items",
+ "operationId": "read_items_items__get",
+ "parameters": [
+ {
+ "required": True,
+ "schema": {
+ "type": "string",
+ "minLength": 3,
+ "title": "Q",
+ },
+ "name": "q",
+ "in": "query",
+ }
+ ],
+ }
+ }
+ },
+ "components": {
+ "schemas": {
+ "ValidationError": {
+ "title": "ValidationError",
+ "required": ["loc", "msg", "type"],
+ "type": "object",
+ "properties": {
+ "loc": {
+ "title": "Location",
+ "type": "array",
+ "items": {
+ "anyOf": [{"type": "string"}, {"type": "integer"}]
+ },
+ },
+ "msg": {"title": "Message", "type": "string"},
+ "type": {"title": "Error Type", "type": "string"},
+ },
+ },
+ "HTTPValidationError": {
+ "title": "HTTPValidationError",
+ "type": "object",
+ "properties": {
+ "detail": {
+ "title": "Detail",
+ "type": "array",
+ "items": {"$ref": "#/components/schemas/ValidationError"},
+ }
+ },
+ },
+ }
+ },
+ }
diff --git a/tests/test_tutorial/test_query_params_str_validations/test_tutorial006c.py b/tests/test_tutorial/test_query_params_str_validations/test_tutorial006c.py
new file mode 100644
index 0000000000..f287b5dcd8
--- /dev/null
+++ b/tests/test_tutorial/test_query_params_str_validations/test_tutorial006c.py
@@ -0,0 +1,148 @@
+import importlib
+
+import pytest
+from fastapi.testclient import TestClient
+
+from ...utils import needs_py310
+
+
+@pytest.fixture(
+ name="client",
+ params=[
+ pytest.param("tutorial006c_py39"),
+ pytest.param("tutorial006c_py310", marks=needs_py310),
+ pytest.param("tutorial006c_an_py39"),
+ pytest.param("tutorial006c_an_py310", marks=needs_py310),
+ ],
+)
+def get_client(request: pytest.FixtureRequest):
+ mod = importlib.import_module(
+ f"docs_src.query_params_str_validations.{request.param}"
+ )
+ client = TestClient(mod.app)
+ return client
+
+
+@pytest.mark.xfail(
+ reason="Code example is not valid. See https://github.com/fastapi/fastapi/issues/12419"
+)
+def test_query_params_str_validations_no_query(client: TestClient):
+ response = client.get("/items/")
+ assert response.status_code == 200
+ assert response.json() == { # pragma: no cover
+ "items": [{"item_id": "Foo"}, {"item_id": "Bar"}],
+ }
+
+
+@pytest.mark.xfail(
+ reason="Code example is not valid. See https://github.com/fastapi/fastapi/issues/12419"
+)
+def test_query_params_str_validations_empty_str(client: TestClient):
+ response = client.get("/items/?q=")
+ assert response.status_code == 200
+ assert response.json() == { # pragma: no cover
+ "items": [{"item_id": "Foo"}, {"item_id": "Bar"}],
+ }
+
+
+def test_query_params_str_validations_q_query(client: TestClient):
+ response = client.get("/items/", params={"q": "query"})
+ assert response.status_code == 200
+ assert response.json() == {
+ "items": [{"item_id": "Foo"}, {"item_id": "Bar"}],
+ "q": "query",
+ }
+
+
+def test_query_params_str_validations_q_short(client: TestClient):
+ response = client.get("/items/", params={"q": "fa"})
+ assert response.status_code == 422
+ assert response.json() == {
+ "detail": [
+ {
+ "type": "string_too_short",
+ "loc": ["query", "q"],
+ "msg": "String should have at least 3 characters",
+ "input": "fa",
+ "ctx": {"min_length": 3},
+ }
+ ]
+ }
+
+
+def test_openapi_schema(client: TestClient):
+ response = client.get("/openapi.json")
+ assert response.status_code == 200, response.text
+ assert response.json() == {
+ "openapi": "3.1.0",
+ "info": {"title": "FastAPI", "version": "0.1.0"},
+ "paths": {
+ "/items/": {
+ "get": {
+ "responses": {
+ "200": {
+ "description": "Successful Response",
+ "content": {"application/json": {"schema": {}}},
+ },
+ "422": {
+ "description": "Validation Error",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/HTTPValidationError"
+ }
+ }
+ },
+ },
+ },
+ "summary": "Read Items",
+ "operationId": "read_items_items__get",
+ "parameters": [
+ {
+ "required": True,
+ "schema": {
+ "anyOf": [
+ {"type": "string", "minLength": 3},
+ {"type": "null"},
+ ],
+ "title": "Q",
+ },
+ "name": "q",
+ "in": "query",
+ }
+ ],
+ }
+ }
+ },
+ "components": {
+ "schemas": {
+ "ValidationError": {
+ "title": "ValidationError",
+ "required": ["loc", "msg", "type"],
+ "type": "object",
+ "properties": {
+ "loc": {
+ "title": "Location",
+ "type": "array",
+ "items": {
+ "anyOf": [{"type": "string"}, {"type": "integer"}]
+ },
+ },
+ "msg": {"title": "Message", "type": "string"},
+ "type": {"title": "Error Type", "type": "string"},
+ },
+ },
+ "HTTPValidationError": {
+ "title": "HTTPValidationError",
+ "type": "object",
+ "properties": {
+ "detail": {
+ "title": "Detail",
+ "type": "array",
+ "items": {"$ref": "#/components/schemas/ValidationError"},
+ }
+ },
+ },
+ }
+ },
+ }
diff --git a/tests/test_tutorial/test_query_params_str_validations/test_tutorial007.py b/tests/test_tutorial/test_query_params_str_validations/test_tutorial007.py
new file mode 100644
index 0000000000..b17bc27719
--- /dev/null
+++ b/tests/test_tutorial/test_query_params_str_validations/test_tutorial007.py
@@ -0,0 +1,136 @@
+import importlib
+
+import pytest
+from fastapi.testclient import TestClient
+
+from ...utils import needs_py310
+
+
+@pytest.fixture(
+ name="client",
+ params=[
+ pytest.param("tutorial007_py39"),
+ pytest.param("tutorial007_py310", marks=needs_py310),
+ pytest.param("tutorial007_an_py39"),
+ pytest.param("tutorial007_an_py310", marks=needs_py310),
+ ],
+)
+def get_client(request: pytest.FixtureRequest):
+ mod = importlib.import_module(
+ f"docs_src.query_params_str_validations.{request.param}"
+ )
+
+ client = TestClient(mod.app)
+ return client
+
+
+def test_query_params_str_validations_no_query(client: TestClient):
+ response = client.get("/items/")
+ assert response.status_code == 200
+ assert response.json() == {"items": [{"item_id": "Foo"}, {"item_id": "Bar"}]}
+
+
+def test_query_params_str_validations_q_fixedquery(client: TestClient):
+ response = client.get("/items/", params={"q": "fixedquery"})
+ assert response.status_code == 200
+ assert response.json() == {
+ "items": [{"item_id": "Foo"}, {"item_id": "Bar"}],
+ "q": "fixedquery",
+ }
+
+
+def test_query_params_str_validations_q_fixedquery_too_short(client: TestClient):
+ response = client.get("/items/", params={"q": "fa"})
+ assert response.status_code == 422
+ assert response.json() == {
+ "detail": [
+ {
+ "type": "string_too_short",
+ "loc": ["query", "q"],
+ "msg": "String should have at least 3 characters",
+ "input": "fa",
+ "ctx": {"min_length": 3},
+ }
+ ]
+ }
+
+
+def test_openapi_schema(client: TestClient):
+ response = client.get("/openapi.json")
+ assert response.status_code == 200, response.text
+ assert response.json() == {
+ "openapi": "3.1.0",
+ "info": {"title": "FastAPI", "version": "0.1.0"},
+ "paths": {
+ "/items/": {
+ "get": {
+ "responses": {
+ "200": {
+ "description": "Successful Response",
+ "content": {"application/json": {"schema": {}}},
+ },
+ "422": {
+ "description": "Validation Error",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/HTTPValidationError"
+ }
+ }
+ },
+ },
+ },
+ "summary": "Read Items",
+ "operationId": "read_items_items__get",
+ "parameters": [
+ {
+ "required": False,
+ "schema": {
+ "anyOf": [
+ {
+ "type": "string",
+ "minLength": 3,
+ },
+ {"type": "null"},
+ ],
+ "title": "Query string",
+ },
+ "name": "q",
+ "in": "query",
+ }
+ ],
+ }
+ }
+ },
+ "components": {
+ "schemas": {
+ "ValidationError": {
+ "title": "ValidationError",
+ "required": ["loc", "msg", "type"],
+ "type": "object",
+ "properties": {
+ "loc": {
+ "title": "Location",
+ "type": "array",
+ "items": {
+ "anyOf": [{"type": "string"}, {"type": "integer"}]
+ },
+ },
+ "msg": {"title": "Message", "type": "string"},
+ "type": {"title": "Error Type", "type": "string"},
+ },
+ },
+ "HTTPValidationError": {
+ "title": "HTTPValidationError",
+ "type": "object",
+ "properties": {
+ "detail": {
+ "title": "Detail",
+ "type": "array",
+ "items": {"$ref": "#/components/schemas/ValidationError"},
+ }
+ },
+ },
+ }
+ },
+ }
diff --git a/tests/test_tutorial/test_query_params_str_validations/test_tutorial008.py b/tests/test_tutorial/test_query_params_str_validations/test_tutorial008.py
new file mode 100644
index 0000000000..c631115744
--- /dev/null
+++ b/tests/test_tutorial/test_query_params_str_validations/test_tutorial008.py
@@ -0,0 +1,138 @@
+import importlib
+
+import pytest
+from fastapi.testclient import TestClient
+
+from ...utils import needs_py310
+
+
+@pytest.fixture(
+ name="client",
+ params=[
+ pytest.param("tutorial008_py39"),
+ pytest.param("tutorial008_py310", marks=needs_py310),
+ pytest.param("tutorial008_an_py39"),
+ pytest.param("tutorial008_an_py310", marks=needs_py310),
+ ],
+)
+def get_client(request: pytest.FixtureRequest):
+ mod = importlib.import_module(
+ f"docs_src.query_params_str_validations.{request.param}"
+ )
+
+ client = TestClient(mod.app)
+ return client
+
+
+def test_query_params_str_validations_no_query(client: TestClient):
+ response = client.get("/items/")
+ assert response.status_code == 200
+ assert response.json() == {"items": [{"item_id": "Foo"}, {"item_id": "Bar"}]}
+
+
+def test_query_params_str_validations_q_fixedquery(client: TestClient):
+ response = client.get("/items/", params={"q": "fixedquery"})
+ assert response.status_code == 200
+ assert response.json() == {
+ "items": [{"item_id": "Foo"}, {"item_id": "Bar"}],
+ "q": "fixedquery",
+ }
+
+
+def test_query_params_str_validations_q_fixedquery_too_short(client: TestClient):
+ response = client.get("/items/", params={"q": "fa"})
+ assert response.status_code == 422
+ assert response.json() == {
+ "detail": [
+ {
+ "type": "string_too_short",
+ "loc": ["query", "q"],
+ "msg": "String should have at least 3 characters",
+ "input": "fa",
+ "ctx": {"min_length": 3},
+ }
+ ]
+ }
+
+
+def test_openapi_schema(client: TestClient):
+ response = client.get("/openapi.json")
+ assert response.status_code == 200, response.text
+ assert response.json() == {
+ "openapi": "3.1.0",
+ "info": {"title": "FastAPI", "version": "0.1.0"},
+ "paths": {
+ "/items/": {
+ "get": {
+ "responses": {
+ "200": {
+ "description": "Successful Response",
+ "content": {"application/json": {"schema": {}}},
+ },
+ "422": {
+ "description": "Validation Error",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/HTTPValidationError"
+ }
+ }
+ },
+ },
+ },
+ "summary": "Read Items",
+ "operationId": "read_items_items__get",
+ "parameters": [
+ {
+ "description": "Query string for the items to search in the database that have a good match",
+ "required": False,
+ "schema": {
+ "anyOf": [
+ {
+ "type": "string",
+ "minLength": 3,
+ },
+ {"type": "null"},
+ ],
+ "title": "Query string",
+ "description": "Query string for the items to search in the database that have a good match",
+ },
+ "name": "q",
+ "in": "query",
+ }
+ ],
+ }
+ }
+ },
+ "components": {
+ "schemas": {
+ "ValidationError": {
+ "title": "ValidationError",
+ "required": ["loc", "msg", "type"],
+ "type": "object",
+ "properties": {
+ "loc": {
+ "title": "Location",
+ "type": "array",
+ "items": {
+ "anyOf": [{"type": "string"}, {"type": "integer"}]
+ },
+ },
+ "msg": {"title": "Message", "type": "string"},
+ "type": {"title": "Error Type", "type": "string"},
+ },
+ },
+ "HTTPValidationError": {
+ "title": "HTTPValidationError",
+ "type": "object",
+ "properties": {
+ "detail": {
+ "title": "Detail",
+ "type": "array",
+ "items": {"$ref": "#/components/schemas/ValidationError"},
+ }
+ },
+ },
+ }
+ },
+ }
diff --git a/tests/test_tutorial/test_query_params_str_validations/test_tutorial009.py b/tests/test_tutorial/test_query_params_str_validations/test_tutorial009.py
new file mode 100644
index 0000000000..7e9d69d41c
--- /dev/null
+++ b/tests/test_tutorial/test_query_params_str_validations/test_tutorial009.py
@@ -0,0 +1,123 @@
+import importlib
+
+import pytest
+from fastapi.testclient import TestClient
+
+from ...utils import needs_py310
+
+
+@pytest.fixture(
+ name="client",
+ params=[
+ pytest.param("tutorial009_py39"),
+ pytest.param("tutorial009_py310", marks=needs_py310),
+ pytest.param("tutorial009_an_py39"),
+ pytest.param("tutorial009_an_py310", marks=needs_py310),
+ ],
+)
+def get_client(request: pytest.FixtureRequest):
+ mod = importlib.import_module(
+ f"docs_src.query_params_str_validations.{request.param}"
+ )
+
+ client = TestClient(mod.app)
+ return client
+
+
+def test_query_params_str_validations_no_query(client: TestClient):
+ response = client.get("/items/")
+ assert response.status_code == 200
+ assert response.json() == {"items": [{"item_id": "Foo"}, {"item_id": "Bar"}]}
+
+
+def test_query_params_str_validations_item_query_fixedquery(client: TestClient):
+ response = client.get("/items/", params={"item-query": "fixedquery"})
+ assert response.status_code == 200
+ assert response.json() == {
+ "items": [{"item_id": "Foo"}, {"item_id": "Bar"}],
+ "q": "fixedquery",
+ }
+
+
+def test_query_params_str_validations_q_fixedquery(client: TestClient):
+ response = client.get("/items/", params={"q": "fixedquery"})
+ assert response.status_code == 200
+ assert response.json() == {"items": [{"item_id": "Foo"}, {"item_id": "Bar"}]}
+
+
+def test_openapi_schema(client: TestClient):
+ response = client.get("/openapi.json")
+ assert response.status_code == 200, response.text
+ assert response.json() == {
+ "openapi": "3.1.0",
+ "info": {"title": "FastAPI", "version": "0.1.0"},
+ "paths": {
+ "/items/": {
+ "get": {
+ "responses": {
+ "200": {
+ "description": "Successful Response",
+ "content": {"application/json": {"schema": {}}},
+ },
+ "422": {
+ "description": "Validation Error",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/HTTPValidationError"
+ }
+ }
+ },
+ },
+ },
+ "summary": "Read Items",
+ "operationId": "read_items_items__get",
+ "parameters": [
+ {
+ "schema": {
+ "anyOf": [
+ {"type": "string"},
+ {"type": "null"},
+ ],
+ "title": "Item-Query",
+ },
+ "required": False,
+ "name": "item-query",
+ "in": "query",
+ }
+ ],
+ }
+ }
+ },
+ "components": {
+ "schemas": {
+ "ValidationError": {
+ "title": "ValidationError",
+ "required": ["loc", "msg", "type"],
+ "type": "object",
+ "properties": {
+ "loc": {
+ "title": "Location",
+ "type": "array",
+ "items": {
+ "anyOf": [{"type": "string"}, {"type": "integer"}]
+ },
+ },
+ "msg": {"title": "Message", "type": "string"},
+ "type": {"title": "Error Type", "type": "string"},
+ },
+ },
+ "HTTPValidationError": {
+ "title": "HTTPValidationError",
+ "type": "object",
+ "properties": {
+ "detail": {
+ "title": "Detail",
+ "type": "array",
+ "items": {"$ref": "#/components/schemas/ValidationError"},
+ }
+ },
+ },
+ }
+ },
+ }
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 e08e169633..00889c5bf7 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,20 +1,18 @@
import importlib
import pytest
-from dirty_equals import IsDict
from fastapi._compat import PYDANTIC_VERSION_MINOR_TUPLE
from fastapi.testclient import TestClient
-from ...utils import needs_py39, needs_py310
+from ...utils import needs_py310
@pytest.fixture(
name="client",
params=[
- "tutorial010",
+ pytest.param("tutorial010_py39"),
pytest.param("tutorial010_py310", marks=needs_py310),
- "tutorial010_an",
- pytest.param("tutorial010_an_py39", marks=needs_py39),
+ pytest.param("tutorial010_an_py39"),
pytest.param("tutorial010_an_py310", marks=needs_py310),
],
)
@@ -51,31 +49,17 @@ def test_query_params_str_validations_q_fixedquery(client: TestClient):
def test_query_params_str_validations_item_query_nonregexquery(client: TestClient):
response = client.get("/items/", params={"item-query": "nonregexquery"})
assert response.status_code == 422
- assert response.json() == IsDict(
- {
- "detail": [
- {
- "type": "string_pattern_mismatch",
- "loc": ["query", "item-query"],
- "msg": "String should match pattern '^fixedquery$'",
- "input": "nonregexquery",
- "ctx": {"pattern": "^fixedquery$"},
- }
- ]
- }
- ) | IsDict(
- # TODO: remove when deprecating Pydantic v1
- {
- "detail": [
- {
- "ctx": {"pattern": "^fixedquery$"},
- "loc": ["query", "item-query"],
- "msg": 'string does not match regex "^fixedquery$"',
- "type": "value_error.str.regex",
- }
- ]
- }
- )
+ assert response.json() == {
+ "detail": [
+ {
+ "type": "string_pattern_mismatch",
+ "loc": ["query", "item-query"],
+ "msg": "String should match pattern '^fixedquery$'",
+ "input": "nonregexquery",
+ "ctx": {"pattern": "^fixedquery$"},
+ }
+ ]
+ }
def test_openapi_schema(client: TestClient):
@@ -110,38 +94,25 @@ def test_openapi_schema(client: TestClient):
"description": "Query string for the items to search in the database that have a good match",
"required": False,
"deprecated": True,
- "schema": IsDict(
- {
- "anyOf": [
- {
- "type": "string",
- "minLength": 3,
- "maxLength": 50,
- "pattern": "^fixedquery$",
- },
- {"type": "null"},
- ],
- "title": "Query string",
- "description": "Query string for the items to search in the database that have a good match",
- # See https://github.com/pydantic/pydantic/blob/80353c29a824c55dea4667b328ba8f329879ac9f/tests/test_fastapi.sh#L25-L34.
- **(
- {"deprecated": True}
- if PYDANTIC_VERSION_MINOR_TUPLE >= (2, 10)
- else {}
- ),
- }
- )
- | IsDict(
- # TODO: remove when deprecating Pydantic v1
- {
- "title": "Query string",
- "maxLength": 50,
- "minLength": 3,
- "pattern": "^fixedquery$",
- "type": "string",
- "description": "Query string for the items to search in the database that have a good match",
- }
- ),
+ "schema": {
+ "anyOf": [
+ {
+ "type": "string",
+ "minLength": 3,
+ "maxLength": 50,
+ "pattern": "^fixedquery$",
+ },
+ {"type": "null"},
+ ],
+ "title": "Query string",
+ "description": "Query string for the items to search in the database that have a good match",
+ # See https://github.com/pydantic/pydantic/blob/80353c29a824c55dea4667b328ba8f329879ac9f/tests/test_fastapi.sh#L25-L34.
+ **(
+ {"deprecated": True}
+ if PYDANTIC_VERSION_MINOR_TUPLE >= (2, 10)
+ else {}
+ ),
+ },
"name": "item-query",
"in": "query",
}
diff --git a/tests/test_tutorial/test_query_params_str_validations/test_tutorial011.py b/tests/test_tutorial/test_query_params_str_validations/test_tutorial011.py
index f4da25752b..11de33ae14 100644
--- a/tests/test_tutorial/test_query_params_str_validations/test_tutorial011.py
+++ b/tests/test_tutorial/test_query_params_str_validations/test_tutorial011.py
@@ -1,20 +1,17 @@
import importlib
import pytest
-from dirty_equals import IsDict
from fastapi.testclient import TestClient
-from ...utils import needs_py39, needs_py310
+from ...utils import needs_py310
@pytest.fixture(
name="client",
params=[
- "tutorial011",
- pytest.param("tutorial011_py39", marks=needs_py310),
+ pytest.param("tutorial011_py39"),
pytest.param("tutorial011_py310", marks=needs_py310),
- "tutorial011_an",
- pytest.param("tutorial011_an_py39", marks=needs_py39),
+ pytest.param("tutorial011_an_py39"),
pytest.param("tutorial011_an_py310", marks=needs_py310),
],
)
@@ -71,23 +68,13 @@ def test_openapi_schema(client: TestClient):
"parameters": [
{
"required": False,
- "schema": IsDict(
- {
- "anyOf": [
- {"type": "array", "items": {"type": "string"}},
- {"type": "null"},
- ],
- "title": "Q",
- }
- )
- | IsDict(
- # TODO: remove when deprecating Pydantic v1
- {
- "title": "Q",
- "type": "array",
- "items": {"type": "string"},
- }
- ),
+ "schema": {
+ "anyOf": [
+ {"type": "array", "items": {"type": "string"}},
+ {"type": "null"},
+ ],
+ "title": "Q",
+ },
"name": "q",
"in": "query",
}
diff --git a/tests/test_tutorial/test_query_params_str_validations/test_tutorial012.py b/tests/test_tutorial/test_query_params_str_validations/test_tutorial012.py
index 549a90519e..1826928611 100644
--- a/tests/test_tutorial/test_query_params_str_validations/test_tutorial012.py
+++ b/tests/test_tutorial/test_query_params_str_validations/test_tutorial012.py
@@ -3,16 +3,12 @@ import importlib
import pytest
from fastapi.testclient import TestClient
-from ...utils import needs_py39
-
@pytest.fixture(
name="client",
params=[
- "tutorial012",
- pytest.param("tutorial012_py39", marks=needs_py39),
- "tutorial012_an",
- pytest.param("tutorial012_an_py39", marks=needs_py39),
+ pytest.param("tutorial012_py39"),
+ pytest.param("tutorial012_an_py39"),
],
)
def get_client(request: pytest.FixtureRequest):
diff --git a/tests/test_tutorial/test_query_params_str_validations/test_tutorial013.py b/tests/test_tutorial/test_query_params_str_validations/test_tutorial013.py
index f2f5f7a858..46c367c86b 100644
--- a/tests/test_tutorial/test_query_params_str_validations/test_tutorial013.py
+++ b/tests/test_tutorial/test_query_params_str_validations/test_tutorial013.py
@@ -3,15 +3,12 @@ import importlib
import pytest
from fastapi.testclient import TestClient
-from ...utils import needs_py39
-
@pytest.fixture(
name="client",
params=[
- "tutorial013",
- "tutorial013_an",
- pytest.param("tutorial013_an_py39", marks=needs_py39),
+ "tutorial013_py39",
+ "tutorial013_an_py39",
],
)
def get_client(request: pytest.FixtureRequest):
diff --git a/tests/test_tutorial/test_query_params_str_validations/test_tutorial014.py b/tests/test_tutorial/test_query_params_str_validations/test_tutorial014.py
index edd40bb1ab..0feaccfa44 100644
--- a/tests/test_tutorial/test_query_params_str_validations/test_tutorial014.py
+++ b/tests/test_tutorial/test_query_params_str_validations/test_tutorial014.py
@@ -3,16 +3,15 @@ import importlib
import pytest
from fastapi.testclient import TestClient
-from ...utils import needs_py39, needs_py310
+from ...utils import needs_py310
@pytest.fixture(
name="client",
params=[
- "tutorial014",
+ pytest.param("tutorial014_py39"),
pytest.param("tutorial014_py310", marks=needs_py310),
- "tutorial014_an",
- pytest.param("tutorial014_an_py39", marks=needs_py39),
+ pytest.param("tutorial014_an_py39"),
pytest.param("tutorial014_an_py310", marks=needs_py310),
],
)
diff --git a/tests/test_tutorial/test_query_params_str_validations/test_tutorial015.py b/tests/test_tutorial/test_query_params_str_validations/test_tutorial015.py
index ae1c40286d..82bb606a9b 100644
--- a/tests/test_tutorial/test_query_params_str_validations/test_tutorial015.py
+++ b/tests/test_tutorial/test_query_params_str_validations/test_tutorial015.py
@@ -5,15 +5,14 @@ from dirty_equals import IsStr
from fastapi.testclient import TestClient
from inline_snapshot import snapshot
-from ...utils import needs_py39, needs_py310, needs_pydanticv2
+from ...utils import needs_py310
@pytest.fixture(
name="client",
params=[
- pytest.param("tutorial015_an", marks=needs_pydanticv2),
- pytest.param("tutorial015_an_py310", marks=(needs_py310, needs_pydanticv2)),
- pytest.param("tutorial015_an_py39", marks=(needs_py39, needs_pydanticv2)),
+ pytest.param("tutorial015_an_py39"),
+ pytest.param("tutorial015_an_py310", marks=[needs_py310]),
],
)
def get_client(request: pytest.FixtureRequest):
diff --git a/tests/test_tutorial/test_request_files/test_tutorial001.py b/tests/test_tutorial/test_request_files/test_tutorial001.py
index b069199612..e0e1bbe639 100644
--- a/tests/test_tutorial/test_request_files/test_tutorial001.py
+++ b/tests/test_tutorial/test_request_files/test_tutorial001.py
@@ -1,18 +1,14 @@
import importlib
import pytest
-from dirty_equals import IsDict
from fastapi.testclient import TestClient
-from ...utils import needs_py39
-
@pytest.fixture(
name="client",
params=[
- "tutorial001",
- "tutorial001_an",
- pytest.param("tutorial001_an_py39", marks=needs_py39),
+ "tutorial001_py39",
+ "tutorial001_an_py39",
],
)
def get_client(request: pytest.FixtureRequest):
@@ -25,57 +21,31 @@ def get_client(request: pytest.FixtureRequest):
def test_post_form_no_body(client: TestClient):
response = client.post("/files/")
assert response.status_code == 422, response.text
- assert response.json() == IsDict(
- {
- "detail": [
- {
- "type": "missing",
- "loc": ["body", "file"],
- "msg": "Field required",
- "input": None,
- }
- ]
- }
- ) | IsDict(
- # TODO: remove when deprecating Pydantic v1
- {
- "detail": [
- {
- "loc": ["body", "file"],
- "msg": "field required",
- "type": "value_error.missing",
- }
- ]
- }
- )
+ assert response.json() == {
+ "detail": [
+ {
+ "type": "missing",
+ "loc": ["body", "file"],
+ "msg": "Field required",
+ "input": None,
+ }
+ ]
+ }
def test_post_body_json(client: TestClient):
response = client.post("/files/", json={"file": "Foo"})
assert response.status_code == 422, response.text
- assert response.json() == IsDict(
- {
- "detail": [
- {
- "type": "missing",
- "loc": ["body", "file"],
- "msg": "Field required",
- "input": None,
- }
- ]
- }
- ) | IsDict(
- # TODO: remove when deprecating Pydantic v1
- {
- "detail": [
- {
- "loc": ["body", "file"],
- "msg": "field required",
- "type": "value_error.missing",
- }
- ]
- }
- )
+ assert response.json() == {
+ "detail": [
+ {
+ "type": "missing",
+ "loc": ["body", "file"],
+ "msg": "Field required",
+ "input": None,
+ }
+ ]
+ }
def test_post_file(tmp_path, client: TestClient):
diff --git a/tests/test_tutorial/test_request_files/test_tutorial001_02.py b/tests/test_tutorial/test_request_files/test_tutorial001_02.py
index 9075a17561..18948c5444 100644
--- a/tests/test_tutorial/test_request_files/test_tutorial001_02.py
+++ b/tests/test_tutorial/test_request_files/test_tutorial001_02.py
@@ -2,19 +2,18 @@ import importlib
from pathlib import Path
import pytest
-from dirty_equals import IsDict
from fastapi.testclient import TestClient
+from inline_snapshot import snapshot
-from ...utils import needs_py39, needs_py310
+from ...utils import needs_py310
@pytest.fixture(
name="client",
params=[
- "tutorial001_02",
+ pytest.param("tutorial001_02_py39"),
pytest.param("tutorial001_02_py310", marks=needs_py310),
- "tutorial001_02_an",
- pytest.param("tutorial001_02_an_py39", marks=needs_py39),
+ pytest.param("tutorial001_02_an_py39"),
pytest.param("tutorial001_02_an_py310", marks=needs_py310),
],
)
@@ -60,166 +59,132 @@ def test_post_upload_file(tmp_path: Path, client: TestClient):
def test_openapi_schema(client: TestClient):
response = client.get("/openapi.json")
assert response.status_code == 200, response.text
- assert response.json() == {
- "openapi": "3.1.0",
- "info": {"title": "FastAPI", "version": "0.1.0"},
- "paths": {
- "/files/": {
- "post": {
- "summary": "Create File",
- "operationId": "create_file_files__post",
- "requestBody": {
- "content": {
- "multipart/form-data": {
- "schema": IsDict(
- {
- "allOf": [
- {
- "$ref": "#/components/schemas/Body_create_file_files__post"
- }
- ],
- "title": "Body",
- }
- )
- | IsDict(
- # TODO: remove when deprecating Pydantic v1
- {
+ assert response.json() == snapshot(
+ {
+ "openapi": "3.1.0",
+ "info": {"title": "FastAPI", "version": "0.1.0"},
+ "paths": {
+ "/files/": {
+ "post": {
+ "summary": "Create File",
+ "operationId": "create_file_files__post",
+ "requestBody": {
+ "content": {
+ "multipart/form-data": {
+ "schema": {
"$ref": "#/components/schemas/Body_create_file_files__post"
}
- )
- }
- }
- },
- "responses": {
- "200": {
- "description": "Successful Response",
- "content": {"application/json": {"schema": {}}},
- },
- "422": {
- "description": "Validation Error",
- "content": {
- "application/json": {
- "schema": {
- "$ref": "#/components/schemas/HTTPValidationError"
- }
}
+ }
+ },
+ "responses": {
+ "200": {
+ "description": "Successful Response",
+ "content": {"application/json": {"schema": {}}},
+ },
+ "422": {
+ "description": "Validation Error",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/HTTPValidationError"
+ }
+ }
+ },
},
},
- },
- }
- },
- "/uploadfile/": {
- "post": {
- "summary": "Create Upload File",
- "operationId": "create_upload_file_uploadfile__post",
- "requestBody": {
- "content": {
- "multipart/form-data": {
- "schema": IsDict(
- {
- "allOf": [
- {
- "$ref": "#/components/schemas/Body_create_upload_file_uploadfile__post"
- }
- ],
- "title": "Body",
- }
- )
- | IsDict(
- # TODO: remove when deprecating Pydantic v1
- {
+ }
+ },
+ "/uploadfile/": {
+ "post": {
+ "summary": "Create Upload File",
+ "operationId": "create_upload_file_uploadfile__post",
+ "requestBody": {
+ "content": {
+ "multipart/form-data": {
+ "schema": {
"$ref": "#/components/schemas/Body_create_upload_file_uploadfile__post"
}
- )
- }
- }
- },
- "responses": {
- "200": {
- "description": "Successful Response",
- "content": {"application/json": {"schema": {}}},
- },
- "422": {
- "description": "Validation Error",
- "content": {
- "application/json": {
- "schema": {
- "$ref": "#/components/schemas/HTTPValidationError"
- }
}
+ }
+ },
+ "responses": {
+ "200": {
+ "description": "Successful Response",
+ "content": {"application/json": {"schema": {}}},
},
+ "422": {
+ "description": "Validation Error",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/HTTPValidationError"
+ }
+ }
+ },
+ },
+ },
+ }
+ },
+ },
+ "components": {
+ "schemas": {
+ "Body_create_file_files__post": {
+ "title": "Body_create_file_files__post",
+ "type": "object",
+ "properties": {
+ "file": {
+ "title": "File",
+ "anyOf": [
+ {"type": "string", "format": "binary"},
+ {"type": "null"},
+ ],
+ }
+ },
+ },
+ "Body_create_upload_file_uploadfile__post": {
+ "title": "Body_create_upload_file_uploadfile__post",
+ "type": "object",
+ "properties": {
+ "file": {
+ "title": "File",
+ "anyOf": [
+ {"type": "string", "format": "binary"},
+ {"type": "null"},
+ ],
+ }
+ },
+ },
+ "HTTPValidationError": {
+ "title": "HTTPValidationError",
+ "type": "object",
+ "properties": {
+ "detail": {
+ "title": "Detail",
+ "type": "array",
+ "items": {
+ "$ref": "#/components/schemas/ValidationError"
+ },
+ }
+ },
+ },
+ "ValidationError": {
+ "title": "ValidationError",
+ "required": ["loc", "msg", "type"],
+ "type": "object",
+ "properties": {
+ "loc": {
+ "title": "Location",
+ "type": "array",
+ "items": {
+ "anyOf": [{"type": "string"}, {"type": "integer"}]
+ },
+ },
+ "msg": {"title": "Message", "type": "string"},
+ "type": {"title": "Error Type", "type": "string"},
},
},
}
},
- },
- "components": {
- "schemas": {
- "Body_create_file_files__post": {
- "title": "Body_create_file_files__post",
- "type": "object",
- "properties": {
- "file": IsDict(
- {
- "title": "File",
- "anyOf": [
- {"type": "string", "format": "binary"},
- {"type": "null"},
- ],
- }
- )
- | IsDict(
- # TODO: remove when deprecating Pydantic v1
- {"title": "File", "type": "string", "format": "binary"}
- )
- },
- },
- "Body_create_upload_file_uploadfile__post": {
- "title": "Body_create_upload_file_uploadfile__post",
- "type": "object",
- "properties": {
- "file": IsDict(
- {
- "title": "File",
- "anyOf": [
- {"type": "string", "format": "binary"},
- {"type": "null"},
- ],
- }
- )
- | IsDict(
- # TODO: remove when deprecating Pydantic v1
- {"title": "File", "type": "string", "format": "binary"}
- )
- },
- },
- "HTTPValidationError": {
- "title": "HTTPValidationError",
- "type": "object",
- "properties": {
- "detail": {
- "title": "Detail",
- "type": "array",
- "items": {"$ref": "#/components/schemas/ValidationError"},
- }
- },
- },
- "ValidationError": {
- "title": "ValidationError",
- "required": ["loc", "msg", "type"],
- "type": "object",
- "properties": {
- "loc": {
- "title": "Location",
- "type": "array",
- "items": {
- "anyOf": [{"type": "string"}, {"type": "integer"}]
- },
- },
- "msg": {"title": "Message", "type": "string"},
- "type": {"title": "Error Type", "type": "string"},
- },
- },
- }
- },
- }
+ }
+ )
diff --git a/tests/test_tutorial/test_request_files/test_tutorial001_03.py b/tests/test_tutorial/test_request_files/test_tutorial001_03.py
index 9fbe2166c1..53a7a0cf85 100644
--- a/tests/test_tutorial/test_request_files/test_tutorial001_03.py
+++ b/tests/test_tutorial/test_request_files/test_tutorial001_03.py
@@ -3,15 +3,12 @@ import importlib
import pytest
from fastapi.testclient import TestClient
-from ...utils import needs_py39
-
@pytest.fixture(
name="client",
params=[
- "tutorial001_03",
- "tutorial001_03_an",
- pytest.param("tutorial001_03_an_py39", marks=needs_py39),
+ "tutorial001_03_py39",
+ "tutorial001_03_an_py39",
],
)
def get_client(request: pytest.FixtureRequest):
diff --git a/tests/test_tutorial/test_request_files/test_tutorial002.py b/tests/test_tutorial/test_request_files/test_tutorial002.py
index 446a876578..03772419ad 100644
--- a/tests/test_tutorial/test_request_files/test_tutorial002.py
+++ b/tests/test_tutorial/test_request_files/test_tutorial002.py
@@ -1,20 +1,15 @@
import importlib
import pytest
-from dirty_equals import IsDict
from fastapi import FastAPI
from fastapi.testclient import TestClient
-from ...utils import needs_py39
-
@pytest.fixture(
name="app",
params=[
- "tutorial002",
- "tutorial002_an",
- pytest.param("tutorial002_py39", marks=needs_py39),
- pytest.param("tutorial002_an_py39", marks=needs_py39),
+ "tutorial002_py39",
+ "tutorial002_an_py39",
],
)
def get_app(request: pytest.FixtureRequest):
@@ -32,57 +27,31 @@ def get_client(app: FastAPI):
def test_post_form_no_body(client: TestClient):
response = client.post("/files/")
assert response.status_code == 422, response.text
- assert response.json() == IsDict(
- {
- "detail": [
- {
- "type": "missing",
- "loc": ["body", "files"],
- "msg": "Field required",
- "input": None,
- }
- ]
- }
- ) | IsDict(
- # TODO: remove when deprecating Pydantic v1
- {
- "detail": [
- {
- "loc": ["body", "files"],
- "msg": "field required",
- "type": "value_error.missing",
- }
- ]
- }
- )
+ assert response.json() == {
+ "detail": [
+ {
+ "type": "missing",
+ "loc": ["body", "files"],
+ "msg": "Field required",
+ "input": None,
+ }
+ ]
+ }
def test_post_body_json(client: TestClient):
response = client.post("/files/", json={"file": "Foo"})
assert response.status_code == 422, response.text
- assert response.json() == IsDict(
- {
- "detail": [
- {
- "type": "missing",
- "loc": ["body", "files"],
- "msg": "Field required",
- "input": None,
- }
- ]
- }
- ) | IsDict(
- # TODO: remove when deprecating Pydantic v1
- {
- "detail": [
- {
- "loc": ["body", "files"],
- "msg": "field required",
- "type": "value_error.missing",
- }
- ]
- }
- )
+ assert response.json() == {
+ "detail": [
+ {
+ "type": "missing",
+ "loc": ["body", "files"],
+ "msg": "Field required",
+ "input": None,
+ }
+ ]
+ }
def test_post_files(tmp_path, app: FastAPI):
diff --git a/tests/test_tutorial/test_request_files/test_tutorial003.py b/tests/test_tutorial/test_request_files/test_tutorial003.py
index 8534ba3e9a..fa4bfd5695 100644
--- a/tests/test_tutorial/test_request_files/test_tutorial003.py
+++ b/tests/test_tutorial/test_request_files/test_tutorial003.py
@@ -4,16 +4,12 @@ import pytest
from fastapi import FastAPI
from fastapi.testclient import TestClient
-from ...utils import needs_py39
-
@pytest.fixture(
name="app",
params=[
- "tutorial003",
- "tutorial003_an",
- pytest.param("tutorial003_py39", marks=needs_py39),
- pytest.param("tutorial003_an_py39", marks=needs_py39),
+ "tutorial003_py39",
+ "tutorial003_an_py39",
],
)
def get_app(request: pytest.FixtureRequest):
diff --git a/tests/test_tutorial/test_request_form_models/test_tutorial001.py b/tests/test_tutorial/test_request_form_models/test_tutorial001.py
index 1ca3c96d33..0c43dd7b21 100644
--- a/tests/test_tutorial/test_request_form_models/test_tutorial001.py
+++ b/tests/test_tutorial/test_request_form_models/test_tutorial001.py
@@ -1,18 +1,14 @@
import importlib
import pytest
-from dirty_equals import IsDict
from fastapi.testclient import TestClient
-from ...utils import needs_py39
-
@pytest.fixture(
name="client",
params=[
- "tutorial001",
- "tutorial001_an",
- pytest.param("tutorial001_an_py39", marks=needs_py39),
+ "tutorial001_py39",
+ "tutorial001_an_py39",
],
)
def get_client(request: pytest.FixtureRequest):
@@ -31,135 +27,73 @@ def test_post_body_form(client: TestClient):
def test_post_body_form_no_password(client: TestClient):
response = client.post("/login/", data={"username": "Foo"})
assert response.status_code == 422
- assert response.json() == IsDict(
- {
- "detail": [
- {
- "type": "missing",
- "loc": ["body", "password"],
- "msg": "Field required",
- "input": {"username": "Foo"},
- }
- ]
- }
- ) | IsDict(
- # TODO: remove when deprecating Pydantic v1
- {
- "detail": [
- {
- "loc": ["body", "password"],
- "msg": "field required",
- "type": "value_error.missing",
- }
- ]
- }
- )
+ assert response.json() == {
+ "detail": [
+ {
+ "type": "missing",
+ "loc": ["body", "password"],
+ "msg": "Field required",
+ "input": {"username": "Foo"},
+ }
+ ]
+ }
def test_post_body_form_no_username(client: TestClient):
response = client.post("/login/", data={"password": "secret"})
assert response.status_code == 422
- assert response.json() == IsDict(
- {
- "detail": [
- {
- "type": "missing",
- "loc": ["body", "username"],
- "msg": "Field required",
- "input": {"password": "secret"},
- }
- ]
- }
- ) | IsDict(
- # TODO: remove when deprecating Pydantic v1
- {
- "detail": [
- {
- "loc": ["body", "username"],
- "msg": "field required",
- "type": "value_error.missing",
- }
- ]
- }
- )
+ assert response.json() == {
+ "detail": [
+ {
+ "type": "missing",
+ "loc": ["body", "username"],
+ "msg": "Field required",
+ "input": {"password": "secret"},
+ }
+ ]
+ }
def test_post_body_form_no_data(client: TestClient):
response = client.post("/login/")
assert response.status_code == 422
- assert response.json() == IsDict(
- {
- "detail": [
- {
- "type": "missing",
- "loc": ["body", "username"],
- "msg": "Field required",
- "input": {},
- },
- {
- "type": "missing",
- "loc": ["body", "password"],
- "msg": "Field required",
- "input": {},
- },
- ]
- }
- ) | IsDict(
- # TODO: remove when deprecating Pydantic v1
- {
- "detail": [
- {
- "loc": ["body", "username"],
- "msg": "field required",
- "type": "value_error.missing",
- },
- {
- "loc": ["body", "password"],
- "msg": "field required",
- "type": "value_error.missing",
- },
- ]
- }
- )
+ assert response.json() == {
+ "detail": [
+ {
+ "type": "missing",
+ "loc": ["body", "username"],
+ "msg": "Field required",
+ "input": {},
+ },
+ {
+ "type": "missing",
+ "loc": ["body", "password"],
+ "msg": "Field required",
+ "input": {},
+ },
+ ]
+ }
def test_post_body_json(client: TestClient):
response = client.post("/login/", json={"username": "Foo", "password": "secret"})
assert response.status_code == 422, response.text
- assert response.json() == IsDict(
- {
- "detail": [
- {
- "type": "missing",
- "loc": ["body", "username"],
- "msg": "Field required",
- "input": {},
- },
- {
- "type": "missing",
- "loc": ["body", "password"],
- "msg": "Field required",
- "input": {},
- },
- ]
- }
- ) | IsDict(
- # TODO: remove when deprecating Pydantic v1
- {
- "detail": [
- {
- "loc": ["body", "username"],
- "msg": "field required",
- "type": "value_error.missing",
- },
- {
- "loc": ["body", "password"],
- "msg": "field required",
- "type": "value_error.missing",
- },
- ]
- }
- )
+ assert response.json() == {
+ "detail": [
+ {
+ "type": "missing",
+ "loc": ["body", "username"],
+ "msg": "Field required",
+ "input": {},
+ },
+ {
+ "type": "missing",
+ "loc": ["body", "password"],
+ "msg": "Field required",
+ "input": {},
+ },
+ ]
+ }
def test_openapi_schema(client: TestClient):
diff --git a/tests/test_tutorial/test_request_form_models/test_tutorial002.py b/tests/test_tutorial/test_request_form_models/test_tutorial002.py
index b3f6be63ab..238f8fa2ef 100644
--- a/tests/test_tutorial/test_request_form_models/test_tutorial002.py
+++ b/tests/test_tutorial/test_request_form_models/test_tutorial002.py
@@ -3,15 +3,12 @@ import importlib
import pytest
from fastapi.testclient import TestClient
-from ...utils import needs_py39, needs_pydanticv2
-
@pytest.fixture(
name="client",
params=[
- "tutorial002",
- "tutorial002_an",
- pytest.param("tutorial002_an_py39", marks=needs_py39),
+ "tutorial002_py39",
+ "tutorial002_an_py39",
],
)
def get_client(request: pytest.FixtureRequest):
@@ -21,14 +18,12 @@ def get_client(request: pytest.FixtureRequest):
return client
-@needs_pydanticv2
def test_post_body_form(client: TestClient):
response = client.post("/login/", data={"username": "Foo", "password": "secret"})
assert response.status_code == 200
assert response.json() == {"username": "Foo", "password": "secret"}
-@needs_pydanticv2
def test_post_body_extra_form(client: TestClient):
response = client.post(
"/login/", data={"username": "Foo", "password": "secret", "extra": "extra"}
@@ -46,7 +41,6 @@ def test_post_body_extra_form(client: TestClient):
}
-@needs_pydanticv2
def test_post_body_form_no_password(client: TestClient):
response = client.post("/login/", data={"username": "Foo"})
assert response.status_code == 422
@@ -62,7 +56,6 @@ def test_post_body_form_no_password(client: TestClient):
}
-@needs_pydanticv2
def test_post_body_form_no_username(client: TestClient):
response = client.post("/login/", data={"password": "secret"})
assert response.status_code == 422
@@ -78,7 +71,6 @@ def test_post_body_form_no_username(client: TestClient):
}
-@needs_pydanticv2
def test_post_body_form_no_data(client: TestClient):
response = client.post("/login/")
assert response.status_code == 422
@@ -100,7 +92,6 @@ def test_post_body_form_no_data(client: TestClient):
}
-@needs_pydanticv2
def test_post_body_json(client: TestClient):
response = client.post("/login/", json={"username": "Foo", "password": "secret"})
assert response.status_code == 422, response.text
@@ -122,7 +113,6 @@ def test_post_body_json(client: TestClient):
}
-@needs_pydanticv2
def test_openapi_schema(client: TestClient):
response = client.get("/openapi.json")
assert response.status_code == 200, response.text
diff --git a/tests/test_tutorial/test_request_form_models/test_tutorial002_pv1.py b/tests/test_tutorial/test_request_form_models/test_tutorial002_pv1.py
deleted file mode 100644
index b503f23a53..0000000000
--- a/tests/test_tutorial/test_request_form_models/test_tutorial002_pv1.py
+++ /dev/null
@@ -1,205 +0,0 @@
-import importlib
-
-import pytest
-from fastapi.testclient import TestClient
-
-from ...utils import needs_py39, needs_pydanticv1
-
-
-@pytest.fixture(
- name="client",
- params=[
- "tutorial002_pv1",
- "tutorial002_pv1_an",
- pytest.param("tutorial002_pv1_an_py39", marks=needs_py39),
- ],
-)
-def get_client(request: pytest.FixtureRequest):
- mod = importlib.import_module(f"docs_src.request_form_models.{request.param}")
-
- client = TestClient(mod.app)
- return client
-
-
-# TODO: remove when deprecating Pydantic v1
-@needs_pydanticv1
-def test_post_body_form(client: TestClient):
- response = client.post("/login/", data={"username": "Foo", "password": "secret"})
- assert response.status_code == 200
- assert response.json() == {"username": "Foo", "password": "secret"}
-
-
-# TODO: remove when deprecating Pydantic v1
-@needs_pydanticv1
-def test_post_body_extra_form(client: TestClient):
- response = client.post(
- "/login/", data={"username": "Foo", "password": "secret", "extra": "extra"}
- )
- assert response.status_code == 422
- assert response.json() == {
- "detail": [
- {
- "type": "value_error.extra",
- "loc": ["body", "extra"],
- "msg": "extra fields not permitted",
- }
- ]
- }
-
-
-# TODO: remove when deprecating Pydantic v1
-@needs_pydanticv1
-def test_post_body_form_no_password(client: TestClient):
- response = client.post("/login/", data={"username": "Foo"})
- assert response.status_code == 422
- assert response.json() == {
- "detail": [
- {
- "type": "value_error.missing",
- "loc": ["body", "password"],
- "msg": "field required",
- }
- ]
- }
-
-
-# TODO: remove when deprecating Pydantic v1
-@needs_pydanticv1
-def test_post_body_form_no_username(client: TestClient):
- response = client.post("/login/", data={"password": "secret"})
- assert response.status_code == 422
- assert response.json() == {
- "detail": [
- {
- "type": "value_error.missing",
- "loc": ["body", "username"],
- "msg": "field required",
- }
- ]
- }
-
-
-# TODO: remove when deprecating Pydantic v1
-@needs_pydanticv1
-def test_post_body_form_no_data(client: TestClient):
- response = client.post("/login/")
- assert response.status_code == 422
- assert response.json() == {
- "detail": [
- {
- "type": "value_error.missing",
- "loc": ["body", "username"],
- "msg": "field required",
- },
- {
- "type": "value_error.missing",
- "loc": ["body", "password"],
- "msg": "field required",
- },
- ]
- }
-
-
-# TODO: remove when deprecating Pydantic v1
-@needs_pydanticv1
-def test_post_body_json(client: TestClient):
- response = client.post("/login/", json={"username": "Foo", "password": "secret"})
- assert response.status_code == 422, response.text
- assert response.json() == {
- "detail": [
- {
- "type": "value_error.missing",
- "loc": ["body", "username"],
- "msg": "field required",
- },
- {
- "type": "value_error.missing",
- "loc": ["body", "password"],
- "msg": "field required",
- },
- ]
- }
-
-
-# TODO: remove when deprecating Pydantic v1
-@needs_pydanticv1
-def test_openapi_schema(client: TestClient):
- response = client.get("/openapi.json")
- assert response.status_code == 200, response.text
- assert response.json() == {
- "openapi": "3.1.0",
- "info": {"title": "FastAPI", "version": "0.1.0"},
- "paths": {
- "/login/": {
- "post": {
- "responses": {
- "200": {
- "description": "Successful Response",
- "content": {"application/json": {"schema": {}}},
- },
- "422": {
- "description": "Validation Error",
- "content": {
- "application/json": {
- "schema": {
- "$ref": "#/components/schemas/HTTPValidationError"
- }
- }
- },
- },
- },
- "summary": "Login",
- "operationId": "login_login__post",
- "requestBody": {
- "content": {
- "application/x-www-form-urlencoded": {
- "schema": {"$ref": "#/components/schemas/FormData"}
- }
- },
- "required": True,
- },
- }
- }
- },
- "components": {
- "schemas": {
- "FormData": {
- "properties": {
- "username": {"type": "string", "title": "Username"},
- "password": {"type": "string", "title": "Password"},
- },
- "additionalProperties": False,
- "type": "object",
- "required": ["username", "password"],
- "title": "FormData",
- },
- "ValidationError": {
- "title": "ValidationError",
- "required": ["loc", "msg", "type"],
- "type": "object",
- "properties": {
- "loc": {
- "title": "Location",
- "type": "array",
- "items": {
- "anyOf": [{"type": "string"}, {"type": "integer"}]
- },
- },
- "msg": {"title": "Message", "type": "string"},
- "type": {"title": "Error Type", "type": "string"},
- },
- },
- "HTTPValidationError": {
- "title": "HTTPValidationError",
- "type": "object",
- "properties": {
- "detail": {
- "title": "Detail",
- "type": "array",
- "items": {"$ref": "#/components/schemas/ValidationError"},
- }
- },
- },
- }
- },
- }
diff --git a/tests/test_tutorial/test_request_forms/test_tutorial001.py b/tests/test_tutorial/test_request_forms/test_tutorial001.py
index 321f8022b7..4276414fc2 100644
--- a/tests/test_tutorial/test_request_forms/test_tutorial001.py
+++ b/tests/test_tutorial/test_request_forms/test_tutorial001.py
@@ -1,18 +1,14 @@
import importlib
import pytest
-from dirty_equals import IsDict
from fastapi.testclient import TestClient
-from ...utils import needs_py39
-
@pytest.fixture(
name="client",
params=[
- "tutorial001",
- "tutorial001_an",
- pytest.param("tutorial001_an_py39", marks=needs_py39),
+ "tutorial001_py39",
+ "tutorial001_an_py39",
],
)
def get_client(request: pytest.FixtureRequest):
@@ -31,135 +27,73 @@ def test_post_body_form(client: TestClient):
def test_post_body_form_no_password(client: TestClient):
response = client.post("/login/", data={"username": "Foo"})
assert response.status_code == 422
- assert response.json() == IsDict(
- {
- "detail": [
- {
- "type": "missing",
- "loc": ["body", "password"],
- "msg": "Field required",
- "input": None,
- }
- ]
- }
- ) | IsDict(
- # TODO: remove when deprecating Pydantic v1
- {
- "detail": [
- {
- "loc": ["body", "password"],
- "msg": "field required",
- "type": "value_error.missing",
- }
- ]
- }
- )
+ assert response.json() == {
+ "detail": [
+ {
+ "type": "missing",
+ "loc": ["body", "password"],
+ "msg": "Field required",
+ "input": None,
+ }
+ ]
+ }
def test_post_body_form_no_username(client: TestClient):
response = client.post("/login/", data={"password": "secret"})
assert response.status_code == 422
- assert response.json() == IsDict(
- {
- "detail": [
- {
- "type": "missing",
- "loc": ["body", "username"],
- "msg": "Field required",
- "input": None,
- }
- ]
- }
- ) | IsDict(
- # TODO: remove when deprecating Pydantic v1
- {
- "detail": [
- {
- "loc": ["body", "username"],
- "msg": "field required",
- "type": "value_error.missing",
- }
- ]
- }
- )
+ assert response.json() == {
+ "detail": [
+ {
+ "type": "missing",
+ "loc": ["body", "username"],
+ "msg": "Field required",
+ "input": None,
+ }
+ ]
+ }
def test_post_body_form_no_data(client: TestClient):
response = client.post("/login/")
assert response.status_code == 422
- assert response.json() == IsDict(
- {
- "detail": [
- {
- "type": "missing",
- "loc": ["body", "username"],
- "msg": "Field required",
- "input": None,
- },
- {
- "type": "missing",
- "loc": ["body", "password"],
- "msg": "Field required",
- "input": None,
- },
- ]
- }
- ) | IsDict(
- # TODO: remove when deprecating Pydantic v1
- {
- "detail": [
- {
- "loc": ["body", "username"],
- "msg": "field required",
- "type": "value_error.missing",
- },
- {
- "loc": ["body", "password"],
- "msg": "field required",
- "type": "value_error.missing",
- },
- ]
- }
- )
+ assert response.json() == {
+ "detail": [
+ {
+ "type": "missing",
+ "loc": ["body", "username"],
+ "msg": "Field required",
+ "input": None,
+ },
+ {
+ "type": "missing",
+ "loc": ["body", "password"],
+ "msg": "Field required",
+ "input": None,
+ },
+ ]
+ }
def test_post_body_json(client: TestClient):
response = client.post("/login/", json={"username": "Foo", "password": "secret"})
assert response.status_code == 422, response.text
- assert response.json() == IsDict(
- {
- "detail": [
- {
- "type": "missing",
- "loc": ["body", "username"],
- "msg": "Field required",
- "input": None,
- },
- {
- "type": "missing",
- "loc": ["body", "password"],
- "msg": "Field required",
- "input": None,
- },
- ]
- }
- ) | IsDict(
- # TODO: remove when deprecating Pydantic v1
- {
- "detail": [
- {
- "loc": ["body", "username"],
- "msg": "field required",
- "type": "value_error.missing",
- },
- {
- "loc": ["body", "password"],
- "msg": "field required",
- "type": "value_error.missing",
- },
- ]
- }
- )
+ assert response.json() == {
+ "detail": [
+ {
+ "type": "missing",
+ "loc": ["body", "username"],
+ "msg": "Field required",
+ "input": None,
+ },
+ {
+ "type": "missing",
+ "loc": ["body", "password"],
+ "msg": "Field required",
+ "input": None,
+ },
+ ]
+ }
def test_openapi_schema(client: TestClient):
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 d12219245e..7fa4c3de57 100644
--- a/tests/test_tutorial/test_request_forms_and_files/test_tutorial001.py
+++ b/tests/test_tutorial/test_request_forms_and_files/test_tutorial001.py
@@ -1,19 +1,15 @@
import importlib
import pytest
-from dirty_equals import IsDict
from fastapi import FastAPI
from fastapi.testclient import TestClient
-from ...utils import needs_py39
-
@pytest.fixture(
name="app",
params=[
- "tutorial001",
- "tutorial001_an",
- pytest.param("tutorial001_an_py39", marks=needs_py39),
+ "tutorial001_py39",
+ "tutorial001_an_py39",
],
)
def get_app(request: pytest.FixtureRequest):
@@ -31,140 +27,76 @@ def get_client(app: FastAPI):
def test_post_form_no_body(client: TestClient):
response = client.post("/files/")
assert response.status_code == 422, response.text
- assert response.json() == IsDict(
- {
- "detail": [
- {
- "type": "missing",
- "loc": ["body", "file"],
- "msg": "Field required",
- "input": None,
- },
- {
- "type": "missing",
- "loc": ["body", "fileb"],
- "msg": "Field required",
- "input": None,
- },
- {
- "type": "missing",
- "loc": ["body", "token"],
- "msg": "Field required",
- "input": None,
- },
- ]
- }
- ) | IsDict(
- # TODO: remove when deprecating Pydantic v1
- {
- "detail": [
- {
- "loc": ["body", "file"],
- "msg": "field required",
- "type": "value_error.missing",
- },
- {
- "loc": ["body", "fileb"],
- "msg": "field required",
- "type": "value_error.missing",
- },
- {
- "loc": ["body", "token"],
- "msg": "field required",
- "type": "value_error.missing",
- },
- ]
- }
- )
+ assert response.json() == {
+ "detail": [
+ {
+ "type": "missing",
+ "loc": ["body", "file"],
+ "msg": "Field required",
+ "input": None,
+ },
+ {
+ "type": "missing",
+ "loc": ["body", "fileb"],
+ "msg": "Field required",
+ "input": None,
+ },
+ {
+ "type": "missing",
+ "loc": ["body", "token"],
+ "msg": "Field required",
+ "input": None,
+ },
+ ]
+ }
def test_post_form_no_file(client: TestClient):
response = client.post("/files/", data={"token": "foo"})
assert response.status_code == 422, response.text
- assert response.json() == IsDict(
- {
- "detail": [
- {
- "type": "missing",
- "loc": ["body", "file"],
- "msg": "Field required",
- "input": None,
- },
- {
- "type": "missing",
- "loc": ["body", "fileb"],
- "msg": "Field required",
- "input": None,
- },
- ]
- }
- ) | IsDict(
- # TODO: remove when deprecating Pydantic v1
- {
- "detail": [
- {
- "loc": ["body", "file"],
- "msg": "field required",
- "type": "value_error.missing",
- },
- {
- "loc": ["body", "fileb"],
- "msg": "field required",
- "type": "value_error.missing",
- },
- ]
- }
- )
+ assert response.json() == {
+ "detail": [
+ {
+ "type": "missing",
+ "loc": ["body", "file"],
+ "msg": "Field required",
+ "input": None,
+ },
+ {
+ "type": "missing",
+ "loc": ["body", "fileb"],
+ "msg": "Field required",
+ "input": None,
+ },
+ ]
+ }
def test_post_body_json(client: TestClient):
response = client.post("/files/", json={"file": "Foo", "token": "Bar"})
assert response.status_code == 422, response.text
- assert response.json() == IsDict(
- {
- "detail": [
- {
- "type": "missing",
- "loc": ["body", "file"],
- "msg": "Field required",
- "input": None,
- },
- {
- "type": "missing",
- "loc": ["body", "fileb"],
- "msg": "Field required",
- "input": None,
- },
- {
- "type": "missing",
- "loc": ["body", "token"],
- "msg": "Field required",
- "input": None,
- },
- ]
- }
- ) | IsDict(
- # TODO: remove when deprecating Pydantic v1
- {
- "detail": [
- {
- "loc": ["body", "file"],
- "msg": "field required",
- "type": "value_error.missing",
- },
- {
- "loc": ["body", "fileb"],
- "msg": "field required",
- "type": "value_error.missing",
- },
- {
- "loc": ["body", "token"],
- "msg": "field required",
- "type": "value_error.missing",
- },
- ]
- }
- )
+ assert response.json() == {
+ "detail": [
+ {
+ "type": "missing",
+ "loc": ["body", "file"],
+ "msg": "Field required",
+ "input": None,
+ },
+ {
+ "type": "missing",
+ "loc": ["body", "fileb"],
+ "msg": "Field required",
+ "input": None,
+ },
+ {
+ "type": "missing",
+ "loc": ["body", "token"],
+ "msg": "Field required",
+ "input": None,
+ },
+ ]
+ }
def test_post_file_no_token(tmp_path, app: FastAPI):
@@ -175,40 +107,22 @@ def test_post_file_no_token(tmp_path, app: FastAPI):
with path.open("rb") as file:
response = client.post("/files/", files={"file": file})
assert response.status_code == 422, response.text
- assert response.json() == IsDict(
- {
- "detail": [
- {
- "type": "missing",
- "loc": ["body", "fileb"],
- "msg": "Field required",
- "input": None,
- },
- {
- "type": "missing",
- "loc": ["body", "token"],
- "msg": "Field required",
- "input": None,
- },
- ]
- }
- ) | IsDict(
- # TODO: remove when deprecating Pydantic v1
- {
- "detail": [
- {
- "loc": ["body", "fileb"],
- "msg": "field required",
- "type": "value_error.missing",
- },
- {
- "loc": ["body", "token"],
- "msg": "field required",
- "type": "value_error.missing",
- },
- ]
- }
- )
+ assert response.json() == {
+ "detail": [
+ {
+ "type": "missing",
+ "loc": ["body", "fileb"],
+ "msg": "Field required",
+ "input": None,
+ },
+ {
+ "type": "missing",
+ "loc": ["body", "token"],
+ "msg": "Field required",
+ "input": None,
+ },
+ ]
+ }
def test_post_files_and_token(tmp_path, app: FastAPI):
diff --git a/tests/test_tutorial/test_response_change_status_code/test_tutorial001.py b/tests/test_tutorial/test_response_change_status_code/test_tutorial001.py
index 8ce3dcf1ab..05d5ca619f 100644
--- a/tests/test_tutorial/test_response_change_status_code/test_tutorial001.py
+++ b/tests/test_tutorial/test_response_change_status_code/test_tutorial001.py
@@ -1,6 +1,6 @@
from fastapi.testclient import TestClient
-from docs_src.response_change_status_code.tutorial001 import app
+from docs_src.response_change_status_code.tutorial001_py39 import app
client = TestClient(app)
diff --git a/tests/test_tutorial/test_response_cookies/test_tutorial001.py b/tests/test_tutorial/test_response_cookies/test_tutorial001.py
index eecd1a24c9..6b931c8bda 100644
--- a/tests/test_tutorial/test_response_cookies/test_tutorial001.py
+++ b/tests/test_tutorial/test_response_cookies/test_tutorial001.py
@@ -1,6 +1,6 @@
from fastapi.testclient import TestClient
-from docs_src.response_cookies.tutorial001 import app
+from docs_src.response_cookies.tutorial001_py39 import app
client = TestClient(app)
diff --git a/tests/test_tutorial/test_response_cookies/test_tutorial002.py b/tests/test_tutorial/test_response_cookies/test_tutorial002.py
index 3e390025fa..3ee5f500c5 100644
--- a/tests/test_tutorial/test_response_cookies/test_tutorial002.py
+++ b/tests/test_tutorial/test_response_cookies/test_tutorial002.py
@@ -1,6 +1,6 @@
from fastapi.testclient import TestClient
-from docs_src.response_cookies.tutorial002 import app
+from docs_src.response_cookies.tutorial002_py39 import app
client = TestClient(app)
diff --git a/tests/test_tutorial/test_response_directly/test_tutorial001.py b/tests/test_tutorial/test_response_directly/test_tutorial001.py
index 2cc4f3b0c1..2d0c387195 100644
--- a/tests/test_tutorial/test_response_directly/test_tutorial001.py
+++ b/tests/test_tutorial/test_response_directly/test_tutorial001.py
@@ -3,13 +3,13 @@ import importlib
import pytest
from fastapi.testclient import TestClient
-from ...utils import needs_py310, needs_pydanticv1, needs_pydanticv2
+from ...utils import needs_py310
@pytest.fixture(
name="client",
params=[
- pytest.param("tutorial001"),
+ pytest.param("tutorial001_py39"),
pytest.param("tutorial001_py310", marks=needs_py310),
],
)
@@ -37,7 +37,6 @@ def test_path_operation(client: TestClient):
}
-@needs_pydanticv2
def test_openapi_schema_pv2(client: TestClient):
response = client.get("/openapi.json")
assert response.status_code == 200, response.text
@@ -151,138 +150,3 @@ def test_openapi_schema_pv2(client: TestClient):
},
},
}
-
-
-@needs_pydanticv1
-def test_openapi_schema_pv1(client: TestClient):
- 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": {
- "/items/{id}": {
- "put": {
- "operationId": "update_item_items__id__put",
- "parameters": [
- {
- "in": "path",
- "name": "id",
- "required": True,
- "schema": {
- "title": "Id",
- "type": "string",
- },
- },
- ],
- "requestBody": {
- "content": {
- "application/json": {
- "schema": {
- "$ref": "#/components/schemas/Item",
- },
- },
- },
- "required": True,
- },
- "responses": {
- "200": {
- "content": {
- "application/json": {
- "schema": {},
- },
- },
- "description": "Successful Response",
- },
- "422": {
- "content": {
- "application/json": {
- "schema": {
- "$ref": "#/components/schemas/HTTPValidationError",
- },
- },
- },
- "description": "Validation Error",
- },
- },
- "summary": "Update Item",
- },
- },
- },
- "components": {
- "schemas": {
- "HTTPValidationError": {
- "properties": {
- "detail": {
- "items": {
- "$ref": "#/components/schemas/ValidationError",
- },
- "title": "Detail",
- "type": "array",
- },
- },
- "title": "HTTPValidationError",
- "type": "object",
- },
- "Item": {
- "properties": {
- "description": {
- "title": "Description",
- "type": "string",
- },
- "timestamp": {
- "format": "date-time",
- "title": "Timestamp",
- "type": "string",
- },
- "title": {
- "title": "Title",
- "type": "string",
- },
- },
- "required": [
- "title",
- "timestamp",
- ],
- "title": "Item",
- "type": "object",
- },
- "ValidationError": {
- "properties": {
- "loc": {
- "items": {
- "anyOf": [
- {
- "type": "string",
- },
- {
- "type": "integer",
- },
- ],
- },
- "title": "Location",
- "type": "array",
- },
- "msg": {
- "title": "Message",
- "type": "string",
- },
- "type": {
- "title": "Error Type",
- "type": "string",
- },
- },
- "required": [
- "loc",
- "msg",
- "type",
- ],
- "title": "ValidationError",
- "type": "object",
- },
- },
- },
- }
diff --git a/tests/test_tutorial/test_response_directly/test_tutorial002.py b/tests/test_tutorial/test_response_directly/test_tutorial002.py
new file mode 100644
index 0000000000..ef84575723
--- /dev/null
+++ b/tests/test_tutorial/test_response_directly/test_tutorial002.py
@@ -0,0 +1,65 @@
+import importlib
+
+import pytest
+from fastapi.testclient import TestClient
+
+
+@pytest.fixture(
+ name="client",
+ params=[
+ pytest.param("tutorial002_py39"),
+ ],
+)
+def get_client(request: pytest.FixtureRequest):
+ mod = importlib.import_module(f"docs_src.response_directly.{request.param}")
+
+ client = TestClient(mod.app)
+ return client
+
+
+def test_path_operation(client: TestClient):
+ expected_content = """
+
+
+
+ You'll have to use soap here.
+
+
+ """
+
+ response = client.get("/legacy/")
+ assert response.status_code == 200, response.text
+ assert response.headers["content-type"] == "application/xml"
+ assert response.text == expected_content
+
+
+def test_openapi_schema(client: TestClient):
+ 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": {
+ "/legacy/": {
+ "get": {
+ "operationId": "get_legacy_data_legacy__get",
+ "responses": {
+ "200": {
+ "content": {
+ "application/json": {
+ "schema": {},
+ },
+ },
+ "description": "Successful Response",
+ },
+ },
+ "summary": "Get Legacy Data",
+ },
+ },
+ },
+ }
diff --git a/tests/test_tutorial/test_response_headers/test_tutorial001.py b/tests/test_tutorial/test_response_headers/test_tutorial001.py
index 1549d6b5b1..6232aad23e 100644
--- a/tests/test_tutorial/test_response_headers/test_tutorial001.py
+++ b/tests/test_tutorial/test_response_headers/test_tutorial001.py
@@ -1,6 +1,6 @@
from fastapi.testclient import TestClient
-from docs_src.response_headers.tutorial001 import app
+from docs_src.response_headers.tutorial001_py39 import app
client = TestClient(app)
diff --git a/tests/test_tutorial/test_response_headers/test_tutorial002.py b/tests/test_tutorial/test_response_headers/test_tutorial002.py
index 2826833f84..2ac2226cb1 100644
--- a/tests/test_tutorial/test_response_headers/test_tutorial002.py
+++ b/tests/test_tutorial/test_response_headers/test_tutorial002.py
@@ -1,6 +1,6 @@
from fastapi.testclient import TestClient
-from docs_src.response_headers.tutorial002 import app
+from docs_src.response_headers.tutorial002_py39 import app
client = TestClient(app)
diff --git a/tests/test_tutorial/test_response_model/test_tutorial001_tutorial001_01.py b/tests/test_tutorial/test_response_model/test_tutorial001_tutorial001_01.py
new file mode 100644
index 0000000000..10692f9904
--- /dev/null
+++ b/tests/test_tutorial/test_response_model/test_tutorial001_tutorial001_01.py
@@ -0,0 +1,193 @@
+import importlib
+
+import pytest
+from fastapi.testclient import TestClient
+
+from ...utils import needs_py310
+
+
+@pytest.fixture(
+ name="client",
+ params=[
+ pytest.param("tutorial001_py39"),
+ pytest.param("tutorial001_py310", marks=needs_py310),
+ pytest.param("tutorial001_01_py39"),
+ pytest.param("tutorial001_01_py310", marks=needs_py310),
+ ],
+)
+def get_client(request: pytest.FixtureRequest):
+ mod = importlib.import_module(f"docs_src.response_model.{request.param}")
+
+ client = TestClient(mod.app)
+ return client
+
+
+def test_read_items(client: TestClient):
+ response = client.get("/items/")
+ assert response.status_code == 200, response.text
+ assert response.json() == [
+ {
+ "name": "Portal Gun",
+ "description": None,
+ "price": 42.0,
+ "tags": [],
+ "tax": None,
+ },
+ {
+ "name": "Plumbus",
+ "description": None,
+ "price": 32.0,
+ "tags": [],
+ "tax": None,
+ },
+ ]
+
+
+def test_create_item(client: TestClient):
+ item_data = {
+ "name": "Test Item",
+ "description": "A test item",
+ "price": 10.5,
+ "tax": 1.5,
+ "tags": ["test", "item"],
+ }
+ response = client.post("/items/", json=item_data)
+ assert response.status_code == 200, response.text
+ assert response.json() == item_data
+
+
+def test_create_item_only_required(client: TestClient):
+ response = client.post(
+ "/items/",
+ json={
+ "name": "Test Item",
+ "price": 10.5,
+ },
+ )
+ assert response.status_code == 200, response.text
+ assert response.json() == {
+ "name": "Test Item",
+ "price": 10.5,
+ "description": None,
+ "tax": None,
+ "tags": [],
+ }
+
+
+def test_openapi_schema(client: TestClient):
+ response = client.get("/openapi.json")
+ assert response.status_code == 200, response.text
+ assert response.json() == {
+ "openapi": "3.1.0",
+ "info": {"title": "FastAPI", "version": "0.1.0"},
+ "paths": {
+ "/items/": {
+ "get": {
+ "responses": {
+ "200": {
+ "description": "Successful Response",
+ "content": {
+ "application/json": {
+ "schema": {
+ "type": "array",
+ "items": {"$ref": "#/components/schemas/Item"},
+ "title": "Response Read Items Items Get",
+ }
+ }
+ },
+ },
+ },
+ "summary": "Read Items",
+ "operationId": "read_items_items__get",
+ },
+ "post": {
+ "requestBody": {
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/Item",
+ },
+ },
+ },
+ "required": True,
+ },
+ "responses": {
+ "200": {
+ "description": "Successful Response",
+ "content": {
+ "application/json": {
+ "schema": {"$ref": "#/components/schemas/Item"},
+ }
+ },
+ },
+ "422": {
+ "description": "Validation Error",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/HTTPValidationError"
+ }
+ }
+ },
+ },
+ },
+ "summary": "Create Item",
+ "operationId": "create_item_items__post",
+ },
+ }
+ },
+ "components": {
+ "schemas": {
+ "Item": {
+ "title": "Item",
+ "required": ["name", "price"],
+ "type": "object",
+ "properties": {
+ "name": {"title": "Name", "type": "string"},
+ "price": {"title": "Price", "type": "number"},
+ "description": {
+ "title": "Description",
+ "anyOf": [{"type": "string"}, {"type": "null"}],
+ },
+ "tax": {
+ "title": "Tax",
+ "anyOf": [{"type": "number"}, {"type": "null"}],
+ },
+ "tags": {
+ "title": "Tags",
+ "type": "array",
+ "items": {"type": "string"},
+ "default": [],
+ },
+ },
+ },
+ "ValidationError": {
+ "title": "ValidationError",
+ "required": ["loc", "msg", "type"],
+ "type": "object",
+ "properties": {
+ "loc": {
+ "title": "Location",
+ "type": "array",
+ "items": {
+ "anyOf": [{"type": "string"}, {"type": "integer"}]
+ },
+ },
+ "msg": {"title": "Message", "type": "string"},
+ "type": {"title": "Error Type", "type": "string"},
+ },
+ },
+ "HTTPValidationError": {
+ "title": "HTTPValidationError",
+ "type": "object",
+ "properties": {
+ "detail": {
+ "title": "Detail",
+ "type": "array",
+ "items": {"$ref": "#/components/schemas/ValidationError"},
+ }
+ },
+ },
+ }
+ },
+ }
diff --git a/tests/test_filter_pydantic_sub_model/test_filter_pydantic_sub_model_pv1.py b/tests/test_tutorial/test_response_model/test_tutorial002.py
similarity index 58%
rename from tests/test_filter_pydantic_sub_model/test_filter_pydantic_sub_model_pv1.py
rename to tests/test_tutorial/test_response_model/test_tutorial002.py
index 48732dbf06..216d4c420c 100644
--- a/tests/test_filter_pydantic_sub_model/test_filter_pydantic_sub_model_pv1.py
+++ b/tests/test_tutorial/test_response_model/test_tutorial002.py
@@ -1,43 +1,40 @@
+import importlib
+
import pytest
-from fastapi.exceptions import ResponseValidationError
from fastapi.testclient import TestClient
-from ..utils import needs_pydanticv1
+from ...utils import needs_py310
-@pytest.fixture(name="client")
-def get_client():
- from .app_pv1 import app
+@pytest.fixture(
+ name="client",
+ params=[
+ pytest.param("tutorial002_py39"),
+ pytest.param("tutorial002_py310", marks=needs_py310),
+ ],
+)
+def get_client(request: pytest.FixtureRequest):
+ mod = importlib.import_module(f"docs_src.response_model.{request.param}")
- client = TestClient(app)
+ client = TestClient(mod.app)
return client
-@needs_pydanticv1
-def test_filter_sub_model(client: TestClient):
- response = client.get("/model/modelA")
- assert response.status_code == 200, response.text
- assert response.json() == {
- "name": "modelA",
- "description": "model-a-desc",
- "model_b": {"username": "test-user"},
+def test_post_user(client: TestClient):
+ user_data = {
+ "username": "foo",
+ "password": "fighter",
+ "email": "foo@example.com",
+ "full_name": "Grave Dohl",
}
+ response = client.post(
+ "/user/",
+ json=user_data,
+ )
+ assert response.status_code == 200, response.text
+ assert response.json() == user_data
-@needs_pydanticv1
-def test_validator_is_cloned(client: TestClient):
- with pytest.raises(ResponseValidationError) as err:
- client.get("/model/modelX")
- assert err.value.errors() == [
- {
- "loc": ("response", "name"),
- "msg": "name must end in A",
- "type": "value_error",
- }
- ]
-
-
-@needs_pydanticv1
def test_openapi_schema(client: TestClient):
response = client.get("/openapi.json")
assert response.status_code == 200, response.text
@@ -45,24 +42,14 @@ def test_openapi_schema(client: TestClient):
"openapi": "3.1.0",
"info": {"title": "FastAPI", "version": "0.1.0"},
"paths": {
- "/model/{name}": {
- "get": {
- "summary": "Get Model A",
- "operationId": "get_model_a_model__name__get",
- "parameters": [
- {
- "required": True,
- "schema": {"title": "Name", "type": "string"},
- "name": "name",
- "in": "path",
- }
- ],
+ "/user/": {
+ "post": {
"responses": {
"200": {
"description": "Successful Response",
"content": {
"application/json": {
- "schema": {"$ref": "#/components/schemas/ModelA"}
+ "schema": {"$ref": "#/components/schemas/UserIn"}
}
},
},
@@ -77,38 +64,39 @@ def test_openapi_schema(client: TestClient):
},
},
},
+ "summary": "Create User",
+ "operationId": "create_user_user__post",
+ "requestBody": {
+ "content": {
+ "application/json": {
+ "schema": {"$ref": "#/components/schemas/UserIn"}
+ }
+ },
+ "required": True,
+ },
}
}
},
"components": {
"schemas": {
- "HTTPValidationError": {
- "title": "HTTPValidationError",
+ "UserIn": {
+ "title": "UserIn",
+ "required": ["username", "password", "email"],
"type": "object",
"properties": {
- "detail": {
- "title": "Detail",
- "type": "array",
- "items": {"$ref": "#/components/schemas/ValidationError"},
- }
+ "username": {"title": "Username", "type": "string"},
+ "password": {"title": "Password", "type": "string"},
+ "email": {
+ "title": "Email",
+ "type": "string",
+ "format": "email",
+ },
+ "full_name": {
+ "title": "Full Name",
+ "anyOf": [{"type": "string"}, {"type": "null"}],
+ },
},
},
- "ModelA": {
- "title": "ModelA",
- "required": ["name", "model_b"],
- "type": "object",
- "properties": {
- "name": {"title": "Name", "type": "string"},
- "description": {"title": "Description", "type": "string"},
- "model_b": {"$ref": "#/components/schemas/ModelB"},
- },
- },
- "ModelB": {
- "title": "ModelB",
- "required": ["username"],
- "type": "object",
- "properties": {"username": {"title": "Username", "type": "string"}},
- },
"ValidationError": {
"title": "ValidationError",
"required": ["loc", "msg", "type"],
@@ -125,6 +113,17 @@ def test_openapi_schema(client: TestClient):
"type": {"title": "Error Type", "type": "string"},
},
},
+ "HTTPValidationError": {
+ "title": "HTTPValidationError",
+ "type": "object",
+ "properties": {
+ "detail": {
+ "title": "Detail",
+ "type": "array",
+ "items": {"$ref": "#/components/schemas/ValidationError"},
+ }
+ },
+ },
}
},
}
diff --git a/tests/test_tutorial/test_response_model/test_tutorial003.py b/tests/test_tutorial/test_response_model/test_tutorial003.py
index 70cfd6e4cc..35ed5572dd 100644
--- a/tests/test_tutorial/test_response_model/test_tutorial003.py
+++ b/tests/test_tutorial/test_response_model/test_tutorial003.py
@@ -1,8 +1,8 @@
import importlib
import pytest
-from dirty_equals import IsDict, IsOneOf
from fastapi.testclient import TestClient
+from inline_snapshot import snapshot
from ...utils import needs_py310
@@ -10,7 +10,7 @@ from ...utils import needs_py310
@pytest.fixture(
name="client",
params=[
- "tutorial003",
+ pytest.param("tutorial003_py39"),
pytest.param("tutorial003_py310", marks=needs_py310),
],
)
@@ -42,125 +42,115 @@ def test_post_user(client: TestClient):
def test_openapi_schema(client: TestClient):
response = client.get("/openapi.json")
assert response.status_code == 200, response.text
- assert response.json() == {
- "openapi": "3.1.0",
- "info": {"title": "FastAPI", "version": "0.1.0"},
- "paths": {
- "/user/": {
- "post": {
- "responses": {
- "200": {
- "description": "Successful Response",
- "content": {
- "application/json": {
- "schema": {"$ref": "#/components/schemas/UserOut"}
- }
+ assert response.json() == snapshot(
+ {
+ "openapi": "3.1.0",
+ "info": {"title": "FastAPI", "version": "0.1.0"},
+ "paths": {
+ "/user/": {
+ "post": {
+ "responses": {
+ "200": {
+ "description": "Successful Response",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/UserOut"
+ }
+ }
+ },
+ },
+ "422": {
+ "description": "Validation Error",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/HTTPValidationError"
+ }
+ }
+ },
},
},
- "422": {
- "description": "Validation Error",
+ "summary": "Create User",
+ "operationId": "create_user_user__post",
+ "requestBody": {
"content": {
"application/json": {
- "schema": {
- "$ref": "#/components/schemas/HTTPValidationError"
- }
+ "schema": {"$ref": "#/components/schemas/UserIn"}
}
},
+ "required": True,
+ },
+ }
+ }
+ },
+ "components": {
+ "schemas": {
+ "UserOut": {
+ "title": "UserOut",
+ "required": ["username", "email"],
+ "type": "object",
+ "properties": {
+ "username": {"title": "Username", "type": "string"},
+ "email": {
+ "title": "Email",
+ "type": "string",
+ "format": "email",
+ },
+ "full_name": {
+ "title": "Full Name",
+ "anyOf": [{"type": "string"}, {"type": "null"}],
+ },
},
},
- "summary": "Create User",
- "operationId": "create_user_user__post",
- "requestBody": {
- "content": {
- "application/json": {
- "schema": {"$ref": "#/components/schemas/UserIn"}
+ "UserIn": {
+ "title": "UserIn",
+ "required": ["username", "password", "email"],
+ "type": "object",
+ "properties": {
+ "username": {"title": "Username", "type": "string"},
+ "password": {"title": "Password", "type": "string"},
+ "email": {
+ "title": "Email",
+ "type": "string",
+ "format": "email",
+ },
+ "full_name": {
+ "title": "Full Name",
+ "anyOf": [{"type": "string"}, {"type": "null"}],
+ },
+ },
+ },
+ "ValidationError": {
+ "title": "ValidationError",
+ "required": ["loc", "msg", "type"],
+ "type": "object",
+ "properties": {
+ "loc": {
+ "title": "Location",
+ "type": "array",
+ "items": {
+ "anyOf": [{"type": "string"}, {"type": "integer"}]
+ },
+ },
+ "msg": {"title": "Message", "type": "string"},
+ "type": {"title": "Error Type", "type": "string"},
+ },
+ },
+ "HTTPValidationError": {
+ "title": "HTTPValidationError",
+ "type": "object",
+ "properties": {
+ "detail": {
+ "title": "Detail",
+ "type": "array",
+ "items": {
+ "$ref": "#/components/schemas/ValidationError"
+ },
}
},
- "required": True,
},
}
- }
- },
- "components": {
- "schemas": {
- "UserOut": {
- "title": "UserOut",
- "required": IsOneOf(
- ["username", "email", "full_name"],
- # TODO: remove when deprecating Pydantic v1
- ["username", "email"],
- ),
- "type": "object",
- "properties": {
- "username": {"title": "Username", "type": "string"},
- "email": {
- "title": "Email",
- "type": "string",
- "format": "email",
- },
- "full_name": IsDict(
- {
- "title": "Full Name",
- "anyOf": [{"type": "string"}, {"type": "null"}],
- }
- )
- | IsDict(
- # TODO: remove when deprecating Pydantic v1
- {"title": "Full Name", "type": "string"}
- ),
- },
- },
- "UserIn": {
- "title": "UserIn",
- "required": ["username", "password", "email"],
- "type": "object",
- "properties": {
- "username": {"title": "Username", "type": "string"},
- "password": {"title": "Password", "type": "string"},
- "email": {
- "title": "Email",
- "type": "string",
- "format": "email",
- },
- "full_name": IsDict(
- {
- "title": "Full Name",
- "anyOf": [{"type": "string"}, {"type": "null"}],
- }
- )
- | IsDict(
- # TODO: remove when deprecating Pydantic v1
- {"title": "Full Name", "type": "string"}
- ),
- },
- },
- "ValidationError": {
- "title": "ValidationError",
- "required": ["loc", "msg", "type"],
- "type": "object",
- "properties": {
- "loc": {
- "title": "Location",
- "type": "array",
- "items": {
- "anyOf": [{"type": "string"}, {"type": "integer"}]
- },
- },
- "msg": {"title": "Message", "type": "string"},
- "type": {"title": "Error Type", "type": "string"},
- },
- },
- "HTTPValidationError": {
- "title": "HTTPValidationError",
- "type": "object",
- "properties": {
- "detail": {
- "title": "Detail",
- "type": "array",
- "items": {"$ref": "#/components/schemas/ValidationError"},
- }
- },
- },
- }
- },
- }
+ },
+ }
+ )
diff --git a/tests/test_tutorial/test_response_model/test_tutorial003_01.py b/tests/test_tutorial/test_response_model/test_tutorial003_01.py
index 3975856b6c..fa1eb62770 100644
--- a/tests/test_tutorial/test_response_model/test_tutorial003_01.py
+++ b/tests/test_tutorial/test_response_model/test_tutorial003_01.py
@@ -1,8 +1,8 @@
import importlib
import pytest
-from dirty_equals import IsDict, IsOneOf
from fastapi.testclient import TestClient
+from inline_snapshot import snapshot
from ...utils import needs_py310
@@ -10,7 +10,7 @@ from ...utils import needs_py310
@pytest.fixture(
name="client",
params=[
- "tutorial003_01",
+ pytest.param("tutorial003_01_py39"),
pytest.param("tutorial003_01_py310", marks=needs_py310),
],
)
@@ -42,125 +42,115 @@ def test_post_user(client: TestClient):
def test_openapi_schema(client: TestClient):
response = client.get("/openapi.json")
assert response.status_code == 200, response.text
- assert response.json() == {
- "openapi": "3.1.0",
- "info": {"title": "FastAPI", "version": "0.1.0"},
- "paths": {
- "/user/": {
- "post": {
- "summary": "Create User",
- "operationId": "create_user_user__post",
- "requestBody": {
- "content": {
- "application/json": {
- "schema": {"$ref": "#/components/schemas/UserIn"}
+ assert response.json() == snapshot(
+ {
+ "openapi": "3.1.0",
+ "info": {"title": "FastAPI", "version": "0.1.0"},
+ "paths": {
+ "/user/": {
+ "post": {
+ "summary": "Create User",
+ "operationId": "create_user_user__post",
+ "requestBody": {
+ "content": {
+ "application/json": {
+ "schema": {"$ref": "#/components/schemas/UserIn"}
+ }
+ },
+ "required": True,
+ },
+ "responses": {
+ "200": {
+ "description": "Successful Response",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/BaseUser"
+ }
+ }
+ },
+ },
+ "422": {
+ "description": "Validation Error",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/HTTPValidationError"
+ }
+ }
+ },
+ },
+ },
+ }
+ }
+ },
+ "components": {
+ "schemas": {
+ "BaseUser": {
+ "title": "BaseUser",
+ "required": ["username", "email"],
+ "type": "object",
+ "properties": {
+ "username": {"title": "Username", "type": "string"},
+ "email": {
+ "title": "Email",
+ "type": "string",
+ "format": "email",
+ },
+ "full_name": {
+ "title": "Full Name",
+ "anyOf": [{"type": "string"}, {"type": "null"}],
+ },
+ },
+ },
+ "HTTPValidationError": {
+ "title": "HTTPValidationError",
+ "type": "object",
+ "properties": {
+ "detail": {
+ "title": "Detail",
+ "type": "array",
+ "items": {
+ "$ref": "#/components/schemas/ValidationError"
+ },
}
},
- "required": True,
},
- "responses": {
- "200": {
- "description": "Successful Response",
- "content": {
- "application/json": {
- "schema": {"$ref": "#/components/schemas/BaseUser"}
- }
+ "UserIn": {
+ "title": "UserIn",
+ "required": ["username", "email", "password"],
+ "type": "object",
+ "properties": {
+ "username": {"title": "Username", "type": "string"},
+ "email": {
+ "title": "Email",
+ "type": "string",
+ "format": "email",
},
+ "full_name": {
+ "title": "Full Name",
+ "anyOf": [{"type": "string"}, {"type": "null"}],
+ },
+ "password": {"title": "Password", "type": "string"},
},
- "422": {
- "description": "Validation Error",
- "content": {
- "application/json": {
- "schema": {
- "$ref": "#/components/schemas/HTTPValidationError"
- }
- }
+ },
+ "ValidationError": {
+ "title": "ValidationError",
+ "required": ["loc", "msg", "type"],
+ "type": "object",
+ "properties": {
+ "loc": {
+ "title": "Location",
+ "type": "array",
+ "items": {
+ "anyOf": [{"type": "string"}, {"type": "integer"}]
+ },
},
+ "msg": {"title": "Message", "type": "string"},
+ "type": {"title": "Error Type", "type": "string"},
},
},
}
- }
- },
- "components": {
- "schemas": {
- "BaseUser": {
- "title": "BaseUser",
- "required": IsOneOf(
- ["username", "email", "full_name"],
- # TODO: remove when deprecating Pydantic v1
- ["username", "email"],
- ),
- "type": "object",
- "properties": {
- "username": {"title": "Username", "type": "string"},
- "email": {
- "title": "Email",
- "type": "string",
- "format": "email",
- },
- "full_name": IsDict(
- {
- "title": "Full Name",
- "anyOf": [{"type": "string"}, {"type": "null"}],
- }
- )
- | IsDict(
- # TODO: remove when deprecating Pydantic v1
- {"title": "Full Name", "type": "string"}
- ),
- },
- },
- "HTTPValidationError": {
- "title": "HTTPValidationError",
- "type": "object",
- "properties": {
- "detail": {
- "title": "Detail",
- "type": "array",
- "items": {"$ref": "#/components/schemas/ValidationError"},
- }
- },
- },
- "UserIn": {
- "title": "UserIn",
- "required": ["username", "email", "password"],
- "type": "object",
- "properties": {
- "username": {"title": "Username", "type": "string"},
- "email": {
- "title": "Email",
- "type": "string",
- "format": "email",
- },
- "full_name": IsDict(
- {
- "title": "Full Name",
- "anyOf": [{"type": "string"}, {"type": "null"}],
- }
- )
- | IsDict(
- # TODO: remove when deprecating Pydantic v1
- {"title": "Full Name", "type": "string"}
- ),
- "password": {"title": "Password", "type": "string"},
- },
- },
- "ValidationError": {
- "title": "ValidationError",
- "required": ["loc", "msg", "type"],
- "type": "object",
- "properties": {
- "loc": {
- "title": "Location",
- "type": "array",
- "items": {
- "anyOf": [{"type": "string"}, {"type": "integer"}]
- },
- },
- "msg": {"title": "Message", "type": "string"},
- "type": {"title": "Error Type", "type": "string"},
- },
- },
- }
- },
- }
+ },
+ }
+ )
diff --git a/tests/test_tutorial/test_response_model/test_tutorial003_02.py b/tests/test_tutorial/test_response_model/test_tutorial003_02.py
index eabd203456..b7507b7110 100644
--- a/tests/test_tutorial/test_response_model/test_tutorial003_02.py
+++ b/tests/test_tutorial/test_response_model/test_tutorial003_02.py
@@ -1,6 +1,6 @@
from fastapi.testclient import TestClient
-from docs_src.response_model.tutorial003_02 import app
+from docs_src.response_model.tutorial003_02_py39 import app
client = TestClient(app)
diff --git a/tests/test_tutorial/test_response_model/test_tutorial003_03.py b/tests/test_tutorial/test_response_model/test_tutorial003_03.py
index 970ff58450..ea3c733b24 100644
--- a/tests/test_tutorial/test_response_model/test_tutorial003_03.py
+++ b/tests/test_tutorial/test_response_model/test_tutorial003_03.py
@@ -1,6 +1,6 @@
from fastapi.testclient import TestClient
-from docs_src.response_model.tutorial003_03 import app
+from docs_src.response_model.tutorial003_03_py39 import app
client = TestClient(app)
diff --git a/tests/test_tutorial/test_response_model/test_tutorial003_04.py b/tests/test_tutorial/test_response_model/test_tutorial003_04.py
index f32e93ddcb..145af126fd 100644
--- a/tests/test_tutorial/test_response_model/test_tutorial003_04.py
+++ b/tests/test_tutorial/test_response_model/test_tutorial003_04.py
@@ -9,7 +9,7 @@ from ...utils import needs_py310
@pytest.mark.parametrize(
"module_name",
[
- "tutorial003_04",
+ pytest.param("tutorial003_04_py39"),
pytest.param("tutorial003_04_py310", marks=needs_py310),
],
)
diff --git a/tests/test_tutorial/test_response_model/test_tutorial003_05.py b/tests/test_tutorial/test_response_model/test_tutorial003_05.py
index 9500852e15..19a7c601bb 100644
--- a/tests/test_tutorial/test_response_model/test_tutorial003_05.py
+++ b/tests/test_tutorial/test_response_model/test_tutorial003_05.py
@@ -9,7 +9,7 @@ from ...utils import needs_py310
@pytest.fixture(
name="client",
params=[
- "tutorial003_05",
+ pytest.param("tutorial003_05_py39"),
pytest.param("tutorial003_05_py310", marks=needs_py310),
],
)
diff --git a/tests/test_tutorial/test_response_model/test_tutorial004.py b/tests/test_tutorial/test_response_model/test_tutorial004.py
index 449a52b813..9c0d95ebd0 100644
--- a/tests/test_tutorial/test_response_model/test_tutorial004.py
+++ b/tests/test_tutorial/test_response_model/test_tutorial004.py
@@ -1,17 +1,16 @@
import importlib
import pytest
-from dirty_equals import IsDict, IsOneOf
from fastapi.testclient import TestClient
+from inline_snapshot import snapshot
-from ...utils import needs_py39, needs_py310
+from ...utils import needs_py310
@pytest.fixture(
name="client",
params=[
- "tutorial004",
- pytest.param("tutorial004_py39", marks=needs_py39),
+ pytest.param("tutorial004_py39"),
pytest.param("tutorial004_py310", marks=needs_py310),
],
)
@@ -51,104 +50,98 @@ def test_get(url, data, client: TestClient):
def test_openapi_schema(client: TestClient):
response = client.get("/openapi.json")
assert response.status_code == 200, response.text
- assert response.json() == {
- "openapi": "3.1.0",
- "info": {"title": "FastAPI", "version": "0.1.0"},
- "paths": {
- "/items/{item_id}": {
- "get": {
- "responses": {
- "200": {
- "description": "Successful Response",
- "content": {
- "application/json": {
- "schema": {"$ref": "#/components/schemas/Item"}
- }
- },
- },
- "422": {
- "description": "Validation Error",
- "content": {
- "application/json": {
- "schema": {
- "$ref": "#/components/schemas/HTTPValidationError"
+ assert response.json() == snapshot(
+ {
+ "openapi": "3.1.0",
+ "info": {"title": "FastAPI", "version": "0.1.0"},
+ "paths": {
+ "/items/{item_id}": {
+ "get": {
+ "responses": {
+ "200": {
+ "description": "Successful Response",
+ "content": {
+ "application/json": {
+ "schema": {"$ref": "#/components/schemas/Item"}
}
- }
+ },
+ },
+ "422": {
+ "description": "Validation Error",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/HTTPValidationError"
+ }
+ }
+ },
},
},
- },
- "summary": "Read Item",
- "operationId": "read_item_items__item_id__get",
- "parameters": [
- {
- "required": True,
- "schema": {"title": "Item Id", "type": "string"},
- "name": "item_id",
- "in": "path",
- }
- ],
- }
- }
- },
- "components": {
- "schemas": {
- "Item": {
- "title": "Item",
- "required": IsOneOf(
- ["name", "description", "price", "tax", "tags"],
- # TODO: remove when deprecating Pydantic v1
- ["name", "price"],
- ),
- "type": "object",
- "properties": {
- "name": {"title": "Name", "type": "string"},
- "price": {"title": "Price", "type": "number"},
- "description": IsDict(
+ "summary": "Read Item",
+ "operationId": "read_item_items__item_id__get",
+ "parameters": [
{
+ "required": True,
+ "schema": {"title": "Item Id", "type": "string"},
+ "name": "item_id",
+ "in": "path",
+ }
+ ],
+ }
+ }
+ },
+ "components": {
+ "schemas": {
+ "Item": {
+ "title": "Item",
+ "required": ["name", "price"],
+ "type": "object",
+ "properties": {
+ "name": {"title": "Name", "type": "string"},
+ "price": {"title": "Price", "type": "number"},
+ "description": {
"title": "Description",
"anyOf": [{"type": "string"}, {"type": "null"}],
- }
- )
- | IsDict(
- # TODO: remove when deprecating Pydantic v1
- {"title": "Description", "type": "string"}
- ),
- "tax": {"title": "Tax", "type": "number", "default": 10.5},
- "tags": {
- "title": "Tags",
- "type": "array",
- "items": {"type": "string"},
- "default": [],
- },
- },
- },
- "ValidationError": {
- "title": "ValidationError",
- "required": ["loc", "msg", "type"],
- "type": "object",
- "properties": {
- "loc": {
- "title": "Location",
- "type": "array",
- "items": {
- "anyOf": [{"type": "string"}, {"type": "integer"}]
+ },
+ "tax": {"title": "Tax", "type": "number", "default": 10.5},
+ "tags": {
+ "title": "Tags",
+ "type": "array",
+ "items": {"type": "string"},
+ "default": [],
},
},
- "msg": {"title": "Message", "type": "string"},
- "type": {"title": "Error Type", "type": "string"},
},
- },
- "HTTPValidationError": {
- "title": "HTTPValidationError",
- "type": "object",
- "properties": {
- "detail": {
- "title": "Detail",
- "type": "array",
- "items": {"$ref": "#/components/schemas/ValidationError"},
- }
+ "ValidationError": {
+ "title": "ValidationError",
+ "required": ["loc", "msg", "type"],
+ "type": "object",
+ "properties": {
+ "loc": {
+ "title": "Location",
+ "type": "array",
+ "items": {
+ "anyOf": [{"type": "string"}, {"type": "integer"}]
+ },
+ },
+ "msg": {"title": "Message", "type": "string"},
+ "type": {"title": "Error Type", "type": "string"},
+ },
},
- },
- }
- },
- }
+ "HTTPValidationError": {
+ "title": "HTTPValidationError",
+ "type": "object",
+ "properties": {
+ "detail": {
+ "title": "Detail",
+ "type": "array",
+ "items": {
+ "$ref": "#/components/schemas/ValidationError"
+ },
+ }
+ },
+ },
+ }
+ },
+ }
+ )
diff --git a/tests/test_tutorial/test_response_model/test_tutorial005.py b/tests/test_tutorial/test_response_model/test_tutorial005.py
index a633a3fddd..63e8535db0 100644
--- a/tests/test_tutorial/test_response_model/test_tutorial005.py
+++ b/tests/test_tutorial/test_response_model/test_tutorial005.py
@@ -1,8 +1,8 @@
import importlib
import pytest
-from dirty_equals import IsDict, IsOneOf
from fastapi.testclient import TestClient
+from inline_snapshot import snapshot
from ...utils import needs_py310
@@ -10,7 +10,7 @@ from ...utils import needs_py310
@pytest.fixture(
name="client",
params=[
- "tutorial005",
+ pytest.param("tutorial005_py39"),
pytest.param("tutorial005_py310", marks=needs_py310),
],
)
@@ -40,132 +40,126 @@ def test_read_item_public_data(client: TestClient):
def test_openapi_schema(client: TestClient):
response = client.get("/openapi.json")
assert response.status_code == 200, response.text
- assert response.json() == {
- "openapi": "3.1.0",
- "info": {"title": "FastAPI", "version": "0.1.0"},
- "paths": {
- "/items/{item_id}/name": {
- "get": {
- "responses": {
- "200": {
- "description": "Successful Response",
- "content": {
- "application/json": {
- "schema": {"$ref": "#/components/schemas/Item"}
- }
- },
- },
- "422": {
- "description": "Validation Error",
- "content": {
- "application/json": {
- "schema": {
- "$ref": "#/components/schemas/HTTPValidationError"
+ assert response.json() == snapshot(
+ {
+ "openapi": "3.1.0",
+ "info": {"title": "FastAPI", "version": "0.1.0"},
+ "paths": {
+ "/items/{item_id}/name": {
+ "get": {
+ "responses": {
+ "200": {
+ "description": "Successful Response",
+ "content": {
+ "application/json": {
+ "schema": {"$ref": "#/components/schemas/Item"}
}
- }
+ },
},
- },
- },
- "summary": "Read Item Name",
- "operationId": "read_item_name_items__item_id__name_get",
- "parameters": [
- {
- "required": True,
- "schema": {"title": "Item Id", "type": "string"},
- "name": "item_id",
- "in": "path",
- }
- ],
- }
- },
- "/items/{item_id}/public": {
- "get": {
- "responses": {
- "200": {
- "description": "Successful Response",
- "content": {
- "application/json": {
- "schema": {"$ref": "#/components/schemas/Item"}
- }
- },
- },
- "422": {
- "description": "Validation Error",
- "content": {
- "application/json": {
- "schema": {
- "$ref": "#/components/schemas/HTTPValidationError"
+ "422": {
+ "description": "Validation Error",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/HTTPValidationError"
+ }
}
- }
+ },
},
},
- },
- "summary": "Read Item Public Data",
- "operationId": "read_item_public_data_items__item_id__public_get",
- "parameters": [
- {
- "required": True,
- "schema": {"title": "Item Id", "type": "string"},
- "name": "item_id",
- "in": "path",
- }
- ],
- }
- },
- },
- "components": {
- "schemas": {
- "Item": {
- "title": "Item",
- "required": IsOneOf(
- ["name", "description", "price", "tax"],
- # TODO: remove when deprecating Pydantic v1
- ["name", "price"],
- ),
- "type": "object",
- "properties": {
- "name": {"title": "Name", "type": "string"},
- "price": {"title": "Price", "type": "number"},
- "description": IsDict(
+ "summary": "Read Item Name",
+ "operationId": "read_item_name_items__item_id__name_get",
+ "parameters": [
{
+ "required": True,
+ "schema": {"title": "Item Id", "type": "string"},
+ "name": "item_id",
+ "in": "path",
+ }
+ ],
+ }
+ },
+ "/items/{item_id}/public": {
+ "get": {
+ "responses": {
+ "200": {
+ "description": "Successful Response",
+ "content": {
+ "application/json": {
+ "schema": {"$ref": "#/components/schemas/Item"}
+ }
+ },
+ },
+ "422": {
+ "description": "Validation Error",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/HTTPValidationError"
+ }
+ }
+ },
+ },
+ },
+ "summary": "Read Item Public Data",
+ "operationId": "read_item_public_data_items__item_id__public_get",
+ "parameters": [
+ {
+ "required": True,
+ "schema": {"title": "Item Id", "type": "string"},
+ "name": "item_id",
+ "in": "path",
+ }
+ ],
+ }
+ },
+ },
+ "components": {
+ "schemas": {
+ "Item": {
+ "title": "Item",
+ "required": ["name", "price"],
+ "type": "object",
+ "properties": {
+ "name": {"title": "Name", "type": "string"},
+ "price": {"title": "Price", "type": "number"},
+ "description": {
"title": "Description",
"anyOf": [{"type": "string"}, {"type": "null"}],
- }
- )
- | IsDict(
- # TODO: remove when deprecating Pydantic v1
- {"title": "Description", "type": "string"}
- ),
- "tax": {"title": "Tax", "type": "number", "default": 10.5},
- },
- },
- "ValidationError": {
- "title": "ValidationError",
- "required": ["loc", "msg", "type"],
- "type": "object",
- "properties": {
- "loc": {
- "title": "Location",
- "type": "array",
- "items": {
- "anyOf": [{"type": "string"}, {"type": "integer"}]
},
+ "tax": {"title": "Tax", "type": "number", "default": 10.5},
},
- "msg": {"title": "Message", "type": "string"},
- "type": {"title": "Error Type", "type": "string"},
},
- },
- "HTTPValidationError": {
- "title": "HTTPValidationError",
- "type": "object",
- "properties": {
- "detail": {
- "title": "Detail",
- "type": "array",
- "items": {"$ref": "#/components/schemas/ValidationError"},
- }
+ "ValidationError": {
+ "title": "ValidationError",
+ "required": ["loc", "msg", "type"],
+ "type": "object",
+ "properties": {
+ "loc": {
+ "title": "Location",
+ "type": "array",
+ "items": {
+ "anyOf": [{"type": "string"}, {"type": "integer"}]
+ },
+ },
+ "msg": {"title": "Message", "type": "string"},
+ "type": {"title": "Error Type", "type": "string"},
+ },
},
- },
- }
- },
- }
+ "HTTPValidationError": {
+ "title": "HTTPValidationError",
+ "type": "object",
+ "properties": {
+ "detail": {
+ "title": "Detail",
+ "type": "array",
+ "items": {
+ "$ref": "#/components/schemas/ValidationError"
+ },
+ }
+ },
+ },
+ }
+ },
+ }
+ )
diff --git a/tests/test_tutorial/test_response_model/test_tutorial006.py b/tests/test_tutorial/test_response_model/test_tutorial006.py
index 863522d1b4..08ab659527 100644
--- a/tests/test_tutorial/test_response_model/test_tutorial006.py
+++ b/tests/test_tutorial/test_response_model/test_tutorial006.py
@@ -1,8 +1,8 @@
import importlib
import pytest
-from dirty_equals import IsDict, IsOneOf
from fastapi.testclient import TestClient
+from inline_snapshot import snapshot
from ...utils import needs_py310
@@ -10,7 +10,7 @@ from ...utils import needs_py310
@pytest.fixture(
name="client",
params=[
- "tutorial006",
+ pytest.param("tutorial006_py39"),
pytest.param("tutorial006_py310", marks=needs_py310),
],
)
@@ -40,132 +40,126 @@ def test_read_item_public_data(client: TestClient):
def test_openapi_schema(client: TestClient):
response = client.get("/openapi.json")
assert response.status_code == 200, response.text
- assert response.json() == {
- "openapi": "3.1.0",
- "info": {"title": "FastAPI", "version": "0.1.0"},
- "paths": {
- "/items/{item_id}/name": {
- "get": {
- "responses": {
- "200": {
- "description": "Successful Response",
- "content": {
- "application/json": {
- "schema": {"$ref": "#/components/schemas/Item"}
- }
- },
- },
- "422": {
- "description": "Validation Error",
- "content": {
- "application/json": {
- "schema": {
- "$ref": "#/components/schemas/HTTPValidationError"
+ assert response.json() == snapshot(
+ {
+ "openapi": "3.1.0",
+ "info": {"title": "FastAPI", "version": "0.1.0"},
+ "paths": {
+ "/items/{item_id}/name": {
+ "get": {
+ "responses": {
+ "200": {
+ "description": "Successful Response",
+ "content": {
+ "application/json": {
+ "schema": {"$ref": "#/components/schemas/Item"}
}
- }
+ },
},
- },
- },
- "summary": "Read Item Name",
- "operationId": "read_item_name_items__item_id__name_get",
- "parameters": [
- {
- "required": True,
- "schema": {"title": "Item Id", "type": "string"},
- "name": "item_id",
- "in": "path",
- }
- ],
- }
- },
- "/items/{item_id}/public": {
- "get": {
- "responses": {
- "200": {
- "description": "Successful Response",
- "content": {
- "application/json": {
- "schema": {"$ref": "#/components/schemas/Item"}
- }
- },
- },
- "422": {
- "description": "Validation Error",
- "content": {
- "application/json": {
- "schema": {
- "$ref": "#/components/schemas/HTTPValidationError"
+ "422": {
+ "description": "Validation Error",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/HTTPValidationError"
+ }
}
- }
+ },
},
},
- },
- "summary": "Read Item Public Data",
- "operationId": "read_item_public_data_items__item_id__public_get",
- "parameters": [
- {
- "required": True,
- "schema": {"title": "Item Id", "type": "string"},
- "name": "item_id",
- "in": "path",
- }
- ],
- }
- },
- },
- "components": {
- "schemas": {
- "Item": {
- "title": "Item",
- "required": IsOneOf(
- ["name", "description", "price", "tax"],
- # TODO: remove when deprecating Pydantic v1
- ["name", "price"],
- ),
- "type": "object",
- "properties": {
- "name": {"title": "Name", "type": "string"},
- "price": {"title": "Price", "type": "number"},
- "description": IsDict(
+ "summary": "Read Item Name",
+ "operationId": "read_item_name_items__item_id__name_get",
+ "parameters": [
{
+ "required": True,
+ "schema": {"title": "Item Id", "type": "string"},
+ "name": "item_id",
+ "in": "path",
+ }
+ ],
+ }
+ },
+ "/items/{item_id}/public": {
+ "get": {
+ "responses": {
+ "200": {
+ "description": "Successful Response",
+ "content": {
+ "application/json": {
+ "schema": {"$ref": "#/components/schemas/Item"}
+ }
+ },
+ },
+ "422": {
+ "description": "Validation Error",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/HTTPValidationError"
+ }
+ }
+ },
+ },
+ },
+ "summary": "Read Item Public Data",
+ "operationId": "read_item_public_data_items__item_id__public_get",
+ "parameters": [
+ {
+ "required": True,
+ "schema": {"title": "Item Id", "type": "string"},
+ "name": "item_id",
+ "in": "path",
+ }
+ ],
+ }
+ },
+ },
+ "components": {
+ "schemas": {
+ "Item": {
+ "title": "Item",
+ "required": ["name", "price"],
+ "type": "object",
+ "properties": {
+ "name": {"title": "Name", "type": "string"},
+ "price": {"title": "Price", "type": "number"},
+ "description": {
"title": "Description",
"anyOf": [{"type": "string"}, {"type": "null"}],
- }
- )
- | IsDict(
- # TODO: remove when deprecating Pydantic v1
- {"title": "Description", "type": "string"}
- ),
- "tax": {"title": "Tax", "type": "number", "default": 10.5},
- },
- },
- "ValidationError": {
- "title": "ValidationError",
- "required": ["loc", "msg", "type"],
- "type": "object",
- "properties": {
- "loc": {
- "title": "Location",
- "type": "array",
- "items": {
- "anyOf": [{"type": "string"}, {"type": "integer"}]
},
+ "tax": {"title": "Tax", "type": "number", "default": 10.5},
},
- "msg": {"title": "Message", "type": "string"},
- "type": {"title": "Error Type", "type": "string"},
},
- },
- "HTTPValidationError": {
- "title": "HTTPValidationError",
- "type": "object",
- "properties": {
- "detail": {
- "title": "Detail",
- "type": "array",
- "items": {"$ref": "#/components/schemas/ValidationError"},
- }
+ "ValidationError": {
+ "title": "ValidationError",
+ "required": ["loc", "msg", "type"],
+ "type": "object",
+ "properties": {
+ "loc": {
+ "title": "Location",
+ "type": "array",
+ "items": {
+ "anyOf": [{"type": "string"}, {"type": "integer"}]
+ },
+ },
+ "msg": {"title": "Message", "type": "string"},
+ "type": {"title": "Error Type", "type": "string"},
+ },
},
- },
- }
- },
- }
+ "HTTPValidationError": {
+ "title": "HTTPValidationError",
+ "type": "object",
+ "properties": {
+ "detail": {
+ "title": "Detail",
+ "type": "array",
+ "items": {
+ "$ref": "#/components/schemas/ValidationError"
+ },
+ }
+ },
+ },
+ }
+ },
+ }
+ )
diff --git a/tests/test_tutorial/test_response_status_code/__init__.py b/tests/test_tutorial/test_response_status_code/__init__.py
new file mode 100644
index 0000000000..e69de29bb2
diff --git a/tests/test_tutorial/test_response_status_code/test_tutorial001_tutorial002.py b/tests/test_tutorial/test_response_status_code/test_tutorial001_tutorial002.py
new file mode 100644
index 0000000000..ddf55a045d
--- /dev/null
+++ b/tests/test_tutorial/test_response_status_code/test_tutorial001_tutorial002.py
@@ -0,0 +1,96 @@
+import importlib
+
+import pytest
+from fastapi.testclient import TestClient
+
+
+@pytest.fixture(
+ name="client",
+ params=[
+ pytest.param("tutorial001_py39"),
+ pytest.param("tutorial002_py39"),
+ ],
+)
+def get_client(request: pytest.FixtureRequest):
+ mod = importlib.import_module(f"docs_src.response_status_code.{request.param}")
+
+ client = TestClient(mod.app)
+ return client
+
+
+def test_create_item(client: TestClient):
+ response = client.post("/items/", params={"name": "Test Item"})
+ assert response.status_code == 201, response.text
+ assert response.json() == {"name": "Test Item"}
+
+
+def test_openapi_schema(client: TestClient):
+ response = client.get("/openapi.json")
+ assert response.status_code == 200, response.text
+ assert response.json() == {
+ "openapi": "3.1.0",
+ "info": {"title": "FastAPI", "version": "0.1.0"},
+ "paths": {
+ "/items/": {
+ "post": {
+ "parameters": [
+ {
+ "name": "name",
+ "in": "query",
+ "required": True,
+ "schema": {"title": "Name", "type": "string"},
+ }
+ ],
+ "summary": "Create Item",
+ "operationId": "create_item_items__post",
+ "responses": {
+ "201": {
+ "description": "Successful Response",
+ "content": {"application/json": {"schema": {}}},
+ },
+ "422": {
+ "description": "Validation Error",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/HTTPValidationError"
+ }
+ }
+ },
+ },
+ },
+ }
+ }
+ },
+ "components": {
+ "schemas": {
+ "ValidationError": {
+ "title": "ValidationError",
+ "required": ["loc", "msg", "type"],
+ "type": "object",
+ "properties": {
+ "loc": {
+ "title": "Location",
+ "type": "array",
+ "items": {
+ "anyOf": [{"type": "string"}, {"type": "integer"}]
+ },
+ },
+ "msg": {"title": "Message", "type": "string"},
+ "type": {"title": "Error Type", "type": "string"},
+ },
+ },
+ "HTTPValidationError": {
+ "title": "HTTPValidationError",
+ "type": "object",
+ "properties": {
+ "detail": {
+ "title": "Detail",
+ "type": "array",
+ "items": {"$ref": "#/components/schemas/ValidationError"},
+ }
+ },
+ },
+ }
+ },
+ }
diff --git a/tests/test_tutorial/test_schema_extra_example/test_tutorial001.py b/tests/test_tutorial/test_schema_extra_example/test_tutorial001.py
index c21cbb4bc2..82f69fd463 100644
--- a/tests/test_tutorial/test_schema_extra_example/test_tutorial001.py
+++ b/tests/test_tutorial/test_schema_extra_example/test_tutorial001.py
@@ -3,13 +3,13 @@ import importlib
import pytest
from fastapi.testclient import TestClient
-from ...utils import needs_py310, needs_pydanticv2
+from ...utils import needs_py310
@pytest.fixture(
name="client",
params=[
- "tutorial001",
+ pytest.param("tutorial001_py39"),
pytest.param("tutorial001_py310", marks=needs_py310),
],
)
@@ -20,7 +20,6 @@ def get_client(request: pytest.FixtureRequest):
return client
-@needs_pydanticv2
def test_post_body_example(client: TestClient):
response = client.put(
"/items/5",
@@ -34,7 +33,6 @@ def test_post_body_example(client: TestClient):
assert response.status_code == 200
-@needs_pydanticv2
def test_openapi_schema(client: TestClient):
response = client.get("/openapi.json")
assert response.status_code == 200, response.text
diff --git a/tests/test_tutorial/test_schema_extra_example/test_tutorial001_pv1.py b/tests/test_tutorial/test_schema_extra_example/test_tutorial002.py
similarity index 79%
rename from tests/test_tutorial/test_schema_extra_example/test_tutorial001_pv1.py
rename to tests/test_tutorial/test_schema_extra_example/test_tutorial002.py
index b79f42e642..4f52408605 100644
--- a/tests/test_tutorial/test_schema_extra_example/test_tutorial001_pv1.py
+++ b/tests/test_tutorial/test_schema_extra_example/test_tutorial002.py
@@ -3,14 +3,14 @@ import importlib
import pytest
from fastapi.testclient import TestClient
-from ...utils import needs_py310, needs_pydanticv1
+from ...utils import needs_py310
@pytest.fixture(
name="client",
params=[
- "tutorial001_pv1",
- pytest.param("tutorial001_pv1_py310", marks=needs_py310),
+ pytest.param("tutorial002_py39"),
+ pytest.param("tutorial002_py310", marks=needs_py310),
],
)
def get_client(request: pytest.FixtureRequest):
@@ -20,7 +20,6 @@ def get_client(request: pytest.FixtureRequest):
return client
-@needs_pydanticv1
def test_post_body_example(client: TestClient):
response = client.put(
"/items/5",
@@ -34,7 +33,6 @@ def test_post_body_example(client: TestClient):
assert response.status_code == 200
-@needs_pydanticv1
def test_openapi_schema(client: TestClient):
response = client.get("/openapi.json")
assert response.status_code == 200, response.text
@@ -49,19 +47,19 @@ def test_openapi_schema(client: TestClient):
"operationId": "update_item_items__item_id__put",
"parameters": [
{
- "required": True,
- "schema": {"type": "integer", "title": "Item Id"},
"name": "item_id",
"in": "path",
+ "required": True,
+ "schema": {"type": "integer", "title": "Item Id"},
}
],
"requestBody": {
+ "required": True,
"content": {
"application/json": {
"schema": {"$ref": "#/components/schemas/Item"}
}
},
- "required": True,
},
"responses": {
"200": {
@@ -97,22 +95,30 @@ def test_openapi_schema(client: TestClient):
},
"Item": {
"properties": {
- "name": {"type": "string", "title": "Name"},
- "description": {"type": "string", "title": "Description"},
- "price": {"type": "number", "title": "Price"},
- "tax": {"type": "number", "title": "Tax"},
+ "name": {
+ "type": "string",
+ "title": "Name",
+ "examples": ["Foo"],
+ },
+ "description": {
+ "anyOf": [{"type": "string"}, {"type": "null"}],
+ "title": "Description",
+ "examples": ["A very nice Item"],
+ },
+ "price": {
+ "type": "number",
+ "title": "Price",
+ "examples": [35.4],
+ },
+ "tax": {
+ "anyOf": [{"type": "number"}, {"type": "null"}],
+ "title": "Tax",
+ "examples": [3.2],
+ },
},
"type": "object",
"required": ["name", "price"],
"title": "Item",
- "examples": [
- {
- "name": "Foo",
- "description": "A very nice Item",
- "price": 35.4,
- "tax": 3.2,
- }
- ],
},
"ValidationError": {
"properties": {
diff --git a/tests/test_tutorial/test_schema_extra_example/test_tutorial003.py b/tests/test_tutorial/test_schema_extra_example/test_tutorial003.py
new file mode 100644
index 0000000000..3529a9bf02
--- /dev/null
+++ b/tests/test_tutorial/test_schema_extra_example/test_tutorial003.py
@@ -0,0 +1,143 @@
+import importlib
+
+import pytest
+from fastapi.testclient import TestClient
+
+from ...utils import needs_py310
+
+
+@pytest.fixture(
+ name="client",
+ params=[
+ pytest.param("tutorial003_py39"),
+ pytest.param("tutorial003_py310", marks=needs_py310),
+ pytest.param("tutorial003_an_py39"),
+ pytest.param("tutorial003_an_py310", marks=needs_py310),
+ ],
+)
+def get_client(request: pytest.FixtureRequest):
+ mod = importlib.import_module(f"docs_src.schema_extra_example.{request.param}")
+
+ client = TestClient(mod.app)
+ return client
+
+
+def test_post_body_example(client: TestClient):
+ response = client.put(
+ "/items/5",
+ json={
+ "name": "Foo",
+ "description": "A very nice Item",
+ "price": 35.4,
+ "tax": 3.2,
+ },
+ )
+ assert response.status_code == 200
+
+
+def test_openapi_schema(client: TestClient):
+ response = client.get("/openapi.json")
+ assert response.status_code == 200, response.text
+ # insert_assert(response.json())
+ assert response.json() == {
+ "openapi": "3.1.0",
+ "info": {"title": "FastAPI", "version": "0.1.0"},
+ "paths": {
+ "/items/{item_id}": {
+ "put": {
+ "summary": "Update Item",
+ "operationId": "update_item_items__item_id__put",
+ "parameters": [
+ {
+ "name": "item_id",
+ "in": "path",
+ "required": True,
+ "schema": {"type": "integer", "title": "Item Id"},
+ }
+ ],
+ "requestBody": {
+ "required": True,
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/Item",
+ "examples": [
+ {
+ "description": "A very nice Item",
+ "name": "Foo",
+ "price": 35.4,
+ "tax": 3.2,
+ }
+ ],
+ },
+ }
+ },
+ },
+ "responses": {
+ "200": {
+ "description": "Successful Response",
+ "content": {"application/json": {"schema": {}}},
+ },
+ "422": {
+ "description": "Validation Error",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/HTTPValidationError"
+ }
+ }
+ },
+ },
+ },
+ }
+ }
+ },
+ "components": {
+ "schemas": {
+ "HTTPValidationError": {
+ "properties": {
+ "detail": {
+ "items": {"$ref": "#/components/schemas/ValidationError"},
+ "type": "array",
+ "title": "Detail",
+ }
+ },
+ "type": "object",
+ "title": "HTTPValidationError",
+ },
+ "Item": {
+ "properties": {
+ "name": {"type": "string", "title": "Name"},
+ "description": {
+ "anyOf": [{"type": "string"}, {"type": "null"}],
+ "title": "Description",
+ },
+ "price": {"type": "number", "title": "Price"},
+ "tax": {
+ "anyOf": [{"type": "number"}, {"type": "null"}],
+ "title": "Tax",
+ },
+ },
+ "type": "object",
+ "required": ["name", "price"],
+ "title": "Item",
+ },
+ "ValidationError": {
+ "properties": {
+ "loc": {
+ "items": {
+ "anyOf": [{"type": "string"}, {"type": "integer"}]
+ },
+ "type": "array",
+ "title": "Location",
+ },
+ "msg": {"type": "string", "title": "Message"},
+ "type": {"type": "string", "title": "Error Type"},
+ },
+ "type": "object",
+ "required": ["loc", "msg", "type"],
+ "title": "ValidationError",
+ },
+ }
+ },
+ }
diff --git a/tests/test_tutorial/test_schema_extra_example/test_tutorial004.py b/tests/test_tutorial/test_schema_extra_example/test_tutorial004.py
index 61aefd12a8..9326e06290 100644
--- a/tests/test_tutorial/test_schema_extra_example/test_tutorial004.py
+++ b/tests/test_tutorial/test_schema_extra_example/test_tutorial004.py
@@ -1,19 +1,17 @@
import importlib
import pytest
-from dirty_equals import IsDict
from fastapi.testclient import TestClient
-from ...utils import needs_py39, needs_py310
+from ...utils import needs_py310
@pytest.fixture(
name="client",
params=[
- "tutorial004",
+ pytest.param("tutorial004_py39"),
pytest.param("tutorial004_py310", marks=needs_py310),
- "tutorial004_an",
- pytest.param("tutorial004_an_py39", marks=needs_py39),
+ pytest.param("tutorial004_an_py39"),
pytest.param("tutorial004_an_py310", marks=needs_py310),
],
)
@@ -59,46 +57,22 @@ def test_openapi_schema(client: TestClient):
"requestBody": {
"content": {
"application/json": {
- "schema": IsDict(
- {
- "$ref": "#/components/schemas/Item",
- "examples": [
- {
- "name": "Foo",
- "description": "A very nice Item",
- "price": 35.4,
- "tax": 3.2,
- },
- {"name": "Bar", "price": "35.4"},
- {
- "name": "Baz",
- "price": "thirty five point four",
- },
- ],
- }
- )
- | IsDict(
- # TODO: remove when deprecating Pydantic v1
- {
- "allOf": [
- {"$ref": "#/components/schemas/Item"}
- ],
- "title": "Item",
- "examples": [
- {
- "name": "Foo",
- "description": "A very nice Item",
- "price": 35.4,
- "tax": 3.2,
- },
- {"name": "Bar", "price": "35.4"},
- {
- "name": "Baz",
- "price": "thirty five point four",
- },
- ],
- }
- )
+ "schema": {
+ "$ref": "#/components/schemas/Item",
+ "examples": [
+ {
+ "name": "Foo",
+ "description": "A very nice Item",
+ "price": 35.4,
+ "tax": 3.2,
+ },
+ {"name": "Bar", "price": "35.4"},
+ {
+ "name": "Baz",
+ "price": "thirty five point four",
+ },
+ ],
+ }
}
},
"required": True,
@@ -141,27 +115,15 @@ def test_openapi_schema(client: TestClient):
"type": "object",
"properties": {
"name": {"title": "Name", "type": "string"},
- "description": IsDict(
- {
- "title": "Description",
- "anyOf": [{"type": "string"}, {"type": "null"}],
- }
- )
- | IsDict(
- # TODO: remove when deprecating Pydantic v1
- {"title": "Description", "type": "string"}
- ),
+ "description": {
+ "title": "Description",
+ "anyOf": [{"type": "string"}, {"type": "null"}],
+ },
"price": {"title": "Price", "type": "number"},
- "tax": IsDict(
- {
- "title": "Tax",
- "anyOf": [{"type": "number"}, {"type": "null"}],
- }
- )
- | IsDict(
- # TODO: remove when deprecating Pydantic v1
- {"title": "Tax", "type": "number"}
- ),
+ "tax": {
+ "title": "Tax",
+ "anyOf": [{"type": "number"}, {"type": "null"}],
+ },
},
},
"ValidationError": {
diff --git a/tests/test_tutorial/test_schema_extra_example/test_tutorial005.py b/tests/test_tutorial/test_schema_extra_example/test_tutorial005.py
index 12859227b1..2d0dee48ca 100644
--- a/tests/test_tutorial/test_schema_extra_example/test_tutorial005.py
+++ b/tests/test_tutorial/test_schema_extra_example/test_tutorial005.py
@@ -1,19 +1,17 @@
import importlib
import pytest
-from dirty_equals import IsDict
from fastapi.testclient import TestClient
-from ...utils import needs_py39, needs_py310
+from ...utils import needs_py310
@pytest.fixture(
name="client",
params=[
- "tutorial005",
+ pytest.param("tutorial005_py39"),
pytest.param("tutorial005_py310", marks=needs_py310),
- "tutorial005_an",
- pytest.param("tutorial005_an_py39", marks=needs_py39),
+ pytest.param("tutorial005_an_py39"),
pytest.param("tutorial005_an_py310", marks=needs_py310),
],
)
@@ -59,16 +57,7 @@ def test_openapi_schema(client: TestClient) -> None:
"requestBody": {
"content": {
"application/json": {
- "schema": IsDict({"$ref": "#/components/schemas/Item"})
- | IsDict(
- # TODO: remove when deprecating Pydantic v1
- {
- "allOf": [
- {"$ref": "#/components/schemas/Item"}
- ],
- "title": "Item",
- }
- ),
+ "schema": {"$ref": "#/components/schemas/Item"},
"examples": {
"normal": {
"summary": "A normal example",
@@ -135,27 +124,15 @@ def test_openapi_schema(client: TestClient) -> None:
"type": "object",
"properties": {
"name": {"title": "Name", "type": "string"},
- "description": IsDict(
- {
- "title": "Description",
- "anyOf": [{"type": "string"}, {"type": "null"}],
- }
- )
- | IsDict(
- # TODO: remove when deprecating Pydantic v1
- {"title": "Description", "type": "string"}
- ),
+ "description": {
+ "title": "Description",
+ "anyOf": [{"type": "string"}, {"type": "null"}],
+ },
"price": {"title": "Price", "type": "number"},
- "tax": IsDict(
- {
- "title": "Tax",
- "anyOf": [{"type": "number"}, {"type": "null"}],
- }
- )
- | IsDict(
- # TODO: remove when deprecating Pydantic v1
- {"title": "Tax", "type": "number"}
- ),
+ "tax": {
+ "title": "Tax",
+ "anyOf": [{"type": "number"}, {"type": "null"}],
+ },
},
},
"ValidationError": {
diff --git a/tests/test_tutorial/test_security/test_tutorial001.py b/tests/test_tutorial/test_security/test_tutorial001.py
index f572d6e3e1..cdaa50b191 100644
--- a/tests/test_tutorial/test_security/test_tutorial001.py
+++ b/tests/test_tutorial/test_security/test_tutorial001.py
@@ -3,15 +3,12 @@ import importlib
import pytest
from fastapi.testclient import TestClient
-from ...utils import needs_py39
-
@pytest.fixture(
name="client",
params=[
- "tutorial001",
- "tutorial001_an",
- pytest.param("tutorial001_an_py39", marks=needs_py39),
+ pytest.param("tutorial001_py39"),
+ pytest.param("tutorial001_an_py39"),
],
)
def get_client(request: pytest.FixtureRequest):
diff --git a/tests/test_tutorial/test_security/test_tutorial002.py b/tests/test_tutorial/test_security/test_tutorial002.py
new file mode 100644
index 0000000000..85c076b1d2
--- /dev/null
+++ b/tests/test_tutorial/test_security/test_tutorial002.py
@@ -0,0 +1,71 @@
+import importlib
+
+import pytest
+from fastapi.testclient import TestClient
+
+from ...utils import needs_py310
+
+
+@pytest.fixture(
+ name="client",
+ params=[
+ pytest.param("tutorial002_py39"),
+ pytest.param("tutorial002_py310", marks=needs_py310),
+ pytest.param("tutorial002_an_py39"),
+ pytest.param("tutorial002_an_py310", marks=needs_py310),
+ ],
+)
+def get_client(request: pytest.FixtureRequest):
+ mod = importlib.import_module(f"docs_src.security.{request.param}")
+ client = TestClient(mod.app)
+ return client
+
+
+def test_no_token(client: TestClient):
+ response = client.get("/users/me")
+ assert response.status_code == 401, response.text
+ assert response.json() == {"detail": "Not authenticated"}
+ assert response.headers["WWW-Authenticate"] == "Bearer"
+
+
+def test_token(client: TestClient):
+ response = client.get("/users/me", headers={"Authorization": "Bearer testtoken"})
+ assert response.status_code == 200, response.text
+ assert response.json() == {
+ "username": "testtokenfakedecoded",
+ "email": "john@example.com",
+ "full_name": "John Doe",
+ "disabled": None,
+ }
+
+
+def test_openapi_schema(client: TestClient):
+ response = client.get("/openapi.json")
+ assert response.status_code == 200, response.text
+ assert response.json() == {
+ "openapi": "3.1.0",
+ "info": {"title": "FastAPI", "version": "0.1.0"},
+ "paths": {
+ "/users/me": {
+ "get": {
+ "responses": {
+ "200": {
+ "description": "Successful Response",
+ "content": {"application/json": {"schema": {}}},
+ }
+ },
+ "summary": "Read Users Me",
+ "operationId": "read_users_me_users_me_get",
+ "security": [{"OAuth2PasswordBearer": []}],
+ }
+ }
+ },
+ "components": {
+ "securitySchemes": {
+ "OAuth2PasswordBearer": {
+ "type": "oauth2",
+ "flows": {"password": {"scopes": {}, "tokenUrl": "token"}},
+ }
+ },
+ },
+ }
diff --git a/tests/test_tutorial/test_security/test_tutorial003.py b/tests/test_tutorial/test_security/test_tutorial003.py
index 6b87351139..6a786348cf 100644
--- a/tests/test_tutorial/test_security/test_tutorial003.py
+++ b/tests/test_tutorial/test_security/test_tutorial003.py
@@ -1,19 +1,17 @@
import importlib
import pytest
-from dirty_equals import IsDict
from fastapi.testclient import TestClient
-from ...utils import needs_py39, needs_py310
+from ...utils import needs_py310
@pytest.fixture(
name="client",
params=[
- "tutorial003",
+ pytest.param("tutorial003_py39"),
pytest.param("tutorial003_py310", marks=needs_py310),
- "tutorial003_an",
- pytest.param("tutorial003_an_py39", marks=needs_py39),
+ pytest.param("tutorial003_an_py39"),
pytest.param("tutorial003_an_py310", marks=needs_py310),
],
)
@@ -145,23 +143,13 @@ def test_openapi_schema(client: TestClient):
"required": ["username", "password"],
"type": "object",
"properties": {
- "grant_type": IsDict(
- {
- "title": "Grant Type",
- "anyOf": [
- {"pattern": "^password$", "type": "string"},
- {"type": "null"},
- ],
- }
- )
- | IsDict(
- # TODO: remove when deprecating Pydantic v1
- {
- "title": "Grant Type",
- "pattern": "^password$",
- "type": "string",
- }
- ),
+ "grant_type": {
+ "title": "Grant Type",
+ "anyOf": [
+ {"pattern": "^password$", "type": "string"},
+ {"type": "null"},
+ ],
+ },
"username": {"title": "Username", "type": "string"},
"password": {
"title": "Password",
@@ -169,31 +157,15 @@ def test_openapi_schema(client: TestClient):
"format": "password",
},
"scope": {"title": "Scope", "type": "string", "default": ""},
- "client_id": IsDict(
- {
- "title": "Client Id",
- "anyOf": [{"type": "string"}, {"type": "null"}],
- }
- )
- | IsDict(
- # TODO: remove when deprecating Pydantic v1
- {"title": "Client Id", "type": "string"}
- ),
- "client_secret": IsDict(
- {
- "title": "Client Secret",
- "anyOf": [{"type": "string"}, {"type": "null"}],
- "format": "password",
- }
- )
- | IsDict(
- # TODO: remove when deprecating Pydantic v1
- {
- "title": "Client Secret",
- "type": "string",
- "format": "password",
- }
- ),
+ "client_id": {
+ "title": "Client Id",
+ "anyOf": [{"type": "string"}, {"type": "null"}],
+ },
+ "client_secret": {
+ "title": "Client Secret",
+ "anyOf": [{"type": "string"}, {"type": "null"}],
+ "format": "password",
+ },
},
},
"ValidationError": {
diff --git a/tests/test_tutorial/test_security/test_tutorial004.py b/tests/test_tutorial/test_security/test_tutorial004.py
new file mode 100644
index 0000000000..b5e3d39ef7
--- /dev/null
+++ b/tests/test_tutorial/test_security/test_tutorial004.py
@@ -0,0 +1,363 @@
+import importlib
+from types import ModuleType
+from unittest.mock import patch
+
+import pytest
+from fastapi.testclient import TestClient
+
+from ...utils import needs_py310
+
+
+@pytest.fixture(
+ name="mod",
+ params=[
+ pytest.param("tutorial004_py39"),
+ pytest.param("tutorial004_py310", marks=needs_py310),
+ pytest.param("tutorial004_an_py39"),
+ pytest.param("tutorial004_an_py310", marks=needs_py310),
+ ],
+)
+def get_mod(request: pytest.FixtureRequest):
+ mod = importlib.import_module(f"docs_src.security.{request.param}")
+
+ return mod
+
+
+def get_access_token(*, username="johndoe", password="secret", client: TestClient):
+ data = {"username": username, "password": password}
+ response = client.post("/token", data=data)
+ content = response.json()
+ access_token = content.get("access_token")
+ return access_token
+
+
+def test_login(mod: ModuleType):
+ client = TestClient(mod.app)
+ response = client.post("/token", data={"username": "johndoe", "password": "secret"})
+ assert response.status_code == 200, response.text
+ content = response.json()
+ assert "access_token" in content
+ assert content["token_type"] == "bearer"
+
+
+def test_login_incorrect_password(mod: ModuleType):
+ client = TestClient(mod.app)
+ response = client.post(
+ "/token", data={"username": "johndoe", "password": "incorrect"}
+ )
+ assert response.status_code == 401, response.text
+ assert response.json() == {"detail": "Incorrect username or password"}
+
+
+def test_login_incorrect_username(mod: ModuleType):
+ client = TestClient(mod.app)
+ response = client.post("/token", data={"username": "foo", "password": "secret"})
+ assert response.status_code == 401, response.text
+ assert response.json() == {"detail": "Incorrect username or password"}
+
+
+def test_no_token(mod: ModuleType):
+ client = TestClient(mod.app)
+ response = client.get("/users/me")
+ assert response.status_code == 401, response.text
+ assert response.json() == {"detail": "Not authenticated"}
+ assert response.headers["WWW-Authenticate"] == "Bearer"
+
+
+def test_token(mod: ModuleType):
+ client = TestClient(mod.app)
+ access_token = get_access_token(client=client)
+ response = client.get(
+ "/users/me", headers={"Authorization": f"Bearer {access_token}"}
+ )
+ assert response.status_code == 200, response.text
+ assert response.json() == {
+ "username": "johndoe",
+ "full_name": "John Doe",
+ "email": "johndoe@example.com",
+ "disabled": False,
+ }
+
+
+def test_incorrect_token(mod: ModuleType):
+ client = TestClient(mod.app)
+ response = client.get("/users/me", headers={"Authorization": "Bearer nonexistent"})
+ assert response.status_code == 401, response.text
+ assert response.json() == {"detail": "Could not validate credentials"}
+ assert response.headers["WWW-Authenticate"] == "Bearer"
+
+
+def test_incorrect_token_type(mod: ModuleType):
+ client = TestClient(mod.app)
+ response = client.get(
+ "/users/me", headers={"Authorization": "Notexistent testtoken"}
+ )
+ assert response.status_code == 401, response.text
+ assert response.json() == {"detail": "Not authenticated"}
+ assert response.headers["WWW-Authenticate"] == "Bearer"
+
+
+def test_verify_password(mod: ModuleType):
+ assert mod.verify_password(
+ "secret", mod.fake_users_db["johndoe"]["hashed_password"]
+ )
+
+
+def test_get_password_hash(mod: ModuleType):
+ assert mod.get_password_hash("johndoe")
+
+
+def test_create_access_token(mod: ModuleType):
+ access_token = mod.create_access_token(data={"data": "foo"})
+ assert access_token
+
+
+def test_token_no_sub(mod: ModuleType):
+ client = TestClient(mod.app)
+
+ response = client.get(
+ "/users/me",
+ headers={
+ "Authorization": "Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJkYXRhIjoiZm9vIn0.9ynBhuYb4e6aW3oJr_K_TBgwcMTDpRToQIE25L57rOE"
+ },
+ )
+ assert response.status_code == 401, response.text
+ assert response.json() == {"detail": "Could not validate credentials"}
+ assert response.headers["WWW-Authenticate"] == "Bearer"
+
+
+def test_token_no_username(mod: ModuleType):
+ client = TestClient(mod.app)
+
+ response = client.get(
+ "/users/me",
+ headers={
+ "Authorization": "Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiJmb28ifQ.NnExK_dlNAYyzACrXtXDrcWOgGY2JuPbI4eDaHdfK5Y"
+ },
+ )
+ assert response.status_code == 401, response.text
+ assert response.json() == {"detail": "Could not validate credentials"}
+ assert response.headers["WWW-Authenticate"] == "Bearer"
+
+
+def test_token_nonexistent_user(mod: ModuleType):
+ client = TestClient(mod.app)
+
+ response = client.get(
+ "/users/me",
+ headers={
+ "Authorization": "Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiJ1c2VybmFtZTpib2IifQ.HcfCW67Uda-0gz54ZWTqmtgJnZeNem0Q757eTa9EZuw"
+ },
+ )
+ assert response.status_code == 401, response.text
+ assert response.json() == {"detail": "Could not validate credentials"}
+ assert response.headers["WWW-Authenticate"] == "Bearer"
+
+
+def test_token_inactive_user(mod: ModuleType):
+ client = TestClient(mod.app)
+ alice_user_data = {
+ "username": "alice",
+ "full_name": "Alice Wonderson",
+ "email": "alice@example.com",
+ "hashed_password": mod.get_password_hash("secretalice"),
+ "disabled": True,
+ }
+ with patch.dict(f"{mod.__name__}.fake_users_db", {"alice": alice_user_data}):
+ access_token = get_access_token(
+ username="alice", password="secretalice", client=client
+ )
+ response = client.get(
+ "/users/me", headers={"Authorization": f"Bearer {access_token}"}
+ )
+ assert response.status_code == 400, response.text
+ assert response.json() == {"detail": "Inactive user"}
+
+
+def test_read_items(mod: ModuleType):
+ client = TestClient(mod.app)
+ access_token = get_access_token(client=client)
+ response = client.get(
+ "/users/me/items/", headers={"Authorization": f"Bearer {access_token}"}
+ )
+ assert response.status_code == 200, response.text
+ assert response.json() == [{"item_id": "Foo", "owner": "johndoe"}]
+
+
+def test_openapi_schema(mod: ModuleType):
+ client = TestClient(mod.app)
+ response = client.get("/openapi.json")
+ assert response.status_code == 200, response.text
+ assert response.json() == {
+ "openapi": "3.1.0",
+ "info": {"title": "FastAPI", "version": "0.1.0"},
+ "paths": {
+ "/token": {
+ "post": {
+ "responses": {
+ "200": {
+ "description": "Successful Response",
+ "content": {
+ "application/json": {
+ "schema": {"$ref": "#/components/schemas/Token"}
+ }
+ },
+ },
+ "422": {
+ "description": "Validation Error",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/HTTPValidationError"
+ }
+ }
+ },
+ },
+ },
+ "summary": "Login For Access Token",
+ "operationId": "login_for_access_token_token_post",
+ "requestBody": {
+ "content": {
+ "application/x-www-form-urlencoded": {
+ "schema": {
+ "$ref": "#/components/schemas/Body_login_for_access_token_token_post"
+ }
+ }
+ },
+ "required": True,
+ },
+ }
+ },
+ "/users/me/": {
+ "get": {
+ "responses": {
+ "200": {
+ "description": "Successful Response",
+ "content": {
+ "application/json": {
+ "schema": {"$ref": "#/components/schemas/User"}
+ }
+ },
+ }
+ },
+ "summary": "Read Users Me",
+ "operationId": "read_users_me_users_me__get",
+ "security": [{"OAuth2PasswordBearer": []}],
+ }
+ },
+ "/users/me/items/": {
+ "get": {
+ "responses": {
+ "200": {
+ "description": "Successful Response",
+ "content": {"application/json": {"schema": {}}},
+ }
+ },
+ "summary": "Read Own Items",
+ "operationId": "read_own_items_users_me_items__get",
+ "security": [{"OAuth2PasswordBearer": []}],
+ }
+ },
+ },
+ "components": {
+ "schemas": {
+ "User": {
+ "title": "User",
+ "required": ["username"],
+ "type": "object",
+ "properties": {
+ "username": {"title": "Username", "type": "string"},
+ "email": {
+ "title": "Email",
+ "anyOf": [{"type": "string"}, {"type": "null"}],
+ },
+ "full_name": {
+ "title": "Full Name",
+ "anyOf": [{"type": "string"}, {"type": "null"}],
+ },
+ "disabled": {
+ "title": "Disabled",
+ "anyOf": [{"type": "boolean"}, {"type": "null"}],
+ },
+ },
+ },
+ "Token": {
+ "title": "Token",
+ "required": ["access_token", "token_type"],
+ "type": "object",
+ "properties": {
+ "access_token": {"title": "Access Token", "type": "string"},
+ "token_type": {"title": "Token Type", "type": "string"},
+ },
+ },
+ "Body_login_for_access_token_token_post": {
+ "title": "Body_login_for_access_token_token_post",
+ "required": ["username", "password"],
+ "type": "object",
+ "properties": {
+ "grant_type": {
+ "title": "Grant Type",
+ "anyOf": [
+ {"pattern": "^password$", "type": "string"},
+ {"type": "null"},
+ ],
+ },
+ "username": {"title": "Username", "type": "string"},
+ "password": {
+ "title": "Password",
+ "type": "string",
+ "format": "password",
+ },
+ "scope": {"title": "Scope", "type": "string", "default": ""},
+ "client_id": {
+ "title": "Client Id",
+ "anyOf": [{"type": "string"}, {"type": "null"}],
+ },
+ "client_secret": {
+ "title": "Client Secret",
+ "anyOf": [{"type": "string"}, {"type": "null"}],
+ "format": "password",
+ },
+ },
+ },
+ "ValidationError": {
+ "title": "ValidationError",
+ "required": ["loc", "msg", "type"],
+ "type": "object",
+ "properties": {
+ "loc": {
+ "title": "Location",
+ "type": "array",
+ "items": {
+ "anyOf": [{"type": "string"}, {"type": "integer"}]
+ },
+ },
+ "msg": {"title": "Message", "type": "string"},
+ "type": {"title": "Error Type", "type": "string"},
+ },
+ },
+ "HTTPValidationError": {
+ "title": "HTTPValidationError",
+ "type": "object",
+ "properties": {
+ "detail": {
+ "title": "Detail",
+ "type": "array",
+ "items": {"$ref": "#/components/schemas/ValidationError"},
+ }
+ },
+ },
+ },
+ "securitySchemes": {
+ "OAuth2PasswordBearer": {
+ "type": "oauth2",
+ "flows": {
+ "password": {
+ "scopes": {},
+ "tokenUrl": "token",
+ }
+ },
+ }
+ },
+ },
+ }
diff --git a/tests/test_tutorial/test_security/test_tutorial005.py b/tests/test_tutorial/test_security/test_tutorial005.py
index ad644d61bb..25b47f0adc 100644
--- a/tests/test_tutorial/test_security/test_tutorial005.py
+++ b/tests/test_tutorial/test_security/test_tutorial005.py
@@ -2,20 +2,18 @@ import importlib
from types import ModuleType
import pytest
-from dirty_equals import IsDict, IsOneOf
from fastapi.testclient import TestClient
+from inline_snapshot import snapshot
-from ...utils import needs_py39, needs_py310
+from ...utils import needs_py310
@pytest.fixture(
name="mod",
params=[
- "tutorial005",
+ pytest.param("tutorial005_py39"),
pytest.param("tutorial005_py310", marks=needs_py310),
- "tutorial005_an",
- pytest.param("tutorial005_py39", marks=needs_py39),
- pytest.param("tutorial005_an_py39", marks=needs_py39),
+ pytest.param("tutorial005_an_py39"),
pytest.param("tutorial005_an_py310", marks=needs_py310),
],
)
@@ -217,240 +215,200 @@ def test_openapi_schema(mod: ModuleType):
client = TestClient(mod.app)
response = client.get("/openapi.json")
assert response.status_code == 200, response.text
- assert response.json() == {
- "openapi": "3.1.0",
- "info": {"title": "FastAPI", "version": "0.1.0"},
- "paths": {
- "/token": {
- "post": {
- "responses": {
- "200": {
- "description": "Successful Response",
- "content": {
- "application/json": {
- "schema": {"$ref": "#/components/schemas/Token"}
- }
+ assert response.json() == snapshot(
+ {
+ "openapi": "3.1.0",
+ "info": {"title": "FastAPI", "version": "0.1.0"},
+ "paths": {
+ "/token": {
+ "post": {
+ "responses": {
+ "200": {
+ "description": "Successful Response",
+ "content": {
+ "application/json": {
+ "schema": {"$ref": "#/components/schemas/Token"}
+ }
+ },
+ },
+ "422": {
+ "description": "Validation Error",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/HTTPValidationError"
+ }
+ }
+ },
},
},
- "422": {
- "description": "Validation Error",
+ "summary": "Login For Access Token",
+ "operationId": "login_for_access_token_token_post",
+ "requestBody": {
"content": {
- "application/json": {
+ "application/x-www-form-urlencoded": {
"schema": {
- "$ref": "#/components/schemas/HTTPValidationError"
+ "$ref": "#/components/schemas/Body_login_for_access_token_token_post"
}
}
},
+ "required": True,
},
- },
- "summary": "Login For Access Token",
- "operationId": "login_for_access_token_token_post",
- "requestBody": {
- "content": {
- "application/x-www-form-urlencoded": {
- "schema": {
- "$ref": "#/components/schemas/Body_login_for_access_token_token_post"
- }
+ }
+ },
+ "/users/me/": {
+ "get": {
+ "responses": {
+ "200": {
+ "description": "Successful Response",
+ "content": {
+ "application/json": {
+ "schema": {"$ref": "#/components/schemas/User"}
+ }
+ },
}
},
- "required": True,
- },
- }
+ "summary": "Read Users Me",
+ "operationId": "read_users_me_users_me__get",
+ "security": [{"OAuth2PasswordBearer": ["me"]}],
+ }
+ },
+ "/users/me/items/": {
+ "get": {
+ "responses": {
+ "200": {
+ "description": "Successful Response",
+ "content": {"application/json": {"schema": {}}},
+ }
+ },
+ "summary": "Read Own Items",
+ "operationId": "read_own_items_users_me_items__get",
+ "security": [{"OAuth2PasswordBearer": ["items", "me"]}],
+ }
+ },
+ "/status/": {
+ "get": {
+ "responses": {
+ "200": {
+ "description": "Successful Response",
+ "content": {"application/json": {"schema": {}}},
+ }
+ },
+ "summary": "Read System Status",
+ "operationId": "read_system_status_status__get",
+ "security": [{"OAuth2PasswordBearer": []}],
+ }
+ },
},
- "/users/me/": {
- "get": {
- "responses": {
- "200": {
- "description": "Successful Response",
- "content": {
- "application/json": {
- "schema": {"$ref": "#/components/schemas/User"}
- }
- },
- }
- },
- "summary": "Read Users Me",
- "operationId": "read_users_me_users_me__get",
- "security": [{"OAuth2PasswordBearer": ["me"]}],
- }
- },
- "/users/me/items/": {
- "get": {
- "responses": {
- "200": {
- "description": "Successful Response",
- "content": {"application/json": {"schema": {}}},
- }
- },
- "summary": "Read Own Items",
- "operationId": "read_own_items_users_me_items__get",
- "security": [{"OAuth2PasswordBearer": ["items", "me"]}],
- }
- },
- "/status/": {
- "get": {
- "responses": {
- "200": {
- "description": "Successful Response",
- "content": {"application/json": {"schema": {}}},
- }
- },
- "summary": "Read System Status",
- "operationId": "read_system_status_status__get",
- "security": [{"OAuth2PasswordBearer": []}],
- }
- },
- },
- "components": {
- "schemas": {
- "User": {
- "title": "User",
- "required": IsOneOf(
- ["username", "email", "full_name", "disabled"],
- # TODO: remove when deprecating Pydantic v1
- ["username"],
- ),
- "type": "object",
- "properties": {
- "username": {"title": "Username", "type": "string"},
- "email": IsDict(
- {
+ "components": {
+ "schemas": {
+ "User": {
+ "title": "User",
+ "required": ["username"],
+ "type": "object",
+ "properties": {
+ "username": {"title": "Username", "type": "string"},
+ "email": {
"title": "Email",
"anyOf": [{"type": "string"}, {"type": "null"}],
- }
- )
- | IsDict(
- # TODO: remove when deprecating Pydantic v1
- {"title": "Email", "type": "string"}
- ),
- "full_name": IsDict(
- {
+ },
+ "full_name": {
"title": "Full Name",
"anyOf": [{"type": "string"}, {"type": "null"}],
- }
- )
- | IsDict(
- # TODO: remove when deprecating Pydantic v1
- {"title": "Full Name", "type": "string"}
- ),
- "disabled": IsDict(
- {
+ },
+ "disabled": {
"title": "Disabled",
"anyOf": [{"type": "boolean"}, {"type": "null"}],
- }
- )
- | IsDict(
- # TODO: remove when deprecating Pydantic v1
- {"title": "Disabled", "type": "boolean"}
- ),
+ },
+ },
},
- },
- "Token": {
- "title": "Token",
- "required": ["access_token", "token_type"],
- "type": "object",
- "properties": {
- "access_token": {"title": "Access Token", "type": "string"},
- "token_type": {"title": "Token Type", "type": "string"},
+ "Token": {
+ "title": "Token",
+ "required": ["access_token", "token_type"],
+ "type": "object",
+ "properties": {
+ "access_token": {"title": "Access Token", "type": "string"},
+ "token_type": {"title": "Token Type", "type": "string"},
+ },
},
- },
- "Body_login_for_access_token_token_post": {
- "title": "Body_login_for_access_token_token_post",
- "required": ["username", "password"],
- "type": "object",
- "properties": {
- "grant_type": IsDict(
- {
+ "Body_login_for_access_token_token_post": {
+ "title": "Body_login_for_access_token_token_post",
+ "required": ["username", "password"],
+ "type": "object",
+ "properties": {
+ "grant_type": {
"title": "Grant Type",
"anyOf": [
{"pattern": "^password$", "type": "string"},
{"type": "null"},
],
- }
- )
- | IsDict(
- # TODO: remove when deprecating Pydantic v1
- {
- "title": "Grant Type",
- "pattern": "^password$",
+ },
+ "username": {"title": "Username", "type": "string"},
+ "password": {
+ "title": "Password",
"type": "string",
- }
- ),
- "username": {"title": "Username", "type": "string"},
- "password": {
- "title": "Password",
- "type": "string",
- "format": "password",
- },
- "scope": {"title": "Scope", "type": "string", "default": ""},
- "client_id": IsDict(
- {
+ "format": "password",
+ },
+ "scope": {
+ "title": "Scope",
+ "type": "string",
+ "default": "",
+ },
+ "client_id": {
"title": "Client Id",
"anyOf": [{"type": "string"}, {"type": "null"}],
- }
- )
- | IsDict(
- # TODO: remove when deprecating Pydantic v1
- {"title": "Client Id", "type": "string"}
- ),
- "client_secret": IsDict(
- {
+ },
+ "client_secret": {
"title": "Client Secret",
"anyOf": [{"type": "string"}, {"type": "null"}],
"format": "password",
- }
- )
- | IsDict(
- # TODO: remove when deprecating Pydantic v1
- {
- "title": "Client Secret",
- "type": "string",
- "format": "password",
- }
- ),
- },
- },
- "ValidationError": {
- "title": "ValidationError",
- "required": ["loc", "msg", "type"],
- "type": "object",
- "properties": {
- "loc": {
- "title": "Location",
- "type": "array",
- "items": {
- "anyOf": [{"type": "string"}, {"type": "integer"}]
},
},
- "msg": {"title": "Message", "type": "string"},
- "type": {"title": "Error Type", "type": "string"},
},
- },
- "HTTPValidationError": {
- "title": "HTTPValidationError",
- "type": "object",
- "properties": {
- "detail": {
- "title": "Detail",
- "type": "array",
- "items": {"$ref": "#/components/schemas/ValidationError"},
- }
- },
- },
- },
- "securitySchemes": {
- "OAuth2PasswordBearer": {
- "type": "oauth2",
- "flows": {
- "password": {
- "scopes": {
- "me": "Read information about the current user.",
- "items": "Read items.",
+ "ValidationError": {
+ "title": "ValidationError",
+ "required": ["loc", "msg", "type"],
+ "type": "object",
+ "properties": {
+ "loc": {
+ "title": "Location",
+ "type": "array",
+ "items": {
+ "anyOf": [{"type": "string"}, {"type": "integer"}]
+ },
},
- "tokenUrl": "token",
- }
+ "msg": {"title": "Message", "type": "string"},
+ "type": {"title": "Error Type", "type": "string"},
+ },
},
- }
+ "HTTPValidationError": {
+ "title": "HTTPValidationError",
+ "type": "object",
+ "properties": {
+ "detail": {
+ "title": "Detail",
+ "type": "array",
+ "items": {
+ "$ref": "#/components/schemas/ValidationError"
+ },
+ }
+ },
+ },
+ },
+ "securitySchemes": {
+ "OAuth2PasswordBearer": {
+ "type": "oauth2",
+ "flows": {
+ "password": {
+ "scopes": {
+ "me": "Read information about the current user.",
+ "items": "Read items.",
+ },
+ "tokenUrl": "token",
+ }
+ },
+ }
+ },
},
- },
- }
+ }
+ )
diff --git a/tests/test_tutorial/test_security/test_tutorial006.py b/tests/test_tutorial/test_security/test_tutorial006.py
index 9587159dc2..a4b3104bbc 100644
--- a/tests/test_tutorial/test_security/test_tutorial006.py
+++ b/tests/test_tutorial/test_security/test_tutorial006.py
@@ -4,15 +4,12 @@ from base64 import b64encode
import pytest
from fastapi.testclient import TestClient
-from ...utils import needs_py39
-
@pytest.fixture(
name="client",
params=[
- "tutorial006",
- "tutorial006_an",
- pytest.param("tutorial006_an_py39", marks=needs_py39),
+ pytest.param("tutorial006_py39"),
+ pytest.param("tutorial006_an_py39"),
],
)
def get_client(request: pytest.FixtureRequest):
diff --git a/tests/test_tutorial/test_security/test_tutorial007.py b/tests/test_tutorial/test_security/test_tutorial007.py
new file mode 100644
index 0000000000..28b70a2d43
--- /dev/null
+++ b/tests/test_tutorial/test_security/test_tutorial007.py
@@ -0,0 +1,89 @@
+import importlib
+from base64 import b64encode
+
+import pytest
+from fastapi.testclient import TestClient
+
+
+@pytest.fixture(
+ name="client",
+ params=[
+ pytest.param("tutorial007_py39"),
+ pytest.param("tutorial007_an_py39"),
+ ],
+)
+def get_client(request: pytest.FixtureRequest):
+ mod = importlib.import_module(f"docs_src.security.{request.param}")
+ return TestClient(mod.app)
+
+
+def test_security_http_basic(client: TestClient):
+ response = client.get("/users/me", auth=("stanleyjobson", "swordfish"))
+ assert response.status_code == 200, response.text
+ assert response.json() == {"username": "stanleyjobson"}
+
+
+def test_security_http_basic_no_credentials(client: TestClient):
+ response = client.get("/users/me")
+ assert response.json() == {"detail": "Not authenticated"}
+ assert response.status_code == 401, response.text
+ assert response.headers["WWW-Authenticate"] == "Basic"
+
+
+def test_security_http_basic_invalid_credentials(client: TestClient):
+ response = client.get(
+ "/users/me", headers={"Authorization": "Basic notabase64token"}
+ )
+ assert response.status_code == 401, response.text
+ assert response.headers["WWW-Authenticate"] == "Basic"
+ assert response.json() == {"detail": "Not authenticated"}
+
+
+def test_security_http_basic_non_basic_credentials(client: TestClient):
+ payload = b64encode(b"johnsecret").decode("ascii")
+ auth_header = f"Basic {payload}"
+ response = client.get("/users/me", headers={"Authorization": auth_header})
+ assert response.status_code == 401, response.text
+ assert response.headers["WWW-Authenticate"] == "Basic"
+ assert response.json() == {"detail": "Not authenticated"}
+
+
+def test_security_http_basic_invalid_username(client: TestClient):
+ response = client.get("/users/me", auth=("alice", "swordfish"))
+ assert response.status_code == 401, response.text
+ assert response.json() == {"detail": "Incorrect username or password"}
+ assert response.headers["WWW-Authenticate"] == "Basic"
+
+
+def test_security_http_basic_invalid_password(client: TestClient):
+ response = client.get("/users/me", auth=("stanleyjobson", "wrongpassword"))
+ assert response.status_code == 401, response.text
+ assert response.json() == {"detail": "Incorrect username or password"}
+ assert response.headers["WWW-Authenticate"] == "Basic"
+
+
+def test_openapi_schema(client: TestClient):
+ response = client.get("/openapi.json")
+ assert response.status_code == 200, response.text
+ assert response.json() == {
+ "openapi": "3.1.0",
+ "info": {"title": "FastAPI", "version": "0.1.0"},
+ "paths": {
+ "/users/me": {
+ "get": {
+ "responses": {
+ "200": {
+ "description": "Successful Response",
+ "content": {"application/json": {"schema": {}}},
+ }
+ },
+ "summary": "Read Current User",
+ "operationId": "read_current_user_users_me_get",
+ "security": [{"HTTPBasic": []}],
+ }
+ }
+ },
+ "components": {
+ "securitySchemes": {"HTTPBasic": {"type": "http", "scheme": "basic"}}
+ },
+ }
diff --git a/tests/test_tutorial/test_separate_openapi_schemas/test_tutorial001.py b/tests/test_tutorial/test_separate_openapi_schemas/test_tutorial001.py
index 059fb889b3..275b234877 100644
--- a/tests/test_tutorial/test_separate_openapi_schemas/test_tutorial001.py
+++ b/tests/test_tutorial/test_separate_openapi_schemas/test_tutorial001.py
@@ -3,15 +3,14 @@ import importlib
import pytest
from fastapi.testclient import TestClient
-from ...utils import needs_py39, needs_py310, needs_pydanticv2
+from ...utils import needs_py310
@pytest.fixture(
name="client",
params=[
- "tutorial001",
+ pytest.param("tutorial001_py39"),
pytest.param("tutorial001_py310", marks=needs_py310),
- pytest.param("tutorial001_py39", marks=needs_py39),
],
)
def get_client(request: pytest.FixtureRequest) -> TestClient:
@@ -39,7 +38,6 @@ def test_read_items(client: TestClient) -> None:
]
-@needs_pydanticv2
def test_openapi_schema(client: TestClient) -> None:
response = client.get("/openapi.json")
assert response.status_code == 200, response.text
diff --git a/tests/test_tutorial/test_separate_openapi_schemas/test_tutorial002.py b/tests/test_tutorial/test_separate_openapi_schemas/test_tutorial002.py
index cc9afeab75..8230e39226 100644
--- a/tests/test_tutorial/test_separate_openapi_schemas/test_tutorial002.py
+++ b/tests/test_tutorial/test_separate_openapi_schemas/test_tutorial002.py
@@ -3,15 +3,14 @@ import importlib
import pytest
from fastapi.testclient import TestClient
-from ...utils import needs_py39, needs_py310, needs_pydanticv2
+from ...utils import needs_py310
@pytest.fixture(
name="client",
params=[
- "tutorial002",
+ pytest.param("tutorial002_py39"),
pytest.param("tutorial002_py310", marks=needs_py310),
- pytest.param("tutorial002_py39", marks=needs_py39),
],
)
def get_client(request: pytest.FixtureRequest) -> TestClient:
@@ -39,7 +38,6 @@ def test_read_items(client: TestClient) -> None:
]
-@needs_pydanticv2
def test_openapi_schema(client: TestClient) -> None:
response = client.get("/openapi.json")
assert response.status_code == 200, response.text
diff --git a/tests/test_tutorial/test_settings/test_app01.py b/tests/test_tutorial/test_settings/test_app01.py
new file mode 100644
index 0000000000..0c5e440f1a
--- /dev/null
+++ b/tests/test_tutorial/test_settings/test_app01.py
@@ -0,0 +1,78 @@
+import importlib
+import sys
+
+import pytest
+from dirty_equals import IsAnyStr
+from fastapi.testclient import TestClient
+from pydantic import ValidationError
+from pytest import MonkeyPatch
+
+
+@pytest.fixture(
+ name="mod_name",
+ params=[
+ pytest.param("app01_py39"),
+ ],
+)
+def get_mod_name(request: pytest.FixtureRequest):
+ return f"docs_src.settings.{request.param}.main"
+
+
+@pytest.fixture(name="client")
+def get_test_client(mod_name: str, monkeypatch: MonkeyPatch) -> TestClient:
+ if mod_name in sys.modules:
+ del sys.modules[mod_name]
+ monkeypatch.setenv("ADMIN_EMAIL", "admin@example.com")
+ main_mod = importlib.import_module(mod_name)
+ return TestClient(main_mod.app)
+
+
+def test_settings_validation_error(mod_name: str, monkeypatch: MonkeyPatch):
+ monkeypatch.delenv("ADMIN_EMAIL", raising=False)
+ if mod_name in sys.modules:
+ del sys.modules[mod_name] # pragma: no cover
+
+ with pytest.raises(ValidationError) as exc_info:
+ importlib.import_module(mod_name)
+ assert exc_info.value.errors() == [
+ {
+ "loc": ("admin_email",),
+ "msg": "Field required",
+ "type": "missing",
+ "input": {},
+ "url": IsAnyStr,
+ }
+ ]
+
+
+def test_app(client: TestClient):
+ response = client.get("/info")
+ data = response.json()
+ assert data == {
+ "app_name": "Awesome API",
+ "admin_email": "admin@example.com",
+ "items_per_user": 50,
+ }
+
+
+def test_openapi_schema(client: TestClient):
+ response = client.get("/openapi.json")
+ assert response.status_code == 200, response.text
+ assert response.json() == {
+ "openapi": "3.1.0",
+ "info": {"title": "FastAPI", "version": "0.1.0"},
+ "paths": {
+ "/info": {
+ "get": {
+ "operationId": "info_info_get",
+ "responses": {
+ "200": {
+ "description": "Successful Response",
+ "content": {"application/json": {"schema": {}}},
+ }
+ },
+ "summary": "Info",
+ }
+ }
+ },
+ }
diff --git a/tests/test_tutorial/test_settings/test_app02.py b/tests/test_tutorial/test_settings/test_app02.py
index 5e1232ea01..9cbed4fd1b 100644
--- a/tests/test_tutorial/test_settings/test_app02.py
+++ b/tests/test_tutorial/test_settings/test_app02.py
@@ -4,15 +4,12 @@ from types import ModuleType
import pytest
from pytest import MonkeyPatch
-from ...utils import needs_py39, needs_pydanticv2
-
@pytest.fixture(
name="mod_path",
params=[
- pytest.param("app02"),
- pytest.param("app02_an"),
- pytest.param("app02_an_py39", marks=needs_py39),
+ pytest.param("app02_py39"),
+ pytest.param("app02_an_py39"),
],
)
def get_mod_path(request: pytest.FixtureRequest):
@@ -32,7 +29,6 @@ def get_test_main_mod(mod_path: str) -> ModuleType:
return test_main_mod
-@needs_pydanticv2
def test_settings(main_mod: ModuleType, monkeypatch: MonkeyPatch):
monkeypatch.setenv("ADMIN_EMAIL", "admin@example.com")
settings = main_mod.get_settings()
@@ -40,6 +36,5 @@ def test_settings(main_mod: ModuleType, monkeypatch: MonkeyPatch):
assert settings.items_per_user == 50
-@needs_pydanticv2
def test_override_settings(test_main_mod: ModuleType):
test_main_mod.test_app()
diff --git a/tests/test_tutorial/test_settings/test_app03.py b/tests/test_tutorial/test_settings/test_app03.py
index d9872c15f2..72de497967 100644
--- a/tests/test_tutorial/test_settings/test_app03.py
+++ b/tests/test_tutorial/test_settings/test_app03.py
@@ -5,15 +5,12 @@ import pytest
from fastapi.testclient import TestClient
from pytest import MonkeyPatch
-from ...utils import needs_py39, needs_pydanticv1, needs_pydanticv2
-
@pytest.fixture(
name="mod_path",
params=[
- pytest.param("app03"),
- pytest.param("app03_an"),
- pytest.param("app03_an_py39", marks=needs_py39),
+ pytest.param("app03_py39"),
+ pytest.param("app03_an_py39"),
],
)
def get_mod_path(request: pytest.FixtureRequest):
@@ -27,7 +24,6 @@ def get_main_mod(mod_path: str) -> ModuleType:
return main_mod
-@needs_pydanticv2
def test_settings(main_mod: ModuleType, monkeypatch: MonkeyPatch):
monkeypatch.setenv("ADMIN_EMAIL", "admin@example.com")
settings = main_mod.get_settings()
@@ -36,17 +32,6 @@ def test_settings(main_mod: ModuleType, monkeypatch: MonkeyPatch):
assert settings.items_per_user == 50
-@needs_pydanticv1
-def test_settings_pv1(mod_path: str, monkeypatch: MonkeyPatch):
- monkeypatch.setenv("ADMIN_EMAIL", "admin@example.com")
- config_mod = importlib.import_module(f"{mod_path}.config_pv1")
- settings = config_mod.Settings()
- assert settings.app_name == "Awesome API"
- assert settings.admin_email == "admin@example.com"
- assert settings.items_per_user == 50
-
-
-@needs_pydanticv2
def test_endpoint(main_mod: ModuleType, monkeypatch: MonkeyPatch):
monkeypatch.setenv("ADMIN_EMAIL", "admin@example.com")
client = TestClient(main_mod.app)
diff --git a/tests/test_tutorial/test_settings/test_tutorial001.py b/tests/test_tutorial/test_settings/test_tutorial001.py
index 92a5782d4d..f4576a0d21 100644
--- a/tests/test_tutorial/test_settings/test_tutorial001.py
+++ b/tests/test_tutorial/test_settings/test_tutorial001.py
@@ -4,16 +4,8 @@ import pytest
from fastapi.testclient import TestClient
from pytest import MonkeyPatch
-from ...utils import needs_pydanticv1, needs_pydanticv2
-
-@pytest.fixture(
- name="app",
- params=[
- pytest.param("tutorial001", marks=needs_pydanticv2),
- pytest.param("tutorial001_pv1", marks=needs_pydanticv1),
- ],
-)
+@pytest.fixture(name="app", params=[pytest.param("tutorial001_py39")])
def get_app(request: pytest.FixtureRequest, monkeypatch: MonkeyPatch):
monkeypatch.setenv("ADMIN_EMAIL", "admin@example.com")
mod = importlib.import_module(f"docs_src.settings.{request.param}")
diff --git a/tests/test_tutorial/test_sql_databases/test_tutorial001.py b/tests/test_tutorial/test_sql_databases/test_tutorial001.py
index b45be4884d..2c628f5257 100644
--- a/tests/test_tutorial/test_sql_databases/test_tutorial001.py
+++ b/tests/test_tutorial/test_sql_databases/test_tutorial001.py
@@ -2,14 +2,14 @@ import importlib
import warnings
import pytest
-from dirty_equals import IsDict, IsInt
+from dirty_equals import IsInt
from fastapi.testclient import TestClient
from inline_snapshot import snapshot
from sqlalchemy import StaticPool
from sqlmodel import SQLModel, create_engine
from sqlmodel.main import default_registry
-from tests.utils import needs_py39, needs_py310
+from tests.utils import needs_py310
def clear_sqlmodel():
@@ -22,11 +22,9 @@ def clear_sqlmodel():
@pytest.fixture(
name="client",
params=[
- "tutorial001",
- pytest.param("tutorial001_py39", marks=needs_py39),
+ pytest.param("tutorial001_py39"),
pytest.param("tutorial001_py310", marks=needs_py310),
- "tutorial001_an",
- pytest.param("tutorial001_an_py39", marks=needs_py39),
+ pytest.param("tutorial001_an_py39"),
pytest.param("tutorial001_an_py310", marks=needs_py310),
],
)
@@ -320,33 +318,15 @@ def test_openapi_schema(client: TestClient):
},
"Hero": {
"properties": {
- "id": IsDict(
- {
- "anyOf": [{"type": "integer"}, {"type": "null"}],
- "title": "Id",
- }
- )
- | IsDict(
- # TODO: remove when deprecating Pydantic v1
- {
- "type": "integer",
- "title": "Id",
- }
- ),
+ "id": {
+ "anyOf": [{"type": "integer"}, {"type": "null"}],
+ "title": "Id",
+ },
"name": {"type": "string", "title": "Name"},
- "age": IsDict(
- {
- "anyOf": [{"type": "integer"}, {"type": "null"}],
- "title": "Age",
- }
- )
- | IsDict(
- # TODO: remove when deprecating Pydantic v1
- {
- "type": "integer",
- "title": "Age",
- }
- ),
+ "age": {
+ "anyOf": [{"type": "integer"}, {"type": "null"}],
+ "title": "Age",
+ },
"secret_name": {"type": "string", "title": "Secret Name"},
},
"type": "object",
diff --git a/tests/test_tutorial/test_sql_databases/test_tutorial002.py b/tests/test_tutorial/test_sql_databases/test_tutorial002.py
index da0b8b7ce7..c72c16e9ae 100644
--- a/tests/test_tutorial/test_sql_databases/test_tutorial002.py
+++ b/tests/test_tutorial/test_sql_databases/test_tutorial002.py
@@ -2,14 +2,14 @@ import importlib
import warnings
import pytest
-from dirty_equals import IsDict, IsInt
+from dirty_equals import IsInt
from fastapi.testclient import TestClient
from inline_snapshot import Is, snapshot
from sqlalchemy import StaticPool
from sqlmodel import SQLModel, create_engine
from sqlmodel.main import default_registry
-from tests.utils import needs_py39, needs_py310
+from tests.utils import needs_py310
def clear_sqlmodel():
@@ -22,11 +22,9 @@ def clear_sqlmodel():
@pytest.fixture(
name="client",
params=[
- "tutorial002",
- pytest.param("tutorial002_py39", marks=needs_py39),
+ pytest.param("tutorial002_py39"),
pytest.param("tutorial002_py310", marks=needs_py310),
- "tutorial002_an",
- pytest.param("tutorial002_an_py39", marks=needs_py39),
+ pytest.param("tutorial002_an_py39"),
pytest.param("tutorial002_an_py310", marks=needs_py310),
],
)
@@ -375,19 +373,10 @@ def test_openapi_schema(client: TestClient):
"HeroCreate": {
"properties": {
"name": {"type": "string", "title": "Name"},
- "age": IsDict(
- {
- "anyOf": [{"type": "integer"}, {"type": "null"}],
- "title": "Age",
- }
- )
- | IsDict(
- # TODO: remove when deprecating Pydantic v1
- {
- "type": "integer",
- "title": "Age",
- }
- ),
+ "age": {
+ "anyOf": [{"type": "integer"}, {"type": "null"}],
+ "title": "Age",
+ },
"secret_name": {"type": "string", "title": "Secret Name"},
},
"type": "object",
@@ -397,19 +386,10 @@ def test_openapi_schema(client: TestClient):
"HeroPublic": {
"properties": {
"name": {"type": "string", "title": "Name"},
- "age": IsDict(
- {
- "anyOf": [{"type": "integer"}, {"type": "null"}],
- "title": "Age",
- }
- )
- | IsDict(
- # TODO: remove when deprecating Pydantic v1
- {
- "type": "integer",
- "title": "Age",
- }
- ),
+ "age": {
+ "anyOf": [{"type": "integer"}, {"type": "null"}],
+ "title": "Age",
+ },
"id": {"type": "integer", "title": "Id"},
},
"type": "object",
@@ -418,45 +398,18 @@ def test_openapi_schema(client: TestClient):
},
"HeroUpdate": {
"properties": {
- "name": IsDict(
- {
- "anyOf": [{"type": "string"}, {"type": "null"}],
- "title": "Name",
- }
- )
- | IsDict(
- # TODO: remove when deprecating Pydantic v1
- {
- "type": "string",
- "title": "Name",
- }
- ),
- "age": IsDict(
- {
- "anyOf": [{"type": "integer"}, {"type": "null"}],
- "title": "Age",
- }
- )
- | IsDict(
- # TODO: remove when deprecating Pydantic v1
- {
- "type": "integer",
- "title": "Age",
- }
- ),
- "secret_name": IsDict(
- {
- "anyOf": [{"type": "string"}, {"type": "null"}],
- "title": "Secret Name",
- }
- )
- | IsDict(
- # TODO: remove when deprecating Pydantic v1
- {
- "type": "string",
- "title": "Secret Name",
- }
- ),
+ "name": {
+ "anyOf": [{"type": "string"}, {"type": "null"}],
+ "title": "Name",
+ },
+ "age": {
+ "anyOf": [{"type": "integer"}, {"type": "null"}],
+ "title": "Age",
+ },
+ "secret_name": {
+ "anyOf": [{"type": "string"}, {"type": "null"}],
+ "title": "Secret Name",
+ },
},
"type": "object",
"title": "HeroUpdate",
diff --git a/tests/test_tutorial/test_static_files/__init__.py b/tests/test_tutorial/test_static_files/__init__.py
new file mode 100644
index 0000000000..e69de29bb2
diff --git a/tests/test_tutorial/test_static_files/test_tutorial001.py b/tests/test_tutorial/test_static_files/test_tutorial001.py
new file mode 100644
index 0000000000..4fbf19ae82
--- /dev/null
+++ b/tests/test_tutorial/test_static_files/test_tutorial001.py
@@ -0,0 +1,40 @@
+import os
+from pathlib import Path
+
+import pytest
+from fastapi.testclient import TestClient
+
+
+@pytest.fixture(scope="module")
+def client():
+ static_dir: Path = Path(os.getcwd()) / "static"
+ static_dir.mkdir(exist_ok=True)
+ sample_file = static_dir / "sample.txt"
+ sample_file.write_text("This is a sample static file.")
+ from docs_src.static_files.tutorial001_py39 import app
+
+ with TestClient(app) as client:
+ yield client
+ sample_file.unlink()
+ static_dir.rmdir()
+
+
+def test_static_files(client: TestClient):
+ response = client.get("/static/sample.txt")
+ assert response.status_code == 200, response.text
+ assert response.text == "This is a sample static file."
+
+
+def test_static_files_not_found(client: TestClient):
+ response = client.get("/static/non_existent_file.txt")
+ assert response.status_code == 404, response.text
+
+
+def test_openapi_schema(client: TestClient):
+ response = client.get("/openapi.json")
+ assert response.status_code == 200, response.text
+ assert response.json() == {
+ "openapi": "3.1.0",
+ "info": {"title": "FastAPI", "version": "0.1.0"},
+ "paths": {},
+ }
diff --git a/tests/test_tutorial/test_sub_applications/test_tutorial001.py b/tests/test_tutorial/test_sub_applications/test_tutorial001.py
index 0790d207be..ef1f80164b 100644
--- a/tests/test_tutorial/test_sub_applications/test_tutorial001.py
+++ b/tests/test_tutorial/test_sub_applications/test_tutorial001.py
@@ -1,6 +1,6 @@
from fastapi.testclient import TestClient
-from docs_src.sub_applications.tutorial001 import app
+from docs_src.sub_applications.tutorial001_py39 import app
client = TestClient(app)
diff --git a/tests/test_tutorial/test_templates/test_tutorial001.py b/tests/test_tutorial/test_templates/test_tutorial001.py
index 4d4729425e..818508037d 100644
--- a/tests/test_tutorial/test_templates/test_tutorial001.py
+++ b/tests/test_tutorial/test_templates/test_tutorial001.py
@@ -11,7 +11,7 @@ def test_main():
shutil.rmtree("./templates")
shutil.copytree("./docs_src/templates/templates/", "./templates")
shutil.copytree("./docs_src/templates/static/", "./static")
- from docs_src.templates.tutorial001 import app
+ from docs_src.templates.tutorial001_py39 import app
client = TestClient(app)
response = client.get("/items/foo")
diff --git a/tests/test_tutorial/test_testing/test_main.py b/tests/test_tutorial/test_testing/test_main_a.py
similarity index 90%
rename from tests/test_tutorial/test_testing/test_main.py
rename to tests/test_tutorial/test_testing/test_main_a.py
index fe34980813..9b3c796bdc 100644
--- a/tests/test_tutorial/test_testing/test_main.py
+++ b/tests/test_tutorial/test_testing/test_main_a.py
@@ -1,4 +1,4 @@
-from docs_src.app_testing.test_main import client, test_read_main
+from docs_src.app_testing.app_a_py39.test_main import client, test_read_main
def test_main():
diff --git a/tests/test_tutorial/test_testing/test_main_b.py b/tests/test_tutorial/test_testing/test_main_b.py
index aa7f969c6d..3d679cd5a6 100644
--- a/tests/test_tutorial/test_testing/test_main_b.py
+++ b/tests/test_tutorial/test_testing/test_main_b.py
@@ -3,16 +3,15 @@ from types import ModuleType
import pytest
-from ...utils import needs_py39, needs_py310
+from ...utils import needs_py310
@pytest.fixture(
name="test_module",
params=[
- "app_b.test_main",
+ "app_b_py39.test_main",
pytest.param("app_b_py310.test_main", marks=needs_py310),
- "app_b_an.test_main",
- pytest.param("app_b_an_py39.test_main", marks=needs_py39),
+ "app_b_an_py39.test_main",
pytest.param("app_b_an_py310.test_main", marks=needs_py310),
],
)
diff --git a/tests/test_tutorial/test_testing/test_tutorial001.py b/tests/test_tutorial/test_testing/test_tutorial001.py
index 471e896c93..5f6533306e 100644
--- a/tests/test_tutorial/test_testing/test_tutorial001.py
+++ b/tests/test_tutorial/test_testing/test_tutorial001.py
@@ -1,4 +1,4 @@
-from docs_src.app_testing.tutorial001 import client, test_read_main
+from docs_src.app_testing.tutorial001_py39 import client, test_read_main
def test_main():
diff --git a/tests/test_tutorial/test_testing/test_tutorial002.py b/tests/test_tutorial/test_testing/test_tutorial002.py
index ec4f91ee7f..cc9b5ba27c 100644
--- a/tests/test_tutorial/test_testing/test_tutorial002.py
+++ b/tests/test_tutorial/test_testing/test_tutorial002.py
@@ -1,4 +1,4 @@
-from docs_src.app_testing.tutorial002 import test_read_main, test_websocket
+from docs_src.app_testing.tutorial002_py39 import test_read_main, test_websocket
def test_main():
diff --git a/tests/test_tutorial/test_testing/test_tutorial003.py b/tests/test_tutorial/test_testing/test_tutorial003.py
index 2a5d670712..4faa820e98 100644
--- a/tests/test_tutorial/test_testing/test_tutorial003.py
+++ b/tests/test_tutorial/test_testing/test_tutorial003.py
@@ -3,5 +3,5 @@ import pytest
def test_main():
with pytest.warns(DeprecationWarning):
- from docs_src.app_testing.tutorial003 import test_read_items
+ from docs_src.app_testing.tutorial003_py39 import test_read_items
test_read_items()
diff --git a/tests/test_tutorial/test_testing/test_tutorial004.py b/tests/test_tutorial/test_testing/test_tutorial004.py
index 812ee44c1f..c95214ffe3 100644
--- a/tests/test_tutorial/test_testing/test_tutorial004.py
+++ b/tests/test_tutorial/test_testing/test_tutorial004.py
@@ -1,4 +1,4 @@
-from docs_src.app_testing.tutorial004 import test_read_items
+from docs_src.app_testing.tutorial004_py39 import test_read_items
def test_main():
diff --git a/tests/test_tutorial/test_testing_dependencies/test_tutorial001.py b/tests/test_tutorial/test_testing_dependencies/test_tutorial001.py
index 00ee6ab1ea..6e9656bf55 100644
--- a/tests/test_tutorial/test_testing_dependencies/test_tutorial001.py
+++ b/tests/test_tutorial/test_testing_dependencies/test_tutorial001.py
@@ -3,16 +3,15 @@ from types import ModuleType
import pytest
-from ...utils import needs_py39, needs_py310
+from ...utils import needs_py310
@pytest.fixture(
name="test_module",
params=[
- "tutorial001",
+ pytest.param("tutorial001_py39"),
pytest.param("tutorial001_py310", marks=needs_py310),
- "tutorial001_an",
- pytest.param("tutorial001_an_py39", marks=needs_py39),
+ pytest.param("tutorial001_an_py39"),
pytest.param("tutorial001_an_py310", marks=needs_py310),
],
)
diff --git a/tests/test_tutorial/test_using_request_directly/test_tutorial001.py b/tests/test_tutorial/test_using_request_directly/test_tutorial001.py
index 54c53ae1e3..33e661b164 100644
--- a/tests/test_tutorial/test_using_request_directly/test_tutorial001.py
+++ b/tests/test_tutorial/test_using_request_directly/test_tutorial001.py
@@ -1,6 +1,6 @@
from fastapi.testclient import TestClient
-from docs_src.using_request_directly.tutorial001 import app
+from docs_src.using_request_directly.tutorial001_py39 import app
client = TestClient(app)
diff --git a/tests/test_tutorial/test_websockets/test_tutorial001.py b/tests/test_tutorial/test_websockets/test_tutorial001.py
index 7dbecb2650..4f8368db28 100644
--- a/tests/test_tutorial/test_websockets/test_tutorial001.py
+++ b/tests/test_tutorial/test_websockets/test_tutorial001.py
@@ -2,7 +2,7 @@ import pytest
from fastapi.testclient import TestClient
from fastapi.websockets import WebSocketDisconnect
-from docs_src.websockets.tutorial001 import app
+from docs_src.websockets.tutorial001_py39 import app
client = TestClient(app)
diff --git a/tests/test_tutorial/test_websockets/test_tutorial002.py b/tests/test_tutorial/test_websockets/test_tutorial002.py
index 51aa5752a6..ebf1fc8e81 100644
--- a/tests/test_tutorial/test_websockets/test_tutorial002.py
+++ b/tests/test_tutorial/test_websockets/test_tutorial002.py
@@ -5,16 +5,15 @@ from fastapi import FastAPI
from fastapi.testclient import TestClient
from fastapi.websockets import WebSocketDisconnect
-from ...utils import needs_py39, needs_py310
+from ...utils import needs_py310
@pytest.fixture(
name="app",
params=[
- "tutorial002",
+ pytest.param("tutorial002_py39"),
pytest.param("tutorial002_py310", marks=needs_py310),
- "tutorial002_an",
- pytest.param("tutorial002_an_py39", marks=needs_py39),
+ pytest.param("tutorial002_an_py39"),
pytest.param("tutorial002_an_py310", marks=needs_py310),
],
)
diff --git a/tests/test_tutorial/test_websockets/test_tutorial003.py b/tests/test_tutorial/test_websockets/test_tutorial003.py
index 85efc18590..0be1fc81d6 100644
--- a/tests/test_tutorial/test_websockets/test_tutorial003.py
+++ b/tests/test_tutorial/test_websockets/test_tutorial003.py
@@ -4,14 +4,11 @@ from types import ModuleType
import pytest
from fastapi.testclient import TestClient
-from ...utils import needs_py39
-
@pytest.fixture(
name="mod",
params=[
- pytest.param("tutorial003"),
- pytest.param("tutorial003_py39", marks=needs_py39),
+ pytest.param("tutorial003_py39"),
],
)
def get_mod(request: pytest.FixtureRequest):
@@ -32,17 +29,16 @@ def get_client(mod: ModuleType):
return client
-@needs_py39
def test_get(client: TestClient, html: str):
response = client.get("/")
assert response.text == html
-@needs_py39
def test_websocket_handle_disconnection(client: TestClient):
- with client.websocket_connect("/ws/1234") as connection, client.websocket_connect(
- "/ws/5678"
- ) as connection_two:
+ with (
+ client.websocket_connect("/ws/1234") as connection,
+ client.websocket_connect("/ws/5678") as connection_two,
+ ):
connection.send_text("Hello from 1234")
data1 = connection.receive_text()
assert data1 == "You wrote: Hello from 1234"
diff --git a/tests/test_tutorial/test_wsgi/test_tutorial001.py b/tests/test_tutorial/test_wsgi/test_tutorial001.py
index 4f82252739..9fe8c2a4b8 100644
--- a/tests/test_tutorial/test_wsgi/test_tutorial001.py
+++ b/tests/test_tutorial/test_wsgi/test_tutorial001.py
@@ -1,6 +1,6 @@
from fastapi.testclient import TestClient
-from docs_src.wsgi.tutorial001 import app
+from docs_src.wsgi.tutorial001_py39 import app
client = TestClient(app)
diff --git a/tests/test_union_body.py b/tests/test_union_body.py
index c15acacd18..ee7fcc4231 100644
--- a/tests/test_union_body.py
+++ b/tests/test_union_body.py
@@ -1,6 +1,5 @@
from typing import Optional, Union
-from dirty_equals import IsDict
from fastapi import FastAPI
from fastapi.testclient import TestClient
from pydantic import BaseModel
@@ -91,18 +90,12 @@ def test_openapi_schema():
"Item": {
"title": "Item",
"type": "object",
- "properties": IsDict(
- {
- "name": {
- "title": "Name",
- "anyOf": [{"type": "string"}, {"type": "null"}],
- }
+ "properties": {
+ "name": {
+ "title": "Name",
+ "anyOf": [{"type": "string"}, {"type": "null"}],
}
- )
- | IsDict(
- # TODO: remove when deprecating Pydantic v1
- {"name": {"title": "Name", "type": "string"}}
- ),
+ },
},
"ValidationError": {
"title": "ValidationError",
diff --git a/tests/test_union_body_discriminator.py b/tests/test_union_body_discriminator.py
index 6af9e1d226..6c31649bcc 100644
--- a/tests/test_union_body_discriminator.py
+++ b/tests/test_union_body_discriminator.py
@@ -1,16 +1,12 @@
-from typing import Any, Dict, Union
+from typing import Annotated, Any, Union
-from dirty_equals import IsDict
from fastapi import FastAPI
from fastapi.testclient import TestClient
from inline_snapshot import snapshot
from pydantic import BaseModel, Field
-from typing_extensions import Annotated, Literal
-
-from .utils import needs_pydanticv2
+from typing_extensions import Literal
-@needs_pydanticv2
def test_discriminator_pydantic_v2() -> None:
from pydantic import Tag
@@ -32,7 +28,7 @@ def test_discriminator_pydantic_v2() -> None:
@app.post("/items/")
def save_union_body_discriminator(
item: Item, q: Annotated[str, Field(description="Query string")]
- ) -> Dict[str, Any]:
+ ) -> dict[str, Any]:
return {"item": item}
client = TestClient(app)
@@ -93,21 +89,11 @@ def test_discriminator_pydantic_v2() -> None:
"description": "Successful Response",
"content": {
"application/json": {
- "schema": IsDict(
- {
- # Pydantic 2.10, in Python 3.8
- # TODO: remove when dropping support for Python 3.8
- "type": "object",
- "title": "Response Save Union Body Discriminator Items Post",
- }
- )
- | IsDict(
- {
- "type": "object",
- "additionalProperties": True,
- "title": "Response Save Union Body Discriminator Items Post",
- }
- )
+ "schema": {
+ "type": "object",
+ "additionalProperties": True,
+ "title": "Response Save Union Body Discriminator Items Post",
+ }
}
},
},
diff --git a/tests/test_union_body_discriminator_annotated.py b/tests/test_union_body_discriminator_annotated.py
index 14145e6f60..42a6aed24c 100644
--- a/tests/test_union_body_discriminator_annotated.py
+++ b/tests/test_union_body_discriminator_annotated.py
@@ -1,15 +1,12 @@
# Ref: https://github.com/fastapi/fastapi/discussions/14495
-from typing import Union
+from typing import Annotated, Union
import pytest
from fastapi import FastAPI
from fastapi.testclient import TestClient
from inline_snapshot import snapshot
from pydantic import BaseModel
-from typing_extensions import Annotated
-
-from .utils import needs_pydanticv2
@pytest.fixture(name="client")
@@ -48,21 +45,18 @@ def client_fixture() -> TestClient:
return client
-@needs_pydanticv2
def test_union_body_discriminator_assignment(client: TestClient) -> None:
response = client.post("/pet/assignment", json={"pet_type": "cat", "meows": 5})
assert response.status_code == 200, response.text
assert response.json() == {"pet_type": "cat", "meows": 5}
-@needs_pydanticv2
def test_union_body_discriminator_annotated(client: TestClient) -> None:
response = client.post("/pet/annotated", json={"pet_type": "dog", "barks": 3.5})
assert response.status_code == 200, response.text
assert response.json() == {"pet_type": "dog", "barks": 3.5}
-@needs_pydanticv2
def test_openapi_schema(client: TestClient) -> None:
response = client.get("/openapi.json")
assert response.status_code == 200, response.text
diff --git a/tests/test_union_forms.py b/tests/test_union_forms.py
index cbe98ea825..018949f0c7 100644
--- a/tests/test_union_forms.py
+++ b/tests/test_union_forms.py
@@ -1,9 +1,8 @@
-from typing import Union
+from typing import Annotated, Union
from fastapi import FastAPI, Form
from fastapi.testclient import TestClient
from pydantic import BaseModel
-from typing_extensions import Annotated
app = FastAPI()
diff --git a/tests/test_union_inherited_body.py b/tests/test_union_inherited_body.py
index ef75d459ea..3c062e7f5a 100644
--- a/tests/test_union_inherited_body.py
+++ b/tests/test_union_inherited_body.py
@@ -1,6 +1,5 @@
from typing import Optional, Union
-from dirty_equals import IsDict
from fastapi import FastAPI
from fastapi.testclient import TestClient
from pydantic import BaseModel
@@ -86,16 +85,10 @@ def test_openapi_schema():
"title": "Item",
"type": "object",
"properties": {
- "name": IsDict(
- {
- "title": "Name",
- "anyOf": [{"type": "string"}, {"type": "null"}],
- }
- )
- | IsDict(
- # TODO: remove when deprecating Pydantic v1
- {"title": "Name", "type": "string"}
- )
+ "name": {
+ "title": "Name",
+ "anyOf": [{"type": "string"}, {"type": "null"}],
+ }
},
},
"ExtendedItem": {
@@ -103,16 +96,10 @@ def test_openapi_schema():
"required": ["age"],
"type": "object",
"properties": {
- "name": IsDict(
- {
- "title": "Name",
- "anyOf": [{"type": "string"}, {"type": "null"}],
- }
- )
- | IsDict(
- # TODO: remove when deprecating Pydantic v1
- {"title": "Name", "type": "string"}
- ),
+ "name": {
+ "title": "Name",
+ "anyOf": [{"type": "string"}, {"type": "null"}],
+ },
"age": {"title": "Age", "type": "integer"},
},
},
diff --git a/tests/test_validate_response.py b/tests/test_validate_response.py
index cd97007a44..938d419566 100644
--- a/tests/test_validate_response.py
+++ b/tests/test_validate_response.py
@@ -1,4 +1,4 @@
-from typing import List, Optional, Union
+from typing import Optional, Union
import pytest
from fastapi import FastAPI
@@ -12,7 +12,7 @@ app = FastAPI()
class Item(BaseModel):
name: str
price: Optional[float] = None
- owner_ids: Optional[List[int]] = None
+ owner_ids: Optional[list[int]] = None
@app.get("/items/invalid", response_model=Item)
@@ -38,7 +38,7 @@ def get_innerinvalid():
return {"name": "double invalid", "price": "foo", "owner_ids": ["foo", "bar"]}
-@app.get("/items/invalidlist", response_model=List[Item])
+@app.get("/items/invalidlist", response_model=list[Item])
def get_invalidlist():
return [
{"name": "foo"},
diff --git a/tests/test_validate_response_dataclass.py b/tests/test_validate_response_dataclass.py
index 0415988a0b..67282bcde1 100644
--- a/tests/test_validate_response_dataclass.py
+++ b/tests/test_validate_response_dataclass.py
@@ -1,4 +1,4 @@
-from typing import List, Optional
+from typing import Optional
import pytest
from fastapi import FastAPI
@@ -13,7 +13,7 @@ app = FastAPI()
class Item:
name: str
price: Optional[float] = None
- owner_ids: Optional[List[int]] = None
+ owner_ids: Optional[list[int]] = None
@app.get("/items/invalid", response_model=Item)
@@ -26,7 +26,7 @@ def get_innerinvalid():
return {"name": "double invalid", "price": "foo", "owner_ids": ["foo", "bar"]}
-@app.get("/items/invalidlist", response_model=List[Item])
+@app.get("/items/invalidlist", response_model=list[Item])
def get_invalidlist():
return [
{"name": "foo"},
diff --git a/tests/test_validate_response_recursive/app.py b/tests/test_validate_response_recursive/app.py
index d23d279808..d51aa848d0 100644
--- a/tests/test_validate_response_recursive/app.py
+++ b/tests/test_validate_response_recursive/app.py
@@ -1,34 +1,27 @@
-from typing import List
-
from fastapi import FastAPI
-from fastapi._compat import PYDANTIC_V2
from pydantic import BaseModel
app = FastAPI()
class RecursiveItem(BaseModel):
- sub_items: List["RecursiveItem"] = []
+ sub_items: list["RecursiveItem"] = []
name: str
class RecursiveSubitemInSubmodel(BaseModel):
- sub_items2: List["RecursiveItemViaSubmodel"] = []
+ sub_items2: list["RecursiveItemViaSubmodel"] = []
name: str
class RecursiveItemViaSubmodel(BaseModel):
- sub_items1: List[RecursiveSubitemInSubmodel] = []
+ sub_items1: list[RecursiveSubitemInSubmodel] = []
name: str
-if PYDANTIC_V2:
- RecursiveItem.model_rebuild()
- RecursiveSubitemInSubmodel.model_rebuild()
- RecursiveItemViaSubmodel.model_rebuild()
-else:
- RecursiveItem.update_forward_refs()
- RecursiveSubitemInSubmodel.update_forward_refs()
+RecursiveItem.model_rebuild()
+RecursiveSubitemInSubmodel.model_rebuild()
+RecursiveItemViaSubmodel.model_rebuild()
@app.get("/items/recursive", response_model=RecursiveItem)
diff --git a/tests/test_webhooks_security.py b/tests/test_webhooks_security.py
index 21a694cb54..982ae1e21d 100644
--- a/tests/test_webhooks_security.py
+++ b/tests/test_webhooks_security.py
@@ -1,10 +1,10 @@
from datetime import datetime
+from typing import Annotated
from fastapi import FastAPI, Security
from fastapi.security import HTTPBearer
from fastapi.testclient import TestClient
from pydantic import BaseModel
-from typing_extensions import Annotated
app = FastAPI()
diff --git a/tests/test_ws_dependencies.py b/tests/test_ws_dependencies.py
index ccb1c4b7da..51b982c00e 100644
--- a/tests/test_ws_dependencies.py
+++ b/tests/test_ws_dependencies.py
@@ -1,16 +1,15 @@
import json
-from typing import List
+from typing import Annotated
from fastapi import APIRouter, Depends, FastAPI, WebSocket
from fastapi.testclient import TestClient
-from typing_extensions import Annotated
-def dependency_list() -> List[str]:
+def dependency_list() -> list[str]:
return []
-DepList = Annotated[List[str], Depends(dependency_list)]
+DepList = Annotated[list[str], Depends(dependency_list)]
def create_dependency(name: str):
diff --git a/tests/utils.py b/tests/utils.py
index 691e92bbfb..efa0bfd52b 100644
--- a/tests/utils.py
+++ b/tests/utils.py
@@ -1,43 +1,17 @@
import sys
import pytest
-from fastapi._compat import PYDANTIC_V2
-from inline_snapshot import Snapshot
needs_py39 = pytest.mark.skipif(sys.version_info < (3, 9), reason="requires python3.9+")
needs_py310 = pytest.mark.skipif(
sys.version_info < (3, 10), reason="requires python3.10+"
)
needs_py_lt_314 = pytest.mark.skipif(
- sys.version_info > (3, 13), reason="requires python3.13-"
+ sys.version_info >= (3, 14), reason="requires python3.13-"
)
-needs_pydanticv2 = pytest.mark.skipif(not PYDANTIC_V2, reason="requires Pydantic v2")
-needs_pydanticv1 = pytest.mark.skipif(PYDANTIC_V2, reason="requires Pydantic v1")
def skip_module_if_py_gte_314():
"""Skip entire module on Python 3.14+ at import time."""
if sys.version_info >= (3, 14):
pytest.skip("requires python3.13-", allow_module_level=True)
-
-
-def pydantic_snapshot(
- *,
- v2: Snapshot,
- v1: Snapshot, # TODO: remove v1 argument when deprecating Pydantic v1
-):
- """
- This function should be used like this:
-
- >>> assert value == pydantic_snapshot(v2=snapshot(),v1=snapshot())
-
- inline-snapshot will create the snapshots when pytest is executed for each versions of pydantic.
-
- It is also possible to use the function inside snapshots for version-specific values.
-
- >>> assert value == snapshot({
- "data": "some data",
- "version_specific": pydantic_snapshot(v2=snapshot(),v1=snapshot()),
- })
- """
- return v2 if PYDANTIC_V2 else v1