Compare commits

...

329 Commits

Author SHA1 Message Date
Sebastián Ramírez
7b2993682f 🔖 Release 0.21.0 2019-05-15 14:54:46 +04:00
Sebastián Ramírez
73fad03b46 📝 Update release notes 2019-05-15 14:53:43 +04:00
Ricardo Momm
b0b88f9d5b 🔊 Raise from previous exception (#195) 2019-05-15 14:50:58 +04:00
Sebastián Ramírez
49d33f9f70 📝 Update release notes 2019-05-15 14:45:04 +04:00
Sebastián Ramírez
1f27981045 📝 Update release notes 2019-05-15 14:44:00 +04:00
euri10
f541d2c200 Use a logger instead of the root logging (#222) 2019-05-15 14:43:31 +04:00
euri10
0e99b23ebc ⬆️ Upgrade Pydantic to version 0.25 (#225) 2019-05-15 14:19:51 +04:00
Sebastián Ramírez
de341abe66 📝 Update release notes 2019-05-14 22:06:55 +04:00
Derek J. Lambert
4a1648b04e ✏️ Minor spelling fix in routing (#221) 2019-05-14 22:04:18 +04:00
Sebastián Ramírez
5f13b53ea5 🔧 Enable FastAPI releases bot in main Gitter channel 2019-05-11 19:44:39 +04:00
Sebastián Ramírez
5189c93d85 🔖 Release 0.20.1 2019-05-11 19:38:08 +04:00
Sebastián Ramírez
e612989313 📝 Update release notes 2019-05-11 13:46:17 +04:00
Steve B
d675991a34 add py.typed to ship typing information (#209)
As described in https://www.python.org/dev/peps/pep-0561/
2019-05-11 13:43:47 +04:00
Sebastián Ramírez
d03678dfbb 📝 Update release notes 2019-04-27 20:03:23 +04:00
Sebastián Ramírez
6ff89284c5 Add FastAPI releases bot for Gitter (#189)
* 🔥 Remove development util script

* 🎨 Reformat release notes with markdown-only code (no HTML)

*  Add FastAPI releases bot for Gitter
2019-04-27 20:02:32 +04:00
Sebastián Ramírez
7f673cf4e9 🔖 Release 0.20.0 2019-04-27 17:51:31 +04:00
Sebastián Ramírez
bac7230027 📝 Update release notes 2019-04-27 17:07:17 +04:00
Christopher Dignam
866af5bca6 ✏️ Fix typos in docs, from forms (#176) 2019-04-27 17:05:06 +04:00
Sebastián Ramírez
f4be79be51 📝 Update release notes 2019-04-27 17:04:00 +04:00
Sebastián Ramírez
3797c04946 Use 401 with WWW-Authenticate for OAuth2 and add scope_str (#188) 2019-04-27 17:00:56 +04:00
Sebastián Ramírez
9a9bfd7f93 📝 Update release notes 2019-04-26 19:28:54 +04:00
Sebastián Ramírez
ada1ecdb00 📝 Add Hypercorn as an alternative ASGI server (#187) 2019-04-26 19:26:38 +04:00
Sebastián Ramírez
3bbd38313b 📝 Update release notes 2019-04-26 19:08:04 +04:00
Sebastián Ramírez
c1df0f6b84 Add docs and tests for Jinja2 templates (#186)
*  Add docs and tests for Jinja2 templates

* 🎨 Fix format in test, remove unused import
2019-04-26 18:49:15 +04:00
Sebastián Ramírez
0cd5485597 📝 Update release notes 2019-04-26 15:17:32 +04:00
Sebastián Ramírez
528ef7e079 Docs and tests, responses with headers and cookies (#185) 2019-04-26 15:13:59 +04:00
Sebastián Ramírez
8e3a7699a3 🔖 Release 0.19.0 2019-04-26 13:48:30 +04:00
Sebastián Ramírez
8998ccaffb 📝 Update release notes 2019-04-26 13:45:38 +04:00
Sebastián Ramírez
2b7f201a44 📝 Add docs about returning a response directly and encoder (#184) 2019-04-26 13:40:23 +04:00
Sebastián Ramírez
192ebba2a2 ♻️ Rename parameter content_type to response_class (#183) 2019-04-26 13:11:16 +04:00
Sebastián Ramírez
8880c4cb03 🔖 Release 0.18.0 2019-04-22 21:08:43 +04:00
Sebastián Ramírez
6324be684f 📝 Update release notes 2019-04-21 22:31:43 +04:00
Sebastián Ramírez
c705685394 Add docs for HTTP Basic Auth and tests (#177) 2019-04-21 22:30:58 +04:00
Sebastián Ramírez
945f401d8e 📝 Update release notes 2019-04-21 21:46:00 +04:00
Sebastián Ramírez
f216d340ec Add automatic header handling for HTTP Basic Auth (#175)
*  Add automatic header handling for HTTP Basic Auth

* 🎨 Remove obsolete comment
2019-04-21 21:44:25 +04:00
Sebastián Ramírez
a4558e7053 📝 Update release notes 2019-04-21 20:21:53 +04:00
Sebastián Ramírez
298f8478e2 🔒 Fix development dependencies security (#174) 2019-04-21 20:20:25 +04:00
Sebastián Ramírez
b86d163470 📝 Rename additional response OpenAPI declarations 2019-04-21 20:13:26 +04:00
Sebastián Ramírez
9e2d37b89c 📝 Update release notes 2019-04-21 19:57:07 +04:00
Sebastián Ramírez
97adadd9e1 📝 Add docs for middleware (#173) 2019-04-21 19:56:20 +04:00
Sebastián Ramírez
26e3dffb37 🚀 Deploy when tagged using Python 3.6 2019-04-20 22:16:07 +04:00
Sebastián Ramírez
aa7b4bd101 🔖 0.17.0 2019-04-20 22:12:55 +04:00
Sebastián Ramírez
ffc4c716c0 🚀 Make Flit publish from CI (#170) 2019-04-20 22:09:35 +04:00
Sebastián Ramírez
ef7b6e8eaf 📝 Update Release Notes 2019-04-20 21:15:03 +04:00
Sebastián Ramírez
596243f4a5 Add docs about CORS (#169) 2019-04-20 21:13:01 +04:00
Sebastián Ramírez
766bf1c5aa 📝 Update release notes 2019-04-20 20:31:44 +04:00
Sebastián Ramírez
9e748dbca4 By default, encode by alias (#168) 2019-04-20 20:29:54 +04:00
Sebastián Ramírez
cefe6cf92c 🔖 Release version 0.16.0 2019-04-16 23:28:13 +04:00
Sebastián Ramírez
be3953499f 📝 Update release notes 2019-04-16 23:27:25 +04:00
Sebastián Ramírez
546d233dec ♻️ Update Pydantic usage, types, values, minor structure changes (#164) 2019-04-16 23:26:09 +04:00
Sebastián Ramírez
61dd36a945 Upgrade docstring Markdown parsing (#163)
*  Upgrade docstring Markdown parsing

* 📝 Update release notes
2019-04-16 22:49:18 +04:00
Sebastián Ramírez
27f9d55c3e 📝 Update release notes 2019-04-16 22:43:59 +04:00
euri10
906cc60f65 ⬆️ Upgrade Pydantic to 0.23 (#160)
* Add websocket to APIRouter

* Upgrade pydantic to v0.23.0

* Forgot pyproject.toml

* ⬆️ Upgrade some Pipfile.lock dependencies
2019-04-16 22:42:00 +04:00
Sebastián Ramírez
69afaf256f 📝 Update release notes 2019-04-16 22:21:32 +04:00
Daniel Michaels
4ab349a2a8 ✏️ fixed small typo /tutorial/extra-models.md (#159) 2019-04-16 22:20:03 +04:00
Sebastián Ramírez
9c258107b4 📝 Update release notes 2019-04-16 22:18:42 +04:00
hayata-yamamoto
29a4f90bcd 📝 fix URL examples in Tutorial: Query Parameters (#157)
* modify tutorial

* modify item_id
2019-04-16 22:16:16 +04:00
Sebastián Ramírez
361fd00777 📝 Add note about Swagger UI and multi-part uploads 2019-04-14 22:24:31 +04:00
Sebastián Ramírez
4c3cf31730 🔖 Release 0.15.0, multi-file uploads 2019-04-14 22:14:20 +04:00
Sebastián Ramírez
aad6b123f7 Add support for multi-file uploads (#158) 2019-04-14 22:12:14 +04:00
Sebastián Ramírez
e40e87c662 📝 Use same link in benchmarks as in index 2019-04-12 22:56:09 +04:00
Sebastián Ramírez
84de980977 Add docs about responses with additional status codes (#156)
*  Add docs about responses with additional status codes

* 📝 Update docs, link to documenting additional responses
2019-04-12 22:43:21 +04:00
Sebastián Ramírez
08484603ee 🔖 Release 0.14.0 2019-04-12 21:56:22 +04:00
Sebastián Ramírez
ab6dd60997 📝 Add note on installing and running pytest 2019-04-12 21:45:19 +04:00
Sebastián Ramírez
c9ef7bd6dc 📝 Update release notes 2019-04-12 21:27:24 +04:00
Sebastián Ramírez
88ece95a30 🎨 Improve automatic naming of path operations in API docs (#155)
* 🎨 Improve operation summary naming

* 📝 Update names in README

* 🚚 Improve names of security tutorial
2019-04-12 21:25:26 +04:00
Sebastián Ramírez
366c5db0bb 📝 Update release notes 2019-04-12 20:18:48 +04:00
Sebastián Ramírez
46e3811f8d Add testing docs and tests (#151)
* ✏️ Fix typo in security intro

*  Add testing docs and tests

* 🐛 Debug Travis coverage

* 🐛 Debug Travis coverage, report XML

* 💚 Make Travis/Flit use same code install

*  Revert Travis/Codecov debugging changes
2019-04-12 20:15:05 +04:00
Sebastián Ramírez
613e211d20 📝 Update release notes 2019-04-12 11:51:26 +04:00
William Hayes
500f2b2ad4 Add deeplinking to Swagger UI (#148)
Update the Swagger UI docs to deep link to path operations to share them more easily.
2019-04-12 11:49:32 +04:00
Sebastián Ramírez
5cf7718657 📝 Update release notes 2019-04-12 11:40:56 +04:00
Sebastián Ramírez
727b656c8d ⬆️ Update development dependencies, Pipfile.lock (#150) 2019-04-12 11:39:06 +04:00
Sebastián Ramírez
cc7102e9b8 📝 Add opinions in main page 2019-04-10 22:27:28 +04:00
Sebastián Ramírez
5123915fe4 📝 Include Hug and Falcon in Alternatives/Inspiration 2019-04-10 22:09:50 +04:00
Sebastián Ramírez
1b8bbd51d8 🔖 Release 0.13.0 2019-04-09 23:38:11 +04:00
Sebastián Ramírez
1e4f86db6d 📝 Update release notes and OAuth2 scopes docs 2019-04-09 23:36:18 +04:00
Sebastián Ramírez
7391056daf Add OAuth2 scopes with SecurityScopes, upgrade Security (#141)
*  Upgrade OAuth2 Security with scopes handling

* 📝 Update Security tutorial with OAuth2 and JWT

*  Add tutorial code for OAuth2 with scopes (and JWT)

*  Add tests for tutorial/OAuth2 with scopes

* 🐛 Fix security_scopes type declaration

*  Add docs and tests for SecurityScopes
2019-04-09 23:29:04 +04:00
Sebastián Ramírez
6a274d18b4 🔖 Release 0.12.1, fix responses in include_router 2019-04-05 20:08:36 +04:00
Sebastián Ramírez
62626b0175 📝 Update release notes 2019-04-05 20:08:00 +04:00
Sebastián Ramírez
c8df3ae57c 🐛 Fix handling additional responses in include_router (#140) 2019-04-05 20:06:40 +04:00
Sebastián Ramírez
6f7f9268f6 📝 Update release notes 2019-04-05 16:24:04 +04:00
Matthew McLeod
50653e205f 📝 Fix typo in SQL tutorial (#138) 2019-04-05 16:22:33 +04:00
Sebastián Ramírez
50a280b17b 📝 Update release notes 2019-04-05 16:21:17 +04:00
Mostapha Sadeghipour Roudsari
c1da3b38a3 📝 fix typos in nested models and OAuth2 with JWT (#127) 2019-04-05 16:08:59 +04:00
Sebastián Ramírez
e68a68c97c 🔖 Release 0.12.0, add additional responses 2019-04-05 14:35:01 +04:00
Sebastián Ramírez
907e613ff2 🔧 Update test-conv-html.sh to allow extra params 2019-04-05 14:29:36 +04:00
Sebastián Ramírez
f0fc2fad2c 📝 Update release notes 2019-04-05 14:28:30 +04:00
Sebastián Ramírez
ad471307e2 Additional Responses (#97)
Add additional responses to OpenAPI, including Pydantic models or schemas directly, custom status codes, media types, extending `response_model`, etc.
2019-04-05 14:18:28 +04:00
Sebastián Ramírez
2bd775988f Add/refactor addditional responses, tests, docs 2019-04-05 13:54:00 +04:00
Sebastián Ramírez
c59ddc8a24 🔖 Release 0.11.0 2019-04-03 15:51:44 +04:00
Sebastián Ramírez
378b39bbbc 📝 Update release notes 2019-04-03 15:49:58 +04:00
Sebastián Ramírez
37e0306517 📝 Update default error response in SQL tutorial 2019-04-03 15:49:40 +04:00
Sebastián Ramírez
fad3a9e1dc Add auto_error to security utils (#134)
to allow them to be optional, also allowing the declaration of multiple security schemes
2019-04-03 15:44:52 +04:00
Sebastián Ramírez
b35b0a9a90 📝 Update release notes 2019-03-31 22:05:03 +04:00
Alex Iribarren
1426b6200a 🗃️ Close the DB even if exceptions are raised (#89)
* Close the DB even if exceptions are raised

* 📝 Add note about closing DB in finally
2019-03-31 22:01:32 +04:00
Sebastián Ramírez
40e5f3764e 📝 Update release notes 2019-03-31 20:56:52 +04:00
Alif Jahan
e5c75807ce 🔥 removed duplicate dependency in pyproject.toml (#128) 2019-03-31 20:55:12 +04:00
Sebastián Ramírez
deff2b6678 🔖 Release 0.10.3 2019-03-30 21:54:00 +04:00
Sebastián Ramírez
7c572fdb3a 📝 Update release notes 2019-03-30 21:32:24 +04:00
Daniel Hahler
ae970638cf 👷 Set Travis to use dist=xenial and Python 3.7 instead of 3.7-dev (#92) 2019-03-30 21:30:31 +04:00
Sebastián Ramírez
deae92bba1 📝 Update release notes 2019-03-30 21:09:47 +04:00
yihuang
f806ba642a 🔥 Remove repeated param declaration (#123) 2019-03-30 21:07:41 +04:00
Sebastián Ramírez
5a3cf863da 📝 Update release notes 2019-03-30 19:55:01 +04:00
Sebastián Ramírez
dd6ab23b62 Add docs/tests extending OpenAPI (#126) 2019-03-30 19:53:44 +04:00
Sebastián Ramírez
0449499188 📝 Update release notes 2019-03-30 18:32:23 +04:00
The Gitter Badger
4dc7b32861 📝 Add a Gitter chat badge and links (#117)
* Add Gitter badge

* 📝 Add links and badges to Gitter chat
2019-03-30 18:30:02 +04:00
Sebastián Ramírez
08d849d5c5 📝 Update release notes 2019-03-29 19:06:02 +04:00
James Saunders
714e68b5f0 📝 Add note in response model docs: why not return type annotations (#109)
* Update response model documentation to explain design choice

Closes #101

* 📝 Update note about return function type annotation
2019-03-29 19:02:53 +04:00
Sebastián Ramírez
3d4f59f35a 📝 Udpate release notes 2019-03-29 18:43:40 +04:00
Stratos Gerakakis
3ce2920fef 🐛 fix name of shutdown_event in docs (#105)
Fix name copy/paste name error in docs source for startup/shutdown events.
2019-03-29 18:39:57 +04:00
Sebastián Ramírez
825f397918 🔖 Release 0.10.2 2019-03-29 15:17:34 +04:00
Sebastián Ramírez
b390e32372 📝 Update release notes 2019-03-29 15:16:56 +04:00
Sebastián Ramírez
b7d184363f 🐛 Fix JSON Schema of additional properties (#121)
#87
2019-03-29 15:15:49 +04:00
Sebastián Ramírez
2ddb804940 📝 Update release notes 2019-03-25 23:48:27 +04:00
Sebastián Ramírez
a2c9f666b5 📝 Add note about Celery in background tasks 2019-03-25 23:47:25 +04:00
Sebastián Ramírez
1594222e39 📝 Update Release Notes 2019-03-25 23:28:36 +04:00
Sebastián Ramírez
dc1e94d05f Document and test union and list response models (#108) 2019-03-25 23:28:09 +04:00
Sebastián Ramírez
b0f7961b65 🔖 Release 0.10.1: support for encode/databases 2019-03-25 22:21:59 +04:00
Sebastián Ramírez
1c2ecbb89a Add docs and tests for encode/databases (#107)
*  Add docs and tests for encode/databases

*  Add testing-only dependency, databases
2019-03-25 22:17:31 +04:00
Sebastián Ramírez
5a6e47bd49 🔖 Release 0.10.0: BackgroundTasks and websockets fix 2019-03-24 23:37:37 +04:00
Sebastián Ramírez
58872dca74 📝 Udpate release notes 2019-03-24 23:36:57 +04:00
Sebastián Ramírez
9b04593260 Add support for BackgroundTasks parameters (#103)
*  Add support for BackgroundTasks parameters

* 🐛 Fix type declaration in dependencies

* 🐛 Fix coverage of util in tests
2019-03-24 23:33:35 +04:00
euri10
6d77e2ac5f Add websocket to APIRouter (#100)
* Add websocket to APIRouter

* Restore upstream/master Pipfile.lock (git checkout upstream/master -- Pipfile.lock)

* Added tests for router with a prefix
2019-03-24 23:18:20 +04:00
Sebastián Ramírez
b16ca54c30 📝 Update Release Notes 2019-03-24 12:46:13 +04:00
Sebastián Ramírez
834723cf2c Add events docs and tests (#99) 2019-03-24 12:45:46 +04:00
Mohammed
eda9b28338 files formatting 2019-03-23 13:10:45 +03:00
Mohammed
7514ac6fb0 100% test coverage 2019-03-23 13:01:53 +03:00
Mohammed
25fb4239cc increase test coverage 2019-03-23 01:13:09 +03:00
Mohammed
65568065e0 Remove extra code. 2019-03-23 00:47:32 +03:00
Mohammed
95679ca5e6 Fix: adding additional_responses on .include_router() 2019-03-23 00:37:10 +03:00
Mohammed
84a300ef84 Formatting according to guide 2019-03-22 22:54:48 +03:00
Mohammed
c6d28c8209 Accept Multiple Additional Responses 2019-03-22 22:50:47 +03:00
Mohammed
3984e9b8ac Additional Responses test 2019-03-22 22:40:46 +03:00
Mohammed
aa0bca7bb2 Additional Responses implementation 2019-03-22 22:40:07 +03:00
Sebastián Ramírez
9778542ba6 🔖 Release 0.9.1, multi value/duplicate query/header 2019-03-22 21:52:37 +04:00
Sebastián Ramírez
34c34c68d2 📝 Update release notes 2019-03-22 21:51:36 +04:00
Sebastián Ramírez
c64f8346ae Multi-value query parameters and duplicate headers (#95)
* 📝 Document multi-value query parameters

*  Document and test multiple query values

*  Document receiving duplicate headers
2019-03-22 21:47:54 +04:00
Sebastián Ramírez
4f852878d6 🔖 Release 0.9.0, compatible with latest Pydantic 2019-03-22 16:29:33 +04:00
Sebastián Ramírez
59bc4b7d69 📝 Update links in help section 2019-03-22 16:28:28 +04:00
Sebastián Ramírez
3cae2ccbae 📝 Fix link from deployment to bigger applications 2019-03-21 20:35:49 +04:00
Matt Hegarty
e21ba7646a ✏️ typo: fist_name -> first_name (#72) 2019-03-21 18:50:47 +04:00
Sebastián Ramírez
10498fcfbd 📝 Update release notes 2019-03-21 18:48:17 +04:00
Sebastián Ramírez
3f7b7837fb 🔀 Merge PR #72 2019-03-21 18:46:02 +04:00
Sebastián Ramírez
1c26e77a66 📝 Update release notes 2019-03-21 18:40:59 +04:00
Sebastián Ramírez
108c2f3c0e ⬆️ Update Pydantic to 0.21.0 (#90)
* ⬆️ Upgrade Pydantic and others (isort), update docs after changes by isort

* 🎨 Format with newest isort, update type hints in jsonable_encoder

* 🔧 Update test script, to avoid Pydantic type errors

* ⬆️ Update pyproject.toml with latest Pydantic
2019-03-21 18:40:29 +04:00
Sebastián Ramírez
f2fd948ce3 📝 Update release notes 2019-03-21 18:10:08 +04:00
Sebastián Ramírez
b269655b7f 📝 Add docs for application configuration (OpenAPI) 2019-03-21 18:08:10 +04:00
Sebastián Ramírez
a174f01901 🔖 Release version 0.8.0 2019-03-16 21:24:26 +04:00
Sebastián Ramírez
9b76ad1870 ✏️ Fix typos in README 2019-03-16 21:23:35 +04:00
Sebastián Ramírez
f1c367aead 📝 Update docs - Release Notes 2019-03-16 21:21:56 +04:00
Sebastián Ramírez
8291c664b9 🔀 Merge origin master with release notes 2019-03-16 21:20:54 +04:00
euri10
e8472ebbd1 🔧 Make scripts executable (#76) 2019-03-16 21:19:13 +04:00
Sebastián Ramírez
f4391e2a87 📝 Add tags parameter to Release Notes 2019-03-16 21:17:27 +04:00
euri10
11c755bee3 Add tags parameter to app.include_router (#55) 2019-03-16 21:15:08 +04:00
Sebastián Ramírez
35054a450c 📝 Update release notes 2019-03-09 22:12:00 +04:00
Sebastián Ramírez
da60de33c1 📝 Update Uvicorn docs with new --reload option (#74) 2019-03-09 22:10:25 +04:00
Sebastián Ramírez
c0758dfe71 📝 Update release-notes with isort changes 2019-03-09 15:04:47 +04:00
Sebastián Ramírez
1112ac7538 ⬆️ Update imports and scripts for new isort versions (#75) 2019-03-09 15:04:13 +04:00
Sebastián Ramírez
ac2b18bf40 🔖 Release 0.7.1, Raspberry Pi deployment and docs 2019-03-04 20:07:11 +04:00
Sebastián Ramírez
b89a24448b 📝 Update release notes 2019-03-04 20:06:24 +04:00
Zaar Hai
e76216dd26 Clarification about possible performance hit (#64)
* Furether technical details towards #33.

* 📝 Update note about previous async frameworks
2019-03-04 20:04:16 +04:00
Sebastián Ramírez
123d778a0c 📝 Add instructions for Docker on Raspberry Pi 2019-03-04 19:37:46 +04:00
Sebastián Ramírez
829ad209a6 📝 Update benchmarks link 2019-03-04 17:29:53 +04:00
Sebastián Ramírez
b15a65c37e 📝 Update release notes 2019-03-04 11:18:45 +04:00
Sebastián Ramírez
0eed798aac 👷 Limit Docker trigger to branch master 2019-03-04 11:17:56 +04:00
Sebastián Ramírez
2caca42b9e 👷 Trigger Docker images build on Travis (#65) 2019-03-04 11:12:21 +04:00
Sebastián Ramírez
7658d0af16 📝 Clarify uploadfile async method calls 2019-03-04 11:07:15 +04:00
Sebastián Ramírez
c14ec50f73 🔖 Release 0.7.0, with support for UploadFile 2019-03-03 21:06:42 +04:00
Sebastián Ramírez
6b6ea0da2e 📝 Update release notes with UploadFile 2019-03-03 21:05:58 +04:00
Sebastián Ramírez
0b9fe62a10 Add support for UploadFile class annotations (#63)
*  Add support for UploadFile annotations

* 📝 Update File upload docs with FileUpload class

*  Add tests for UploadFile support

* 📝 Update UploadFile docs
2019-03-03 20:52:37 +04:00
Sebastián Ramírez
1f03e85f06 🔖 Release 0.6.4 2019-03-02 22:33:48 +04:00
Sebastián Ramírez
b98bf178a6 📝 Update release notes with WebSockets 2019-03-02 21:51:01 +04:00
Sebastián Ramírez
bbd2198fa2 Add docs for WebSockets (#62) 2019-03-02 21:45:15 +04:00
Sebastián Ramírez
e2723e8480 📝 Update release notes 2019-03-02 20:00:27 +04:00
Sebastián Ramírez
1896153d58 ✏️ Fix typos 2019-03-02 19:54:52 +04:00
Sebastián Ramírez
770b4421f9 📝 Add History, Design and Future to docs 2019-03-02 19:54:15 +04:00
Sebastián Ramírez
e89aacbdf7 📝 Add link to Python docs in debugging section 2019-03-02 17:56:30 +04:00
Sebastián Ramírez
cf25291650 📝 Update release notes 2019-03-02 17:55:07 +04:00
Sebastián Ramírez
13772fbd11 📝 Add note about bigger applications in Docker 2019-03-02 17:52:24 +04:00
Sebastián Ramírez
1d69b6f480 📝 Update release notes 2019-03-02 17:44:48 +04:00
Sebastián Ramírez
01d6aa3dd1 📝 Add docs for debugging 2019-03-02 17:40:01 +04:00
Sebastián Ramírez
74db8ddf9b 📝 Update release notes 2019-03-02 13:53:16 +04:00
Sebastián Ramírez
819b3b2516 📝 Add technical details about async def handling (#61)
#33
2019-03-02 13:48:06 +04:00
Sebastián Ramírez
76fb2879ed ✏️ Fix typo in release notes 2019-03-02 13:02:06 +04:00
Sebastián Ramírez
daaf654868 🔖 Release 0.6.3: favicons in docs 2019-02-24 01:49:04 +04:00
Sebastián Ramírez
6e0553b4cf 📝 Update release notes, favicons 2019-02-24 01:32:39 +04:00
Sebastián Ramírez
8e1ecaf221 💄 Add FastAPI favicons to docs (#53) 2019-02-24 01:31:50 +04:00
Sebastián Ramírez
9e610030fb ✏️ Fix typo in release notes 2019-02-24 01:12:33 +04:00
Sebastián Ramírez
9940c1511e 🔖 Release 0.6.2, SQL tutorial improvements and project generator 2019-02-24 01:09:49 +04:00
Sebastián Ramírez
24d94298d0 📝 Update release notes with SQL tutorial changes 2019-02-24 01:09:00 +04:00
Sebastián Ramírez
e3b4019fa3 Update SQL with dependency and intro project generator (#52) 2019-02-24 01:04:44 +04:00
Sebastián Ramírez
502ab432b8 💄 Add PNG images to improve link previews 2019-02-23 23:59:17 +04:00
Sebastián Ramírez
9051ec3816 📝 Improve naming of middleware in SQLAlchemy tutorial 2019-02-21 10:15:39 +04:00
Sebastián Ramírez
22f4e18cdd ✏️ Fix GraphQL typo 2019-02-20 22:02:19 +04:00
Sebastián Ramírez
4473e6a096 🔖 Release 0.6.1: GraphQL 2019-02-20 21:59:24 +04:00
Sebastián Ramírez
984dd71d13 Add docs for GraphQL (#48) 2019-02-20 21:58:26 +04:00
Sebastián Ramírez
bf53518141 📝 Include PR in Release Notes 2019-02-19 21:22:51 +04:00
Sebastián Ramírez
0ed55eb7d3 🔖 Release 0.6.0, upgrade Starlette, improve SQLAlchemy compatibility 2019-02-19 21:20:32 +04:00
Sebastián Ramírez
12e087f0b5 Use request.state for SQLAlchemy session in tutorial (#45) 2019-02-19 21:18:28 +04:00
Sebastián Ramírez
ba10838c30 ⬆️ Upgrade Starlette and fix compatibility (#44) 2019-02-19 20:27:48 +04:00
Sebastián Ramírez
656e1c7ce9 🙈 Add test.db to .gitignore 2019-02-18 22:55:48 +04:00
Sebastián Ramírez
88b31e6a4d 🔖 Release 0.5.1: docs 2019-02-18 22:52:03 +04:00
Sebastián Ramírez
2c3b826810 📝 Add contributing/development docs (#42) 2019-02-18 22:40:31 +04:00
Sebastián Ramírez
aa64eecda6 Update error handling docs, including Starlette's utils (#41)
📝 Update error handling docs, including Starlette's utils
2019-02-18 21:58:21 +04:00
Sebastián Ramírez
712b18a58a 📝 Update docs 2019-02-16 19:36:09 +04:00
Sebastián Ramírez
a809da5567 📝 Add note about path declaration order 2019-02-16 19:23:42 +04:00
Sebastián Ramírez
80b68cd97d 📝 Add section about help/getting help 2019-02-16 18:10:15 +04:00
Sebastián Ramírez
894e131e03 🔖 Release 0.5.0 with new HTTPException 2019-02-16 17:06:31 +04:00
Sebastián Ramírez
8772e2f2ee Add HTTPException with custom headers (#35)
* 📝 Update Release Notes with issue templates

*  Add HTTPException with support for headers

Including docs and tests

* 📝 Update Security docs to use new HTTPException
2019-02-16 17:01:29 +04:00
Sebastián Ramírez
7edbd9345b Update issue templates (#34)
Update issue templates
2019-02-16 14:09:20 +04:00
Sebastián Ramírez
56819fdd89 📝 Update Release Notes 2019-02-16 13:47:05 +04:00
euri10
febf8e7341 📝 Add docs for using the Starlette Request directly (#25)
Add docs for using the Starlette Request directly
2019-02-16 12:44:56 +04:00
Sebastián Ramírez
293ebd7cc2 📝 Update Release Notes 2019-02-15 23:19:19 +04:00
Sebastián Ramírez
54e3949f74 📝 Update SQLAlchemy docs, with current workaround 2019-02-15 22:05:18 +04:00
Sebastián Ramírez
acbcbba94f 🔖 Release 0.4.0 with openapi_prefix, #26 2019-02-14 23:04:55 +04:00
Sebastián Ramírez
f7b7a099c3 📝 Update Release Notes and openapi_prefix docs 2019-02-14 23:02:47 +04:00
Kabir Khan
0ea0d0e82a Add Open API prefix route - correct docs behind reverse proxy (#26)
Add Open API prefix route - correct docs behind reverse proxy.
2019-02-14 22:57:49 +04:00
Sebastián Ramírez
890f1f7899 📝 Add note about DB Browser for SQLite in SQL docs 2019-02-12 23:31:18 +04:00
Sebastián Ramírez
783816a7e3 📝 Update Release Notes 2019-02-12 23:07:54 +04:00
Sebastián Ramírez
7863490c8c 🔖 Release after SQLAlchemy fix: 0.3.0 2019-02-12 23:06:05 +04:00
Sebastián Ramírez
955e9fcb31 Update fix SQLAlchemy support with ORM (#30)
 SQLAlchemy ORM support

Improved jsonable_encoder with SQLAlchemy support, tests running with SQLite, improved and updated SQL docs

*  Add SQLAlchemy to development dependencies (not required for using FastAPI)

*  Add sqlalchemy to testing dependencies (not required to use FastAPI)
2019-02-12 23:02:21 +04:00
Sebastián Ramírez
9484f939ed 🔖 Bump version, after fix, release 2019-02-12 21:46:35 +04:00
Sebastián Ramírez
9745a5d1ae 🐛 Fix jsonable_encoder for models with Config (#29)
but without json_encoders
2019-02-12 21:43:34 +04:00
Sebastián Ramírez
92c825be6a 🔖 Release 0.2.0 2019-02-08 16:09:48 +04:00
euri10
32438c85f6 Using pydantic custom encoders (#21)
Add support for Pydantic custom JSON encoders.
2019-02-08 16:06:19 +04:00
Sebastián Ramírez
02e53fde90 📝 Update release notes 2019-02-08 15:43:00 +04:00
Ken Kinder
902cdaf010 Fix typos (#24)
Fix typos in security section.
2019-02-08 15:41:13 +04:00
Sebastián Ramírez
04d77bb1c4 ✏️ Fix typos in index and alternatives 2019-02-08 15:39:26 +04:00
Sebastián Ramírez
6d9fc08a7e 🚀 Bump version and add Release Notes 2019-02-01 14:23:20 +04:00
euri10
5c9c088a2a Upgrade Starlette version (#17)
Upgrade Starlette version
2019-02-01 14:14:23 +04:00
Sebastián Ramírez
014c7df142 📝 Add Requests to inspiration 2019-01-24 22:31:33 +04:00
Sebastián Ramírez
9259dc228a 📈 Add Analytics to understand docs usage and improvements 2019-01-24 21:58:27 +04:00
Sebastián Ramírez
de431d948d Merge pull request #11 from tiangolo/fix-10
Pin versions of dependencies and bump version
2019-01-23 16:12:09 +01:00
Sebastián Ramírez
3d2c0993c1 📌 Pin versions of dependencies and bump version 2019-01-23 18:57:48 +04:00
Sebastián Ramírez
37bc3614fd 📝 Fix docs clarification about dict unwrapping
in extra-models and simple-oauth2 #7
2019-01-14 23:01:34 +04:00
Sebastián Ramírez
188da34529 📝 Clarify docs, alternatives, about APISpec OAI versions 2019-01-14 21:26:29 +04:00
Sebastián Ramírez
d692c28f52 📝 Add docs for bigger applications and APIRouter
and update tests to match docs
2019-01-14 19:23:38 +04:00
Sebastián Ramírez
8568862a19 📝 Add docs for response status codes 2019-01-14 17:30:55 +04:00
Sebastián Ramírez
dfa067b061 📝 Add screenshot to body-schema tutorial 2019-01-10 20:52:06 +04:00
Sebastián Ramírez
0d1b97fb94 📝 Add docs for deployment, with Docker, HTTPS, etc 2019-01-05 20:24:33 +04:00
Sebastián Ramírez
df1e754380 🔧 Update development environment dependencies 2019-01-05 18:49:50 +04:00
Sebastián Ramírez
e5b341c7dd 🔖 Bump version after fix for constrained bytes 2019-01-05 17:38:59 +04:00
Sebastián Ramírez
577c5a84db 🐛 Fix constrained bytes, from defaults in Pydantic
#2
2019-01-05 17:30:27 +04:00
Sebastián Ramírez
a5cfee434d 📝 Update docs for dependencies 2019-01-05 17:19:41 +04:00
Sebastián Ramírez
9a8349bf96 📝 Improve explanation of dependencies 2019-01-01 19:27:02 +04:00
Sebastián Ramírez
a59408f68c ✏️ Fix typo in dependencies docs 2018-12-30 22:18:45 +04:00
Sebastián Ramírez
3c08b05ea6 🔖 Bump version, after query and header as lists
and bug fixes for Python 3.7
2018-12-30 21:46:49 +04:00
Sebastián Ramírez
60599bad99 🐛 Fix Python 3.7 specific list query handling 2018-12-30 21:43:34 +04:00
Sebastián Ramírez
ccf30b5c2e 📝 Update docs, 100% coverage 2018-12-30 00:17:22 +04:00
Sebastián Ramírez
ca0652aebf 🐛 Fix type checks for Python 3.7 2018-12-30 00:14:39 +04:00
Sebastián Ramírez
be957e7c99 Allow lists of query or header params
and add tests for them
2018-12-30 00:07:31 +04:00
Sebastián Ramírez
90af868146 Add security checks for HTTP utils
and tests for them
2018-12-29 23:04:54 +04:00
Sebastián Ramírez
660f917d79 ✏️ Fix typos and docs notes 2018-12-29 18:43:58 +04:00
Sebastián Ramírez
5278314f2f 🔖 Bump version, new security features and bug fixes 2018-12-28 20:40:40 +04:00
Sebastián Ramírez
4a0316bcfe 🎨 Add missing type definition 2018-12-28 20:39:04 +04:00
Sebastián Ramírez
0393a093d3 Improve security utilities and add tests 2018-12-28 20:35:48 +04:00
Sebastián Ramírez
27f530a7ff 📝 Update docs, clarify what's a schema 2018-12-28 16:32:03 +04:00
Sebastián Ramírez
c3e5e65093 🎨 Fix missing format 2018-12-28 16:11:45 +04:00
Sebastián Ramírez
804ec460fc ⬆️ Add tests, fix issues and update Pydantic 2018-12-28 16:10:29 +04:00
Sebastián Ramírez
0125ea4f83 📝 Update tutorials 2018-12-28 16:03:54 +04:00
Sebastián Ramírez
216770118a ✏️ Fix typos 2018-12-27 17:25:39 +04:00
Sebastián Ramírez
a935d66b10 📝 Update docs about alternatives, inspiration and benchmarks 2018-12-27 17:14:46 +04:00
Sebastián Ramírez
dd2541bc97 📝 Improve explanation of request bodies 2018-12-26 19:01:15 +04:00
Sebastián Ramírez
098e629344 🔖 Bump version, after changes in OAuth2 utils 2018-12-24 20:21:28 +04:00
Sebastián Ramírez
bbe5f28b77 📝 Add docs for OAuth2 security 2018-12-24 20:20:48 +04:00
Sebastián Ramírez
4a0922ebab ♻️ Update OAuth2 class utilities to be dependencies 2018-12-24 20:20:21 +04:00
Sebastián Ramírez
8f16868c6a Add passlib and pyjwt to development dependencies 2018-12-24 20:19:05 +04:00
Sebastián Ramírez
bc3e7f2bbc 🔖 Version bump, fixing several issues, lots of docs and tests 2018-12-24 09:35:20 +04:00
Sebastián Ramírez
58848be2de Add pending tests to temporal dir 2018-12-24 09:35:02 +04:00
Sebastián Ramírez
cfb65d0e15 🐛 Fix utility OAuth2PasswordRequestForm to use forms
and be used as a dependency
2018-12-24 09:34:28 +04:00
Sebastián Ramírez
855daa2e53 📝 Add tutorial for complete OAuth2 password flow 2018-12-24 09:33:48 +04:00
Sebastián Ramírez
de54e85152 📝 Add Security tutorial: Get current user 2018-12-24 08:03:59 +04:00
Sebastián Ramírez
b8d3070daf 📝 Add first Security tutorials 2018-12-23 23:25:57 +04:00
Sebastián Ramírez
471c9cfc2d 📝 Add example screenshot for dependencies 2018-12-23 21:29:59 +04:00
Sebastián Ramírez
b79c13baed 📝 Update and add docs for dependencies 2018-12-23 21:21:37 +04:00
Sebastián Ramírez
332ee4aee1 📝 Update and clarify first-steps tutorial 2018-12-23 18:42:29 +04:00
Sebastián Ramírez
ad40f4a457 📝 Fix double editor screenshot 2018-12-22 20:23:24 +04:00
Sebastián Ramírez
6b9931f882 Add tests for metadata 2018-12-22 18:47:05 +04:00
Sebastián Ramírez
4c51bb6714 Test extra routes, with parameters directly 2018-12-22 18:30:34 +04:00
Sebastián Ramírez
57ff677027 Add tests for validation errors in response 2018-12-22 18:20:01 +04:00
Sebastián Ramírez
613c3f3e95 Test all HTTP methods 2018-12-22 18:18:19 +04:00
Sebastián Ramírez
bf6d923ca8 Add ujson for local development 2018-12-22 17:23:51 +04:00
Sebastián Ramírez
252188c686 Update tests for HTML content and remove unneeded tests 2018-12-22 17:23:04 +04:00
Sebastián Ramírez
510fec9bee ♻️ Refactor jsonable_encoder and test it
with nested arbitrary classes
2018-12-22 17:15:04 +04:00
Sebastián Ramírez
a73709507c Add docs, tests and fixes for extra data types
including refactor of jsonable_encoder to allow other object and model types
2018-12-22 14:35:48 +04:00
Sebastián Ramírez
75407b9295 🚨 Fix mypy type errors 2018-12-22 09:05:13 +04:00
Sebastián Ramírez
3180f35bdd Fix OpenAPI test for body schema 2018-12-22 09:00:58 +04:00
Sebastián Ramírez
d498b7feb3 Add tests for response_model 2018-12-22 08:54:52 +04:00
Sebastián Ramírez
3269e6a95c Test custom responses 2018-12-22 08:47:44 +04:00
Sebastián Ramírez
f1808de18e Add tests for form and files 2018-12-22 08:39:26 +04:00
Sebastián Ramírez
748dc375db 🐛 Fix Form and File params must always be embeded
and add tests for forms and files
2018-12-22 08:24:48 +04:00
Sebastián Ramírez
b38fb937b0 🔇 Remove debugging prints 2018-12-22 08:21:02 +04:00
Sebastián Ramírez
23ef570bf6 Add test-cov-html script for local coverage
analysis and debugging
2018-12-22 07:42:24 +04:00
Sebastián Ramírez
c25a71e352 🐛 Re-implement check for body as a workaround
while encode/starlette#287 is merged
2018-12-22 07:40:56 +04:00
Sebastián Ramírez
0c5e684ff9 📝 Add Project Generation section 2018-12-21 20:27:03 +04:00
Sebastián Ramírez
b097a538ab 🔖 Bump version, after fix for email_validator and docs 2018-12-21 16:33:45 +04:00
Sebastián Ramírez
a0628f3f6f 📝 Update docs to improve look in GitHub 2018-12-21 16:32:09 +04:00
Sebastián Ramírez
16f6dc66e2 📝 Update README from docs source 2018-12-21 16:24:15 +04:00
Sebastián Ramírez
07b68365f1 📝 Update docs and index to make clear what FastAPI does 2018-12-21 16:23:28 +04:00
Sebastián Ramírez
0a65c41909 📝 Move tutorial src files to top level docs 2018-12-21 16:22:33 +04:00
Sebastián Ramírez
d5e782074f 🐛 Fix email_validator error, generated by autoflake 2018-12-21 14:51:17 +04:00
Sebastián Ramírez
b5a0c228e5 Recover extensive tests for path and params 2018-12-18 23:48:02 +04:00
Sebastián Ramírez
4b94da956c Update query param tests and docs 2018-12-18 23:38:38 +04:00
Sebastián Ramírez
b59e8ffcf6 🎨 Format tests for Cookies 2018-12-18 23:15:26 +04:00
Sebastián Ramírez
7f382127cc Add tests for body with Schema 2018-12-18 23:15:03 +04:00
Sebastián Ramírez
3513b039b9 Test cookies 2018-12-18 23:04:53 +04:00
Sebastián Ramírez
4cf15503cb 📝 Make badges be links to new tab (_blank) 2018-12-18 23:00:04 +04:00
Sebastián Ramírez
22dc7e9132 Test for missing required body 2018-12-18 22:57:09 +04:00
Sebastián Ramírez
7ee32ea197 📝 Fix broken link to docs 2018-12-18 22:56:36 +04:00
Sebastián Ramírez
e6ca71523b 📝 Update docs highlighting after re-sort imports
coming back to flit, after pipenv
2018-12-18 22:55:30 +04:00
Sebastián Ramírez
7da9625505 💚 Revert to flit install and re-format
As it has shown to be more reliable, and closer to final user environments
2018-12-18 22:36:04 +04:00
Sebastián Ramírez
ae50492735 Add tests for header parameters 2018-12-18 22:33:59 +04:00
Sebastián Ramírez
bcb967f98a 💚 Try fixing Travis, again... 2018-12-18 22:22:07 +04:00
Sebastián Ramírez
19c6a2b9bd 🐛 Install dev-packages with pipenv, not pip 2018-12-18 22:13:42 +04:00
Sebastián Ramírez
01dd913634 💚 Install dev-packages in Travis 2018-12-18 22:11:04 +04:00
Sebastián Ramírez
343ecb7669 💚 Use pipenv in Travis 2018-12-18 22:08:47 +04:00
Sebastián Ramírez
e9f2a3c291 Update tutorial renamer to exclude files 2018-12-18 21:59:51 +04:00
Sebastián Ramírez
00e2e544c7 ♻️ Re-format tutorials, files names and tests
for tutorial files
2018-12-18 21:59:06 +04:00
Sebastián Ramírez
dcb076b752 🐛 Fix optional bodies raising an error
when not provided in the request
2018-12-18 21:11:24 +04:00
Sebastián Ramírez
659b8ae8af 📝 Update docs, typos, aclarations, fix examples
for NoSQL models
2018-12-17 22:50:22 +04:00
Sebastián Ramírez
2a48b10be3 📝 Add Python type hints tutorial 2018-12-17 22:27:26 +04:00
Sebastián Ramírez
5bd167e0e7 📝 Add second tutorial src for python-types 2018-12-17 20:41:19 +04:00
Sebastián Ramírez
58b69493a9 📝 Add tutorial src for python-types 2018-12-17 20:36:53 +04:00
Sebastián Ramírez
786c392bd5 💚 Fix Netlify build with pipenv 2018-12-17 18:56:48 +04:00
Sebastián Ramírez
acc15230ea Update query tests, application type checks
and temporarily disable coverage fail, to allow publishing docs from Travis
2018-12-17 15:48:38 +04:00
Sebastián Ramírez
a84960b13d 💚 Update Netlify docs build, try 78 2018-12-15 22:16:54 +04:00
Sebastián Ramírez
61779949f4 🔥 Remove un-used requirements.txt 2018-12-15 22:11:28 +04:00
Sebastián Ramírez
10134803a9 💚 Call docs build with Python module 2018-12-15 22:10:12 +04:00
Sebastián Ramírez
5085652479 🔥 Remove dist hidden old file 2018-12-15 22:07:37 +04:00
457 changed files with 19113 additions and 1999 deletions

42
.github/ISSUE_TEMPLATE/bug_report.md vendored Normal file
View File

@@ -0,0 +1,42 @@
---
name: Bug report
about: Create a report to help us improve
title: "[BUG]"
labels: bug
assignees: ''
---
**Describe the bug**
A clear and concise description of what the bug is.
**To Reproduce**
Steps to reproduce the behavior:
1. Create a file with '...'
2. Add a path operation function with '....'
3. Open the browser and call it with a payload of '....'
4. See error
**Expected behavior**
A clear and concise description of what you expected to happen.
**Screenshots**
If applicable, add screenshots to help explain your problem.
**Environment:**
- OS: [e.g. Linux / Windows / macOS]
- FastAPI Version [e.g. 0.3.0], get it with:
```Python
import fastapi
print(fastapi.__version__)
```
- Python version, get it with:
```bash
python --version
```
**Additional context**
Add any other context about the problem here.

View File

@@ -0,0 +1,20 @@
---
name: Feature request
about: Suggest an idea for this project
title: "[FEATURE]"
labels: enhancement
assignees: ''
---
**Is your feature request related to a problem? Please describe.**
A clear and concise description of what the problem is. Ex. I want to be able to [...] but I can't because [...]
**Describe the solution you'd like**
A clear and concise description of what you want to happen.
**Describe alternatives you've considered**
A clear and concise description of any alternative solutions or features you've considered.
**Additional context**
Add any other context or screenshots about the feature request here.

17
.github/ISSUE_TEMPLATE/question.md vendored Normal file
View File

@@ -0,0 +1,17 @@
---
name: Question
about: Ask a question
title: "[QUESTION]"
labels: question
assignees: ''
---
**Description**
How can I [...]?
Is it possible to [...]?
**Additional context**
Add any other context or screenshots about the feature request here.

2
.gitignore vendored
View File

@@ -10,3 +10,5 @@ site
.coverage
coverage.xml
.netlify
test.db
log.txt

View File

@@ -1,17 +1,26 @@
dist: xenial
language: python
cache: pip
python:
- "3.6"
- "3.7-dev"
- "3.7"
install:
- pip install flit
- flit install
- flit install --symlink
script:
- bash scripts/test.sh
after_script:
- bash <(curl -s https://codecov.io/bash)
deploy:
provider: script
script: bash scripts/deploy.sh
on:
tags: true
python: "3.6"

15
Pipfile
View File

@@ -5,10 +5,7 @@ verify_ssl = true
[dev-packages]
mypy = "*"
jedi = "*"
black = "*"
prospector = "*"
rope = "*"
jupyter = "*"
better-exceptions = "*"
pytest = "*"
@@ -20,10 +17,18 @@ mkdocs = "*"
mkdocs-material = "*"
markdown-include = "*"
autoflake = "*"
email-validator = "*"
ujson = "*"
flake8 = "*"
python-multipart = "*"
sqlalchemy = "*"
uvicorn = "*"
[packages]
starlette = "*"
pydantic = "*"
starlette = "==0.11.1"
pydantic = "==0.25.0"
databases = {extras = ["sqlite"],version = "*"}
hypercorn = "*"
[requires]
python_version = "3.6"

842
Pipfile.lock generated
View File

File diff suppressed because it is too large Load Diff

172
README.md
View File

@@ -1,45 +1,70 @@
<p align="center">
<a href="https://fastapi.tiangolo.com"><img src="https://fastapi.tiangolo.com/img/logo-margin/logo-teal-vector.svg" alt='FastAPI'></a>
<a href="https://fastapi.tiangolo.com"><img src="https://fastapi.tiangolo.com/img/logo-margin/logo-teal.png" alt="FastAPI"></a>
</p>
<p align="center">
<em>FastAPI framework, high performance, easy to learn, fast to code, ready for production</em>
</p>
<p align="center">
<a href="https://travis-ci.org/tiangolo/fastapi">
<a href="https://travis-ci.org/tiangolo/fastapi" target="_blank">
<img src="https://travis-ci.org/tiangolo/fastapi.svg?branch=master" alt="Build Status">
</a>
<a href="https://codecov.io/gh/tiangolo/fastapi">
<a href="https://codecov.io/gh/tiangolo/fastapi" target="_blank">
<img src="https://codecov.io/gh/tiangolo/fastapi/branch/master/graph/badge.svg" alt="Coverage">
</a>
<a href="https://pypi.org/project/fastapi">
<a href="https://pypi.org/project/fastapi" target="_blank">
<img src="https://badge.fury.io/py/fastapi.svg" alt="Package version">
</a>
<a href="https://gitter.im/tiangolo/fastapi?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge" target="_blank">
<img src="https://badges.gitter.im/tiangolo/fastapi.svg" alt="Join the chat at https://gitter.im/tiangolo/fastapi">
</a>
</p>
---
**Documentation**: [https://fastapi.tiangolo.com](https://fastapi.tiangolo.com)
**Documentation**: <a href="https://fastapi.tiangolo.com" target="_blank">https://fastapi.tiangolo.com</a>
**Source Code**: [https://github.com/tiangolo/fastapi](https://github.com/tiangolo/fastapi)
**Source Code**: <a href="https://github.com/tiangolo/fastapi" target="_blank">https://github.com/tiangolo/fastapi</a>
---
FastAPI is a modern, fast (high-performance), web framework for building APIs with Python 3.6+.
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).
* **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% *.
* **Less bugs**: Reduce about 40% of human (developer) induced errors. *
* **Fewer bugs**: Reduce about 40% of human (developer) induced errors. *
* **Intuitive**: Great editor support. <abbr title="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. Less bugs.
* **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: <a href="https://github.com/OAI/OpenAPI-Specification" target="_blank">OpenAPI</a> and <a href="http://json-schema.org/" target="_blank">JSON Schema</a>.
* **Standards-based**: Based on (and fully compatible with) the open standards for APIs: <a href="https://github.com/OAI/OpenAPI-Specification" target="_blank">OpenAPI</a> (previously known as Swagger) and <a href="http://json-schema.org/" target="_blank">JSON Schema</a>.
<small>* estimation based on tests on an internal development team, building production applications.</small>
## Opinions
"*[...] 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.*"
<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>
---
"*Im over the moon excited about **FastAPI**. Its so fun!*"
<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>
---
"*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.*"
<div style="text-align: right; margin-right: 10%;">Timothy Crosley - <strong><a href="http://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>
---
## Requirements
@@ -57,7 +82,7 @@ FastAPI stands on the shoulders of giants:
$ pip install fastapi
```
You will also need an ASGI server, for production such as <a href="http://www.uvicorn.org" target="_blank">uvicorn</a>.
You will also need an ASGI server, for production such as <a href="http://www.uvicorn.org" target="_blank">Uvicorn</a> or <a href="https://gitlab.com/pgjones/hypercorn" target="_blank">Hypercorn</a>.
```bash
$ pip install uvicorn
@@ -65,6 +90,8 @@ $ pip install uvicorn
## Example
### Create it
* Create a file `main.py` with:
```Python
@@ -72,50 +99,79 @@ from fastapi import FastAPI
app = FastAPI()
@app.get('/')
@app.get("/")
def read_root():
return {'hello': 'world'}
return {"Hello": "World"}
@app.get("/items/{item_id}")
def read_item(item_id: int, q: str = None):
return {"item_id": item_id, "q": q}
```
<details markdown="1">
<summary>Or use <code>async def</code>...</summary>
Or if your code uses `async` / `await`, use `async def`:
If your code uses `async` / `await`, use `async def`:
```Python hl_lines="6"
```Python hl_lines="7 12"
from fastapi import FastAPI
app = FastAPI()
@app.get('/')
@app.get("/")
async def read_root():
return {'hello': 'world'}
return {"Hello": "World"}
@app.get("/items/{item_id}")
async def read_item(item_id: int, q: str = None):
return {"item_id": item_id, "q": q}
```
!!! note
If you don't know, check the section about [`async` and `await` in the docs](async.md).
**Note**:
If 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>.
</details>
* Run the server with:
### Run it
Run the server with:
```bash
uvicorn main:app --debug
uvicorn main:app --reload
```
!!! note
The command `uvicorn main:app` refers to:
<details markdown="1">
<summary>About the command <code>uvicorn main:app --reload</code>...</summary>
* `main`: the file `main.py` (the Python "module").
* `app`: the object created inside of `main.py` with the line `app = FastAPI()`.
* `--debug`: make the server restart after code changes. Only do this for development.
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 <a href="http://127.0.0.1:8000" target="_blank">http://127.0.0.1:8000</a>.
Open your browser at <a href="http://127.0.0.1:8000/items/5?q=somequery" target="_blank">http://127.0.0.1:8000/items/5?q=somequery</a>.
You will see the JSON response as:
```JSON
{"hello": "world"}
{"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 <a href="http://127.0.0.1:8000/docs" target="_blank">http://127.0.0.1:8000/docs</a>.
@@ -135,14 +191,12 @@ You will see the alternative automatic documentation (provided by <a href="https
## Example upgrade
Now modify the file `main.py` to include:
Now modify the file `main.py` to receive a body from a `PUT` request.
* a path parameter `item_id`.
* a body, declared using standard Python types (thanks to Pydantic).
* an optional query parameter `q`.
Declare the body using standard Python types, thanks to Pydantic.
```Python hl_lines="2 7 8 9 10 19"
```Python hl_lines="2 7 8 9 10 24"
from fastapi import FastAPI
from pydantic import BaseModel
@@ -155,23 +209,28 @@ class Item(BaseModel):
is_offer: bool = None
@app.get('/')
async def read_root():
return {'hello': 'world'}
@app.get("/")
def read_root():
return {"Hello": "World"}
@app.post('/items/{item_id}')
async def create_item(item_id: int, item: Item, q: str = None):
return {"item_name": item.name, "item_id": item_id, "query": q}
@app.get("/items/{item_id}")
def read_item(item_id: int, q: str = None):
return {"item_id": item_id, "q": q}
@app.put("/items/{item_id}")
def update_item(item_id: int, item: Item):
return {"item_name": item.name, "item_id": item_id}
```
The server should reload automatically (because you added `--debug` to the `uvicorn` command above).
The server should reload automatically (because you added `--reload` to the `uvicorn` command above).
### Interactive API docs upgrade
Now go to <a href="http://127.0.0.1:8000/docs" target="_blank">http://127.0.0.1:8000/docs</a>.
* The interactive API documentation will be automatically updated, including the new query, and body:
* The interactive API documentation will be automatically updated, including the new body:
![Swagger UI](https://fastapi.tiangolo.com/img/index/index-03-swagger-02.png)
@@ -223,7 +282,7 @@ item: Item
* Validation of data:
* Automatic and clear errors when the data is invalid.
* Validation even for deeply nested JSON objects.
* <abbr title="also known as: serialization, parsing, marshalling">Conversion</abbr> of input data: coming from the network, to Python data and types. Reading from:
* <abbr title="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.
@@ -245,20 +304,20 @@ item: Item
Coming back to the previous code example, **FastAPI** will:
* Validate that there is an `item_id` in the path.
* Validate that the `item_id` is of type `int`.
* Validate that there is an `item_id` in the path for `GET` and `PUT` requests.
* Validate that the `item_id` is of type `int` for `GET` and `PUT` requests.
* If it is not, the client will see a useful, clear error.
* Check if there is an optional query parameter named `q` (as in `http://127.0.0.1:8000/items/foo?q=somequery`).
* 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.
* As the `q` parameter is declared with `= None`, it is optional.
* Without the `None` it would be required (as is the body).
* Read the body as JSON:
* Without the `None` it would be required (as is the body in the case with `PUT`).
* For `PUT` requests to `/items/{item_id}`, Read the body as JSON:
* Check that it has a required attribute `name` that should be a `str`.
* Check that is has a required attribute `price` that has to be a `float`.
* Check that it has an optional attribute `is_offer`, that should be a `bool`, if present.
* All this would also work for deeply nested JSON objects.
* Convert from and to JSON automatically.
* Document everything as an OpenAPI schema, that can be used by:
* Interactive documentation sytems.
* Document everything with OpenAPI, that can be used by:
* Interactive documentation systems.
* Automatic client code generation systems, for many languages.
* Provide 2 interactive documentation web interfaces directly.
@@ -270,7 +329,7 @@ We just scratched the surface, but you already get the idea of how it all works.
Try changing the line with:
```Python
return {"item_name": item.name, "item_id": item_id, "query": q}
return {"item_name": item.name, "item_id": item_id}
```
...from:
@@ -290,12 +349,12 @@ Try changing the line with:
![editor support](https://fastapi.tiangolo.com/img/vscode-completion.png)
For a more complete example including more features, [see the tutorial - user guide](tutorial/intro/).
For a more complete example including more features, see the <a href="https://fastapi.tiangolo.com/tutorial/intro/">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 constrains** as `maximum_length` or `regex`.
* How to set **validation constraints** as `maximum_length` or `regex`.
* A very powerful and easy to use **<abbr title="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).
@@ -308,6 +367,11 @@ For a more complete example including more features, [see the tutorial - user gu
* ...and more.
## Performance
Independent 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" 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 <a href="https://fastapi.tiangolo.com/benchmarks/" target="_blank">Benchmarks</a>.
## Optional Dependencies
@@ -332,7 +396,7 @@ Used by FastAPI / Starlette:
* <a href="http://www.uvicorn.org" target="_blank"><code>uvicorn</code></a> - for the server that loads and serves your application.
You can install all of these with `pip3 install fastapi[full]`.
You can install all of these with `pip3 install fastapi[all]`.
## License

View File

@@ -1,15 +0,0 @@
[build-system]
requires = ["flit"]
build-backend = "flit.buildapi"
[tool.flit.metadata]
module = "fastapi"
author = "Sebastián Ramírez"
author-email = "tiangolo@gmail.com"
home-page = "https://github.com/tiangolo/fastapi"
classifiers = ["License :: OSI Approved :: MIT License"]
requires = [
"starlette >=0.9.7",
"pydantic >=0.16"
]
requires-python = ">=3.6"

410
docs/alternatives.md Normal file
View File

@@ -0,0 +1,410 @@
What inspired **FastAPI**, how it compares to other alternatives and what it learned from them.
## Intro
**FastAPI** wouldn't exist if not for the previous work of others.
There have been many tools created before that have helped inspire its creation.
I have been avoiding the creation of a new framework for several years. First I tried to solve all the features covered by **FastAPI** using many different frameworks, plug-ins, and tools.
But at some point, there was no other option than creating something that provided all these features, taking the best ideas from previous tools, and combining them in the best way possible, using language features that weren't even available before (Python 3.6+ type hints).
## Previous tools
### <a href="https://www.djangoproject.com/" target="_blank">Django</a>
It's the most popular Python framework and is widely trusted. It is used to build systems like Instagram.
It's relatively tightly coupled with relational databases (like MySQL or PostgreSQL), so, having a NoSQL database (like Couchbase, MongoDB, Cassandra, etc) as the main store engine is not very easy.
It was created to generate the HTML in the backend, not to create APIs used by a modern frontend (like React, Vue.js and Angular) or by other systems (like <abbr title="Internet of Things">IoT</abbr> devices) communicating with it.
### <a href="https://www.django-rest-framework.org/" target="_blank">Django REST Framework</a>
Django REST framework was created to be a flexible toolkit for building Web APIs using Django underneath, to improve its API capabilities.
It is used by many companies including Mozilla, Red Hat and Eventbrite.
It was one of the first examples of **automatic API documentation**, and this was specifically one of the first ideas that inspired "the search for" **FastAPI**.
!!! note
Django REST Framework was created by Tom Christie. The same creator of Starlette and Uvicorn, on which **FastAPI** is based.
!!! check "Inspired **FastAPI** to"
Have an automatic API documentation web user interface.
### <a href="http://flask.pocoo.org/" target="_blank">Flask</a>
Flask is a "microframework", it doesn't include database integrations nor many of the things that come by default in Django.
This simplicity and flexibility allow doing things like using NoSQL databases as the main data storage system.
As it is very simple, it's relatively intuitive to learn, although the documentation gets somewhat technical at some points.
It is also commonly used for other applications that don't necessarily need a database, user management, or any of the many features that come pre-built in Django. Although many of these features can be added with plug-ins.
This decoupling of parts, and being a "microframework" that could be extended to cover exactly what is needed was a key feature that I wanted to keep.
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"
Be a micro-framework. Making it easy to mix and match the tools and parts needed.
Have a simple and easy to use routing system.
### <a href="http://docs.python-requests.org" target="_blank">Requests</a>
**FastAPI** is not actually an alternative to **Requests**. Their scope is very different.
It would actually be common to use Requests *inside* of a FastAPI application.
But still, FastAPI got quite some inspiration from Requests.
**Requests** is a library to *interact* with APIs (as a client), while **FastAPI** is a library to *build* APIs (as a server).
They are, more or less, at opposite ends, complementing each other.
Requests has a very simple and intuitive design, it's very easy to use, with sensible defaults. But at the same time, it's very powerful and customizable.
That's why, as said in the official website:
> Requests is one of the most downloaded Python packages of all time
The way you use it is very simple. For example, to do a `GET` request, you would write:
```Python
response = requests.get("http://example.com/some/url")
```
The FastAPI counterpart API path operation could look like:
```Python hl_lines="1"
@app.get("/some/url")
def read_url():
return {"message": "Hello World"}
```
See the similarities in `requests.get(...)` and `@app.get(...)`.
!!! check "Inspired **FastAPI** to"
* Have a simple and intuitive API.
* Use HTTP method names (operations) directly, in a straightforward and intuitive way.
* Have sensible defaults, but powerful customizations.
### <a href="https://swagger.io/" target="_blank">Swagger</a> / <a href="https://github.com/OAI/OpenAPI-Specification/" target="_blank">OpenAPI</a>
The main feature I wanted from Django REST Framework was the automatic API documentation.
Then I found that there was a standard to document APIs, using JSON (or YAML, an extension of JSON) called Swagger.
And there was a web user interface for Swagger APIs already created. So, being able to generate Swagger documentation for an API would allow using this web user interface automatically.
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"
Adopt and use an open standard for API specifications, instead of a custom schema.
And integrate standards-based user interface tools:
* <a href="https://github.com/swagger-api/swagger-ui" target="_blank">Swagger UI</a>
* <a href="https://github.com/Rebilly/ReDoc" target="_blank">ReDoc</a>
These two were chosen for being fairly popular and stable, but doing a quick search, you could find dozens of additional alternative user interfaces for OpenAPI (that you can use with **FastAPI**).
### Flask REST frameworks
There are several Flask REST frameworks, but after investing the time and work into investigating them, I found that many are discontinued or abandoned, with several standing issues that made them unfit.
### <a href="https://marshmallow.readthedocs.io/en/3.0/" target="_blank">Marshmallow</a>
One of the main features needed by API systems is data "<abbr title="also called marshalling, conversion">serialization</abbr>" which is taking data from the code (Python) and converting it into something that can be sent through the network. For example, converting an object containing data from a database into a JSON object. Converting `datetime` objects into strings, etc.
Another big feature needed by APIs is data validation, making sure that the data is valid, given certain parameters. For example, that some field is an `int`, and not some random string. This is especially useful for incoming data.
Without a data validation system, you would have to do all the checks by hand, in code.
These features are what Marshmallow was built to provide. It is a great library, and I have used it a lot before.
But it was created before there existed Python type hints. So, to define every <abbr title="the definition of how data should be formed">schema</abbr> you need to use specific utils and classes provided by Marshmallow.
!!! check "Inspired **FastAPI** to"
Use code to define "schemas" that provide data types and validation, automatically.
### <a href="https://webargs.readthedocs.io/en/latest/" target="_blank">Webargs</a>
Another big feature required by APIs is <abbr title="reading and converting to Python data">parsing</abbr> data from incoming requests.
Webargs is a tool that was made to provide that on top of several frameworks, including Flask.
It uses Marshmallow underneath to do the data validation. And it was created by the same guys.
It's a great tool and I have used it a lot too, before having **FastAPI**.
!!! info
Webargs was created by the same Marshmallow guys.
!!! check "Inspired **FastAPI** to"
Have automatic validation of incoming request data.
### <a href="https://apispec.readthedocs.io/en/stable/" target="_blank">APISpec</a>
Marshmallow and Webargs provide validation, parsing and serialization as plug-ins.
But documentation is still missing. Then APISpec was created.
It is a plug-in for many frameworks (and there's a plug-in for Starlette too).
The way it works is that you write the definition of the schema using YAML format inside the docstring of each function handling a route.
And it generates OpenAPI schemas.
That's how it works in Flask, Starlette, Responder, etc.
But then, we have again the problem of having a micro-syntax, inside of a Python string (a big YAML).
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
APISpec was created by the same Marshmallow guys.
!!! check "Inspired **FastAPI** to"
Support the open standard for APIs, OpenAPI.
### <a href="https://flask-apispec.readthedocs.io/en/latest/" target="_blank">Flask-apispec</a>
It's a Flask plug-in, that ties together Webargs, Marshmallow and APISpec.
It uses the information from Webargs and Marshmallow to automatically generate OpenAPI schemas, using APISpec.
It's a great tool, very under-rated. It should be way more popular than many Flask plug-ins out there. It might be due to its documentation being too concise and abstract.
This solved having to write YAML (another syntax) inside of Python docstrings.
This combination of Flask, Flask-apispec with Marshmallow and Webargs was my favorite backend stack until building **FastAPI**.
Using it led to the creation of several Flask full-stack generators. These are the main stack I (and several external teams) have been using up to now:
* <a href="https://github.com/tiangolo/full-stack" target="_blank">https://github.com/tiangolo/full-stack</a>
* <a href="https://github.com/tiangolo/full-stack-flask-couchbase" target="_blank">https://github.com/tiangolo/full-stack-flask-couchbase</a>
* <a href="https://github.com/tiangolo/full-stack-flask-couchdb" target="_blank">https://github.com/tiangolo/full-stack-flask-couchdb</a>
And these same full-stack generators were the base of the <a href="/project-generation/" target="_blank">**FastAPI** project generator</a>.
!!! info
Flask-apispec was created by the same Marshmallow guys.
!!! check "Inspired **FastAPI** to"
Generate the OpenAPI schema automatically, from the same code that defines serialization and validation.
### <a href="https://nestjs.com/" target="_blank">NestJS</a> (and <a href="https://angular.io/" target="_blank">Angular</a>)
This isn't even Python, NestJS is a JavaScript (TypeScript) NodeJS framework inspired by Angular.
It achieves something somewhat similar to what can be done with Flask-apispec.
It has an integrated dependency injection system, inspired by Angular two. It requires pre-registering the "injectables" (like all the other dependency injection systems I know), so, it adds to the verbosity and code repetition.
As the parameters are described with TypeScript types (similar to Python type hints), editor support is quite good.
But as TypeScript data is not preserved after compilation to JavaScript, it cannot rely on the types to define validation, serialization and documentation at the same time. Due to this and some design decisions, to get validation, serialization and automatic schema generation, it's needed to add decorators in many places. So, it becomes quite verbose.
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"
Use Python types to have great editor support.
Have a powerful dependency injection system. Find a way to minimize code repetition.
### <a href="https://sanic.readthedocs.io/en/latest/" target="_blank">Sanic</a>
It was one of the first extremely fast Python frameworks based on `asyncio`. It was made to be very similar to Flask.
!!! note "Technical Details"
It used <a href="https://github.com/MagicStack/uvloop" target="_blank">`uvloop`</a> instead of the default Python `asyncio` loop. That's what made it so fast.
It <a href="https://github.com/huge-success/sanic/issues/761" target="_blank">still doesn't implement the ASGI spec for Python asynchronous web development</a>, but it clearly inspired Uvicorn and Starlette, that are currently faster than Sanic in open benchmarks.
!!! check "Inspired **FastAPI** to"
Find a way to have a crazy performance.
That's why **FastAPI** is based on Starlette, as it is the fastest framework available (tested by third-party benchmarks).
### <a href="https://falconframework.org/" target="_blank">Falcon</a>
Falcon is another high performance Python framework, it is designed to be minimal, and work as the foundation of other frameworks like Hug.
It uses the previous standard for Python web frameworks (WSGI) which is synchronous, so it can't handle Websockets and other use cases. Nevertheless, it also has a very good performance.
It is designed to have functions that receive two parameters, one "request" and one "response". Then you "read" parts from the request, and "write" parts to the response. Because of this design, it is not possible to declare request parameters and bodies with standard Python type hints as function parameters.
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"
Find ways to get great performance.
### <a href="https://moltenframework.com/" target="_blank">Molten</a>
I discovered Molten in the first stages of building **FastAPI**. And it has quite similar ideas:
* Based on Python type hints.
* Validation and documentation from these types.
* Dependency Injection system.
It doesn't use a data validation, serialization and documentation third-party library like Pydantic, it has its own. So, these data type definitions would not be reusable as easily.
It requires a little bit more verbose configurations. And as it is based on WSGI (instead of ASGI), it is not designed to take advantage of the high-performance provided by tools like Uvicorn, Starlette and Sanic.
The dependency injection system requires pre-registration of the dependencies and the dependencies are solved based on the declared types. So, it's not possible to declare more than one "component" that provides a certain type.
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"
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.
This actually inspired updating parts of Pydantic, to support the same validation declaration style (all this functionality is now already available in Pydantic).
### <a href="http://www.hug.rest/" target="_blank">Hug</a>
Hug was one of the first frameworks to implement the declaration of API parameter types using Python type hints. This was a great idea that inspired other tools to do the same.
It used custom types in its declarations instead of standard Python types, but it was still a huge step forward.
It also was one of the first frameworks to generate a custom schema declaring the whole API in JSON.
It was not based on a standard like OpenAPI and JSON Schema. So it wouldn't be straightforward to integrate it with other tools, like Swagger UI. But again, it was a very innovative idea.
It has an interesting, uncommon feature: using the same framework, it's possible to create APIs and also CLIs.
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
Hug was created by Timothy Crosley, the same creator of <a href="https://github.com/timothycrosley/isort" target="_blank">`isort`</a>, a great tool to automatically sort imports in Python files.
!!! check "Ideas inspired in **FastAPI**"
Hug inspired parts of APIStar, and was one of the tools I found most promising, alongside APIStar.
Hug helped inspiring **FastAPI** to use Python type hints to declare parameters, and to generate a schema defining the API automatically.
### <a href="https://github.com/encode/apistar" target="_blank">APIStar</a> (<= 0.5)
Right before deciding to build **FastAPI** I found **APIStar** server. It had almost everything I was looking for and had a great design.
It was one of the first implementations of a framework using Python type hints to declare parameters and requests that I ever saw (before NestJS and Molten). I found it more or less at the same time as Hug. But APIStar used the OpenAPI standard.
It had automatic data validation, data serialization and OpenAPI schema generation based on the same type hints in several places.
Body schema definitions didn't use the same Python type hints like Pydantic, it was a bit more similar to Marshmallow, so, editor support wouldn't be as good, but still, APIStar was the best available option.
It had the best performance benchmarks at the time (only surpassed by Starlette).
At first, it didn't have an automatic API documentation web UI, but I knew I could add Swagger UI to it.
It had a dependency injection system. It required pre-registration of components, as other tools discussed above. But still, it was a great feature.
I was never able to use it in a full project, as it didn't have security integration, so, I couldn't replace all the features I was having with the full-stack generators based on Flask-apispec. I had in my backlog of projects to create a pull request adding that functionality.
But then, the project's focus shifted.
It was no longer an API web framework, as the creator needed to focus on Starlette.
Now APIStar is a set of tools to validate OpenAPI specifications, not a web framework.
!!! info
APIStar was created by Tom Christie. The same guy that created:
* Django REST Framework
* Starlette (in which **FastAPI** is based)
* Uvicorn (used by Starlette and **FastAPI**)
!!! check "Inspired **FastAPI** to"
Exist.
The idea of declaring multiple things (data validation, serialization and documentation) with the same Python types, that at the same time provided great editor support, was something I considered a brilliant idea.
And after searching for a long time for a similar framework and testing many different alternatives, APIStar was the best option available.
Then APIStar stopped to exist as a server and Starlette was created, and was a new better foundation for such a system. That was the final inspiration to build **FastAPI**.
I consider **FastAPI** a "spiritual successor" to APIStar, while improving and increasing the features, typing system, and other parts, based on the learnings from all these previous tools.
## Used by **FastAPI**
### <a href="https://pydantic-docs.helpmanual.io/" target="_blank">Pydantic</a>
Pydantic is a library to define data validation, serialization and documentation (using JSON Schema) based on Python type hints.
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"
Handle all the data validation, data serialization and automatic model documentation (based on JSON Schema).
**FastAPI** then takes that JSON Schema data and puts it in OpenAPI, apart from all the other things it does.
### <a href="https://www.starlette.io/" target="_blank">Starlette</a>
Starlette is a lightweight <abbr title="The new standard for building asynchronous Python web">ASGI</abbr> framework/toolkit, which is ideal for building high-performance asyncio services.
It is very simple and intuitive. It's designed to be easily extensible, and have modular components.
It has:
* Seriously impressive performance.
* WebSocket support.
* GraphQL support.
* In-process background tasks.
* Startup and shutdown events.
* Test client built on requests.
* CORS, GZip, Static Files, Streaming responses.
* Session and Cookie support.
* 100% test coverage.
* 100% type annotated codebase.
* Zero hard dependencies.
Starlette is currently the fastest Python framework tested. Only surpassed by Uvicorn, which is not a framework, but a server.
Starlette provides all the basic web microframework functionality.
But it doesn't provide automatic data validation, serialization or documentation.
That's one of the main things that **FastAPI** adds on top, all based on Python type hints (using Pydantic). That, plus the dependency injection system, security utilities, OpenAPI schema generation, etc.
!!! note "Technical Details"
ASGI is a new "standard" being developed by Django core team members. It is still not a "Python standard" (a PEP), although they are in the process of doing that.
Nevertheless, it is already being used as a "standard" by several tools. This greatly improves interoperability, as you could switch Uvicorn for any other ASGI server (like Daphne or Hypercorn), or you could add ASGI compatible tools, like `python-socketio`.
!!! check "**FastAPI** uses it to"
Handle all the core web parts. Adding features on top.
The class `FastAPI` itself inherits directly from the class `Starlette`.
So, anything that you can do with Starlette, you can do it directly with **FastAPI**, as it is basically Starlette on steroids.
### <a href="https://www.uvicorn.org/" target="_blank">Uvicorn</a>
Uvicorn is a lightning-fast ASGI server, built on uvloop and httptools.
It is not a web framework, but a server. For example, it doesn't provide tools for routing by paths. That's something that a framework like Starlette (or **FastAPI**) would provide on top.
It is the recommended server for Starlette and **FastAPI**.
!!! check "**FastAPI** recommends it as"
The main web server to run **FastAPI** applications.
You can combine it with Gunicorn, to have an asynchronous multi-process server.
Check more details in the <a href="/deployment/" target="_blank">Deployment</a> section.
## Benchmarks and speed
To understand, compare, and see the difference between Uvicorn, Starlette and FastAPI, check the section about [Benchmarks](/benchmarks/).

View File

@@ -329,7 +329,7 @@ So, about the egg and the chicken, how do you call the first `async` function?
If you are working with **FastAPI** you don't have to worry about that, because that "first" function will be your path operation function, and FastAPI will know how to do the right thing.
But if you want to use `async` / `await` without FastAPI, <a href="https://docs.python.org/3/library/asyncio-task.html#coroutine" target="_blank">check the official Python docs</a>
But if you want to use `async` / `await` without FastAPI, <a href="https://docs.python.org/3/library/asyncio-task.html#coroutine" target="_blank">check the official Python docs</a>.
### Other forms of asynchronous code
@@ -362,3 +362,43 @@ Let's see the same phrase from above:
That should make more sense now.
All that is what powers FastAPI (through Starlette) and what makes it have such an impressive performance.
## Very Technical Details
!!! warning
You can probably skip this.
These are very technical details of how **FastAPI** works underneath.
If you have quite some technical knowledge (co-routines, threads, blocking, etc) and are curious about how FastAPI handles `async def` vs normal `def`, go ahead.
### Path operation functions
When you declare a *path operation function* with normal `def` instead of `async def`, it is run in an external threadpool that is then awaited, instead of being called directly (as it would block the server).
If you are coming from another async framework that does not work in the way described above and you are used to define trivial compute-only *path operation functions* with plain `def` for a tiny performance gain (about 100 nanoseconds), please note that in **FastAPI** the effect would be quite opposite. In these cases, it's better to use `async def` unless your *path operation functions* use code that performs blocking <abbr title="Input/Output: disk reading or writing, network communications.">IO</abbr>.
Still, in both situations, chances are that **FastAPI** will <a href="https://fastapi.tiangolo.com/#performance" target="_blank">still be faster</a> than (or at least comparable to) your previous framework.
### Dependencies
The same applies for dependencies. If a dependency is a standard `def` function instead of `async def`, it is run in the external threadpool.
### Sub-dependencies
You can have multiple dependencies and sub-dependencies requiring each other (as parameters of the function definitions), some of them might be created with `async def` and some with normal `def`. It would still work, and the ones created with normal `def` would be called on an external thread instead of being "awaited".
### Other utility functions
Any other utility function that you call directly can be created with normal `def` or `async def` and FastAPI won't affect the way you call it.
This is in contrast to the functions that FastAPI calls for you: *path operation functions* and dependencies.
If your utility function is a normal function with `def`, it will be called directly (as you write it in your code), not in a threadpool, if the function is created with `async def` then you should await for that function when you call it in your code.
---
Again, these are very technical details that would probably be useful if you came searching for them.
Otherwise, you should be good with the guidelines from the section above: <a href="#in-a-hurry">In a hurry?</a>.

32
docs/benchmarks.md Normal file
View File

@@ -0,0 +1,32 @@
Independent 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" target="_blank">one of the fastest Python frameworks available</a>, only below Starlette and Uvicorn themselves (used internally by FastAPI). (*)
But when checking benchmarks and comparisons you should have the following in mind.
## Benchmarks and speed
When you check the benchmarks, it is common to see several tools of different types compared as equivalent.
Specifically, to see Uvicorn, Starlette and FastAPI compared together (among many other tools).
The simplest the problem solved by the tool, the better performance it will get. And most of the benchmarks don't test the additional features provided by the tool.
The hierarchy is like:
* **Uvicorn**: an ASGI server
* **Starlette**: (uses Uvicorn) a web microframework
* **FastAPI**: (uses Starlette) an API microframework with several additional features for building APIs, with data validation, etc.
* **Uvicorn**:
* Will have the best performance, as it doesn't have much extra code apart from the server itself.
* You wouldn't write an application in Uvicorn directly. That would mean that your code would have to include more or less, at least, all the code provided by Starlette (or **FastAPI**). And if you did that, your final application would have the same overhead as having used a framework and minimizing your app code and bugs.
* If you are comparing Uvicorn, compare it against Daphne, Hypercorn, uWSGI, etc. Application servers.
* **Starlette**:
* Will have the next best performance, after Uvicorn. In fact, Starlette uses Uvicorn to run. So, it probably can only get "slower" than Uvicorn by having to execute more code.
* But it provides you the tools to build simple web applications, with routing based on paths, etc.
* If you are comparing Starlette, compare it against Sanic, Flask, Django, etc. Web frameworks (or microframeworks).
* **FastAPI**:
* The same way that Starlette uses Uvicorn and cannot be faster than it, **FastAPI** uses Starlette, so it cannot be faster than it.
* FastAPI provides more features on top of Starlette. Features that you almost always need when building APIs, like data validation and serialization. And by using it, you get automatic documentation for free (the automatic documentation doesn't even add overhead to running applications, it is generated on startup).
* If you didn't use FastAPI and used Starlette directly (or another tool, like Sanic, Flask, Responder, etc) you would have to implement all the data validation and serialization yourself. So, your final application would still have the same overhead as if it was built using FastAPI. And in many cases, this data validation and serialization is the biggest amount of code written in applications.
* So, by using FastAPI you are saving development time, bugs, lines of code, and you would probably get the same performance (or better) you would if you didn't use it (as you would have to implement it all in your code).
* If you are comparing FastAPI, compare it against a web application framework (or set of tools) that provides data validation, serialization and documentation, like Flask-apispec, NestJS, Molten, etc. Frameworks with integrated automatic data validation, serialization and documentation.

123
docs/contributing.md Normal file
View File

@@ -0,0 +1,123 @@
First, you might want to see the basic ways to <a href="https://fastapi.tiangolo.com/help-fastapi/" target="_blank">help FastAPI and get help</a>.
## Developing
If you already cloned the repository and you know that you need to deep dive in the code, here are some guidelines to set up your environment.
### Pipenv
If you are using <a href="https://pipenv.readthedocs.io/en/latest/" target="_blank">Pipenv</a>, you can create a virtual environment and install the packages with:
```bash
pipenv install --dev
```
Then you can activate that virtual environment with:
```bash
pipenv shell
```
### No Pipenv
If you are not using Pipenv, you can create a virtual environment with your preferred tool, and install the packages listed in the file `Pipfile`.
### Flit
**FastAPI** uses <a href="https://flit.readthedocs.io/en/latest/index.html" target="_blank">Flit</a> to build, package and publish the project.
If you installed the development dependencies with one of the methods above, you already have the `flit` command.
To install your local version of FastAPI as a package in your local environment, run:
```bash
flit install --symlink
```
It will install your local FastAPI in your local environment.
#### 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.
And if you update that local FastAPI source code, as it is installed with `--symlink`, 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.
### Format
There is a script that you can run that will format and clean all your code:
```bash
bash scripts/lint.sh
```
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:
```bash
flit install --symlink
```
### Docs
The documentation uses <a href="https://www.mkdocs.org/" target="_blank">MkDocs</a>.
All the documentation is in Markdown format in the directory `./docs`.
Many of the tutorials have blocks of code.
In most of the cases, these blocks of code are actual complete applications that can be run as is.
In fact, those blocks of code are not written inside the Markdown, they are Python files in the `./docs/src/` directory.
And those Python files are included/injected in the documentation when generating the site.
#### Docs for tests
Most of the tests actually run against the example source files in the documentation.
This helps making sure that:
* The documentation is up to date.
* The documentation examples can be run as is.
* Most of the features are covered by the documentation, ensured by the coverage tests.
During local development, there is a script that builds the site and checks for any changes, live-reloading:
```bash
bash scripts/docs-live.sh
```
It will serve the documentation on `http://0.0.0.0:8008`.
That way, you can edit the documentation/source files and see the changes live.
#### Apps and docs at the same time
And if you run the examples with, e.g.:
```bash
uvicorn tutorial001:app --reload
```
as Uvicorn by default will use the port `8000`, the documentation on port `8008` won't clash.
### Tests
There is a script that you can run locally to test all the code and generate coverage reports in HTML:
```bash
bash scripts/test-cov-html.sh
```
This command generates a directory `./htmlcov/`, if you open the file `./htmlcov/index.html` in your browser, you can explore interactively the regions of code that are covered by the tests, and notice if there is any region missing.

View File

@@ -1 +1,274 @@
Coming soon...
You can use <a href="https://www.docker.com/" target="_blank">**Docker**</a> for deployment. It has several advantages like security, replicability, development simplicity, etc.
In this section you'll see instructions and links to guides to know how to:
* Make your **FastAPI** application a Docker image/container with maximum performance. In about **5 min**.
* (Optionally) understand what you, as a developer, need to know about HTTPS.
* Set up a Docker Swarm mode cluster with automatic HTTPS, even on a simple $5 USD/month server. In about **20 min**.
* Generate and deploy a full **FastAPI** application, using your Docker Swarm cluster, with HTTPS, etc. In about **10 min**.
---
You can also easily use **FastAPI** in a standard server directly too (without Docker).
## Docker
If you are using Docker, you can use the official Docker image:
### <a href="https://github.com/tiangolo/uvicorn-gunicorn-fastapi-docker" target="_blank">tiangolo/uvicorn-gunicorn-fastapi</a>
This image has an "auto-tuning" mechanism included, so that you can just add your code and get very high performance automatically. And without making sacrifices.
But you can still change and update all the configurations with environment variables or configuration files.
!!! tip
To see all the configurations and options, go to the Docker image page: <a href="https://github.com/tiangolo/uvicorn-gunicorn-fastapi-docker" target="_blank">tiangolo/uvicorn-gunicorn-fastapi</a>.
### Create a `Dockerfile`
* Go to your project directory.
* Create a `Dockerfile` with:
```Dockerfile
FROM tiangolo/uvicorn-gunicorn-fastapi:python3.7
COPY ./app /app
```
#### Bigger Applications
If you followed the section about creating <a href="https://fastapi.tiangolo.com/tutorial/bigger-applications/" target="_blank">Bigger Applications with Multiple Files
</a>, your `Dockerfile` might instead look like:
```Dockerfile
FROM tiangolo/uvicorn-gunicorn-fastapi:python3.7
COPY ./app /app/app
```
#### Raspberry Pi and other architectures
If you are running Docker in a Raspberry Pi (that has an ARM processor) or any other architecture, you can create a `Dockerfile` from scratch, based on a Python base image (that is multi-architecture) and use Uvicorn alone.
In this case, your `Dockerfile` could look like:
```Dockerfile
FROM python:3.7
RUN pip install fastapi uvicorn
EXPOSE 80
COPY ./app /app
CMD ["uvicorn", "app.main:app", "--host", "0.0.0.0", "--port", "80"]
```
### Create the **FastAPI** Code
* Create an `app` directory and enter in it.
* Create a `main.py` file with:
```Python
from fastapi import FastAPI
app = FastAPI()
@app.get("/")
def read_root():
return {"Hello": "World"}
@app.get("/items/{item_id}")
def read_item(item_id: int, q: str = None):
return {"item_id": item_id, "q": q}
```
* You should now have a directory structure like:
```
.
├── app
│ └── main.py
└── Dockerfile
```
### Build the Docker image
* Go to the project directory (in where your `Dockerfile` is, containing your `app` directory).
* Build your FastAPI image:
```bash
docker build -t myimage .
```
### Start the Docker container
* Run a container based on your image:
```bash
docker run -d --name mycontainer -p 80:80 myimage
```
Now you have an optimized FastAPI server in a Docker container. Auto-tuned for your current server (and number of CPU cores).
### Check it
You should be able to check it in your Docker container's URL, for example: <a href="http://192.168.99.100/items/5?q=somequery" target="_blank">http://192.168.99.100/items/5?q=somequery</a> or <a href="http://127.0.0.1/items/5?q=somequery" target="_blank">http://127.0.0.1/items/5?q=somequery</a> (or equivalent, using your Docker host).
You will see something like:
```JSON
{"item_id": 5, "q": "somequery"}
```
### Interactive API docs
Now you can go to <a href="http://192.168.99.100/docs" target="_blank">http://192.168.99.100/docs</a> or <a href="http://127.0.0.1/docs" target="_blank">http://127.0.0.1/docs</a> (or equivalent, using your Docker host).
You will see the automatic interactive API documentation (provided by <a href="https://github.com/swagger-api/swagger-ui" target="_blank">Swagger UI</a>):
![Swagger UI](https://fastapi.tiangolo.com/img/index/index-01-swagger-ui-simple.png)
### Alternative API docs
And you can also go to <a href="http://192.168.99.100/redoc" target="_blank">http://192.168.99.100/redoc</a> or <a href="http://127.0.0.1/redoc" target="_blank">http://127.0.0.1/redoc</a> (or equivalent, using your Docker host).
You will see the alternative automatic documentation (provided by <a href="https://github.com/Rebilly/ReDoc" target="_blank">ReDoc</a>):
![ReDoc](https://fastapi.tiangolo.com/img/index/index-02-redoc-simple.png)
## HTTPS
### About HTTPS
It is easy to assume that HTTPS is something that is just "enabled" or not.
But it is way more complex than that.
!!! tip
If you are in a hurry or don't care, continue with the next section for step by step instructions to set everything up.
To learn the basics of HTTPS, from a consumer perspective, check <a href="https://howhttps.works/" target="_blank">https://howhttps.works/</a>.
Now, from a developer's perspective, here are several things to have in mind while thinking about HTTPS:
* For HTTPS, the server needs to have "certificates" generated by a third party.
* Those certificates are actually acquired from the third-party, not "generated".
* Certificates have a lifetime.
* They expire.
* And then they need to be renewed, acquired again from the third party.
* The encryption of the connection happens at the TCP level.
* That's one layer below HTTP.
* So, the certificate and encryption handling is done before HTTP.
* TCP doesn't know about "domains". Only about IP addresses.
* The information about the specific domain requested goes in the HTTP data.
* The HTTPS certificates "certificate" a certain domain, but the protocol and encryption happen at the TCP level, before knowing which domain is being dealt with.
* By default, that would mean that you can only have one HTTPS certificate per IP address.
* No matter how big is your server and how small each application you have there might be. But...
* There's an extension to the TLS protocol (the one handling the encryption at the TCP level, before HTTP) called <a href="https://en.wikipedia.org/wiki/Server_Name_Indication" target="_blank"><abbr title="Server Name Indication">SNI</abbr></a>.
* This SNI extension allows one single server (with a single IP address) to have several HTTPS certificates and server multiple HTTPS domains/applications.
* For this to work, a single component (program) running in the server, listening in the public IP address, must have all the HTTPS certificates in the server.
* After having a secure connection, the communication protocol is the same HTTP.
* It goes encrypted, but the encrypted contents are the same HTTP protocol.
It is a common practice to have one program/HTTP server running in the server (the machine, host, etc) and managing all the HTTPS parts, sending the decrypted HTTP requests to the actual HTTP application running in the same server (the **FastAPI** application, in this case), take the HTTP response from the application, encrypt it using the appropriate certificate and sending it back to the client using HTTPS. This server is ofter called a <a href="https://en.wikipedia.org/wiki/TLS_termination_proxy" target="_blank">TLS Termination Proxy</a>.
### Let's Encrypt
Up to some years ago, these HTTPS certificates were sold by trusted third-parties.
The process to acquire one of these certificates used to be cumbersome, require quite some paperwork and the certificates were quite expensive.
But then <a href="https://letsencrypt.org/" target="_blank">Let's Encrypt</a> was created.
It is a project from the Linux Foundation. It provides HTTPS certificates for free. In an automated way. These certificates use all the standard cryptographic security, and are short lived (about 3 months), so, the security is actually increased, by reducing their lifespan.
The domain's are securely verified and the certificates are generated automatically. This also allows automatizing the renewal of these certificates.
The idea is to automatize the acquisition and renewal of these certificates, so that you can have secure HTTPS, free, forever.
### Traefik
<a href="https://traefik.io/" target="_blank">Traefik</a> is a high performance reverse proxy / load balancer. It can do the "TLS Termination Proxy" job (apart from other features).
It has integration with Let's Encrypt. So, it can handle all the HTTPS parts, including certificate acquisition and renewal.
It also has integrations with Docker. So, you can declare your domains in each application configurations and have it read those configurations, generate the HTTPS certificates and serve HTTPS to your application, all automatically. Without requiring any change in its configuration.
---
With this information and tools, continue with the next section to combine everything.
## Docker Swarm mode cluster with Traefik and HTTPS
You can have a Docker Swarm mode cluster set up in minutes (about 20 min) with a main Traefik handling HTTPS (including certificate acquisition and renewal).
By using Docker Swarm mode, you can start with a "cluster" of a single machine (it can even be a $5 USD / month server) and then you can grow as much as you need adding more servers.
To set up a Docker Swarm Mode cluster with Traefik and HTTPS handling, follow this guide:
### <a href="https://medium.com/@tiangolo/docker-swarm-mode-and-traefik-for-a-https-cluster-20328dba6232" target="_blank">Docker Swarm Mode and Traefik for an HTTPS cluster</a>.
### Deploy a FastAPI application
The easiest way to set everything up, would be using the <a href="/project-generation/" target="_blank">FastAPI project generator</a>.
It is designed to be integrated with this Docker Swarm cluster with Traefik and HTTPS described above.
You can generate a project in about 2 min.
The generated project has instructions to deploy it, doing it takes other 2 min.
## Alternatively, deploy **FastAPI** without Docker
You can deploy **FastAPI** directly without Docker too.
You just need to install an ASGI compatible server like:
* <a href="https://www.uvicorn.org/" target="_blank">Uvicorn</a>, a lightning-fast ASGI server, built on uvloop and httptools.
```bash
pip install uvicorn
```
* <a href="https://gitlab.com/pgjones/hypercorn" target="_blank">Hypercorn</a>, an ASGI server also compatible with HTTP/2.
```bash
pip install hypercorn
```
...or any other ASGI server.
And run your application the same way you have done in the tutorials, but without the `--reload` option, e.g.:
```bash
uvicorn main:app --host 0.0.0.0 --port 80
```
or with Hypercorn:
```bash
hypercorn main:app --bind 0.0.0.0:80
```
You might want to set up some tooling to make sure it is restarted automatically if it stops.
You might also want to install <a href="https://gunicorn.org/" target="_blank">Gunicorn</a> and <a href="https://www.uvicorn.org/#running-with-gunicorn" target="_blank">use it as a manager for Uvicorn</a>, or use Hypercorn with multiple workers.
Making sure to fine-tune the number of workers, etc.
But if you are doing all that, you might just use the Docker image that does it automatically.

View File

@@ -27,7 +27,7 @@ Interactive API documentation and exploration web user interfaces. As the framew
It's all based on standard **Python 3.6 type** declarations (thanks to Pydantic). No new syntax to learn. Just standard modern Python.
If you need a 2 minute refresher of how to use Python types (even if you don't use FastAPI), check the tutorial section: [Python types](tutorial/python-types.md).
If you need a 2 minute refresher of how to use Python types (even if you don't use FastAPI), check the tutorial section: [Python types](python-types.md).
You write standard Python with types:
@@ -61,18 +61,17 @@ second_user_data = {
"joined": "2018-11-30",
}
# **second_user_data means:
# pass the keys and values of the dict
# directly as key-value arguments
# equivalent to:
# id=4, name="Mary", joined="2018-11-30"
my_second_user: User = User(**second_user_data)
```
!!! info
`**second_user_data` means:
Pass the keys and values of the `second_user_data` dict directly as key-value arguments, equivalent to: `User(id=4, name="Mary", joined="2018-11-30")`
### Editor support
All the framework was designed to be easy and intuitive to use, all the decisons where tested on multiple editors even before starting development, to ensure the best development experience.
All the framework was designed to be easy and intuitive to use, all the decisions where tested on multiple editors even before starting development, to ensure the best development experience.
In the last Python developer survey it was clear <a href="https://www.jetbrains.com/research/python-developers-survey-2017/#tools-and-features" target="_blank">that the most used feature is "autocompletion"</a>.
@@ -90,7 +89,7 @@ Here's how your editor might help you:
![editor support](img/pycharm-completion.png)
You will get completion in code you might even consider imposible before. As for example, the `price` key inside a JSON body (that could have been nested) that comes from a request.
You will get completion in code you might even consider impossible before. As for example, the `price` key inside a JSON body (that could have been nested) that comes from a request.
No more typing the wrong key names, coming back and forth between docs, or scrolling up and down to find if you finally used `username` or `user_name`.
@@ -154,7 +153,7 @@ Any integration is designed to be so simple to use (with dependencies) that you
### Tested
* 100% <abbr title="The amount of code that is automatically tested">test coverage</abbr> (* not yet, in a couple days).
* 100% <abbr title="The amount of code that is automatically tested">test coverage</abbr>.
* 100% <abbr title="Python type annotations, with this your editor and external tools can give you better support">type annotated</abbr> code base.
* Used in production applications.
@@ -202,4 +201,4 @@ With **FastAPI** you get all of **Pydantic**'s features (as FastAPI is based on
* You can have deeply **nested JSON** objects and have them all validated and annotated.
* **Extendible**:
* Pydantic allows custom data types to be defined or you can extend validation with methods on a model decorated with the validator decorator.
* 100% test coverage.
* 100% test coverage.

109
docs/help-fastapi.md Normal file
View File

@@ -0,0 +1,109 @@
Are you liking **FastAPI**?
Would you like to help FastAPI, other users, and the author?
Or would you like to get help with **FastAPI**?
There are very simple ways to help (several involve just one or two clicks).
And there are several ways to get help too.
## Star **FastAPI** in GitHub
You can "star" FastAPI in GitHub (clicking the star button at the top right): <a href="https://github.com/tiangolo/fastapi" target="_blank">https://github.com/tiangolo/fastapi</a>.
By adding a star, other users will be able to find it more easily and see that it has been already useful for others.
## Watch the GitHub repository for releases
You can "watch" FastAPI in GitHub (clicking the "watch" button at the top right): <a href="https://github.com/tiangolo/fastapi" target="_blank">https://github.com/tiangolo/fastapi</a>.
There you can select "Releases only".
Doing it, you will receive notifications (in your email) whenever there's a new release (a new version) of **FastAPI** with bug fixes and new features.
## Join the chat
<a href="https://gitter.im/tiangolo/fastapi?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge" target="_blank">
<img src="https://badges.gitter.im/tiangolo/fastapi.svg" alt="Join the chat at https://gitter.im/tiangolo/fastapi">
</a>
Join the chat on Gitter: <a href="https://gitter.im/tiangolo/fastapi" target="_blank">https://gitter.im/tiangolo/fastapi</a>.
There you can ask quick questions, help others, share ideas, etc.
## Connect with the author
You can connect with <a href="https://tiangolo.com" target="_blank">me (Sebastián Ramírez / `tiangolo`)</a>, the author.
You can:
* <a href="https://github.com/tiangolo" target="_blank">Follow me on **GitHub**</a>.
* See other Open Source projects I have created that could help you.
* Follow me to see when I create a new Open Source project.
* <a href="https://twitter.com/tiangolo" target="_blank">Follow me on **Twitter**</a>.
* Tell me how you use FastAPI (I love to hear that).
* Ask questions.
* <a href="https://www.linkedin.com/in/tiangolo/" target="_blank">Connect with me on **Linkedin**</a>.
* Talk to me.
* Endorse me or recommend me :)
* <a href="https://medium.com/@tiangolo" target="_blank">Read what I write (or follow me) on **Medium**</a>.
* Read other ideas, articles and tools I have created.
* Follow me to see when I publish something new.
## Tweet about **FastAPI**
<a href="http://twitter.com/home/?status=I'm loving FastAPI because... https://github.com/tiangolo/fastapi cc @tiangolo" target="_blank">Tweet about **FastAPI**</a> and let me and others why you like it.
## Let me know how are you using **FastAPI**
I love to hear about how **FastAPI** is being used, what have you liked in it, in which project/company are you using it, etc.
You can let me know:
* <a href="http://twitter.com/home/?status=Hey @tiangolo, I'm using FastAPI at..." target="_blank">On **Twitter**</a>.
* <a href="https://www.linkedin.com/in/tiangolo/" target="_blank">On **Linkedin**</a>.
* <a href="https://medium.com/@tiangolo" target="_blank">On **Medium**</a>.
## Vote for FastAPI
You can vote to include FastAPI in several "awesome lists":
* <a href="https://github.com/vinta/awesome-python/pull/1209" target="_blank">Vote to include **FastAPI** in `awesome-python`</a>.
* <a href="https://github.com/timofurrer/awesome-asyncio/pull/43" target="_blank">Vote to include **FastAPI** in `awesome-asyncio`</a>.
## Help others with issues in GitHub
You can see <a href="https://github.com/tiangolo/fastapi/issues" target="_blank">existing issues</a> and try and help others.
## Watch the GitHub repository
You can "watch" FastAPI in GitHub (clicking the "watch" button at the top right): <a href="https://github.com/tiangolo/fastapi" target="_blank">https://github.com/tiangolo/fastapi</a>.
If you select "Watching" instead of "Releases only", you will receive notifications when someone creates a new issue.
Then you can try and help them solving those issues.
## Create issues
You can <a href="https://github.com/tiangolo/fastapi/issues/new/choose" target="_blank">create a new issue</a> in the GitHub repository, for example to:
* Report a bug/issue.
* Suggest a new feature.
* Ask a question.
## Create a Pull Request
You can <a href="https://github.com/tiangolo/fastapi" target="_blank">create a Pull Request</a>, for example:
* To fix a typo you found on the documentation.
* To propose new documentation sections.
* To fix an existing issue/bug.
* To add a new feature.
---
Thanks!

View File

@@ -0,0 +1,83 @@
Some time ago, <a href="https://github.com/tiangolo/fastapi/issues/3#issuecomment-454956920" target="_blank">a **FastAPI** user asked</a>:
> Whats the history of this project? It seems to have come from nowhere to awesome in a few weeks [...]
Here's a little bit of that history.
## Alternatives
I have been creating APIs with complex requirements for several years (Machine Learning, distributed systems, asynchronous jobs, NoSQL databases, etc), leading several teams of developers.
As part of that, I needed to investigate, test and use many alternatives.
The history of **FastAPI** is in great part the history of its predecessors.
As said in the section <a href="https://fastapi.tiangolo.com/alternatives/" target="_blank">Alternatives</a>:
<blockquote markdown="1">
**FastAPI** wouldn't exist if not for the previous work of others.
There have been many tools created before that have helped inspire its creation.
I have been avoiding the creation of a new framework for several years. First I tried to solve all the features covered by **FastAPI** using many different frameworks, plug-ins, and tools.
But at some point, there was no other option than creating something that provided all these features, taking the best ideas from previous tools, and combining them in the best way possible, using language features that weren't even available before (Python 3.6+ type hints).
</blockquote>
## Investigation
By using all the previous alternatives I had the chance to learn from all of them, take ideas, and combine them in the best way I could find for myself and the teams of developers I have worked with.
For example, it was clear that ideally it should be based on standard Python type hints.
Also, the best approach was to use already existing standards.
So, before even starting to code **FastAPI**, I spent several months studying the specs for OpenAPI, JSON Schema, OAuth2, etc. Understanding their relationship, overlap, and differences.
## Design
Then I spent some time designing the developer "API" I wanted to have as a user (as a developer using FastAPI).
I tested several ideas in the most popular Python editors: PyCharm, VS Code, Jedi based editors.
By the last <a href="https://www.jetbrains.com/research/python-developers-survey-2018/#development-tools" target="_blank">Python Developer Survey</a>, that covers about 80% of the users.
It means that **FastAPI** was specifically tested with the editors used by 80% of the Python developers. And as most of the other editors tend to work similarly, all its benefits should work for virtually all editors.
That way I could find the best ways to reduce code duplication as much as possible, to have completion everywhere, type and error checks, etc.
All in a way that provided the best development experience for all the developers.
## Requirements
After testing several alternatives, I decided that I was going to use <a href="https://pydantic-docs.helpmanual.io/" target="_blank">**Pydantic**</a> for its advantages.
Then I contributed to it, to make it fully compliant with JSON Schema, to support different ways to define constraint declarations, and to improve editor support (type checks, autocompletion) based on the tests in several editors.
During the development, I also contributed to <a href="https://www.starlette.io/" target="_blank">**Starlette**</a>, the other key requirement.
## Development
By the time I started creating **FastAPI** itself, most of the pieces were already in place, the design was defined, the requirements and tools were ready, and the knowledge about the standards and specifications was clear and fresh.
## Future
By this point, it's already clear that **FastAPI** with its ideas is being useful for many people.
It is being chosen over previous alternatives for suiting many use cases better.
Many developers and teams already depend on **FastAPI** for their projects (including me and my team).
But still, there are many improvements and features to come.
**FastAPI** has a great future ahead.
And <a href="https://fastapi.tiangolo.com/help-fastapi/" target="_blank">your help</a> is greatly appreciated.

View File

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.4 KiB

BIN
docs/img/icon-white-bg.png Normal file
View File

Binary file not shown.

After

Width:  |  Height:  |  Size: 5.1 KiB

View File

Binary file not shown.

Before

Width:  |  Height:  |  Size: 46 KiB

After

Width:  |  Height:  |  Size: 72 KiB

View File

Binary file not shown.

Before

Width:  |  Height:  |  Size: 52 KiB

After

Width:  |  Height:  |  Size: 67 KiB

View File

Binary file not shown.

Before

Width:  |  Height:  |  Size: 66 KiB

After

Width:  |  Height:  |  Size: 73 KiB

View File

Binary file not shown.

Before

Width:  |  Height:  |  Size: 64 KiB

After

Width:  |  Height:  |  Size: 66 KiB

View File

Binary file not shown.

Before

Width:  |  Height:  |  Size: 88 KiB

After

Width:  |  Height:  |  Size: 70 KiB

View File

Binary file not shown.

Before

Width:  |  Height:  |  Size: 76 KiB

After

Width:  |  Height:  |  Size: 77 KiB

View File

Binary file not shown.

After

Width:  |  Height:  |  Size: 17 KiB

View File

Binary file not shown.

After

Width:  |  Height:  |  Size: 21 KiB

View File

Binary file not shown.

Before

Width:  |  Height:  |  Size: 43 KiB

After

Width:  |  Height:  |  Size: 50 KiB

View File

Binary file not shown.

After

Width:  |  Height:  |  Size: 17 KiB

View File

Binary file not shown.

After

Width:  |  Height:  |  Size: 47 KiB

View File

Binary file not shown.

After

Width:  |  Height:  |  Size: 42 KiB

View File

Binary file not shown.

After

Width:  |  Height:  |  Size: 18 KiB

View File

Binary file not shown.

After

Width:  |  Height:  |  Size: 42 KiB

View File

Binary file not shown.

After

Width:  |  Height:  |  Size: 29 KiB

View File

Binary file not shown.

After

Width:  |  Height:  |  Size: 80 KiB

View File

Binary file not shown.

After

Width:  |  Height:  |  Size: 37 KiB

View File

Binary file not shown.

After

Width:  |  Height:  |  Size: 69 KiB

View File

Binary file not shown.

After

Width:  |  Height:  |  Size: 76 KiB

View File

Binary file not shown.

After

Width:  |  Height:  |  Size: 77 KiB

View File

Binary file not shown.

After

Width:  |  Height:  |  Size: 170 KiB

View File

Binary file not shown.

Before

Width:  |  Height:  |  Size: 104 KiB

After

Width:  |  Height:  |  Size: 65 KiB

View File

Binary file not shown.

After

Width:  |  Height:  |  Size: 63 KiB

View File

Binary file not shown.

After

Width:  |  Height:  |  Size: 93 KiB

View File

Binary file not shown.

Before

Width:  |  Height:  |  Size: 87 KiB

After

Width:  |  Height:  |  Size: 85 KiB

View File

Binary file not shown.

After

Width:  |  Height:  |  Size: 71 KiB

View File

Binary file not shown.

After

Width:  |  Height:  |  Size: 72 KiB

View File

Binary file not shown.

After

Width:  |  Height:  |  Size: 21 KiB

View File

Binary file not shown.

After

Width:  |  Height:  |  Size: 53 KiB

View File

Binary file not shown.

After

Width:  |  Height:  |  Size: 79 KiB

View File

Binary file not shown.

After

Width:  |  Height:  |  Size: 90 KiB

View File

Binary file not shown.

After

Width:  |  Height:  |  Size: 82 KiB

View File

Binary file not shown.

After

Width:  |  Height:  |  Size: 79 KiB

View File

Binary file not shown.

After

Width:  |  Height:  |  Size: 89 KiB

View File

Binary file not shown.

After

Width:  |  Height:  |  Size: 60 KiB

View File

Binary file not shown.

After

Width:  |  Height:  |  Size: 86 KiB

View File

Binary file not shown.

After

Width:  |  Height:  |  Size: 108 KiB

View File

Binary file not shown.

After

Width:  |  Height:  |  Size: 155 KiB

View File

Binary file not shown.

After

Width:  |  Height:  |  Size: 79 KiB

View File

Binary file not shown.

After

Width:  |  Height:  |  Size: 68 KiB

View File

Binary file not shown.

After

Width:  |  Height:  |  Size: 77 KiB

View File

Binary file not shown.

After

Width:  |  Height:  |  Size: 82 KiB

View File

Binary file not shown.

After

Width:  |  Height:  |  Size: 49 KiB

View File

Binary file not shown.

After

Width:  |  Height:  |  Size: 52 KiB

View File

Binary file not shown.

After

Width:  |  Height:  |  Size: 17 KiB

View File

Binary file not shown.

After

Width:  |  Height:  |  Size: 18 KiB

View File

Binary file not shown.

After

Width:  |  Height:  |  Size: 21 KiB

View File

Binary file not shown.

After

Width:  |  Height:  |  Size: 30 KiB

View File

Binary file not shown.

Before

Width:  |  Height:  |  Size: 49 KiB

After

Width:  |  Height:  |  Size: 61 KiB

View File

@@ -1,45 +1,70 @@
<p align="center">
<a href="https://fastapi.tiangolo.com"><img src="https://fastapi.tiangolo.com/img/logo-margin/logo-teal-vector.svg" alt='FastAPI'></a>
<a href="https://fastapi.tiangolo.com"><img src="https://fastapi.tiangolo.com/img/logo-margin/logo-teal.png" alt="FastAPI"></a>
</p>
<p align="center">
<em>FastAPI framework, high performance, easy to learn, fast to code, ready for production</em>
</p>
<p align="center">
<a href="https://travis-ci.org/tiangolo/fastapi">
<a href="https://travis-ci.org/tiangolo/fastapi" target="_blank">
<img src="https://travis-ci.org/tiangolo/fastapi.svg?branch=master" alt="Build Status">
</a>
<a href="https://codecov.io/gh/tiangolo/fastapi">
<a href="https://codecov.io/gh/tiangolo/fastapi" target="_blank">
<img src="https://codecov.io/gh/tiangolo/fastapi/branch/master/graph/badge.svg" alt="Coverage">
</a>
<a href="https://pypi.org/project/fastapi">
<a href="https://pypi.org/project/fastapi" target="_blank">
<img src="https://badge.fury.io/py/fastapi.svg" alt="Package version">
</a>
<a href="https://gitter.im/tiangolo/fastapi?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge" target="_blank">
<img src="https://badges.gitter.im/tiangolo/fastapi.svg" alt="Join the chat at https://gitter.im/tiangolo/fastapi">
</a>
</p>
---
**Documentation**: [https://fastapi.tiangolo.com](https://fastapi.tiangolo.com)
**Documentation**: <a href="https://fastapi.tiangolo.com" target="_blank">https://fastapi.tiangolo.com</a>
**Source Code**: [https://github.com/tiangolo/fastapi](https://github.com/tiangolo/fastapi)
**Source Code**: <a href="https://github.com/tiangolo/fastapi" target="_blank">https://github.com/tiangolo/fastapi</a>
---
FastAPI is a modern, fast (high-performance), web framework for building APIs with Python 3.6+.
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).
* **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% *.
* **Less bugs**: Reduce about 40% of human (developer) induced errors. *
* **Fewer bugs**: Reduce about 40% of human (developer) induced errors. *
* **Intuitive**: Great editor support. <abbr title="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. Less bugs.
* **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: <a href="https://github.com/OAI/OpenAPI-Specification" target="_blank">OpenAPI</a> and <a href="http://json-schema.org/" target="_blank">JSON Schema</a>.
* **Standards-based**: Based on (and fully compatible with) the open standards for APIs: <a href="https://github.com/OAI/OpenAPI-Specification" target="_blank">OpenAPI</a> (previously known as Swagger) and <a href="http://json-schema.org/" target="_blank">JSON Schema</a>.
<small>* estimation based on tests on an internal development team, building production applications.</small>
## Opinions
"*[...] 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.*"
<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>
---
"*Im over the moon excited about **FastAPI**. Its so fun!*"
<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>
---
"*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.*"
<div style="text-align: right; margin-right: 10%;">Timothy Crosley - <strong><a href="http://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>
---
## Requirements
@@ -57,7 +82,7 @@ FastAPI stands on the shoulders of giants:
$ pip install fastapi
```
You will also need an ASGI server, for production such as <a href="http://www.uvicorn.org" target="_blank">uvicorn</a>.
You will also need an ASGI server, for production such as <a href="http://www.uvicorn.org" target="_blank">Uvicorn</a> or <a href="https://gitlab.com/pgjones/hypercorn" target="_blank">Hypercorn</a>.
```bash
$ pip install uvicorn
@@ -65,6 +90,8 @@ $ pip install uvicorn
## Example
### Create it
* Create a file `main.py` with:
```Python
@@ -72,50 +99,79 @@ from fastapi import FastAPI
app = FastAPI()
@app.get('/')
@app.get("/")
def read_root():
return {'hello': 'world'}
return {"Hello": "World"}
@app.get("/items/{item_id}")
def read_item(item_id: int, q: str = None):
return {"item_id": item_id, "q": q}
```
<details markdown="1">
<summary>Or use <code>async def</code>...</summary>
Or if your code uses `async` / `await`, use `async def`:
If your code uses `async` / `await`, use `async def`:
```Python hl_lines="6"
```Python hl_lines="7 12"
from fastapi import FastAPI
app = FastAPI()
@app.get('/')
@app.get("/")
async def read_root():
return {'hello': 'world'}
return {"Hello": "World"}
@app.get("/items/{item_id}")
async def read_item(item_id: int, q: str = None):
return {"item_id": item_id, "q": q}
```
!!! note
If you don't know, check the section about [`async` and `await` in the docs](async.md).
**Note**:
If 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>.
</details>
* Run the server with:
### Run it
Run the server with:
```bash
uvicorn main:app --debug
uvicorn main:app --reload
```
!!! note
The command `uvicorn main:app` refers to:
<details markdown="1">
<summary>About the command <code>uvicorn main:app --reload</code>...</summary>
* `main`: the file `main.py` (the Python "module").
* `app`: the object created inside of `main.py` with the line `app = FastAPI()`.
* `--debug`: make the server restart after code changes. Only do this for development.
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 <a href="http://127.0.0.1:8000" target="_blank">http://127.0.0.1:8000</a>.
Open your browser at <a href="http://127.0.0.1:8000/items/5?q=somequery" target="_blank">http://127.0.0.1:8000/items/5?q=somequery</a>.
You will see the JSON response as:
```JSON
{"hello": "world"}
{"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 <a href="http://127.0.0.1:8000/docs" target="_blank">http://127.0.0.1:8000/docs</a>.
@@ -135,14 +191,12 @@ You will see the alternative automatic documentation (provided by <a href="https
## Example upgrade
Now modify the file `main.py` to include:
Now modify the file `main.py` to receive a body from a `PUT` request.
* a path parameter `item_id`.
* a body, declared using standard Python types (thanks to Pydantic).
* an optional query parameter `q`.
Declare the body using standard Python types, thanks to Pydantic.
```Python hl_lines="2 7 8 9 10 19"
```Python hl_lines="2 7 8 9 10 24"
from fastapi import FastAPI
from pydantic import BaseModel
@@ -155,23 +209,28 @@ class Item(BaseModel):
is_offer: bool = None
@app.get('/')
async def read_root():
return {'hello': 'world'}
@app.get("/")
def read_root():
return {"Hello": "World"}
@app.post('/items/{item_id}')
async def create_item(item_id: int, item: Item, q: str = None):
return {"item_name": item.name, "item_id": item_id, "query": q}
@app.get("/items/{item_id}")
def read_item(item_id: int, q: str = None):
return {"item_id": item_id, "q": q}
@app.put("/items/{item_id}")
def update_item(item_id: int, item: Item):
return {"item_name": item.name, "item_id": item_id}
```
The server should reload automatically (because you added `--debug` to the `uvicorn` command above).
The server should reload automatically (because you added `--reload` to the `uvicorn` command above).
### Interactive API docs upgrade
Now go to <a href="http://127.0.0.1:8000/docs" target="_blank">http://127.0.0.1:8000/docs</a>.
* The interactive API documentation will be automatically updated, including the new query, and body:
* The interactive API documentation will be automatically updated, including the new body:
![Swagger UI](https://fastapi.tiangolo.com/img/index/index-03-swagger-02.png)
@@ -223,7 +282,7 @@ item: Item
* Validation of data:
* Automatic and clear errors when the data is invalid.
* Validation even for deeply nested JSON objects.
* <abbr title="also known as: serialization, parsing, marshalling">Conversion</abbr> of input data: coming from the network, to Python data and types. Reading from:
* <abbr title="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.
@@ -245,20 +304,20 @@ item: Item
Coming back to the previous code example, **FastAPI** will:
* Validate that there is an `item_id` in the path.
* Validate that the `item_id` is of type `int`.
* Validate that there is an `item_id` in the path for `GET` and `PUT` requests.
* Validate that the `item_id` is of type `int` for `GET` and `PUT` requests.
* If it is not, the client will see a useful, clear error.
* Check if there is an optional query parameter named `q` (as in `http://127.0.0.1:8000/items/foo?q=somequery`).
* 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.
* As the `q` parameter is declared with `= None`, it is optional.
* Without the `None` it would be required (as is the body).
* Read the body as JSON:
* Without the `None` it would be required (as is the body in the case with `PUT`).
* For `PUT` requests to `/items/{item_id}`, Read the body as JSON:
* Check that it has a required attribute `name` that should be a `str`.
* Check that is has a required attribute `price` that has to be a `float`.
* Check that it has an optional attribute `is_offer`, that should be a `bool`, if present.
* All this would also work for deeply nested JSON objects.
* Convert from and to JSON automatically.
* Document everything as an OpenAPI schema, that can be used by:
* Interactive documentation sytems.
* Document everything with OpenAPI, that can be used by:
* Interactive documentation systems.
* Automatic client code generation systems, for many languages.
* Provide 2 interactive documentation web interfaces directly.
@@ -270,7 +329,7 @@ We just scratched the surface, but you already get the idea of how it all works.
Try changing the line with:
```Python
return {"item_name": item.name, "item_id": item_id, "query": q}
return {"item_name": item.name, "item_id": item_id}
```
...from:
@@ -290,12 +349,12 @@ Try changing the line with:
![editor support](https://fastapi.tiangolo.com/img/vscode-completion.png)
For a more complete example including more features, [see the tutorial - user guide](tutorial/intro/).
For a more complete example including more features, see the <a href="https://fastapi.tiangolo.com/tutorial/intro/">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 constrains** as `maximum_length` or `regex`.
* How to set **validation constraints** as `maximum_length` or `regex`.
* A very powerful and easy to use **<abbr title="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).
@@ -308,6 +367,11 @@ For a more complete example including more features, [see the tutorial - user gu
* ...and more.
## Performance
Independent 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" 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 <a href="https://fastapi.tiangolo.com/benchmarks/" target="_blank">Benchmarks</a>.
## Optional Dependencies
@@ -332,7 +396,7 @@ Used by FastAPI / Starlette:
* <a href="http://www.uvicorn.org" target="_blank"><code>uvicorn</code></a> - for the server that loads and serves your application.
You can install all of these with `pip3 install fastapi[full]`.
You can install all of these with `pip3 install fastapi[all]`.
## License

103
docs/project-generation.md Normal file
View File

@@ -0,0 +1,103 @@
There is a project generator that you can use to get started, with a lot of the initial set up, security, database and first API endpoints already done for you.
## Full-Stack-FastAPI-PostgreSQL
GitHub: <a href="https://github.com/tiangolo/full-stack-fastapi-postgresql" target="_blank">https://github.com/tiangolo/full-stack-fastapi-postgresql</a>
### Features
* Full **Docker** integration (Docker based).
* Docker Swarm Mode deployment.
* **Docker Compose** integration and optimization for local development
* **Production ready** Python web server using Uvicorn and Gunicorn.
* Python **[FastAPI](https://github.com/tiangolo/fastapi)** backend:
* **Fast**: Very high performance, on par with **NodeJS** and **Go** (thanks to Starlette and Pydantic).
* **Intuitive**: Great editor support. <abbr title="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.
* **Robust**: Get production-ready code. With automatic interactive documentation.
* **Standards-based**: Based on (and fully compatible with) the open standards for APIs: <a href="https://github.com/OAI/OpenAPI-Specification" target="_blank">OpenAPI</a> and <a href="http://json-schema.org/" target="_blank">JSON Schema</a>.
* [**Many other features**](https://github.com/tiangolo/fastapi) including automatic validation, serialization, interactive documentation, authentication with OAuth2 JWT tokens, etc.
* **Secure password** hashing by default.
* **JWT token** authentication.
* **SQLAlchemy** models (independent of Flask extensions, so they can be used with Celery workers directly).
* Basic starting models for users (modify and remove as you need).
* **Alembic** migrations.
* **CORS** (Cross Origin Resource Sharing).
* **Celery** worker that can import and use models and code from the rest of the backend selectively (you don't have to install the complete app in each worker).
* REST backend tests based on **Pytest**, integrated with Docker, so you can test the full API interaction, independent on the database. As it runs in Docker, it can build a new data store from scratch each time (so you can use ElasticSearch, MongoDB, CouchDB, or whatever you want, and just test that the API works).
* Easy Python integration with **Jupyter Kernels** for remote or in-Docker development with extensions like Atom Hydrogen or Visual Studio Code Jupyter.
* **Vue** frontend:
* Generated with Vue CLI.
* **JWT Authentication** handling.
* Login view.
* After login, main dashboard view.
* Main dashboard with user creation and edition.
* Self user edition.
* **Vuex**.
* **Vue-router**.
* **Vuetify** for beautiful material design components.
* **TypeScript**.
* Docker server based on **Nginx** (configured to play nicely with Vue-router).
* Docker multi-stage building, so you don't need to save or commit compiled code.
* Frontend tests ran at build time (can be disabled too).
* Made as modular as possible, so it works out of the box, but you can re-generate with Vue CLI or create it as you need, and re-use what you want.
* **PGAdmin** for PostgreSQL database, you can modify it to use PHPMyAdmin and MySQL easily.
* **Flower** for Celery jobs monitoring.
* Load balancing between frontend and backend with **Traefik**, so you can have both under the same domain, separated by path, but served by different containers.
* Traefik integration, including Let's Encrypt **HTTPS** certificates automatic generation.
* GitLab **CI** (continuous integration), including frontend and backend testing.
## Full-Stack-FastAPI-Couchbase
GitHub: <a href="https://github.com/tiangolo/full-stack-fastapi-couchbase" target="_blank">https://github.com/tiangolo/full-stack-fastapi-couchbase</a>
### Features
* Full **Docker** integration (Docker based).
* Docker Swarm Mode deployment.
* **Docker Compose** integration and optimization for local development.
* **Production ready** Python web server using Uvicorn and Gunicorn.
* Python **[FastAPI](https://github.com/tiangolo/fastapi)** backend:
* **Fast**: Very high performance, on par with **NodeJS** and **Go** (thanks to Starlette and Pydantic).
* **Intuitive**: Great editor support. <abbr title="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.
* **Robust**: Get production-ready code. With automatic interactive documentation.
* **Standards-based**: Based on (and fully compatible with) the open standards for APIs: <a href="https://github.com/OAI/OpenAPI-Specification" target="_blank">OpenAPI</a> and <a href="http://json-schema.org/" target="_blank">JSON Schema</a>.
* [**Many other features**](https://github.com/tiangolo/fastapi) including automatic validation, serialization, interactive documentation, authentication with OAuth2 JWT tokens, etc.
* **Secure password** hashing by default.
* **JWT token** authentication.
* **CORS** (Cross Origin Resource Sharing).
* **Celery** worker that can import and use code from the rest of the backend selectively (you don't have to install the complete app in each worker).
* **NoSQL Couchbase** database that supports direct synchronization via Couchbase Sync Gateway for offline-first applications.
* **Full Text Search** integrated, using Couchbase.
* REST backend tests based on Pytest, integrated with Docker, so you can test the full API interaction, independent on the database. As it runs in Docker, it can build a new data store from scratch each time (so you can use ElasticSearch, MongoDB, or whatever you want, and just test that the API works).
* Easy Python integration with **Jupyter** Kernels for remote or in-Docker development with extensions like Atom Hydrogen or Visual Studio Code Jupyter.
* **Email notifications** for account creation and password recovery, compatible with:
* Mailgun
* SparkPost
* SendGrid
* ...any other provider that can generate standard SMTP credentials.
* **Vue** frontend:
* Generated with Vue CLI.
* **JWT Authentication** handling.
* Login view.
* After login, main dashboard view.
* Main dashboard with user creation and edition.
* Self user edition.
* **Vuex**.
* **Vue-router**.
* **Vuetify** for beautiful material design components.
* **TypeScript**.
* Docker server based on **Nginx** (configured to play nicely with Vue-router).
* Docker multi-stage building, so you don't need to save or commit compiled code.
* Frontend tests ran at build time (can be disabled too).
* Made as modular as possible, so it works out of the box, but you can re-generate with Vue CLI or create it as you need, and re-use what you want.
* **Flower** for Celery jobs monitoring.
* Load balancing between frontend and backend with **Traefik**, so you can have both under the same domain, separated by path, but served by different containers.
* Traefik integration, including Let's Encrypt **HTTPS** certificates automatic generation.
* GitLab **CI** (continuous integration), including frontend and backend testing.

288
docs/python-types.md Normal file
View File

@@ -0,0 +1,288 @@
**Python 3.6+** has support for optional "type hints".
These **"type hints"** are a new syntax (since Python 3.6+) that allow declaring the <abbr title="for example: str, int, float, bool">type</abbr> of a variable.
By declaring types for your variables, editors and tools can give you better support.
This is just a **quick tutorial / refresher** about Python type hints. It covers only the minimum necessary to use them with **FastAPI**... which is actually very little.
**FastAPI** is all based on these type hints, they give it many advantages and benefits.
But even if you never use **FastAPI**, you would benefit from learning a bit about them.
!!! note
If you are a Python expert, and you already know everything about type hints, skip to the next chapter.
## Motivation
Let's start with a simple example:
```Python
{!./src/python_types/tutorial001.py!}
```
Calling this program outputs:
```
John Doe
```
The function does the following:
* Takes a `first_name` and `last_name`.
* Converts the first letter of each one to upper case with `title()`.
* <abbr title="Puts them together, as one. With the contents of one after the other.">Concatenates</abbr> them with a space in the middle.
```Python hl_lines="2"
{!./src/python_types/tutorial001.py!}
```
### Edit it
It's a very simple program.
But now imagine that you were writing it from scratch.
At some point you would have started the definition of the function, you had the parameters ready...
But then you have to call "that method that converts the first letter to upper case".
Was it `upper`? Was it `uppercase`? `first_uppercase`? `capitalize`?
Then, you try with the old programmer's friend, editor autocompletion.
You type the first parameter of the function, `first_name`, then a dot (`.`) and then hit `Ctrl+Space` to trigger the completion.
But, sadly, you get nothing useful:
<img src="/img/python-types/image01.png">
### Add types
Let's modify a single line from the previous version.
We will change exactly this fragment, the parameters of the function, from:
```Python
first_name, last_name
```
to:
```Python
first_name: str, last_name: str
```
That's it.
Those are the "type hints":
```Python hl_lines="1"
{!./src/python_types/tutorial002.py!}
```
That is not the same as declaring default values like would be with:
```Python
first_name="john", last_name="doe"
```
It's a different thing.
We are using colons (`:`), not equals (`=`).
And adding type hints normally doesn't change what happens from what would happen without them.
But now, imagine you are again in the middle of creating that function, but with type hints.
At the same point, you try to trigger the autocomplete with `Ctrl+Space` and you see:
<img src="/img/python-types/image02.png">
With that, you can scroll, seeing the options, until you find the one that "rings a bell":
<img src="/img/python-types/image03.png">
## More motivation
Check this function, it already has type hints:
```Python hl_lines="1"
{!./src/python_types/tutorial003.py!}
```
Because the editor knows the types of the variables, you don't only get completion, you also get error checks:
<img src="/img/python-types/image04.png">
Now you know that you have to fix it, convert `age` to a string with `str(age)`:
```Python hl_lines="2"
{!./src/python_types/tutorial004.py!}
```
## Declaring types
You just saw the main place to declare type hints. As function parameters.
This is also the main place you would use them with **FastAPI**.
### Simple types
You can declare all the standard Python types, not only `str`.
You can use, for example:
* `int`
* `float`
* `bool`
* `bytes`
```Python hl_lines="1"
{!./src/python_types/tutorial005.py!}
```
### Types with subtypes
There are some data structures that can contain other values, like `dict`, `list`, `set` and `tuple`. And the internal values can have their own type too.
To declare those types and the subtypes, you can use the standard Python module `typing`.
It exists specifically to support these type hints.
#### Lists
For example, let's define a variable to be a `list` of `str`.
From `typing`, import `List` (with a capital `L`):
```Python hl_lines="1"
{!./src/python_types/tutorial006.py!}
```
Declare the variable, with the same colon (`:`) syntax.
As the type, put the `List`.
As the list is a type that takes a "subtype", you put the subtype in square brackets:
```Python hl_lines="4"
{!./src/python_types/tutorial006.py!}
```
That means: "the variable `items` is a `list`, and each of the items in this list is a `str`".
By doing that, your editor can provide support even while processing items from the list.
Without types, that's almost impossible to achieve:
<img src="/img/python-types/image05.png">
Notice that the variable `item` is one of the elements in the list `items`.
And still, the editor knows it is a `str`, and provides support for that.
#### Tuples and Sets
You would do the same to declare `tuple`s and `set`s:
```Python hl_lines="1 4"
{!./src/python_types/tutorial007.py!}
```
This means:
* The variable `items_t` is a `tuple`, and each of its items is an `int`.
* The variable `items_s` is a `set`, and each of its items is of type `bytes`.
#### Dicts
To define a `dict`, you pass 2 subtypes, separated by commas.
The first subtype is for the keys of the `dict`.
The second subtype is for the values of the `dict`:
```Python hl_lines="1 4"
{!./src/python_types/tutorial008.py!}
```
This means:
* The variable `prices` is a `dict`:
* The keys of this `dict` are of type `str` (let's say, the name of each item).
* The values of this `dict` are of type `float` (let's say, the price of each item).
### Classes as types
You can also declare a class as the type of a variable.
Let's say you have a class `Person`, with a name:
```Python hl_lines="1 2 3"
{!./src/python_types/tutorial009.py!}
```
Then you can declare a variable to be of type `Person`:
```Python hl_lines="6"
{!./src/python_types/tutorial009.py!}
```
And then, again, you get all the editor support:
<img src="/img/python-types/image06.png">
## Pydantic models
<a href="https://pydantic-docs.helpmanual.io/" target="_blank">Pydantic</a> is a Python library to perform data validation.
You declare the "shape" of the data as classes with attributes.
And each attribute has a type.
Then you create an instance of that class with some values and it will validate the values, convert them to the appropriate type (if that's the case) and give you an object with all the data.
And you get all the editor support with that resulting object.
Taken from the official Pydantic docs:
```Python
{!./src/python_types/tutorial010.py!}
```
!!! info
To learn more about <a href="https://pydantic-docs.helpmanual.io/" target="_blank">Pydantic, check its docs</a>.
**FastAPI** is all based on Pydantic.
You will see a lot more of all this in practice in the <a href="/tutorial/intro/" target="_blank">Tutorial - User Guide</a> (the next section).
## Type hints in **FastAPI**
**FastAPI** takes advantage of these type hints to do several things.
With **FastAPI** you declare parameters with type hints and you get:
* **Editor support**.
* **Type checks**.
...and **FastAPI** uses the same declarations to:
* **Define requirements**: from request path parameters, query parameters, headers, bodies, dependencies, etc.
* **Convert data**: from the request to the required type.
* **Validate data**: coming from each request:
* Generating **automatic errors** returned to the client when the data is invalid.
* **Document** the API using OpenAPI:
* which is then used by the automatic interactive documentation user interfaces.
This might all sound abstract. Don't worry. You'll see all this in action in the <a href="/tutorial/intro/" target="_blank">Tutorial - User Guide</a> (the next section).
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
If you already went through all the tutorial and came back to see more about types, a good resource is <a href="https://mypy.readthedocs.io/en/latest/cheat_sheet_py3.html" target="_blank">the "cheat sheet" from `mypy`</a>.

281
docs/release-notes.md Normal file
View File

@@ -0,0 +1,281 @@
## Next release
## 0.21.0
* On body parsing errors, raise `from` previous exception, to allow better introspection in logging code. PR [#192](https://github.com/tiangolo/fastapi/pull/195) by [@ricardomomm](https://github.com/ricardomomm).
* Use Python logger named "`fastapi`" instead of root logger. PR [#222](https://github.com/tiangolo/fastapi/pull/222) by [@euri10](https://github.com/euri10).
* Upgrade Pydantic to version 0.25. PR [#225](https://github.com/tiangolo/fastapi/pull/225) by [@euri10](https://github.com/euri10).
* Fix typo in routing. PR [#221](https://github.com/tiangolo/fastapi/pull/221) by [@djlambert](https://github.com/djlambert).
## 0.20.1
* Add typing information to package including file `py.typed`. PR [#209](https://github.com/tiangolo/fastapi/pull/209) by [@meadsteve](https://github.com/meadsteve).
* Add FastAPI bot for Gitter. To automatically announce new releases. PR [#189](https://github.com/tiangolo/fastapi/pull/189).
## 0.20.0
* Upgrade OAuth2:
* Upgrade Password flow using Bearer tokens to use the correct HTTP status code 401 `UNAUTHORIZED`, with `WWW-Authenticate` headers.
* Update, simplify, and improve all the [security docs](https://fastapi.tiangolo.com/tutorial/security/intro/).
* Add new `scope_str` to `SecurityScopes` and update docs: [OAuth2 scopes](https://fastapi.tiangolo.com/tutorial/security/oauth2-scopes/).
* Update docs, images, tests.
* PR [#188](https://github.com/tiangolo/fastapi/pull/188).
* Include [Hypercorn](https://gitlab.com/pgjones/hypercorn) as an alternative ASGI server in the docs. PR [#187](https://github.com/tiangolo/fastapi/pull/187).
* Add docs for [Static Files](https://fastapi.tiangolo.com/tutorial/static-files/) and [Templates](https://fastapi.tiangolo.com/tutorial/templates/). PR [#186](https://github.com/tiangolo/fastapi/pull/186).
* Add docs for handling [Response Cookies](https://fastapi.tiangolo.com/tutorial/response-cookies/) and [Response Headers](https://fastapi.tiangolo.com/tutorial/response-headers/). PR [#185](https://github.com/tiangolo/fastapi/pull/185).
* Fix typos in docs. PR [#176](https://github.com/tiangolo/fastapi/pull/176) by [@chdsbd](https://github.com/chdsbd).
## 0.19.0
* Rename _path operation decorator_ parameter `content_type` to `response_class`. PR [#183](https://github.com/tiangolo/fastapi/pull/183).
* Add docs:
* How to use the `jsonable_encoder` in [JSON compatible encoder](https://fastapi.tiangolo.com/tutorial/encoder/).
* How to [Return a Response directly](https://fastapi.tiangolo.com/tutorial/response-directly/).
* Update how to use a [Custom Response Class](https://fastapi.tiangolo.com/tutorial/custom-response/).
* PR [#184](https://github.com/tiangolo/fastapi/pull/184).
## 0.18.0
* Add docs for [HTTP Basic Auth](https://fastapi.tiangolo.com/tutorial/custom-response/). PR [#177](https://github.com/tiangolo/fastapi/pull/177).
* Upgrade HTTP Basic Auth handling with automatic headers (automatic browser login prompt). PR [#175](https://github.com/tiangolo/fastapi/pull/175).
* Update dependencies for security. PR [#174](https://github.com/tiangolo/fastapi/pull/174).
* Add docs for [Middleware](https://fastapi.tiangolo.com/tutorial/middleware/). PR [#173](https://github.com/tiangolo/fastapi/pull/173).
## 0.17.0
* Make Flit publish from CI. PR [#170](https://github.com/tiangolo/fastapi/pull/170).
* Add documentation about handling [CORS (Cross-Origin Resource Sharing)](https://fastapi.tiangolo.com/tutorial/cors/). PR [#169](https://github.com/tiangolo/fastapi/pull/169).
* By default, encode by alias. This allows using Pydantic `alias` parameters working by default. PR [#168](https://github.com/tiangolo/fastapi/pull/168).
## 0.16.0
* Upgrade _path operation_ `doctsring` parsing to support proper Markdown descriptions. New documentation at [Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#description-from-docstring). PR [#163](https://github.com/tiangolo/fastapi/pull/163).
* Refactor internal usage of Pydantic to use correct data types. PR [#164](https://github.com/tiangolo/fastapi/pull/164).
* Upgrade Pydantic to version `0.23`. PR [#160](https://github.com/tiangolo/fastapi/pull/160) by [@euri10](https://github.com/euri10).
* Fix typo in Tutorial about Extra Models. PR [#159](https://github.com/tiangolo/fastapi/pull/159) by [@danielmichaels](https://github.com/danielmichaels).
* Fix [Query Parameters](https://fastapi.tiangolo.com/tutorial/query-params/) URL examples in docs. PR [#157](https://github.com/tiangolo/fastapi/pull/157) by [@hayata-yamamoto](https://github.com/hayata-yamamoto).
## 0.15.0
* Add support for multiple file uploads (as a single form field). New docs at: [Multiple file uploads](https://fastapi.tiangolo.com/tutorial/request-files/#multiple-file-uploads). PR [#158](https://github.com/tiangolo/fastapi/pull/158).
* Add docs for: [Additional Status Codes](https://fastapi.tiangolo.com/tutorial/additional-status-codes/). PR [#156](https://github.com/tiangolo/fastapi/pull/156).
## 0.14.0
* Improve automatically generated names of path operations in OpenAPI (in API docs). A function `read_items` instead of having a generated name "Read Items Get" will have "Read Items". PR [#155](https://github.com/tiangolo/fastapi/pull/155).
* Add docs for: [Testing **FastAPI**](https://fastapi.tiangolo.com/tutorial/testing/). PR [#151](https://github.com/tiangolo/fastapi/pull/151).
* Update `/docs` Swagger UI to enable deep linking. This allows sharing the URL pointing directly to the path operation documentation in the docs. PR [#148](https://github.com/tiangolo/fastapi/pull/148) by [@wshayes](https://github.com/wshayes).
* Update development dependencies, `Pipfile.lock`. PR [#150](https://github.com/tiangolo/fastapi/pull/150).
* Include Falcon and Hug in: [Alternatives, Inspiration and Comparisons](https://fastapi.tiangolo.com/alternatives/).
## 0.13.0
* Improve/upgrade OAuth2 scopes support with `SecurityScopes`:
* `SecurityScopes` can be declared as a parameter like `Request`, to get the scopes of all super-dependencies/dependants.
* Improve `Security` handling, merging scopes when declaring `SecurityScopes`.
* Allow using `SecurityBase` (like `OAuth2`) classes with `Depends` and still document them. `Security` now is needed only to declare `scopes`.
* Updated docs about: [OAuth2 with Password (and hashing), Bearer with JWT tokens](https://fastapi.tiangolo.com/tutorial/security/oauth2-jwt/).
* New docs about: [OAuth2 scopes](https://fastapi.tiangolo.com/tutorial/security/oauth2-scopes/).
* PR [#141](https://github.com/tiangolo/fastapi/pull/141).
## 0.12.1
* Fix bug: handling additional `responses` in `APIRouter.include_router()`. PR [#140](https://github.com/tiangolo/fastapi/pull/140).
* Fix typo in SQL tutorial. PR [#138](https://github.com/tiangolo/fastapi/pull/138) by [@mostaphaRoudsari](https://github.com/mostaphaRoudsari).
* Fix typos in section about nested models and OAuth2 with JWT. PR [#127](https://github.com/tiangolo/fastapi/pull/127) by [@mmcloud](https://github.com/mmcloud).
## 0.12.0
* Add additional `responses` parameter to _path operation decorators_ to extend responses in OpenAPI (and API docs).
* It also allows extending existing responses generated from `response_model`, declare other media types (like images), etc.
* The new documentation is here: [Additional Responses](https://fastapi.tiangolo.com/tutorial/additional-responses/).
* `responses` can also be added to `.include_router()`, the updated docs are here: [Bigger Applications](https://fastapi.tiangolo.com/tutorial/bigger-applications/#add-some-custom-tags-and-responses).
* PR [#97](https://github.com/tiangolo/fastapi/pull/97) originally initiated by [@barsi](https://github.com/barsi).
* Update `scripts/test-cov-html.sh` to allow passing extra parameters like `-vv`, for development.
## 0.11.0
* Add `auto_error` parameter to security utility functions. Allowing them to be optional. Also allowing to have multiple alternative security schemes that are then checked in a single dependency instead of each one verifying and returning the error to the client automatically when not satisfied. PR [#134](https://github.com/tiangolo/fastapi/pull/134).
* Update [SQL Tutorial](https://fastapi.tiangolo.com/tutorial/sql-databases/#create-a-middleware-to-handle-sessions) to close database sessions even when there are exceptions. PR [#89](https://github.com/tiangolo/fastapi/pull/89) by [@alexiri](https://github.com/alexiri).
* Fix duplicate dependency in `pyproject.toml`. PR [#128](https://github.com/tiangolo/fastapi/pull/128) by [@zxalif](https://github.com/zxalif).
## 0.10.3
* Add Gitter chat, badge, links, etc. [https://gitter.im/tiangolo/fastapi](https://gitter.im/tiangolo/fastapi) . PR [#117](https://github.com/tiangolo/fastapi/pull/117).
* Add docs about [Extending OpenAPI](https://fastapi.tiangolo.com/tutorial/extending-openapi/). PR [#126](https://github.com/tiangolo/fastapi/pull/126).
* Make Travis run Ubuntu Xenial (newer version) and Python 3.7 instead of Python 3.7-dev. PR [#92](https://github.com/tiangolo/fastapi/pull/92) by [@blueyed](https://github.com/blueyed).
* Fix duplicated param variable creation. PR [#123](https://github.com/tiangolo/fastapi/pull/123) by [@yihuang](https://github.com/yihuang).
* Add note in [Response Model docs](https://fastapi.tiangolo.com/tutorial/response-model/) about why using a function parameter instead of a function return type annotation. PR [#109](https://github.com/tiangolo/fastapi/pull/109) by [@JHSaunders](https://github.com/JHSaunders).
* Fix event docs (startup/shutdown) function name. PR [#105](https://github.com/tiangolo/fastapi/pull/105) by [@stratosgear](https://github.com/stratosgear).
## 0.10.2
* Fix OpenAPI (JSON Schema) for declarations of Python `Union` (JSON Schema `additionalProperties`). PR [#121](https://github.com/tiangolo/fastapi/pull/121).
* Update [Background Tasks](https://fastapi.tiangolo.com/tutorial/background-tasks/) with a note on Celery.
* Document response models using unions and lists, updated at: [Extra Models](https://fastapi.tiangolo.com/tutorial/extra-models/). PR [#108](https://github.com/tiangolo/fastapi/pull/108).
## 0.10.1
* Add docs and tests for [encode/databases](https://github.com/encode/databases). New docs at: [Async SQL (Relational) Databases](https://fastapi.tiangolo.com/tutorial/async-sql-databases/). PR [#107](https://github.com/tiangolo/fastapi/pull/107).
## 0.10.0
* Add support for Background Tasks in _path operation functions_ and dependencies. New documentation about [Background Tasks is here](https://fastapi.tiangolo.com/tutorial/background-tasks/). PR [#103](https://github.com/tiangolo/fastapi/pull/103).
* Add support for `.websocket_route()` in `APIRouter`. PR [#100](https://github.com/tiangolo/fastapi/pull/100) by [@euri10](https://github.com/euri10).
* New docs section about [Events: startup - shutdown](https://fastapi.tiangolo.com/tutorial/events/). PR [#99](https://github.com/tiangolo/fastapi/pull/99).
## 0.9.1
* Document receiving [Multiple values with the same query parameter](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#query-parameter-list-multiple-values) and [Duplicate headers](https://fastapi.tiangolo.com/tutorial/header-params/#duplicate-headers). PR [#95](https://github.com/tiangolo/fastapi/pull/95).
## 0.9.0
* Upgrade compatible Pydantic version to `0.21.0`. PR [#90](https://github.com/tiangolo/fastapi/pull/90).
* Add documentation for: [Application Configuration](https://fastapi.tiangolo.com/tutorial/application-configuration/).
* Fix typo in docs. PR [#76](https://github.com/tiangolo/fastapi/pull/76) by [@matthewhegarty](https://github.com/matthewhegarty).
* Fix link in "Deployment" to "Bigger Applications".
## 0.8.0
* Make development scripts executable. PR [#76](https://github.com/tiangolo/fastapi/pull/76) by [@euri10](https://github.com/euri10).
* Add support for adding `tags` in `app.include_router()`. PR [#55](https://github.com/tiangolo/fastapi/pull/55) by [@euri10](https://github.com/euri10). Documentation updated in the section: [Bigger Applications](https://fastapi.tiangolo.com/tutorial/bigger-applications/).
* Update docs related to Uvicorn to use new `--reload` option from version `0.5.x`. PR [#74](https://github.com/tiangolo/fastapi/pull/74).
* Update `isort` imports and scripts to be compatible with newer versions. PR [#75](https://github.com/tiangolo/fastapi/pull/75).
## 0.7.1
* Update [technical details about `async def` handling](https://fastapi.tiangolo.com/async/#path-operation-functions) with respect to previous frameworks. PR [#64](https://github.com/tiangolo/fastapi/pull/64) by [@haizaar](https://github.com/haizaar).
* Add [deployment documentation for Docker in Raspberry Pi](https://fastapi.tiangolo.com/deployment/#raspberry-pi-and-other-architectures) and other architectures.
* Trigger Docker images build on Travis CI automatically. PR [#65](https://github.com/tiangolo/fastapi/pull/65).
## 0.7.0
* Add support for `UploadFile` in `File` parameter annotations.
* This includes a file-like interface.
* Here's the updated documentation for declaring [`File` parameters with `UploadFile`](https://fastapi.tiangolo.com/tutorial/request-files/#file-parameters-with-uploadfile).
* And here's the updated documentation for using [`Form` parameters mixed with `File` parameters, supporting `bytes` and `UploadFile`](https://fastapi.tiangolo.com/tutorial/request-forms-and-files/) at the same time.
* PR [#63](https://github.com/tiangolo/fastapi/pull/63).
## 0.6.4
* Add [technical details about `async def` handling to docs](https://fastapi.tiangolo.com/async/#very-technical-details). PR [#61](https://github.com/tiangolo/fastapi/pull/61).
* Add docs for [Debugging FastAPI applications in editors](https://fastapi.tiangolo.com/tutorial/debugging/).
* Clarify [Bigger Applications deployed with Docker](https://fastapi.tiangolo.com/deployment/#bigger-applications).
* Fix typos in docs.
* Add section about [History, Design and Future](https://fastapi.tiangolo.com/history-design-future/).
* Add docs for using [WebSockets with **FastAPI**](https://fastapi.tiangolo.com/tutorial/websockets/). PR [#62](https://github.com/tiangolo/fastapi/pull/62).
## 0.6.3
* Add Favicons to docs. PR [#53](https://github.com/tiangolo/fastapi/pull/53).
## 0.6.2
* Introduce new project generator based on FastAPI and PostgreSQL: [https://github.com/tiangolo/full-stack-fastapi-postgresql](https://github.com/tiangolo/full-stack-fastapi-postgresql). PR [#52](https://github.com/tiangolo/fastapi/pull/52).
* Update [SQL tutorial with SQLAlchemy, using `Depends` to improve editor support and reduce code repetition](https://fastapi.tiangolo.com/tutorial/sql-databases/). PR [#52](https://github.com/tiangolo/fastapi/pull/52).
* Improve middleware naming in tutorial for SQL with SQLAlchemy [https://fastapi.tiangolo.com/tutorial/sql-databases/](https://fastapi.tiangolo.com/tutorial/sql-databases/).
## 0.6.1
* Add docs for GraphQL: [https://fastapi.tiangolo.com/tutorial/graphql/](https://fastapi.tiangolo.com/tutorial/graphql/). PR [#48](https://github.com/tiangolo/fastapi/pull/48).
## 0.6.0
* Update SQL with SQLAlchemy tutorial at [https://fastapi.tiangolo.com/tutorial/sql-databases/](https://fastapi.tiangolo.com/tutorial/sql-databases/) using the new official `request.state`. PR [#45](https://github.com/tiangolo/fastapi/pull/45).
* Upgrade Starlette to version `0.11.1` and add required compatibility changes. PR [#44](https://github.com/tiangolo/fastapi/pull/44).
## 0.5.1
* Add section about [helping and getting help with **FastAPI**](https://fastapi.tiangolo.com/help-fastapi/).
* Add note about [path operations order in docs](https://fastapi.tiangolo.com/tutorial/path-params/#order-matters).
* Update [section about error handling](https://fastapi.tiangolo.com/tutorial/handling-errors/) with more information and make relation with Starlette error handling utilities more explicit. PR [#41](https://github.com/tiangolo/fastapi/pull/41).
* Add <a href="" target="_blank">Development - Contributing section to the docs</a>. PR [#42](https://github.com/tiangolo/fastapi/pull/42).
## 0.5.0
* Add new `HTTPException` with support for custom headers. With new documentation for handling errors at: [https://fastapi.tiangolo.com/tutorial/handling-errors/](https://fastapi.tiangolo.com/tutorial/handling-errors/). PR [#35](https://github.com/tiangolo/fastapi/pull/35).
* Add [documentation to use Starlette `Request` object](https://fastapi.tiangolo.com/tutorial/using-request-directly/) directly. Check [#25](https://github.com/tiangolo/fastapi/pull/25) by [@euri10](https://github.com/euri10).
* Add issue templates to simplify reporting bugs, getting help, etc: [#34](https://github.com/tiangolo/fastapi/pull/34).
* Update example for the SQLAlchemy tutorial at [https://fastapi.tiangolo.com/tutorial/sql-databases/](https://fastapi.tiangolo.com/tutorial/sql-databases/) using middleware and database session attached to request.
## 0.4.0
* Add `openapi_prefix`, support for reverse proxy and mounting sub-applications. See the docs at [https://fastapi.tiangolo.com/tutorial/sub-applications-proxy/](https://fastapi.tiangolo.com/tutorial/sub-applications-proxy/): [#26](https://github.com/tiangolo/fastapi/pull/26) by [@kabirkhan](https://github.com/kabirkhan).
* Update [docs/tutorial for SQLAlchemy](https://fastapi.tiangolo.com/tutorial/sql-databases/) including note about _DB Browser for SQLite_.
## 0.3.0
* Fix/add SQLAlchemy support, including ORM, and update [docs for SQLAlchemy](https://fastapi.tiangolo.com/tutorial/sql-databases/): [#30](https://github.com/tiangolo/fastapi/pull/30).
## 0.2.1
* Fix `jsonable_encoder` for Pydantic models with `Config` but without `json_encoders`: [#29](https://github.com/tiangolo/fastapi/pull/29).
## 0.2.0
* Fix typos in Security section: [#24](https://github.com/tiangolo/fastapi/pull/24) by [@kkinder](https://github.com/kkinder).
* Add support for Pydantic custom JSON encoders: [#21](https://github.com/tiangolo/fastapi/pull/21) by [@euri10](https://github.com/euri10).
## 0.1.19
* Upgrade Starlette version to the current latest `0.10.1`: [#17](https://github.com/tiangolo/fastapi/pull/17) by [@euri10](https://github.com/euri10).

View File

@@ -0,0 +1,23 @@
from fastapi import FastAPI
from pydantic import BaseModel
from starlette.responses import JSONResponse
class Item(BaseModel):
id: str
value: str
class Message(BaseModel):
message: str
app = FastAPI()
@app.get("/items/{item_id}", response_model=Item, responses={404: {"model": Message}})
async def read_item(item_id: str):
if item_id == "foo":
return {"id": "foo", "value": "there goes my hero"}
else:
return JSONResponse(status_code=404, content={"message": "Item not found"})

View File

@@ -0,0 +1,28 @@
from fastapi import FastAPI
from pydantic import BaseModel
from starlette.responses import FileResponse
class Item(BaseModel):
id: str
value: str
app = FastAPI()
@app.get(
"/items/{item_id}",
response_model=Item,
responses={
200: {
"content": {"image/png": {}},
"description": "Return the JSON item or an image.",
}
},
)
async def read_item(item_id: str, img: bool = None):
if img:
return FileResponse("image.png", media_type="image/png")
else:
return {"id": "foo", "value": "there goes my hero"}

View File

@@ -0,0 +1,37 @@
from fastapi import FastAPI
from pydantic import BaseModel
from starlette.responses import JSONResponse
class Item(BaseModel):
id: str
value: str
class Message(BaseModel):
message: str
app = FastAPI()
@app.get(
"/items/{item_id}",
response_model=Item,
responses={
404: {"model": Message, "description": "The item was not found"},
200: {
"description": "Item requested by ID",
"content": {
"application/json": {
"example": {"id": "bar", "value": "The bar tenders"}
}
},
},
},
)
async def read_item(item_id: str):
if item_id == "foo":
return {"id": "foo", "value": "there goes my hero"}
else:
return JSONResponse(status_code=404, content={"message": "Item not found"})

View File

@@ -0,0 +1,30 @@
from fastapi import FastAPI
from pydantic import BaseModel
from starlette.responses import FileResponse
class Item(BaseModel):
id: str
value: str
responses = {
404: {"description": "Item not found"},
302: {"description": "The item was moved"},
403: {"description": "Not enough privileges"},
}
app = FastAPI()
@app.get(
"/items/{item_id}",
response_model=Item,
responses={**responses, 200: {"content": {"image/png": {}}}},
)
async def read_item(item_id: str, img: bool = None):
if img:
return FileResponse("image.png", media_type="image/png")
else:
return {"id": "foo", "value": "there goes my hero"}

View File

@@ -0,0 +1,20 @@
from fastapi import Body, FastAPI
from starlette.responses import JSONResponse
from starlette.status import HTTP_201_CREATED
app = FastAPI()
items = {"foo": {"name": "Fighters", "size": 6}, "bar": {"name": "Tenders", "size": 3}}
@app.put("/items/{item_id}")
async def upsert_item(item_id: str, name: str = Body(None), size: int = Body(None)):
if item_id in items:
item = items[item_id]
item["name"] = name
item["size"] = size
return item
else:
item = {"name": name, "size": size}
items[item_id] = item
return JSONResponse(status_code=HTTP_201_CREATED, content=item)

View File

@@ -0,0 +1,8 @@
from fastapi import FastAPI
app = FastAPI()
@app.get("/")
async def read_main():
return {"msg": "Hello World"}

View File

@@ -0,0 +1,11 @@
from starlette.testclient import TestClient
from .main import app
client = TestClient(app)
def test_read_main():
response = client.get("/")
assert response.status_code == 200
assert response.json() == {"msg": "Hello World"}

View File

@@ -0,0 +1,18 @@
from fastapi import FastAPI
from starlette.testclient import TestClient
app = FastAPI()
@app.get("/")
async def read_main():
return {"msg": "Hello World"}
client = TestClient(app)
def test_read_main():
response = client.get("/")
assert response.status_code == 200
assert response.json() == {"msg": "Hello World"}

View File

@@ -0,0 +1,31 @@
from fastapi import FastAPI
from starlette.testclient import TestClient
from starlette.websockets import WebSocket
app = FastAPI()
@app.get("/")
async def read_main():
return {"msg": "Hello World"}
@app.websocket_route("/ws")
async def websocket(websocket: WebSocket):
await websocket.accept()
await websocket.send_json({"msg": "Hello WebSocket"})
await websocket.close()
def test_read_main():
client = TestClient(app)
response = client.get("/")
assert response.status_code == 200
assert response.json() == {"msg": "Hello World"}
def test_websocket():
client = TestClient(app)
with client.websocket_connect("/ws") as websocket:
data = websocket.receive_json()
assert data == {"msg": "Hello WebSocket"}

View File

@@ -0,0 +1,24 @@
from fastapi import FastAPI
from starlette.testclient import TestClient
app = FastAPI()
items = {}
@app.on_event("startup")
async def startup_event():
items["foo"] = {"name": "Fighters"}
items["bar"] = {"name": "Tenders"}
@app.get("/items/{item_id}")
async def read_items(item_id: str):
return items[item_id]
def test_read_items():
with TestClient(app) as client:
response = client.get("/items/foo")
assert response.status_code == 200
assert response.json() == {"name": "Fighters"}

View File

@@ -1,8 +1,6 @@
from fastapi import FastAPI
app = FastAPI(
title="My Super Project", version="2.5.0", openapi_url="/api/v1/openapi.json"
)
app = FastAPI(openapi_url="/api/v1/openapi.json")
@app.get("/items/")

View File

@@ -0,0 +1,8 @@
from fastapi import FastAPI
app = FastAPI(docs_url="/documentation", redoc_url=None)
@app.get("/items/")
async def read_items():
return [{"name": "Foo"}]

View File

@@ -0,0 +1,65 @@
from typing import List
import databases
import sqlalchemy
from fastapi import FastAPI
from pydantic import BaseModel
# SQLAlchemy specific code, as with any other app
DATABASE_URL = "sqlite:///./test.db"
# DATABASE_URL = "postgresql://user:password@postgresserver/db"
database = databases.Database(DATABASE_URL)
metadata = sqlalchemy.MetaData()
notes = sqlalchemy.Table(
"notes",
metadata,
sqlalchemy.Column("id", sqlalchemy.Integer, primary_key=True),
sqlalchemy.Column("text", sqlalchemy.String),
sqlalchemy.Column("completed", sqlalchemy.Boolean),
)
engine = sqlalchemy.create_engine(
DATABASE_URL, connect_args={"check_same_thread": False}
)
metadata.create_all(engine)
class NoteIn(BaseModel):
text: str
completed: bool
class Note(BaseModel):
id: int
text: str
completed: bool
app = FastAPI()
@app.on_event("startup")
async def startup():
await database.connect()
@app.on_event("shutdown")
async def shutdown():
await database.disconnect()
@app.get("/notes/", response_model=List[Note])
async def read_notes():
query = notes.select()
return await database.fetch_all(query)
@app.post("/notes/", response_model=Note)
async def create_note(note: NoteIn):
query = notes.insert().values(text=note.text, completed=note.completed)
last_record_id = await database.execute(query)
return {**note.dict(), "id": last_record_id}

View File

@@ -0,0 +1,15 @@
from fastapi import BackgroundTasks, FastAPI
app = FastAPI()
def write_notification(email: str, message=""):
with open("log.txt", mode="w") as email_file:
content = f"notification for {email}: {message}"
email_file.write(content)
@app.post("/send-notification/{email}")
async def send_notification(email: str, background_tasks: BackgroundTasks):
background_tasks.add_task(write_notification, email, message="some notification")
return {"message": "Notification sent in the background"}

View File

@@ -0,0 +1,24 @@
from fastapi import BackgroundTasks, Depends, FastAPI
app = FastAPI()
def write_log(message: str):
with open("log.txt", mode="a") as log:
log.write(message)
def get_query(background_tasks: BackgroundTasks, q: str = None):
if q:
message = f"found query: {q}\n"
background_tasks.add_task(write_log, message)
return q
@app.post("/send-notification/{email}")
async def send_notification(
email: str, background_tasks: BackgroundTasks, q: str = Depends(get_query)
):
message = f"message to {email}\n"
background_tasks.add_task(write_log, message)
return {"message": "Message sent"}

View File

View File

View File

@@ -0,0 +1,13 @@
from fastapi import FastAPI
from .routers import items, users
app = FastAPI()
app.include_router(users.router)
app.include_router(
items.router,
prefix="/items",
tags=["items"],
responses={404: {"description": "Not found"}},
)

View File

View File

@@ -0,0 +1,24 @@
from fastapi import APIRouter, HTTPException
router = APIRouter()
@router.get("/")
async def read_items():
return [{"name": "Item Foo"}, {"name": "item Bar"}]
@router.get("/{item_id}")
async def read_item(item_id: str):
return {"name": "Fake Specific Item", "item_id": item_id}
@router.put(
"/{item_id}",
tags=["custom"],
responses={403: {"description": "Operation forbidden"}},
)
async def update_item(item_id: str):
if item_id != "foo":
raise HTTPException(status_code=403, detail="You can only update the item: foo")
return {"item_id": item_id, "name": "The Fighters"}

View File

@@ -3,16 +3,16 @@ from fastapi import APIRouter
router = APIRouter()
@router.get("/users/")
@router.get("/users/", tags=["users"])
async def read_users():
return [{"username": "Foo"}, {"username": "Bar"}]
@router.get("/users/{username}")
async def read_user(username: str):
return {"username": username}
@router.get("/users/me")
@router.get("/users/me", tags=["users"])
async def read_user_me():
return {"username": "fakecurrentuser"}
@router.get("/users/{username}", tags=["users"])
async def read_user(username: str):
return {"username": username}

View File

@@ -15,7 +15,7 @@ class Item(BaseModel):
async def update_item(
*,
item_id: int = Path(..., title="The ID of the item to get", ge=0, le=1000),
q: str,
q: str = None,
item: Item = None,
):
results = {"item_id": item_id}

Some files were not shown because too many files have changed in this diff Show More