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 fastapi import FastAPI
153from typing import Optional
154
155app = FastAPI()
156
157
158@app.get("/")
159def read_root():
160    return {"Hello": "World"}
161
162
163@app.get("/items/{item_id}")
164def read_item(item_id: int, q: str = Optional[None]):
165    return {"item_id": item_id, "q": q}
166```
167
168<details markdown="1">
169<summary>Or use <code>async def</code>...</summary>
170
171If your code uses `async` / `await`, use `async def`:
172
173```Python hl_lines="7  12"
174from fastapi import FastAPI
175from typing import Optional
176
177app = FastAPI()
178
179
180@app.get("/")
181async def read_root():
182    return {"Hello": "World"}
183
184
185@app.get("/items/{item_id}")
186async def read_item(item_id: int, q: Optional[str] = None):
187    return {"item_id": item_id, "q": q}
188```
189
190**Note**:
191
192If 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>.
193
194</details>
195
196### Run it
197
198Run the server with:
199
200<div class="termy">
201
202```console
203$ uvicorn main:app --reload
204
205INFO:     Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit)
206INFO:     Started reloader process [28720]
207INFO:     Started server process [28722]
208INFO:     Waiting for application startup.
209INFO:     Application startup complete.
210```
211
212</div>
213
214<details markdown="1">
215<summary>About the command <code>uvicorn main:app --reload</code>...</summary>
216
217The command `uvicorn main:app` refers to:
218
219* `main`: the file `main.py` (the Python "module").
220* `app`: the object created inside of `main.py` with the line `app = FastAPI()`.
221* `--reload`: make the server restart after code changes. Only do this for development.
222
223</details>
224
225### Check it
226
227Open 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>.
228
229You will see the JSON response as:
230
231```JSON
232{"item_id": 5, "q": "somequery"}
233```
234
235You already created an API that:
236
237* Receives HTTP requests in the _paths_ `/` and `/items/{item_id}`.
238* Both _paths_ take `GET` <em>operations</em> (also known as HTTP _methods_).
239* The _path_ `/items/{item_id}` has a _path parameter_ `item_id` that should be an `int`.
240* The _path_ `/items/{item_id}` has an optional `str` _query parameter_ `q`.
241
242### Interactive API docs
243
244Now go to <a href="http://127.0.0.1:8000/docs" class="external-link" target="_blank">http://127.0.0.1:8000/docs</a>.
245
246You 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>):
247
248![Swagger UI](https://fastapi.tiangolo.com/img/index/index-01-swagger-ui-simple.png)
249
250### Alternative API docs
251
252And 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>.
253
254You will see the alternative automatic documentation (provided by <a href="https://github.com/Rebilly/ReDoc" class="external-link" target="_blank">ReDoc</a>):
255
256![ReDoc](https://fastapi.tiangolo.com/img/index/index-02-redoc-simple.png)
257
258## Example upgrade
259
260Now modify the file `main.py` to receive a body from a `PUT` request.
261
262Declare the body using standard Python types, thanks to Pydantic.
263
264```Python hl_lines="2  7-10  23-25"
265from fastapi import FastAPI
266from pydantic import BaseModel
267from typing import Optional
268
269app = FastAPI()
270
271
272class Item(BaseModel):
273    name: str
274    price: float
275    is_offer: bool = Optional[None]
276
277
278@app.get("/")
279def read_root():
280    return {"Hello": "World"}
281
282
283@app.get("/items/{item_id}")
284def read_item(item_id: int, q: Optional[str] = None):
285    return {"item_id": item_id, "q": q}
286
287
288@app.put("/items/{item_id}")
289def update_item(item_id: int, item: Item):
290    return {"item_name": item.name, "item_id": item_id}
291```
292
293The server should reload automatically (because you added `--reload` to the `uvicorn` command above).
294
295### Interactive API docs upgrade
296
297Now go to <a href="http://127.0.0.1:8000/docs" class="external-link" target="_blank">http://127.0.0.1:8000/docs</a>.
298
299* The interactive API documentation will be automatically updated, including the new body:
300
301![Swagger UI](https://fastapi.tiangolo.com/img/index/index-03-swagger-02.png)
302
303* Click on the button "Try it out", it allows you to fill the parameters and directly interact with the API:
304
305![Swagger UI interaction](https://fastapi.tiangolo.com/img/index/index-04-swagger-03.png)
306
307* 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:
308
309![Swagger UI interaction](https://fastapi.tiangolo.com/img/index/index-05-swagger-04.png)
310
311### Alternative API docs upgrade
312
313And 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>.
314
315* The alternative documentation will also reflect the new query parameter and body:
316
317![ReDoc](https://fastapi.tiangolo.com/img/index/index-06-redoc-02.png)
318
319### Recap
320
321In summary, you declare **once** the types of parameters, body, etc. as function parameters.
322
323You do that with standard modern Python types.
324
325You don't have to learn a new syntax, the methods or classes of a specific library, etc.
326
327Just standard **Python 3.6+**.
328
329For example, for an `int`:
330
331```Python
332item_id: int
333```
334
335or for a more complex `Item` model:
336
337```Python
338item: Item
339```
340
341...and with that single declaration you get:
342
343* Editor support, including:
344    * Completion.
345    * Type checks.
346* Validation of data:
347    * Automatic and clear errors when the data is invalid.
348    * Validation even for deeply nested JSON objects.
349* <abbr title="also known as: serialization, parsing, marshalling">Conversion</abbr> of input data: coming from the network to Python data and types. Reading from:
350    * JSON.
351    * Path parameters.
352    * Query parameters.
353    * Cookies.
354    * Headers.
355    * Forms.
356    * Files.
357* <abbr title="also known as: serialization, parsing, marshalling">Conversion</abbr> of output data: converting from Python data and types to network data (as JSON):
358    * Convert Python types (`str`, `int`, `float`, `bool`, `list`, etc).
359    * `datetime` objects.
360    * `UUID` objects.
361    * Database models.
362    * ...and many more.
363* Automatic interactive API documentation, including 2 alternative user interfaces:
364    * Swagger UI.
365    * ReDoc.
366
367---
368
369Coming back to the previous code example, **FastAPI** will:
370
371* Validate that there is an `item_id` in the path for `GET` and `PUT` requests.
372* Validate that the `item_id` is of type `int` for `GET` and `PUT` requests.
373    * If it is not, the client will see a useful, clear error.
374* 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.
375    * As the `q` parameter is declared with `= None`, it is optional.
376    * Without the `None` it would be required (as is the body in the case with `PUT`).
377* For `PUT` requests to `/items/{item_id}`, Read the body as JSON:
378    * Check that it has a required attribute `name` that should be a `str`.
379    * Check that it has a required attribute `price` that has to be a `float`.
380    * Check that it has an optional attribute `is_offer`, that should be a `bool`, if present.
381    * All this would also work for deeply nested JSON objects.
382* Convert from and to JSON automatically.
383* Document everything with OpenAPI, that can be used by:
384    * Interactive documentation systems.
385    * Automatic client code generation systems, for many languages.
386* Provide 2 interactive documentation web interfaces directly.
387
388---
389
390We just scratched the surface, but you already get the idea of how it all works.
391
392Try changing the line with:
393
394```Python
395    return {"item_name": item.name, "item_id": item_id}
396```
397
398...from:
399
400```Python
401        ... "item_name": item.name ...
402```
403
404...to:
405
406```Python
407        ... "item_price": item.price ...
408```
409
410...and see how your editor will auto-complete the attributes and know their types:
411
412![editor support](https://fastapi.tiangolo.com/img/vscode-completion.png)
413
414For a more complete example including more features, see the <a href="https://fastapi.tiangolo.com/tutorial/">Tutorial - User Guide</a>.
415
416**Spoiler alert**: the tutorial - user guide includes:
417
418* Declaration of **parameters** from other different places as: **headers**, **cookies**, **form fields** and **files**.
419* How to set **validation constraints** as `maximum_length` or `regex`.
420* A very powerful and easy to use **<abbr title="also known as components, resources, providers, services, injectables">Dependency Injection</abbr>** system.
421* Security and authentication, including support for **OAuth2** with **JWT tokens** and **HTTP Basic** auth.
422* More advanced (but equally easy) techniques for declaring **deeply nested JSON models** (thanks to Pydantic).
423* Many extra features (thanks to Starlette) as:
424    * **WebSockets**
425    * **GraphQL**
426    * extremely easy tests based on `requests` and `pytest`
427    * **CORS**
428    * **Cookie Sessions**
429    * ...and more.
430
431## Performance
432
433Independent 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). (*)
434
435To understand more about it, see the section <a href="https://fastapi.tiangolo.com/benchmarks/" class="internal-link" target="_blank">Benchmarks</a>.
436
437## Optional Dependencies
438
439Used by Pydantic:
440
441* <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>.
442* <a href="https://github.com/JoshData/python-email-validator" target="_blank"><code>email_validator</code></a> - for email validation.
443
444Used by Starlette:
445
446* <a href="https://requests.readthedocs.io" target="_blank"><code>requests</code></a> - Required if you want to use the `TestClient`.
447* <a href="https://github.com/Tinche/aiofiles" target="_blank"><code>aiofiles</code></a> - Required if you want to use `FileResponse` or `StaticFiles`.
448* <a href="https://jinja.palletsprojects.com" target="_blank"><code>jinja2</code></a> - Required if you want to use the default template configuration.
449* <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()`.
450* <a href="https://pythonhosted.org/itsdangerous/" target="_blank"><code>itsdangerous</code></a> - Required for `SessionMiddleware` support.
451* <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).
452* <a href="https://graphene-python.org/" target="_blank"><code>graphene</code></a> - Required for `GraphQLApp` support.
453* <a href="https://github.com/esnme/ultrajson" target="_blank"><code>ujson</code></a> - Required if you want to use `UJSONResponse`.
454
455Used by FastAPI / Starlette:
456
457* <a href="https://www.uvicorn.org" target="_blank"><code>uvicorn</code></a> - for the server that loads and serves your application.
458* <a href="https://github.com/ijl/orjson" target="_blank"><code>orjson</code></a> - Required if you want to use `ORJSONResponse`.
459
460You can install all of these with `pip install fastapi[all]`.
461
462## License
463
464This project is licensed under the terms of the MIT license.
465