Merge branch 'master' into patch-1

This commit is contained in:
Muhammad Ashiq Ameer 2024-05-12 23:06:29 +05:30 committed by GitHub
commit e31090dec2
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
62 changed files with 1519 additions and 844 deletions

View File

@ -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

View File

@ -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:

View File

@ -8,6 +8,13 @@ on:
jobs:
publish:
runs-on: ubuntu-latest
strategy:
matrix:
package:
- fastapi
- fastapi-slim
permissions:
id-token: write
steps:
- name: Dump GitHub context
env:
@ -21,19 +28,14 @@ jobs:
# Issue ref: https://github.com/actions/setup-python/issues/436
# cache: "pip"
# cache-dependency-path: pyproject.toml
- uses: actions/cache@v4
id: cache
with:
path: ${{ env.pythonLocation }}
key: ${{ runner.os }}-python-${{ env.pythonLocation }}-${{ hashFiles('pyproject.toml') }}-publish
- name: Install build dependencies
run: pip install build
- name: Build distribution
env:
TIANGOLO_BUILD_PACKAGE: ${{ matrix.package }}
run: python -m build
- name: Publish
uses: pypa/gh-action-pypi-publish@v1.8.14
with:
password: ${{ secrets.PYPI_API_TOKEN }}
- name: Dump GitHub context
env:
GITHUB_CONTEXT: ${{ toJson(github) }}

View File

@ -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

View File

@ -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) }}

View File

@ -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

View File

@ -27,7 +27,7 @@
---
FastAPI is a modern, fast (high-performance), web framework for building APIs with Python 3.8+ based on standard Python type hints.
FastAPI is a modern, fast (high-performance), web framework for building APIs with Python based on standard Python type hints.
The key features are:
@ -122,8 +122,6 @@ If you are building a <abbr title="Command Line Interface">CLI</abbr> app to be
## Requirements
Python 3.8+
FastAPI stands on the shoulders of giants:
* <a href="https://www.starlette.io/" class="external-link" target="_blank">Starlette</a> for the web parts.
@ -141,18 +139,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 +199,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 +224,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 +303,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
@ -338,7 +337,7 @@ You do that with standard modern Python types.
You don't have to learn a new syntax, the methods or classes of a specific library, etc.
Just standard **Python 3.8+**.
Just standard **Python**.
For example, for an `int`:
@ -448,7 +447,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 +460,33 @@ 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.
* <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`.
* `fastapi-cli` - to provide the `fastapi` command.
You can install all of these with `pip install "fastapi[all]"`.
When you install `fastapi` it comes these standard dependencies.
## `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

View File

@ -27,7 +27,7 @@
---
FastAPI Python 3.8+ ilə API yaratmaq üçün standart Python <abbr title="Tip Məsləhətləri: Type Hints">tip məsləhətlərinə</abbr> əsaslanan, müasir, sürətli (yüksək performanslı) framework-dür.
FastAPI Python ilə API yaratmaq üçün standart Python <abbr title="Tip Məsləhətləri: Type Hints">tip məsləhətlərinə</abbr> əsaslanan, müasir, sürətli (yüksək performanslı) framework-dür.
Əsas xüsusiyyətləri bunlardır:
@ -115,8 +115,6 @@ FastAPI Python 3.8+ ilə API yaratmaq üçün standart Python <abbr title="Tip M
## Tələblər
Python 3.8+
FastAPI nəhənglərin çiyinlərində dayanır:
* Web tərəfi üçün <a href="https://www.starlette.io/" class="external-link" target="_blank">Starlette</a>.
@ -330,7 +328,7 @@ Bunu standart müasir Python tipləri ilə edirsiniz.
Yeni sintaksis, müəyyən bir kitabxananın metodlarını və ya siniflərini və s. öyrənmək məcburiyyətində deyilsiniz.
Sadəcə standart **Python 3.8+**.
Sadəcə standart **Python**.
Məsələn, `int` üçün:

View File

@ -36,7 +36,7 @@ hide:
---
FastAPI ist ein modernes, schnelles (hoch performantes) Webframework zur Erstellung von APIs mit Python 3.8+ auf Basis von Standard-Python-Typhinweisen.
FastAPI ist ein modernes, schnelles (hoch performantes) Webframework zur Erstellung von APIs mit Python auf Basis von Standard-Python-Typhinweisen.
Seine Schlüssel-Merkmale sind:
@ -125,8 +125,6 @@ Wenn Sie eine <abbr title="Command Line Interface Kommandozeilen-Schnittstel
## Anforderungen
Python 3.8+
FastAPI steht auf den Schultern von Giganten:
* <a href="https://www.starlette.io/" class="external-link" target="_blank">Starlette</a> für die Webanteile.
@ -340,7 +338,7 @@ Das machen Sie mit modernen Standard-Python-Typen.
Sie müssen keine neue Syntax, Methoden oder Klassen einer bestimmten Bibliothek usw. lernen.
Nur Standard-**Python 3.8+**.
Nur Standard-**Python+**.
Zum Beispiel für ein `int`:

View File

@ -56,10 +56,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
@ -98,15 +95,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 +116,12 @@ sponsors:
- login: ProteinQure
avatarUrl: https://avatars.githubusercontent.com/u/33707203?v=4
url: https://github.com/ProteinQure
- 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: jsoques
avatarUrl: https://avatars.githubusercontent.com/u/12414216?u=620921d94196546cc8b9eae2cc4cbc3f95bab42f&v=4
url: https://github.com/jsoques
@ -146,15 +149,9 @@ 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: CodeProcessor
avatarUrl: https://avatars.githubusercontent.com/u/24785073?u=b4dd0ef3f42ced86412a060dd2bd6c8caaf771aa&v=4
url: https://github.com/CodeProcessor
- login: patsatsia
avatarUrl: https://avatars.githubusercontent.com/u/61111267?u=3271b85f7a37b479c8d0ae0a235182e83c166edf&v=4
url: https://github.com/patsatsia
@ -170,15 +167,15 @@ sponsors:
- login: DelfinaCare
avatarUrl: https://avatars.githubusercontent.com/u/83734439?v=4
url: https://github.com/DelfinaCare
- 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 +185,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: koconder
avatarUrl: https://avatars.githubusercontent.com/u/25068?u=582657b23622aaa3dfe68bd028a780f272f456fa&v=4
url: https://github.com/koconder
- 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
@ -209,21 +209,24 @@ sponsors:
- login: Shark009
avatarUrl: https://avatars.githubusercontent.com/u/3163309?u=0c6f4091b0eda05c44c390466199826e6dc6e431&v=4
url: https://github.com/Shark009
- login: dblackrun
avatarUrl: https://avatars.githubusercontent.com/u/3528486?v=4
url: https://github.com/dblackrun
- 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
- login: ericof
avatarUrl: https://avatars.githubusercontent.com/u/306014?u=cf7c8733620397e6584a451505581c01c5d842d7&v=4
url: https://github.com/ericof
- login: falquaddoomi
avatarUrl: https://avatars.githubusercontent.com/u/312923?u=aab6efa665ed9495ce37371af1cd637ec554772f&v=4
url: https://github.com/falquaddoomi
- login: wshayes
avatarUrl: https://avatars.githubusercontent.com/u/365303?u=07ca03c5ee811eb0920e633cc3c3db73dbec1aa5&v=4
url: https://github.com/wshayes
@ -236,6 +239,12 @@ sponsors:
- login: mintuhouse
avatarUrl: https://avatars.githubusercontent.com/u/769950?u=ecfbd79a97d33177e0d093ddb088283cf7fe8444&v=4
url: https://github.com/mintuhouse
- login: dblackrun
avatarUrl: https://avatars.githubusercontent.com/u/3528486?v=4
url: https://github.com/dblackrun
- login: simw
avatarUrl: https://avatars.githubusercontent.com/u/6322526?v=4
url: https://github.com/simw
- login: Rehket
avatarUrl: https://avatars.githubusercontent.com/u/7015688?u=3afb0ba200feebbc7f958950e92db34df2a3c172&v=4
url: https://github.com/Rehket
@ -245,12 +254,6 @@ sponsors:
- login: TrevorBenson
avatarUrl: https://avatars.githubusercontent.com/u/9167887?u=afdd1766fdb79e04e59094cc6a54cd011ee7f686&v=4
url: https://github.com/TrevorBenson
- 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
@ -284,15 +287,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
@ -312,11 +315,14 @@ sponsors:
avatarUrl: https://avatars.githubusercontent.com/u/33275230?u=eb223cad27017bb1e936ee9b429b450d092d0236&v=4
url: https://github.com/engineerjoe440
- login: bnkc
avatarUrl: https://avatars.githubusercontent.com/u/34930566?u=fa1dc8db3e920cf5c5636b97180a6f811fa01aaf&v=4
avatarUrl: https://avatars.githubusercontent.com/u/34930566?u=db5e6f4f87836cad26c2aa90ce390ce49041c5a9&v=4
url: https://github.com/bnkc
- login: petercool
avatarUrl: https://avatars.githubusercontent.com/u/37613029?u=81c525232bb35780945a68e88afd96bb2cdad9c4&v=4
url: https://github.com/petercool
- login: DevOpsKev
avatarUrl: https://avatars.githubusercontent.com/u/36336550?u=6ccd5978fdaab06f37e22f2a14a7439341df7f67&v=4
url: https://github.com/DevOpsKev
- login: Zuzah
avatarUrl: https://avatars.githubusercontent.com/u/10934846?u=1ef43e075ddc87bd1178372bf4d95ee6175cae27&v=4
url: https://github.com/Zuzah
- login: JimFawkes
avatarUrl: https://avatars.githubusercontent.com/u/12075115?u=dc58ecfd064d72887c34bf500ddfd52592509acd&v=4
url: https://github.com/JimFawkes
@ -338,9 +344,6 @@ sponsors:
- 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
@ -350,12 +353,15 @@ sponsors:
- 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: zk-Call
avatarUrl: https://avatars.githubusercontent.com/u/147117264?v=4
url: https://github.com/zk-Call
- login: petercool
avatarUrl: https://avatars.githubusercontent.com/u/37613029?u=81c525232bb35780945a68e88afd96bb2cdad9c4&v=4
url: https://github.com/petercool
- login: curegit
avatarUrl: https://avatars.githubusercontent.com/u/37978051?u=1733c322079118c0cdc573c03d92813f50a9faec&v=4
url: https://github.com/curegit
@ -375,11 +381,17 @@ sponsors:
avatarUrl: https://avatars.githubusercontent.com/u/44609997?v=4
url: https://github.com/ArtyomVancyan
- 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: 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: miguelgr
avatarUrl: https://avatars.githubusercontent.com/u/1484589?u=54556072b8136efa12ae3b6902032ea2a39ace4b&v=4
url: https://github.com/miguelgr
@ -419,12 +431,6 @@ sponsors:
- login: securancy
avatarUrl: https://avatars.githubusercontent.com/u/606673?v=4
url: https://github.com/securancy
- 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
@ -470,6 +476,9 @@ sponsors:
- 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,24 +497,24 @@ 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: sadikkuzu
avatarUrl: https://avatars.githubusercontent.com/u/23168063?u=d179c06bb9f65c4167fcab118526819f8e0dac17&v=4
url: https://github.com/sadikkuzu
- login: Mehver
avatarUrl: https://avatars.githubusercontent.com/u/75297777?u=dcd857f4278df055d98cd3486c2ce8bad368eb50&v=4
url: https://github.com/Mehver
- 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: zee229
avatarUrl: https://avatars.githubusercontent.com/u/48365508?u=eac8e8bb968ed3391439a98490d3e6e5f6f2826b&v=4
url: https://github.com/zee229
- login: Patechoc
avatarUrl: https://avatars.githubusercontent.com/u/2376641?u=23b49e9eda04f078cb74fa3f93593aa6a57bb138&v=4
url: https://github.com/Patechoc

File diff suppressed because it is too large Load Diff

View File

@ -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)
```

View File

@ -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:

View File

@ -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**:

View File

@ -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)
```

View File

@ -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)
```

View File

@ -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!

View File

@ -26,6 +26,7 @@
position: relative;
-webkit-box-sizing: border-box;
box-sizing: border-box;
line-height: 1.2;
}
[data-termynal]:before {

View File

@ -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**.

View File

@ -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>
@ -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
@ -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

View File

@ -1,8 +1,68 @@
# 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.
@ -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,6 +103,8 @@ 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.
@ -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.

View File

@ -0,0 +1,84 @@
# FastAPI CLI
**FastAPI CLI** is a command line program `fastapi` 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: [&apos;/home/user/code/awesomeapp&apos;]
<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>
That command line program called `fastapi` is **FastAPI CLI**.
FastAPI CLI takes the path to your Python program and automatically detects the variable with the FastAPI (commonly named `app`) and how to import it, 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`
When you run `fastapi dev`, it will run on development mode.
By default, it will have **auto-reload** enabled, so it will automatically reload the server when you make changes to your code. This is resource intensive and could be less stable than without it, you should only use it for development.
By default it will listen on the IP address `127.0.0.1`, which is the IP for your machine to communicate with itself alone (`localhost`).
## `fastapi run`
When you run `fastapi run`, it will run on production mode by default.
It will have **auto-reload disabled** by default.
It will listen 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}.

View File

@ -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.

View File

@ -36,7 +36,7 @@ hide:
---
FastAPI is a modern, fast (high-performance), web framework for building APIs with Python 3.8+ based on standard Python type hints.
FastAPI is a modern, fast (high-performance), web framework for building APIs with Python based on standard Python type hints.
The key features are:
@ -124,8 +124,6 @@ If you are building a <abbr title="Command Line Interface">CLI</abbr> app to be
## Requirements
Python 3.8+
FastAPI stands on the shoulders of giants:
* <a href="https://www.starlette.io/" class="external-link" target="_blank">Starlette</a> for the web parts.
@ -143,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
@ -215,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.
```
@ -227,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>
@ -306,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
@ -340,7 +339,7 @@ You do that with standard modern Python types.
You don't have to learn a new syntax, the methods or classes of a specific library, etc.
Just standard **Python 3.8+**.
Just standard **Python**.
For example, for an `int`:
@ -450,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:
@ -463,16 +462,33 @@ 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.
* <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`.
* `fastapi-cli` - to provide the `fastapi` command.
You can install all of these with `pip install "fastapi[all]"`.
When you install `fastapi` it comes these standard dependencies.
## `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

View File

@ -7,17 +7,85 @@ hide:
## Latest Changes
* 🌐 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).
### Docs
* ✏️ Fix link in `fastapi-cli.md`. PR [#11524](https://github.com/tiangolo/fastapi/pull/11524) by [@svlandeg](https://github.com/svlandeg).
### Translations
* 🌐 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
* 👷 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).
* ✏️ Fix typo in `fastapi/security/api_key.py`. PR [#11481](https://github.com/tiangolo/fastapi/pull/11481) by [@ch33zer](https://github.com/ch33zer).
* ✏️ Fix typo in `security/http.py`. PR [#11455](https://github.com/tiangolo/fastapi/pull/11455) by [@omarmoo5](https://github.com/omarmoo5).
### Translations
* 🌐 Add Traditional Chinese translation for `docs/zh-hant/benchmarks.md`. PR [#11484](https://github.com/tiangolo/fastapi/pull/11484) by [@KNChiu](https://github.com/KNChiu).
* 🌐 Update Chinese translation for `docs/zh/docs/fastapi-people.md`. PR [#11476](https://github.com/tiangolo/fastapi/pull/11476) by [@billzhong](https://github.com/billzhong).
* 🌐 Add Chinese translation for `docs/zh/docs/how-to/index.md` and `docs/zh/docs/how-to/general.md`. PR [#11443](https://github.com/tiangolo/fastapi/pull/11443) by [@billzhong](https://github.com/billzhong).
* 🌐 Add Spanish translation for cookie-params `docs/es/docs/tutorial/cookie-params.md`. PR [#11410](https://github.com/tiangolo/fastapi/pull/11410) by [@fabianfalon](https://github.com/fabianfalon).
### Internal
* ⬆ Bump mkdocstrings[python] from 0.23.0 to 0.24.3. PR [#11469](https://github.com/tiangolo/fastapi/pull/11469) by [@dependabot[bot]](https://github.com/apps/dependabot).
* 🔨 Update internal scripts and remove unused ones. PR [#11499](https://github.com/tiangolo/fastapi/pull/11499) by [@tiangolo](https://github.com/tiangolo).
* 🔧 Migrate from Hatch to PDM for the internal build. PR [#11498](https://github.com/tiangolo/fastapi/pull/11498) by [@tiangolo](https://github.com/tiangolo).
* ⬆️ Upgrade MkDocs Material and re-enable cards. PR [#11466](https://github.com/tiangolo/fastapi/pull/11466) by [@tiangolo](https://github.com/tiangolo).
* ⬆ Bump pillow from 10.2.0 to 10.3.0. PR [#11403](https://github.com/tiangolo/fastapi/pull/11403) by [@dependabot[bot]](https://github.com/apps/dependabot).
* 🔧 Ungroup dependabot updates. PR [#11465](https://github.com/tiangolo/fastapi/pull/11465) by [@tiangolo](https://github.com/tiangolo).

View File

@ -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: [&apos;/home/user/code/awesomeapp&apos;]
<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

View File

@ -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: [&apos;/home/user/code/awesomeapp&apos;]
<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

View File

@ -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

View File

@ -32,7 +32,7 @@ hide:
**Código Fuente**: <a href="https://github.com/tiangolo/fastapi" target="_blank">https://github.com/tiangolo/fastapi</a>
---
FastAPI es un web framework moderno y rápido (de alto rendimiento) para construir APIs con Python 3.8+ basado en las anotaciones de tipos estándar de Python.
FastAPI es un web framework moderno y rápido (de alto rendimiento) para construir APIs con Python basado en las anotaciones de tipos estándar de Python.
Sus características principales son:
@ -115,8 +115,6 @@ Si estás construyendo un app de <abbr title="Interfaz de línea de comandos en
## Requisitos
Python 3.8+
FastAPI está sobre los hombros de gigantes:
* <a href="https://www.starlette.io/" class="external-link" target="_blank">Starlette</a> para las partes web.
@ -328,7 +326,7 @@ Lo haces con tipos modernos estándar de Python.
No tienes que aprender una sintaxis nueva, los métodos o clases de una library específica, etc.
Solo **Python 3.8+** estándar.
Solo **Python** estándar.
Por ejemplo, para un `int`:

View File

@ -36,7 +36,7 @@ hide:
---
FastAPI est un framework web moderne et rapide (haute performance) pour la création d'API avec Python 3.8+, basé sur les annotations de type standard de Python.
FastAPI est un framework web moderne et rapide (haute performance) pour la création d'API avec Python, basé sur les annotations de type standard de Python.
Les principales fonctionnalités sont :
@ -124,8 +124,6 @@ Si vous souhaitez construire une application <abbr title="Command Line Interface
## Prérequis
Python 3.8+
FastAPI repose sur les épaules de géants :
* <a href="https://www.starlette.io/" class="external-link" target="_blank">Starlette</a> pour les parties web.
@ -340,7 +338,7 @@ Vous faites cela avec les types Python standard modernes.
Vous n'avez pas à apprendre une nouvelle syntaxe, les méthodes ou les classes d'une bibliothèque spécifique, etc.
Juste du **Python 3.8+** standard.
Juste du **Python** standard.
Par exemple, pour un `int`:

View File

@ -26,7 +26,7 @@
**Forrás kód**: <a href="https://github.com/tiangolo/fastapi" target="_blank">https://github.com/tiangolo/fastapi</a>
---
A FastAPI egy modern, gyors (nagy teljesítményű), webes keretrendszer API-ok építéséhez Python 3.8+-al, a Python szabványos típusjelöléseire építve.
A FastAPI egy modern, gyors (nagy teljesítményű), webes keretrendszer API-ok építéséhez Python -al, a Python szabványos típusjelöléseire építve.
Kulcs funkciók:
@ -115,8 +115,6 @@ Ha egy olyan CLI alkalmazást fejlesztesz amit a parancssorban kell használni w
## Követelmények
Python 3.8+
A FastAPI óriások vállán áll:
* <a href="https://www.starlette.io/" class="external-link" target="_blank">Starlette</a> a webes részekhez.
@ -331,7 +329,7 @@ Ezt standard modern Python típusokkal csinálod.
Nem kell új szintaxist, vagy specifikus könyvtár mert metódósait, stb. megtanulnod.
Csak standard **Python 3.8+**.
Csak standard **Python**.
Például egy `int`-nek:

View File

@ -33,7 +33,7 @@ hide:
---
FastAPI は、Pythonの標準である型ヒントに基づいてPython 3.8 以降でAPI を構築するための、モダンで、高速(高パフォーマンス)な、Web フレームワークです。
FastAPI は、Pythonの標準である型ヒントに基づいてPython 以降でAPI を構築するための、モダンで、高速(高パフォーマンス)な、Web フレームワークです。
主な特徴:
@ -116,8 +116,6 @@ FastAPI は、Pythonの標準である型ヒントに基づいてPython 3.8 以
## 必要条件
Python 3.8+
FastAPI は巨人の肩の上に立っています。
- Web の部分は<a href="https://www.starlette.io/" class="external-link" target="_blank">Starlette</a>

View File

@ -33,7 +33,7 @@ hide:
---
FastAPI는 현대적이고, 빠르며(고성능), 파이썬 표준 타입 힌트에 기초한 Python3.8+의 API를 빌드하기 위한 웹 프레임워크입니다.
FastAPI는 현대적이고, 빠르며(고성능), 파이썬 표준 타입 힌트에 기초한 Python의 API를 빌드하기 위한 웹 프레임워크입니다.
주요 특징으로:
@ -116,8 +116,6 @@ FastAPI는 현대적이고, 빠르며(고성능), 파이썬 표준 타입 힌트
## 요구사항
Python 3.8+
FastAPI는 거인들의 어깨 위에 서 있습니다:
* 웹 부분을 위한 <a href="https://www.starlette.io/" class="external-link" target="_blank">Starlette</a>.
@ -332,7 +330,7 @@ def update_item(item_id: int, item: Item):
새로운 문법, 특정 라이브러리의 메소드나 클래스 등을 배울 필요가 없습니다.
그저 표준 **Python 3.8+** 입니다.
그저 표준 **Python** 입니다.
예를 들어, `int`에 대해선:

View File

@ -33,7 +33,7 @@ hide:
---
FastAPI to nowoczesny, wydajny framework webowy do budowania API z użyciem Pythona 3.8+ bazujący na standardowym typowaniu Pythona.
FastAPI to nowoczesny, wydajny framework webowy do budowania API z użyciem Pythona bazujący na standardowym typowaniu Pythona.
Kluczowe cechy:
@ -115,8 +115,6 @@ Jeżeli tworzysz aplikacje <abbr title="aplikacja z interfejsem konsolowym">CLI<
## Wymagania
Python 3.8+
FastAPI oparty jest na:
* <a href="https://www.starlette.io/" class="external-link" target="_blank">Starlette</a> dla części webowej.
@ -330,7 +328,7 @@ Robisz to tak samo jak ze standardowymi typami w Pythonie.
Nie musisz sie uczyć żadnej nowej składni, metod lub klas ze specyficznych bibliotek itp.
Po prostu standardowy **Python 3.8+**.
Po prostu standardowy **Python**.
Na przykład, dla danych typu `int`:

View File

@ -33,7 +33,7 @@ hide:
---
FastAPI é um moderno e rápido (alta performance) _framework web_ para construção de APIs com Python 3.8 ou superior, baseado nos _type hints_ padrões do Python.
FastAPI é um moderno e rápido (alta performance) _framework web_ para construção de APIs com Python, baseado nos _type hints_ padrões do Python.
Os recursos chave são:
@ -109,8 +109,6 @@ Se você estiver construindo uma aplicação <abbr title="Command Line Interface
## Requisitos
Python 3.8+
FastAPI está nos ombros de gigantes:
* <a href="https://www.starlette.io/" class="external-link" target="_blank">Starlette</a> para as partes web.
@ -325,7 +323,7 @@ Você faz com tipos padrão do Python moderno.
Você não terá que aprender uma nova sintaxe, métodos ou classes de uma biblioteca específica etc.
Apenas **Python 3.8+** padrão.
Apenas **Python** padrão.
Por exemplo, para um `int`:

View File

@ -36,7 +36,7 @@ hide:
---
FastAPI — это современный, быстрый (высокопроизводительный) веб-фреймворк для создания API используя Python 3.8+, в основе которого лежит стандартная аннотация типов Python.
FastAPI — это современный, быстрый (высокопроизводительный) веб-фреймворк для создания API используя Python, в основе которого лежит стандартная аннотация типов Python.
Ключевые особенности:
@ -118,8 +118,6 @@ FastAPI — это современный, быстрый (высокопрои
## Зависимости
Python 3.8+
FastAPI стоит на плечах гигантов:
* <a href="https://www.starlette.io/" class="external-link" target="_blank">Starlette</a> для части связанной с вебом.
@ -334,7 +332,7 @@ def update_item(item_id: int, item: Item):
Вам не нужно изучать новый синтаксис, методы или классы конкретной библиотеки и т. д.
Только стандартный **Python 3.8+**.
Только стандартный **Python**.
Например, для `int`:

View File

@ -36,7 +36,7 @@ hide:
---
FastAPI, Python <abbr title="Python 3.8 ve üzeri">3.8+</abbr>'nin standart <abbr title="Tip Belirteçleri: Type Hints">tip belirteçleri</abbr>ne dayalı, modern ve hızlı (yüksek performanslı) API'lar oluşturmak için kullanılabilecek web framework'tür.
FastAPI, Python 'nin standart <abbr title="Tip Belirteçleri: Type Hints">tip belirteçleri</abbr>ne dayalı, modern ve hızlı (yüksek performanslı) API'lar oluşturmak için kullanılabilecek web framework'tür.
Temel özellikleri şunlardır:
@ -124,8 +124,6 @@ Eğer API yerine, terminalde kullanılmak üzere bir <abbr title="Komut Satırı
## Gereksinimler
Python 3.8+
FastAPI iki devin omuzları üstünde duruyor:
* Web tarafı için <a href="https://www.starlette.io/" class="external-link" target="_blank">Starlette</a>.
@ -340,7 +338,7 @@ Bu işlemi standart modern Python tipleriyle yapıyoruz.
Yeni bir sözdizimi yapısını, bir kütüphane özel metod veya sınıfları öğrenmeye gerek yoktur.
Hepsi sadece **Python 3.8+** standartlarına dayalıdır.
Hepsi sadece **Python** standartlarına dayalıdır.
Örnek olarak, `int` tanımlamak için:

View File

@ -0,0 +1,92 @@
# Form Verisi
İstek gövdesinde JSON verisi yerine form alanlarını karşılamanız gerketiğinde `Form` sınıfını kullanabilirsiniz.
!!! info "Bilgi"
Formları kullanmak için öncelikle <a href="https://github.com/Kludex/python-multipart" class="external-link" target="_blank">`python-multipart`</a> paketini indirmeniz gerekmektedir.
Örneğin `pip install python-multipart`.
## `Form` Sınıfını Projenize Dahil Edin
`Form` sınıfını `fastapi`'den projenize dahil edin:
=== "Python 3.9+"
```Python hl_lines="3"
{!> ../../../docs_src/request_forms/tutorial001_an_py39.py!}
```
=== "Python 3.8+"
```Python hl_lines="1"
{!> ../../../docs_src/request_forms/tutorial001_an.py!}
```
=== "Python 3.8+ non-Annotated"
!!! tip
Prefer to use the `Annotated` version if possible.
```Python hl_lines="1"
{!> ../../../docs_src/request_forms/tutorial001.py!}
```
## `Form` Parametrelerini Tanımlayın
Form parametrelerini `Body` veya `Query` için yaptığınız gibi oluşturun:
=== "Python 3.9+"
```Python hl_lines="9"
{!> ../../../docs_src/request_forms/tutorial001_an_py39.py!}
```
=== "Python 3.8+"
```Python hl_lines="8"
{!> ../../../docs_src/request_forms/tutorial001_an.py!}
```
=== "Python 3.8+ non-Annotated"
!!! tip
Prefer to use the `Annotated` version if possible.
```Python hl_lines="7"
{!> ../../../docs_src/request_forms/tutorial001.py!}
```
Örneğin, OAuth2 spesifikasyonunun kullanılabileceği ("şifre akışı" olarak adlandırılan) yollardan birinde, form alanları olarak <abbr title="Kullanıcı Adı: Username">"username"</abbr> ve <abbr title="Şifre: Password">"password"</abbr> gönderilmesi gerekir.
Bu <abbr title="Spesifikasyon: Specification">spesifikasyon</abbr> form alanlarını adlandırırken isimlerinin birebir `username` ve `password` olmasını ve JSON verisi yerine form verisi olarak gönderilmesini gerektirir.
`Form` sınıfıyla tanımlama yaparken `Body`, `Query`, `Path` ve `Cookie` sınıflarında kullandığınız aynı validasyon, örnekler, isimlendirme (örneğin `username` yerine `user-name` kullanımı) ve daha fazla konfigurasyonu kullanabilirsiniz.
!!! info "Bilgi"
`Form` doğrudan `Body` sınıfını miras alan bir sınıftır.
!!! tip "İpucu"
Form gövdelerini tanımlamak için `Form` sınıfını kullanmanız gerekir; çünkü bu olmadan parametreler sorgu parametreleri veya gövde (JSON) parametreleri olarak yorumlanır.
## "Form Alanları" Hakkında
HTML formlarının (`<form></form>`) verileri sunucuya gönderirken JSON'dan farklı özel bir kodlama kullanır.
**FastAPI** bu verilerin JSON yerine doğru şekilde okunmasını sağlayacaktır.
!!! note "Teknik Detaylar"
Form verileri normalde `application/x-www-form-urlencoded` medya tipiyle kodlanır.
Ancak form içerisinde dosyalar yer aldığında `multipart/form-data` olarak kodlanır. Bir sonraki bölümde dosyaların işlenmesi hakkında bilgi edineceksiniz.
Form kodlama türleri ve form alanları hakkında daha fazla bilgi edinmek istiyorsanız <a href="https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods/POST" class="external-link" target="_blank"><abbr title="Mozilla Developer Network">MDN</abbr> web docs for <code>POST</code></a> sayfasını ziyaret edebilirsiniz.
!!! warning "Uyarı"
*Yol operasyonları* içerisinde birden fazla `Form` parametresi tanımlayabilirsiniz ancak bunlarla birlikte JSON verisi kabul eden `Body` alanları tanımlayamazsınız çünkü bu durumda istek gövdesi `application/json` yerine `application/x-www-form-urlencoded` ile kodlanmış olur.
Bu **FastAPI**'ın getirdiği bir kısıtlama değildir, HTTP protokolünün bir parçasıdır.
## Özet
Form verisi girdi parametreleri tanımlamak için `Form` sınıfını kullanın.

View File

@ -27,7 +27,7 @@
---
FastAPI - це сучасний, швидкий (високопродуктивний), вебфреймворк для створення API за допомогою Python 3.8+,в основі якого лежить стандартна анотація типів Python.
FastAPI - це сучасний, швидкий (високопродуктивний), вебфреймворк для створення API за допомогою Python,в основі якого лежить стандартна анотація типів Python.
Ключові особливості:
@ -110,8 +110,6 @@ FastAPI - це сучасний, швидкий (високопродуктив
## Вимоги
Python 3.8+
FastAPI стоїть на плечах гігантів:
* <a href="https://www.starlette.io/" class="external-link" target="_blank">Starlette</a> для web частини.
@ -326,7 +324,7 @@ def update_item(item_id: int, item: Item):
Вам не потрібно вивчати новий синтаксис, методи чи класи конкретної бібліотеки тощо.
Використовуючи стандартний **Python 3.8+**.
Використовуючи стандартний **Python**.
Наприклад, для `int`:

View File

@ -36,7 +36,7 @@ hide:
---
FastAPI là một web framework hiện đại, hiệu năng cao để xây dựng web APIs với Python 3.8+ dựa trên tiêu chuẩn Python type hints.
FastAPI là một web framework hiện đại, hiệu năng cao để xây dựng web APIs với Python dựa trên tiêu chuẩn Python type hints.
Những tính năng như:
@ -125,8 +125,6 @@ Nếu bạn đang xây dựng một <abbr title="Giao diện dòng lệnh">CLI</
## Yêu cầu
Python 3.8+
FastAPI đứng trên vai những người khổng lồ:
* <a href="https://www.starlette.io/" class="external-link" target="_blank">Starlette</a> cho phần web.
@ -341,7 +339,7 @@ Bạn định nghĩa bằng cách sử dụng các kiểu dữ liệu chuẩn c
Bạn không phải học một cú pháp mới, các phương thức và class của một thư viện cụ thể nào.
Chỉ cần sử dụng các chuẩn của **Python 3.8+**.
Chỉ cần sử dụng các chuẩn của **Python**.
Ví dụ, với một tham số kiểu `int`:

View File

@ -36,7 +36,7 @@ hide:
---
FastAPI jẹ́ ìgbàlódé, tí ó yára (iṣẹ-giga), ìlànà wẹ́ẹ́bù fún kikọ àwọn API pẹ̀lú Python 3.8+ èyí tí ó da lori àwọn ìtọ́kasí àmì irúfẹ́ Python.
FastAPI jẹ́ ìgbàlódé, tí ó yára (iṣẹ-giga), ìlànà wẹ́ẹ́bù fún kikọ àwọn API pẹ̀lú Python èyí tí ó da lori àwọn ìtọ́kasí àmì irúfẹ́ Python.
Àwọn ẹya pàtàkì ni:
@ -124,8 +124,6 @@ Ti o ba n kọ ohun èlò <abbr title="Command Line Interface">CLI</abbr> láti
## Èròjà
Python 3.8+
FastAPI dúró lórí àwọn èjìká tí àwọn òmíràn:
* <a href="https://www.starlette.io/" class="external-link" target="_blank">Starlette</a> fún àwọn ẹ̀yà ayélujára.
@ -340,7 +338,7 @@ O ṣe ìyẹn pẹ̀lú irúfẹ́ àmì ìtọ́kasí ìgbàlódé Python.
O ò nílò láti kọ́ síńtáàsì tuntun, ìlànà tàbí ọ̀wọ́ kíláàsì kan pàtó, abbl (i.e. àti bẹbẹ lọ).
Ìtọ́kasí **Python 3.8+**
Ìtọ́kasí **Python**
Fún àpẹẹrẹ, fún `int`:

View File

@ -0,0 +1,34 @@
# 基準測試
由第三方機構 TechEmpower 的基準測試表明在 Uvicorn 下運行的 **FastAPI** 應用程式是 <a href="https://www.techempower.com/benchmarks/#section=test&runid=7464e520-0dc2-473d-bd34-dbdfd7e85911&hw=ph&test=query&l=zijzen-7" class="external-link" target="_blank">最快的 Python 可用框架之一</a>,僅次於 Starlette 和 Uvicorn 本身(於 FastAPI 內部使用)。
但是在查看基準得分和對比時,請注意以下幾點。
## 基準測試和速度
當你查看基準測試時,時常會見到幾個不同類型的工具被同時進行測試。
具體來說,是將 Uvicorn、Starlette 和 FastAPI 同時進行比較(以及許多其他工具)。
該工具解決的問題越簡單,其效能就越好。而且大多數基準測試不會測試該工具提供的附加功能。
層次結構如下:
* **Uvicorn**ASGI 伺服器
* **Starlette**:(使用 Uvicorn一個網頁微框架
* **FastAPI**:(使用 Starlette一個 API 微框架,具有用於建立 API 的多個附加功能、資料驗證等。
* **Uvicorn**
* 具有最佳效能,因為除了伺服器本身之外,它沒有太多額外的程式碼。
* 你不會直接在 Uvicorn 中編寫應用程式。這意味著你的程式碼必須或多或少地包含 Starlette或 **FastAPI**)提供的所有程式碼。如果你這樣做,你的最終應用程式將具有與使用框架相同的開銷並最大限度地減少應用程式程式碼和錯誤。
* 如果你要比較 Uvicorn請將其與 Daphne、Hypercorn、uWSGI 等應用程式伺服器進行比較。
* **Starlette**
* 繼 Uvicorn 之後的次佳表現。事實上Starlette 使用 Uvicorn 來運行。因此它將可能只透過執行更多程式碼而變得比 Uvicorn「慢」。
* 但它為你提供了建立簡單網頁應用程式的工具,以及基於路徑的路由等。
* 如果你要比較 Starlette請將其與 Sanic、Flask、Django 等網頁框架(或微框架)進行比較。
* **FastAPI**
* 就像 Starlette 使用 Uvicorn 並不能比它更快一樣, **FastAPI** 使用 Starlette所以它不能比它更快。
* FastAPI 在 Starlette 基礎之上提供了更多功能。包含建構 API 時所需要的功能例如資料驗證和序列化。FastAPI 可以幫助你自動產生 API 文件,(應用程式啟動時將會自動生成文件,所以不會增加應用程式運行時的開銷)。
* 如果你沒有使用 FastAPI 而是直接使用 Starlette或其他工具如 Sanic、Flask、Responder 等),你將必須自行實現所有資料驗證和序列化。因此,你的最終應用程式仍然具有與使用 FastAPI 建置相同的開銷。在許多情況下,這種資料驗證和序列化是應用程式中編寫最大量的程式碼。
* 因此透過使用 FastAPI你可以節省開發時間、錯誤與程式碼數量並且相比不使用 FastAPI 你很大可能會獲得相同或更好的效能(因為那樣你必須在程式碼中實現所有相同的功能)。
* 如果你要與 FastAPI 比較,請將其與能夠提供資料驗證、序列化和文件的網頁應用程式框架(或工具集)進行比較,例如 Flask-apispec、NestJS、Molten 等框架。

View File

@ -27,7 +27,7 @@
---
FastAPI 是一個現代、快速(高效能)的 web 框架,用於 Python 3.8+ 並採用標準 Python 型別提示。
FastAPI 是一個現代、快速(高效能)的 web 框架,用於 Python 並採用標準 Python 型別提示。
主要特點包含:
@ -115,8 +115,6 @@ FastAPI 是一個現代、快速(高效能)的 web 框架,用於 Python 3.
## 安裝需求
Python 3.8+
FastAPI 是站在以下巨人的肩膀上:
- <a href="https://www.starlette.io/" class="external-link" target="_blank">Starlette</a> 負責網頁的部分
@ -331,7 +329,7 @@ def update_item(item_id: int, item: Item):
你不需要學習新的語法、類別、方法或函式庫等等。
只需要使用 **Python 3.8 以上的版本**。
只需要使用 **Python 以上的版本**。
舉個範例,比如宣告 int 的型別:

View File

@ -14,15 +14,32 @@ HTTP 基础授权让浏览器显示内置的用户名与密码提示。
## 简单的 HTTP 基础授权
* 导入 `HTTPBsic` 与 `HTTPBasicCredentials`
* 使用 `HTTPBsic` 创建**安全概图**
* 导入 `HTTPBasic` 与 `HTTPBasicCredentials`
* 使用 `HTTPBasic` 创建**安全概图**
* 在*路径操作*的依赖项中使用 `security`
* 返回类型为 `HTTPBasicCredentials` 的对象:
* 包含发送的 `username``password`
```Python hl_lines="2 6 10"
{!../../../docs_src/security/tutorial006.py!}
```
=== "Python 3.9+"
```Python hl_lines="4 8 12"
{!> ../../../docs_src/security/tutorial006_an_py39.py!}
```
=== "Python 3.8+"
```Python hl_lines="2 7 11"
{!> ../../../docs_src/security/tutorial006_an.py!}
```
=== "Python 3.8+ non-Annotated"
!!! tip
尽可能选择使用 `Annotated` 的版本。
```Python hl_lines="2 6 10"
{!> ../../../docs_src/security/tutorial006.py!}
```
第一次打开 URL或在 API 文档中点击 **Execute** 按钮)时,浏览器要求输入用户名与密码:
@ -34,13 +51,35 @@ HTTP 基础授权让浏览器显示内置的用户名与密码提示。
使用依赖项检查用户名与密码是否正确。
为此要使用 Python 标准模块 <a href="https://docs.python.org/3/library/secrets.html" class="external-link" target="_blank">`secrets`</a> 检查用户名与密码
为此要使用 Python 标准模块 <a href="https://docs.python.org/3/library/secrets.html" class="external-link" target="_blank">`secrets`</a> 检查用户名与密码
```Python hl_lines="1 11-13"
{!../../../docs_src/security/tutorial007.py!}
```
`secrets.compare_digest()` 需要仅包含 ASCII 字符(英语字符)的 `bytes``str`,这意味着它不适用于像`á`一样的字符,如 `Sebastián`
这段代码确保 `credentials.username``"stanleyjobson"`,且 `credentials.password` 是`"swordfish"`。与以下代码类似:
为了解决这个问题,我们首先将 `username``password` 转换为使用 UTF-8 编码的 `bytes`
然后我们可以使用 `secrets.compare_digest()` 来确保 `credentials.username``"stanleyjobson"`,且 `credentials.password` 是`"swordfish"`。
=== "Python 3.9+"
```Python hl_lines="1 12-24"
{!> ../../../docs_src/security/tutorial007_an_py39.py!}
```
=== "Python 3.8+"
```Python hl_lines="1 12-24"
{!> ../../../docs_src/security/tutorial007_an.py!}
```
=== "Python 3.8+ non-Annotated"
!!! tip
尽可能选择使用 `Annotated` 的版本。
```Python hl_lines="1 11-21"
{!> ../../../docs_src/security/tutorial007.py!}
```
这类似于:
```Python
if not (credentials.username == "stanleyjobson") or not (credentials.password == "swordfish"):
@ -102,6 +141,23 @@ if "stanleyjobsox" == "stanleyjobson" and "love123" == "swordfish":
检测到凭证不正确后,返回 `HTTPException` 及状态码 401与无凭证时返回的内容一样并添加请求头 `WWW-Authenticate`,让浏览器再次显示登录提示:
```Python hl_lines="15-19"
{!../../../docs_src/security/tutorial007.py!}
```
=== "Python 3.9+"
```Python hl_lines="26-30"
{!> ../../../docs_src/security/tutorial007_an_py39.py!}
```
=== "Python 3.8+"
```Python hl_lines="26-30"
{!> ../../../docs_src/security/tutorial007_an.py!}
```
=== "Python 3.8+ non-Annotated"
!!! tip
尽可能选择使用 `Annotated` 的版本。
```Python hl_lines="23-27"
{!> ../../../docs_src/security/tutorial007.py!}
```

View File

@ -33,39 +33,98 @@ FastAPI 有一个非常棒的社区,它欢迎来自各个领域和背景的朋
这些人:
* [帮助他人解决 GitHub 的 issues](help-fastapi.md#github_1){.internal-link target=_blank}。
* [帮助他人解决 GitHub 上的问题](help-fastapi.md#github_1){.internal-link target=_blank}。
* [创建 Pull Requests](help-fastapi.md#pr){.internal-link target=_blank}。
* 审核 Pull Requests 对于 [翻译](contributing.md#_8){.internal-link target=_blank} 尤为重要。
向他们致以掌声。 👏 🙇
## 上个月最活跃的用户
## FastAPI 专家
上个月这些用户致力于 [帮助他人解决 GitHub 的 issues](help-fastapi.md#github_1){.internal-link target=_blank}。
这些用户一直以来致力于 [帮助他人解决 GitHub 上的问题](help-fastapi.md#github_1){.internal-link target=_blank}。 🙇
他们通过帮助许多人而被证明是 **FastAPI 专家**。 ✨
!!! 小提示
你也可以成为认可的 FastAPI 专家!
只需要 [帮助他人解决 GitHub 上的问题](help-fastapi.md#github_1){.internal-link target=_blank}。 🤓
你可以查看不同时期的 **FastAPI 专家**
* [上个月](#fastapi-experts-last-month) 🤓
* [三个月](#fastapi-experts-3-months) 😎
* [六个月](#fastapi-experts-6-months) 🧐
* [一年](#fastapi-experts-1-year) 🧑‍🔬
* [**全部时间**](#fastapi-experts-all-time) 🧙
## FastAPI 专家 - 上个月
这些是在过去一个月中 [在 GitHub 上帮助他人解答最多问题](help-fastapi.md#github_1){.internal-link target=_blank} 的用户。 🤓
{% if people %}
<div class="user-list user-list-center">
{% for user in people.last_month_experts[:10] %}
<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">Issues replied: {{ user.count }}</div></div>
<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">回答问题数: {{ user.count }}</div></div>
{% endfor %}
</div>
{% endif %}
## 专家组
### FastAPI 专家 - 三个月
以下是 **FastAPI 专家**。 🤓
这些是在过去三个月中 [在 GitHub 上帮助他人解答最多问题](help-fastapi.md#github_1){.internal-link target=_blank} 的用户。 😎
这些用户一直以来致力于 [帮助他人解决 GitHub 的 issues](help-fastapi.md#github_1){.internal-link target=_blank}。
{% if people %}
<div class="user-list user-list-center">
{% for user in people.three_months_experts[:10] %}
他们通过帮助许多人而被证明是专家。✨
<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">回答问题数: {{ user.count }}</div></div>
{% endfor %}
</div>
{% endif %}
### FastAPI 专家 - 六个月
这些是在过去六个月中 [在 GitHub 上帮助他人解答最多问题](help-fastapi.md#github_1){.internal-link target=_blank} 的用户。 🧐
{% if people %}
<div class="user-list user-list-center">
{% for user in people.six_months_experts[:10] %}
<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">回答问题数: {{ user.count }}</div></div>
{% endfor %}
</div>
{% endif %}
### FastAPI 专家 - 一年
这些是在过去一年中 [在 GitHub 上帮助他人解答最多问题](help-fastapi.md#github_1){.internal-link target=_blank} 的用户。 🧑‍🔬
{% if people %}
<div class="user-list user-list-center">
{% for user in people.one_year_experts[:20] %}
<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">回答问题数: {{ user.count }}</div></div>
{% endfor %}
</div>
{% endif %}
## FastAPI 专家 - 全部时间
以下是全部时间的 **FastAPI 专家**。 🤓🤯
这些用户一直以来致力于 [帮助他人解决 GitHub 的 上的问题](help-fastapi.md#github_1){.internal-link target=_blank}。 🧙
{% if people %}
<div class="user-list user-list-center">
{% for user in people.experts[:50] %}
<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">Issues replied: {{ user.count }}</div></div>
<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">回答问题数: {{ user.count }}</div></div>
{% endfor %}
</div>
@ -89,25 +148,19 @@ FastAPI 有一个非常棒的社区,它欢迎来自各个领域和背景的朋
</div>
{% endif %}
还有很多其他贡献者超过100个你可以在 <a href="https://github.com/tiangolo/fastapi/graphs/contributors" class="external-link" target="_blank">FastAPI GitHub 贡献者页面</a> 中看到他们。👷
还有很多别的贡献者超过100个你可以在 <a href="https://github.com/tiangolo/fastapi/graphs/contributors" class="external-link" target="_blank">FastAPI GitHub 贡献者页面</a> 中看到他们。👷
## 杰出审核者
## 杰出翻译审核者
以下用户是「杰出的评审者」。 🕵️
以下用户是 **杰出的评审者**。 🕵️
### 翻译审核
我只会说少数几种语言(而且还不是很流利 😅)。所以,具备[能力去批准文档翻译](contributing.md#_8){.internal-link target=_blank} 是这些评审者们。如果没有它们,就不会有多语言文档。
---
**杰出的评审者** 🕵️ 评审了最多来自他人的 Pull Requests他们保证了代码、文档尤其是 **翻译** 的质量。
我只会说少数几种语言(而且还不是很流利 😅)。所以这些评审者们具备[能力去批准文档翻译](contributing.md#_8){.internal-link target=_blank}。如果没有他们,就不会有多语言文档。
{% if people %}
<div class="user-list user-list-center">
{% for user in people.top_translations_reviewers[:50] %}
<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">Reviews: {{ user.count }}</div></div>
<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">审核数: {{ user.count }}</div></div>
{% endfor %}
</div>

View File

@ -0,0 +1,78 @@
# 配置 Swagger UI
你可以配置一些额外的 <a href="https://swagger.io/docs/open-source-tools/swagger-ui/usage/configuration" class="external-link" target="_blank">Swagger UI 参数</a>.
如果需要配置它们,可以在创建 `FastAPI()` 应用对象时或调用 `get_swagger_ui_html()` 函数时传递 `swagger_ui_parameters` 参数。
`swagger_ui_parameters` 接受一个直接传递给 Swagger UI的字典包含配置参数键值对。
FastAPI会将这些配置转换为 **JSON**,使其与 JavaScript 兼容,因为这是 Swagger UI 需要的。
## 不使用语法高亮
比如,你可以禁用 Swagger UI 中的语法高亮。
当没有改变设置时,语法高亮默认启用:
<img src="/img/tutorial/extending-openapi/image02.png">
但是你可以通过设置 `syntaxHighlight``False` 来禁用 Swagger UI 中的语法高亮:
```Python hl_lines="3"
{!../../../docs_src/configure_swagger_ui/tutorial001.py!}
```
...在此之后Swagger UI 将不会高亮代码:
<img src="/img/tutorial/extending-openapi/image03.png">
## 改变主题
同样地,你也可以通过设置键 `"syntaxHighlight.theme"` 来设置语法高亮主题(注意中间有一个点):
```Python hl_lines="3"
{!../../../docs_src/configure_swagger_ui/tutorial002.py!}
```
这个配置会改变语法高亮主题:
<img src="/img/tutorial/extending-openapi/image04.png">
## 改变默认 Swagger UI 参数
FastAPI 包含了一些默认配置参数,适用于大多数用例。
其包括这些默认配置参数:
```Python
{!../../../fastapi/openapi/docs.py[ln:7-23]!}
```
你可以通过在 `swagger_ui_parameters` 中设置不同的值来覆盖它们。
比如,如果要禁用 `deepLinking`,你可以像这样传递设置到 `swagger_ui_parameters` 中:
```Python hl_lines="3"
{!../../../docs_src/configure_swagger_ui/tutorial003.py!}
```
## 其他 Swagger UI 参数
查看其他 Swagger UI 参数,请阅读 <a href="https://swagger.io/docs/open-source-tools/swagger-ui/usage/configuration" class="external-link" target="_blank">docs for Swagger UI parameters</a>
## JavaScript-only 配置
Swagger UI 同样允许使用 **JavaScript-only** 配置对象例如JavaScript 函数)。
FastAPI 包含这些 JavaScript-only 的 `presets` 设置:
```JavaScript
presets: [
SwaggerUIBundle.presets.apis,
SwaggerUIBundle.SwaggerUIStandalonePreset
]
```
这些是 **JavaScript** 对象,而不是字符串,所以你不能直接从 Python 代码中传递它们。
如果你需要像这样使用 JavaScript-only 配置,你可以使用上述方法之一。覆盖所有 Swagger UI *path operation* 并手动编写任何你需要的 JavaScript。

View File

@ -36,7 +36,7 @@ hide:
---
FastAPI 是一个用于构建 API 的现代、快速(高性能)的 web 框架,使用 Python 3.8+ 并基于标准的 Python 类型提示。
FastAPI 是一个用于构建 API 的现代、快速(高性能)的 web 框架,使用 Python 并基于标准的 Python 类型提示。
关键特性:
@ -119,7 +119,7 @@ FastAPI 是一个用于构建 API 的现代、快速(高性能)的 web 框
## 依赖
Python 3.8 及更高版本
Python 及更高版本
FastAPI 站在以下巨人的肩膀之上:
@ -335,7 +335,7 @@ def update_item(item_id: int, item: Item):
你不需要去学习新的语法、了解特定库的方法或类,等等。
只需要使用标准的 **Python 3.8 及更高版本**。
只需要使用标准的 **Python 及更高版本**。
举个例子,比如声明 `int` 类型:

View File

@ -1,12 +1,19 @@
# SQL (关系型) 数据库
!!! info
这些文档即将被更新。🎉
当前版本假设Pydantic v1和SQLAlchemy版本小于2。
新的文档将包括Pydantic v2以及 <a href="https://sqlmodel.tiangolo.com/" class="external-link" target="_blank">SQLModel</a>也是基于SQLAlchemy一旦SQLModel更新为为使用Pydantic v2。
**FastAPI**不需要你使用SQL(关系型)数据库。
但是您可以使用任何您想要的关系型数据库。
在这里,让我们看一个使用着[SQLAlchemy](https://www.sqlalchemy.org/)的示例。
您可以很容易地将SQLAlchemy支持任何数据库
您可以很容易地将其调整为任何SQLAlchemy支持的数据库
* PostgreSQL
* MySQL
@ -74,13 +81,13 @@ ORM 具有在代码和数据库表(“*关系型”)中的**对象**之间
└── schemas.py
```
该文件`__init__.py`只是一个空文件,但它告诉 Python 其中`sql_app`的所有模块Python 文件)都是一个包。
该文件`__init__.py`只是一个空文件,但它告诉 Python `sql_app` 是一个包。
现在让我们看看每个文件/模块的作用。
## 安装 SQLAlchemy
先下载`SQLAlchemy`所需要的依赖:
首先你需要安装`SQLAlchemy`:
<div class="termy">
@ -152,17 +159,17 @@ connect_args={"check_same_thread": False}
这是为了防止意外地为不同的事物(不同的请求)共享相同的连接。
但是在 FastAPI 中,普遍使用def函数,多个线程可以为同一个请求与数据库交互,所以我们需要使用`connect_args={"check_same_thread": False}`来让SQLite允许这样。
但是在 FastAPI 中,使用普通函数def,多个线程可以为同一个请求与数据库交互,所以我们需要使用`connect_args={"check_same_thread": False}`来让SQLite允许这样。
此外,我们将确保每个请求都在依赖项中获得自己的数据库连接会话,因此不需要该默认机制。
### 创建一个`SessionLocal`类
每个实例`SessionLocal`都会是一个数据库会话。当然该类本身还不是数据库会话。
每个`SessionLocal`类的实例都会是一个数据库会话。当然该类本身还不是数据库会话。
但是一旦我们创建了一个`SessionLocal`类的实例,这个实例将是实际的数据库会话。
我们命名它是`SessionLocal`为了将它与我们从 SQLAlchemy 导入的`Session`区别开来。
我们将它命名为`SessionLocal`是为了将它与我们从 SQLAlchemy 导入的`Session`区别开来。
稍后我们将使用`Session`(从 SQLAlchemy 导入的那个)。
@ -176,7 +183,7 @@ connect_args={"check_same_thread": False}
现在我们将使用`declarative_base()`返回一个类。
稍后我们将用这个类继承来创建每个数据库模型或类ORM 模型):
稍后我们将继承这个类来创建每个数据库模型或类ORM 模型):
```Python hl_lines="13"
{!../../../docs_src/sql_databases/sql_app/database.py!}
@ -209,7 +216,7 @@ connect_args={"check_same_thread": False}
### 创建模型属性/列
现在创建所有模型(类)属性。
现在创建所有模型(类)属性。
这些属性中的每一个都代表其相应数据库表中的一列。
@ -252,13 +259,13 @@ connect_args={"check_same_thread": False}
### 创建初始 Pydantic*模型*/模式
创建一个`ItemBase`和`UserBase`Pydantic*模型*或者我们说“schema”以及在创建或读取数据时具有共同的属性。
创建一个`ItemBase`和`UserBase`Pydantic*模型*或者我们说“schema”,他们拥有创建或读取数据时具有的共同属性。
`ItemCreate`为 创建一个`UserCreate`继承自它们的所有属性(因此它们将具有相同的属性),以及创建所需的任何其他数据(属性)。
然后创建一个继承自他们的`ItemCreate`和`UserCreate`,并添加创建时所需的其他数据(或属性)。
因此在创建时也应当有一个`password`属性。
但是为了安全起见,`password`不会出现在其他同类 Pydantic*模型*中,例如用户请求时不应该从 API 返回响应中包含它
但是为了安全起见,`password`不会出现在其他同类 Pydantic*模型*中,例如通过API读取一个用户数据时它不应当包含在内
=== "Python 3.10+"
@ -368,7 +375,7 @@ Pydantic`orm_mode`将告诉 Pydantic*模型*读取数据,即它不是一个`di
id = data["id"]
```
尝试从属性中获取它,如:
它还会尝试从属性中获取它,如:
```Python
id = data.id
@ -404,7 +411,7 @@ current_user.items
在这个文件中,我们将编写可重用的函数用来与数据库中的数据进行交互。
**CRUD**分别为:**增加**、**查询**、**更改**和**删除**,即增删改查。
**CRUD**分别为:增加(**C**reate、查询**R**ead、更改**U**pdate、删除**D**elete,即增删改查。
...虽然在这个例子中我们只是新增和查询。
@ -414,7 +421,7 @@ current_user.items
导入之前的`models`SQLAlchemy 模型)和`schemas`Pydantic*模型*/模式)。
创建一些实用函数来完成:
创建一些工具函数来完成:
* 通过 ID 和电子邮件查询单个用户。
* 查询多个用户。
@ -429,14 +436,14 @@ current_user.items
### 创建数据
现在创建实用程序函数来创建数据。
现在创建工具函数来创建数据。
它的步骤是:
* 使用您的数据创建一个 SQLAlchemy 模型*实例。*
* 使用`add`来将该实例对象添加到您的数据库。
* 使用`commit`来对数据库的事务提交(以便保存它们)。
* 使用`refresh`来刷新您的数据库实例(以便它包含来自数据库的任何新数据,例如生成的 ID
* 使用`add`来将该实例对象添加到数据库会话
* 使用`commit`来将更改提交到数据库(以便保存它们)。
* 使用`refresh`来刷新您的实例对象(以便它包含来自数据库的任何新数据,例如生成的 ID
```Python hl_lines="18-24 31-36"
{!../../../docs_src/sql_databases/sql_app/crud.py!}
@ -505,11 +512,11 @@ current_user.items
现在使用我们在`sql_app/database.py`文件中创建的`SessionLocal`来创建依赖项。
我们需要每个请求有一个独立的数据库会话/连接(`SessionLocal`),在所有请求中使用相同的会话,然后在请求完成后关闭它。
我们需要每个请求有一个独立的数据库会话/连接(`SessionLocal`),在整个请求中使用相同的会话,然后在请求完成后关闭它。
然后将为下一个请求创建一个新会话。
为此,我们将创建一个新的依赖项`yield`,正如前面关于[Dependencies with`yield`](https://fastapi.tiangolo.com/zh/tutorial/dependencies/dependencies-with-yield/)的部分中所解释的那样。
为此,我们将创建一个包含`yield`的依赖项,正如前面关于[Dependencies with`yield`](https://fastapi.tiangolo.com/zh/tutorial/dependencies/dependencies-with-yield/)的部分中所解释的那样。
我们的依赖项将创建一个新的 SQLAlchemy `SessionLocal`,它将在单个请求中使用,然后在请求完成后关闭它。
@ -729,13 +736,13 @@ $ uvicorn sql_app.main:app --reload
## 中间件替代数据库会话
如果你不能使用依赖项`yield`——例如,如果你没有使用**Python 3.7**并且不能安装上面提到的**Python 3.6**的“backports” ——你可以在类似的“中间件”中设置会话方法
如果你不能使用带有`yield`的依赖项——例如,如果你没有使用**Python 3.7**并且不能安装上面提到的**Python 3.6**的“backports” ——你可以使用类似的方法在“中间件”中设置会话
“中间件”基本功能是一个为每个请求执行的函数在请求之前进行执行相应的代码,以及在请求执行之后执行相应的代码
“中间件”基本上是一个对每个请求都执行的函数,其中一些代码在端点函数之前执行,另一些代码在端点函数之后执行
### 创建中间件
我们将添加中间件(只是一个函数)将为每个请求创建一个新的 SQLAlchemy`SessionLocal`,将其添加到请求中,然后在请求完成后关闭它。
我们要添加的中间件(只是一个函数)将为每个请求创建一个新的 SQLAlchemy`SessionLocal`,将其添加到请求中,然后在请求完成后关闭它。
=== "Python 3.9+"
@ -760,7 +767,7 @@ $ uvicorn sql_app.main:app --reload
`request.state`是每个`Request`对象的属性。它用于存储附加到请求本身的任意对象,例如本例中的数据库会话。您可以在[Starlette 的关于`Request`state](https://www.starlette.io/requests/#other-state)的文档中了解更多信息。
对于这种情况下,它帮助我们确保在所有请求中使用单个数据库会话,然后关闭(在中间件中)。
对于这种情况下,它帮助我们确保在整个请求中使用单个数据库会话,然后关闭(在中间件中)。
### 使用`yield`依赖项与使用中间件的区别
@ -776,9 +783,9 @@ $ uvicorn sql_app.main:app --reload
* 即使处理该请求的*路径操作*不需要数据库。
!!! tip
`tyield`当依赖项 足以满足用例时,使用`tyield`依赖项方法会更好。
最好使用带有yield的依赖项如果这足够满足用例需求
!!! info
`yield`的依赖项是最近刚加入**FastAPI**中的。
带有`yield`的依赖项是最近刚加入**FastAPI**中的。
所以本教程的先前版本只有带有中间件的示例,并且可能有多个应用程序使用中间件进行数据库会话管理。

View File

@ -1,6 +1,6 @@
"""FastAPI framework, high performance, easy to learn, fast to code, ready for production"""
__version__ = "0.110.2"
__version__ = "0.111.0"
from starlette import status as status

View File

@ -76,7 +76,7 @@ class APIKeyQuery(APIKeyBase):
Doc(
"""
By default, if the query parameter is not provided, `APIKeyQuery` will
automatically cancel the request and sebd the client an error.
automatically cancel the request and send the client an error.
If `auto_error` is set to `False`, when the query parameter is not
available, instead of erroring out, the dependency result will be

39
pdm_build.py Normal file
View File

@ -0,0 +1,39 @@
import os
from typing import Any, Dict, List
from pdm.backend.hooks import Context
TIANGOLO_BUILD_PACKAGE = os.getenv("TIANGOLO_BUILD_PACKAGE", "fastapi")
def pdm_build_initialize(context: Context) -> None:
metadata = context.config.metadata
# Get custom config for the current package, from the env var
config: Dict[str, Any] = context.config.data["tool"]["tiangolo"][
"_internal-slim-build"
]["packages"][TIANGOLO_BUILD_PACKAGE]
project_config: Dict[str, Any] = config["project"]
# Get main optional dependencies, extras
optional_dependencies: Dict[str, List[str]] = metadata.get(
"optional-dependencies", {}
)
# Get custom optional dependencies name to always include in this (non-slim) package
include_optional_dependencies: List[str] = config.get(
"include-optional-dependencies", []
)
# Override main [project] configs with custom configs for this package
for key, value in project_config.items():
metadata[key] = value
# Get custom build config for the current package
build_config: Dict[str, Any] = (
config.get("tool", {}).get("pdm", {}).get("build", {})
)
# Override PDM build config with custom build config for this package
for key, value in build_config.items():
context.config.build_config[key] = value
# Get main dependencies
dependencies: List[str] = metadata.get("dependencies", [])
# Add optional dependencies to the default dependencies for this (non-slim) package
for include_optional in include_optional_dependencies:
optional_dependencies_group = optional_dependencies.get(include_optional, [])
dependencies.extend(optional_dependencies_group)

View File

@ -1,13 +1,13 @@
[build-system]
requires = ["hatchling >= 1.13.0"]
build-backend = "hatchling.build"
requires = ["pdm-backend"]
build-backend = "pdm.backend"
[project]
name = "fastapi"
dynamic = ["version"]
description = "FastAPI framework, high performance, easy to learn, fast to code, ready for production"
readme = "README.md"
requires-python = ">=3.8"
license = "MIT"
authors = [
{ name = "Sebastián Ramírez", email = "tiangolo@gmail.com" },
]
@ -45,7 +45,6 @@ dependencies = [
"pydantic>=1.7.4,!=1.8,!=1.8.1,!=2.0.0,!=2.0.1,!=2.1.0,<3.0.0",
"typing-extensions>=4.8.0",
]
dynamic = ["version"]
[project.urls]
Homepage = "https://github.com/tiangolo/fastapi"
@ -53,22 +52,101 @@ Documentation = "https://fastapi.tiangolo.com/"
Repository = "https://github.com/tiangolo/fastapi"
[project.optional-dependencies]
all = [
standard = [
"fastapi-cli >=0.0.2",
# For the test client
"httpx >=0.23.0",
# For templates
"jinja2 >=2.11.2",
# For forms and file uploads
"python-multipart >=0.0.7",
"itsdangerous >=1.1.0",
"pyyaml >=5.3.1",
# For UJSONResponse
"ujson >=4.0.1,!=4.0.2,!=4.1.0,!=4.2.0,!=4.3.0,!=5.0.0,!=5.1.0",
# For ORJSONResponse
"orjson >=3.2.1",
# To validate email fields
"email_validator >=2.0.0",
# Uvicorn with uvloop
"uvicorn[standard] >=0.12.0",
# TODO: this should be part of some pydantic optional extra dependencies
# # Settings management
# "pydantic-settings >=2.0.0",
# # Extra Pydantic data types
# "pydantic-extra-types >=2.0.0",
]
all = [
"fastapi-cli >=0.0.2",
# # For the test client
"httpx >=0.23.0",
# For templates
"jinja2 >=2.11.2",
# For forms and file uploads
"python-multipart >=0.0.7",
# For Starlette's SessionMiddleware, not commonly used with FastAPI
"itsdangerous >=1.1.0",
# For Starlette's schema generation, would not be used with FastAPI
"pyyaml >=5.3.1",
# For UJSONResponse
"ujson >=4.0.1,!=4.0.2,!=4.1.0,!=4.2.0,!=4.3.0,!=5.0.0,!=5.1.0",
# For ORJSONResponse
"orjson >=3.2.1",
# To validate email fields
"email_validator >=2.0.0",
# Uvicorn with uvloop
"uvicorn[standard] >=0.12.0",
# Settings management
"pydantic-settings >=2.0.0",
# Extra Pydantic data types
"pydantic-extra-types >=2.0.0",
]
[tool.hatch.version]
path = "fastapi/__init__.py"
[tool.pdm]
version = { source = "file", path = "fastapi/__init__.py" }
distribution = true
[tool.pdm.build]
source-includes = [
"tests/",
"docs_src/",
"requirements*.txt",
"scripts/",
# For a test
"docs/en/docs/img/favicon.png",
]
[tool.tiangolo._internal-slim-build.packages.fastapi-slim.project]
name = "fastapi-slim"
[tool.tiangolo._internal-slim-build.packages.fastapi]
include-optional-dependencies = ["standard"]
[tool.tiangolo._internal-slim-build.packages.fastapi.project.optional-dependencies]
all = [
# # For the test client
"httpx >=0.23.0",
# For templates
"jinja2 >=2.11.2",
# For forms and file uploads
"python-multipart >=0.0.7",
# For Starlette's SessionMiddleware, not commonly used with FastAPI
"itsdangerous >=1.1.0",
# For Starlette's schema generation, would not be used with FastAPI
"pyyaml >=5.3.1",
# For UJSONResponse
"ujson >=4.0.1,!=4.0.2,!=4.1.0,!=4.2.0,!=4.3.0,!=5.0.0,!=5.1.0",
# For ORJSONResponse
"orjson >=3.2.1",
# To validate email fields
"email_validator >=2.0.0",
# Uvicorn with uvloop
"uvicorn[standard] >=0.12.0",
# Settings management
"pydantic-settings >=2.0.0",
# Extra Pydantic data types
"pydantic-extra-types >=2.0.0",
]
[tool.mypy]
strict = true

View File

@ -11,7 +11,7 @@ jieba==0.42.1
pillow==10.3.0
# For image processing by Material for MkDocs
cairosvg==2.7.0
mkdocstrings[python]==0.23.0
mkdocstrings[python]==0.24.3
griffe-typingdoc==0.2.2
# For griffe, it formats with black
black==24.3.0

View File

@ -1,19 +1,14 @@
-e .
-e .[all]
-r requirements-docs-tests.txt
pydantic-settings >=2.0.0
pytest >=7.1.3,<8.0.0
coverage[toml] >= 6.5.0,< 8.0
mypy ==1.8.0
ruff ==0.2.0
email_validator >=1.1.1,<3.0.0
dirty-equals ==0.6.0
# TODO: once removing databases from tutorial, upgrade SQLAlchemy
# probably when including SQLModel
sqlalchemy >=1.3.18,<1.4.43
databases[sqlite] >=0.3.2,<0.7.0
orjson >=3.2.1,<4.0.0
ujson >=4.0.1,!=4.0.2,!=4.1.0,!=4.2.0,!=4.3.0,!=5.0.0,!=5.1.0,<6.0.0
python-multipart >=0.0.7,<0.1.0
flask >=1.1.2,<3.0.0
anyio[trio] >=3.2.1,<4.0.0
python-jose[cryptography] >=3.3.0,<4.0.0

View File

@ -1,7 +1,6 @@
-e .[all]
-r requirements-tests.txt
-r requirements-docs.txt
uvicorn[standard] >=0.12.0,<0.23.0
pre-commit >=2.17.0,<4.0.0
# For generating screenshots
playwright

View File

@ -1,8 +0,0 @@
#!/usr/bin/env bash
set -e
set -x
# Check README.md is up to date
python ./scripts/docs.py verify-docs
python ./scripts/docs.py build-all

View File

@ -1,8 +0,0 @@
#!/bin/sh -e
if [ -d 'dist' ] ; then
rm -r dist
fi
if [ -d 'site' ] ; then
rm -r site
fi

View File

@ -1,5 +0,0 @@
#!/usr/bin/env bash
set -e
mkdocs serve --dev-addr 0.0.0.0:8008

View File

@ -1,5 +1,5 @@
#!/bin/sh -e
set -x
ruff fastapi tests docs_src scripts --fix
ruff check fastapi tests docs_src scripts --fix
ruff format fastapi tests docs_src scripts

View File

@ -4,5 +4,5 @@ set -e
set -x
mypy fastapi
ruff fastapi tests docs_src scripts
ruff check fastapi tests docs_src scripts
ruff format fastapi tests --check

View File

@ -1,14 +0,0 @@
#!/usr/bin/env bash
set -x
set -e
# Install pip
cd /tmp
curl https://bootstrap.pypa.io/get-pip.py -o get-pip.py
python3.6 get-pip.py --user
cd -
# Install Flit to be able to install all
python3.6 -m pip install --user flit
# Install with Flit
python3.6 -m flit install --user --extras doc
# Finally, run mkdocs
python3.6 -m mkdocs build

View File

@ -1,5 +0,0 @@
#!/usr/bin/env bash
set -e
flit publish