FastAPI is a modern, fast (high-performance), web framework for building APIs with Python 3.6+ based on standard Python type hints.
FastAPI is a modern, fast (high-performance), web framework for building APIs with Python 3.7+ based on standard Python type hints.
The key features are:
The key features are:
@ -112,7 +112,7 @@ If you are building a <abbr title="Command Line Interface">CLI</abbr> app to be
## Requirements
## Requirements
Python 3.6+
Python 3.7+
FastAPI stands on the shoulders of giants:
FastAPI stands on the shoulders of giants:
@ -131,7 +131,7 @@ $ pip install fastapi
</div>
</div>
You will also need an ASGI server, for production such as <ahref="https://www.uvicorn.org"class="external-link"target="_blank">Uvicorn</a> or <ahref="https://gitlab.com/pgjones/hypercorn"class="external-link"target="_blank">Hypercorn</a>.
You will also need an ASGI server, for production such as <ahref="https://www.uvicorn.org"class="external-link"target="_blank">Uvicorn</a> or <ahref="https://github.com/pgjones/hypercorn"class="external-link"target="_blank">Hypercorn</a>.
<divclass="termy">
<divclass="termy">
@ -328,7 +328,7 @@ You do that with standard modern Python types.
You don't have to learn a new syntax, the methods or classes of a specific library, etc.
You don't have to learn a new syntax, the methods or classes of a specific library, etc.
You are encouraged to [write tests](https://fastapi.tiangolo.com/tutorial/testing/) for your application and update your FastAPI version frequently after ensuring that your tests are passing. This way you will benefit from the latest features, bug fixes, and **security fixes**.
You are encouraged to [write tests](https://fastapi.tiangolo.com/tutorial/testing/) for your application and update your FastAPI version frequently after ensuring that your tests are passing. This way you will benefit from the latest features, bug fixes, and **security fixes**.
FastAPI is a modern, fast (high-performance), web framework for building APIs with Python 3.6+ based on standard Python type hints.
The key features are:
* **Fast**: Very high performance, on par with **NodeJS** and **Go** (thanks to Starlette and Pydantic). [One of the fastest Python frameworks available](#performance).
* **Fast to code**: Increase the speed to develop features by about 200% to 300%. *
* **Fewer bugs**: Reduce about 40% of human (developer) induced errors. *
* **Intuitive**: Great editor support. <abbrtitle="also known as auto-complete, autocompletion, IntelliSense">Completion</abbr> everywhere. Less time debugging.
* **Easy**: Designed to be easy to use and learn. Less time reading docs.
* **Short**: Minimize code duplication. Multiple features from each parameter declaration. Fewer bugs.
* **Robust**: Get production-ready code. With automatic interactive documentation.
* **Standards-based**: Based on (and fully compatible with) the open standards for APIs: <ahref="https://github.com/OAI/OpenAPI-Specification"class="external-link"target="_blank">OpenAPI</a> (previously known as Swagger) and <ahref="https://json-schema.org/"class="external-link"target="_blank">JSON Schema</a>.
<small>* estimation based on tests on an internal development team, building production applications.</small>
"_[...] I'm using **FastAPI** a ton these days. [...] I'm actually planning to use it for all of my team's **ML services at Microsoft**. Some of them are getting integrated into the core **Windows** product and some **Office** products._"
"_We adopted the **FastAPI** library to spawn a **REST** server that can be queried to obtain **predictions**. [for Ludwig]_"
<divstyle="text-align: right; margin-right: 10%;">Piero Molino, Yaroslav Dudin, and Sai Sumanth Miryala - <strong>Uber</strong><ahref="https://eng.uber.com/ludwig-v0-2/"target="_blank"><small>(ref)</small></a></div>
---
"_**Netflix** is pleased to announce the open-source release of our **crisis management** orchestration framework: **Dispatch**! [built with **FastAPI**]_"
"_Honestly, what you've built looks super solid and polished. In many ways, it's what I wanted **Hug** to be - it's really inspiring to see someone build that._"
"_If you're looking to learn one **modern framework** for building REST APIs, check out **FastAPI** [...] It's fast, easy to use and easy to learn [...]_"
"_We've switched over to **FastAPI** for our **APIs** [...] I think you'll like it [...]_"
If you are building a <abbrtitle="Command Line Interface">CLI</abbr> app to be used in the terminal instead of a web API, check out <ahref="https://typer.tiangolo.com/"class="external-link"target="_blank">**Typer**</a>.
**Typer** is FastAPI's little sibling. And it's intended to be the **FastAPI of CLIs**. ⌨️ 🚀
## Requirements
Python 3.7+
FastAPI stands on the shoulders of giants:
* <ahref="https://www.starlette.io/"class="external-link"target="_blank">Starlette</a> for the web parts.
* <ahref="https://pydantic-docs.helpmanual.io/"class="external-link"target="_blank">Pydantic</a> for the data parts.
## Installation
<divclass="termy">
```console
$ pip install fastapi
---> 100%
```
</div>
You will also need an ASGI server, for production such as <ahref="https://www.uvicorn.org"class="external-link"target="_blank">Uvicorn</a> or <ahref="https://gitlab.com/pgjones/hypercorn"class="external-link"target="_blank">Hypercorn</a>.
If you don't know, check the _"In a hurry?"_ section about <ahref="https://fastapi.tiangolo.com/async/#in-a-hurry"target="_blank">`async` and `await` in the docs</a>.
</details>
### Run it
Run the server with:
<divclass="termy">
```console
$ uvicorn main:app --reload
INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit)
INFO: Started reloader process [28720]
INFO: Started server process [28722]
INFO: Waiting for application startup.
INFO: Application startup complete.
```
</div>
<detailsmarkdown="1">
<summary>About the command <code>uvicorn main:app --reload</code>...</summary>
The command `uvicorn main:app` refers to:
* `main`: the file `main.py` (the Python "module").
* `app`: the object created inside of `main.py` with the line `app = FastAPI()`.
* `--reload`: make the server restart after code changes. Only do this for development.
</details>
### Check it
Open your browser at <ahref="http://127.0.0.1:8000/items/5?q=somequery"class="external-link"target="_blank">http://127.0.0.1:8000/items/5?q=somequery</a>.
You will see the JSON response as:
```JSON
{"item_id": 5, "q": "somequery"}
```
You already created an API that:
* Receives HTTP requests in the _paths_`/` and `/items/{item_id}`.
* Both _paths_ take `GET`<em>operations</em> (also known as HTTP _methods_).
* The _path_`/items/{item_id}` has a _path parameter_`item_id` that should be an `int`.
* The _path_`/items/{item_id}` has an optional `str`_query parameter_`q`.
### Interactive API docs
Now go to <ahref="http://127.0.0.1:8000/docs"class="external-link"target="_blank">http://127.0.0.1:8000/docs</a>.
You will see the automatic interactive API documentation (provided by <ahref="https://github.com/swagger-api/swagger-ui"class="external-link"target="_blank">Swagger UI</a>):
And now, go to <ahref="http://127.0.0.1:8000/redoc"class="external-link"target="_blank">http://127.0.0.1:8000/redoc</a>.
You will see the alternative automatic documentation (provided by <ahref="https://github.com/Rebilly/ReDoc"class="external-link"target="_blank">ReDoc</a>):
* Then click on the "Execute" button, the user interface will communicate with your API, send the parameters, get the results and show them on the screen:
In summary, you declare **once** the types of parameters, body, etc. as function parameters.
You do that with standard modern Python types.
You don't have to learn a new syntax, the methods or classes of a specific library, etc.
Just standard **Python 3.6+**.
For example, for an `int`:
```Python
item_id: int
```
or for a more complex `Item` model:
```Python
item: Item
```
...and with that single declaration you get:
* Editor support, including:
* Completion.
* Type checks.
* Validation of data:
* Automatic and clear errors when the data is invalid.
* Validation even for deeply nested JSON objects.
* <abbrtitle="also known as: serialization, parsing, marshalling">Conversion</abbr> of input data: coming from the network to Python data and types. Reading from:
* JSON.
* Path parameters.
* Query parameters.
* Cookies.
* Headers.
* Forms.
* Files.
* <abbrtitle="also known as: serialization, parsing, marshalling">Conversion</abbr> of output data: converting from Python data and types to network data (as JSON):
For a more complete example including more features, see the <ahref="https://fastapi.tiangolo.com/tutorial/">Tutorial - User Guide</a>.
**Spoiler alert**: the tutorial - user guide includes:
* Declaration of **parameters** from other different places as: **headers**, **cookies**, **form fields** and **files**.
* How to set **validation constraints** as `maximum_length` or `regex`.
* A very powerful and easy to use **<abbrtitle="also known as components, resources, providers, services, injectables">Dependency Injection</abbr>** system.
* Security and authentication, including support for **OAuth2** with **JWT tokens** and **HTTP Basic** auth.
* More advanced (but equally easy) techniques for declaring **deeply nested JSON models** (thanks to Pydantic).
* Many extra features (thanks to Starlette) as:
* **WebSockets**
* **GraphQL**
* extremely easy tests based on `requests` and `pytest`
* **CORS**
* **Cookie Sessions**
* ...and more.
## Performance
Independent TechEmpower benchmarks show **FastAPI** applications running under Uvicorn as <ahref="https://www.techempower.com/benchmarks/#section=test&runid=7464e520-0dc2-473d-bd34-dbdfd7e85911&hw=ph&test=query&l=zijzen-7"class="external-link"target="_blank">one of the fastest Python frameworks available</a>, only below Starlette and Uvicorn themselves (used internally by FastAPI). (*)
To understand more about it, see the section <ahref="https://fastapi.tiangolo.com/benchmarks/"class="internal-link"target="_blank">Benchmarks</a>.
## Optional Dependencies
Used by Pydantic:
* <ahref="https://github.com/esnme/ultrajson"target="_blank"><code>ujson</code></a> - for faster JSON <abbrtitle="converting the string that comes from an HTTP request into Python data">"parsing"</abbr>.
* <ahref="https://github.com/JoshData/python-email-validator"target="_blank"><code>email_validator</code></a> - for email validation.
Used by Starlette:
* <ahref="https://requests.readthedocs.io"target="_blank"><code>requests</code></a> - Required if you want to use the `TestClient`.
* <ahref="https://jinja.palletsprojects.com"target="_blank"><code>jinja2</code></a> - Required if you want to use the default template configuration.
* <ahref="https://andrew-d.github.io/python-multipart/"target="_blank"><code>python-multipart</code></a> - Required if you want to support form <abbrtitle="converting the string that comes from an HTTP request into Python data">"parsing"</abbr>, with `request.form()`.
* <ahref="https://pythonhosted.org/itsdangerous/"target="_blank"><code>itsdangerous</code></a> - Required for `SessionMiddleware` support.
* <ahref="https://pyyaml.org/wiki/PyYAMLDocumentation"target="_blank"><code>pyyaml</code></a> - Required for Starlette's `SchemaGenerator` support (you probably don't need it with FastAPI).
* <ahref="https://graphene-python.org/"target="_blank"><code>graphene</code></a> - Required for `GraphQLApp` support.
* <ahref="https://github.com/esnme/ultrajson"target="_blank"><code>ujson</code></a> - Required if you want to use `UJSONResponse`.
Used by FastAPI / Starlette:
* <ahref="https://www.uvicorn.org"target="_blank"><code>uvicorn</code></a> - for the server that loads and serves your application.
* <ahref="https://github.com/ijl/orjson"target="_blank"><code>orjson</code></a> - Required if you want to use `ORJSONResponse`.
You can install all of these with `pip install fastapi[all]`.
## License
This project is licensed under the terms of the MIT license.
@ -8,7 +8,7 @@ But FastAPI also supports using <a href="https://docs.python.org/3/library/datac
{!../../../docs_src/dataclasses/tutorial001.py!}
{!../../../docs_src/dataclasses/tutorial001.py!}
```
```
This is still thanks to **Pydantic**, as it has <ahref="https://pydantic-docs.helpmanual.io/usage/dataclasses/#use-of-stdlib-dataclasses-with-basemodel"class="external-link"target="_blank">internal support for `dataclasses`</a>.
This is still supported thanks to **Pydantic**, as it has <ahref="https://pydantic-docs.helpmanual.io/usage/dataclasses/#use-of-stdlib-dataclasses-with-basemodel"class="external-link"target="_blank">internal support for `dataclasses`</a>.
So, even with the code above that doesn't use Pydantic explicitly, FastAPI is using Pydantic to convert those standard dataclasses to Pydantic's own flavor of dataclasses.
So, even with the code above that doesn't use Pydantic explicitly, FastAPI is using Pydantic to convert those standard dataclasses to Pydantic's own flavor of dataclasses.
Every time you install a new package with `pip` under that environment, activate the environment again.
Every time you install a new package with `pip` under that environment, activate the environment again.
This makes sure that if you use a terminal program installed by that package (like `flit`), you use the one from your local environment and not any other that could be installed globally.
This makes sure that if you use a terminal program installed by that package, you use the one from your local environment and not any other that could be installed globally.
### Flit
### pip
**FastAPI** uses <ahref="https://flit.readthedocs.io/en/latest/index.html"class="external-link"target="_blank">Flit</a> to build, package and publish the project.
After activating the environment as described above:
After activating the environment as described above, install `flit`:
<divclass="termy">
<divclass="termy">
```console
```console
$ pip install flit
$ pip install -e .[dev,doc,test]
---> 100%
---> 100%
```
```
</div>
</div>
Now re-activate the environment to make sure you are using the `flit` you just installed (and not a global one).
And now use `flit` to install the development dependencies:
=== "Linux, macOS"
<divclass="termy">
```console
$ flit install --deps develop --symlink
---> 100%
```
</div>
=== "Windows"
If you are on Windows, use `--pth-file` instead of `--symlink`:
<divclass="termy">
```console
$ flit install --deps develop --pth-file
---> 100%
```
</div>
It will install all the dependencies and your local FastAPI in your local environment.
It will install all the dependencies and your local FastAPI in your local environment.
#### Using your local FastAPI
#### Using your local FastAPI
If you create a Python file that imports and uses FastAPI, and run it with the Python from your local environment, it will use your local FastAPI source code.
If you create a Python file that imports and uses FastAPI, and run it with the Python from your local environment, it will use your local FastAPI source code.
And if you update that local FastAPI source code, as it is installed with `--symlink` (or `--pth-file` on Windows), when you run that Python file again, it will use the fresh version of FastAPI you just edited.
And if you update that local FastAPI source code, as it is installed with `-e`, when you run that Python file again, it will use the fresh version of FastAPI you just edited.
That way, you don't have to "install" your local version to be able to test every change.
That way, you don't have to "install" your local version to be able to test every change.
@ -171,7 +139,7 @@ $ bash scripts/format.sh
It will also auto-sort all your imports.
It will also auto-sort all your imports.
For it to sort them correctly, you need to have FastAPI installed locally in your environment, with the command in the section above using `--symlink` (or `--pth-file` on Windows).
For it to sort them correctly, you need to have FastAPI installed locally in your environment, with the command in the section above using `-e`.
FastAPI is a modern, fast (high-performance), web framework for building APIs with Python 3.6+ based on standard Python type hints.
FastAPI is a modern, fast (high-performance), web framework for building APIs with Python 3.7+ based on standard Python type hints.
The key features are:
The key features are:
@ -109,7 +109,7 @@ If you are building a <abbr title="Command Line Interface">CLI</abbr> app to be
## Requirements
## Requirements
Python 3.6+
Python 3.7+
FastAPI stands on the shoulders of giants:
FastAPI stands on the shoulders of giants:
@ -128,7 +128,7 @@ $ pip install fastapi
</div>
</div>
You will also need an ASGI server, for production such as <ahref="https://www.uvicorn.org"class="external-link"target="_blank">Uvicorn</a> or <ahref="https://gitlab.com/pgjones/hypercorn"class="external-link"target="_blank">Hypercorn</a>.
You will also need an ASGI server, for production such as <ahref="https://www.uvicorn.org"class="external-link"target="_blank">Uvicorn</a> or <ahref="https://github.com/pgjones/hypercorn"class="external-link"target="_blank">Hypercorn</a>.
<divclass="termy">
<divclass="termy">
@ -325,7 +325,7 @@ You do that with standard modern Python types.
You don't have to learn a new syntax, the methods or classes of a specific library, etc.
You don't have to learn a new syntax, the methods or classes of a specific library, etc.
* 🐛 Make sure a parameter defined as required is kept required in OpenAPI even if defined as optional in another dependency. PR [#4319](https://github.com/tiangolo/fastapi/pull/4319) by [@cd17822](https://github.com/cd17822).
* ⬆ [pre-commit.ci] pre-commit autoupdate. PR [#5408](https://github.com/tiangolo/fastapi/pull/5408) by [@pre-commit-ci[bot]](https://github.com/apps/pre-commit-ci).
* ♻ Internal small refactor, move `operation_id` parameter position in delete method for consistency with the code. PR [#4474](https://github.com/tiangolo/fastapi/pull/4474) by [@hiel](https://github.com/hiel).
* ⬆️ Upgrade Typer to include Rich in scripts for docs. PR [#5502](https://github.com/tiangolo/fastapi/pull/5502) by [@tiangolo](https://github.com/tiangolo).
* 🐛 Fix calling `mkdocs` for languages as a subprocess to fix/enable MkDocs Material search plugin. PR [#5501](https://github.com/tiangolo/fastapi/pull/5501) by [@tiangolo](https://github.com/tiangolo).
## 0.85.1
### Fixes
* 🐛 Fix support for strings in OpenAPI status codes: `default`, `1XX`, `2XX`, `3XX`, `4XX`, `5XX`. PR [#5187](https://github.com/tiangolo/fastapi/pull/5187) by [@JarroVGIT](https://github.com/JarroVGIT).
### Docs
* 📝 Add WayScript x FastAPI Tutorial to External Links section. PR [#5407](https://github.com/tiangolo/fastapi/pull/5407) by [@moneeka](https://github.com/moneeka).
### Internal
* 👥 Update FastAPI People. PR [#5447](https://github.com/tiangolo/fastapi/pull/5447) by [@github-actions[bot]](https://github.com/apps/github-actions).
* 🔧 Disable Material for MkDocs search plugin. PR [#5495](https://github.com/tiangolo/fastapi/pull/5495) by [@tiangolo](https://github.com/tiangolo).
* 🔇 Ignore Trio warning in tests for CI. PR [#5483](https://github.com/tiangolo/fastapi/pull/5483) by [@samuelcolvin](https://github.com/samuelcolvin).
## 0.85.0
### Features
* ⬆ Upgrade version required of Starlette from `0.19.1` to `0.20.4`. Initial PR [#4820](https://github.com/tiangolo/fastapi/pull/4820) by [@Kludex](https://github.com/Kludex).
* This includes several bug fixes in Starlette.
* ⬆️ Upgrade Uvicorn max version in public extras: all. From `>=0.12.0,<0.18.0` to `>=0.12.0,<0.19.0`. PR [#5401](https://github.com/tiangolo/fastapi/pull/5401) by [@tiangolo](https://github.com/tiangolo).
### Internal
* ⬆️ Upgrade dependencies for doc and dev internal extras: Typer, Uvicorn. PR [#5400](https://github.com/tiangolo/fastapi/pull/5400) by [@tiangolo](https://github.com/tiangolo).
* ⬆️ Upgrade test dependencies: Black, HTTPX, databases, types-ujson. PR [#5399](https://github.com/tiangolo/fastapi/pull/5399) by [@tiangolo](https://github.com/tiangolo).
* ⬆️ Upgrade mypy and tweak internal type annotations. PR [#5398](https://github.com/tiangolo/fastapi/pull/5398) by [@tiangolo](https://github.com/tiangolo).
* 🔧 Update test dependencies, upgrade Pytest, move dependencies from dev to test. PR [#5396](https://github.com/tiangolo/fastapi/pull/5396) by [@tiangolo](https://github.com/tiangolo).
## 0.84.0
### Breaking Changes
This version of FastAPI drops support for Python 3.6. 🔥 Please upgrade to a supported version of Python (3.7 or above), Python 3.6 reached the end-of-life a long time ago. 😅☠
* 🔧 Update package metadata, drop support for Python 3.6, move build internals from Flit to Hatch. PR [#5240](https://github.com/tiangolo/fastapi/pull/5240) by [@ofek](https://github.com/ofek).
## 0.83.0
🚨 This is probably the last release (or one of the last releases) to support Python 3.6. 🔥
Python 3.6 reached the [end-of-life and is no longer supported by Python](https://www.python.org/downloads/release/python-3615/) since around a year ago.
You hopefully updated to a supported version of Python a while ago. If you haven't, you really should.
### Features
* ✨ Add support in `jsonable_encoder` for include and exclude with dataclasses. PR [#4923](https://github.com/tiangolo/fastapi/pull/4923) by [@DCsunset](https://github.com/DCsunset).
### Fixes
* 🐛 Fix `RuntimeError` raised when `HTTPException` has a status code with no content. PR [#5365](https://github.com/tiangolo/fastapi/pull/5365) by [@iudeen](https://github.com/iudeen).
* 🐛 Fix empty reponse body when default `status_code` is empty but the a `Response` parameter with `response.status_code` is set. PR [#5360](https://github.com/tiangolo/fastapi/pull/5360) by [@tmeckel](https://github.com/tmeckel).
### Docs
* 📝 Update `SECURITY.md`. PR [#5377](https://github.com/tiangolo/fastapi/pull/5377) by [@Kludex](https://github.com/Kludex).
### Internal
* ⬆ [pre-commit.ci] pre-commit autoupdate. PR [#5352](https://github.com/tiangolo/fastapi/pull/5352) by [@pre-commit-ci[bot]](https://github.com/apps/pre-commit-ci).
## 0.82.0
🚨 This is probably the last release (or one of the last releases) to support Python 3.6. 🔥
Python 3.6 reached the [end-of-life and is no longer supported by Python](https://www.python.org/downloads/release/python-3615/) since around a year ago.
You hopefully updated to a supported version of Python a while ago. If you haven't, you really should.
### Features
* ✨ Export `WebSocketState` in `fastapi.websockets`. PR [#4376](https://github.com/tiangolo/fastapi/pull/4376) by [@matiuszka](https://github.com/matiuszka).
* ✨ Support Python internal description on Pydantic model's docstring. PR [#3032](https://github.com/tiangolo/fastapi/pull/3032) by [@Kludex](https://github.com/Kludex).
* ✨ Support Python internal description on Pydantic model's docstring. PR [#3032](https://github.com/tiangolo/fastapi/pull/3032) by [@Kludex](https://github.com/Kludex).
* ✨ Update `ORJSONResponse` to support non `str` keys and serializing Numpy arrays. PR [#3892](https://github.com/tiangolo/fastapi/pull/3892) by [@baby5](https://github.com/baby5).
* ✨ Update `ORJSONResponse` to support non `str` keys and serializing Numpy arrays. PR [#3892](https://github.com/tiangolo/fastapi/pull/3892) by [@baby5](https://github.com/baby5).
* 🔧 Update sponsors, disable ImgWhale. PR [#5338](https://github.com/tiangolo/fastapi/pull/5338) by [@tiangolo](https://github.com/tiangolo).
### Fixes
* 🐛 Allow exit code for dependencies with `yield` to always execute, by removing capacity limiter for them, to e.g. allow closing DB connections without deadlocks. PR [#5122](https://github.com/tiangolo/fastapi/pull/5122) by [@adriangb](https://github.com/adriangb).
* 🐛 Fix FastAPI People GitHub Action: set HTTPX timeout for GraphQL query request. PR [#5222](https://github.com/tiangolo/fastapi/pull/5222) by [@iudeen](https://github.com/iudeen).
* 🐛 Make sure a parameter defined as required is kept required in OpenAPI even if defined as optional in another dependency. PR [#4319](https://github.com/tiangolo/fastapi/pull/4319) by [@cd17822](https://github.com/cd17822).
* 🐛 Fix support for path parameters in WebSockets. PR [#3879](https://github.com/tiangolo/fastapi/pull/3879) by [@davidbrochart](https://github.com/davidbrochart).
### Docs
* ✏ Update Hypercorn link, now pointing to GitHub. PR [#5346](https://github.com/tiangolo/fastapi/pull/5346) by [@baconfield](https://github.com/baconfield).
* ✏ Tweak wording in `docs/en/docs/advanced/dataclasses.md`. PR [#3698](https://github.com/tiangolo/fastapi/pull/3698) by [@pfackeldey](https://github.com/pfackeldey).
* 📝 Add note about Python 3.10 `X | Y` operator in explanation about Response Models. PR [#5307](https://github.com/tiangolo/fastapi/pull/5307) by [@MendyLanda](https://github.com/MendyLanda).
* 📝 Add link to New Relic article: "How to monitor FastAPI application performance using Python agent". PR [#5260](https://github.com/tiangolo/fastapi/pull/5260) by [@sjyothi54](https://github.com/sjyothi54).
* 📝 Update docs for `ORJSONResponse` with details about improving performance. PR [#2615](https://github.com/tiangolo/fastapi/pull/2615) by [@falkben](https://github.com/falkben).
* 📝 Update docs for `ORJSONResponse` with details about improving performance. PR [#2615](https://github.com/tiangolo/fastapi/pull/2615) by [@falkben](https://github.com/falkben).
* 📝 Add docs for creating a custom Response class. PR [#5331](https://github.com/tiangolo/fastapi/pull/5331) by [@tiangolo](https://github.com/tiangolo).
* 📝 Add docs for creating a custom Response class. PR [#5331](https://github.com/tiangolo/fastapi/pull/5331) by [@tiangolo](https://github.com/tiangolo).
* 📝 Add tip about using alias for form data fields. PR [#5329](https://github.com/tiangolo/fastapi/pull/5329) by [@tiangolo](https://github.com/tiangolo).
* 📝 Add tip about using alias for form data fields. PR [#5329](https://github.com/tiangolo/fastapi/pull/5329) by [@tiangolo](https://github.com/tiangolo).
* 🐛 Fix support for path parameters in WebSockets. PR [#3879](https://github.com/tiangolo/fastapi/pull/3879) by [@davidbrochart](https://github.com/davidbrochart).
### Translations
* 🌐 Add Russian translation for `docs/ru/docs/features.md`. PR [#5315](https://github.com/tiangolo/fastapi/pull/5315) by [@Xewus](https://github.com/Xewus).
* 🌐 Update Chinese translation for `docs/zh/docs/tutorial/request-files.md`. PR [#4529](https://github.com/tiangolo/fastapi/pull/4529) by [@ASpathfinder](https://github.com/ASpathfinder).
* 🌐 Add Chinese translation for `docs/zh/docs/tutorial/encoder.md`. PR [#4969](https://github.com/tiangolo/fastapi/pull/4969) by [@Zssaer](https://github.com/Zssaer).
* 🌐 Fix MkDocs file line for Portuguese translation of `background-task.md`. PR [#5242](https://github.com/tiangolo/fastapi/pull/5242) by [@ComicShrimp](https://github.com/ComicShrimp).
### Internal
* 👥 Update FastAPI People. PR [#5347](https://github.com/tiangolo/fastapi/pull/5347) by [@github-actions[bot]](https://github.com/apps/github-actions).
* ⬆ Bump dawidd6/action-download-artifact from 2.22.0 to 2.23.0. PR [#5321](https://github.com/tiangolo/fastapi/pull/5321) by [@dependabot[bot]](https://github.com/apps/dependabot).
* ⬆ [pre-commit.ci] pre-commit autoupdate. PR [#5318](https://github.com/tiangolo/fastapi/pull/5318) by [@pre-commit-ci[bot]](https://github.com/apps/pre-commit-ci).
* ✏ Fix a small code highlight line error. PR [#5256](https://github.com/tiangolo/fastapi/pull/5256) by [@hjlarry](https://github.com/hjlarry).
* ♻ Internal small refactor, move `operation_id` parameter position in delete method for consistency with the code. PR [#4474](https://github.com/tiangolo/fastapi/pull/4474) by [@hiel](https://github.com/hiel).
* 🔧 Update sponsors, disable ImgWhale. PR [#5338](https://github.com/tiangolo/fastapi/pull/5338) by [@tiangolo](https://github.com/tiangolo).
@ -89,61 +89,29 @@ Se ele exibir o binário `pip` em `env/bin/pip` então funcionou. 🎉
!!! tip
!!! tip
Toda vez que você instalar um novo pacote com `pip` nesse ambiente, ative o ambiente novamente.
Toda vez que você instalar um novo pacote com `pip` nesse ambiente, ative o ambiente novamente.
Isso garante que se você usar um programa instalado por aquele pacote (como `flit`), você utilizará aquele de seu ambiente local e não outro que possa estar instalado globalmente.
Isso garante que se você usar um programa instalado por aquele pacote, você utilizará aquele de seu ambiente local e não outro que possa estar instalado globalmente.
### Flit
### pip
**FastAPI** utiliza <ahref="https://flit.readthedocs.io/en/latest/index.html"class="external-link"target="_blank">Flit</a> para construir, empacotar e publicar o projeto.
Após ativar o ambiente como descrito acima:
Após ativar o ambiente como descrito acima, instale o `flit`:
<divclass="termy">
<divclass="termy">
```console
```console
$ pip install flit
$ pip install -e .[dev,doc,test]
---> 100%
---> 100%
```
```
</div>
</div>
Ative novamente o ambiente para ter certeza que você esteja utilizando o `flit` que você acabou de instalar (e não um global).
E agora use `flit` para instalar as dependências de desenvolvimento:
=== "Linux, macOS"
<divclass="termy">
```console
$ flit install --deps develop --symlink
---> 100%
```
</div>
=== "Windows"
Se você está no Windows, use `--pth-file` ao invés de `--symlink`:
<divclass="termy">
```console
$ flit install --deps develop --pth-file
---> 100%
```
</div>
Isso irá instalar todas as dependências e seu FastAPI local em seu ambiente local.
Isso irá instalar todas as dependências e seu FastAPI local em seu ambiente local.
#### Usando seu FastAPI local
#### Usando seu FastAPI local
Se você cria um arquivo Python que importa e usa FastAPI, e roda com Python de seu ambiente local, ele irá utilizar o código fonte de seu FastAPI local.
Se você cria um arquivo Python que importa e usa FastAPI, e roda com Python de seu ambiente local, ele irá utilizar o código fonte de seu FastAPI local.
E se você atualizar o código fonte do FastAPI local, como ele é instalado com `--symlink` (ou `--pth-file` no Windows), quando você rodar aquele arquivo Python novamente, ele irá utilizar a nova versão do FastAPI que você acabou de editar.
E se você atualizar o código fonte do FastAPI local, como ele é instalado com `-e`, quando você rodar aquele arquivo Python novamente, ele irá utilizar a nova versão do FastAPI que você acabou de editar.
Desse modo, você não tem que "instalar" sua versão local para ser capaz de testar cada mudança.
Desse modo, você não tem que "instalar" sua versão local para ser capaz de testar cada mudança.
@ -161,7 +129,7 @@ $ bash scripts/format.sh
Ele irá organizar também todos os seus imports.
Ele irá organizar também todos os seus imports.
Para que ele organize os imports corretamente, você precisa ter o FastAPI instalado localmente em seu ambiente, com o comando na seção acima usando `--symlink` (ou `--pth-file` no Windows).
Para que ele organize os imports corretamente, você precisa ter o FastAPI instalado localmente em seu ambiente, com o comando na seção acima usando `-e`.
* <ahref="https://github.com/OAI/OpenAPI-Specification"class="external-link"target="_blank"><strong>OpenAPI</strong></a> для создания API, включая объявления <abbrtitle="также известных, как HTTP-методы, такие, как: POST, GET, PUT, DELETE">операций</abbr><abbrtitle="известные как: эндпоинты, маршруты, 'ручки' и т.п.">пути</abbr>, параметров, тела запроса, безопасности и т.д.
* Автоматическое документирование моделей данных в соответствии с <ahref="https://json-schema.org/"class="external-link"target="_blank"><strong>JSON Schema</strong></a> (так как спецификация OpenAPI сама основана на JSON Schema).
* Разработан, придерживаясь этих стандартов, после тщательного их изучения. Эти стандарты изначально включены во фреймфорк, а не являются дополнительной надстройкой.
* Это также позволяет использовать автоматическую **генерацию клиентского кода** на многих языках.
### Автоматически генерируемая документация
Интерактивная документация для API и исследования пользовательских веб-интерфейсов. Поскольку этот фреймворк основан на OpenAPI, существует несколько вариантов документирования, 2 из которых включены по умолчанию.
* <ahref="https://github.com/swagger-api/swagger-ui"class="external-link"target="_blank"><strong>Swagger UI</strong></a>, с интерактивным взаимодействием, вызывает и тестирует ваш API прямо из браузера.
Все эти возможности основаны на стандартных **аннотациях типов Python 3.6** (благодаря Pydantic). Не нужно изучать новый синтаксис. Только лишь стандартный современный Python.
Если вам нужно освежить знания, как использовать аннотации типов в Python (даже если вы не используете FastAPI), выделите 2 минуты и просмотрите краткое руководство: [Введение в аннотации типов Python¶
](python-types.md){.internal-link target=_blank}.
Вы пишете на стандартном Python с аннотациями типов:
```Python
from datetime import date
from pydantic import BaseModel
# Объявляем параметр user_id с типом `str`
# и получаем поддержку редактора внутри функции
def main(user_id: str):
return user_id
# Модель Pydantic
class User(BaseModel):
id: int
name: str
joined: date
```
Это можно использовать так:
```Python
my_user: User = User(id=3, name="John Doe", joined="2018-07-19")
second_user_data = {
"id": 4,
"name": "Mary",
"joined": "2018-11-30",
}
my_second_user: User = User(**second_user_data)
```
!!! Информация
`**second_user_data` означает:
Передать ключи и значения словаря `second_user_data`, в качестве аргументов типа "ключ-значение", это эквивалентно: `User(id=4, name="Mary", joined="2018-11-30")` .
### Поддержка редакторов (IDE)
Весь фреймворк был продуман так, чтобы быть простым и интуитивно понятным в использовании, все решения были проверены на множестве редакторов еще до начала разработки, чтобы обеспечить наилучшие условия при написании кода.
В опросе Python-разработчиков было выяснено, <ahref="https://www.jetbrains.com/research/python-developers-survey-2017/#tools-and-features"class="external-link"target="_blank">что наиболее часто используемой функцией редакторов, является "автодополнение"</a>.
Вся структура **FastAPI** основана на удовлетворении этой возможности. Автодополнение работает везде.
Вам редко нужно будет возвращаться к документации.
Вот как ваш редактор может вам помочь:
* в <ahref="https://code.visualstudio.com/"class="external-link"target="_blank">Visual Studio Code</a>:
Вы будете получать автодополнение кода даже там, где вы считали это невозможным раньше.
Как пример, ключ `price` внутри тела JSON (который может быть вложенным), приходящего в запросе.
Больше никаких неправильных имён ключей, метания по документации или прокручивания кода вверх и вниз, в попытках узнать - использовали вы ранее `username` или `user_name`.
### Краткость
FastAPI имеет продуманные значения **по умолчанию** для всего, с произвольными настройками везде. Все параметры могут быть тонко подстроены так, чтобы делать то, что вам нужно и определять необходимый вам API.
Но, по умолчанию, всё это **"и так работает"**.
### Проверка значений
* Проверка значений для большинства (или всех?) **типов данных** Python, включая:
* Объекты JSON (`dict`).
* Массивы JSON (`list`) с установленными типами элементов.
* Строковые (`str`) поля с ограничением минимальной и максимальной длины.
* Числа (`int`, `float`) с минимальными и максимальными значениями и т.п.
* Проверка для более экзотических типов, таких как:
* URL.
* Email.
* UUID.
* ...и другие.
Все проверки обрабатываются хорошо зарекомендовавшим себя и надежным **Pydantic**.
### Безопасность и аутентификация
Встроеные функции безопасности и аутентификации. Без каких-либо компромиссов с базами данных или моделями данных.
Все схемы безопасности, определённые в OpenAPI, включая:
* HTTP Basic.
* **OAuth2** (также с **токенами JWT**). Ознакомьтесь с руководством [OAuth2 с JWT](tutorial/security/oauth2-jwt.md){.internal-link target=_blank}.
* Ключи API в:
* Заголовках.
* Параметрах запросов.
* Cookies и т.п.
Вдобавок все функции безопасности от Starlette (включая **сессионные cookies**).
Все инструменты и компоненты спроектированы для многократного использования и легко интегрируются с вашими системами, хранилищами данных, реляционными и NoSQL базами данных и т. д.
### Внедрение зависимостей
FastAPI включает в себя чрезвычайно простую в использовании, но чрезвычайно мощную систему <abbrtitle='известную как: "components", "resources", "services", "providers"'><strong>Внедрения зависимостей</strong></abbr>.
* Даже зависимости могут иметь зависимости, создавая иерархию или **"графы" зависимостей**.
* Всё **автоматически обрабатывается** фреймворком.
* Все зависимости могут запрашивать данные из запросов и **дополнять операции пути** ограничениями и автоматической документацией.
* **Автоматическая проверка** даже для параметров *операций пути*, определенных в зависимостях.
* Поддержка сложных систем аутентификации пользователей, **соединений с базами данных** и т.д.
* **Никаких компромиссов** с базами данных, интерфейсами и т.д. Но легкая интеграция со всеми ними.
### Нет ограничений на "Плагины"
Или, другими словами, нет сложностей с ними, импортируйте и используйте нужный вам код.
Любая интеграция разработана настолько простой в использовании (с зависимостями), что вы можете создать "плагин" для своего приложения в пару строк кода, используя ту же структуру и синтаксис, что и для ваших *операций пути*.
### Проверен
* 100% <abbrtitle="Количество автоматически проверямого кода">покрытие тестами</abbr>.
* 100% <abbrtitle="Аннотации типов Python, благодаря которым ваш редактор и другие инструменты могут обеспечить вам лучшую поддержку">аннотирование типов</abbr> в кодовой базе.
* Используется в реально работающих приложениях.
## Основные свойства Starlette
**FastAPI** основан на <ahref="https://www.starlette.io/"class="external-link"target="_blank"><strong>Starlette</strong></a> и полностью совместим с ним. Так что, любой дополнительный код Starlette, который у вас есть, будет также работать.
На самом деле, `FastAPI` - это класс, унаследованный от `Starlette`. Таким образом, если вы уже знаете или используете Starlette, большая часть функционала будет работать так же.
С **FastAPI** вы получаете все возможности **Starlette** (так как FastAPI это всего лишь Starlette на стероидах):
* Серьёзно впечатляющая производительность. Это <ahref="https://github.com/encode/starlette#performance"class="external-link"target="_blank">один из самых быстрых фреймворков на Python</a>, наравне с приложениями использующими **NodeJS** или **Go**.
* Поддержка **WebSocket**.
* Фоновые задачи для процессов.
* События запуска и выключения.
* Тестовый клиент построен на библиотеке `requests`.
**FastAPI** основан на <ahref="https://pydantic-docs.helpmanual.io"class="external-link"target="_blank"><strong>Pydantic</strong></a> и полностью совместим с ним. Так что, любой дополнительный код Pydantic, который у вас есть, будет также работать.
Включая внешние библиотеки, также основанные на Pydantic, такие как: <abbrtitle="Object-Relational Mapper">ORM'ы</abbr>, <abbrtitle="Object-Document Mapper">ODM'ы</abbr> для баз данных.
Это также означает, что во многих случаях вы можете передавать тот же объект, который получили из запроса, **непосредственно в базу данных**, так как всё проверяется автоматически.
И наоборот, во многих случаях вы можете просто передать объект, полученный из базы данных, **непосредственно клиенту**.
С **FastAPI** вы получаете все возможности **Pydantic** (так как, FastAPI основан на Pydantic, для обработки данных):
* **Никакой нервотрёпки** :
* Не нужно изучать новых схем в микроязыках.
* Если вы знаете аннотации типов в Python, вы знаете, как использовать Pydantic.
* Прекрасно сочетается с вашими **<abbrtitle="Интегрированное окружение для разработки, похожее на текстовый редактор">IDE</abbr>/<abbrtitle="программа проверяющая ошибки в коде">linter</abbr>/мозгом**:
* Потому что структуры данных pydantic - это всего лишь экземпляры классов, определённых вами. Автодополнение, проверка кода, mypy и ваша интуиция - всё будет работать с вашими проверенными данными.
* **Быстродействие**:
* В <ahref="https://pydantic-docs.helpmanual.io/benchmarks/"class="external-link"target="_blank">тестовых замерах</a> Pydantic быстрее, чем все другие проверенные библиотеки.
* Проверка **сложных структур**:
* Использование иерархических моделей Pydantic; `List`, `Dict` и т.п. из модуля `typing` (входит в стандартную библиотеку Python).
* Валидаторы позволяют четко и легко определять, проверять и документировать сложные схемы данных в виде JSON Schema.
* У вас могут быть глубоко **вложенные объекты JSON** и все они будут проверены и аннотированы.
* **Расширяемость**:
* Pydantic позволяет определять пользовательские типы данных или расширять проверку методами модели, с помощью проверочных декораторов.
# TODO: needed by asyncio in Python 3.9.7 https://bugs.python.org/issue45097, try to remove on 3.9.8
# TODO: needed by asyncio in Python 3.9.7 https://bugs.python.org/issue45097, try to remove on 3.9.8
'ignore:The loop argument is deprecated since Python 3\.8, and scheduled for removal in Python 3\.10:DeprecationWarning:asyncio',
'ignore:The loop argument is deprecated since Python 3\.8, and scheduled for removal in Python 3\.10:DeprecationWarning:asyncio',
'ignore:starlette.middleware.wsgi is deprecated and will be removed in a future release\..*:DeprecationWarning:starlette',
'ignore:starlette.middleware.wsgi is deprecated and will be removed in a future release\..*:DeprecationWarning:starlette',
# TODO: remove after dropping support for Python 3.6
# see https://trio.readthedocs.io/en/stable/history.html#trio-0-22-0-2022-09-28
'ignore:Python 3.6 is no longer supported by the Python core team. Therefore, support for it is deprecated in cryptography and will be removed in a future release.:UserWarning:jose',