diff --git a/README.md b/README.md index 393ce9f01..6f13f9eae 100644 --- a/README.md +++ b/README.md @@ -47,7 +47,6 @@ The key features are: - @@ -55,7 +54,6 @@ The key features are: - diff --git a/docs/de/docs/deployment/cloud.md b/docs/de/docs/deployment/cloud.md index 2d70fe4e5..042a92a81 100644 --- a/docs/de/docs/deployment/cloud.md +++ b/docs/de/docs/deployment/cloud.md @@ -10,8 +10,4 @@ Einige Cloud-Anbieter ✨ [**sponsern FastAPI**](../help-fastapi.md#den-autor-sp Und es zeigt deren wahres Engagement für FastAPI und seine **Community** (Sie), da diese Ihnen nicht nur einen **guten Service** bieten möchten, sondern auch sicherstellen möchten, dass Sie über ein **gutes und gesundes Framework** verfügen, FastAPI. 🙇 -Vielleicht möchten Sie deren Dienste ausprobieren und deren Anleitungen folgen: - -* Platform.sh -* Porter -* Coherence +Vielleicht möchten Sie deren Dienste ausprobieren und deren Anleitungen folgen. diff --git a/docs/en/data/sponsors.yml b/docs/en/data/sponsors.yml index 2b3cd282d..ae28410e7 100644 --- a/docs/en/data/sponsors.yml +++ b/docs/en/data/sponsors.yml @@ -2,9 +2,6 @@ gold: - url: https://blockbee.io?ref=fastapi title: BlockBee Cryptocurrency Payment Gateway img: https://fastapi.tiangolo.com/img/sponsors/blockbee.png - - url: https://platform.sh/try-it-now/?utm_source=fastapi-signup&utm_medium=banner&utm_campaign=FastAPI-signup-June-2023 - title: "Build, run and scale your apps on a modern, reliable, and secure PaaS." - img: https://fastapi.tiangolo.com/img/sponsors/platform-sh.png - url: https://github.com/scalar/scalar/?utm_source=fastapi&utm_medium=website&utm_campaign=main-badge title: "Scalar: Beautiful Open-Source API References from Swagger/OpenAPI files" img: https://fastapi.tiangolo.com/img/sponsors/scalar.svg @@ -26,9 +23,6 @@ gold: - url: https://subtotal.com/?utm_source=fastapi&utm_medium=sponsorship&utm_campaign=open-source title: The Gold Standard in Retail Account Linking img: https://fastapi.tiangolo.com/img/sponsors/subtotal.svg - - url: https://vibe.mobb.ai/?utm_source=Fast+APi&utm_medium=Image&utm_campaign=MVS - title: Secure Your AI-Generated Code to Unlock Dev Productivity - img: https://fastapi.tiangolo.com/img/sponsors/mobbai.png - url: https://docs.railway.com/guides/fastapi?utm_medium=integration&utm_source=docs&utm_campaign=fastapi title: Deploy enterprise applications at startup speed img: https://fastapi.tiangolo.com/img/sponsors/railway.png diff --git a/docs/en/docs/advanced/behind-a-proxy.md b/docs/en/docs/advanced/behind-a-proxy.md index 0f100306a..4d19d29e0 100644 --- a/docs/en/docs/advanced/behind-a-proxy.md +++ b/docs/en/docs/advanced/behind-a-proxy.md @@ -1,6 +1,105 @@ # Behind a Proxy { #behind-a-proxy } -In some situations, you might need to use a **proxy** server like Traefik or Nginx with a configuration that adds an extra path prefix that is not seen by your application. +In many situations, you would use a **proxy** like Traefik or Nginx in front of your FastAPI app. + +These proxies could handle HTTPS certificates and other things. + +## Proxy Forwarded Headers { #proxy-forwarded-headers } + +A **proxy** in front of your application would normally set some headers on the fly before sending the requests to your **server** to let the server know that the request was **forwarded** by the proxy, letting it know the original (public) URL, including the domain, that it is using HTTPS, etc. + +The **server** program (for example **Uvicorn** via **FastAPI CLI**) is capable of interpreting these headers, and then passing that information to your application. + +But for security, as the server doesn't know it is behind a trusted proxy, it won't interpret those headers. + +/// note | Technical Details + +The proxy headers are: + +* X-Forwarded-For +* X-Forwarded-Proto +* X-Forwarded-Host + +/// + +### Enable Proxy Forwarded Headers { #enable-proxy-forwarded-headers } + +You can start FastAPI CLI with the *CLI Option* `--forwarded-allow-ips` and pass the IP addresses that should be trusted to read those forwarded headers. + +If you set it to `--forwarded-allow-ips="*"` it would trust all the incoming IPs. + +If your **server** is behind a trusted **proxy** and only the proxy talks to it, this would make it accept whatever is the IP of that **proxy**. + +
+ +```console +$ fastapi run --forwarded-allow-ips="*" + +INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit) +``` + +
+ +### Redirects with HTTPS { #redirects-with-https } + +For example, let's say you define a *path operation* `/items/`: + +{* ../../docs_src/behind_a_proxy/tutorial001_01.py hl[6] *} + +If the client tries to go to `/items`, by default, it would be redirected to `/items/`. + +But before setting the *CLI Option* `--forwarded-allow-ips` it could redirect to `http://localhost:8000/items/`. + +But maybe your application is hosted at `https://mysuperapp.com`, and the redirection should be to `https://mysuperapp.com/items/`. + +By setting `--proxy-headers` now FastAPI would be able to redirect to the right location. 😎 + +``` +https://mysuperapp.com/items/ +``` + +/// tip + +If you want to learn more about HTTPS, check the guide [About HTTPS](../deployment/https.md){.internal-link target=_blank}. + +/// + +### How Proxy Forwarded Headers Work + +Here's a visual representation of how the **proxy** adds forwarded headers between the client and the **application server**: + +```mermaid +sequenceDiagram + participant Client + participant Proxy as Proxy/Load Balancer + participant Server as FastAPI Server + + Client->>Proxy: HTTPS Request
Host: mysuperapp.com
Path: /items + + Note over Proxy: Proxy adds forwarded headers + + Proxy->>Server: HTTP Request
X-Forwarded-For: [client IP]
X-Forwarded-Proto: https
X-Forwarded-Host: mysuperapp.com
Path: /items + + Note over Server: Server interprets headers
(if --forwarded-allow-ips is set) + + Server->>Proxy: HTTP Response
with correct HTTPS URLs + + Proxy->>Client: HTTPS Response +``` + +The **proxy** intercepts the original client request and adds the special *forwarded* headers (`X-Forwarded-*`) before passing the request to the **application server**. + +These headers preserve information about the original request that would otherwise be lost: + +* **X-Forwarded-For**: The original client's IP address +* **X-Forwarded-Proto**: The original protocol (`https`) +* **X-Forwarded-Host**: The original host (`mysuperapp.com`) + +When **FastAPI CLI** is configured with `--forwarded-allow-ips`, it trusts these headers and uses them, for example to generate the correct URLs in redirects. + +## Proxy with a stripped path prefix { #proxy-with-a-stripped-path-prefix } + +You could have a proxy that adds a path prefix to your application. In these cases you can use `root_path` to configure your application. @@ -10,8 +109,6 @@ The `root_path` is used to handle these specific cases. And it's also used internally when mounting sub-applications. -## Proxy with a stripped path prefix { #proxy-with-a-stripped-path-prefix } - Having a proxy with a stripped path prefix, in this case, means that you could declare a path at `/app` in your code, but then, you add a layer on top (the proxy) that would put your **FastAPI** application under a path like `/api/v1`. In this case, the original path `/app` would actually be served at `/api/v1/app`. @@ -73,7 +170,7 @@ To achieve this, you can use the command line option `--root-path` like:
```console -$ fastapi run main.py --root-path /api/v1 +$ fastapi run main.py --forwarded-allow-ips="*" --root-path /api/v1 INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit) ``` @@ -103,7 +200,7 @@ Then, if you start Uvicorn with:
```console -$ fastapi run main.py --root-path /api/v1 +$ fastapi run main.py --forwarded-allow-ips="*" --root-path /api/v1 INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit) ``` @@ -224,7 +321,7 @@ And now start your app, using the `--root-path` option:
```console -$ fastapi run main.py --root-path /api/v1 +$ fastapi run main.py --forwarded-allow-ips="*" --root-path /api/v1 INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit) ``` diff --git a/docs/en/docs/deployment/cloud.md b/docs/en/docs/deployment/cloud.md index cb723dd13..c88c4b51a 100644 --- a/docs/en/docs/deployment/cloud.md +++ b/docs/en/docs/deployment/cloud.md @@ -12,7 +12,5 @@ And it shows their true commitment to FastAPI and its **community** (you), as th You might want to try their services and follow their guides: -* Platform.sh -* Porter * Render * Railway diff --git a/docs/en/docs/deployment/https.md b/docs/en/docs/deployment/https.md index b52ed40c8..a249a3672 100644 --- a/docs/en/docs/deployment/https.md +++ b/docs/en/docs/deployment/https.md @@ -190,6 +190,38 @@ To do that, and to accommodate different application needs, there are several wa All this renewal process, while still serving the app, is one of the main reasons why you would want to have a **separate system to handle HTTPS** with a TLS Termination Proxy instead of just using the TLS certificates with the application server directly (e.g. Uvicorn). +## Proxy Forwarded Headers { #proxy-forwarded-headers } + +When using a proxy to handle HTTPS, your **application server** (for example Uvicorn via FastAPI CLI) doesn't known anything about the HTTPS process, it communicates with plain HTTP with the **TLS Termination Proxy**. + +This **proxy** would normally set some HTTP headers on the fly before transmitting the request to the **application server**, to let the application server know that the request is being **forwarded** by the proxy. + +/// note | Technical Details + +The proxy headers are: + +* X-Forwarded-For +* X-Forwarded-Proto +* X-Forwarded-Host + +/// + +Nevertheless, as the **application server** doesn't know it is behind a trusted **proxy**, by default, it wouldn't trust those headers. + +But you can configure the **application server** to trust the *forwarded* headers sent by the **proxy**. If you are using FastAPI CLI, you can use the *CLI Option* `--forwarded-allow-ips` to tell it from which IPs it should trust those *forwarded* headers. + +For example, if the **application server** is only receiving communication from the trusted **proxy**, you can set it to `--forwarded-allow-ips="*"` to make it trust all incoming IPs, as it will only receive requests from whatever is the IP used by the **proxy**. + +This way the application would be able to know what is its own public URL, if it is using HTTPS, the domain, etc. + +This would be useful for example to properly handle redirects. + +/// tip + +You can learn more about this in the documentation for [Behind a Proxy - Enable Proxy Forwarded Headers](../advanced/behind-a-proxy.md#enable-proxy-forwarded-headers){.internal-link target=_blank} + +/// + ## Recap { #recap } Having **HTTPS** is very important, and quite **critical** in most cases. Most of the effort you as a developer have to put around HTTPS is just about **understanding these concepts** and how they work. diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index 85937d172..d669b5dd0 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -9,6 +9,7 @@ hide: ### Docs +* 📝 Add documentation for Behind a Proxy - Proxy Forwarded Headers, using `--forwarded-allow-ips="*"`. PR [#14028](https://github.com/fastapi/fastapi/pull/14028) by [@tiangolo](https://github.com/tiangolo). * 📝 Add deprecation info block about `dict()` in `docs/tutorial/body.md`. PR [#13906](https://github.com/fastapi/fastapi/pull/13906) by [@jomkv](https://github.com/jomkv). * 📝 Fix Twitter to be X (Twitter) everywhere in documentation. PR [#13809](https://github.com/fastapi/fastapi/pull/13809) by [@valentinDruzhinin](https://github.com/valentinDruzhinin). * 🐛 Prevent scroll-to-top on restart/fast buttons in `termynal.js`. PR [#13714](https://github.com/fastapi/fastapi/pull/13714) by [@Ashish-Pandey62](https://github.com/Ashish-Pandey62). @@ -34,6 +35,8 @@ hide: ### Internal +* 🔧 Update sponsors: remove Platform.sh. PR [#14027](https://github.com/fastapi/fastapi/pull/14027) by [@tiangolo](https://github.com/tiangolo). +* 🔧 Update sponsors: remove Mobb. PR [#14026](https://github.com/fastapi/fastapi/pull/14026) by [@tiangolo](https://github.com/tiangolo). * 🛠️ Update `mkdocs_hooks` to handle headers with permalinks when building docs. PR [#14025](https://github.com/fastapi/fastapi/pull/14025) by [@tiangolo](https://github.com/tiangolo). * ⬆ [pre-commit.ci] pre-commit autoupdate. PR [#14016](https://github.com/fastapi/fastapi/pull/14016) by [@pre-commit-ci[bot]](https://github.com/apps/pre-commit-ci). * ⬆ Bump `mkdocs-macros-plugin` from 1.3.7 to 1.3.9. PR [#14003](https://github.com/fastapi/fastapi/pull/14003) by [@YuriiMotov](https://github.com/YuriiMotov). diff --git a/docs/en/overrides/main.html b/docs/en/overrides/main.html index 131e00d44..c7ffaef5d 100644 --- a/docs/en/overrides/main.html +++ b/docs/en/overrides/main.html @@ -32,12 +32,6 @@
- -
diff --git a/docs/es/docs/deployment/cloud.md b/docs/es/docs/deployment/cloud.md index fe47d5dcf..f72b88c03 100644 --- a/docs/es/docs/deployment/cloud.md +++ b/docs/es/docs/deployment/cloud.md @@ -12,7 +12,4 @@ Y muestra su verdadero compromiso con FastAPI y su **comunidad** (tú), ya que n Podrías querer probar sus servicios y seguir sus guías: -* Platform.sh -* Porter -* Coherence * Render diff --git a/docs/ko/docs/deployment/cloud.md b/docs/ko/docs/deployment/cloud.md index 2d6938e20..dbc814bbd 100644 --- a/docs/ko/docs/deployment/cloud.md +++ b/docs/ko/docs/deployment/cloud.md @@ -10,7 +10,4 @@ 이는 FastAPI와 **커뮤니티** (여러분)에 대한 진정한 헌신을 보여줍니다. 그들은 여러분에게 **좋은 서비스**를 제공할 뿐 만이 아니라 여러분이 **훌륭하고 건강한 프레임워크인** FastAPI 를 사용하길 원하기 때문입니다. 🙇 -아래와 같은 서비스를 사용해보고 각 서비스의 가이드를 따를 수도 있습니다: - -* Platform.sh -* Porter +아래와 같은 서비스를 사용해보고 각 서비스의 가이드를 따를 수도 있습니다. diff --git a/docs/mkdocs.yml b/docs/mkdocs.yml new file mode 100644 index 000000000..e69de29bb diff --git a/docs/pt/docs/deployment/cloud.md b/docs/pt/docs/deployment/cloud.md index e6522f50f..fc490db4d 100644 --- a/docs/pt/docs/deployment/cloud.md +++ b/docs/pt/docs/deployment/cloud.md @@ -10,8 +10,4 @@ Alguns provedores de nuvem ✨ [**patrocinam o FastAPI**](../help-fastapi.md#spo E isso mostra seu verdadeiro comprometimento com o FastAPI e sua **comunidade** (você), pois eles não querem apenas fornecer a você um **bom serviço**, mas também querem ter certeza de que você tenha uma **estrutura boa e saudável**, o FastAPI. 🙇 -Talvez você queira experimentar os serviços deles e seguir os guias: - -* Platform.sh -* Porter -* Coherence +Talvez você queira experimentar os serviços deles e seguir os guias. diff --git a/docs/tr/docs/deployment/cloud.md b/docs/tr/docs/deployment/cloud.md index 5639567d4..4f82e9d0b 100644 --- a/docs/tr/docs/deployment/cloud.md +++ b/docs/tr/docs/deployment/cloud.md @@ -10,8 +10,4 @@ Bazı bulut sağlayıcılar ✨ [**FastAPI destekçileridir**](../help-fastapi.m Ayrıca, size **iyi servisler** sağlamakla kalmayıp, **iyi ve sağlıklı bir framework** olan FastAPI'a bağlılıklarını gösterir. -Bu hizmetleri denemek ve kılavuzlarını incelemek isteyebilirsiniz: - -* Platform.sh -* Porter -* Coherence +Bu hizmetleri denemek ve kılavuzlarını incelemek isteyebilirsiniz. diff --git a/docs/vi/docs/deployment/cloud.md b/docs/vi/docs/deployment/cloud.md index 9ab72769d..1d76522c3 100644 --- a/docs/vi/docs/deployment/cloud.md +++ b/docs/vi/docs/deployment/cloud.md @@ -11,7 +11,4 @@ Thêm nữa, điều này cũng thể hiện cam kết thực sự của họ đ Bạn có thể thử các dịch vụ của họ và làm theo hướng dẫn của họ: -* Platform.sh -* Porter -* Coherence * Render diff --git a/docs/zh-hant/docs/deployment/cloud.md b/docs/zh-hant/docs/deployment/cloud.md index 29ebe3ff5..426937d3e 100644 --- a/docs/zh-hant/docs/deployment/cloud.md +++ b/docs/zh-hant/docs/deployment/cloud.md @@ -10,8 +10,4 @@ 這也展現了他們對 FastAPI 和其**社群**(包括你)的真正承諾,他們不僅希望為你提供**優質的服務**,還希望確保你擁有一個**良好且健康的框架**:FastAPI。🙇 -你可能會想嘗試他們的服務,以下有他們的指南: - -* Platform.sh -* Porter -* Coherence +你可能會想嘗試他們的服務,以下有他們的指南. diff --git a/docs/zh/docs/deployment/cloud.md b/docs/zh/docs/deployment/cloud.md index b086b7b6b..8a892a560 100644 --- a/docs/zh/docs/deployment/cloud.md +++ b/docs/zh/docs/deployment/cloud.md @@ -10,7 +10,4 @@ 这表明了他们对 FastAPI 及其**社区**(您)的真正承诺,因为他们不仅想为您提供**良好的服务**,而且还想确保您拥有一个**良好且健康的框架**:FastAPI。 🙇 -您可能想尝试他们的服务并阅读他们的指南: - -* Platform.sh -* Porter +您可能想尝试他们的服务并阅读他们的指南. diff --git a/docs_src/behind_a_proxy/tutorial001_01.py b/docs_src/behind_a_proxy/tutorial001_01.py new file mode 100644 index 000000000..52b114395 --- /dev/null +++ b/docs_src/behind_a_proxy/tutorial001_01.py @@ -0,0 +1,8 @@ +from fastapi import FastAPI + +app = FastAPI() + + +@app.get("/items/") +def read_items(): + return ["plumbus", "portal gun"] diff --git a/docs_src/handling_errors/tutorial002.py b/docs_src/handling_errors/tutorial002.py index c7909ae69..28f407783 100644 --- a/docs_src/handling_errors/tutorial002.py +++ b/docs_src/handling_errors/tutorial002.py @@ -7,7 +7,10 @@ items = {"foo": "The Foo Wrestlers"} @app.get("/items-header/{item_id}") async def read_item_header(item_id: str): +<<<<<<< HEAD +======= +>>>>>>> 04662ba7f7ef44ed136abb3a45bd4d4082847f2f if item_id not in items: raise HTTPException( status_code=404, diff --git a/tests/test_tutorial/test_behind_a_proxy/test_tutorial001_01.py b/tests/test_tutorial/test_behind_a_proxy/test_tutorial001_01.py new file mode 100644 index 000000000..f13046e01 --- /dev/null +++ b/tests/test_tutorial/test_behind_a_proxy/test_tutorial001_01.py @@ -0,0 +1,21 @@ +from fastapi.testclient import TestClient + +from docs_src.behind_a_proxy.tutorial001_01 import app + +client = TestClient( + app, + base_url="https://example.com", + follow_redirects=False, +) + + +def test_redirect() -> None: + response = client.get("/items") + assert response.status_code == 307 + assert response.headers["location"] == "https://example.com/items/" + + +def test_no_redirect() -> None: + response = client.get("/items/") + assert response.status_code == 200 + assert response.json() == ["plumbus", "portal gun"]