1 2{!../../../docs/missing-translation.md!} 3 4 5<p align="center"> 6 <a href="https://fastapi.tiangolo.com"><img src="https://fastapi.tiangolo.com/img/logo-margin/logo-teal.png" alt="FastAPI"></a> 7</p> 8<p align="center"> 9 <em>FastAPI framework, high performance, easy to learn, fast to code, ready for production</em> 10</p> 11<p align="center"> 12<a href="https://travis-ci.com/tiangolo/fastapi" target="_blank"> 13 <img src="https://travis-ci.com/tiangolo/fastapi.svg?branch=master" alt="Build Status"> 14</a> 15<a href="https://codecov.io/gh/tiangolo/fastapi" target="_blank"> 16 <img src="https://img.shields.io/codecov/c/github/tiangolo/fastapi" alt="Coverage"> 17</a> 18<a href="https://pypi.org/project/fastapi" target="_blank"> 19 <img src="https://badge.fury.io/py/fastapi.svg" alt="Package version"> 20</a> 21</p> 22 23--- 24 25**Documentation**: <a href="https://fastapi.tiangolo.com" target="_blank">https://fastapi.tiangolo.com</a> 26 27**Source Code**: <a href="https://github.com/tiangolo/fastapi" target="_blank">https://github.com/tiangolo/fastapi</a> 28 29--- 30 31FastAPI is a modern, fast (high-performance), web framework for building APIs with Python 3.6+ based on standard Python type hints. 32 33The key features are: 34 35* **Fast**: Very high performance, on par with **NodeJS** and **Go** (thanks to Starlette and Pydantic). [One of the fastest Python frameworks available](#performance). 36 37* **Fast to code**: Increase the speed to develop features by about 200% to 300%. * 38* **Fewer bugs**: Reduce about 40% of human (developer) induced errors. * 39* **Intuitive**: Great editor support. <abbr title="also known as auto-complete, autocompletion, IntelliSense">Completion</abbr> everywhere. Less time debugging. 40* **Easy**: Designed to be easy to use and learn. Less time reading docs. 41* **Short**: Minimize code duplication. Multiple features from each parameter declaration. Fewer bugs. 42* **Robust**: Get production-ready code. With automatic interactive documentation. 43* **Standards-based**: Based on (and fully compatible with) the open standards for APIs: <a href="https://github.com/OAI/OpenAPI-Specification" class="external-link" target="_blank">OpenAPI</a> (previously known as Swagger) and <a href="https://json-schema.org/" class="external-link" target="_blank">JSON Schema</a>. 44 45<small>* estimation based on tests on an internal development team, building production applications.</small> 46 47## Sponsors 48 49<!-- sponsors --> 50 51{% if sponsors %} 52{% for sponsor in sponsors.gold -%} 53<a href="{{ sponsor.url }}" target="_blank" title="{{ sponsor.title }}"><img src="{{ sponsor.img }}" style="border-radius:15px"></a> 54{% endfor -%} 55{%- for sponsor in sponsors.silver -%} 56<a href="{{ sponsor.url }}" target="_blank" title="{{ sponsor.title }}"><img src="{{ sponsor.img }}" style="border-radius:15px"></a> 57{% endfor %} 58{% endif %} 59 60<!-- /sponsors --> 61 62<a href="https://fastapi.tiangolo.com/fastapi-people/#sponsors" class="external-link" target="_blank">Other sponsors</a> 63 64## Opinions 65 66"_[...] 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._" 67 68<div style="text-align: right; margin-right: 10%;">Kabir Khan - <strong>Microsoft</strong> <a href="https://github.com/tiangolo/fastapi/pull/26" target="_blank"><small>(ref)</small></a></div> 69 70--- 71 72"_We adopted the **FastAPI** library to spawn a **REST** server that can be queried to obtain **predictions**. [for Ludwig]_" 73 74<div style="text-align: right; margin-right: 10%;">Piero Molino, Yaroslav Dudin, and Sai Sumanth Miryala - <strong>Uber</strong> <a href="https://eng.uber.com/ludwig-v0-2/" target="_blank"><small>(ref)</small></a></div> 75 76--- 77 78"_**Netflix** is pleased to announce the open-source release of our **crisis management** orchestration framework: **Dispatch**! [built with **FastAPI**]_" 79 80<div style="text-align: right; margin-right: 10%;">Kevin Glisson, Marc Vilanova, Forest Monsen - <strong>Netflix</strong> <a href="https://netflixtechblog.com/introducing-dispatch-da4b8a2a8072" target="_blank"><small>(ref)</small></a></div> 81 82--- 83 84"_I’m over the moon excited about **FastAPI**. It’s so fun!_" 85 86<div style="text-align: right; margin-right: 10%;">Brian Okken - <strong><a href="https://pythonbytes.fm/episodes/show/123/time-to-right-the-py-wrongs?time_in_sec=855" target="_blank">Python Bytes</a> podcast host</strong> <a href="https://twitter.com/brianokken/status/1112220079972728832" target="_blank"><small>(ref)</small></a></div> 87 88--- 89 90"_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._" 91 92<div style="text-align: right; margin-right: 10%;">Timothy Crosley - <strong><a href="https://www.hug.rest/" target="_blank">Hug</a> creator</strong> <a href="https://news.ycombinator.com/item?id=19455465" target="_blank"><small>(ref)</small></a></div> 93 94--- 95 96"_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 [...]_" 97 98"_We've switched over to **FastAPI** for our **APIs** [...] I think you'll like it [...]_" 99 100<div style="text-align: right; margin-right: 10%;">Ines Montani - Matthew Honnibal - <strong><a href="https://explosion.ai" target="_blank">Explosion AI</a> founders - <a href="https://spacy.io" target="_blank">spaCy</a> creators</strong> <a href="https://twitter.com/_inesmontani/status/1144173225322143744" target="_blank"><small>(ref)</small></a> - <a href="https://twitter.com/honnibal/status/1144031421859655680" target="_blank"><small>(ref)</small></a></div> 101 102--- 103 104## **Typer**, the FastAPI of CLIs 105 106<a href="https://typer.tiangolo.com" target="_blank"><img src="https://typer.tiangolo.com/img/logo-margin/logo-margin-vector.svg" style="width: 20%;"></a> 107 108If you are building a <abbr title="Command Line Interface">CLI</abbr> app to be used in the terminal instead of a web API, check out <a href="https://typer.tiangolo.com/" class="external-link" target="_blank">**Typer**</a>. 109 110**Typer** is FastAPI's little sibling. And it's intended to be the **FastAPI of CLIs**. ⌨️ 111 112## Requirements 113 114Python 3.6+ 115 116FastAPI stands on the shoulders of giants: 117 118* <a href="https://www.starlette.io/" class="external-link" target="_blank">Starlette</a> for the web parts. 119* <a href="https://pydantic-docs.helpmanual.io/" class="external-link" target="_blank">Pydantic</a> for the data parts. 120 121## Installation 122 123<div class="termy"> 124 125```console 126$ pip install fastapi 127 128---> 100% 129``` 130 131</div> 132 133You will also need an ASGI server, for production such as <a href="https://www.uvicorn.org" class="external-link" target="_blank">Uvicorn</a> or <a href="https://gitlab.com/pgjones/hypercorn" class="external-link" target="_blank">Hypercorn</a>. 134 135<div class="termy"> 136 137```console 138$ pip install uvicorn[standard] 139 140---> 100% 141``` 142 143</div> 144 145## Example 146 147### Create it 148 149* Create a file `main.py` with: 150 151```Python 152from typing import Optional 153 154from fastapi import FastAPI 155 156app = FastAPI() 157 158 159@app.get("/") 160def read_root(): 161 return {"Hello": "World"} 162 163 164@app.get("/items/{item_id}") 165def read_item(item_id: int, q: Optional[str] = None): 166 return {"item_id": item_id, "q": q} 167``` 168 169<details markdown="1"> 170<summary>Or use <code>async def</code>...</summary> 171 172If your code uses `async` / `await`, use `async def`: 173 174```Python hl_lines="9 14" 175from typing import Optional 176 177from fastapi import FastAPI 178 179app = FastAPI() 180 181 182@app.get("/") 183async def read_root(): 184 return {"Hello": "World"} 185 186 187@app.get("/items/{item_id}") 188async def read_item(item_id: int, q: Optional[str] = None): 189 return {"item_id": item_id, "q": q} 190``` 191 192**Note**: 193 194If you don't know, check the _"In a hurry?"_ section about <a href="https://fastapi.tiangolo.com/async/#in-a-hurry" target="_blank">`async` and `await` in the docs</a>. 195 196</details> 197 198### Run it 199 200Run the server with: 201 202<div class="termy"> 203 204```console 205$ uvicorn main:app --reload 206 207INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit) 208INFO: Started reloader process [28720] 209INFO: Started server process [28722] 210INFO: Waiting for application startup. 211INFO: Application startup complete. 212``` 213 214</div> 215 216<details markdown="1"> 217<summary>About the command <code>uvicorn main:app --reload</code>...</summary> 218 219The command `uvicorn main:app` refers to: 220 221* `main`: the file `main.py` (the Python "module"). 222* `app`: the object created inside of `main.py` with the line `app = FastAPI()`. 223* `--reload`: make the server restart after code changes. Only do this for development. 224 225</details> 226 227### Check it 228 229Open your browser at <a href="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>. 230 231You will see the JSON response as: 232 233```JSON 234{"item_id": 5, "q": "somequery"} 235``` 236 237You already created an API that: 238 239* Receives HTTP requests in the _paths_ `/` and `/items/{item_id}`. 240* Both _paths_ take `GET` <em>operations</em> (also known as HTTP _methods_). 241* The _path_ `/items/{item_id}` has a _path parameter_ `item_id` that should be an `int`. 242* The _path_ `/items/{item_id}` has an optional `str` _query parameter_ `q`. 243 244### Interactive API docs 245 246Now go to <a href="http://127.0.0.1:8000/docs" class="external-link" target="_blank">http://127.0.0.1:8000/docs</a>. 247 248You will see the automatic interactive API documentation (provided by <a href="https://github.com/swagger-api/swagger-ui" class="external-link" target="_blank">Swagger UI</a>): 249 250![Swagger UI](https://fastapi.tiangolo.com/img/index/index-01-swagger-ui-simple.png) 251 252### Alternative API docs 253 254And now, go to <a href="http://127.0.0.1:8000/redoc" class="external-link" target="_blank">http://127.0.0.1:8000/redoc</a>. 255 256You will see the alternative automatic documentation (provided by <a href="https://github.com/Rebilly/ReDoc" class="external-link" target="_blank">ReDoc</a>): 257 258![ReDoc](https://fastapi.tiangolo.com/img/index/index-02-redoc-simple.png) 259 260## Example upgrade 261 262Now modify the file `main.py` to receive a body from a `PUT` request. 263 264Declare the body using standard Python types, thanks to Pydantic. 265 266```Python hl_lines="4 9-12 25-27" 267from typing import Optional 268 269from fastapi import FastAPI 270from pydantic import BaseModel 271 272app = FastAPI() 273 274 275class Item(BaseModel): 276 name: str 277 price: float 278 is_offer: Optional[bool] = None 279 280 281@app.get("/") 282def read_root(): 283 return {"Hello": "World"} 284 285 286@app.get("/items/{item_id}") 287def read_item(item_id: int, q: Optional[str] = None): 288 return {"item_id": item_id, "q": q} 289 290 291@app.put("/items/{item_id}") 292def update_item(item_id: int, item: Item): 293 return {"item_name": item.name, "item_id": item_id} 294``` 295 296The server should reload automatically (because you added `--reload` to the `uvicorn` command above). 297 298### Interactive API docs upgrade 299 300Now go to <a href="http://127.0.0.1:8000/docs" class="external-link" target="_blank">http://127.0.0.1:8000/docs</a>. 301 302* The interactive API documentation will be automatically updated, including the new body: 303 304![Swagger UI](https://fastapi.tiangolo.com/img/index/index-03-swagger-02.png) 305 306* Click on the button "Try it out", it allows you to fill the parameters and directly interact with the API: 307 308![Swagger UI interaction](https://fastapi.tiangolo.com/img/index/index-04-swagger-03.png) 309 310* 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: 311 312![Swagger UI interaction](https://fastapi.tiangolo.com/img/index/index-05-swagger-04.png) 313 314### Alternative API docs upgrade 315 316And now, go to <a href="http://127.0.0.1:8000/redoc" class="external-link" target="_blank">http://127.0.0.1:8000/redoc</a>. 317 318* The alternative documentation will also reflect the new query parameter and body: 319 320![ReDoc](https://fastapi.tiangolo.com/img/index/index-06-redoc-02.png) 321 322### Recap 323 324In summary, you declare **once** the types of parameters, body, etc. as function parameters. 325 326You do that with standard modern Python types. 327 328You don't have to learn a new syntax, the methods or classes of a specific library, etc. 329 330Just standard **Python 3.6+**. 331 332For example, for an `int`: 333 334```Python 335item_id: int 336``` 337 338or for a more complex `Item` model: 339 340```Python 341item: Item 342``` 343 344...and with that single declaration you get: 345 346* Editor support, including: 347 * Completion. 348 * Type checks. 349* Validation of data: 350 * Automatic and clear errors when the data is invalid. 351 * Validation even for deeply nested JSON objects. 352* <abbr title="also known as: serialization, parsing, marshalling">Conversion</abbr> of input data: coming from the network to Python data and types. Reading from: 353 * JSON. 354 * Path parameters. 355 * Query parameters. 356 * Cookies. 357 * Headers. 358 * Forms. 359 * Files. 360* <abbr title="also known as: serialization, parsing, marshalling">Conversion</abbr> of output data: converting from Python data and types to network data (as JSON): 361 * Convert Python types (`str`, `int`, `float`, `bool`, `list`, etc). 362 * `datetime` objects. 363 * `UUID` objects. 364 * Database models. 365 * ...and many more. 366* Automatic interactive API documentation, including 2 alternative user interfaces: 367 * Swagger UI. 368 * ReDoc. 369 370--- 371 372Coming back to the previous code example, **FastAPI** will: 373 374* Validate that there is an `item_id` in the path for `GET` and `PUT` requests. 375* Validate that the `item_id` is of type `int` for `GET` and `PUT` requests. 376 * If it is not, the client will see a useful, clear error. 377* Check if there is an optional query parameter named `q` (as in `http://127.0.0.1:8000/items/foo?q=somequery`) for `GET` requests. 378 * As the `q` parameter is declared with `= None`, it is optional. 379 * Without the `None` it would be required (as is the body in the case with `PUT`). 380* For `PUT` requests to `/items/{item_id}`, Read the body as JSON: 381 * Check that it has a required attribute `name` that should be a `str`. 382 * Check that it has a required attribute `price` that has to be a `float`. 383 * Check that it has an optional attribute `is_offer`, that should be a `bool`, if present. 384 * All this would also work for deeply nested JSON objects. 385* Convert from and to JSON automatically. 386* Document everything with OpenAPI, that can be used by: 387 * Interactive documentation systems. 388 * Automatic client code generation systems, for many languages. 389* Provide 2 interactive documentation web interfaces directly. 390 391--- 392 393We just scratched the surface, but you already get the idea of how it all works. 394 395Try changing the line with: 396 397```Python 398 return {"item_name": item.name, "item_id": item_id} 399``` 400 401...from: 402 403```Python 404 ... "item_name": item.name ... 405``` 406 407...to: 408 409```Python 410 ... "item_price": item.price ... 411``` 412 413...and see how your editor will auto-complete the attributes and know their types: 414 415![editor support](https://fastapi.tiangolo.com/img/vscode-completion.png) 416 417For a more complete example including more features, see the <a href="https://fastapi.tiangolo.com/tutorial/">Tutorial - User Guide</a>. 418 419**Spoiler alert**: the tutorial - user guide includes: 420 421* Declaration of **parameters** from other different places as: **headers**, **cookies**, **form fields** and **files**. 422* How to set **validation constraints** as `maximum_length` or `regex`. 423* A very powerful and easy to use **<abbr title="also known as components, resources, providers, services, injectables">Dependency Injection</abbr>** system. 424* Security and authentication, including support for **OAuth2** with **JWT tokens** and **HTTP Basic** auth. 425* More advanced (but equally easy) techniques for declaring **deeply nested JSON models** (thanks to Pydantic). 426* Many extra features (thanks to Starlette) as: 427 * **WebSockets** 428 * **GraphQL** 429 * extremely easy tests based on `requests` and `pytest` 430 * **CORS** 431 * **Cookie Sessions** 432 * ...and more. 433 434## Performance 435 436Independent TechEmpower benchmarks show **FastAPI** applications running under Uvicorn as <a href="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). (*) 437 438To understand more about it, see the section <a href="https://fastapi.tiangolo.com/benchmarks/" class="internal-link" target="_blank">Benchmarks</a>. 439 440## Optional Dependencies 441 442Used by Pydantic: 443 444* <a href="https://github.com/esnme/ultrajson" target="_blank"><code>ujson</code></a> - for faster JSON <abbr title="converting the string that comes from an HTTP request into Python data">"parsing"</abbr>. 445* <a href="https://github.com/JoshData/python-email-validator" target="_blank"><code>email_validator</code></a> - for email validation. 446 447Used by Starlette: 448 449* <a href="https://requests.readthedocs.io" target="_blank"><code>requests</code></a> - Required if you want to use the `TestClient`. 450* <a href="https://github.com/Tinche/aiofiles" target="_blank"><code>aiofiles</code></a> - Required if you want to use `FileResponse` or `StaticFiles`. 451* <a href="https://jinja.palletsprojects.com" target="_blank"><code>jinja2</code></a> - Required if you want to use the default template configuration. 452* <a href="https://andrew-d.github.io/python-multipart/" target="_blank"><code>python-multipart</code></a> - Required if you want to support form <abbr title="converting the string that comes from an HTTP request into Python data">"parsing"</abbr>, with `request.form()`. 453* <a href="https://pythonhosted.org/itsdangerous/" target="_blank"><code>itsdangerous</code></a> - Required for `SessionMiddleware` support. 454* <a href="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). 455* <a href="https://graphene-python.org/" target="_blank"><code>graphene</code></a> - Required for `GraphQLApp` support. 456* <a href="https://github.com/esnme/ultrajson" target="_blank"><code>ujson</code></a> - Required if you want to use `UJSONResponse`. 457 458Used by FastAPI / Starlette: 459 460* <a href="https://www.uvicorn.org" target="_blank"><code>uvicorn</code></a> - for the server that loads and serves your application. 461* <a href="https://github.com/ijl/orjson" target="_blank"><code>orjson</code></a> - Required if you want to use `ORJSONResponse`. 462 463You can install all of these with `pip install fastapi[all]`. 464 465## License 466 467This project is licensed under the terms of the MIT license. 468