<ahref="https://github.com/scalar/scalar/?utm_source=fastapi&utm_medium=website&utm_campaign=main-badge"target="_blank"title="Scalar: Beautiful Open-Source API References from Swagger/OpenAPI files"><imgsrc="https://fastapi.tiangolo.com/img/sponsors/scalar.svg"></a>
<ahref="https://www.propelauth.com/?utm_source=fastapi&utm_campaign=1223&utm_medium=mainbadge"target="_blank"title="Auth, user management and more for your B2B product"><imgsrc="https://fastapi.tiangolo.com/img/sponsors/propelauth.png"></a>
<ahref="https://liblab.com?utm_source=fastapi"target="_blank"title="liblab - Generate SDKs from FastAPI"><imgsrc="https://fastapi.tiangolo.com/img/sponsors/liblab.png"></a>
<ahref="https://docs.render.com/deploy-fastapi?utm_source=deploydoc&utm_medium=referral&utm_campaign=fastapi"target="_blank"title="Deploy & scale any full-stack web app on Render. Focus on building apps, not infra."><imgsrc="https://fastapi.tiangolo.com/img/sponsors/render.svg"></a>
<ahref="https://www.coderabbit.ai/?utm_source=fastapi&utm_medium=badge&utm_campaign=fastapi"target="_blank"title="Cut Code Review Time & Bugs in Half with CodeRabbit"><imgsrc="https://fastapi.tiangolo.com/img/sponsors/coderabbit.png"></a>
<ahref="https://subtotal.com/?utm_source=fastapi&utm_medium=sponsorship&utm_campaign=open-source"target="_blank"title="The Gold Standard in Retail Account Linking"><imgsrc="https://fastapi.tiangolo.com/img/sponsors/subtotal.svg"></a>
@ -68,9 +66,7 @@ The key features are:
<ahref="https://www.svix.com/"target="_blank"title="Svix - Webhooks as a service"><imgsrc="https://fastapi.tiangolo.com/img/sponsors/svix.svg"></a>
<ahref="https://www.permit.io/blog/implement-authorization-in-fastapi?utm_source=github&utm_medium=referral&utm_campaign=fastapi"target="_blank"title="Fine-Grained Authorization for FastAPI"><imgsrc="https://fastapi.tiangolo.com/img/sponsors/permit.png"></a>
<ahref="https://www.interviewpal.com/?utm_source=fastapi&utm_medium=open-source&utm_campaign=dev-hiring"target="_blank"title="InterviewPal - AI Interview Coach for Engineers and Devs"><imgsrc="https://fastapi.tiangolo.com/img/sponsors/interviewpal.png"></a>
<ahref="https://dribia.com/en/"target="_blank"title="Dribia - Data Science within your reach"><imgsrc="https://fastapi.tiangolo.com/img/sponsors/dribia.png"></a>
<ahref="https://talordata.com/?campaignid=oh5dVZ3Zc3YGiAI2&utm_source=fastapi&utm_term=fastapi"target="_blank"title="TalorData SERP API - Multi-Engine Search Results Data"><imgsrc="https://fastapi.tiangolo.com/img/sponsors/talordata.png"></a>
<ahref="https://www.rapidproxy.io/?ref=fastapi"target="_blank"title="Try RapidProxy for free - Residential Proxies with 90M+ Global IPs. Starting from $0.65/GB for web scraping, automation, and data collection."><imgsrc="https://fastapi.tiangolo.com/img/sponsors/rapidproxy.png"></a>
<!-- /sponsors -->
@ -450,9 +446,7 @@ For a more complete example including more features, see the <a href="https://fa
### Deploy your app (optional)
You can optionally deploy your FastAPI app to [FastAPI Cloud](https://fastapicloud.com), go and join the waiting list if you haven't. 🚀
If you already have a **FastAPI Cloud** account (we invited you from the waiting list 😉), you can deploy your application with one command.
You can optionally deploy your FastAPI app to [FastAPI Cloud](https://fastapicloud.com) with a single command. 🚀
<divclass="termy">
@ -468,6 +462,8 @@ Deploying to FastAPI Cloud...
</div>
The CLI will automatically detect your FastAPI application and deploy it to the cloud. If you are not logged in, your browser will open to complete the authentication process.
That's it! Now you can access your app at that URL. ✨
@ -34,7 +34,7 @@ Beachten Sie, dass Sie die `JSONResponse` direkt zurückgeben müssen.
///
/// info | Info
/// note | Hinweis
Der `model`-Schlüssel ist nicht Teil von OpenAPI.
@ -183,7 +183,7 @@ Beachten Sie, dass Sie das Bild direkt mit einer `FileResponse` zurückgeben mü
///
/// info | Info
/// note | Hinweis
Sofern Sie in Ihrem Parameter `responses` nicht explizit einen anderen Medientyp angeben, geht FastAPI davon aus, dass die Response denselben Medientyp wie die Haupt-Response-Klasse hat (Standardmäßig `application/json`).
@ -120,7 +120,7 @@ Um eine Funktion hinzuzufügen, die beim Shutdown der Anwendung ausgeführt werd
Hier schreibt die `shutdown`-Eventhandler-Funktion eine Textzeile `"Application shutdown"` in eine Datei `log.txt`.
/// info | Info
/// note | Hinweis
In der Funktion `open()` bedeutet `mode="a"` „append“ („anhängen“), sodass die Zeile nach dem, was sich in dieser Datei befindet, hinzugefügt wird, ohne den vorherigen Inhalt zu überschreiben.
@ -152,7 +152,7 @@ Nur ein technisches Detail für die neugierigen Nerds. 🤓
In der technischen ASGI-Spezifikation ist dies Teil des [Lifespan Protokolls](https://asgi.readthedocs.io/en/latest/specs/lifespan.html) und definiert Events namens `startup` und `shutdown`.
/// info | Info
/// note | Hinweis
Weitere Informationen zu Starlettes `lifespan`-Handlern finden Sie in [Starlettes Lifespan-Dokumentation](https://www.starlette.dev/lifespan/).
Einige dieser Lösungen sind möglicherweise auch Open Source oder bieten kostenlose Tarife an, sodass Sie diese ohne finanzielle Verpflichtung ausprobieren können. Andere kommerzielle SDK-Generatoren sind online verfügbar und können dort gefunden werden. 🤓
@ -173,7 +173,7 @@ Verwenden Sie nun den Parameter `callbacks` im *Pfadoperation-Dekorator Ihrer AP
/// tip | Tipp
Beachten Sie, dass Sie nicht den Router selbst (`invoices_callback_router`) an `callback=` übergeben, sondern das Attribut `.routes`, wie in `invoices_callback_router.routes`.
Beachten Sie, dass Sie nicht den Router selbst (`invoices_callback_router`) an `callback=` übergeben, sondern das Attribut `.routes`, wie in `invoices_callback_router.routes`. FastAPI wird diese Routen verwenden, um die Callback-OpenAPI-Dokumentation zu generieren.
@ -22,7 +22,7 @@ Mit **FastAPI**, mithilfe von OpenAPI, können Sie die Namen dieser Webhooks, di
Dies kann es Ihren Benutzern viel einfacher machen, **deren APIs zu implementieren**, um Ihre **Webhook**-Requests zu empfangen. Möglicherweise können diese sogar einen Teil ihres eigenen API-Codes automatisch generieren.
/// info | Info
/// note | Hinweis
Webhooks sind in OpenAPI 3.1.0 und höher verfügbar und werden von FastAPI `0.99.0` und höher unterstützt.
@ -36,7 +36,7 @@ Wenn Sie eine **FastAPI**-Anwendung erstellen, gibt es ein `webhooks`-Attribut,
Die von Ihnen definierten Webhooks landen im **OpenAPI**-Schema und der automatischen **Dokumentations-Oberfläche**.
/// info | Info
/// note | Hinweis
Das `app.webhooks`-Objekt ist eigentlich nur ein `APIRouter`, derselbe Typ, den Sie verwenden würden, wenn Sie Ihre App mit mehreren Dateien strukturieren.
@ -16,17 +16,11 @@ Sie müssten sicherstellen, dass sie für jede Operation eindeutig ist.
### Verwendung des Namens der *Pfadoperation-Funktion* als operationId { #using-the-path-operation-function-name-as-the-operationid }
Wenn Sie die Funktionsnamen Ihrer API als `operationId`s verwenden möchten, können Sie über alle iterieren und die `operation_id` jeder *Pfadoperation* mit deren `APIRoute.name` überschreiben.
Wenn Sie die Funktionsnamen Ihrer APIs als `operationId`s verwenden möchten, können Sie `FastAPI` eine eigene `generate_unique_id_function` übergeben.
Sie sollten dies tun, nachdem Sie alle Ihre *Pfadoperationen* hinzugefügt haben.
Diese Funktion erhält jeweils die `APIRoute` und gibt die `operationId` zurück, die für diese Pfadoperation verwendet werden soll.
@ -4,7 +4,7 @@ Wenn Sie Daten streamen möchten, die als JSON strukturiert werden können, soll
Wenn Sie jedoch **reine Binärdaten** oder Strings streamen möchten, so können Sie es machen.
/// info | Info
/// note | Hinweis
Hinzugefügt in FastAPI 0.134.0.
@ -90,7 +90,7 @@ Beispielsweise haben sie kein `await file.read()` oder `async for chunk in file`
Und in vielen Fällen wäre das Lesen eine blockierende Operation (die die Event-Loop blockieren könnte), weil von der Festplatte oder aus dem Netzwerk gelesen wird.
/// info | Info
/// note | Hinweis
Das obige Beispiel ist tatsächlich eine Ausnahme, weil sich das `io.BytesIO`-Objekt bereits im Speicher befindet, daher blockiert sein Lesen nichts.
Es gibt andere Formate und Tools zum Definieren und Installieren von Paketabhängigkeiten.
@ -334,7 +334,7 @@ $ docker build -t myimage .
Beachten Sie das `.` am Ende, es entspricht `./` und teilt Docker mit, welches Verzeichnis zum Erstellen des Containerimages verwendet werden soll.
In diesem Fall handelt es sich um dasselbe aktuelle Verzeichnis (`.`).
In diesem Case handelt es sich um dasselbe aktuelle Verzeichnis (`.`).
///
@ -556,7 +556,7 @@ Wenn Sie Container (z. B. Docker, Kubernetes) verwenden, können Sie hauptsächl
Wenn Sie **mehrere Container** haben, von denen wahrscheinlich jeder einen **einzelnen Prozess** ausführt (z. B. in einem **Kubernetes**-Cluster), dann möchten Sie wahrscheinlich einen **separaten Container** haben, welcher die Arbeit der **Vorab-Schritte** in einem einzelnen Container, mit einem einzelnen Prozess ausführt, **bevor** die replizierten Workercontainer ausgeführt werden.
/// info | Info
/// note | Hinweis
Wenn Sie Kubernetes verwenden, wäre dies wahrscheinlich ein [Init-Container](https://kubernetes.io/docs/concepts/workloads/pods/init-containers/).
Sie können Ihre FastAPI-App in der [FastAPI Cloud](https://fastapicloud.com) mit **einem einzigen Befehl** deployen – tragen Sie sich in die Warteliste ein, falls noch nicht geschehen. 🚀
## Anmelden { #login }
Stellen Sie sicher, dass Sie bereits ein **FastAPI-Cloud-Konto** haben (wir haben Sie von der Warteliste eingeladen 😉).
Melden Sie sich dann an:
<divclass="termy">
```console
$ fastapi login
You are logged in to FastAPI Cloud 🚀
```
</div>
## Deployen { #deploy }
Stellen Sie Ihre App jetzt mit **einem einzigen Befehl** bereit:
Sie können Ihre FastAPI-App in der [FastAPI Cloud](https://fastapicloud.com) mit **einem einzigen Befehl** deployen. 🚀
<divclass="termy">
@ -36,6 +16,8 @@ Deploying to FastAPI Cloud...
</div>
Das CLI erkennt Ihre FastAPI-App automatisch und deployt sie in die Cloud. Wenn Sie nicht angemeldet sind, öffnet sich Ihr Browser, um den Authentifizierungsprozess abzuschließen.
Das war’s! Jetzt können Sie Ihre App unter dieser URL aufrufen. ✨
## Über FastAPI Cloud { #about-fastapi-cloud }
@ -62,4 +44,4 @@ Folgen Sie den Anleitungen Ihres Cloudanbieters, um dort FastAPI-Apps zu deploye
## Auf den eigenen Server deployen { #deploy-your-own-server }
Ich werde Ihnen später in diesem **Deployment-Leitfaden** auch alle Details zeigen, sodass Sie verstehen, was passiert, was geschehen muss und wie Sie FastAPI-Apps selbst deployen können, auch auf Ihre eigenen Server. 🤓
Ich werde Ihnen später in diesem **Deployment**-Leitfaden auch alle Details zeigen, sodass Sie verstehen, was passiert, was geschehen muss und wie Sie FastAPI-Apps selbst deployen können, auch auf Ihre eigenen Server. 🤓
@ -17,7 +17,7 @@ Wie Sie im vorherigen Kapitel über [Deployment-Konzepte](concepts.md) gesehen h
Hier zeige ich Ihnen, wie Sie **Uvicorn** mit **Workerprozessen** verwenden, indem Sie den `fastapi`-Befehl oder den `uvicorn`-Befehl direkt verwenden.
/// info | Info
/// note | Hinweis
Wenn Sie Container verwenden, beispielsweise mit Docker oder Kubernetes, erzähle ich Ihnen mehr darüber im nächsten Kapitel: [FastAPI in Containern – Docker](docker.md).
@ -25,9 +25,17 @@ Diese Funktion `get_openapi()` erhält als Parameter:
* `openapi_version`: Die Version der verwendeten OpenAPI-Spezifikation. Standardmäßig die neueste Version: `3.1.0`.
* `summary`: Eine kurze Zusammenfassung der API.
* `description`: Die Beschreibung Ihrer API. Dies kann Markdown enthalten und wird in der Dokumentation angezeigt.
* `routes`: Eine Liste von Routen, dies sind alle registrierten *Pfadoperationen*. Sie stammen von `app.routes`.
* `routes`: Die Routen der Anwendung, entnommen aus `app.routes`. FastAPI nutzt sie, um die registrierten *Pfadoperationen* zu sammeln, einschließlich derer aus eingebundenen Routern.
/// info | Info
/// tip | Technische Details
`app.routes` ist eine Routenstruktur auf niedrigerer Ebene. Sie kann Routenkandidaten enthalten, die FastAPI intern für eingebundene Router verwendet, nicht nur endgültige `APIRoute`-Objekte.
Sie können dennoch `app.routes` an `get_openapi()` übergeben. FastAPI durchläuft diesen Routenbaum, um die tatsächlich wirksamen Pfadoperationen zu sammeln.
///
/// note | Hinweis
Der Parameter `summary` ist in OpenAPI 3.1.0 und höher verfügbar und wird von FastAPI 0.99.0 und höher unterstützt.
**Hinweis**: Stellen Sie sicher, dass Sie `"fastapi[standard]"` in Anführungszeichen setzen, damit es in allen Terminals funktioniert.
**Hinweis**: Stellen Sie sicher, dass Sie „fastapi[standard]“ in Anführungszeichen setzen, damit es in allen Terminals funktioniert.
## Beispiel { #example }
@ -492,9 +492,7 @@ Für ein vollständigeres Beispiel, mit weiteren Funktionen, siehe das <a href="
### Ihre App deployen (optional) { #deploy-your-app-optional }
Optional können Sie Ihre FastAPI-App in die [FastAPI Cloud](https://fastapicloud.com) deployen, gehen Sie und treten Sie der Warteliste bei, falls noch nicht geschehen. 🚀
Wenn Sie bereits ein **FastAPI Cloud**-Konto haben (wir haben Sie von der Warteliste eingeladen 😉), können Sie Ihre Anwendung mit einem einzigen Befehl deployen.
Optional können Sie Ihre FastAPI-App mit einem einzigen Befehl in die [FastAPI Cloud](https://fastapicloud.com) deployen. 🚀
<divclass="termy">
@ -510,6 +508,8 @@ Deploying to FastAPI Cloud...
</div>
Das CLI erkennt Ihre FastAPI-Anwendung automatisch und deployt sie in die Cloud. Wenn Sie nicht eingeloggt sind, wird Ihr Browser geöffnet, um den Authentifizierungsprozess abzuschließen.
Das war’s! Jetzt können Sie unter dieser URL auf Ihre App zugreifen. ✨
@ -396,9 +396,9 @@ Es wird alle Routen von diesem Router als Teil von dieser inkludieren.
/// note | Technische Details
Tatsächlich wird intern eine *Pfadoperation* für jede *Pfadoperation* erstellt, die im `APIRouter` deklariert wurde.
FastAPI behält den ursprünglichen `APIRouter` und seine `APIRoute`s aktiv, wenn der Router in die Hauptanwendung eingebunden wird.
Hinter den Kulissen wird es also tatsächlich so funktionieren, als ob alles dieselbe einzige Anwendung wäre.
Das bedeutet, dass benutzerdefinierte Subklassen von `APIRouter` und `APIRoute` auch nach dem Einbinden weiterhin beteiligt sein können.
///
@ -406,7 +406,7 @@ Hinter den Kulissen wird es also tatsächlich so funktionieren, als ob alles die
Bei der Einbindung von Routern müssen Sie sich keine Gedanken über die Leistung machen.
Dies dauert Mikrosekunden und geschieht nur beim Start.
Dies ist so konzipiert, dass es leichtgewichtig ist und keinen Overhead pro Request hinzufügt.
Es hat also keinen Einfluss auf die Leistung. ⚡
@ -459,9 +459,9 @@ und es wird korrekt funktionieren, zusammen mit allen anderen *Pfadoperationen*,
Die `APIRouter` sind nicht „gemountet“, sie sind nicht vom Rest der Anwendung isoliert.
Das liegt daran, dass wir deren *Pfadoperationen* in das OpenAPI-Schema und die Benutzeroberflächen einbinden möchten.
Das liegt daran, dass wir ihre *Pfadoperationen* im OpenAPI-Schema und in den Benutzeroberflächen inkludieren möchten.
Da wir sie nicht einfach isolieren und unabhängig vom Rest „mounten“ können, werden die *Pfadoperationen* „geklont“ (neu erstellt) und nicht direkt einbezogen.
FastAPI behält die ursprünglichen Router und Pfadoperationen aktiv und kombiniert Router-Präfixe, Abhängigkeiten, Tags, Responses und weitere Metadaten beim Bearbeiten von Requests und beim Generieren von OpenAPI.
///
@ -532,4 +532,16 @@ Auf die gleiche Weise, wie Sie einen `APIRouter` in eine `FastAPI`-Anwendung ein
router.include_router(other_router)
```
Stellen Sie sicher, dass Sie dies tun, bevor Sie `router` in die `FastAPI`-App einbinden, damit auch die *Pfadoperationen* von `other_router` inkludiert werden.
Sie können dies vor oder nach dem Einbinden von `router` in die `FastAPI`-App tun. FastAPI inkludiert die *Pfadoperationen* von `other_router` dennoch in Routing und OpenAPI.
Gleiches gilt für später zu den Routern hinzugefügte *Pfadoperationen*. Sie sind auch über die frühere Inklusion sichtbar.
/// warning | Technische Details
Vermeiden Sie es, `router.routes` direkt zu mutieren, nachdem ein Router inkludiert wurde. FastAPI behandelt Router-Inklusion als „live“, sodass der ursprüngliche Router und seine Routen Teil des Routings und der OpenAPI-Generierung bleiben.
Verwenden Sie dokumentierte APIs wie Pfadoperation-Dekoratoren und `.include_router()`, um Routen und Router hinzuzufügen.
Betrachten Sie `router.routes` als eine Low-Level-Routenstruktur, die sowohl Routendefinitionen als auch inkludierte Router enthalten kann, und verlassen Sie sich nicht darauf als flache Liste endgültiger Pfadoperationen.
`Body` hat die gleichen zusätzlichen Validierungs- und Metadaten-Parameter wie `Query`, `Path` und andere, die Sie später kennenlernen werden.
@ -123,7 +123,7 @@ Standardmäßig wird **FastAPI** dann seinen Body direkt erwarten.
Aber wenn Sie möchten, dass es einen JSON-Body mit einem Schlüssel `item` erwartet, und darin den Inhalt des Modells, so wie es das tut, wenn Sie mehrere Body-Parameter deklarieren, dann können Sie den speziellen `Body`-Parameter `embed` setzen:
Bitte beachten Sie, dass Browser Cookies auf spezielle Weise und im Hintergrund bearbeiten, sodass sie **nicht** leicht **JavaScript** erlauben, diese zu berühren.
@ -24,13 +24,13 @@ Aber denken Sie daran, dass, wenn Sie `Query`, `Path`, `Cookie` und andere von `
///
/// info | Info
/// note | Hinweis
Um Cookies zu deklarieren, müssen Sie `Cookie` verwenden, da die Parameter sonst als Query-Parameter interpretiert würden.
///
/// info | Info
/// note | Hinweis
Beachten Sie, dass **Browser Cookies auf besondere Weise und hinter den Kulissen handhaben** und **JavaScript****nicht** ohne Weiteres erlauben, auf sie zuzugreifen.
@ -50,7 +50,7 @@ In diesem Fall erwartet diese Abhängigkeit:
Und dann wird einfach ein <abbrtitle="Dictionary – Zuordnungstabelle: In anderen Sprachen auch Hash, Map, Objekt, Assoziatives Array genannt">`dict`</abbr> zurückgegeben, welches diese Werte enthält.
/// info | Info
/// note | Hinweis
FastAPI unterstützt (und empfiehlt die Verwendung von) `Annotated` seit Version 0.95.0.
### `fastapi dev` mit Pfad { #fastapi-dev-with-path }
### `fastapi dev` mit Pfad oder mit der CLI-Option `--entrypoint`{ #fastapi-dev-with-path-or-with-entrypoint-cli-option }
Sie können auch den Dateipfad an den Befehl `fastapi dev` übergeben, und er wird das zu verwendende FastAPI-App-Objekt erraten:
@ -188,29 +188,19 @@ Sie können auch den Dateipfad an den Befehl `fastapi dev` übergeben, und er wi
$ fastapi dev main.py
```
Aber Sie müssten sich daran erinnern, bei jedem Aufruf des `fastapi`-Befehls den korrekten Pfad zu übergeben.
Zusätzlich könnten andere Tools es nicht finden, z. B. die [VS Code-Erweiterung](../editor-support.md) oder [FastAPI Cloud](https://fastapicloud.com). Daher wird empfohlen, den `entrypoint` in `pyproject.toml` zu verwenden.
### Ihre App deployen (optional) { #deploy-your-app-optional }
Sie können optional Ihre FastAPI-App in der [FastAPI Cloud](https://fastapicloud.com) deployen, treten Sie der Warteliste bei, falls Sie es noch nicht getan haben. 🚀
Wenn Sie bereits ein **FastAPI Cloud**-Konto haben (wir haben Sie von der Warteliste eingeladen 😉), können Sie Ihre Anwendung mit einem Befehl deployen.
Vor dem Deployen, stellen Sie sicher, dass Sie eingeloggt sind:
<divclass="termy">
Oder Sie können die Option `--entrypoint` an den Befehl `fastapi dev` übergeben:
```console
$ fastapi login
You are logged in to FastAPI Cloud 🚀
$ fastapi dev --entrypoint main:app
```
</div>
Aber Sie müssten sich daran erinnern, bei jedem Aufruf des `fastapi`-Befehls den korrekten Pfad\entrypoint zu übergeben.
Zusätzlich könnten andere Tools es nicht finden, z. B. die [VS Code-Erweiterung](../editor-support.md) oder [FastAPI Cloud](https://fastapicloud.com). Daher wird empfohlen, den `entrypoint` in `pyproject.toml` zu verwenden.
Dann stellen Sie Ihre App bereit:
### Ihre App deployen (optional) { #deploy-your-app-optional }
Sie können optional Ihre FastAPI-App in der [FastAPI Cloud](https://fastapicloud.com) mit einem einzigen Befehl deployen. 🚀
<divclass="termy">
@ -226,6 +216,8 @@ Deploying to FastAPI Cloud...
</div>
Das CLI erkennt Ihre FastAPI-Anwendung automatisch und deployt sie in die Cloud. Wenn Sie nicht eingeloggt sind, wird Ihr Browser geöffnet, um die Authentifizierung abzuschließen.
Das war's! Jetzt können Sie Ihre App unter dieser URL aufrufen. ✨
## Zusammenfassung, Schritt für Schritt { #recap-step-by-step }
@ -270,7 +262,7 @@ https://example.com/items/foo
/items/foo
```
/// info | Info
/// note | Hinweis
Ein „Pfad“ wird häufig auch als „Endpunkt“ oder „Route“ bezeichnet.
@ -322,7 +314,7 @@ Das `@app.get("/")` sagt **FastAPI**, dass die Funktion direkt darunter für die
* den Pfad `/`
* unter der Verwendung der <dfntitle="eine HTTP-GET-Methode"><code>get</code>-Operation</dfn> gehen
/// info | `@decorator` Info
/// note | `@decorator` Info
Diese `@something`-Syntax wird in Python „Dekorator“ genannt.
@ -20,7 +20,7 @@ Sie können den Typ eines Pfad-Parameters in der Argumentliste der Funktion dekl
In diesem Fall wird `item_id` als `int` deklariert, also als Ganzzahl.
/// check | Testen
/// tip | Tipp
Dadurch erhalten Sie Editor-Unterstützung innerhalb Ihrer Funktion, mit Fehlerprüfungen, Codevervollständigung, usw.
@ -34,7 +34,7 @@ Wenn Sie dieses Beispiel ausführen und Ihren Browser unter [http://127.0.0.1:80
{"item_id":3}
```
/// check | Testen
/// tip | Tipp
Beachten Sie, dass der Wert, den Ihre Funktion erhält und zurückgibt, die Zahl `3` ist, also ein `int`. Nicht der String „3“, also ein `str`.
@ -66,7 +66,7 @@ Der Pfad-Parameter `item_id` hatte den Wert „foo“, was kein `int` ist.
Die gleiche Fehlermeldung würde angezeigt werden, wenn Sie ein `float` (also eine Kommazahl) statt eines `int`s übergeben würden, wie etwa in: [http://127.0.0.1:8000/items/4.2](http://127.0.0.1:8000/items/4.2)
/// check | Testen
/// tip | Tipp
Sprich, mit der gleichen Python-Typdeklaration gibt Ihnen **FastAPI** Datenvalidierung.
@ -82,7 +82,7 @@ Wenn Sie die Seite [http://127.0.0.1:8000/docs](http://127.0.0.1:8000/docs) in I
<imgsrc="/img/tutorial/path-params/image01.png">
/// check | Testen
/// tip | Tipp
Wiederum, mit dieser gleichen Python-Typdeklaration gibt Ihnen **FastAPI** eine automatische, interaktive Dokumentation (verwendet die Swagger-Benutzeroberfläche).
@ -65,7 +65,7 @@ Auf die gleiche Weise können Sie optionale Query-Parameter deklarieren, indem S
In diesem Fall wird der Funktionsparameter `q` optional und standardmäßig `None` sein.
/// check | Testen
/// tip | Tipp
Beachten Sie auch, dass **FastAPI** intelligent genug ist, um zu erkennen, dass `item_id` ein Pfad-Parameter ist und `q` keiner, daher muss letzteres ein Query-Parameter sein.
@ -32,7 +32,7 @@ Die <dfn title="Spezifikation">Spezifikation</dfn> erfordert, dass die Felder ex
Mit `Form` haben Sie die gleichen Konfigurationsmöglichkeiten wie mit `Body` (und `Query`, `Path`, `Cookie`), inklusive Validierung, Beispielen, einem Alias (z. B. `user-name` statt `username`), usw.
/// info | Info
/// note | Hinweis
`Form` ist eine Klasse, die direkt von `Body` erbt.
@ -56,7 +56,7 @@ Daten aus Formularen werden normalerweise mit dem <abbr title="Medientyp">„med
Wenn das Formular stattdessen Dateien enthält, werden diese mit `multipart/form-data` kodiert. Im nächsten Kapitel erfahren Sie mehr über die Handhabung von Dateien.
Wenn Sie mehr über Formularfelder und ihre Kodierungen lesen möchten, besuchen Sie die [<abbr title="Mozilla Developer Network – Mozilla-Entwicklernetzwerk">MDN</abbr>-Webdokumentation für `POST`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods/POST).
Wenn Sie mehr über Formularfelder und ihre Kodierungen lesen möchten, besuchen Sie die [<abbr title="Mozilla Developer Network - Mozilla-Entwicklernetzwerk">MDN</abbr>-Webdokumentation für `POST`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods/POST).
@ -18,7 +18,7 @@ Beachten Sie, dass `status_code` ein Parameter der „Dekorator“-Methode ist (
Dem `status_code`-Parameter wird eine Zahl mit dem HTTP-Statuscode übergeben.
/// info | Info
/// note | Hinweis
Alternativ kann `status_code` auch ein `IntEnum` erhalten, wie etwa Pythons [`http.HTTPStatus`](https://docs.python.org/3/library/http.html#http.HTTPStatus).
@ -24,7 +24,7 @@ Sie könnten das beispielsweise verwenden, um Metadaten für eine Frontend-Benut
///
/// info | Info
/// note | Hinweis
OpenAPI 3.1.0 (verwendet seit FastAPI 0.99.0) hat Unterstützung für `examples` hinzugefügt, was Teil des **JSON Schema** Standards ist.
@ -155,7 +155,7 @@ OpenAPI fügte auch die Felder `example` und `examples` zu anderen Teilen der Sp
* `File()`
* `Form()`
/// info | Info
/// note | Hinweis
Dieser alte, OpenAPI-spezifische `examples`-Parameter heißt seit FastAPI `0.103.0` jetzt `openapi_examples`.
@ -171,7 +171,7 @@ Und jetzt hat dieses neue `examples`-Feld Vorrang vor dem alten (und benutzerdef
Dieses neue `examples`-Feld in JSON Schema ist **nur eine `list`** von Beispielen, kein Dict mit zusätzlichen Metadaten wie an den anderen Stellen in OpenAPI (oben beschrieben).
/// info | Info
/// note | Hinweis
Selbst, nachdem OpenAPI 3.1.0 veröffentlicht wurde, mit dieser neuen, einfacheren Integration mit JSON Schema, unterstützte Swagger UI, das Tool, das die automatische Dokumentation bereitstellt, eine Zeit lang OpenAPI 3.1.0 nicht (das tut es seit Version 5.0.0 🎉).
@ -24,7 +24,7 @@ Kopieren Sie das Beispiel in eine Datei `main.py`:
## Ausführen { #run-it }
/// info | Info
/// note | Hinweis
Das Paket [`python-multipart`](https://github.com/Kludex/python-multipart) wird automatisch mit **FastAPI** installiert, wenn Sie den Befehl `pip install "fastapi[standard]"` ausführen.
@ -62,7 +62,7 @@ Sie werden etwa Folgendes sehen:
<imgsrc="/img/tutorial/security/image01.png">
/// check | Authorize-Button!
/// tip | Authorize-Button!
Sie haben bereits einen glänzenden, neuen „Authorize“-Button.
@ -120,7 +120,7 @@ Betrachten wir es also aus dieser vereinfachten Sicht:
In diesem Beispiel verwenden wir **OAuth2** mit dem **Password**-Flow und einem **Bearer**-Token. Wir machen das mit der Klasse `OAuth2PasswordBearer`.
/// info | Info
/// note | Hinweis
Ein „Bearer“-Token ist nicht die einzige Option.
@ -150,7 +150,7 @@ Dieser Parameter erstellt nicht diesen Endpunkt / diese *Pfadoperation*, sondern
Wir werden demnächst auch die eigentliche Pfadoperation erstellen.
/// info | Info
/// note | Hinweis
Wenn Sie ein sehr strenger „Pythonista“ sind, missfällt Ihnen möglicherweise die Schreibweise des Parameternamens `tokenUrl` anstelle von `token_url`.
@ -178,7 +178,7 @@ Diese Abhängigkeit stellt einen `str` bereit, der dem Parameter `token` der *Pf
**FastAPI** weiß, dass es diese Abhängigkeit verwenden kann, um ein „Sicherheitsschema“ im OpenAPI-Schema (und der automatischen API-Dokumentation) zu definieren.
/// info | Technische Details
/// note | Technische Details
**FastAPI** weiß, dass es die Klasse `OAuth2PasswordBearer` (deklariert in einer Abhängigkeit) verwenden kann, um das Sicherheitsschema in OpenAPI zu definieren, da es von `fastapi.security.oauth2.OAuth2` erbt, das wiederum von `fastapi.security.base.SecurityBase` erbt.
@ -52,7 +52,7 @@ Weil Sie `Depends` verwenden, wird **FastAPI** hier aber nicht verwirrt.
///
/// check | Testen
/// tip | Tipp
Die Art und Weise, wie dieses System von Abhängigkeiten konzipiert ist, ermöglicht es uns, verschiedene Abhängigkeiten (verschiedene „Dependables“) zu haben, die alle ein `User`-Modell zurückgeben.
Sie können Daten mithilfe von **Server-Sent Events** (SSE) an den Client streamen.
Das ist ähnlich wie [JSON Lines streamen](stream-json-lines.md), verwendet aber das Format `text/event-stream`, das von Browsern nativ mit der [die `EventSource`-API](https://developer.mozilla.org/en-US/docs/Web/API/EventSource) unterstützt wird.
Das ist ähnlich wie [JSON Lines streamen](stream-json-lines.md), verwendet aber das Format `text/event-stream`, das von Browsern nativ mit der [`EventSource`-API](https://developer.mozilla.org/en-US/docs/Web/API/EventSource) unterstützt wird.
/// info | Info
/// note | Hinweis
Hinzugefügt in FastAPI 0.135.0.
@ -29,7 +29,7 @@ SSE wird häufig für KI-Chat-Streaming, Live-Benachrichtigungen, Logs und Obser
/// tip | Tipp
Wenn Sie Binärdaten streamen wollen, z. B. Video oder Audio, sehen Sie im fortgeschrittenen Handbuch nach: [Daten streamen](../advanced/stream-data.md).
Wenn Sie Binärdaten streamen wollen, z. B. Video oder Audio, sehen Sie im Handbuch für fortgeschrittene Benutzer nach: [Daten streamen](../advanced/stream-data.md).
///
@ -103,7 +103,7 @@ Sie können ihn als Header-Parameter einlesen und verwenden, um den Stream dort
## SSE mit POST { #sse-with-post }
SSE funktioniert mit **jedem HTTP-Method**, nicht nur mit `GET`.
SSE funktioniert mit **jeder HTTP-Methode**, nicht nur mit `GET`.
Das ist nützlich für Protokolle wie [MCP](https://modelcontextprotocol.io), die SSE über `POST` streamen:
@ -113,7 +113,7 @@ Das ist nützlich für Protokolle wie [MCP](https://modelcontextprotocol.io), di
FastAPI implementiert einige bewährte SSE-Praktiken direkt out of the box.
- Alle 15 Sekunden, wenn keine Nachricht gesendet wurde, einen **„keep alive“-`ping`-Kommentar** senden, um zu verhindern, dass einige Proxys die Verbindung schließen, wie in der [HTML-Spezifikation: Server-Sent Events](https://html.spec.whatwg.org/multipage/server-sent-events.html#authoring-notes) vorgeschlagen.
- Einen **„keep alive“-`ping`-Kommentar** alle 15 Sekunden senden, wenn keine Nachricht gesendet wurde, um zu verhindern, dass einige Proxys die Verbindung schließen, wie in der [HTML-Spezifikation: Server-Sent Events](https://html.spec.whatwg.org/multipage/server-sent-events.html#authoring-notes) vorgeschlagen.
- Den Header `Cache-Control: no-cache` setzen, um **Caching** des Streams zu verhindern.
- Einen speziellen Header `X-Accel-Buffering: no` setzen, um **Buffering** in einigen Proxys wie Nginx zu verhindern.
Sie könnten eine Folge von Daten haben, die Sie in einem „Stream“ senden möchten, das können Sie mit **JSON Lines** tun.
/// info | Info
/// note | Hinweis
Hinzugefügt in FastAPI 0.134.0.
@ -48,7 +48,7 @@ Eine Response hätte einen Content-Type von `application/jsonl` (anstelle von `a
Es ist einem JSON-Array (entspricht einer Python-Liste) sehr ähnlich, aber anstatt in `[]` eingeschlossen zu sein und `,` zwischen den Elementen zu haben, gibt es hier **ein JSON-Objekt pro Zeile**, sie sind durch ein Zeilenumbruchzeichen getrennt.
/// info | Info
/// note | Hinweis
Der wichtige Punkt ist, dass Ihre App in der Lage ist, jede Zeile der Reihe nach zu erzeugen, während der Client die vorherigen Zeilen konsumiert.
@ -8,7 +8,7 @@ Damit können Sie [pytest](https://docs.pytest.org/) direkt mit **FastAPI** verw
## `TestClient` verwenden { #using-testclient }
/// info | Info
/// note | Hinweis
Um `TestClient` zu verwenden, installieren Sie zunächst [`httpx`](https://www.python-httpx.org).
@ -145,7 +145,7 @@ Z. B.:
Weitere Informationen zum Übergeben von Daten an das Backend (mithilfe von `httpx` oder dem `TestClient`) finden Sie in der [HTTPX-Dokumentation](https://www.python-httpx.org).
/// info | Info
/// note | Hinweis
Beachten Sie, dass der `TestClient` Daten empfängt, die nach JSON konvertiert werden können, keine Pydantic-Modelle.
Some of these solutions may also be open source or offer free tiers, so you can try them without a financial commitment. Other commercial SDK generators are available and can be found online. 🤓
@ -167,13 +167,13 @@ Notice how the callback URL used contains the URL received as a query parameter
At this point you have the *callback path operation(s)* needed (the one(s) that the *external developer* should implement in the *external API*) in the callback router you created above.
Now use the parameter `callbacks` in *your API's path operation decorator* to pass the attribute `.routes`(that's actually just a `list` of routes/*path operations*) from that callback router:
Now use the parameter `callbacks` in *your API's path operation decorator* to pass the attribute `.routes` from that callback router:
Notice that you are not passing the router itself (`invoices_callback_router`) to `callback=`, but the attribute`.routes`, as in `invoices_callback_router.routes`.
Notice that you are not passing the router itself (`invoices_callback_router`) to `callbacks=`, but its`.routes`, as in `invoices_callback_router.routes`. FastAPI will use those routes to generate the callback OpenAPI documentation.
@ -16,17 +16,11 @@ You would have to make sure that it is unique for each operation.
### Using the *path operation function* name as the operationId { #using-the-path-operation-function-name-as-the-operationid }
If you want to use your APIs' function names as `operationId`s, you can iterate over all of them and override each *path operation's*`operation_id` using their `APIRoute.name`.
If you want to use your APIs' function names as `operationId`s, you can pass a custom `generate_unique_id_function` to `FastAPI`.
You should do it after adding all your *path operations*.
The function receives each `APIRoute` and returns the `operationId` to use for that path operation.
You can deploy your FastAPI app to [FastAPI Cloud](https://fastapicloud.com) with **one command**, go and join the waiting list if you haven't. 🚀
## Login { #login }
Make sure you already have a **FastAPI Cloud** account (we invited you from the waiting list 😉).
Then log in:
<divclass="termy">
```console
$ fastapi login
You are logged in to FastAPI Cloud 🚀
```
</div>
## Deploy { #deploy }
Now deploy your app, with **one command**:
You can deploy your FastAPI app to [FastAPI Cloud](https://fastapicloud.com) with just **one command**. 🚀
<divclass="termy">
@ -36,6 +16,8 @@ Deploying to FastAPI Cloud...
</div>
The CLI will automatically detect your FastAPI application and deploy it to the cloud. If you are not logged in, your browser will open to complete the authentication process.
That's it! Now you can access your app at that URL. ✨
@ -25,7 +25,15 @@ And that function `get_openapi()` receives as parameters:
* `openapi_version`: The version of the OpenAPI specification used. By default, the latest: `3.1.0`.
* `summary`: A short summary of the API.
* `description`: The description of your API, this can include markdown and will be shown in the docs.
* `routes`: A list of routes, these are each of the registered *path operations*. They are taken from `app.routes`.
* `routes`: The routes from the application, taken from `app.routes`. FastAPI uses them to collect the registered *path operations*, including those from included routers.
/// tip | Technical Details
`app.routes` is a lower-level route tree. It can include route candidates that FastAPI uses internally for included routers, not only final `APIRoute` objects.
You can still pass `app.routes` to `get_openapi()`. FastAPI will traverse that route tree to collect the effective path operations.
@ -492,9 +492,7 @@ For a more complete example including more features, see the <a href="https://fa
### Deploy your app (optional) { #deploy-your-app-optional }
You can optionally deploy your FastAPI app to [FastAPI Cloud](https://fastapicloud.com), go and join the waiting list if you haven't. 🚀
If you already have a **FastAPI Cloud** account (we invited you from the waiting list 😉), you can deploy your application with one command.
You can optionally deploy your FastAPI app to [FastAPI Cloud](https://fastapicloud.com) with a single command. 🚀
<divclass="termy">
@ -510,6 +508,8 @@ Deploying to FastAPI Cloud...
</div>
The CLI will automatically detect your FastAPI application and deploy it to the cloud. If you are not logged in, your browser will open to complete the authentication process.
That's it! Now you can access your app at that URL. ✨
* 🌐 Update translations for fr (update-outdated). PR [#15761](https://github.com/fastapi/fastapi/pull/15761) by [@tiangolo](https://github.com/tiangolo).
* 🌐 Update translations for zh-hant (update-outdated). PR [#15760](https://github.com/fastapi/fastapi/pull/15760) by [@tiangolo](https://github.com/tiangolo).
* 🌐 Update translations for de (update-outdated). PR [#15759](https://github.com/fastapi/fastapi/pull/15759) by [@tiangolo](https://github.com/tiangolo).
* 🌐 Update translations for ko (update-outdated). PR [#15757](https://github.com/fastapi/fastapi/pull/15757) by [@tiangolo](https://github.com/tiangolo).
* 🌐 Update translations for uk (update-outdated). PR [#15756](https://github.com/fastapi/fastapi/pull/15756) by [@tiangolo](https://github.com/tiangolo).
* 🌐 Update translations for zh (update-outdated). PR [#15755](https://github.com/fastapi/fastapi/pull/15755) by [@tiangolo](https://github.com/tiangolo).
* 🌐 Update translations for tr (update-outdated). PR [#15754](https://github.com/fastapi/fastapi/pull/15754) by [@tiangolo](https://github.com/tiangolo).
* 🌐 Update translations for pt (update-outdated). PR [#15753](https://github.com/fastapi/fastapi/pull/15753) by [@tiangolo](https://github.com/tiangolo).
* 🌐 Update translations for es (update-outdated). PR [#15752](https://github.com/fastapi/fastapi/pull/15752) by [@tiangolo](https://github.com/tiangolo).
* 🌐 Update translations for ja (update-outdated). PR [#15751](https://github.com/fastapi/fastapi/pull/15751) by [@tiangolo](https://github.com/tiangolo).
* 🌐 Update translations for ru (update-outdated). PR [#15758](https://github.com/fastapi/fastapi/pull/15758) by [@tiangolo](https://github.com/tiangolo).
### Internal
* 🔥 Remove unused scripts. PR [#15771](https://github.com/fastapi/fastapi/pull/15771) by [@tiangolo](https://github.com/tiangolo).
* 🔧 Add ty configs to check docs sources. PR [#15770](https://github.com/fastapi/fastapi/pull/15770) by [@tiangolo](https://github.com/tiangolo).
* 🔧 Add ty configs to check docs sources. PR [#15769](https://github.com/fastapi/fastapi/pull/15769) by [@tiangolo](https://github.com/tiangolo).
## 0.137.1 (2026-06-15)
### Fixes
* 🚨 Fix typing checks for APIRoute. PR [#15765](https://github.com/fastapi/fastapi/pull/15765) by [@tiangolo](https://github.com/tiangolo).
* 🐛 Fix bug, allow empty path in path operation in prefixless router. PR [#15763](https://github.com/fastapi/fastapi/pull/15763) by [@tiangolo](https://github.com/tiangolo).
## 0.137.0 (2026-06-14)
### Breaking Changes
* ♻️ Refactor internals to preserve `APIRouter` and `APIRoute` instances. PR [#15745](https://github.com/fastapi/fastapi/pull/15745) by [@tiangolo](https://github.com/tiangolo).
Unblocks ✨ SO MANY THINGS ✨
Before this, `router.include_router(other_router)` would take each path operation from `other_router` and "clone" it, or recreate it from scratch.
This would mean that in the end there was only one top level router, part of the app.
The way it is structured here is that there are a few additional classes to handle intermediate metadata for router and route inclusion. That way the information of "router X includes Y and Y includes Z" is stored somewhere, without affecting (recreating / clonning) the final route.
#### Non Objectives
Dependencies for 404: previously I intended to support dependencies that would be executed even for 404, but that would conflict with the fact that a router could _not_ find a match, but the next router _did_ find a match. Executing dependencies in the router that did not find a match would not make sense, they could consume the request, body, etc. This original idea was discarded.
#### Specific Breaking Changes
Now `router.routes` is no longer a plain list of `APIRoute` objects, it can contain these intermediate objects that can contain additional routers, forming a tree.
Any logic that depended on iterating on the `router.routes` directly would be affected, that logic cannot expect to be able to extract data from a plain list of routes, as it's no longer a plain list but a tree.
Additionally, any logic that iterated on `router.routes` to modify them would now also see these new objects, and would not see all the routes in the app.
`router.routes` should be considered an internal implementation detail, only passed around to the FastAPI functions that need it.
#### Features
* Adding routes (path operations) after a router is included now works, they are reflected as they are not copied.
* Including `subrouter` in `mainrouter` can be done before adding routes (path operations) to `subrouter`, because now the the entire object is stored instead of copying the routes.
* As routes are not copied, in some cases that might save some memory.
#### Alpha Features
This is not documented yet, so it's not officially supported yet and could change in the future.
But, as `APIRoute` and `APIRouter` instances are now preserved, they could be customized.
`APIRouter` has two new methods, `.matches()` and `.handle()`, counterpart to the existing ones in `APIRoute`. With this a router could customize how it matches and handles requests. For example, it could match only requests that include some specific header, for example for handling versions in headers.
Still, for now, consider this very experimental and potentially changing and breaking in the future.
#### Future Features Enabled
* Custom `APIRoute` subclasses (undocumented, but alraedy works as desccribed above)
* Custom `APIRouter` subclasses (undocumented, but already works as described above)
* Dependencies per router
* Exception handlers per router
* Middleware per router
* Other features planned
### Docs
* 📝 Update release notes. PR [#15747](https://github.com/fastapi/fastapi/pull/15747) by [@tiangolo](https://github.com/tiangolo).
* ✏️ Use `Annotated` in inline example in `docs/en/docs/tutorial/body-multiple-params.md`. PR [#15591](https://github.com/fastapi/fastapi/pull/15591) by [@TheArchons](https://github.com/TheArchons).
* 📝 Remove "NGINX Unit" from the list of ASGI-servers in docs. PR [#15475](https://github.com/fastapi/fastapi/pull/15475) by [@angryfoxx](https://github.com/angryfoxx).
* 📝 Update `docs/en/docs/tutorial/security/oauth2-jwt.md`. PR [#14781](https://github.com/fastapi/fastapi/pull/14781) by [@zadevhub](https://github.com/zadevhub).
@ -29,6 +111,16 @@ hide:
### Internal
* 🔧 Update sponsors: remove TalorData. PR [#15744](https://github.com/fastapi/fastapi/pull/15744) by [@tiangolo](https://github.com/tiangolo).
* 🔧 Update sponsors: remove ExoFlare. PR [#15736](https://github.com/fastapi/fastapi/pull/15736) by [@tiangolo](https://github.com/tiangolo).
* 🔧 Update sponsors: remove InterviewPal. PR [#15735](https://github.com/fastapi/fastapi/pull/15735) by [@tiangolo](https://github.com/tiangolo).
* 🔧 Update sponsors: remove Liblab. PR [#15731](https://github.com/fastapi/fastapi/pull/15731) by [@tiangolo](https://github.com/tiangolo).
* 🔧 Update sponsors: remove Scalar. PR [#15730](https://github.com/fastapi/fastapi/pull/15730) by [@tiangolo](https://github.com/tiangolo).
* ⬆ Bump the python-packages group across 1 directory with 6 updates. PR [#15721](https://github.com/fastapi/fastapi/pull/15721) by [@dependabot[bot]](https://github.com/apps/dependabot).
* ⬆ Bump python-multipart from 0.0.29 to 0.0.30. PR [#15723](https://github.com/fastapi/fastapi/pull/15723) by [@dependabot[bot]](https://github.com/apps/dependabot).
* ⬆ Bump the github-actions group with 3 updates. PR [#15720](https://github.com/fastapi/fastapi/pull/15720) by [@dependabot[bot]](https://github.com/apps/dependabot).
* ⬆ Bump starlette from 1.1.0 to 1.2.1. PR [#15722](https://github.com/fastapi/fastapi/pull/15722) by [@dependabot[bot]](https://github.com/apps/dependabot).
* ⬆ Bump https://github.com/crate-ci/typos from v1.46.0 to v1.47.1 in the pre-commit group. PR [#15719](https://github.com/fastapi/fastapi/pull/15719) by [@dependabot[bot]](https://github.com/apps/dependabot).
* 🔧 Update sponsors, add Rapidproxy. PR [#15689](https://github.com/fastapi/fastapi/pull/15689) by [@tiangolo](https://github.com/tiangolo).
* 🔧 Update sponsors: Remove TestMu. PR [#15688](https://github.com/fastapi/fastapi/pull/15688) by [@tiangolo](https://github.com/tiangolo).
* ⬆ Bump the python-packages group across 1 directory with 11 updates. PR [#15683](https://github.com/fastapi/fastapi/pull/15683) by [@dependabot[bot]](https://github.com/apps/dependabot).
@ -396,9 +396,9 @@ It will include all the routes from that router as part of it.
/// note | Technical Details
It will actually internally create a *path operation* for each *path operation* that was declared in the `APIRouter`.
FastAPI keeps the original `APIRouter` and its `APIRoute`s active when the router is included in the main application.
So, behind the scenes, it will actually work as if everything was the same single app.
That means custom `APIRouter` and `APIRoute` subclasses can still participate after the router is included.
///
@ -406,7 +406,7 @@ So, behind the scenes, it will actually work as if everything was the same singl
You don't have to worry about performance when including routers.
This will take microseconds and will only happen at startup.
This is designed to be lightweight and to avoid adding overhead to each request.
So it won't affect performance. ⚡
@ -461,7 +461,7 @@ The `APIRouter`s are not "mounted", they are not isolated from the rest of the a
This is because we want to include their *path operations* in the OpenAPI schema and the user interfaces.
As we cannot just isolate them and "mount" them independently of the rest, the *path operations* are "cloned" (re-created), not included directly.
FastAPI keeps the original routers and path operations active, and combines the router prefixes, dependencies, tags, responses, and other metadata when handling requests and generating OpenAPI.
///
@ -532,4 +532,16 @@ The same way you can include an `APIRouter` in a `FastAPI` application, you can
router.include_router(other_router)
```
Make sure you do it before including `router` in the `FastAPI` app, so that the *path operations* from `other_router` are also included.
You can do this before or after including `router` in the `FastAPI` app. FastAPI will still include the *path operations* from `other_router` in routing and OpenAPI.
The same applies to *path operations* added later to the routers. They will be visible through the earlier inclusion too.
/// warning | Technical Details
Avoid directly mutating `router.routes` after including a router. FastAPI treats router inclusion as live, so the original router and its routes remain part of routing and OpenAPI generation.
Use documented APIs such as path operation decorators and `.include_router()` to add routes and routers.
Treat `router.routes` as a lower-level route tree that can contain route definitions and included routers, and avoid relying on it as a flat list of final path operations.
@ -200,23 +200,7 @@ Additionally, other tools might not be able to find it, for example the [VS Code
### Deploy your app (optional) { #deploy-your-app-optional }
You can optionally deploy your FastAPI app to [FastAPI Cloud](https://fastapicloud.com), go and join the waiting list if you haven't. 🚀
If you already have a **FastAPI Cloud** account (we invited you from the waiting list 😉), you can deploy your application with one command.
Before deploying, make sure you are logged in:
<divclass="termy">
```console
$ fastapi login
You are logged in to FastAPI Cloud 🚀
```
</div>
Then deploy your app:
You can optionally deploy your FastAPI app to [FastAPI Cloud](https://fastapicloud.com) with a single command. 🚀
<divclass="termy">
@ -232,6 +216,8 @@ Deploying to FastAPI Cloud...
</div>
The CLI will automatically detect your FastAPI application and deploy it to the cloud. If you are not logged in, your browser will open to complete the authentication process.
That's it! Now you can access your app at that URL. ✨
<atitle="Auth, user management and more for your B2B product"style="display: block; position: relative;"href="https://www.propelauth.com/?utm_source=fastapi&utm_campaign=1223&utm_medium=topbanner"target="_blank">
<atitle="Deploy & scale any full-stack web app on Render. Focus on building apps, not infra."style="display: block; position: relative;"href="https://docs.render.com/deploy-fastapi?utm_source=deploydoc&utm_medium=referral&utm_campaign=fastapi"target="_blank">
@ -34,7 +34,7 @@ Ten en cuenta que debes devolver el `JSONResponse` directamente.
///
/// info | Información
/// note | Nota
La clave `model` no es parte de OpenAPI.
@ -183,7 +183,7 @@ Nota que debes devolver la imagen usando un `FileResponse` directamente.
///
/// info | Información
/// note | Nota
A menos que especifiques un media type diferente explícitamente en tu parámetro `responses`, FastAPI asumirá que el response tiene el mismo media type que la clase de response principal (por defecto `application/json`).
@ -98,7 +98,7 @@ Por ejemplo, si tenías una sesión de base de datos en una dependencia con `yie
Este comportamiento se revirtió en la 0.118.0, para hacer que el código de salida después de `yield` se ejecute después de que la response sea enviada.
/// info | Información
/// note | Nota
Como verás abajo, esto es muy similar al comportamiento anterior a la versión 0.106.0, pero con varias mejoras y arreglos de bugs para casos límite.
@ -24,7 +24,7 @@ Si declaras un [Response Model](../tutorial/response-model.md) FastAPI lo usará
Si no declaras un response model, FastAPI usará el `jsonable_encoder` explicado en [Codificador Compatible con JSON](../tutorial/encoder.md) y lo pondrá en un `JSONResponse`.
Si declaras un `response_class` con un media type JSON (`application/json`), como es el caso con `JSONResponse`, los datos que devuelvas se convertirán automáticamente (y serán filtrados) con cualquier `response_model` de Pydantic que hayas declarado en el *path operation decorator*. Pero los datos no se serializarán a bytes JSON con Pydantic, en su lugar se convertirán con el `jsonable_encoder` y luego se pasarán a la clase `JSONResponse`, que los serializará a bytes usando la librería JSON estándar de Python.
Si declaras un `response_class` con un media type JSON (`application/json`), como es el caso con `JSONResponse`, los datos que devuelvas se convertirán automáticamente (y serán filtrados) con cualquier `response_model` de Pydantic que hayas declarado en el *path operation decorator*. Pero los datos no se serializarán a bytes JSON con Pydantic, en su lugar se convertirán con el `jsonable_encoder` y luego se pasarán a la clase `JSONResponse`, que los serializará a bytes usando el paquete JSON estándar de Python.
### Rendimiento JSON { #json-performance }
@ -41,7 +41,7 @@ Para devolver un response con HTML directamente desde **FastAPI**, usa `HTMLResp
El parámetro `response_class` también se utilizará para definir el "media type" del response.
@ -65,7 +65,7 @@ Una `Response` devuelta directamente por tu *path operation function* no se docu
///
/// info | Información
/// note | Nota
Por supuesto, el `Content-Type` header real, el código de estado, etc., provendrán del objeto `Response` que devolviste.
@ -181,7 +181,7 @@ Toma un generador `async` o un generador/iterador normal (una función con `yiel
Una tarea `async` solo puede cancelarse cuando llega a un `await`. Si no hay `await`, el generador (función con `yield`) no se puede cancelar correctamente y puede seguir ejecutándose incluso después de solicitar la cancelación.
Como este pequeño ejemplo no necesita ninguna sentencia`await`, añadimos un `await anyio.sleep(0)` para darle al loop de eventos la oportunidad de manejar la cancelación.
Como este pequeño ejemplo no necesita ninguna statement`await`, añadimos un `await anyio.sleep(0)` para darle al loop de eventos la oportunidad de manejar la cancelación.
Esto sería aún más importante con streams grandes o infinitos.
@ -120,7 +120,7 @@ Para añadir una función que debería ejecutarse cuando la aplicación se esté
Aquí, la función manejadora del evento `shutdown` escribirá una línea de texto `"Application shutdown"` a un archivo `log.txt`.
/// info | Información
/// note | Nota
En la función `open()`, el `mode="a"` significa "añadir", por lo tanto, la línea será añadida después de lo que sea que esté en ese archivo, sin sobrescribir el contenido anterior.
@ -152,7 +152,7 @@ Solo un detalle técnico para los nerds curiosos. 🤓
Por debajo, en la especificación técnica ASGI, esto es parte del [Protocolo de Lifespan](https://asgi.readthedocs.io/en/latest/specs/lifespan.html), y define eventos llamados `startup` y `shutdown`.
/// info | Información
/// note | Nota
Puedes leer más sobre los manejadores `lifespan` de Starlette en [la documentación de `Lifespan` de Starlette](https://www.starlette.dev/lifespan/).
@ -22,16 +22,15 @@ FastAPI genera automáticamente especificaciones **OpenAPI 3.1**, así que cualq
## Generadores de SDKs de sponsors de FastAPI { #sdk-generators-from-fastapi-sponsors }
Esta sección destaca soluciones **respaldadas por empresas** y **venture-backed** de compañías que sponsorean FastAPI. Estos productos ofrecen **funcionalidades adicionales** e **integraciones** además de SDKs generados de alta calidad.
Esta sección destaca soluciones **respaldadas por empresas** y **venture-backed** de compañías que sponsor FastAPI. Estos productos ofrecen **funcionalidades adicionales** e **integraciones** además de SDKs generados de alta calidad.
Al ✨ [**sponsorear FastAPI**](../help-fastapi.md#sponsor-the-author) ✨, estas compañías ayudan a asegurar que el framework y su **ecosistema** se mantengan saludables y **sustentables**.
Al ✨ [**ser sponsor de FastAPI**](../help-fastapi.md#sponsor-the-author) ✨, estas compañías ayudan a asegurar que el framework y su **ecosistema** se mantengan saludables y **sustentables**.
Su sponsorship también demuestra un fuerte compromiso con la **comunidad** de FastAPI (tú), mostrando que no solo les importa ofrecer un **gran servicio**, sino también apoyar un **framework robusto y próspero**, FastAPI. 🙇
Algunas de estas soluciones también pueden ser open source u ofrecer niveles gratuitos, así que puedes probarlas sin un compromiso financiero. Hay otros generadores de SDK comerciales disponibles y se pueden encontrar en línea. 🤓
@ -4,7 +4,7 @@ Podrías crear una API con una *path operation* que podría desencadenar un requ
El proceso que ocurre cuando tu aplicación API llama a la *API externa* se llama un "callback". Porque el software que escribió el desarrollador externo envía un request a tu API y luego tu API hace un *callback*, enviando un request a una *API externa* (que probablemente fue creada por el mismo desarrollador).
En este caso, podrías querer documentar cómo esa API externa *debería* verse. Qué *path operation* debería tener, qué cuerpo debería esperar, qué response debería devolver, etc.
En este caso, podrías querer documentar cómo esa API externa *debería* verse. Qué *path operation* debería tener, qué body debería esperar, qué response debería devolver, etc.
## Una aplicación con callbacks { #an-app-with-callbacks }
@ -167,13 +167,13 @@ Observa cómo la URL del callback utilizada contiene la URL recibida como parám
En este punto tienes las *path operation(s)* del callback necesarias (las que el *desarrollador externo* debería implementar en la *API externa*) en el router de callback que creaste arriba.
Ahora usa el parámetro `callbacks` en el *decorador de path operation de tu API* para pasar el atributo `.routes`(que en realidad es solo un `list` de rutas/*path operations*) de ese router de callback:
Ahora usa el parámetro `callbacks` en el *decorador de path operation de tu API* para pasar el atributo `.routes` de ese router de callback:
Observa que no estás pasando el router en sí (`invoices_callback_router`) a `callback=`, sino el atributo`.routes`, como en `invoices_callback_router.routes`.
Observa que no estás pasando el router en sí (`invoices_callback_router`) a `callbacks=`, sino su`.routes`, como en `invoices_callback_router.routes`.**FastAPI** usará esas rutas para generar la documentación OpenAPI del callback.
@ -22,7 +22,7 @@ Con **FastAPI**, usando OpenAPI, puedes definir los nombres de estos webhooks, l
Esto puede hacer mucho más fácil para tus usuarios **implementar sus APIs** para recibir tus requests de **webhook**, incluso podrían ser capaces de autogenerar algo de su propio código de API.
/// info | Información
/// note | Nota
Los webhooks están disponibles en OpenAPI 3.1.0 y superiores, soportados por FastAPI `0.99.0` y superiores.
@ -36,7 +36,7 @@ Cuando creas una aplicación de **FastAPI**, hay un atributo `webhooks` que pued
Los webhooks que defines terminarán en el esquema de **OpenAPI** y en la interfaz automática de **documentación**.
/// info | Información
/// note | Nota
El objeto `app.webhooks` es en realidad solo un `APIRouter`, el mismo tipo que usarías al estructurar tu aplicación con múltiples archivos.
@ -16,17 +16,11 @@ Tendrías que asegurarte de que sea único para cada operación.
### Usar el nombre de la *path operation function* como el operationId { #using-the-path-operation-function-name-as-the-operationid }
Si quieres usar los nombres de las funciones de tus APIs como `operationId`s, puedes iterar sobre todas ellas y sobrescribir el `operation_id` de cada *path operation* usando su `APIRoute.name`.
Si quieres usar los nombres de las funciones de tus APIs como `operationId`s, puedes pasar una `generate_unique_id_function` personalizada a `FastAPI`.
Deberías hacerlo después de agregar todas tus *path operations*.
La función recibe cada `APIRoute` y devuelve el `operationId` a usar para esa *path operation*.
@ -16,9 +16,9 @@ Normalmente tendrás mucho mejor rendimiento usando un [Response Model](../tutor
## Devolver una `Response` { #return-a-response }
De hecho, puedes devolver cualquier`Response` o cualquier subclase de ella.
Puedes devolver una`Response` o cualquier subclase de ella.
/// info | Información
/// note | Nota
`JSONResponse` en sí misma es una subclase de `Response`.
@ -78,6 +78,6 @@ En su lugar, toma los bytes JSON generados con Pydantic usando el response model
Cuando devuelves una `Response` directamente, sus datos no son validados, convertidos (serializados), ni documentados automáticamente.
Pero aún puedes documentarlo como se describe en [Additional Responses in OpenAPI](additional-responses.md).
Pero aún puedes documentarlo como se describe en [Respuestas adicionales en OpenAPI](additional-responses.md).
Puedes ver en secciones posteriores cómo usar/declarar estas `Response`s personalizadas mientras todavía tienes conversión automática de datos, documentación, etc.
@ -40,7 +40,7 @@ Ten en cuenta que ambos tienen el mismo host.
Luego, usando el frontend, puedes hacer que el agente de IA haga cosas en tu nombre.
Como está corriendo localmente y no en Internet abierta, decides no tener ninguna autenticación configurada, confiando simplemente en el acceso a la red local.
Como está corriendo **localmente** y no en Internet abierta, decides **no tener ninguna autenticación** configurada, confiando simplemente en el acceso a la red local.
Entonces, uno de tus usuarios podría instalarlo y ejecutarlo localmente.
@ -69,9 +69,9 @@ Si tu app está en Internet abierta, no “confiarías en la red” ni permitir
Los atacantes podrían simplemente ejecutar un script para enviar requests a tu API, sin necesidad de interacción del navegador, así que probablemente ya estás asegurando cualquier endpoint privilegiado.
En ese caso, este ataque/riesgo no aplica a ti.
En ese caso, **este ataque/riesgo no aplica a ti**.
Este riesgo y ataque es relevante principalmente cuando la app corre en la red local y esa es la única protección asumida.
Este riesgo y ataque es relevante principalmente cuando la app corre en la **red local** y esa es la **única protección asumida**.
## Permitir requests sin Content-Type { #allowing-requests-without-content-type }
@ -81,7 +81,7 @@ Si necesitas soportar clientes que no envían un header `Content-Type`, puedes d
Con esta configuración, las requests sin un header `Content-Type` tendrán su body parseado como JSON, que es el mismo comportamiento de versiones anteriores de FastAPI.
/// info | Información
/// note | Nota
Este comportamiento y configuración se añadieron en FastAPI 0.132.0.