```console
-$ fastapi run main.py --root-path /api/v1
+$ fastapi run main.py --forwarded-allow-ips="*" --root-path /api/v1
: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit)
```
@@ -90,7 +187,7 @@ And the `--root-path` command line option provides that `root_path`.
///
-### Checking the current `root_path`
+### Checking the current `root_path` { #checking-the-current-root-path }
You can get the current `root_path` used by your application for each request, it is part of the `scope` dictionary (that's part of the ASGI spec).
@@ -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)
```
@@ -119,7 +216,7 @@ The response would be something like:
}
```
-### Setting the `root_path` in the FastAPI app
+### Setting the `root_path` in the FastAPI app { #setting-the-root-path-in-the-fastapi-app }
Alternatively, if you don't have a way to provide a command line option like `--root-path` or equivalent, you can set the `root_path` parameter when creating your FastAPI app:
@@ -127,7 +224,7 @@ Alternatively, if you don't have a way to provide a command line option like `--
Passing the `root_path` to `FastAPI` would be the equivalent of passing the `--root-path` command line option to Uvicorn or Hypercorn.
-### About `root_path`
+### About `root_path` { #about-root-path }
Keep in mind that the server (Uvicorn) won't use that `root_path` for anything else than passing it to the app.
@@ -144,7 +241,7 @@ So, it won't expect to be accessed at `http://127.0.0.1:8000/api/v1/app`.
Uvicorn will expect the proxy to access Uvicorn at `http://127.0.0.1:8000/app`, and then it would be the proxy's responsibility to add the extra `/api/v1` prefix on top.
-## About proxies with a stripped path prefix
+## About proxies with a stripped path prefix { #about-proxies-with-a-stripped-path-prefix }
Keep in mind that a proxy with stripped path prefix is only one of the ways to configure it.
@@ -152,7 +249,7 @@ Probably in many cases the default will be that the proxy doesn't have a strippe
In a case like that (without a stripped path prefix), the proxy would listen on something like `https://myawesomeapp.com`, and then if the browser goes to `https://myawesomeapp.com/api/v1/app` and your server (e.g. Uvicorn) listens on `http://127.0.0.1:8000` the proxy (without a stripped path prefix) would access Uvicorn at the same path: `http://127.0.0.1:8000/api/v1/app`.
-## Testing locally with Traefik
+## Testing locally with Traefik { #testing-locally-with-traefik }
You can easily run the experiment locally with a stripped path prefix using
Traefik.
@@ -224,14 +321,14 @@ 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)
```
-### Check the responses
+### Check the responses { #check-the-responses }
Now, if you go to the URL with the port for Uvicorn:
http://127.0.0.1:8000/app, you will see the normal response:
@@ -267,7 +364,7 @@ And the version without the path prefix (`http://127.0.0.1:8000/app`), provided
That demonstrates how the Proxy (Traefik) uses the path prefix and how the server (Uvicorn) uses the `root_path` from the option `--root-path`.
-### Check the docs UI
+### Check the docs UI { #check-the-docs-ui }
But here's the fun part. â¨
@@ -287,7 +384,7 @@ Right as we wanted it. âī¸
This is because FastAPI uses this `root_path` to create the default `server` in OpenAPI with the URL provided by `root_path`.
-## Additional servers
+## Additional servers { #additional-servers }
/// warning
@@ -346,7 +443,7 @@ The docs UI will interact with the server that you select.
///
-### Disable automatic server from `root_path`
+### Disable automatic server from `root_path` { #disable-automatic-server-from-root-path }
If you don't want **FastAPI** to include an automatic server using the `root_path`, you can use the parameter `root_path_in_servers=False`:
@@ -354,7 +451,7 @@ If you don't want **FastAPI** to include an automatic server using the `root_pat
and then it won't include it in the OpenAPI schema.
-## Mounting a sub-application
+## Mounting a sub-application { #mounting-a-sub-application }
If you need to mount a sub-application (as described in [Sub Applications - Mounts](sub-applications.md){.internal-link target=_blank}) while also using a proxy with `root_path`, you can do it normally, as you would expect.
diff --git a/docs/en/docs/advanced/custom-response.md b/docs/en/docs/advanced/custom-response.md
index 8268dd81a..5473d939c 100644
--- a/docs/en/docs/advanced/custom-response.md
+++ b/docs/en/docs/advanced/custom-response.md
@@ -1,4 +1,4 @@
-# Custom Response - HTML, Stream, File, others
+# Custom Response - HTML, Stream, File, others { #custom-response-html-stream-file-others }
By default, **FastAPI** will return the responses using `JSONResponse`.
@@ -18,7 +18,7 @@ If you use a response class with no media type, FastAPI will expect your respons
///
-## Use `ORJSONResponse`
+## Use `ORJSONResponse` { #use-orjsonresponse }
For example, if you are squeezing performance, you can install and use
`orjson` and set the response to be `ORJSONResponse`.
@@ -48,7 +48,7 @@ The `ORJSONResponse` is only available in FastAPI, not in Starlette.
///
-## HTML Response
+## HTML Response { #html-response }
To return a response with HTML directly from **FastAPI**, use `HTMLResponse`.
@@ -67,7 +67,7 @@ And it will be documented as such in OpenAPI.
///
-### Return a `Response`
+### Return a `Response` { #return-a-response }
As seen in [Return a Response directly](response-directly.md){.internal-link target=_blank}, you can also override the response directly in your *path operation*, by returning it.
@@ -87,13 +87,13 @@ Of course, the actual `Content-Type` header, status code, etc, will come from th
///
-### Document in OpenAPI and override `Response`
+### Document in OpenAPI and override `Response` { #document-in-openapi-and-override-response }
If you want to override the response from inside of the function but at the same time document the "media type" in OpenAPI, you can use the `response_class` parameter AND return a `Response` object.
The `response_class` will then be used only to document the OpenAPI *path operation*, but your `Response` will be used as is.
-#### Return an `HTMLResponse` directly
+#### Return an `HTMLResponse` directly { #return-an-htmlresponse-directly }
For example, it could be something like:
@@ -107,7 +107,7 @@ But as you passed the `HTMLResponse` in the `response_class` too, **FastAPI** wi

-## Available responses
+## Available responses { #available-responses }
Here are some of the available responses.
@@ -121,7 +121,7 @@ You could also use `from starlette.responses import HTMLResponse`.
///
-### `Response`
+### `Response` { #response }
The main `Response` class, all the other responses inherit from it.
@@ -138,23 +138,23 @@ FastAPI (actually Starlette) will automatically include a Content-Length header.
{* ../../docs_src/response_directly/tutorial002.py hl[1,18] *}
-### `HTMLResponse`
+### `HTMLResponse` { #htmlresponse }
Takes some text or bytes and returns an HTML response, as you read above.
-### `PlainTextResponse`
+### `PlainTextResponse` { #plaintextresponse }
Takes some text or bytes and returns a plain text response.
{* ../../docs_src/custom_response/tutorial005.py hl[2,7,9] *}
-### `JSONResponse`
+### `JSONResponse` { #jsonresponse }
Takes some data and returns an `application/json` encoded response.
This is the default response used in **FastAPI**, as you read above.
-### `ORJSONResponse`
+### `ORJSONResponse` { #orjsonresponse }
A fast alternative JSON response using
`orjson`, as you read above.
@@ -164,7 +164,7 @@ This requires installing `orjson` for example with `pip install orjson`.
///
-### `UJSONResponse`
+### `UJSONResponse` { #ujsonresponse }
An alternative JSON response using
`ujson`.
@@ -188,7 +188,7 @@ It's possible that `ORJSONResponse` might be a faster alternative.
///
-### `RedirectResponse`
+### `RedirectResponse` { #redirectresponse }
Returns an HTTP redirect. Uses a 307 status code (Temporary Redirect) by default.
@@ -213,13 +213,13 @@ You can also use the `status_code` parameter combined with the `response_class`
{* ../../docs_src/custom_response/tutorial006c.py hl[2,7,9] *}
-### `StreamingResponse`
+### `StreamingResponse` { #streamingresponse }
Takes an async generator or a normal generator/iterator and streams the response body.
{* ../../docs_src/custom_response/tutorial007.py hl[2,14] *}
-#### Using `StreamingResponse` with file-like objects
+#### Using `StreamingResponse` with file-like objects { #using-streamingresponse-with-file-like-objects }
If you have a file-like object (e.g. the object returned by `open()`), you can create a generator function to iterate over that file-like object.
@@ -243,7 +243,7 @@ Notice that here as we are using standard `open()` that doesn't support `async`
///
-### `FileResponse`
+### `FileResponse` { #fileresponse }
Asynchronously streams a file as the response.
@@ -264,7 +264,7 @@ You can also use the `response_class` parameter:
In this case, you can return the file path directly from your *path operation* function.
-## Custom response class
+## Custom response class { #custom-response-class }
You can create your own custom response class, inheriting from `Response` and using it.
@@ -292,7 +292,7 @@ Now instead of returning:
Of course, you will probably find much better ways to take advantage of this than formatting JSON. đ
-## Default response class
+## Default response class { #default-response-class }
When creating a **FastAPI** class instance or an `APIRouter` you can specify which response class to use by default.
@@ -308,6 +308,6 @@ You can still override `response_class` in *path operations* as before.
///
-## Additional documentation
+## Additional documentation { #additional-documentation }
You can also declare the media type and many other details in OpenAPI using `responses`: [Additional Responses in OpenAPI](additional-responses.md){.internal-link target=_blank}.
diff --git a/docs/en/docs/advanced/dataclasses.md b/docs/en/docs/advanced/dataclasses.md
index 2936c6d5d..b7b9b65c5 100644
--- a/docs/en/docs/advanced/dataclasses.md
+++ b/docs/en/docs/advanced/dataclasses.md
@@ -1,4 +1,4 @@
-# Using Dataclasses
+# Using Dataclasses { #using-dataclasses }
FastAPI is built on top of **Pydantic**, and I have been showing you how to use Pydantic models to declare requests and responses.
@@ -28,7 +28,7 @@ But if you have a bunch of dataclasses laying around, this is a nice trick to us
///
-## Dataclasses in `response_model`
+## Dataclasses in `response_model` { #dataclasses-in-response-model }
You can also use `dataclasses` in the `response_model` parameter:
@@ -40,7 +40,7 @@ This way, its schema will show up in the API docs user interface:

-## Dataclasses in Nested Data Structures
+## Dataclasses in Nested Data Structures { #dataclasses-in-nested-data-structures }
You can also combine `dataclasses` with other type annotations to make nested data structures.
@@ -84,12 +84,12 @@ You can combine `dataclasses` with other type annotations in many different comb
Check the in-code annotation tips above to see more specific details.
-## Learn More
+## Learn More { #learn-more }
You can also combine `dataclasses` with other Pydantic models, inherit from them, include them in your own models, etc.
To learn more, check the
Pydantic docs about dataclasses.
-## Version
+## Version { #version }
This is available since FastAPI version `0.67.0`. đ
diff --git a/docs/en/docs/advanced/events.md b/docs/en/docs/advanced/events.md
index 19465d891..c805e81ee 100644
--- a/docs/en/docs/advanced/events.md
+++ b/docs/en/docs/advanced/events.md
@@ -1,4 +1,4 @@
-# Lifespan Events
+# Lifespan Events { #lifespan-events }
You can define logic (code) that should be executed before the application **starts up**. This means that this code will be executed **once**, **before** the application **starts receiving requests**.
@@ -8,7 +8,7 @@ Because this code is executed before the application **starts** taking requests,
This can be very useful for setting up **resources** that you need to use for the whole app, and that are **shared** among requests, and/or that you need to **clean up** afterwards. For example, a database connection pool, or loading a shared machine learning model.
-## Use Case
+## Use Case { #use-case }
Let's start with an example **use case** and then see how to solve it with this.
@@ -22,7 +22,7 @@ You could load it at the top level of the module/file, but that would also mean
That's what we'll solve, let's load the model before the requests are handled, but only right before the application starts receiving requests, not while the code is being loaded.
-## Lifespan
+## Lifespan { #lifespan }
You can define this *startup* and *shutdown* logic using the `lifespan` parameter of the `FastAPI` app, and a "context manager" (I'll show you what that is in a second).
@@ -44,7 +44,7 @@ Maybe you need to start a new version, or you just got tired of running it. đ¤ˇ
///
-### Lifespan function
+### Lifespan function { #lifespan-function }
The first thing to notice, is that we are defining an async function with `yield`. This is very similar to Dependencies with `yield`.
@@ -54,7 +54,7 @@ The first part of the function, before the `yield`, will be executed **before**
And the part after the `yield` will be executed **after** the application has finished.
-### Async Context Manager
+### Async Context Manager { #async-context-manager }
If you check, the function is decorated with an `@asynccontextmanager`.
@@ -84,7 +84,7 @@ The `lifespan` parameter of the `FastAPI` app takes an **async context manager**
{* ../../docs_src/events/tutorial003.py hl[22] *}
-## Alternative Events (deprecated)
+## Alternative Events (deprecated) { #alternative-events-deprecated }
/// warning
@@ -100,7 +100,7 @@ You can define event handlers (functions) that need to be executed before the ap
These functions can be declared with `async def` or normal `def`.
-### `startup` event
+### `startup` event { #startup-event }
To add a function that should be run before the application starts, declare it with the event `"startup"`:
@@ -112,7 +112,7 @@ You can add more than one event handler function.
And your application won't start receiving requests until all the `startup` event handlers have completed.
-### `shutdown` event
+### `shutdown` event { #shutdown-event }
To add a function that should be run when the application is shutting down, declare it with the event `"shutdown"`:
@@ -138,7 +138,7 @@ So, we declare the event handler function with standard `def` instead of `async
///
-### `startup` and `shutdown` together
+### `startup` and `shutdown` together { #startup-and-shutdown-together }
There's a high chance that the logic for your *startup* and *shutdown* is connected, you might want to start something and then finish it, acquire a resource and then release it, etc.
@@ -146,7 +146,7 @@ Doing that in separated functions that don't share logic or variables together i
Because of that, it's now recommended to instead use the `lifespan` as explained above.
-## Technical Details
+## Technical Details { #technical-details }
Just a technical detail for the curious nerds. đ¤
@@ -160,6 +160,6 @@ Including how to handle lifespan state that can be used in other areas of your c
///
-## Sub Applications
+## Sub Applications { #sub-applications }
đ¨ Keep in mind that these lifespan events (startup and shutdown) will only be executed for the main application, not for [Sub Applications - Mounts](sub-applications.md){.internal-link target=_blank}.
diff --git a/docs/en/docs/advanced/generate-clients.md b/docs/en/docs/advanced/generate-clients.md
index 3b9dc83f0..897c30808 100644
--- a/docs/en/docs/advanced/generate-clients.md
+++ b/docs/en/docs/advanced/generate-clients.md
@@ -1,34 +1,42 @@
-# Generate Clients
+# Generating SDKs { #generating-sdks }
-As **FastAPI** is based on the OpenAPI specification, you get automatic compatibility with many tools, including the automatic API docs (provided by Swagger UI).
+Because **FastAPI** is based on the **OpenAPI** specification, its APIs can be described in a standard format that many tools understand.
-One particular advantage that is not necessarily obvious is that you can **generate clients** (sometimes called
**SDKs** ) for your API, for many different **programming languages**.
+This makes it easy to generate up-to-date **documentation**, client libraries (
**SDKs**) in multiple languages, and **testing** or **automation workflows** that stay in sync with your code.
-## OpenAPI Client Generators
+In this guide, you'll learn how to generate a **TypeScript SDK** for your FastAPI backend.
-There are many tools to generate clients from **OpenAPI**.
+## Open Source SDK Generators { #open-source-sdk-generators }
-A common tool is
OpenAPI Generator.
+A versatile option is the
OpenAPI Generator, which supports **many programming languages** and can generate SDKs from your OpenAPI specification.
-If you are building a **frontend**, a very interesting alternative is
openapi-ts.
+For **TypeScript clients**,
Hey API is a purpose-built solution, providing an optimized experience for the TypeScript ecosystem.
-## Client and SDK Generators - Sponsor
+You can discover more SDK generators on
OpenAPI.Tools.
-There are also some **company-backed** Client and SDK generators based on OpenAPI (FastAPI), in some cases they can offer you **additional features** on top of high-quality generated SDKs/clients.
+/// tip
+
+FastAPI automatically generates **OpenAPI 3.1** specifications, so any tool you use must support this version.
+
+///
+
+## SDK Generators from FastAPI Sponsors { #sdk-generators-from-fastapi-sponsors }
+
+This section highlights **venture-backed** and **company-supported** solutions from companies that sponsor FastAPI. These products provide **additional features** and **integrations** on top of high-quality generated SDKs.
-Some of them also ⨠[**sponsor FastAPI**](../help-fastapi.md#sponsor-the-author){.internal-link target=_blank} â¨, this ensures the continued and healthy **development** of FastAPI and its **ecosystem**.
+By ⨠[**sponsoring FastAPI**](../help-fastapi.md#sponsor-the-author){.internal-link target=_blank} â¨, these companies help ensure the framework and its **ecosystem** remain healthy and **sustainable**.
-And it shows their true commitment to FastAPI and its **community** (you), as they not only want to provide you a **good service** but also want to make sure you have a **good and healthy framework**, FastAPI. đ
+Their sponsorship also demonstrates a strong commitment to the FastAPI **community** (you), showing that they care not only about offering a **great service** but also about supporting a **robust and thriving framework**, FastAPI. đ
For example, you might want to try:
-*
Speakeasy
-*
Stainless
-*
liblab
+*
Speakeasy
+*
Stainless
+*
liblab
-There are also several other companies offering similar services that you can search and find online. đ¤
+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. đ¤
-## Generate a TypeScript Frontend Client
+## Create a TypeScript SDK { #create-a-typescript-sdk }
Let's start with a simple FastAPI application:
@@ -36,80 +44,33 @@ Let's start with a simple FastAPI application:
Notice that the *path operations* define the models they use for request payload and response payload, using the models `Item` and `ResponseMessage`.
-### API Docs
+### API Docs { #api-docs }
-If you go to the API docs, you will see that it has the **schemas** for the data to be sent in requests and received in responses:
+If you go to `/docs`, you will see that it has the **schemas** for the data to be sent in requests and received in responses:

You can see those schemas because they were declared with the models in the app.
-That information is available in the app's **OpenAPI schema**, and then shown in the API docs (by Swagger UI).
-
-And that same information from the models that is included in OpenAPI is what can be used to **generate the client code**.
-
-### Generate a TypeScript Client
-
-Now that we have the app with the models, we can generate the client code for the frontend.
-
-#### Install `openapi-ts`
-
-You can install `openapi-ts` in your frontend code with:
-
-
+That information is available in the app's **OpenAPI schema**, and then shown in the API docs.
-```console
-$ npm install @hey-api/openapi-ts --save-dev
+That same information from the models that is included in OpenAPI is what can be used to **generate the client code**.
----> 100%
-```
-
-
-
-#### Generate Client Code
-
-To generate the client code you can use the command line application `openapi-ts` that would now be installed.
-
-Because it is installed in the local project, you probably wouldn't be able to call that command directly, but you would put it on your `package.json` file.
-
-It could look like this:
+### Hey API { #hey-api }
-```JSON hl_lines="7"
-{
- "name": "frontend-app",
- "version": "1.0.0",
- "description": "",
- "main": "index.js",
- "scripts": {
- "generate-client": "openapi-ts --input http://localhost:8000/openapi.json --output ./src/client --client axios"
- },
- "author": "",
- "license": "",
- "devDependencies": {
- "@hey-api/openapi-ts": "^0.27.38",
- "typescript": "^4.6.2"
- }
-}
-```
-
-After having that NPM `generate-client` script there, you can run it with:
-
-
+Once we have a FastAPI app with the models, we can use Hey API to generate a TypeScript client. The fastest way to do that is via npx.
-```console
-$ npm run generate-client
-
-frontend-app@1.0.0 generate-client /home/user/code/frontend-app
-> openapi-ts --input http://localhost:8000/openapi.json --output ./src/client --client axios
+```sh
+npx @hey-api/openapi-ts -i http://localhost:8000/openapi.json -o src/client
```
-
+This will generate a TypeScript SDK in `./src/client`.
-That command will generate code in `./src/client` and will use `axios` (the frontend HTTP library) internally.
+You can learn how to
install `@hey-api/openapi-ts` and read about the
generated output on their website.
-### Try Out the Client Code
+### Using the SDK { #using-the-sdk }
-Now you can import and use the client code, it could look like this, notice that you get autocompletion for the methods:
+Now you can import and use the client code. It could look like this, notice that you get autocompletion for the methods:

@@ -131,30 +92,30 @@ The response object will also have autocompletion:

-## FastAPI App with Tags
+## FastAPI App with Tags { #fastapi-app-with-tags }
-In many cases your FastAPI app will be bigger, and you will probably use tags to separate different groups of *path operations*.
+In many cases, your FastAPI app will be bigger, and you will probably use tags to separate different groups of *path operations*.
For example, you could have a section for **items** and another section for **users**, and they could be separated by tags:
{* ../../docs_src/generate_clients/tutorial002_py39.py hl[21,26,34] *}
-### Generate a TypeScript Client with Tags
+### Generate a TypeScript Client with Tags { #generate-a-typescript-client-with-tags }
If you generate a client for a FastAPI app using tags, it will normally also separate the client code based on the tags.
-This way you will be able to have things ordered and grouped correctly for the client code:
+This way, you will be able to have things ordered and grouped correctly for the client code:

-In this case you have:
+In this case, you have:
* `ItemsService`
* `UsersService`
-### Client Method Names
+### Client Method Names { #client-method-names }
-Right now the generated method names like `createItemItemsPost` don't look very clean:
+Right now, the generated method names like `createItemItemsPost` don't look very clean:
```TypeScript
ItemsService.createItemItemsPost({name: "Plumbus", price: 5})
@@ -166,17 +127,17 @@ OpenAPI requires that each operation ID is unique across all the *path operation
But I'll show you how to improve that next. đ¤
-## Custom Operation IDs and Better Method Names
+## Custom Operation IDs and Better Method Names { #custom-operation-ids-and-better-method-names }
You can **modify** the way these operation IDs are **generated** to make them simpler and have **simpler method names** in the clients.
-In this case you will have to ensure that each operation ID is **unique** in some other way.
+In this case, you will have to ensure that each operation ID is **unique** in some other way.
For example, you could make sure that each *path operation* has a tag, and then generate the operation ID based on the **tag** and the *path operation* **name** (the function name).
-### Custom Generate Unique ID Function
+### Custom Generate Unique ID Function { #custom-generate-unique-id-function }
-FastAPI uses a **unique ID** for each *path operation*, it is used for the **operation ID** and also for the names of any needed custom models, for requests or responses.
+FastAPI uses a **unique ID** for each *path operation*, which is used for the **operation ID** and also for the names of any needed custom models, for requests or responses.
You can customize that function. It takes an `APIRoute` and outputs a string.
@@ -186,15 +147,15 @@ You can then pass that custom function to **FastAPI** as the `generate_unique_id
{* ../../docs_src/generate_clients/tutorial003_py39.py hl[6:7,10] *}
-### Generate a TypeScript Client with Custom Operation IDs
+### Generate a TypeScript Client with Custom Operation IDs { #generate-a-typescript-client-with-custom-operation-ids }
-Now if you generate the client again, you will see that it has the improved method names:
+Now, if you generate the client again, you will see that it has the improved method names:

As you see, the method names now have the tag and then the function name, now they don't include information from the URL path and the HTTP operation.
-### Preprocess the OpenAPI Specification for the Client Generator
+### Preprocess the OpenAPI Specification for the Client Generator { #preprocess-the-openapi-specification-for-the-client-generator }
The generated code still has some **duplicated information**.
@@ -202,7 +163,7 @@ We already know that this method is related to the **items** because that word i
We will probably still want to keep it for OpenAPI in general, as that will ensure that the operation IDs are **unique**.
-But for the generated client we could **modify** the OpenAPI operation IDs right before generating the clients, just to make those method names nicer and **cleaner**.
+But for the generated client, we could **modify** the OpenAPI operation IDs right before generating the clients, just to make those method names nicer and **cleaner**.
We could download the OpenAPI JSON to a file `openapi.json` and then we could **remove that prefixed tag** with a script like this:
@@ -218,35 +179,21 @@ We could download the OpenAPI JSON to a file `openapi.json` and then we could **
With that, the operation IDs would be renamed from things like `items-get_items` to just `get_items`, that way the client generator can generate simpler method names.
-### Generate a TypeScript Client with the Preprocessed OpenAPI
-
-Now as the end result is in a file `openapi.json`, you would modify the `package.json` to use that local file, for example:
-
-```JSON hl_lines="7"
-{
- "name": "frontend-app",
- "version": "1.0.0",
- "description": "",
- "main": "index.js",
- "scripts": {
- "generate-client": "openapi-ts --input ./openapi.json --output ./src/client --client axios"
- },
- "author": "",
- "license": "",
- "devDependencies": {
- "@hey-api/openapi-ts": "^0.27.38",
- "typescript": "^4.6.2"
- }
-}
+### Generate a TypeScript Client with the Preprocessed OpenAPI { #generate-a-typescript-client-with-the-preprocessed-openapi }
+
+Since the end result is now in an `openapi.json` file, you need to update your input location:
+
+```sh
+npx @hey-api/openapi-ts -i ./openapi.json -o src/client
```
After generating the new client, you would now have **clean method names**, with all the **autocompletion**, **inline errors**, etc:

-## Benefits
+## Benefits { #benefits }
-When using the automatically generated clients you would get **autocompletion** for:
+When using the automatically generated clients, you would get **autocompletion** for:
* Methods.
* Request payloads in the body, query parameters, etc.
@@ -256,6 +203,6 @@ You would also have **inline errors** for everything.
And whenever you update the backend code, and **regenerate** the frontend, it would have any new *path operations* available as methods, the old ones removed, and any other change would be reflected on the generated code. đ¤
-This also means that if something changed it will be **reflected** on the client code automatically. And if you **build** the client it will error out if you have any **mismatch** in the data used.
+This also means that if something changed, it will be **reflected** on the client code automatically. And if you **build** the client, it will error out if you have any **mismatch** in the data used.
So, you would **detect many errors** very early in the development cycle instead of having to wait for the errors to show up to your final users in production and then trying to debug where the problem is. â¨
diff --git a/docs/en/docs/advanced/index.md b/docs/en/docs/advanced/index.md
index 47385e2c6..9355516fb 100644
--- a/docs/en/docs/advanced/index.md
+++ b/docs/en/docs/advanced/index.md
@@ -1,6 +1,6 @@
-# Advanced User Guide
+# Advanced User Guide { #advanced-user-guide }
-## Additional Features
+## Additional Features { #additional-features }
The main [Tutorial - User Guide](../tutorial/index.md){.internal-link target=_blank} should be enough to give you a tour through all the main features of **FastAPI**.
@@ -14,7 +14,7 @@ And it's possible that for your use case, the solution is in one of them.
///
-## Read the Tutorial first
+## Read the Tutorial first { #read-the-tutorial-first }
You could still use most of the features in **FastAPI** with the knowledge from the main [Tutorial - User Guide](../tutorial/index.md){.internal-link target=_blank}.
diff --git a/docs/en/docs/advanced/middleware.md b/docs/en/docs/advanced/middleware.md
index 1d40b1c8f..d1be4afff 100644
--- a/docs/en/docs/advanced/middleware.md
+++ b/docs/en/docs/advanced/middleware.md
@@ -1,4 +1,4 @@
-# Advanced Middleware
+# Advanced Middleware { #advanced-middleware }
In the main tutorial you read how to add [Custom Middleware](../tutorial/middleware.md){.internal-link target=_blank} to your application.
@@ -6,7 +6,7 @@ And then you also read how to handle [CORS with the `CORSMiddleware`](../tutoria
In this section we'll see how to use other middlewares.
-## Adding ASGI middlewares
+## Adding ASGI middlewares { #adding-asgi-middlewares }
As **FastAPI** is based on Starlette and implements the
ASGI specification, you can use any ASGI middleware.
@@ -39,7 +39,7 @@ app.add_middleware(UnicornMiddleware, some_config="rainbow")
`app.add_middleware()` receives a middleware class as the first argument and any additional arguments to be passed to the middleware.
-## Integrated middlewares
+## Integrated middlewares { #integrated-middlewares }
**FastAPI** includes several middlewares for common use cases, we'll see next how to use them.
@@ -51,7 +51,7 @@ For the next examples, you could also use `from starlette.middleware.something i
///
-## `HTTPSRedirectMiddleware`
+## `HTTPSRedirectMiddleware` { #httpsredirectmiddleware }
Enforces that all incoming requests must either be `https` or `wss`.
@@ -59,7 +59,7 @@ Any incoming request to `http` or `ws` will be redirected to the secure scheme i
{* ../../docs_src/advanced_middleware/tutorial001.py hl[2,6] *}
-## `TrustedHostMiddleware`
+## `TrustedHostMiddleware` { #trustedhostmiddleware }
Enforces that all incoming requests have a correctly set `Host` header, in order to guard against HTTP Host Header attacks.
@@ -68,10 +68,11 @@ Enforces that all incoming requests have a correctly set `Host` header, in order
The following arguments are supported:
* `allowed_hosts` - A list of domain names that should be allowed as hostnames. Wildcard domains such as `*.example.com` are supported for matching subdomains. To allow any hostname either use `allowed_hosts=["*"]` or omit the middleware.
+* `www_redirect` - If set to True, requests to non-www versions of the allowed hosts will be redirected to their www counterparts. Defaults to `True`.
If an incoming request does not validate correctly then a `400` response will be sent.
-## `GZipMiddleware`
+## `GZipMiddleware` { #gzipmiddleware }
Handles GZip responses for any request that includes `"gzip"` in the `Accept-Encoding` header.
@@ -84,7 +85,7 @@ The following arguments are supported:
* `minimum_size` - Do not GZip responses that are smaller than this minimum size in bytes. Defaults to `500`.
* `compresslevel` - Used during GZip compression. It is an integer ranging from 1 to 9. Defaults to `9`. Lower value results in faster compression but larger file sizes, while higher value results in slower compression but smaller file sizes.
-## Other middlewares
+## Other middlewares { #other-middlewares }
There are many other ASGI middlewares.
diff --git a/docs/en/docs/advanced/openapi-callbacks.md b/docs/en/docs/advanced/openapi-callbacks.md
index ca9065a89..059d893c2 100644
--- a/docs/en/docs/advanced/openapi-callbacks.md
+++ b/docs/en/docs/advanced/openapi-callbacks.md
@@ -1,4 +1,4 @@
-# OpenAPI Callbacks
+# OpenAPI Callbacks { #openapi-callbacks }
You could create an API with a *path operation* that could trigger a request to an *external API* created by someone else (probably the same developer that would be *using* your API).
@@ -6,7 +6,7 @@ The process that happens when your API app calls the *external API* is named a "
In this case, you could want to document how that external API *should* look like. What *path operation* it should have, what body it should expect, what response it should return, etc.
-## An app with callbacks
+## An app with callbacks { #an-app-with-callbacks }
Let's see all this with an example.
@@ -23,7 +23,7 @@ Then your API will (let's imagine):
* Send a notification back to the API user (the external developer).
* This will be done by sending a POST request (from *your API*) to some *external API* provided by that external developer (this is the "callback").
-## The normal **FastAPI** app
+## The normal **FastAPI** app { #the-normal-fastapi-app }
Let's first see how the normal API app would look like before adding the callback.
@@ -41,7 +41,7 @@ The `callback_url` query parameter uses a Pydantic
OpenAPI 3 expression (see more below) where it can use variables with parameters and parts of the original request sent to *your API*.
-### The callback path expression
+### The callback path expression { #the-callback-path-expression }
The callback *path* can have an
OpenAPI 3 expression that can contain parts of the original request sent to *your API*.
@@ -163,7 +163,7 @@ Notice how the callback URL used contains the URL received as a query parameter
///
-### Add the callback router
+### Add the callback router { #add-the-callback-router }
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.
@@ -177,7 +177,7 @@ Notice that you are not passing the router itself (`invoices_callback_router`) t
///
-### Check the docs
+### Check the docs { #check-the-docs }
Now you can start your app and go to
http://127.0.0.1:8000/docs.
diff --git a/docs/en/docs/advanced/openapi-webhooks.md b/docs/en/docs/advanced/openapi-webhooks.md
index 97aaa41af..416cf4b75 100644
--- a/docs/en/docs/advanced/openapi-webhooks.md
+++ b/docs/en/docs/advanced/openapi-webhooks.md
@@ -1,4 +1,4 @@
-# OpenAPI Webhooks
+# OpenAPI Webhooks { #openapi-webhooks }
There are cases where you want to tell your API **users** that your app could call *their* app (sending a request) with some data, normally to **notify** of some type of **event**.
@@ -6,7 +6,7 @@ This means that instead of the normal process of your users sending requests to
This is normally called a **webhook**.
-## Webhooks steps
+## Webhooks steps { #webhooks-steps }
The process normally is that **you define** in your code what is the message that you will send, the **body of the request**.
@@ -16,7 +16,7 @@ And **your users** define in some way (for example in a web dashboard somewhere)
All the **logic** about how to register the URLs for webhooks and the code to actually send those requests is up to you. You write it however you want to in **your own code**.
-## Documenting webhooks with **FastAPI** and OpenAPI
+## Documenting webhooks with **FastAPI** and OpenAPI { #documenting-webhooks-with-fastapi-and-openapi }
With **FastAPI**, using OpenAPI, you can define the names of these webhooks, the types of HTTP operations that your app can send (e.g. `POST`, `PUT`, etc.) and the request **bodies** that your app would send.
@@ -28,7 +28,7 @@ Webhooks are available in OpenAPI 3.1.0 and above, supported by FastAPI `0.99.0`
///
-## An app with webhooks
+## An app with webhooks { #an-app-with-webhooks }
When you create a **FastAPI** application, there is a `webhooks` attribute that you can use to define *webhooks*, the same way you would define *path operations*, for example with `@app.webhooks.post()`.
@@ -46,7 +46,7 @@ Notice that with webhooks you are actually not declaring a *path* (like `/items/
This is because it is expected that **your users** would define the actual **URL path** where they want to receive the webhook request in some other way (e.g. a web dashboard).
-### Check the docs
+### Check the docs { #check-the-docs }
Now you can start your app and go to
http://127.0.0.1:8000/docs.
diff --git a/docs/en/docs/advanced/path-operation-advanced-configuration.md b/docs/en/docs/advanced/path-operation-advanced-configuration.md
index c4814ebd2..b9961f9f3 100644
--- a/docs/en/docs/advanced/path-operation-advanced-configuration.md
+++ b/docs/en/docs/advanced/path-operation-advanced-configuration.md
@@ -1,6 +1,6 @@
-# Path Operation Advanced Configuration
+# Path Operation Advanced Configuration { #path-operation-advanced-configuration }
-## OpenAPI operationId
+## OpenAPI operationId { #openapi-operationid }
/// warning
@@ -14,7 +14,7 @@ You would have to make sure that it is unique for each operation.
{* ../../docs_src/path_operation_advanced_configuration/tutorial001.py hl[6] *}
-### Using the *path operation function* name as the operationId
+### 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`.
@@ -36,13 +36,13 @@ Even if they are in different modules (Python files).
///
-## Exclude from OpenAPI
+## Exclude from OpenAPI { #exclude-from-openapi }
To exclude a *path operation* from the generated OpenAPI schema (and thus, from the automatic documentation systems), use the parameter `include_in_schema` and set it to `False`:
{* ../../docs_src/path_operation_advanced_configuration/tutorial003.py hl[6] *}
-## Advanced description from docstring
+## Advanced description from docstring { #advanced-description-from-docstring }
You can limit the lines used from the docstring of a *path operation function* for OpenAPI.
@@ -52,7 +52,7 @@ It won't show up in the documentation, but other tools (such as Sphinx) will be
{* ../../docs_src/path_operation_advanced_configuration/tutorial004.py hl[19:29] *}
-## Additional Responses
+## Additional Responses { #additional-responses }
You probably have seen how to declare the `response_model` and `status_code` for a *path operation*.
@@ -62,7 +62,7 @@ You can also declare additional responses with their models, status codes, etc.
There's a whole chapter here in the documentation about it, you can read it at [Additional Responses in OpenAPI](additional-responses.md){.internal-link target=_blank}.
-## OpenAPI Extra
+## OpenAPI Extra { #openapi-extra }
When you declare a *path operation* in your application, **FastAPI** automatically generates the relevant metadata about that *path operation* to be included in the OpenAPI schema.
@@ -88,7 +88,7 @@ If you only need to declare additional responses, a more convenient way to do it
You can extend the OpenAPI schema for a *path operation* using the parameter `openapi_extra`.
-### OpenAPI Extensions
+### OpenAPI Extensions { #openapi-extensions }
This `openapi_extra` can be helpful, for example, to declare [OpenAPI Extensions](https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.3.md#specificationExtensions):
@@ -129,7 +129,7 @@ And if you see the resulting OpenAPI (at `/openapi.json` in your API), you will
}
```
-### Custom OpenAPI *path operation* schema
+### Custom OpenAPI *path operation* schema { #custom-openapi-path-operation-schema }
The dictionary in `openapi_extra` will be deeply merged with the automatically generated OpenAPI schema for the *path operation*.
@@ -145,7 +145,7 @@ In this example, we didn't declare any Pydantic model. In fact, the request body
Nevertheless, we can declare the expected schema for the request body.
-### Custom OpenAPI content type
+### Custom OpenAPI content type { #custom-openapi-content-type }
Using this same trick, you could use a Pydantic model to define the JSON Schema that is then included in the custom OpenAPI schema section for the *path operation*.
diff --git a/docs/en/docs/advanced/response-change-status-code.md b/docs/en/docs/advanced/response-change-status-code.md
index 6d3f9f3e8..912ed0f1a 100644
--- a/docs/en/docs/advanced/response-change-status-code.md
+++ b/docs/en/docs/advanced/response-change-status-code.md
@@ -1,10 +1,10 @@
-# Response - Change Status Code
+# Response - Change Status Code { #response-change-status-code }
You probably read before that you can set a default [Response Status Code](../tutorial/response-status-code.md){.internal-link target=_blank}.
But in some cases you need to return a different status code than the default.
-## Use case
+## Use case { #use-case }
For example, imagine that you want to return an HTTP status code of "OK" `200` by default.
@@ -14,7 +14,7 @@ But you still want to be able to filter and convert the data you return with a `
For those cases, you can use a `Response` parameter.
-## Use a `Response` parameter
+## Use a `Response` parameter { #use-a-response-parameter }
You can declare a parameter of type `Response` in your *path operation function* (as you can do for cookies and headers).
diff --git a/docs/en/docs/advanced/response-cookies.md b/docs/en/docs/advanced/response-cookies.md
index f6d17f35d..d8f77b56a 100644
--- a/docs/en/docs/advanced/response-cookies.md
+++ b/docs/en/docs/advanced/response-cookies.md
@@ -1,6 +1,6 @@
-# Response Cookies
+# Response Cookies { #response-cookies }
-## Use a `Response` parameter
+## Use a `Response` parameter { #use-a-response-parameter }
You can declare a parameter of type `Response` in your *path operation function*.
@@ -16,7 +16,7 @@ And if you declared a `response_model`, it will still be used to filter and conv
You can also declare the `Response` parameter in dependencies, and set cookies (and headers) in them.
-## Return a `Response` directly
+## Return a `Response` directly { #return-a-response-directly }
You can also create cookies when returning a `Response` directly in your code.
@@ -36,7 +36,7 @@ And also that you are not sending any data that should have been filtered by a `
///
-### More info
+### More info { #more-info }
/// note | Technical Details
diff --git a/docs/en/docs/advanced/response-directly.md b/docs/en/docs/advanced/response-directly.md
index 691b1e7cd..3197e1bd4 100644
--- a/docs/en/docs/advanced/response-directly.md
+++ b/docs/en/docs/advanced/response-directly.md
@@ -1,4 +1,4 @@
-# Return a Response Directly
+# Return a Response Directly { #return-a-response-directly }
When you create a **FastAPI** *path operation* you can normally return any data from it: a `dict`, a `list`, a Pydantic model, a database model, etc.
@@ -10,7 +10,7 @@ But you can return a `JSONResponse` directly from your *path operations*.
It might be useful, for example, to return custom headers or cookies.
-## Return a `Response`
+## Return a `Response` { #return-a-response }
In fact, you can return any `Response` or any sub-class of it.
@@ -26,7 +26,7 @@ It won't do any data conversion with Pydantic models, it won't convert the conte
This gives you a lot of flexibility. You can return any data type, override any data declaration or validation, etc.
-## Using the `jsonable_encoder` in a `Response`
+## Using the `jsonable_encoder` in a `Response` { #using-the-jsonable-encoder-in-a-response }
Because **FastAPI** doesn't make any changes to a `Response` you return, you have to make sure its contents are ready for it.
@@ -44,7 +44,7 @@ You could also use `from starlette.responses import JSONResponse`.
///
-## Returning a custom `Response`
+## Returning a custom `Response` { #returning-a-custom-response }
The example above shows all the parts you need, but it's not very useful yet, as you could have just returned the `item` directly, and **FastAPI** would put it in a `JSONResponse` for you, converting it to a `dict`, etc. All that by default.
@@ -56,9 +56,9 @@ You could put your XML content in a string, put that in a `Response`, and return
{* ../../docs_src/response_directly/tutorial002.py hl[1,18] *}
-## Notes
+## Notes { #notes }
-When you return a `Response` directly its data is not validated, converted (serialized), nor documented automatically.
+When you return a `Response` directly its data is not validated, converted (serialized), or documented automatically.
But you can still document it as described in [Additional Responses in OpenAPI](additional-responses.md){.internal-link target=_blank}.
diff --git a/docs/en/docs/advanced/response-headers.md b/docs/en/docs/advanced/response-headers.md
index 97e888983..98747eabd 100644
--- a/docs/en/docs/advanced/response-headers.md
+++ b/docs/en/docs/advanced/response-headers.md
@@ -1,6 +1,6 @@
-# Response Headers
+# Response Headers { #response-headers }
-## Use a `Response` parameter
+## Use a `Response` parameter { #use-a-response-parameter }
You can declare a parameter of type `Response` in your *path operation function* (as you can do for cookies).
@@ -16,7 +16,7 @@ And if you declared a `response_model`, it will still be used to filter and conv
You can also declare the `Response` parameter in dependencies, and set headers (and cookies) in them.
-## Return a `Response` directly
+## Return a `Response` directly { #return-a-response-directly }
You can also add headers when you return a `Response` directly.
@@ -34,7 +34,7 @@ And as the `Response` can be used frequently to set headers and cookies, **FastA
///
-## Custom Headers
+## Custom Headers { #custom-headers }
Keep in mind that custom proprietary headers can be added
using the 'X-' prefix.
diff --git a/docs/en/docs/advanced/security/http-basic-auth.md b/docs/en/docs/advanced/security/http-basic-auth.md
index 234e2f940..01b98eeff 100644
--- a/docs/en/docs/advanced/security/http-basic-auth.md
+++ b/docs/en/docs/advanced/security/http-basic-auth.md
@@ -1,4 +1,4 @@
-# HTTP Basic Auth
+# HTTP Basic Auth { #http-basic-auth }
For the simplest cases, you can use HTTP Basic Auth.
@@ -12,7 +12,7 @@ That tells the browser to show the integrated prompt for a username and password
Then, when you type that username and password, the browser sends them in the header automatically.
-## Simple HTTP Basic Auth
+## Simple HTTP Basic Auth { #simple-http-basic-auth }
* Import `HTTPBasic` and `HTTPBasicCredentials`.
* Create a "`security` scheme" using `HTTPBasic`.
@@ -26,7 +26,7 @@ When you try to open the URL for the first time (or click the "Execute" button i

-## Check the username
+## Check the username { #check-the-username }
Here's a more complete example.
@@ -52,7 +52,7 @@ if not (credentials.username == "stanleyjobson") or not (credentials.password ==
But by using the `secrets.compare_digest()` it will be secure against a type of attacks called "timing attacks".
-### Timing Attacks
+### Timing Attacks { #timing-attacks }
But what's a "timing attack"?
@@ -80,19 +80,19 @@ if "stanleyjobsox" == "stanleyjobson" and "love123" == "swordfish":
Python will have to compare the whole `stanleyjobso` in both `stanleyjobsox` and `stanleyjobson` before realizing that both strings are not the same. So it will take some extra microseconds to reply back "Incorrect username or password".
-#### The time to answer helps the attackers
+#### The time to answer helps the attackers { #the-time-to-answer-helps-the-attackers }
At that point, by noticing that the server took some microseconds longer to send the "Incorrect username or password" response, the attackers will know that they got _something_ right, some of the initial letters were right.
And then they can try again knowing that it's probably something more similar to `stanleyjobsox` than to `johndoe`.
-#### A "professional" attack
+#### A "professional" attack { #a-professional-attack }
Of course, the attackers would not try all this by hand, they would write a program to do it, possibly with thousands or millions of tests per second. And they would get just one extra correct letter at a time.
But doing that, in some minutes or hours the attackers would have guessed the correct username and password, with the "help" of our application, just using the time taken to answer.
-#### Fix it with `secrets.compare_digest()`
+#### Fix it with `secrets.compare_digest()` { #fix-it-with-secrets-compare-digest }
But in our code we are actually using `secrets.compare_digest()`.
@@ -100,7 +100,7 @@ In short, it will take the same time to compare `stanleyjobsox` to `stanleyjobso
That way, using `secrets.compare_digest()` in your application code, it will be safe against this whole range of security attacks.
-### Return the error
+### Return the error { #return-the-error }
After detecting that the credentials are incorrect, return an `HTTPException` with a status code 401 (the same returned when no credentials are provided) and add the header `WWW-Authenticate` to make the browser show the login prompt again:
diff --git a/docs/en/docs/advanced/security/index.md b/docs/en/docs/advanced/security/index.md
index edb42132e..996d716b4 100644
--- a/docs/en/docs/advanced/security/index.md
+++ b/docs/en/docs/advanced/security/index.md
@@ -1,6 +1,6 @@
-# Advanced Security
+# Advanced Security { #advanced-security }
-## Additional Features
+## Additional Features { #additional-features }
There are some extra features to handle security apart from the ones covered in the [Tutorial - User Guide: Security](../../tutorial/security/index.md){.internal-link target=_blank}.
@@ -12,7 +12,7 @@ And it's possible that for your use case, the solution is in one of them.
///
-## Read the Tutorial first
+## Read the Tutorial first { #read-the-tutorial-first }
The next sections assume you already read the main [Tutorial - User Guide: Security](../../tutorial/security/index.md){.internal-link target=_blank}.
diff --git a/docs/en/docs/advanced/security/oauth2-scopes.md b/docs/en/docs/advanced/security/oauth2-scopes.md
index 4cb0b39bc..67c927cd0 100644
--- a/docs/en/docs/advanced/security/oauth2-scopes.md
+++ b/docs/en/docs/advanced/security/oauth2-scopes.md
@@ -1,12 +1,12 @@
-# OAuth2 scopes
+# OAuth2 scopes { #oauth2-scopes }
You can use OAuth2 scopes directly with **FastAPI**, they are integrated to work seamlessly.
This would allow you to have a more fine-grained permission system, following the OAuth2 standard, integrated into your OpenAPI application (and the API docs).
-OAuth2 with scopes is the mechanism used by many big authentication providers, like Facebook, Google, GitHub, Microsoft, Twitter, etc. They use it to provide specific permissions to users and applications.
+OAuth2 with scopes is the mechanism used by many big authentication providers, like Facebook, Google, GitHub, Microsoft, X (Twitter), etc. They use it to provide specific permissions to users and applications.
-Every time you "log in with" Facebook, Google, GitHub, Microsoft, Twitter, that application is using OAuth2 with scopes.
+Every time you "log in with" Facebook, Google, GitHub, Microsoft, X (Twitter), that application is using OAuth2 with scopes.
In this section you will see how to manage authentication and authorization with the same OAuth2 with scopes in your **FastAPI** application.
@@ -26,7 +26,7 @@ But if you know you need it, or you are curious, keep reading.
///
-## OAuth2 scopes and OpenAPI
+## OAuth2 scopes and OpenAPI { #oauth2-scopes-and-openapi }
The OAuth2 specification defines "scopes" as a list of strings separated by spaces.
@@ -58,15 +58,15 @@ For OAuth2 they are just strings.
///
-## Global view
+## Global view { #global-view }
First, let's quickly see the parts that change from the examples in the main **Tutorial - User Guide** for [OAuth2 with Password (and hashing), Bearer with JWT tokens](../../tutorial/security/oauth2-jwt.md){.internal-link target=_blank}. Now using OAuth2 scopes:
-{* ../../docs_src/security/tutorial005_an_py310.py hl[5,9,13,47,65,106,108:116,122:125,129:135,140,156] *}
+{* ../../docs_src/security/tutorial005_an_py310.py hl[5,9,13,47,65,106,108:116,122:126,130:136,141,157] *}
Now let's review those changes step by step.
-## OAuth2 Security scheme
+## OAuth2 Security scheme { #oauth2-security-scheme }
The first change is that now we are declaring the OAuth2 security scheme with two available scopes, `me` and `items`.
@@ -82,7 +82,7 @@ This is the same mechanism used when you give permissions while logging in with

-## JWT token with scopes
+## JWT token with scopes { #jwt-token-with-scopes }
Now, modify the token *path operation* to return the scopes requested.
@@ -98,9 +98,9 @@ But in your application, for security, you should make sure you only add the sco
///
-{* ../../docs_src/security/tutorial005_an_py310.py hl[156] *}
+{* ../../docs_src/security/tutorial005_an_py310.py hl[157] *}
-## Declare scopes in *path operations* and dependencies
+## Declare scopes in *path operations* and dependencies { #declare-scopes-in-path-operations-and-dependencies }
Now we declare that the *path operation* for `/users/me/items/` requires the scope `items`.
@@ -124,7 +124,7 @@ We are doing it here to demonstrate how **FastAPI** handles scopes declared at d
///
-{* ../../docs_src/security/tutorial005_an_py310.py hl[5,140,171] *}
+{* ../../docs_src/security/tutorial005_an_py310.py hl[5,141,172] *}
/// info | Technical Details
@@ -136,7 +136,7 @@ But when you import `Query`, `Path`, `Depends`, `Security` and others from `fast
///
-## Use `SecurityScopes`
+## Use `SecurityScopes` { #use-securityscopes }
Now update the dependency `get_current_user`.
@@ -152,7 +152,7 @@ This `SecurityScopes` class is similar to `Request` (`Request` was used to get t
{* ../../docs_src/security/tutorial005_an_py310.py hl[9,106] *}
-## Use the `scopes`
+## Use the `scopes` { #use-the-scopes }
The parameter `security_scopes` will be of type `SecurityScopes`.
@@ -166,7 +166,7 @@ In this exception, we include the scopes required (if any) as a string separated
{* ../../docs_src/security/tutorial005_an_py310.py hl[106,108:116] *}
-## Verify the `username` and data shape
+## Verify the `username` and data shape { #verify-the-username-and-data-shape }
We verify that we get a `username`, and extract the scopes.
@@ -180,17 +180,17 @@ Instead of, for example, a `dict`, or something else, as it could break the appl
We also verify that we have a user with that username, and if not, we raise that same exception we created before.
-{* ../../docs_src/security/tutorial005_an_py310.py hl[47,117:128] *}
+{* ../../docs_src/security/tutorial005_an_py310.py hl[47,117:129] *}
-## Verify the `scopes`
+## Verify the `scopes` { #verify-the-scopes }
We now verify that all the scopes required, by this dependency and all the dependants (including *path operations*), are included in the scopes provided in the token received, otherwise raise an `HTTPException`.
For this, we use `security_scopes.scopes`, that contains a `list` with all these scopes as `str`.
-{* ../../docs_src/security/tutorial005_an_py310.py hl[129:135] *}
+{* ../../docs_src/security/tutorial005_an_py310.py hl[130:136] *}
-## Dependency tree and scopes
+## Dependency tree and scopes { #dependency-tree-and-scopes }
Let's review again this dependency tree and the scopes.
@@ -223,7 +223,7 @@ All depending on the `scopes` declared in each *path operation* and each depende
///
-## More details about `SecurityScopes`
+## More details about `SecurityScopes` { #more-details-about-securityscopes }
You can use `SecurityScopes` at any point, and in multiple places, it doesn't have to be at the "root" dependency.
@@ -233,7 +233,7 @@ Because the `SecurityScopes` will have all the scopes declared by dependants, yo
They will be checked independently for each *path operation*.
-## Check it
+## Check it { #check-it }
If you open the API docs, you can authenticate and specify which scopes you want to authorize.
@@ -245,7 +245,7 @@ And if you select the scope `me` but not the scope `items`, you will be able to
That's what would happen to a third party application that tried to access one of these *path operations* with a token provided by a user, depending on how many permissions the user gave the application.
-## About third party integrations
+## About third party integrations { #about-third-party-integrations }
In this example we are using the OAuth2 "password" flow.
@@ -269,6 +269,6 @@ But in the end, they are implementing the same OAuth2 standard.
**FastAPI** includes utilities for all these OAuth2 authentication flows in `fastapi.security.oauth2`.
-## `Security` in decorator `dependencies`
+## `Security` in decorator `dependencies` { #security-in-decorator-dependencies }
The same way you can define a `list` of `Depends` in the decorator's `dependencies` parameter (as explained in [Dependencies in path operation decorators](../../tutorial/dependencies/dependencies-in-path-operation-decorators.md){.internal-link target=_blank}), you could also use `Security` with `scopes` there.
diff --git a/docs/en/docs/advanced/settings.md b/docs/en/docs/advanced/settings.md
index 1af19a045..a218c3d01 100644
--- a/docs/en/docs/advanced/settings.md
+++ b/docs/en/docs/advanced/settings.md
@@ -1,4 +1,4 @@
-# Settings and Environment Variables
+# Settings and Environment Variables { #settings-and-environment-variables }
In many cases your application could need some external settings or configurations, for example secret keys, database credentials, credentials for email services, etc.
@@ -12,17 +12,17 @@ To understand environment variables you can read [Environment Variables](../envi
///
-## Types and validation
+## Types and validation { #types-and-validation }
These environment variables can only handle text strings, as they are external to Python and have to be compatible with other programs and the rest of the system (and even with different operating systems, as Linux, Windows, macOS).
That means that any value read in Python from an environment variable will be a `str`, and any conversion to a different type or any validation has to be done in code.
-## Pydantic `Settings`
+## Pydantic `Settings` { #pydantic-settings }
Fortunately, Pydantic provides a great utility to handle these settings coming from environment variables with
Pydantic: Settings management.
-### Install `pydantic-settings`
+### Install `pydantic-settings` { #install-pydantic-settings }
First, make sure you create your [virtual environment](../virtual-environments.md){.internal-link target=_blank}, activate it, and then install the `pydantic-settings` package:
@@ -52,7 +52,7 @@ In Pydantic v1 it came included with the main package. Now it is distributed as
///
-### Create the `Settings` object
+### Create the `Settings` object { #create-the-settings-object }
Import `BaseSettings` from Pydantic and create a sub-class, very much like with a Pydantic model.
@@ -88,13 +88,13 @@ Then, when you create an instance of that `Settings` class (in this case, in the
Next it will convert and validate the data. So, when you use that `settings` object, you will have data of the types you declared (e.g. `items_per_user` will be an `int`).
-### Use the `settings`
+### Use the `settings` { #use-the-settings }
Then you can use the new `settings` object in your application:
{* ../../docs_src/settings/tutorial001.py hl[18:20] *}
-### Run the server
+### Run the server { #run-the-server }
Next, you would run the server passing the configurations as environment variables, for example you could set an `ADMIN_EMAIL` and `APP_NAME` with:
@@ -120,7 +120,7 @@ The `app_name` would be `"ChimichangApp"`.
And the `items_per_user` would keep its default value of `50`.
-## Settings in another module
+## Settings in another module { #settings-in-another-module }
You could put those settings in another module file as you saw in [Bigger Applications - Multiple Files](../tutorial/bigger-applications.md){.internal-link target=_blank}.
@@ -138,13 +138,13 @@ You would also need a file `__init__.py` as you saw in [Bigger Applications - Mu
///
-## Settings in a dependency
+## Settings in a dependency { #settings-in-a-dependency }
In some occasions it might be useful to provide the settings from a dependency, instead of having a global object with `settings` that is used everywhere.
This could be especially useful during testing, as it's very easy to override a dependency with your own custom settings.
-### The config file
+### The config file { #the-config-file }
Coming from the previous example, your `config.py` file could look like:
@@ -152,7 +152,7 @@ Coming from the previous example, your `config.py` file could look like:
Notice that now we don't create a default instance `settings = Settings()`.
-### The main app file
+### The main app file { #the-main-app-file }
Now we create a dependency that returns a new `config.Settings()`.
@@ -170,7 +170,7 @@ And then we can require it from the *path operation function* as a dependency an
{* ../../docs_src/settings/app02_an_py39/main.py hl[17,19:21] *}
-### Settings and testing
+### Settings and testing { #settings-and-testing }
Then it would be very easy to provide a different settings object during testing by creating a dependency override for `get_settings`:
@@ -180,7 +180,7 @@ In the dependency override we set a new value for the `admin_email` when creatin
Then we can test that it is used.
-## Reading a `.env` file
+## Reading a `.env` file { #reading-a-env-file }
If you have many settings that possibly change a lot, maybe in different environments, it might be useful to put them on a file and then read them from it as if they were environment variables.
@@ -202,7 +202,7 @@ For this to work, you need to `pip install python-dotenv`.
///
-### The `.env` file
+### The `.env` file { #the-env-file }
You could have a `.env` file with:
@@ -211,7 +211,7 @@ ADMIN_EMAIL="deadpool@example.com"
APP_NAME="ChimichangApp"
```
-### Read settings from `.env`
+### Read settings from `.env` { #read-settings-from-env }
And then update your `config.py` with:
@@ -247,7 +247,7 @@ In Pydantic version 1 the configuration was done in an internal class `Config`,
Here we define the config `env_file` inside of your Pydantic `Settings` class, and set the value to the filename with the dotenv file we want to use.
-### Creating the `Settings` only once with `lru_cache`
+### Creating the `Settings` only once with `lru_cache` { #creating-the-settings-only-once-with-lru-cache }
Reading a file from disk is normally a costly (slow) operation, so you probably want to do it only once and then reuse the same settings object, instead of reading it for each request.
@@ -274,7 +274,7 @@ But as we are using the `@lru_cache` decorator on top, the `Settings` object wil
Then for any subsequent call of `get_settings()` in the dependencies for the next requests, instead of executing the internal code of `get_settings()` and creating a new `Settings` object, it will return the same object that was returned on the first call, again and again.
-#### `lru_cache` Technical Details
+#### `lru_cache` Technical Details { #lru-cache-technical-details }
`@lru_cache` modifies the function it decorates to return the same value that was returned the first time, instead of computing it again, executing the code of the function every time.
@@ -337,7 +337,7 @@ That way, it behaves almost as if it was just a global variable. But as it uses
`@lru_cache` is part of `functools` which is part of Python's standard library, you can read more about it in the
Python docs for `@lru_cache`.
-## Recap
+## Recap { #recap }
You can use Pydantic Settings to handle the settings or configurations for your application, with all the power of Pydantic models.
diff --git a/docs/en/docs/advanced/sub-applications.md b/docs/en/docs/advanced/sub-applications.md
index 48e329fc1..fbd0e1af3 100644
--- a/docs/en/docs/advanced/sub-applications.md
+++ b/docs/en/docs/advanced/sub-applications.md
@@ -1,18 +1,18 @@
-# Sub Applications - Mounts
+# Sub Applications - Mounts { #sub-applications-mounts }
If you need to have two independent FastAPI applications, with their own independent OpenAPI and their own docs UIs, you can have a main app and "mount" one (or more) sub-application(s).
-## Mounting a **FastAPI** application
+## Mounting a **FastAPI** application { #mounting-a-fastapi-application }
"Mounting" means adding a completely "independent" application in a specific path, that then takes care of handling everything under that path, with the _path operations_ declared in that sub-application.
-### Top-level application
+### Top-level application { #top-level-application }
First, create the main, top-level, **FastAPI** application, and its *path operations*:
{* ../../docs_src/sub_applications/tutorial001.py hl[3, 6:8] *}
-### Sub-application
+### Sub-application { #sub-application }
Then, create your sub-application, and its *path operations*.
@@ -20,7 +20,7 @@ This sub-application is just another standard FastAPI application, but this is t
{* ../../docs_src/sub_applications/tutorial001.py hl[11, 14:16] *}
-### Mount the sub-application
+### Mount the sub-application { #mount-the-sub-application }
In your top-level application, `app`, mount the sub-application, `subapi`.
@@ -28,7 +28,7 @@ In this case, it will be mounted at the path `/subapi`:
{* ../../docs_src/sub_applications/tutorial001.py hl[11, 19] *}
-### Check the automatic API docs
+### Check the automatic API docs { #check-the-automatic-api-docs }
Now, run the `fastapi` command with your file:
@@ -56,7 +56,7 @@ You will see the automatic API docs for the sub-application, including only its
If you try interacting with any of the two user interfaces, they will work correctly, because the browser will be able to talk to each specific app or sub-app.
-### Technical Details: `root_path`
+### Technical Details: `root_path` { #technical-details-root-path }
When you mount a sub-application as described above, FastAPI will take care of communicating the mount path for the sub-application using a mechanism from the ASGI specification called a `root_path`.
diff --git a/docs/en/docs/advanced/templates.md b/docs/en/docs/advanced/templates.md
index d9b0ca6f1..f41c47fe8 100644
--- a/docs/en/docs/advanced/templates.md
+++ b/docs/en/docs/advanced/templates.md
@@ -1,4 +1,4 @@
-# Templates
+# Templates { #templates }
You can use any template engine you want with **FastAPI**.
@@ -6,7 +6,7 @@ A common choice is Jinja2, the same one used by Flask and other tools.
There are utilities to configure it easily that you can use directly in your **FastAPI** application (provided by Starlette).
-## Install dependencies
+## Install dependencies { #install-dependencies }
Make sure you create a [virtual environment](../virtual-environments.md){.internal-link target=_blank}, activate it, and install `jinja2`:
@@ -20,7 +20,7 @@ $ pip install jinja2
-## Using `Jinja2Templates`
+## Using `Jinja2Templates` { #using-jinja2templates }
* Import `Jinja2Templates`.
* Create a `templates` object that you can reuse later.
@@ -51,7 +51,7 @@ You could also use `from starlette.templating import Jinja2Templates`.
///
-## Writing templates
+## Writing templates { #writing-templates }
Then you can write a template at `templates/item.html` with, for example:
@@ -59,7 +59,7 @@ Then you can write a template at `templates/item.html` with, for example:
{!../../docs_src/templates/templates/item.html!}
```
-### Template Context Values
+### Template Context Values { #template-context-values }
In the HTML that contains:
@@ -83,7 +83,7 @@ For example, with an ID of `42`, this would render:
Item ID: 42
```
-### Template `url_for` Arguments
+### Template `url_for` Arguments { #template-url-for-arguments }
You can also use `url_for()` inside of the template, it takes as arguments the same arguments that would be used by your *path operation function*.
@@ -105,7 +105,7 @@ For example, with an ID of `42`, this would render:
.
diff --git a/docs/en/docs/advanced/testing-dependencies.md b/docs/en/docs/advanced/testing-dependencies.md
index 17b4f9814..b52b47c96 100644
--- a/docs/en/docs/advanced/testing-dependencies.md
+++ b/docs/en/docs/advanced/testing-dependencies.md
@@ -1,6 +1,6 @@
-# Testing Dependencies with Overrides
+# Testing Dependencies with Overrides { #testing-dependencies-with-overrides }
-## Overriding dependencies during testing
+## Overriding dependencies during testing { #overriding-dependencies-during-testing }
There are some scenarios where you might want to override a dependency during testing.
@@ -8,7 +8,7 @@ You don't want the original dependency to run (nor any of the sub-dependencies i
Instead, you want to provide a different dependency that will be used only during tests (possibly only some specific tests), and will provide a value that can be used where the value of the original dependency was used.
-### Use cases: external service
+### Use cases: external service { #use-cases-external-service }
An example could be that you have an external authentication provider that you need to call.
@@ -20,7 +20,7 @@ You probably want to test the external provider once, but not necessarily call i
In this case, you can override the dependency that calls that provider, and use a custom dependency that returns a mock user, only for your tests.
-### Use the `app.dependency_overrides` attribute
+### Use the `app.dependency_overrides` attribute { #use-the-app-dependency-overrides-attribute }
For these cases, your **FastAPI** application has an attribute `app.dependency_overrides`, it is a simple `dict`.
diff --git a/docs/en/docs/advanced/testing-events.md b/docs/en/docs/advanced/testing-events.md
index 0c554c4ec..cb8881a09 100644
--- a/docs/en/docs/advanced/testing-events.md
+++ b/docs/en/docs/advanced/testing-events.md
@@ -1,5 +1,12 @@
-# Testing Events: startup - shutdown
+# Testing Events: lifespan and startup - shutdown { #testing-events-lifespan-and-startup-shutdown }
-When you need your event handlers (`startup` and `shutdown`) to run in your tests, you can use the `TestClient` with a `with` statement:
+When you need `lifespan` to run in your tests, you can use the `TestClient` with a `with` statement:
+
+{* ../../docs_src/app_testing/tutorial004.py hl[9:15,18,27:28,30:32,41:43] *}
+
+
+You can read more details about the ["Running lifespan in tests in the official Starlette documentation site."](https://www.starlette.io/lifespan/#running-lifespan-in-tests)
+
+For the deprecated `startup` and `shutdown` events, you can use the `TestClient` as follows:
{* ../../docs_src/app_testing/tutorial003.py hl[9:12,20:24] *}
diff --git a/docs/en/docs/advanced/testing-websockets.md b/docs/en/docs/advanced/testing-websockets.md
index 60dfdc343..22f9bb4a0 100644
--- a/docs/en/docs/advanced/testing-websockets.md
+++ b/docs/en/docs/advanced/testing-websockets.md
@@ -1,4 +1,4 @@
-# Testing WebSockets
+# Testing WebSockets { #testing-websockets }
You can use the same `TestClient` to test WebSockets.
diff --git a/docs/en/docs/advanced/using-request-directly.md b/docs/en/docs/advanced/using-request-directly.md
index 2f88c8f20..e412ad462 100644
--- a/docs/en/docs/advanced/using-request-directly.md
+++ b/docs/en/docs/advanced/using-request-directly.md
@@ -1,4 +1,4 @@
-# Using the Request Directly
+# Using the Request Directly { #using-the-request-directly }
Up to now, you have been declaring the parts of the request that you need with their types.
@@ -13,7 +13,7 @@ And by doing so, **FastAPI** is validating that data, converting it and generati
But there are situations where you might need to access the `Request` object directly.
-## Details about the `Request` object
+## Details about the `Request` object { #details-about-the-request-object }
As **FastAPI** is actually **Starlette** underneath, with a layer of several tools on top, you can use Starlette's
object directly when you need to.
@@ -23,7 +23,7 @@ Although any other parameter declared normally (for example, the body with a Pyd
But there are specific cases where it's useful to get the `Request` object.
-## Use the `Request` object directly
+## Use the `Request` object directly { #use-the-request-object-directly }
Let's imagine you want to get the client's IP address/host inside of your *path operation function*.
@@ -43,7 +43,7 @@ The same way, you can declare any other parameter as normally, and additionally,
///
-## `Request` documentation
+## `Request` documentation { #request-documentation }
You can read more details about the
.
diff --git a/docs/en/docs/advanced/websockets.md b/docs/en/docs/advanced/websockets.md
index ee8e901df..4ba24637f 100644
--- a/docs/en/docs/advanced/websockets.md
+++ b/docs/en/docs/advanced/websockets.md
@@ -1,8 +1,8 @@
-# WebSockets
+# WebSockets { #websockets }
You can use
with **FastAPI**.
-## Install `WebSockets`
+## Install `WebSockets` { #install-websockets }
Make sure you create a [virtual environment](../virtual-environments.md){.internal-link target=_blank}, activate it, and install `websockets`:
@@ -16,9 +16,9 @@ $ pip install websockets