Compare commits
168 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
b199364246 | ||
|
|
38db0a5858 | ||
|
|
0f22c76d7d | ||
|
|
4d3ef06029 | ||
|
|
7a9396c839 | ||
|
|
0b1e2ec2a6 | ||
|
|
fb15c48556 | ||
|
|
9d74b23670 | ||
|
|
3a8f6cd1a2 | ||
|
|
60f7fe4006 | ||
|
|
ce5ecaa2a2 | ||
|
|
ebc6a0653a | ||
|
|
e23916d2f9 | ||
|
|
dfcc0322e4 | ||
|
|
9edba691e7 | ||
|
|
36264cffb8 | ||
|
|
511199014f | ||
|
|
9f49708fd8 | ||
|
|
a3a6c61164 | ||
|
|
41e87c0ded | ||
|
|
3960b45223 | ||
|
|
475f0d0158 | ||
|
|
f9ac185bf0 | ||
|
|
13712e2720 | ||
|
|
435c11a406 | ||
|
|
2606671a0a | ||
|
|
7782dd677b | ||
|
|
18d28d4370 | ||
|
|
c8414b986f | ||
|
|
d3cdd3bbd1 | ||
|
|
2d916a9c95 | ||
|
|
912524233b | ||
|
|
09b0a5d153 | ||
|
|
846e8bc886 | ||
|
|
7039c5edc5 | ||
|
|
b45d1da717 | ||
|
|
4eb8db3cd3 | ||
|
|
4343170a28 | ||
|
|
d60f8c59b9 | ||
|
|
8d39e5b74a | ||
|
|
dc3c320020 | ||
|
|
eca465f4c9 | ||
|
|
f785676b83 | ||
|
|
a5ce86dde5 | ||
|
|
6b0dddf55a | ||
|
|
42d52b834a | ||
|
|
0888b3ffc0 | ||
|
|
c37d71da70 | ||
|
|
172b3dfd43 | ||
|
|
2afbdb3a44 | ||
|
|
ed22cc107d | ||
|
|
e304414c93 | ||
|
|
8989940569 | ||
|
|
bd7d503314 | ||
|
|
95e667a00a | ||
|
|
e9f4b7975c | ||
|
|
b08f15048d | ||
|
|
f497efaf94 | ||
|
|
4711785594 | ||
|
|
a74cb19495 | ||
|
|
913659c80d | ||
|
|
c26931ae17 | ||
|
|
06839414fa | ||
|
|
85bad3303f | ||
|
|
26431224d1 | ||
|
|
b7a0fc7e12 | ||
|
|
e62e5e8812 | ||
|
|
33e2fbe20f | ||
|
|
1b9c402643 | ||
|
|
653315c496 | ||
|
|
32259588e8 | ||
|
|
d3388bb4ae | ||
|
|
696dedf8e6 | ||
|
|
d92a76f315 | ||
|
|
df4291699f | ||
|
|
a0761e2b16 | ||
|
|
9d1f0e3512 | ||
|
|
343f5539bd | ||
|
|
e4d08e9e1f | ||
|
|
6257afe304 | ||
|
|
5422612008 | ||
|
|
a883442ee0 | ||
|
|
40bb8fac5b | ||
|
|
57c8490b0a | ||
|
|
7030237306 | ||
|
|
6bc235b2bb | ||
|
|
ad2a09f9f5 | ||
|
|
695601dff4 | ||
|
|
706d2499b5 | ||
|
|
60d87c0ccb | ||
|
|
99a491e95c | ||
|
|
ceaed0a447 | ||
|
|
6fa46e4256 | ||
|
|
a9819dfd8d | ||
|
|
c5bcb806bb | ||
|
|
72346962b0 | ||
|
|
e1068116df | ||
|
|
aed266a7ef | ||
|
|
00ebe9c841 | ||
|
|
e3d9f8cfc7 | ||
|
|
3641c1ea55 | ||
|
|
54ab928acd | ||
|
|
e37dd75485 | ||
|
|
bcb8e64f67 | ||
|
|
256426ede1 | ||
|
|
563b355a75 | ||
|
|
ab8974ef04 | ||
|
|
995bd43619 | ||
|
|
803b9fca98 | ||
|
|
ba1ac2b1f6 | ||
|
|
a751cdd17f | ||
|
|
8b4ce06065 | ||
|
|
d523f7f340 | ||
|
|
aadc3e7dc1 | ||
|
|
a8a3971a99 | ||
|
|
59b17ce804 | ||
|
|
54d0be2388 | ||
|
|
36269edf6a | ||
|
|
f7a11bc0b4 | ||
|
|
86b410e623 | ||
|
|
a69f38340f | ||
|
|
dda2337722 | ||
|
|
f1ab5300a7 | ||
|
|
3e6a59183b | ||
|
|
a4c4eb2964 | ||
|
|
bfe698c667 | ||
|
|
5fa8e38681 | ||
|
|
710b320fd0 | ||
|
|
651dd00a9e | ||
|
|
ca321db5db | ||
|
|
76d0d81e70 | ||
|
|
ad85917f61 | ||
|
|
22b033ebd7 | ||
|
|
d4ce9d5a4a | ||
|
|
23bc02c45a | ||
|
|
1dae11ce50 | ||
|
|
817cc1d754 | ||
|
|
a32902606e | ||
|
|
61ab73ea0f | ||
|
|
038e1142d7 | ||
|
|
dfa75c1587 | ||
|
|
af60d6d8ea | ||
|
|
efeee95db7 | ||
|
|
2c6fb2ecd1 | ||
|
|
1f0eecba81 | ||
|
|
e82e6479f2 | ||
|
|
722107fe60 | ||
|
|
9642ff2637 | ||
|
|
8187c54c73 | ||
|
|
17c1ae886b | ||
|
|
c4f6439888 | ||
|
|
8c2e9ddd50 | ||
|
|
aa50dc200f | ||
|
|
e04d397e32 | ||
|
|
0c82015a8c | ||
|
|
e688c57f30 | ||
|
|
6ec46c17d3 | ||
|
|
8c572a9ef2 | ||
|
|
9406e822ec | ||
|
|
f243315696 | ||
|
|
96b1625eed | ||
|
|
1c3e691875 | ||
|
|
ab8f557250 | ||
|
|
67da3bb52e | ||
|
|
9ed94e4f68 | ||
|
|
d71be59217 | ||
|
|
a94ef3351e | ||
|
|
ea1f2190d3 |
4
.github/workflows/build-docs.yml
vendored
@@ -108,9 +108,9 @@ jobs:
|
||||
path: docs/${{ matrix.lang }}/.cache
|
||||
- name: Build Docs
|
||||
run: python ./scripts/docs.py build-lang ${{ matrix.lang }}
|
||||
- uses: actions/upload-artifact@v3
|
||||
- uses: actions/upload-artifact@v4
|
||||
with:
|
||||
name: docs-site
|
||||
name: docs-site-${{ matrix.lang }}
|
||||
path: ./site/**
|
||||
|
||||
# https://github.com/marketplace/actions/alls-green#why
|
||||
|
||||
16
.github/workflows/deploy-docs.yml
vendored
@@ -19,18 +19,16 @@ jobs:
|
||||
run: |
|
||||
rm -rf ./site
|
||||
mkdir ./site
|
||||
- name: Download Artifact Docs
|
||||
id: download
|
||||
uses: dawidd6/action-download-artifact@v3.1.4
|
||||
- uses: actions/download-artifact@v4
|
||||
with:
|
||||
if_no_artifact_found: ignore
|
||||
github_token: ${{ secrets.FASTAPI_PREVIEW_DOCS_DOWNLOAD_ARTIFACTS }}
|
||||
workflow: build-docs.yml
|
||||
run_id: ${{ github.event.workflow_run.id }}
|
||||
name: docs-site
|
||||
path: ./site/
|
||||
pattern: docs-site-*
|
||||
merge-multiple: true
|
||||
github-token: ${{ secrets.FASTAPI_PREVIEW_DOCS_DOWNLOAD_ARTIFACTS }}
|
||||
run-id: ${{ github.event.workflow_run.id }}
|
||||
- name: Deploy to Cloudflare Pages
|
||||
if: steps.download.outputs.found_artifact == 'true'
|
||||
# hashFiles returns an empty string if there are no files
|
||||
if: hashFiles('./site/*')
|
||||
id: deploy
|
||||
uses: cloudflare/pages-action@v1
|
||||
with:
|
||||
|
||||
1
.github/workflows/publish.yml
vendored
@@ -12,6 +12,7 @@ jobs:
|
||||
matrix:
|
||||
package:
|
||||
- fastapi
|
||||
- fastapi-slim
|
||||
permissions:
|
||||
id-token: write
|
||||
steps:
|
||||
|
||||
11
.github/workflows/smokeshow.yml
vendored
@@ -24,13 +24,14 @@ jobs:
|
||||
|
||||
- run: pip install smokeshow
|
||||
|
||||
- uses: dawidd6/action-download-artifact@v3.1.4
|
||||
- uses: actions/download-artifact@v4
|
||||
with:
|
||||
github_token: ${{ secrets.FASTAPI_SMOKESHOW_DOWNLOAD_ARTIFACTS }}
|
||||
workflow: test.yml
|
||||
commit: ${{ github.event.workflow_run.head_sha }}
|
||||
name: coverage-html
|
||||
path: htmlcov
|
||||
github-token: ${{ secrets.FASTAPI_SMOKESHOW_DOWNLOAD_ARTIFACTS }}
|
||||
run-id: ${{ github.event.workflow_run.id }}
|
||||
|
||||
- run: smokeshow upload coverage-html
|
||||
- run: smokeshow upload htmlcov
|
||||
env:
|
||||
SMOKESHOW_GITHUB_STATUS_DESCRIPTION: Coverage {coverage-percentage}
|
||||
SMOKESHOW_GITHUB_COVERAGE_THRESHOLD: 100
|
||||
|
||||
18
.github/workflows/test-redistribute.yml
vendored
@@ -12,6 +12,11 @@ on:
|
||||
jobs:
|
||||
test-redistribute:
|
||||
runs-on: ubuntu-latest
|
||||
strategy:
|
||||
matrix:
|
||||
package:
|
||||
- fastapi
|
||||
- fastapi-slim
|
||||
steps:
|
||||
- name: Dump GitHub context
|
||||
env:
|
||||
@@ -22,12 +27,11 @@ jobs:
|
||||
uses: actions/setup-python@v5
|
||||
with:
|
||||
python-version: "3.10"
|
||||
# Issue ref: https://github.com/actions/setup-python/issues/436
|
||||
# cache: "pip"
|
||||
# cache-dependency-path: pyproject.toml
|
||||
- name: Install build dependencies
|
||||
run: pip install build
|
||||
- name: Build source distribution
|
||||
env:
|
||||
TIANGOLO_BUILD_PACKAGE: ${{ matrix.package }}
|
||||
run: python -m build --sdist
|
||||
- name: Decompress source distribution
|
||||
run: |
|
||||
@@ -35,16 +39,18 @@ jobs:
|
||||
tar xvf fastapi*.tar.gz
|
||||
- name: Install test dependencies
|
||||
run: |
|
||||
cd dist/fastapi-*/
|
||||
cd dist/fastapi*/
|
||||
pip install -r requirements-tests.txt
|
||||
env:
|
||||
TIANGOLO_BUILD_PACKAGE: ${{ matrix.package }}
|
||||
- name: Run source distribution tests
|
||||
run: |
|
||||
cd dist/fastapi-*/
|
||||
cd dist/fastapi*/
|
||||
bash scripts/test.sh
|
||||
- name: Build wheel distribution
|
||||
run: |
|
||||
cd dist
|
||||
pip wheel --no-deps fastapi-*.tar.gz
|
||||
pip wheel --no-deps fastapi*.tar.gz
|
||||
- name: Dump GitHub context
|
||||
env:
|
||||
GITHUB_CONTEXT: ${{ toJson(github) }}
|
||||
|
||||
11
.github/workflows/test.yml
vendored
@@ -87,9 +87,9 @@ jobs:
|
||||
COVERAGE_FILE: coverage/.coverage.${{ runner.os }}-py${{ matrix.python-version }}
|
||||
CONTEXT: ${{ runner.os }}-py${{ matrix.python-version }}
|
||||
- name: Store coverage files
|
||||
uses: actions/upload-artifact@v3
|
||||
uses: actions/upload-artifact@v4
|
||||
with:
|
||||
name: coverage
|
||||
name: coverage-${{ matrix.python-version }}-${{ matrix.pydantic-version }}
|
||||
path: coverage
|
||||
|
||||
coverage-combine:
|
||||
@@ -108,17 +108,18 @@ jobs:
|
||||
# cache: "pip"
|
||||
# cache-dependency-path: pyproject.toml
|
||||
- name: Get coverage files
|
||||
uses: actions/download-artifact@v3
|
||||
uses: actions/download-artifact@v4
|
||||
with:
|
||||
name: coverage
|
||||
pattern: coverage-*
|
||||
path: coverage
|
||||
merge-multiple: true
|
||||
- run: pip install coverage[toml]
|
||||
- run: ls -la coverage
|
||||
- run: coverage combine coverage
|
||||
- run: coverage report
|
||||
- run: coverage html --show-contexts --title "Coverage for ${{ github.sha }}"
|
||||
- name: Store coverage HTML
|
||||
uses: actions/upload-artifact@v3
|
||||
uses: actions/upload-artifact@v4
|
||||
with:
|
||||
name: coverage-html
|
||||
path: htmlcov
|
||||
|
||||
77
README.md
@@ -53,14 +53,18 @@ The key features are:
|
||||
<a href="https://reflex.dev" target="_blank" title="Reflex"><img src="https://fastapi.tiangolo.com/img/sponsors/reflex.png"></a>
|
||||
<a href="https://github.com/scalar/scalar/?utm_source=fastapi&utm_medium=website&utm_campaign=main-badge" target="_blank" title="Scalar: Beautiful Open-Source API References from Swagger/OpenAPI files"><img src="https://fastapi.tiangolo.com/img/sponsors/scalar.svg"></a>
|
||||
<a href="https://www.propelauth.com/?utm_source=fastapi&utm_campaign=1223&utm_medium=mainbadge" target="_blank" title="Auth, user management and more for your B2B product"><img src="https://fastapi.tiangolo.com/img/sponsors/propelauth.png"></a>
|
||||
<a href="https://www.withcoherence.com/?utm_medium=advertising&utm_source=fastapi&utm_campaign=banner%20january%2024" target="_blank" title="Coherence"><img src="https://fastapi.tiangolo.com/img/sponsors/coherence.png"></a>
|
||||
<a href="https://docs.withcoherence.com/configuration/frameworks/?utm_medium=advertising&utm_source=fastapi&utm_campaign=docs#fastapi-example" target="_blank" title="Coherence"><img src="https://fastapi.tiangolo.com/img/sponsors/coherence.png"></a>
|
||||
<a href="https://www.mongodb.com/developer/languages/python/python-quickstart-fastapi/?utm_campaign=fastapi_framework&utm_source=fastapi_sponsorship&utm_medium=web_referral" target="_blank" title="Simplify Full Stack Development with FastAPI & MongoDB"><img src="https://fastapi.tiangolo.com/img/sponsors/mongodb.png"></a>
|
||||
<a href="https://konghq.com/products/kong-konnect?utm_medium=referral&utm_source=github&utm_campaign=platform&utm_content=fast-api" target="_blank" title="Kong Konnect - API management platform"><img src="https://fastapi.tiangolo.com/img/sponsors/kong.png"></a>
|
||||
<a href="https://zuplo.link/fastapi-gh" target="_blank" title="Zuplo: Scale, Protect, Document, and Monetize your FastAPI"><img src="https://fastapi.tiangolo.com/img/sponsors/zuplo.png"></a>
|
||||
<a href="https://fine.dev?ref=fastapibadge" target="_blank" title="Fine's AI FastAPI Workflow: Effortlessly Deploy and Integrate FastAPI into Your Project"><img src="https://fastapi.tiangolo.com/img/sponsors/fine.png"></a>
|
||||
<a href="https://training.talkpython.fm/fastapi-courses" target="_blank" title="FastAPI video courses on demand from people you trust"><img src="https://fastapi.tiangolo.com/img/sponsors/talkpython-v2.jpg"></a>
|
||||
<a href="https://github.com/deepset-ai/haystack/" target="_blank" title="Build powerful search from composable, open source building blocks"><img src="https://fastapi.tiangolo.com/img/sponsors/haystack-fastapi.svg"></a>
|
||||
<a href="https://databento.com/" target="_blank" title="Pay as you go for market data"><img src="https://fastapi.tiangolo.com/img/sponsors/databento.svg"></a>
|
||||
<a href="https://speakeasyapi.dev?utm_source=fastapi+repo&utm_medium=github+sponsorship" target="_blank" title="SDKs for your API | Speakeasy"><img src="https://fastapi.tiangolo.com/img/sponsors/speakeasy.png"></a>
|
||||
<a href="https://www.svix.com/" target="_blank" title="Svix - Webhooks as a service"><img src="https://fastapi.tiangolo.com/img/sponsors/svix.svg"></a>
|
||||
<a href="https://www.codacy.com/?utm_source=github&utm_medium=sponsors&utm_id=pioneers" target="_blank" title="Take code reviews from hours to minutes"><img src="https://fastapi.tiangolo.com/img/sponsors/codacy.png"></a>
|
||||
<a href="https://www.stainlessapi.com/?utm_source=fastapi&utm_medium=referral" target="_blank" title="Stainless | Generate best-in-class SDKs"><img src="https://fastapi.tiangolo.com/img/sponsors/stainless.png"></a>
|
||||
|
||||
<!-- /sponsors -->
|
||||
|
||||
@@ -139,18 +143,6 @@ $ pip install fastapi
|
||||
|
||||
</div>
|
||||
|
||||
You will also need an ASGI server, for production such as <a href="https://www.uvicorn.org" class="external-link" target="_blank">Uvicorn</a> or <a href="https://github.com/pgjones/hypercorn" class="external-link" target="_blank">Hypercorn</a>.
|
||||
|
||||
<div class="termy">
|
||||
|
||||
```console
|
||||
$ pip install "uvicorn[standard]"
|
||||
|
||||
---> 100%
|
||||
```
|
||||
|
||||
</div>
|
||||
|
||||
## Example
|
||||
|
||||
### Create it
|
||||
@@ -211,11 +203,24 @@ Run the server with:
|
||||
<div class="termy">
|
||||
|
||||
```console
|
||||
$ uvicorn main:app --reload
|
||||
$ fastapi dev main.py
|
||||
|
||||
╭────────── FastAPI CLI - Development mode ───────────╮
|
||||
│ │
|
||||
│ Serving at: http://127.0.0.1:8000 │
|
||||
│ │
|
||||
│ API docs: http://127.0.0.1:8000/docs │
|
||||
│ │
|
||||
│ Running in development mode, for production use: │
|
||||
│ │
|
||||
│ fastapi run │
|
||||
│ │
|
||||
╰─────────────────────────────────────────────────────╯
|
||||
|
||||
INFO: Will watch for changes in these directories: ['/home/user/code/awesomeapp']
|
||||
INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit)
|
||||
INFO: Started reloader process [28720]
|
||||
INFO: Started server process [28722]
|
||||
INFO: Started reloader process [2248755] using WatchFiles
|
||||
INFO: Started server process [2248757]
|
||||
INFO: Waiting for application startup.
|
||||
INFO: Application startup complete.
|
||||
```
|
||||
@@ -223,13 +228,13 @@ INFO: Application startup complete.
|
||||
</div>
|
||||
|
||||
<details markdown="1">
|
||||
<summary>About the command <code>uvicorn main:app --reload</code>...</summary>
|
||||
<summary>About the command <code>fastapi dev main.py</code>...</summary>
|
||||
|
||||
The command `uvicorn main:app` refers to:
|
||||
The command `fastapi dev` reads your `main.py` file, detects the **FastAPI** app in it, and starts a server using <a href="https://www.uvicorn.org" class="external-link" target="_blank">Uvicorn</a>.
|
||||
|
||||
* `main`: the file `main.py` (the Python "module").
|
||||
* `app`: the object created inside of `main.py` with the line `app = FastAPI()`.
|
||||
* `--reload`: make the server restart after code changes. Only do this for development.
|
||||
By default, `fastapi dev` will start with auto-reload enabled for local development.
|
||||
|
||||
You can read more about it in the <a href="https://fastapi.tiangolo.com/fastapi-cli/" target="_blank">FastAPI CLI docs</a>.
|
||||
|
||||
</details>
|
||||
|
||||
@@ -302,7 +307,7 @@ def update_item(item_id: int, item: Item):
|
||||
return {"item_name": item.name, "item_id": item_id}
|
||||
```
|
||||
|
||||
The server should reload automatically (because you added `--reload` to the `uvicorn` command above).
|
||||
The `fastapi dev` server should reload automatically.
|
||||
|
||||
### Interactive API docs upgrade
|
||||
|
||||
@@ -446,7 +451,7 @@ Independent TechEmpower benchmarks show **FastAPI** applications running under U
|
||||
|
||||
To understand more about it, see the section <a href="https://fastapi.tiangolo.com/benchmarks/" class="internal-link" target="_blank">Benchmarks</a>.
|
||||
|
||||
## Optional Dependencies
|
||||
## Dependencies
|
||||
|
||||
Used by Pydantic:
|
||||
|
||||
@@ -459,16 +464,36 @@ Used by Starlette:
|
||||
* <a href="https://www.python-httpx.org" target="_blank"><code>httpx</code></a> - Required if you want to use the `TestClient`.
|
||||
* <a href="https://jinja.palletsprojects.com" target="_blank"><code>jinja2</code></a> - Required if you want to use the default template configuration.
|
||||
* <a href="https://github.com/Kludex/python-multipart" target="_blank"><code>python-multipart</code></a> - Required if you want to support form <abbr title="converting the string that comes from an HTTP request into Python data">"parsing"</abbr>, with `request.form()`.
|
||||
* <a href="https://pythonhosted.org/itsdangerous/" target="_blank"><code>itsdangerous</code></a> - Required for `SessionMiddleware` support.
|
||||
* <a href="https://pyyaml.org/wiki/PyYAMLDocumentation" target="_blank"><code>pyyaml</code></a> - Required for Starlette's `SchemaGenerator` support (you probably don't need it with FastAPI).
|
||||
|
||||
Used by FastAPI / Starlette:
|
||||
|
||||
* <a href="https://www.uvicorn.org" target="_blank"><code>uvicorn</code></a> - for the server that loads and serves your application.
|
||||
* `fastapi-cli` - to provide the `fastapi` command.
|
||||
|
||||
When you install `fastapi` it comes these standard dependencies.
|
||||
|
||||
Additional optional dependencies:
|
||||
|
||||
* <a href="https://github.com/ijl/orjson" target="_blank"><code>orjson</code></a> - Required if you want to use `ORJSONResponse`.
|
||||
* <a href="https://github.com/esnme/ultrajson" target="_blank"><code>ujson</code></a> - Required if you want to use `UJSONResponse`.
|
||||
|
||||
You can install all of these with `pip install "fastapi[all]"`.
|
||||
## `fastapi-slim`
|
||||
|
||||
If you don't want the extra standard optional dependencies, install `fastapi-slim` instead.
|
||||
|
||||
When you install with:
|
||||
|
||||
```bash
|
||||
pip install fastapi
|
||||
```
|
||||
|
||||
...it includes the same code and dependencies as:
|
||||
|
||||
```bash
|
||||
pip install "fastapi-slim[standard]"
|
||||
```
|
||||
|
||||
The standard extra dependencies are the ones mentioned above.
|
||||
|
||||
## License
|
||||
|
||||
|
||||
@@ -126,7 +126,7 @@ $ pip install fastapi
|
||||
|
||||
</div>
|
||||
|
||||
আপনার একটি ASGI সার্ভারেরও প্রয়োজন হবে, প্রোডাকশনের জন্য <a href="https://www.uvicorn.org" class="external-link" target="_blank">Uvicorn</a> অথবা <a href="https://gitlab.com/pgjones/hypercorn" class="external-link" target="_blank">Hypercorn</a>.
|
||||
আপনার একটি ASGI সার্ভারেরও প্রয়োজন হবে, প্রোডাকশনের জন্য <a href="https://www.uvicorn.org" class="external-link" target="_blank">Uvicorn</a> অথবা <a href="https://github.com/pgjones/hypercorn" class="external-link" target="_blank">Hypercorn</a>.
|
||||
|
||||
<div class="termy">
|
||||
|
||||
|
||||
@@ -5,7 +5,7 @@ Das Wichtigste, was Sie zum Ausführen einer **FastAPI**-Anwendung auf einer ent
|
||||
Es gibt 3 Hauptalternativen:
|
||||
|
||||
* <a href="https://www.uvicorn.org/" class="external-link" target="_blank">Uvicorn</a>: ein hochperformanter ASGI-Server.
|
||||
* <a href="https://pgjones.gitlab.io/hypercorn/" class="external-link" target="_blank">Hypercorn</a>: ein ASGI-Server, der unter anderem mit HTTP/2 und Trio kompatibel ist.
|
||||
* <a href="https://hypercorn.readthedocs.io/" class="external-link" target="_blank">Hypercorn</a>: ein ASGI-Server, der unter anderem mit HTTP/2 und Trio kompatibel ist.
|
||||
* <a href="https://github.com/django/daphne" class="external-link" target="_blank">Daphne</a>: Der für Django Channels entwickelte ASGI-Server.
|
||||
|
||||
## Servermaschine und Serverprogramm
|
||||
@@ -43,7 +43,7 @@ Sie können einen ASGI-kompatiblen Server installieren mit:
|
||||
|
||||
=== "Hypercorn"
|
||||
|
||||
* <a href="https://gitlab.com/pgjones/hypercorn" class="external-link" target="_blank">Hypercorn</a>, ein ASGI-Server, der auch mit HTTP/2 kompatibel ist.
|
||||
* <a href="https://github.com/pgjones/hypercorn" class="external-link" target="_blank">Hypercorn</a>, ein ASGI-Server, der auch mit HTTP/2 kompatibel ist.
|
||||
|
||||
<div class="termy">
|
||||
|
||||
|
||||
@@ -96,8 +96,8 @@ Sie können wahrscheinlich mit der rechten Maustaste auf jeden Link klicken und
|
||||
|
||||
**Swagger UI** verwendet folgende Dateien:
|
||||
|
||||
* <a href="https://cdn.jsdelivr.net/npm/swagger-ui-dist@5.9.0/swagger-ui-bundle.js" class="external-link" target="_blank">`swagger-ui-bundle.js`</a>
|
||||
* <a href="https://cdn.jsdelivr.net/npm/swagger-ui-dist@5.9.0/swagger-ui.css" class="external-link" target="_blank">`swagger-ui.css`</a>
|
||||
* <a href="https://cdn.jsdelivr.net/npm/swagger-ui-dist@5/swagger-ui-bundle.js" class="external-link" target="_blank">`swagger-ui-bundle.js`</a>
|
||||
* <a href="https://cdn.jsdelivr.net/npm/swagger-ui-dist@5/swagger-ui.css" class="external-link" target="_blank">`swagger-ui.css`</a>
|
||||
|
||||
Und **ReDoc** verwendet diese Datei:
|
||||
|
||||
|
||||
@@ -18,7 +18,7 @@ Hier sind einige der **GraphQL**-Bibliotheken, welche **ASGI** unterstützen. Di
|
||||
* <a href="https://strawberry.rocks/" class="external-link" target="_blank">Strawberry</a> 🍓
|
||||
* Mit <a href="https://strawberry.rocks/docs/integrations/fastapi" class="external-link" target="_blank">Dokumentation für FastAPI</a>
|
||||
* <a href="https://ariadnegraphql.org/" class="external-link" target="_blank">Ariadne</a>
|
||||
* Mit <a href="https://ariadnegraphql.org/docs/starlette-integration" class="external-link" target="_blank">Dokumentation für Starlette</a> (welche auch für FastAPI gilt)
|
||||
* Mit <a href="https://ariadnegraphql.org/docs/fastapi-integration" class="external-link" target="_blank">Dokumentation für FastAPI</a>
|
||||
* <a href="https://tartiflette.io/" class="external-link" target="_blank">Tartiflette</a>
|
||||
* Mit <a href="https://tartiflette.github.io/tartiflette-asgi/" class="external-link" target="_blank">Tartiflette ASGI</a>, für ASGI-Integration
|
||||
* <a href="https://graphene-python.org/" class="external-link" target="_blank">Graphene</a>
|
||||
|
||||
@@ -142,7 +142,7 @@ $ pip install fastapi
|
||||
|
||||
</div>
|
||||
|
||||
Sie benötigen außerdem einen <abbr title="Asynchronous Server Gateway Interface – Asynchrone Server-Verbindungsschnittstelle">ASGI</abbr>-Server. Für die Produktumgebung beispielsweise <a href="https://www.uvicorn.org" class="external-link" target="_blank">Uvicorn</a> oder <a href="https://gitlab.com/pgjones/hypercorn" class="external-link" target="_blank">Hypercorn</a>.
|
||||
Sie benötigen außerdem einen <abbr title="Asynchronous Server Gateway Interface – Asynchrone Server-Verbindungsschnittstelle">ASGI</abbr>-Server. Für die Produktumgebung beispielsweise <a href="https://www.uvicorn.org" class="external-link" target="_blank">Uvicorn</a> oder <a href="https://github.com/pgjones/hypercorn" class="external-link" target="_blank">Hypercorn</a>.
|
||||
|
||||
<div class="termy">
|
||||
|
||||
@@ -460,7 +460,7 @@ Wird von Starlette verwendet:
|
||||
|
||||
* <a href="https://www.python-httpx.org" target="_blank"><code>httpx</code></a> - erforderlich, wenn Sie den `TestClient` verwenden möchten.
|
||||
* <a href="https://jinja.palletsprojects.com" target="_blank"><code>jinja2</code></a> - erforderlich, wenn Sie die Standardkonfiguration für Templates verwenden möchten.
|
||||
* <a href="https://andrew-d.github.io/python-multipart/" target="_blank"><code>python-multipart</code></a> - erforderlich, wenn Sie Formulare mittels `request.form()` <abbr title="Konvertieren des Strings, der aus einer HTTP-Anfrage stammt, nach Python-Daten">„parsen“</abbr> möchten.
|
||||
* <a href="https://github.com/Kludex/python-multipart" target="_blank"><code>python-multipart</code></a> - erforderlich, wenn Sie Formulare mittels `request.form()` <abbr title="Konvertieren des Strings, der aus einer HTTP-Anfrage stammt, nach Python-Daten">„parsen“</abbr> möchten.
|
||||
* <a href="https://pythonhosted.org/itsdangerous/" target="_blank"><code>itsdangerous</code></a> - erforderlich für `SessionMiddleware` Unterstützung.
|
||||
* <a href="https://pyyaml.org/wiki/PyYAMLDocumentation" target="_blank"><code>pyyaml</code></a> - erforderlich für Starlette's `SchemaGenerator` Unterstützung (Sie brauchen das wahrscheinlich nicht mit FastAPI).
|
||||
* <a href="https://github.com/esnme/ultrajson" target="_blank"><code>ujson</code></a> - erforderlich, wenn Sie `UJSONResponse` verwenden möchten.
|
||||
|
||||
@@ -5,7 +5,7 @@
|
||||
📤 3️⃣ 👑 🎛:
|
||||
|
||||
* <a href="https://www.uvicorn.org/" class="external-link" target="_blank">Uvicorn</a>: ↕ 🎭 🔫 💽.
|
||||
* <a href="https://pgjones.gitlab.io/hypercorn/" class="external-link" target="_blank">Hypercorn</a>: 🔫 💽 🔗 ⏮️ 🇺🇸🔍/2️⃣ & 🎻 👪 🎏 ⚒.
|
||||
* <a href="https://hypercorn.readthedocs.io/" class="external-link" target="_blank">Hypercorn</a>: 🔫 💽 🔗 ⏮️ 🇺🇸🔍/2️⃣ & 🎻 👪 🎏 ⚒.
|
||||
* <a href="https://github.com/django/daphne" class="external-link" target="_blank">👸</a>: 🔫 💽 🏗 ✳ 📻.
|
||||
|
||||
## 💽 🎰 & 💽 📋
|
||||
@@ -43,7 +43,7 @@
|
||||
|
||||
=== "Hypercorn"
|
||||
|
||||
* <a href="https://gitlab.com/pgjones/hypercorn" class="external-link" target="_blank">Hypercorn</a>, 🔫 💽 🔗 ⏮️ 🇺🇸🔍/2️⃣.
|
||||
* <a href="https://github.com/pgjones/hypercorn" class="external-link" target="_blank">Hypercorn</a>, 🔫 💽 🔗 ⏮️ 🇺🇸🔍/2️⃣.
|
||||
|
||||
<div class="termy">
|
||||
|
||||
|
||||
@@ -18,7 +18,7 @@
|
||||
* <a href="https://strawberry.rocks/" class="external-link" target="_blank">🍓</a> 👶
|
||||
* ⏮️ <a href="https://strawberry.rocks/docs/integrations/fastapi" class="external-link" target="_blank">🩺 FastAPI</a>
|
||||
* <a href="https://ariadnegraphql.org/" class="external-link" target="_blank">👸</a>
|
||||
* ⏮️ <a href="https://ariadnegraphql.org/docs/starlette-integration" class="external-link" target="_blank">🩺 💃</a> (👈 ✔ FastAPI)
|
||||
* ⏮️ <a href="https://ariadnegraphql.org/docs/fastapi-integration" class="external-link" target="_blank">🩺 FastAPI</a>
|
||||
* <a href="https://tartiflette.io/" class="external-link" target="_blank">🍟</a>
|
||||
* ⏮️ <a href="https://tartiflette.github.io/tartiflette-asgi/" class="external-link" target="_blank">🍟 🔫</a> 🚚 🔫 🛠️
|
||||
* <a href="https://graphene-python.org/" class="external-link" target="_blank">⚗</a>
|
||||
|
||||
@@ -501,7 +501,7 @@ current_user.items
|
||||
|
||||
"🛠️" ⚒ 🔁 💪 🕐❔ 👆 🔀 📊 👆 🇸🇲 🏷, 🚮 🆕 🔢, ♒️. 🔁 👈 🔀 💽, 🚮 🆕 🏓, 🆕 🏓, ♒️.
|
||||
|
||||
👆 💪 🔎 🖼 ⚗ FastAPI 🏗 📄 ⚪️➡️ [🏗 ⚡ - 📄](../project-generation.md){.internal-link target=_blank}. 🎯 <a href="https://github.com/tiangolo/full-stack-fastapi-postgresql/tree/master/src/backend/app/alembic/" class="external-link" target="_blank"> `alembic` 📁 ℹ 📟</a>.
|
||||
👆 💪 🔎 🖼 ⚗ FastAPI 🏗 📄 ⚪️➡️ [🏗 ⚡ - 📄](../project-generation.md){.internal-link target=_blank}. 🎯 <a href="https://github.com/tiangolo/full-stack-fastapi-template/tree/master/backend/app/alembic" class="external-link" target="_blank"> `alembic` 📁 ℹ 📟</a>.
|
||||
|
||||
### ✍ 🔗
|
||||
|
||||
|
||||
@@ -1,5 +1,8 @@
|
||||
Articles:
|
||||
English:
|
||||
- author: Stephen Siegert - Neon
|
||||
link: https://neon.tech/blog/deploy-a-serverless-fastapi-app-with-neon-postgres-and-aws-app-runner-at-any-scale
|
||||
title: Deploy a Serverless FastAPI App with Neon Postgres and AWS App Runner at any scale
|
||||
- author: Kurtis Pykes - NVIDIA
|
||||
link: https://developer.nvidia.com/blog/building-a-machine-learning-microservice-with-fastapi/
|
||||
title: Building a Machine Learning Microservice with FastAPI
|
||||
@@ -24,7 +27,7 @@ Articles:
|
||||
- author: Nicoló Lino
|
||||
author_link: https://www.nlino.com
|
||||
link: https://github.com/softwarebloat/python-tracing-demo
|
||||
title: Instrument a FastAPI service adding tracing with OpenTelemetry and send/show traces in Grafana Tempo
|
||||
title: Instrument FastAPI with OpenTelemetry tracing and visualize traces in Grafana Tempo.
|
||||
- author: Mikhail Rozhkov, Elena Samuylova
|
||||
author_link: https://www.linkedin.com/in/mnrozhkov/
|
||||
link: https://www.evidentlyai.com/blog/fastapi-tutorial
|
||||
@@ -257,6 +260,10 @@ Articles:
|
||||
author_link: https://medium.com/@krishnardt365
|
||||
link: https://medium.com/@krishnardt365/fastapi-docker-and-postgres-91943e71be92
|
||||
title: Fastapi, Docker(Docker compose) and Postgres
|
||||
- author: Devon Ray
|
||||
author_link: https://devonray.com
|
||||
link: https://devonray.com/blog/deploying-a-fastapi-project-using-aws-lambda-aurora-cdk
|
||||
title: Deployment using Docker, Lambda, Aurora, CDK & GH Actions
|
||||
German:
|
||||
- author: Marcel Sander (actidoo)
|
||||
author_link: https://www.actidoo.com
|
||||
@@ -347,6 +354,11 @@ Articles:
|
||||
author_link: http://editor.leonh.space/
|
||||
link: https://editor.leonh.space/2022/tortoise/
|
||||
title: 'Tortoise ORM / FastAPI 整合快速筆記'
|
||||
Spanish:
|
||||
- author: Eduardo Zepeda
|
||||
author_link: https://coffeebytes.dev/en/authors/eduardo-zepeda/
|
||||
link: https://coffeebytes.dev/es/python-fastapi-el-mejor-framework-de-python/
|
||||
title: 'Tutorial de FastAPI, ¿el mejor framework de Python?'
|
||||
Podcasts:
|
||||
English:
|
||||
- author: Real Python
|
||||
|
||||
@@ -17,6 +17,9 @@ sponsors:
|
||||
- login: cryptapi
|
||||
avatarUrl: https://avatars.githubusercontent.com/u/44925437?u=61369138589bc7fee6c417f3fbd50fbd38286cc4&v=4
|
||||
url: https://github.com/cryptapi
|
||||
- login: Kong
|
||||
avatarUrl: https://avatars.githubusercontent.com/u/962416?v=4
|
||||
url: https://github.com/Kong
|
||||
- login: codacy
|
||||
avatarUrl: https://avatars.githubusercontent.com/u/1834093?v=4
|
||||
url: https://github.com/codacy
|
||||
@@ -48,7 +51,7 @@ sponsors:
|
||||
avatarUrl: https://avatars.githubusercontent.com/u/74335107?v=4
|
||||
url: https://github.com/xoflare
|
||||
- login: marvin-robot
|
||||
avatarUrl: https://avatars.githubusercontent.com/u/41086007?u=091c5cb75af363123d66f58194805a97220ee1a7&v=4
|
||||
avatarUrl: https://avatars.githubusercontent.com/u/41086007?u=b9fcab402d0cd0aec738b6574fe60855cb0cd36d&v=4
|
||||
url: https://github.com/marvin-robot
|
||||
- login: BoostryJP
|
||||
avatarUrl: https://avatars.githubusercontent.com/u/57932412?v=4
|
||||
@@ -56,10 +59,7 @@ sponsors:
|
||||
- login: acsone
|
||||
avatarUrl: https://avatars.githubusercontent.com/u/7601056?v=4
|
||||
url: https://github.com/acsone
|
||||
- - login: owlur
|
||||
avatarUrl: https://avatars.githubusercontent.com/u/20010787?v=4
|
||||
url: https://github.com/owlur
|
||||
- login: Trivie
|
||||
- - login: Trivie
|
||||
avatarUrl: https://avatars.githubusercontent.com/u/8161763?v=4
|
||||
url: https://github.com/Trivie
|
||||
- - login: americanair
|
||||
@@ -71,9 +71,6 @@ sponsors:
|
||||
- login: mainframeindustries
|
||||
avatarUrl: https://avatars.githubusercontent.com/u/55092103?v=4
|
||||
url: https://github.com/mainframeindustries
|
||||
- login: AccentDesign
|
||||
avatarUrl: https://avatars.githubusercontent.com/u/2429332?v=4
|
||||
url: https://github.com/AccentDesign
|
||||
- login: mangualero
|
||||
avatarUrl: https://avatars.githubusercontent.com/u/3422968?u=c59272d7b5a912d6126fd6c6f17db71e20f506eb&v=4
|
||||
url: https://github.com/mangualero
|
||||
@@ -89,7 +86,10 @@ sponsors:
|
||||
- login: povilasb
|
||||
avatarUrl: https://avatars.githubusercontent.com/u/1213442?u=b11f58ed6ceea6e8297c9b310030478ebdac894d&v=4
|
||||
url: https://github.com/povilasb
|
||||
- - login: upciti
|
||||
- - login: jhundman
|
||||
avatarUrl: https://avatars.githubusercontent.com/u/24263908?v=4
|
||||
url: https://github.com/jhundman
|
||||
- login: upciti
|
||||
avatarUrl: https://avatars.githubusercontent.com/u/43346262?v=4
|
||||
url: https://github.com/upciti
|
||||
- - login: samuelcolvin
|
||||
@@ -98,15 +98,15 @@ sponsors:
|
||||
- login: Kludex
|
||||
avatarUrl: https://avatars.githubusercontent.com/u/7353520?u=62adc405ef418f4b6c8caa93d3eb8ab107bc4927&v=4
|
||||
url: https://github.com/Kludex
|
||||
- login: koconder
|
||||
avatarUrl: https://avatars.githubusercontent.com/u/25068?u=582657b23622aaa3dfe68bd028a780f272f456fa&v=4
|
||||
url: https://github.com/koconder
|
||||
- login: b-rad-c
|
||||
avatarUrl: https://avatars.githubusercontent.com/u/25362581?u=5bb10629f4015b62bec1f9a366675d5085551af9&v=4
|
||||
url: https://github.com/b-rad-c
|
||||
- login: ehaca
|
||||
avatarUrl: https://avatars.githubusercontent.com/u/25950317?u=cec1a3e0643b785288ae8260cc295a85ab344995&v=4
|
||||
url: https://github.com/ehaca
|
||||
- login: raphaellaude
|
||||
avatarUrl: https://avatars.githubusercontent.com/u/28026311?u=9ae4b158c0d2cb29ebd46df6b6edb7de08a67566&v=4
|
||||
url: https://github.com/raphaellaude
|
||||
- login: timlrx
|
||||
avatarUrl: https://avatars.githubusercontent.com/u/28362229?u=9a745ca31372ee324af682715ae88ce8522f9094&v=4
|
||||
url: https://github.com/timlrx
|
||||
@@ -119,6 +119,9 @@ sponsors:
|
||||
- login: ProteinQure
|
||||
avatarUrl: https://avatars.githubusercontent.com/u/33707203?v=4
|
||||
url: https://github.com/ProteinQure
|
||||
- login: catherinenelson1
|
||||
avatarUrl: https://avatars.githubusercontent.com/u/11951946?u=e714b957185b8cf3d301cced7fc3ad2842122c6a&v=4
|
||||
url: https://github.com/catherinenelson1
|
||||
- login: jsoques
|
||||
avatarUrl: https://avatars.githubusercontent.com/u/12414216?u=620921d94196546cc8b9eae2cc4cbc3f95bab42f&v=4
|
||||
url: https://github.com/jsoques
|
||||
@@ -146,18 +149,6 @@ sponsors:
|
||||
- login: RaamEEIL
|
||||
avatarUrl: https://avatars.githubusercontent.com/u/20320552?v=4
|
||||
url: https://github.com/RaamEEIL
|
||||
- login: Filimoa
|
||||
avatarUrl: https://avatars.githubusercontent.com/u/21352040?u=0be845711495bbd7b756e13fcaeb8efc1ebd78ba&v=4
|
||||
url: https://github.com/Filimoa
|
||||
- login: prodhype
|
||||
avatarUrl: https://avatars.githubusercontent.com/u/60444672?u=3f278cff25ea37ead487d7861d4a984795de819e&v=4
|
||||
url: https://github.com/prodhype
|
||||
- login: yakkonaut
|
||||
avatarUrl: https://avatars.githubusercontent.com/u/60633704?u=90a71fd631aa998ba4a96480788f017c9904e07b&v=4
|
||||
url: https://github.com/yakkonaut
|
||||
- login: 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
|
||||
@@ -170,15 +161,18 @@ sponsors:
|
||||
- login: DelfinaCare
|
||||
avatarUrl: https://avatars.githubusercontent.com/u/83734439?v=4
|
||||
url: https://github.com/DelfinaCare
|
||||
- login: Eruditis
|
||||
avatarUrl: https://avatars.githubusercontent.com/u/95244703?v=4
|
||||
url: https://github.com/Eruditis
|
||||
- login: jugeeem
|
||||
avatarUrl: https://avatars.githubusercontent.com/u/116043716?u=ae590d79c38ac79c91b9c5caa6887d061e865a3d&v=4
|
||||
url: https://github.com/jugeeem
|
||||
- login: apitally
|
||||
avatarUrl: https://avatars.githubusercontent.com/u/138365043?v=4
|
||||
url: https://github.com/apitally
|
||||
- login: logic-automation
|
||||
avatarUrl: https://avatars.githubusercontent.com/u/144732884?v=4
|
||||
url: https://github.com/logic-automation
|
||||
- login: thenickben
|
||||
avatarUrl: https://avatars.githubusercontent.com/u/40610922?u=1e907d904041b7c91213951a3cb344cd37c14aaf&v=4
|
||||
url: https://github.com/thenickben
|
||||
- login: ddilidili
|
||||
avatarUrl: https://avatars.githubusercontent.com/u/42176885?u=c0a849dde06987434653197b5f638d3deb55fc6c&v=4
|
||||
url: https://github.com/ddilidili
|
||||
@@ -188,12 +182,15 @@ sponsors:
|
||||
- login: dudikbender
|
||||
avatarUrl: https://avatars.githubusercontent.com/u/53487583?u=3a57542938ebfd57579a0111db2b297e606d9681&v=4
|
||||
url: https://github.com/dudikbender
|
||||
- login: prodhype
|
||||
avatarUrl: https://avatars.githubusercontent.com/u/60444672?u=3f278cff25ea37ead487d7861d4a984795de819e&v=4
|
||||
url: https://github.com/prodhype
|
||||
- login: patsatsia
|
||||
avatarUrl: https://avatars.githubusercontent.com/u/61111267?u=3271b85f7a37b479c8d0ae0a235182e83c166edf&v=4
|
||||
url: https://github.com/patsatsia
|
||||
- login: tcsmith
|
||||
avatarUrl: https://avatars.githubusercontent.com/u/989034?u=7d8d741552b3279e8f4d3878679823a705a46f8f&v=4
|
||||
url: https://github.com/tcsmith
|
||||
- login: mickaelandrieu
|
||||
avatarUrl: https://avatars.githubusercontent.com/u/1247388?u=599f6e73e452a9453f2bd91e5c3100750e731ad4&v=4
|
||||
url: https://github.com/mickaelandrieu
|
||||
- login: dodo5522
|
||||
avatarUrl: https://avatars.githubusercontent.com/u/1362607?u=9bf1e0e520cccc547c046610c468ce6115bbcf9f&v=4
|
||||
url: https://github.com/dodo5522
|
||||
@@ -212,12 +209,27 @@ sponsors:
|
||||
- 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: simw
|
||||
avatarUrl: https://avatars.githubusercontent.com/u/6322526?v=4
|
||||
url: https://github.com/simw
|
||||
- login: koconder
|
||||
avatarUrl: https://avatars.githubusercontent.com/u/25068?u=582657b23622aaa3dfe68bd028a780f272f456fa&v=4
|
||||
url: https://github.com/koconder
|
||||
- login: jstanden
|
||||
avatarUrl: https://avatars.githubusercontent.com/u/63288?u=c3658d57d2862c607a0e19c2101c3c51876e36ad&v=4
|
||||
url: https://github.com/jstanden
|
||||
- login: andreaso
|
||||
avatarUrl: https://avatars.githubusercontent.com/u/285964?u=837265cc7562c0685f25b2d81cd9de0434fe107c&v=4
|
||||
url: https://github.com/andreaso
|
||||
- login: 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
|
||||
@@ -248,15 +260,6 @@ sponsors:
|
||||
- login: wdwinslow
|
||||
avatarUrl: https://avatars.githubusercontent.com/u/11562137?u=dc01daafb354135603a263729e3d26d939c0c452&v=4
|
||||
url: https://github.com/wdwinslow
|
||||
- login: catherinenelson1
|
||||
avatarUrl: https://avatars.githubusercontent.com/u/11951946?u=e714b957185b8cf3d301cced7fc3ad2842122c6a&v=4
|
||||
url: https://github.com/catherinenelson1
|
||||
- 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
|
||||
@@ -266,6 +269,9 @@ sponsors:
|
||||
- login: jgreys
|
||||
avatarUrl: https://avatars.githubusercontent.com/u/4136890?u=096820d1ef89877d57d0f68e669ead8b0fde84df&v=4
|
||||
url: https://github.com/jgreys
|
||||
- login: Ryandaydev
|
||||
avatarUrl: https://avatars.githubusercontent.com/u/4292423?u=48f68868db8886fce31a1d802c1003914c6cd7c6&v=4
|
||||
url: https://github.com/Ryandaydev
|
||||
- login: jaredtrog
|
||||
avatarUrl: https://avatars.githubusercontent.com/u/4381365?v=4
|
||||
url: https://github.com/jaredtrog
|
||||
@@ -284,15 +290,15 @@ sponsors:
|
||||
- login: FernandoCelmer
|
||||
avatarUrl: https://avatars.githubusercontent.com/u/6262214?u=d29fff3fd862fda4ca752079f13f32e84c762ea4&v=4
|
||||
url: https://github.com/FernandoCelmer
|
||||
- login: simw
|
||||
avatarUrl: https://avatars.githubusercontent.com/u/6322526?v=4
|
||||
url: https://github.com/simw
|
||||
- - login: getsentry
|
||||
avatarUrl: https://avatars.githubusercontent.com/u/1396951?v=4
|
||||
url: https://github.com/getsentry
|
||||
- - login: pawamoy
|
||||
avatarUrl: https://avatars.githubusercontent.com/u/3999221?u=b030e4c89df2f3a36bc4710b925bdeb6745c9856&v=4
|
||||
url: https://github.com/pawamoy
|
||||
- login: SebTota
|
||||
avatarUrl: https://avatars.githubusercontent.com/u/25122511?v=4
|
||||
url: https://github.com/SebTota
|
||||
- login: nisutec
|
||||
avatarUrl: https://avatars.githubusercontent.com/u/25281462?u=e562484c451fdfc59053163f64405f8eb262b8b0&v=4
|
||||
url: https://github.com/nisutec
|
||||
@@ -305,15 +311,15 @@ sponsors:
|
||||
- login: rlnchow
|
||||
avatarUrl: https://avatars.githubusercontent.com/u/28018479?u=a93ca9cf1422b9ece155784a72d5f2fdbce7adff&v=4
|
||||
url: https://github.com/rlnchow
|
||||
- login: dvlpjrs
|
||||
avatarUrl: https://avatars.githubusercontent.com/u/32254642?u=fbd6ad0324d4f1eb6231cf775be1c7bd4404e961&v=4
|
||||
url: https://github.com/dvlpjrs
|
||||
- login: engineerjoe440
|
||||
avatarUrl: https://avatars.githubusercontent.com/u/33275230?u=eb223cad27017bb1e936ee9b429b450d092d0236&v=4
|
||||
url: https://github.com/engineerjoe440
|
||||
- login: bnkc
|
||||
avatarUrl: https://avatars.githubusercontent.com/u/34930566?u=fa1dc8db3e920cf5c5636b97180a6f811fa01aaf&v=4
|
||||
avatarUrl: https://avatars.githubusercontent.com/u/34930566?u=db5e6f4f87836cad26c2aa90ce390ce49041c5a9&v=4
|
||||
url: https://github.com/bnkc
|
||||
- login: DevOpsKev
|
||||
avatarUrl: https://avatars.githubusercontent.com/u/36336550?u=6ccd5978fdaab06f37e22f2a14a7439341df7f67&v=4
|
||||
url: https://github.com/DevOpsKev
|
||||
- login: petercool
|
||||
avatarUrl: https://avatars.githubusercontent.com/u/37613029?u=81c525232bb35780945a68e88afd96bb2cdad9c4&v=4
|
||||
url: https://github.com/petercool
|
||||
@@ -332,33 +338,33 @@ sponsors:
|
||||
- login: jangia
|
||||
avatarUrl: https://avatars.githubusercontent.com/u/17927101?u=9261b9bb0c3e3bb1ecba43e8915dc58d8c9a077e&v=4
|
||||
url: https://github.com/jangia
|
||||
- login: jackleeio
|
||||
avatarUrl: https://avatars.githubusercontent.com/u/20477587?u=c5184dab6d021733d10c8f975b20e391856303d6&v=4
|
||||
url: https://github.com/jackleeio
|
||||
- login: shuheng-liu
|
||||
avatarUrl: https://avatars.githubusercontent.com/u/22414322?u=813c45f30786c6b511b21a661def025d8f7b609e&v=4
|
||||
url: https://github.com/shuheng-liu
|
||||
- login: pers0n4
|
||||
avatarUrl: https://avatars.githubusercontent.com/u/24864600?u=f211a13a7b572cbbd7779b9c8d8cb428cc7ba07e&v=4
|
||||
url: https://github.com/pers0n4
|
||||
- login: SebTota
|
||||
avatarUrl: https://avatars.githubusercontent.com/u/25122511?v=4
|
||||
url: https://github.com/SebTota
|
||||
- login: fernandosmither
|
||||
avatarUrl: https://avatars.githubusercontent.com/u/66154723?u=a76a037b5d674938a75d2cff862fb6dfd63ec214&v=4
|
||||
url: https://github.com/fernandosmither
|
||||
- login: romabozhanovgithub
|
||||
avatarUrl: https://avatars.githubusercontent.com/u/67696229?u=e4b921eef096415300425aca249348f8abb78ad7&v=4
|
||||
url: https://github.com/romabozhanovgithub
|
||||
- login: PelicanQ
|
||||
avatarUrl: https://avatars.githubusercontent.com/u/77930606?v=4
|
||||
url: https://github.com/PelicanQ
|
||||
- login: jugeeem
|
||||
avatarUrl: https://avatars.githubusercontent.com/u/116043716?u=ae590d79c38ac79c91b9c5caa6887d061e865a3d&v=4
|
||||
url: https://github.com/jugeeem
|
||||
- login: tahmarrrr23
|
||||
avatarUrl: https://avatars.githubusercontent.com/u/138208610?u=465a46b0ff72a74252d3e3a71ac7d2f1919cda28&v=4
|
||||
url: https://github.com/tahmarrrr23
|
||||
- login: curegit
|
||||
avatarUrl: https://avatars.githubusercontent.com/u/37978051?u=1733c322079118c0cdc573c03d92813f50a9faec&v=4
|
||||
url: https://github.com/curegit
|
||||
- login: fernandosmither
|
||||
avatarUrl: https://avatars.githubusercontent.com/u/66154723?u=f79753eb207d01cca5bbb91ac62db6123e7622d1&v=4
|
||||
url: https://github.com/fernandosmither
|
||||
- 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: tahmarrrr23
|
||||
avatarUrl: https://avatars.githubusercontent.com/u/138208610?u=465a46b0ff72a74252d3e3a71ac7d2f1919cda28&v=4
|
||||
url: https://github.com/tahmarrrr23
|
||||
- login: zk-Call
|
||||
avatarUrl: https://avatars.githubusercontent.com/u/147117264?v=4
|
||||
url: https://github.com/zk-Call
|
||||
- login: kristiangronberg
|
||||
avatarUrl: https://avatars.githubusercontent.com/u/42678548?v=4
|
||||
url: https://github.com/kristiangronberg
|
||||
@@ -374,12 +380,21 @@ sponsors:
|
||||
- login: ArtyomVancyan
|
||||
avatarUrl: https://avatars.githubusercontent.com/u/44609997?v=4
|
||||
url: https://github.com/ArtyomVancyan
|
||||
- login: harol97
|
||||
avatarUrl: https://avatars.githubusercontent.com/u/49042862?u=2b18e115ab73f5f09a280be2850f93c58a12e3d2&v=4
|
||||
url: https://github.com/harol97
|
||||
- login: hgalytoby
|
||||
avatarUrl: https://avatars.githubusercontent.com/u/50397689?u=f4888c2c54929bd86eed0d3971d09fcb306e5088&v=4
|
||||
avatarUrl: https://avatars.githubusercontent.com/u/50397689?u=62c7ff3519858423579676cd0efbd7e3f1ffe63a&v=4
|
||||
url: https://github.com/hgalytoby
|
||||
- login: conservative-dude
|
||||
avatarUrl: https://avatars.githubusercontent.com/u/55538308?u=f250c44942ea6e73a6bd90739b381c470c192c11&v=4
|
||||
url: https://github.com/conservative-dude
|
||||
- login: Joaopcamposs
|
||||
avatarUrl: https://avatars.githubusercontent.com/u/57376574?u=699d5ba5ee66af1d089df6b5e532b97169e73650&v=4
|
||||
url: https://github.com/Joaopcamposs
|
||||
- login: browniebroke
|
||||
avatarUrl: https://avatars.githubusercontent.com/u/861044?u=5abfca5588f3e906b31583d7ee62f6de4b68aa24&v=4
|
||||
url: https://github.com/browniebroke
|
||||
- login: miguelgr
|
||||
avatarUrl: https://avatars.githubusercontent.com/u/1484589?u=54556072b8136efa12ae3b6902032ea2a39ace4b&v=4
|
||||
url: https://github.com/miguelgr
|
||||
@@ -395,9 +410,6 @@ sponsors:
|
||||
- login: cbonoz
|
||||
avatarUrl: https://avatars.githubusercontent.com/u/2351087?u=fd3e8030b2cc9fbfbb54a65e9890c548a016f58b&v=4
|
||||
url: https://github.com/cbonoz
|
||||
- login: anthonycorletti
|
||||
avatarUrl: https://avatars.githubusercontent.com/u/3477132?u=dfe51d2080fbd3fee81e05911cd8d50da9dcc709&v=4
|
||||
url: https://github.com/anthonycorletti
|
||||
- login: ddanier
|
||||
avatarUrl: https://avatars.githubusercontent.com/u/113563?u=ed1dc79de72f93bd78581f88ebc6952b62f472da&v=4
|
||||
url: https://github.com/ddanier
|
||||
@@ -422,9 +434,6 @@ sponsors:
|
||||
- login: tochikuji
|
||||
avatarUrl: https://avatars.githubusercontent.com/u/851759?v=4
|
||||
url: https://github.com/tochikuji
|
||||
- login: browniebroke
|
||||
avatarUrl: https://avatars.githubusercontent.com/u/861044?u=5abfca5588f3e906b31583d7ee62f6de4b68aa24&v=4
|
||||
url: https://github.com/browniebroke
|
||||
- login: KentShikama
|
||||
avatarUrl: https://avatars.githubusercontent.com/u/6329898?u=8b236810db9b96333230430837e1f021f9246da1&v=4
|
||||
url: https://github.com/KentShikama
|
||||
@@ -444,7 +453,7 @@ sponsors:
|
||||
avatarUrl: https://avatars.githubusercontent.com/u/9369632?u=8c988f1b008a3f601385a3616f9327820f66e3a5&v=4
|
||||
url: https://github.com/msehnout
|
||||
- login: xncbf
|
||||
avatarUrl: https://avatars.githubusercontent.com/u/9462045?u=ee91e210ae93b9cdd8f248b21cb028316cc0b747&v=4
|
||||
avatarUrl: https://avatars.githubusercontent.com/u/9462045?u=2ef1ede118a72c170805f50b9ad07341fd16a354&v=4
|
||||
url: https://github.com/xncbf
|
||||
- login: DMantis
|
||||
avatarUrl: https://avatars.githubusercontent.com/u/9536869?v=4
|
||||
@@ -467,9 +476,15 @@ sponsors:
|
||||
- login: dzoladz
|
||||
avatarUrl: https://avatars.githubusercontent.com/u/10561752?u=5ee314d54aa79592c18566827ad8914debd5630d&v=4
|
||||
url: https://github.com/dzoladz
|
||||
- login: Zuzah
|
||||
avatarUrl: https://avatars.githubusercontent.com/u/10934846?u=1ef43e075ddc87bd1178372bf4d95ee6175cae27&v=4
|
||||
url: https://github.com/Zuzah
|
||||
- login: Alisa-lisa
|
||||
avatarUrl: https://avatars.githubusercontent.com/u/4137964?u=e7e393504f554f4ff15863a1e01a5746863ef9ce&v=4
|
||||
url: https://github.com/Alisa-lisa
|
||||
- login: Graeme22
|
||||
avatarUrl: https://avatars.githubusercontent.com/u/4185684?u=498182a42300d7bcd4de1215190cb17eb501136c&v=4
|
||||
url: https://github.com/Graeme22
|
||||
- login: danielunderwood
|
||||
avatarUrl: https://avatars.githubusercontent.com/u/4472301?v=4
|
||||
url: https://github.com/danielunderwood
|
||||
@@ -488,30 +503,30 @@ sponsors:
|
||||
- login: jakeecolution
|
||||
avatarUrl: https://avatars.githubusercontent.com/u/5884696?u=4a7c7883fb064b593b50cb6697b54687e6f7aafe&v=4
|
||||
url: https://github.com/jakeecolution
|
||||
- - login: abizovnuralem
|
||||
avatarUrl: https://avatars.githubusercontent.com/u/33475993?u=6ce72b11a16a8232d3dd1f958f460b4735f520d8&v=4
|
||||
url: https://github.com/abizovnuralem
|
||||
- login: danburonline
|
||||
- login: stephane-rbn
|
||||
avatarUrl: https://avatars.githubusercontent.com/u/5939522?u=eb7ffe768fa3bcbcd04de14fe4a47444cc00ec4c&v=4
|
||||
url: https://github.com/stephane-rbn
|
||||
- - login: danburonline
|
||||
avatarUrl: https://avatars.githubusercontent.com/u/34251194?u=94935cccfbec58083ab1e535212d54f1bf2c978a&v=4
|
||||
url: https://github.com/danburonline
|
||||
- login: AliYmn
|
||||
avatarUrl: https://avatars.githubusercontent.com/u/18416653?u=0de5a262e8b4dc0a08d065f30f7a39941e246530&v=4
|
||||
url: https://github.com/AliYmn
|
||||
- login: sadikkuzu
|
||||
avatarUrl: https://avatars.githubusercontent.com/u/23168063?u=d179c06bb9f65c4167fcab118526819f8e0dac17&v=4
|
||||
url: https://github.com/sadikkuzu
|
||||
- login: tran-hai-long
|
||||
avatarUrl: https://avatars.githubusercontent.com/u/119793901?u=3b173a845dcf099b275bdc9713a69cbbc36040ce&v=4
|
||||
url: https://github.com/tran-hai-long
|
||||
- login: rwxd
|
||||
avatarUrl: https://avatars.githubusercontent.com/u/40308458?u=cd04a39e3655923be4f25c2ba8a5a07b3da3230a&v=4
|
||||
url: https://github.com/rwxd
|
||||
- login: YungBricoCoop
|
||||
avatarUrl: https://avatars.githubusercontent.com/u/42273436?u=80470b400c416d1eabc2cc71b1efffc0e3503146&v=4
|
||||
url: https://github.com/YungBricoCoop
|
||||
- login: nlazaro
|
||||
avatarUrl: https://avatars.githubusercontent.com/u/44237350?u=939a570fc965d93e9db1284b5acc173c1a0be4a0&v=4
|
||||
url: https://github.com/nlazaro
|
||||
- login: Patechoc
|
||||
avatarUrl: https://avatars.githubusercontent.com/u/2376641?u=23b49e9eda04f078cb74fa3f93593aa6a57bb138&v=4
|
||||
url: https://github.com/Patechoc
|
||||
- login: ssbarnea
|
||||
avatarUrl: https://avatars.githubusercontent.com/u/102495?u=c2efbf6fea2737e21dfc6b1113c4edc9644e9eaa&v=4
|
||||
url: https://github.com/ssbarnea
|
||||
- login: yuawn
|
||||
avatarUrl: https://avatars.githubusercontent.com/u/5111198?u=5315576f3fe1a70fd2d0f02181588f4eea5d353d&v=4
|
||||
url: https://github.com/yuawn
|
||||
- login: dongzhenye
|
||||
avatarUrl: https://avatars.githubusercontent.com/u/5765843?u=fe420c9a4c41e5b060faaf44029f5485616b470d&v=4
|
||||
url: https://github.com/dongzhenye
|
||||
|
||||
@@ -20,12 +20,21 @@ gold:
|
||||
- url: https://www.propelauth.com/?utm_source=fastapi&utm_campaign=1223&utm_medium=mainbadge
|
||||
title: Auth, user management and more for your B2B product
|
||||
img: https://fastapi.tiangolo.com/img/sponsors/propelauth.png
|
||||
- url: https://www.withcoherence.com/?utm_medium=advertising&utm_source=fastapi&utm_campaign=banner%20january%2024
|
||||
- url: https://docs.withcoherence.com/configuration/frameworks/?utm_medium=advertising&utm_source=fastapi&utm_campaign=docs#fastapi-example
|
||||
title: Coherence
|
||||
img: https://fastapi.tiangolo.com/img/sponsors/coherence.png
|
||||
- url: https://www.mongodb.com/developer/languages/python/python-quickstart-fastapi/?utm_campaign=fastapi_framework&utm_source=fastapi_sponsorship&utm_medium=web_referral
|
||||
title: Simplify Full Stack Development with FastAPI & MongoDB
|
||||
img: https://fastapi.tiangolo.com/img/sponsors/mongodb.png
|
||||
- url: https://konghq.com/products/kong-konnect?utm_medium=referral&utm_source=github&utm_campaign=platform&utm_content=fast-api
|
||||
title: Kong Konnect - API management platform
|
||||
img: https://fastapi.tiangolo.com/img/sponsors/kong.png
|
||||
- url: https://zuplo.link/fastapi-gh
|
||||
title: 'Zuplo: Scale, Protect, Document, and Monetize your FastAPI'
|
||||
img: https://fastapi.tiangolo.com/img/sponsors/zuplo.png
|
||||
- url: https://fine.dev?ref=fastapibadge
|
||||
title: "Fine's AI FastAPI Workflow: Effortlessly Deploy and Integrate FastAPI into Your Project"
|
||||
img: https://fastapi.tiangolo.com/img/sponsors/fine.png
|
||||
silver:
|
||||
- url: https://training.talkpython.fm/fastapi-courses
|
||||
title: FastAPI video courses on demand from people you trust
|
||||
@@ -45,6 +54,9 @@ silver:
|
||||
- url: https://www.codacy.com/?utm_source=github&utm_medium=sponsors&utm_id=pioneers
|
||||
title: Take code reviews from hours to minutes
|
||||
img: https://fastapi.tiangolo.com/img/sponsors/codacy.png
|
||||
- url: https://www.stainlessapi.com/?utm_source=fastapi&utm_medium=referral
|
||||
title: Stainless | Generate best-in-class SDKs
|
||||
img: https://fastapi.tiangolo.com/img/sponsors/stainless.png
|
||||
bronze:
|
||||
- url: https://www.exoflare.com/open-source/?utm_source=FastAPI&utm_campaign=open_source
|
||||
title: Biosecurity risk assessments made easy.
|
||||
|
||||
@@ -28,3 +28,5 @@ logins:
|
||||
- bump-sh
|
||||
- andrew-propelauth
|
||||
- svix
|
||||
- zuplo-oss
|
||||
- Kong
|
||||
|
||||
@@ -224,7 +224,7 @@ Here, `new_dict` will contain all the key-value pairs from `old_dict` plus the n
|
||||
}
|
||||
```
|
||||
|
||||
You can use that technique to re-use some predefined responses in your *path operations* and combine them with additional custom ones.
|
||||
You can use that technique to reuse some predefined responses in your *path operations* and combine them with additional custom ones.
|
||||
|
||||
For example:
|
||||
|
||||
|
||||
@@ -22,7 +22,7 @@ Even though all your code is written assuming there's just `/app`.
|
||||
{!../../../docs_src/behind_a_proxy/tutorial001.py!}
|
||||
```
|
||||
|
||||
And the proxy would be **"stripping"** the **path prefix** on the fly before transmitting the request to Uvicorn, keeping your application convinced that it is being served at `/app`, so that you don't have to update all your code to include the prefix `/api/v1`.
|
||||
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`.
|
||||
|
||||
Up to here, everything would work as normally.
|
||||
|
||||
@@ -63,7 +63,7 @@ The docs UI would also need the OpenAPI schema to declare that this API `server`
|
||||
}
|
||||
```
|
||||
|
||||
In this example, the "Proxy" could be something like **Traefik**. And the server would be something like **Uvicorn**, running your FastAPI application.
|
||||
In this example, the "Proxy" could be something like **Traefik**. And the server would be something like FastAPI CLI with **Uvicorn**, running your FastAPI application.
|
||||
|
||||
### Providing the `root_path`
|
||||
|
||||
@@ -72,7 +72,7 @@ To achieve this, you can use the command line option `--root-path` like:
|
||||
<div class="termy">
|
||||
|
||||
```console
|
||||
$ uvicorn main:app --root-path /api/v1
|
||||
$ fastapi run main.py --root-path /api/v1
|
||||
|
||||
<span style="color: green;">INFO</span>: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit)
|
||||
```
|
||||
@@ -101,7 +101,7 @@ Then, if you start Uvicorn with:
|
||||
<div class="termy">
|
||||
|
||||
```console
|
||||
$ uvicorn main:app --root-path /api/v1
|
||||
$ fastapi run main.py --root-path /api/v1
|
||||
|
||||
<span style="color: green;">INFO</span>: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit)
|
||||
```
|
||||
@@ -216,12 +216,12 @@ INFO[0000] Configuration loaded from file: /home/user/awesomeapi/traefik.toml
|
||||
|
||||
</div>
|
||||
|
||||
And now start your app with Uvicorn, using the `--root-path` option:
|
||||
And now start your app, using the `--root-path` option:
|
||||
|
||||
<div class="termy">
|
||||
|
||||
```console
|
||||
$ uvicorn main:app --root-path /api/v1
|
||||
$ fastapi run main.py --root-path /api/v1
|
||||
|
||||
<span style="color: green;">INFO</span>: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit)
|
||||
```
|
||||
|
||||
@@ -39,7 +39,7 @@ But if you are certain that the content that you are returning is **serializable
|
||||
And it will be documented as such in OpenAPI.
|
||||
|
||||
!!! tip
|
||||
The `ORJSONResponse` is currently only available in FastAPI, not in Starlette.
|
||||
The `ORJSONResponse` is only available in FastAPI, not in Starlette.
|
||||
|
||||
## HTML Response
|
||||
|
||||
@@ -149,10 +149,16 @@ This is the default response used in **FastAPI**, as you read above.
|
||||
|
||||
A fast alternative JSON response using <a href="https://github.com/ijl/orjson" class="external-link" target="_blank">`orjson`</a>, as you read above.
|
||||
|
||||
!!! info
|
||||
This requires installing `orjson` for example with `pip install orjson`.
|
||||
|
||||
### `UJSONResponse`
|
||||
|
||||
An alternative JSON response using <a href="https://github.com/ultrajson/ultrajson" class="external-link" target="_blank">`ujson`</a>.
|
||||
|
||||
!!! info
|
||||
This requires installing `ujson` for example with `pip install ujson`.
|
||||
|
||||
!!! warning
|
||||
`ujson` is less careful than Python's built-in implementation in how it handles some edge-cases.
|
||||
|
||||
|
||||
@@ -20,7 +20,7 @@ Some of them also ✨ [**sponsor FastAPI**](../help-fastapi.md#sponsor-the-autho
|
||||
|
||||
And it shows their true commitment to FastAPI and its **community** (you), as they not only want to provide you a **good service** but also want to make sure you have a **good and healthy framework**, FastAPI. 🙇
|
||||
|
||||
For example, you might want to try <a href="https://speakeasyapi.dev/?utm_source=fastapi+repo&utm_medium=github+sponsorship" class="external-link" target="_blank">Speakeasy</a>.
|
||||
For example, you might want to try <a href="https://speakeasyapi.dev/?utm_source=fastapi+repo&utm_medium=github+sponsorship" class="external-link" target="_blank">Speakeasy</a> and <a href="https://www.stainlessapi.com/?utm_source=fastapi&utm_medium=referral" class="external-link" target="_blank">Stainless</a>.
|
||||
|
||||
There are also several other companies offering similar services that you can search and find online. 🤓
|
||||
|
||||
|
||||
@@ -172,7 +172,7 @@ Now use the parameter `callbacks` in *your API's path operation decorator* to pa
|
||||
|
||||
### Check the docs
|
||||
|
||||
Now you can start your app with Uvicorn and go to <a href="http://127.0.0.1:8000/docs" class="external-link" target="_blank">http://127.0.0.1:8000/docs</a>.
|
||||
Now you can start your app and go to <a href="http://127.0.0.1:8000/docs" class="external-link" target="_blank">http://127.0.0.1:8000/docs</a>.
|
||||
|
||||
You will see your docs including a "Callbacks" section for your *path operation* that shows how the *external API* should look like:
|
||||
|
||||
|
||||
@@ -44,7 +44,7 @@ This is because it is expected that **your users** would define the actual **URL
|
||||
|
||||
### Check the docs
|
||||
|
||||
Now you can start your app with Uvicorn and go to <a href="http://127.0.0.1:8000/docs" class="external-link" target="_blank">http://127.0.0.1:8000/docs</a>.
|
||||
Now you can start your app and go to <a href="http://127.0.0.1:8000/docs" class="external-link" target="_blank">http://127.0.0.1:8000/docs</a>.
|
||||
|
||||
You will see your docs have the normal *path operations* and now also some **webhooks**:
|
||||
|
||||
|
||||
@@ -187,6 +187,6 @@ And then in our code, we parse that YAML content directly, and then we are again
|
||||
In Pydantic version 1 the method to parse and validate an object was `Item.parse_obj()`, in Pydantic version 2, the method is called `Item.model_validate()`.
|
||||
|
||||
!!! tip
|
||||
Here we re-use the same Pydantic model.
|
||||
Here we reuse the same Pydantic model.
|
||||
|
||||
But the same way, we could have validated it in some other way.
|
||||
|
||||
@@ -58,19 +58,19 @@ First, let's quickly see the parts that change from the examples in the main **T
|
||||
|
||||
=== "Python 3.10+"
|
||||
|
||||
```Python hl_lines="4 8 12 46 64 105 107-115 121-124 128-134 139 155"
|
||||
```Python hl_lines="5 9 13 47 65 106 108-116 122-125 129-135 140 156"
|
||||
{!> ../../../docs_src/security/tutorial005_an_py310.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.9+"
|
||||
|
||||
```Python hl_lines="2 4 8 12 46 64 105 107-115 121-124 128-134 139 155"
|
||||
```Python hl_lines="2 5 9 13 47 65 106 108-116 122-125 129-135 140 156"
|
||||
{!> ../../../docs_src/security/tutorial005_an_py39.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.8+"
|
||||
|
||||
```Python hl_lines="2 4 8 12 47 65 106 108-116 122-125 129-135 140 156"
|
||||
```Python hl_lines="2 5 9 13 48 66 107 109-117 123-126 130-136 141 157"
|
||||
{!> ../../../docs_src/security/tutorial005_an.py!}
|
||||
```
|
||||
|
||||
@@ -79,7 +79,7 @@ First, let's quickly see the parts that change from the examples in the main **T
|
||||
!!! tip
|
||||
Prefer to use the `Annotated` version if possible.
|
||||
|
||||
```Python hl_lines="3 7 11 45 63 104 106-114 120-123 127-133 138 154"
|
||||
```Python hl_lines="4 8 12 46 64 105 107-115 121-124 128-134 139 155"
|
||||
{!> ../../../docs_src/security/tutorial005_py310.py!}
|
||||
```
|
||||
|
||||
@@ -88,7 +88,7 @@ First, let's quickly see the parts that change from the examples in the main **T
|
||||
!!! tip
|
||||
Prefer to use the `Annotated` version if possible.
|
||||
|
||||
```Python hl_lines="2 4 8 12 46 64 105 107-115 121-124 128-134 139 155"
|
||||
```Python hl_lines="2 5 9 13 47 65 106 108-116 122-125 129-135 140 156"
|
||||
{!> ../../../docs_src/security/tutorial005_py39.py!}
|
||||
```
|
||||
|
||||
@@ -97,7 +97,7 @@ First, let's quickly see the parts that change from the examples in the main **T
|
||||
!!! tip
|
||||
Prefer to use the `Annotated` version if possible.
|
||||
|
||||
```Python hl_lines="2 4 8 12 46 64 105 107-115 121-124 128-134 139 155"
|
||||
```Python hl_lines="2 5 9 13 47 65 106 108-116 122-125 129-135 140 156"
|
||||
{!> ../../../docs_src/security/tutorial005.py!}
|
||||
```
|
||||
|
||||
@@ -111,19 +111,19 @@ The `scopes` parameter receives a `dict` with each scope as a key and the descri
|
||||
|
||||
=== "Python 3.10+"
|
||||
|
||||
```Python hl_lines="62-65"
|
||||
```Python hl_lines="63-66"
|
||||
{!> ../../../docs_src/security/tutorial005_an_py310.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.9+"
|
||||
|
||||
```Python hl_lines="62-65"
|
||||
```Python hl_lines="63-66"
|
||||
{!> ../../../docs_src/security/tutorial005_an_py39.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.8+"
|
||||
|
||||
```Python hl_lines="63-66"
|
||||
```Python hl_lines="64-67"
|
||||
{!> ../../../docs_src/security/tutorial005_an.py!}
|
||||
```
|
||||
|
||||
@@ -132,7 +132,7 @@ The `scopes` parameter receives a `dict` with each scope as a key and the descri
|
||||
!!! tip
|
||||
Prefer to use the `Annotated` version if possible.
|
||||
|
||||
```Python hl_lines="61-64"
|
||||
```Python hl_lines="62-65"
|
||||
{!> ../../../docs_src/security/tutorial005_py310.py!}
|
||||
```
|
||||
|
||||
@@ -142,7 +142,7 @@ The `scopes` parameter receives a `dict` with each scope as a key and the descri
|
||||
!!! tip
|
||||
Prefer to use the `Annotated` version if possible.
|
||||
|
||||
```Python hl_lines="62-65"
|
||||
```Python hl_lines="63-66"
|
||||
{!> ../../../docs_src/security/tutorial005_py39.py!}
|
||||
```
|
||||
|
||||
@@ -151,7 +151,7 @@ The `scopes` parameter receives a `dict` with each scope as a key and the descri
|
||||
!!! tip
|
||||
Prefer to use the `Annotated` version if possible.
|
||||
|
||||
```Python hl_lines="62-65"
|
||||
```Python hl_lines="63-66"
|
||||
{!> ../../../docs_src/security/tutorial005.py!}
|
||||
```
|
||||
|
||||
@@ -178,19 +178,19 @@ And we return the scopes as part of the JWT token.
|
||||
|
||||
=== "Python 3.10+"
|
||||
|
||||
```Python hl_lines="155"
|
||||
```Python hl_lines="156"
|
||||
{!> ../../../docs_src/security/tutorial005_an_py310.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.9+"
|
||||
|
||||
```Python hl_lines="155"
|
||||
```Python hl_lines="156"
|
||||
{!> ../../../docs_src/security/tutorial005_an_py39.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.8+"
|
||||
|
||||
```Python hl_lines="156"
|
||||
```Python hl_lines="157"
|
||||
{!> ../../../docs_src/security/tutorial005_an.py!}
|
||||
```
|
||||
|
||||
@@ -199,7 +199,7 @@ And we return the scopes as part of the JWT token.
|
||||
!!! tip
|
||||
Prefer to use the `Annotated` version if possible.
|
||||
|
||||
```Python hl_lines="154"
|
||||
```Python hl_lines="155"
|
||||
{!> ../../../docs_src/security/tutorial005_py310.py!}
|
||||
```
|
||||
|
||||
@@ -208,7 +208,7 @@ And we return the scopes as part of the JWT token.
|
||||
!!! tip
|
||||
Prefer to use the `Annotated` version if possible.
|
||||
|
||||
```Python hl_lines="155"
|
||||
```Python hl_lines="156"
|
||||
{!> ../../../docs_src/security/tutorial005_py39.py!}
|
||||
```
|
||||
|
||||
@@ -217,7 +217,7 @@ And we return the scopes as part of the JWT token.
|
||||
!!! tip
|
||||
Prefer to use the `Annotated` version if possible.
|
||||
|
||||
```Python hl_lines="155"
|
||||
```Python hl_lines="156"
|
||||
{!> ../../../docs_src/security/tutorial005.py!}
|
||||
```
|
||||
|
||||
@@ -244,19 +244,19 @@ In this case, it requires the scope `me` (it could require more than one scope).
|
||||
|
||||
=== "Python 3.10+"
|
||||
|
||||
```Python hl_lines="4 139 170"
|
||||
```Python hl_lines="5 140 171"
|
||||
{!> ../../../docs_src/security/tutorial005_an_py310.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.9+"
|
||||
|
||||
```Python hl_lines="4 139 170"
|
||||
```Python hl_lines="5 140 171"
|
||||
{!> ../../../docs_src/security/tutorial005_an_py39.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.8+"
|
||||
|
||||
```Python hl_lines="4 140 171"
|
||||
```Python hl_lines="5 141 172"
|
||||
{!> ../../../docs_src/security/tutorial005_an.py!}
|
||||
```
|
||||
|
||||
@@ -265,7 +265,7 @@ In this case, it requires the scope `me` (it could require more than one scope).
|
||||
!!! tip
|
||||
Prefer to use the `Annotated` version if possible.
|
||||
|
||||
```Python hl_lines="3 138 167"
|
||||
```Python hl_lines="4 139 168"
|
||||
{!> ../../../docs_src/security/tutorial005_py310.py!}
|
||||
```
|
||||
|
||||
@@ -274,7 +274,7 @@ In this case, it requires the scope `me` (it could require more than one scope).
|
||||
!!! tip
|
||||
Prefer to use the `Annotated` version if possible.
|
||||
|
||||
```Python hl_lines="4 139 168"
|
||||
```Python hl_lines="5 140 169"
|
||||
{!> ../../../docs_src/security/tutorial005_py39.py!}
|
||||
```
|
||||
|
||||
@@ -283,7 +283,7 @@ In this case, it requires the scope `me` (it could require more than one scope).
|
||||
!!! tip
|
||||
Prefer to use the `Annotated` version if possible.
|
||||
|
||||
```Python hl_lines="4 139 168"
|
||||
```Python hl_lines="5 140 169"
|
||||
{!> ../../../docs_src/security/tutorial005.py!}
|
||||
```
|
||||
|
||||
@@ -310,19 +310,19 @@ This `SecurityScopes` class is similar to `Request` (`Request` was used to get t
|
||||
|
||||
=== "Python 3.10+"
|
||||
|
||||
```Python hl_lines="8 105"
|
||||
```Python hl_lines="9 106"
|
||||
{!> ../../../docs_src/security/tutorial005_an_py310.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.9+"
|
||||
|
||||
```Python hl_lines="8 105"
|
||||
```Python hl_lines="9 106"
|
||||
{!> ../../../docs_src/security/tutorial005_an_py39.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.8+"
|
||||
|
||||
```Python hl_lines="8 106"
|
||||
```Python hl_lines="9 107"
|
||||
{!> ../../../docs_src/security/tutorial005_an.py!}
|
||||
```
|
||||
|
||||
@@ -331,7 +331,7 @@ This `SecurityScopes` class is similar to `Request` (`Request` was used to get t
|
||||
!!! tip
|
||||
Prefer to use the `Annotated` version if possible.
|
||||
|
||||
```Python hl_lines="7 104"
|
||||
```Python hl_lines="8 105"
|
||||
{!> ../../../docs_src/security/tutorial005_py310.py!}
|
||||
```
|
||||
|
||||
@@ -340,7 +340,7 @@ This `SecurityScopes` class is similar to `Request` (`Request` was used to get t
|
||||
!!! tip
|
||||
Prefer to use the `Annotated` version if possible.
|
||||
|
||||
```Python hl_lines="8 105"
|
||||
```Python hl_lines="9 106"
|
||||
{!> ../../../docs_src/security/tutorial005_py39.py!}
|
||||
```
|
||||
|
||||
@@ -349,7 +349,7 @@ This `SecurityScopes` class is similar to `Request` (`Request` was used to get t
|
||||
!!! tip
|
||||
Prefer to use the `Annotated` version if possible.
|
||||
|
||||
```Python hl_lines="8 105"
|
||||
```Python hl_lines="9 106"
|
||||
{!> ../../../docs_src/security/tutorial005.py!}
|
||||
```
|
||||
|
||||
@@ -361,25 +361,25 @@ It will have a property `scopes` with a list containing all the scopes required
|
||||
|
||||
The `security_scopes` object (of class `SecurityScopes`) also provides a `scope_str` attribute with a single string, containing those scopes separated by spaces (we are going to use it).
|
||||
|
||||
We create an `HTTPException` that we can re-use (`raise`) later at several points.
|
||||
We create an `HTTPException` that we can reuse (`raise`) later at several points.
|
||||
|
||||
In this exception, we include the scopes required (if any) as a string separated by spaces (using `scope_str`). We put that string containing the scopes in the `WWW-Authenticate` header (this is part of the spec).
|
||||
|
||||
=== "Python 3.10+"
|
||||
|
||||
```Python hl_lines="105 107-115"
|
||||
```Python hl_lines="106 108-116"
|
||||
{!> ../../../docs_src/security/tutorial005_an_py310.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.9+"
|
||||
|
||||
```Python hl_lines="105 107-115"
|
||||
```Python hl_lines="106 108-116"
|
||||
{!> ../../../docs_src/security/tutorial005_an_py39.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.8+"
|
||||
|
||||
```Python hl_lines="106 108-116"
|
||||
```Python hl_lines="107 109-117"
|
||||
{!> ../../../docs_src/security/tutorial005_an.py!}
|
||||
```
|
||||
|
||||
@@ -388,7 +388,7 @@ In this exception, we include the scopes required (if any) as a string separated
|
||||
!!! tip
|
||||
Prefer to use the `Annotated` version if possible.
|
||||
|
||||
```Python hl_lines="104 106-114"
|
||||
```Python hl_lines="105 107-115"
|
||||
{!> ../../../docs_src/security/tutorial005_py310.py!}
|
||||
```
|
||||
|
||||
@@ -397,7 +397,7 @@ In this exception, we include the scopes required (if any) as a string separated
|
||||
!!! tip
|
||||
Prefer to use the `Annotated` version if possible.
|
||||
|
||||
```Python hl_lines="105 107-115"
|
||||
```Python hl_lines="106 108-116"
|
||||
{!> ../../../docs_src/security/tutorial005_py39.py!}
|
||||
```
|
||||
|
||||
@@ -406,7 +406,7 @@ In this exception, we include the scopes required (if any) as a string separated
|
||||
!!! tip
|
||||
Prefer to use the `Annotated` version if possible.
|
||||
|
||||
```Python hl_lines="105 107-115"
|
||||
```Python hl_lines="106 108-116"
|
||||
{!> ../../../docs_src/security/tutorial005.py!}
|
||||
```
|
||||
|
||||
@@ -426,19 +426,19 @@ We also verify that we have a user with that username, and if not, we raise that
|
||||
|
||||
=== "Python 3.10+"
|
||||
|
||||
```Python hl_lines="46 116-127"
|
||||
```Python hl_lines="47 117-128"
|
||||
{!> ../../../docs_src/security/tutorial005_an_py310.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.9+"
|
||||
|
||||
```Python hl_lines="46 116-127"
|
||||
```Python hl_lines="47 117-128"
|
||||
{!> ../../../docs_src/security/tutorial005_an_py39.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.8+"
|
||||
|
||||
```Python hl_lines="47 117-128"
|
||||
```Python hl_lines="48 118-129"
|
||||
{!> ../../../docs_src/security/tutorial005_an.py!}
|
||||
```
|
||||
|
||||
@@ -447,7 +447,7 @@ We also verify that we have a user with that username, and if not, we raise that
|
||||
!!! tip
|
||||
Prefer to use the `Annotated` version if possible.
|
||||
|
||||
```Python hl_lines="45 115-126"
|
||||
```Python hl_lines="46 116-127"
|
||||
{!> ../../../docs_src/security/tutorial005_py310.py!}
|
||||
```
|
||||
|
||||
@@ -456,7 +456,7 @@ We also verify that we have a user with that username, and if not, we raise that
|
||||
!!! tip
|
||||
Prefer to use the `Annotated` version if possible.
|
||||
|
||||
```Python hl_lines="46 116-127"
|
||||
```Python hl_lines="47 117-128"
|
||||
{!> ../../../docs_src/security/tutorial005_py39.py!}
|
||||
```
|
||||
|
||||
@@ -465,7 +465,7 @@ We also verify that we have a user with that username, and if not, we raise that
|
||||
!!! tip
|
||||
Prefer to use the `Annotated` version if possible.
|
||||
|
||||
```Python hl_lines="46 116-127"
|
||||
```Python hl_lines="47 117-128"
|
||||
{!> ../../../docs_src/security/tutorial005.py!}
|
||||
```
|
||||
|
||||
@@ -477,19 +477,19 @@ For this, we use `security_scopes.scopes`, that contains a `list` with all these
|
||||
|
||||
=== "Python 3.10+"
|
||||
|
||||
```Python hl_lines="128-134"
|
||||
```Python hl_lines="129-135"
|
||||
{!> ../../../docs_src/security/tutorial005_an_py310.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.9+"
|
||||
|
||||
```Python hl_lines="128-134"
|
||||
```Python hl_lines="129-135"
|
||||
{!> ../../../docs_src/security/tutorial005_an_py39.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.8+"
|
||||
|
||||
```Python hl_lines="129-135"
|
||||
```Python hl_lines="130-136"
|
||||
{!> ../../../docs_src/security/tutorial005_an.py!}
|
||||
```
|
||||
|
||||
@@ -498,7 +498,7 @@ For this, we use `security_scopes.scopes`, that contains a `list` with all these
|
||||
!!! tip
|
||||
Prefer to use the `Annotated` version if possible.
|
||||
|
||||
```Python hl_lines="127-133"
|
||||
```Python hl_lines="128-134"
|
||||
{!> ../../../docs_src/security/tutorial005_py310.py!}
|
||||
```
|
||||
|
||||
@@ -507,7 +507,7 @@ For this, we use `security_scopes.scopes`, that contains a `list` with all these
|
||||
!!! tip
|
||||
Prefer to use the `Annotated` version if possible.
|
||||
|
||||
```Python hl_lines="128-134"
|
||||
```Python hl_lines="129-135"
|
||||
{!> ../../../docs_src/security/tutorial005_py39.py!}
|
||||
```
|
||||
|
||||
@@ -516,7 +516,7 @@ For this, we use `security_scopes.scopes`, that contains a `list` with all these
|
||||
!!! tip
|
||||
Prefer to use the `Annotated` version if possible.
|
||||
|
||||
```Python hl_lines="128-134"
|
||||
```Python hl_lines="129-135"
|
||||
{!> ../../../docs_src/security/tutorial005.py!}
|
||||
```
|
||||
|
||||
|
||||
@@ -199,7 +199,7 @@ Next, you would run the server passing the configurations as environment variabl
|
||||
<div class="termy">
|
||||
|
||||
```console
|
||||
$ ADMIN_EMAIL="deadpool@example.com" APP_NAME="ChimichangApp" uvicorn main:app
|
||||
$ ADMIN_EMAIL="deadpool@example.com" APP_NAME="ChimichangApp" fastapi run main.py
|
||||
|
||||
<span style="color: green;">INFO</span>: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit)
|
||||
```
|
||||
@@ -369,7 +369,7 @@ Here we define the config `env_file` inside of your Pydantic `Settings` class, a
|
||||
|
||||
### Creating the `Settings` only once with `lru_cache`
|
||||
|
||||
Reading a file from disk is normally a costly (slow) operation, so you probably want to do it only once and then re-use the same settings object, instead of reading it for each request.
|
||||
Reading a file from disk is normally a costly (slow) operation, so you probably want to do it only once and then reuse the same settings object, instead of reading it for each request.
|
||||
|
||||
But every time we do:
|
||||
|
||||
|
||||
@@ -23,7 +23,7 @@ $ pip install jinja2
|
||||
## Using `Jinja2Templates`
|
||||
|
||||
* Import `Jinja2Templates`.
|
||||
* Create a `templates` object that you can re-use later.
|
||||
* Create a `templates` object that you can reuse later.
|
||||
* Declare a `Request` parameter in the *path operation* that will return a template.
|
||||
* Use the `templates` you created to render and return a `TemplateResponse`, 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.
|
||||
|
||||
|
||||
@@ -72,7 +72,7 @@ If your file is named `main.py`, run your application with:
|
||||
<div class="termy">
|
||||
|
||||
```console
|
||||
$ uvicorn main:app --reload
|
||||
$ fastapi dev main.py
|
||||
|
||||
<span style="color: green;">INFO</span>: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit)
|
||||
```
|
||||
@@ -160,7 +160,7 @@ If your file is named `main.py`, run your application with:
|
||||
<div class="termy">
|
||||
|
||||
```console
|
||||
$ uvicorn main:app --reload
|
||||
$ fastapi dev main.py
|
||||
|
||||
<span style="color: green;">INFO</span>: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit)
|
||||
```
|
||||
|
||||
@@ -22,7 +22,7 @@ Now, every request under the path `/v1/` will be handled by the Flask applicatio
|
||||
|
||||
And the rest will be handled by **FastAPI**.
|
||||
|
||||
If you run it with Uvicorn and go to <a href="http://localhost:8000/v1/" class="external-link" target="_blank">http://localhost:8000/v1/</a> you will see the response from Flask:
|
||||
If you run it and go to <a href="http://localhost:8000/v1/" class="external-link" target="_blank">http://localhost:8000/v1/</a> you will see the response from Flask:
|
||||
|
||||
```txt
|
||||
Hello, World from Flask!
|
||||
|
||||
@@ -222,7 +222,7 @@ All of the cashiers doing all the work with one client after the other 👨
|
||||
|
||||
And you have to wait 🕙 in the line for a long time or you lose your turn.
|
||||
|
||||
You probably wouldn't want to take your crush 😍 with you to do errands at the bank 🏦.
|
||||
You probably wouldn't want to take your crush 😍 with you to run errands at the bank 🏦.
|
||||
|
||||
### Burger Conclusion
|
||||
|
||||
|
||||
@@ -26,6 +26,7 @@
|
||||
position: relative;
|
||||
-webkit-box-sizing: border-box;
|
||||
box-sizing: border-box;
|
||||
line-height: 1.2;
|
||||
}
|
||||
|
||||
[data-termynal]:before {
|
||||
|
||||
@@ -94,7 +94,7 @@ In most cases, when you create a web API, you want it to be **always running**,
|
||||
|
||||
### In a Remote Server
|
||||
|
||||
When you set up a remote server (a cloud server, a virtual machine, etc.) the simplest thing you can do is to run Uvicorn (or similar) manually, the same way you do when developing locally.
|
||||
When you set up a remote server (a cloud server, a virtual machine, etc.) the simplest thing you can do is to use `fastapi run`, Uvicorn (or similar) manually, the same way you do when developing locally.
|
||||
|
||||
And it will work and will be useful **during development**.
|
||||
|
||||
|
||||
@@ -21,10 +21,10 @@ RUN pip install --no-cache-dir --upgrade -r /code/requirements.txt
|
||||
|
||||
COPY ./app /code/app
|
||||
|
||||
CMD ["uvicorn", "app.main:app", "--host", "0.0.0.0", "--port", "80"]
|
||||
CMD ["fastapi", "run", "app/main.py", "--port", "80"]
|
||||
|
||||
# If running behind a proxy like Nginx or Traefik add --proxy-headers
|
||||
# CMD ["uvicorn", "app.main:app", "--host", "0.0.0.0", "--port", "80", "--proxy-headers"]
|
||||
# CMD ["fastapi", "run", "app/main.py", "--port", "80", "--proxy-headers"]
|
||||
```
|
||||
|
||||
</details>
|
||||
@@ -70,7 +70,7 @@ And there are many other images for different things like databases, for example
|
||||
|
||||
By using a pre-made container image it's very easy to **combine** and use different tools. For example, to try out a new database. In most cases, you can use the **official images**, and just configure them with environment variables.
|
||||
|
||||
That way, in many cases you can learn about containers and Docker and re-use that knowledge with many different tools and components.
|
||||
That way, in many cases you can learn about containers and Docker and reuse that knowledge with many different tools and components.
|
||||
|
||||
So, you would run **multiple containers** with different things, like a database, a Python application, a web server with a React frontend application, and connect them together via their internal network.
|
||||
|
||||
@@ -113,9 +113,8 @@ You would of course use the same ideas you read in [About FastAPI versions](vers
|
||||
For example, your `requirements.txt` could look like:
|
||||
|
||||
```
|
||||
fastapi>=0.68.0,<0.69.0
|
||||
pydantic>=1.8.0,<2.0.0
|
||||
uvicorn>=0.15.0,<0.16.0
|
||||
fastapi>=0.112.0,<0.113.0
|
||||
pydantic>=2.7.0,<3.0.0
|
||||
```
|
||||
|
||||
And you would normally install those package dependencies with `pip`, for example:
|
||||
@@ -125,7 +124,7 @@ And you would normally install those package dependencies with `pip`, for exampl
|
||||
```console
|
||||
$ pip install -r requirements.txt
|
||||
---> 100%
|
||||
Successfully installed fastapi pydantic uvicorn
|
||||
Successfully installed fastapi pydantic
|
||||
```
|
||||
|
||||
</div>
|
||||
@@ -133,8 +132,6 @@ Successfully installed fastapi pydantic uvicorn
|
||||
!!! info
|
||||
There are other formats and tools to define and install package dependencies.
|
||||
|
||||
I'll show you an example using Poetry later in a section below. 👇
|
||||
|
||||
### Create the **FastAPI** Code
|
||||
|
||||
* Create an `app` directory and enter it.
|
||||
@@ -180,7 +177,7 @@ RUN pip install --no-cache-dir --upgrade -r /code/requirements.txt
|
||||
COPY ./app /code/app
|
||||
|
||||
# (6)
|
||||
CMD ["uvicorn", "app.main:app", "--host", "0.0.0.0", "--port", "80"]
|
||||
CMD ["fastapi", "run", "app/main.py", "--port", "80"]
|
||||
```
|
||||
|
||||
1. Start from the official Python base image.
|
||||
@@ -214,14 +211,12 @@ CMD ["uvicorn", "app.main:app", "--host", "0.0.0.0", "--port", "80"]
|
||||
|
||||
So, it's important to put this **near the end** of the `Dockerfile`, to optimize the container image build times.
|
||||
|
||||
6. Set the **command** to run the `uvicorn` server.
|
||||
6. Set the **command** to use `fastapi run`, which uses Uvicorn underneath.
|
||||
|
||||
`CMD` takes a list of strings, each of these strings is what you would type in the command line separated by spaces.
|
||||
|
||||
This command will be run from the **current working directory**, the same `/code` directory you set above with `WORKDIR /code`.
|
||||
|
||||
Because the program will be started at `/code` and inside of it is the directory `./app` with your code, **Uvicorn** will be able to see and **import** `app` from `app.main`.
|
||||
|
||||
!!! tip
|
||||
Review what each line does by clicking each number bubble in the code. 👆
|
||||
|
||||
@@ -238,10 +233,10 @@ You should now have a directory structure like:
|
||||
|
||||
#### Behind a TLS Termination Proxy
|
||||
|
||||
If you are running your container behind a TLS Termination Proxy (load balancer) like Nginx or Traefik, add the option `--proxy-headers`, this will tell Uvicorn to trust the headers sent by that proxy telling it that the application is running behind HTTPS, etc.
|
||||
If you are running your container behind a TLS Termination Proxy (load balancer) like Nginx or Traefik, add the option `--proxy-headers`, this will tell Uvicorn (through the FastAPI CLI) to trust the headers sent by that proxy telling it that the application is running behind HTTPS, etc.
|
||||
|
||||
```Dockerfile
|
||||
CMD ["uvicorn", "app.main:app", "--proxy-headers", "--host", "0.0.0.0", "--port", "80"]
|
||||
CMD ["fastapi", "run", "app/main.py", "--proxy-headers", "--port", "80"]
|
||||
```
|
||||
|
||||
#### Docker Cache
|
||||
@@ -254,7 +249,7 @@ COPY ./requirements.txt /code/requirements.txt
|
||||
|
||||
Docker and other tools **build** these container images **incrementally**, adding **one layer on top of the other**, starting from the top of the `Dockerfile` and adding any files created by each of the instructions of the `Dockerfile`.
|
||||
|
||||
Docker and similar tools also use an **internal cache** when building the image, if a file hasn't changed since the last time building the container image, then it will **re-use the same layer** created the last time, instead of copying the file again and creating a new layer from scratch.
|
||||
Docker and similar tools also use an **internal cache** when building the image, if a file hasn't changed since the last time building the container image, then it will **reuse the same layer** created the last time, instead of copying the file again and creating a new layer from scratch.
|
||||
|
||||
Just avoiding the copy of files doesn't necessarily improve things too much, but because it used the cache for that step, it can **use the cache for the next step**. For example, it could use the cache for the instruction that installs dependencies with:
|
||||
|
||||
@@ -362,14 +357,14 @@ RUN pip install --no-cache-dir --upgrade -r /code/requirements.txt
|
||||
COPY ./main.py /code/
|
||||
|
||||
# (2)
|
||||
CMD ["uvicorn", "main:app", "--host", "0.0.0.0", "--port", "80"]
|
||||
CMD ["fastapi", "run", "main.py", "--port", "80"]
|
||||
```
|
||||
|
||||
1. Copy the `main.py` file to the `/code` directory directly (without any `./app` directory).
|
||||
|
||||
2. Run Uvicorn and tell it to import the `app` object from `main` (instead of importing from `app.main`).
|
||||
2. Use `fastapi run` to serve your application in the single file `main.py`.
|
||||
|
||||
Then adjust the Uvicorn command to use the new module `main` instead of `app.main` to import the FastAPI object `app`.
|
||||
When you pass the file to `fastapi run` it will detect automatically that it is a single file and not part of a package and will know how to import it and serve your FastAPI app. 😎
|
||||
|
||||
## Deployment Concepts
|
||||
|
||||
@@ -626,7 +621,7 @@ RUN pip install --no-cache-dir --upgrade -r /code/requirements.txt
|
||||
COPY ./app /code/app
|
||||
|
||||
# (11)
|
||||
CMD ["uvicorn", "app.main:app", "--host", "0.0.0.0", "--port", "80"]
|
||||
CMD ["fastapi", "run", "app/main.py", "--port", "80"]
|
||||
```
|
||||
|
||||
1. This is the first stage, it is named `requirements-stage`.
|
||||
@@ -655,7 +650,7 @@ CMD ["uvicorn", "app.main:app", "--host", "0.0.0.0", "--port", "80"]
|
||||
|
||||
10. Copy the `app` directory to the `/code` directory.
|
||||
|
||||
11. Run the `uvicorn` command, telling it to use the `app` object imported from `app.main`.
|
||||
11. Use the `fastapi run` command to run your app.
|
||||
|
||||
!!! tip
|
||||
Click the bubble numbers to see what each line does.
|
||||
@@ -677,7 +672,7 @@ Then in the next (and final) stage you would build the image more or less in the
|
||||
Again, if you are running your container behind a TLS Termination Proxy (load balancer) like Nginx or Traefik, add the option `--proxy-headers` to the command:
|
||||
|
||||
```Dockerfile
|
||||
CMD ["uvicorn", "app.main:app", "--proxy-headers", "--host", "0.0.0.0", "--port", "80"]
|
||||
CMD ["fastapi", "run", "app/main.py", "--proxy-headers", "--port", "80"]
|
||||
```
|
||||
|
||||
## Recap
|
||||
|
||||
@@ -1,11 +1,71 @@
|
||||
# Run a Server Manually - Uvicorn
|
||||
# Run a Server Manually
|
||||
|
||||
The main thing you need to run a **FastAPI** application in a remote server machine is an ASGI server program like **Uvicorn**.
|
||||
## Use the `fastapi run` Command
|
||||
|
||||
There are 3 main alternatives:
|
||||
In short, use `fastapi run` to serve your FastAPI application:
|
||||
|
||||
<div class="termy">
|
||||
|
||||
```console
|
||||
$ <font color="#4E9A06">fastapi</font> run <u style="text-decoration-style:single">main.py</u>
|
||||
<font color="#3465A4">INFO </font> Using path <font color="#3465A4">main.py</font>
|
||||
<font color="#3465A4">INFO </font> Resolved absolute path <font color="#75507B">/home/user/code/awesomeapp/</font><font color="#AD7FA8">main.py</font>
|
||||
<font color="#3465A4">INFO </font> Searching for package file structure from directories with <font color="#3465A4">__init__.py</font> files
|
||||
<font color="#3465A4">INFO </font> Importing from <font color="#75507B">/home/user/code/</font><font color="#AD7FA8">awesomeapp</font>
|
||||
|
||||
╭─ <font color="#8AE234"><b>Python module file</b></font> ─╮
|
||||
│ │
|
||||
│ 🐍 main.py │
|
||||
│ │
|
||||
╰──────────────────────╯
|
||||
|
||||
<font color="#3465A4">INFO </font> Importing module <font color="#4E9A06">main</font>
|
||||
<font color="#3465A4">INFO </font> Found importable FastAPI app
|
||||
|
||||
╭─ <font color="#8AE234"><b>Importable FastAPI app</b></font> ─╮
|
||||
│ │
|
||||
│ <span style="background-color:#272822"><font color="#FF4689">from</font></span><span style="background-color:#272822"><font color="#F8F8F2"> main </font></span><span style="background-color:#272822"><font color="#FF4689">import</font></span><span style="background-color:#272822"><font color="#F8F8F2"> app</font></span><span style="background-color:#272822"> </span> │
|
||||
│ │
|
||||
╰──────────────────────────╯
|
||||
|
||||
<font color="#3465A4">INFO </font> Using import string <font color="#8AE234"><b>main:app</b></font>
|
||||
|
||||
<font color="#4E9A06">╭─────────── FastAPI CLI - Production mode ───────────╮</font>
|
||||
<font color="#4E9A06">│ │</font>
|
||||
<font color="#4E9A06">│ Serving at: http://0.0.0.0:8000 │</font>
|
||||
<font color="#4E9A06">│ │</font>
|
||||
<font color="#4E9A06">│ API docs: http://0.0.0.0:8000/docs │</font>
|
||||
<font color="#4E9A06">│ │</font>
|
||||
<font color="#4E9A06">│ Running in production mode, for development use: │</font>
|
||||
<font color="#4E9A06">│ │</font>
|
||||
<font color="#4E9A06">│ </font><font color="#8AE234"><b>fastapi dev</b></font><font color="#4E9A06"> │</font>
|
||||
<font color="#4E9A06">│ │</font>
|
||||
<font color="#4E9A06">╰─────────────────────────────────────────────────────╯</font>
|
||||
|
||||
<font color="#4E9A06">INFO</font>: Started server process [<font color="#06989A">2306215</font>]
|
||||
<font color="#4E9A06">INFO</font>: Waiting for application startup.
|
||||
<font color="#4E9A06">INFO</font>: Application startup complete.
|
||||
<font color="#4E9A06">INFO</font>: Uvicorn running on <b>http://0.0.0.0:8000</b> (Press CTRL+C to quit)
|
||||
```
|
||||
|
||||
</div>
|
||||
|
||||
That would work for most of the cases. 😎
|
||||
|
||||
You could use that command for example to start your **FastAPI** app in a container, in a server, etc.
|
||||
|
||||
## ASGI Servers
|
||||
|
||||
Let's go a little deeper into the details.
|
||||
|
||||
FastAPI uses a standard for building Python web frameworks and servers called <abbr title="Asynchronous Server Gateway Interface">ASGI</abbr>. FastAPI is an ASGI web framework.
|
||||
|
||||
The main thing you need to run a **FastAPI** application (or any other ASGI application) in a remote server machine is an ASGI server program like **Uvicorn**, this is the one that comes by default in the `fastapi` command.
|
||||
|
||||
There are several alternatives, including:
|
||||
|
||||
* <a href="https://www.uvicorn.org/" class="external-link" target="_blank">Uvicorn</a>: a high performance ASGI server.
|
||||
* <a href="https://pgjones.gitlab.io/hypercorn/" class="external-link" target="_blank">Hypercorn</a>: an ASGI server compatible with HTTP/2 and Trio among other features.
|
||||
* <a href="https://hypercorn.readthedocs.io/" class="external-link" target="_blank">Hypercorn</a>: an ASGI server compatible with HTTP/2 and Trio among other features.
|
||||
* <a href="https://github.com/django/daphne" class="external-link" target="_blank">Daphne</a>: the ASGI server built for Django Channels.
|
||||
|
||||
## Server Machine and Server Program
|
||||
@@ -20,7 +80,9 @@ When referring to the remote machine, it's common to call it **server**, but als
|
||||
|
||||
## Install the Server Program
|
||||
|
||||
You can install an ASGI compatible server with:
|
||||
When you install FastAPI, it comes with a production server, Uvicorn, and you can start it with the `fastapi run` command.
|
||||
|
||||
But you can also install an ASGI server manually:
|
||||
|
||||
=== "Uvicorn"
|
||||
|
||||
@@ -41,9 +103,11 @@ You can install an ASGI compatible server with:
|
||||
|
||||
That including `uvloop`, the high-performance drop-in replacement for `asyncio`, that provides the big concurrency performance boost.
|
||||
|
||||
When you install FastAPI with something like `pip install fastapi` you already get `uvicorn[standard]` as well.
|
||||
|
||||
=== "Hypercorn"
|
||||
|
||||
* <a href="https://gitlab.com/pgjones/hypercorn" class="external-link" target="_blank">Hypercorn</a>, an ASGI server also compatible with HTTP/2.
|
||||
* <a href="https://github.com/pgjones/hypercorn" class="external-link" target="_blank">Hypercorn</a>, an ASGI server also compatible with HTTP/2.
|
||||
|
||||
<div class="termy">
|
||||
|
||||
@@ -59,7 +123,7 @@ You can install an ASGI compatible server with:
|
||||
|
||||
## Run the Server Program
|
||||
|
||||
You can then run your application the same way you have done in the tutorials, but without the `--reload` option, e.g.:
|
||||
If you installed an ASGI server manually, you would normally need to pass an import string in a special format for it to import your FastAPI application:
|
||||
|
||||
=== "Uvicorn"
|
||||
|
||||
@@ -85,8 +149,20 @@ You can then run your application the same way you have done in the tutorials, b
|
||||
|
||||
</div>
|
||||
|
||||
!!! note
|
||||
The command `uvicorn main:app` refers to:
|
||||
|
||||
* `main`: the file `main.py` (the Python "module").
|
||||
* `app`: the object created inside of `main.py` with the line `app = FastAPI()`.
|
||||
|
||||
It is equivalent to:
|
||||
|
||||
```Python
|
||||
from main import app
|
||||
```
|
||||
|
||||
!!! warning
|
||||
Remember to remove the `--reload` option if you were using it.
|
||||
Uvicorn and others support a `--reload` option that is useful during development.
|
||||
|
||||
The `--reload` option consumes much more resources, is more unstable, etc.
|
||||
|
||||
|
||||
80
docs/en/docs/fastapi-cli.md
Normal file
@@ -0,0 +1,80 @@
|
||||
# FastAPI CLI
|
||||
|
||||
**FastAPI CLI** is a command line program that you can use to serve your FastAPI app, manage your FastAPI project, and more.
|
||||
|
||||
When you install FastAPI (e.g. with `pip install fastapi`), it includes a package called `fastapi-cli`, this package provides the `fastapi` command in the terminal.
|
||||
|
||||
To run your FastAPI app for development, you can use the `fastapi dev` command:
|
||||
|
||||
<div class="termy">
|
||||
|
||||
```console
|
||||
$ <font color="#4E9A06">fastapi</font> dev <u style="text-decoration-style:single">main.py</u>
|
||||
<font color="#3465A4">INFO </font> Using path <font color="#3465A4">main.py</font>
|
||||
<font color="#3465A4">INFO </font> Resolved absolute path <font color="#75507B">/home/user/code/awesomeapp/</font><font color="#AD7FA8">main.py</font>
|
||||
<font color="#3465A4">INFO </font> Searching for package file structure from directories with <font color="#3465A4">__init__.py</font> files
|
||||
<font color="#3465A4">INFO </font> Importing from <font color="#75507B">/home/user/code/</font><font color="#AD7FA8">awesomeapp</font>
|
||||
|
||||
╭─ <font color="#8AE234"><b>Python module file</b></font> ─╮
|
||||
│ │
|
||||
│ 🐍 main.py │
|
||||
│ │
|
||||
╰──────────────────────╯
|
||||
|
||||
<font color="#3465A4">INFO </font> Importing module <font color="#4E9A06">main</font>
|
||||
<font color="#3465A4">INFO </font> Found importable FastAPI app
|
||||
|
||||
╭─ <font color="#8AE234"><b>Importable FastAPI app</b></font> ─╮
|
||||
│ │
|
||||
│ <span style="background-color:#272822"><font color="#FF4689">from</font></span><span style="background-color:#272822"><font color="#F8F8F2"> main </font></span><span style="background-color:#272822"><font color="#FF4689">import</font></span><span style="background-color:#272822"><font color="#F8F8F2"> app</font></span><span style="background-color:#272822"> </span> │
|
||||
│ │
|
||||
╰──────────────────────────╯
|
||||
|
||||
<font color="#3465A4">INFO </font> Using import string <font color="#8AE234"><b>main:app</b></font>
|
||||
|
||||
<span style="background-color:#C4A000"><font color="#2E3436">╭────────── FastAPI CLI - Development mode ───────────╮</font></span>
|
||||
<span style="background-color:#C4A000"><font color="#2E3436">│ │</font></span>
|
||||
<span style="background-color:#C4A000"><font color="#2E3436">│ Serving at: http://127.0.0.1:8000 │</font></span>
|
||||
<span style="background-color:#C4A000"><font color="#2E3436">│ │</font></span>
|
||||
<span style="background-color:#C4A000"><font color="#2E3436">│ API docs: http://127.0.0.1:8000/docs │</font></span>
|
||||
<span style="background-color:#C4A000"><font color="#2E3436">│ │</font></span>
|
||||
<span style="background-color:#C4A000"><font color="#2E3436">│ Running in development mode, for production use: │</font></span>
|
||||
<span style="background-color:#C4A000"><font color="#2E3436">│ │</font></span>
|
||||
<span style="background-color:#C4A000"><font color="#2E3436">│ </font></span><span style="background-color:#C4A000"><font color="#555753"><b>fastapi run</b></font></span><span style="background-color:#C4A000"><font color="#2E3436"> │</font></span>
|
||||
<span style="background-color:#C4A000"><font color="#2E3436">│ │</font></span>
|
||||
<span style="background-color:#C4A000"><font color="#2E3436">╰─────────────────────────────────────────────────────╯</font></span>
|
||||
|
||||
<font color="#4E9A06">INFO</font>: Will watch for changes in these directories: ['/home/user/code/awesomeapp']
|
||||
<font color="#4E9A06">INFO</font>: Uvicorn running on <b>http://127.0.0.1:8000</b> (Press CTRL+C to quit)
|
||||
<font color="#4E9A06">INFO</font>: Started reloader process [<font color="#34E2E2"><b>2265862</b></font>] using <font color="#34E2E2"><b>WatchFiles</b></font>
|
||||
<font color="#4E9A06">INFO</font>: Started server process [<font color="#06989A">2265873</font>]
|
||||
<font color="#4E9A06">INFO</font>: Waiting for application startup.
|
||||
<font color="#4E9A06">INFO</font>: Application startup complete.
|
||||
```
|
||||
|
||||
</div>
|
||||
|
||||
The command line program called `fastapi` is **FastAPI CLI**.
|
||||
|
||||
FastAPI CLI takes the path to your Python program (e.g. `main.py`) and automatically detects the `FastAPI` instance (commonly named `app`), determines the correct import process, and then serves it.
|
||||
|
||||
For production you would use `fastapi run` instead. 🚀
|
||||
|
||||
Internally, **FastAPI CLI** uses <a href="https://www.uvicorn.org" class="external-link" target="_blank">Uvicorn</a>, a high-performance, production-ready, ASGI server. 😎
|
||||
|
||||
## `fastapi dev`
|
||||
|
||||
Running `fastapi dev` initiates development mode.
|
||||
|
||||
By default, **auto-reload** is enabled, automatically reloading the server when you make changes to your code. This is resource-intensive and could be less stable than when it's disabled. You should only use it for development. It also listens on the IP address `127.0.0.1`, which is the IP for your machine to communicate with itself alone (`localhost`).
|
||||
|
||||
## `fastapi run`
|
||||
|
||||
Executing `fastapi run` starts FastAPI in production mode by default.
|
||||
|
||||
By default, **auto-reload** is disabled. It also listens on the IP address `0.0.0.0`, which means all the available IP addresses, this way it will be publicly accessible to anyone that can communicate with the machine. This is how you would normally run it in production, for example, in a container.
|
||||
|
||||
In most cases you would (and should) have a "termination proxy" handling HTTPS for you on top, this will depend on how you deploy your application, your provider might do this for you, or you might need to set it up yourself.
|
||||
|
||||
!!! tip
|
||||
You can learn more about it in the [deployment documentation](deployment/index.md){.internal-link target=_blank}.
|
||||
@@ -30,7 +30,7 @@ Interactive API documentation and exploration web user interfaces. As the framew
|
||||
|
||||
### Just Modern Python
|
||||
|
||||
It's all based on standard **Python 3.6 type** declarations (thanks to Pydantic). No new syntax to learn. Just standard modern Python.
|
||||
It's all based on standard **Python type** declarations (thanks to Pydantic). No new syntax to learn. Just standard modern Python.
|
||||
|
||||
If you need a 2 minute refresher of how to use Python types (even if you don't use FastAPI), check the short tutorial: [Python Types](python-types.md){.internal-link target=_blank}.
|
||||
|
||||
@@ -77,7 +77,7 @@ my_second_user: User = User(**second_user_data)
|
||||
|
||||
All the framework was designed to be easy and intuitive to use, all the decisions were tested on multiple editors even before starting development, to ensure the best development experience.
|
||||
|
||||
In the last Python developer survey it was clear <a href="https://www.jetbrains.com/research/python-developers-survey-2017/#tools-and-features" class="external-link" target="_blank">that the most used feature is "autocompletion"</a>.
|
||||
In the Python developer surveys, it's clear <a href="https://www.jetbrains.com/research/python-developers-survey-2017/#tools-and-features" class="external-link" target="_blank">that one of the most used features is "autocompletion"</a>.
|
||||
|
||||
The whole **FastAPI** framework is based to satisfy that. Autocompletion works everywhere.
|
||||
|
||||
|
||||
@@ -26,7 +26,7 @@ To disable them, set their URLs to `None` when creating your `FastAPI` app:
|
||||
|
||||
Now you can create the *path operations* for the custom docs.
|
||||
|
||||
You can re-use FastAPI's internal functions to create the HTML pages for the docs, and pass them the needed arguments:
|
||||
You can reuse FastAPI's internal functions to create the HTML pages for the docs, and pass them the needed arguments:
|
||||
|
||||
* `openapi_url`: the URL where the HTML page for the docs can get the OpenAPI schema for your API. You can use here the attribute `app.openapi_url`.
|
||||
* `title`: the title of your API.
|
||||
@@ -96,8 +96,8 @@ You can probably right-click each link and select an option similar to `Save lin
|
||||
|
||||
**Swagger UI** uses the files:
|
||||
|
||||
* <a href="https://cdn.jsdelivr.net/npm/swagger-ui-dist@5.9.0/swagger-ui-bundle.js" class="external-link" target="_blank">`swagger-ui-bundle.js`</a>
|
||||
* <a href="https://cdn.jsdelivr.net/npm/swagger-ui-dist@5.9.0/swagger-ui.css" class="external-link" target="_blank">`swagger-ui.css`</a>
|
||||
* <a href="https://cdn.jsdelivr.net/npm/swagger-ui-dist@5/swagger-ui-bundle.js" class="external-link" target="_blank">`swagger-ui-bundle.js`</a>
|
||||
* <a href="https://cdn.jsdelivr.net/npm/swagger-ui-dist@5/swagger-ui.css" class="external-link" target="_blank">`swagger-ui.css`</a>
|
||||
|
||||
And **ReDoc** uses the file:
|
||||
|
||||
@@ -163,7 +163,7 @@ To disable them, set their URLs to `None` when creating your `FastAPI` app:
|
||||
|
||||
And the same way as with a custom CDN, now you can create the *path operations* for the custom docs.
|
||||
|
||||
Again, you can re-use FastAPI's internal functions to create the HTML pages for the docs, and pass them the needed arguments:
|
||||
Again, you can reuse FastAPI's internal functions to create the HTML pages for the docs, and pass them the needed arguments:
|
||||
|
||||
* `openapi_url`: the URL where the HTML page for the docs can get the OpenAPI schema for your API. You can use here the attribute `app.openapi_url`.
|
||||
* `title`: the title of your API.
|
||||
|
||||
@@ -18,7 +18,7 @@ Here are some of the **GraphQL** libraries that have **ASGI** support. You could
|
||||
* <a href="https://strawberry.rocks/" class="external-link" target="_blank">Strawberry</a> 🍓
|
||||
* With <a href="https://strawberry.rocks/docs/integrations/fastapi" class="external-link" target="_blank">docs for FastAPI</a>
|
||||
* <a href="https://ariadnegraphql.org/" class="external-link" target="_blank">Ariadne</a>
|
||||
* With <a href="https://ariadnegraphql.org/docs/starlette-integration" class="external-link" target="_blank">docs for Starlette</a> (that also apply to FastAPI)
|
||||
* With <a href="https://ariadnegraphql.org/docs/fastapi-integration" class="external-link" target="_blank">docs for FastAPI</a>
|
||||
* <a href="https://tartiflette.io/" class="external-link" target="_blank">Tartiflette</a>
|
||||
* With <a href="https://tartiflette.github.io/tartiflette-asgi/" class="external-link" target="_blank">Tartiflette ASGI</a> to provide ASGI integration
|
||||
* <a href="https://graphene-python.org/" class="external-link" target="_blank">Graphene</a>
|
||||
|
||||
@@ -108,7 +108,7 @@ Now create a function that will:
|
||||
* Get the document with that ID.
|
||||
* Put the contents of the document in a `UserInDB` model.
|
||||
|
||||
By creating a function that is only dedicated to getting your user from a `username` (or any other parameter) independent of your *path operation function*, you can more easily re-use it in multiple parts and also add <abbr title="Automated test, written in code, that checks if another piece of code is working correctly.">unit tests</abbr> for it:
|
||||
By creating a function that is only dedicated to getting your user from a `username` (or any other parameter) independent of your *path operation function*, you can more easily reuse it in multiple parts and also add <abbr title="Automated test, written in code, that checks if another piece of code is working correctly.">unit tests</abbr> for it:
|
||||
|
||||
```Python hl_lines="36-42"
|
||||
{!../../../docs_src/nosql_databases/tutorial001.py!}
|
||||
|
||||
BIN
docs/en/docs/img/sponsors/fine-banner.png
Normal file
|
After Width: | Height: | Size: 11 KiB |
BIN
docs/en/docs/img/sponsors/fine.png
Normal file
|
After Width: | Height: | Size: 21 KiB |
BIN
docs/en/docs/img/sponsors/kong-banner.png
Normal file
|
After Width: | Height: | Size: 21 KiB |
BIN
docs/en/docs/img/sponsors/kong.png
Normal file
|
After Width: | Height: | Size: 30 KiB |
BIN
docs/en/docs/img/sponsors/stainless.png
Normal file
|
After Width: | Height: | Size: 29 KiB |
BIN
docs/en/docs/img/sponsors/zuplo-banner.png
Normal file
|
After Width: | Height: | Size: 1.7 KiB |
BIN
docs/en/docs/img/sponsors/zuplo.png
Normal file
|
After Width: | Height: | Size: 18 KiB |
@@ -141,18 +141,6 @@ $ pip install fastapi
|
||||
|
||||
</div>
|
||||
|
||||
You will also need an ASGI server, for production such as <a href="https://www.uvicorn.org" class="external-link" target="_blank">Uvicorn</a> or <a href="https://github.com/pgjones/hypercorn" class="external-link" target="_blank">Hypercorn</a>.
|
||||
|
||||
<div class="termy">
|
||||
|
||||
```console
|
||||
$ pip install "uvicorn[standard]"
|
||||
|
||||
---> 100%
|
||||
```
|
||||
|
||||
</div>
|
||||
|
||||
## Example
|
||||
|
||||
### Create it
|
||||
@@ -213,11 +201,24 @@ Run the server with:
|
||||
<div class="termy">
|
||||
|
||||
```console
|
||||
$ uvicorn main:app --reload
|
||||
$ fastapi dev main.py
|
||||
|
||||
╭────────── FastAPI CLI - Development mode ───────────╮
|
||||
│ │
|
||||
│ Serving at: http://127.0.0.1:8000 │
|
||||
│ │
|
||||
│ API docs: http://127.0.0.1:8000/docs │
|
||||
│ │
|
||||
│ Running in development mode, for production use: │
|
||||
│ │
|
||||
│ fastapi run │
|
||||
│ │
|
||||
╰─────────────────────────────────────────────────────╯
|
||||
|
||||
INFO: Will watch for changes in these directories: ['/home/user/code/awesomeapp']
|
||||
INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit)
|
||||
INFO: Started reloader process [28720]
|
||||
INFO: Started server process [28722]
|
||||
INFO: Started reloader process [2248755] using WatchFiles
|
||||
INFO: Started server process [2248757]
|
||||
INFO: Waiting for application startup.
|
||||
INFO: Application startup complete.
|
||||
```
|
||||
@@ -225,13 +226,13 @@ INFO: Application startup complete.
|
||||
</div>
|
||||
|
||||
<details markdown="1">
|
||||
<summary>About the command <code>uvicorn main:app --reload</code>...</summary>
|
||||
<summary>About the command <code>fastapi dev main.py</code>...</summary>
|
||||
|
||||
The command `uvicorn main:app` refers to:
|
||||
The command `fastapi dev` reads your `main.py` file, detects the **FastAPI** app in it, and starts a server using <a href="https://www.uvicorn.org" class="external-link" target="_blank">Uvicorn</a>.
|
||||
|
||||
* `main`: the file `main.py` (the Python "module").
|
||||
* `app`: the object created inside of `main.py` with the line `app = FastAPI()`.
|
||||
* `--reload`: make the server restart after code changes. Only do this for development.
|
||||
By default, `fastapi dev` will start with auto-reload enabled for local development.
|
||||
|
||||
You can read more about it in the <a href="https://fastapi.tiangolo.com/fastapi-cli/" target="_blank">FastAPI CLI docs</a>.
|
||||
|
||||
</details>
|
||||
|
||||
@@ -304,7 +305,7 @@ def update_item(item_id: int, item: Item):
|
||||
return {"item_name": item.name, "item_id": item_id}
|
||||
```
|
||||
|
||||
The server should reload automatically (because you added `--reload` to the `uvicorn` command above).
|
||||
The `fastapi dev` server should reload automatically.
|
||||
|
||||
### Interactive API docs upgrade
|
||||
|
||||
@@ -448,7 +449,7 @@ Independent TechEmpower benchmarks show **FastAPI** applications running under U
|
||||
|
||||
To understand more about it, see the section <a href="https://fastapi.tiangolo.com/benchmarks/" class="internal-link" target="_blank">Benchmarks</a>.
|
||||
|
||||
## Optional Dependencies
|
||||
## Dependencies
|
||||
|
||||
Used by Pydantic:
|
||||
|
||||
@@ -461,16 +462,36 @@ Used by Starlette:
|
||||
* <a href="https://www.python-httpx.org" target="_blank"><code>httpx</code></a> - Required if you want to use the `TestClient`.
|
||||
* <a href="https://jinja.palletsprojects.com" target="_blank"><code>jinja2</code></a> - Required if you want to use the default template configuration.
|
||||
* <a href="https://github.com/Kludex/python-multipart" target="_blank"><code>python-multipart</code></a> - Required if you want to support form <abbr title="converting the string that comes from an HTTP request into Python data">"parsing"</abbr>, with `request.form()`.
|
||||
* <a href="https://pythonhosted.org/itsdangerous/" target="_blank"><code>itsdangerous</code></a> - Required for `SessionMiddleware` support.
|
||||
* <a href="https://pyyaml.org/wiki/PyYAMLDocumentation" target="_blank"><code>pyyaml</code></a> - Required for Starlette's `SchemaGenerator` support (you probably don't need it with FastAPI).
|
||||
|
||||
Used by FastAPI / Starlette:
|
||||
|
||||
* <a href="https://www.uvicorn.org" target="_blank"><code>uvicorn</code></a> - for the server that loads and serves your application.
|
||||
* `fastapi-cli` - to provide the `fastapi` command.
|
||||
|
||||
When you install `fastapi` it comes these standard dependencies.
|
||||
|
||||
Additional optional dependencies:
|
||||
|
||||
* <a href="https://github.com/ijl/orjson" target="_blank"><code>orjson</code></a> - Required if you want to use `ORJSONResponse`.
|
||||
* <a href="https://github.com/esnme/ultrajson" target="_blank"><code>ujson</code></a> - Required if you want to use `UJSONResponse`.
|
||||
|
||||
You can install all of these with `pip install "fastapi[all]"`.
|
||||
## `fastapi-slim`
|
||||
|
||||
If you don't want the extra standard optional dependencies, install `fastapi-slim` instead.
|
||||
|
||||
When you install with:
|
||||
|
||||
```bash
|
||||
pip install fastapi
|
||||
```
|
||||
|
||||
...it includes the same code and dependencies as:
|
||||
|
||||
```bash
|
||||
pip install "fastapi-slim[standard]"
|
||||
```
|
||||
|
||||
The standard extra dependencies are the ones mentioned above.
|
||||
|
||||
## License
|
||||
|
||||
|
||||
@@ -476,7 +476,7 @@ You will see a lot more of all this in practice in the [Tutorial - User Guide](t
|
||||
|
||||
## Type Hints with Metadata Annotations
|
||||
|
||||
Python also has a feature that allows putting **additional metadata** in these type hints using `Annotated`.
|
||||
Python also has a feature that allows putting **additional <abbr title="Data about the data, in this case, information about the type, e.g. a description.">metadata</abbr>** in these type hints using `Annotated`.
|
||||
|
||||
=== "Python 3.9+"
|
||||
|
||||
|
||||
@@ -5,10 +5,143 @@ hide:
|
||||
|
||||
# Release Notes
|
||||
|
||||
## 0.110.3
|
||||
|
||||
## Latest Changes
|
||||
|
||||
## 0.111.1
|
||||
|
||||
### Upgrades
|
||||
|
||||
* ➖ Remove `orjson` and `ujson` from default dependencies. PR [#11842](https://github.com/tiangolo/fastapi/pull/11842) by [@tiangolo](https://github.com/tiangolo).
|
||||
* These dependencies are still installed when you install with `pip install "fastapi[all]"`. But they not included in `pip install fastapi`.
|
||||
* 📝 Restored Swagger-UI links to use the latest version possible. PR [#11459](https://github.com/tiangolo/fastapi/pull/11459) by [@UltimateLobster](https://github.com/UltimateLobster).
|
||||
|
||||
### Docs
|
||||
|
||||
* ✏️ Rewording in `docs/en/docs/fastapi-cli.md`. PR [#11716](https://github.com/tiangolo/fastapi/pull/11716) by [@alejsdev](https://github.com/alejsdev).
|
||||
* 📝 Update Hypercorn links in all the docs. PR [#11744](https://github.com/tiangolo/fastapi/pull/11744) by [@kittydoor](https://github.com/kittydoor).
|
||||
* 📝 Update docs with Ariadne reference from Starlette to FastAPI. PR [#11797](https://github.com/tiangolo/fastapi/pull/11797) by [@DamianCzajkowski](https://github.com/DamianCzajkowski).
|
||||
* 📝 Update fastapi instrumentation external link. PR [#11317](https://github.com/tiangolo/fastapi/pull/11317) by [@softwarebloat](https://github.com/softwarebloat).
|
||||
* ✏️ Fix links to alembic example repo in docs. PR [#11628](https://github.com/tiangolo/fastapi/pull/11628) by [@augiwan](https://github.com/augiwan).
|
||||
* ✏️ Update `docs/en/docs/fastapi-cli.md`. PR [#11715](https://github.com/tiangolo/fastapi/pull/11715) by [@alejsdev](https://github.com/alejsdev).
|
||||
* 📝 Update External Links . PR [#11500](https://github.com/tiangolo/fastapi/pull/11500) by [@devon2018](https://github.com/devon2018).
|
||||
* 📝 Add External Link: Tutorial de FastAPI, ¿el mejor framework de Python?. PR [#11618](https://github.com/tiangolo/fastapi/pull/11618) by [@EduardoZepeda](https://github.com/EduardoZepeda).
|
||||
* 📝 Fix typo in `docs/en/docs/tutorial/body-multiple-params.md`. PR [#11698](https://github.com/tiangolo/fastapi/pull/11698) by [@mwb-u](https://github.com/mwb-u).
|
||||
* 📝 Add External Link: Deploy a Serverless FastAPI App with Neon Postgres and AWS App Runner at any scale. PR [#11633](https://github.com/tiangolo/fastapi/pull/11633) by [@ananis25](https://github.com/ananis25).
|
||||
* 📝 Update `security/first-steps.md`. PR [#11674](https://github.com/tiangolo/fastapi/pull/11674) by [@alejsdev](https://github.com/alejsdev).
|
||||
* 📝 Update `security/first-steps.md`. PR [#11673](https://github.com/tiangolo/fastapi/pull/11673) by [@alejsdev](https://github.com/alejsdev).
|
||||
* 📝 Update note in `path-params-numeric-validations.md`. PR [#11672](https://github.com/tiangolo/fastapi/pull/11672) by [@alejsdev](https://github.com/alejsdev).
|
||||
* 📝 Tweak intro docs about `Annotated` and `Query()` params. PR [#11664](https://github.com/tiangolo/fastapi/pull/11664) by [@tiangolo](https://github.com/tiangolo).
|
||||
* 📝 Update JWT auth documentation to use PyJWT instead of pyhon-jose. PR [#11589](https://github.com/tiangolo/fastapi/pull/11589) by [@estebanx64](https://github.com/estebanx64).
|
||||
* 📝 Update docs. PR [#11603](https://github.com/tiangolo/fastapi/pull/11603) by [@alejsdev](https://github.com/alejsdev).
|
||||
* ✏️ Fix typo: convert every 're-use' to 'reuse'.. PR [#11598](https://github.com/tiangolo/fastapi/pull/11598) by [@hasansezertasan](https://github.com/hasansezertasan).
|
||||
* ✏️ Fix typo in `fastapi/applications.py`. PR [#11593](https://github.com/tiangolo/fastapi/pull/11593) by [@petarmaric](https://github.com/petarmaric).
|
||||
* ✏️ Fix link in `fastapi-cli.md`. PR [#11524](https://github.com/tiangolo/fastapi/pull/11524) by [@svlandeg](https://github.com/svlandeg).
|
||||
|
||||
### Translations
|
||||
|
||||
* 🌐 Add Spanish translation for `docs/es/docs/how-to/graphql.md`. PR [#11697](https://github.com/tiangolo/fastapi/pull/11697) by [@camigomezdev](https://github.com/camigomezdev).
|
||||
* 🌐 Add Portuguese translation for `docs/pt/docs/reference/index.md`. PR [#11840](https://github.com/tiangolo/fastapi/pull/11840) by [@lucasbalieiro](https://github.com/lucasbalieiro).
|
||||
* 🌐 Fix link in German translation. PR [#11836](https://github.com/tiangolo/fastapi/pull/11836) by [@anitahammer](https://github.com/anitahammer).
|
||||
* 🌐 Add Portuguese translation for `docs/pt/docs/tutorial/dependencies/sub-dependencies.md`. PR [#11792](https://github.com/tiangolo/fastapi/pull/11792) by [@Joao-Pedro-P-Holanda](https://github.com/Joao-Pedro-P-Holanda).
|
||||
* 🌐 Add Turkish translation for `docs/tr/docs/tutorial/request-forms.md`. PR [#11553](https://github.com/tiangolo/fastapi/pull/11553) by [@hasansezertasan](https://github.com/hasansezertasan).
|
||||
* 🌐 Add Portuguese translation for `docs/pt/docs/reference/exceptions.md`. PR [#11834](https://github.com/tiangolo/fastapi/pull/11834) by [@lucasbalieiro](https://github.com/lucasbalieiro).
|
||||
* 🌐 Add Portuguese translation for `docs/pt/docs/tutorial/dependencies/global-dependencies.md`. PR [#11826](https://github.com/tiangolo/fastapi/pull/11826) by [@Joao-Pedro-P-Holanda](https://github.com/Joao-Pedro-P-Holanda).
|
||||
* 🌐 Add Portuguese translation for `docs/pt/docs/how-to/general.md`. PR [#11825](https://github.com/tiangolo/fastapi/pull/11825) by [@lucasbalieiro](https://github.com/lucasbalieiro).
|
||||
* 🌐 Add Portuguese translation for `docs/pt/docs/advanced/async-tests.md`. PR [#11808](https://github.com/tiangolo/fastapi/pull/11808) by [@ceb10n](https://github.com/ceb10n).
|
||||
* 🌐 Add Ukrainian translation for `docs/uk/docs/tutorial/first-steps.md`. PR [#11809](https://github.com/tiangolo/fastapi/pull/11809) by [@vkhoroshchak](https://github.com/vkhoroshchak).
|
||||
* 🌐 Add Portuguese translation for `docs/pt/docs/tutorial/dependencies/dependencies-in-path-operation-operators.md`. PR [#11804](https://github.com/tiangolo/fastapi/pull/11804) by [@Joao-Pedro-P-Holanda](https://github.com/Joao-Pedro-P-Holanda).
|
||||
* 🌐 Add Chinese translation for `docs/zh/docs/fastapi-cli.md`. PR [#11786](https://github.com/tiangolo/fastapi/pull/11786) by [@logan2d5](https://github.com/logan2d5).
|
||||
* 🌐 Add Portuguese translation for `docs/pt/docs/advanced/openapi-webhooks.md`. PR [#11791](https://github.com/tiangolo/fastapi/pull/11791) by [@ceb10n](https://github.com/ceb10n).
|
||||
* 🌐 Update Chinese translation for `docs/tutorial/security/oauth2-jwt.md`. PR [#11781](https://github.com/tiangolo/fastapi/pull/11781) by [@logan2d5](https://github.com/logan2d5).
|
||||
* 📝 Fix image missing in French translation for `docs/fr/docs/async.md` . PR [#11787](https://github.com/tiangolo/fastapi/pull/11787) by [@pe-brian](https://github.com/pe-brian).
|
||||
* 🌐 Add Portuguese translation for `docs/pt/docs/advanced/advanced-dependencies.md`. PR [#11775](https://github.com/tiangolo/fastapi/pull/11775) by [@ceb10n](https://github.com/ceb10n).
|
||||
* 🌐 Add Portuguese translation for `docs/pt/docs/tutorial/dependencies/classes-as-dependencies.md`. PR [#11768](https://github.com/tiangolo/fastapi/pull/11768) by [@Joao-Pedro-P-Holanda](https://github.com/Joao-Pedro-P-Holanda).
|
||||
* 🌐 Add Portuguese translation for `docs/pt/docs/advanced/additional-status-codes.md`. PR [#11753](https://github.com/tiangolo/fastapi/pull/11753) by [@ceb10n](https://github.com/ceb10n).
|
||||
* 🌐 Add Portuguese translation for `docs/pt/docs/tutorial/dependencies/index.md`. PR [#11757](https://github.com/tiangolo/fastapi/pull/11757) by [@Joao-Pedro-P-Holanda](https://github.com/Joao-Pedro-P-Holanda).
|
||||
* 🌐 Add Portuguese translation for `docs/pt/docs/advanced/settings.md`. PR [#11739](https://github.com/tiangolo/fastapi/pull/11739) by [@Joao-Pedro-P-Holanda](https://github.com/Joao-Pedro-P-Holanda).
|
||||
* 🌐 Add French translation for `docs/fr/docs/learn/index.md`. PR [#11712](https://github.com/tiangolo/fastapi/pull/11712) by [@benjaminvandammeholberton](https://github.com/benjaminvandammeholberton).
|
||||
* 🌐 Add Portuguese translation for `docs/pt/docs/how-to/index.md`. PR [#11731](https://github.com/tiangolo/fastapi/pull/11731) by [@vhsenna](https://github.com/vhsenna).
|
||||
* 🌐 Add Portuguese translation for `docs/pt/docs/advanced/additional-responses.md`. PR [#11736](https://github.com/tiangolo/fastapi/pull/11736) by [@ceb10n](https://github.com/ceb10n).
|
||||
* 🌐 Add Portuguese translation for `docs/pt/docs/advanced/benchmarks.md`. PR [#11713](https://github.com/tiangolo/fastapi/pull/11713) by [@ceb10n](https://github.com/ceb10n).
|
||||
* 🌐 Fix Korean translation for `docs/ko/docs/tutorial/response-status-code.md`. PR [#11718](https://github.com/tiangolo/fastapi/pull/11718) by [@nayeonkinn](https://github.com/nayeonkinn).
|
||||
* 🌐 Add Korean translation for `docs/ko/docs/tutorial/extra-data-types.md`. PR [#11711](https://github.com/tiangolo/fastapi/pull/11711) by [@nayeonkinn](https://github.com/nayeonkinn).
|
||||
* 🌐 Fix Korean translation for `docs/ko/docs/tutorial/body-nested-models.md`. PR [#11710](https://github.com/tiangolo/fastapi/pull/11710) by [@nayeonkinn](https://github.com/nayeonkinn).
|
||||
* 🌐 Add Portuguese translation for `docs/pt/docs/advanced/fastapi-cli.md`. PR [#11641](https://github.com/tiangolo/fastapi/pull/11641) by [@ayr-ton](https://github.com/ayr-ton).
|
||||
* 🌐 Add Traditional Chinese translation for `docs/zh-hant/docs/fastapi-people.md`. PR [#11639](https://github.com/tiangolo/fastapi/pull/11639) by [@hsuanchi](https://github.com/hsuanchi).
|
||||
* 🌐 Add Turkish translation for `docs/tr/docs/advanced/index.md`. PR [#11606](https://github.com/tiangolo/fastapi/pull/11606) by [@hasansezertasan](https://github.com/hasansezertasan).
|
||||
* 🌐 Add Turkish translation for `docs/tr/docs/deployment/cloud.md`. PR [#11610](https://github.com/tiangolo/fastapi/pull/11610) by [@hasansezertasan](https://github.com/hasansezertasan).
|
||||
* 🌐 Add Turkish translation for `docs/tr/docs/advanced/security/index.md`. PR [#11609](https://github.com/tiangolo/fastapi/pull/11609) by [@hasansezertasan](https://github.com/hasansezertasan).
|
||||
* 🌐 Add Turkish translation for `docs/tr/docs/advanced/testing-websockets.md`. PR [#11608](https://github.com/tiangolo/fastapi/pull/11608) by [@hasansezertasan](https://github.com/hasansezertasan).
|
||||
* 🌐 Add Turkish translation for `docs/tr/docs/how-to/general.md`. PR [#11607](https://github.com/tiangolo/fastapi/pull/11607) by [@hasansezertasan](https://github.com/hasansezertasan).
|
||||
* 🌐 Update Chinese translation for `docs/zh/docs/advanced/templates.md`. PR [#11620](https://github.com/tiangolo/fastapi/pull/11620) by [@chaoless](https://github.com/chaoless).
|
||||
* 🌐 Add Turkish translation for `docs/tr/docs/deployment/index.md`. PR [#11605](https://github.com/tiangolo/fastapi/pull/11605) by [@hasansezertasan](https://github.com/hasansezertasan).
|
||||
* 🌐 Add Turkish translation for `docs/tr/docs/tutorial/static-files.md`. PR [#11599](https://github.com/tiangolo/fastapi/pull/11599) by [@hasansezertasan](https://github.com/hasansezertasan).
|
||||
* 🌐 Polish translation for `docs/pl/docs/fastapi-people.md`. PR [#10196](https://github.com/tiangolo/fastapi/pull/10196) by [@isulim](https://github.com/isulim).
|
||||
* 🌐 Add Turkish translation for `docs/tr/docs/advanced/wsgi.md`. PR [#11575](https://github.com/tiangolo/fastapi/pull/11575) by [@hasansezertasan](https://github.com/hasansezertasan).
|
||||
* 🌐 Add Turkish translation for `docs/tr/docs/tutorial/cookie-params.md`. PR [#11561](https://github.com/tiangolo/fastapi/pull/11561) by [@hasansezertasan](https://github.com/hasansezertasan).
|
||||
* 🌐 Add Russian translation for `docs/ru/docs/about/index.md`. PR [#10961](https://github.com/tiangolo/fastapi/pull/10961) by [@s111d](https://github.com/s111d).
|
||||
* 🌐 Update Chinese translation for `docs/zh/docs/tutorial/sql-databases.md`. PR [#11539](https://github.com/tiangolo/fastapi/pull/11539) by [@chaoless](https://github.com/chaoless).
|
||||
* 🌐 Add Chinese translation for `docs/zh/docs/how-to/configure-swagger-ui.md`. PR [#11501](https://github.com/tiangolo/fastapi/pull/11501) by [@Lucas-lyh](https://github.com/Lucas-lyh).
|
||||
* 🌐 Update Chinese translation for `/docs/advanced/security/http-basic-auth.md`. PR [#11512](https://github.com/tiangolo/fastapi/pull/11512) by [@nick-cjyx9](https://github.com/nick-cjyx9).
|
||||
|
||||
### Internal
|
||||
|
||||
* ♻️ Simplify internal docs script. PR [#11777](https://github.com/tiangolo/fastapi/pull/11777) by [@gitworkflows](https://github.com/gitworkflows).
|
||||
* 🔧 Update sponsors: add Fine. PR [#11784](https://github.com/tiangolo/fastapi/pull/11784) by [@tiangolo](https://github.com/tiangolo).
|
||||
* 🔧 Tweak sponsors: Kong URL. PR [#11765](https://github.com/tiangolo/fastapi/pull/11765) by [@tiangolo](https://github.com/tiangolo).
|
||||
* 🔧 Tweak sponsors: Kong URL. PR [#11764](https://github.com/tiangolo/fastapi/pull/11764) by [@tiangolo](https://github.com/tiangolo).
|
||||
* 🔧 Update sponsors, add Stainless. PR [#11763](https://github.com/tiangolo/fastapi/pull/11763) by [@tiangolo](https://github.com/tiangolo).
|
||||
* 🔧 Update sponsors, add Zuplo. PR [#11729](https://github.com/tiangolo/fastapi/pull/11729) by [@tiangolo](https://github.com/tiangolo).
|
||||
* 🔧 Update Sponsor link: Coherence. PR [#11730](https://github.com/tiangolo/fastapi/pull/11730) by [@tiangolo](https://github.com/tiangolo).
|
||||
* 👥 Update FastAPI People. PR [#11669](https://github.com/tiangolo/fastapi/pull/11669) by [@tiangolo](https://github.com/tiangolo).
|
||||
* 🔧 Add sponsor Kong. PR [#11662](https://github.com/tiangolo/fastapi/pull/11662) by [@tiangolo](https://github.com/tiangolo).
|
||||
* 👷 Update Smokeshow, fix sync download artifact and smokeshow configs. PR [#11563](https://github.com/tiangolo/fastapi/pull/11563) by [@tiangolo](https://github.com/tiangolo).
|
||||
* 👷 Update Smokeshow download artifact GitHub Action. PR [#11562](https://github.com/tiangolo/fastapi/pull/11562) by [@tiangolo](https://github.com/tiangolo).
|
||||
* 👷 Update GitHub actions to download and upload artifacts to v4, for docs and coverage. PR [#11550](https://github.com/tiangolo/fastapi/pull/11550) by [@tamird](https://github.com/tamird).
|
||||
* 👷 Tweak CI for test-redistribute, add needed env vars for slim. PR [#11549](https://github.com/tiangolo/fastapi/pull/11549) by [@tiangolo](https://github.com/tiangolo).
|
||||
* 👥 Update FastAPI People. PR [#11511](https://github.com/tiangolo/fastapi/pull/11511) by [@tiangolo](https://github.com/tiangolo).
|
||||
|
||||
## 0.111.0
|
||||
|
||||
### Features
|
||||
|
||||
* ✨ Add FastAPI CLI, the new `fastapi` command. PR [#11522](https://github.com/tiangolo/fastapi/pull/11522) by [@tiangolo](https://github.com/tiangolo).
|
||||
* New docs: [FastAPI CLI](https://fastapi.tiangolo.com/fastapi-cli/).
|
||||
|
||||
Try it out with:
|
||||
|
||||
```console
|
||||
$ pip install --upgrade fastapi
|
||||
|
||||
$ fastapi dev main.py
|
||||
|
||||
|
||||
╭────────── FastAPI CLI - Development mode ───────────╮
|
||||
│ │
|
||||
│ Serving at: http://127.0.0.1:8000 │
|
||||
│ │
|
||||
│ API docs: http://127.0.0.1:8000/docs │
|
||||
│ │
|
||||
│ Running in development mode, for production use: │
|
||||
│ │
|
||||
│ fastapi run │
|
||||
│ │
|
||||
╰─────────────────────────────────────────────────────╯
|
||||
|
||||
INFO: Will watch for changes in these directories: ['/home/user/code/awesomeapp']
|
||||
INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit)
|
||||
INFO: Started reloader process [2248755] using WatchFiles
|
||||
INFO: Started server process [2248757]
|
||||
INFO: Waiting for application startup.
|
||||
INFO: Application startup complete.
|
||||
```
|
||||
|
||||
### Refactors
|
||||
|
||||
* 🔧 Add configs and setup for `fastapi-slim` including optional extras `fastapi-slim[standard]`, and `fastapi` including by default the same `standard` extras. PR [#11503](https://github.com/tiangolo/fastapi/pull/11503) by [@tiangolo](https://github.com/tiangolo).
|
||||
|
||||
## 0.110.3
|
||||
|
||||
### Docs
|
||||
|
||||
* 📝 Update references to Python version, FastAPI supports all the current versions, no need to make the version explicit. PR [#11496](https://github.com/tiangolo/fastapi/pull/11496) by [@tiangolo](https://github.com/tiangolo).
|
||||
@@ -3808,7 +3941,7 @@ Note: all the previous parameters are still there, so it's still possible to dec
|
||||
* New documentation about exceptions handlers:
|
||||
* [Install custom exception handlers](https://fastapi.tiangolo.com/tutorial/handling-errors/#install-custom-exception-handlers).
|
||||
* [Override the default exception handlers](https://fastapi.tiangolo.com/tutorial/handling-errors/#override-the-default-exception-handlers).
|
||||
* [Re-use **FastAPI's** exception handlers](https://fastapi.tiangolo.com/tutorial/handling-errors/#re-use-fastapis-exception-handlers).
|
||||
* [Reuse **FastAPI's** exception handlers](https://fastapi.tiangolo.com/tutorial/handling-errors/#reuse-fastapis-exception-handlers).
|
||||
* PR [#273](https://github.com/tiangolo/fastapi/pull/273).
|
||||
|
||||
* Fix support for *paths* in *path parameters* without needing explicit `Path(...)`.
|
||||
|
||||
@@ -55,7 +55,7 @@ Inside of your *path operation function*, pass your task function to the *backgr
|
||||
|
||||
Using `BackgroundTasks` also works with the dependency injection system, you can declare a parameter of type `BackgroundTasks` at multiple levels: in a *path operation function*, in a dependency (dependable), in a sub-dependency, etc.
|
||||
|
||||
**FastAPI** knows what to do in each case and how to re-use the same object, so that all the background tasks are merged together and are run in the background afterwards:
|
||||
**FastAPI** knows what to do in each case and how to reuse the same object, so that all the background tasks are merged together and are run in the background afterwards:
|
||||
|
||||
=== "Python 3.10+"
|
||||
|
||||
|
||||
@@ -97,7 +97,7 @@ So, it will then use the parameter names as keys (field names) in the body, and
|
||||
Notice that even though the `item` was declared the same way as before, it is now expected to be inside of the body with a key `item`.
|
||||
|
||||
|
||||
**FastAPI** will do the automatic conversion from the request, so that the parameter `item` receives it's specific content and the same for `user`.
|
||||
**FastAPI** will do the automatic conversion from the request, so that the parameter `item` receives its specific content and the same for `user`.
|
||||
|
||||
It will perform the validation of the compound data, and will document it like that for the OpenAPI schema and automatic docs.
|
||||
|
||||
|
||||
@@ -107,7 +107,7 @@ These dependencies can `raise` exceptions, the same as normal dependencies:
|
||||
|
||||
And they can return values or not, the values won't be used.
|
||||
|
||||
So, you can re-use a normal dependency (that returns a value) you already use somewhere else, and even though the value won't be used, the dependency will be executed:
|
||||
So, you can reuse a normal dependency (that returns a value) you already use somewhere else, and even though the value won't be used, the dependency will be executed:
|
||||
|
||||
=== "Python 3.9+"
|
||||
|
||||
|
||||
@@ -157,7 +157,7 @@ query_extractor --> query_or_cookie_extractor --> read_query
|
||||
|
||||
If one of your dependencies is declared multiple times for the same *path operation*, for example, multiple dependencies have a common sub-dependency, **FastAPI** will know to call that sub-dependency only once per request.
|
||||
|
||||
And it will save the returned value in a <abbr title="A utility/system to store computed/generated values, to re-use them instead of computing them again.">"cache"</abbr> and pass it to all the "dependants" that need it in that specific request, instead of calling the dependency multiple times for the same request.
|
||||
And it will save the returned value in a <abbr title="A utility/system to store computed/generated values, to reuse them instead of computing them again.">"cache"</abbr> and pass it to all the "dependants" that need it in that specific request, instead of calling the dependency multiple times for the same request.
|
||||
|
||||
In an advanced scenario where you know you need the dependency to be called at every step (possibly multiple times) in the same request instead of using the "cached" value, you can set the parameter `use_cache=False` when using `Depends`:
|
||||
|
||||
|
||||
@@ -13,24 +13,51 @@ Run the live server:
|
||||
<div class="termy">
|
||||
|
||||
```console
|
||||
$ uvicorn main:app --reload
|
||||
$ <font color="#4E9A06">fastapi</font> dev <u style="text-decoration-style:single">main.py</u>
|
||||
<font color="#3465A4">INFO </font> Using path <font color="#3465A4">main.py</font>
|
||||
<font color="#3465A4">INFO </font> Resolved absolute path <font color="#75507B">/home/user/code/awesomeapp/</font><font color="#AD7FA8">main.py</font>
|
||||
<font color="#3465A4">INFO </font> Searching for package file structure from directories with <font color="#3465A4">__init__.py</font> files
|
||||
<font color="#3465A4">INFO </font> Importing from <font color="#75507B">/home/user/code/</font><font color="#AD7FA8">awesomeapp</font>
|
||||
|
||||
<span style="color: green;">INFO</span>: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit)
|
||||
<span style="color: green;">INFO</span>: Started reloader process [28720]
|
||||
<span style="color: green;">INFO</span>: Started server process [28722]
|
||||
<span style="color: green;">INFO</span>: Waiting for application startup.
|
||||
<span style="color: green;">INFO</span>: Application startup complete.
|
||||
╭─ <font color="#8AE234"><b>Python module file</b></font> ─╮
|
||||
│ │
|
||||
│ 🐍 main.py │
|
||||
│ │
|
||||
╰──────────────────────╯
|
||||
|
||||
<font color="#3465A4">INFO </font> Importing module <font color="#4E9A06">main</font>
|
||||
<font color="#3465A4">INFO </font> Found importable FastAPI app
|
||||
|
||||
╭─ <font color="#8AE234"><b>Importable FastAPI app</b></font> ─╮
|
||||
│ │
|
||||
│ <span style="background-color:#272822"><font color="#FF4689">from</font></span><span style="background-color:#272822"><font color="#F8F8F2"> main </font></span><span style="background-color:#272822"><font color="#FF4689">import</font></span><span style="background-color:#272822"><font color="#F8F8F2"> app</font></span><span style="background-color:#272822"> </span> │
|
||||
│ │
|
||||
╰──────────────────────────╯
|
||||
|
||||
<font color="#3465A4">INFO </font> Using import string <font color="#8AE234"><b>main:app</b></font>
|
||||
|
||||
<span style="background-color:#C4A000"><font color="#2E3436">╭────────── FastAPI CLI - Development mode ───────────╮</font></span>
|
||||
<span style="background-color:#C4A000"><font color="#2E3436">│ │</font></span>
|
||||
<span style="background-color:#C4A000"><font color="#2E3436">│ Serving at: http://127.0.0.1:8000 │</font></span>
|
||||
<span style="background-color:#C4A000"><font color="#2E3436">│ │</font></span>
|
||||
<span style="background-color:#C4A000"><font color="#2E3436">│ API docs: http://127.0.0.1:8000/docs │</font></span>
|
||||
<span style="background-color:#C4A000"><font color="#2E3436">│ │</font></span>
|
||||
<span style="background-color:#C4A000"><font color="#2E3436">│ Running in development mode, for production use: │</font></span>
|
||||
<span style="background-color:#C4A000"><font color="#2E3436">│ │</font></span>
|
||||
<span style="background-color:#C4A000"><font color="#2E3436">│ </font></span><span style="background-color:#C4A000"><font color="#555753"><b>fastapi run</b></font></span><span style="background-color:#C4A000"><font color="#2E3436"> │</font></span>
|
||||
<span style="background-color:#C4A000"><font color="#2E3436">│ │</font></span>
|
||||
<span style="background-color:#C4A000"><font color="#2E3436">╰─────────────────────────────────────────────────────╯</font></span>
|
||||
|
||||
<font color="#4E9A06">INFO</font>: Will watch for changes in these directories: ['/home/user/code/awesomeapp']
|
||||
<font color="#4E9A06">INFO</font>: Uvicorn running on <b>http://127.0.0.1:8000</b> (Press CTRL+C to quit)
|
||||
<font color="#4E9A06">INFO</font>: Started reloader process [<font color="#34E2E2"><b>2265862</b></font>] using <font color="#34E2E2"><b>WatchFiles</b></font>
|
||||
<font color="#4E9A06">INFO</font>: Started server process [<font color="#06989A">2265873</font>]
|
||||
<font color="#4E9A06">INFO</font>: Waiting for application startup.
|
||||
<font color="#4E9A06">INFO</font>: Application startup complete.
|
||||
```
|
||||
|
||||
</div>
|
||||
|
||||
!!! note
|
||||
The command `uvicorn main:app` refers to:
|
||||
|
||||
* `main`: the file `main.py` (the Python "module").
|
||||
* `app`: the object created inside of `main.py` with the line `app = FastAPI()`.
|
||||
* `--reload`: make the server restart after code changes. Only use for development.
|
||||
|
||||
In the output, there's a line with something like:
|
||||
|
||||
```hl_lines="4"
|
||||
@@ -151,36 +178,6 @@ Here the `app` variable will be an "instance" of the class `FastAPI`.
|
||||
|
||||
This will be the main point of interaction to create all your API.
|
||||
|
||||
This `app` is the same one referred by `uvicorn` in the command:
|
||||
|
||||
<div class="termy">
|
||||
|
||||
```console
|
||||
$ uvicorn main:app --reload
|
||||
|
||||
<span style="color: green;">INFO</span>: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit)
|
||||
```
|
||||
|
||||
</div>
|
||||
|
||||
If you create your app like:
|
||||
|
||||
```Python hl_lines="3"
|
||||
{!../../../docs_src/first_steps/tutorial002.py!}
|
||||
```
|
||||
|
||||
And put it in a file `main.py`, then you would call `uvicorn` like:
|
||||
|
||||
<div class="termy">
|
||||
|
||||
```console
|
||||
$ uvicorn main:my_awesome_api --reload
|
||||
|
||||
<span style="color: green;">INFO</span>: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit)
|
||||
```
|
||||
|
||||
</div>
|
||||
|
||||
### Step 3: create a *path operation*
|
||||
|
||||
#### Path
|
||||
@@ -328,6 +325,6 @@ There are many other objects and models that will be automatically converted to
|
||||
|
||||
* Import `FastAPI`.
|
||||
* Create an `app` instance.
|
||||
* Write a **path operation decorator** (like `@app.get("/")`).
|
||||
* Write a **path operation function** (like `def root(): ...` above).
|
||||
* Run the development server (like `uvicorn main:app --reload`).
|
||||
* Write a **path operation decorator** using decorators like `@app.get("/")`.
|
||||
* Define a **path operation function**; for example, `def root(): ...`.
|
||||
* Run the development server using the command `fastapi dev`.
|
||||
|
||||
@@ -248,12 +248,12 @@ In this example, to be able to have both `HTTPException`s in the same code, Star
|
||||
from starlette.exceptions import HTTPException as StarletteHTTPException
|
||||
```
|
||||
|
||||
### Re-use **FastAPI**'s exception handlers
|
||||
### Reuse **FastAPI**'s exception handlers
|
||||
|
||||
If you want to use the exception along with the same default exception handlers from **FastAPI**, You can import and re-use the default exception handlers from `fastapi.exception_handlers`:
|
||||
If you want to use the exception along with the same default exception handlers from **FastAPI**, You can import and reuse the default exception handlers from `fastapi.exception_handlers`:
|
||||
|
||||
```Python hl_lines="2-5 15 21"
|
||||
{!../../../docs_src/handling_errors/tutorial006.py!}
|
||||
```
|
||||
|
||||
In this example you are just `print`ing the error with a very expressive message, but you get the idea. You can use the exception and then just re-use the default exception handlers.
|
||||
In this example you are just `print`ing the error with a very expressive message, but you get the idea. You can use the exception and then just reuse the default exception handlers.
|
||||
|
||||
@@ -12,18 +12,53 @@ So you can come back and see exactly what you need.
|
||||
|
||||
All the code blocks can be copied and used directly (they are actually tested Python files).
|
||||
|
||||
To run any of the examples, copy the code to a file `main.py`, and start `uvicorn` with:
|
||||
To run any of the examples, copy the code to a file `main.py`, and start `fastapi dev` with:
|
||||
|
||||
<div class="termy">
|
||||
|
||||
```console
|
||||
$ uvicorn main:app --reload
|
||||
$ <font color="#4E9A06">fastapi</font> dev <u style="text-decoration-style:single">main.py</u>
|
||||
<font color="#3465A4">INFO </font> Using path <font color="#3465A4">main.py</font>
|
||||
<font color="#3465A4">INFO </font> Resolved absolute path <font color="#75507B">/home/user/code/awesomeapp/</font><font color="#AD7FA8">main.py</font>
|
||||
<font color="#3465A4">INFO </font> Searching for package file structure from directories with <font color="#3465A4">__init__.py</font> files
|
||||
<font color="#3465A4">INFO </font> Importing from <font color="#75507B">/home/user/code/</font><font color="#AD7FA8">awesomeapp</font>
|
||||
|
||||
<span style="color: green;">INFO</span>: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit)
|
||||
<span style="color: green;">INFO</span>: Started reloader process [28720]
|
||||
<span style="color: green;">INFO</span>: Started server process [28722]
|
||||
<span style="color: green;">INFO</span>: Waiting for application startup.
|
||||
<span style="color: green;">INFO</span>: Application startup complete.
|
||||
╭─ <font color="#8AE234"><b>Python module file</b></font> ─╮
|
||||
│ │
|
||||
│ 🐍 main.py │
|
||||
│ │
|
||||
╰──────────────────────╯
|
||||
|
||||
<font color="#3465A4">INFO </font> Importing module <font color="#4E9A06">main</font>
|
||||
<font color="#3465A4">INFO </font> Found importable FastAPI app
|
||||
|
||||
╭─ <font color="#8AE234"><b>Importable FastAPI app</b></font> ─╮
|
||||
│ │
|
||||
│ <span style="background-color:#272822"><font color="#FF4689">from</font></span><span style="background-color:#272822"><font color="#F8F8F2"> main </font></span><span style="background-color:#272822"><font color="#FF4689">import</font></span><span style="background-color:#272822"><font color="#F8F8F2"> app</font></span><span style="background-color:#272822"> </span> │
|
||||
│ │
|
||||
╰──────────────────────────╯
|
||||
|
||||
<font color="#3465A4">INFO </font> Using import string <font color="#8AE234"><b>main:app</b></font>
|
||||
|
||||
<span style="background-color:#C4A000"><font color="#2E3436">╭────────── FastAPI CLI - Development mode ───────────╮</font></span>
|
||||
<span style="background-color:#C4A000"><font color="#2E3436">│ │</font></span>
|
||||
<span style="background-color:#C4A000"><font color="#2E3436">│ Serving at: http://127.0.0.1:8000 │</font></span>
|
||||
<span style="background-color:#C4A000"><font color="#2E3436">│ │</font></span>
|
||||
<span style="background-color:#C4A000"><font color="#2E3436">│ API docs: http://127.0.0.1:8000/docs │</font></span>
|
||||
<span style="background-color:#C4A000"><font color="#2E3436">│ │</font></span>
|
||||
<span style="background-color:#C4A000"><font color="#2E3436">│ Running in development mode, for production use: │</font></span>
|
||||
<span style="background-color:#C4A000"><font color="#2E3436">│ │</font></span>
|
||||
<span style="background-color:#C4A000"><font color="#2E3436">│ </font></span><span style="background-color:#C4A000"><font color="#555753"><b>fastapi run</b></font></span><span style="background-color:#C4A000"><font color="#2E3436"> │</font></span>
|
||||
<span style="background-color:#C4A000"><font color="#2E3436">│ │</font></span>
|
||||
<span style="background-color:#C4A000"><font color="#2E3436">╰─────────────────────────────────────────────────────╯</font></span>
|
||||
|
||||
<font color="#4E9A06">INFO</font>: Will watch for changes in these directories: ['/home/user/code/awesomeapp']
|
||||
<font color="#4E9A06">INFO</font>: Uvicorn running on <b>http://127.0.0.1:8000</b> (Press CTRL+C to quit)
|
||||
<font color="#4E9A06">INFO</font>: Started reloader process [<font color="#34E2E2"><b>2265862</b></font>] using <font color="#34E2E2"><b>WatchFiles</b></font>
|
||||
<font color="#4E9A06">INFO</font>: Started server process [<font color="#06989A">2265873</font>]
|
||||
<font color="#4E9A06">INFO</font>: Waiting for application startup.
|
||||
<font color="#4E9A06">INFO</font>: Application startup complete.
|
||||
</pre>
|
||||
```
|
||||
|
||||
</div>
|
||||
@@ -36,38 +71,22 @@ Using it in your editor is what really shows you the benefits of FastAPI, seeing
|
||||
|
||||
## Install FastAPI
|
||||
|
||||
The first step is to install FastAPI.
|
||||
|
||||
For the tutorial, you might want to install it with all the optional dependencies and features:
|
||||
The first step is to install FastAPI:
|
||||
|
||||
<div class="termy">
|
||||
|
||||
```console
|
||||
$ pip install "fastapi[all]"
|
||||
$ pip install fastapi
|
||||
|
||||
---> 100%
|
||||
```
|
||||
|
||||
</div>
|
||||
|
||||
...that also includes `uvicorn`, that you can use as the server that runs your code.
|
||||
|
||||
!!! note
|
||||
You can also install it part by part.
|
||||
When you install with `pip install fastapi` it comes with some default optional standard dependencies.
|
||||
|
||||
This is what you would probably do once you want to deploy your application to production:
|
||||
|
||||
```
|
||||
pip install fastapi
|
||||
```
|
||||
|
||||
Also install `uvicorn` to work as the server:
|
||||
|
||||
```
|
||||
pip install "uvicorn[standard]"
|
||||
```
|
||||
|
||||
And the same for each of the optional dependencies that you want to use.
|
||||
If you don't want to have those optional dependencies, you can instead install `pip install fastapi-slim`.
|
||||
|
||||
## Advanced User Guide
|
||||
|
||||
|
||||
@@ -92,11 +92,7 @@ For example, to declare a `title` metadata value for the path parameter `item_id
|
||||
```
|
||||
|
||||
!!! note
|
||||
A path parameter is always required as it has to be part of the path.
|
||||
|
||||
So, you should declare it with `...` to mark it as required.
|
||||
|
||||
Nevertheless, even if you declared it with `None` or set a default value, it would not affect anything, it would still be always required.
|
||||
A path parameter is always required as it has to be part of the path. Even if you declared it with `None` or set a default value, it would not affect anything, it would still be always required.
|
||||
|
||||
## Order the parameters as you need
|
||||
|
||||
|
||||
@@ -99,7 +99,7 @@ Now let's jump to the fun stuff. 🎉
|
||||
|
||||
## Add `Query` to `Annotated` in the `q` parameter
|
||||
|
||||
Now that we have this `Annotated` where we can put more metadata, add `Query` to it, and set the parameter `max_length` to 50:
|
||||
Now that we have this `Annotated` where we can put more information (in this case some additional validation), add `Query` inside of `Annotated`, and set the parameter `max_length` to `50`:
|
||||
|
||||
=== "Python 3.10+"
|
||||
|
||||
@@ -115,7 +115,11 @@ Now that we have this `Annotated` where we can put more metadata, add `Query` to
|
||||
|
||||
Notice that the default value is still `None`, so the parameter is still optional.
|
||||
|
||||
But now, having `Query(max_length=50)` inside of `Annotated`, we are telling FastAPI that we want it to extract this value from the query parameters (this would have been the default anyway 🤷) and that we want to have **additional validation** for this value (that's why we do this, to get the additional validation). 😎
|
||||
But now, having `Query(max_length=50)` inside of `Annotated`, we are telling FastAPI that we want it to have **additional validation** for this value, we want it to have maximum 50 characters. 😎
|
||||
|
||||
!!! tip
|
||||
|
||||
Here we are using `Query()` because this is a **query parameter**. Later we will see others like `Path()`, `Body()`, `Header()`, and `Cookie()`, that also accept the same arguments as `Query()`.
|
||||
|
||||
FastAPI will now:
|
||||
|
||||
|
||||
@@ -45,9 +45,11 @@ Copy the example in a file `main.py`:
|
||||
## Run it
|
||||
|
||||
!!! info
|
||||
First install <a href="https://github.com/Kludex/python-multipart" class="external-link" target="_blank">`python-multipart`</a>.
|
||||
The <a href="https://github.com/Kludex/python-multipart" class="external-link" target="_blank">`python-multipart`</a> package is automatically installed with **FastAPI** when you run the `pip install fastapi` command.
|
||||
|
||||
E.g. `pip install python-multipart`.
|
||||
However, if you use the `pip install fastapi-slim` command, the `python-multipart` package is not included by default. To install it manually, use the following command:
|
||||
|
||||
`pip install python-multipart`
|
||||
|
||||
This is because **OAuth2** uses "form data" for sending the `username` and `password`.
|
||||
|
||||
@@ -56,7 +58,7 @@ Run the example with:
|
||||
<div class="termy">
|
||||
|
||||
```console
|
||||
$ uvicorn main:app --reload
|
||||
$ fastapi dev main.py
|
||||
|
||||
<span style="color: green;">INFO</span>: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit)
|
||||
```
|
||||
|
||||
@@ -26,28 +26,24 @@ After a week, the token will be expired and the user will not be authorized and
|
||||
|
||||
If you want to play with JWT tokens and see how they work, check <a href="https://jwt.io/" class="external-link" target="_blank">https://jwt.io</a>.
|
||||
|
||||
## Install `python-jose`
|
||||
## Install `PyJWT`
|
||||
|
||||
We need to install `python-jose` to generate and verify the JWT tokens in Python:
|
||||
We need to install `PyJWT` to generate and verify the JWT tokens in Python:
|
||||
|
||||
<div class="termy">
|
||||
|
||||
```console
|
||||
$ pip install "python-jose[cryptography]"
|
||||
$ pip install pyjwt
|
||||
|
||||
---> 100%
|
||||
```
|
||||
|
||||
</div>
|
||||
|
||||
<a href="https://github.com/mpdavis/python-jose" class="external-link" target="_blank">Python-jose</a> requires a cryptographic backend as an extra.
|
||||
!!! info
|
||||
If you are planning to use digital signature algorithms like RSA or ECDSA, you should install the cryptography library dependency `pyjwt[crypto]`.
|
||||
|
||||
Here we are using the recommended one: <a href="https://cryptography.io/" class="external-link" target="_blank">pyca/cryptography</a>.
|
||||
|
||||
!!! tip
|
||||
This tutorial previously used <a href="https://pyjwt.readthedocs.io/" class="external-link" target="_blank">PyJWT</a>.
|
||||
|
||||
But it was updated to use Python-jose instead as it provides all the features from PyJWT plus some extras that you might need later when building integrations with other tools.
|
||||
You can read more about it in the <a href="https://pyjwt.readthedocs.io/en/latest/installation.html" class="external-link" target="_blank">PyJWT Installation docs</a>.
|
||||
|
||||
## Password hashing
|
||||
|
||||
@@ -111,19 +107,19 @@ And another one to authenticate and return a user.
|
||||
|
||||
=== "Python 3.10+"
|
||||
|
||||
```Python hl_lines="7 48 55-56 59-60 69-75"
|
||||
```Python hl_lines="8 49 56-57 60-61 70-76"
|
||||
{!> ../../../docs_src/security/tutorial004_an_py310.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.9+"
|
||||
|
||||
```Python hl_lines="7 48 55-56 59-60 69-75"
|
||||
```Python hl_lines="8 49 56-57 60-61 70-76"
|
||||
{!> ../../../docs_src/security/tutorial004_an_py39.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.8+"
|
||||
|
||||
```Python hl_lines="7 49 56-57 60-61 70-76"
|
||||
```Python hl_lines="8 50 57-58 61-62 71-77"
|
||||
{!> ../../../docs_src/security/tutorial004_an.py!}
|
||||
```
|
||||
|
||||
@@ -132,7 +128,7 @@ And another one to authenticate and return a user.
|
||||
!!! tip
|
||||
Prefer to use the `Annotated` version if possible.
|
||||
|
||||
```Python hl_lines="6 47 54-55 58-59 68-74"
|
||||
```Python hl_lines="7 48 55-56 59-60 69-75"
|
||||
{!> ../../../docs_src/security/tutorial004_py310.py!}
|
||||
```
|
||||
|
||||
@@ -141,7 +137,7 @@ And another one to authenticate and return a user.
|
||||
!!! tip
|
||||
Prefer to use the `Annotated` version if possible.
|
||||
|
||||
```Python hl_lines="7 48 55-56 59-60 69-75"
|
||||
```Python hl_lines="8 49 56-57 60-61 70-76"
|
||||
{!> ../../../docs_src/security/tutorial004.py!}
|
||||
```
|
||||
|
||||
@@ -178,19 +174,19 @@ Create a utility function to generate a new access token.
|
||||
|
||||
=== "Python 3.10+"
|
||||
|
||||
```Python hl_lines="6 12-14 28-30 78-86"
|
||||
```Python hl_lines="4 7 13-15 29-31 79-87"
|
||||
{!> ../../../docs_src/security/tutorial004_an_py310.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.9+"
|
||||
|
||||
```Python hl_lines="6 12-14 28-30 78-86"
|
||||
```Python hl_lines="4 7 13-15 29-31 79-87"
|
||||
{!> ../../../docs_src/security/tutorial004_an_py39.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.8+"
|
||||
|
||||
```Python hl_lines="6 13-15 29-31 79-87"
|
||||
```Python hl_lines="4 7 14-16 30-32 80-88"
|
||||
{!> ../../../docs_src/security/tutorial004_an.py!}
|
||||
```
|
||||
|
||||
@@ -199,7 +195,7 @@ Create a utility function to generate a new access token.
|
||||
!!! tip
|
||||
Prefer to use the `Annotated` version if possible.
|
||||
|
||||
```Python hl_lines="5 11-13 27-29 77-85"
|
||||
```Python hl_lines="3 6 12-14 28-30 78-86"
|
||||
{!> ../../../docs_src/security/tutorial004_py310.py!}
|
||||
```
|
||||
|
||||
@@ -208,7 +204,7 @@ Create a utility function to generate a new access token.
|
||||
!!! tip
|
||||
Prefer to use the `Annotated` version if possible.
|
||||
|
||||
```Python hl_lines="6 12-14 28-30 78-86"
|
||||
```Python hl_lines="4 7 13-15 29-31 79-87"
|
||||
{!> ../../../docs_src/security/tutorial004.py!}
|
||||
```
|
||||
|
||||
@@ -222,19 +218,19 @@ If the token is invalid, return an HTTP error right away.
|
||||
|
||||
=== "Python 3.10+"
|
||||
|
||||
```Python hl_lines="89-106"
|
||||
```Python hl_lines="90-107"
|
||||
{!> ../../../docs_src/security/tutorial004_an_py310.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.9+"
|
||||
|
||||
```Python hl_lines="89-106"
|
||||
```Python hl_lines="90-107"
|
||||
{!> ../../../docs_src/security/tutorial004_an_py39.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.8+"
|
||||
|
||||
```Python hl_lines="90-107"
|
||||
```Python hl_lines="91-108"
|
||||
{!> ../../../docs_src/security/tutorial004_an.py!}
|
||||
```
|
||||
|
||||
@@ -243,7 +239,7 @@ If the token is invalid, return an HTTP error right away.
|
||||
!!! tip
|
||||
Prefer to use the `Annotated` version if possible.
|
||||
|
||||
```Python hl_lines="88-105"
|
||||
```Python hl_lines="89-106"
|
||||
{!> ../../../docs_src/security/tutorial004_py310.py!}
|
||||
```
|
||||
|
||||
@@ -252,7 +248,7 @@ If the token is invalid, return an HTTP error right away.
|
||||
!!! tip
|
||||
Prefer to use the `Annotated` version if possible.
|
||||
|
||||
```Python hl_lines="89-106"
|
||||
```Python hl_lines="90-107"
|
||||
{!> ../../../docs_src/security/tutorial004.py!}
|
||||
```
|
||||
|
||||
@@ -264,19 +260,19 @@ Create a real JWT access token and return it.
|
||||
|
||||
=== "Python 3.10+"
|
||||
|
||||
```Python hl_lines="117-132"
|
||||
```Python hl_lines="118-133"
|
||||
{!> ../../../docs_src/security/tutorial004_an_py310.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.9+"
|
||||
|
||||
```Python hl_lines="117-132"
|
||||
```Python hl_lines="118-133"
|
||||
{!> ../../../docs_src/security/tutorial004_an_py39.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.8+"
|
||||
|
||||
```Python hl_lines="118-133"
|
||||
```Python hl_lines="119-134"
|
||||
{!> ../../../docs_src/security/tutorial004_an.py!}
|
||||
```
|
||||
|
||||
@@ -285,7 +281,7 @@ Create a real JWT access token and return it.
|
||||
!!! tip
|
||||
Prefer to use the `Annotated` version if possible.
|
||||
|
||||
```Python hl_lines="114-129"
|
||||
```Python hl_lines="115-130"
|
||||
{!> ../../../docs_src/security/tutorial004_py310.py!}
|
||||
```
|
||||
|
||||
@@ -294,7 +290,7 @@ Create a real JWT access token and return it.
|
||||
!!! tip
|
||||
Prefer to use the `Annotated` version if possible.
|
||||
|
||||
```Python hl_lines="115-130"
|
||||
```Python hl_lines="116-131"
|
||||
{!> ../../../docs_src/security/tutorial004.py!}
|
||||
```
|
||||
|
||||
@@ -384,7 +380,7 @@ Many packages that simplify it a lot have to make many compromises with the data
|
||||
|
||||
It gives you all the flexibility to choose the ones that fit your project the best.
|
||||
|
||||
And you can use directly many well maintained and widely used packages like `passlib` and `python-jose`, because **FastAPI** doesn't require any complex mechanisms to integrate external packages.
|
||||
And you can use directly many well maintained and widely used packages like `passlib` and `PyJWT`, because **FastAPI** doesn't require any complex mechanisms to integrate external packages.
|
||||
|
||||
But it provides you the tools to simplify the process as much as possible without compromising flexibility, robustness, or security.
|
||||
|
||||
|
||||
@@ -513,7 +513,7 @@ And you would also use Alembic for "migrations" (that's its main job).
|
||||
|
||||
A "migration" is the set of steps needed whenever you change the structure of your SQLAlchemy models, add a new attribute, etc. to replicate those changes in the database, add a new column, a new table, etc.
|
||||
|
||||
You can find an example of Alembic in a FastAPI project in the templates from [Project Generation - Template](../project-generation.md){.internal-link target=_blank}. Specifically in <a href="https://github.com/tiangolo/full-stack-fastapi-postgresql/tree/master/src/backend/app/alembic" class="external-link" target="_blank">the `alembic` directory in the source code</a>.
|
||||
You can find an example of Alembic in a FastAPI project in the [Full Stack FastAPI Template](../project-generation.md){.internal-link target=_blank}. Specifically in <a href="https://github.com/tiangolo/full-stack-fastapi-template/tree/master/backend/app/alembic" class="external-link" target="_blank">the `alembic` directory in the source code</a>.
|
||||
|
||||
### Create a dependency
|
||||
|
||||
|
||||
@@ -167,6 +167,7 @@ nav:
|
||||
- advanced/openapi-webhooks.md
|
||||
- advanced/wsgi.md
|
||||
- advanced/generate-clients.md
|
||||
- fastapi-cli.md
|
||||
- Deployment:
|
||||
- deployment/index.md
|
||||
- deployment/versions.md
|
||||
|
||||
@@ -65,7 +65,7 @@
|
||||
</a>
|
||||
</div>
|
||||
<div class="item">
|
||||
<a title="Coherence" style="display: block; position: relative;" href="https://www.withcoherence.com/?utm_medium=advertising&utm_source=fastapi&utm_campaign=banner%20january%2024" target="_blank">
|
||||
<a title="Coherence" style="display: block; position: relative;" href="https://docs.withcoherence.com/configuration/frameworks/?utm_medium=advertising&utm_source=fastapi&utm_campaign=docs#fastapi-example" target="_blank">
|
||||
<span class="sponsor-badge">sponsor</span>
|
||||
<img class="sponsor-image" src="/img/sponsors/coherence-banner.png" />
|
||||
</a>
|
||||
@@ -76,6 +76,24 @@
|
||||
<img class="sponsor-image" src="/img/sponsors/mongodb-banner.png" />
|
||||
</a>
|
||||
</div>
|
||||
<div class="item">
|
||||
<a title="Kong Konnect - API management platform" style="display: block; position: relative;" href="https://konghq.com/products/kong-konnect?utm_medium=referral&utm_source=github&utm_campaign=platform&utm_content=fast-api" target="_blank">
|
||||
<span class="sponsor-badge">sponsor</span>
|
||||
<img class="sponsor-image" src="/img/sponsors/kong-banner.png" />
|
||||
</a>
|
||||
</div>
|
||||
<div class="item">
|
||||
<a title="Zuplo: Scale, Protect, Document, and Monetize your FastAPI" style="display: block; position: relative;" href="https://zuplo.link/fastapi-web" target="_blank">
|
||||
<span class="sponsor-badge">sponsor</span>
|
||||
<img class="sponsor-image" src="/img/sponsors/zuplo-banner.png" />
|
||||
</a>
|
||||
</div>
|
||||
<div class="item">
|
||||
<a title="Fine's AI FastAPI Workflow: Effortlessly Deploy and Integrate FastAPI into Your Project" style="display: block; position: relative;" href="https://fine.dev?ref=fastapibanner" target="_blank">
|
||||
<span class="sponsor-badge">sponsor</span>
|
||||
<img class="sponsor-image" src="/img/sponsors/fine-banner.png" />
|
||||
</a>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
{% endblock %}
|
||||
|
||||
56
docs/es/docs/how-to/graphql.md
Normal file
@@ -0,0 +1,56 @@
|
||||
# GraphQL
|
||||
|
||||
Como **FastAPI** está basado en el estándar **ASGI**, es muy fácil integrar cualquier library **GraphQL** que sea compatible con ASGI.
|
||||
|
||||
Puedes combinar *operaciones de path* regulares de la library de FastAPI con GraphQL en la misma aplicación.
|
||||
|
||||
!!! tip
|
||||
**GraphQL** resuelve algunos casos de uso específicos.
|
||||
|
||||
Tiene **ventajas** y **desventajas** cuando lo comparas con **APIs web** comunes.
|
||||
|
||||
Asegúrate de evaluar si los **beneficios** para tu caso de uso compensan las **desventajas.** 🤓
|
||||
|
||||
## Librerías GraphQL
|
||||
|
||||
Aquí hay algunas de las libraries de **GraphQL** que tienen soporte con **ASGI** las cuales podrías usar con **FastAPI**:
|
||||
|
||||
* <a href="https://strawberry.rocks/" class="external-link" target="_blank">Strawberry</a> 🍓
|
||||
* Con <a href="https://strawberry.rocks/docs/integrations/fastapi" class="external-link" target="_blank">documentación para FastAPI</a>
|
||||
* <a href="https://ariadnegraphql.org/" class="external-link" target="_blank">Ariadne</a>
|
||||
* Con <a href="https://ariadnegraphql.org/docs/fastapi-integration" class="external-link" target="_blank">documentación para FastAPI</a>
|
||||
* <a href="https://tartiflette.io/" class="external-link" target="_blank">Tartiflette</a>
|
||||
* Con <a href="https://tartiflette.github.io/tartiflette-asgi/" class="external-link" target="_blank">Tartiflette ASGI</a> para proveer integración con ASGI
|
||||
* <a href="https://graphene-python.org/" class="external-link" target="_blank">Graphene</a>
|
||||
* Con <a href="https://github.com/ciscorn/starlette-graphene3" class="external-link" target="_blank">starlette-graphene3</a>
|
||||
|
||||
## GraphQL con Strawberry
|
||||
|
||||
Si necesitas o quieres trabajar con **GraphQL**, <a href="https://strawberry.rocks/" class="external-link" target="_blank">**Strawberry**</a> es la library **recomendada** por el diseño más cercano a **FastAPI**, el cual es completamente basado en **anotaciones de tipo**.
|
||||
|
||||
Dependiendo de tus casos de uso, podrías preferir usar una library diferente, pero si me preguntas, probablemente te recomendaría **Strawberry**.
|
||||
|
||||
Aquí hay una pequeña muestra de cómo podrías integrar Strawberry con FastAPI:
|
||||
|
||||
```Python hl_lines="3 22 25-26"
|
||||
{!../../../docs_src/graphql/tutorial001.py!}
|
||||
```
|
||||
|
||||
Puedes aprender más sobre Strawberry en la <a href="https://strawberry.rocks/" class="external-link" target="_blank">documentación de Strawberry</a>.
|
||||
|
||||
Y también en la documentación sobre <a href="https://strawberry.rocks/docs/integrations/fastapi" class="external-link" target="_blank">Strawberry con FastAPI</a>.
|
||||
|
||||
## Clase obsoleta `GraphQLApp` en Starlette
|
||||
|
||||
Versiones anteriores de Starlette incluyen la clase `GraphQLApp` para integrarlo con <a href="https://graphene-python.org/" class="external-link" target="_blank">Graphene</a>.
|
||||
|
||||
Esto fue marcado como obsoleto en Starlette, pero si aún tienes código que lo usa, puedes fácilmente **migrar** a <a href="https://github.com/ciscorn/starlette-graphene3" class="external-link" target="_blank">starlette-graphene3</a>, la cual cubre el mismo caso de uso y tiene una **interfaz casi idéntica.**
|
||||
|
||||
!!! tip
|
||||
Si necesitas GraphQL, te recomendaría revisar <a href="https://strawberry.rocks/" class="external-link" target="_blank">Strawberry</a>, que es basada en anotaciones de tipo en vez de clases y tipos personalizados.
|
||||
|
||||
## Aprende más
|
||||
|
||||
Puedes aprender más acerca de **GraphQL** en la <a href="https://graphql.org/" class="external-link" target="_blank">documentación oficial de GraphQL</a>.
|
||||
|
||||
También puedes leer más acerca de cada library descrita anteriormente en sus enlaces.
|
||||
@@ -132,7 +132,7 @@ $ pip install fastapi
|
||||
|
||||
</div>
|
||||
|
||||
También vas a necesitar un servidor ASGI para producción cómo <a href="https://www.uvicorn.org" class="external-link" target="_blank">Uvicorn</a> o <a href="https://gitlab.com/pgjones/hypercorn" class="external-link" target="_blank">Hypercorn</a>.
|
||||
También vas a necesitar un servidor ASGI para producción cómo <a href="https://www.uvicorn.org" class="external-link" target="_blank">Uvicorn</a> o <a href="https://github.com/pgjones/hypercorn" class="external-link" target="_blank">Hypercorn</a>.
|
||||
|
||||
<div class="termy">
|
||||
|
||||
|
||||
@@ -134,7 +134,7 @@ $ pip install fastapi
|
||||
|
||||
</div>
|
||||
|
||||
نصب یک سرور پروداکشن نظیر <a href="https://www.uvicorn.org" class="external-link" target="_blank">Uvicorn</a> یا <a href="https://gitlab.com/pgjones/hypercorn" class="external-link" target="_blank">Hypercorn</a> نیز جزء نیازمندیهاست.
|
||||
نصب یک سرور پروداکشن نظیر <a href="https://www.uvicorn.org" class="external-link" target="_blank">Uvicorn</a> یا <a href="https://github.com/pgjones/hypercorn" class="external-link" target="_blank">Hypercorn</a> نیز جزء نیازمندیهاست.
|
||||
|
||||
<div class="termy">
|
||||
|
||||
|
||||
@@ -103,24 +103,41 @@ Pour expliquer la différence, voici une histoire de burgers :
|
||||
|
||||
Vous amenez votre crush 😍 dans votre fast food 🍔 favori, et faites la queue pendant que le serveur 💁 prend les commandes des personnes devant vous.
|
||||
|
||||
<img src="/img/async/concurrent-burgers/concurrent-burgers-01.png" class="illustration">
|
||||
|
||||
Puis vient votre tour, vous commandez alors 2 magnifiques burgers 🍔 pour votre crush 😍 et vous.
|
||||
|
||||
Vous payez 💸.
|
||||
<img src="/img/async/concurrent-burgers/concurrent-burgers-02.png" class="illustration">
|
||||
|
||||
Le serveur 💁 dit quelque chose à son collègue dans la cuisine 👨🍳 pour qu'il sache qu'il doit préparer vos burgers 🍔 (bien qu'il soit déjà en train de préparer ceux des clients précédents).
|
||||
|
||||
<img src="/img/async/concurrent-burgers/concurrent-burgers-03.png" class="illustration">
|
||||
|
||||
Vous payez 💸.
|
||||
|
||||
Le serveur 💁 vous donne le numéro assigné à votre commande.
|
||||
|
||||
<img src="/img/async/concurrent-burgers/concurrent-burgers-04.png" class="illustration">
|
||||
|
||||
Pendant que vous attendez, vous allez choisir une table avec votre crush 😍, vous discutez avec votre crush 😍 pendant un long moment (les burgers étant "magnifiques" ils sont très longs à préparer ✨🍔✨).
|
||||
|
||||
Pendant que vous êtes assis à table, en attendant que les burgers 🍔 soient prêts, vous pouvez passer ce temps à admirer à quel point votre crush 😍 est géniale, mignonne et intelligente ✨😍✨.
|
||||
|
||||
<img src="/img/async/concurrent-burgers/concurrent-burgers-05.png" class="illustration">
|
||||
|
||||
Pendant que vous discutez avec votre crush 😍, de temps en temps vous jetez un coup d'oeil au nombre affiché au-dessus du comptoir pour savoir si c'est à votre tour d'être servis.
|
||||
|
||||
Jusqu'au moment où c'est (enfin) votre tour. Vous allez au comptoir, récupérez vos burgers 🍔 et revenez à votre table.
|
||||
|
||||
<img src="/img/async/concurrent-burgers/concurrent-burgers-06.png" class="illustration">
|
||||
|
||||
Vous et votre crush 😍 mangez les burgers 🍔 et passez un bon moment ✨.
|
||||
|
||||
<img src="/img/async/concurrent-burgers/concurrent-burgers-07.png" class="illustration">
|
||||
|
||||
!!! info
|
||||
Illustrations proposées par <a href="https://www.instagram.com/ketrinadrawsalot" class="external-link" target="_blank">Ketrina Thompson</a>. 🎨
|
||||
|
||||
---
|
||||
|
||||
Imaginez que vous êtes l'ordinateur / le programme 🤖 dans cette histoire.
|
||||
@@ -149,26 +166,41 @@ Vous attendez pendant que plusieurs (disons 8) serveurs qui sont aussi des cuisi
|
||||
|
||||
Chaque personne devant vous attend 🕙 que son burger 🍔 soit prêt avant de quitter le comptoir car chacun des 8 serveurs va lui-même préparer le burger directement avant de prendre la commande suivante.
|
||||
|
||||
<img src="/img/async/parallel-burgers/parallel-burgers-01.png" class="illustration">
|
||||
|
||||
Puis c'est enfin votre tour, vous commandez 2 magnifiques burgers 🍔 pour vous et votre crush 😍.
|
||||
|
||||
Vous payez 💸.
|
||||
|
||||
<img src="/img/async/parallel-burgers/parallel-burgers-02.png" class="illustration">
|
||||
|
||||
Le serveur va dans la cuisine 👨🍳.
|
||||
|
||||
Vous attendez devant le comptoir afin que personne ne prenne vos burgers 🍔 avant vous, vu qu'il n'y a pas de numéro de commande.
|
||||
|
||||
<img src="/img/async/parallel-burgers/parallel-burgers-03.png" class="illustration">
|
||||
|
||||
Vous et votre crush 😍 étant occupés à vérifier que personne ne passe devant vous prendre vos burgers au moment où ils arriveront 🕙, vous ne pouvez pas vous préoccuper de votre crush 😞.
|
||||
|
||||
C'est du travail "synchrone", vous être "synchronisés" avec le serveur/cuisinier 👨🍳. Vous devez attendre 🕙 et être présent au moment exact où le serveur/cuisinier 👨🍳 finira les burgers 🍔 et vous les donnera, sinon quelqu'un risque de vous les prendre.
|
||||
|
||||
<img src="/img/async/parallel-burgers/parallel-burgers-04.png" class="illustration">
|
||||
|
||||
Puis le serveur/cuisinier 👨🍳 revient enfin avec vos burgers 🍔, après un long moment d'attente 🕙 devant le comptoir.
|
||||
|
||||
<img src="/img/async/parallel-burgers/parallel-burgers-05.png" class="illustration">
|
||||
|
||||
Vous prenez vos burgers 🍔 et allez à une table avec votre crush 😍
|
||||
|
||||
Vous les mangez, et vous avez terminé 🍔 ⏹.
|
||||
|
||||
<img src="/img/async/parallel-burgers/parallel-burgers-06.png" class="illustration">
|
||||
|
||||
Durant tout ce processus, il n'y a presque pas eu de discussions ou de flirts car la plupart de votre temps à été passé à attendre 🕙 devant le comptoir 😞.
|
||||
|
||||
!!! info
|
||||
Illustrations proposées par <a href="https://www.instagram.com/ketrinadrawsalot" class="external-link" target="_blank">Ketrina Thompson</a>. 🎨
|
||||
|
||||
---
|
||||
|
||||
Dans ce scénario de burgers parallèles, vous êtes un ordinateur / programme 🤖 avec deux processeurs (vous et votre crush 😍) attendant 🕙 à deux et dédiant votre attention 🕙 à "attendre devant le comptoir" pour une longue durée.
|
||||
|
||||
@@ -5,7 +5,7 @@ La principale chose dont vous avez besoin pour exécuter une application **FastA
|
||||
Il existe 3 principales alternatives :
|
||||
|
||||
* <a href="https://www.uvicorn.org/" class="external-link" target="_blank">Uvicorn</a> : un serveur ASGI haute performance.
|
||||
* <a href="https://pgjones.gitlab.io/hypercorn/" class="external-link" target="_blank">Hypercorn</a> : un serveur
|
||||
* <a href="https://hypercorn.readthedocs.io/" class="external-link" target="_blank">Hypercorn</a> : un serveur
|
||||
ASGI compatible avec HTTP/2 et Trio entre autres fonctionnalités.
|
||||
* <a href="https://github.com/django/daphne" class="external-link" target="_blank">Daphne</a> : le serveur ASGI
|
||||
conçu pour Django Channels.
|
||||
@@ -46,7 +46,7 @@ Vous pouvez installer un serveur compatible ASGI avec :
|
||||
|
||||
=== "Hypercorn"
|
||||
|
||||
* <a href="https://gitlab.com/pgjones/hypercorn" class="external-link" target="_blank">Hypercorn</a>, un serveur ASGI également compatible avec HTTP/2.
|
||||
* <a href="https://github.com/pgjones/hypercorn" class="external-link" target="_blank">Hypercorn</a>, un serveur ASGI également compatible avec HTTP/2.
|
||||
|
||||
<div class="termy">
|
||||
|
||||
|
||||
5
docs/fr/docs/learn/index.md
Normal file
@@ -0,0 +1,5 @@
|
||||
# Apprendre
|
||||
|
||||
Voici les sections introductives et les tutoriels pour apprendre **FastAPI**.
|
||||
|
||||
Vous pouvez considérer ceci comme un **manuel**, un **cours**, la **méthode officielle** et recommandée pour appréhender FastAPI. 😎
|
||||
@@ -138,7 +138,7 @@ $ pip install fastapi
|
||||
|
||||
</div>
|
||||
|
||||
תצטרכו גם שרת ASGI כגון <a href="https://www.uvicorn.org" class="external-link" target="_blank">Uvicorn</a> או <a href="https://gitlab.com/pgjones/hypercorn" class="external-link" target="_blank">Hypercorn</a>.
|
||||
תצטרכו גם שרת ASGI כגון <a href="https://www.uvicorn.org" class="external-link" target="_blank">Uvicorn</a> או <a href="https://github.com/pgjones/hypercorn" class="external-link" target="_blank">Hypercorn</a>.
|
||||
|
||||
<div dir="ltr" class="termy">
|
||||
|
||||
|
||||
@@ -129,7 +129,7 @@ $ pip install fastapi
|
||||
|
||||
</div>
|
||||
|
||||
Per il rilascio in produzione, sarà necessario un server ASGI come <a href="http://www.uvicorn.org" class="external-link" target="_blank">Uvicorn</a> oppure <a href="https://gitlab.com/pgjones/hypercorn" class="external-link" target="_blank">Hypercorn</a>.
|
||||
Per il rilascio in produzione, sarà necessario un server ASGI come <a href="http://www.uvicorn.org" class="external-link" target="_blank">Uvicorn</a> oppure <a href="https://github.com/pgjones/hypercorn" class="external-link" target="_blank">Hypercorn</a>.
|
||||
|
||||
<div class="termy">
|
||||
|
||||
|
||||
@@ -25,7 +25,7 @@
|
||||
|
||||
=== "Hypercorn"
|
||||
|
||||
* <a href="https://gitlab.com/pgjones/hypercorn" class="external-link" target="_blank">Hypercorn</a>, HTTP/2にも対応しているASGIサーバ。
|
||||
* <a href="https://github.com/pgjones/hypercorn" class="external-link" target="_blank">Hypercorn</a>, HTTP/2にも対応しているASGIサーバ。
|
||||
|
||||
<div class="termy">
|
||||
|
||||
|
||||
@@ -133,7 +133,7 @@ $ pip install fastapi
|
||||
|
||||
</div>
|
||||
|
||||
本番環境では、<a href="https://www.uvicorn.org" class="external-link" target="_blank">Uvicorn</a> または、 <a href="https://gitlab.com/pgjones/hypercorn" class="external-link" target="_blank">Hypercorn</a>のような、 ASGI サーバーが必要になります。
|
||||
本番環境では、<a href="https://www.uvicorn.org" class="external-link" target="_blank">Uvicorn</a> または、 <a href="https://github.com/pgjones/hypercorn" class="external-link" target="_blank">Hypercorn</a>のような、 ASGI サーバーが必要になります。
|
||||
|
||||
<div class="termy">
|
||||
|
||||
|
||||
@@ -133,7 +133,7 @@ $ pip install fastapi
|
||||
|
||||
</div>
|
||||
|
||||
프로덕션을 위해 <a href="http://www.uvicorn.org" class="external-link" target="_blank">Uvicorn</a> 또는 <a href="https://gitlab.com/pgjones/hypercorn" class="external-link" target="_blank">Hypercorn</a>과 같은 ASGI 서버도 필요할 겁니다.
|
||||
프로덕션을 위해 <a href="http://www.uvicorn.org" class="external-link" target="_blank">Uvicorn</a> 또는 <a href="https://github.com/pgjones/hypercorn" class="external-link" target="_blank">Hypercorn</a>과 같은 ASGI 서버도 필요할 겁니다.
|
||||
|
||||
<div class="termy">
|
||||
|
||||
|
||||
@@ -48,7 +48,7 @@ my_list: List[str]
|
||||
|
||||
## 집합 타입
|
||||
|
||||
그런데 생각해보니 태그는 반복되면 안 돼고, 고유한(Unique) 문자열이어야 할 것 같습니다.
|
||||
그런데 생각해보니 태그는 반복되면 안 되고, 고유한(Unique) 문자열이어야 할 것 같습니다.
|
||||
|
||||
그리고 파이썬은 집합을 위한 특별한 데이터 타입 `set`이 있습니다.
|
||||
|
||||
|
||||
130
docs/ko/docs/tutorial/extra-data-types.md
Normal file
@@ -0,0 +1,130 @@
|
||||
# 추가 데이터 자료형
|
||||
|
||||
지금까지 일반적인 데이터 자료형을 사용했습니다. 예를 들면 다음과 같습니다:
|
||||
|
||||
* `int`
|
||||
* `float`
|
||||
* `str`
|
||||
* `bool`
|
||||
|
||||
하지만 더 복잡한 데이터 자료형 또한 사용할 수 있습니다.
|
||||
|
||||
그리고 지금까지와 같은 기능들을 여전히 사용할 수 있습니다.
|
||||
|
||||
* 훌륭한 편집기 지원.
|
||||
* 들어오는 요청의 데이터 변환.
|
||||
* 응답 데이터의 데이터 변환.
|
||||
* 데이터 검증.
|
||||
* 자동 어노테이션과 문서화.
|
||||
|
||||
## 다른 데이터 자료형
|
||||
|
||||
아래의 추가적인 데이터 자료형을 사용할 수 있습니다:
|
||||
|
||||
* `UUID`:
|
||||
* 표준 "범용 고유 식별자"로, 많은 데이터베이스와 시스템에서 ID로 사용됩니다.
|
||||
* 요청과 응답에서 `str`로 표현됩니다.
|
||||
* `datetime.datetime`:
|
||||
* 파이썬의 `datetime.datetime`.
|
||||
* 요청과 응답에서 `2008-09-15T15:53:00+05:00`와 같은 ISO 8601 형식의 `str`로 표현됩니다.
|
||||
* `datetime.date`:
|
||||
* 파이썬의 `datetime.date`.
|
||||
* 요청과 응답에서 `2008-09-15`와 같은 ISO 8601 형식의 `str`로 표현됩니다.
|
||||
* `datetime.time`:
|
||||
* 파이썬의 `datetime.time`.
|
||||
* 요청과 응답에서 `14:23:55.003`와 같은 ISO 8601 형식의 `str`로 표현됩니다.
|
||||
* `datetime.timedelta`:
|
||||
* 파이썬의 `datetime.timedelta`.
|
||||
* 요청과 응답에서 전체 초(seconds)의 `float`로 표현됩니다.
|
||||
* Pydantic은 "ISO 8601 시차 인코딩"으로 표현하는 것 또한 허용합니다. <a href="https://docs.pydantic.dev/latest/concepts/serialization/#json_encoders" class="external-link" target="_blank">더 많은 정보는 이 문서에서 확인하십시오.</a>.
|
||||
* `frozenset`:
|
||||
* 요청과 응답에서 `set`와 동일하게 취급됩니다:
|
||||
* 요청 시, 리스트를 읽어 중복을 제거하고 `set`로 변환합니다.
|
||||
* 응답 시, `set`는 `list`로 변환됩니다.
|
||||
* 생성된 스키마는 (JSON 스키마의 `uniqueItems`를 이용해) `set`의 값이 고유함을 명시합니다.
|
||||
* `bytes`:
|
||||
* 표준 파이썬의 `bytes`.
|
||||
* 요청과 응답에서 `str`로 취급됩니다.
|
||||
* 생성된 스키마는 이것이 `binary` "형식"의 `str`임을 명시합니다.
|
||||
* `Decimal`:
|
||||
* 표준 파이썬의 `Decimal`.
|
||||
* 요청과 응답에서 `float`와 동일하게 다뤄집니다.
|
||||
* 여기에서 모든 유효한 pydantic 데이터 자료형을 확인할 수 있습니다: <a href="https://docs.pydantic.dev/latest/usage/types/types/" class="external-link" target="_blank">Pydantic 데이터 자료형</a>.
|
||||
|
||||
## 예시
|
||||
|
||||
위의 몇몇 자료형을 매개변수로 사용하는 *경로 작동* 예시입니다.
|
||||
|
||||
=== "Python 3.10+"
|
||||
|
||||
```Python hl_lines="1 3 12-16"
|
||||
{!> ../../../docs_src/extra_data_types/tutorial001_an_py310.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.9+"
|
||||
|
||||
```Python hl_lines="1 3 12-16"
|
||||
{!> ../../../docs_src/extra_data_types/tutorial001_an_py39.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.8+"
|
||||
|
||||
```Python hl_lines="1 3 13-17"
|
||||
{!> ../../../docs_src/extra_data_types/tutorial001_an.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.10+ non-Annotated"
|
||||
|
||||
!!! tip
|
||||
Prefer to use the `Annotated` version if possible.
|
||||
|
||||
```Python hl_lines="1 2 11-15"
|
||||
{!> ../../../docs_src/extra_data_types/tutorial001_py310.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.8+ non-Annotated"
|
||||
|
||||
!!! tip
|
||||
Prefer to use the `Annotated` version if possible.
|
||||
|
||||
```Python hl_lines="1 2 12-16"
|
||||
{!> ../../../docs_src/extra_data_types/tutorial001.py!}
|
||||
```
|
||||
|
||||
함수 안의 매개변수가 그들만의 데이터 자료형을 가지고 있으며, 예를 들어, 다음과 같이 날짜를 조작할 수 있음을 참고하십시오:
|
||||
|
||||
=== "Python 3.10+"
|
||||
|
||||
```Python hl_lines="18-19"
|
||||
{!> ../../../docs_src/extra_data_types/tutorial001_an_py310.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.9+"
|
||||
|
||||
```Python hl_lines="18-19"
|
||||
{!> ../../../docs_src/extra_data_types/tutorial001_an_py39.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.8+"
|
||||
|
||||
```Python hl_lines="19-20"
|
||||
{!> ../../../docs_src/extra_data_types/tutorial001_an.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.10+ non-Annotated"
|
||||
|
||||
!!! tip
|
||||
Prefer to use the `Annotated` version if possible.
|
||||
|
||||
```Python hl_lines="17-18"
|
||||
{!> ../../../docs_src/extra_data_types/tutorial001_py310.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.8+ non-Annotated"
|
||||
|
||||
!!! tip
|
||||
Prefer to use the `Annotated` version if possible.
|
||||
|
||||
```Python hl_lines="18-19"
|
||||
{!> ../../../docs_src/extra_data_types/tutorial001.py!}
|
||||
```
|
||||
@@ -43,16 +43,16 @@ HTTP는 세자리의 숫자 상태 코드를 응답의 일부로 전송합니다
|
||||
|
||||
요약하자면:
|
||||
|
||||
* `**1xx**` 상태 코드는 "정보"용입니다. 이들은 직접적으로는 잘 사용되지는 않습니다. 이 상태 코드를 갖는 응답들은 본문을 가질 수 없습니다.
|
||||
* `**2xx**` 상태 코드는 "성공적인" 응답을 위해 사용됩니다. 가장 많이 사용되는 유형입니다.
|
||||
* `1xx` 상태 코드는 "정보"용입니다. 이들은 직접적으로는 잘 사용되지는 않습니다. 이 상태 코드를 갖는 응답들은 본문을 가질 수 없습니다.
|
||||
* **`2xx`** 상태 코드는 "성공적인" 응답을 위해 사용됩니다. 가장 많이 사용되는 유형입니다.
|
||||
* `200` 은 디폴트 상태 코드로, 모든 것이 "성공적임"을 의미합니다.
|
||||
* 다른 예로는 `201` "생성됨"이 있습니다. 일반적으로 데이터베이스에 새로운 레코드를 생성한 후 사용합니다.
|
||||
* 단, `204` "내용 없음"은 특별한 경우입니다. 이것은 클라이언트에게 반환할 내용이 없는 경우 사용합니다. 따라서 응답은 본문을 가질 수 없습니다.
|
||||
* `**3xx**` 상태 코드는 "리다이렉션"용입니다. 본문을 가질 수 없는 `304` "수정되지 않음"을 제외하고, 이 상태 코드를 갖는 응답에는 본문이 있을 수도, 없을 수도 있습니다.
|
||||
* `**4xx**` 상태 코드는 "클라이언트 오류" 응답을 위해 사용됩니다. 이것은 아마 가장 많이 사용하게 될 두번째 유형입니다.
|
||||
* **`3xx`** 상태 코드는 "리다이렉션"용입니다. 본문을 가질 수 없는 `304` "수정되지 않음"을 제외하고, 이 상태 코드를 갖는 응답에는 본문이 있을 수도, 없을 수도 있습니다.
|
||||
* **`4xx`** 상태 코드는 "클라이언트 오류" 응답을 위해 사용됩니다. 이것은 아마 가장 많이 사용하게 될 두번째 유형입니다.
|
||||
* 일례로 `404` 는 "찾을 수 없음" 응답을 위해 사용합니다.
|
||||
* 일반적인 클라이언트 오류의 경우 `400` 을 사용할 수 있습니다.
|
||||
* `**5xx**` 상태 코드는 서버 오류에 사용됩니다. 이것들을 직접 사용할 일은 거의 없습니다. 응용 프로그램 코드나 서버의 일부에서 문제가 발생하면 자동으로 이들 상태 코드 중 하나를 반환합니다.
|
||||
* `5xx` 상태 코드는 서버 오류에 사용됩니다. 이것들을 직접 사용할 일은 거의 없습니다. 응용 프로그램 코드나 서버의 일부에서 문제가 발생하면 자동으로 이들 상태 코드 중 하나를 반환합니다.
|
||||
|
||||
!!! tip "팁"
|
||||
각각의 상태 코드와 이들이 의미하는 내용에 대해 더 알고싶다면 <a href="https://developer.mozilla.org/en-US/docs/Web/HTTP/Status" class="external-link" target="_blank"><abbr title="Mozilla Developer Network">MDN</abbr> HTTP 상태 코드에 관한 문서</a> 를 확인하십시오.
|
||||
@@ -82,7 +82,7 @@ HTTP는 세자리의 숫자 상태 코드를 응답의 일부로 전송합니다
|
||||
!!! note "기술적 세부사항"
|
||||
`from starlette import status` 역시 사용할 수 있습니다.
|
||||
|
||||
**FastAPI**는 개발자인 당신의 편의를 위해 `fastapi.status` 와 동일한 `starlette.status` 도 제공합니다. 하지만 이것은 Starlette로부터 직접 제공됩니다.
|
||||
**FastAPI**는 개발자인 여러분의 편의를 위해 `fastapi.status` 와 동일한 `starlette.status` 도 제공합니다. 하지만 이것은 Starlette로부터 직접 제공됩니다.
|
||||
|
||||
## 기본값 변경
|
||||
|
||||
|
||||
178
docs/pl/docs/fastapi-people.md
Normal file
@@ -0,0 +1,178 @@
|
||||
# Ludzie FastAPI
|
||||
|
||||
FastAPI posiada wspaniałą społeczność, która jest otwarta dla ludzi z każdego środowiska.
|
||||
|
||||
## Twórca - Opienik
|
||||
|
||||
Cześć! 👋
|
||||
|
||||
To ja:
|
||||
|
||||
{% if people %}
|
||||
<div class="user-list user-list-center">
|
||||
{% for user in people.maintainers %}
|
||||
|
||||
<div class="user"><a href="{{ user.url }}" target="_blank"><div class="avatar-wrapper"><img src="{{ user.avatarUrl }}"/></div><div class="title">@{{ user.login }}</div></a> <div class="count">Liczba odpowiedzi: {{ user.answers }}</div><div class="count">Pull Requesty: {{ user.prs }}</div></div>
|
||||
{% endfor %}
|
||||
|
||||
</div>
|
||||
{% endif %}
|
||||
|
||||
Jestem twórcą i opiekunem **FastAPI**. Możesz przeczytać więcej na ten temat w [Pomoc FastAPI - Uzyskaj pomoc - Skontaktuj się z autorem](help-fastapi.md#connect-with-the-author){.internal-link target=_blank}.
|
||||
|
||||
...Ale tutaj chcę pokazać Ci społeczność.
|
||||
|
||||
---
|
||||
|
||||
**FastAPI** otrzymuje wiele wsparcia od społeczności. Chciałbym podkreślić ich wkład.
|
||||
|
||||
To są ludzie, którzy:
|
||||
|
||||
* [Pomagają innym z pytaniami na GitHub](help-fastapi.md#help-others-with-questions-in-github){.internal-link target=_blank}.
|
||||
* [Tworzą Pull Requesty](help-fastapi.md#create-a-pull-request){.internal-link target=_blank}.
|
||||
* Oceniają Pull Requesty, [to szczególnie ważne dla tłumaczeń](contributing.md#translations){.internal-link target=_blank}.
|
||||
|
||||
Proszę o brawa dla nich. 👏 🙇
|
||||
|
||||
## Najaktywniejsi użytkownicy w zeszłym miesiącu
|
||||
|
||||
Oto niektórzy użytkownicy, którzy [pomagali innym w największej liczbie pytań na GitHubie](help-fastapi.md#help-others-with-questions-in-github){.internal-link target=_blank} podczas ostatniego miesiąca. ☕
|
||||
|
||||
{% if people %}
|
||||
<div class="user-list user-list-center">
|
||||
{% for user in people.last_month_active %}
|
||||
|
||||
<div class="user"><a href="{{ user.url }}" target="_blank"><div class="avatar-wrapper"><img src="{{ user.avatarUrl }}"/></div><div class="title">@{{ user.login }}</div></a> <div class="count">Udzielonych odpowiedzi: {{ user.count }}</div></div>
|
||||
{% endfor %}
|
||||
|
||||
</div>
|
||||
{% endif %}
|
||||
|
||||
## Eksperci
|
||||
|
||||
Oto **eksperci FastAPI**. 🤓
|
||||
|
||||
To użytkownicy, którzy [pomogli innym z największa liczbą pytań na GitHubie](help-fastapi.md#help-others-with-questions-in-github){.internal-link target=_blank} od *samego początku*.
|
||||
|
||||
Poprzez pomoc wielu innym, udowodnili, że są ekspertami. ✨
|
||||
|
||||
{% if people %}
|
||||
<div class="user-list user-list-center">
|
||||
{% for user in people.experts %}
|
||||
|
||||
<div class="user"><a href="{{ user.url }}" target="_blank"><div class="avatar-wrapper"><img src="{{ user.avatarUrl }}"/></div><div class="title">@{{ user.login }}</div></a> <div class="count">Udzielonych odpowiedzi: {{ user.count }}</div></div>
|
||||
{% endfor %}
|
||||
|
||||
</div>
|
||||
{% endif %}
|
||||
|
||||
## Najlepsi Kontrybutorzy
|
||||
|
||||
Oto **Najlepsi Kontrybutorzy**. 👷
|
||||
|
||||
Ci użytkownicy [stworzyli najwięcej Pull Requestów](help-fastapi.md#create-a-pull-request){.internal-link target=_blank}, które zostały *wcalone*.
|
||||
|
||||
Współtworzyli kod źródłowy, dokumentację, tłumaczenia itp. 📦
|
||||
|
||||
{% if people %}
|
||||
<div class="user-list user-list-center">
|
||||
{% for user in people.top_contributors %}
|
||||
|
||||
<div class="user"><a href="{{ user.url }}" target="_blank"><div class="avatar-wrapper"><img src="{{ user.avatarUrl }}"/></div><div class="title">@{{ user.login }}</div></a> <div class="count">Pull Requesty: {{ user.count }}</div></div>
|
||||
{% endfor %}
|
||||
|
||||
</div>
|
||||
{% endif %}
|
||||
|
||||
Jest wielu więcej kontrybutorów (ponad setka), możesz zobaczyć ich wszystkich na stronie <a href="https://github.com/tiangolo/fastapi/graphs/contributors" class="external-link" target="_blank">Kontrybutorzy FastAPI na GitHub</a>. 👷
|
||||
|
||||
## Najlepsi Oceniajacy
|
||||
|
||||
Ci uzytkownicy są **Najlepszymi oceniającymi**. 🕵️
|
||||
|
||||
### Oceny Tłumaczeń
|
||||
|
||||
Ja mówię tylko kilkoma językami (i to niezbyt dobrze 😅). Zatem oceniający są tymi, którzy mają [**moc zatwierdzania tłumaczeń**](contributing.md#translations){.internal-link target=_blank} dokumentacji. Bez nich nie byłoby dokumentacji w kilku innych językach.
|
||||
|
||||
---
|
||||
|
||||
**Najlepsi Oceniający** 🕵️ przejrzeli więcej Pull Requestów, niż inni, zapewniając jakość kodu, dokumentacji, a zwłaszcza **tłumaczeń**.
|
||||
|
||||
{% if people %}
|
||||
<div class="user-list user-list-center">
|
||||
{% for user in people.top_reviewers %}
|
||||
|
||||
<div class="user"><a href="{{ user.url }}" target="_blank"><div class="avatar-wrapper"><img src="{{ user.avatarUrl }}"/></div><div class="title">@{{ user.login }}</div></a> <div class="count">Liczba ocen: {{ user.count }}</div></div>
|
||||
{% endfor %}
|
||||
|
||||
</div>
|
||||
{% endif %}
|
||||
|
||||
## Sponsorzy
|
||||
|
||||
Oto **Sponsorzy**. 😎
|
||||
|
||||
Wspierają moją pracę nad **FastAPI** (i innymi), głównie poprzez <a href="https://github.com/sponsors/tiangolo" class="external-link" target="_blank">GitHub Sponsors</a>.
|
||||
|
||||
{% if sponsors %}
|
||||
|
||||
{% if sponsors.gold %}
|
||||
|
||||
### Złoci Sponsorzy
|
||||
|
||||
{% for sponsor in sponsors.gold -%}
|
||||
<a href="{{ sponsor.url }}" target="_blank" title="{{ sponsor.title }}"><img src="{{ sponsor.img }}" style="border-radius:15px"></a>
|
||||
{% endfor %}
|
||||
{% endif %}
|
||||
|
||||
{% if sponsors.silver %}
|
||||
|
||||
### Srebrni Sponsorzy
|
||||
|
||||
{% for sponsor in sponsors.silver -%}
|
||||
<a href="{{ sponsor.url }}" target="_blank" title="{{ sponsor.title }}"><img src="{{ sponsor.img }}" style="border-radius:15px"></a>
|
||||
{% endfor %}
|
||||
{% endif %}
|
||||
|
||||
{% if sponsors.bronze %}
|
||||
|
||||
### Brązowi Sponsorzy
|
||||
|
||||
{% for sponsor in sponsors.bronze -%}
|
||||
<a href="{{ sponsor.url }}" target="_blank" title="{{ sponsor.title }}"><img src="{{ sponsor.img }}" style="border-radius:15px"></a>
|
||||
{% endfor %}
|
||||
{% endif %}
|
||||
|
||||
{% endif %}
|
||||
|
||||
### Indywidualni Sponsorzy
|
||||
|
||||
{% if github_sponsors %}
|
||||
{% for group in github_sponsors.sponsors %}
|
||||
|
||||
<div class="user-list user-list-center">
|
||||
|
||||
{% for user in group %}
|
||||
{% if user.login not in sponsors_badge.logins %}
|
||||
|
||||
<div class="user"><a href="{{ user.url }}" target="_blank"><div class="avatar-wrapper"><img src="{{ user.avatarUrl }}"/></div><div class="title">@{{ user.login }}</div></a></div>
|
||||
|
||||
{% endif %}
|
||||
{% endfor %}
|
||||
|
||||
</div>
|
||||
|
||||
{% endfor %}
|
||||
{% endif %}
|
||||
|
||||
## Techniczne szczegóły danych
|
||||
|
||||
Głównym celem tej strony jest podkreślenie wysiłku społeczności w pomaganiu innym.
|
||||
|
||||
Szczególnie włączając wysiłki, które są zwykle mniej widoczne, a w wielu przypadkach bardziej żmudne, tak jak pomaganie innym z pytaniami i ocenianie Pull Requestów z tłumaczeniami.
|
||||
|
||||
Dane są obliczane każdego miesiąca, możesz przeczytać <a href="https://github.com/tiangolo/fastapi/blob/master/.github/actions/people/app/main.py" class="external-link" target="_blank">kod źródłowy tutaj</a>.
|
||||
|
||||
Tutaj również podkreślam wkład od sponsorów.
|
||||
|
||||
Zastrzegam sobie prawo do aktualizacji algorytmu, sekcji, progów itp. (na wszelki wypadek 🤷).
|
||||
@@ -132,7 +132,7 @@ $ pip install fastapi
|
||||
|
||||
</div>
|
||||
|
||||
Na serwerze produkcyjnym będziesz także potrzebował serwera ASGI, np. <a href="https://www.uvicorn.org" class="external-link" target="_blank">Uvicorn</a> lub <a href="https://gitlab.com/pgjones/hypercorn" class="external-link" target="_blank">Hypercorn</a>.
|
||||
Na serwerze produkcyjnym będziesz także potrzebował serwera ASGI, np. <a href="https://www.uvicorn.org" class="external-link" target="_blank">Uvicorn</a> lub <a href="https://github.com/pgjones/hypercorn" class="external-link" target="_blank">Hypercorn</a>.
|
||||
|
||||
<div class="termy">
|
||||
|
||||
|
||||
240
docs/pt/docs/advanced/additional-responses.md
Normal file
@@ -0,0 +1,240 @@
|
||||
# Retornos Adicionais no OpenAPI
|
||||
|
||||
!!! warning "Aviso"
|
||||
Este é um tema bem avançado.
|
||||
|
||||
Se você está começando com o **FastAPI**, provavelmente você não precisa disso.
|
||||
|
||||
Você pode declarar retornos adicionais, com códigos de status adicionais, media types, descrições, etc.
|
||||
|
||||
Essas respostas adicionais serão incluídas no esquema do OpenAPI, e também aparecerão na documentação da API.
|
||||
|
||||
Porém para as respostas adicionais, você deve garantir que está retornando um `Response` como por exemplo o `JSONResponse` diretamente, junto com o código de status e o conteúdo.
|
||||
|
||||
## Retorno Adicional com `model`
|
||||
|
||||
Você pode fornecer o parâmetro `responses` aos seus *decoradores de caminho*.
|
||||
|
||||
Este parâmetro recebe um `dict`, as chaves são os códigos de status para cada retorno, como por exemplo `200`, e os valores são um outro `dict` com a informação de cada um deles.
|
||||
|
||||
Cada um desses `dict` de retorno pode ter uma chave `model`, contendo um modelo do Pydantic, assim como o `response_model`.
|
||||
|
||||
O **FastAPI** pegará este modelo, gerará o esquema JSON dele e incluirá no local correto do OpenAPI.
|
||||
|
||||
Por exemplo, para declarar um outro retorno com o status code `404` e um modelo do Pydantic chamado `Message`, você pode escrever:
|
||||
|
||||
```Python hl_lines="18 22"
|
||||
{!../../../docs_src/additional_responses/tutorial001.py!}
|
||||
```
|
||||
|
||||
!!! note "Nota"
|
||||
Lembre-se que você deve retornar o `JSONResponse` diretamente.
|
||||
|
||||
!!! info "Informação"
|
||||
A chave `model` não é parte do OpenAPI.
|
||||
|
||||
O **FastAPI** pegará o modelo do Pydantic, gerará o `JSON Schema`, e adicionará no local correto.
|
||||
|
||||
O local correto é:
|
||||
|
||||
* Na chave `content`, que tem como valor um outro objeto JSON (`dict`) que contém:
|
||||
* Uma chave com o media type, como por exemplo `application/json`, que contém como valor um outro objeto JSON, contendo::
|
||||
* Uma chave `schema`, que contém como valor o JSON Schema do modelo, sendo este o local correto.
|
||||
* O **FastAPI** adiciona aqui a referência dos esquemas JSON globais que estão localizados em outro lugar, ao invés de incluí-lo diretamente. Deste modo, outras aplicações e clientes podem utilizar estes esquemas JSON diretamente, fornecer melhores ferramentas de geração de código, etc.
|
||||
|
||||
O retorno gerado no OpenAI para esta *operação de caminho* será:
|
||||
|
||||
```JSON hl_lines="3-12"
|
||||
{
|
||||
"responses": {
|
||||
"404": {
|
||||
"description": "Additional Response",
|
||||
"content": {
|
||||
"application/json": {
|
||||
"schema": {
|
||||
"$ref": "#/components/schemas/Message"
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"200": {
|
||||
"description": "Successful Response",
|
||||
"content": {
|
||||
"application/json": {
|
||||
"schema": {
|
||||
"$ref": "#/components/schemas/Item"
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"422": {
|
||||
"description": "Validation Error",
|
||||
"content": {
|
||||
"application/json": {
|
||||
"schema": {
|
||||
"$ref": "#/components/schemas/HTTPValidationError"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
Os esquemas são referenciados em outro local dentro do esquema OpenAPI:
|
||||
|
||||
```JSON hl_lines="4-16"
|
||||
{
|
||||
"components": {
|
||||
"schemas": {
|
||||
"Message": {
|
||||
"title": "Message",
|
||||
"required": [
|
||||
"message"
|
||||
],
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"message": {
|
||||
"title": "Message",
|
||||
"type": "string"
|
||||
}
|
||||
}
|
||||
},
|
||||
"Item": {
|
||||
"title": "Item",
|
||||
"required": [
|
||||
"id",
|
||||
"value"
|
||||
],
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"id": {
|
||||
"title": "Id",
|
||||
"type": "string"
|
||||
},
|
||||
"value": {
|
||||
"title": "Value",
|
||||
"type": "string"
|
||||
}
|
||||
}
|
||||
},
|
||||
"ValidationError": {
|
||||
"title": "ValidationError",
|
||||
"required": [
|
||||
"loc",
|
||||
"msg",
|
||||
"type"
|
||||
],
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"loc": {
|
||||
"title": "Location",
|
||||
"type": "array",
|
||||
"items": {
|
||||
"type": "string"
|
||||
}
|
||||
},
|
||||
"msg": {
|
||||
"title": "Message",
|
||||
"type": "string"
|
||||
},
|
||||
"type": {
|
||||
"title": "Error Type",
|
||||
"type": "string"
|
||||
}
|
||||
}
|
||||
},
|
||||
"HTTPValidationError": {
|
||||
"title": "HTTPValidationError",
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"detail": {
|
||||
"title": "Detail",
|
||||
"type": "array",
|
||||
"items": {
|
||||
"$ref": "#/components/schemas/ValidationError"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## Media types adicionais para o retorno principal
|
||||
|
||||
Você pode utilizar o mesmo parâmetro `responses` para adicionar diferentes media types para o mesmo retorno principal.
|
||||
|
||||
Por exemplo, você pode adicionar um media type adicional de `image/png`, declarando que a sua *operação de caminho* pode retornar um objeto JSON (com o media type `application/json`) ou uma imagem PNG:
|
||||
|
||||
```Python hl_lines="19-24 28"
|
||||
{!../../../docs_src/additional_responses/tutorial002.py!}
|
||||
```
|
||||
|
||||
!!! note "Nota"
|
||||
Note que você deve retornar a imagem utilizando um `FileResponse` diretamente.
|
||||
|
||||
!!! info "Informação"
|
||||
A menos que você especifique um media type diferente explicitamente em seu parâmetro `responses`, o FastAPI assumirá que o retorno possui o mesmo media type contido na classe principal de retorno (padrão `application/json`).
|
||||
|
||||
Porém se você especificou uma classe de retorno com o valor `None` como media type, o FastAPI utilizará `application/json` para qualquer retorno adicional que possui um modelo associado.
|
||||
|
||||
## Combinando informações
|
||||
|
||||
Você também pode combinar informações de diferentes lugares, incluindo os parâmetros `response_model`, `status_code`, e `responses`.
|
||||
|
||||
Você pode declarar um `response_model`, utilizando o código de status padrão `200` (ou um customizado caso você precise), e depois adicionar informações adicionais para esse mesmo retorno em `responses`, diretamente no esquema OpenAPI.
|
||||
|
||||
O **FastAPI** manterá as informações adicionais do `responses`, e combinará com o esquema JSON do seu modelo.
|
||||
|
||||
Por exemplo, você pode declarar um retorno com o código de status `404` que utiliza um modelo do Pydantic que possui um `description` customizado.
|
||||
|
||||
E um retorno com o código de status `200` que utiliza o seu `response_model`, porém inclui um `example` customizado:
|
||||
|
||||
```Python hl_lines="20-31"
|
||||
{!../../../docs_src/additional_responses/tutorial003.py!}
|
||||
```
|
||||
|
||||
Isso será combinado e incluído em seu OpenAPI, e disponibilizado na documentação da sua API:
|
||||
|
||||
<img src="/img/tutorial/additional-responses/image01.png">
|
||||
|
||||
## Combinar retornos predefinidos e personalizados
|
||||
|
||||
Você pode querer possuir alguns retornos predefinidos que são aplicados para diversas *operações de caminho*, porém você deseja combinar com retornos personalizados que são necessários para cada *operação de caminho*.
|
||||
|
||||
Para estes casos, você pode utilizar a técnica do Python de "desempacotamento" de um `dict` utilizando `**dict_to_unpack`:
|
||||
|
||||
```Python
|
||||
old_dict = {
|
||||
"old key": "old value",
|
||||
"second old key": "second old value",
|
||||
}
|
||||
new_dict = {**old_dict, "new key": "new value"}
|
||||
```
|
||||
|
||||
Aqui, o `new_dict` terá todos os pares de chave-valor do `old_dict` mais o novo par de chave-valor:
|
||||
|
||||
```Python
|
||||
{
|
||||
"old key": "old value",
|
||||
"second old key": "second old value",
|
||||
"new key": "new value",
|
||||
}
|
||||
```
|
||||
|
||||
Você pode utilizar essa técnica para reutilizar alguns retornos predefinidos nas suas *operações de caminho* e combiná-las com personalizações adicionais.
|
||||
|
||||
Por exemplo:
|
||||
|
||||
```Python hl_lines="13-17 26"
|
||||
{!../../../docs_src/additional_responses/tutorial004.py!}
|
||||
```
|
||||
|
||||
## Mais informações sobre retornos OpenAPI
|
||||
|
||||
Para verificar exatamente o que você pode incluir nos retornos, você pode conferir estas seções na especificação do OpenAPI:
|
||||
|
||||
* <a href="https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.1.0.md#responsesObject" class="external-link" target="_blank">Objeto de Retorno OpenAPI</a>, inclui o `Response Object`.
|
||||
* <a href="https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.1.0.md#responseObject" class="external-link" target="_blank">Objeto de Retorno OpenAPI</a>, você pode incluir qualquer coisa dele diretamente em cada retorno dentro do seu parâmetro `responses`. Incluindo `description`, `headers`, `content` (dentro dele que você declara diferentes media types e esquemas JSON), e `links`.
|
||||
69
docs/pt/docs/advanced/additional-status-codes.md
Normal file
@@ -0,0 +1,69 @@
|
||||
# Códigos de status adicionais
|
||||
|
||||
Por padrão, o **FastAPI** retornará as respostas utilizando o `JSONResponse`, adicionando o conteúdo do retorno da sua *operação de caminho* dentro do `JSONResponse`.
|
||||
|
||||
Ele usará o código de status padrão ou o que você definir na sua *operação de caminho*.
|
||||
|
||||
## Códigos de status adicionais
|
||||
|
||||
Caso você queira retornar códigos de status adicionais além do código principal, você pode fazer isso retornando um `Response` diretamente, como por exemplo um `JSONResponse`, e definir os códigos de status adicionais diretamente.
|
||||
|
||||
Por exemplo, vamos dizer que você deseja ter uma *operação de caminho* que permita atualizar itens, e retornar um código de status HTTP 200 "OK" quando for bem sucedido.
|
||||
|
||||
Mas você também deseja aceitar novos itens. E quando os itens não existiam, ele os cria, e retorna o código de status HTTP 201 "Created.
|
||||
|
||||
Para conseguir isso, importe `JSONResponse` e retorne o seu conteúdo diretamente, definindo o `status_code` que você deseja:
|
||||
|
||||
=== "Python 3.10+"
|
||||
|
||||
```Python hl_lines="4 25"
|
||||
{!> ../../../docs_src/additional_status_codes/tutorial001_an_py310.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.9+"
|
||||
|
||||
```Python hl_lines="4 25"
|
||||
{!> ../../../docs_src/additional_status_codes/tutorial001_an_py39.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.8+"
|
||||
|
||||
```Python hl_lines="4 26"
|
||||
{!> ../../../docs_src/additional_status_codes/tutorial001_an.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.10+ non-Annotated"
|
||||
|
||||
!!! tip "Dica"
|
||||
Faça uso da versão `Annotated` quando possível.
|
||||
|
||||
```Python hl_lines="2 23"
|
||||
{!> ../../../docs_src/additional_status_codes/tutorial001_py310.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.8+ non-Annotated"
|
||||
|
||||
!!! tip "Dica"
|
||||
Faça uso da versão `Annotated` quando possível.
|
||||
|
||||
```Python hl_lines="4 25"
|
||||
{!> ../../../docs_src/additional_status_codes/tutorial001.py!}
|
||||
```
|
||||
|
||||
!!! warning "Aviso"
|
||||
Quando você retorna um `Response` diretamente, como no exemplo acima, ele será retornado diretamente.
|
||||
|
||||
Ele não será serializado com um modelo, etc.
|
||||
|
||||
Garanta que ele tenha toda informação que você deseja, e que os valores sejam um JSON válido (caso você esteja usando `JSONResponse`).
|
||||
|
||||
!!! note "Detalhes técnicos"
|
||||
Você também pode utilizar `from starlette.responses import JSONResponse`.
|
||||
|
||||
O **FastAPI** disponibiliza o `starlette.responses` como `fastapi.responses` apenas por conveniência para você, o programador. Porém a maioria dos retornos disponíveis vem diretamente do Starlette. O mesmo com `status`.
|
||||
|
||||
## OpenAPI e documentação da API
|
||||
|
||||
Se você retorna códigos de status adicionais e retornos diretamente, eles não serão incluídos no esquema do OpenAPI (a documentação da API), porque o FastAPI não tem como saber de antemão o que será retornado.
|
||||
|
||||
Mas você pode documentar isso no seu código, utilizando: [Retornos Adicionais](additional-responses.md){.internal-link target=_blank}.
|
||||
138
docs/pt/docs/advanced/advanced-dependencies.md
Normal file
@@ -0,0 +1,138 @@
|
||||
# Dependências avançadas
|
||||
|
||||
## Dependências parametrizadas
|
||||
|
||||
Todas as dependências que vimos até agora são funções ou classes fixas.
|
||||
|
||||
Mas podem ocorrer casos onde você deseja ser capaz de definir parâmetros na dependência, sem ter a necessidade de declarar diversas funções ou classes.
|
||||
|
||||
Vamos imaginar que queremos ter uma dependência que verifica se o parâmetro de consulta `q` possui um valor fixo.
|
||||
|
||||
Porém nós queremos poder parametrizar o conteúdo fixo.
|
||||
|
||||
## Uma instância "chamável"
|
||||
|
||||
Em Python existe uma maneira de fazer com que uma instância de uma classe seja um "chamável".
|
||||
|
||||
Não propriamente a classe (que já é um chamável), mas a instância desta classe.
|
||||
|
||||
Para fazer isso, nós declaramos o método `__call__`:
|
||||
|
||||
=== "Python 3.9+"
|
||||
|
||||
```Python hl_lines="12"
|
||||
{!> ../../../docs_src/dependencies/tutorial011_an_py39.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.8+"
|
||||
|
||||
```Python hl_lines="11"
|
||||
{!> ../../../docs_src/dependencies/tutorial011_an.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.8+ non-Annotated"
|
||||
|
||||
!!! tip "Dica"
|
||||
Prefira utilizar a versão `Annotated` se possível.
|
||||
|
||||
```Python hl_lines="10"
|
||||
{!> ../../../docs_src/dependencies/tutorial011.py!}
|
||||
```
|
||||
|
||||
Neste caso, o `__call__` é o que o **FastAPI** utilizará para verificar parâmetros adicionais e sub dependências, e isso é o que será chamado para passar o valor ao parâmetro na sua *função de operação de rota* posteriormente.
|
||||
|
||||
## Parametrizar a instância
|
||||
|
||||
E agora, nós podemos utilizar o `__init__` para declarar os parâmetros da instância que podemos utilizar para "parametrizar" a dependência:
|
||||
|
||||
=== "Python 3.9+"
|
||||
|
||||
```Python hl_lines="9"
|
||||
{!> ../../../docs_src/dependencies/tutorial011_an_py39.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.8+"
|
||||
|
||||
```Python hl_lines="8"
|
||||
{!> ../../../docs_src/dependencies/tutorial011_an.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.8+ non-Annotated"
|
||||
|
||||
!!! tip "Dica"
|
||||
Prefira utilizar a versão `Annotated` se possível.
|
||||
|
||||
```Python hl_lines="7"
|
||||
{!> ../../../docs_src/dependencies/tutorial011.py!}
|
||||
```
|
||||
|
||||
Neste caso, o **FastAPI** nunca tocará ou se importará com o `__init__`, nós vamos utilizar diretamente em nosso código.
|
||||
|
||||
## Crie uma instância
|
||||
|
||||
Nós poderíamos criar uma instância desta classe com:
|
||||
|
||||
=== "Python 3.9+"
|
||||
|
||||
```Python hl_lines="18"
|
||||
{!> ../../../docs_src/dependencies/tutorial011_an_py39.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.8+"
|
||||
|
||||
```Python hl_lines="17"
|
||||
{!> ../../../docs_src/dependencies/tutorial011_an.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.8+ non-Annotated"
|
||||
|
||||
!!! tip "Dica"
|
||||
Prefira utilizar a versão `Annotated` se possível.
|
||||
|
||||
```Python hl_lines="16"
|
||||
{!> ../../../docs_src/dependencies/tutorial011.py!}
|
||||
```
|
||||
|
||||
E deste modo nós podemos "parametrizar" a nossa dependência, que agora possui `"bar"` dentro dele, como o atributo `checker.fixed_content`.
|
||||
|
||||
## Utilize a instância como dependência
|
||||
|
||||
Então, nós podemos utilizar este `checker` em um `Depends(checker)`, no lugar de `Depends(FixedContentQueryChecker)`, porque a dependência é a instância, `checker`, e não a própria classe.
|
||||
|
||||
E quando a dependência for resolvida, o **FastAPI** chamará este `checker` como:
|
||||
|
||||
```Python
|
||||
checker(q="somequery")
|
||||
```
|
||||
|
||||
...e passar o que quer que isso retorne como valor da dependência em nossa *função de operação de rota* como o parâmetro `fixed_content_included`:
|
||||
|
||||
=== "Python 3.9+"
|
||||
|
||||
```Python hl_lines="22"
|
||||
{!> ../../../docs_src/dependencies/tutorial011_an_py39.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.8+"
|
||||
|
||||
```Python hl_lines="21"
|
||||
{!> ../../../docs_src/dependencies/tutorial011_an.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.8+ non-Annotated"
|
||||
|
||||
!!! tip "Dica"
|
||||
Prefira utilizar a versão `Annotated` se possível.
|
||||
|
||||
```Python hl_lines="20"
|
||||
{!> ../../../docs_src/dependencies/tutorial011.py!}
|
||||
```
|
||||
|
||||
!!! tip "Dica"
|
||||
Tudo isso parece não ser natural. E pode não estar muito claro ou aparentar ser útil ainda.
|
||||
|
||||
Estes exemplos são intencionalmente simples, porém mostram como tudo funciona.
|
||||
|
||||
Nos capítulos sobre segurança, existem funções utilitárias que são implementadas desta maneira.
|
||||
|
||||
Se você entendeu tudo isso, você já sabe como essas funções utilitárias para segurança funcionam por debaixo dos panos.
|
||||
95
docs/pt/docs/advanced/async-tests.md
Normal file
@@ -0,0 +1,95 @@
|
||||
# Testes Assíncronos
|
||||
|
||||
Você já viu como testar as suas aplicações **FastAPI** utilizando o `TestClient` que é fornecido. Até agora, você viu apenas como escrever testes síncronos, sem utilizar funções `async`.
|
||||
|
||||
Ser capaz de utilizar funções assíncronas em seus testes pode ser útil, por exemplo, quando você está realizando uma consulta em seu banco de dados de maneira assíncrona. Imagine que você deseja testar realizando requisições para a sua aplicação FastAPI e depois verificar que a sua aplicação inseriu corretamente as informações no banco de dados, ao utilizar uma biblioteca assíncrona para banco de dados.
|
||||
|
||||
Vamos ver como nós podemos fazer isso funcionar.
|
||||
|
||||
## pytest.mark.anyio
|
||||
|
||||
Se quisermos chamar funções assíncronas em nossos testes, as nossas funções de teste precisam ser assíncronas. O AnyIO oferece um plugin bem legal para isso, que nos permite especificar que algumas das nossas funções de teste precisam ser chamadas de forma assíncrona.
|
||||
|
||||
## HTTPX
|
||||
|
||||
Mesmo que a sua aplicação **FastAPI** utilize funções normais com `def` no lugar de `async def`, ela ainda é uma aplicação `async` por baixo dos panos.
|
||||
|
||||
O `TestClient` faz algumas mágicas para invocar a aplicação FastAPI assíncrona em suas funções `def` normais, utilizando o pytest padrão. Porém a mágica não acontece mais quando nós estamos utilizando dentro de funções assíncronas. Ao executar os nossos testes de forma assíncrona, nós não podemos mais utilizar o `TestClient` dentro das nossas funções de teste.
|
||||
|
||||
O `TestClient` é baseado no <a href="https://www.python-httpx.org" class="external-link" target="_blank">HTTPX</a>, e felizmente nós podemos utilizá-lo diretamente para testar a API.
|
||||
|
||||
## Exemplo
|
||||
|
||||
Para um exemplos simples, vamos considerar uma estrutura de arquivos semelhante ao descrito em [Bigger Applications](../tutorial/bigger-applications.md){.internal-link target=_blank} e [Testing](../tutorial/testing.md){.internal-link target=_blank}:
|
||||
|
||||
```
|
||||
.
|
||||
├── app
|
||||
│ ├── __init__.py
|
||||
│ ├── main.py
|
||||
│ └── test_main.py
|
||||
```
|
||||
|
||||
O arquivo `main.py` teria:
|
||||
|
||||
```Python
|
||||
{!../../../docs_src/async_tests/main.py!}
|
||||
```
|
||||
|
||||
O arquivo `test_main.py` teria os testes para para o arquivo `main.py`, ele poderia ficar assim:
|
||||
|
||||
```Python
|
||||
{!../../../docs_src/async_tests/test_main.py!}
|
||||
```
|
||||
|
||||
## Executá-lo
|
||||
|
||||
Você pode executar os seus testes normalmente via:
|
||||
|
||||
<div class="termy">
|
||||
|
||||
```console
|
||||
$ pytest
|
||||
|
||||
---> 100%
|
||||
```
|
||||
|
||||
</div>
|
||||
|
||||
## Em Detalhes
|
||||
|
||||
O marcador `@pytest.mark.anyio` informa ao pytest que esta função de teste deve ser invocada de maneira assíncrona:
|
||||
|
||||
```Python hl_lines="7"
|
||||
{!../../../docs_src/async_tests/test_main.py!}
|
||||
```
|
||||
|
||||
!!! tip "Dica"
|
||||
Note que a função de teste é `async def` agora, no lugar de apenas `def` como quando estávamos utilizando o `TestClient` anteriormente.
|
||||
|
||||
Então podemos criar um `AsyncClient` com a aplicação, e enviar requisições assíncronas para ela utilizando `await`.
|
||||
|
||||
```Python hl_lines="9-10"
|
||||
{!../../../docs_src/async_tests/test_main.py!}
|
||||
```
|
||||
|
||||
Isso é equivalente a:
|
||||
|
||||
```Python
|
||||
response = client.get('/')
|
||||
```
|
||||
|
||||
...que nós utilizamos para fazer as nossas requisições utilizando o `TestClient`.
|
||||
|
||||
!!! tip "Dica"
|
||||
Note que nós estamos utilizando async/await com o novo `AsyncClient` - a requisição é assíncrona.
|
||||
|
||||
!!! warning "Aviso"
|
||||
Se a sua aplicação depende dos eventos de vida útil (*lifespan*), o `AsyncClient` não acionará estes eventos. Para garantir que eles são acionados, utilize o `LifespanManager` do <a href="https://github.com/florimondmanca/asgi-lifespan#usage" class="external-link" target="_blank">florimondmanca/asgi-lifespan</a>.
|
||||
|
||||
## Outras Chamadas de Funções Assíncronas
|
||||
|
||||
Como a função de teste agora é assíncrona, você pode chamar (e `esperar`) outras funções `async` além de enviar requisições para a sua aplicação FastAPI em seus testes, exatamente como você as chamaria em qualquer outro lugar do seu código.
|
||||
|
||||
!!! tip "Dica"
|
||||
Se você se deparar com um `RuntimeError: Task attached to a different loop` ao integrar funções assíncronas em seus testes (e.g. ao utilizar o <a href="https://stackoverflow.com/questions/41584243/runtimeerror-task-attached-to-a-different-loop" class="external-link" target="_blank">MotorClient do MongoDB</a>) Lembre-se de instanciar objetos que precisam de um loop de eventos (*event loop*) apenas em funções assíncronas, e.g. um *"callback"* `'@app.on_event("startup")`.
|
||||
34
docs/pt/docs/advanced/benchmarks.md
Normal file
@@ -0,0 +1,34 @@
|
||||
# Benchmarks
|
||||
|
||||
Benchmarks independentes da TechEmpower mostram que aplicações **FastAPI** rodando com o Uvicorn como <a href="https://www.techempower.com/benchmarks/#section=test&runid=7464e520-0dc2-473d-bd34-dbdfd7e85911&hw=ph&test=query&l=zijzen-7" class="external-link" target="_blank">um dos frameworks Python mais rápidos disponíveis</a>, ficando atrás apenas do Starlette e Uvicorn (utilizado internamente pelo FastAPI).
|
||||
|
||||
Porém, ao verificar benchmarks e comparações você deve prestar atenção ao seguinte:
|
||||
|
||||
## Benchmarks e velocidade
|
||||
|
||||
Quando você verifica os benchmarks, é comum ver diversas ferramentas de diferentes tipos comparados como se fossem equivalentes.
|
||||
|
||||
Especificamente, para ver o Uvicorn, Starlette e FastAPI comparados entre si (entre diversas outras ferramentas).
|
||||
|
||||
Quanto mais simples o problema resolvido pela ferramenta, melhor será a performance. E a maioria das análises não testa funcionalidades adicionais que são oferecidas pela ferramenta.
|
||||
|
||||
A hierarquia é:
|
||||
|
||||
* **Uvicorn**: um servidor ASGI
|
||||
* **Starlette**: (utiliza Uvicorn) um microframework web
|
||||
* **FastAPI**: (utiliza Starlette) um microframework para APIs com diversas funcionalidades adicionais para a construção de APIs, com validação de dados, etc.
|
||||
|
||||
* **Uvicorn**:
|
||||
* Terá a melhor performance, pois não possui muito código além do próprio servidor.
|
||||
* Você não escreveria uma aplicação utilizando o Uvicorn diretamente. Isso significaria que o seu código teria que incluir pelo menos todo o código fornecido pelo Starlette (ou o **FastAPI**). E caso você fizesse isso, a sua aplicação final teria a mesma sobrecarga que teria se utilizasse um framework, minimizando o código e os bugs.
|
||||
* Se você está comparando o Uvicorn, compare com os servidores de aplicação Daphne, Hypercorn, uWSGI, etc.
|
||||
* **Starlette**:
|
||||
* Terá o melhor desempenho, depois do Uvicorn. Na verdade, o Starlette utiliza o Uvicorn para rodar. Portanto, ele pode ficar mais "devagar" que o Uvicorn apenas por ter que executar mais código.
|
||||
* Mas ele fornece as ferramentas para construir aplicações web simples, com roteamento baseado em caminhos, etc.
|
||||
* Se você está comparando o Starlette, compare-o com o Sanic, Flask, Django, etc. Frameworks web (ou microframeworks).
|
||||
* **FastAPI**:
|
||||
* Da mesma forma que o Starlette utiliza o Uvicorn e não consegue ser mais rápido que ele, o **FastAPI** utiliza o Starlette, portanto, ele não consegue ser mais rápido que ele.
|
||||
* O FastAPI provê mais funcionalidades em cima do Starlette. Funcionalidades que você quase sempre precisará quando estiver construindo APIs, como validação de dados e serialização. E ao utilizá-lo, você obtém documentação automática sem custo nenhum (a documentação automática sequer adiciona sobrecarga nas aplicações rodando, pois ela é gerada na inicialização).
|
||||
* Caso você não utilize o FastAPI e faz uso do Starlette diretamente (ou outra ferramenta, como o Sanic, Flask, Responder, etc) você mesmo teria que implementar toda a validação de dados e serialização. Então, a sua aplicação final ainda teria a mesma sobrecarga caso estivesse usando o FastAPI. E em muitos casos, validação de dados e serialização é a maior parte do código escrito em aplicações.
|
||||
* Então, ao utilizar o FastAPI, você está economizando tempo de programação, evitando bugs, linhas de código, e provavelmente terá a mesma performance (ou até melhor) do que teria caso você não o utilizasse (já que você teria que implementar tudo no seu código).
|
||||
* Se você está comparando o FastAPI, compare-o com frameworks de aplicações web (ou conjunto de ferramentas) que oferecem validação de dados, serialização e documentação, como por exemplo o Flask-apispec, NestJS, Molten, etc. Frameworks que possuem validação integrada de dados, serialização e documentação.
|
||||
51
docs/pt/docs/advanced/openapi-webhooks.md
Normal file
@@ -0,0 +1,51 @@
|
||||
# Webhooks OpenAPI
|
||||
|
||||
Existem situações onde você deseja informar os **usuários** da sua API que a sua aplicação pode chamar a aplicação *deles* (enviando uma requisição) com alguns dados, normalmente para **notificar** algum tipo de **evento**.
|
||||
|
||||
Isso significa que no lugar do processo normal de seus usuários enviarem requisições para a sua API, é a **sua API** (ou sua aplicação) que poderia **enviar requisições para o sistema deles** (para a API deles, a aplicação deles).
|
||||
|
||||
Isso normalmente é chamado de **webhook**.
|
||||
|
||||
## Etapas dos Webhooks
|
||||
|
||||
Normalmente, o processo é que **você define** em seu código qual é a mensagem que você irá mandar, o **corpo da sua requisição**.
|
||||
|
||||
Você também define de alguma maneira em quais **momentos** a sua aplicação mandará essas requisições ou eventos.
|
||||
|
||||
E os **seus usuários** definem de alguma forma (em algum painel por exemplo) a **URL** que a sua aplicação deve enviar essas requisições.
|
||||
|
||||
Toda a **lógica** sobre como cadastrar as URLs para os webhooks e o código para enviar de fato as requisições cabe a você definir. Você escreve da maneira que você desejar no **seu próprio código**.
|
||||
|
||||
## Documentando webhooks com o FastAPI e OpenAPI
|
||||
|
||||
Com o **FastAPI**, utilizando o OpenAPI, você pode definir os nomes destes webhooks, os tipos das operações HTTP que a sua aplicação pode enviar (e.g. `POST`, `PUT`, etc.) e os **corpos** da requisição que a sua aplicação enviaria.
|
||||
|
||||
Isto pode facilitar bastante para os seus usuários **implementarem as APIs deles** para receber as requisições dos seus **webhooks**, eles podem inclusive ser capazes de gerar parte do código da API deles.
|
||||
|
||||
!!! info "Informação"
|
||||
Webhooks estão disponíveis a partir do OpenAPI 3.1.0, e possui suporte do FastAPI a partir da versão `0.99.0`.
|
||||
|
||||
## Uma aplicação com webhooks
|
||||
|
||||
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()`.
|
||||
|
||||
```Python hl_lines="9-13 36-53"
|
||||
{!../../../docs_src/openapi_webhooks/tutorial001.py!}
|
||||
```
|
||||
|
||||
Os webhooks que você define aparecerão no esquema do **OpenAPI** e na **página de documentação** gerada automaticamente.
|
||||
|
||||
!!! info "Informação"
|
||||
O objeto `app.webhooks` é na verdade apenas um `APIRouter`, o mesmo tipo que você utilizaria ao estruturar a sua aplicação com diversos arquivos.
|
||||
|
||||
Note que utilizando webhooks você não está de fato declarando uma **rota** (como `/items/`), o texto que informa é apenas um **identificador** do webhook (o nome do evento), por exemplo em `@app.webhooks.post("new-subscription")`, o nome do webhook é `new-subscription`.
|
||||
|
||||
Isto porque espera-se que os **seus usuários** definam o verdadeiro **caminho da URL** onde eles desejam receber a requisição do webhook de algum outra maneira. (e.g. um painel).
|
||||
|
||||
### Confira a documentação
|
||||
|
||||
Agora você pode iniciar a sua aplicação e ir até <a href="http://127.0.0.1:8000/docs" class="external-link" target="_blank">http://127.0.0.1:8000/docs</a>.
|
||||
|
||||
Você verá que a sua documentação possui as *operações de rota* normais e agora também possui alguns **webhooks**:
|
||||
|
||||
<img src="/img/tutorial/openapi-webhooks/image01.png">
|
||||
485
docs/pt/docs/advanced/settings.md
Normal file
@@ -0,0 +1,485 @@
|
||||
# Configurações e Variáveis de Ambiente
|
||||
|
||||
Em muitos casos a sua aplicação pode precisar de configurações externas, como chaves secretas, credenciais de banco de dados, credenciais para serviços de email, etc.
|
||||
|
||||
A maioria dessas configurações é variável (podem mudar), como URLs de bancos de dados. E muitas delas podem conter dados sensíveis, como tokens secretos.
|
||||
|
||||
Por isso é comum prover essas configurações como variáveis de ambiente que são utilizidas pela aplicação.
|
||||
|
||||
## Variáveis de Ambiente
|
||||
|
||||
!!! dica
|
||||
Se você já sabe o que são variáveis de ambiente e como utilizá-las, sinta-se livre para avançar para o próximo tópico.
|
||||
|
||||
Uma <a href="https://pt.wikipedia.org/wiki/Variável_de_ambiente" class="external-link" target="_blank">variável de ambiente</a> (abreviada em inglês para "env var") é uma variável definida fora do código Python, no sistema operacional, e pode ser lida pelo seu código Python (ou por outros programas).
|
||||
|
||||
Você pode criar e utilizar variáveis de ambiente no terminal, sem precisar utilizar Python:
|
||||
|
||||
=== "Linux, macOS, Windows Bash"
|
||||
|
||||
<div class="termy">
|
||||
|
||||
```console
|
||||
// Você pode criar uma env var MY_NAME usando
|
||||
$ export MY_NAME="Wade Wilson"
|
||||
|
||||
// E utilizá-la em outros programas, como
|
||||
$ echo "Hello $MY_NAME"
|
||||
|
||||
Hello Wade Wilson
|
||||
```
|
||||
|
||||
</div>
|
||||
|
||||
=== "Windows PowerShell"
|
||||
|
||||
<div class="termy">
|
||||
|
||||
```console
|
||||
// Criando env var MY_NAME
|
||||
$ $Env:MY_NAME = "Wade Wilson"
|
||||
|
||||
// Usando em outros programas, como
|
||||
$ echo "Hello $Env:MY_NAME"
|
||||
|
||||
Hello Wade Wilson
|
||||
```
|
||||
|
||||
</div>
|
||||
|
||||
### Lendo variáveis de ambiente com Python
|
||||
|
||||
Você também pode criar variáveis de ambiente fora do Python, no terminal (ou com qualquer outro método), e realizar a leitura delas no Python.
|
||||
|
||||
Por exemplo, você pode definir um arquivo `main.py` com o seguinte código:
|
||||
|
||||
```Python hl_lines="3"
|
||||
import os
|
||||
|
||||
name = os.getenv("MY_NAME", "World")
|
||||
print(f"Hello {name} from Python")
|
||||
```
|
||||
|
||||
!!! dica
|
||||
O segundo parâmetro em <a href="https://docs.python.org/3.8/library/os.html#os.getenv" class="external-link" target="_blank">`os.getenv()`</a> é o valor padrão para o retorno.
|
||||
|
||||
Se nenhum valor for informado, `None` é utilizado por padrão, aqui definimos `"World"` como o valor padrão a ser utilizado.
|
||||
|
||||
E depois você pode executar esse arquivo:
|
||||
|
||||
<div class="termy">
|
||||
|
||||
```console
|
||||
// Aqui ainda não definimos a env var
|
||||
$ python main.py
|
||||
|
||||
// Por isso obtemos o valor padrão
|
||||
|
||||
Hello World from Python
|
||||
|
||||
// Mas se definirmos uma variável de ambiente primeiro
|
||||
$ export MY_NAME="Wade Wilson"
|
||||
|
||||
// E executarmos o programa novamente
|
||||
$ python main.py
|
||||
|
||||
// Agora ele pode ler a variável de ambiente
|
||||
|
||||
Hello Wade Wilson from Python
|
||||
```
|
||||
|
||||
</div>
|
||||
|
||||
Como variáveis de ambiente podem ser definidas fora do código da aplicação, mas acessadas pela aplicação, e não precisam ser armazenadas (versionadas com `git`) junto dos outros arquivos, é comum utilizá-las para guardar configurações.
|
||||
|
||||
Você também pode criar uma variável de ambiente específica para uma invocação de um programa, que é acessível somente para esse programa, e somente enquanto ele estiver executando.
|
||||
|
||||
Para fazer isso, crie a variável imediatamente antes de iniciar o programa, na mesma linha:
|
||||
|
||||
<div class="termy">
|
||||
|
||||
```console
|
||||
// Criando uma env var MY_NAME na mesma linha da execução do programa
|
||||
$ MY_NAME="Wade Wilson" python main.py
|
||||
|
||||
// Agora a aplicação consegue ler a variável de ambiente
|
||||
|
||||
Hello Wade Wilson from Python
|
||||
|
||||
// E a variável deixa de existir após isso
|
||||
$ python main.py
|
||||
|
||||
Hello World from Python
|
||||
```
|
||||
|
||||
</div>
|
||||
|
||||
!!! dica
|
||||
Você pode ler mais sobre isso em: <a href="https://12factor.net/pt_br/config" class="external-link" target="_blank">The Twelve-Factor App: Configurações</a>.
|
||||
|
||||
### Tipagem e Validação
|
||||
|
||||
Essas variáveis de ambiente suportam apenas strings, por serem externas ao Python e por que precisam ser compatíveis com outros programas e o resto do sistema (e até mesmo com outros sistemas operacionais, como Linux, Windows e macOS).
|
||||
|
||||
Isso significa que qualquer valor obtido de uma variável de ambiente em Python terá o tipo `str`, e qualquer conversão para um tipo diferente ou validação deve ser realizada no código.
|
||||
|
||||
## Pydantic `Settings`
|
||||
|
||||
Por sorte, o Pydantic possui uma funcionalidade para lidar com essas configurações vindas de variáveis de ambiente utilizando <a href="https://docs.pydantic.dev/latest/usage/pydantic_settings/" class="external-link" target="_blank">Pydantic: Settings management</a>.
|
||||
|
||||
### Instalando `pydantic-settings`
|
||||
|
||||
Primeiro, instale o pacote `pydantic-settings`:
|
||||
|
||||
<div class="termy">
|
||||
|
||||
```console
|
||||
$ pip install pydantic-settings
|
||||
---> 100%
|
||||
```
|
||||
|
||||
</div>
|
||||
|
||||
Ele também está incluído no fastapi quando você instala com a opção `all`:
|
||||
|
||||
<div class="termy">
|
||||
|
||||
```console
|
||||
$ pip install "fastapi[all]"
|
||||
---> 100%
|
||||
```
|
||||
|
||||
</div>
|
||||
|
||||
!!! info
|
||||
Na v1 do Pydantic ele estava incluído no pacote principal. Agora ele está distribuido como um pacote independente para que você possa optar por instalar ou não caso você não precise dessa funcionalidade.
|
||||
|
||||
### Criando o objeto `Settings`
|
||||
|
||||
Importe a classe `BaseSettings` do Pydantic e crie uma nova subclasse, de forma parecida com um modelo do Pydantic.
|
||||
|
||||
Os atributos da classe são declarados com anotações de tipo, e possíveis valores padrão, da mesma maneira que os modelos do Pydantic.
|
||||
|
||||
Você pode utilizar todas as ferramentas e funcionalidades de validação que são utilizadas nos modelos do Pydantic, como tipos de dados diferentes e validações adicionei com `Field()`.
|
||||
|
||||
=== "Pydantic v2"
|
||||
|
||||
```Python hl_lines="2 5-8 11"
|
||||
{!> ../../../docs_src/settings/tutorial001.py!}
|
||||
```
|
||||
|
||||
=== "Pydantic v1"
|
||||
|
||||
!!! Info
|
||||
Na versão 1 do Pydantic você importaria `BaseSettings` diretamente do módulo `pydantic` em vez do módulo `pydantic_settings`.
|
||||
|
||||
```Python hl_lines="2 5-8 11"
|
||||
{!> ../../../docs_src/settings/tutorial001_pv1.py!}
|
||||
```
|
||||
|
||||
!!! dica
|
||||
Se você quiser algo pronto para copiar e colar na sua aplicação, não use esse exemplo, mas sim o exemplo abaixo.
|
||||
|
||||
Portanto, quando você cria uma instância da classe `Settings` (nesse caso, o objeto `settings`), o Pydantic lê as variáveis de ambiente sem diferenciar maiúsculas e minúsculas, por isso, uma variável maiúscula `APP_NAME` será usada para o atributo `app_name`.
|
||||
|
||||
Depois ele irá converter e validar os dados. Assim, quando você utilizar aquele objeto `settings`, os dados terão o tipo que você declarou (e.g. `items_per_user` será do tipo `int`).
|
||||
|
||||
### Usando o objeto `settings`
|
||||
|
||||
Depois, Você pode utilizar o novo objeto `settings` na sua aplicação:
|
||||
|
||||
```Python hl_lines="18-20"
|
||||
{!../../../docs_src/settings/tutorial001.py!}
|
||||
```
|
||||
|
||||
### Executando o servidor
|
||||
|
||||
No próximo passo, você pode inicializar o servidor passando as configurações em forma de variáveis de ambiente, por exemplo, você poderia definir `ADMIN_EMAIL` e `APP_NAME` da seguinte forma:
|
||||
|
||||
<div class="termy">
|
||||
|
||||
```console
|
||||
$ ADMIN_EMAIL="deadpool@example.com" APP_NAME="ChimichangApp" fastapi run main.py
|
||||
|
||||
<span style="color: green;">INFO</span>: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit)
|
||||
```
|
||||
|
||||
</div>
|
||||
|
||||
!!! dica
|
||||
Para definir múltiplas variáveis de ambiente para um único comando basta separá-las utilizando espaços, e incluir todas elas antes do comando.
|
||||
|
||||
Assim, o atributo `admin_email` seria definido como `"deadpool@example.com"`.
|
||||
|
||||
`app_name` seria `"ChimichangApp"`.
|
||||
|
||||
E `items_per_user` manteria o valor padrão de `50`.
|
||||
|
||||
## Configurações em um módulo separado
|
||||
|
||||
Você também pode incluir essas configurações em um arquivo de um módulo separado como visto em [Bigger Applications - Multiple Files](../tutorial/bigger-applications.md){.internal-link target=\_blank}.
|
||||
|
||||
Por exemplo, você pode adicionar um arquivo `config.py` com:
|
||||
|
||||
```Python
|
||||
{!../../../docs_src/settings/app01/config.py!}
|
||||
```
|
||||
|
||||
E utilizar essa configuração em `main.py`:
|
||||
|
||||
```Python hl_lines="3 11-13"
|
||||
{!../../../docs_src/settings/app01/main.py!}
|
||||
```
|
||||
|
||||
!!! dica
|
||||
Você também precisa incluir um arquivo `__init__.py` como visto em [Bigger Applications - Multiple Files](../tutorial/bigger-applications.md){.internal-link target=\_blank}.
|
||||
|
||||
## Configurações em uma dependência
|
||||
|
||||
Em certas ocasiões, pode ser útil fornecer essas configurações a partir de uma dependência, em vez de definir um objeto global `settings` que é utilizado em toda a aplicação.
|
||||
|
||||
Isso é especialmente útil durante os testes, já que é bastante simples sobrescrever uma dependência com suas configurações personalizadas.
|
||||
|
||||
### O arquivo de configuração
|
||||
|
||||
Baseando-se no exemplo anterior, seu arquivo `config.py` seria parecido com isso:
|
||||
|
||||
```Python hl_lines="10"
|
||||
{!../../../docs_src/settings/app02/config.py!}
|
||||
```
|
||||
|
||||
Perceba que dessa vez não criamos uma instância padrão `settings = Settings()`.
|
||||
|
||||
### O arquivo principal da aplicação
|
||||
|
||||
Agora criamos a dependência que retorna um novo objeto `config.Settings()`.
|
||||
|
||||
=== "Python 3.9+"
|
||||
|
||||
```Python hl_lines="6 12-13"
|
||||
{!> ../../../docs_src/settings/app02_an_py39/main.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.8+"
|
||||
|
||||
```Python hl_lines="6 12-13"
|
||||
{!> ../../../docs_src/settings/app02_an/main.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.8+ non-Annotated"
|
||||
|
||||
!!! dica
|
||||
Utilize a versão com `Annotated` se possível.
|
||||
|
||||
```Python hl_lines="5 11-12"
|
||||
{!> ../../../docs_src/settings/app02/main.py!}
|
||||
```
|
||||
|
||||
!!! dica
|
||||
Vamos discutir sobre `@lru_cache` logo mais.
|
||||
|
||||
Por enquanto, você pode considerar `get_settings()` como uma função normal.
|
||||
|
||||
E então podemos declarar essas configurações como uma dependência na função de operação da rota e utilizar onde for necessário.
|
||||
|
||||
=== "Python 3.9+"
|
||||
|
||||
```Python hl_lines="17 19-21"
|
||||
{!> ../../../docs_src/settings/app02_an_py39/main.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.8+"
|
||||
|
||||
```Python hl_lines="17 19-21"
|
||||
{!> ../../../docs_src/settings/app02_an/main.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.8+ non-Annotated"
|
||||
|
||||
!!! dica
|
||||
Utilize a versão com `Annotated` se possível.
|
||||
|
||||
```Python hl_lines="16 18-20"
|
||||
{!> ../../../docs_src/settings/app02/main.py!}
|
||||
```
|
||||
|
||||
### Configurações e testes
|
||||
|
||||
Então seria muito fácil fornecer uma configuração diferente durante a execução dos testes sobrescrevendo a dependência de `get_settings`:
|
||||
|
||||
```Python hl_lines="9-10 13 21"
|
||||
{!../../../docs_src/settings/app02/test_main.py!}
|
||||
```
|
||||
|
||||
Na sobrescrita da dependência, definimos um novo valor para `admin_email` quando instanciamos um novo objeto `Settings`, e então retornamos esse novo objeto.
|
||||
|
||||
Após isso, podemos testar se o valor está sendo utilizado.
|
||||
|
||||
## Lendo um arquivo `.env`
|
||||
|
||||
Se você tiver muitas configurações que variem bastante, talvez em ambientes distintos, pode ser útil colocá-las em um arquivo e depois lê-las como se fossem variáveis de ambiente.
|
||||
|
||||
Essa prática é tão comum que possui um nome, essas variáveis de ambiente normalmente são colocadas em um arquivo `.env`, e esse arquivo é chamado de "dotenv".
|
||||
|
||||
!!! dica
|
||||
Um arquivo iniciando com um ponto final (`.`) é um arquivo oculto em sistemas baseados em Unix, como Linux e MacOS.
|
||||
|
||||
Mas um arquivo dotenv não precisa ter esse nome exato.
|
||||
|
||||
Pydantic suporta a leitura desses tipos de arquivos utilizando uma biblioteca externa. Você pode ler mais em <a href="https://docs.pydantic.dev/latest/concepts/pydantic_settings/#dotenv-env-support" class="external-link" target="_blank">Pydantic Settings: Dotenv (.env) support</a>.
|
||||
|
||||
!!! dica
|
||||
Para que isso funcione você precisa executar `pip install python-dotenv`.
|
||||
|
||||
### O arquivo `.env`
|
||||
|
||||
Você pode definir um arquivo `.env` com o seguinte conteúdo:
|
||||
|
||||
```bash
|
||||
ADMIN_EMAIL="deadpool@example.com"
|
||||
APP_NAME="ChimichangApp"
|
||||
```
|
||||
|
||||
### Obtendo configurações do `.env`
|
||||
|
||||
E então adicionar o seguinte código em `config.py`:
|
||||
|
||||
=== "Pydantic v2"
|
||||
|
||||
```Python hl_lines="9"
|
||||
{!> ../../../docs_src/settings/app03_an/config.py!}
|
||||
```
|
||||
|
||||
!!! dica
|
||||
O atributo `model_config` é usado apenas para configuração do Pydantic. Você pode ler mais em <a href="https://docs.pydantic.dev/latest/usage/model_config/" class="external-link" target="_blank">Pydantic Model Config</a>.
|
||||
|
||||
=== "Pydantic v1"
|
||||
|
||||
```Python hl_lines="9-10"
|
||||
{!> ../../../docs_src/settings/app03_an/config_pv1.py!}
|
||||
```
|
||||
|
||||
!!! dica
|
||||
A classe `Config` é usada apenas para configuração do Pydantic. Você pode ler mais em <a href="https://docs.pydantic.dev/1.10/usage/model_config/" class="external-link" target="_blank">Pydantic Model Config</a>.
|
||||
|
||||
!!! info
|
||||
Na versão 1 do Pydantic a configuração é realizada por uma classe interna `Config`, na versão 2 do Pydantic isso é feito com o atributo `model_config`. Esse atributo recebe um `dict`, para utilizar o autocomplete e checagem de erros do seu editor de texto você pode importar e utilizar `SettingsConfigDict` para definir esse `dict`.
|
||||
|
||||
Aqui definimos a configuração `env_file` dentro da classe `Settings` do Pydantic, e definimos o valor como o nome do arquivo dotenv que queremos utilizar.
|
||||
|
||||
### Declarando `Settings` apenas uma vez com `lru_cache`
|
||||
|
||||
Ler o conteúdo de um arquivo em disco normalmente é uma operação custosa (lenta), então você provavelmente quer fazer isso apenas um vez e reutilizar o mesmo objeto settings depois, em vez de ler os valores a cada requisição.
|
||||
|
||||
Mas cada vez que fazemos:
|
||||
|
||||
```Python
|
||||
Settings()
|
||||
```
|
||||
|
||||
um novo objeto `Settings` é instanciado, e durante a instanciação, o arquivo `.env` é lido novamente.
|
||||
|
||||
Se a função da dependência fosse apenas:
|
||||
|
||||
```Python
|
||||
def get_settings():
|
||||
return Settings()
|
||||
```
|
||||
|
||||
Iriamos criar um novo objeto a cada requisição, e estaríamos lendo o arquivo `.env` a cada requisição. ⚠️
|
||||
|
||||
Mas como estamos utilizando o decorador `@lru_cache` acima, o objeto `Settings` é criado apenas uma vez, na primeira vez que a função é chamada. ✔️
|
||||
|
||||
=== "Python 3.9+"
|
||||
|
||||
```Python hl_lines="1 11"
|
||||
{!> ../../../docs_src/settings/app03_an_py39/main.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.8+"
|
||||
|
||||
```Python hl_lines="1 11"
|
||||
{!> ../../../docs_src/settings/app03_an/main.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.8+ non-Annotated"
|
||||
|
||||
!!! dica
|
||||
Utilize a versão com `Annotated` se possível.
|
||||
|
||||
```Python hl_lines="1 10"
|
||||
{!> ../../../docs_src/settings/app03/main.py!}
|
||||
```
|
||||
|
||||
Dessa forma, todas as chamadas da função `get_settings()` nas dependências das próximas requisições, em vez de executar o código interno de `get_settings()` e instanciar um novo objeto `Settings`, irão retornar o mesmo objeto que foi retornado na primeira chamada, de novo e de novo.
|
||||
|
||||
#### Detalhes Técnicos de `lru_cache`
|
||||
|
||||
`@lru_cache` modifica a função decorada para retornar o mesmo valor que foi retornado na primeira vez, em vez de calculá-lo novamente, executando o código da função toda vez.
|
||||
|
||||
Assim, a função abaixo do decorador é executada uma única vez para cada combinação dos argumentos passados. E os valores retornados para cada combinação de argumentos são sempre reutilizados para cada nova chamada da função com a mesma combinação de argumentos.
|
||||
|
||||
Por exemplo, se você definir uma função:
|
||||
|
||||
```Python
|
||||
@lru_cache
|
||||
def say_hi(name: str, salutation: str = "Ms."):
|
||||
return f"Hello {salutation} {name}"
|
||||
```
|
||||
|
||||
Seu programa poderia executar dessa forma:
|
||||
|
||||
```mermaid
|
||||
sequenceDiagram
|
||||
|
||||
participant code as Código
|
||||
participant function as say_hi()
|
||||
participant execute as Executar Função
|
||||
|
||||
rect rgba(0, 255, 0, .1)
|
||||
code ->> function: say_hi(name="Camila")
|
||||
function ->> execute: executar código da função
|
||||
execute ->> code: retornar o resultado
|
||||
end
|
||||
|
||||
rect rgba(0, 255, 255, .1)
|
||||
code ->> function: say_hi(name="Camila")
|
||||
function ->> code: retornar resultado armazenado
|
||||
end
|
||||
|
||||
rect rgba(0, 255, 0, .1)
|
||||
code ->> function: say_hi(name="Rick")
|
||||
function ->> execute: executar código da função
|
||||
execute ->> code: retornar o resultado
|
||||
end
|
||||
|
||||
rect rgba(0, 255, 0, .1)
|
||||
code ->> function: say_hi(name="Rick", salutation="Mr.")
|
||||
function ->> execute: executar código da função
|
||||
execute ->> code: retornar o resultado
|
||||
end
|
||||
|
||||
rect rgba(0, 255, 255, .1)
|
||||
code ->> function: say_hi(name="Rick")
|
||||
function ->> code: retornar resultado armazenado
|
||||
end
|
||||
|
||||
rect rgba(0, 255, 255, .1)
|
||||
code ->> function: say_hi(name="Camila")
|
||||
function ->> code: retornar resultado armazenado
|
||||
end
|
||||
```
|
||||
|
||||
No caso da nossa dependência `get_settings()`, a função não recebe nenhum argumento, então ela sempre retorna o mesmo valor.
|
||||
|
||||
Dessa forma, ela se comporta praticamente como uma variável global, mas ao ser utilizada como uma função de uma dependência, pode facilmente ser sobrescrita durante os testes.
|
||||
|
||||
`@lru_cache` é definido no módulo `functools` que faz parte da biblioteca padrão do Python, você pode ler mais sobre esse decorador no link <a href="https://docs.python.org/3/library/functools.html#functools.lru_cache" class="external-link" target="_blank">Python Docs sobre `@lru_cache`</a>.
|
||||
|
||||
## Recapitulando
|
||||
|
||||
Você pode usar o módulo Pydantic Settings para gerenciar as configurações de sua aplicação, utilizando todo o poder dos modelos Pydantic.
|
||||
|
||||
- Utilizar dependências simplifica os testes.
|
||||
- Você pode utilizar arquivos .env junto das configurações do Pydantic.
|
||||
- Utilizar o decorador `@lru_cache` evita que o arquivo .env seja lido de novo e de novo para cada requisição, enquanto permite que você sobrescreva durante os testes.
|
||||
@@ -345,7 +345,7 @@ Você apenas precisa instalar um servidor ASGI compatível como:
|
||||
|
||||
=== "Hypercorn"
|
||||
|
||||
* <a href="https://gitlab.com/pgjones/hypercorn" class="external-link" target="_blank">Hypercorn</a>, um servidor ASGI também compatível com HTTP/2.
|
||||
* <a href="https://github.com/pgjones/hypercorn" class="external-link" target="_blank">Hypercorn</a>, um servidor ASGI também compatível com HTTP/2.
|
||||
|
||||
<div class="termy">
|
||||
|
||||
|
||||
84
docs/pt/docs/fastapi-cli.md
Normal file
@@ -0,0 +1,84 @@
|
||||
# FastAPI CLI
|
||||
|
||||
**FastAPI CLI** é uma interface por linha de comando do `fastapi` que você pode usar para rodar sua app FastAPI, gerenciar seu projeto FastAPI e mais.
|
||||
|
||||
Quando você instala o FastAPI (ex.: com `pip install fastapi`), isso inclui um pacote chamado `fastapi-cli`. Esse pacote disponibiliza o comando `fastapi` no terminal.
|
||||
|
||||
Para rodar seu app FastAPI em desenvolvimento, você pode usar o comando `fastapi dev`:
|
||||
|
||||
<div class="termy">
|
||||
|
||||
```console
|
||||
$ <font color="#4E9A06">fastapi</font> dev <u style="text-decoration-style:single">main.py</u>
|
||||
<font color="#3465A4">INFO </font> Using path <font color="#3465A4">main.py</font>
|
||||
<font color="#3465A4">INFO </font> Resolved absolute path <font color="#75507B">/home/user/code/awesomeapp/</font><font color="#AD7FA8">main.py</font>
|
||||
<font color="#3465A4">INFO </font> Searching for package file structure from directories with <font color="#3465A4">__init__.py</font> files
|
||||
<font color="#3465A4">INFO </font> Importing from <font color="#75507B">/home/user/code/</font><font color="#AD7FA8">awesomeapp</font>
|
||||
|
||||
╭─ <font color="#8AE234"><b>Python module file</b></font> ─╮
|
||||
│ │
|
||||
│ 🐍 main.py │
|
||||
│ │
|
||||
╰──────────────────────╯
|
||||
|
||||
<font color="#3465A4">INFO </font> Importing module <font color="#4E9A06">main</font>
|
||||
<font color="#3465A4">INFO </font> Found importable FastAPI app
|
||||
|
||||
╭─ <font color="#8AE234"><b>Importable FastAPI app</b></font> ─╮
|
||||
│ │
|
||||
│ <span style="background-color:#272822"><font color="#FF4689">from</font></span><span style="background-color:#272822"><font color="#F8F8F2"> main </font></span><span style="background-color:#272822"><font color="#FF4689">import</font></span><span style="background-color:#272822"><font color="#F8F8F2"> app</font></span><span style="background-color:#272822"> </span> │
|
||||
│ │
|
||||
╰──────────────────────────╯
|
||||
|
||||
<font color="#3465A4">INFO </font> Using import string <font color="#8AE234"><b>main:app</b></font>
|
||||
|
||||
<span style="background-color:#C4A000"><font color="#2E3436">╭────────── FastAPI CLI - Development mode ───────────╮</font></span>
|
||||
<span style="background-color:#C4A000"><font color="#2E3436">│ │</font></span>
|
||||
<span style="background-color:#C4A000"><font color="#2E3436">│ Serving at: http://127.0.0.1:8000 │</font></span>
|
||||
<span style="background-color:#C4A000"><font color="#2E3436">│ │</font></span>
|
||||
<span style="background-color:#C4A000"><font color="#2E3436">│ API docs: http://127.0.0.1:8000/docs │</font></span>
|
||||
<span style="background-color:#C4A000"><font color="#2E3436">│ │</font></span>
|
||||
<span style="background-color:#C4A000"><font color="#2E3436">│ Running in development mode, for production use: │</font></span>
|
||||
<span style="background-color:#C4A000"><font color="#2E3436">│ │</font></span>
|
||||
<span style="background-color:#C4A000"><font color="#2E3436">│ </font></span><span style="background-color:#C4A000"><font color="#555753"><b>fastapi run</b></font></span><span style="background-color:#C4A000"><font color="#2E3436"> │</font></span>
|
||||
<span style="background-color:#C4A000"><font color="#2E3436">│ │</font></span>
|
||||
<span style="background-color:#C4A000"><font color="#2E3436">╰─────────────────────────────────────────────────────╯</font></span>
|
||||
|
||||
<font color="#4E9A06">INFO</font>: Will watch for changes in these directories: ['/home/user/code/awesomeapp']
|
||||
<font color="#4E9A06">INFO</font>: Uvicorn running on <b>http://127.0.0.1:8000</b> (Press CTRL+C to quit)
|
||||
<font color="#4E9A06">INFO</font>: Started reloader process [<font color="#34E2E2"><b>2265862</b></font>] using <font color="#34E2E2"><b>WatchFiles</b></font>
|
||||
<font color="#4E9A06">INFO</font>: Started server process [<font color="#06989A">2265873</font>]
|
||||
<font color="#4E9A06">INFO</font>: Waiting for application startup.
|
||||
<font color="#4E9A06">INFO</font>: Application startup complete.
|
||||
```
|
||||
|
||||
</div>
|
||||
|
||||
Aquele commando por linha de programa chamado `fastapi` é o **FastAPI CLI**.
|
||||
|
||||
O FastAPI CLI recebe o caminho do seu programa Python, detecta automaticamente a variável com o FastAPI (comumente nomeada `app`) e como importá-la, e então a serve.
|
||||
|
||||
Para produção você usaria `fastapi run` no lugar. 🚀
|
||||
|
||||
Internamente, **FastAPI CLI** usa <a href="https://www.uvicorn.org" class="external-link" target="_blank">Uvicorn</a>, um servidor ASGI de alta performance e pronto para produção. 😎
|
||||
|
||||
## `fastapi dev`
|
||||
|
||||
Quando você roda `fastapi dev`, isso vai executar em modo de desenvolvimento.
|
||||
|
||||
Por padrão, teremos o **recarregamento automático** ativo, então o programa irá recarregar o servidor automaticamente toda vez que você fizer mudanças no seu código. Isso usa muitos recursos e pode ser menos estável. Você deve apenas usá-lo em modo de desenvolvimento.
|
||||
|
||||
O servidor de desenvolvimento escutará no endereço de IP `127.0.0.1` por padrão, este é o IP que sua máquina usa para se comunicar com ela mesma (`localhost`).
|
||||
|
||||
## `fastapi run`
|
||||
|
||||
Quando você rodar `fastapi run`, isso executará em modo de produção por padrão.
|
||||
|
||||
Este modo terá **recarregamento automático desativado** por padrão.
|
||||
|
||||
Isso irá escutar no endereço de IP `0.0.0.0`, o que significa todos os endereços IP disponíveis, dessa forma o programa estará acessível publicamente para qualquer um que consiga se comunicar com a máquina. Isso é como você normalmente roda em produção em um contêiner, por exemplo.
|
||||
|
||||
Em muitos casos você pode ter (e deveria ter) um "proxy de saída" tratando HTTPS no topo, isso dependerá de como você fará o deploy da sua aplicação, seu provedor pode fazer isso pra você ou talvez seja necessário fazer você mesmo.
|
||||
|
||||
!!! tip
|
||||
Você pode aprender mais sobre em [documentação de deployment](deployment/index.md){.internal-link target=_blank}.
|
||||
39
docs/pt/docs/how-to/general.md
Normal file
@@ -0,0 +1,39 @@
|
||||
# Geral - Como Fazer - Receitas
|
||||
|
||||
Aqui estão vários links para outros locais na documentação, para perguntas gerais ou frequentes
|
||||
|
||||
## Filtro de dados- Segurança
|
||||
|
||||
Para assegurar que você não vai retornar mais dados do que deveria, leia a seção [Tutorial - Response Model - Return Type](../tutorial/response-model.md){.internal-link target=_blank}.
|
||||
|
||||
## Tags de Documentação - OpenAPI
|
||||
Para adicionar tags às suas *rotas* e agrupá-las na UI da documentação, leia a seção [Tutorial - Path Operation Configurations - Tags](../tutorial/path-operation-configuration.md#tags){.internal-link target=_blank}.
|
||||
|
||||
## Resumo e Descrição da documentação - OpenAPI
|
||||
|
||||
Para adicionar um resumo e uma descrição às suas *rotas* e exibi-los na UI da documentação, leia a seção [Tutorial - Path Operation Configurations - Summary and Description](../tutorial/path-operation-configuration.md#summary-and-description){.internal-link target=_blank}.
|
||||
|
||||
## Documentação das Descrições de Resposta - OpenAPI
|
||||
|
||||
Para definir a descrição de uma resposta exibida na interface da documentação, leia a seção [Tutorial - Path Operation Configurations - Response description](../tutorial/path-operation-configuration.md#response-description){.internal-link target=_blank}.
|
||||
|
||||
## Documentação para Depreciar uma *Operação de Rota* - OpenAPI
|
||||
|
||||
Para depreciar uma *operação de rota* e exibi-la na interface da documentação, leia a seção [Tutorial - Path Operation Configurations - Deprecation](../tutorial/path-operation-configuration.md#deprecate-a-path-operation){.internal-link target=_blank}.
|
||||
|
||||
## Converter qualquer dado para JSON
|
||||
|
||||
|
||||
Para converter qualquer dado para um formato compatível com JSON, leia a seção [Tutorial - JSON Compatible Encoder](../tutorial/encoder.md){.internal-link target=_blank}.
|
||||
|
||||
## OpenAPI Metadata - Docs
|
||||
|
||||
Para adicionar metadados ao seu esquema OpenAPI, incluindo licensa, versão, contato, etc, leia a seção [Tutorial - Metadata and Docs URLs](../tutorial/metadata.md){.internal-link target=_blank}.
|
||||
|
||||
## OpenAPI com URL customizada
|
||||
|
||||
Para customizar a URL do OpenAPI (ou removê-la), leia a seção [Tutorial - Metadata and Docs URLs](../tutorial/metadata.md#openapi-url){.internal-link target=_blank}.
|
||||
|
||||
## URLs de documentação do OpenAPI
|
||||
|
||||
Para alterar as URLs usadas para as interfaces de usuário da documentação gerada automaticamente, leia a seção [Tutorial - Metadata and Docs URLs](../tutorial/metadata.md#docs-urls){.internal-link target=_blank}.
|
||||
11
docs/pt/docs/how-to/index.md
Normal file
@@ -0,0 +1,11 @@
|
||||
# Como Fazer - Exemplos Práticos
|
||||
|
||||
Aqui você encontrará diferentes exemplos práticos ou tutoriais de "como fazer" para vários tópicos.
|
||||
|
||||
A maioria dessas ideias será mais ou menos **independente**, e na maioria dos casos você só precisará estudá-las se elas se aplicarem diretamente ao **seu projeto**.
|
||||
|
||||
Se algo parecer interessante e útil para o seu projeto, vá em frente e dê uma olhada. Caso contrário, você pode simplesmente ignorá-lo.
|
||||
|
||||
!!! tip
|
||||
|
||||
Se você deseja **aprender FastAPI** de forma estruturada (recomendado), leia capítulo por capítulo [Tutorial - Guia de Usuário](../tutorial/index.md){.internal-link target=_blank} em vez disso.
|
||||
@@ -126,7 +126,7 @@ $ pip install fastapi
|
||||
|
||||
</div>
|
||||
|
||||
Você também precisará de um servidor ASGI para produção, tal como <a href="https://www.uvicorn.org" class="external-link" target="_blank">Uvicorn</a> ou <a href="https://gitlab.com/pgjones/hypercorn" class="external-link" target="_blank">Hypercorn</a>.
|
||||
Você também precisará de um servidor ASGI para produção, tal como <a href="https://www.uvicorn.org" class="external-link" target="_blank">Uvicorn</a> ou <a href="https://github.com/pgjones/hypercorn" class="external-link" target="_blank">Hypercorn</a>.
|
||||
|
||||
<div class="termy">
|
||||
|
||||
|
||||
20
docs/pt/docs/reference/exceptions.md
Normal file
@@ -0,0 +1,20 @@
|
||||
# Exceções - `HTTPException` e `WebSocketException`
|
||||
|
||||
Essas são as exceções que você pode lançar para mostrar erros ao cliente.
|
||||
|
||||
Quando você lança uma exceção, como aconteceria com o Python normal, o restante da execução é abortado. Dessa forma, você pode lançar essas exceções de qualquer lugar do código para abortar uma solicitação e mostrar o erro ao cliente.
|
||||
|
||||
Você pode usar:
|
||||
|
||||
* `HTTPException`
|
||||
* `WebSocketException`
|
||||
|
||||
Essas exceções podem ser importadas diretamente do `fastapi`:
|
||||
|
||||
```python
|
||||
from fastapi import HTTPException, WebSocketException
|
||||
```
|
||||
|
||||
::: fastapi.HTTPException
|
||||
|
||||
::: fastapi.WebSocketException
|
||||
6
docs/pt/docs/reference/index.md
Normal file
@@ -0,0 +1,6 @@
|
||||
# Referência - API de Código
|
||||
|
||||
Aqui está a referência ou API de código, as classes, funções, parâmetros, atributos e todas as partes do FastAPI que você pode usar em suas aplicações.
|
||||
|
||||
Se você quer **aprender FastAPI**, é muito melhor ler o
|
||||
[FastAPI Tutorial](https://fastapi.tiangolo.com/tutorial/).
|
||||
497
docs/pt/docs/tutorial/dependencies/classes-as-dependencies.md
Normal file
@@ -0,0 +1,497 @@
|
||||
# Classes como Dependências
|
||||
|
||||
Antes de nos aprofundarmos no sistema de **Injeção de Dependência**, vamos melhorar o exemplo anterior.
|
||||
|
||||
## `dict` do exemplo anterior
|
||||
|
||||
No exemplo anterior, nós retornávamos um `dict` da nossa dependência ("injetável"):
|
||||
|
||||
=== "Python 3.10+"
|
||||
|
||||
```Python hl_lines="9"
|
||||
{!> ../../../docs_src/dependencies/tutorial001_an_py310.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.9+"
|
||||
|
||||
```Python hl_lines="11"
|
||||
{!> ../../../docs_src/dependencies/tutorial001_an_py39.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.8+"
|
||||
|
||||
```Python hl_lines="12"
|
||||
{!> ../../../docs_src/dependencies/tutorial001_an.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.10+ non-Annotated"
|
||||
|
||||
!!! tip "Dica"
|
||||
Utilize a versão com `Annotated` se possível.
|
||||
|
||||
```Python hl_lines="7"
|
||||
{!> ../../../docs_src/dependencies/tutorial001_py310.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.8+ non-Annotated"
|
||||
|
||||
!!! tip "Dica"
|
||||
Utilize a versão com `Annotated` se possível.
|
||||
|
||||
```Python hl_lines="11"
|
||||
{!> ../../../docs_src/dependencies/tutorial001.py!}
|
||||
```
|
||||
|
||||
Mas assim obtemos um `dict` como valor do parâmetro `commons` na *função de operação de rota*.
|
||||
|
||||
E sabemos que editores de texto não têm como oferecer muitas funcionalidades (como sugestões automáticas) para objetos do tipo `dict`, por que não há como eles saberem o tipo das chaves e dos valores.
|
||||
|
||||
Podemos fazer melhor...
|
||||
|
||||
## O que caracteriza uma dependência
|
||||
|
||||
Até agora você apenas viu dependências declaradas como funções.
|
||||
|
||||
Mas essa não é a única forma de declarar dependências (mesmo que provavelmente seja a mais comum).
|
||||
|
||||
O fator principal para uma dependência é que ela deve ser "chamável"
|
||||
|
||||
Um objeto "chamável" em Python é qualquer coisa que o Python possa "chamar" como uma função
|
||||
|
||||
Então se você tiver um objeto `alguma_coisa` (que pode *não* ser uma função) que você possa "chamar" (executá-lo) dessa maneira:
|
||||
|
||||
```Python
|
||||
something()
|
||||
```
|
||||
|
||||
ou
|
||||
|
||||
```Python
|
||||
something(some_argument, some_keyword_argument="foo")
|
||||
```
|
||||
|
||||
Então esse objeto é um "chamável".
|
||||
|
||||
## Classes como dependências
|
||||
|
||||
Você deve ter percebido que para criar um instância de uma classe em Python, a mesma sintaxe é utilizada.
|
||||
|
||||
Por exemplo:
|
||||
|
||||
```Python
|
||||
class Cat:
|
||||
def __init__(self, name: str):
|
||||
self.name = name
|
||||
|
||||
|
||||
fluffy = Cat(name="Mr Fluffy")
|
||||
```
|
||||
|
||||
Nesse caso, `fluffy` é uma instância da classe `Cat`.
|
||||
|
||||
E para criar `fluffy`, você está "chamando" `Cat`.
|
||||
|
||||
Então, uma classe Python também é "chamável".
|
||||
|
||||
Então, no **FastAPI**, você pode utilizar uma classe Python como uma dependência.
|
||||
|
||||
O que o FastAPI realmente verifica, é se a dependência é algo chamável (função, classe, ou outra coisa) e os parâmetros que foram definidos.
|
||||
|
||||
Se você passar algo "chamável" como uma dependência do **FastAPI**, o framework irá analisar os parâmetros desse "chamável" e processá-los da mesma forma que os parâmetros de uma *função de operação de rota*. Incluindo as sub-dependências.
|
||||
|
||||
Isso também se aplica a objetos chamáveis que não recebem nenhum parâmetro. Da mesma forma que uma *função de operação de rota* sem parâmetros.
|
||||
|
||||
Então, podemos mudar o "injetável" na dependência `common_parameters` acima para a classe `CommonQueryParams`:
|
||||
|
||||
=== "Python 3.10+"
|
||||
|
||||
```Python hl_lines="11-15"
|
||||
{!> ../../../docs_src/dependencies/tutorial002_an_py310.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.9+"
|
||||
|
||||
```Python hl_lines="11-15"
|
||||
{!> ../../../docs_src/dependencies/tutorial002_an_py39.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.8+"
|
||||
|
||||
```Python hl_lines="12-16"
|
||||
{!> ../../../docs_src/dependencies/tutorial002_an.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.10+ non-Annotated"
|
||||
|
||||
!!! tip "Dica"
|
||||
Utilize a versão com `Annotated` se possível.
|
||||
|
||||
|
||||
```Python hl_lines="9-13"
|
||||
{!> ../../../docs_src/dependencies/tutorial002_py310.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.8+ non-Annotated"
|
||||
|
||||
!!! tip "Dica"
|
||||
Utilize a versão com `Annotated` se possível.
|
||||
|
||||
|
||||
```Python hl_lines="11-15"
|
||||
{!> ../../../docs_src/dependencies/tutorial002.py!}
|
||||
```
|
||||
|
||||
Observe o método `__init__` usado para criar uma instância da classe:
|
||||
|
||||
=== "Python 3.10+"
|
||||
|
||||
```Python hl_lines="12"
|
||||
{!> ../../../docs_src/dependencies/tutorial002_an_py310.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.9+"
|
||||
|
||||
```Python hl_lines="12"
|
||||
{!> ../../../docs_src/dependencies/tutorial002_an_py39.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.8+"
|
||||
|
||||
```Python hl_lines="13"
|
||||
{!> ../../../docs_src/dependencies/tutorial002_an.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.10+ non-Annotated"
|
||||
|
||||
!!! tip "Dica"
|
||||
Utilize a versão com `Annotated` se possível.
|
||||
|
||||
|
||||
```Python hl_lines="10"
|
||||
{!> ../../../docs_src/dependencies/tutorial002_py310.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.8+ non-Annotated"
|
||||
|
||||
!!! tip "Dica"
|
||||
Utilize a versão com `Annotated` se possível.
|
||||
|
||||
|
||||
```Python hl_lines="12"
|
||||
{!> ../../../docs_src/dependencies/tutorial002.py!}
|
||||
```
|
||||
|
||||
...ele possui os mesmos parâmetros que nosso `common_parameters` anterior:
|
||||
|
||||
=== "Python 3.10+"
|
||||
|
||||
```Python hl_lines="8"
|
||||
{!> ../../../docs_src/dependencies/tutorial001_an_py310.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.9+"
|
||||
|
||||
```Python hl_lines="9"
|
||||
{!> ../../../docs_src/dependencies/tutorial001_an_py39.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.8+"
|
||||
|
||||
```Python hl_lines="10"
|
||||
{!> ../../../docs_src/dependencies/tutorial001_an.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.10+ non-Annotated"
|
||||
|
||||
!!! tip "Dica"
|
||||
Utilize a versão com `Annotated` se possível.
|
||||
|
||||
|
||||
```Python hl_lines="6"
|
||||
{!> ../../../docs_src/dependencies/tutorial001_py310.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.8+ non-Annotated"
|
||||
|
||||
!!! tip "Dica"
|
||||
Utilize a versão com `Annotated` se possível.
|
||||
|
||||
|
||||
```Python hl_lines="9"
|
||||
{!> ../../../docs_src/dependencies/tutorial001.py!}
|
||||
```
|
||||
|
||||
Esses parâmetros são utilizados pelo **FastAPI** para "definir" a dependência.
|
||||
|
||||
Em ambos os casos teremos:
|
||||
|
||||
* Um parâmetro de consulta `q` opcional do tipo `str`.
|
||||
* Um parâmetro de consulta `skip` do tipo `int`, com valor padrão `0`.
|
||||
* Um parâmetro de consulta `limit` do tipo `int`, com valor padrão `100`.
|
||||
|
||||
Os dados serão convertidos, validados, documentados no esquema da OpenAPI e etc nos dois casos.
|
||||
|
||||
## Utilizando
|
||||
|
||||
Agora você pode declarar sua dependência utilizando essa classe.
|
||||
|
||||
=== "Python 3.10+"
|
||||
|
||||
```Python hl_lines="19"
|
||||
{!> ../../../docs_src/dependencies/tutorial002_an_py310.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.9+"
|
||||
|
||||
```Python hl_lines="19"
|
||||
{!> ../../../docs_src/dependencies/tutorial002_an_py39.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.8+"
|
||||
|
||||
```Python hl_lines="20"
|
||||
{!> ../../../docs_src/dependencies/tutorial002_an.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.10+ non-Annotated"
|
||||
|
||||
!!! tip "Dica"
|
||||
Utilize a versão com `Annotated` se possível.
|
||||
|
||||
|
||||
```Python hl_lines="17"
|
||||
{!> ../../../docs_src/dependencies/tutorial002_py310.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.8+ non-Annotated"
|
||||
|
||||
!!! tip "Dica"
|
||||
Utilize a versão com `Annotated` se possível.
|
||||
|
||||
|
||||
```Python hl_lines="19"
|
||||
{!> ../../../docs_src/dependencies/tutorial002.py!}
|
||||
```
|
||||
|
||||
O **FastAPI** chama a classe `CommonQueryParams`. Isso cria uma "instância" dessa classe e é a instância que será passada para o parâmetro `commons` na sua função.
|
||||
|
||||
## Anotações de Tipo vs `Depends`
|
||||
|
||||
Perceba como escrevemos `CommonQueryParams` duas vezes no código abaixo:
|
||||
|
||||
=== "Python 3.8+"
|
||||
|
||||
```Python
|
||||
commons: Annotated[CommonQueryParams, Depends(CommonQueryParams)]
|
||||
```
|
||||
|
||||
=== "Python 3.8+ non-Annotated"
|
||||
|
||||
!!! tip "Dica"
|
||||
Utilize a versão com `Annotated` se possível.
|
||||
|
||||
|
||||
```Python
|
||||
commons: CommonQueryParams = Depends(CommonQueryParams)
|
||||
```
|
||||
|
||||
O último `CommonQueryParams`, em:
|
||||
|
||||
```Python
|
||||
... Depends(CommonQueryParams)
|
||||
```
|
||||
|
||||
...é o que o **FastAPI** irá realmente usar para saber qual é a dependência.
|
||||
|
||||
É a partir dele que o FastAPI irá extrair os parâmetros passados e será o que o FastAPI irá realmente chamar.
|
||||
|
||||
---
|
||||
|
||||
Nesse caso, o primeiro `CommonQueryParams`, em:
|
||||
|
||||
=== "Python 3.8+"
|
||||
|
||||
```Python
|
||||
commons: Annotated[CommonQueryParams, ...
|
||||
```
|
||||
|
||||
=== "Python 3.8+ non-Annotated"
|
||||
|
||||
!!! tip "Dica"
|
||||
Utilize a versão com `Annotated` se possível.
|
||||
|
||||
|
||||
```Python
|
||||
commons: CommonQueryParams ...
|
||||
```
|
||||
|
||||
...não tem nenhum signficado especial para o **FastAPI**. O FastAPI não irá utilizá-lo para conversão dos dados, validação, etc (já que ele utiliza `Depends(CommonQueryParams)` para isso).
|
||||
|
||||
Na verdade você poderia escrever apenas:
|
||||
|
||||
=== "Python 3.8+"
|
||||
|
||||
```Python
|
||||
commons: Annotated[Any, Depends(CommonQueryParams)]
|
||||
```
|
||||
|
||||
=== "Python 3.8+ non-Annotated"
|
||||
|
||||
!!! tip "Dica"
|
||||
Utilize a versão com `Annotated` se possível.
|
||||
|
||||
|
||||
```Python
|
||||
commons = Depends(CommonQueryParams)
|
||||
```
|
||||
|
||||
...como em:
|
||||
|
||||
=== "Python 3.10+"
|
||||
|
||||
```Python hl_lines="19"
|
||||
{!> ../../../docs_src/dependencies/tutorial003_an_py310.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.9+"
|
||||
|
||||
```Python hl_lines="19"
|
||||
{!> ../../../docs_src/dependencies/tutorial003_an_py39.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.8+"
|
||||
|
||||
```Python hl_lines="20"
|
||||
{!> ../../../docs_src/dependencies/tutorial003_an.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.10+ non-Annotated"
|
||||
|
||||
!!! tip "Dica"
|
||||
Utilize a versão com `Annotated` se possível.
|
||||
|
||||
|
||||
```Python hl_lines="17"
|
||||
{!> ../../../docs_src/dependencies/tutorial003_py310.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.8+ non-Annotated"
|
||||
|
||||
!!! tip "Dica"
|
||||
Utilize a versão com `Annotated` se possível.
|
||||
|
||||
|
||||
```Python hl_lines="19"
|
||||
{!> ../../../docs_src/dependencies/tutorial003.py!}
|
||||
```
|
||||
|
||||
Mas declarar o tipo é encorajado por que é a forma que o seu editor de texto sabe o que será passado como valor do parâmetro `commons`.
|
||||
|
||||
<img src="/img/tutorial/dependencies/image02.png">
|
||||
|
||||
## Pegando um Atalho
|
||||
|
||||
Mas você pode ver que temos uma repetição do código neste exemplo, escrevendo `CommonQueryParams` duas vezes:
|
||||
|
||||
=== "Python 3.8+"
|
||||
|
||||
```Python
|
||||
commons: Annotated[CommonQueryParams, Depends(CommonQueryParams)]
|
||||
```
|
||||
|
||||
=== "Python 3.8+ non-Annotated"
|
||||
|
||||
!!! tip "Dica"
|
||||
Utilize a versão com `Annotated` se possível.
|
||||
|
||||
```Python
|
||||
commons: CommonQueryParams = Depends(CommonQueryParams)
|
||||
```
|
||||
|
||||
O **FastAPI** nos fornece um atalho para esses casos, onde a dependência é *especificamente* uma classe que o **FastAPI** irá "chamar" para criar uma instância da própria classe.
|
||||
|
||||
Para esses casos específicos, você pode fazer o seguinte:
|
||||
|
||||
Em vez de escrever:
|
||||
|
||||
=== "Python 3.8+"
|
||||
|
||||
```Python
|
||||
commons: Annotated[CommonQueryParams, Depends(CommonQueryParams)]
|
||||
```
|
||||
|
||||
=== "Python 3.8+ non-Annotated"
|
||||
|
||||
!!! tip "Dica"
|
||||
Utilize a versão com `Annotated` se possível.
|
||||
|
||||
```Python
|
||||
commons: CommonQueryParams = Depends(CommonQueryParams)
|
||||
```
|
||||
|
||||
...escreva:
|
||||
|
||||
=== "Python 3.8+"
|
||||
|
||||
```Python
|
||||
commons: Annotated[CommonQueryParams, Depends()]
|
||||
```
|
||||
|
||||
=== "Python 3.8 non-Annotated"
|
||||
|
||||
!!! tip "Dica"
|
||||
Utilize a versão com `Annotated` se possível.
|
||||
|
||||
|
||||
```Python
|
||||
commons: CommonQueryParams = Depends()
|
||||
```
|
||||
|
||||
Você declara a dependência como o tipo do parâmetro, e utiliza `Depends()` sem nenhum parâmetro, em vez de ter que escrever a classe *novamente* dentro de `Depends(CommonQueryParams)`.
|
||||
|
||||
O mesmo exemplo ficaria então dessa forma:
|
||||
|
||||
=== "Python 3.10+"
|
||||
|
||||
```Python hl_lines="19"
|
||||
{!> ../../../docs_src/dependencies/tutorial004_an_py310.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.9+"
|
||||
|
||||
```Python hl_lines="19"
|
||||
{!> ../../../docs_src/dependencies/tutorial004_an_py39.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.8+"
|
||||
|
||||
```Python hl_lines="20"
|
||||
{!> ../../../docs_src/dependencies/tutorial004_an.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.10+ non-Annotated"
|
||||
|
||||
!!! tip "Dica"
|
||||
Utilize a versão com `Annotated` se possível.
|
||||
|
||||
|
||||
```Python hl_lines="17"
|
||||
{!> ../../../docs_src/dependencies/tutorial004_py310.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.8+ non-Annotated"
|
||||
|
||||
!!! tip "Dica"
|
||||
Utilize a versão com `Annotated` se possível.
|
||||
|
||||
|
||||
```Python hl_lines="19"
|
||||
{!> ../../../docs_src/dependencies/tutorial004.py!}
|
||||
```
|
||||
|
||||
...e o **FastAPI** saberá o que fazer.
|
||||
|
||||
!!! tip "Dica"
|
||||
Se isso parece mais confuso do que útil, não utilize, você não *precisa* disso.
|
||||
|
||||
É apenas um atalho. Por que o **FastAPI** se preocupa em ajudar a minimizar a repetição de código.
|
||||
@@ -0,0 +1,138 @@
|
||||
# Dependências em decoradores de operações de rota
|
||||
|
||||
Em alguns casos você não precisa necessariamente retornar o valor de uma dependência dentro de uma *função de operação de rota*.
|
||||
|
||||
Ou a dependência não retorna nenhum valor.
|
||||
|
||||
Mas você ainda precisa que ela seja executada/resolvida.
|
||||
|
||||
Para esses casos, em vez de declarar um parâmetro em uma *função de operação de rota* com `Depends`, você pode adicionar um argumento `dependencies` do tipo `list` ao decorador da operação de rota.
|
||||
|
||||
## Adicionando `dependencies` ao decorador da operação de rota
|
||||
|
||||
O *decorador da operação de rota* recebe um argumento opcional `dependencies`.
|
||||
|
||||
Ele deve ser uma lista de `Depends()`:
|
||||
|
||||
=== "Python 3.9+"
|
||||
|
||||
```Python hl_lines="19"
|
||||
{!> ../../../docs_src/dependencies/tutorial006_an_py39.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.8+"
|
||||
|
||||
```Python hl_lines="18"
|
||||
{!> ../../../docs_src/dependencies/tutorial006_an.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.8 non-Annotated"
|
||||
|
||||
!!! tip "Dica"
|
||||
Utilize a versão com `Annotated` se possível
|
||||
|
||||
```Python hl_lines="17"
|
||||
{!> ../../../docs_src/dependencies/tutorial006.py!}
|
||||
```
|
||||
Essas dependências serão executadas/resolvidas da mesma forma que dependências comuns. Mas o valor delas (se existir algum) não será passado para a sua *função de operação de rota*.
|
||||
|
||||
!!! tip "Dica"
|
||||
Alguns editores de texto checam parâmetros de funções não utilizados, e os mostram como erros.
|
||||
|
||||
Utilizando `dependencies` no *decorador da operação de rota* você pode garantir que elas serão executadas enquanto evita errors de editores/ferramentas.
|
||||
|
||||
Isso também pode ser útil para evitar confundir novos desenvolvedores que ao ver um parâmetro não usado no seu código podem pensar que ele é desnecessário.
|
||||
|
||||
!!! info "Informação"
|
||||
Neste exemplo utilizamos cabeçalhos personalizados inventados `X-Keys` e `X-Token`.
|
||||
|
||||
Mas em situações reais, como implementações de segurança, você pode obter mais vantagens em usar as [Ferramentas de segurança integradas (o próximo capítulo)](../security/index.md){.internal-link target=_blank}.
|
||||
|
||||
## Erros das dependências e valores de retorno
|
||||
|
||||
Você pode utilizar as mesmas *funções* de dependências que você usaria normalmente.
|
||||
|
||||
### Requisitos de Dependências
|
||||
|
||||
Dependências podem declarar requisitos de requisições (como cabeçalhos) ou outras subdependências:
|
||||
|
||||
=== "Python 3.9+"
|
||||
|
||||
```Python hl_lines="8 13"
|
||||
{!> ../../../docs_src/dependencies/tutorial006_an_py39.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.8+"
|
||||
|
||||
```Python hl_lines="7 12"
|
||||
{!> ../../../docs_src/dependencies/tutorial006_an.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.8 non-Annotated"
|
||||
|
||||
!!! tip "Dica"
|
||||
Utilize a versão com `Annotated` se possível
|
||||
|
||||
```Python hl_lines="6 11"
|
||||
{!> ../../../docs_src/dependencies/tutorial006.py!}
|
||||
```
|
||||
|
||||
### Levantando exceções
|
||||
|
||||
Essas dependências podem levantar exceções, da mesma forma que dependências comuns:
|
||||
|
||||
=== "Python 3.9+"
|
||||
|
||||
```Python hl_lines="10 15"
|
||||
{!> ../../../docs_src/dependencies/tutorial006_an_py39.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.8+"
|
||||
|
||||
```Python hl_lines="9 14"
|
||||
{!> ../../../docs_src/dependencies/tutorial006_an.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.8 non-Annotated"
|
||||
|
||||
!!! tip "Dica"
|
||||
Utilize a versão com `Annotated` se possível
|
||||
|
||||
```Python hl_lines="8 13"
|
||||
{!> ../../../docs_src/dependencies/tutorial006.py!}
|
||||
```
|
||||
|
||||
### Valores de retorno
|
||||
|
||||
E elas também podem ou não retornar valores, eles não serão utilizados.
|
||||
|
||||
Então, você pode reutilizar uma dependência comum (que retorna um valor) que já seja utilizada em outro lugar, e mesmo que o valor não seja utilizado, a dependência será executada:
|
||||
|
||||
=== "Python 3.9+"
|
||||
|
||||
```Python hl_lines="11 16"
|
||||
{!> ../../../docs_src/dependencies/tutorial006_an_py39.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.8+"
|
||||
|
||||
```Python hl_lines="10 15"
|
||||
{!> ../../../docs_src/dependencies/tutorial006_an.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.8 non-Annotated"
|
||||
|
||||
!!! tip "Dica"
|
||||
Utilize a versão com `Annotated` se possível
|
||||
|
||||
```Python hl_lines="9 14"
|
||||
{!> ../../../docs_src/dependencies/tutorial006.py!}
|
||||
```
|
||||
|
||||
## Dependências para um grupo de *operações de rota*
|
||||
|
||||
Mais a frente, quando você ler sobre como estruturar aplicações maiores ([Bigger Applications - Multiple Files](../../tutorial/bigger-applications.md){.internal-link target=_blank}), possivelmente com múltiplos arquivos, você aprenderá a declarar um único parâmetro `dependencies` para um grupo de *operações de rota*.
|
||||
|
||||
## Dependências globais
|
||||
|
||||
No próximo passo veremos como adicionar dependências para uma aplicação `FastAPI` inteira, para que ela seja aplicada em toda *operação de rota*.
|
||||
34
docs/pt/docs/tutorial/dependencies/global-dependencies.md
Normal file
@@ -0,0 +1,34 @@
|
||||
# Dependências Globais
|
||||
|
||||
Para alguns tipos de aplicação específicos você pode querer adicionar dependências para toda a aplicação.
|
||||
|
||||
De forma semelhante a [adicionar dependências (`dependencies`) em *decoradores de operação de rota*](dependencies-in-path-operation-decorators.md){.internal-link target=_blank}, você pode adicioná-las à aplicação `FastAPI`.
|
||||
|
||||
Nesse caso, elas serão aplicadas a todas as *operações de rota* da aplicação:
|
||||
|
||||
=== "Python 3.9+"
|
||||
|
||||
```Python hl_lines="16"
|
||||
{!> ../../../docs_src/dependencies/tutorial012_an_py39.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.8+"
|
||||
|
||||
```Python hl_lines="16"
|
||||
{!> ../../../docs_src/dependencies/tutorial012_an.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.8 non-Annotated"
|
||||
|
||||
!!! tip "Dica"
|
||||
Utilize a versão com `Annotated` se possível.
|
||||
|
||||
```Python hl_lines="15"
|
||||
{!> ../../../docs_src/dependencies/tutorial012.py!}
|
||||
```
|
||||
|
||||
E todos os conceitos apresentados na sessão sobre [adicionar dependências em *decoradores de operação de rota*](dependencies-in-path-operation-decorators.md){.internal-link target=_blank} ainda se aplicam, mas nesse caso, para todas as *operações de rota* da aplicação.
|
||||
|
||||
## Dependências para conjuntos de *operações de rota*
|
||||
|
||||
Mais para a frente, quando você ler sobre como estruturar aplicações maiores ([Bigger Applications - Multiple Files](../../tutorial/bigger-applications.md){.internal-link target=_blank}), possivelmente com múltiplos arquivos, você irá aprender a declarar um único parâmetro `dependencies` para um conjunto de *operações de rota*.
|
||||
353
docs/pt/docs/tutorial/dependencies/index.md
Normal file
@@ -0,0 +1,353 @@
|
||||
# Dependências
|
||||
|
||||
O **FastAPI** possui um poderoso, mas intuitivo sistema de **<abbr title="também conhecidos como, recursos, provedores, serviços, injetáveis">Injeção de Dependência</abbr>**.
|
||||
|
||||
Esse sistema foi pensado para ser fácil de usar, e permitir que qualquer desenvolvedor possa integrar facilmente outros componentes ao **FastAPI**.
|
||||
|
||||
## O que é "Injeção de Dependência"
|
||||
|
||||
**"Injeção de Dependência"** no mundo da programação significa, que existe uma maneira de declarar no seu código (nesse caso, suas *funções de operação de rota*) para declarar as coisas que ele precisa para funcionar e que serão utilizadas: "dependências".
|
||||
|
||||
Então, esse sistema (nesse caso o **FastAPI**) se encarrega de fazer o que for preciso para fornecer essas dependências para o código ("injetando" as dependências).
|
||||
|
||||
Isso é bastante útil quando você precisa:
|
||||
|
||||
* Definir uma lógica compartilhada (mesmo formato de código repetidamente).
|
||||
* Compartilhar conexões com banco de dados.
|
||||
* Aplicar regras de segurança, autenticação, papéis de usuários, etc.
|
||||
* E muitas outras coisas...
|
||||
|
||||
Tudo isso, enquanto minimizamos a repetição de código.
|
||||
|
||||
## Primeiros passos
|
||||
|
||||
Vamos ver um exemplo simples. Tão simples que não será muito útil, por enquanto.
|
||||
|
||||
Mas dessa forma podemos focar em como o sistema de **Injeção de Dependência** funciona.
|
||||
|
||||
### Criando uma dependência, ou "injetável"
|
||||
|
||||
Primeiro vamos focar na dependência.
|
||||
|
||||
Ela é apenas uma função que pode receber os mesmos parâmetros de uma *função de operação de rota*:
|
||||
|
||||
=== "Python 3.10+"
|
||||
|
||||
```Python hl_lines="8-9"
|
||||
{!> ../../../docs_src/dependencies/tutorial001_an_py310.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.9+"
|
||||
|
||||
```Python hl_lines="8-11"
|
||||
{!> ../../../docs_src/dependencies/tutorial001_an_py39.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.8+"
|
||||
|
||||
```Python hl_lines="9-12"
|
||||
{!> ../../../docs_src/dependencies/tutorial001_an.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.10+ non-Annotated"
|
||||
|
||||
!!! tip "Dica"
|
||||
Utilize a versão com `Annotated` se possível.
|
||||
|
||||
```Python hl_lines="6-7"
|
||||
{!> ../../../docs_src/dependencies/tutorial001_py310.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.8+ non-Annotated"
|
||||
|
||||
!!! tip "Dica"
|
||||
Utilize a versão com `Annotated` se possível.
|
||||
|
||||
```Python hl_lines="8-11"
|
||||
{!> ../../../docs_src/dependencies/tutorial001.py!}
|
||||
```
|
||||
|
||||
E pronto.
|
||||
|
||||
**2 linhas**.
|
||||
|
||||
E com a mesma forma e estrutura de todas as suas *funções de operação de rota*.
|
||||
|
||||
Você pode pensar nela como uma *função de operação de rota* sem o "decorador" (sem a linha `@app.get("/some-path")`).
|
||||
|
||||
E com qualquer retorno que você desejar.
|
||||
|
||||
Neste caso, a dependência espera por:
|
||||
|
||||
* Um parâmetro de consulta opcional `q` do tipo `str`.
|
||||
* Um parâmetro de consulta opcional `skip` do tipo `int`, e igual a `0` por padrão.
|
||||
* Um parâmetro de consulta opcional `limit` do tipo `int`, e igual a `100` por padrão.
|
||||
|
||||
E então retorna um `dict` contendo esses valores.
|
||||
|
||||
!!! info "Informação"
|
||||
FastAPI passou a suportar a notação `Annotated` (e começou a recomendá-la) na versão 0.95.0.
|
||||
|
||||
Se você utiliza uma versão anterior, ocorrerão erros ao tentar utilizar `Annotated`.
|
||||
|
||||
Certifique-se de [Atualizar a versão do FastAPI](../../deployment/versions.md#atualizando-as-versoes-do-fastapi){.internal-link target=_blank} para pelo menos 0.95.1 antes de usar `Annotated`.
|
||||
|
||||
### Importando `Depends`
|
||||
|
||||
=== "Python 3.10+"
|
||||
|
||||
```Python hl_lines="3"
|
||||
{!> ../../../docs_src/dependencies/tutorial001_an_py310.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.9+"
|
||||
|
||||
```Python hl_lines="3"
|
||||
{!> ../../../docs_src/dependencies/tutorial001_an_py39.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.8+"
|
||||
|
||||
```Python hl_lines="3"
|
||||
{!> ../../../docs_src/dependencies/tutorial001_an.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.10+ non-Annotated"
|
||||
|
||||
!!! tip "Dica"
|
||||
Utilize a versão com `Annotated` se possível.
|
||||
|
||||
```Python hl_lines="1"
|
||||
{!> ../../../docs_src/dependencies/tutorial001_py310.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.8+ non-Annotated"
|
||||
|
||||
!!! tip "Dica"
|
||||
Utilize a versão com `Annotated` se possível.
|
||||
|
||||
```Python hl_lines="3"
|
||||
{!> ../../../docs_src/dependencies/tutorial001.py!}
|
||||
```
|
||||
|
||||
### Declarando a dependência, no "dependente"
|
||||
|
||||
Da mesma forma que você utiliza `Body`, `Query`, etc. Como parâmetros de sua *função de operação de rota*, utilize `Depends` com um novo parâmetro:
|
||||
|
||||
=== "Python 3.10+"
|
||||
|
||||
```Python hl_lines="13 18"
|
||||
{!> ../../../docs_src/dependencies/tutorial001_an_py310.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.9+"
|
||||
|
||||
```Python hl_lines="15 20"
|
||||
{!> ../../../docs_src/dependencies/tutorial001_an_py39.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.8+"
|
||||
|
||||
```Python hl_lines="16 21"
|
||||
{!> ../../../docs_src/dependencies/tutorial001_an.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.10+ non-Annotated"
|
||||
|
||||
!!! tip "Dica"
|
||||
Utilize a versão com `Annotated` se possível.
|
||||
|
||||
```Python hl_lines="11 16"
|
||||
{!> ../../../docs_src/dependencies/tutorial001_py310.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.8+ non-Annotated"
|
||||
|
||||
!!! tip "Dica"
|
||||
Utilize a versão com `Annotated` se possível.
|
||||
|
||||
```Python hl_lines="15 20"
|
||||
{!> ../../../docs_src/dependencies/tutorial001.py!}
|
||||
```
|
||||
|
||||
Ainda que `Depends` seja utilizado nos parâmetros da função da mesma forma que `Body`, `Query`, etc, `Depends` funciona de uma forma um pouco diferente.
|
||||
|
||||
Você fornece um único parâmetro para `Depends`.
|
||||
|
||||
Esse parâmetro deve ser algo como uma função.
|
||||
|
||||
Você **não chama a função** diretamente (não adicione os parênteses no final), apenas a passe como parâmetro de `Depends()`.
|
||||
|
||||
E essa função vai receber os parâmetros da mesma forma que uma *função de operação de rota*.
|
||||
|
||||
!!! tip "Dica"
|
||||
Você verá quais outras "coisas", além de funções, podem ser usadas como dependências no próximo capítulo.
|
||||
|
||||
Sempre que uma nova requisição for realizada, o **FastAPI** se encarrega de:
|
||||
|
||||
* Chamar sua dependência ("injetável") com os parâmetros corretos.
|
||||
* Obter o resultado da função.
|
||||
* Atribuir esse resultado para o parâmetro em sua *função de operação de rota*.
|
||||
|
||||
```mermaid
|
||||
graph TB
|
||||
|
||||
common_parameters(["common_parameters"])
|
||||
read_items["/items/"]
|
||||
read_users["/users/"]
|
||||
|
||||
common_parameters --> read_items
|
||||
common_parameters --> read_users
|
||||
```
|
||||
|
||||
Assim, você escreve um código compartilhado apenas uma vez e o **FastAPI** se encarrega de chamá-lo em suas *operações de rota*.
|
||||
|
||||
!!! check "Checando"
|
||||
Perceba que você não precisa criar uma classe especial e enviar a dependência para algum outro lugar em que o **FastAPI** a "registre" ou realize qualquer operação similar.
|
||||
|
||||
Você apenas envia para `Depends` e o **FastAPI** sabe como fazer o resto.
|
||||
|
||||
## Compartilhando dependências `Annotated`
|
||||
|
||||
Nos exemplos acima, você pode ver que existe uma pequena **duplicação de código**.
|
||||
|
||||
Quando você precisa utilizar a dependência `common_parameters()`, você precisa escrever o parâmetro inteiro com uma anotação de tipo e `Depends()`:
|
||||
|
||||
```Python
|
||||
commons: Annotated[dict, Depends(common_parameters)]
|
||||
```
|
||||
|
||||
Mas como estamos utilizando `Annotated`, podemos guardar esse valor `Annotated` em uma variável e utilizá-la em múltiplos locais:
|
||||
|
||||
=== "Python 3.10+"
|
||||
|
||||
```Python hl_lines="12 16 21"
|
||||
{!> ../../../docs_src/dependencies/tutorial001_02_an_py310.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.9+"
|
||||
|
||||
```Python hl_lines="14 18 23"
|
||||
{!> ../../../docs_src/dependencies/tutorial001_02_an_py39.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.8+"
|
||||
|
||||
```Python hl_lines="15 19 24"
|
||||
{!> ../../../docs_src/dependencies/tutorial001_02_an.py!}
|
||||
```
|
||||
|
||||
!!! tip "Dica"
|
||||
Isso é apenas Python padrão, essa funcionalidade é chamada de "type alias", e na verdade não é específica ao **FastAPI**.
|
||||
|
||||
Mas como o **FastAPI** se baseia em convenções do Python, incluindo `Annotated`, você pode incluir esse truque no seu código. 😎
|
||||
|
||||
As dependências continuarão funcionando como esperado, e a **melhor parte** é que a **informação sobre o tipo é preservada**, o que signfica que seu editor de texto ainda irá incluir **preenchimento automático**, **visualização de erros**, etc. O mesmo vale para ferramentas como `mypy`.
|
||||
|
||||
Isso é especialmente útil para uma **base de código grande** onde **as mesmas dependências** são utilizadas repetidamente em **muitas *operações de rota***.
|
||||
|
||||
## `Async` ou não, eis a questão
|
||||
|
||||
Como as dependências também serão chamadas pelo **FastAPI** (da mesma forma que *funções de operação de rota*), as mesmas regras se aplicam ao definir suas funções.
|
||||
|
||||
Você pode utilizar `async def` ou apenas `def`.
|
||||
|
||||
E você pode declarar dependências utilizando `async def` dentro de *funções de operação de rota* definidas com `def`, ou declarar dependências com `def` e utilizar dentro de *funções de operação de rota* definidas com `async def`, etc.
|
||||
|
||||
Não faz diferença. O **FastAPI** sabe o que fazer.
|
||||
|
||||
!!! note "Nota"
|
||||
Caso você não conheça, veja em [Async: *"Com Pressa?"*](../../async.md#com-pressa){.internal-link target=_blank} a sessão acerca de `async` e `await` na documentação.
|
||||
|
||||
## Integrando com OpenAPI
|
||||
|
||||
Todas as declarações de requisições, validações e requisitos para suas dependências (e sub-dependências) serão integradas em um mesmo esquema OpenAPI.
|
||||
|
||||
Então, a documentação interativa também terá toda a informação sobre essas dependências:
|
||||
|
||||
<img src="/img/tutorial/dependencies/image01.png">
|
||||
|
||||
## Caso de Uso Simples
|
||||
|
||||
Se você parar para ver, *funções de operação de rota* são declaradas para serem usadas sempre que uma *rota* e uma *operação* se encaixam, e então o **FastAPI** se encarrega de chamar a função correspondente com os argumentos corretos, extraindo os dados da requisição.
|
||||
|
||||
Na verdade, todos (ou a maioria) dos frameworks web funcionam da mesma forma.
|
||||
|
||||
Você nunca chama essas funções diretamente. Elas são chamadas pelo framework utilizado (nesse caso, **FastAPI**).
|
||||
|
||||
Com o Sistema de Injeção de Dependência, você também pode informar ao **FastAPI** que sua *função de operação de rota* também "depende" em algo a mais que deve ser executado antes de sua *função de operação de rota*, e o **FastAPI** se encarrega de executar e "injetar" os resultados.
|
||||
|
||||
Outros termos comuns para essa mesma ideia de "injeção de dependência" são:
|
||||
|
||||
* recursos
|
||||
* provedores
|
||||
* serviços
|
||||
* injetáveis
|
||||
* componentes
|
||||
|
||||
## Plug-ins em **FastAPI**
|
||||
|
||||
Integrações e "plug-ins" podem ser construídos com o sistema de **Injeção de Dependência**. Mas na verdade, **não há necessidade de criar "plug-ins"**, já que utilizando dependências é possível declarar um número infinito de integrações e interações que se tornam disponíveis para as suas *funções de operação de rota*.
|
||||
|
||||
E as dependências pode ser criadas de uma forma bastante simples e intuitiva que permite que você importe apenas os pacotes Python que forem necessários, e integrá-los com as funções de sua API em algumas linhas de código, *literalmente*.
|
||||
|
||||
Você verá exemplos disso nos próximos capítulos, acerca de bancos de dados relacionais e NoSQL, segurança, etc.
|
||||
|
||||
## Compatibilidade do **FastAPI**
|
||||
|
||||
A simplicidade do sistema de injeção de dependência do **FastAPI** faz ele compatível com:
|
||||
|
||||
* todos os bancos de dados relacionais
|
||||
* bancos de dados NoSQL
|
||||
* pacotes externos
|
||||
* APIs externas
|
||||
* sistemas de autenticação e autorização
|
||||
* istemas de monitoramento de uso para APIs
|
||||
* sistemas de injeção de dados de resposta
|
||||
* etc.
|
||||
|
||||
## Simples e Poderoso
|
||||
|
||||
Mesmo que o sistema hierárquico de injeção de dependência seja simples de definir e utilizar, ele ainda é bastante poderoso.
|
||||
|
||||
Você pode definir dependências que por sua vez definem suas próprias dependências.
|
||||
|
||||
No fim, uma árvore hierárquica de dependências é criadas, e o sistema de **Injeção de Dependência** toma conta de resolver todas essas dependências (e as sub-dependências delas) para você, e provê (injeta) os resultados em cada passo.
|
||||
|
||||
Por exemplo, vamos supor que você possua 4 endpoints na sua API (*operações de rota*):
|
||||
|
||||
* `/items/public/`
|
||||
* `/items/private/`
|
||||
* `/users/{user_id}/activate`
|
||||
* `/items/pro/`
|
||||
|
||||
Você poderia adicionar diferentes requisitos de permissão para cada um deles utilizando apenas dependências e sub-dependências:
|
||||
|
||||
```mermaid
|
||||
graph TB
|
||||
|
||||
current_user(["current_user"])
|
||||
active_user(["active_user"])
|
||||
admin_user(["admin_user"])
|
||||
paying_user(["paying_user"])
|
||||
|
||||
public["/items/public/"]
|
||||
private["/items/private/"]
|
||||
activate_user["/users/{user_id}/activate"]
|
||||
pro_items["/items/pro/"]
|
||||
|
||||
current_user --> active_user
|
||||
active_user --> admin_user
|
||||
active_user --> paying_user
|
||||
|
||||
current_user --> public
|
||||
active_user --> private
|
||||
admin_user --> activate_user
|
||||
paying_user --> pro_items
|
||||
```
|
||||
|
||||
## Integração com **OpenAPI**
|
||||
|
||||
Todas essas dependências, ao declarar os requisitos para suas *operações de rota*, também adicionam parâmetros, validações, etc.
|
||||
|
||||
O **FastAPI** se encarrega de adicionar tudo isso ao esquema OpenAPI, para que seja mostrado nos sistemas de documentação interativa.
|
||||