@ -34,7 +34,7 @@ Keep in mind that you have to return the `JSONResponse` directly.
///
/// info
/// note
The `model` key is not part of OpenAPI.
@ -183,7 +183,7 @@ Notice that you have to return the image using a `FileResponse` directly.
///
/// info
/// note
Unless you specify a different media type explicitly in your `responses` parameter, FastAPI will assume the response has the same media type as the main response class (default `application/json`).
@ -120,7 +120,7 @@ To add a function that should be run when the application is shutting down, decl
Here, the `shutdown` event handler function will write a text line `"Application shutdown"` to a file `log.txt`.
/// info
/// note
In the `open()` function, the `mode="a"` means "append", so, the line will be added after whatever is on that file, without overwriting the previous contents.
@ -152,7 +152,7 @@ Just a technical detail for the curious nerds. 🤓
Underneath, in the ASGI technical specification, this is part of the [Lifespan Protocol](https://asgi.readthedocs.io/en/latest/specs/lifespan.html), and it defines events called `startup` and `shutdown`.
/// info
/// note
You can read more about the Starlette `lifespan` handlers in [Starlette's Lifespan' docs](https://www.starlette.dev/lifespan/).
@ -22,7 +22,7 @@ With **FastAPI**, using OpenAPI, you can define the names of these webhooks, the
This can make it a lot easier for your users to **implement their APIs** to receive your **webhook** requests, they might even be able to autogenerate some of their own API code.
/// info
/// note
Webhooks are available in OpenAPI 3.1.0 and above, supported by FastAPI `0.99.0` and above.
@ -36,7 +36,7 @@ When you create a **FastAPI** application, there is a `webhooks` attribute that
The webhooks that you define will end up in the **OpenAPI** schema and the automatic **docs UI**.
/// info
/// note
The `app.webhooks` object is actually just an `APIRouter`, the same type you would use when structuring your app with multiple files.
@ -81,7 +81,7 @@ If you need to support clients that don't send a `Content-Type` header, you can
With this setting, requests without a `Content-Type` header will have their body parsed as JSON, which is the same behavior as older versions of FastAPI.
/// info
/// note
This behavior and configuration was added in FastAPI 0.132.0.
@ -36,7 +36,7 @@ Django REST Framework was created by Tom Christie. The same creator of Starlette
///
/// check | Inspired **FastAPI** to
/// tip | Inspired **FastAPI** to
Have an automatic API documentation web user interface.
@ -56,7 +56,7 @@ This decoupling of parts, and being a "microframework" that could be extended to
Given the simplicity of Flask, it seemed like a good match for building APIs. The next thing to find was a "Django REST Framework" for Flask.
/// check | Inspired **FastAPI** to
/// tip | Inspired **FastAPI** to
Be a micro-framework. Making it easy to mix and match the tools and parts needed.
@ -98,7 +98,7 @@ def read_url():
See the similarities in `requests.get(...)` and `@app.get(...)`.
/// check | Inspired **FastAPI** to
/// tip | Inspired **FastAPI** to
* Have a simple and intuitive API.
* Use HTTP method names (operations) directly, in a straightforward and intuitive way.
@ -118,7 +118,7 @@ At some point, Swagger was given to the Linux Foundation, to be renamed OpenAPI.
That's why when talking about version 2.0 it's common to say "Swagger", and for version 3+ "OpenAPI".
/// check | Inspired **FastAPI** to
/// tip | Inspired **FastAPI** to
Adopt and use an open standard for API specifications, instead of a custom schema.
@ -147,7 +147,7 @@ These features are what Marshmallow was built to provide. It is a great library,
But it was created before there existed Python type hints. So, to define every <dfntitle="the definition of how data should be formed">schema</dfn> you need to use specific utils and classes provided by Marshmallow.
/// check | Inspired **FastAPI** to
/// tip | Inspired **FastAPI** to
Use code to define "schemas" that provide data types and validation, automatically.
@ -163,13 +163,13 @@ It uses Marshmallow underneath to do the data validation. And it was created by
It's a great tool and I have used it a lot too, before having **FastAPI**.
/// info
/// note
Webargs was created by the same Marshmallow developers.
///
/// check | Inspired **FastAPI** to
/// tip | Inspired **FastAPI** to
Have automatic validation of incoming request data.
@ -193,13 +193,13 @@ But then, we have again the problem of having a micro-syntax, inside of a Python
The editor can't help much with that. And if we modify parameters or Marshmallow schemas and forget to also modify that YAML docstring, the generated schema would be obsolete.
/// info
/// note
APISpec was created by the same Marshmallow developers.
///
/// check | Inspired **FastAPI** to
/// tip | Inspired **FastAPI** to
Support the open standard for APIs, OpenAPI.
@ -225,13 +225,13 @@ Using it led to the creation of several Flask full-stack generators. These are t
And these same full-stack generators were the base of the [**FastAPI** Project Generators](project-generation.md).
/// info
/// note
Flask-apispec was created by the same Marshmallow developers.
///
/// check | Inspired **FastAPI** to
/// tip | Inspired **FastAPI** to
Generate the OpenAPI schema automatically, from the same code that defines serialization and validation.
@ -251,7 +251,7 @@ But as TypeScript data is not preserved after compilation to JavaScript, it cann
It can't handle nested models very well. So, if the JSON body in the request is a JSON object that has inner fields that in turn are nested JSON objects, it cannot be properly documented and validated.
/// check | Inspired **FastAPI** to
/// tip | Inspired **FastAPI** to
Use Python types to have great editor support.
@ -271,7 +271,7 @@ It clearly inspired Uvicorn and Starlette, that are currently faster than Sanic
///
/// check | Inspired **FastAPI** to
/// tip | Inspired **FastAPI** to
Find a way to have a crazy performance.
@ -287,7 +287,7 @@ It is designed to have functions that receive two parameters, one "request" and
So, data validation, serialization, and documentation, have to be done in code, not automatically. Or they have to be implemented as a framework on top of Falcon, like Hug. This same distinction happens in other frameworks that are inspired by Falcon's design, of having one request object and one response object as parameters.
/// check | Inspired **FastAPI** to
/// tip | Inspired **FastAPI** to
Find ways to get great performance.
@ -313,7 +313,7 @@ The dependency injection system requires pre-registration of the dependencies an
Routes are declared in a single place, using functions declared in other places (instead of using decorators that can be placed right on top of the function that handles the endpoint). This is closer to how Django does it than to how Flask (and Starlette) does it. It separates in the code things that are relatively tightly coupled.
/// check | Inspired **FastAPI** to
/// tip | Inspired **FastAPI** to
Define extra validations for data types using the "default" value of model attributes. This improves editor support, and it was not available in Pydantic before.
@ -335,13 +335,13 @@ It has an interesting, uncommon feature: using the same framework, it's possible
As it is based on the previous standard for synchronous Python web frameworks (WSGI), it can't handle Websockets and other things, although it still has high performance too.
/// info
/// note
Hug was created by Timothy Crosley, the same creator of [`isort`](https://github.com/timothycrosley/isort), a great tool to automatically sort imports in Python files.
///
/// check | Ideas inspiring **FastAPI**
/// tip | Ideas inspiring **FastAPI**
Hug inspired parts of APIStar, and was one of the tools I found most promising, alongside APIStar.
@ -375,7 +375,7 @@ It was no longer an API web framework, as the creator needed to focus on Starlet
Now APIStar is a set of tools to validate OpenAPI specifications, not a web framework.
/// info
/// note
APIStar was created by Tom Christie. The same guy that created:
@ -385,7 +385,7 @@ APIStar was created by Tom Christie. The same guy that created:
///
/// check | Inspired **FastAPI** to
/// tip | Inspired **FastAPI** to
Exist.
@ -409,7 +409,7 @@ That makes it extremely intuitive.
It is comparable to Marshmallow. Although it's faster than Marshmallow in benchmarks. And as it is based on the same Python type hints, the editor support is great.
/// check | **FastAPI** uses it to
/// tip | **FastAPI** uses it to
Handle all the data validation, data serialization and automatic model documentation (based on JSON Schema).
@ -452,7 +452,7 @@ Nevertheless, it is already being used as a "standard" by several tools. This gr
///
/// check | **FastAPI** uses it to
/// tip | **FastAPI** uses it to
Handle all the core web parts. Adding features on top.
@ -470,7 +470,7 @@ It is not a web framework, but a server. For example, it doesn't provide tools f
It is the recommended server for Starlette and **FastAPI**.
/// check | **FastAPI** recommends it as
/// tip | **FastAPI** recommends it as
The main web server to run **FastAPI** applications.
There are other formats and tools to define and install package dependencies.
@ -556,7 +556,7 @@ If you are using containers (e.g. Docker, Kubernetes), then there are two main a
If you have **multiple containers**, probably each one running a **single process** (for example, in a **Kubernetes** cluster), then you would probably want to have a **separate container** doing the work of the **previous steps** in a single container, running a single process, **before** running the replicated worker containers.
/// info
/// note
If you are using Kubernetes, this would probably be an [Init Container](https://kubernetes.io/docs/concepts/workloads/pods/init-containers/).
@ -17,7 +17,7 @@ As you saw in the previous chapter about [Deployment Concepts](concepts.md), the
Here I'll show you how to use **Uvicorn** with **worker processes** using the `fastapi` command or the `uvicorn` command directly.
/// info
/// note
If you are using containers, for example with Docker or Kubernetes, I'll tell you more about that in the next chapter: [FastAPI in Containers - Docker](docker.md).
To learn more about [Pydantic, check its docs](https://docs.pydantic.dev/).
@ -341,7 +341,7 @@ This might all sound abstract. Don't worry. You'll see all this in action in the
The important thing is that by using standard Python types, in a single place (instead of adding more classes, decorators, etc), **FastAPI** will do a lot of the work for you.
/// info
/// note
If you already went through all the tutorial and came back to see more about types, a good resource is [the "cheat sheet" from `mypy`](https://mypy.readthedocs.io/en/latest/cheat_sheet_py3.html).
@ -4,7 +4,7 @@ If you are building an application or a web API, it's rarely the case that you c
**FastAPI** provides a convenience tool to structure your application while keeping all the flexibility.
/// info
/// note
If you come from Flask, this would be the equivalent of Flask's Blueprints.
@ -194,7 +194,7 @@ Having `dependencies` in the `APIRouter` can be used, for example, to require au
///
/// check
/// tip
The `prefix`, `tags`, `responses`, and `dependencies` parameters are (as in many other cases) just a feature from **FastAPI** to help you avoid code duplication.
@ -339,7 +339,7 @@ We could also import them like:
from app.routers import items, users
```
/// info
/// note
The first version is a "relative import":
@ -382,7 +382,7 @@ Now, let's include the `router`s from the submodules `users` and `items`:
@ -65,7 +65,7 @@ The same way, you can declare optional query parameters, by setting their defaul
In this case, the function parameter `q` will be optional, and will be `None` by default.
/// check
/// tip
Also notice that **FastAPI** is smart enough to notice that the path parameter `item_id` is a path parameter and `q` is not, so, it's a query parameter.
When you need to receive form fields instead of JSON, you can use `Form`.
/// info
/// note
To use forms, first install [`python-multipart`](https://github.com/Kludex/python-multipart).
@ -32,7 +32,7 @@ The <dfn title="specification">spec</dfn> requires the fields to be exactly name
With `Form` you can declare the same configurations as with `Body` (and `Query`, `Path`, `Cookie`), including validation, examples, an alias (e.g. `user-name` instead of `username`), etc.
/// info
/// note
`Form` is a class that inherits directly from `Body`.
@ -18,7 +18,7 @@ Notice that `status_code` is a parameter of the "decorator" method (`get`, `post
The `status_code` parameter receives a number with the HTTP status code.
/// info
/// note
`status_code` can alternatively also receive an `IntEnum`, such as Python's [`http.HTTPStatus`](https://docs.python.org/3/library/http.html#http.HTTPStatus).
@ -24,7 +24,7 @@ For example you could use it to add metadata for a frontend user interface, etc.
///
/// info
/// note
OpenAPI 3.1.0 (used since FastAPI 0.99.0) added support for `examples`, which is part of the **JSON Schema** standard.
@ -155,7 +155,7 @@ OpenAPI also added `example` and `examples` fields to other parts of the specifi
* `File()`
* `Form()`
/// info
/// note
This old OpenAPI-specific `examples` parameter is now `openapi_examples` since FastAPI `0.103.0`.
@ -171,7 +171,7 @@ And now this new `examples` field takes precedence over the old single (and cust
This new `examples` field in JSON Schema is **just a `list`** of examples, not a dict with extra metadata as in the other places in OpenAPI (described above).
/// info
/// note
Even after OpenAPI 3.1.0 was released with this new simpler integration with JSON Schema, for a while, Swagger UI, the tool that provides the automatic docs, didn't support OpenAPI 3.1.0 (it does since version 5.0.0 🎉).
@ -24,7 +24,7 @@ Copy the example in a file `main.py`:
## Run it { #run-it }
/// info
/// note
The [`python-multipart`](https://github.com/Kludex/python-multipart) package is automatically installed with **FastAPI** when you run the `pip install "fastapi[standard]"` command.
@ -60,7 +60,7 @@ You will see something like this:
<imgsrc="/img/tutorial/security/image01.png">
/// check | Authorize button!
/// tip | Authorize button!
You already have a shiny new "Authorize" button.
@ -118,7 +118,7 @@ So, let's review it from that simplified point of view:
In this example we are going to use **OAuth2**, with the **Password** flow, using a **Bearer** token. We do that using the `OAuth2PasswordBearer` class.
/// info
/// note
A "bearer" token is not the only option.
@ -148,7 +148,7 @@ This parameter doesn't create that endpoint / *path operation*, but declares tha
We will soon also create the actual path operation.
/// info
/// note
If you are a very strict "Pythonista" you might dislike the style of the parameter name `tokenUrl` instead of `token_url`.
@ -176,7 +176,7 @@ This dependency will provide a `str` that is assigned to the parameter `token` o
**FastAPI** will know that it can use this dependency to define a "security scheme" in the OpenAPI schema (and the automatic API docs).
/// info | Technical Details
/// note | Technical Details
**FastAPI** will know that it can use the class `OAuth2PasswordBearer` (declared in a dependency) to define the security scheme in OpenAPI because it inherits from `fastapi.security.oauth2.OAuth2`, which in turn inherits from `fastapi.security.base.SecurityBase`.
@ -4,7 +4,7 @@ You can stream data to the client using **Server-Sent Events** (SSE).
This is similar to [Stream JSON Lines](stream-json-lines.md), but uses the `text/event-stream` format, which is supported natively by browsers with the [`EventSource` API](https://developer.mozilla.org/en-US/docs/Web/API/EventSource).
You could have a sequence of data that you would like to send in a "**stream**", you could do it with **JSON Lines**.
/// info
/// note
Added in FastAPI 0.134.0.
@ -48,7 +48,7 @@ A response would have a content type of `application/jsonl` (instead of `applica
It's very similar to a JSON array (equivalent of a Python list), but instead of being wrapped in `[]` and having `,` between the items, it has **one JSON object per line**, they are separated by a new line character.
/// info
/// note
The important point is that your app will be able to produce each line in turn, while the client consumes the previous lines.
@ -8,7 +8,7 @@ With it, you can use [pytest](https://docs.pytest.org/) directly with **FastAPI*
## Using `TestClient` { #using-testclient }
/// info
/// note
To use `TestClient`, first install [`httpx`](https://www.python-httpx.org).
@ -144,7 +144,7 @@ E.g.:
For more information about how to pass data to the backend (using `httpx` or the `TestClient`) check the [HTTPX documentation](https://www.python-httpx.org).
/// info
/// note
Note that the `TestClient` receives data that can be converted to JSON, not Pydantic models.
When you work in Python projects you probably should use a **virtual environment** (or a similar mechanism) to isolate the packages you install for each project.
/// info
/// note
If you already know about virtual environments, how to create them and use them, you might want to skip this section. 🤓
@ -18,7 +18,7 @@ A **virtual environment** is a directory with some files in it.
///
/// info
/// note
This page will teach you how to use **virtual environments** and how they work.