Compare commits

...

160 Commits

Author SHA1 Message Date
Sebastián Ramírez
717a1ec409 🔖 Release version 0.68.0 2021-07-29 23:03:57 +02:00
Sebastián Ramírez
eba2c66532 🔖 Update release notes 2021-07-29 23:02:42 +02:00
github-actions
3788ca4640 📝 Update release notes 2021-07-29 21:00:53 +00:00
Sebastián Ramírez
97fa743ecb Update OpenAPI models, supporting recursive models and extensions (#3628) 2021-07-29 20:59:26 +00:00
github-actions
e726b7b771 📝 Update release notes 2021-07-29 20:28:25 +00:00
github-actions
6a22b75afd 📝 Update release notes 2021-07-29 20:25:17 +00:00
github-actions
4093d9b22a 📝 Update release notes 2021-07-29 20:23:19 +00:00
Urchin
18daf8f301 🌐 Add Russian translation for docs/python-types.md (#3039) 2021-07-29 22:22:43 +02:00
jaystone776
962578bec2 🌐 Add Chinese translation for docs/tutorial/dependencies/index.md (#3489)
Co-authored-by: Sebastián Ramírez <tiangolo@gmail.com>
2021-07-29 22:21:38 +02:00
Urchin
85cff59109 🌐 Add Russian translation for docs/external-links.md (#3036) 2021-07-29 20:21:06 +00:00
github-actions
b869c7c872 📝 Update release notes 2021-07-29 20:16:29 +00:00
jaystone776
016c3f0d5b 🌐 Add Chinese translation for docs/tutorial/dependencies/global-dependencies.md (#3493)
as title
2021-07-29 22:15:54 +02:00
github-actions
4eb9c60652 📝 Update release notes 2021-07-29 20:15:22 +00:00
Lucas
8879757a88 🌐 Add Portuguese translation for docs/deployment/versions.md (#3618)
Co-authored-by: Marcelo Trylesinski <marcelotryle@gmail.com>
2021-07-29 22:14:40 +02:00
Sebastián Ramírez
fadfcfda4a 📝 Update release notes 2021-07-29 22:12:55 +02:00
github-actions
b8c4149e89 📝 Update release notes 2021-07-29 20:01:49 +00:00
Edouard Lavery-Plante
836bb97a2d Add support for extensions and updates to the OpenAPI schema in path operations (#1922)
Co-authored-by: Sebastián Ramírez <tiangolo@gmail.com>
2021-07-29 22:01:13 +02:00
github-actions
7db359182d 📝 Update release notes 2021-07-29 15:30:57 +00:00
James Curtin
4eada92883 Import and re-export data structures from Starlette, used by Request properties, on fastapi.datastructures (#1872)
Co-authored-by: Sebastián Ramírez <tiangolo@gmail.com>
2021-07-29 17:30:18 +02:00
github-actions
6a74f3a0c1 📝 Update release notes 2021-07-29 15:18:55 +00:00
Edward Knight
daa0765653 📝 Update docs about async and response-model with more gender neutral language (#1869) 2021-07-29 17:18:20 +02:00
github-actions
27e26b5939 📝 Update release notes 2021-07-29 15:10:59 +00:00
dkreeft
6f45f43709 Add additonal OpenAPI metadata parameters to FastAPI class, shown on the automatic API docs UI (#1812)
Co-authored-by: Marcelo Trylesinski <marcelotryle@gmail.com>
Co-authored-by: dkreeft <dkreeft@xccelerated.io>
Co-authored-by: Sebastián Ramírez <tiangolo@gmail.com>
2021-07-29 17:10:22 +02:00
github-actions
6c80e9a8e0 📝 Update release notes 2021-07-29 10:31:22 +00:00
Hylke Postma
3b2e891917 Add description parameter to all the security scheme classes, e.g. APIKeyQuery(name="key", description="A very cool API key") (#1757)
Co-authored-by: Hylke Postma <h.postma@docuwork.nl>
Co-authored-by: Sebastián Ramírez <tiangolo@gmail.com>
2021-07-29 12:30:48 +02:00
github-actions
9121fccf55 📝 Update release notes 2021-07-29 09:26:40 +00:00
Marcelo Trylesinski
fa2c750443 Add the docs_src directory to test coverage and update tests (#1904)
Co-authored-by: Sebastián Ramírez <tiangolo@gmail.com>
2021-07-29 11:26:07 +02:00
github-actions
29e7b31ee6 📝 Update release notes 2021-07-28 15:36:03 +00:00
Yuya Sato
bb6c6ed5d1 🌐 Add Japanese translation for docs/tutorial/security/oauth2-jwt.md (#3526)
Co-authored-by: tokusumi <41147016+tokusumi@users.noreply.github.com>
Co-authored-by: Sho Nakamura <sh0nk.developer@gmail.com>
2021-07-28 17:35:25 +02:00
github-actions
1a5273773e 📝 Update release notes 2021-07-27 10:23:49 +00:00
Sebastián Ramírez
3f40c37905 🔧 Add new GitHub templates with forms for new issues (#3612) 2021-07-27 10:23:09 +00:00
Sebastián Ramírez
996dfd05bd 📝 Update release notes 2021-07-21 21:15:58 +02:00
github-actions
0a1dd7894c 📝 Update release notes 2021-07-21 19:14:32 +00:00
Sebastián Ramírez
dbfd3f7e18 📝 Add official FastAPI Twitter to docs (#3578) 2021-07-21 21:13:58 +02:00
Sebastián Ramírez
a0209a0d2c 🔖 Release version 0.67.0 2021-07-21 20:00:39 +02:00
Sebastián Ramírez
099aab79e6 📝 Update release notes 2021-07-21 19:59:38 +02:00
github-actions
7dc5b94d45 📝 Update release notes 2021-07-21 17:54:42 +00:00
Sebastián Ramírez
684c0077cc Add support for dataclasses in request bodies and response_model (#3577) 2021-07-21 19:54:08 +02:00
github-actions
75d8a6b5c2 📝 Update release notes 2021-07-21 14:39:54 +00:00
Sebastián Ramírez
96fdfc53cc Support dataclasses in responses (#3576)
Co-authored-by: amit lissack <amit@opentrons.com>
2021-07-21 14:39:12 +00:00
github-actions
49517d3310 📝 Update release notes 2021-07-21 13:16:08 +00:00
Ehigie Aito
9355cc4eaa 📝 Add external link: How to Create A Fake Certificate Authority And Generate TLS Certs for FastAPI (#2839)
Co-authored-by: Sebastián Ramírez <tiangolo@gmail.com>
2021-07-21 13:15:33 +00:00
github-actions
1ce59152e7 📝 Update release notes 2021-07-21 12:44:53 +00:00
jaystone776
1241f7f0b7 ✏ Fix code highlighted line in: body-nested-models.md (#3463) 2021-07-21 14:44:15 +02:00
github-actions
fd74c0f6a4 📝 Update release notes 2021-07-21 12:42:05 +00:00
jaystone776
e4eac12c34 ✏ Fix typo in body-nested-models.md (#3462)
Typo in line 201, *where* should be *were*
2021-07-21 14:41:24 +02:00
github-actions
b235653a6c 📝 Update release notes 2021-07-21 12:37:40 +00:00
David Brakman
4cb4bdb984 ✏ Fix typo "might me" -> "might be" in docs/en/docs/tutorial/schema-extra-example.md (#3362)
Co-authored-by: Sebastián Ramírez <tiangolo@gmail.com>
2021-07-21 12:37:06 +00:00
github-actions
ba596152d9 📝 Update release notes 2021-07-21 12:28:48 +00:00
Shahriyar Rzayev
a1227624c8 📝 Add external link: Building simple E-Commerce with NuxtJS and FastAPI (#3271)
Co-authored-by: Sebastián Ramírez <tiangolo@gmail.com>
2021-07-21 12:28:15 +00:00
github-actions
9ce1ae771c 📝 Update release notes 2021-07-21 12:21:46 +00:00
Rodrigo Arenas
b9fed9b485 📝 Add external link: Serve a machine learning model using Sklearn, FastAPI and Docker (#2974)
Co-authored-by: rodrigoarenas456 <31422766+rodrigoarenas456@users.noreply.github.com>
Co-authored-by: Sebastián Ramírez <tiangolo@gmail.com>
2021-07-21 14:20:53 +02:00
github-actions
0d97e1f97d 📝 Update release notes 2021-07-21 12:15:08 +00:00
Marcelo Trylesinski
1ce7258a01 ✏️ Fix typo on docstring in datastructures file (#2887) 2021-07-21 14:14:34 +02:00
github-actions
bcd06fdfdf 📝 Update release notes 2021-07-21 12:11:22 +00:00
Marcelo Trylesinski
fc35b7d18d 🎨 Improve style for sponsors, add radius border (#2388)
Co-authored-by: Sebastián Ramírez <tiangolo@gmail.com>
2021-07-21 14:10:47 +02:00
github-actions
8c12ab0d5b 📝 Update release notes 2021-07-21 11:15:03 +00:00
Sebastián Ramírez
38194a29bc 📝 Add External Link: Deploy FastAPI on Ubuntu and Serve using Caddy 2 Web Server (#3572) 2021-07-21 13:14:28 +02:00
github-actions
6b65de6033 📝 Update release notes 2021-07-21 11:12:47 +00:00
github-actions
f80230d654 📝 Update release notes 2021-07-21 11:11:43 +00:00
github-actions
f6cc418d79 📝 Update release notes 2021-07-21 11:10:13 +00:00
github-actions
3ce9407093 📝 Update release notes 2021-07-21 11:08:47 +00:00
github-actions
ef1716c39e 📝 Update release notes 2021-07-21 10:42:13 +00:00
Sebastián Ramírez
9ab7da6562 👷 Update GitHub Action latest-changes, strike 2 (#3575) 2021-07-21 10:41:32 +00:00
Sebastián Ramírez
fcfff5e8e5 👷 Update GitHub Action latest-changes (#3574) 2021-07-21 10:33:42 +00:00
Sebastián Ramírez
67ef62a4dd 👷 Update GitHub Action latest-changes (#3573) 2021-07-21 09:54:27 +00:00
Sebastián Ramírez
7741635b3b 🔧 Add External Link, replaces #1898 (#3571) 2021-07-21 09:39:12 +00:00
Sebastián Ramírez
3d81bc638b 👷 Rename and clarify CI workflow job names (#3570) 2021-07-21 11:24:40 +02:00
github-actions
c1801738b0 📝 Update release notes 2021-07-21 08:52:50 +00:00
Sebastián Ramírez
ba84f167f5 🔧 Sort external links in docs to have the most recent at the top (#3568) 2021-07-21 10:52:10 +02:00
Sebastián Ramírez
0a38c51b9e 🔖 Release 0.66.1 2021-07-19 21:26:52 +02:00
Sebastián Ramírez
db5b2bdf56 📝 Update release notes 2021-07-19 21:21:40 +02:00
github-actions
5ac84120b3 📝 Update release notes 2021-07-19 19:15:35 +00:00
Thomas Grainger
2d296c5d07 🔧 Configure strict pytest options and update/refactor tests (#2790)
Co-authored-by: Sebastián Ramírez <tiangolo@gmail.com>
2021-07-19 21:14:58 +02:00
github-actions
71c96d9eb9 📝 Update release notes 2021-07-19 12:49:41 +00:00
Mark H
5342a0a00f 🌐 Add basic setup for German translations (#3522) 2021-07-19 14:49:09 +02:00
github-actions
163b086f21 📝 Update release notes 2021-07-19 12:47:20 +00:00
oandersonmagalhaes
0876d3df1d 🌐 Add Portuguese translation for docs/tutorial/security/index.md (#3507)
Co-authored-by: Izabela Guerreiro <izaguerreiro@gmail.com>
Co-authored-by: Sebastián Ramírez <tiangolo@gmail.com>
2021-07-19 14:46:39 +02:00
github-actions
50baf5e804 📝 Update release notes 2021-07-19 12:33:34 +00:00
Lucas
3d6da2c32d 🌐 Add Portuguese translation for docs/deployment/index.md (#3337) 2021-07-19 14:32:54 +02:00
github-actions
e721d04350 📝 Update release notes 2021-07-05 11:45:43 +00:00
Sebastián Ramírez
8cc6f9baac ⬆️ Upgrade python-jose dependency for tests (#3468) 2021-07-05 13:45:03 +02:00
Sebastián Ramírez
dfd453e001 📝 Update release notes 2021-07-04 21:18:45 +02:00
Sebastián Ramírez
7e9d5aacf8 🔖 Release version 0.66.0 2021-07-04 20:59:46 +02:00
Sebastián Ramírez
d27a218bc3 📝 Update release notes 2021-07-04 20:58:49 +02:00
github-actions
0c4ded88fe 📝 Update release notes 2021-07-04 18:54:19 +00:00
Rubikoid
0e0931d308 🐛 Fix include/exclude for dicts in jsonable_encoder (#2016)
Co-authored-by: Sebastián Ramírez <tiangolo@gmail.com>
2021-07-04 20:53:40 +02:00
github-actions
dcfa9eb8fe 📝 Update release notes 2021-07-04 17:35:19 +00:00
Camila Gutierrez
6ebf60b175 🌐 Add Spanish translation for tutorial/query-params.md (#2243)
Co-authored-by: Sebastián Ramírez <tiangolo@gmail.com>
2021-07-04 19:34:46 +02:00
github-actions
a4d0724a97 📝 Update release notes 2021-07-04 17:06:51 +00:00
Juan Funez
c235e9b78c 🌐 Add Spanish translation for advanced/response-directly.md (#1253)
Co-authored-by: Camila Gutierrez <mariacamilagl30@gmail.com>
2021-07-04 19:06:18 +02:00
github-actions
5fa3e239db 📝 Update release notes 2021-07-04 14:15:04 +00:00
Juan Funez
3d1b107d70 🌐 Add Spanish translation for advanced/additional-status-codes.md (#1252)
Co-authored-by: Camila Gutierrez <mariacamilagl30@gmail.com>
2021-07-04 16:14:29 +02:00
github-actions
18e0828daf 📝 Update release notes 2021-07-04 12:50:02 +00:00
Juan Funez
f16c7729bd 🌐 Add Spanish translation for advanced/path-operation-advanced-configuration.md (#1251)
Co-authored-by: Camila Gutierrez <mariacamilagl@users.noreply.github.com>
Co-authored-by: Sebastián Ramírez <tiangolo@gmail.com>
Co-authored-by: Camila Gutierrez <mariacamilagl30@gmail.com>
2021-07-04 14:49:31 +02:00
Sebastián Ramírez
9f3c8cd139 📝 Update release notes, add links to docs 2021-07-03 21:59:39 +02:00
github-actions
a7a35aee61 📝 Update release notes 2021-07-03 19:52:03 +00:00
Sebastián Ramírez
dc5a966548 Allow setting the response_class to RedirectResponse and returning the URL from the function (#3457) 2021-07-03 21:51:28 +02:00
github-actions
ea8d7f689e 📝 Update release notes 2021-07-03 17:16:33 +00:00
Jacob Magnusson
0ed6c92341 🐛 Support custom OpenAPI / JSON Schema fields in the generated output OpenAPI (#1429)
Co-authored-by: Sebastián Ramírez <tiangolo@gmail.com>
2021-07-03 19:15:59 +02:00
Sebastián Ramírez
79f52c76cf 🔖 Release version 0.65.3 2021-07-03 18:33:32 +02:00
Sebastián Ramírez
b725e9eb45 📝 Update release notes 2021-07-03 18:32:50 +02:00
Sebastián Ramírez
787e54b096 📝 Update release notes 2021-07-03 18:30:46 +02:00
github-actions
15fd60b29a 📝 Update release notes 2021-07-03 16:26:48 +00:00
Sebastián Ramírez
edf6b2d61f ♻ Assume request bodies contain JSON when no Content-Type header is provided (#3456) 2021-07-03 18:25:12 +02:00
github-actions
7eb17fc874 📝 Update release notes 2021-07-03 15:13:30 +00:00
Nasaruddin
7e4bfaf0e9 🌐 Initialize Indonesian translations (#3014)
Co-authored-by: Nasaruddin <nasaruddin@skorpoints.com>
2021-07-03 17:12:51 +02:00
github-actions
e1d4fc5325 📝 Update release notes 2021-07-03 14:47:21 +00:00
Camila Gutierrez
faec748ef6 🌐 Add Spanish translation of Tutorial - Path Parameters (#2219)
Co-authored-by: Pedro A. Moreno <pedabraham@gmail.com>
Co-authored-by: Sebastián Ramírez <tiangolo@gmail.com>
2021-07-03 16:46:49 +02:00
github-actions
afec8c4580 📝 Update release notes 2021-07-03 14:14:01 +00:00
Camila Gutierrez
8a1f0aa3b6 🌐 Add Spanish translation of Tutorial - First Steps (#2208)
Co-authored-by: Sebastián Ramírez <tiangolo@gmail.com>
2021-07-03 16:13:28 +02:00
github-actions
f784644510 📝 Update release notes 2021-07-02 15:18:24 +00:00
github-actions[bot]
710a2f745c 👥 Update FastAPI People (#3450)
Co-authored-by: github-actions <github-actions@github.com>
Co-authored-by: Sebastián Ramírez <tiangolo@gmail.com>
2021-07-02 17:17:49 +02:00
github-actions
bd230fe473 📝 Update release notes 2021-07-02 15:00:53 +00:00
Mário Victor Ribeiro Silva
9c5b000956 🌐 Portuguese translation of Tutorial - Body - Fields (#3420)
Co-authored-by: Sebastián Ramírez <tiangolo@gmail.com>
2021-07-02 17:00:11 +02:00
github-actions
a9f2a25feb 📝 Update release notes 2021-07-02 14:54:56 +00:00
jaystone776
c00c2d1ecf 🌐 Add Chinese translation for Tutorial - Request - Forms - and - Files (#3249)
Co-authored-by: Sebastián Ramírez <tiangolo@gmail.com>
2021-07-02 16:54:22 +02:00
github-actions
dd7bbae837 📝 Update release notes 2021-07-02 14:44:04 +00:00
jaystone776
0a84d48a82 🌐 Add Chinese translation for Tutorial - Handling - Errors (#3299)
Co-authored-by: Sebastián Ramírez <tiangolo@gmail.com>
2021-07-02 16:43:28 +02:00
github-actions
e5d0b97dee 📝 Update release notes 2021-07-02 14:36:34 +00:00
jaystone776
811c3f873f 🌐 Add Chinese translation for Tutorial - Form - Data (#3248)
Co-authored-by: Sebastián Ramírez <tiangolo@gmail.com>
2021-07-02 16:35:58 +02:00
github-actions
662fc81544 📝 Update release notes 2021-07-02 14:27:36 +00:00
github-actions[bot]
5e2f2d541d 👥 Update FastAPI People (#3319)
Co-authored-by: github-actions <github-actions@github.com>
2021-07-02 16:27:02 +02:00
github-actions
8116d8158b 📝 Update release notes 2021-07-02 14:24:16 +00:00
jaystone776
e6836781d5 🌐 Add Chinese translation for Tutorial - Body - Updates (#3237)
Co-authored-by: Xie Wei <ampedee@gmail.com>
Co-authored-by: Sebastián Ramírez <tiangolo@gmail.com>
2021-07-02 16:23:41 +02:00
github-actions
098088c763 📝 Update release notes 2021-07-02 14:21:11 +00:00
Hareru
4bf9a52043 🌐 Add Chinese translation for FastAPI People (#3112)
Co-authored-by: Xie Wei <ampedee@gmail.com>
Co-authored-by: Sebastián Ramírez <tiangolo@gmail.com>
2021-07-02 16:20:36 +02:00
github-actions
eb6f964ede 📝 Update release notes 2021-07-02 14:18:44 +00:00
Sam Courtemanche
4473a9bcbf 🌐 Add French translation for Project Generation (#3197)
Co-authored-by: Sebastián Ramírez <tiangolo@gmail.com>
2021-07-02 16:18:06 +02:00
github-actions
fdc7c96ece 📝 Update release notes 2021-07-02 14:14:28 +00:00
Sam Courtemanche
a694be81ae 🌐 Add French translation for Python Types Intro (#3185) 2021-07-02 16:13:52 +02:00
github-actions
0abb743e9c 📝 Update release notes 2021-07-02 14:12:43 +00:00
Sam Courtemanche
acda3f06b0 🌐 Add French translation for External Links (#3103)
Co-authored-by: Sebastián Ramírez <tiangolo@gmail.com>
2021-07-02 16:12:05 +02:00
github-actions
3127bc4e05 📝 Update release notes 2021-07-02 14:06:45 +00:00
Ruidy
18b24df9c8 🌐 Add French translation for Alternatives, Inspiration and Comparisons (#3020)
Co-authored-by: Jérôme Fink <jerome.fink@student.unamur.be>
Co-authored-by: Sam Courtemanche <sam.courtemanche.ipod@gmail.com>
2021-07-02 16:06:10 +02:00
github-actions
b27758fe13 📝 Update release notes 2021-07-02 14:03:22 +00:00
BoYanZh
a0b2006230 🌐 Fix Chinese translation code snippet mismatch in Tutorial - Python Types Intro 2021-07-02 16:02:45 +02:00
github-actions
bd143ffa5a 📝 Update release notes 2021-07-02 13:43:04 +00:00
Fabio Serrao
77c1988a8b 🌐 Add Portuguese translation for Development Contributing (#1364) 2021-07-02 15:42:29 +02:00
github-actions
26a36f79fa 📝 Update release notes 2021-06-29 21:23:00 +00:00
Sebastián Ramírez
97d8d4016b ⬆ Upgrade docs development dependency on typer-cli to >=0.0.12 to fix conflicts (#3429) 2021-06-29 23:22:23 +02:00
github-actions
246e80512d 📝 Update release notes 2021-06-29 12:24:59 +00:00
jaystone776
fc6827d68a 🌐 Add Chinese translation for Tutorial - Request - Files (#3244)
Co-authored-by: Xie Wei <ampedee@gmail.com>
2021-06-29 14:24:19 +02:00
Sebastián Ramírez
4d91f978d2 🔖 Release version 0.65.2 2021-06-09 10:17:27 +02:00
Sebastián Ramírez
aabe2c7d66 📝 Update release notes 2021-06-09 10:16:25 +02:00
Sebastián Ramírez
377234ad8e 🔒 Create Security Policy 2021-06-07 14:55:40 +02:00
github-actions
38b785813f 📝 Update release notes 2021-06-07 10:46:59 +00:00
Patrick Wang
fa7e3c996e 🐛 Check Content-Type request header before assuming JSON (#2118)
Co-authored-by: Patrick Wang <patrickkwang@users.noreply.github.com>
Co-authored-by: Sebastián Ramírez <tiangolo@gmail.com>
2021-06-07 12:46:18 +02:00
github-actions
90120dd6e8 📝 Update release notes 2021-06-07 08:53:24 +00:00
Sebastián Ramírez
36772548b7 🔧 Update sponsors badge, course bundle (#3340)
* 🔧 Update sponsors badge, course bundle

* 🍱 Update course bundle SVG sizes
2021-06-07 10:52:44 +02:00
github-actions
40bb0c5f36 📝 Update release notes 2021-05-26 09:26:47 +00:00
Sebastián Ramírez
60918d25a1 🔧 Add new gold sponsor Jina 🎉 (#3291) 2021-05-26 11:26:06 +02:00
github-actions
3afce2c4b8 📝 Update release notes 2021-05-25 15:06:28 +00:00
Sebastián Ramírez
9f6f25d54c 🔧 Add new banner sponsor badge for FastAPI courses bundle (#3288) 2021-05-25 17:05:39 +02:00
Sebastián Ramírez
d5b09cd958 🔧 Add new banner sponsor badge for FastAPI courses bundle (#3288) 2021-05-25 17:05:04 +02:00
github-actions
aece74982d 📝 Update release notes 2021-05-16 18:28:24 +00:00
Sebastián Ramírez
2b1e5b9f82 👷 Upgrade Issue Manager GitHub Action (#3236) 2021-05-16 20:27:45 +02:00
Sebastián Ramírez
43df5d05ed 🔖 Release FastAPI version 0.65.1 2021-05-11 23:19:14 +02:00
github-actions
eaa49ebd20 📝 Update release notes 2021-05-11 21:17:51 +00:00
Sebastián Ramírez
a6293397bc 📌 Upgrade pydantic pin, to handle security vulnerability CVE-2021-29510 (#3213) 2021-05-11 23:17:17 +02:00
163 changed files with 12368 additions and 841 deletions

View File

@@ -1 +1,4 @@
blank_issues_enabled: false
contact_links:
- name: Security Contact
about: Please report security vulnerabilities to security@tiangolo.com

View File

@@ -0,0 +1,181 @@
name: Feature Request
description: Suggest an idea or ask for a feature that you would like to have in FastAPI
labels: [enhancement]
body:
- type: markdown
attributes:
value: |
Thanks for your interest in FastAPI! 🚀
Please follow these instructions, fill every question, and do every step. 🙏
I'm asking this because answering questions and solving problems in GitHub issues is what consumes most of the time.
I end up not being able to add new features, fix bugs, review pull requests, etc. as fast as I wish because I have to spend too much time handling issues.
All that, on top of all the incredible help provided by a bunch of community members, the [FastAPI Experts](https://fastapi.tiangolo.com/fastapi-people/#experts), that give a lot of their time to come here and help others.
That's a lot of work they are doing, but if more FastAPI users came to help others like them just a little bit more, it would be much less effort for them (and you and me 😅).
By asking questions in a structured way (following this) it will be much easier to help you.
And there's a high chance that you will find the solution along the way and you won't even have to submit it and wait for an answer. 😎
As there are too many issues with questions, I'll have to close the incomplete ones. That will allow me (and others) to focus on helping people like you that follow the whole process and help us help you. 🤓
- type: checkboxes
id: checks
attributes:
label: First Check
description: Please confirm and check all the following options.
options:
- label: I added a very descriptive title to this issue.
required: true
- label: I used the GitHub search to find a similar issue and didn't find it.
required: true
- label: I searched the FastAPI documentation, with the integrated search.
required: true
- label: I already searched in Google "How to X in FastAPI" and didn't find any information.
required: true
- label: I already read and followed all the tutorial in the docs and didn't find an answer.
required: true
- label: I already checked if it is not related to FastAPI but to [Pydantic](https://github.com/samuelcolvin/pydantic).
required: true
- label: I already checked if it is not related to FastAPI but to [Swagger UI](https://github.com/swagger-api/swagger-ui).
required: true
- label: I already checked if it is not related to FastAPI but to [ReDoc](https://github.com/Redocly/redoc).
required: true
- type: checkboxes
id: help
attributes:
label: Commit to Help
description: |
After submitting this, I commit to one of:
* Read open issues with questions until I find 2 issues where I can help someone and add a comment to help there.
* I already hit the "watch" button in this repository to receive notifications and I commit to help at least 2 people that ask questions in the future.
* Implement a Pull Request for a confirmed bug.
options:
- label: I commit to help with one of those options 👆
required: true
- type: textarea
id: example
attributes:
label: Example Code
description: |
Please add a self-contained, [minimal, reproducible, example](https://stackoverflow.com/help/minimal-reproducible-example) with your use case.
If I (or someone) can copy it, run it, and see it right away, there's a much higher chance I (or someone) will be able to help you.
placeholder: |
from fastapi import FastAPI
app = FastAPI()
@app.get("/")
def read_root():
return {"Hello": "World"}
render: python
validations:
required: true
- type: textarea
id: description
attributes:
label: Description
description: |
What is your feature request?
Write a short description telling me what you are trying to solve and what you are currently doing.
placeholder: |
* Open the browser and call the endpoint `/`.
* It returns a JSON with `{"Hello": "World"}`.
* I would like it to have an extra parameter to teleport me to the moon and back.
validations:
required: true
- type: textarea
id: wanted-solution
attributes:
label: Wanted Solution
description: |
Tell me what's the solution you would like.
placeholder: |
I would like it to have a `teleport_to_moon` parameter that defaults to `False`, and can be set to `True` to teleport me.
validations:
required: true
- type: textarea
id: wanted-code
attributes:
label: Wanted Code
description: Show me an example of how you would want the code to look like.
placeholder: |
from fastapi import FastAPI
app = FastAPI()
@app.get("/", teleport_to_moon=True)
def read_root():
return {"Hello": "World"}
render: python
validations:
required: true
- type: textarea
id: alternatives
attributes:
label: Alternatives
description: |
Tell me about alternatives you've considered.
placeholder: |
To wait for Space X moon travel plans to drop down long after they release them. But I would rather teleport.
- type: dropdown
id: os
attributes:
label: Operating System
description: What operating system are you on?
multiple: true
options:
- Linux
- Windows
- macOS
- Other
validations:
required: true
- type: textarea
id: os-details
attributes:
label: Operating System Details
description: You can add more details about your operating system here, in particular if you chose "Other".
- type: input
id: fastapi-version
attributes:
label: FastAPI Version
description: |
What FastAPI version are you using?
You can find the FastAPI version with:
```bash
python -c "import fastapi; print(fastapi.__version__)"
```
validations:
required: true
- type: input
id: python-version
attributes:
label: Python Version
description: |
What Python version are you using?
You can find the Python version with:
```bash
python --version
```
validations:
required: true
- type: textarea
id: context
attributes:
label: Additional Context
description: Add any additional context information or screenshots you think are useful.

View File

@@ -1,104 +0,0 @@
---
name: Feature request
about: Suggest an idea for this project
title: ""
labels: enhancement
assignees: ''
---
### First check
* [ ] I added a very descriptive title to this issue.
* [ ] I used the GitHub search to find a similar issue and didn't find it.
* [ ] I searched the FastAPI documentation, with the integrated search.
* [ ] I already searched in Google "How to X in FastAPI" and didn't find any information.
* [ ] I already read and followed all the tutorial in the docs and didn't find an answer.
* [ ] I already checked if it is not related to FastAPI but to [Pydantic](https://github.com/samuelcolvin/pydantic).
* [ ] I already checked if it is not related to FastAPI but to [Swagger UI](https://github.com/swagger-api/swagger-ui).
* [ ] I already checked if it is not related to FastAPI but to [ReDoc](https://github.com/Redocly/redoc).
* [ ] After submitting this, I commit to:
* Read open issues with questions until I find 2 issues where I can help someone and add a comment to help there.
* Or, I already hit the "watch" button in this repository to receive notifications and I commit to help at least 2 people that ask questions in the future.
* Implement a Pull Request for a confirmed bug.
<!--
I'm asking all this because answering questions and solving problems in GitHub issues consumes a lot of time. I end up not being able to add new features, fix bugs, review Pull Requests, etc. as fast as I wish because I have to spend too much time handling issues.
All that, on top of all the incredible help provided by a bunch of community members that give a lot of their time to come here and help others.
That's a lot of work they are doing, but if more FastAPI users came to help others like them just a little bit more, it would be much less effort for them (and you and me 😅).
-->
### Example
Here's a self-contained [minimal, reproducible, example](https://stackoverflow.com/help/minimal-reproducible-example) with my use case:
<!-- Replace the code below with your own self-contained, minimal, reproducible, example -->
```Python
from fastapi import FastAPI
app = FastAPI()
@app.get("/")
def read_root():
return {"Hello": "World"}
```
### Description
<!-- Replace the content below with your own feature request -->
* Open the browser and call the endpoint `/`.
* It returns a JSON with `{"Hello": "World"}`.
* I would like it to have an extra parameter to teleport me to the moon and back.
### The solution you would like
<!-- Replace this with your own content -->
I would like it to have a `teleport_to_moon` parameter that defaults to `False`, and can be set to `True` to teleport me:
```Python
from fastapi import FastAPI
app = FastAPI()
@app.get("/", teleport_to_moon=True)
def read_root():
return {"Hello": "World"}
```
### Describe alternatives you've considered
<!-- Replace this with your own ideas -->
To wait for Space X moon travel plans to drop down long after they release them. But I would rather teleport.
### Environment
* OS: [e.g. Linux / Windows / macOS]:
* FastAPI Version [e.g. 0.3.0]:
To know the FastAPI version use:
```bash
python -c "import fastapi; print(fastapi.__version__)"
```
* Python version:
To know the Python version use:
```bash
python --version
```
### Additional context
<!-- Add any other context or screenshots about the question here. -->

View File

@@ -1,81 +0,0 @@
---
name: Question or Problem
about: Ask a question or ask about a problem
title: ""
labels: question
assignees: ""
---
### First check
* [ ] I added a very descriptive title to this issue.
* [ ] I used the GitHub search to find a similar issue and didn't find it.
* [ ] I searched the FastAPI documentation, with the integrated search.
* [ ] I already searched in Google "How to X in FastAPI" and didn't find any information.
* [ ] I already read and followed all the tutorial in the docs and didn't find an answer.
* [ ] I already checked if it is not related to FastAPI but to [Pydantic](https://github.com/samuelcolvin/pydantic).
* [ ] I already checked if it is not related to FastAPI but to [Swagger UI](https://github.com/swagger-api/swagger-ui).
* [ ] I already checked if it is not related to FastAPI but to [ReDoc](https://github.com/Redocly/redoc).
* [ ] After submitting this, I commit to one of:
* Read open issues with questions until I find 2 issues where I can help someone and add a comment to help there.
* I already hit the "watch" button in this repository to receive notifications and I commit to help at least 2 people that ask questions in the future.
* Implement a Pull Request for a confirmed bug.
<!--
I'm asking all this because answering questions and solving problems in GitHub issues consumes a lot of time. I end up not being able to add new features, fix bugs, review Pull Requests, etc. as fast as I wish because I have to spend too much time handling issues.
All that, on top of all the incredible help provided by a bunch of community members that give a lot of their time to come here and help others.
That's a lot of work they are doing, but if more FastAPI users came to help others like them just a little bit more, it would be much less effort for them (and you and me 😅).
-->
### Example
Here's a self-contained, [minimal, reproducible, example](https://stackoverflow.com/help/minimal-reproducible-example) with my use case:
<!-- Replace the code below with your own self-contained, minimal, reproducible, example, if I (or someone) can copy it, run it, and see it right away, there's a much higher chance I (or someone) will be able to help you -->
```Python
from fastapi import FastAPI
app = FastAPI()
@app.get("/")
def read_root():
return {"Hello": "World"}
```
### Description
<!-- Replace the content below with your own problem, question, or error -->
* Open the browser and call the endpoint `/`.
* It returns a JSON with `{"Hello": "World"}`.
* But I expected it to return `{"Hello": "Sara"}`.
### Environment
* OS: [e.g. Linux / Windows / macOS]:
* FastAPI Version [e.g. 0.3.0]:
To know the FastAPI version use:
```bash
python -c "import fastapi; print(fastapi.__version__)"
```
* Python version:
To know the Python version use:
```bash
python --version
```
### Additional context
<!-- Add any other context or screenshots about the question here. -->

146
.github/ISSUE_TEMPLATE/question.yml vendored Normal file
View File

@@ -0,0 +1,146 @@
name: Question or Problem
description: Ask a question or ask about a problem
labels: [question]
body:
- type: markdown
attributes:
value: |
Thanks for your interest in FastAPI! 🚀
Please follow these instructions, fill every question, and do every step. 🙏
I'm asking this because answering questions and solving problems in GitHub issues is what consumes most of the time.
I end up not being able to add new features, fix bugs, review pull requests, etc. as fast as I wish because I have to spend too much time handling issues.
All that, on top of all the incredible help provided by a bunch of community members, the [FastAPI Experts](https://fastapi.tiangolo.com/fastapi-people/#experts), that give a lot of their time to come here and help others.
That's a lot of work they are doing, but if more FastAPI users came to help others like them just a little bit more, it would be much less effort for them (and you and me 😅).
By asking questions in a structured way (following this) it will be much easier to help you.
And there's a high chance that you will find the solution along the way and you won't even have to submit it and wait for an answer. 😎
As there are too many issues with questions, I'll have to close the incomplete ones. That will allow me (and others) to focus on helping people like you that follow the whole process and help us help you. 🤓
- type: checkboxes
id: checks
attributes:
label: First Check
description: Please confirm and check all the following options.
options:
- label: I added a very descriptive title to this issue.
required: true
- label: I used the GitHub search to find a similar issue and didn't find it.
required: true
- label: I searched the FastAPI documentation, with the integrated search.
required: true
- label: I already searched in Google "How to X in FastAPI" and didn't find any information.
required: true
- label: I already read and followed all the tutorial in the docs and didn't find an answer.
required: true
- label: I already checked if it is not related to FastAPI but to [Pydantic](https://github.com/samuelcolvin/pydantic).
required: true
- label: I already checked if it is not related to FastAPI but to [Swagger UI](https://github.com/swagger-api/swagger-ui).
required: true
- label: I already checked if it is not related to FastAPI but to [ReDoc](https://github.com/Redocly/redoc).
required: true
- type: checkboxes
id: help
attributes:
label: Commit to Help
description: |
After submitting this, I commit to one of:
* Read open issues with questions until I find 2 issues where I can help someone and add a comment to help there.
* I already hit the "watch" button in this repository to receive notifications and I commit to help at least 2 people that ask questions in the future.
* Implement a Pull Request for a confirmed bug.
options:
- label: I commit to help with one of those options 👆
required: true
- type: textarea
id: example
attributes:
label: Example Code
description: |
Please add a self-contained, [minimal, reproducible, example](https://stackoverflow.com/help/minimal-reproducible-example) with your use case.
If I (or someone) can copy it, run it, and see it right away, there's a much higher chance I (or someone) will be able to help you.
placeholder: |
from fastapi import FastAPI
app = FastAPI()
@app.get("/")
def read_root():
return {"Hello": "World"}
render: python
validations:
required: true
- type: textarea
id: description
attributes:
label: Description
description: |
What is the problem, question, or error?
Write a short description telling me what you are doing, what you expect to happen, and what is currently happening.
placeholder: |
* Open the browser and call the endpoint `/`.
* It returns a JSON with `{"Hello": "World"}`.
* But I expected it to return `{"Hello": "Sara"}`.
validations:
required: true
- type: dropdown
id: os
attributes:
label: Operating System
description: What operating system are you on?
multiple: true
options:
- Linux
- Windows
- macOS
- Other
validations:
required: true
- type: textarea
id: os-details
attributes:
label: Operating System Details
description: You can add more details about your operating system here, in particular if you chose "Other".
- type: input
id: fastapi-version
attributes:
label: FastAPI Version
description: |
What FastAPI version are you using?
You can find the FastAPI version with:
```bash
python -c "import fastapi; print(fastapi.__version__)"
```
validations:
required: true
- type: input
id: python-version
attributes:
label: Python Version
description: |
What Python version are you using?
You can find the Python version with:
```bash
python --version
```
validations:
required: true
- type: textarea
id: context
attributes:
label: Additional Context
description: Add any additional context information or screenshots you think are useful.

View File

@@ -4,7 +4,7 @@ on:
pull_request:
types: [opened, synchronize]
jobs:
build:
build-docs:
runs-on: ubuntu-18.04
steps:
- name: Dump GitHub context
@@ -26,7 +26,7 @@ jobs:
run: python3.7 -m pip install flit
- name: Install docs extras
if: steps.cache.outputs.cache-hit != 'true'
run: python3.7 -m flit install --extras doc
run: python3.7 -m flit install --deps production --extras doc
- name: Install Material for MkDocs Insiders
if: github.event.pull_request.head.repo.fork == false && steps.cache.outputs.cache-hit != 'true'
run: pip install git+https://${{ secrets.ACTIONS_TOKEN }}@github.com/squidfunk/mkdocs-material-insiders.git

View File

@@ -6,23 +6,25 @@ on:
issue_comment:
types:
- created
- edited
issues:
types:
- labeled
pull_request_target:
types:
- labeled
workflow_dispatch:
jobs:
issue-manager:
runs-on: ubuntu-latest
steps:
- uses: tiangolo/issue-manager@0.2.0
- uses: tiangolo/issue-manager@0.4.0
with:
token: ${{ secrets.GITHUB_TOKEN }}
config: >
{
"answered": {
"users": ["tiangolo", "dmontagu"],
"delay": 864000,
"message": "Assuming the original issue was solved, it will be automatically closed now. But feel free to add more comments or create new issues."
"message": "Assuming the original need was handled, this will be automatically closed now. But feel free to add more comments or create new issues or PRs."
}
}

View File

@@ -11,12 +11,27 @@ on:
number:
description: PR number
required: true
debug_enabled:
description: 'Run the build with tmate debugging enabled (https://github.com/marketplace/actions/debugging-with-tmate)'
required: false
default: false
jobs:
latest-changes:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
with:
# To allow latest-changes to commit to master
token: ${{ secrets.ACTIONS_TOKEN }}
# Allow debugging with tmate
- name: Setup tmate session
uses: mxschmitt/action-tmate@v3
if: ${{ github.event_name == 'workflow_dispatch' && github.event.inputs.debug_enabled }}
with:
limit-access-to-actor: true
token: ${{ secrets.ACTIONS_TOKEN }}
standard_token: ${{ secrets.GITHUB_TOKEN }}
- uses: docker://tiangolo/latest-changes:0.0.3
with:
token: ${{ secrets.GITHUB_TOKEN }}

View File

@@ -7,7 +7,7 @@ on:
- completed
jobs:
deploy:
preview-docs:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2

View File

@@ -45,6 +45,7 @@ The key features are:
<!-- sponsors -->
<a href="https://www.deta.sh/?ref=fastapi" target="_blank" title="The launchpad for all your (team's) ideas"><img src="https://fastapi.tiangolo.com/img/sponsors/deta.svg"></a>
<a href="https://bit.ly/2QSouzH" target="_blank" title="Jina: build neural search-as-a-service for any kind of data in just minutes."><img src="https://fastapi.tiangolo.com/img/sponsors/jina.svg"></a>
<a href="https://www.investsuite.com/jobs" target="_blank" title="Wealthtech jobs with FastAPI"><img src="https://fastapi.tiangolo.com/img/sponsors/investsuite.svg"></a>
<a href="https://www.vim.so/?utm_source=FastAPI" target="_blank" title="We help you master vim with interactive exercises"><img src="https://fastapi.tiangolo.com/img/sponsors/vimso.png"></a>
<a href="https://talkpython.fm/fastapi-sponsor" target="_blank" title="FastAPI video courses on demand from people you trust"><img src="https://fastapi.tiangolo.com/img/sponsors/talkpython.png"></a>

31
SECURITY.md Normal file
View File

@@ -0,0 +1,31 @@
# Security Policy
Security is very important for FastAPI and its community. 🔒
Learn more about it below. 👇
## Versions
The latest versions of FastAPI are supported.
You are encouraged to [write tests](https://fastapi.tiangolo.com/tutorial/testing/) for your application and update your FastAPI version frequently after ensuring that your tests are passing. This way you will benefit from the latest features, bug fixes, and **security fixes**.
You can learn more about [FastAPI versions and how to pin and upgrade them](https://fastapi.tiangolo.com/deployment/versions/) for your project in the docs.
## Reporting a Vulnerability
If you think you found a vulnerability, and even if you are not sure about it, please report it right away by sending an email to: security@tiangolo.com. Please try to be as explicit as possible, describing all the steps and example code to reproduce the security issue.
I (the author, [@tiangolo](https://twitter.com/tiangolo)) will review it thoroughly and get back to you.
## Public Discussions
Please restrain from publicly discussing a potential security vulnerability. 🙊
It's better to discuss privately and try to find a solution first, to limit the potential impact as much as possible.
---
Thanks for your help!
The FastAPI community and I thank you for that. 🙇

467
docs/de/docs/index.md Normal file
View File

@@ -0,0 +1,467 @@
{!../../../docs/missing-translation.md!}
<p align="center">
<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://github.com/tiangolo/fastapi/actions?query=workflow%3ATest" target="_blank">
<img src="https://github.com/tiangolo/fastapi/workflows/Test/badge.svg" alt="Test">
</a>
<a href="https://codecov.io/gh/tiangolo/fastapi" target="_blank">
<img src="https://img.shields.io/codecov/c/github/tiangolo/fastapi?color=%2334D058" alt="Coverage">
</a>
<a href="https://pypi.org/project/fastapi" target="_blank">
<img src="https://img.shields.io/pypi/v/fastapi?color=%2334D058&label=pypi%20package" alt="Package version">
</a>
</p>
---
**Documentation**: <a href="https://fastapi.tiangolo.com" target="_blank">https://fastapi.tiangolo.com</a>
**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+ based on standard Python type hints.
The key features are:
* **Fast**: Very high performance, on par with **NodeJS** and **Go** (thanks to Starlette and Pydantic). [One of the fastest Python frameworks available](#performance).
* **Fast to code**: Increase the speed to develop features by about 200% to 300%. *
* **Fewer bugs**: Reduce about 40% of human (developer) induced errors. *
* **Intuitive**: Great editor support. <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. 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" class="external-link" target="_blank">OpenAPI</a> (previously known as Swagger) and <a href="https://json-schema.org/" class="external-link" target="_blank">JSON Schema</a>.
<small>* estimation based on tests on an internal development team, building production applications.</small>
## Sponsors
<!-- sponsors -->
{% if sponsors %}
{% for sponsor in sponsors.gold -%}
<a href="{{ sponsor.url }}" target="_blank" title="{{ sponsor.title }}"><img src="{{ sponsor.img }}" style="border-radius:15px"></a>
{% endfor -%}
{%- for sponsor in sponsors.silver -%}
<a href="{{ sponsor.url }}" target="_blank" title="{{ sponsor.title }}"><img src="{{ sponsor.img }}" style="border-radius:15px"></a>
{% endfor %}
{% endif %}
<!-- /sponsors -->
<a href="https://fastapi.tiangolo.com/fastapi-people/#sponsors" class="external-link" target="_blank">Other sponsors</a>
## 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>
---
"_We adopted the **FastAPI** library to spawn a **REST** server that can be queried to obtain **predictions**. [for Ludwig]_"
<div style="text-align: right; margin-right: 10%;">Piero Molino, Yaroslav Dudin, and Sai Sumanth Miryala - <strong>Uber</strong> <a href="https://eng.uber.com/ludwig-v0-2/" target="_blank"><small>(ref)</small></a></div>
---
"_**Netflix** is pleased to announce the open-source release of our **crisis management** orchestration framework: **Dispatch**! [built with **FastAPI**]_"
<div style="text-align: right; margin-right: 10%;">Kevin Glisson, Marc Vilanova, Forest Monsen - <strong>Netflix</strong> <a href="https://netflixtechblog.com/introducing-dispatch-da4b8a2a8072" target="_blank"><small>(ref)</small></a></div>
---
"_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="https://www.hug.rest/" target="_blank">Hug</a> creator</strong> <a href="https://news.ycombinator.com/item?id=19455465" target="_blank"><small>(ref)</small></a></div>
---
"_If you're looking to learn one **modern framework** for building REST APIs, check out **FastAPI** [...] It's fast, easy to use and easy to learn [...]_"
"_We've switched over to **FastAPI** for our **APIs** [...] I think you'll like it [...]_"
<div style="text-align: right; margin-right: 10%;">Ines Montani - Matthew Honnibal - <strong><a href="https://explosion.ai" target="_blank">Explosion AI</a> founders - <a href="https://spacy.io" target="_blank">spaCy</a> creators</strong> <a href="https://twitter.com/_inesmontani/status/1144173225322143744" target="_blank"><small>(ref)</small></a> - <a href="https://twitter.com/honnibal/status/1144031421859655680" target="_blank"><small>(ref)</small></a></div>
---
## **Typer**, the FastAPI of CLIs
<a href="https://typer.tiangolo.com" target="_blank"><img src="https://typer.tiangolo.com/img/logo-margin/logo-margin-vector.svg" style="width: 20%;"></a>
If you are building a <abbr title="Command Line Interface">CLI</abbr> app to be used in the terminal instead of a web API, check out <a href="https://typer.tiangolo.com/" class="external-link" target="_blank">**Typer**</a>.
**Typer** is FastAPI's little sibling. And it's intended to be the **FastAPI of CLIs**. ⌨️ 🚀
## Requirements
Python 3.6+
FastAPI stands on the shoulders of giants:
* <a href="https://www.starlette.io/" class="external-link" target="_blank">Starlette</a> for the web parts.
* <a href="https://pydantic-docs.helpmanual.io/" class="external-link" target="_blank">Pydantic</a> for the data parts.
## Installation
<div class="termy">
```console
$ pip install fastapi
---> 100%
```
</div>
You will also need an ASGI server, for production such as <a href="https://www.uvicorn.org" class="external-link" target="_blank">Uvicorn</a> or <a href="https://gitlab.com/pgjones/hypercorn" class="external-link" target="_blank">Hypercorn</a>.
<div class="termy">
```console
$ pip install uvicorn[standard]
---> 100%
```
</div>
## Example
### Create it
* Create a file `main.py` with:
```Python
from typing import Optional
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: Optional[str] = None):
return {"item_id": item_id, "q": q}
```
<details markdown="1">
<summary>Or use <code>async def</code>...</summary>
If your code uses `async` / `await`, use `async def`:
```Python hl_lines="9 14"
from typing import Optional
from fastapi import FastAPI
app = FastAPI()
@app.get("/")
async def read_root():
return {"Hello": "World"}
@app.get("/items/{item_id}")
async def read_item(item_id: int, q: Optional[str] = None):
return {"item_id": item_id, "q": q}
```
**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 it
Run the server with:
<div class="termy">
```console
$ uvicorn main:app --reload
INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit)
INFO: Started reloader process [28720]
INFO: Started server process [28722]
INFO: Waiting for application startup.
INFO: Application startup complete.
```
</div>
<details markdown="1">
<summary>About the command <code>uvicorn main:app --reload</code>...</summary>
The command `uvicorn main:app` refers to:
* `main`: the file `main.py` (the Python "module").
* `app`: the object created inside of `main.py` with the line `app = FastAPI()`.
* `--reload`: make the server restart after code changes. Only do this for development.
</details>
### Check it
Open your browser at <a href="http://127.0.0.1:8000/items/5?q=somequery" class="external-link" target="_blank">http://127.0.0.1:8000/items/5?q=somequery</a>.
You will see the JSON response as:
```JSON
{"item_id": 5, "q": "somequery"}
```
You already created an API that:
* Receives HTTP requests in the _paths_ `/` and `/items/{item_id}`.
* Both _paths_ take `GET` <em>operations</em> (also known as HTTP _methods_).
* The _path_ `/items/{item_id}` has a _path parameter_ `item_id` that should be an `int`.
* The _path_ `/items/{item_id}` has an optional `str` _query parameter_ `q`.
### Interactive API docs
Now go to <a href="http://127.0.0.1:8000/docs" class="external-link" target="_blank">http://127.0.0.1:8000/docs</a>.
You will see the automatic interactive API documentation (provided by <a href="https://github.com/swagger-api/swagger-ui" class="external-link" target="_blank">Swagger UI</a>):
![Swagger UI](https://fastapi.tiangolo.com/img/index/index-01-swagger-ui-simple.png)
### Alternative API docs
And now, go to <a href="http://127.0.0.1:8000/redoc" class="external-link" target="_blank">http://127.0.0.1:8000/redoc</a>.
You will see the alternative automatic documentation (provided by <a href="https://github.com/Rebilly/ReDoc" class="external-link" target="_blank">ReDoc</a>):
![ReDoc](https://fastapi.tiangolo.com/img/index/index-02-redoc-simple.png)
## Example upgrade
Now modify the file `main.py` to receive a body from a `PUT` request.
Declare the body using standard Python types, thanks to Pydantic.
```Python hl_lines="4 9-12 25-27"
from typing import Optional
from fastapi import FastAPI
from pydantic import BaseModel
app = FastAPI()
class Item(BaseModel):
name: str
price: float
is_offer: Optional[bool] = None
@app.get("/")
def read_root():
return {"Hello": "World"}
@app.get("/items/{item_id}")
def read_item(item_id: int, q: Optional[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 `--reload` to the `uvicorn` command above).
### Interactive API docs upgrade
Now go to <a href="http://127.0.0.1:8000/docs" class="external-link" target="_blank">http://127.0.0.1:8000/docs</a>.
* 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)
* Click on the button "Try it out", it allows you to fill the parameters and directly interact with the API:
![Swagger UI interaction](https://fastapi.tiangolo.com/img/index/index-04-swagger-03.png)
* Then click on the "Execute" button, the user interface will communicate with your API, send the parameters, get the results and show them on the screen:
![Swagger UI interaction](https://fastapi.tiangolo.com/img/index/index-05-swagger-04.png)
### Alternative API docs upgrade
And now, go to <a href="http://127.0.0.1:8000/redoc" class="external-link" target="_blank">http://127.0.0.1:8000/redoc</a>.
* The alternative documentation will also reflect the new query parameter and body:
![ReDoc](https://fastapi.tiangolo.com/img/index/index-06-redoc-02.png)
### Recap
In summary, you declare **once** the types of parameters, body, etc. as function parameters.
You do that with standard modern Python types.
You don't have to learn a new syntax, the methods or classes of a specific library, etc.
Just standard **Python 3.6+**.
For example, for an `int`:
```Python
item_id: int
```
or for a more complex `Item` model:
```Python
item: Item
```
...and with that single declaration you get:
* Editor support, including:
* Completion.
* Type checks.
* Validation of data:
* Automatic and clear errors when the data is invalid.
* Validation even for deeply nested JSON objects.
* <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.
* Cookies.
* Headers.
* Forms.
* Files.
* <abbr title="also known as: serialization, parsing, marshalling">Conversion</abbr> of output data: converting from Python data and types to network data (as JSON):
* Convert Python types (`str`, `int`, `float`, `bool`, `list`, etc).
* `datetime` objects.
* `UUID` objects.
* Database models.
* ...and many more.
* Automatic interactive API documentation, including 2 alternative user interfaces:
* Swagger UI.
* ReDoc.
---
Coming back to the previous code example, **FastAPI** will:
* 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`) 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 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 it 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 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.
---
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}
```
...from:
```Python
... "item_name": item.name ...
```
...to:
```Python
... "item_price": item.price ...
```
...and see how your editor will auto-complete the attributes and know their types:
![editor support](https://fastapi.tiangolo.com/img/vscode-completion.png)
For a more complete example including more features, see the <a href="https://fastapi.tiangolo.com/tutorial/">Tutorial - User Guide</a>.
**Spoiler alert**: the tutorial - user guide includes:
* Declaration of **parameters** from other different places as: **headers**, **cookies**, **form fields** and **files**.
* How to set **validation constraints** as `maximum_length` or `regex`.
* A very powerful and easy to use **<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).
* Many extra features (thanks to Starlette) as:
* **WebSockets**
* **GraphQL**
* extremely easy tests based on `requests` and `pytest`
* **CORS**
* **Cookie Sessions**
* ...and more.
## Performance
Independent TechEmpower benchmarks show **FastAPI** applications running under Uvicorn as <a href="https://www.techempower.com/benchmarks/#section=test&runid=7464e520-0dc2-473d-bd34-dbdfd7e85911&hw=ph&test=query&l=zijzen-7" class="external-link" target="_blank">one of the fastest Python frameworks available</a>, only below Starlette and Uvicorn themselves (used internally by FastAPI). (*)
To understand more about it, see the section <a href="https://fastapi.tiangolo.com/benchmarks/" class="internal-link" target="_blank">Benchmarks</a>.
## Optional Dependencies
Used by Pydantic:
* <a href="https://github.com/esnme/ultrajson" target="_blank"><code>ujson</code></a> - for faster JSON <abbr title="converting the string that comes from an HTTP request into Python data">"parsing"</abbr>.
* <a href="https://github.com/JoshData/python-email-validator" target="_blank"><code>email_validator</code></a> - for email validation.
Used by Starlette:
* <a href="https://requests.readthedocs.io" target="_blank"><code>requests</code></a> - Required if you want to use the `TestClient`.
* <a href="https://github.com/Tinche/aiofiles" target="_blank"><code>aiofiles</code></a> - Required if you want to use `FileResponse` or `StaticFiles`.
* <a href="https://jinja.palletsprojects.com" target="_blank"><code>jinja2</code></a> - Required if you want to use the default template configuration.
* <a href="https://andrew-d.github.io/python-multipart/" target="_blank"><code>python-multipart</code></a> - Required if you want to support form <abbr title="converting the string that comes from an HTTP request into Python data">"parsing"</abbr>, with `request.form()`.
* <a href="https://pythonhosted.org/itsdangerous/" target="_blank"><code>itsdangerous</code></a> - Required for `SessionMiddleware` support.
* <a href="https://pyyaml.org/wiki/PyYAMLDocumentation" target="_blank"><code>pyyaml</code></a> - Required for Starlette's `SchemaGenerator` support (you probably don't need it with FastAPI).
* <a href="https://graphene-python.org/" target="_blank"><code>graphene</code></a> - Required for `GraphQLApp` support.
* <a href="https://github.com/esnme/ultrajson" target="_blank"><code>ujson</code></a> - Required if you want to use `UJSONResponse`.
Used by FastAPI / Starlette:
* <a href="https://www.uvicorn.org" target="_blank"><code>uvicorn</code></a> - for the server that loads and serves your application.
* <a href="https://github.com/ijl/orjson" target="_blank"><code>orjson</code></a> - Required if you want to use `ORJSONResponse`.
You can install all of these with `pip install fastapi[all]`.
## License
This project is licensed under the terms of the MIT license.

125
docs/de/mkdocs.yml Normal file
View File

@@ -0,0 +1,125 @@
site_name: FastAPI
site_description: FastAPI framework, high performance, easy to learn, fast to code, ready for production
site_url: https://fastapi.tiangolo.com/de/
theme:
name: material
custom_dir: overrides
palette:
- scheme: default
primary: teal
accent: amber
toggle:
icon: material/lightbulb-outline
name: Switch to light mode
- scheme: slate
primary: teal
accent: amber
toggle:
icon: material/lightbulb
name: Switch to dark mode
features:
- search.suggest
- search.highlight
icon:
repo: fontawesome/brands/github-alt
logo: https://fastapi.tiangolo.com/img/icon-white.svg
favicon: https://fastapi.tiangolo.com/img/favicon.png
language: de
repo_name: tiangolo/fastapi
repo_url: https://github.com/tiangolo/fastapi
edit_uri: ''
google_analytics:
- UA-133183413-1
- auto
plugins:
- search
- markdownextradata:
data: data
nav:
- FastAPI: index.md
- Languages:
- en: /
- de: /de/
- es: /es/
- fr: /fr/
- id: /id/
- it: /it/
- ja: /ja/
- ko: /ko/
- pl: /pl/
- pt: /pt/
- ru: /ru/
- sq: /sq/
- tr: /tr/
- uk: /uk/
- zh: /zh/
markdown_extensions:
- toc:
permalink: true
- markdown.extensions.codehilite:
guess_lang: false
- markdown_include.include:
base_path: docs
- admonition
- codehilite
- extra
- pymdownx.superfences:
custom_fences:
- name: mermaid
class: mermaid
format: !!python/name:pymdownx.superfences.fence_div_format ''
- pymdownx.tabbed
extra:
social:
- icon: fontawesome/brands/github-alt
link: https://github.com/tiangolo/fastapi
- icon: fontawesome/brands/discord
link: https://discord.gg/VQjSZaeJmf
- icon: fontawesome/brands/twitter
link: https://twitter.com/fastapi
- icon: fontawesome/brands/linkedin
link: https://www.linkedin.com/in/tiangolo
- icon: fontawesome/brands/dev
link: https://dev.to/tiangolo
- icon: fontawesome/brands/medium
link: https://medium.com/@tiangolo
- icon: fontawesome/solid/globe
link: https://tiangolo.com
alternate:
- link: /
name: en - English
- link: /de/
name: de
- link: /es/
name: es - español
- link: /fr/
name: fr - français
- link: /id/
name: id
- link: /it/
name: it - italiano
- link: /ja/
name: ja - 日本語
- link: /ko/
name: ko - 한국어
- link: /pl/
name: pl
- link: /pt/
name: pt - português
- link: /ru/
name: ru - русский язык
- link: /sq/
name: sq - shqip
- link: /tr/
name: tr - Türkçe
- link: /uk/
name: uk - українська мова
- link: /zh/
name: zh - 汉语
extra_css:
- https://fastapi.tiangolo.com/css/termynal.css
- https://fastapi.tiangolo.com/css/custom.css
extra_javascript:
- https://unpkg.com/mermaid@8.4.6/dist/mermaid.min.js
- https://fastapi.tiangolo.com/js/termynal.js
- https://fastapi.tiangolo.com/js/custom.js

0
docs/de/overrides/.gitignore vendored Normal file
View File

View File

@@ -1,258 +1,278 @@
articles:
english:
- link: https://medium.com/@williamhayes/fastapi-starlette-debug-vs-prod-5f7561db3a59
title: FastAPI/Starlette debug vs prod
author_link: https://medium.com/@williamhayes
author: William Hayes
- link: https://medium.com/data-rebels/fastapi-google-as-an-external-authentication-provider-3a527672cf33
title: FastAPIGoogle as an external authentication provider
author_link: https://medium.com/@nilsdebruin
author: Nils de Bruin
- link: https://medium.com/data-rebels/fastapi-how-to-add-basic-and-cookie-authentication-a45c85ef47d3
title: FastAPIHow to add basic and cookie authentication
author_link: https://medium.com/@nilsdebruin
author: Nils de Bruin
- link: https://dev.to/errietta/introduction-to-the-fastapi-python-framework-2n10
title: Introduction to the fastapi python framework
author_link: https://dev.to/errietta
author: Errieta Kostala
- link: https://nickc1.github.io/api,/scikit-learn/2019/01/10/scikit-fastapi.html
title: "FastAPI and Scikit-Learn: Easily Deploy Models"
author_link: https://nickc1.github.io/
author: Nick Cortale
- link: https://medium.com/data-rebels/fastapi-authentication-revisited-enabling-api-key-authentication-122dc5975680
title: "FastAPI authentication revisited: Enabling API key authentication"
author_link: https://medium.com/@nilsdebruin
author: Nils de Bruin
- link: https://medium.com/@nico.axtmann95/deploying-a-scikit-learn-model-with-onnx-und-fastapi-1af398268915
title: Deploying a scikit-learn model with ONNX and FastAPI
author_link: https://www.linkedin.com/in/nico-axtmann
author: Nico Axtmann
- link: https://geekflare.com/python-asynchronous-web-frameworks/
title: Top 5 Asynchronous Web Frameworks for Python
author_link: https://geekflare.com/author/ankush/
author: Ankush Thakur
- link: https://medium.com/@gntrm/jwt-authentication-with-fastapi-and-aws-cognito-1333f7f2729e
title: JWT Authentication with FastAPI and AWS Cognito
author_link: https://twitter.com/gntrm
author: Johannes Gontrum
- link: https://towardsdatascience.com/how-to-deploy-a-machine-learning-model-dc51200fe8cf
title: How to Deploy a Machine Learning Model
author_link: https://www.linkedin.com/in/mgrootendorst/
author: Maarten Grootendorst
- link: https://eng.uber.com/ludwig-v0-2/
title: "Uber: Ludwig v0.2 Adds New Features and Other Improvements to its Deep Learning Toolbox [including a FastAPI server]"
author_link: https://eng.uber.com
author: Uber Engineering
- link: https://gitlab.com/euri10/fastapi_cheatsheet
title: A FastAPI and Swagger UI visual cheatsheet
author_link: https://gitlab.com/euri10
author: "@euri10"
- link: https://medium.com/@mike.p.moritz/using-docker-compose-to-deploy-a-lightweight-python-rest-api-with-a-job-queue-37e6072a209b
title: Using Docker Compose to deploy a lightweight Python REST API with a job queue
author_link: https://medium.com/@mike.p.moritz
author: Mike Moritz
- link: https://robwagner.dev/tortoise-fastapi-setup/
title: Setting up Tortoise ORM with FastAPI
author_link: https://robwagner.dev/
author: Rob Wagner
- link: https://dev.to/dbanty/why-i-m-leaving-flask-3ki6
title: Why I'm Leaving Flask
author_link: https://dev.to/dbanty
author: Dylan Anthony
- link: https://medium.com/python-data/how-to-deploy-tensorflow-2-0-models-as-an-api-service-with-fastapi-docker-128b177e81f3
title: How To Deploy Tensorflow 2.0 Models As An API Service With FastAPI & Docker
author_link: https://medium.com/@bbrenyah
author: Bernard Brenyah
- link: https://testdriven.io/blog/fastapi-crud/
title: "TestDriven.io: Developing and Testing an Asynchronous API with FastAPI and Pytest"
author_link: https://testdriven.io/authors/herman
author: Michael Herman
- link: https://towardsdatascience.com/deploying-iris-classifications-with-fastapi-and-docker-7c9b83fdec3a
title: "Towards Data Science: Deploying Iris Classifications with FastAPI and Docker"
author_link: https://towardsdatascience.com/@mandygu
author: Mandy Gu
- link: https://medium.com/analytics-vidhya/deploy-machine-learning-models-with-keras-fastapi-redis-and-docker-4940df614ece
title: Deploy Machine Learning Models with Keras, FastAPI, Redis and Docker
author_link: https://medium.com/@shane.soh
author: Shane Soh
- link: https://medium.com/@arthur393/another-boilerplate-to-fastapi-azure-pipeline-ci-pytest-3c8d9a4be0bb
title: "Another Boilerplate to FastAPI: Azure Pipeline CI + Pytest"
author_link: https://twitter.com/arthurheinrique
author: Arthur Henrique
- link: https://iwpnd.pw/articles/2020-01/deploy-fastapi-to-aws-lambda
title: How to continuously deploy a FastAPI to AWS Lambda with AWS SAM
author_link: https://iwpnd.pw
author: Benjamin Ramser
- link: https://www.tutlinks.com/create-and-deploy-fastapi-app-to-heroku/
title: Create and Deploy FastAPI app to Heroku without using Docker
author_link: https://www.linkedin.com/in/navule/
author: Navule Pavan Kumar Rao
- link: https://iwpnd.pw/articles/2020-03/apache-kafka-fastapi-geostream
title: Apache Kafka producer and consumer with FastAPI and aiokafka
author_link: https://iwpnd.pw
author: Benjamin Ramser
- link: https://wuilly.com/2019/10/real-time-notifications-with-python-and-postgres/
title: Real-time Notifications with Python and Postgres
author_link: https://wuilly.com/
author: Guillermo Cruz
- link: https://dev.to/paurakhsharma/microservice-in-python-using-fastapi-24cc
title: Microservice in Python using FastAPI
author_link: https://twitter.com/PaurakhSharma
author: Paurakh Sharma Humagain
- link: https://dev.to/cuongld2/build-simple-api-service-with-python-fastapi-part-1-581o
title: Build simple API service with Python FastAPI — Part 1
author_link: https://dev.to/cuongld2
author: cuongld2
- link: https://paulsec.github.io/posts/fastapi_plus_zeit_serverless_fu/
title: FastAPI + Zeit.co = 🚀
author_link: https://twitter.com/PaulWebSec
author: Paul Sec
- link: https://dev.to/tiangolo/build-a-web-api-from-scratch-with-fastapi-the-workshop-2ehe
title: Build a web API from scratch with FastAPI - the workshop
author_link: https://twitter.com/tiangolo
author: Sebastián Ramírez (tiangolo)
- link: https://www.twilio.com/blog/build-secure-twilio-webhook-python-fastapi
title: Build a Secure Twilio Webhook with Python and FastAPI
author_link: https://www.twilio.com
author: Twilio
- link: https://www.stavros.io/posts/fastapi-with-django/
title: Using FastAPI with Django
author_link: https://twitter.com/Stavros
author: Stavros Korokithakis
- link: https://netflixtechblog.com/introducing-dispatch-da4b8a2a8072
title: Introducing Dispatch
author_link: https://netflixtechblog.com/
author: Netflix
- link: https://davidefiocco.github.io/streamlit-fastapi-ml-serving/
title: Machine learning model serving in Python using FastAPI and streamlit
author_link: https://github.com/davidefiocco
author: Davide Fiocco
- link: https://www.tutlinks.com/deploy-fastapi-on-azure/
title: Deploy FastAPI on Azure App Service
author_link: https://www.linkedin.com/in/navule/
author: Navule Pavan Kumar Rao
- link: https://towardsdatascience.com/build-and-host-fast-data-science-applications-using-fastapi-823be8a1d6a0
title: Build And Host Fast Data Science Applications Using FastAPI
author_link: https://medium.com/@farhadmalik
author: Farhad Malik
- link: https://medium.com/@gabbyprecious2000/creating-a-crud-app-with-fastapi-part-one-7c049292ad37
title: Creating a CRUD App with FastAPI (Part one)
author_link: https://medium.com/@gabbyprecious2000
author: Precious Ndubueze
- link: https://julienharbulot.com/notification-server.html
title: HTTP server to display desktop notifications
author_link: https://julienharbulot.com/
author: Julien Harbulot
- link: https://guitton.co/posts/fastapi-monitoring/
title: How to monitor your FastAPI service
author_link: https://twitter.com/louis_guitton
author: Louis Guitton
- link: https://amitness.com/2020/06/fastapi-vs-flask/
title: FastAPI for Flask Users
author_link: https://twitter.com/amitness
author: Amit Chaudhary
- link: https://valonjanuzaj.medium.com/deploy-a-dockerized-fastapi-application-to-aws-cc757830ba1b
title: Deploy a dockerized FastAPI application to AWS
author_link: https://www.linkedin.com/in/valon-januzaj-b02692187/
author: Valon Januzaj
- link: https://dompatmore.com/blog/authenticate-your-fastapi-app-with-auth0
title: Authenticate Your FastAPI App with auth0
author_link: https://twitter.com/dompatmore
author: Dom Patmore
japanese:
- link: https://qiita.com/mtitg/items/47770e9a562dd150631d
title: FastAPIDB接続してCRUDするPython製APIサーバーを構築
author_link: https://qiita.com/mtitg
author: "@mtitg"
- link: https://qiita.com/ryoryomaru/items/59958ed385b3571d50de
title: python製の最新APIフレームワーク FastAPI を触ってみた
author_link: https://qiita.com/ryoryomaru
author: "@ryoryomaru"
- link: https://qiita.com/angel_katayoku/items/0e1f5dbbe62efc612a78
title: FastAPIでCORSを回避
author_link: https://qiita.com/angel_katayoku
author: "@angel_katayoku"
- link: https://qiita.com/angel_katayoku/items/4fbc1a4e2b33fa2237d2
title: FastAPIをMySQLと接続してDockerで管理してみる
author_link: https://qiita.com/angel_katayoku
author: "@angel_katayoku"
- link: https://qiita.com/angel_katayoku/items/8a458a8952f50b73f420
title: FastAPIでPOSTされたJSONのレスポンスbodyを受け取る
author_link: https://qiita.com/angel_katayoku
author: "@angel_katayoku"
- link: https://qiita.com/hikarut/items/b178af2e2440c67c6ac4
title: フロントエンド開発者向けのDockerによるPython開発環境構築
author_link: https://qiita.com/hikarut
author: Hikaru Takahashi
- link: https://rightcode.co.jp/blog/information-technology/fastapi-tutorial-todo-apps-environment
title: "【第1回】FastAPIチュートリアル: ToDoアプリを作ってみよう【環境構築編】"
author_link: https://rightcode.co.jp/author/jun
author: ライトコードメディア編集部
- link: https://rightcode.co.jp/blog/information-technology/fastapi-tutorial-todo-apps-model-building
title: "【第2回】FastAPIチュートリアル: ToDoアプリを作ってみよう【モデル構築編】"
author_link: https://rightcode.co.jp/author/jun
author: ライトコードメディア編集部
- link: https://rightcode.co.jp/blog/information-technology/fastapi-tutorial-todo-apps-authentication-user-registration
title: "【第3回】FastAPIチュートリアル: toDoアプリを作ってみよう【認証・ユーザ登録編】"
author_link: https://rightcode.co.jp/author/jun
author: ライトコードメディア編集部
- link: https://rightcode.co.jp/blog/information-technology/fastapi-tutorial-todo-apps-admin-page-improvement
title: "【第4回】FastAPIチュートリアル: toDoアプリを作ってみよう【管理者ページ改良編】"
author_link: https://rightcode.co.jp/author/jun
author: ライトコードメディア編集部
- link: https://qiita.com/bee2/items/0ad260ab9835a2087dae
title: PythonのWeb frameworkのパフォーマンス比較 (Django, Flask, responder, FastAPI, japronto)
author_link: https://qiita.com/bee2
author: "@bee2"
- link: https://qiita.com/bee2/items/75d9c0d7ba20e7a4a0e9
title: "[FastAPI] Python製のASGI Web フレームワーク FastAPIに入門する"
author_link: https://qiita.com/bee2
author: "@bee2"
vietnamese:
- link: https://fullstackstation.com/fastapi-trien-khai-bang-docker/
title: "FASTAPI: TRIỂN KHAI BẰNG DOCKER"
author_link: https://fullstackstation.com/author/figonking/
author: Nguyễn Nhân
russian:
- link: https://habr.com/ru/post/454440/
title: "Мелкая питонячая радость #2: Starlette - Солидная примочка FastAPI"
author_link: https://habr.com/ru/users/57uff3r/
author: Andrey Korchak
- link: https://habr.com/ru/post/478620/
title: Почему Вы должны попробовать FastAPI?
author_link: https://github.com/prostomarkeloff
author: prostomarkeloff
- link: https://trkohler.com/fast-api-introduction-to-framework
title: "FastAPI: знакомимся с фреймворком"
author_link: https://www.linkedin.com/in/trkohler/
author: Troy Köhler
- author: "@pystar"
author_link: https://pystar.substack.com/
link: https://pystar.substack.com/p/how-to-create-a-fake-certificate
title: How to Create A Fake Certificate Authority And Generate TLS Certs for FastAPI
- author: Shahriyar(Shako) Rzayev
author_link: https://www.linkedin.com/in/shahriyar-rzayev/
link: https://www.azepug.az/posts/fastapi/#building-simple-e-commerce-with-nuxtjs-and-fastapi-series
title: Building simple E-Commerce with NuxtJS and FastAPI
- author: Rodrigo Arenas
author_link: https://rodrigo-arenas.medium.com/
link: https://medium.com/analytics-vidhya/serve-a-machine-learning-model-using-sklearn-fastapi-and-docker-85aabf96729b
title: "Serve a machine learning model using Sklearn, FastAPI and Docker"
- author: Navule Pavan Kumar Rao
author_link: https://www.linkedin.com/in/navule/
link: https://www.tutlinks.com/deploy-fastapi-on-ubuntu-gunicorn-caddy-2/
title: Deploy FastAPI on Ubuntu and Serve using Caddy 2 Web Server
- author: Patrick Ladon
author_link: https://dev.to/factorlive
link: https://dev.to/factorlive/python-facebook-messenger-webhook-with-fastapi-on-glitch-4n90
title: Python Facebook messenger webhook with FastAPI on Glitch
- author: Dom Patmore
author_link: https://twitter.com/dompatmore
link: https://dompatmore.com/blog/authenticate-your-fastapi-app-with-auth0
title: Authenticate Your FastAPI App with auth0
- author: Valon Januzaj
author_link: https://www.linkedin.com/in/valon-januzaj-b02692187/
link: https://valonjanuzaj.medium.com/deploy-a-dockerized-fastapi-application-to-aws-cc757830ba1b
title: Deploy a dockerized FastAPI application to AWS
- author: Amit Chaudhary
author_link: https://twitter.com/amitness
link: https://amitness.com/2020/06/fastapi-vs-flask/
title: FastAPI for Flask Users
- author: Louis Guitton
author_link: https://twitter.com/louis_guitton
link: https://guitton.co/posts/fastapi-monitoring/
title: How to monitor your FastAPI service
- author: Julien Harbulot
author_link: https://julienharbulot.com/
link: https://julienharbulot.com/notification-server.html
title: HTTP server to display desktop notifications
- author: Precious Ndubueze
author_link: https://medium.com/@gabbyprecious2000
link: https://medium.com/@gabbyprecious2000/creating-a-crud-app-with-fastapi-part-one-7c049292ad37
title: Creating a CRUD App with FastAPI (Part one)
- author: Farhad Malik
author_link: https://medium.com/@farhadmalik
link: https://towardsdatascience.com/build-and-host-fast-data-science-applications-using-fastapi-823be8a1d6a0
title: Build And Host Fast Data Science Applications Using FastAPI
- author: Navule Pavan Kumar Rao
author_link: https://www.linkedin.com/in/navule/
link: https://www.tutlinks.com/deploy-fastapi-on-azure/
title: Deploy FastAPI on Azure App Service
- author: Davide Fiocco
author_link: https://github.com/davidefiocco
link: https://davidefiocco.github.io/streamlit-fastapi-ml-serving/
title: Machine learning model serving in Python using FastAPI and streamlit
- author: Netflix
author_link: https://netflixtechblog.com/
link: https://netflixtechblog.com/introducing-dispatch-da4b8a2a8072
title: Introducing Dispatch
- author: Stavros Korokithakis
author_link: https://twitter.com/Stavros
link: https://www.stavros.io/posts/fastapi-with-django/
title: Using FastAPI with Django
- author: Twilio
author_link: https://www.twilio.com
link: https://www.twilio.com/blog/build-secure-twilio-webhook-python-fastapi
title: Build a Secure Twilio Webhook with Python and FastAPI
- author: Sebastián Ramírez (tiangolo)
author_link: https://twitter.com/tiangolo
link: https://dev.to/tiangolo/build-a-web-api-from-scratch-with-fastapi-the-workshop-2ehe
title: Build a web API from scratch with FastAPI - the workshop
- author: Paul Sec
author_link: https://twitter.com/PaulWebSec
link: https://paulsec.github.io/posts/fastapi_plus_zeit_serverless_fu/
title: FastAPI + Zeit.co = 🚀
- author: cuongld2
author_link: https://dev.to/cuongld2
link: https://dev.to/cuongld2/build-simple-api-service-with-python-fastapi-part-1-581o
title: Build simple API service with Python FastAPI — Part 1
- author: Paurakh Sharma Humagain
author_link: https://twitter.com/PaurakhSharma
link: https://dev.to/paurakhsharma/microservice-in-python-using-fastapi-24cc
title: Microservice in Python using FastAPI
- author: Guillermo Cruz
author_link: https://wuilly.com/
link: https://wuilly.com/2019/10/real-time-notifications-with-python-and-postgres/
title: Real-time Notifications with Python and Postgres
- author: Benjamin Ramser
author_link: https://iwpnd.pw
link: https://iwpnd.pw/articles/2020-03/apache-kafka-fastapi-geostream
title: Apache Kafka producer and consumer with FastAPI and aiokafka
- author: Navule Pavan Kumar Rao
author_link: https://www.linkedin.com/in/navule/
link: https://www.tutlinks.com/create-and-deploy-fastapi-app-to-heroku/
title: Create and Deploy FastAPI app to Heroku without using Docker
- author: Benjamin Ramser
author_link: https://iwpnd.pw
link: https://iwpnd.pw/articles/2020-01/deploy-fastapi-to-aws-lambda
title: How to continuously deploy a FastAPI to AWS Lambda with AWS SAM
- author: Arthur Henrique
author_link: https://twitter.com/arthurheinrique
link: https://medium.com/@arthur393/another-boilerplate-to-fastapi-azure-pipeline-ci-pytest-3c8d9a4be0bb
title: 'Another Boilerplate to FastAPI: Azure Pipeline CI + Pytest'
- author: Shane Soh
author_link: https://medium.com/@shane.soh
link: https://medium.com/analytics-vidhya/deploy-machine-learning-models-with-keras-fastapi-redis-and-docker-4940df614ece
title: Deploy Machine Learning Models with Keras, FastAPI, Redis and Docker
- author: Mandy Gu
author_link: https://towardsdatascience.com/@mandygu
link: https://towardsdatascience.com/deploying-iris-classifications-with-fastapi-and-docker-7c9b83fdec3a
title: 'Towards Data Science: Deploying Iris Classifications with FastAPI and Docker'
- author: Michael Herman
author_link: https://testdriven.io/authors/herman
link: https://testdriven.io/blog/fastapi-crud/
title: 'TestDriven.io: Developing and Testing an Asynchronous API with FastAPI and Pytest'
- author: Bernard Brenyah
author_link: https://medium.com/@bbrenyah
link: https://medium.com/python-data/how-to-deploy-tensorflow-2-0-models-as-an-api-service-with-fastapi-docker-128b177e81f3
title: How To Deploy Tensorflow 2.0 Models As An API Service With FastAPI & Docker
- author: Dylan Anthony
author_link: https://dev.to/dbanty
link: https://dev.to/dbanty/why-i-m-leaving-flask-3ki6
title: Why I'm Leaving Flask
- author: Rob Wagner
author_link: https://robwagner.dev/
link: https://robwagner.dev/tortoise-fastapi-setup/
title: Setting up Tortoise ORM with FastAPI
- author: Mike Moritz
author_link: https://medium.com/@mike.p.moritz
link: https://medium.com/@mike.p.moritz/using-docker-compose-to-deploy-a-lightweight-python-rest-api-with-a-job-queue-37e6072a209b
title: Using Docker Compose to deploy a lightweight Python REST API with a job queue
- author: '@euri10'
author_link: https://gitlab.com/euri10
link: https://gitlab.com/euri10/fastapi_cheatsheet
title: A FastAPI and Swagger UI visual cheatsheet
- author: Uber Engineering
author_link: https://eng.uber.com
link: https://eng.uber.com/ludwig-v0-2/
title: 'Uber: Ludwig v0.2 Adds New Features and Other Improvements to its Deep Learning Toolbox [including a FastAPI server]'
- author: Maarten Grootendorst
author_link: https://www.linkedin.com/in/mgrootendorst/
link: https://towardsdatascience.com/how-to-deploy-a-machine-learning-model-dc51200fe8cf
title: How to Deploy a Machine Learning Model
- author: Johannes Gontrum
author_link: https://twitter.com/gntrm
link: https://medium.com/@gntrm/jwt-authentication-with-fastapi-and-aws-cognito-1333f7f2729e
title: JWT Authentication with FastAPI and AWS Cognito
- author: Ankush Thakur
author_link: https://geekflare.com/author/ankush/
link: https://geekflare.com/python-asynchronous-web-frameworks/
title: Top 5 Asynchronous Web Frameworks for Python
- author: Nico Axtmann
author_link: https://www.linkedin.com/in/nico-axtmann
link: https://medium.com/@nico.axtmann95/deploying-a-scikit-learn-model-with-onnx-und-fastapi-1af398268915
title: Deploying a scikit-learn model with ONNX and FastAPI
- author: Nils de Bruin
author_link: https://medium.com/@nilsdebruin
link: https://medium.com/data-rebels/fastapi-authentication-revisited-enabling-api-key-authentication-122dc5975680
title: 'FastAPI authentication revisited: Enabling API key authentication'
- author: Nick Cortale
author_link: https://nickc1.github.io/
link: https://nickc1.github.io/api,/scikit-learn/2019/01/10/scikit-fastapi.html
title: 'FastAPI and Scikit-Learn: Easily Deploy Models'
- author: Errieta Kostala
author_link: https://dev.to/errietta
link: https://dev.to/errietta/introduction-to-the-fastapi-python-framework-2n10
title: Introduction to the fastapi python framework
- author: Nils de Bruin
author_link: https://medium.com/@nilsdebruin
link: https://medium.com/data-rebels/fastapi-how-to-add-basic-and-cookie-authentication-a45c85ef47d3
title: FastAPIHow to add basic and cookie authentication
- author: Nils de Bruin
author_link: https://medium.com/@nilsdebruin
link: https://medium.com/data-rebels/fastapi-google-as-an-external-authentication-provider-3a527672cf33
title: FastAPIGoogle as an external authentication provider
- author: William Hayes
author_link: https://medium.com/@williamhayes
link: https://medium.com/@williamhayes/fastapi-starlette-debug-vs-prod-5f7561db3a59
title: FastAPI/Starlette debug vs prod
german:
- link: https://blog.codecentric.de/2019/08/inbetriebnahme-eines-scikit-learn-modells-mit-onnx-und-fastapi/
title: Inbetriebnahme eines scikit-learn-Modells mit ONNX und FastAPI
author_link: https://twitter.com/_nicoax
author: Nico Axtmann
- author: Nico Axtmann
author_link: https://twitter.com/_nicoax
link: https://blog.codecentric.de/2019/08/inbetriebnahme-eines-scikit-learn-modells-mit-onnx-und-fastapi/
title: Inbetriebnahme eines scikit-learn-Modells mit ONNX und FastAPI
japanese:
- author: '@bee2'
author_link: https://qiita.com/bee2
link: https://qiita.com/bee2/items/75d9c0d7ba20e7a4a0e9
title: '[FastAPI] Python製のASGI Web フレームワーク FastAPIに入門する'
- author: '@bee2'
author_link: https://qiita.com/bee2
link: https://qiita.com/bee2/items/0ad260ab9835a2087dae
title: PythonのWeb frameworkのパフォーマンス比較 (Django, Flask, responder, FastAPI, japronto)
- author: ライトコードメディア編集部
author_link: https://rightcode.co.jp/author/jun
link: https://rightcode.co.jp/blog/information-technology/fastapi-tutorial-todo-apps-admin-page-improvement
title: '【第4回】FastAPIチュートリアル: toDoアプリを作ってみよう【管理者ページ改良編】'
- author: ライトコードメディア編集部
author_link: https://rightcode.co.jp/author/jun
link: https://rightcode.co.jp/blog/information-technology/fastapi-tutorial-todo-apps-authentication-user-registration
title: '【第3回】FastAPIチュートリアル: toDoアプリを作ってみよう【認証・ユーザ登録編】'
- author: ライトコードメディア編集部
author_link: https://rightcode.co.jp/author/jun
link: https://rightcode.co.jp/blog/information-technology/fastapi-tutorial-todo-apps-model-building
title: '【第2回】FastAPIチュートリアル: ToDoアプリを作ってみよう【モデル構築編】'
- author: ライトコードメディア編集部
author_link: https://rightcode.co.jp/author/jun
link: https://rightcode.co.jp/blog/information-technology/fastapi-tutorial-todo-apps-environment
title: '【第1回】FastAPIチュートリアル: ToDoアプリを作ってみよう【環境構築編】'
- author: Hikaru Takahashi
author_link: https://qiita.com/hikarut
link: https://qiita.com/hikarut/items/b178af2e2440c67c6ac4
title: フロントエンド開発者向けのDockerによるPython開発環境構築
- author: '@angel_katayoku'
author_link: https://qiita.com/angel_katayoku
link: https://qiita.com/angel_katayoku/items/8a458a8952f50b73f420
title: FastAPIでPOSTされたJSONのレスポンスbodyを受け取る
- author: '@angel_katayoku'
author_link: https://qiita.com/angel_katayoku
link: https://qiita.com/angel_katayoku/items/4fbc1a4e2b33fa2237d2
title: FastAPIをMySQLと接続してDockerで管理してみる
- author: '@angel_katayoku'
author_link: https://qiita.com/angel_katayoku
link: https://qiita.com/angel_katayoku/items/0e1f5dbbe62efc612a78
title: FastAPIでCORSを回避
- author: '@ryoryomaru'
author_link: https://qiita.com/ryoryomaru
link: https://qiita.com/ryoryomaru/items/59958ed385b3571d50de
title: python製の最新APIフレームワーク FastAPI を触ってみた
- author: '@mtitg'
author_link: https://qiita.com/mtitg
link: https://qiita.com/mtitg/items/47770e9a562dd150631d
title: FastAPIDB接続してCRUDするPython製APIサーバーを構築
russian:
- author: Troy Köhler
author_link: https://www.linkedin.com/in/trkohler/
link: https://trkohler.com/fast-api-introduction-to-framework
title: 'FastAPI: знакомимся с фреймворком'
- author: prostomarkeloff
author_link: https://github.com/prostomarkeloff
link: https://habr.com/ru/post/478620/
title: Почему Вы должны попробовать FastAPI?
- author: Andrey Korchak
author_link: https://habr.com/ru/users/57uff3r/
link: https://habr.com/ru/post/454440/
title: 'Мелкая питонячая радость #2: Starlette - Солидная примочка FastAPI'
vietnamese:
- author: Nguyễn Nhân
author_link: https://fullstackstation.com/author/figonking/
link: https://fullstackstation.com/fastapi-trien-khai-bang-docker/
title: 'FASTAPI: TRIỂN KHAI BẰNG DOCKER'
podcasts:
english:
- link: https://pythonbytes.fm/episodes/show/123/time-to-right-the-py-wrongs?time_in_sec=855
title: FastAPI on PythonBytes
author_link: https://pythonbytes.fm/
author: Python Bytes FM
- link: https://www.pythonpodcast.com/fastapi-web-application-framework-episode-259/
title: "Build The Next Generation Of Python Web Applications With FastAPI - Episode 259 - interview to Sebastían Ramírez (tiangolo)"
author_link: https://www.pythonpodcast.com/
author: Podcast.`__init__`
- author: Podcast.`__init__`
author_link: https://www.pythonpodcast.com/
link: https://www.pythonpodcast.com/fastapi-web-application-framework-episode-259/
title: Build The Next Generation Of Python Web Applications With FastAPI - Episode 259 - interview to Sebastían Ramírez (tiangolo)
- author: Python Bytes FM
author_link: https://pythonbytes.fm/
link: https://pythonbytes.fm/episodes/show/123/time-to-right-the-py-wrongs?time_in_sec=855
title: FastAPI on PythonBytes
talks:
english:
- link: https://www.youtube.com/watch?v=3DLwPcrE5mA
title: "PyCon UK 2019: FastAPI from the ground up"
author_link: https://twitter.com/chriswithers13
author: Chris Withers
- link: https://www.youtube.com/watch?v=z9K5pwb0rt8
title: "PyConBY 2020: Serve ML models easily with FastAPI"
author_link: https://twitter.com/tiangolo
author: "Sebastián Ramírez (tiangolo)"
- link: https://www.youtube.com/watch?v=PnpTY1f4k2U
title: "[VIRTUAL] Py.Amsterdam's flying Software Circus: Intro to FastAPI"
author_link: https://twitter.com/tiangolo
author: "Sebastián Ramírez (tiangolo)"
- author: Sebastián Ramírez (tiangolo)
author_link: https://twitter.com/tiangolo
link: https://www.youtube.com/watch?v=PnpTY1f4k2U
title: '[VIRTUAL] Py.Amsterdam''s flying Software Circus: Intro to FastAPI'
- author: Sebastián Ramírez (tiangolo)
author_link: https://twitter.com/tiangolo
link: https://www.youtube.com/watch?v=z9K5pwb0rt8
title: 'PyConBY 2020: Serve ML models easily with FastAPI'
- author: Chris Withers
author_link: https://twitter.com/chriswithers13
link: https://www.youtube.com/watch?v=3DLwPcrE5mA
title: 'PyCon UK 2019: FastAPI from the ground up'

View File

@@ -1,24 +1,24 @@
maintainers:
- login: tiangolo
answers: 1221
prs: 222
answers: 1225
prs: 232
avatarUrl: https://avatars.githubusercontent.com/u/1326112?u=05f95ca7fdead36edd9c86be46b4ef6c3c71f876&v=4
url: https://github.com/tiangolo
experts:
- login: Kludex
count: 267
avatarUrl: https://avatars.githubusercontent.com/u/7353520?u=cf8455cb899806b774a3a71073f88583adec99f6&v=4
url: https://github.com/Kludex
- login: dmontagu
count: 262
avatarUrl: https://avatars.githubusercontent.com/u/35119617?u=58ed2a45798a4339700e2f62b2e12e6e54bf0396&v=4
url: https://github.com/dmontagu
- login: Kludex
count: 240
avatarUrl: https://avatars.githubusercontent.com/u/7353520?u=cf8455cb899806b774a3a71073f88583adec99f6&v=4
url: https://github.com/Kludex
- login: ycd
count: 211
count: 216
avatarUrl: https://avatars.githubusercontent.com/u/62724709?u=826f228edf0bab0d19ad1d5c4ba4df1047ccffef&v=4
url: https://github.com/ycd
- login: Mause
count: 174
count: 182
avatarUrl: https://avatars.githubusercontent.com/u/1405026?v=4
url: https://github.com/Mause
- login: euri10
@@ -29,22 +29,22 @@ experts:
count: 130
avatarUrl: https://avatars.githubusercontent.com/u/331403?v=4
url: https://github.com/phy25
- login: ArcLightSlavik
count: 64
avatarUrl: https://avatars.githubusercontent.com/u/31127044?u=81a84af39c89b898b0fbc5a04e8834f60f23e55a&v=4
url: https://github.com/ArcLightSlavik
- login: falkben
count: 56
avatarUrl: https://avatars.githubusercontent.com/u/653031?u=0c8d8f33d87f1aa1a6488d3f02105e9abc838105&v=4
url: https://github.com/falkben
- login: ArcLightSlavik
count: 50
avatarUrl: https://avatars.githubusercontent.com/u/31127044?u=6e53b1a2f340d77429d435babcec107c7cc50972&v=4
url: https://github.com/ArcLightSlavik
- login: raphaelauv
count: 47
avatarUrl: https://avatars.githubusercontent.com/u/10202690?u=e6f86f5c0c3026a15d6b51792fa3e532b12f1371&v=4
url: https://github.com/raphaelauv
- login: sm-Fifteen
count: 46
avatarUrl: https://avatars.githubusercontent.com/u/516999?u=437c0c5038558c67e887ccd863c1ba0f846c03da&v=4
url: https://github.com/sm-Fifteen
- login: raphaelauv
count: 41
avatarUrl: https://avatars.githubusercontent.com/u/10202690?u=e6f86f5c0c3026a15d6b51792fa3e532b12f1371&v=4
url: https://github.com/raphaelauv
- login: includeamin
count: 38
avatarUrl: https://avatars.githubusercontent.com/u/11836741?u=8bd5ef7e62fe6a82055e33c4c0e0a7879ff8cfb6&v=4
@@ -54,7 +54,7 @@ experts:
avatarUrl: https://avatars.githubusercontent.com/u/28061158?u=72309cc1f2e04e40fa38b29969cb4e9d3f722e7b&v=4
url: https://github.com/prostomarkeloff
- login: Dustyposa
count: 31
count: 32
avatarUrl: https://avatars.githubusercontent.com/u/27180793?u=5cf2877f50b3eb2bc55086089a78a36f07042889&v=4
url: https://github.com/Dustyposa
- login: krishnardt
@@ -77,6 +77,10 @@ experts:
count: 24
avatarUrl: https://avatars.githubusercontent.com/u/9435877?u=719327b7d2c4c62212456d771bfa7c6b8dbb9eac&v=4
url: https://github.com/SirTelemak
- login: chbndrhnns
count: 22
avatarUrl: https://avatars.githubusercontent.com/u/7534547?v=4
url: https://github.com/chbndrhnns
- login: acnebs
count: 22
avatarUrl: https://avatars.githubusercontent.com/u/9054108?u=bfd127b3e6200f4d00afd714f0fc95c2512df19b&v=4
@@ -85,6 +89,10 @@ experts:
count: 22
avatarUrl: https://avatars.githubusercontent.com/u/22559461?u=a9cc3238217e21dc8796a1a500f01b722adb082c&v=4
url: https://github.com/nsidnev
- login: frankie567
count: 21
avatarUrl: https://avatars.githubusercontent.com/u/1144727?u=72adf1cb1d29787305c99700d669561952cea0af&v=4
url: https://github.com/frankie567
- login: chris-allnutt
count: 21
avatarUrl: https://avatars.githubusercontent.com/u/565544?v=4
@@ -93,6 +101,10 @@ experts:
count: 19
avatarUrl: https://avatars.githubusercontent.com/u/24581770?v=4
url: https://github.com/retnikt
- login: Hultner
count: 18
avatarUrl: https://avatars.githubusercontent.com/u/2669034?u=115e53df959309898ad8dc9443fbb35fee71df07&v=4
url: https://github.com/Hultner
- login: jorgerpo
count: 17
avatarUrl: https://avatars.githubusercontent.com/u/12537771?u=7444d20019198e34911082780cc7ad73f2b97cb3&v=4
@@ -101,22 +113,18 @@ experts:
count: 17
avatarUrl: https://avatars.githubusercontent.com/u/28262306?u=66ee21316275ef356081c2efc4ed7a4572e690dc&v=4
url: https://github.com/nkhitrov
- login: chbndrhnns
count: 15
avatarUrl: https://avatars.githubusercontent.com/u/7534547?v=4
url: https://github.com/chbndrhnns
- login: waynerv
count: 14
count: 15
avatarUrl: https://avatars.githubusercontent.com/u/39515546?u=ec35139777597cdbbbddda29bf8b9d4396b429a9&v=4
url: https://github.com/waynerv
- login: haizaar
count: 13
avatarUrl: https://avatars.githubusercontent.com/u/58201?u=4f1f9843d69433ca0d380d95146cfe119e5fdac4&v=4
url: https://github.com/haizaar
- login: frankie567
- login: acidjunk
count: 11
avatarUrl: https://avatars.githubusercontent.com/u/1144727?u=72adf1cb1d29787305c99700d669561952cea0af&v=4
url: https://github.com/frankie567
avatarUrl: https://avatars.githubusercontent.com/u/685002?u=b5094ab4527fc84b006c0ac9ff54367bdebb2267&v=4
url: https://github.com/acidjunk
- login: zamiramir
count: 11
avatarUrl: https://avatars.githubusercontent.com/u/40475662?u=e58ef61034e8d0d6a312cc956fb09b9c3332b449&v=4
@@ -139,25 +147,37 @@ experts:
url: https://github.com/stefanondisponibile
last_month_active:
- login: Kludex
count: 13
count: 12
avatarUrl: https://avatars.githubusercontent.com/u/7353520?u=cf8455cb899806b774a3a71073f88583adec99f6&v=4
url: https://github.com/Kludex
- login: ycd
count: 7
avatarUrl: https://avatars.githubusercontent.com/u/62724709?u=826f228edf0bab0d19ad1d5c4ba4df1047ccffef&v=4
url: https://github.com/ycd
- login: raphaelauv
count: 6
avatarUrl: https://avatars.githubusercontent.com/u/10202690?u=e6f86f5c0c3026a15d6b51792fa3e532b12f1371&v=4
url: https://github.com/raphaelauv
- login: frankie567
count: 5
count: 9
avatarUrl: https://avatars.githubusercontent.com/u/1144727?u=72adf1cb1d29787305c99700d669561952cea0af&v=4
url: https://github.com/frankie567
- login: insomnes
- login: Mause
count: 6
avatarUrl: https://avatars.githubusercontent.com/u/1405026?v=4
url: https://github.com/Mause
- login: ArcLightSlavik
count: 6
avatarUrl: https://avatars.githubusercontent.com/u/31127044?u=81a84af39c89b898b0fbc5a04e8834f60f23e55a&v=4
url: https://github.com/ArcLightSlavik
- login: gyKa
count: 4
avatarUrl: https://avatars.githubusercontent.com/u/16958893?u=f8be7088d5076d963984a21f95f44e559192d912&v=4
url: https://github.com/insomnes
avatarUrl: https://avatars.githubusercontent.com/u/1000842?v=4
url: https://github.com/gyKa
- login: ricky-sb
count: 3
avatarUrl: https://avatars.githubusercontent.com/u/10700079?v=4
url: https://github.com/ricky-sb
- login: captainCapitalism
count: 3
avatarUrl: https://avatars.githubusercontent.com/u/32553875?v=4
url: https://github.com/captainCapitalism
- login: acidjunk
count: 3
avatarUrl: https://avatars.githubusercontent.com/u/685002?u=b5094ab4527fc84b006c0ac9ff54367bdebb2267&v=4
url: https://github.com/acidjunk
top_contributors:
- login: waynerv
count: 25
@@ -184,7 +204,7 @@ top_contributors:
avatarUrl: https://avatars.githubusercontent.com/u/31848542?u=706e1ee3f248245f2d68b976d149d06fd5a2010d&v=4
url: https://github.com/RunningIkkyu
- login: Serrones
count: 6
count: 7
avatarUrl: https://avatars.githubusercontent.com/u/22691749?u=4795b880e13ca33a73e52fc0ef7dc9c60c8fce47&v=4
url: https://github.com/Serrones
- login: hard-coders
@@ -211,29 +231,33 @@ top_contributors:
count: 4
avatarUrl: https://avatars.githubusercontent.com/u/39375566?u=5a44657c0544111ee3c132d9bb9951c2804f7969&v=4
url: https://github.com/komtaki
- login: Smlep
count: 4
avatarUrl: https://avatars.githubusercontent.com/u/16785985?v=4
url: https://github.com/Smlep
top_reviewers:
- login: Kludex
count: 75
count: 80
avatarUrl: https://avatars.githubusercontent.com/u/7353520?u=cf8455cb899806b774a3a71073f88583adec99f6&v=4
url: https://github.com/Kludex
- login: tokusumi
count: 44
avatarUrl: https://avatars.githubusercontent.com/u/41147016?u=55010621aece725aa702270b54fed829b6a1fe60&v=4
url: https://github.com/tokusumi
- login: ycd
count: 39
avatarUrl: https://avatars.githubusercontent.com/u/62724709?u=826f228edf0bab0d19ad1d5c4ba4df1047ccffef&v=4
url: https://github.com/ycd
- login: Laineyzhang55
count: 34
count: 42
avatarUrl: https://avatars.githubusercontent.com/u/59285379?v=4
url: https://github.com/Laineyzhang55
- login: ycd
count: 41
avatarUrl: https://avatars.githubusercontent.com/u/62724709?u=826f228edf0bab0d19ad1d5c4ba4df1047ccffef&v=4
url: https://github.com/ycd
- login: waynerv
count: 32
count: 38
avatarUrl: https://avatars.githubusercontent.com/u/39515546?u=ec35139777597cdbbbddda29bf8b9d4396b429a9&v=4
url: https://github.com/waynerv
- login: AdrianDeAnda
count: 26
count: 28
avatarUrl: https://avatars.githubusercontent.com/u/1024932?u=bb7f8a0d6c9de4e9d0320a9f271210206e202250&v=4
url: https://github.com/AdrianDeAnda
- login: dmontagu
@@ -244,6 +268,14 @@ top_reviewers:
count: 21
avatarUrl: https://avatars.githubusercontent.com/u/39375566?u=5a44657c0544111ee3c132d9bb9951c2804f7969&v=4
url: https://github.com/komtaki
- login: ArcLightSlavik
count: 20
avatarUrl: https://avatars.githubusercontent.com/u/31127044?u=81a84af39c89b898b0fbc5a04e8834f60f23e55a&v=4
url: https://github.com/ArcLightSlavik
- login: cassiobotaro
count: 16
avatarUrl: https://avatars.githubusercontent.com/u/3127847?u=b0a652331da17efeb85cd6e3a4969182e5004804&v=4
url: https://github.com/cassiobotaro
- login: yanever
count: 16
avatarUrl: https://avatars.githubusercontent.com/u/21978760?v=4
@@ -260,18 +292,10 @@ top_reviewers:
count: 15
avatarUrl: https://avatars.githubusercontent.com/u/63476957?u=6c86e59b48e0394d4db230f37fc9ad4d7e2c27c7&v=4
url: https://github.com/delhi09
- login: cassiobotaro
count: 14
avatarUrl: https://avatars.githubusercontent.com/u/3127847?u=b0a652331da17efeb85cd6e3a4969182e5004804&v=4
url: https://github.com/cassiobotaro
- login: RunningIkkyu
count: 12
avatarUrl: https://avatars.githubusercontent.com/u/31848542?u=706e1ee3f248245f2d68b976d149d06fd5a2010d&v=4
url: https://github.com/RunningIkkyu
- login: ArcLightSlavik
count: 12
avatarUrl: https://avatars.githubusercontent.com/u/31127044?u=6e53b1a2f340d77429d435babcec107c7cc50972&v=4
url: https://github.com/ArcLightSlavik
- login: hard-coders
count: 12
avatarUrl: https://avatars.githubusercontent.com/u/9651103?u=f2d3d2038c55d86d7f9348f4e6c5e30191e4ee8b&v=4
@@ -296,6 +320,14 @@ top_reviewers:
count: 9
avatarUrl: https://avatars.githubusercontent.com/u/13096845?u=646eba44db720e37d0dbe8e98e77ab534ea78a20&v=4
url: https://github.com/PandaHun
- login: bezaca
count: 9
avatarUrl: https://avatars.githubusercontent.com/u/69092910?u=4ac58eab99bd37d663f3d23551df96d4fbdbf760&v=4
url: https://github.com/bezaca
- login: lsglucas
count: 8
avatarUrl: https://avatars.githubusercontent.com/u/61513630?u=320e43fe4dc7bc6efc64e9b8f325f8075634fd20&v=4
url: https://github.com/lsglucas
- login: rjNemo
count: 8
avatarUrl: https://avatars.githubusercontent.com/u/56785022?u=d5c3a02567c8649e146fcfc51b6060ccaf8adef8&v=4
@@ -316,22 +348,26 @@ top_reviewers:
count: 7
avatarUrl: https://avatars.githubusercontent.com/u/10202690?u=e6f86f5c0c3026a15d6b51792fa3e532b12f1371&v=4
url: https://github.com/raphaelauv
- login: NastasiaSaby
count: 7
avatarUrl: https://avatars.githubusercontent.com/u/8245071?u=b3afd005f9e4bf080c219ef61a592b3a8004b764&v=4
url: https://github.com/NastasiaSaby
- login: Smlep
count: 7
avatarUrl: https://avatars.githubusercontent.com/u/16785985?v=4
url: https://github.com/Smlep
- login: jovicon
count: 6
avatarUrl: https://avatars.githubusercontent.com/u/21287303?u=b049eac3e51a4c0473c2efe66b4d28a7d8f2b572&v=4
url: https://github.com/jovicon
- login: NastasiaSaby
- login: Mause
count: 6
avatarUrl: https://avatars.githubusercontent.com/u/8245071?u=b3afd005f9e4bf080c219ef61a592b3a8004b764&v=4
url: https://github.com/NastasiaSaby
avatarUrl: https://avatars.githubusercontent.com/u/1405026?v=4
url: https://github.com/Mause
- login: nimctl
count: 5
avatarUrl: https://avatars.githubusercontent.com/u/49960770?u=e39b11d47188744ee07b2a1c7ce1a1bdf3c80760&v=4
url: https://github.com/nimctl
- login: Mause
count: 5
avatarUrl: https://avatars.githubusercontent.com/u/1405026?v=4
url: https://github.com/Mause
- login: juntatalor
count: 5
avatarUrl: https://avatars.githubusercontent.com/u/8134632?v=4
@@ -340,6 +376,10 @@ top_reviewers:
count: 5
avatarUrl: https://avatars.githubusercontent.com/u/63564282?u=0078826509dbecb2fdb543f4e881c9cd06157893&v=4
url: https://github.com/SnkSynthesis
- login: anthonycepeda
count: 5
avatarUrl: https://avatars.githubusercontent.com/u/72019805?u=892f700c79f9732211bd5221bf16eec32356a732&v=4
url: https://github.com/anthonycepeda
- login: euri10
count: 4
avatarUrl: https://avatars.githubusercontent.com/u/1104190?u=321a2e953e6645a7d09b732786c7a8061e0f8a8b&v=4
@@ -356,6 +396,10 @@ top_reviewers:
count: 4
avatarUrl: https://avatars.githubusercontent.com/u/31370133?v=4
url: https://github.com/Zxilly
- login: Bluenix2
count: 4
avatarUrl: https://avatars.githubusercontent.com/u/38372706?u=c9d28aff15958d6ebf1971148bfb3154ff943c4f&v=4
url: https://github.com/Bluenix2
sponsors_50:
- login: johnadjei
avatarUrl: https://avatars.githubusercontent.com/u/767860?v=4
@@ -363,6 +407,9 @@ sponsors_50:
- login: wdwinslow
avatarUrl: https://avatars.githubusercontent.com/u/11562137?u=dc01daafb354135603a263729e3d26d939c0c452&v=4
url: https://github.com/wdwinslow
- login: bingwu-chime
avatarUrl: https://avatars.githubusercontent.com/u/67026650?u=603a6b345f25c20c6706a8a6c7f71ae688d649a5&v=4
url: https://github.com/bingwu-chime
sponsors:
- login: kamalgill
avatarUrl: https://avatars.githubusercontent.com/u/133923?u=0df9181d97436ce330e9acf90ab8a54b7022efe7&v=4
@@ -370,15 +417,15 @@ sponsors:
- login: grillazz
avatarUrl: https://avatars.githubusercontent.com/u/3415861?u=16d7d0ffa5dfb99f8834f8f76d90e138ba09b94a&v=4
url: https://github.com/grillazz
- login: CarlosDomingues
avatarUrl: https://avatars.githubusercontent.com/u/11181378?u=4c15832fa030a5f3fd024ca4912093b4b59a40bd&v=4
url: https://github.com/CarlosDomingues
- login: tizz98
avatarUrl: https://avatars.githubusercontent.com/u/5739698?u=f095a3659e3a8e7c69ccd822696990b521ea25f9&v=4
url: https://github.com/tizz98
- login: jmaralc
avatarUrl: https://avatars.githubusercontent.com/u/21101214?u=b15a9f07b7cbf6c9dcdbcb6550bbd2c52f55aa50&v=4
url: https://github.com/jmaralc
- login: lucone83
avatarUrl: https://avatars.githubusercontent.com/u/2812607?u=49c0c4454d4c98eacdcac0e33c1d83dc6fe5a37f&v=4
url: https://github.com/lucone83
- login: psgandalf
avatarUrl: https://avatars.githubusercontent.com/u/8134158?v=4
url: https://github.com/psgandalf
- login: samuelcolvin
avatarUrl: https://avatars.githubusercontent.com/u/4039449?u=807390ba9cfe23906c3bf8a0d56aaca3cf2bfa0d&v=4
url: https://github.com/samuelcolvin
@@ -394,8 +441,11 @@ sponsors:
- login: falkben
avatarUrl: https://avatars.githubusercontent.com/u/653031?u=0c8d8f33d87f1aa1a6488d3f02105e9abc838105&v=4
url: https://github.com/falkben
- login: jqueguiner
avatarUrl: https://avatars.githubusercontent.com/u/690878?u=e4835b2a985a0f2d52018e4926cb5a58c26a62e8&v=4
url: https://github.com/jqueguiner
- login: Mazyod
avatarUrl: https://avatars.githubusercontent.com/u/860511?u=a76c978bdf91c2b332ab8769935fa415d0a8091b&v=4
avatarUrl: https://avatars.githubusercontent.com/u/860511?v=4
url: https://github.com/Mazyod
- login: ltieman
avatarUrl: https://avatars.githubusercontent.com/u/1084689?u=e69b17de17cb3ca141a17daa7ccbe173ceb1eb17&v=4
@@ -415,9 +465,9 @@ sponsors:
- login: madisonmay
avatarUrl: https://avatars.githubusercontent.com/u/2645393?u=f22b93c6ea345a4d26a90a3834dfc7f0789fcb63&v=4
url: https://github.com/madisonmay
- login: jorgecarleitao
avatarUrl: https://avatars.githubusercontent.com/u/2772607?u=6ba4aa5ded7b492043ba76f3f900e3b4cc102b57&v=4
url: https://github.com/jorgecarleitao
- login: saivarunk
avatarUrl: https://avatars.githubusercontent.com/u/2976867?u=71f4385e781e9a9e871a52f2d4686f9a8d69ba2f&v=4
url: https://github.com/saivarunk
- login: andre1sk
avatarUrl: https://avatars.githubusercontent.com/u/3148093?v=4
url: https://github.com/andre1sk
@@ -430,18 +480,21 @@ sponsors:
- login: dudil
avatarUrl: https://avatars.githubusercontent.com/u/4785835?u=58b7ea39123e0507f3b2996448a27256b16fd697&v=4
url: https://github.com/dudil
- login: p141592
avatarUrl: https://avatars.githubusercontent.com/u/5256328?u=07bc6374282ab3d08511afebaa5d511987d034f1&v=4
url: https://github.com/p141592
- login: ennui93
avatarUrl: https://avatars.githubusercontent.com/u/5300907?u=5b5452725ddb391b2caaebf34e05aba873591c3a&v=4
url: https://github.com/ennui93
- login: sco1
avatarUrl: https://avatars.githubusercontent.com/u/5323929?u=2b8434060d0c9d93de80a2a945baed94a412c31e&v=4
url: https://github.com/sco1
- login: MacroPower
avatarUrl: https://avatars.githubusercontent.com/u/5648814?u=b2730000c9f9a471282b9849d2cc85711d7973d4&v=4
url: https://github.com/MacroPower
- login: ginomempin
avatarUrl: https://avatars.githubusercontent.com/u/6091865?v=4
url: https://github.com/ginomempin
- login: iwpnd
avatarUrl: https://avatars.githubusercontent.com/u/6152183?u=b2286006daafff5f991557344fee20b5da59639a&v=4
url: https://github.com/iwpnd
- login: s3ich4n
avatarUrl: https://avatars.githubusercontent.com/u/6926298?u=ba3025d698e1c986655e776ae383a3d60d9d578e&v=4
url: https://github.com/s3ich4n
@@ -451,9 +504,6 @@ sponsors:
- login: christippett
avatarUrl: https://avatars.githubusercontent.com/u/7218120?u=434b9d29287d7de25772d94ddc74a9bd6d969284&v=4
url: https://github.com/christippett
- login: yukiyan
avatarUrl: https://avatars.githubusercontent.com/u/7304122?u=fadb64baf3934c708349bbea1142d260a6b6ce6b&v=4
url: https://github.com/yukiyan
- login: Kludex
avatarUrl: https://avatars.githubusercontent.com/u/7353520?u=cf8455cb899806b774a3a71073f88583adec99f6&v=4
url: https://github.com/Kludex
@@ -466,18 +516,12 @@ sponsors:
- login: cristeaadrian
avatarUrl: https://avatars.githubusercontent.com/u/9112724?v=4
url: https://github.com/cristeaadrian
- login: opunsoars
avatarUrl: https://avatars.githubusercontent.com/u/9273060?u=97f5ecec274e159b22787ca2f466f13ab1797758&v=4
url: https://github.com/opunsoars
- login: otivvormes
avatarUrl: https://avatars.githubusercontent.com/u/11317418?u=6de1edefb6afd0108c0ad2816bd6efc4464a9c44&v=4
url: https://github.com/otivvormes
- login: iambobmae
avatarUrl: https://avatars.githubusercontent.com/u/12390270?u=c9a35c2ee5092a9b4135ebb1f91b7f521c467031&v=4
url: https://github.com/iambobmae
- login: Cozmo25
avatarUrl: https://avatars.githubusercontent.com/u/12619962?u=679dcd6785121e14f6254e9dd0961baf3b1fef5d&v=4
url: https://github.com/Cozmo25
- login: ronaldnwilliams
avatarUrl: https://avatars.githubusercontent.com/u/13632749?u=ac41a086d0728bf66a9d2bee9e5e377041ff44a4&v=4
url: https://github.com/ronaldnwilliams
@@ -508,6 +552,9 @@ sponsors:
- login: daddycocoaman
avatarUrl: https://avatars.githubusercontent.com/u/21189155?u=756f6a17c71c538b11470f70839baacab43807ef&v=4
url: https://github.com/daddycocoaman
- login: Filimoa
avatarUrl: https://avatars.githubusercontent.com/u/21352040?u=75e02d102d2ee3e3d793e555fa5c63045913ccb0&v=4
url: https://github.com/Filimoa
- login: raminsj13
avatarUrl: https://avatars.githubusercontent.com/u/24259406?u=d51f2a526312ebba150a06936ed187ca0727d329&v=4
url: https://github.com/raminsj13
@@ -520,9 +567,6 @@ sponsors:
- login: orihomie
avatarUrl: https://avatars.githubusercontent.com/u/29889683?u=6bc2135a52fcb3a49e69e7d50190796618185fda&v=4
url: https://github.com/orihomie
- login: Huffon
avatarUrl: https://avatars.githubusercontent.com/u/31345506?u=c41bdf60facd004ec6364bf718ce16f8da2b884f&v=4
url: https://github.com/Huffon
- login: SaltyCoco
avatarUrl: https://avatars.githubusercontent.com/u/31451104?u=6ee4e17c07d21b7054f54a12fa9cc377a1b24ff9&v=4
url: https://github.com/SaltyCoco
@@ -541,9 +585,6 @@ sponsors:
- login: dudikbender
avatarUrl: https://avatars.githubusercontent.com/u/53487583?u=494f85229115076121b3639a3806bbac1c6ae7f6&v=4
url: https://github.com/dudikbender
- login: Brontomerus
avatarUrl: https://avatars.githubusercontent.com/u/61284158?u=4aee24daee1921daa722cde3fcb6701e3e37ea31&v=4
url: https://github.com/Brontomerus
- login: primer-io
avatarUrl: https://avatars.githubusercontent.com/u/62146168?v=4
url: https://github.com/primer-io
@@ -556,24 +597,24 @@ sponsors:
- login: anthonycepeda
avatarUrl: https://avatars.githubusercontent.com/u/72019805?u=892f700c79f9732211bd5221bf16eec32356a732&v=4
url: https://github.com/anthonycepeda
- login: pqhaa
avatarUrl: https://avatars.githubusercontent.com/u/81242906?u=a71c5869241fc14dea6e413fb4b84287fefed38e&v=4
url: https://github.com/pqhaa
- login: saldistefano
avatarUrl: https://avatars.githubusercontent.com/u/82109221?v=4
url: https://github.com/saldistefano
- login: linux-china
avatarUrl: https://avatars.githubusercontent.com/u/46711?v=4
url: https://github.com/linux-china
- login: jhb
avatarUrl: https://avatars.githubusercontent.com/u/142217?v=4
url: https://github.com/jhb
- login: yourkin
avatarUrl: https://avatars.githubusercontent.com/u/178984?v=4
url: https://github.com/yourkin
- login: jmagnusson
avatarUrl: https://avatars.githubusercontent.com/u/190835?v=4
url: https://github.com/jmagnusson
- login: slafs
avatarUrl: https://avatars.githubusercontent.com/u/210173?v=4
url: https://github.com/slafs
- login: adamghill
avatarUrl: https://avatars.githubusercontent.com/u/317045?u=f1349d5ffe84a19f324e204777859fbf69ddf633&v=4
url: https://github.com/adamghill
- login: eteq
avatarUrl: https://avatars.githubusercontent.com/u/346587?v=4
url: https://github.com/eteq
@@ -583,15 +624,24 @@ sponsors:
- login: hongqn
avatarUrl: https://avatars.githubusercontent.com/u/405587?u=470b4c04832e45141fd5264d3354845cc9fc6466&v=4
url: https://github.com/hongqn
- login: lukin0110
avatarUrl: https://avatars.githubusercontent.com/u/992275?u=d20b7e18b213ae7004585b382eccb542db5ffe48&v=4
url: https://github.com/lukin0110
- login: rinckd
avatarUrl: https://avatars.githubusercontent.com/u/546002?u=1fcc7e664dc86524a0af6837a0c222829c3fd4e5&v=4
url: https://github.com/rinckd
- login: Pytlicek
avatarUrl: https://avatars.githubusercontent.com/u/1430522?u=169dba3bfbc04ed214a914640ff435969f19ddb3&v=4
url: https://github.com/Pytlicek
- login: okken
avatarUrl: https://avatars.githubusercontent.com/u/1568356?u=0a991a21bdc62e2bea9ad311652f2c45f453dc84&v=4
url: https://github.com/okken
- login: leogregianin
avatarUrl: https://avatars.githubusercontent.com/u/1684053?u=94ddd387601bd1805034dbe83e6eba0491c15323&v=4
url: https://github.com/leogregianin
- login: cbonoz
avatarUrl: https://avatars.githubusercontent.com/u/2351087?u=fd3e8030b2cc9fbfbb54a65e9890c548a016f58b&v=4
url: https://github.com/cbonoz
- login: rglsk
avatarUrl: https://avatars.githubusercontent.com/u/2768101?u=e349c88673f2155fe021331377c656a9d74bcc25&v=4
url: https://github.com/rglsk
- login: Atem18
avatarUrl: https://avatars.githubusercontent.com/u/2875254?v=4
url: https://github.com/Atem18
@@ -602,7 +652,7 @@ sponsors:
avatarUrl: https://avatars.githubusercontent.com/u/3438238?u=c57605077c31a8f7b2341fc4912507f91b4a5621&v=4
url: https://github.com/igorcorrea
- login: zsinx6
avatarUrl: https://avatars.githubusercontent.com/u/3532625?v=4
avatarUrl: https://avatars.githubusercontent.com/u/3532625?u=ba75a5dc744d1116ccfeaaf30d41cb2fe81fe8dd&v=4
url: https://github.com/zsinx6
- login: pawamoy
avatarUrl: https://avatars.githubusercontent.com/u/3999221?u=b030e4c89df2f3a36bc4710b925bdeb6745c9856&v=4
@@ -610,9 +660,12 @@ sponsors:
- login: spyker77
avatarUrl: https://avatars.githubusercontent.com/u/4953435?u=568baae6469628e020fe0bab16e395b7ae10c7d3&v=4
url: https://github.com/spyker77
- login: iwpnd
avatarUrl: https://avatars.githubusercontent.com/u/6152183?u=b2286006daafff5f991557344fee20b5da59639a&v=4
url: https://github.com/iwpnd
- login: serfer2
avatarUrl: https://avatars.githubusercontent.com/u/5196592?u=e8798d87120952ed41876778f0cc8a1ddb47f901&v=4
url: https://github.com/serfer2
- login: JonasKs
avatarUrl: https://avatars.githubusercontent.com/u/5310116?u=98a049f3e1491bffb91e1feb7e93def6881a9389&v=4
url: https://github.com/JonasKs
- login: holec
avatarUrl: https://avatars.githubusercontent.com/u/6438041?u=f5af71ec85b3a9d7b8139cb5af0512b02fa9ab1e&v=4
url: https://github.com/holec
@@ -631,45 +684,69 @@ sponsors:
- login: hard-coders
avatarUrl: https://avatars.githubusercontent.com/u/9651103?u=f2d3d2038c55d86d7f9348f4e6c5e30191e4ee8b&v=4
url: https://github.com/hard-coders
- login: satwikkansal
avatarUrl: https://avatars.githubusercontent.com/u/10217535?u=b12d6ef74ea297de9e46da6933b1a5b7ba9e6a61&v=4
url: https://github.com/satwikkansal
- login: pheanex
avatarUrl: https://avatars.githubusercontent.com/u/10408624?u=5b6bab6ee174aa6e991333e06eb29f628741013d&v=4
url: https://github.com/pheanex
- login: wotori
avatarUrl: https://avatars.githubusercontent.com/u/10486621?u=0044c295b91694b8c9bccc0a805681f794250f7b&v=4
url: https://github.com/wotori
- login: JimFawkes
avatarUrl: https://avatars.githubusercontent.com/u/12075115?u=dc58ecfd064d72887c34bf500ddfd52592509acd&v=4
url: https://github.com/JimFawkes
- login: logan-connolly
avatarUrl: https://avatars.githubusercontent.com/u/16244943?u=8ae66dfbba936463cc8aa0dd7a6d2b4c0cc757eb&v=4
url: https://github.com/logan-connolly
- login: sebastianmarines
avatarUrl: https://avatars.githubusercontent.com/u/18373185?u=e0be7c230456a2bdc0825e3d6541ea8966e22028&v=4
url: https://github.com/sebastianmarines
- login: Filimoa
avatarUrl: https://avatars.githubusercontent.com/u/21352040?u=75e02d102d2ee3e3d793e555fa5c63045913ccb0&v=4
url: https://github.com/Filimoa
- login: iPr0ger
avatarUrl: https://avatars.githubusercontent.com/u/19322290?v=4
url: https://github.com/iPr0ger
- login: sadikkuzu
avatarUrl: https://avatars.githubusercontent.com/u/23168063?u=765ed469c44c004560079210ccdad5b29938eaa9&v=4
url: https://github.com/sadikkuzu
- login: ghandic
avatarUrl: https://avatars.githubusercontent.com/u/23500353?u=e2e1d736f924d9be81e8bfc565b6d8836ba99773&v=4
url: https://github.com/ghandic
- login: MoronVV
avatarUrl: https://avatars.githubusercontent.com/u/24293616?v=4
url: https://github.com/MoronVV
- login: AngusWG
avatarUrl: https://avatars.githubusercontent.com/u/26385612?u=f4d4c8bd2097cdd58eb9e385932b83c78777f3c0&v=4
url: https://github.com/AngusWG
- login: mertguvencli
avatarUrl: https://avatars.githubusercontent.com/u/29762151?u=16a906d90df96c8cff9ea131a575c4bc171b1523&v=4
url: https://github.com/mertguvencli
- login: rgreen32
avatarUrl: https://avatars.githubusercontent.com/u/35779241?u=c9d64ad1ab364b6a1ec8e3d859da9ca802d681d8&v=4
url: https://github.com/rgreen32
- login: leynier
avatarUrl: https://avatars.githubusercontent.com/u/36774373?u=60eee7ab14aada5aab8af6fbd11d14732750a7ab&v=4
url: https://github.com/leynier
- login: askurihin
avatarUrl: https://avatars.githubusercontent.com/u/37978981?v=4
url: https://github.com/askurihin
- login: berrysauce
avatarUrl: https://avatars.githubusercontent.com/u/38889179?u=758ed15a5be8bbd03855f5a74f42c19f7946ee32&v=4
url: https://github.com/berrysauce
- login: JitPackJoyride
avatarUrl: https://avatars.githubusercontent.com/u/40203625?u=9638bfeacfa5940358188f8205ce662bba022b53&v=4
url: https://github.com/JitPackJoyride
- login: es3n1n
avatarUrl: https://avatars.githubusercontent.com/u/40367813?u=f562f0f93b108a923be6aba1ec041128286c3c50&v=4
avatarUrl: https://avatars.githubusercontent.com/u/40367813?u=e881a3880f1e342d19a1ea7c8e1b6d76c52dc294&v=4
url: https://github.com/es3n1n
- login: ilias-ant
avatarUrl: https://avatars.githubusercontent.com/u/42189572?u=064bf3a60fcb3c445ab038386321098920b3f4e4&v=4
avatarUrl: https://avatars.githubusercontent.com/u/42189572?u=a2d6121bac4d125d92ec207460fa3f1842d37e66&v=4
url: https://github.com/ilias-ant
- login: kbhatiya999
avatarUrl: https://avatars.githubusercontent.com/u/47816034?v=4
url: https://github.com/kbhatiya999
- login: akanz1
avatarUrl: https://avatars.githubusercontent.com/u/51492342?u=2280f57134118714645e16b535c1a37adf6b369b&v=4
url: https://github.com/akanz1
- login: rychardvale
avatarUrl: https://avatars.githubusercontent.com/u/54805553?u=3d20ab05301d05f9ac3500fb79a2bfee3842b753&v=4
url: https://github.com/rychardvale
- login: athemeart
avatarUrl: https://avatars.githubusercontent.com/u/61623624?v=4
url: https://github.com/athemeart
- login: Rhythmicc
avatarUrl: https://avatars.githubusercontent.com/u/29839231?u=2100781089a259707c475c4547bd7995b0fc18ee&v=4
url: https://github.com/Rhythmicc

View File

@@ -2,6 +2,9 @@ gold:
- url: https://www.deta.sh/?ref=fastapi
title: The launchpad for all your (team's) ideas
img: https://fastapi.tiangolo.com/img/sponsors/deta.svg
- url: https://bit.ly/2QSouzH
title: "Jina: build neural search-as-a-service for any kind of data in just minutes."
img: https://fastapi.tiangolo.com/img/sponsors/jina.svg
silver:
- url: https://www.investsuite.com/jobs
title: Wealthtech jobs with FastAPI

View File

@@ -161,10 +161,33 @@ An alternative JSON response using <a href="https://github.com/ultrajson/ultrajs
Returns an HTTP redirect. Uses a 307 status code (Temporary Redirect) by default.
You can return a `RedirectResponse` directly:
```Python hl_lines="2 9"
{!../../../docs_src/custom_response/tutorial006.py!}
```
---
Or you can use it in the `response_class` parameter:
```Python hl_lines="2 7 9"
{!../../../docs_src/custom_response/tutorial006b.py!}
```
If you do that, then you can return the URL directly from your *path operation* function.
In this case, the `status_code` used will be the default one for the `RedirectResponse`, which is `307`.
---
You can also use the `status_code` parameter combined with the `response_class` parameter:
```Python hl_lines="2 7 9"
{!../../../docs_src/custom_response/tutorial006c.py!}
```
### `StreamingResponse`
Takes an async generator or a normal generator/iterator and streams the response body.
@@ -175,14 +198,24 @@ Takes an async generator or a normal generator/iterator and streams the response
#### Using `StreamingResponse` with file-like objects
If you have a file-like object (e.g. the object returned by `open()`), you can return it in a `StreamingResponse`.
If you have a file-like object (e.g. the object returned by `open()`), you can create a generator function to iterate over that file-like object.
That way, you don't have to read it all first in memory, and you can pass that generator function to the `StreamingResponse`, and return it.
This includes many libraries to interact with cloud storage, video processing, and others.
```Python hl_lines="2 10-11"
```{ .python .annotate hl_lines="2 10-12 14" }
{!../../../docs_src/custom_response/tutorial008.py!}
```
1. This is the generator function. It's a "generator function" because it contains `yield` statements inside.
2. By using a `with` block, we make sure that the file-like object is closed after the generator function is done. So, after it finishes sending the response.
3. This `yield from` tells the function to iterate over that thing named `file_like`. And then, for each part iterated, yield that part as coming from this generator function.
So, it is a generator function that transfers the "generating" work to something else internally.
By doing it this way, we can put it in a `with` block, and that way, ensure that it is closed after finishing.
!!! tip
Notice that here as we are using standard `open()` that doesn't support `async` and `await`, we declare the path operation with normal `def`.
@@ -203,6 +236,14 @@ File responses will include appropriate `Content-Length`, `Last-Modified` and `E
{!../../../docs_src/custom_response/tutorial009.py!}
```
You can also use the `response_class` parameter:
```Python hl_lines="2 8 10"
{!../../../docs_src/custom_response/tutorial009b.py!}
```
In this case, you can return the file path directly from your *path operation* function.
## Default response class
When creating a **FastAPI** class instance or an `APIRouter` you can specify which response class to use by default.

View File

@@ -0,0 +1,98 @@
# Using Dataclasses
FastAPI is built on top of **Pydantic**, and I have been showing you how to use Pydantic models to declare requests and responses.
But FastAPI also supports using <a href="https://docs.python.org/3/library/dataclasses.html" class="external-link" target="_blank">`dataclasses`</a> the same way:
```Python hl_lines="1 7-12 19-20"
{!../../../docs_src/dataclasses/tutorial001.py!}
```
This is still thanks to **Pydantic**, as it has <a href="https://pydantic-docs.helpmanual.io/usage/dataclasses/#use-of-stdlib-dataclasses-with-basemodel" class="external-link" target="_blank">internal support for `dataclasses`</a>.
So, even with the code above that doesn't use Pydantic explicitly, FastAPI is using Pydantic to convert those standard dataclasses to Pydantic's own flavor of dataclasses.
And of course, it supports the same:
* data validation
* data serialization
* data documentation, etc.
This works the same way as with Pydantic models. And it is actually achieved in the same way underneath, using Pydantic.
!!! info
Have in mind that dataclasses can't do everything Pydantic models can do.
So, you might still need to use Pydantic models.
But if you have a bunch of dataclasses laying around, this is a nice trick to use them to power a web API using FastAPI. 🤓
## Dataclasses in `response_model`
You can also use `dataclasses` in the `response_model` parameter:
```Python hl_lines="1 7-13 19"
{!../../../docs_src/dataclasses/tutorial002.py!}
```
The dataclass will be automatically converted to a Pydantic dataclass.
This way, its schema will show up in the API docs user interface:
<img src="/img/tutorial/dataclasses/image01.png">
## Dataclasses in Nested Data Structures
You can also combine `dataclasses` with other type annotations to make nested data structures.
In some cases, you might still have to use Pydantic's version of `dataclasses`. For example, if you have errors with the automatically generated API documentation.
In that case, you can simply swap the standard `dataclasses` with `pydantic.dataclasses`, which is a drop-in replacement:
```{ .python .annotate hl_lines="1 5 8-11 14-17 23-25 28" }
{!../../../docs_src/dataclasses/tutorial003.py!}
```
1. We still import `field` from standard `dataclasses`.
2. `pydantic.dataclasses` is a drop-in replacement for `dataclasses`.
3. The `Author` dataclass includes a list of `Item` dataclasses.
4. The `Author` dataclass is used as the `response_model` parameter.
5. You can use other standard type annotations with dataclasses as the request body.
In this case, it's a list of `Item` dataclasses.
6. Here we are returning a dictionary that contains `items` which is a list of dataclasses.
FastAPI is still capable of <abbr title="converting the data to a format that can be transmitted">serializing</abbr> the data to JSON.
7. Here the `response_model` is using a type annotation of a list of `Author` dataclasses.
Again, you can combine `dataclasses` with standard type annotations.
8. Notice that this *path operation function* uses regular `def` instead of `async def`.
As always, in FastAPI you can combine `def` and `async def` as needed.
If you need a refresher about when to use which, check out the section _"In a hurry?"_ in the docs about <a href="https://fastapi.tiangolo.com/async/#in-a-hurry" target="_blank" class="internal-link">`async` and `await`</a>.
9. This *path operation function* is not returning dataclasses (although it could), but a list of dictionaries with internal data.
FastAPI will use the `response_model` parameter (that includes dataclasses) to convert the response.
You can combine `dataclasses` with other type annotations in many different combinations to form complex data structures.
Check the in-code annotation tips above to see more specific details.
## Learn More
You can also combine `dataclasses` with other Pydantic models, inherit from them, include them in your own models, etc.
To learn more, check the <a href="https://pydantic-docs.helpmanual.io/usage/dataclasses/" class="external-link" target="_blank">Pydantic docs about dataclasses</a>.
## Version
This is available since FastAPI version `0.67.0`. 🔖

View File

@@ -33,7 +33,7 @@ You should do it after adding all your *path operations*.
## Exclude from OpenAPI
To exclude a *path operation* from the generated OpenAPI schema (and thus, from the automatic documentation systems), use the parameter `include_in_schema` and set it to `False`;
To exclude a *path operation* from the generated OpenAPI schema (and thus, from the automatic documentation systems), use the parameter `include_in_schema` and set it to `False`:
```Python hl_lines="6"
{!../../../docs_src/path_operation_advanced_configuration/tutorial003.py!}
@@ -50,3 +50,121 @@ It won't show up in the documentation, but other tools (such as Sphinx) will be
```Python hl_lines="19-29"
{!../../../docs_src/path_operation_advanced_configuration/tutorial004.py!}
```
## Additional Responses
You probably have seen how to declare the `response_model` and `status_code` for a *path operation*.
That defines the metadata about the main response of a *path operation*.
You can also declare additional responses with their models, status codes, etc.
There's a whole chapter here in the documentation about it, you can read it at [Additional Responses in OpenAPI](./additional-responses.md){.internal-link target=_blank}.
## OpenAPI Extra
When you declare a *path operation* in your application, **FastAPI** automatically generates the relevant metadata about that *path operation* to be included in the OpenAPI schema.
!!! note "Technical details"
In the OpenAPI specification it is called the <a href="https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.3.md#operation-object" class="external-link" target="_blank">Operation Object</a>.
It has all the information about the *path operation* and is used to generate the automatic documentation.
It includes the `tags`, `parameters`, `requestBody`, `responses`, etc.
This *path operation*-specific OpenAPI schema is normally generated automatically by **FastAPI**, but you can also extend it.
!!! tip
This is a low level extension point.
If you only need to declare additonal responses, a more convenient way to do it is with [Additional Responses in OpenAPI](./additional-responses.md){.internal-link target=_blank}.
You can extend the OpenAPI schema for a *path operation* using the parameter `openapi_extra`.
### OpenAPI Extensions
This `openapi_extra` can be helpful, for example, to declare [OpenAPI Extensions](https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.3.md#specificationExtensions):
```Python hl_lines="6"
{!../../../docs_src/path_operation_advanced_configuration/tutorial005.py!}
```
If you open the automatic API docs, your extension will show up at the bottom of the specific *path operation*.
<img src="/img/tutorial/path-operation-advanced-configuration/image01.png">
And if you see the resulting OpenAPI (at `/openapi.json` in your API), you will see your extension as part of the specific *path operation* too:
```JSON hl_lines="22"
{
"openapi": "3.0.2",
"info": {
"title": "FastAPI",
"version": "0.1.0"
},
"paths": {
"/items/": {
"get": {
"summary": "Read Items",
"operationId": "read_items_items__get",
"responses": {
"200": {
"description": "Successful Response",
"content": {
"application/json": {
"schema": {}
}
}
}
},
"x-aperture-labs-portal": "blue"
}
}
}
}
```
### Custom OpenAPI *path operation* schema
The dictionary in `openapi_extra` will be deeply merged with the automatically generated OpenAPI schema for the *path operation*.
So, you could add additional data to the automatically generated schema.
For example, you could decide to read and validate the request with your own code, without using the automatic features of FastAPI with Pydantic, but you could still want to define the request in the OpenAPI schema.
You could do that with `openapi_extra`:
```Python hl_lines="20-37 39-40"
{!../../../docs_src/path_operation_advanced_configuration/tutorial006.py!}
```
In this example, we didn't declare any Pydantic model. In fact, the request body is not even <abbr title="converted from some plain format, like bytes, into Python objects">parsed</abbr> as JSON, it is read directly as `bytes`, and the function `magic_data_reader()` would be in charge of parsing it in some way.
Nevertheless, we can declare the expected schema for the request body.
### Custom OpenAPI content type
Using this same trick, you could use a Pydantic model to define the JSON Schema that is then included in the custom OpenAPI schema section for the *path operation*.
And you could do this even if the data type in the request is not JSON.
For example, in this application we don't use FastAPI's integrated functionality to extract the JSON Schema from Pydantic models nor the automatic validation for JSON. In fact, we are declaring the request content type as YAML, not JSON:
```Python hl_lines="17-22 24"
{!../../../docs_src/path_operation_advanced_configuration/tutorial007.py!}
```
Nevertheless, although we are not using the default integrated functionality, we are still using a Pydantic model to manually generate the JSON Schema for the data that we want to receive in YAML.
Then we use the request directly, and extract the body as `bytes`. This means that FastAPI won't even try to parse the request payload as JSON.
And then in our code, we parse that YAML content directly, and then we are again using the same Pydantic model to validate the YAML content:
```Python hl_lines="26-33"
{!../../../docs_src/path_operation_advanced_configuration/tutorial007.py!}
```
!!! tip
Here we re-use the same Pydantic model.
But the same way, we could have validated it in some other way.

View File

@@ -235,7 +235,7 @@ And then we can require it from the *path operation function* as a dependency an
Then it would be very easy to provide a different settings object during testing by creating a dependency override for `get_settings`:
```Python hl_lines="8-9 12 21"
```Python hl_lines="9-10 13 21"
{!../../../docs_src/settings/app02/test_main.py!}
```
@@ -288,7 +288,7 @@ Reading a file from disk is normally a costly (slow) operation, so you probably
But every time we do:
```Python
config.Settings()
Settings()
```
a new `Settings` object would be created, and at creation it would read the `.env` file again.
@@ -297,7 +297,7 @@ If the dependency function was just like:
```Python
def get_settings():
return config.Settings()
return Settings()
```
we would create that object for each request, and we would be reading the `.env` file for each request. ⚠️

View File

@@ -102,13 +102,15 @@ To see the difference, imagine the following story about burgers:
### Concurrent Burgers
<!-- The gender neutral cook emoji "🧑‍🍳" does not render well in browsers. In the meantime, I'm using a mix of male "👨‍🍳" and female "👩‍🍳" cooks. -->
You go with your crush 😍 to get fast food 🍔, you stand in line while the cashier 💁 takes the orders from the people in front of you.
Then it's your turn, you place your order of 2 very fancy burgers 🍔 for your crush 😍 and you.
You pay 💸.
The cashier 💁 says something to the guy in the kitchen 👨‍🍳 so he knows he has to prepare your burgers 🍔 (even though he is currently preparing the ones for the previous clients).
The cashier 💁 says something to the cook in the kitchen 👨‍🍳 so they know they have to prepare your burgers 🍔 (even though they are currently preparing the ones for the previous clients).
The cashier 💁 gives you the number of your turn.
@@ -146,9 +148,9 @@ Now let's imagine these aren't "Concurrent Burgers", but "Parallel Burgers".
You go with your crush 😍 to get parallel fast food 🍔.
You stand in line while several (let's say 8) cashiers that at the same time are cooks 👨‍🍳👨‍🍳👨‍🍳👨‍🍳👨‍🍳👨‍🍳👨‍🍳👨‍🍳 take the orders from the people in front of you.
You stand in line while several (let's say 8) cashiers that at the same time are cooks 👩‍🍳👨‍🍳👩‍🍳👨‍🍳👩‍🍳👨‍🍳👩‍🍳👨‍🍳 take the orders from the people in front of you.
Everyone before you is waiting 🕙 for their burgers 🍔 to be ready before leaving the counter because each of the 8 cashiers goes himself and prepares the burger right away before getting the next order.
Everyone before you is waiting 🕙 for their burgers 🍔 to be ready before leaving the counter because each of the 8 cashiers goes and prepares the burger right away before getting the next order.
Then it's finally your turn, you place your order of 2 very fancy burgers 🍔 for your crush 😍 and you.
@@ -174,7 +176,7 @@ There was not much talk or flirting as most of the time was spent waiting 🕙 i
In this scenario of the parallel burgers, you are a computer / program 🤖 with two processors (you and your crush 😍), both waiting 🕙 and dedicating their attention ⏯ to be "waiting on the counter" 🕙 for a long time.
The fast food store has 8 processors (cashiers/cooks) 👨‍🍳👨‍🍳👨‍🍳👨‍🍳👨‍🍳👨‍🍳👨‍🍳👨‍🍳. While the concurrent burgers store might have had only 2 (one cashier and one cook) 💁 👨‍🍳.
The fast food store has 8 processors (cashiers/cooks) 👩‍🍳👨‍🍳👩‍🍳👨‍🍳👩‍🍳👨‍🍳👩‍🍳👨‍🍳. While the concurrent burgers store might have had only 2 (one cashier and one cook) 💁 👨‍🍳.
But still, the final experience is not the best 😞.
@@ -236,7 +238,7 @@ You could have turns as in the burgers example, first the living room, then the
It would take the same amount of time to finish with or without turns (concurrency) and you would have done the same amount of work.
But in this case, if you could bring the 8 ex-cashier/cooks/now-cleaners 👨‍🍳👨‍🍳👨‍🍳👨‍🍳👨‍🍳👨‍🍳👨‍🍳👨‍🍳, and each one of them (plus you) could take a zone of the house to clean it, you could do all the work in **parallel**, with the extra help, and finish much sooner.
But in this case, if you could bring the 8 ex-cashier/cooks/now-cleaners 👩‍🍳👨‍🍳👩‍🍳👨‍🍳👩‍🍳👨‍🍳👩‍🍳👨‍🍳, and each one of them (plus you) could take a zone of the house to clean it, you could do all the work in **parallel**, with the extra help, and finish much sooner.
In this scenario, each one of the cleaners (including you) would be a processor, doing their part of the job.

View File

@@ -89,8 +89,17 @@ a.announce-link:hover {
z-index: 10;
}
.announce-wrapper .sponsor-image {
display: block;
border-radius: 20px;
}
.announce-wrapper>div {
min-height: 40px;
display: flex;
align-items: center;
}
.twitter {
color: #00acee;
}

View File

@@ -118,7 +118,7 @@ They are supporting my work with **FastAPI** (and others), mainly through <a hre
{% if sponsors %}
{% for sponsor in sponsors.gold -%}
<a href="{{ sponsor.url }}" target="_blank" title="{{ sponsor.title }}"><img src="{{ sponsor.img }}"></a>
<a href="{{ sponsor.url }}" target="_blank" title="{{ sponsor.title }}"><img src="{{ sponsor.img }}" style="border-radius:15px"></a>
{% endfor %}
{% endif %}
@@ -126,7 +126,7 @@ They are supporting my work with **FastAPI** (and others), mainly through <a hre
{% if sponsors %}
{% for sponsor in sponsors.silver -%}
<a href="{{ sponsor.url }}" target="_blank" title="{{ sponsor.title }}"><img src="{{ sponsor.img }}"></a>
<a href="{{ sponsor.url }}" target="_blank" title="{{ sponsor.title }}"><img src="{{ sponsor.img }}" style="border-radius:15px"></a>
{% endfor %}
{% endif %}
@@ -134,7 +134,7 @@ They are supporting my work with **FastAPI** (and others), mainly through <a hre
{% if sponsors %}
{% for sponsor in sponsors.bronze -%}
<a href="{{ sponsor.url }}" target="_blank" title="{{ sponsor.title }}"><img src="{{ sponsor.img }}"></a>
<a href="{{ sponsor.url }}" target="_blank" title="{{ sponsor.title }}"><img src="{{ sponsor.img }}" style="border-radius:15px"></a>
{% endfor %}
{% endif %}

View File

@@ -20,6 +20,10 @@ You can subscribe to the (infrequent) [**FastAPI and friends** newsletter](/news
* Breaking changes 🚨
* Tips and tricks ✅
## Follow FastAPI on Twitter
<a href="https://twitter.com/fastapi" class="external-link" target="_blank">Follow @fastapi on **Twitter**</a> to get the latest news about **FastAPI**. 🐦
## 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" class="external-link" target="_blank">https://github.com/tiangolo/fastapi</a>. ⭐️
@@ -32,7 +36,7 @@ You can "watch" FastAPI in GitHub (clicking the "watch" button at the top right)
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.
By 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.
## Connect with the author
@@ -46,17 +50,18 @@ You can:
* <a href="https://twitter.com/tiangolo" class="external-link" target="_blank">Follow me on **Twitter**</a>.
* Tell me how you use FastAPI (I love to hear that).
* Hear when I make announcements or release new tools.
* You can also <a href="https://twitter.com/fastapi" class="external-link" target="_blank">follow @fastapi on Twitter</a> (a separate account).
* <a href="https://www.linkedin.com/in/tiangolo/" class="external-link" target="_blank">Connect with me on **Linkedin**</a>.
* Hear when I make announcements or release new tools (although I use Twitter more often 🤷‍♂).
* Read what I write (or follow me) on <a href="https://dev.to/tiangolo" class="external-link" target="_blank">**Dev.to**</a> or <a href="https://medium.com/@tiangolo" class="external-link" target="_blank">**Medium**</a>.
* Read other ideas, articles, and about tools I have created.
* Read other ideas, articles, and read about tools I have created.
* Follow me to read when I publish something new.
## Tweet about **FastAPI**
<a href="https://twitter.com/compose/tweet?text=I'm loving FastAPI because... https://github.com/tiangolo/fastapi cc @tiangolo" class="external-link" target="_blank">Tweet about **FastAPI**</a> and let me and others know why you like it. 🎉
<a href="https://twitter.com/compose/tweet?text=I'm loving @fastapi because... https://github.com/tiangolo/fastapi" class="external-link" target="_blank">Tweet about **FastAPI**</a> and let me and others know why you like it. 🎉
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.
I love to hear about how **FastAPI** is being used, what you have liked in it, in which project/company are you using it, etc.
## Vote for FastAPI
@@ -67,15 +72,15 @@ I love to hear about how **FastAPI** is being used, what have you liked in it, i
You can see <a href="https://github.com/tiangolo/fastapi/issues" class="external-link" target="_blank">existing issues</a> and try and help others, most of the times they are questions that you might already know the answer for. 🤓
If you are helping a lot of people on issues you might become an official [FastAPI Expert](fastapi-people.md#experts){.internal-link target=_blank}. 🎉
If you are helping a lot of people with issues, you might become an official [FastAPI Expert](fastapi-people.md#experts){.internal-link target=_blank}. 🎉
## 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" class="external-link" 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.
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.
Then you can try and help them solve those issues.
## Create issues
@@ -84,7 +89,7 @@ You can <a href="https://github.com/tiangolo/fastapi/issues/new/choose" class="e
* Ask a **question** or ask about a **problem**.
* Suggest a new **feature**.
**Note**: if you create an issue then I'm going to ask you to also help others. 😉
**Note**: if you create an issue, then I'm going to ask you to also help others. 😉
## Create a Pull Request
@@ -92,9 +97,9 @@ You can [contribute](contributing.md){.internal-link target=_blank} to the sourc
* To fix a typo you found on the documentation.
* To share an article, video, or podcast you created or found about FastAPI by <a href="https://github.com/tiangolo/fastapi/edit/master/docs/en/data/external_links.yml" class="external-link" target="_blank">editing this file</a>.
* Make sure you add your link to the end of the corresponding section.
* Make sure you add your link to the start of the corresponding section.
* To help [translate the documentation](contributing.md#translations){.internal-link target=_blank} to your language.
* You can also help reviewing the translations created by others.
* You can also help to review the translations created by others.
* To propose new documentation sections.
* To fix an existing issue/bug.
* To add a new feature.

View File

@@ -0,0 +1,293 @@
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<svg
xmlns:dc="http://purl.org/dc/elements/1.1/"
xmlns:cc="http://creativecommons.org/ns#"
xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"
xmlns:svg="http://www.w3.org/2000/svg"
xmlns="http://www.w3.org/2000/svg"
xmlns:sodipodi="http://sodipodi.sourceforge.net/DTD/sodipodi-0.dtd"
xmlns:inkscape="http://www.inkscape.org/namespaces/inkscape"
width="429.96896"
height="40"
viewBox="0 0 113.76262 10.583333"
version="1.1"
id="svg853"
inkscape:version="1.0.2 (1.0.2+r75+1)"
sodipodi:docname="fastapi-course-bundle-banner.svg">
<defs
id="defs847" />
<sodipodi:namedview
id="base"
pagecolor="#ffffff"
bordercolor="#666666"
borderopacity="1.0"
inkscape:pageopacity="0.0"
inkscape:pageshadow="2"
inkscape:zoom="2.8"
inkscape:cx="222.91167"
inkscape:cy="33.521565"
inkscape:document-units="mm"
inkscape:current-layer="g3355"
inkscape:document-rotation="0"
showgrid="false"
inkscape:snap-object-midpoints="true"
inkscape:snap-center="true"
inkscape:snap-page="true"
inkscape:window-width="1920"
inkscape:window-height="1025"
inkscape:window-x="0"
inkscape:window-y="27"
inkscape:window-maximized="1"
units="px" />
<metadata
id="metadata850">
<rdf:RDF>
<cc:Work
rdf:about="">
<dc:format>image/svg+xml</dc:format>
<dc:type
rdf:resource="http://purl.org/dc/dcmitype/StillImage" />
<dc:title></dc:title>
</cc:Work>
</rdf:RDF>
</metadata>
<g
inkscape:label="Layer 1"
inkscape:groupmode="layer"
id="layer1"
transform="translate(-80.634914,-82.650791)">
<g
id="g3355"
transform="matrix(1.4999999,0,0,1.4999999,-40.317455,-41.325393)">
<rect
style="fill:#ffffff;stroke-width:0.197707;stop-color:#000000"
id="rect1784"
width="75.841751"
height="7.0555558"
x="80.634918"
y="82.650795" />
<g
aria-label="FastAPI Course Bundle. Get 3 in-depth courses. Save 10%!"
transform="scale(1.0561291,0.94685395)"
id="text871"
style="font-size:2.43444px;line-height:1.25;font-family:Ubuntu;-inkscape-font-specification:Ubuntu;letter-spacing:0px;word-spacing:0px;stroke-width:0.0608608">
<path
d="m 84.413426,90.970748 h -0.72629 v 0.764329 h -0.228229 v -1.730735 h 1.0722 v 0.187814 h -0.843971 v 0.591968 h 0.72629 z"
style="font-style:normal;font-variant:normal;font-weight:normal;font-stretch:normal;font-family:Roboto;-inkscape-font-specification:Roboto;stroke-width:0.0608608"
id="path3922" />
<path
d="m 85.526042,91.735077 q -0.01902,-0.03804 -0.03091,-0.135511 -0.153342,0.159285 -0.366117,0.159285 -0.190191,0 -0.312626,-0.106982 -0.121247,-0.108171 -0.121247,-0.2734 0,-0.200888 0.152153,-0.311437 0.153341,-0.111737 0.430306,-0.111737 h 0.213965 v -0.101038 q 0,-0.115303 -0.06894,-0.183059 -0.06894,-0.06894 -0.203266,-0.06894 -0.11768,0 -0.197323,0.05943 -0.07964,0.05943 -0.07964,0.143831 h -0.221096 q 0,-0.09628 0.06775,-0.185436 0.06894,-0.09034 0.185436,-0.142643 0.11768,-0.0523 0.257946,-0.0523 0.222285,0 0.348286,0.111737 0.126002,0.110548 0.130756,0.305494 v 0.591968 q 0,0.177115 0.04517,0.28172 v 0.01902 z m -0.364929,-0.167606 q 0.103416,0 0.196134,-0.05349 0.09272,-0.05349 0.134323,-0.139077 v -0.263889 h -0.172361 q -0.404155,0 -0.404155,0.23655 0,0.103416 0.06894,0.161662 0.06894,0.05824 0.177115,0.05824 z"
style="font-style:normal;font-variant:normal;font-weight:normal;font-stretch:normal;font-family:Roboto;-inkscape-font-specification:Roboto;stroke-width:0.0608608"
id="path3924" />
<path
d="m 86.807451,91.393922 q 0,-0.08915 -0.06776,-0.137888 -0.06657,-0.04993 -0.234172,-0.08558 -0.166417,-0.03566 -0.265078,-0.08559 -0.09747,-0.04993 -0.14502,-0.118869 -0.04636,-0.06894 -0.04636,-0.16404 0,-0.158096 0.133133,-0.267455 0.134322,-0.10936 0.342343,-0.10936 0.21872,0 0.35423,0.112926 0.1367,0.112925 0.1367,0.288852 h -0.221097 q 0,-0.09034 -0.07726,-0.155719 -0.07608,-0.06538 -0.192568,-0.06538 -0.120058,0 -0.187813,0.0523 -0.06776,0.0523 -0.06776,0.136699 0,0.07964 0.063,0.120058 0.063,0.04042 0.22704,0.07726 0.165228,0.03685 0.267456,0.08796 0.102227,0.05111 0.150964,0.123624 0.04993,0.07132 0.04993,0.174737 0,0.172361 -0.137888,0.276966 -0.137889,0.103416 -0.357797,0.103416 -0.154529,0 -0.273399,-0.05468 -0.118869,-0.05468 -0.186624,-0.152153 -0.06657,-0.09866 -0.06657,-0.212775 h 0.219908 q 0.0059,0.110548 0.08796,0.175926 0.08321,0.06419 0.218719,0.06419 0.124813,0 0.199701,-0.04993 0.07608,-0.05111 0.07608,-0.135511 z"
style="font-style:normal;font-variant:normal;font-weight:normal;font-stretch:normal;font-family:Roboto;-inkscape-font-specification:Roboto;stroke-width:0.0608608"
id="path3926" />
<path
d="m 87.612195,90.137476 v 0.311437 h 0.240116 v 0.169983 h -0.240116 v 0.797612 q 0,0.07727 0.03209,0.116491 0.03209,0.03804 0.109359,0.03804 0.03804,0 0.104605,-0.01426 v 0.178304 q -0.08677,0.02377 -0.168794,0.02377 -0.147398,0 -0.222285,-0.08915 -0.07489,-0.08915 -0.07489,-0.253191 v -0.797612 h -0.234172 v -0.169983 h 0.234172 v -0.311437 z"
style="font-style:normal;font-variant:normal;font-weight:normal;font-stretch:normal;font-family:Roboto;-inkscape-font-specification:Roboto;stroke-width:0.0608608"
id="path3928" />
<path
d="m 89.098059,91.283374 h -0.725102 l -0.16285,0.451703 h -0.235361 l 0.660912,-1.730735 h 0.1997 l 0.662102,1.730735 h -0.234173 z m -0.656157,-0.187813 h 0.588402 l -0.294796,-0.809499 z"
style="font-style:normal;font-variant:normal;font-weight:normal;font-stretch:normal;font-family:Roboto;-inkscape-font-specification:Roboto;stroke-width:0.0608608"
id="path3930" />
<path
d="m 89.958671,91.057523 v 0.677554 h -0.228228 v -1.730735 h 0.638327 q 0.284097,0 0.444571,0.145021 0.161662,0.14502 0.161662,0.383947 0,0.252003 -0.158096,0.388702 -0.156908,0.135511 -0.450514,0.135511 z m 0,-0.186625 h 0.410099 q 0.183058,0 0.280531,-0.08558 0.09747,-0.08678 0.09747,-0.249626 0,-0.15453 -0.09747,-0.247247 -0.09747,-0.09272 -0.267455,-0.09628 h -0.423175 z"
style="font-style:normal;font-variant:normal;font-weight:normal;font-stretch:normal;font-family:Roboto;-inkscape-font-specification:Roboto;stroke-width:0.0608608"
id="path3932" />
<path
d="m 91.511103,91.735077 h -0.228229 v -1.730735 h 0.228229 z"
style="font-style:normal;font-variant:normal;font-weight:normal;font-stretch:normal;font-family:Roboto;-inkscape-font-specification:Roboto;stroke-width:0.0608608"
id="path3934" />
<path
d="m 93.843315,91.158562 q -0.02021,0.279342 -0.206833,0.439815 -0.185436,0.160474 -0.48974,0.160474 -0.332834,0 -0.524213,-0.223474 -0.190191,-0.224663 -0.190191,-0.615742 v -0.105794 q 0,-0.249625 0.08796,-0.439816 0.08796,-0.19019 0.250814,-0.291229 0.164039,-0.102228 0.380381,-0.102228 0.29955,0 0.482609,0.160474 0.183058,0.160473 0.211587,0.450514 h -0.356607 q -0.01308,-0.167606 -0.09391,-0.242493 -0.07964,-0.07608 -0.243682,-0.07608 -0.178303,0 -0.267455,0.128378 -0.08796,0.12719 -0.09034,0.395834 v 0.130756 q 0,0.280532 0.0844,0.410099 0.08559,0.129567 0.268645,0.129567 0.165228,0 0.246059,-0.07489 0.08202,-0.07608 0.09391,-0.234172 z"
style="font-weight:bold"
id="path3936" />
<path
d="m 94.001411,91.080108 q 0,-0.191379 0.0737,-0.341154 0.0737,-0.149776 0.211587,-0.231795 0.139077,-0.08202 0.322135,-0.08202 0.260324,0 0.424363,0.159285 0.165228,0.159284 0.184247,0.432683 l 0.0024,0.08796 q 0,0.295985 -0.165228,0.475477 -0.165229,0.178304 -0.443382,0.178304 -0.278154,0 -0.444571,-0.178304 -0.165228,-0.178304 -0.165228,-0.484986 z m 0.343532,0.02496 q 0,0.183059 0.06894,0.280532 0.06894,0.09628 0.197323,0.09628 0.124812,0 0.194945,-0.0951 0.07013,-0.09628 0.07013,-0.306682 0,-0.179492 -0.07013,-0.278154 -0.07013,-0.09866 -0.197323,-0.09866 -0.126001,0 -0.194945,0.09866 -0.06894,0.09747 -0.06894,0.303116 z"
style="font-weight:bold"
id="path3938" />
<path
d="m 96.204056,91.604321 q -0.12719,0.15453 -0.351853,0.15453 -0.206832,0 -0.316192,-0.118869 -0.108171,-0.11887 -0.110548,-0.348287 v -0.842782 h 0.343532 v 0.830895 q 0,0.200889 0.183058,0.200889 0.174738,0 0.240116,-0.121247 v -0.910537 h 0.34472 v 1.286164 h -0.323324 z"
style="font-weight:bold"
id="path3940" />
<path
d="m 97.521126,90.771048 q -0.07013,-0.0095 -0.123624,-0.0095 -0.194945,0 -0.255568,0.131944 v 0.841594 h -0.343532 v -1.286164 h 0.324513 l 0.0095,0.153341 q 0.103416,-0.177115 0.286475,-0.177115 0.05706,0 0.106982,0.01545 z"
style="font-weight:bold"
id="path3942" />
<path
d="m 98.384116,91.379658 q 0,-0.063 -0.063,-0.09866 -0.06181,-0.03685 -0.1997,-0.06538 -0.458835,-0.09628 -0.458835,-0.389891 0,-0.171172 0.141455,-0.285286 0.142643,-0.115303 0.37206,-0.115303 0.244871,0 0.39108,0.115303 0.147397,0.115303 0.147397,0.29955 h -0.343531 q 0,-0.0737 -0.04755,-0.121246 -0.04755,-0.04874 -0.148587,-0.04874 -0.08677,0 -0.134322,0.03923 -0.04755,0.03923 -0.04755,0.09985 0,0.05706 0.05349,0.09272 0.05468,0.03447 0.183058,0.06062 0.128379,0.02496 0.216342,0.05706 0.27221,0.09985 0.27221,0.345909 0,0.175926 -0.150963,0.285286 -0.150964,0.108171 -0.389891,0.108171 -0.161662,0 -0.287663,-0.05706 -0.124813,-0.05825 -0.196135,-0.158096 -0.07132,-0.101039 -0.07132,-0.217531 h 0.325701 q 0.0048,0.09153 0.06776,0.140266 0.063,0.04874 0.168794,0.04874 0.09866,0 0.148586,-0.03685 0.05111,-0.03804 0.05111,-0.09866 z"
style="font-weight:bold"
id="path3944" />
<path
d="m 99.530014,91.758851 q -0.282909,0 -0.461212,-0.173549 -0.177115,-0.173549 -0.177115,-0.462401 v -0.03328 q 0,-0.193756 0.07489,-0.345909 0.07489,-0.153341 0.211587,-0.235361 0.137888,-0.08321 0.313815,-0.08321 0.263889,0 0.414853,0.166417 0.152151,0.166417 0.152151,0.47191 v 0.140266 h -0.819007 q 0.01664,0.126001 0.09985,0.202077 0.0844,0.07608 0.212776,0.07608 0.198511,0 0.310248,-0.143832 l 0.168793,0.189002 q -0.07726,0.10936 -0.209208,0.171171 -0.131945,0.06062 -0.292418,0.06062 z m -0.03923,-1.055558 q -0.102227,0 -0.166417,0.06894 -0.063,0.06894 -0.08083,0.197323 h 0.477854 v -0.02734 q -0.0024,-0.114115 -0.06181,-0.175927 -0.05943,-0.063 -0.168794,-0.063 z"
style="font-weight:bold"
id="path3946" />
<path
d="m 100.88631,91.735077 v -1.730735 h 0.60623 q 0.31501,0 0.47786,0.121247 0.16285,0.120058 0.16285,0.353041 0,0.12719 -0.0654,0.224663 -0.0654,0.09628 -0.18187,0.141454 0.13313,0.03328 0.20921,0.134322 0.0773,0.101039 0.0773,0.247248 0,0.249625 -0.15928,0.378004 -0.15928,0.128379 -0.45408,0.130756 z m 0.35661,-0.75363 v 0.467155 h 0.30549 q 0.126,0 0.19614,-0.05943 0.0713,-0.06062 0.0713,-0.166417 0,-0.237738 -0.24606,-0.241304 z m 0,-0.252003 h 0.26389 q 0.26983,-0.0048 0.26983,-0.215153 0,-0.117681 -0.0689,-0.168794 -0.0678,-0.0523 -0.21516,-0.0523 h -0.24962 z"
style="font-weight:bold"
id="path3948" />
<path
d="m 103.18881,91.604321 q -0.12719,0.15453 -0.35186,0.15453 -0.20683,0 -0.31619,-0.118869 -0.10817,-0.11887 -0.11055,-0.348287 v -0.842782 h 0.34353 v 0.830895 q 0,0.200889 0.18306,0.200889 0.17474,0 0.24012,-0.121247 v -0.910537 h 0.34472 v 1.286164 h -0.32333 z"
style="font-weight:bold"
id="path3950" />
<path
d="m 104.09934,90.448913 0.0107,0.148586 q 0.13789,-0.17236 0.36968,-0.17236 0.20446,0 0.30431,0.120058 0.0999,0.120058 0.10223,0.358985 v 0.830895 h -0.34353 v -0.822575 q 0,-0.109359 -0.0476,-0.158095 -0.0476,-0.04993 -0.1581,-0.04993 -0.14502,0 -0.21753,0.123624 v 0.906972 h -0.34353 v -1.286164 z"
style="font-weight:bold"
id="path3952" />
<path
d="m 105.09428,91.082485 q 0,-0.300739 0.13432,-0.479042 0.13551,-0.178304 0.36968,-0.178304 0.18782,0 0.31025,0.140266 v -0.656158 h 0.34472 v 1.82583 H 105.943 l -0.0166,-0.1367 q -0.12838,0.160474 -0.33045,0.160474 -0.22704,0 -0.36493,-0.178304 -0.1367,-0.179492 -0.1367,-0.498062 z m 0.34353,0.02496 q 0,0.180681 0.063,0.276965 0.063,0.09628 0.18306,0.09628 0.15928,0 0.22466,-0.134322 v -0.507571 q -0.0642,-0.134323 -0.22228,-0.134323 -0.24844,0 -0.24844,0.402967 z"
style="font-weight:bold"
id="path3954" />
<path
d="m 106.88445,91.735077 h -0.34472 v -1.82583 h 0.34472 z"
style="font-weight:bold"
id="path3956" />
<path
d="m 107.76051,91.758851 q -0.28291,0 -0.46121,-0.173549 -0.17711,-0.173549 -0.17711,-0.462401 v -0.03328 q 0,-0.193756 0.0749,-0.345909 0.0749,-0.153341 0.21159,-0.235361 0.13789,-0.08321 0.31382,-0.08321 0.26388,0 0.41485,0.166417 0.15215,0.166417 0.15215,0.47191 v 0.140266 h -0.81901 q 0.0166,0.126001 0.0998,0.202077 0.0844,0.07608 0.21278,0.07608 0.19851,0 0.31025,-0.143832 l 0.16879,0.189002 q -0.0773,0.10936 -0.20921,0.171171 -0.13194,0.06062 -0.29242,0.06062 z m -0.0392,-1.055558 q -0.10223,0 -0.16642,0.06894 -0.063,0.06894 -0.0808,0.197323 h 0.47785 v -0.02734 q -0.002,-0.114115 -0.0618,-0.175927 -0.0594,-0.063 -0.16879,-0.063 z"
style="font-weight:bold"
id="path3958" />
<path
d="m 108.52484,91.619774 q 0,-0.05706 0.0333,-0.0951 0.0345,-0.03804 0.10222,-0.03804 0.0678,0 0.10223,0.03804 0.0357,0.03804 0.0357,0.0951 0,0.05468 -0.0357,0.09153 -0.0345,0.03685 -0.10223,0.03685 -0.0677,0 -0.10222,-0.03685 -0.0333,-0.03685 -0.0333,-0.09153 z"
style="font-style:normal;font-variant:normal;font-weight:normal;font-stretch:normal;font-family:Roboto;-inkscape-font-specification:Roboto;stroke-width:0.0608608"
id="path3960" />
<path
d="m 111.07815,91.508037 q -0.088,0.126001 -0.24606,0.189002 -0.15691,0.06181 -0.36612,0.06181 -0.21158,0 -0.37562,-0.09866 -0.16404,-0.09985 -0.25438,-0.282908 -0.0892,-0.183059 -0.0915,-0.424363 v -0.150964 q 0,-0.391079 0.18187,-0.606232 0.18306,-0.215154 0.51351,-0.215154 0.27103,0 0.43625,0.139077 0.16523,0.137889 0.20208,0.392268 h -0.22823 q -0.0642,-0.343531 -0.40891,-0.343531 -0.22942,0 -0.34828,0.161662 -0.11768,0.160473 -0.11887,0.465967 v 0.141454 q 0,0.291229 0.13313,0.46359 0.13313,0.171171 0.36017,0.171171 0.12838,0 0.22467,-0.02853 0.0963,-0.02853 0.15928,-0.09628 v -0.388702 h -0.40059 v -0.185436 h 0.62763 z"
style="font-style:normal;font-variant:normal;font-weight:normal;font-stretch:normal;font-family:Roboto;-inkscape-font-specification:Roboto;stroke-width:0.0608608"
id="path3962" />
<path
d="m 111.95897,91.758851 q -0.26151,0 -0.42555,-0.171172 -0.16404,-0.17236 -0.16404,-0.460023 v -0.04042 q 0,-0.191379 0.0725,-0.341154 0.0737,-0.150964 0.20445,-0.235361 0.13195,-0.08559 0.28529,-0.08559 0.25081,0 0.38989,0.165228 0.13908,0.165228 0.13908,0.473099 v 0.09153 h -0.87131 q 0.005,0.19019 0.11055,0.307871 0.10698,0.116491 0.27102,0.116491 0.11649,0 0.19732,-0.04755 0.0808,-0.04755 0.14145,-0.126002 l 0.13433,0.104605 q -0.16167,0.248437 -0.48499,0.248437 z m -0.0273,-1.153031 q -0.13313,0 -0.22347,0.09747 -0.0903,0.09628 -0.11174,0.271021 h 0.64427 v -0.01664 q -0.01,-0.167606 -0.0903,-0.259135 -0.0808,-0.09272 -0.21872,-0.09272 z"
style="font-style:normal;font-variant:normal;font-weight:normal;font-stretch:normal;font-family:Roboto;-inkscape-font-specification:Roboto;stroke-width:0.0608608"
id="path3964" />
<path
d="m 113.01215,90.137476 v 0.311437 h 0.24012 v 0.169983 h -0.24012 v 0.797612 q 0,0.07727 0.0321,0.116491 0.0321,0.03804 0.10936,0.03804 0.038,0 0.1046,-0.01426 v 0.178304 q -0.0868,0.02377 -0.16879,0.02377 -0.1474,0 -0.22229,-0.08915 -0.0749,-0.08915 -0.0749,-0.253191 v -0.797612 h -0.23417 v -0.169983 h 0.23417 v -0.311437 z"
style="font-style:normal;font-variant:normal;font-weight:normal;font-stretch:normal;font-family:Roboto;-inkscape-font-specification:Roboto;stroke-width:0.0608608"
id="path3966" />
<path
d="m 114.40886,90.762727 h 0.16523 q 0.15572,-0.0024 0.24487,-0.08202 0.0891,-0.07964 0.0891,-0.215153 0,-0.304305 -0.30311,-0.304305 -0.14264,0 -0.22823,0.08202 -0.0844,0.08083 -0.0844,0.215153 h -0.21991 q 0,-0.205643 0.14978,-0.341154 0.15096,-0.1367 0.38276,-0.1367 0.24487,0 0.38395,0.129568 0.13907,0.129567 0.13907,0.360173 0,0.112926 -0.0737,0.21872 -0.0725,0.105793 -0.19851,0.158095 0.14264,0.04517 0.21991,0.149776 0.0784,0.104604 0.0784,0.255568 0,0.232984 -0.15215,0.369683 -0.15215,0.1367 -0.39583,0.1367 -0.24368,0 -0.39703,-0.131945 -0.15215,-0.131945 -0.15215,-0.348287 h 0.2211 q 0,0.1367 0.0892,0.21872 0.0892,0.08202 0.23893,0.08202 0.15928,0 0.24368,-0.08321 0.0844,-0.08321 0.0844,-0.238927 0,-0.150964 -0.0927,-0.231795 -0.0927,-0.08083 -0.26746,-0.08321 h -0.16523 z"
style="font-style:normal;font-variant:normal;font-weight:normal;font-stretch:normal;font-family:Roboto;-inkscape-font-specification:Roboto;stroke-width:0.0608608"
id="path3968" />
<path
d="m 116.32385,91.735077 h -0.21991 v -1.286164 h 0.21991 z m -0.23774,-1.627319 q 0,-0.05349 0.0321,-0.09034 0.0333,-0.03685 0.0975,-0.03685 0.0642,0 0.0975,0.03685 0.0333,0.03685 0.0333,0.09034 0,0.05349 -0.0333,0.08915 -0.0333,0.03566 -0.0975,0.03566 -0.0642,0 -0.0975,-0.03566 -0.0321,-0.03566 -0.0321,-0.08915 z"
style="font-style:normal;font-variant:normal;font-weight:normal;font-stretch:normal;font-family:Roboto;-inkscape-font-specification:Roboto;stroke-width:0.0608608"
id="path3970" />
<path
d="m 116.88253,90.448913 0.007,0.161662 q 0.1474,-0.185436 0.38514,-0.185436 0.40772,0 0.41129,0.460024 v 0.849914 h -0.21991 v -0.851103 q -0.001,-0.139077 -0.0642,-0.205644 -0.0618,-0.06657 -0.19376,-0.06657 -0.10698,0 -0.18781,0.05706 -0.0808,0.05706 -0.126,0.149775 v 0.916481 h -0.21991 v -1.286164 z"
style="font-style:normal;font-variant:normal;font-weight:normal;font-stretch:normal;font-family:Roboto;-inkscape-font-specification:Roboto;stroke-width:0.0608608"
id="path3972" />
<path
d="m 118.47775,91.089617 h -0.58008 v -0.179492 h 0.58008 z"
style="font-style:normal;font-variant:normal;font-weight:normal;font-stretch:normal;font-family:Roboto;-inkscape-font-specification:Roboto;stroke-width:0.0608608"
id="path3974" />
<path
d="m 118.63704,91.081297 q 0,-0.295984 0.14026,-0.475477 0.14027,-0.180681 0.36731,-0.180681 0.22585,0 0.3578,0.15453 v -0.670422 h 0.2199 v 1.82583 h -0.20207 l -0.0107,-0.137888 q -0.13195,0.161662 -0.36731,0.161662 -0.22347,0 -0.36493,-0.183059 -0.14026,-0.183058 -0.14026,-0.477854 z m 0.21991,0.02496 q 0,0.218719 0.0903,0.342343 0.0903,0.123624 0.24962,0.123624 0.20921,0 0.3055,-0.187813 v -0.59078 q -0.0987,-0.181869 -0.30312,-0.181869 -0.16166,0 -0.252,0.124812 -0.0903,0.124813 -0.0903,0.369683 z"
style="font-style:normal;font-variant:normal;font-weight:normal;font-stretch:normal;font-family:Roboto;-inkscape-font-specification:Roboto;stroke-width:0.0608608"
id="path3976" />
<path
d="m 120.59838,91.758851 q -0.26151,0 -0.42555,-0.171172 -0.16404,-0.17236 -0.16404,-0.460023 v -0.04042 q 0,-0.191379 0.0725,-0.341154 0.0737,-0.150964 0.20445,-0.235361 0.13195,-0.08559 0.28529,-0.08559 0.25081,0 0.38989,0.165228 0.13908,0.165228 0.13908,0.473099 v 0.09153 h -0.87131 q 0.005,0.19019 0.11054,0.307871 0.10699,0.116491 0.27103,0.116491 0.11649,0 0.19732,-0.04755 0.0808,-0.04755 0.14145,-0.126002 l 0.13432,0.104605 q -0.16166,0.248437 -0.48498,0.248437 z m -0.0273,-1.153031 q -0.13313,0 -0.22348,0.09747 -0.0903,0.09628 -0.11173,0.271021 h 0.64427 v -0.01664 q -0.01,-0.167606 -0.0903,-0.259135 -0.0808,-0.09272 -0.21872,-0.09272 z"
style="font-style:normal;font-variant:normal;font-weight:normal;font-stretch:normal;font-family:Roboto;-inkscape-font-specification:Roboto;stroke-width:0.0608608"
id="path3978" />
<path
d="m 122.43966,91.106259 q 0,0.293607 -0.13432,0.473099 -0.13432,0.179493 -0.36374,0.179493 -0.23417,0 -0.36849,-0.148587 v 0.619309 h -0.21991 v -1.78066 h 0.20089 l 0.0107,0.142643 q 0.13432,-0.166417 0.37325,-0.166417 0.23179,0 0.36611,0.174738 0.13551,0.174737 0.13551,0.486174 z m -0.2199,-0.02496 q 0,-0.217531 -0.0927,-0.343532 -0.0927,-0.126001 -0.25438,-0.126001 -0.1997,0 -0.29955,0.177115 v 0.614553 q 0.0987,0.175926 0.30193,0.175926 0.15809,0 0.25081,-0.124812 0.0939,-0.126002 0.0939,-0.373249 z"
style="font-style:normal;font-variant:normal;font-weight:normal;font-stretch:normal;font-family:Roboto;-inkscape-font-specification:Roboto;stroke-width:0.0608608"
id="path3980" />
<path
d="m 123.01618,90.137476 v 0.311437 h 0.24011 v 0.169983 h -0.24011 v 0.797612 q 0,0.07727 0.0321,0.116491 0.0321,0.03804 0.10936,0.03804 0.038,0 0.10461,-0.01426 v 0.178304 q -0.0868,0.02377 -0.1688,0.02377 -0.1474,0 -0.22228,-0.08915 -0.0749,-0.08915 -0.0749,-0.253191 v -0.797612 h -0.23417 v -0.169983 h 0.23417 v -0.311437 z"
style="font-style:normal;font-variant:normal;font-weight:normal;font-stretch:normal;font-family:Roboto;-inkscape-font-specification:Roboto;stroke-width:0.0608608"
id="path3982" />
<path
d="m 123.73177,90.604631 q 0.14621,-0.179492 0.38038,-0.179492 0.40772,0 0.41129,0.460024 v 0.849914 h -0.21991 v -0.851103 q -0.001,-0.139077 -0.0642,-0.205644 -0.0618,-0.06657 -0.19376,-0.06657 -0.10698,0 -0.18781,0.05706 -0.0808,0.05706 -0.126,0.149775 v 0.916481 h -0.21991 v -1.82583 h 0.21991 z"
style="font-style:normal;font-variant:normal;font-weight:normal;font-stretch:normal;font-family:Roboto;-inkscape-font-specification:Roboto;stroke-width:0.0608608"
id="path3984" />
<path
d="m 125.97245,91.579358 q 0.11769,0 0.20565,-0.07132 0.088,-0.07132 0.0975,-0.178304 h 0.20802 q -0.006,0.110548 -0.0761,0.210399 -0.0701,0.09985 -0.18782,0.159284 -0.11649,0.05944 -0.24725,0.05944 -0.2627,0 -0.41841,-0.174738 -0.15453,-0.175926 -0.15453,-0.480231 v -0.03685 q 0,-0.187813 0.0689,-0.334022 0.0689,-0.146209 0.19732,-0.22704 0.12957,-0.08083 0.3055,-0.08083 0.21634,0 0.35898,0.129567 0.14383,0.129568 0.15334,0.3364 h -0.20802 q -0.01,-0.124813 -0.0951,-0.204455 -0.0844,-0.08083 -0.20921,-0.08083 -0.16761,0 -0.26033,0.121247 -0.0915,0.120057 -0.0915,0.348286 v 0.0416 q 0,0.222286 0.0915,0.342344 0.0915,0.120057 0.26151,0.120057 z"
style="font-style:normal;font-variant:normal;font-weight:normal;font-stretch:normal;font-family:Roboto;-inkscape-font-specification:Roboto;stroke-width:0.0608608"
id="path3986" />
<path
d="m 126.67259,91.080108 q 0,-0.189002 0.0737,-0.339966 0.0749,-0.150964 0.20683,-0.232983 0.13314,-0.08202 0.30312,-0.08202 0.2627,0 0.42436,0.18187 0.16285,0.18187 0.16285,0.483797 v 0.01545 q 0,0.187813 -0.0725,0.337589 -0.0713,0.148586 -0.20564,0.231794 -0.13313,0.08321 -0.30668,0.08321 -0.26151,0 -0.42436,-0.18187 -0.16167,-0.18187 -0.16167,-0.48142 z m 0.2211,0.02615 q 0,0.213965 0.0987,0.343532 0.0999,0.129567 0.26627,0.129567 0.1676,0 0.26627,-0.130756 0.0987,-0.131944 0.0987,-0.368494 0,-0.211587 -0.10104,-0.342343 -0.0999,-0.131945 -0.26627,-0.131945 -0.16285,0 -0.2627,0.129567 -0.0998,0.129568 -0.0998,0.370872 z"
style="font-style:normal;font-variant:normal;font-weight:normal;font-stretch:normal;font-family:Roboto;-inkscape-font-specification:Roboto;stroke-width:0.0608608"
id="path3988" />
<path
d="m 128.91327,91.607887 q -0.12837,0.150964 -0.37681,0.150964 -0.20564,0 -0.31381,-0.118869 -0.10699,-0.120058 -0.10818,-0.35423 v -0.836839 h 0.21991 v 0.830895 q 0,0.292418 0.23774,0.292418 0.252,0 0.33521,-0.187813 v -0.9355 h 0.21991 v 1.286164 h -0.20921 z"
style="font-style:normal;font-variant:normal;font-weight:normal;font-stretch:normal;font-family:Roboto;-inkscape-font-specification:Roboto;stroke-width:0.0608608"
id="path3990" />
<path
d="m 130.08176,90.646236 q -0.0499,-0.0083 -0.10817,-0.0083 -0.21634,0 -0.29361,0.184247 v 0.912915 h -0.21991 v -1.286164 h 0.21397 l 0.004,0.148586 q 0.10817,-0.17236 0.30669,-0.17236 0.0642,0 0.0975,0.01664 z"
style="font-style:normal;font-variant:normal;font-weight:normal;font-stretch:normal;font-family:Roboto;-inkscape-font-specification:Roboto;stroke-width:0.0608608"
id="path3992" />
<path
d="m 131.03152,91.393922 q 0,-0.08915 -0.0677,-0.137888 -0.0666,-0.04993 -0.23418,-0.08558 -0.16641,-0.03566 -0.26507,-0.08559 -0.0975,-0.04993 -0.14502,-0.118869 -0.0464,-0.06894 -0.0464,-0.16404 0,-0.158096 0.13313,-0.267455 0.13432,-0.10936 0.34234,-0.10936 0.21872,0 0.35423,0.112926 0.1367,0.112925 0.1367,0.288852 h -0.22109 q 0,-0.09034 -0.0773,-0.155719 -0.0761,-0.06538 -0.19257,-0.06538 -0.12005,0 -0.18781,0.0523 -0.0677,0.0523 -0.0677,0.136699 0,0.07964 0.063,0.120058 0.063,0.04042 0.22704,0.07726 0.16522,0.03685 0.26745,0.08796 0.10223,0.05111 0.15097,0.123624 0.0499,0.07132 0.0499,0.174737 0,0.172361 -0.13789,0.276966 -0.13789,0.103416 -0.35779,0.103416 -0.15453,0 -0.2734,-0.05468 -0.11887,-0.05468 -0.18663,-0.152153 -0.0666,-0.09866 -0.0666,-0.212775 h 0.2199 q 0.006,0.110548 0.088,0.175926 0.0832,0.06419 0.21872,0.06419 0.12481,0 0.1997,-0.04993 0.0761,-0.05111 0.0761,-0.135511 z"
style="font-style:normal;font-variant:normal;font-weight:normal;font-stretch:normal;font-family:Roboto;-inkscape-font-specification:Roboto;stroke-width:0.0608608"
id="path3994" />
<path
d="m 132.07163,91.758851 q -0.26151,0 -0.42555,-0.171172 -0.16404,-0.17236 -0.16404,-0.460023 v -0.04042 q 0,-0.191379 0.0725,-0.341154 0.0737,-0.150964 0.20445,-0.235361 0.13195,-0.08559 0.28529,-0.08559 0.25081,0 0.38989,0.165228 0.13908,0.165228 0.13908,0.473099 v 0.09153 h -0.87131 q 0.005,0.19019 0.11054,0.307871 0.10699,0.116491 0.27103,0.116491 0.11649,0 0.19732,-0.04755 0.0808,-0.04755 0.14145,-0.126002 l 0.13433,0.104605 q -0.16167,0.248437 -0.48499,0.248437 z m -0.0273,-1.153031 q -0.13313,0 -0.22347,0.09747 -0.0903,0.09628 -0.11174,0.271021 h 0.64427 v -0.01664 q -0.01,-0.167606 -0.0903,-0.259135 -0.0808,-0.09272 -0.21872,-0.09272 z"
style="font-style:normal;font-variant:normal;font-weight:normal;font-stretch:normal;font-family:Roboto;-inkscape-font-specification:Roboto;stroke-width:0.0608608"
id="path3996" />
<path
d="m 133.57532,91.393922 q 0,-0.08915 -0.0678,-0.137888 -0.0666,-0.04993 -0.23417,-0.08558 -0.16642,-0.03566 -0.26508,-0.08559 -0.0975,-0.04993 -0.14502,-0.118869 -0.0464,-0.06894 -0.0464,-0.16404 0,-0.158096 0.13313,-0.267455 0.13432,-0.10936 0.34234,-0.10936 0.21872,0 0.35423,0.112926 0.1367,0.112925 0.1367,0.288852 h -0.22109 q 0,-0.09034 -0.0773,-0.155719 -0.0761,-0.06538 -0.19257,-0.06538 -0.12005,0 -0.18781,0.0523 -0.0678,0.0523 -0.0678,0.136699 0,0.07964 0.063,0.120058 0.063,0.04042 0.22704,0.07726 0.16522,0.03685 0.26745,0.08796 0.10223,0.05111 0.15097,0.123624 0.0499,0.07132 0.0499,0.174737 0,0.172361 -0.13789,0.276966 -0.13789,0.103416 -0.35779,0.103416 -0.15453,0 -0.2734,-0.05468 -0.11887,-0.05468 -0.18663,-0.152153 -0.0666,-0.09866 -0.0666,-0.212775 h 0.2199 q 0.006,0.110548 0.088,0.175926 0.0832,0.06419 0.21872,0.06419 0.12481,0 0.1997,-0.04993 0.0761,-0.05111 0.0761,-0.135511 z"
style="font-style:normal;font-variant:normal;font-weight:normal;font-stretch:normal;font-family:Roboto;-inkscape-font-specification:Roboto;stroke-width:0.0608608"
id="path3998" />
<path
d="m 134.08646,91.619774 q 0,-0.05706 0.0333,-0.0951 0.0345,-0.03804 0.10223,-0.03804 0.0677,0 0.10223,0.03804 0.0357,0.03804 0.0357,0.0951 0,0.05468 -0.0357,0.09153 -0.0345,0.03685 -0.10223,0.03685 -0.0678,0 -0.10223,-0.03685 -0.0333,-0.03685 -0.0333,-0.09153 z"
style="font-style:normal;font-variant:normal;font-weight:normal;font-stretch:normal;font-family:Roboto;-inkscape-font-specification:Roboto;stroke-width:0.0608608"
id="path4000" />
<path
d="m 136.21303,91.280997 q 0,-0.101039 -0.0713,-0.15453 -0.0713,-0.05468 -0.25676,-0.114114 -0.18544,-0.06062 -0.29361,-0.11887 -0.29479,-0.159284 -0.29479,-0.429117 0,-0.140266 0.0785,-0.249625 0.0796,-0.110549 0.22704,-0.172361 0.14859,-0.06181 0.33284,-0.06181 0.18543,0 0.33045,0.06776 0.14502,0.06657 0.22466,0.189002 0.0808,0.122435 0.0808,0.278154 h -0.35661 q 0,-0.11887 -0.0749,-0.184248 -0.0749,-0.06657 -0.2104,-0.06657 -0.13075,0 -0.20326,0.05587 -0.0725,0.05468 -0.0725,0.145021 0,0.0844 0.0844,0.141454 0.0856,0.05706 0.25082,0.106982 0.3043,0.09153 0.44338,0.22704 0.13908,0.135511 0.13908,0.337588 0,0.224663 -0.16999,0.353042 -0.16998,0.12719 -0.45764,0.12719 -0.1997,0 -0.36374,-0.07251 -0.16404,-0.0737 -0.25082,-0.200889 -0.0856,-0.12719 -0.0856,-0.294796 h 0.35779 q 0,0.286475 0.34235,0.286475 0.12719,0 0.19851,-0.05111 0.0713,-0.0523 0.0713,-0.14502 z"
style="font-weight:bold"
id="path4002" />
<path
d="m 137.53604,91.735077 q -0.0238,-0.04636 -0.0345,-0.115303 -0.12481,0.139077 -0.32451,0.139077 -0.18901,0 -0.31382,-0.10936 -0.12362,-0.109359 -0.12362,-0.275776 0,-0.204455 0.15096,-0.313815 0.15215,-0.109359 0.43863,-0.110548 h 0.15809 v -0.0737 q 0,-0.08915 -0.0464,-0.142643 -0.0452,-0.05349 -0.14384,-0.05349 -0.0868,0 -0.1367,0.0416 -0.0487,0.0416 -0.0487,0.114115 h -0.34353 q 0,-0.111737 0.0689,-0.206833 0.0689,-0.0951 0.19495,-0.148586 0.126,-0.05468 0.2829,-0.05468 0.23774,0 0.37682,0.120058 0.14027,0.118869 0.14027,0.335211 v 0.557496 q 0.001,0.183059 0.0511,0.276965 v 0.02021 z m -0.2841,-0.238927 q 0.0761,0 0.14027,-0.03328 0.0642,-0.03447 0.0951,-0.09153 v -0.221096 h -0.12837 q -0.25795,0 -0.27459,0.178303 l -0.001,0.02021 q 0,0.06419 0.0452,0.105794 0.0452,0.0416 0.12362,0.0416 z"
style="font-weight:bold"
id="path4004" />
<path
d="m 138.5607,91.315469 0.23892,-0.866556 h 0.35899 l -0.43388,1.286164 h -0.32807 l -0.43388,-1.286164 h 0.35899 z"
style="font-weight:bold"
id="path4006" />
<path
d="m 139.88846,91.758851 q -0.2829,0 -0.46121,-0.173549 -0.17711,-0.173549 -0.17711,-0.462401 v -0.03328 q 0,-0.193756 0.0749,-0.345909 0.0749,-0.153341 0.21159,-0.235361 0.13789,-0.08321 0.31382,-0.08321 0.26389,0 0.41485,0.166417 0.15215,0.166417 0.15215,0.47191 v 0.140266 h -0.81901 q 0.0166,0.126001 0.0999,0.202077 0.0844,0.07608 0.21278,0.07608 0.19851,0 0.31025,-0.143832 l 0.16879,0.189002 q -0.0773,0.10936 -0.20921,0.171171 -0.13194,0.06062 -0.29242,0.06062 z m -0.0392,-1.055558 q -0.10223,0 -0.16642,0.06894 -0.063,0.06894 -0.0808,0.197323 h 0.47785 v -0.02734 q -0.002,-0.114115 -0.0618,-0.175927 -0.0594,-0.063 -0.16879,-0.063 z"
style="font-weight:bold"
id="path4008" />
<path
d="m 142.04237,91.735077 h -0.34353 v -1.324202 l -0.4101,0.12719 v -0.279343 l 0.71678,-0.256757 h 0.0369 z"
style="font-weight:bold"
id="path4010" />
<path
d="m 143.77073,91.019485 q 0,0.358984 -0.14859,0.549175 -0.14858,0.190191 -0.43506,0.190191 -0.28291,0 -0.43268,-0.186625 -0.14978,-0.186624 -0.15334,-0.534911 v -0.318569 q 0,-0.362551 0.14977,-0.550364 0.15097,-0.187814 0.43388,-0.187814 0.2829,0 0.43268,0.186625 0.14977,0.185436 0.15334,0.533722 z m -0.34353,-0.349476 q 0,-0.215153 -0.0594,-0.312625 -0.0582,-0.09866 -0.18305,-0.09866 -0.12125,0 -0.1795,0.09391 -0.0571,0.09272 -0.0606,0.291229 v 0.420797 q 0,0.211587 0.0571,0.315003 0.0582,0.102228 0.18543,0.102228 0.126,0 0.18187,-0.09866 0.0559,-0.09866 0.0582,-0.301927 z"
style="font-weight:bold"
id="path4012" />
<path
d="m 143.99896,90.337176 q 0,-0.159285 0.10341,-0.257946 0.10342,-0.09985 0.27103,-0.09985 0.16998,0 0.27339,0.09866 0.10342,0.09747 0.10342,0.265078 v 0.08559 q 0,0.160473 -0.10342,0.257946 -0.10341,0.09747 -0.27102,0.09747 -0.16879,0 -0.2734,-0.09747 -0.10341,-0.09866 -0.10341,-0.265078 z m 0.22823,0.09153 q 0,0.07132 0.0404,0.115303 0.0416,0.04279 0.10817,0.04279 0.0666,0 0.1058,-0.04398 0.0392,-0.04398 0.0392,-0.11768 v -0.08796 q 0,-0.07132 -0.0392,-0.115303 -0.0392,-0.04398 -0.10817,-0.04398 -0.0654,0 -0.1058,0.04398 -0.0404,0.04279 -0.0404,0.120058 z m 0.5991,0.882009 q 0,-0.160473 0.1046,-0.257946 0.10461,-0.09866 0.27102,-0.09866 0.1688,0 0.27221,0.09747 0.10461,0.09628 0.10461,0.266267 v 0.08559 q 0,0.159285 -0.10223,0.257946 -0.10223,0.09747 -0.27221,0.09747 -0.17117,0 -0.27459,-0.09866 -0.10341,-0.09866 -0.10341,-0.261512 z m 0.22823,0.09272 q 0,0.06538 0.0428,0.111737 0.0428,0.04636 0.10698,0.04636 0.14502,0 0.14502,-0.160473 v -0.09034 q 0,-0.07132 -0.0404,-0.114114 -0.0404,-0.04398 -0.10699,-0.04398 -0.0666,0 -0.10698,0.04398 -0.0404,0.04279 -0.0404,0.11768 z m -0.61099,0.202078 -0.16761,-0.09034 0.84516,-1.352731 0.16761,0.09034 z"
style="font-weight:bold"
id="path4014" />
<path
d="m 146.16475,91.203732 h -0.28528 l -0.0404,-1.19939 h 0.36612 z m -0.14264,0.187813 q 0.0868,0 0.13908,0.05111 0.0535,0.05111 0.0535,0.130756 0,0.07845 -0.0535,0.129567 -0.0523,0.05111 -0.13908,0.05111 -0.0856,0 -0.13908,-0.05111 -0.0523,-0.05111 -0.0523,-0.129567 0,-0.07845 0.0523,-0.129567 0.0535,-0.0523 0.13908,-0.0523 z"
style="font-weight:bold"
id="path4016" />
</g>
<g
id="g896"
transform="matrix(0.11457918,0,0,0.11457918,82.917314,84.127369)">
<path
fill="#fdd888"
d="m 33,31 c 0,2.2 -1.8,4 -4,4 H 7 C 4.8,35 3,33.2 3,31 V 14 c 0,-2.2 1.8,-4 4,-4 h 22 c 2.2,0 4,1.8 4,4 z"
id="path873" />
<path
fill="#fdd888"
d="m 36,11 c 0,2.2 -1.8,4 -4,4 H 4 C 1.8,15 0,13.2 0,11 0,8.8 1.8,7 4,7 h 28 c 2.2,0 4,1.8 4,4 z"
id="path875" />
<path
fill="#fcab40"
d="m 3,15 h 30 v 2 H 3 Z"
id="path877" />
<path
fill="#da2f47"
d="m 19,3 h -2 c -1.657,0 -3,1.343 -3,3 v 29 h 8 V 6 C 22,4.344 20.657,3 19,3 Z"
id="path879" />
<path
fill="#da2f47"
d="m 16,7 c 1.1,0 1.263,-0.516 0.361,-1.147 L 9.639,1.147 C 8.737,0.516 7.554,0.781 7.008,1.736 L 4.992,5.264 C 4.446,6.219 4.9,7 6,7 Z m 4,0 C 18.9,7 18.737,6.484 19.639,5.853 l 6.723,-4.706 c 0.901,-0.631 2.085,-0.366 2.631,0.589 l 2.016,3.527 C 31.554,6.219 31.1,7 30,7 Z"
id="path881" />
</g>
</g>
</g>
</svg>

After

Width:  |  Height:  |  Size: 34 KiB

View File

File diff suppressed because one or more lines are too long

After

Width:  |  Height:  |  Size: 41 KiB

View File

File diff suppressed because one or more lines are too long

After

Width:  |  Height:  |  Size: 215 KiB

View File

Binary file not shown.

After

Width:  |  Height:  |  Size: 71 KiB

View File

Binary file not shown.

Before

Width:  |  Height:  |  Size: 37 KiB

After

Width:  |  Height:  |  Size: 88 KiB

View File

Binary file not shown.

After

Width:  |  Height:  |  Size: 66 KiB

View File

@@ -46,10 +46,10 @@ The key features are:
{% if sponsors %}
{% for sponsor in sponsors.gold -%}
<a href="{{ sponsor.url }}" target="_blank" title="{{ sponsor.title }}"><img src="{{ sponsor.img }}"></a>
<a href="{{ sponsor.url }}" target="_blank" title="{{ sponsor.title }}"><img src="{{ sponsor.img }}" style="border-radius:15px"></a>
{% endfor -%}
{%- for sponsor in sponsors.silver -%}
<a href="{{ sponsor.url }}" target="_blank" title="{{ sponsor.title }}"><img src="{{ sponsor.img }}"></a>
<a href="{{ sponsor.url }}" target="_blank" title="{{ sponsor.title }}"><img src="{{ sponsor.img }}" style="border-radius:15px"></a>
{% endfor %}
{% endif %}

View File

@@ -3,6 +3,156 @@
## Latest Changes
## 0.68.0
### Features
* ✨ Add support for extensions and updates to the OpenAPI schema in each *path operation*. New docs: [FastAPI Path Operation Advanced Configuration - OpenAPI Extra](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#openapi-extra). Initial PR [#1922](https://github.com/tiangolo/fastapi/pull/1922) by [@edouardlp](https://github.com/edouardlp).
* ✨ Add additonal OpenAPI metadata parameters to `FastAPI` class, shown on the automatic API docs UI. New docs: [Metadata and Docs URLs](https://fastapi.tiangolo.com/tutorial/metadata/). Initial PR [#1812](https://github.com/tiangolo/fastapi/pull/1812) by [@dkreeft](https://github.com/dkreeft).
* ✨ Add `description` parameter to all the security scheme classes, e.g. `APIKeyQuery(name="key", description="A very cool API key")`. PR [#1757](https://github.com/tiangolo/fastapi/pull/1757) by [@hylkepostma](https://github.com/hylkepostma).
* ✨ Update OpenAPI models, supporting recursive models and extensions. PR [#3628](https://github.com/tiangolo/fastapi/pull/3628) by [@tiangolo](https://github.com/tiangolo).
* ✨ Import and re-export data structures from Starlette, used by Request properties, on `fastapi.datastructures`. Initial PR [#1872](https://github.com/tiangolo/fastapi/pull/1872) by [@jamescurtin](https://github.com/jamescurtin).
### Docs
* 📝 Update docs about async and response-model with more gender neutral language. PR [#1869](https://github.com/tiangolo/fastapi/pull/1869) by [@Edward-Knight](https://github.com/Edward-Knight).
### Translations
* 🌐 Add Russian translation for `docs/python-types.md`. PR [#3039](https://github.com/tiangolo/fastapi/pull/3039) by [@dukkee](https://github.com/dukkee).
* 🌐 Add Chinese translation for `docs/tutorial/dependencies/index.md`. PR [#3489](https://github.com/tiangolo/fastapi/pull/3489) by [@jaystone776](https://github.com/jaystone776).
* 🌐 Add Russian translation for `docs/external-links.md`. PR [#3036](https://github.com/tiangolo/fastapi/pull/3036) by [@dukkee](https://github.com/dukkee).
* 🌐 Add Chinese translation for `docs/tutorial/dependencies/global-dependencies.md`. PR [#3493](https://github.com/tiangolo/fastapi/pull/3493) by [@jaystone776](https://github.com/jaystone776).
* 🌐 Add Portuguese translation for `docs/deployment/versions.md`. PR [#3618](https://github.com/tiangolo/fastapi/pull/3618) by [@lsglucas](https://github.com/lsglucas).
* 🌐 Add Japanese translation for `docs/tutorial/security/oauth2-jwt.md`. PR [#3526](https://github.com/tiangolo/fastapi/pull/3526) by [@sattosan](https://github.com/sattosan).
### Internal
* ✅ Add the `docs_src` directory to test coverage and update tests. Initial PR [#1904](https://github.com/tiangolo/fastapi/pull/1904) by [@Kludex](https://github.com/Kludex).
* 🔧 Add new GitHub templates with forms for new issues. PR [#3612](https://github.com/tiangolo/fastapi/pull/3612) by [@tiangolo](https://github.com/tiangolo).
* 📝 Add official FastAPI Twitter to docs: [@fastapi](https://twitter.com/fastapi). PR [#3578](https://github.com/tiangolo/fastapi/pull/3578) by [@tiangolo](https://github.com/tiangolo).
## 0.67.0
### Features
* ✨ Add support for `dataclasses` in request bodies and `response_model`. New documentation: [Advanced User Guide - Using Dataclasses](https://fastapi.tiangolo.com/advanced/dataclasses/). PR [#3577](https://github.com/tiangolo/fastapi/pull/3577) by [@tiangolo](https://github.com/tiangolo).
* ✨ Support `dataclasses` in responses. PR [#3576](https://github.com/tiangolo/fastapi/pull/3576) by [@tiangolo](https://github.com/tiangolo), continuation from initial PR [#2722](https://github.com/tiangolo/fastapi/pull/2722) by [@amitlissack](https://github.com/amitlissack).
### Docs
* 📝 Add external link: How to Create A Fake Certificate Authority And Generate TLS Certs for FastAPI. PR [#2839](https://github.com/tiangolo/fastapi/pull/2839) by [@aitoehigie](https://github.com/aitoehigie).
* ✏ Fix code highlighted line in: `body-nested-models.md`. PR [#3463](https://github.com/tiangolo/fastapi/pull/3463) by [@jaystone776](https://github.com/jaystone776).
* ✏ Fix typo in `body-nested-models.md`. PR [#3462](https://github.com/tiangolo/fastapi/pull/3462) by [@jaystone776](https://github.com/jaystone776).
* ✏ Fix typo "might me" -> "might be" in `docs/en/docs/tutorial/schema-extra-example.md`. PR [#3362](https://github.com/tiangolo/fastapi/pull/3362) by [@dbrakman](https://github.com/dbrakman).
* 📝 Add external link: Building simple E-Commerce with NuxtJS and FastAPI. PR [#3271](https://github.com/tiangolo/fastapi/pull/3271) by [@ShahriyarR](https://github.com/ShahriyarR).
* 📝 Add external link: Serve a machine learning model using Sklearn, FastAPI and Docker. PR [#2974](https://github.com/tiangolo/fastapi/pull/2974) by [@rodrigo-arenas](https://github.com/rodrigo-arenas).
* ✏️ Fix typo on docstring in datastructures file. PR [#2887](https://github.com/tiangolo/fastapi/pull/2887) by [@Kludex](https://github.com/Kludex).
* 📝 Add External Link: Deploy FastAPI on Ubuntu and Serve using Caddy 2 Web Server. PR [#3572](https://github.com/tiangolo/fastapi/pull/3572) by [@tiangolo](https://github.com/tiangolo).
* 📝 Add External Link, replaces #1898. PR [#3571](https://github.com/tiangolo/fastapi/pull/3571) by [@tiangolo](https://github.com/tiangolo).
### Internal
* 🎨 Improve style for sponsors, add radius border. PR [#2388](https://github.com/tiangolo/fastapi/pull/2388) by [@Kludex](https://github.com/Kludex).
* 👷 Update GitHub Action latest-changes. PR [#3574](https://github.com/tiangolo/fastapi/pull/3574) by [@tiangolo](https://github.com/tiangolo).
* 👷 Update GitHub Action latest-changes. PR [#3573](https://github.com/tiangolo/fastapi/pull/3573) by [@tiangolo](https://github.com/tiangolo).
* 👷 Rename and clarify CI workflow job names. PR [#3570](https://github.com/tiangolo/fastapi/pull/3570) by [@tiangolo](https://github.com/tiangolo).
* 👷 Update GitHub Action latest-changes, strike 2 ⚾. PR [#3575](https://github.com/tiangolo/fastapi/pull/3575) by [@tiangolo](https://github.com/tiangolo).
* 🔧 Sort external links in docs to have the most recent at the top. PR [#3568](https://github.com/tiangolo/fastapi/pull/3568) by [@tiangolo](https://github.com/tiangolo).
## 0.66.1
### Translations
* 🌐 Add basic setup for German translations. PR [#3522](https://github.com/tiangolo/fastapi/pull/3522) by [@0x4Dark](https://github.com/0x4Dark).
* 🌐 Add Portuguese translation for `docs/tutorial/security/index.md`. PR [#3507](https://github.com/tiangolo/fastapi/pull/3507) by [@oandersonmagalhaes](https://github.com/oandersonmagalhaes).
* 🌐 Add Portuguese translation for `docs/deployment/index.md`. PR [#3337](https://github.com/tiangolo/fastapi/pull/3337) by [@lsglucas](https://github.com/lsglucas).
### Internal
* 🔧 Configure strict pytest options and update/refactor tests. Upgrade pytest to `>=6.2.4,<7.0.0` and pytest-cov to `>=2.12.0,<3.0.0`. Initial PR [#2790](https://github.com/tiangolo/fastapi/pull/2790) by [@graingert](https://github.com/graingert).
* ⬆️ Upgrade python-jose dependency to `>=3.3.0,<4.0.0` for tests. PR [#3468](https://github.com/tiangolo/fastapi/pull/3468) by [@tiangolo](https://github.com/tiangolo).
## 0.66.0
### Features
* ✨ Allow setting the `response_class` to `RedirectResponse` or `FileResponse` and returning the URL from the function. New and updated docs are in the tutorial section **Custom Response - HTML, Stream, File, others**, in [RedirectResponse](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse) and in [FileResponse](https://fastapi.tiangolo.com/advanced/custom-response/#fileresponse). PR [#3457](https://github.com/tiangolo/fastapi/pull/3457) by [@tiangolo](https://github.com/tiangolo).
### Fixes
* 🐛 Fix include/exclude for dicts in `jsonable_encoder`. PR [#2016](https://github.com/tiangolo/fastapi/pull/2016) by [@Rubikoid](https://github.com/Rubikoid).
* 🐛 Support custom OpenAPI / JSON Schema fields in the generated output OpenAPI. PR [#1429](https://github.com/tiangolo/fastapi/pull/1429) by [@jmagnusson](https://github.com/jmagnusson).
### Translations
* 🌐 Add Spanish translation for `tutorial/query-params.md`. PR [#2243](https://github.com/tiangolo/fastapi/pull/2243) by [@mariacamilagl](https://github.com/mariacamilagl).
* 🌐 Add Spanish translation for `advanced/response-directly.md`. PR [#1253](https://github.com/tiangolo/fastapi/pull/1253) by [@jfunez](https://github.com/jfunez).
* 🌐 Add Spanish translation for `advanced/additional-status-codes.md`. PR [#1252](https://github.com/tiangolo/fastapi/pull/1252) by [@jfunez](https://github.com/jfunez).
* 🌐 Add Spanish translation for `advanced/path-operation-advanced-configuration.md`. PR [#1251](https://github.com/tiangolo/fastapi/pull/1251) by [@jfunez](https://github.com/jfunez).
## 0.65.3
### Fixes
* ♻ Assume request bodies contain JSON when no Content-Type header is provided. This fixes a breaking change introduced by [0.65.2 with PR #2118](https://github.com/tiangolo/fastapi/pull/2118). It should allow upgrading FastAPI applications with clients that send JSON data without a `Content-Type` header. And there's still protection against CSRFs. PR [#3456](https://github.com/tiangolo/fastapi/pull/3456) by [@tiangolo](https://github.com/tiangolo).
### Translations
* 🌐 Initialize Indonesian translations. PR [#3014](https://github.com/tiangolo/fastapi/pull/3014) by [@pace-noge](https://github.com/pace-noge).
* 🌐 Add Spanish translation of Tutorial - Path Parameters. PR [#2219](https://github.com/tiangolo/fastapi/pull/2219) by [@mariacamilagl](https://github.com/mariacamilagl).
* 🌐 Add Spanish translation of Tutorial - First Steps. PR [#2208](https://github.com/tiangolo/fastapi/pull/2208) by [@mariacamilagl](https://github.com/mariacamilagl).
* 🌐 Portuguese translation of Tutorial - Body - Fields. PR [#3420](https://github.com/tiangolo/fastapi/pull/3420) by [@ComicShrimp](https://github.com/ComicShrimp).
* 🌐 Add Chinese translation for Tutorial - Request - Forms - and - Files. PR [#3249](https://github.com/tiangolo/fastapi/pull/3249) by [@jaystone776](https://github.com/jaystone776).
* 🌐 Add Chinese translation for Tutorial - Handling - Errors. PR [#3299](https://github.com/tiangolo/fastapi/pull/3299) by [@jaystone776](https://github.com/jaystone776).
* 🌐 Add Chinese translation for Tutorial - Form - Data. PR [#3248](https://github.com/tiangolo/fastapi/pull/3248) by [@jaystone776](https://github.com/jaystone776).
* 🌐 Add Chinese translation for Tutorial - Body - Updates. PR [#3237](https://github.com/tiangolo/fastapi/pull/3237) by [@jaystone776](https://github.com/jaystone776).
* 🌐 Add Chinese translation for FastAPI People. PR [#3112](https://github.com/tiangolo/fastapi/pull/3112) by [@hareru](https://github.com/hareru).
* 🌐 Add French translation for Project Generation. PR [#3197](https://github.com/tiangolo/fastapi/pull/3197) by [@Smlep](https://github.com/Smlep).
* 🌐 Add French translation for Python Types Intro. PR [#3185](https://github.com/tiangolo/fastapi/pull/3185) by [@Smlep](https://github.com/Smlep).
* 🌐 Add French translation for External Links. PR [#3103](https://github.com/tiangolo/fastapi/pull/3103) by [@Smlep](https://github.com/Smlep).
* 🌐 Add French translation for Alternatives, Inspiration and Comparisons. PR [#3020](https://github.com/tiangolo/fastapi/pull/3020) by [@rjNemo](https://github.com/rjNemo).
* 🌐 Fix Chinese translation code snippet mismatch in Tutorial - Python Types Intro. PR [#2573](https://github.com/tiangolo/fastapi/pull/2573) by [@BoYanZh](https://github.com/BoYanZh).
* 🌐 Add Portuguese translation for Development Contributing. PR [#1364](https://github.com/tiangolo/fastapi/pull/1364) by [@Serrones](https://github.com/Serrones).
* 🌐 Add Chinese translation for Tutorial - Request - Files. PR [#3244](https://github.com/tiangolo/fastapi/pull/3244) by [@jaystone776](https://github.com/jaystone776).
### Internal
* 👥 Update FastAPI People. PR [#3450](https://github.com/tiangolo/fastapi/pull/3450) by [@github-actions[bot]](https://github.com/apps/github-actions).
* 👥 Update FastAPI People. PR [#3319](https://github.com/tiangolo/fastapi/pull/3319) by [@github-actions[bot]](https://github.com/apps/github-actions).
* ⬆ Upgrade docs development dependency on `typer-cli` to >=0.0.12 to fix conflicts. PR [#3429](https://github.com/tiangolo/fastapi/pull/3429) by [@tiangolo](https://github.com/tiangolo).
## 0.65.2
### Security fixes
* 🔒 Check Content-Type request header before assuming JSON. Initial PR [#2118](https://github.com/tiangolo/fastapi/pull/2118) by [@patrickkwang](https://github.com/patrickkwang).
This change fixes a [CSRF](https://en.wikipedia.org/wiki/Cross-site_request_forgery) security vulnerability when using cookies for authentication in path operations with JSON payloads sent by browsers.
In versions lower than `0.65.2`, FastAPI would try to read the request payload as JSON even if the `content-type` header sent was not set to `application/json` or a compatible JSON media type (e.g. `application/geo+json`).
So, a request with a content type of `text/plain` containing JSON data would be accepted and the JSON data would be extracted.
But requests with content type `text/plain` are exempt from [CORS](https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS) preflights, for being considered [Simple requests](https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS#simple_requests). So, the browser would execute them right away including cookies, and the text content could be a JSON string that would be parsed and accepted by the FastAPI application.
See [CVE-2021-32677](https://github.com/tiangolo/fastapi/security/advisories/GHSA-8h2j-cgx8-6xv7) for more details.
Thanks to [Dima Boger](https://twitter.com/b0g3r) for the security report! 🙇🔒
### Internal
* 🔧 Update sponsors badge, course bundle. PR [#3340](https://github.com/tiangolo/fastapi/pull/3340) by [@tiangolo](https://github.com/tiangolo).
* 🔧 Add new gold sponsor Jina 🎉. PR [#3291](https://github.com/tiangolo/fastapi/pull/3291) by [@tiangolo](https://github.com/tiangolo).
* 🔧 Add new banner sponsor badge for FastAPI courses bundle. PR [#3288](https://github.com/tiangolo/fastapi/pull/3288) by [@tiangolo](https://github.com/tiangolo).
* 👷 Upgrade Issue Manager GitHub Action. PR [#3236](https://github.com/tiangolo/fastapi/pull/3236) by [@tiangolo](https://github.com/tiangolo).
## 0.65.1
### Security fixes
* 📌 Upgrade pydantic pin, to handle security vulnerability [CVE-2021-29510](https://github.com/samuelcolvin/pydantic/security/advisories/GHSA-5jqp-qgf6-3pvh). PR [#3213](https://github.com/tiangolo/fastapi/pull/3213) by [@tiangolo](https://github.com/tiangolo).
## 0.65.0
### Breaking Changes - Upgrade

View File

@@ -198,7 +198,7 @@ Even for items inside of lists:
<img src="/img/tutorial/body-nested-models/image01.png">
You couldn't get this kind of editor support if you where working directly with `dict` instead of Pydantic models.
You couldn't get this kind of editor support if you were working directly with `dict` instead of Pydantic models.
But you don't have to worry about them either, incoming dicts are converted automatically and your output is converted automatically to JSON too.
@@ -218,7 +218,7 @@ That's what we are going to see here.
In this case, you would accept any `dict` as long as it has `int` keys with `float` values:
```Python hl_lines="15"
```Python hl_lines="9"
{!../../../docs_src/body_nested_models/tutorial009.py!}
```

View File

@@ -2,21 +2,28 @@
You can customize several metadata configurations in your **FastAPI** application.
## Title, description, and version
## Metadata for API
You can set the:
You can set the following fields that are used in the OpenAPI specification and the automatic API docs UIs:
* **Title**: used as your API's title/name, in OpenAPI and the automatic API docs UIs.
* **Description**: the description of your API, in OpenAPI and the automatic API docs UIs.
* **Version**: the version of your API, e.g. `v2` or `2.5.0`.
* Useful for example if you had a previous version of the application, also using OpenAPI.
| Parameter | Type | Description |
|------------|------|-------------|
| `title` | `str` | The title of the API. |
| `description` | `str` | A short description of the API. It can use Markdown. |
| `version` | `string` | The version of the API. This is the version of your own application, not of OpenAPI. For example `2.5.0`. |
| `terms_of_service` | `str` | A URL to the Terms of Service for the API. If provided, this has to be a URL. |
| `contact` | `dict` | The contact information for the exposed API. It can contain several fields. <details><summary><code>contact</code> fields</summary><table><thead><tr><th>Parameter</th><th>Type</th><th>Description</th></tr></thead><tbody><tr><td><code>name</code></td><td><code>str</code></td><td>The identifying name of the contact person/organization.</td></tr><tr><td><code>url</code></td><td><code>str</code></td><td>The URL pointing to the contact information. MUST be in the format of a URL.</td></tr><tr><td><code>email</code></td><td><code>str</code></td><td>The email address of the contact person/organization. MUST be in the format of an email address.</td></tr></tbody></table></details> |
| `license_info` | `dict` | The license information for the exposed API. It can contain several fields. <details><summary><code>license_info</code> fields</summary><table><thead><tr><th>Parameter</th><th>Type</th><th>Description</th></tr></thead><tbody><tr><td><code>name</code></td><td><code>str</code></td><td><strong>REQUIRED</strong> (if a <code>license_info</code> is set). The license name used for the API.</td></tr><tr><td><code>url</code></td><td><code>str</code></td><td>A URL to the license used for the API. MUST be in the format of a URL.</td></tr></tbody></table></details> |
To set them, use the parameters `title`, `description`, and `version`:
You can set them as follows:
```Python hl_lines="4-6"
```Python hl_lines="3-16 19-31"
{!../../../docs_src/metadata/tutorial001.py!}
```
!!! tip
You can write Markdown in the `description` field and it will be rendered in the output.
With this configuration, the automatic API docs would look like:
<img src="/img/tutorial/metadata/image01.png">

View File

@@ -47,7 +47,7 @@ And we are using this model to declare our input and the same model to declare o
Now, whenever a browser is creating a user with a password, the API will return the same password in the response.
In this case, it might not be a problem, because the user himself is sending the password.
In this case, it might not be a problem, because the user themself is sending the password.
But if we use the same model for another *path operation*, we could be sending our user's passwords to every client.

View File

@@ -88,7 +88,7 @@ With `examples` added to `Body()` the `/docs` would look like:
!!! warning
These are very technical details about the standards **JSON Schema** and **OpenAPI**.
If the ideas above already work for you, that might me enough, and you probably don't need these details, feel free to skip them.
If the ideas above already work for you, that might be enough, and you probably don't need these details, feel free to skip them.
When you add an example inside of a Pydantic model, using `schema_extra` or `Field(example="something")` that example is added to the **JSON Schema** for that Pydantic model.

View File

@@ -39,8 +39,10 @@ nav:
- FastAPI: index.md
- Languages:
- en: /
- de: /de/
- es: /es/
- fr: /fr/
- id: /id/
- it: /it/
- ja: /ja/
- ko: /ko/
@@ -117,6 +119,7 @@ nav:
- advanced/security/oauth2-scopes.md
- advanced/security/http-basic-auth.md
- advanced/using-request-directly.md
- advanced/dataclasses.md
- advanced/middleware.md
- advanced/sql-databases-peewee.md
- advanced/async-sql-databases.md
@@ -177,7 +180,7 @@ extra:
- icon: fontawesome/brands/discord
link: https://discord.gg/VQjSZaeJmf
- icon: fontawesome/brands/twitter
link: https://twitter.com/tiangolo
link: https://twitter.com/fastapi
- icon: fontawesome/brands/linkedin
link: https://www.linkedin.com/in/tiangolo
- icon: fontawesome/brands/dev
@@ -189,10 +192,14 @@ extra:
alternate:
- link: /
name: en - English
- link: /de/
name: de
- link: /es/
name: es - español
- link: /fr/
name: fr - français
- link: /id/
name: id
- link: /it/
name: it - italiano
- link: /ja/

View File

@@ -3,6 +3,13 @@
{% block announce %}
<div class="announce-wrapper">
<div id="announce-left">
<div class="item">
<a class="announce-link" href="https://twitter.com/fastapi" target="_blank">
<span class="twemoji twitter">
{% include ".icons/fontawesome/brands/twitter.svg" %}
</span> Follow <strong>@fastapi</strong> on <strong>Twitter</strong> to stay updated
</a>
</div>
<div class="item">
<a class="announce-link" href="https://fastapi.tiangolo.com/newsletter/">
<span class="twemoji">
@@ -16,9 +23,21 @@
</div>
<div id="announce-right" style="position: relative;">
<div class="item">
<a title="The launchpad for all your (team's) ideas" style="display: block; position: relative;" href="https://www.deta.sh/?ref=fastapi">
<a title="The launchpad for all your (team's) ideas" style="display: block; position: relative;" href="https://www.deta.sh/?ref=fastapi" target="_blank">
<span class="sponsor-badge">sponsor</span>
<img style="display: block;" src="/img/sponsors/deta-banner.svg" />
<img class="sponsor-image" src="/img/sponsors/deta-banner.svg" />
</a>
</div>
<div class="item">
<a title="Get three courses at 10% off their current prices! Plus, we'll be donating 10% of all profits from sales of this bundle to the FastAPI team." style="display: block; position: relative;" href="https://testdriven.io/talkpython/" target="_blank">
<span class="sponsor-badge">sponsor</span>
<img class="sponsor-image" src="/img/sponsors/fastapi-course-bundle-banner.svg" />
</a>
</div>
<div class="item">
<a title="Jina: build neural search-as-a-service for any kind of data in just minutes." style="display: block; position: relative;" href="https://bit.ly/2QSouzH" target="_blank">
<span class="sponsor-badge">sponsor</span>
<img class="sponsor-image" src="/img/sponsors/jina-banner.svg" />
</a>
</div>
</div>

View File

@@ -0,0 +1,37 @@
# Códigos de estado adicionales
Por defecto, **FastAPI** devolverá las respuestas utilizando una `JSONResponse`, poniendo el contenido que devuelves en tu *operación de path* dentro de esa `JSONResponse`.
Utilizará el código de estado por defecto, o el que hayas asignado en tu *operación de path*.
## Códigos de estado adicionales
Si quieres devolver códigos de estado adicionales además del principal, puedes hacerlo devolviendo directamente una `Response`, como una `JSONResponse`, y asignar directamente el código de estado adicional.
Por ejemplo, digamos que quieres tener una *operación de path* que permita actualizar ítems y devolver códigos de estado HTTP 200 "OK" cuando sea exitosa.
Pero también quieres que acepte nuevos ítems. Cuando los ítems no existan anteriormente, serán creados y devolverá un código de estado HTTP 201 "Created".
Para conseguir esto importa `JSONResponse` y devuelve ahí directamente tu contenido, asignando el `status_code` que quieras:
```Python hl_lines="2 19"
{!../../../docs_src/additional_status_codes/tutorial001.py!}
```
!!! warning "Advertencia"
Cuando devuelves directamente una `Response`, como en los ejemplos anteriores, será devuelta directamente.
No será serializado con el modelo, etc.
Asegurate de que la respuesta tenga los datos que quieras, y que los valores sean JSON válidos (si estás usando `JSONResponse`).
!!! note "Detalles Técnicos"
También podrías utilizar `from starlette.responses import JSONResponse`.
**FastAPI** provee las mismas `starlette.responses` que `fastapi.responses` simplemente como una convención para ti, el desarrollador. Pero la mayoría de las respuestas disponibles vienen directamente de Starlette. Lo mismo con `status`.
## OpenAPI y documentación de API
Si quieres devolver códigos de estado y respuestas adicionales directamente, estas no estarán incluidas en el schema de OpenAPI (documentación de API), porque FastAPI no tiene una manera de conocer de antemano lo que vas a devolver.
Pero puedes documentar eso en tu código usando [Respuestas Adicionales](additional-responses.md){.internal-link target=_blank}.

View File

@@ -0,0 +1,52 @@
# Configuración avanzada de las operaciones de path
## OpenAPI operationId
!!! warning "Advertencia"
Si no eres una persona "experta" en OpenAPI, probablemente no necesitas leer esto.
Puedes asignar el `operationId` de OpenAPI para ser usado en tu *operación de path* con el parámetro `operation_id`.
En este caso tendrías que asegurarte de que sea único para cada operación.
```Python hl_lines="6"
{!../../../docs_src/path_operation_advanced_configuration/tutorial001.py!}
```
### Usando el nombre de la *función de la operación de path* en el operationId
Si quieres usar tus nombres de funciones de API como `operationId`s, puedes iterar sobre todos ellos y sobrescribir `operation_id` de cada *operación de path* usando su `APIRoute.name`.
Deberías hacerlo después de adicionar todas tus *operaciones de path*.
```Python hl_lines="2 12 13 14 15 16 17 18 19 20 21 24"
{!../../../docs_src/path_operation_advanced_configuration/tutorial002.py!}
```
!!! tip "Consejo"
Si llamas manualmente a `app.openapi()`, debes actualizar el `operationId`s antes de hacerlo.
!!! warning "Advertencia"
Si haces esto, debes asegurarte de que cada una de tus *funciones de las operaciones de path* tenga un nombre único.
Incluso si están en diferentes módulos (archivos Python).
## Excluir de OpenAPI
Para excluir una *operación de path* del esquema OpenAPI generado (y por tanto del la documentación generada automáticamente), usa el parámetro `include_in_schema` y asigna el valor como `False`;
```Python hl_lines="6"
{!../../../docs_src/path_operation_advanced_configuration/tutorial003.py!}
```
## Descripción avanzada desde el docstring
Puedes limitar las líneas usadas desde el docstring de una *operación de path* para OpenAPI.
Agregar un `\f` (un carácter de "form feed" escapado) hace que **FastAPI** trunque el output utilizada para OpenAPI en ese punto.
No será mostrado en la documentación, pero otras herramientas (como Sphinx) serán capaces de usar el resto.
```Python hl_lines="19 20 21 22 23 24 25 26 27 28 29"
{!../../../docs_src/path_operation_advanced_configuration/tutorial004.py!}
```

View File

@@ -0,0 +1,63 @@
# Devolver una respuesta directamente
Cuando creas una *operación de path* normalmente puedes devolver cualquier dato: un `dict`, una `list`, un modelo Pydantic, un modelo de base de datos, etc.
Por defecto, **FastAPI** convertiría automáticamente ese valor devuelto a JSON usando el `jsonable_encoder` explicado en [Codificador Compatible JSON](../tutorial/encoder.md){.internal-link target=_blank}.
Luego, tras bastidores, pondría esos datos compatibles con JSON (por ejemplo, un `dict`) dentro de una `JSONResponse` que se usaría para enviar la respuesta al cliente.
Pero puedes devolver una `JSONResponse` directamente de tu *operación de path*.
Esto puede ser útil, por ejemplo, para devolver cookies o headers personalizados.
## Devolver una `Response`
De hecho, puedes devolver cualquier `Response` o cualquier subclase de la misma.
!!! tip "Consejo"
`JSONResponse` en sí misma es una subclase de `Response`.
Y cuando devuelves una `Response`, **FastAPI** la pasará directamente.
No hará ninguna conversión de datos con modelos Pydantic, no convertirá el contenido a ningún tipo, etc.
Esto te da mucha flexibilidad. Puedes devolver cualquier tipo de dato, sobrescribir cualquer declaración de datos o validación, etc.
## Usando el `jsonable_encoder` en una `Response`
Como **FastAPI** no realiza ningún cambio en la `Response` que devuelves, debes asegurarte de que el contenido está listo.
Por ejemplo, no puedes poner un modelo Pydantic en una `JSONResponse` sin primero convertirlo a un `dict` con todos los tipos de datos (como `datetime`, `UUID`, etc) convertidos a tipos compatibles con JSON.
Para esos casos, puedes usar el `jsonable_encoder` para convertir tus datos antes de pasarlos a la respuesta:
```Python hl_lines="4 6 20 21"
{!../../../docs_src/response_directly/tutorial001.py!}
```
!!! note "Detalles Técnicos"
También puedes usar `from starlette.responses import JSONResponse`.
**FastAPI** provee `starlette.responses` como `fastapi.responses`, simplemente como una conveniencia para ti, el desarrollador. Pero la mayoría de las respuestas disponibles vienen directamente de Starlette.
## Devolviendo una `Response` personalizada
El ejemplo anterior muestra las partes que necesitas, pero no es muy útil todavía, dado que podrías simplemente devolver el `item` directamente, y **FastAPI** lo pondría en una `JSONResponse` por ti, convirtiéndolo en un `dict`, etc. Todo esto por defecto.
Ahora, veamos cómo puedes usarlo para devolver una respuesta personalizada.
Digamos que quieres devolver una respuesta <a href="https://en.wikipedia.org/wiki/XML" class="external-link" target="_blank">XML</a>.
Podrías poner tu contenido XML en un string, ponerlo en una `Response` y devolverlo:
```Python hl_lines="1 18"
{!../../../docs_src/response_directly/tutorial002.py!}
```
## Notas
Cuando devuelves una `Response` directamente, los datos no son validados, convertidos (serializados), ni documentados automáticamente.
Pero todavía es posible documentarlo como es descrito en [Respuestas adicionales en OpenAPI](additional-responses.md){.internal-link target=_blank}.
Puedes ver en secciones posteriores como usar/declarar esas `Response`s personalizadas aún teniendo conversión automática de datos, documentación, etc.

View File

@@ -39,13 +39,16 @@ Sus características principales son:
<small>* Esta estimación está basada en pruebas con un equipo de desarrollo interno contruyendo aplicaciones listas para producción.</small>
## Gold Sponsors
## Sponsors
<!-- sponsors -->
{% if sponsors %}
{% for sponsor in sponsors.gold -%}
<a href="{{ sponsor.url }}" target="_blank" title="{{ sponsor.title }}"><img src="{{ sponsor.img }}"></a>
<a href="{{ sponsor.url }}" target="_blank" title="{{ sponsor.title }}"><img src="{{ sponsor.img }}" style="border-radius:15px"></a>
{% endfor -%}
{%- for sponsor in sponsors.silver -%}
<a href="{{ sponsor.url }}" target="_blank" title="{{ sponsor.title }}"><img src="{{ sponsor.img }}" style="border-radius:15px"></a>
{% endfor %}
{% endif %}

View File

@@ -0,0 +1,333 @@
# Primeros pasos
Un archivo muy simple de FastAPI podría verse así:
```Python
{!../../../docs_src/first_steps/tutorial001.py!}
```
Copia eso a un archivo `main.py`.
Corre el servidor en vivo:
<div class="termy">
```console
$ uvicorn main:app --reload
<span style="color: green;">INFO</span>: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit)
<span style="color: green;">INFO</span>: Started reloader process [28720]
<span style="color: green;">INFO</span>: Started server process [28722]
<span style="color: green;">INFO</span>: Waiting for application startup.
<span style="color: green;">INFO</span>: Application startup complete.
```
</div>
!!! note "Nota"
El comando `uvicorn main:app` se refiere a:
* `main`: el archivo `main.py` (el "módulo" de Python).
* `app`: el objeto creado dentro de `main.py` con la línea `app = FastAPI()`.
* `--reload`: hace que el servidor se reinicie cada vez que cambia el código. Úsalo únicamente para desarrollo.
En el output, hay una línea que dice más o menos:
```hl_lines="4"
INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit)
```
Esa línea muestra la URL dónde se está sirviendo tu app en tu maquina local.
### Revísalo
Abre tu navegador en <a href="http://127.0.0.1:8000" class="external-link" target="_blank">http://127.0.0.1:8000</a>.
Verás la respuesta en JSON:
```JSON
{"message": "Hello World"}
```
### Documentación interactiva de la API
Ahora dirígete a <a href="http://127.0.0.1:8000/docs" class="external-link" target="_blank">http://127.0.0.1:8000/docs</a>.
Ahí verás la documentación automática e interactiva de la API (proveída por <a href="https://github.com/swagger-api/swagger-ui" class="external-link" target="_blank">Swagger UI</a>):
![Swagger UI](https://fastapi.tiangolo.com/img/index/index-01-swagger-ui-simple.png)
### Documentación alternativa de la API
Ahora, dirígete a <a href="http://127.0.0.1:8000/redoc" class="external-link" target="_blank">http://127.0.0.1:8000/redoc</a>.
Aquí verás la documentación automática alternativa (proveída por <a href="https://github.com/Rebilly/ReDoc" class="external-link" target="_blank">ReDoc</a>):
![ReDoc](https://fastapi.tiangolo.com/img/index/index-02-redoc-simple.png)
### OpenAPI
**FastAPI** genera un "schema" con toda tu API usando el estándar para definir APIs, **OpenAPI**.
#### "Schema"
Un "schema" es una definición o descripción de algo. No es el código que la implementa, sino solo una descripción abstracta.
#### "Schema" de la API
En este caso, <a href="https://github.com/OAI/OpenAPI-Specification" class="external-link" target="_blank">OpenAPI</a> es una especificación que dicta como se debe definir el schema de tu API.
La definición del schema incluye los paths de tu API, los parámetros que podría recibir, etc.
#### "Schema" de datos
El concepto "schema" también se puede referir a la forma de algunos datos, como un contenido en formato JSON.
En ese caso haría referencia a los atributos del JSON, los tipos de datos que tiene, etc.
#### OpenAPI y JSON Schema
OpenAPI define un schema de API para tu API. Ese schema incluye definiciones (o "schemas") de los datos enviados y recibidos por tu API usando **JSON Schema**, el estándar para los schemas de datos en JSON.
#### Revisa el `openapi.json`
Si sientes curiosidad por saber cómo se ve el schema de OpenAPI en bruto, FastAPI genera automáticamente un (schema) JSON con la descripción de todo tu API.
Lo puedes ver directamente en: <a href="http://127.0.0.1:8000/openapi.json" class="external-link" target="_blank">http://127.0.0.1:8000/openapi.json</a>.
Esto te mostrará un JSON que comienza con algo como:
```JSON
{
"openapi": "3.0.2",
"info": {
"title": "FastAPI",
"version": "0.1.0"
},
"paths": {
"/items/": {
"get": {
"responses": {
"200": {
"description": "Successful Response",
"content": {
"application/json": {
...
```
#### ¿Para qué se usa OpenAPI?
El schema de OpenAPI es lo que alimenta a los dos sistemas de documentación interactiva incluidos.
También hay docenas de alternativas, todas basadas en OpenAPI. Podrías añadir fácilmente cualquiera de esas alternativas a tu aplicación construida con **FastAPI**.
También podrías usarlo para generar código automáticamente, para los clientes que se comunican con tu API. Por ejemplo, frontend, móvil o aplicaciones de IoT.
## Repaso, paso a paso
### Paso 1: importa `FastAPI`
```Python hl_lines="1"
{!../../../docs_src/first_steps/tutorial001.py!}
```
`FastAPI` es una clase de Python que provee toda la funcionalidad para tu API.
!!! note "Detalles Técnicos"
`FastAPI` es una clase que hereda directamente de `Starlette`.
También puedes usar toda la funcionalidad de <a href="https://www.starlette.io/" class="external-link" target="_blank">Starlette</a>.
### Paso 2: crea un "instance" de `FastAPI`
```Python hl_lines="3"
{!../../../docs_src/first_steps/tutorial001.py!}
```
Aquí la variable `app` será un instance de la clase `FastAPI`.
Este será el punto de interacción principal para crear todo tu API.
Esta `app` es la misma a la que nos referimos cuando usamos el comando de `uvicorn`:
<div class="termy">
```console
$ uvicorn main:app --reload
<span style="color: green;">INFO</span>: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit)
```
</div>
Si creas un app como:
```Python hl_lines="3"
{!../../../docs_src/first_steps/tutorial002.py!}
```
y lo guardas en un archivo `main.py`, entonces ejecutarías `uvicorn` así:
<div class="termy">
```console
$ uvicorn main:my_awesome_api --reload
<span style="color: green;">INFO</span>: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit)
```
</div>
### Paso 3: crea un *operación de path*
#### Path
"Path" aquí se refiere a la última parte de una URL comenzando desde el primer `/`.
Entonces, en una URL como:
```
https://example.com/items/foo
```
...el path sería:
```
/items/foo
```
!!! info "Información"
Un "path" también se conoce habitualmente como "endpoint", "route" o "ruta".
Cuando construyes una API, el "path" es la manera principal de separar los <abbr title="en inglés: separation of concerns">"intereses"</abbr> y los "recursos".
#### Operación
"Operación" aquí se refiere a uno de los "métodos" de HTTP.
Uno como:
* `POST`
* `GET`
* `PUT`
* `DELETE`
...y los más exóticos:
* `OPTIONS`
* `HEAD`
* `PATCH`
* `TRACE`
En el protocolo de HTTP, te puedes comunicar con cada path usando uno (o más) de estos "métodos".
---
Cuando construyes APIs, normalmente usas uno de estos métodos específicos de HTTP para realizar una acción específica.
Normalmente usas:
* `POST`: para crear datos.
* `GET`: para leer datos.
* `PUT`: para actualizar datos.
* `DELETE`: para borrar datos.
Así que en OpenAPI, cada uno de estos métodos de HTTP es referido como una "operación".
Nosotros también los llamaremos "**operación**".
#### Define un *decorador de operaciones de path*
```Python hl_lines="6"
{!../../../docs_src/first_steps/tutorial001.py!}
```
El `@app.get("/")` le dice a **FastAPI** que la función que tiene justo debajo está a cargo de manejar los requests que van a:
* el path `/`
* usando una <abbr title="an HTTP GET method">operación <code>get</code></abbr>
!!! info "Información sobre `@decorator`"
Esa sintaxis `@algo` se llama un "decorador" en Python.
Lo pones encima de una función. Es como un lindo sombrero decorado (creo que de ahí salió el concepto).
Un "decorador" toma la función que tiene debajo y hace algo con ella.
En nuestro caso, este decorador le dice a **FastAPI** que la función que está debajo corresponde al **path** `/` con una **operación** `get`.
Es el "**decorador de operaciones de path**".
También puedes usar las otras operaciones:
* `@app.post()`
* `@app.put()`
* `@app.delete()`
y las más exóticas:
* `@app.options()`
* `@app.head()`
* `@app.patch()`
* `@app.trace()`
!!! tip "Consejo"
Tienes la libertad de usar cada operación (método de HTTP) como quieras.
**FastAPI** no impone ningún significado específico.
La información que está presentada aquí es una guía, no un requerimiento.
Por ejemplo, cuando usas GraphQL normalmente realizas todas las acciones usando únicamente operaciones `POST`.
### Paso 4: define la **función de la operación de path**
Esta es nuestra "**función de la operación de path**":
* **path**: es `/`.
* **operación**: es `get`.
* **función**: es la función debajo del "decorador" (debajo de `@app.get("/")`).
```Python hl_lines="7"
{!../../../docs_src/first_steps/tutorial001.py!}
```
Esto es una función de Python.
Esta función será llamada por **FastAPI** cada vez que reciba un request en la URL "`/`" usando una operación `GET`.
En este caso es una función `async`.
---
También podrías definirla como una función normal, en vez de `async def`:
```Python hl_lines="7"
{!../../../docs_src/first_steps/tutorial003.py!}
```
!!! note "Nota"
Si no sabes la diferencia, revisa el [Async: *"¿Tienes prisa?"*](../async.md#in-a-hurry){.internal-link target=_blank}.
### Paso 5: devuelve el contenido
```Python hl_lines="8"
{!../../../docs_src/first_steps/tutorial001.py!}
```
Puedes devolver `dict`, `list`, valores singulares como un `str`, `int`, etc.
También puedes devolver modelos de Pydantic (ya verás más sobre esto más adelante).
Hay muchos objetos y modelos que pueden ser convertidos automáticamente a JSON (incluyendo ORMs, etc.). Intenta usar tus favoritos, es muy probable que ya tengan soporte.
## Repaso
* Importa `FastAPI`.
* Crea un instance de `app`.
* Escribe un **decorador de operación de path** (como `@app.get("/")`).
* Escribe una **función de la operación de path** (como `def root(): ...` arriba).
* Corre el servidor de desarrollo (como `uvicorn main:app --reload`).

View File

@@ -0,0 +1,244 @@
# Parámetros de path
Puedes declarar los "parámetros" o "variables" con la misma sintaxis que usan los format strings de Python:
```Python hl_lines="6-7"
{!../../../docs_src/path_params/tutorial001.py!}
```
El valor del parámetro de path `item_id` será pasado a tu función como el argumento `item_id`.
Entonces, si corres este ejemplo y vas a <a href="http://127.0.0.1:8000/items/foo" class="external-link" target="_blank">http://127.0.0.1:8000/items/foo</a>, verás una respuesta de:
```JSON
{"item_id":"foo"}
```
## Parámetros de path con tipos
Puedes declarar el tipo de un parámetro de path en la función usando las anotaciones de tipos estándar de Python:
```Python hl_lines="7"
{!../../../docs_src/path_params/tutorial002.py!}
```
En este caso, `item_id` es declarado como un `int`.
!!! check "Revisa"
Esto te dará soporte en el editor dentro de tu función, con chequeos de errores, autocompletado, etc.
## <abbr title="también conocido en inglés como: serialization, parsing, marshalling">Conversión</abbr> de datos
Si corres este ejemplo y abres tu navegador en <a href="http://127.0.0.1:8000/items/3" class="external-link" target="_blank">http://127.0.0.1:8000/items/3</a> verás una respuesta de:
```JSON
{"item_id":3}
```
!!! check "Revisa"
Observa que el valor que recibió (y devolvió) tu función es `3`, como un Python `int`, y no un string `"3"`.
Entonces, con esa declaración de tipos **FastAPI** te da <abbr title="convertir el string que viene de un HTTP request a datos de Python">"parsing"</abbr> automático del request.
## Validación de datos
Pero si abres tu navegador en <a href="http://127.0.0.1:8000/items/foo" class="external-link" target="_blank">http://127.0.0.1:8000/items/foo</a> verás este lindo error de HTTP:
```JSON
{
"detail": [
{
"loc": [
"path",
"item_id"
],
"msg": "value is not a valid integer",
"type": "type_error.integer"
}
]
}
```
debido a que el parámetro de path `item_id` tenía el valor `"foo"`, que no es un `int`.
El mismo error aparecería si pasaras un `float` en vez de un `int` como en: <a href="http://127.0.0.1:8000/items/4.2" class="external-link" target="_blank">http://127.0.0.1:8000/items/4.2</a>
!!! check "Revisa"
Así, con la misma declaración de tipo de Python, **FastAPI** te da validación de datos.
Observa que el error también muestra claramente el punto exacto en el que no pasó la validación.
Esto es increíblemente útil cuando estás desarrollando y debugging código que interactúa con tu API.
## Documentación
Cuando abras tu navegador en <a href="http://127.0.0.1:8000/docs" class="external-link" target="_blank">http://127.0.0.1:8000/docs</a> verás la documentación automática e interactiva del API como:
<img src="/img/tutorial/path-params/image01.png">
!!! check "Revisa"
Nuevamente, con la misma declaración de tipo de Python, **FastAPI** te da documentación automática e interactiva (integrándose con Swagger UI)
Observa que el parámetro de path está declarado como un integer.
## Beneficios basados en estándares, documentación alternativa
Debido a que el schema generado es del estándar <a href="https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.2.md" class="external-link" target="_blank">OpenAPI</a> hay muchas herramientas compatibles.
Es por esto que **FastAPI** mismo provee una documentación alternativa de la API (usando ReDoc), a la que puedes acceder en <a href="http://127.0.0.1:8000/redoc" class="external-link" target="_blank">http://127.0.0.1:8000/redoc</a>:
<img src="/img/tutorial/path-params/image02.png">
De la misma manera hay muchas herramientas compatibles. Incluyendo herramientas de generación de código para muchos lenguajes.
## Pydantic
Toda la validación de datos es realizada tras bastidores por <a href="https://pydantic-docs.helpmanual.io/" class="external-link" target="_blank">Pydantic</a>, así que obtienes todos sus beneficios. Así sabes que estás en buenas manos.
Puedes usar las mismas declaraciones de tipos con `str`, `float`, `bool` y otros tipos de datos más complejos.
Exploraremos varios de estos tipos en los próximos capítulos del tutorial.
## El orden importa
Cuando creas *operaciones de path* puedes encontrarte con situaciones en las que tengas un path fijo.
Digamos algo como `/users/me` que sea para obtener datos del usuario actual.
... y luego puedes tener el path `/users/{user_id}` para obtener los datos sobre un usuario específico asociados a un ID de usuario.
Porque las *operaciones de path* son evaluadas en orden, tienes que asegurarte de que el path para `/users/me` sea declarado antes que el path para `/users/{user_id}`:
```Python hl_lines="6 11"
{!../../../docs_src/path_params/tutorial003.py!}
```
De otra manera el path para `/users/{user_id}` coincidiría también con `/users/me` "pensando" que está recibiendo el parámetro `user_id` con el valor `"me"`.
## Valores predefinidos
Si tienes una *operación de path* que recibe un *parámetro de path* pero quieres que los valores posibles del *parámetro de path* sean predefinidos puedes usar un <abbr title="Enumeration">`Enum`</abbr> estándar de Python.
### Crea una clase `Enum`
Importa `Enum` y crea una sub-clase que herede desde `str` y desde `Enum`.
Al heredar desde `str` la documentación de la API podrá saber que los valores deben ser de tipo `string` y podrá mostrarlos correctamente.
Luego crea atributos de clase con valores fijos, que serán los valores disponibles válidos:
```Python hl_lines="1 6-9"
{!../../../docs_src/path_params/tutorial005.py!}
```
!!! info "Información"
Las <a href="https://docs.python.org/3/library/enum.html" class="external-link" target="_blank">Enumerations (o enums) están disponibles en Python</a> desde la versión 3.4.
!!! tip "Consejo"
Si lo estás dudando, "AlexNet", "ResNet", y "LeNet" son solo nombres de <abbr title="Tecnicamente, arquitecturas de modelos de Deep Learning">modelos</abbr> de Machine Learning.
### Declara un *parámetro de path*
Luego, crea un *parámetro de path* con anotaciones de tipos usando la clase enum que creaste (`ModelName`):
```Python hl_lines="16"
{!../../../docs_src/path_params/tutorial005.py!}
```
### Revisa la documentación
Debido a que los valores disponibles para el *parámetro de path* están predefinidos, la documentación interactiva los puede mostrar bien:
<img src="/img/tutorial/path-params/image03.png">
### Trabajando con los *enumerations* de Python
El valor del *parámetro de path* será un *enumeration member*.
#### Compara *enumeration members*
Puedes compararlo con el *enumeration member* en el enum (`ModelName`) que creaste:
```Python hl_lines="17"
{!../../../docs_src/path_params/tutorial005.py!}
```
#### Obtén el *enumeration value*
Puedes obtener el valor exacto (un `str` en este caso) usando `model_name.value`, o en general, `your_enum_member.value`:
```Python hl_lines="20"
{!../../../docs_src/path_params/tutorial005.py!}
```
!!! tip "Consejo"
También podrías obtener el valor `"lenet"` con `ModelName.lenet.value`.
#### Devuelve *enumeration members*
Puedes devolver *enum members* desde tu *operación de path* inclusive en un body de JSON anidado (por ejemplo, un `dict`).
Ellos serán convertidos a sus valores correspondientes (strings en este caso) antes de devolverlos al cliente:
```Python hl_lines="18 21 23"
{!../../../docs_src/path_params/tutorial005.py!}
```
En tu cliente obtendrás una respuesta en JSON como:
```JSON
{
"model_name": "alexnet",
"message": "Deep Learning FTW!"
}
```
## Parámetros de path parameters que contienen paths
Digamos que tienes una *operación de path* con un path `/files/{file_path}`.
Pero necesitas que el mismo `file_path` contenga un path como `home/johndoe/myfile.txt`.
Entonces, la URL para ese archivo sería algo como: `/files/home/johndoe/myfile.txt`.
### Soporte de OpenAPI
OpenAPI no soporta una manera de declarar un *parámetro de path* que contenga un path, dado que esto podría llevar a escenarios que son difíciles de probar y definir.
Sin embargo, lo puedes hacer en **FastAPI** usando una de las herramientas internas de Starlette.
La documentación seguirá funcionando, aunque no añadirá ninguna información diciendo que el parámetro debería contener un path.
### Convertidor de path
Usando una opción directamente desde Starlette puedes declarar un *parámetro de path* que contenga un path usando una URL como:
```
/files/{file_path:path}
```
En este caso el nombre del parámetro es `file_path` y la última parte, `:path`, le dice que el parámetro debería coincidir con cualquier path.
Entonces lo puedes usar con:
```Python hl_lines="6"
{!../../../docs_src/path_params/tutorial004.py!}
```
!!! tip "Consejo"
Podrías necesitar que el parámetro contenga `/home/johndoe/myfile.txt` con un slash inicial (`/`).
En este caso la URL sería `/files//home/johndoe/myfile.txt` con un slash doble (`//`) entre `files` y `home`.
## Repaso
Con **FastAPI**, usando declaraciones de tipo de Python intuitivas y estándares, obtienes:
* Soporte en el editor: chequeos de errores, auto-completado, etc.
* "<abbr title="convertir el string que viene de un HTTP request a datos de Python">Parsing</abbr>" de datos
* Validación de datos
* Anotación de la API y documentación automática
Solo tienes que declararlos una vez.
Esa es probablemente la principal ventaja visible de **FastAPI** sobre otros frameworks alternativos (aparte del rendimiento puro).

View File

@@ -0,0 +1,197 @@
# Parámetros de query
Cuando declaras otros parámetros de la función que no hacen parte de los parámetros de path estos se interpretan automáticamente como parámetros de "query".
```Python hl_lines="9"
{!../../../docs_src/query_params/tutorial001.py!}
```
El query es el conjunto de pares de key-value que van después del `?` en la URL, separados por caracteres `&`.
Por ejemplo, en la URL:
```
http://127.0.0.1:8000/items/?skip=0&limit=10
```
...los parámetros de query son:
* `skip`: con un valor de `0`
* `limit`: con un valor de `10`
Dado que son parte de la URL son strings "naturalmente".
Pero cuando los declaras con tipos de Python (en el ejemplo arriba, como `int`) son convertidos a ese tipo y son validados con él.
Todo el proceso que aplicaba a los parámetros de path también aplica a los parámetros de query:
* Soporte del editor (obviamente)
* <abbr title="convertir el string que viene de un HTTP request a datos de Python">"Parsing"</abbr> de datos
* Validación de datos
* Documentación automática
## Configuraciones por defecto
Como los parámetros de query no están fijos en una parte del path pueden ser opcionales y pueden tener valores por defecto.
El ejemplo arriba tiene `skip=0` y `limit=10` como los valores por defecto.
Entonces, si vas a la URL:
```
http://127.0.0.1:8000/items/
```
Sería lo mismo que ir a:
```
http://127.0.0.1:8000/items/?skip=0&limit=10
```
Pero, si por ejemplo vas a:
```
http://127.0.0.1:8000/items/?skip=20
```
Los valores de los parámetros en tu función serán:
* `skip=20`: porque lo definiste en la URL
* `limit=10`: porque era el valor por defecto
## Parámetros opcionales
Del mismo modo puedes declarar parámetros de query opcionales definiendo el valor por defecto como `None`:
```Python hl_lines="9"
{!../../../docs_src/query_params/tutorial002.py!}
```
En este caso el parámetro de la función `q` será opcional y será `None` por defecto.
!!! check "Revisa"
También puedes notar que **FastAPI** es lo suficientemente inteligente para darse cuenta de que el parámetro de path `item_id` es un parámetro de path y que `q` no lo es, y por lo tanto es un parámetro de query.
!!! note "Nota"
FastAPI sabrá que `q` es opcional por el `= None`.
El `Optional` en `Optional[str]` no es usado por FastAPI (FastAPI solo usará la parte `str`), pero el `Optional[str]` le permitirá a tu editor ayudarte a encontrar errores en tu código.
## Conversión de tipos de parámetros de query
También puedes declarar tipos `bool` y serán convertidos:
```Python hl_lines="9"
{!../../../docs_src/query_params/tutorial003.py!}
```
En este caso, si vas a:
```
http://127.0.0.1:8000/items/foo?short=1
```
o
```
http://127.0.0.1:8000/items/foo?short=True
```
o
```
http://127.0.0.1:8000/items/foo?short=true
```
o
```
http://127.0.0.1:8000/items/foo?short=on
```
o
```
http://127.0.0.1:8000/items/foo?short=yes
```
o cualquier otra variación (mayúsculas, primera letra en mayúscula, etc.) tu función verá el parámetro `short` con un valor `bool` de `True`. Si no, lo verá como `False`.
## Múltiples parámetros de path y query
Puedes declarar múltiples parámetros de path y parámetros de query al mismo tiempo. **FastAPI** sabe cuál es cuál.
No los tienes que declarar en un orden específico.
Serán detectados por nombre:
```Python hl_lines="8 10"
{!../../../docs_src/query_params/tutorial004.py!}
```
## Parámetros de query requeridos
Cuando declaras un valor por defecto para los parámetros que no son de path (por ahora solo hemos visto parámetros de query), entonces no es requerido.
Si no quieres añadir un valor específico sino solo hacerlo opcional, pon el valor por defecto como `None`.
Pero cuando quieres hacer que un parámetro de query sea requerido, puedes simplemente no declararle un valor por defecto:
```Python hl_lines="6-7"
{!../../../docs_src/query_params/tutorial005.py!}
```
Aquí el parámetro de query `needy` es un parámetro de query requerido, del tipo `str`.
Si abres tu navegador en una URL como:
```
http://127.0.0.1:8000/items/foo-item
```
...sin añadir el parámetro `needy` requerido, verás un error como:
```JSON
{
"detail": [
{
"loc": [
"query",
"needy"
],
"msg": "field required",
"type": "value_error.missing"
}
]
}
```
Dado que `needy` es un parámetro requerido necesitarías declararlo en la URL:
```
http://127.0.0.1:8000/items/foo-item?needy=sooooneedy
```
...esto funcionaría:
```JSON
{
"item_id": "foo-item",
"needy": "sooooneedy"
}
```
Por supuesto que también puedes definir algunos parámetros como requeridos, con un valor por defecto y otros completamente opcionales:
```Python hl_lines="10"
{!../../../docs_src/query_params/tutorial006.py!}
```
En este caso hay 3 parámetros de query:
* `needy`, un `str` requerido.
* `skip`, un `int` con un valor por defecto de `0`.
* `limit`, un `int` opcional.
!!! tip "Consejo"
También podrías usar los `Enum`s de la misma manera que con los [Parámetros de path](path-params.md#predefined-values){.internal-link target=_blank}.

View File

@@ -39,8 +39,10 @@ nav:
- FastAPI: index.md
- Languages:
- en: /
- de: /de/
- es: /es/
- fr: /fr/
- id: /id/
- it: /it/
- ja: /ja/
- ko: /ko/
@@ -55,6 +57,9 @@ nav:
- python-types.md
- Tutorial - Guía de Usuario:
- tutorial/index.md
- tutorial/first-steps.md
- tutorial/path-params.md
- tutorial/query-params.md
- Guía de Usuario Avanzada:
- advanced/index.md
- async.md
@@ -81,7 +86,7 @@ extra:
- icon: fontawesome/brands/discord
link: https://discord.gg/VQjSZaeJmf
- icon: fontawesome/brands/twitter
link: https://twitter.com/tiangolo
link: https://twitter.com/fastapi
- icon: fontawesome/brands/linkedin
link: https://www.linkedin.com/in/tiangolo
- icon: fontawesome/brands/dev
@@ -93,10 +98,14 @@ extra:
alternate:
- link: /
name: en - English
- link: /de/
name: de
- link: /es/
name: es - español
- link: /fr/
name: fr - français
- link: /id/
name: id
- link: /it/
name: it - italiano
- link: /ja/

View File

@@ -0,0 +1,446 @@
# Alternatives, inspiration et comparaisons
Ce qui a inspiré **FastAPI**, comment il se compare à d'autres solutions et ce qu'il en a appris.
## Intro
**FastAPI** n'existerait pas sans les précédentes contributions d'autres projets.
De nombreux outils ont été créés auparavant et ont contribué à inspirer sa création.
J'ai évité la création d'un nouveau framework pendant plusieurs années. J'ai d'abord essayé de combler toutes les
fonctionnalités couvertes par **FastAPI** en utilisant de nombreux frameworks, plug-ins et outils différents.
Mais à un moment donné il n'y avait pas d'autre option que de créer quelque chose qui offrait toutes ces
fonctionnalités, en reprenant et en combinant de la meilleure façon possible les meilleures idées des outils
précédents, en utilisant des fonctionnalités du langage qui n'étaient même pas disponibles auparavant (type hints depuis Python 3.6+).
## Outils précédents
### <a href="https://www.djangoproject.com/" class="external-link" target="_blank">Django</a>
C'est le framework Python le plus populaire et il bénéficie d'une grande confiance. Il est utilisé pour construire
des systèmes tel qu'Instagram.
Il est relativement fortement couplé aux bases de données relationnelles (comme MySQL ou PostgreSQL), de sorte qu'il
n'est pas très facile d'utiliser une base de données NoSQL (comme Couchbase, MongoDB, Cassandra, etc.) comme principal moyen de
stockage.
Il a été créé pour générer le HTML en backend, pas pour créer des API consommées par un frontend moderne (comme React, Vue.js et Angular) ou par d'autres systèmes (comme les appareils <abbr title="Internet of Things">IoT</abbr>) communiquant avec lui.
### <a href="https://www.django-rest-framework.org/" class="external-link" target="_blank">Django REST Framework</a>
Django REST framework a été conçu comme une boîte à outils flexible permettant de construire des API Web à partir de Django, afin d'améliorer ses capacités en matière d'API.
Il est utilisé par de nombreuses entreprises, dont Mozilla, Red Hat et Eventbrite.
Il s'agissait de l'un des premiers exemples de **documentation automatique pour API**, et c'est précisément l'une des
premières idées qui a inspiré "la recherche de" **FastAPI**.
!!! note
Django REST framework a été créé par Tom Christie. Le créateur de Starlette et Uvicorn, sur lesquels **FastAPI** est basé.
!!! check "A inspiré **FastAPI** à"
Avoir une interface de documentation automatique de l'API.
### <a href="https://flask.palletsprojects.com" class="external-link" target="_blank">Flask</a>
Flask est un "micro-framework", il ne comprend pas d'intégrations de bases de données ni beaucoup de choses qui sont fournies par défaut dans Django.
Cette simplicité et cette flexibilité permettent d'utiliser des bases de données NoSQL comme principal système de stockage de données.
Comme il est très simple, son apprentissage est relativement intuitif, bien que la documentation soit quelque peu
technique par moments.
Il est aussi couramment utilisé pour d'autres applications qui n'ont pas nécessairement besoin d'une base de données, de gestion des utilisateurs ou de l'une des nombreuses fonctionnalités préinstallées dans Django. Bien que beaucoup de ces fonctionnalités puissent être ajoutées avec des plug-ins.
Ce découplage des parties, et le fait d'être un "micro-framework" qui puisse être étendu pour couvrir exactement ce
qui est nécessaire, était une caractéristique clé que je voulais conserver.
Compte tenu de la simplicité de Flask, il semblait bien adapté à la création d'API. La prochaine chose à trouver était un "Django REST Framework" pour Flask.
!!! check "A inspiré **FastAPI** à"
Être un micro-framework. Il est donc facile de combiner les outils et les pièces nécessaires.
Proposer un système de routage simple et facile à utiliser.
### <a href="https://requests.readthedocs.io" class="external-link" target="_blank">Requests</a>
**FastAPI** n'est pas réellement une alternative à **Requests**. Leur cadre est très différent.
Il serait en fait plus courant d'utiliser Requests _à l'intérieur_ d'une application FastAPI.
Mais quand même, FastAPI s'est inspiré de Requests.
**Requests** est une bibliothèque pour _interagir_ avec les API (en tant que client), tandis que **FastAPI** est une bibliothèque pour _créer_ des API (en tant que serveur).
Ils sont, plus ou moins, aux extrémités opposées, se complétant l'un l'autre.
Requests a un design très simple et intuitif, il est très facile à utiliser, avec des valeurs par défaut raisonnables, tout en étant très puissant et personnalisable.
C'est pourquoi, comme le dit le site officiel :
> Requests est l'un des packages Python les plus téléchargés de tous les temps
La façon dont vous l'utilisez est très simple. Par exemple, pour faire une requête `GET`, vous devez écrire :
```Python
response = requests.get("http://example.com/some/url")
```
En contrepartie l'API _des opérations de chemin_ de FastAPI pourrait ressembler à ceci :
```Python hl_lines="1"
@app.get("/some/url")
def read_url():
return {"message": "Hello World"}
```
Notez les similitudes entre `requests.get(...)` et `@app.get(...)`.
!!! check "A inspiré **FastAPI** à"
_ Avoir une API simple et intuitive.
_ Utiliser les noms de méthodes HTTP (opérations) directement, de manière simple et intuitive. \* Avoir des valeurs par défaut raisonnables, mais des personnalisations puissantes.
### <a href="https://swagger.io/" class="external-link" target="_blank">Swagger</a> / <a href="https://github.com/OAI/OpenAPI-Specification/" class="external-link" target="_blank">OpenAPI</a>
La principale fonctionnalité que j'ai emprunté à Django REST Framework était la documentation automatique des API.
Puis j'ai découvert qu'il existait une norme pour documenter les API, en utilisant JSON (ou YAML, une extension de JSON) appelée Swagger.
Il existait déjà une interface utilisateur Web pour les API Swagger. Donc, être capable de générer une documentation
Swagger pour une API permettrait d'utiliser cette interface utilisateur web automatiquement.
À un moment donné, Swagger a été cédé à la Fondation Linux, puis a été rebaptisé OpenAPI.
C'est pourquoi, lorsqu'on parle de la version 2.0, il est courant de dire "Swagger", et pour la version 3+ "OpenAPI".
!!! check "A inspiré **FastAPI** à"
Adopter et utiliser une norme ouverte pour les spécifications des API, au lieu d'un schéma personnalisé.
Intégrer des outils d'interface utilisateur basés sur des normes :
* <a href="https://github.com/swagger-api/swagger-ui" class="external-link" target="_blank">Swagger UI</a>
* <a href="https://github.com/Rebilly/ReDoc" class="external-link" target="_blank">ReDoc</a>
Ces deux-là ont été choisis parce qu'ils sont populaires et stables, mais en faisant une recherche rapide, vous pourriez trouver des dizaines d'alternatives supplémentaires pour OpenAPI (que vous pouvez utiliser avec **FastAPI**).
### Frameworks REST pour Flask
Il y a plusieurs frameworks REST pour Flask, mais après avoir investi du temps et du travail pour les étudier, j'ai
découvert que le développement de beaucoup d'entre eux sont suspendus ou abandonnés, avec plusieurs problèmes
permanents qui les rendent inadaptés.
### <a href="https://marshmallow.readthedocs.io/en/3.0/" class="external-link" target="_blank">Marshmallow</a>
L'une des principales fonctionnalités nécessaires aux systèmes API est la "<abbr title="également appelée
marshalling, conversion">sérialisation</abbr>" des données, qui consiste à prendre les données du code (Python) et à
les convertir en quelque chose qui peut être envoyé sur le réseau. Par exemple, convertir un objet contenant des
données provenant d'une base de données en un objet JSON. Convertir des objets `datetime` en strings, etc.
La validation des données est une autre fonctionnalité importante dont ont besoin les API. Elle permet de s'assurer
que les données sont valides, compte tenu de certains paramètres. Par exemple, qu'un champ est un `int`, et non un
string.
Ceci est particulièrement utile pour les données entrantes.
Sans un système de validation des données, vous devriez effectuer toutes les vérifications à la main, dans le code.
Ces fonctionnalités sont ce pourquoi Marshmallow a été construit. C'est une excellente bibliothèque, et je l'ai déjà beaucoup utilisée.
Mais elle a été créée avant que les type hints n'existent en Python. Ainsi, pour définir chaque <abbr title="la définition de
la façon dont les données doivent être formées">schéma</abbr>, vous devez utiliser des utilitaires et des classes spécifiques fournies par Marshmallow.
!!! check "A inspiré **FastAPI** à"
Utilisez du code pour définir des "schémas" qui fournissent automatiquement les types de données et la validation.
### <a href="https://webargs.readthedocs.io/en/latest/" class="external-link" target="_blank">Webargs</a>
Une autre grande fonctionnalité requise par les API est le <abbr title="la lecture et la conversion en données
Python">parsing</abbr> des données provenant des requêtes entrantes.
Webargs est un outil qui a été créé pour fournir cela par-dessus plusieurs frameworks, dont Flask.
Il utilise Marshmallow pour effectuer la validation des données. Et il a été créé par les mêmes développeurs.
C'est un outil formidable et je l'ai beaucoup utilisé aussi, avant d'avoir **FastAPI**.
!!! info
Webargs a été créé par les développeurs de Marshmallow.
!!! check "A inspiré **FastAPI** à"
Disposer d'une validation automatique des données des requêtes entrantes.
### <a href="https://apispec.readthedocs.io/en/stable/" class="external-link" target="_blank">APISpec</a>
Marshmallow et Webargs fournissent la validation, l'analyse et la sérialisation en tant que plug-ins.
Mais la documentation fait toujours défaut. C'est alors qu'APISpec a été créé.
Il s'agit d'un plug-in pour de nombreux frameworks (et il existe également un plug-in pour Starlette).
Le principe est le suivant : vous écrivez la définition du schéma au format YAML dans la docstring de chaque fonction gérant une route.
Et il génère des schémas OpenAPI.
C'est ainsi que cela fonctionne dans Flask, Starlette, Responder, etc.
Mais alors, nous avons à nouveau le problème d'avoir une micro-syntaxe, dans une docstring Python (un gros morceau de YAML).
L'éditeur ne peut guère aider en la matière. Et si nous modifions les paramètres ou les schémas Marshmallow et que nous oublions de modifier également cette docstring YAML, le schéma généré deviendrait obsolète.
!!! info
APISpec a été créé par les développeurs de Marshmallow.
!!! check "A inspiré **FastAPI** à"
Supporter la norme ouverte pour les API, OpenAPI.
### <a href="https://flask-apispec.readthedocs.io/en/latest/" class="external-link" target="_blank">Flask-apispec</a>
C'est un plug-in pour Flask, qui relie Webargs, Marshmallow et APISpec.
Il utilise les informations de Webargs et Marshmallow pour générer automatiquement des schémas OpenAPI, en utilisant APISpec.
C'est un excellent outil, très sous-estimé. Il devrait être beaucoup plus populaire que de nombreux plug-ins Flask. C'est peut-être dû au fait que sa documentation est trop concise et abstraite.
Cela a permis de ne pas avoir à écrire YAML (une autre syntaxe) à l'intérieur des docstrings Python.
Cette combinaison de Flask, Flask-apispec avec Marshmallow et Webargs était ma stack backend préférée jusqu'à la création de **FastAPI**.
Son utilisation a conduit à la création de plusieurs générateurs Flask full-stack. Ce sont les principales stacks que
j'ai (ainsi que plusieurs équipes externes) utilisées jusqu'à présent :
- <a href="https://github.com/tiangolo/full-stack" class="external-link" target="_blank">https://github.com/tiangolo/full-stack</a>
- <a href="https://github.com/tiangolo/full-stack-flask-couchbase" class="external-link" target="_blank">https://github.com/tiangolo/full-stack-flask-couchbase</a>
- <a href="https://github.com/tiangolo/full-stack-flask-couchdb" class="external-link" target="_blank">https://github.com/tiangolo/full-stack-flask-couchdb</a>
Ces mêmes générateurs full-stack ont servi de base aux [Générateurs de projets pour **FastAPI**](project-generation.md){.internal-link target=\_blank}.
!!! info
Flask-apispec a été créé par les développeurs de Marshmallow.
!!! check "A inspiré **FastAPI** à"
Générer le schéma OpenAPI automatiquement, à partir du même code qui définit la sérialisation et la validation.
### <a href="https://nestjs.com/" class="external-link" target="_blank">NestJS</a> (et <a href="https://angular.io/" class="external-link" target="_blank">Angular</a>)
Ce n'est même pas du Python, NestJS est un framework JavaScript (TypeScript) NodeJS inspiré d'Angular.
Il réalise quelque chose de similaire à ce qui peut être fait avec Flask-apispec.
Il possède un système d'injection de dépendances intégré, inspiré d'Angular 2. Il nécessite de pré-enregistrer les "injectables" (comme tous les autres systèmes d'injection de dépendances que je connais), donc, cela ajoute à la verbosité et à la répétition du code.
Comme les paramètres sont décrits avec des types TypeScript (similaires aux type hints de Python), la prise en charge
par l'éditeur est assez bonne.
Mais comme les données TypeScript ne sont pas préservées après la compilation en JavaScript, il ne peut pas compter sur les types pour définir la validation, la sérialisation et la documentation en même temps. En raison de cela et de certaines décisions de conception, pour obtenir la validation, la sérialisation et la génération automatique de schémas, il est nécessaire d'ajouter des décorateurs à de nombreux endroits. Cela devient donc assez verbeux.
Il ne peut pas très bien gérer les modèles imbriqués. Ainsi, si le corps JSON de la requête est un objet JSON comportant des champs internes qui sont à leur tour des objets JSON imbriqués, il ne peut pas être correctement documenté et validé.
!!! check "A inspiré **FastAPI** à"
Utiliser les types Python pour bénéficier d'un excellent support de l'éditeur.
Disposer d'un puissant système d'injection de dépendances. Trouver un moyen de minimiser la répétition du code.
### <a href="https://sanic.readthedocs.io/en/latest/" class="external-link" target="_blank">Sanic</a>
C'était l'un des premiers frameworks Python extrêmement rapides basés sur `asyncio`. Il a été conçu pour être très similaire à Flask.
!!! note "Détails techniques"
Il utilisait <a href="https://github.com/MagicStack/uvloop" class="external-link" target="_blank">`uvloop`</a> au lieu du système par défaut de Python `asyncio`. C'est ce qui l'a rendu si rapide.
Il a clairement inspiré Uvicorn et Starlette, qui sont actuellement plus rapides que Sanic dans les benchmarks.
!!! check "A inspiré **FastAPI** à"
Trouvez un moyen d'avoir une performance folle.
C'est pourquoi **FastAPI** est basé sur Starlette, car il s'agit du framework le plus rapide disponible (testé par des benchmarks tiers).
### <a href="https://falconframework.org/" class="external-link" target="_blank">Falcon</a>
Falcon est un autre framework Python haute performance, il est conçu pour être minimal, et est utilisé comme fondation pour d'autres frameworks comme Hug.
Il utilise le standard précédent pour les frameworks web Python (WSGI) qui est synchrone, donc il ne peut pas gérer les WebSockets et d'autres cas d'utilisation. Néanmoins, il offre de très bonnes performances.
Il est conçu pour avoir des fonctions qui reçoivent deux paramètres, une "requête" et une "réponse". Ensuite, vous
"lisez" des parties de la requête et "écrivez" des parties dans la réponse. En raison de cette conception, il n'est
pas possible de déclarer des paramètres de requête et des corps avec des indications de type Python standard comme paramètres de fonction.
Ainsi, la validation, la sérialisation et la documentation des données doivent être effectuées dans le code, et non pas automatiquement. Ou bien elles doivent être implémentées comme un framework au-dessus de Falcon, comme Hug. Cette même distinction se retrouve dans d'autres frameworks qui s'inspirent de la conception de Falcon, qui consiste à avoir un objet de requête et un objet de réponse comme paramètres.
!!! check "A inspiré **FastAPI** à"
Trouver des moyens d'obtenir de bonnes performances.
Avec Hug (puisque Hug est basé sur Falcon), **FastAPI** a inspiré la déclaration d'un paramètre `response` dans les fonctions.
Bien que dans FastAPI, il est facultatif, et est utilisé principalement pour définir les en-têtes, les cookies, et les codes de statut alternatifs.
### <a href="https://moltenframework.com/" class="external-link" target="_blank">Molten</a>
J'ai découvert Molten lors des premières étapes de développement de **FastAPI**. Et il a des idées assez similaires :
- Basé sur les type hints Python.
- Validation et documentation via ces types.
- Système d'injection de dépendances.
Il n'utilise pas une librairie tiers de validation, sérialisation et de documentation tel que Pydantic, il utilise son propre système. Ainsi, ces définitions de types de données ne sont pas réutilisables aussi facilement.
Il nécessite une configuration un peu plus verbeuse. Et comme il est basé sur WSGI (au lieu dASGI), il n'est pas
conçu pour profiter des hautes performances fournies par des outils comme Uvicorn, Starlette et Sanic.
Le système d'injection de dépendances exige le pré-enregistrement des dépendances et les dépendances sont résolues sur la base des types déclarés. Ainsi, il n'est pas possible de déclarer plus d'un "composant" qui fournit un certain type.
Les routes sont déclarées à un seul endroit, en utilisant des fonctions déclarées à d'autres endroits (au lieu
d'utiliser des décorateurs qui peuvent être placés juste au-dessus de la fonction qui gère l'endpoint). Cette
méthode est plus proche de celle de Django que de celle de Flask (et Starlette). Il sépare dans le code des choses
qui sont relativement fortement couplées.
!!! check "A inspiré **FastAPI** à"
Définir des validations supplémentaires pour les types de données utilisant la valeur "par défaut" des attributs du modèle. Ceci améliore le support de l'éditeur, et n'était pas disponible dans Pydantic auparavant.
Cela a en fait inspiré la mise à jour de certaines parties de Pydantic, afin de supporter le même style de déclaration de validation (toute cette fonctionnalité est maintenant déjà disponible dans Pydantic).
### <a href="https://www.hug.rest/" class="external-link" target="_blank">Hug</a>
Hug a été l'un des premiers frameworks à implémenter la déclaration des types de paramètres d'API en utilisant les type hints Python. C'était une excellente idée qui a inspiré d'autres outils à faire de même.
Il utilisait des types personnalisés dans ses déclarations au lieu des types Python standard, mais c'était tout de même un énorme pas en avant.
Il a également été l'un des premiers frameworks à générer un schéma personnalisé déclarant l'ensemble de l'API en JSON.
Il n'était pas basé sur une norme comme OpenAPI et JSON Schema. Il ne serait donc pas simple de l'intégrer à d'autres outils, comme Swagger UI. Mais encore une fois, c'était une idée très innovante.
Il présente une caractéristique intéressante et peu commune : à l'aide du même framework, il est possible de créer des
API et des CLI.
Comme il est basé sur l'ancienne norme pour les frameworks web Python synchrones (WSGI), il ne peut pas gérer les Websockets et autres, bien qu'il soit également très performant.
!!! info
Hug a été créé par Timothy Crosley, le créateur de <a href="https://github.com/timothycrosley/isort" class="external-link" target="_blank">`isort`</a>, un excellent outil pour trier automatiquement les imports dans les fichiers Python.
!!! check "A inspiré **FastAPI** à"
Hug a inspiré certaines parties d'APIStar, et était l'un des outils que je trouvais les plus prometteurs, à côté d'APIStar.
Hug a contribué à inspirer **FastAPI** pour utiliser les type hints Python
pour déclarer les paramètres, et pour générer automatiquement un schéma définissant l'API.
Hug a inspiré **FastAPI** pour déclarer un paramètre `response` dans les fonctions pour définir les en-têtes et les cookies.
### <a href="https://github.com/encode/apistar" class="external-link" target="_blank">APIStar</a> (<= 0.5)
Juste avant de décider de développer **FastAPI**, j'ai trouvé le serveur **APIStar**. Il contenait presque tout ce
que je recherchais et avait un beau design.
C'était l'une des premières implémentations d'un framework utilisant les type hints Python pour déclarer les paramètres
et les requêtes que j'ai vues (avant NestJS et Molten). Je l'ai trouvé plus ou moins en même temps que Hug. Mais APIStar utilisait le standard OpenAPI.
Il disposait de la validation automatique, sérialisation des données et d'une génération de schéma OpenAPI basée sur les mêmes type hints à plusieurs endroits.
La définition du schéma de corps de requête n'utilisait pas les mêmes type hints Python que Pydantic, il était un peu plus proche de Marshmallow, donc le support de l'éditeur n'était pas aussi bon, mais APIStar était quand même la meilleure option disponible.
Il avait les meilleures performances d'après les benchmarks de l'époque (seulement surpassé par Starlette).
Au départ, il ne disposait pas d'une interface web de documentation automatique de l'API, mais je savais que je pouvais lui ajouter une interface Swagger.
Il avait un système d'injection de dépendances. Il nécessitait un pré-enregistrement des composants, comme d'autres outils discutés ci-dessus. Mais c'était quand même une excellente fonctionnalité.
Je n'ai jamais pu l'utiliser dans un projet complet, car il n'avait pas d'intégration de sécurité, et je ne pouvais donc pas remplacer toutes les fonctionnalités que j'avais avec les générateurs complets basés sur Flask-apispec. J'avais dans mon backlog de projets de créer une pull request pour ajouter cette fonctionnalité.
Mais ensuite, le projet a changé d'orientation.
Il ne s'agissait plus d'un framework web API, le créateur devant se concentrer sur Starlette.
Maintenant, APIStar est un ensemble d'outils pour valider les spécifications OpenAPI, et non un framework web.
!!! info
APIStar a été créé par Tom Christie. Le même gars qui a créé :
* Django REST Framework
* Starlette (sur lequel **FastAPI** est basé)
* Uvicorn (utilisé par Starlette et **FastAPI**)
!!! check "A inspiré **FastAPI** à"
Exister.
L'idée de déclarer plusieurs choses (validation des données, sérialisation et documentation) avec les mêmes types Python, tout en offrant un excellent support pour les éditeurs, était pour moi une idée brillante.
Et après avoir longtemps cherché un framework similaire et testé de nombreuses alternatives, APIStar était la meilleure option disponible.
Puis APIStar a cessé d'exister en tant que serveur et Starlette a été créé, et a constitué une meilleure base pour un tel système. Ce fut l'inspiration finale pour construire **FastAPI**.
Je considère **FastAPI** comme un "successeur spirituel" d'APIStar, tout en améliorant et en augmentant les fonctionnalités, le système de typage et d'autres parties, sur la base des enseignements tirés de tous ces outils précédents.
## Utilisés par **FastAPI**
### <a href="https://pydantic-docs.helpmanual.io/" class="external-link" target="_blank">Pydantic</a>
Pydantic est une bibliothèque permettant de définir la validation, la sérialisation et la documentation des données (à l'aide de JSON Schema) en se basant sur les Python type hints.
Cela le rend extrêmement intuitif.
Il est comparable à Marshmallow. Bien qu'il soit plus rapide que Marshmallow dans les benchmarks. Et comme il est
basé sur les mêmes type hints Python, le support de l'éditeur est grand.
!!! check "**FastAPI** l'utilise pour"
Gérer toute la validation des données, leur sérialisation et la documentation automatique du modèle (basée sur le schéma JSON).
**FastAPI** prend ensuite ces données JSON Schema et les place dans OpenAPI, en plus de toutes les autres choses qu'il fait.
### <a href="https://www.starlette.io/" class="external-link" target="_blank">Starlette</a>
Starlette est un framework/toolkit léger <abbr title="Le nouveau standard pour construire des applications web assynchrones en Python">ASGI</abbr>, qui est idéal pour construire des services asyncio performants.
Il est très simple et intuitif. Il est conçu pour être facilement extensible et avoir des composants modulaires.
Il offre :
- Des performances vraiment impressionnantes.
- Le support des WebSockets.
- Le support de GraphQL.
- Les tâches d'arrière-plan.
- Les événements de démarrage et d'arrêt.
- Un client de test basé sur request.
- CORS, GZip, fichiers statiques, streaming des réponses.
- Le support des sessions et des cookies.
- Une couverture de test à 100 %.
- 100 % de la base de code avec des annotations de type.
- Zéro forte dépendance à d'autres packages.
Starlette est actuellement le framework Python le plus rapide testé. Seulement dépassé par Uvicorn, qui n'est pas un framework, mais un serveur.
Starlette fournit toutes les fonctionnalités de base d'un micro-framework web.
Mais il ne fournit pas de validation automatique des données, de sérialisation ou de documentation.
C'est l'une des principales choses que **FastAPI** ajoute par-dessus, le tout basé sur les type hints Python (en utilisant Pydantic). Cela, plus le système d'injection de dépendances, les utilitaires de sécurité, la génération de schémas OpenAPI, etc.
!!! note "Détails techniques"
ASGI est une nouvelle "norme" développée par les membres de l'équipe principale de Django. Il ne s'agit pas encore d'une "norme Python" (un PEP), bien qu'ils soient en train de le faire.
Néanmoins, il est déjà utilisé comme "standard" par plusieurs outils. Cela améliore grandement l'interopérabilité, puisque vous pouvez remplacer Uvicorn par n'importe quel autre serveur ASGI (comme Daphne ou Hypercorn), ou vous pouvez ajouter des outils compatibles ASGI, comme `python-socketio`.
!!! check "**FastAPI** l'utilise pour"
Gérer toutes les parties web de base. Ajouter des fonctionnalités par-dessus.
La classe `FastAPI` elle-même hérite directement de la classe `Starlette`.
Ainsi, tout ce que vous pouvez faire avec Starlette, vous pouvez le faire directement avec **FastAPI**, car il s'agit en fait de Starlette sous stéroïdes.
### <a href="https://www.uvicorn.org/" class="external-link" target="_blank">Uvicorn</a>
Uvicorn est un serveur ASGI rapide comme l'éclair, basé sur uvloop et httptools.
Il ne s'agit pas d'un framework web, mais d'un serveur. Par exemple, il ne fournit pas d'outils pour le routing. C'est
quelque chose qu'un framework comme Starlette (ou **FastAPI**) fournirait par-dessus.
C'est le serveur recommandé pour Starlette et **FastAPI**.
!!! check "**FastAPI** le recommande comme"
Le serveur web principal pour exécuter les applications **FastAPI**.
Vous pouvez le combiner avec Gunicorn, pour avoir un serveur multi-processus asynchrone.
Pour plus de détails, consultez la section [Déploiement](deployment/index.md){.internal-link target=_blank}.
## Benchmarks et vitesse
Pour comprendre, comparer et voir la différence entre Uvicorn, Starlette et FastAPI, consultez la section sur les [Benchmarks](benchmarks.md){.internal-link target=\_blank}.

View File

@@ -0,0 +1,82 @@
# Articles et liens externes
**FastAPI** possède une grande communauté en constante extension.
Il existe de nombreux articles, outils et projets liés à **FastAPI**.
Voici une liste incomplète de certains d'entre eux.
!!! tip "Astuce"
Si vous avez un article, projet, outil, ou quoi que ce soit lié à **FastAPI** qui n'est actuellement pas listé ici, créez une <a href="https://github.com/tiangolo/fastapi/edit/master/docs/en/data/external_links.yml" class="external-link" target="_blank">Pull Request l'ajoutant</a>.
## Articles
### Anglais
{% if external_links %}
{% for article in external_links.articles.english %}
* <a href="{{ article.link }}" class="external-link" target="_blank">{{ article.title }}</a> par <a href="{{ article.author_link }}" class="external-link" target="_blank">{{ article.author }}</a>.
{% endfor %}
{% endif %}
### Japonais
{% if external_links %}
{% for article in external_links.articles.japanese %}
* <a href="{{ article.link }}" class="external-link" target="_blank">{{ article.title }}</a> par <a href="{{ article.author_link }}" class="external-link" target="_blank">{{ article.author }}</a>.
{% endfor %}
{% endif %}
### Vietnamien
{% if external_links %}
{% for article in external_links.articles.vietnamese %}
* <a href="{{ article.link }}" class="external-link" target="_blank">{{ article.title }}</a> par <a href="{{ article.author_link }}" class="external-link" target="_blank">{{ article.author }}</a>.
{% endfor %}
{% endif %}
### Russe
{% if external_links %}
{% for article in external_links.articles.russian %}
* <a href="{{ article.link }}" class="external-link" target="_blank">{{ article.title }}</a> par <a href="{{ article.author_link }}" class="external-link" target="_blank">{{ article.author }}</a>.
{% endfor %}
{% endif %}
### Allemand
{% if external_links %}
{% for article in external_links.articles.german %}
* <a href="{{ article.link }}" class="external-link" target="_blank">{{ article.title }}</a> par <a href="{{ article.author_link }}" class="external-link" target="_blank">{{ article.author }}</a>.
{% endfor %}
{% endif %}
## Podcasts
{% if external_links %}
{% for article in external_links.podcasts.english %}
* <a href="{{ article.link }}" class="external-link" target="_blank">{{ article.title }}</a> par <a href="{{ article.author_link }}" class="external-link" target="_blank">{{ article.author }}</a>.
{% endfor %}
{% endif %}
## Conférences
{% if external_links %}
{% for article in external_links.talks.english %}
* <a href="{{ article.link }}" class="external-link" target="_blank">{{ article.title }}</a> par <a href="{{ article.author_link }}" class="external-link" target="_blank">{{ article.author }}</a>.
{% endfor %}
{% endif %}
## Projets
Les projets Github avec le topic `fastapi` les plus récents :
<div class="github-topic-projects">
</div>

View File

@@ -114,6 +114,46 @@ Ce sont les **Sponsors**. 😎
Ils soutiennent mon travail avec **FastAPI** (et d'autres) avec <a href="https://github.com/sponsors/tiangolo" class="external-link" target="_blank">GitHub Sponsors</a>.
### Gold Sponsors
{% if sponsors %}
{% for sponsor in sponsors.gold -%}
<a href="{{ sponsor.url }}" target="_blank" title="{{ sponsor.title }}"><img src="{{ sponsor.img }}" style="border-radius:15px"></a>
{% endfor %}
{% endif %}
### Silver Sponsors
{% if sponsors %}
{% for sponsor in sponsors.silver -%}
<a href="{{ sponsor.url }}" target="_blank" title="{{ sponsor.title }}"><img src="{{ sponsor.img }}" style="border-radius:15px"></a>
{% endfor %}
{% endif %}
### Bronze Sponsors
{% if sponsors %}
{% for sponsor in sponsors.bronze -%}
<a href="{{ sponsor.url }}" target="_blank" title="{{ sponsor.title }}"><img src="{{ sponsor.img }}" style="border-radius:15px"></a>
{% endfor %}
{% endif %}
### Individual Sponsors
{% if people %}
{% if people.sponsors_50 %}
<div class="user-list user-list-center">
{% for user in people.sponsors_50 %}
<div class="user"><a href="{{ user.url }}" target="_blank"><div class="avatar-wrapper"><img src="{{ user.avatarUrl }}"/></div><div class="title">@{{ user.login }}</div></a></div>
{% endfor %}
</div>
{% endif %}
{% endif %}
{% if people %}
<div class="user-list user-list-center">
{% for user in people.sponsors %}

View File

@@ -44,13 +44,16 @@ The key features are:
<small>* estimation based on tests on an internal development team, building production applications.</small>
## Gold Sponsors
## Sponsors
<!-- sponsors -->
{% if sponsors %}
{% for sponsor in sponsors.gold -%}
<a href="{{ sponsor.url }}" target="_blank" title="{{ sponsor.title }}"><img src="{{ sponsor.img }}"></a>
<a href="{{ sponsor.url }}" target="_blank" title="{{ sponsor.title }}"><img src="{{ sponsor.img }}" style="border-radius:15px"></a>
{% endfor -%}
{%- for sponsor in sponsors.silver -%}
<a href="{{ sponsor.url }}" target="_blank" title="{{ sponsor.title }}"><img src="{{ sponsor.img }}" style="border-radius:15px"></a>
{% endfor %}
{% endif %}

View File

@@ -0,0 +1,84 @@
# Génération de projets - Modèle
Vous pouvez utiliser un générateur de projet pour commencer, qui réalisera pour vous la mise en place de bases côté architecture globale, sécurité, base de données et premières routes d'API.
Un générateur de projet fera toujours une mise en place très subjective que vous devriez modifier et adapter suivant vos besoins, mais cela reste un bon point de départ pour vos projets.
## Full Stack FastAPI PostgreSQL
GitHub : <a href="https://github.com/tiangolo/full-stack-fastapi-postgresql" class="external-link" target="_blank">https://github.com/tiangolo/full-stack-fastapi-postgresql</a>
### Full Stack FastAPI PostgreSQL - Fonctionnalités
* Intégration **Docker** complète (basée sur Docker).
* Déploiement Docker en mode <a href="https://docs.docker.com/engine/swarm/" class="external-link" target="_blank">Swarm</a>
* Intégration **Docker Compose** et optimisation pour développement local.
* Serveur web Python **prêt au déploiement** utilisant Uvicorn et Gunicorn.
* Backend Python <a href="https://github.com/tiangolo/fastapi" class="external-link" target="_blank">**FastAPI**</a> :
* **Rapide** : Très hautes performances, comparables à **NodeJS** ou **Go** (grâce à Starlette et Pydantic).
* **Intuitif** : Excellent support des éditeurs. <abbr title="aussi appelée auto-complétion, autocomplétion, IntelliSense...">Complétion</abbr> partout. Moins de temps passé à déboguer.
* **Facile** : Fait pour être facile à utiliser et apprendre. Moins de temps passé à lire de la documentation.
* **Concis** : Minimise la duplication de code. Plusieurs fonctionnalités à chaque déclaration de paramètre.
* **Robuste** : Obtenez du code prêt pour être utilisé en production. Avec de la documentation automatique interactive.
* **Basé sur des normes** : Basé sur (et totalement compatible avec) les normes ouvertes pour les APIs : <a href="https://github.com/OAI/OpenAPI-Specification" class="external-link" target="_blank">OpenAPI</a> et <a href="https://json-schema.org/" class="external-link" target="_blank">JSON Schema</a>.
* <a href="https://fastapi.tiangolo.com/features/" class="external-link" target="_blank">**Et bien d'autres fonctionnalités**</a> comme la validation automatique, la sérialisation, l'authentification avec OAuth2 JWT tokens, etc.
* Hashage de **mots de passe sécurisé** par défaut.
* Authentification par **jetons JWT**.
* Modèles **SQLAlchemy** (indépendants des extensions Flask, afin qu'ils puissent être utilisés directement avec des *workers* Celery).
* Modèle de démarrages basiques pour les utilisateurs (à modifier et supprimer au besoin).
* Migrations **Alembic**.
* **CORS** (partage des ressources entre origines multiples, ou *Cross Origin Resource Sharing*).
* *Worker* **Celery** pouvant importer et utiliser les modèles et le code du reste du backend.
* Tests du backend REST basés sur **Pytest**, intégrés dans Docker, pour que vous puissiez tester toutes les interactions de l'API indépendamment de la base de données. Étant exécutés dans Docker, les tests peuvent utiliser un nouvel entrepôt de données créé de zéro à chaque fois (vous pouvez donc utiliser ElasticSearch, MongoDB, CouchDB, etc. et juste tester que l'API fonctionne).
* Intégration Python facile avec **Jupyter Kernels** pour le développement à distance ou intra-Docker avec des extensions comme Atom Hydrogen ou Visual Studio Code Jupyter.
* Frontend **Vue** :
* Généré avec Vue CLI.
* Gestion de l'**Authentification JWT**.
* Page de connexion.
* Après la connexion, page de tableau de bord principal.
* Tableau de bord principal avec création et modification d'utilisateurs.
* Modification de ses propres caractéristiques utilisateur.
* **Vuex**.
* **Vue-router**.
* **Vuetify** pour de magnifiques composants *material design*.
* **TypeScript**.
* Serveur Docker basé sur **Nginx** (configuré pour être facilement manipulé avec Vue-router).
* Utilisation de *Docker multi-stage building*, pour ne pas avoir besoin de sauvegarder ou *commit* du code compilé.
* Tests frontend exécutés à la compilation (pouvant être désactivés).
* Fait aussi modulable que possible, pour pouvoir fonctionner comme tel, tout en pouvant être utilisé qu'en partie grâce à Vue CLI.
* **PGAdmin** pour les bases de données PostgreSQL, facilement modifiable pour utiliser PHPMYAdmin ou MySQL.
* **Flower** pour la surveillance de tâches Celery.
* Équilibrage de charge entre le frontend et le backend avec **Traefik**, afin de pouvoir avoir les deux sur le même domaine, séparés par chemins, mais servis par différents conteneurs.
* Intégration Traefik, comprenant la génération automatique de certificat **HTTPS** Let's Encrypt.
* GitLab **CI** (intégration continue), comprenant des tests pour le frontend et le backend.
## Full Stack FastAPI Couchbase
GitHub : <a href="https://github.com/tiangolo/full-stack-fastapi-couchbase" class="external-link" target="_blank">https://github.com/tiangolo/full-stack-fastapi-couchbase</a>
⚠️ **ATTENTION** ⚠️
Si vous démarrez un nouveau projet de zéro, allez voir les alternatives au début de cette page.
Par exemple, le générateur de projet <a href="https://github.com/tiangolo/full-stack-fastapi-postgresql" class="external-link" target="_blank">Full Stack FastAPI PostgreSQL</a> peut être une meilleure alternative, étant activement maintenu et utilisé et comprenant toutes les nouvelles fonctionnalités et améliorations.
Vous êtes toujours libre d'utiliser le générateur basé sur Couchbase si vous le voulez, cela devrait probablement fonctionner correctement, et si vous avez déjà un projet généré en utilisant ce dernier, cela devrait fonctionner aussi (et vous l'avez déjà probablement mis à jour suivant vos besoins).
Vous pouvez en apprendre plus dans la documentation du dépôt GithHub.
## Full Stack FastAPI MongoDB
...viendra surement plus tard, suivant le temps que j'ai. 😅 🎉
## Modèles d'apprentissage automatique avec spaCy et FastAPI
GitHub : <a href="https://github.com/microsoft/cookiecutter-spacy-fastapi" class="external-link" target="_blank">https://github.com/microsoft/cookiecutter-spacy-fastapi</a>
## Modèles d'apprentissage automatique avec spaCy et FastAPI - Fonctionnalités
* Intégration d'un modèle NER **spaCy**.
* Formatage de requête pour **Azure Cognitive Search**.
* Serveur Python web **prêt à utiliser en production** utilisant Uvicorn et Gunicorn.
* Déploiement CI/CD Kubernetes pour **Azure DevOps** (AKS).
* **Multilangues**. Choisissez facilement l'une des langues intégrées à spaCy durant la mise en place du projet.
* **Facilement généralisable** à d'autres bibliothèques similaires (Pytorch, Tensorflow), et non juste spaCy.

View File

@@ -0,0 +1,314 @@
# Introduction aux Types Python
Python supporte des annotations de type (ou *type hints*) optionnelles.
Ces annotations de type constituent une syntaxe spéciale qui permet de déclarer le <abbr title="par exemple : str, int, float, bool">type</abbr> d'une variable.
En déclarant les types de vos variables, cela permet aux différents outils comme les éditeurs de texte d'offrir un meilleur support.
Ce chapitre n'est qu'un **tutoriel rapide / rappel** sur les annotations de type Python.
Seulement le minimum nécessaire pour les utiliser avec **FastAPI** sera couvert... ce qui est en réalité très peu.
**FastAPI** est totalement basé sur ces annotations de type, qui lui donnent de nombreux avantages.
Mais même si vous n'utilisez pas ou n'utiliserez jamais **FastAPI**, vous pourriez bénéficier d'apprendre quelques choses sur ces dernières.
!!! note
Si vous êtes un expert Python, et que vous savez déjà **tout** sur les annotations de type, passez au chapitre suivant.
## Motivations
Prenons un exemple simple :
```Python
{!../../../docs_src/python_types/tutorial001.py!}
```
Exécuter ce programe affiche :
```
John Doe
```
La fonction :
* Prend un `first_name` et un `last_name`.
* Convertit la première lettre de chaque paramètre en majuscules grâce à `title()`.
* Concatène les résultats avec un espace entre les deux.
```Python hl_lines="2"
{!../../../docs_src/python_types/tutorial001.py!}
```
### Limitations
C'est un programme très simple.
Mais maintenant imaginez que vous l'écriviez de zéro.
À un certain point vous auriez commencé la définition de la fonction, vous aviez les paramètres prêts.
Mais vous aviez besoin de "cette méthode qui convertit la première lettre en majuscule".
Était-ce `upper` ? `uppercase` ? `first_uppercase` ? `capitalize` ?
Vous essayez donc d'utiliser le vieil ami du programmeur, l'auto-complétion de l'éditeur.
Vous écrivez le premier paramètre, `first_name`, puis un point (`.`) et appuyez sur `Ctrl+Espace` pour déclencher l'auto-complétion.
Mais malheureusement, rien d'utile n'en résulte :
<img src="/img/python-types/image01.png">
### Ajouter des types
Modifions une seule ligne de la version précédente.
Nous allons changer seulement cet extrait, les paramètres de la fonction, de :
```Python
first_name, last_name
```
à :
```Python
first_name: str, last_name: str
```
C'est tout.
Ce sont des annotations de types :
```Python hl_lines="1"
{!../../../docs_src/python_types/tutorial002.py!}
```
À ne pas confondre avec la déclaration de valeurs par défaut comme ici :
```Python
first_name="john", last_name="doe"
```
C'est une chose différente.
On utilise un deux-points (`:`), et pas un égal (`=`).
Et ajouter des annotations de types ne crée normalement pas de différence avec le comportement qui aurait eu lieu si elles n'étaient pas là.
Maintenant, imaginez que vous êtes en train de créer cette fonction, mais avec des annotations de type cette fois.
Au même moment que durant l'exemple précédent, vous essayez de déclencher l'auto-complétion et vous voyez :
<img src="/img/python-types/image02.png">
Vous pouvez donc dérouler les options jusqu'à trouver la méthode à laquelle vous pensiez.
<img src="/img/python-types/image03.png">
## Plus de motivations
Cette fonction possède déjà des annotations de type :
```Python hl_lines="1"
{!../../../docs_src/python_types/tutorial003.py!}
```
Comme l'éditeur connaît le type des variables, vous n'avez pas seulement l'auto-complétion, mais aussi de la détection d'erreurs :
<img src="/img/python-types/image04.png">
Maintenant que vous avez connaissance du problème, convertissez `age` en <abbr title="string">chaine de caractères</abbr> grâce à `str(age)` :
```Python hl_lines="2"
{!../../../docs_src/python_types/tutorial004.py!}
```
## Déclarer des types
Vous venez de voir là où les types sont généralement déclarés : dans les paramètres de fonctions.
C'est aussi ici que vous les utiliseriez avec **FastAPI**.
### Types simples
Vous pouvez déclarer tous les types de Python, pas seulement `str`.
Comme par exemple :
* `int`
* `float`
* `bool`
* `bytes`
```Python hl_lines="1"
{!../../../docs_src/python_types/tutorial005.py!}
```
### Types génériques avec des paramètres de types
Il existe certaines structures de données qui contiennent d'autres valeurs, comme `dict`, `list`, `set` et `tuple`. Et les valeurs internes peuvent elles aussi avoir leurs propres types.
Pour déclarer ces types et les types internes, on utilise le module standard de Python `typing`.
Il existe spécialement pour supporter ces annotations de types.
#### `List`
Par exemple, définissons une variable comme `list` de `str`.
Importez `List` (avec un `L` majuscule) depuis `typing`.
```Python hl_lines="1"
{!../../../docs_src/python_types/tutorial006.py!}
```
Déclarez la variable, en utilisant la syntaxe des deux-points (`:`).
Et comme type, mettez `List`.
Les listes étant un type contenant des types internes, mettez ces derniers entre crochets (`[`, `]`) :
```Python hl_lines="4"
{!../../../docs_src/python_types/tutorial006.py!}
```
!!! tip "Astuce"
Ces types internes entre crochets sont appelés des "paramètres de type".
Ici, `str` est un paramètre de type passé à `List`.
Ce qui signifie : "la variable `items` est une `list`, et chacun de ses éléments a pour type `str`.
En faisant cela, votre éditeur pourra vous aider, même pendant que vous traitez des éléments de la liste.
<img src="/img/python-types/image05.png">
Sans types, c'est presque impossible à réaliser.
Vous remarquerez que la variable `item` n'est qu'un des éléments de la list `items`.
Et pourtant, l'éditeur sait qu'elle est de type `str` et pourra donc vous aider à l'utiliser.
#### `Tuple` et `Set`
C'est le même fonctionnement pour déclarer un `tuple` ou un `set` :
```Python hl_lines="1 4"
{!../../../docs_src/python_types/tutorial007.py!}
```
Dans cet exemple :
* La variable `items_t` est un `tuple` avec 3 éléments, un `int`, un deuxième `int`, et un `str`.
* La variable `items_s` est un `set`, et chacun de ses éléments est de type `bytes`.
#### `Dict`
Pour définir un `dict`, il faut lui passer 2 paramètres, séparés par une virgule (`,`).
Le premier paramètre de type est pour les clés et le second pour les valeurs du dictionnaire (`dict`).
```Python hl_lines="1 4"
{!../../../docs_src/python_types/tutorial008.py!}
```
Dans cet exemple :
* La variable `prices` est de type `dict` :
* Les clés de ce dictionnaire sont de type `str`.
* Les valeurs de ce dictionnaire sont de type `float`.
#### `Optional`
Vous pouvez aussi utiliser `Optional` pour déclarer qu'une variable a un type, comme `str` mais qu'il est "optionnel" signifiant qu'il pourrait aussi être `None`.
```Python hl_lines="1 4"
{!../../../docs_src/python_types/tutorial009.py!}
```
Utiliser `Optional[str]` plutôt que `str` permettra à l'éditeur de vous aider à détecter les erreurs où vous supposeriez qu'une valeur est toujours de type `str`, alors qu'elle pourrait aussi être `None`.
#### Types génériques
Les types qui peuvent contenir des paramètres de types entre crochets, comme :
* `List`
* `Tuple`
* `Set`
* `Dict`
* `Optional`
* ...et d'autres.
sont appelés des **types génériques** ou **Generics**.
### Classes en tant que types
Vous pouvez aussi déclarer une classe comme type d'une variable.
Disons que vous avez une classe `Person`, avec une variable `name` :
```Python hl_lines="1-3"
{!../../../docs_src/python_types/tutorial010.py!}
```
Vous pouvez ensuite déclarer une variable de type `Person` :
```Python hl_lines="6"
{!../../../docs_src/python_types/tutorial010.py!}
```
Et vous aurez accès, encore une fois, au support complet offert par l'éditeur :
<img src="/img/python-types/image06.png">
## Les modèles Pydantic
<a href="https://pydantic-docs.helpmanual.io/" class="external-link" target="_blank">Pydantic</a> est une bibliothèque Python pour effectuer de la validation de données.
Vous déclarez la forme de la donnée avec des classes et des attributs.
Chaque attribut possède un type.
Puis vous créez une instance de cette classe avec certaines valeurs et **Pydantic** validera les valeurs, les convertira dans le type adéquat (si c'est nécessaire et possible) et vous donnera un objet avec toute la donnée.
Ainsi, votre éditeur vous offrira un support adapté pour l'objet résultant.
Extrait de la documentation officielle de **Pydantic** :
```Python
{!../../../docs_src/python_types/tutorial011.py!}
```
!!! info
Pour en savoir plus à propos de <a href="https://pydantic-docs.helpmanual.io/" class="external-link" target="_blank">Pydantic, allez jeter un coup d'oeil à sa documentation</a>.
**FastAPI** est basé entièrement sur **Pydantic**.
Vous verrez bien plus d'exemples de son utilisation dans [Tutoriel - Guide utilisateur](tutorial/index.md){.internal-link target=_blank}.
## Les annotations de type dans **FastAPI**
**FastAPI** utilise ces annotations pour faire différentes choses.
Avec **FastAPI**, vous déclarez des paramètres grâce aux annotations de types et vous obtenez :
* **du support de l'éditeur**
* **de la vérification de types**
...et **FastAPI** utilise ces mêmes déclarations pour :
* **Définir les prérequis** : depuis les paramètres de chemins des requêtes, les entêtes, les corps, les dépendances, etc.
* **Convertir des données** : depuis la requête vers les types requis.
* **Valider des données** : venant de chaque requête :
* Générant automatiquement des **erreurs** renvoyées au client quand la donnée est invalide.
* **Documenter** l'API avec OpenAPI :
* ce qui ensuite utilisé par les interfaces utilisateur automatiques de documentation interactive.
Tout cela peut paraître bien abstrait, mais ne vous inquiétez pas, vous verrez tout ça en pratique dans [Tutoriel - Guide utilisateur](tutorial/index.md){.internal-link target=_blank}.
Ce qu'il faut retenir c'est qu'en utilisant les types standard de Python, à un seul endroit (plutôt que d'ajouter plus de classes, de décorateurs, etc.), **FastAPI** fera une grande partie du travail pour vous.
!!! info
Si vous avez déjà lu le tutoriel et êtes revenus ici pour voir plus sur les types, une bonne ressource est la <a href="https://mypy.readthedocs.io/en/latest/cheat_sheet_py3.html" class="external-link" target="_blank">"cheat sheet" de `mypy`</a>.

View File

@@ -39,8 +39,10 @@ nav:
- FastAPI: index.md
- Languages:
- en: /
- de: /de/
- es: /es/
- fr: /fr/
- id: /id/
- it: /it/
- ja: /ja/
- ko: /ko/
@@ -53,8 +55,12 @@ nav:
- zh: /zh/
- features.md
- fastapi-people.md
- python-types.md
- Tutoriel - Guide utilisateur:
- tutorial/background-tasks.md
- project-generation.md
- alternatives.md
- external-links.md
markdown_extensions:
- toc:
permalink: true
@@ -78,7 +84,7 @@ extra:
- icon: fontawesome/brands/discord
link: https://discord.gg/VQjSZaeJmf
- icon: fontawesome/brands/twitter
link: https://twitter.com/tiangolo
link: https://twitter.com/fastapi
- icon: fontawesome/brands/linkedin
link: https://www.linkedin.com/in/tiangolo
- icon: fontawesome/brands/dev
@@ -90,10 +96,14 @@ extra:
alternate:
- link: /
name: en - English
- link: /de/
name: de
- link: /es/
name: es - español
- link: /fr/
name: fr - français
- link: /id/
name: id
- link: /it/
name: it - italiano
- link: /ja/

467
docs/id/docs/index.md Normal file
View File

@@ -0,0 +1,467 @@
{!../../../docs/missing-translation.md!}
<p align="center">
<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://github.com/tiangolo/fastapi/actions?query=workflow%3ATest" target="_blank">
<img src="https://github.com/tiangolo/fastapi/workflows/Test/badge.svg" alt="Test">
</a>
<a href="https://codecov.io/gh/tiangolo/fastapi" target="_blank">
<img src="https://img.shields.io/codecov/c/github/tiangolo/fastapi?color=%2334D058" alt="Coverage">
</a>
<a href="https://pypi.org/project/fastapi" target="_blank">
<img src="https://img.shields.io/pypi/v/fastapi?color=%2334D058&label=pypi%20package" alt="Package version">
</a>
</p>
---
**Documentation**: <a href="https://fastapi.tiangolo.com" target="_blank">https://fastapi.tiangolo.com</a>
**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+ based on standard Python type hints.
The key features are:
* **Fast**: Very high performance, on par with **NodeJS** and **Go** (thanks to Starlette and Pydantic). [One of the fastest Python frameworks available](#performance).
* **Fast to code**: Increase the speed to develop features by about 200% to 300%. *
* **Fewer bugs**: Reduce about 40% of human (developer) induced errors. *
* **Intuitive**: Great editor support. <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. 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" class="external-link" target="_blank">OpenAPI</a> (previously known as Swagger) and <a href="https://json-schema.org/" class="external-link" target="_blank">JSON Schema</a>.
<small>* estimation based on tests on an internal development team, building production applications.</small>
## Sponsors
<!-- sponsors -->
{% if sponsors %}
{% for sponsor in sponsors.gold -%}
<a href="{{ sponsor.url }}" target="_blank" title="{{ sponsor.title }}"><img src="{{ sponsor.img }}" style="border-radius:15px"></a>
{% endfor -%}
{%- for sponsor in sponsors.silver -%}
<a href="{{ sponsor.url }}" target="_blank" title="{{ sponsor.title }}"><img src="{{ sponsor.img }}" style="border-radius:15px"></a>
{% endfor %}
{% endif %}
<!-- /sponsors -->
<a href="https://fastapi.tiangolo.com/fastapi-people/#sponsors" class="external-link" target="_blank">Other sponsors</a>
## 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>
---
"_We adopted the **FastAPI** library to spawn a **REST** server that can be queried to obtain **predictions**. [for Ludwig]_"
<div style="text-align: right; margin-right: 10%;">Piero Molino, Yaroslav Dudin, and Sai Sumanth Miryala - <strong>Uber</strong> <a href="https://eng.uber.com/ludwig-v0-2/" target="_blank"><small>(ref)</small></a></div>
---
"_**Netflix** is pleased to announce the open-source release of our **crisis management** orchestration framework: **Dispatch**! [built with **FastAPI**]_"
<div style="text-align: right; margin-right: 10%;">Kevin Glisson, Marc Vilanova, Forest Monsen - <strong>Netflix</strong> <a href="https://netflixtechblog.com/introducing-dispatch-da4b8a2a8072" target="_blank"><small>(ref)</small></a></div>
---
"_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="https://www.hug.rest/" target="_blank">Hug</a> creator</strong> <a href="https://news.ycombinator.com/item?id=19455465" target="_blank"><small>(ref)</small></a></div>
---
"_If you're looking to learn one **modern framework** for building REST APIs, check out **FastAPI** [...] It's fast, easy to use and easy to learn [...]_"
"_We've switched over to **FastAPI** for our **APIs** [...] I think you'll like it [...]_"
<div style="text-align: right; margin-right: 10%;">Ines Montani - Matthew Honnibal - <strong><a href="https://explosion.ai" target="_blank">Explosion AI</a> founders - <a href="https://spacy.io" target="_blank">spaCy</a> creators</strong> <a href="https://twitter.com/_inesmontani/status/1144173225322143744" target="_blank"><small>(ref)</small></a> - <a href="https://twitter.com/honnibal/status/1144031421859655680" target="_blank"><small>(ref)</small></a></div>
---
## **Typer**, the FastAPI of CLIs
<a href="https://typer.tiangolo.com" target="_blank"><img src="https://typer.tiangolo.com/img/logo-margin/logo-margin-vector.svg" style="width: 20%;"></a>
If you are building a <abbr title="Command Line Interface">CLI</abbr> app to be used in the terminal instead of a web API, check out <a href="https://typer.tiangolo.com/" class="external-link" target="_blank">**Typer**</a>.
**Typer** is FastAPI's little sibling. And it's intended to be the **FastAPI of CLIs**. ⌨️ 🚀
## Requirements
Python 3.6+
FastAPI stands on the shoulders of giants:
* <a href="https://www.starlette.io/" class="external-link" target="_blank">Starlette</a> for the web parts.
* <a href="https://pydantic-docs.helpmanual.io/" class="external-link" target="_blank">Pydantic</a> for the data parts.
## Installation
<div class="termy">
```console
$ pip install fastapi
---> 100%
```
</div>
You will also need an ASGI server, for production such as <a href="https://www.uvicorn.org" class="external-link" target="_blank">Uvicorn</a> or <a href="https://gitlab.com/pgjones/hypercorn" class="external-link" target="_blank">Hypercorn</a>.
<div class="termy">
```console
$ pip install uvicorn[standard]
---> 100%
```
</div>
## Example
### Create it
* Create a file `main.py` with:
```Python
from typing import Optional
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: Optional[str] = None):
return {"item_id": item_id, "q": q}
```
<details markdown="1">
<summary>Or use <code>async def</code>...</summary>
If your code uses `async` / `await`, use `async def`:
```Python hl_lines="9 14"
from typing import Optional
from fastapi import FastAPI
app = FastAPI()
@app.get("/")
async def read_root():
return {"Hello": "World"}
@app.get("/items/{item_id}")
async def read_item(item_id: int, q: Optional[str] = None):
return {"item_id": item_id, "q": q}
```
**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 it
Run the server with:
<div class="termy">
```console
$ uvicorn main:app --reload
INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit)
INFO: Started reloader process [28720]
INFO: Started server process [28722]
INFO: Waiting for application startup.
INFO: Application startup complete.
```
</div>
<details markdown="1">
<summary>About the command <code>uvicorn main:app --reload</code>...</summary>
The command `uvicorn main:app` refers to:
* `main`: the file `main.py` (the Python "module").
* `app`: the object created inside of `main.py` with the line `app = FastAPI()`.
* `--reload`: make the server restart after code changes. Only do this for development.
</details>
### Check it
Open your browser at <a href="http://127.0.0.1:8000/items/5?q=somequery" class="external-link" target="_blank">http://127.0.0.1:8000/items/5?q=somequery</a>.
You will see the JSON response as:
```JSON
{"item_id": 5, "q": "somequery"}
```
You already created an API that:
* Receives HTTP requests in the _paths_ `/` and `/items/{item_id}`.
* Both _paths_ take `GET` <em>operations</em> (also known as HTTP _methods_).
* The _path_ `/items/{item_id}` has a _path parameter_ `item_id` that should be an `int`.
* The _path_ `/items/{item_id}` has an optional `str` _query parameter_ `q`.
### Interactive API docs
Now go to <a href="http://127.0.0.1:8000/docs" class="external-link" target="_blank">http://127.0.0.1:8000/docs</a>.
You will see the automatic interactive API documentation (provided by <a href="https://github.com/swagger-api/swagger-ui" class="external-link" target="_blank">Swagger UI</a>):
![Swagger UI](https://fastapi.tiangolo.com/img/index/index-01-swagger-ui-simple.png)
### Alternative API docs
And now, go to <a href="http://127.0.0.1:8000/redoc" class="external-link" target="_blank">http://127.0.0.1:8000/redoc</a>.
You will see the alternative automatic documentation (provided by <a href="https://github.com/Rebilly/ReDoc" class="external-link" target="_blank">ReDoc</a>):
![ReDoc](https://fastapi.tiangolo.com/img/index/index-02-redoc-simple.png)
## Example upgrade
Now modify the file `main.py` to receive a body from a `PUT` request.
Declare the body using standard Python types, thanks to Pydantic.
```Python hl_lines="4 9-12 25-27"
from typing import Optional
from fastapi import FastAPI
from pydantic import BaseModel
app = FastAPI()
class Item(BaseModel):
name: str
price: float
is_offer: Optional[bool] = None
@app.get("/")
def read_root():
return {"Hello": "World"}
@app.get("/items/{item_id}")
def read_item(item_id: int, q: Optional[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 `--reload` to the `uvicorn` command above).
### Interactive API docs upgrade
Now go to <a href="http://127.0.0.1:8000/docs" class="external-link" target="_blank">http://127.0.0.1:8000/docs</a>.
* 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)
* Click on the button "Try it out", it allows you to fill the parameters and directly interact with the API:
![Swagger UI interaction](https://fastapi.tiangolo.com/img/index/index-04-swagger-03.png)
* Then click on the "Execute" button, the user interface will communicate with your API, send the parameters, get the results and show them on the screen:
![Swagger UI interaction](https://fastapi.tiangolo.com/img/index/index-05-swagger-04.png)
### Alternative API docs upgrade
And now, go to <a href="http://127.0.0.1:8000/redoc" class="external-link" target="_blank">http://127.0.0.1:8000/redoc</a>.
* The alternative documentation will also reflect the new query parameter and body:
![ReDoc](https://fastapi.tiangolo.com/img/index/index-06-redoc-02.png)
### Recap
In summary, you declare **once** the types of parameters, body, etc. as function parameters.
You do that with standard modern Python types.
You don't have to learn a new syntax, the methods or classes of a specific library, etc.
Just standard **Python 3.6+**.
For example, for an `int`:
```Python
item_id: int
```
or for a more complex `Item` model:
```Python
item: Item
```
...and with that single declaration you get:
* Editor support, including:
* Completion.
* Type checks.
* Validation of data:
* Automatic and clear errors when the data is invalid.
* Validation even for deeply nested JSON objects.
* <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.
* Cookies.
* Headers.
* Forms.
* Files.
* <abbr title="also known as: serialization, parsing, marshalling">Conversion</abbr> of output data: converting from Python data and types to network data (as JSON):
* Convert Python types (`str`, `int`, `float`, `bool`, `list`, etc).
* `datetime` objects.
* `UUID` objects.
* Database models.
* ...and many more.
* Automatic interactive API documentation, including 2 alternative user interfaces:
* Swagger UI.
* ReDoc.
---
Coming back to the previous code example, **FastAPI** will:
* 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`) 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 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 it 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 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.
---
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}
```
...from:
```Python
... "item_name": item.name ...
```
...to:
```Python
... "item_price": item.price ...
```
...and see how your editor will auto-complete the attributes and know their types:
![editor support](https://fastapi.tiangolo.com/img/vscode-completion.png)
For a more complete example including more features, see the <a href="https://fastapi.tiangolo.com/tutorial/">Tutorial - User Guide</a>.
**Spoiler alert**: the tutorial - user guide includes:
* Declaration of **parameters** from other different places as: **headers**, **cookies**, **form fields** and **files**.
* How to set **validation constraints** as `maximum_length` or `regex`.
* A very powerful and easy to use **<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).
* Many extra features (thanks to Starlette) as:
* **WebSockets**
* **GraphQL**
* extremely easy tests based on `requests` and `pytest`
* **CORS**
* **Cookie Sessions**
* ...and more.
## Performance
Independent TechEmpower benchmarks show **FastAPI** applications running under Uvicorn as <a href="https://www.techempower.com/benchmarks/#section=test&runid=7464e520-0dc2-473d-bd34-dbdfd7e85911&hw=ph&test=query&l=zijzen-7" class="external-link" target="_blank">one of the fastest Python frameworks available</a>, only below Starlette and Uvicorn themselves (used internally by FastAPI). (*)
To understand more about it, see the section <a href="https://fastapi.tiangolo.com/benchmarks/" class="internal-link" target="_blank">Benchmarks</a>.
## Optional Dependencies
Used by Pydantic:
* <a href="https://github.com/esnme/ultrajson" target="_blank"><code>ujson</code></a> - for faster JSON <abbr title="converting the string that comes from an HTTP request into Python data">"parsing"</abbr>.
* <a href="https://github.com/JoshData/python-email-validator" target="_blank"><code>email_validator</code></a> - for email validation.
Used by Starlette:
* <a href="https://requests.readthedocs.io" target="_blank"><code>requests</code></a> - Required if you want to use the `TestClient`.
* <a href="https://github.com/Tinche/aiofiles" target="_blank"><code>aiofiles</code></a> - Required if you want to use `FileResponse` or `StaticFiles`.
* <a href="https://jinja.palletsprojects.com" target="_blank"><code>jinja2</code></a> - Required if you want to use the default template configuration.
* <a href="https://andrew-d.github.io/python-multipart/" target="_blank"><code>python-multipart</code></a> - Required if you want to support form <abbr title="converting the string that comes from an HTTP request into Python data">"parsing"</abbr>, with `request.form()`.
* <a href="https://pythonhosted.org/itsdangerous/" target="_blank"><code>itsdangerous</code></a> - Required for `SessionMiddleware` support.
* <a href="https://pyyaml.org/wiki/PyYAMLDocumentation" target="_blank"><code>pyyaml</code></a> - Required for Starlette's `SchemaGenerator` support (you probably don't need it with FastAPI).
* <a href="https://graphene-python.org/" target="_blank"><code>graphene</code></a> - Required for `GraphQLApp` support.
* <a href="https://github.com/esnme/ultrajson" target="_blank"><code>ujson</code></a> - Required if you want to use `UJSONResponse`.
Used by FastAPI / Starlette:
* <a href="https://www.uvicorn.org" target="_blank"><code>uvicorn</code></a> - for the server that loads and serves your application.
* <a href="https://github.com/ijl/orjson" target="_blank"><code>orjson</code></a> - Required if you want to use `ORJSONResponse`.
You can install all of these with `pip install fastapi[all]`.
## License
This project is licensed under the terms of the MIT license.

125
docs/id/mkdocs.yml Normal file
View File

@@ -0,0 +1,125 @@
site_name: FastAPI
site_description: FastAPI framework, high performance, easy to learn, fast to code, ready for production
site_url: https://fastapi.tiangolo.com/id/
theme:
name: material
custom_dir: overrides
palette:
- scheme: default
primary: teal
accent: amber
toggle:
icon: material/lightbulb-outline
name: Switch to light mode
- scheme: slate
primary: teal
accent: amber
toggle:
icon: material/lightbulb
name: Switch to dark mode
features:
- search.suggest
- search.highlight
icon:
repo: fontawesome/brands/github-alt
logo: https://fastapi.tiangolo.com/img/icon-white.svg
favicon: https://fastapi.tiangolo.com/img/favicon.png
language: id
repo_name: tiangolo/fastapi
repo_url: https://github.com/tiangolo/fastapi
edit_uri: ''
google_analytics:
- UA-133183413-1
- auto
plugins:
- search
- markdownextradata:
data: data
nav:
- FastAPI: index.md
- Languages:
- en: /
- de: /de/
- es: /es/
- fr: /fr/
- id: /id/
- it: /it/
- ja: /ja/
- ko: /ko/
- pl: /pl/
- pt: /pt/
- ru: /ru/
- sq: /sq/
- tr: /tr/
- uk: /uk/
- zh: /zh/
markdown_extensions:
- toc:
permalink: true
- markdown.extensions.codehilite:
guess_lang: false
- markdown_include.include:
base_path: docs
- admonition
- codehilite
- extra
- pymdownx.superfences:
custom_fences:
- name: mermaid
class: mermaid
format: !!python/name:pymdownx.superfences.fence_div_format ''
- pymdownx.tabbed
extra:
social:
- icon: fontawesome/brands/github-alt
link: https://github.com/tiangolo/fastapi
- icon: fontawesome/brands/discord
link: https://discord.gg/VQjSZaeJmf
- icon: fontawesome/brands/twitter
link: https://twitter.com/fastapi
- icon: fontawesome/brands/linkedin
link: https://www.linkedin.com/in/tiangolo
- icon: fontawesome/brands/dev
link: https://dev.to/tiangolo
- icon: fontawesome/brands/medium
link: https://medium.com/@tiangolo
- icon: fontawesome/solid/globe
link: https://tiangolo.com
alternate:
- link: /
name: en - English
- link: /de/
name: de
- link: /es/
name: es - español
- link: /fr/
name: fr - français
- link: /id/
name: id
- link: /it/
name: it - italiano
- link: /ja/
name: ja - 日本語
- link: /ko/
name: ko - 한국어
- link: /pl/
name: pl
- link: /pt/
name: pt - português
- link: /ru/
name: ru - русский язык
- link: /sq/
name: sq - shqip
- link: /tr/
name: tr - Türkçe
- link: /uk/
name: uk - українська мова
- link: /zh/
name: zh - 汉语
extra_css:
- https://fastapi.tiangolo.com/css/termynal.css
- https://fastapi.tiangolo.com/css/custom.css
extra_javascript:
- https://unpkg.com/mermaid@8.4.6/dist/mermaid.min.js
- https://fastapi.tiangolo.com/js/termynal.js
- https://fastapi.tiangolo.com/js/custom.js

0
docs/id/overrides/.gitignore vendored Normal file
View File

View File

@@ -44,13 +44,16 @@ The key features are:
<small>* estimation based on tests on an internal development team, building production applications.</small>
## Gold Sponsors
## Sponsors
<!-- sponsors -->
{% if sponsors %}
{% for sponsor in sponsors.gold -%}
<a href="{{ sponsor.url }}" target="_blank" title="{{ sponsor.title }}"><img src="{{ sponsor.img }}"></a>
<a href="{{ sponsor.url }}" target="_blank" title="{{ sponsor.title }}"><img src="{{ sponsor.img }}" style="border-radius:15px"></a>
{% endfor -%}
{%- for sponsor in sponsors.silver -%}
<a href="{{ sponsor.url }}" target="_blank" title="{{ sponsor.title }}"><img src="{{ sponsor.img }}" style="border-radius:15px"></a>
{% endfor %}
{% endif %}

View File

@@ -39,8 +39,10 @@ nav:
- FastAPI: index.md
- Languages:
- en: /
- de: /de/
- es: /es/
- fr: /fr/
- id: /id/
- it: /it/
- ja: /ja/
- ko: /ko/
@@ -74,7 +76,7 @@ extra:
- icon: fontawesome/brands/discord
link: https://discord.gg/VQjSZaeJmf
- icon: fontawesome/brands/twitter
link: https://twitter.com/tiangolo
link: https://twitter.com/fastapi
- icon: fontawesome/brands/linkedin
link: https://www.linkedin.com/in/tiangolo
- icon: fontawesome/brands/dev
@@ -86,10 +88,14 @@ extra:
alternate:
- link: /
name: en - English
- link: /de/
name: de
- link: /es/
name: es - español
- link: /fr/
name: fr - français
- link: /id/
name: id
- link: /it/
name: it - italiano
- link: /ja/

View File

@@ -179,7 +179,7 @@ HTTPリダイレクトを返します。デフォルトでは307ステータス
これにはクラウドストレージとの連携や映像処理など、多くのライブラリが含まれています。
```Python hl_lines="2 10-11"
```Python hl_lines="2 10-12 14"
{!../../../docs_src/custom_response/tutorial008.py!}
```

View File

@@ -119,7 +119,7 @@ FastAPIには、様々なバックグラウンドの人々を歓迎する素晴
{% if sponsors %}
{% for sponsor in sponsors.gold -%}
<a href="{{ sponsor.url }}" target="_blank" title="{{ sponsor.title }}"><img src="{{ sponsor.img }}"></a>
<a href="{{ sponsor.url }}" target="_blank" title="{{ sponsor.title }}"><img src="{{ sponsor.img }}" style="border-radius:15px"></a>
{% endfor %}
{% endif %}
@@ -127,15 +127,23 @@ FastAPIには、様々なバックグラウンドの人々を歓迎する素晴
{% if sponsors %}
{% for sponsor in sponsors.silver -%}
<a href="{{ sponsor.url }}" target="_blank" title="{{ sponsor.title }}"><img src="{{ sponsor.img }}"></a>
<a href="{{ sponsor.url }}" target="_blank" title="{{ sponsor.title }}"><img src="{{ sponsor.img }}" style="border-radius:15px"></a>
{% endfor %}
{% endif %}
### Bronze Sponsors
{% if sponsors %}
{% for sponsor in sponsors.bronze -%}
<a href="{{ sponsor.url }}" target="_blank" title="{{ sponsor.title }}"><img src="{{ sponsor.img }}" style="border-radius:15px"></a>
{% endfor %}
{% endif %}
### Individual Sponsors
{% if people %}
{% if people.sponsors_50 %}
### Bronze Sponsors
<div class="user-list user-list-center">
{% for user in people.sponsors_50 %}
@@ -147,8 +155,6 @@ FastAPIには、様々なバックグラウンドの人々を歓迎する素晴
{% endif %}
{% endif %}
### Individual Sponsors
{% if people %}
<div class="user-list user-list-center">
{% for user in people.sponsors %}

View File

@@ -40,13 +40,16 @@ FastAPI は、Pythonの標準である型ヒントに基づいてPython 3.6 以
<small>\* 本番アプリケーションを構築している開発チームのテストによる見積もり。</small>
## Gold Sponsors
## Sponsors
<!-- sponsors -->
{% if sponsors %}
{% for sponsor in sponsors.gold -%}
<a href="{{ sponsor.url }}" target="_blank" title="{{ sponsor.title }}"><img src="{{ sponsor.img }}"></a>
<a href="{{ sponsor.url }}" target="_blank" title="{{ sponsor.title }}"><img src="{{ sponsor.img }}" style="border-radius:15px"></a>
{% endfor -%}
{%- for sponsor in sponsors.silver -%}
<a href="{{ sponsor.url }}" target="_blank" title="{{ sponsor.title }}"><img src="{{ sponsor.img }}" style="border-radius:15px"></a>
{% endfor %}
{% endif %}

View File

@@ -0,0 +1,266 @@
# パスワードおよびハッシュ化によるOAuth2、JWTトークンによるBearer
これでセキュリティの流れが全てわかったので、<abbr title="JSON Web Tokens">JWT</abbr>トークンと安全なパスワードのハッシュ化を使用して、実際にアプリケーションを安全にしてみましょう。
このコードは、アプリケーションで実際に使用したり、パスワードハッシュをデータベースに保存するといった用途に利用できます。
本章では、前章の続きから始めて、コードをアップデートしていきます。
## JWT について
JWTとは「JSON Web Tokens」の略称です。
JSONオブジェクトをスペースのない長く密集した文字列で表現したトークンの仕様です。例えば次のようになります
```
eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c
```
これらは暗号化されていないので、誰でもコンテンツから情報を復元できてしまいます。
しかし、トークンは署名されているため、あなたが発行したトークンを受け取った人は、あなたが実際に発行したということを検証できます。
例えば、1週間の有効期限を持つトークンを作成したとします。ユーザーが翌日そのトークンを持って戻ってきたとき、そのユーザーはまだシステムにログインしていることがわかります。
1週間後、トークンが期限切れとなるとどうなるでしょうかユーザーは認可されず、新しいトークンを得るために再びサインインしなければなりません。また、ユーザーまたは第三者がトークンを修正して有効期限を変更しようとした場合、署名が一致しないため、トークンの修正を検知できます。
JWT トークンを使って遊んでみたいという方は、<a href="https://jwt.io/" class="external-link" target="_blank">https://jwt.io</a> をチェックしてください。
## `python-jose` のインストール
PythonでJWTトークンの生成と検証を行うために、`python-jose`をインストールする必要があります:
<div class="termy">
```console
$ pip install python-jose[cryptography]
---> 100%
```
</div>
また、<a href="https://github.com/mpdavis/python-jose" class="external-link" target="_blank">Python-jose</a>だけではなく、暗号を扱うためのパッケージを追加で必要とします。
ここでは、推奨されているものを使用します:<a href="https://cryptography.io/" class="external-link" target="_blank">pyca/cryptography</a>。
!!! tip "豆知識"
このチュートリアルでは以前、<a href="https://pyjwt.readthedocs.io/" class="external-link" target="_blank">PyJWT</a>を使用していました。
しかし、Python-joseは、PyJWTのすべての機能に加えて、後に他のツールと統合して構築する際におそらく必要となる可能性のあるいくつかの追加機能を提供しています。そのため、代わりにPython-joseを使用するように更新されました。
## パスワードのハッシュ化
「ハッシュ化」とは、あるコンテンツ(ここではパスワード)を、規則性のないバイト列(単なる文字列)に変換することです。
特徴として、全く同じ内容(全く同じパスワード)を渡すと、全く同じ規則性のないバイト列に変換されます。
しかし、規則性のないバイト列から元のパスワードに戻すことはできません。
### パスワードのハッシュ化を使う理由
データベースが盗まれても、ユーザーの平文のパスワードは盗まれず、ハッシュ値だけが盗まれます。
したがって、泥棒はそのパスワードを別のシステムで使えません(多くのユーザーはどこでも同じパスワードを使用しているため、危険性があります)。
## `passlib` のインストール
PassLib は、パスワードのハッシュを処理するための優れたPythonパッケージです。
このパッケージは、多くの安全なハッシュアルゴリズムとユーティリティをサポートします。
推奨されるアルゴリズムは「Bcrypt」です。
そのため、Bcryptを指定してPassLibをインストールします
<div class="termy">
```console
$ pip install passlib[bcrypt]
---> 100%
```
</div>
!!! tip "豆知識"
`passlib`を使用すると、**Django**や**Flask**のセキュリティプラグインなどで作成されたパスワードを読み取れるように設定できます。
例えば、Djangoアプリケーションからデータベース内の同じデータをFastAPIアプリケーションと共有できるだけではなく、同じデータベースを使用してDjangoアプリケーションを徐々に移行することもできます。
また、ユーザーはDjangoアプリまたは**FastAPI**アプリからも、同時にログインできるようになります。
## パスワードのハッシュ化と検証
必要なツールを `passlib`からインポートします。
PassLib の「context」を作成します。これは、パスワードのハッシュ化と検証に使用されるものです。
!!! tip "豆知識"
PassLibのcontextには、検証だけが許された非推奨の古いハッシュアルゴリズムを含む、様々なハッシュアルゴリズムを使用した検証機能もあります。
例えば、この機能を使用して、別のシステムDjangoなどによって生成されたパスワードを読み取って検証し、Bcryptなどの別のアルゴリズムを使用して新しいパスワードをハッシュするといったことができます。
そして、同時にそれらはすべてに互換性があります。
ユーザーから送られてきたパスワードをハッシュ化するユーティリティー関数を作成します。
また、受け取ったパスワードが保存されているハッシュと一致するかどうかを検証するユーティリティも作成します。
さらに、ユーザーを認証して返す関数も作成します。
```Python hl_lines="7 48 55-56 59-60 69-75"
{!../../../docs_src/security/tutorial004.py!}
```
!!! note "備考"
新しい(偽の)データベース`fake_users_db`を確認すると、ハッシュ化されたパスワードが次のようになっていることがわかります:`"$2b$12$EixZaYVK1fsbw1ZfbX3OXePaWxn96p36WQoeG6Lruj3vjPGga31lW"`
## JWTトークンの取り扱い
インストールした複数のモジュールをインポートします。
JWTトークンの署名に使用されるランダムな秘密鍵を生成します。
安全なランダム秘密鍵を生成するには、次のコマンドを使用します:
<div class="termy">
```console
$ openssl rand -hex 32
09d25e094faa6ca2556c818166b7a9563b93f7099f6f0f4caa6cf63b88e8d3e7
```
</div>
そして、出力された文字列を変数`SECRET_KEY`にコピーします。(例に記載している秘密鍵は実際に使用しないでください)
JWTトークンの署名に使用するアルゴリズム`"HS256"`を指定した変数`ALGORITHM`を作成します。
トークンの有効期限を指定した変数`ACCESS_TOKEN_EXPIRE_MINUTES`を作成します。
レスポンスのトークンエンドポイントで使用するPydanticモデルを定義します。
新しいアクセストークンを生成するユーティリティ関数を作成します。
```Python hl_lines="6 12-14 28-30 78-86"
{!../../../docs_src/security/tutorial004.py!}
```
## 依存関係の更新
`get_current_user`を更新して、先ほどと同じトークンを受け取るようにしますが、今回はJWTトークンを使用します。
受け取ったトークンを復号して検証し、現在のユーザーを返します。
トークンが無効な場合は、すぐにHTTPエラーを返します。
```Python hl_lines="89-106"
{!../../../docs_src/security/tutorial004.py!}
```
## `/token` パスオペレーションの更新
トークンの有効期限を表す`timedelta`を作成します。
JWTアクセストークンを作成し、それを返します。
```Python hl_lines="115-128"
{!../../../docs_src/security/tutorial004.py!}
```
### JWTの"subject" `sub` についての技術的な詳細
JWTの仕様では、トークンのsubjectを表すキー`sub`があるとされています。
使用するかどうかは任意ですが、`sub`はユーザーの識別情報を入れるように規定されているので、ここで使用します。
JWTは、ユーザーを識別して、そのユーザーがAPI上で直接操作を実行できるようにする以外にも、他の用途で使用されることがあります。
例えば、「車」や「ブログ記事」を識別することができます。
そして、「ドライブ」(車の場合)や「編集」(ブログの場合)など、そのエンティティに関する権限も追加できます。
また、JWTトークンをユーザーまたはボットに渡すことができます。ユーザーは、JWTトークンを使用するだけで、アカウントを持っていなくても、APIが生成したJWTトークンを使ってそれらの行動車の運転、ブログ投稿の編集を実行できるのです。
これらのアイデアを使用すると、JWTをより高度なシナリオに使用できます。
しかしながら、それらのエンティティのいくつかが同じIDを持つ可能性があります。例えば、`foo`(ユーザー`foo`、車 `foo`、ブログ投稿`foo`)などです。
IDの衝突を回避するために、ユーザーのJWTトークンを作成するとき、subキーの値にプレフィックスを付けることができます例えば、`username:`)。したがって、この例では、`sub`の値は次のようになっている可能性があります:`username:johndoe`
覚えておくべき重要なことは、`sub`キーはアプリケーション全体で一意の識別子を持ち、文字列である必要があるということです。
## 確認
サーバーを実行し、ドキュメントに移動します:<a href="http://127.0.0.1:8000/docs" class="external-link" target="_blank">http://127.0.0.1:8000/docs</a>
次のようなユーザーインターフェイスが表示されます:
<img src="/img/tutorial/security/image07.png">
前回と同じ方法でアプリケーションの認可を行います。
次の認証情報を使用します:
Username: `johndoe`
Password: `secret`
!!! check "確認"
コードのどこにも平文のパスワード"`secret`"はなく、ハッシュ化されたものしかないことを確認してください。
<img src="/img/tutorial/security/image08.png">
エンドポイント`/users/me/`を呼び出すと、次のようなレスポンスが得られます:
```JSON
{
"username": "johndoe",
"email": "johndoe@example.com",
"full_name": "John Doe",
"disabled": false
}
```
<img src="/img/tutorial/security/image09.png">
開発者ツールを開くと、送信されるデータにはトークンだけが含まれており、パスワードはユーザーを認証してアクセストークンを取得する最初のリクエストでのみ送信され、その後は送信されないことがわかります。
<img src="/img/tutorial/security/image10.png">
!!! note "備考"
ヘッダーの`Authorization`には、`Bearer`で始まる値があります。
## `scopes` を使った高度なユースケース
OAuth2には、「スコープ」という概念があります。
これらを利用して、JWTトークンに特定の権限セットを追加することができます。
そして、このトークンをユーザーに直接、または第三者に与えて、制限付きでAPIを操作できます。
これらの使用方法や**FastAPI**への統合方法については、**高度なユーザーガイド**で後ほど説明します。
## まとめ
ここまでの説明で、OAuth2やJWTなどの規格を使った安全な**FastAPI**アプリケーションを設定することができます。
ほとんどのフレームワークにおいて、セキュリティを扱うことは非常に複雑な課題となります。
簡略化しすぎたパッケージの多くは、データモデルやデータベース、利用可能な機能について多くの妥協をしなければなりません。そして、あまりにも単純化されたパッケージの中には、実はセキュリティ上の欠陥があるものもあります。
---
**FastAPI**は、どのようなデータベース、データモデル、ツールに対しても妥協することはありません。
そのため、プロジェクトに合わせて自由に選択することができます。
また、**FastAPI**は外部パッケージを統合するために複雑な仕組みを必要としないため、`passlib`や`python-jose`のようなよく整備され広く使われている多くのパッケージを直接使用することができます。
しかし、柔軟性、堅牢性、セキュリティを損なうことなく、可能な限りプロセスを簡素化するためのツールを提供します。
また、OAuth2のような安全で標準的なプロトコルを比較的簡単な方法で使用できるだけではなく、実装することもできます。
OAuth2の「スコープ」を使って、同じ基準でより細かい権限システムを実現する方法については、**高度なユーザーガイド**で詳しく説明しています。スコープ付きのOAuth2は、Facebook、Google、GitHub、Microsoft、Twitterなど、多くの大手認証プロバイダが、サードパーティのアプリケーションと自社のAPIとのやり取りをユーザーに代わって認可するために使用している仕組みです。

View File

@@ -39,8 +39,10 @@ nav:
- FastAPI: index.md
- Languages:
- en: /
- de: /de/
- es: /es/
- fr: /fr/
- id: /id/
- it: /it/
- ja: /ja/
- ko: /ko/
@@ -66,6 +68,7 @@ nav:
- tutorial/body-updates.md
- セキュリティ:
- tutorial/security/first-steps.md
- tutorial/security/oauth2-jwt.md
- tutorial/middleware.md
- tutorial/cors.md
- tutorial/static-files.md
@@ -113,7 +116,7 @@ extra:
- icon: fontawesome/brands/discord
link: https://discord.gg/VQjSZaeJmf
- icon: fontawesome/brands/twitter
link: https://twitter.com/tiangolo
link: https://twitter.com/fastapi
- icon: fontawesome/brands/linkedin
link: https://www.linkedin.com/in/tiangolo
- icon: fontawesome/brands/dev
@@ -125,10 +128,14 @@ extra:
alternate:
- link: /
name: en - English
- link: /de/
name: de
- link: /es/
name: es - español
- link: /fr/
name: fr - français
- link: /id/
name: id
- link: /it/
name: it - italiano
- link: /ja/

View File

@@ -46,7 +46,10 @@ FastAPI는 현대적이고, 빠르며(고성능), 파이썬 표준 타입 힌트
{% if sponsors %}
{% for sponsor in sponsors.gold -%}
<a href="{{ sponsor.url }}" target="_blank" title="{{ sponsor.title }}"><img src="{{ sponsor.img }}"></a>
<a href="{{ sponsor.url }}" target="_blank" title="{{ sponsor.title }}"><img src="{{ sponsor.img }}" style="border-radius:15px"></a>
{% endfor -%}
{%- for sponsor in sponsors.silver -%}
<a href="{{ sponsor.url }}" target="_blank" title="{{ sponsor.title }}"><img src="{{ sponsor.img }}" style="border-radius:15px"></a>
{% endfor %}
{% endif %}

View File

@@ -39,8 +39,10 @@ nav:
- FastAPI: index.md
- Languages:
- en: /
- de: /de/
- es: /es/
- fr: /fr/
- id: /id/
- it: /it/
- ja: /ja/
- ko: /ko/
@@ -80,7 +82,7 @@ extra:
- icon: fontawesome/brands/discord
link: https://discord.gg/VQjSZaeJmf
- icon: fontawesome/brands/twitter
link: https://twitter.com/tiangolo
link: https://twitter.com/fastapi
- icon: fontawesome/brands/linkedin
link: https://www.linkedin.com/in/tiangolo
- icon: fontawesome/brands/dev
@@ -92,10 +94,14 @@ extra:
alternate:
- link: /
name: en - English
- link: /de/
name: de
- link: /es/
name: es - español
- link: /fr/
name: fr - français
- link: /id/
name: id
- link: /it/
name: it - italiano
- link: /ja/

View File

@@ -44,13 +44,16 @@ The key features are:
<small>* estimation based on tests on an internal development team, building production applications.</small>
## Gold Sponsors
## Sponsors
<!-- sponsors -->
{% if sponsors %}
{% for sponsor in sponsors.gold -%}
<a href="{{ sponsor.url }}" target="_blank" title="{{ sponsor.title }}"><img src="{{ sponsor.img }}"></a>
<a href="{{ sponsor.url }}" target="_blank" title="{{ sponsor.title }}"><img src="{{ sponsor.img }}" style="border-radius:15px"></a>
{% endfor -%}
{%- for sponsor in sponsors.silver -%}
<a href="{{ sponsor.url }}" target="_blank" title="{{ sponsor.title }}"><img src="{{ sponsor.img }}" style="border-radius:15px"></a>
{% endfor %}
{% endif %}

View File

@@ -39,8 +39,10 @@ nav:
- FastAPI: index.md
- Languages:
- en: /
- de: /de/
- es: /es/
- fr: /fr/
- id: /id/
- it: /it/
- ja: /ja/
- ko: /ko/
@@ -74,7 +76,7 @@ extra:
- icon: fontawesome/brands/discord
link: https://discord.gg/VQjSZaeJmf
- icon: fontawesome/brands/twitter
link: https://twitter.com/tiangolo
link: https://twitter.com/fastapi
- icon: fontawesome/brands/linkedin
link: https://www.linkedin.com/in/tiangolo
- icon: fontawesome/brands/dev
@@ -86,10 +88,14 @@ extra:
alternate:
- link: /
name: en - English
- link: /de/
name: de
- link: /es/
name: es - español
- link: /fr/
name: fr - français
- link: /id/
name: id
- link: /it/
name: it - italiano
- link: /ja/

View File

@@ -0,0 +1,511 @@
# Desenvolvimento - Contribuindo
Primeiramente, você deveria ver os meios básicos para [ajudar FastAPI e pedir ajuda](help-fastapi.md){.internal-link target=_blank}.
## Desenvolvendo
Se você já clonou o repositório e precisa mergulhar no código, aqui estão algumas orientações para configurar seu ambiente.
### Ambiente virtual com `venv`
Você pode criar um ambiente virtual em um diretório utilizando o módulo `venv` do Python:
<div class="termy">
```console
$ python -m venv env
```
</div>
Isso criará o diretório `./env/` com os binários Python e então você será capaz de instalar pacotes nesse ambiente isolado.
### Ativar o ambiente
Ative o novo ambiente com:
=== "Linux, macOS"
<div class="termy">
```console
$ source ./env/bin/activate
```
</div>
=== "Windows PowerShell"
<div class="termy">
```console
$ .\env\Scripts\Activate.ps1
```
</div>
=== "Windows Bash"
Ou se você usa Bash para Windows (por exemplo <a href="https://gitforwindows.org/" class="external-link" target="_blank">Git Bash</a>):
<div class="termy">
```console
$ source ./env/Scripts/activate
```
</div>
Para verificar se funcionou, use:
=== "Linux, macOS, Windows Bash"
<div class="termy">
```console
$ which pip
some/directory/fastapi/env/bin/pip
```
</div>
=== "Windows PowerShell"
<div class="termy">
```console
$ Get-Command pip
some/directory/fastapi/env/bin/pip
```
</div>
Se ele exibir o binário `pip` em `env/bin/pip` então funcionou. 🎉
!!! tip
Toda vez que você instalar um novo pacote com `pip` nesse ambiente, ative o ambiente novamente.
Isso garante que se você usar um programa instalado por aquele pacote (como `flit`), você utilizará aquele de seu ambiente local e não outro que possa estar instalado globalmente.
### Flit
**FastAPI** utiliza <a href="https://flit.readthedocs.io/en/latest/index.html" class="external-link" target="_blank">Flit</a> para construir, empacotar e publicar o projeto.
Após ativar o ambiente como descrito acima, instale o `flit`:
<div class="termy">
```console
$ pip install flit
---> 100%
```
</div>
Ative novamente o ambiente para ter certeza que você esteja utilizando o `flit` que você acabou de instalar (e não um global).
E agora use `flit` para instalar as dependências de desenvolvimento:
=== "Linux, macOS"
<div class="termy">
```console
$ flit install --deps develop --symlink
---> 100%
```
</div>
=== "Windows"
Se você está no Windows, use `--pth-file` ao invés de `--symlink`:
<div class="termy">
```console
$ flit install --deps develop --pth-file
---> 100%
```
</div>
Isso irá instalar todas as dependências e seu FastAPI local em seu ambiente local.
#### Usando seu FastAPI local
Se você cria um arquivo Python que importa e usa FastAPI, e roda com Python de seu ambiente local, ele irá utilizar o código fonte de seu FastAPI local.
E se você atualizar o código fonte do FastAPI local, como ele é instalado com `--symlink` (ou `--pth-file` no Windows), quando você rodar aquele arquivo Python novamente, ele irá utilizar a nova versão do FastAPI que você acabou de editar.
Desse modo, você não tem que "instalar" sua versão local para ser capaz de testar cada mudança.
### Formato
Tem um arquivo que você pode rodar que irá formatar e limpar todo o seu código:
<div class="termy">
```console
$ bash scripts/format.sh
```
</div>
Ele irá organizar também todos os seus imports.
Para que ele organize os imports corretamente, você precisa ter o FastAPI instalado localmente em seu ambiente, com o comando na seção acima usando `--symlink` (ou `--pth-file` no Windows).
### Formato dos imports
Tem outro _script_ que formata todos os imports e garante que você não tenha imports não utilizados:
<div class="termy">
```console
$ bash scripts/format-imports.sh
```
</div>
Como ele roda um comando após o outro, modificando e revertendo muitos arquivos, ele demora um pouco para concluir, então pode ser um pouco mais fácil utilizar `scripts/format.sh` frequentemente e `scripts/format-imports.sh` somente após "commitar uma branch".
## Documentação
Primeiro, tenha certeza de configurar seu ambiente como descrito acima, isso irá instalar todas as requisições.
A documentação usa <a href="https://www.mkdocs.org/" class="external-link" target="_blank">MkDocs</a>.
E existem ferramentas/_scripts_ extras para controlar as traduções em `./scripts/docs.py`.
!!! tip
Você não precisa ver o código em `./scripts/docs.py`, você apenas o utiliza na linha de comando.
Toda a documentação está no formato Markdown no diretório `./docs/pt/`.
Muitos dos tutoriais tem blocos de código.
Na maioria dos casos, esse blocos de código são aplicações completas que podem ser rodadas do jeito que estão apresentados.
De fato, esses blocos de código não estão escritos dentro do Markdown, eles são arquivos Python dentro do diretório `./docs_src/`.
E esses arquivos Python são incluídos/injetados na documentação quando se gera o site.
### Testes para Documentação
A maioria dos testes na verdade rodam encima dos arquivos fonte na documentação.
Isso ajuda a garantir:
* Que a documentação esteja atualizada.
* Que os exemplos da documentação possam ser rodadas do jeito que estão apresentadas.
* A maior parte dos recursos é coberta pela documentação, garantida por cobertura de testes.
Durante o desenvolvimento local, existe um _script_ que constrói o site e procura por quaisquer mudanças, carregando na hora:
<div class="termy">
```console
$ python ./scripts/docs.py live
<span style="color: green;">[INFO]</span> Serving on http://127.0.0.1:8008
<span style="color: green;">[INFO]</span> Start watching changes
<span style="color: green;">[INFO]</span> Start detecting changes
```
</div>
Isso irá servir a documentação em `http://127.0.0.1:8008`.
Desse jeito, você poderá editar a documentação/arquivos fonte e ver as mudanças na hora.
#### Typer CLI (opcional)
As instruções aqui mostram como utilizar _scripts_ em `./scripts/docs.py` com o programa `python` diretamente.
Mas você pode usar também <a href="https://typer.tiangolo.com/typer-cli/" class="external-link" target="_blank">Typer CLI</a>, e você terá auto-completação para comandos no seu terminal após instalar o _completion_.
Se você instalou Typer CLI, você pode instalar _completion_ com:
<div class="termy">
```console
$ typer --install-completion
zsh completion installed in /home/user/.bashrc.
Completion will take effect once you restart the terminal.
```
</div>
### Aplicações e documentação ao mesmo tempo
Se você rodar os exemplos com, por exemplo:
<div class="termy">
```console
$ uvicorn tutorial001:app --reload
<span style="color: green;">INFO</span>: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit)
```
</div>
como Uvicorn utiliza por padrão a porta `8000`, a documentação na porta `8008` não dará conflito.
### Traduções
Ajuda com traduções É MUITO apreciada! E essa tarefa não pode ser concluída sem a ajuda da comunidade. 🌎 🚀
Aqui estão os passos para ajudar com as traduções.
#### Dicas e orientações
* Verifique sempre os <a href="https://github.com/tiangolo/fastapi/pulls" class="external-link" target="_blank">_pull requests_ existentes</a> para a sua linguagem e faça revisões das alterações e aprove elas.
!!! tip
Você pode <a href="https://help.github.com/en/github/collaborating-with-issues-and-pull-requests/commenting-on-a-pull-request" class="external-link" target="_blank">adicionar comentários com sugestões de alterações</a> para _pull requests_ existentes.
Verifique as documentações sobre <a href="https://help.github.com/en/github/collaborating-with-issues-and-pull-requests/about-pull-request-reviews" class="external-link" target="_blank">adicionar revisão ao _pull request_</a> para aprovação ou solicitação de alterações.
* Verifique em <a href="https://github.com/tiangolo/fastapi/issues" class="external-link" target="_blank">_issues_</a> para ver se existe alguém coordenando traduções para a sua linguagem.
* Adicione um único _pull request_ por página traduzida. Isso tornará muito mais fácil a revisão para as outras pessoas.
Para as linguagens que eu não falo, vou esperar por várias pessoas revisarem a tradução antes de _mergear_.
* Você pode verificar também se há traduções para sua linguagem e adicionar revisão para elas, isso irá me ajudar a saber que a tradução está correta e eu possa _mergear_.
* Utilize os mesmos exemplos Python e somente traduza o texto na documentação. Você não tem que alterar nada no código para que funcione.
* Utilize as mesmas imagens, nomes de arquivo e links. Você não tem que alterar nada disso para que funcione.
* Para verificar o código de duas letras para a linguagem que você quer traduzir, você pode usar a <a href="https://en.wikipedia.org/wiki/List_of_ISO_639-1_codes" class="external-link" target="_blank">Lista de códigos ISO 639-1</a>.
#### Linguagem existente
Vamos dizer que você queira traduzir uma página para uma linguagem que já tenha traduções para algumas páginas, como o Espanhol.
No caso do Espanhol, o código de duas letras é `es`. Então, o diretório para traduções em Espanhol está localizada em `docs/es/`.
!!! tip
A principal ("oficial") linguagem é o Inglês, localizado em `docs/en/`.
Agora rode o _servidor ao vivo_ para as documentações em Espanhol:
<div class="termy">
```console
// Use o comando "live" e passe o código da linguagem como um argumento de linha de comando
$ python ./scripts/docs.py live es
<span style="color: green;">[INFO]</span> Serving on http://127.0.0.1:8008
<span style="color: green;">[INFO]</span> Start watching changes
<span style="color: green;">[INFO]</span> Start detecting changes
```
</div>
Agora você pode ir em <a href="http://127.0.0.1:8008" class="external-link" target="_blank">http://127.0.0.1:8008</a> e ver suas mudanças ao vivo.
Se você procurar no site da documentação do FastAPI, você verá que toda linguagem tem todas as páginas. Mas algumas páginas não estão traduzidas e tem notificação sobre a falta da tradução.
Mas quando você rodar localmente como descrito acima, você somente verá as páginas que já estão traduzidas.
Agora vamos dizer que você queira adicionar uma tradução para a seção [Recursos](features.md){.internal-link target=_blank}.
* Copie o arquivo em:
```
docs/en/docs/features.md
```
* Cole ele exatamente no mesmo local mas para a linguagem que você quer traduzir, por exemplo:
```
docs/es/docs/features.md
```
!!! tip
Observe que a única mudança na rota é o código da linguagem, de `en` para `es`.
* Agora abra o arquivo de configuração MkDocs para Inglês em:
```
docs/en/docs/mkdocs.yml
```
* Procure o lugar onde `docs/features.md` está localizado no arquivo de configuração. Algum lugar como:
```YAML hl_lines="8"
site_name: FastAPI
# Mais coisas
nav:
- FastAPI: index.md
- Languages:
- en: /
- es: /es/
- features.md
```
* Abra o arquivo de configuração MkDocs para a linguagem que você está editando, por exemplo:
```
docs/es/docs/mkdocs.yml
```
* Adicione no mesmo local que está no arquivo em Inglês, por exemplo:
```YAML hl_lines="8"
site_name: FastAPI
# Mais coisas
nav:
- FastAPI: index.md
- Languages:
- en: /
- es: /es/
- features.md
```
Tenha certeza que se existem outras entradas, a nova entrada com sua tradução esteja exatamente na mesma ordem como na versão em Inglês.
Se você for no seu navegador verá que agora a documentação mostra sua nova seção. 🎉
Agora você poderá traduzir tudo e ver como está toda vez que salva o arquivo.
#### Nova linguagem
Vamos dizer que você queira adicionar traduções para uma linguagem que ainda não foi traduzida, nem sequer uma página.
Vamos dizer que você queira adicionar tradução para Haitiano, e ainda não tenha na documentação.
Verificando o link acima, o código para "Haitiano" é `ht`.
O próximo passo é rodar o _script_ para gerar um novo diretório de tradução:
<div class="termy">
```console
// Use o comando new-lang, passe o código da linguagem como um argumento de linha de comando
$ python ./scripts/docs.py new-lang ht
Successfully initialized: docs/ht
Updating ht
Updating en
```
</div>
Agora você pode verificar em seu editor de código o mais novo diretório criado `docs/ht/`.
!!! tip
Crie um primeiro _pull request_ com apenas isso, para iniciar a configuração da nova linguagem, antes de adicionar traduções.
Desse modo outros poderão ajudar com outras páginas enquanto você trabalha na primeira. 🚀
Inicie traduzindo a página principal, `docs/ht/index.md`.
Então você pode continuar com as instruções anteriores, para uma "Linguagem Existente".
##### Nova linguagem não suportada
Se quando rodar o _script_ do _servidor ao vivo_ você pega um erro sobre linguagem não suportada, alguma coisa como:
```
raise TemplateNotFound(template)
jinja2.exceptions.TemplateNotFound: partials/language/xx.html
```
Isso significa que o tema não suporta essa linguagem (nesse caso, com um código falso de duas letras `xx`).
Mas não se preocupe, você pode configurar o tema de linguagem para Inglês e então traduzir o conteúdo da documentação.
Se você precisar fazer isso, edite o `mkdocs.yml` para sua nova linguagem, teremos algo como:
```YAML hl_lines="5"
site_name: FastAPI
# Mais coisas
theme:
# Mais coisas
language: xx
```
Altere essa linguagem de `xx` (do seu código de linguagem) para `en`.
Então você poderá iniciar novamente o _servidor ao vivo_.
#### Pré-visualize o resultado
Quando você usa o _script_ em `./scripts/docs.py` com o comando `live` ele somente exibe os arquivos e traduções disponíveis para a linguagem atual.
Mas uma vez que você tenha concluído, você poderá testar tudo como se parecesse _online_.
Para fazer isso, primeiro construa toda a documentação:
<div class="termy">
```console
// Use o comando "build-all", isso leverá um tempinho
$ python ./scripts/docs.py build-all
Updating es
Updating en
Building docs for: en
Building docs for: es
Successfully built docs for: es
Copying en index.md to README.md
```
</div>
Isso gera toda a documentação em `./docs_build/` para cada linguagem. Isso inclui a adição de quaisquer arquivos com tradução faltando, com uma nota dizendo que "esse arquivo ainda não tem tradução". Mas você não tem que fazer nada com esse diretório.
Então ele constrói todos aqueles _sites_ independentes MkDocs para cada linguagem, combina eles, e gera a saída final em `./site/`.
Então você poderá "servir" eles com o comando `serve`:
<div class="termy">
```console
// Use o comando "serve" após rodar "build-all"
$ python ./scripts/docs.py serve
Warning: this is a very simple server. For development, use mkdocs serve instead.
This is here only to preview a site with translations already built.
Make sure you run the build-all command first.
Serving at: http://127.0.0.1:8008
```
</div>
## Testes
Tem um _script_ que você pode rodar localmente para testar todo o código e gerar relatórios de cobertura em HTML:
<div class="termy">
```console
$ bash scripts/test-cov-html.sh
```
</div>
Esse comando gera um diretório `./htmlcov/`, se você abrir o arquivo `./htmlcov/index.html` no seu navegador, poderá explorar interativamente as regiões de código que estão cobertas pelos testes, e observar se existe alguma região faltando.
### Testes no seu editor
Se você quer usar os testes integrados em seu editor adicione `./docs_src` na sua variável `PYTHONPATH`.
Por exemplo, no VS Code você pode criar um arquivo `.env` com:
```env
PYTHONPATH=./docs_src
```

View File

@@ -0,0 +1,7 @@
# Implantação - Introdução
A implantação de uma aplicação **FastAPI** é relativamente simples.
Existem várias maneiras para fazer isso, dependendo do seu caso específico e das ferramentas que você utiliza.
Você verá mais detalhes para se ter em mente e algumas das técnicas para a implantação nas próximas seções.

View File

@@ -0,0 +1,87 @@
# Sobre as versões do FastAPI
**FastAPI** já está sendo usado em produção em diversas aplicações e sistemas, a cobertura de testes é mantida em 100%, mas seu desenvolvimento está avançando rapidamente.
Novos recursos são adicionados com frequência, bugs são corrigidos regularmente e o código está sempre melhorando.
Esse é o motivo das versões atuais estarem em `0.x.x`, significando que em cada versão pode haver mudanças significativas, tudo isso seguindo as <a href="https://semver.org/lang/pt-BR/" class="external-link" target="_blank">convenções de controle de versão semântica.</a>
Já é possível criar aplicativos de produção com **FastAPI** (e provavelmente você já faz isso há algum tempo), apenas precisando ter certeza de usar uma versão que funcione corretamente com o resto do seu código.
## Fixe a sua versão de `fastapi`
A primeira coisa que você deve fazer é "fixar" a versão do **FastAPI** que você está utilizando na mais atual, na qual você sabe que funciona corretamente para o seu aplicativo.
Por exemplo, supondo que você está usando a versão `0.45.0` em sua aplicação.
Caso você utilize o arquivo `requirements.txt`, você poderia especificar a versão com:
```txt
fastapi==0.45.0
```
Isso significa que você conseguiria utilizar a versão exata `0.45.0`.
Ou, você poderia fixá-la com:
```txt
fastapi>=0.45.0,<0.46.0
```
isso significa que você iria usar as versões `0.45.0` ou acima, mas inferiores à `0.46.0`, por exemplo, a versão `0.45.2` ainda seria aceita.
Se você usar qualquer outra ferramenta para gerenciar suas instalações, como Poetry, Pipenv ou outras, todas elas têm uma maneira que você pode usar para definir as versões específicas dos seus pacotes.
## Versões disponíveis
Você pode ver as versões disponíveis (por exemplo, para verificar qual é a versão atual) em [Release Notes](../release-notes.md){.internal-link target=\_blank}.
## Sobre versões
Seguindo as convenções de controle de versão semântica, qualquer versão abaixo de `1.0.0` pode adicionar mudanças significativas.
FastAPI também segue a convenção de que qualquer alteração de versão "PATCH" é para correção de bugs e alterações não significativas.
!!! tip "Dica"
O "PATCH" é o último número, por exemplo, em `0.2.3`, a versão PATCH é `3`.
Logo, você deveria conseguir fixar a versão, como:
```txt
fastapi>=0.45.0,<0.46.0
```
Mudanças significativas e novos recursos são adicionados em versões "MINOR".
!!! tip "Dica"
O "MINOR" é o número que está no meio, por exemplo, em `0.2.3`, a versão MINOR é `2`.
## Atualizando as versões do FastAPI
Você deve adicionar testes para a sua aplicação.
Com **FastAPI** isso é muito fácil (graças a Starlette), verifique a documentação: [Testing](../tutorial/testing.md){.internal-link target=\_blank}
Após a criação dos testes, você pode atualizar a sua versão do **FastAPI** para uma mais recente, execute os testes para se certificar de que todo o seu código está funcionando corretamente.
Se tudo estiver funcionando, ou após você realizar as alterações necessárias e todos os testes estiverem passando, então você pode fixar sua versão de `FastAPI` para essa mais nova.
## Sobre Starlette
Não é recomendado fixar a versão de `starlette`.
Versões diferentes de **FastAPI** utilizarão uma versão específica e mais recente de Starlette.
Então, você pode deixar **FastAPI** escolher a versão compatível e correta de Starlette.
## Sobre Pydantic
Pydantic incluí os testes para **FastAPI** em seus próprios testes, então as novas versões de Pydantic (acima da `1.0.0`) sempre serão compatíveis com FastAPI.
Você pode fixar qualquer versão de Pydantic que desejar, desde que seja acima da `1.0.0` e abaixo da `2.0.0`.
Por exemplo:
```txt
pydantic>=1.2.0,<2.0.0
```

View File

@@ -39,13 +39,16 @@ Os recursos chave são:
<small>* estimativas baseadas em testes realizados com equipe interna de desenvolvimento, construindo aplicações em produção.</small>
## Gold Sponsors
## Sponsors
<!-- sponsors -->
{% if sponsors %}
{% for sponsor in sponsors.gold -%}
<a href="{{ sponsor.url }}" target="_blank" title="{{ sponsor.title }}"><img src="{{ sponsor.img }}"></a>
<a href="{{ sponsor.url }}" target="_blank" title="{{ sponsor.title }}"><img src="{{ sponsor.img }}" style="border-radius:15px"></a>
{% endfor -%}
{%- for sponsor in sponsors.silver -%}
<a href="{{ sponsor.url }}" target="_blank" title="{{ sponsor.title }}"><img src="{{ sponsor.img }}" style="border-radius:15px"></a>
{% endfor %}
{% endif %}

View File

@@ -0,0 +1,48 @@
# Corpo - Campos
Da mesma forma que você pode declarar validações adicionais e metadados nos parâmetros de *funções de operações de rota* com `Query`, `Path` e `Body`, você pode declarar validações e metadados dentro de modelos do Pydantic usando `Field` do Pydantic.
## Importe `Field`
Primeiro, você tem que importá-lo:
```Python hl_lines="4"
{!../../../docs_src/body_fields/tutorial001.py!}
```
!!! warning "Aviso"
Note que `Field` é importado diretamente do `pydantic`, não do `fastapi` como todo o resto (`Query`, `Path`, `Body`, etc).
## Declare atributos do modelo
Você pode então utilizar `Field` com atributos do modelo:
```Python hl_lines="11-14"
{!../../../docs_src/body_fields/tutorial001.py!}
```
`Field` funciona da mesma forma que `Query`, `Path` e `Body`, ele possui todos os mesmos parâmetros, etc.
!!! note "Detalhes técnicos"
Na realidade, `Query`, `Path` e outros que você verá em seguida, criam objetos de subclasses de uma classe `Param` comum, que é ela mesma uma subclasse da classe `FieldInfo` do Pydantic.
E `Field` do Pydantic retorna uma instância de `FieldInfo` também.
`Body` também retorna objetos de uma subclasse de `FieldInfo` diretamente. E tem outras que você verá mais tarde que são subclasses da classe `Body`.
Lembre-se que quando você importa `Query`, `Path`, e outros de `fastapi`, esse são na realidade funções que retornam classes especiais.
!!! tip "Dica"
Note como cada atributo do modelo com um tipo, valor padrão e `Field` possuem a mesma estrutura que parâmetros de *funções de operações de rota*, com `Field` ao invés de `Path`, `Query` e `Body`.
## Adicione informações extras
Você pode declarar informação extra em `Field`, `Query`, `Body`, etc. E isso será incluído no JSON Schema gerado.
Você irá aprender mais sobre adicionar informações extras posteriormente nessa documentação, quando estiver aprendendo a declarar exemplos.
## Recapitulando
Você pode usar `Field` do Pydantic para declarar validações extras e metadados para atributos do modelo.
Você também pode usar os argumentos de palavras-chave extras para passar metadados do JSON Schema adicionais.

View File

@@ -0,0 +1,101 @@
# Introdução à segurança
Há várias formas de lidar segurança, autenticação e autorização.
E isso normalmente é um tópico “difícil” e complexo.
Em muitos frameworks e sistemas, apenas lidar com segurança e autenticação exige muito esforço e código (em muitos casos isso pode ser 50% ou mais de todo o código escrito).
**FastAPI** tem muitas ferramentas para ajudar você com a parte de **Segurança** facilmente, rapidamente, de uma forma padrão, sem ter que estudar e aprender tudo sobre especificações de segurança.
Mas primeiro, vamos verificar alguns pequenos conceitos.
## Está com pressa?
Se você não se importa com qualquer um desses termos e só precisa adicionar segurança com autenticação baseada em usuário e senha _agora_, pule para os próximos capítulos.
## OAuth2
OAuth2 é uma especificação que define várias formas para lidar com autenticação e autorização.
Ela é bastante extensiva na especificação e cobre casos de uso muito complexos.
Ela inclui uma forma para autenticação usando “third party”/aplicações de terceiros.
Isso é o que todos os sistemas com “Login with Facebook, Google, Twitter, GitHub” usam por baixo.
### OAuth 1
Havia um OAuth 1, que é bem diferente do OAuth2, e mais complexo, isso incluía diretamente as especificações de como criptografar a comunicação.
Não é muito popular ou usado nos dias atuais.
OAuth2 não especifica como criptografar a comunicação, ele espera que você tenha sua aplicação em um servidor HTTPS.
!!! tip "Dica"
Na seção sobre **deployment** você irá ver como configurar HTTPS de modo gratuito, usando Traefik e Lets Encrypt.
## OpenID Connect
OpenID Connect é outra especificação, baseada em **OAuth2**.
Ela é apenas uma extensão do OAuth2 especificando algumas coisas que são relativamente ambíguas no OAuth2, para tentar torná-lo mais interoperável.
Por exemplo, o login do Google usa OpenID Connect (que por baixo dos panos usa OAuth2).
Mas o login do Facebook não tem suporte para OpenID Connect. Ele tem a própria implementação do OAuth2.
### OpenID (não "OpenID Connect")
Houve também uma especificação “OpenID”. Ela tentou resolver a mesma coisa que a **OpenID Connect**, mas não baseada em OAuth2.
Então, ela foi um sistema adicional completo.
Ela não é muito popular ou usada nos dias de hoje.
## OpenAPI
OpenAPI (anteriormente conhecido como Swagger) é a especificação aberta para a criação de APIs (agora parte da Linux Foundation).
**FastAPI** é baseado no **OpenAPI**.
Isso é o que torna possível ter múltiplas automações interativas de interfaces de documentação, geração de código, etc.
OpenAPI tem uma forma para definir múltiplos “esquemas” de segurança.
Por usá-los, você pode ter vantagens de todas essas ferramentas baseadas nos padrões, incluindo os sistemas de documentação interativa.
OpenAPI define os seguintes esquemas de segurança:
* `apiKey`: uma chave específica de aplicação que pode vir de:
* Um parâmetro query.
* Um header.
* Um cookie.
* `http`: padrão HTTP de sistemas autenticação, incluindo:
* `bearer`: um header de `Authorization` com valor de `Bearer` adicionado de um token. Isso é herança do OAuth2.
* HTTP Basic authentication.
* HTTP Digest, etc.
* `oauth2`: todas as formas do OAuth2 para lidar com segurança (chamados "fluxos").
* Vários desses fluxos são apropriados para construir um provedor de autenticação OAuth2 (como Google, Facebook, Twitter, GitHub, etc):
* `implicit`
* `clientCredentials`
* `authorizationCode`
* Mas existe um “fluxo” específico que pode ser perfeitamente usado para resolver autenticação diretamente na mesma aplicação:
* `password`: alguns dos próximos capítulos tratarão disso.
* `openIdConnect`: tem uma forma para definir como descobrir automaticamente o dado da autenticação OAuth2.
* Essa descoberta automática é o que é definido na especificação OpenID Connect.
!!! tip "Dica"
Integração com outros provedores de autenticação/autorização como Google, Facebook, Twitter, GitHub, etc. é bem possível e relativamente fácil.
O problema mais complexo é criar um provedor de autenticação/autorização como eles, mas o FastAPI dá a você ferramentas para fazer isso facilmente, enquanto faz o trabalho pesado para você.
## **FastAPI** utilitários
**FastAPI** fornece várias ferramentas para cada um desses esquemas de segurança no módulo `fastapi.security` que simplesmente usa esses mecanismos de segurança.
Nos próximos capítulos você irá ver como adicionar segurança à sua API usando essas ferramentas disponibilizadas pelo **FastAPI**.
E você irá ver também como isso é automaticamente integrado dentro do sistema de documentação interativo.

View File

@@ -39,8 +39,10 @@ nav:
- FastAPI: index.md
- Languages:
- en: /
- de: /de/
- es: /es/
- fr: /fr/
- id: /id/
- it: /it/
- ja: /ja/
- ko: /ko/
@@ -55,6 +57,12 @@ nav:
- Tutorial - Guia de Usuário:
- tutorial/index.md
- tutorial/first-steps.md
- tutorial/body-fields.md
- Segurança:
- tutorial/security/index.md
- Implantação:
- deployment/index.md
- deployment/versions.md
- alternatives.md
- history-design-future.md
- external-links.md
@@ -82,7 +90,7 @@ extra:
- icon: fontawesome/brands/discord
link: https://discord.gg/VQjSZaeJmf
- icon: fontawesome/brands/twitter
link: https://twitter.com/tiangolo
link: https://twitter.com/fastapi
- icon: fontawesome/brands/linkedin
link: https://www.linkedin.com/in/tiangolo
- icon: fontawesome/brands/dev
@@ -94,10 +102,14 @@ extra:
alternate:
- link: /
name: en - English
- link: /de/
name: de
- link: /es/
name: es - español
- link: /fr/
name: fr - français
- link: /id/
name: id
- link: /it/
name: it - italiano
- link: /ja/

View File

@@ -0,0 +1,82 @@
# Внешние ссылки и статьи
**FastAPI** имеет отличное и постоянно растущее сообщество.
Существует множество сообщений, статей, инструментов и проектов, связанных с **FastAPI**.
Вот неполный список некоторых из них.
!!! tip
Если у вас есть статья, проект, инструмент или что-либо, связанное с **FastAPI**, что еще не перечислено здесь, создайте <a href="https://github.com/tiangolo/fastapi/edit/master/docs/en/data/external_links.yml" class="external-link" target="_blank">Pull Request</a>.
## Статьи
### На английском
{% if external_links %}
{% for article in external_links.articles.english %}
* <a href="{{ article.link }}" class="external-link" target="_blank">{{ article.title }}</a> by <a href="{{ article.author_link }}" class="external-link" target="_blank">{{ article.author }}</a>.
{% endfor %}
{% endif %}
### На японском
{% if external_links %}
{% for article in external_links.articles.japanese %}
* <a href="{{ article.link }}" class="external-link" target="_blank">{{ article.title }}</a> by <a href="{{ article.author_link }}" class="external-link" target="_blank">{{ article.author }}</a>.
{% endfor %}
{% endif %}
### На вьетнамском
{% if external_links %}
{% for article in external_links.articles.vietnamese %}
* <a href="{{ article.link }}" class="external-link" target="_blank">{{ article.title }}</a> by <a href="{{ article.author_link }}" class="external-link" target="_blank">{{ article.author }}</a>.
{% endfor %}
{% endif %}
### На русском
{% if external_links %}
{% for article in external_links.articles.russian %}
* <a href="{{ article.link }}" class="external-link" target="_blank">{{ article.title }}</a> by <a href="{{ article.author_link }}" class="external-link" target="_blank">{{ article.author }}</a>.
{% endfor %}
{% endif %}
### На немецком
{% if external_links %}
{% for article in external_links.articles.german %}
* <a href="{{ article.link }}" class="external-link" target="_blank">{{ article.title }}</a> by <a href="{{ article.author_link }}" class="external-link" target="_blank">{{ article.author }}</a>.
{% endfor %}
{% endif %}
## Подкасты
{% if external_links %}
{% for article in external_links.podcasts.english %}
* <a href="{{ article.link }}" class="external-link" target="_blank">{{ article.title }}</a> by <a href="{{ article.author_link }}" class="external-link" target="_blank">{{ article.author }}</a>.
{% endfor %}
{% endif %}
## Talks
{% if external_links %}
{% for article in external_links.talks.english %}
* <a href="{{ article.link }}" class="external-link" target="_blank">{{ article.title }}</a> by <a href="{{ article.author_link }}" class="external-link" target="_blank">{{ article.author }}</a>.
{% endfor %}
{% endif %}
## Проекты
Последние GitHub-проекты с пометкой `fastapi`:
<div class="github-topic-projects">
</div>

View File

@@ -44,13 +44,16 @@ The key features are:
<small>* estimation based on tests on an internal development team, building production applications.</small>
## Gold Sponsors
## Sponsors
<!-- sponsors -->
{% if sponsors %}
{% for sponsor in sponsors.gold -%}
<a href="{{ sponsor.url }}" target="_blank" title="{{ sponsor.title }}"><img src="{{ sponsor.img }}"></a>
<a href="{{ sponsor.url }}" target="_blank" title="{{ sponsor.title }}"><img src="{{ sponsor.img }}" style="border-radius:15px"></a>
{% endfor -%}
{%- for sponsor in sponsors.silver -%}
<a href="{{ sponsor.url }}" target="_blank" title="{{ sponsor.title }}"><img src="{{ sponsor.img }}" style="border-radius:15px"></a>
{% endfor %}
{% endif %}

View File

@@ -0,0 +1,314 @@
# Введение в аннотации типов Python
Python имеет поддержку необязательных аннотаций типов.
**Аннотации типов** являются специальным синтаксисом, который позволяет определять <abbr title="например: str, int, float, bool">тип</abbr> переменной.
Объявление типов для переменных позволяет улучшить поддержку вашего кода редакторами и различными инструментами.
Это просто **краткое руководство / напоминание** об аннотациях типов в Python. Оно охватывает только минимум, необходимый для их использования с **FastAPI**... что на самом деле очень мало.
**FastAPI** целиком основан на аннотациях типов, у них много выгод и преимуществ.
Но даже если вы никогда не используете **FastAPI**, вам будет полезно немного узнать о них.
!!! note
Если вы являетесь экспертом в Python и уже знаете всё об аннотациях типов, переходите к следующему разделу.
## Мотивация
Давайте начнем с простого примера:
```Python
{!../../../docs_src/python_types/tutorial001.py!}
```
Вызов этой программы выводит:
```
John Doe
```
Функция делает следующее:
* Принимает `first_name` и `last_name`.
* Преобразует первую букву содержимого каждой переменной в верхний регистр с `title()`.
* <abbr title="Объединяет в одно целое, последовательно, друг за другом.">Соединяет</abbr> их через пробел.
```Python hl_lines="2"
{!../../../docs_src/python_types/tutorial001.py!}
```
### Отредактируем пример
Это очень простая программа.
А теперь представьте, что вы пишете её с нуля.
В какой-то момент вы бы начали определение функции, у вас были бы готовы параметры...
Но затем вы должны вызвать «тот метод, который преобразует первую букву в верхний регистр».
Было это `upper`? Или `uppercase`? `first_uppercase`? `capitalize`?
Тогда вы попробуете с давним другом программиста: автодополнением редактора.
Вы вводите первый параметр функции, `first_name`, затем точку (`.`), а затем нажимаете `Ctrl+Space`, чтобы запустить дополнение.
Но, к сожалению, ничего полезного не выходит:
<img src="/img/python-types/image01.png">
### Добавим типы
Давайте изменим одну строчку в предыдущей версии.
Мы изменим именно этот фрагмент, параметры функции, с:
```Python
first_name, last_name
```
на:
```Python
first_name: str, last_name: str
```
Вот и все.
Это аннотации типов:
```Python hl_lines="1"
{!../../../docs_src/python_types/tutorial002.py!}
```
Это не то же самое, что объявление значений по умолчанию, например:
```Python
first_name="john", last_name="doe"
```
Это другая вещь.
Мы используем двоеточия (`:`), а не равно (`=`).
И добавление аннотаций типов обычно не меняет происходящего по сравнению с тем, что произошло бы без неё.
Но теперь представьте, что вы снова находитесь в процессе создания этой функции, но уже с аннотациями типов.
В тот же момент вы пытаетесь запустить автодополнение с помощью `Ctrl+Space` и вы видите:
<img src="/img/python-types/image02.png">
При этом вы можете просматривать варианты, пока не найдёте подходящий:
<img src="/img/python-types/image03.png">
## Больше мотивации
Проверьте эту функцию, она уже имеет аннотации типов:
```Python hl_lines="1"
{!../../../docs_src/python_types/tutorial003.py!}
```
Поскольку редактор знает типы переменных, вы получаете не только дополнение, но и проверки ошибок:
<img src="/img/python-types/image04.png">
Теперь вы знаете, что вам нужно исправить, преобразовав `age` в строку с `str(age)`:
```Python hl_lines="2"
{!../../../docs_src/python_types/tutorial004.py!}
```
## Объявление типов
Вы только что видели основное место для объявления подсказок типов. В качестве параметров функции.
Это также основное место, где вы можете использовать их с **FastAPI**.
### Простые типы
Вы можете объявить все стандартные типы Python, а не только `str`.
Вы можете использовать, к примеру:
* `int`
* `float`
* `bool`
* `bytes`
```Python hl_lines="1"
{!../../../docs_src/python_types/tutorial005.py!}
```
### Generic-типы с параметрами типов
Существуют некоторые структуры данных, которые могут содержать другие значения, например, `dict`, `list`, `set` и `tuple`. И внутренние значения тоже могут иметь свой тип.
Чтобы объявить эти типы и внутренние типы, вы можете использовать стандартный Python-модуль `typing`.
Он существует специально для поддержки подсказок этих типов.
#### `List`
Например, давайте определим переменную как `list`, состоящий из `str`.
Импортируйте `List` из `typing` (с заглавной `L`):
```Python hl_lines="1"
{!../../../docs_src/python_types/tutorial006.py!}
```
Объявите переменную с тем же синтаксисом двоеточия (`:`).
В качестве типа укажите `List`.
Поскольку список является типом, содержащим некоторые внутренние типы, вы помещаете их в квадратные скобки:
```Python hl_lines="4"
{!../../../docs_src/python_types/tutorial006.py!}
```
!!! tip
Эти внутренние типы в квадратных скобках называются «параметрами типов».
В этом случае `str` является параметром типа, передаваемым в `List`.
Это означает: "переменная `items` является `list`, и каждый из элементов этого списка является `str`".
Если вы будете так поступать, редактор может оказывать поддержку даже при обработке элементов списка:
<img src="/img/python-types/image05.png">
Без типов добиться этого практически невозможно.
Обратите внимание, что переменная `item` является одним из элементов списка `items`.
И все же редактор знает, что это `str`, и поддерживает это.
#### `Tuple` и `Set`
Вы бы сделали то же самое, чтобы объявить `tuple` и `set`:
```Python hl_lines="1 4"
{!../../../docs_src/python_types/tutorial007.py!}
```
Это означает:
* Переменная `items_t` является `tuple` с 3 элементами: `int`, другим `int` и `str`.
* Переменная `items_s` является `set` и каждый элемент имеет тип `bytes`.
#### `Dict`
Чтобы определить `dict`, вы передаёте 2 параметра типов, разделённых запятыми.
Первый параметр типа предназначен для ключей `dict`.
Второй параметр типа предназначен для значений `dict`:
```Python hl_lines="1 4"
{!../../../docs_src/python_types/tutorial008.py!}
```
Это означает:
* Переменная `prices` является `dict`:
* Ключи этого `dict` имеют тип `str` (скажем, название каждого элемента).
* Значения этого `dict` имеют тип `float` (скажем, цена каждой позиции).
#### `Optional`
Вы также можете использовать `Optional`, чтобы объявить, что переменная имеет тип, например, `str`, но это является «необязательным», что означает, что она также может быть `None`:
```Python hl_lines="1 4"
{!../../../docs_src/python_types/tutorial009.py!}
```
Использование `Optional[str]` вместо просто `str` позволит редактору помочь вам в обнаружении ошибок, в которых вы могли бы предположить, что значение всегда является `str`, хотя на самом деле это может быть и `None`.
#### Generic-типы
Эти типы принимают параметры в квадратных скобках:
* `List`
* `Tuple`
* `Set`
* `Dict`
* `Optional`
* ...и др.
называются **Generic-типами** или **Generics**.
### Классы как типы
Вы также можете объявить класс как тип переменной.
Допустим, у вас есть класс `Person` с полем `name`:
```Python hl_lines="1-3"
{!../../../docs_src/python_types/tutorial010.py!}
```
Тогда вы можете объявить переменную типа `Person`:
```Python hl_lines="6"
{!../../../docs_src/python_types/tutorial010.py!}
```
И снова вы получаете полную поддержку редактора:
<img src="/img/python-types/image06.png">
## Pydantic-модели
<a href="https://pydantic-docs.helpmanual.io/" class="external-link" target="_blank">Pydantic</a> является Python-библиотекой для выполнения валидации данных.
Вы объявляете «форму» данных как классы с атрибутами.
И каждый атрибут имеет тип.
Затем вы создаете экземпляр этого класса с некоторыми значениями, и он проверяет значения, преобразует их в соответствующий тип (если все верно) и предоставляет вам объект со всеми данными.
И вы получаете полную поддержку редактора для этого итогового объекта.
Взято из официальной документации Pydantic:
```Python
{!../../../docs_src/python_types/tutorial011.py!}
```
!!! info
Чтобы узнать больше о <a href="https://pydantic-docs.helpmanual.io/" class="external-link" target="_blank">Pydantic, читайте его документацию</a>.
**FastAPI** целиком основан на Pydantic.
Вы увидите намного больше всего этого на практике в [Руководстве пользователя](tutorial/index.md){.internal-link target=_blank}.
## Аннотации типов в **FastAPI**
**FastAPI** получает преимущества аннотаций типов для выполнения определённых задач.
С **FastAPI** вы объявляете параметры с аннотациями типов и получаете:
* **Поддержку редактора**.
* **Проверки типов**.
...и **FastAPI** использует тот же механизм для:
* **Определения требований**: из параметров пути запроса, параметров запроса, заголовков, зависимостей и т.д.
* **Преобразования данных**: от запроса к нужному типу.
* **Валидации данных**: исходя из каждого запроса:
* Генерации **автоматических ошибок**, возвращаемых клиенту, когда данные не являются корректными.
* **Документирования** API с использованием OpenAPI:
* который затем используется пользовательскими интерфейсами автоматической интерактивной документации.
Всё это может показаться абстрактным. Не волнуйтесь. Вы увидите всё это в действии в [Руководстве пользователя](tutorial/index.md){.internal-link target=_blank}.
Важно то, что при использовании стандартных типов Python в одном месте (вместо добавления дополнительных классов, декораторов и т.д.) **FastAPI** сделает за вас большую часть работы.
!!! info
Если вы уже прошли всё руководство и вернулись, чтобы узнать больше о типах, хорошим ресурсом является <a href="https://mypy.readthedocs.io/en/latest/cheat_sheet_py3.html" class="external-link" target="_blank">«шпаргалка» от `mypy`</a>.

View File

@@ -39,8 +39,10 @@ nav:
- FastAPI: index.md
- Languages:
- en: /
- de: /de/
- es: /es/
- fr: /fr/
- id: /id/
- it: /it/
- ja: /ja/
- ko: /ko/
@@ -74,7 +76,7 @@ extra:
- icon: fontawesome/brands/discord
link: https://discord.gg/VQjSZaeJmf
- icon: fontawesome/brands/twitter
link: https://twitter.com/tiangolo
link: https://twitter.com/fastapi
- icon: fontawesome/brands/linkedin
link: https://www.linkedin.com/in/tiangolo
- icon: fontawesome/brands/dev
@@ -86,10 +88,14 @@ extra:
alternate:
- link: /
name: en - English
- link: /de/
name: de
- link: /es/
name: es - español
- link: /fr/
name: fr - français
- link: /id/
name: id
- link: /it/
name: it - italiano
- link: /ja/

View File

@@ -44,13 +44,16 @@ The key features are:
<small>* estimation based on tests on an internal development team, building production applications.</small>
## Gold Sponsors
## Sponsors
<!-- sponsors -->
{% if sponsors %}
{% for sponsor in sponsors.gold -%}
<a href="{{ sponsor.url }}" target="_blank" title="{{ sponsor.title }}"><img src="{{ sponsor.img }}"></a>
<a href="{{ sponsor.url }}" target="_blank" title="{{ sponsor.title }}"><img src="{{ sponsor.img }}" style="border-radius:15px"></a>
{% endfor -%}
{%- for sponsor in sponsors.silver -%}
<a href="{{ sponsor.url }}" target="_blank" title="{{ sponsor.title }}"><img src="{{ sponsor.img }}" style="border-radius:15px"></a>
{% endfor %}
{% endif %}

View File

@@ -39,8 +39,10 @@ nav:
- FastAPI: index.md
- Languages:
- en: /
- de: /de/
- es: /es/
- fr: /fr/
- id: /id/
- it: /it/
- ja: /ja/
- ko: /ko/
@@ -74,7 +76,7 @@ extra:
- icon: fontawesome/brands/discord
link: https://discord.gg/VQjSZaeJmf
- icon: fontawesome/brands/twitter
link: https://twitter.com/tiangolo
link: https://twitter.com/fastapi
- icon: fontawesome/brands/linkedin
link: https://www.linkedin.com/in/tiangolo
- icon: fontawesome/brands/dev
@@ -86,10 +88,14 @@ extra:
alternate:
- link: /
name: en - English
- link: /de/
name: de
- link: /es/
name: es - español
- link: /fr/
name: fr - français
- link: /id/
name: id
- link: /it/
name: it - italiano
- link: /ja/

View File

@@ -44,13 +44,16 @@ The key features are:
<small>* estimation based on tests on an internal development team, building production applications.</small>
## Gold Sponsors
## Sponsors
<!-- sponsors -->
{% if sponsors %}
{% for sponsor in sponsors.gold -%}
<a href="{{ sponsor.url }}" target="_blank" title="{{ sponsor.title }}"><img src="{{ sponsor.img }}"></a>
<a href="{{ sponsor.url }}" target="_blank" title="{{ sponsor.title }}"><img src="{{ sponsor.img }}" style="border-radius:15px"></a>
{% endfor -%}
{%- for sponsor in sponsors.silver -%}
<a href="{{ sponsor.url }}" target="_blank" title="{{ sponsor.title }}"><img src="{{ sponsor.img }}" style="border-radius:15px"></a>
{% endfor %}
{% endif %}

View File

@@ -39,8 +39,10 @@ nav:
- FastAPI: index.md
- Languages:
- en: /
- de: /de/
- es: /es/
- fr: /fr/
- id: /id/
- it: /it/
- ja: /ja/
- ko: /ko/
@@ -74,7 +76,7 @@ extra:
- icon: fontawesome/brands/discord
link: https://discord.gg/VQjSZaeJmf
- icon: fontawesome/brands/twitter
link: https://twitter.com/tiangolo
link: https://twitter.com/fastapi
- icon: fontawesome/brands/linkedin
link: https://www.linkedin.com/in/tiangolo
- icon: fontawesome/brands/dev
@@ -86,10 +88,14 @@ extra:
alternate:
- link: /
name: en - English
- link: /de/
name: de
- link: /es/
name: es - español
- link: /fr/
name: fr - français
- link: /id/
name: id
- link: /it/
name: it - italiano
- link: /ja/

View File

@@ -44,13 +44,16 @@ The key features are:
<small>* estimation based on tests on an internal development team, building production applications.</small>
## Gold Sponsors
## Sponsors
<!-- sponsors -->
{% if sponsors %}
{% for sponsor in sponsors.gold -%}
<a href="{{ sponsor.url }}" target="_blank" title="{{ sponsor.title }}"><img src="{{ sponsor.img }}"></a>
<a href="{{ sponsor.url }}" target="_blank" title="{{ sponsor.title }}"><img src="{{ sponsor.img }}" style="border-radius:15px"></a>
{% endfor -%}
{%- for sponsor in sponsors.silver -%}
<a href="{{ sponsor.url }}" target="_blank" title="{{ sponsor.title }}"><img src="{{ sponsor.img }}" style="border-radius:15px"></a>
{% endfor %}
{% endif %}

View File

@@ -39,8 +39,10 @@ nav:
- FastAPI: index.md
- Languages:
- en: /
- de: /de/
- es: /es/
- fr: /fr/
- id: /id/
- it: /it/
- ja: /ja/
- ko: /ko/
@@ -74,7 +76,7 @@ extra:
- icon: fontawesome/brands/discord
link: https://discord.gg/VQjSZaeJmf
- icon: fontawesome/brands/twitter
link: https://twitter.com/tiangolo
link: https://twitter.com/fastapi
- icon: fontawesome/brands/linkedin
link: https://www.linkedin.com/in/tiangolo
- icon: fontawesome/brands/dev
@@ -86,10 +88,14 @@ extra:
alternate:
- link: /
name: en - English
- link: /de/
name: de
- link: /es/
name: es - español
- link: /fr/
name: fr - français
- link: /id/
name: id
- link: /it/
name: it - italiano
- link: /ja/

View File

@@ -183,7 +183,7 @@ FastAPI实际上是 Starlette将自动包含 Content-Length 的头。它
包括许多与云存储,视频处理等交互的库。
```Python hl_lines="2 10 11"
```Python hl_lines="2 10-12 14"
{!../../../docs_src/custom_response/tutorial008.py!}
```

View File

@@ -0,0 +1,177 @@
# FastAPI 社区
FastAPI 有一个非常棒的社区,它欢迎来自各个领域和背景的朋友。
## 创建者 & 维护者
嘿! 👋
这就是我:
{% if people %}
<div class="user-list user-list-center">
{% for user in people.maintainers %}
<div class="user"><a href="{{ user.url }}" target="_blank"><div class="avatar-wrapper"><img src="{{ user.avatarUrl }}"/></div><div class="title">@{{ user.login }}</div></a> <div class="count">Answers: {{ user.answers }}</div><div class="count">Pull Requests: {{ user.prs }}</div></div>
{% endfor %}
</div>
{% endif %}
我是 **FastAPI** 的创建者和维护者. 你能在 [帮助 FastAPI - 获取帮助 - 与作者联系](help-fastapi.md#connect-with-the-author){.internal-link target=_blank} 阅读有关此内容的更多信息。
...但是在这里我想向您展示社区。
---
**FastAPI** 得到了社区的大力支持。因此我想突出他们的贡献。
这些人:
* [帮助他人解决 GitHub 的 issues](help-fastapi.md#help-others-with-issues-in-github){.internal-link target=_blank}。
* [创建 Pull Requests](help-fastapi.md#create-a-pull-request){.internal-link target=_blank}。
* 审核 Pull Requests 对于 [翻译](contributing.md#translations){.internal-link target=_blank} 尤为重要。
向他们致以掌声。 👏 🙇
## 上个月最活跃的用户
上个月这些用户致力于 [帮助他人解决 GitHub 的 issues](help-fastapi.md#help-others-with-issues-in-github){.internal-link target=_blank}。
{% if people %}
<div class="user-list user-list-center">
{% for user in people.last_month_active %}
<div class="user"><a href="{{ user.url }}" target="_blank"><div class="avatar-wrapper"><img src="{{ user.avatarUrl }}"/></div><div class="title">@{{ user.login }}</div></a> <div class="count">Issues replied: {{ user.count }}</div></div>
{% endfor %}
</div>
{% endif %}
## 专家组
以下是 **FastAPI 专家**。 🤓
这些用户一直以来致力于 [帮助他人解决 GitHub 的 issues](help-fastapi.md#help-others-with-issues-in-github){.internal-link target=_blank}。
他们通过帮助许多人而被证明是专家。✨
{% if people %}
<div class="user-list user-list-center">
{% for user in people.experts %}
<div class="user"><a href="{{ user.url }}" target="_blank"><div class="avatar-wrapper"><img src="{{ user.avatarUrl }}"/></div><div class="title">@{{ user.login }}</div></a> <div class="count">Issues replied: {{ user.count }}</div></div>
{% endfor %}
</div>
{% endif %}
## 杰出贡献者
以下是 **杰出的贡献者**。 👷
这些用户 [创建了最多已被合并的 Pull Requests](help-fastapi.md#create-a-pull-request){.internal-link target=_blank}。
他们贡献了源代码,文档,翻译等。 📦
{% if people %}
<div class="user-list user-list-center">
{% for user in people.top_contributors %}
<div class="user"><a href="{{ user.url }}" target="_blank"><div class="avatar-wrapper"><img src="{{ user.avatarUrl }}"/></div><div class="title">@{{ user.login }}</div></a> <div class="count">Pull Requests: {{ user.count }}</div></div>
{% endfor %}
</div>
{% endif %}
还有很多其他贡献者超过100个你可以在 <a href="https://github.com/tiangolo/fastapi/graphs/contributors" class="external-link" target="_blank">FastAPI GitHub 贡献者页面</a> 中看到他们。👷
## 杰出审核者
以下用户是「杰出的评审者」。 🕵️
### 翻译审核
我只会说少数几种语言(而且还不是很流利 😅)。所以,具备[能力去批准文档翻译](contributing.md#translations){.internal-link target=_blank} 是这些评审者们。如果没有它们,就不会有多语言文档。
---
**杰出的评审者** 🕵️ 评审了最多来自他人的 Pull Requests他们保证了代码、文档尤其是 **翻译** 的质量。
{% if people %}
<div class="user-list user-list-center">
{% for user in people.top_reviewers %}
<div class="user"><a href="{{ user.url }}" target="_blank"><div class="avatar-wrapper"><img src="{{ user.avatarUrl }}"/></div><div class="title">@{{ user.login }}</div></a> <div class="count">Reviews: {{ user.count }}</div></div>
{% endfor %}
</div>
{% endif %}
## 赞助商
以下是 **赞助商** 。😎
他们主要通过<a href="https://github.com/sponsors/tiangolo" class="external-link" target="_blank">GitHub Sponsors</a>支持我在 **FastAPI** (和其他项目)的工作。
### 金牌赞助商
{% if sponsors %}
{% for sponsor in sponsors.gold -%}
<a href="{{ sponsor.url }}" target="_blank" title="{{ sponsor.title }}"><img src="{{ sponsor.img }}" style="border-radius:15px"></a>
{% endfor %}
{% endif %}
### 银牌赞助商
{% if sponsors %}
{% for sponsor in sponsors.silver -%}
<a href="{{ sponsor.url }}" target="_blank" title="{{ sponsor.title }}"><img src="{{ sponsor.img }}" style="border-radius:15px"></a>
{% endfor %}
{% endif %}
### 铜牌赞助商
{% if sponsors %}
{% for sponsor in sponsors.bronze -%}
<a href="{{ sponsor.url }}" target="_blank" title="{{ sponsor.title }}"><img src="{{ sponsor.img }}" style="border-radius:15px"></a>
{% endfor %}
{% endif %}
### 个人赞助
{% if people %}
{% if people.sponsors_50 %}
<div class="user-list user-list-center">
{% for user in people.sponsors_50 %}
<div class="user"><a href="{{ user.url }}" target="_blank"><div class="avatar-wrapper"><img src="{{ user.avatarUrl }}"/></div><div class="title">@{{ user.login }}</div></a></div>
{% endfor %}
</div>
{% endif %}
{% endif %}
{% if people %}
<div class="user-list user-list-center">
{% for user in people.sponsors %}
<div class="user"><a href="{{ user.url }}" target="_blank"><div class="avatar-wrapper"><img src="{{ user.avatarUrl }}"/></div><div class="title">@{{ user.login }}</div></a></div>
{% endfor %}
</div>
{% endif %}
## 关于数据 - 技术细节
该页面的目的是突出社区为帮助他人而付出的努力。
尤其是那些不引人注目且涉及更困难的任务,例如帮助他人解决问题或者评审翻译 Pull Requests。
该数据每月计算一次,您可以阅读 <a href="https://github.com/tiangolo/fastapi/blob/master/.github/actions/people/app/main.py" class="external-link" target="_blank">源代码</a>。
这里也强调了赞助商的贡献。
我也保留更新算法,栏目,统计阈值等的权利(以防万一🤷)。

View File

@@ -40,13 +40,16 @@ FastAPI 是一个用于构建 API 的现代、快速(高性能)的 web 框
<small>* 根据对某个构建线上应用的内部开发团队所进行的测试估算得出。</small>
## Gold Sponsors
## Sponsors
<!-- sponsors -->
{% if sponsors %}
{% for sponsor in sponsors.gold -%}
<a href="{{ sponsor.url }}" target="_blank" title="{{ sponsor.title }}"><img src="{{ sponsor.img }}"></a>
<a href="{{ sponsor.url }}" target="_blank" title="{{ sponsor.title }}"><img src="{{ sponsor.img }}" style="border-radius:15px"></a>
{% endfor -%}
{%- for sponsor in sponsors.silver -%}
<a href="{{ sponsor.url }}" target="_blank" title="{{ sponsor.title }}"><img src="{{ sponsor.img }}" style="border-radius:15px"></a>
{% endfor %}
{% endif %}

View File

@@ -222,13 +222,13 @@ John Doe
假设你有一个名为 `Person` 的类,拥有 name 属性:
```Python hl_lines="1-3"
{!../../../docs_src/python_types/tutorial009.py!}
{!../../../docs_src/python_types/tutorial010.py!}
```
接下来,你可以将一个变量声明为 `Person` 类型:
```Python hl_lines="6"
{!../../../docs_src/python_types/tutorial009.py!}
{!../../../docs_src/python_types/tutorial010.py!}
```
然后,你将再次获得所有的编辑器支持:

View File

@@ -0,0 +1,101 @@
# 请求体 - 更新数据
## 用 `PUT` 更新数据
更新数据请用 <a href="https://developer.mozilla.org/zh-CN/docs/Web/HTTP/Methods/PUT" class="external-link" target="_blank">HTTP `PUT`</a> 操作。
把输入数据转换为以 JSON 格式存储的数据(比如,使用 NoSQL 数据库时),可以使用 `jsonable_encoder`。例如,把 `datetime` 转换为 `str`
```Python hl_lines="30-35"
{!../../../docs_src/body_updates/tutorial001.py!}
```
`PUT` 用于接收替换现有数据的数据。
### 关于更新数据的警告
用 `PUT` 把数据项 `bar` 更新为以下内容时:
```Python
{
"name": "Barz",
"price": 3,
"description": None,
}
```
因为上述数据未包含已存储的属性 `"tax": 20.2`,新的输入模型会把 `"tax": 10.5` 作为默认值。
因此,本次操作把 `tax` 的值「更新」为 `10.5`。
## 用 `PATCH` 进行部分更新
<a href="https://developer.mozilla.org/zh-CN/docs/Web/HTTP/Methods/PATCH" class="external-link" target="_blank">HTTP `PATCH`</a> 操作用于更新 *部分* 数据。
即,只发送要更新的数据,其余数据保持不变。
!!! Note "笔记"
`PATCH` 没有 `PUT` 知名,也怎么不常用。
很多人甚至只用 `PUT` 实现部分更新。
**FastAPI** 对此没有任何限制,可以**随意**互换使用这两种操作。
但本指南也会分别介绍这两种操作各自的用途。
### 使用 Pydantic 的 `exclude_unset` 参数
更新部分数据时,可以在 Pydantic 模型的 `.dict()` 中使用 `exclude_unset` 参数。
比如,`item.dict(exclude_unset=True)`。
这段代码生成的 `dict` 只包含创建 `item` 模型时显式设置的数据,而不包括默认值。
然后再用它生成一个只含已设置(在请求中所发送)数据,且省略了默认值的 `dict`
```Python hl_lines="34"
{!../../../docs_src/body_updates/tutorial002.py!}
```
### 使用 Pydantic 的 `update` 参数
接下来,用 `.copy()` 为已有模型创建调用 `update` 参数的副本,该参数为包含更新数据的 `dict`。
例如,`stored_item_model.copy(update=update_data)`
```Python hl_lines="35"
{!../../../docs_src/body_updates/tutorial002.py!}
```
### 更新部分数据小结
简而言之,更新部分数据应:
* 使用 `PATCH` 而不是 `PUT` (可选,也可以用 `PUT`
* 提取存储的数据;
* 把数据放入 Pydantic 模型;
* 生成不含输入模型默认值的 `dict` (使用 `exclude_unset` 参数);
* 只更新用户设置过的值,不用模型中的默认值覆盖已存储过的值。
* 为已存储的模型创建副本,用接收的数据更新其属性 (使用 `update` 参数)。
* 把模型副本转换为可存入数据库的形式(比如,使用 `jsonable_encoder`)。
* 这种方式与 Pydantic 模型的 `.dict()` 方法类似,但能确保把值转换为适配 JSON 的数据类型,例如, 把 `datetime` 转换为 `str` 。
* 把数据保存至数据库;
* 返回更新后的模型。
```Python hl_lines="30-37"
{!../../../docs_src/body_updates/tutorial002.py!}
```
!!! tip "提示"
实际上HTTP `PUT` 也可以完成相同的操作。
但本节以 `PATCH` 为例的原因是,该操作就是为了这种用例创建的。
!!! note "笔记"
注意,输入模型仍需验证。
因此,如果希望接收的部分更新数据可以省略其他所有属性,则要把模型中所有的属性标记为可选(使用默认值或 `None`)。
为了区分用于**更新**所有可选值的模型与用于**创建**包含必选值的模型,请参照[更多模型](extra-models.md){.internal-link target=_blank} 一节中的思路。

View File

@@ -0,0 +1,18 @@
# 全局依赖项
有时,我们要为整个应用添加依赖项。
通过与定义[*路径装饰器依赖项*](dependencies-in-path-operation-decorators.md){.internal-link target=_blank} 类似的方式,可以把依赖项添加至整个 `FastAPI` 应用。
这样一来,就可以为所有*路径操作*应用该依赖项:
```Python hl_lines="15"
{!../../../docs_src/dependencies/tutorial012.py!}
```
[*路径装饰器依赖项*](dependencies-in-path-operation-decorators.md){.internal-link target=_blank} 一章的思路均适用于全局依赖项, 在本例中,这些依赖项可以用于应用中的所有*路径操作*。
## 为一组路径操作定义依赖项
稍后,[大型应用 - 多文件](../../tutorial/bigger-applications.md){.internal-link target=_blank}一章中会介绍如何使用多个文件创建大型应用程序,在这一章中,您将了解到如何为一组*路径操作*声明单个 `dependencies` 参数。

View File

@@ -0,0 +1,212 @@
# 依赖项 - 第一步
FastAPI 提供了简单易用,但功能强大的**<abbr title="也称为组件、资源、提供者、服务、可注入项">依赖注入</abbr>**系统。
这个依赖系统设计的简单易用,可以让开发人员轻松地把组件集成至 **FastAPI**
## 什么是「依赖注入」
编程中的**「依赖注入」**是声明代码(本文中为*路径操作函数* )运行所需的,或要使用的「依赖」的一种方式。
然后,由系统(本文中为 **FastAPI**)负责执行任意需要的逻辑,为代码提供这些依赖(「注入」依赖项)。
依赖注入常用于以下场景:
* 共享业务逻辑(复用相同的代码逻辑)
* 共享数据库连接
* 实现安全、验证、角色权限
* 等……
上述场景均可以使用**依赖注入**,将代码重复最小化。
## 第一步
接下来,我们学习一个非常简单的例子,尽管它过于简单,不是很实用。
但通过这个例子,您可以初步了解「依赖注入」的工作机制。
### 创建依赖项
首先,要关注的是依赖项。
依赖项就是一个函数,且可以使用与*路径操作函数*相同的参数:
```Python hl_lines="8-9"
{!../../../docs_src/dependencies/tutorial001.py!}
```
大功告成。
只用了**2 行**代码。
依赖项函数的形式和结构与*路径操作函数*一样。
因此,可以把依赖项当作没有「装饰器」(即,没有 `@app.get("/some-path")` )的路径操作函数。
依赖项可以返回各种内容。
本例中的依赖项预期接收如下参数:
* 类型为 `str` 的可选查询参数 `q`
* 类型为 `int` 的可选查询参数 `skip`,默认值是 `0`
* 类型为 `int` 的可选查询参数 `limit`,默认值是 `100`
然后,依赖项函数返回包含这些值的 `dict`。
### 导入 `Depends`
```Python hl_lines="3"
{!../../../docs_src/dependencies/tutorial001.py!}
```
### 声明依赖项
与在*路径操作函数*参数中使用 `Body`、`Query` 的方式相同,声明依赖项需要使用 `Depends` 和一个新的参数:
```Python hl_lines="13 18"
{!../../../docs_src/dependencies/tutorial001.py!}
```
虽然,在路径操作函数的参数中使用 `Depends` 的方式与 `Body`、`Query` 相同,但 `Depends` 的工作方式略有不同。
这里只能传给 Depends 一个参数。
且该参数必须是可调用对象,比如函数。
该函数接收的参数和*路径操作函数*的参数一样。
!!! tip "提示"
下一章介绍,除了函数还有哪些「对象」可以用作依赖项。
接收到新的请求时,**FastAPI** 执行如下操作:
* 用正确的参数调用依赖项函数(「可依赖项」)
* 获取函数返回的结果
* 把函数返回的结果赋值给*路径操作函数*的参数
```mermaid
graph TB
common_parameters(["common_parameters"])
read_items["/items/"]
read_users["/users/"]
common_parameters --> read_items
common_parameters --> read_users
```
这样,只编写一次代码,**FastAPI** 就可以为多个*路径操作*共享这段代码 。
!!! check "检查"
注意,无需创建专门的类,并将之传递给 **FastAPI** 以进行「注册」或执行类似的操作。
只要把它传递给 `Depends`**FastAPI** 就知道该如何执行后续操作。
## 要不要使用 `async`
**FastAPI** 调用依赖项的方式与*路径操作函数*一样,因此,定义依赖项函数,也要应用与路径操作函数相同的规则。
即,既可以使用异步的 `async def`,也可以使用普通的 `def` 定义依赖项。
在普通的 `def` *路径操作函数*中,可以声明异步的 `async def` 依赖项;也可以在异步的 `async def` *路径操作函数*中声明普通的 `def` 依赖项。
上述这些操作都是可行的,**FastAPI** 知道该怎么处理。
!!! note "笔记"
如里不了解异步,请参阅[异步:*“着急了?”*](../../async.md){.internal-link target=_blank} 一章中 `async` 和 `await` 的内容。
## 与 OpenAPI 集成
依赖项及子依赖项的所有请求声明、验证和需求都可以集成至同一个 OpenAPI 概图。
所以,交互文档里也会显示依赖项的所有信息:
<img src="/img/tutorial/dependencies/image01.png">
## 简单用法
观察一下就会发现,只要*路径* 和*操作*匹配,就可以使用声明的路径操作函数。然后,**FastAPI** 会用正确的参数调用函数,并提取请求中的数据。
实际上,所有(或大多数)网络框架的工作方式都是这样的。
开发人员永远都不需要直接调用这些函数,这些函数是由框架(在此为 **FastAPI** )调用的。
通过依赖注入系统,只要告诉 **FastAPI** *路径操作函数* 还要「依赖」其他在*路径操作函数*之前执行的内容,**FastAPI** 就会执行函数代码,并「注入」函数返回的结果。
其他与「依赖注入」概念相同的术语为:
* 资源Resource
* 提供方Provider
* 服务Service
* 可注入Injectable
* 组件Component
## **FastAPI** 插件
**依赖注入**系统支持构建集成和「插件」。但实际上FastAPI 根本**不需要创建「插件」**,因为使用依赖项可以声明不限数量的、可用于*路径操作函数*的集成与交互。
创建依赖项非常简单、直观,并且还支持导入 Python 包。毫不夸张地说,只要几行代码就可以把需要的 Python 包与 API 函数集成在一起。
下一章将详细介绍在关系型数据库、NoSQL 数据库、安全等方面使用依赖项的例子。
## **FastAPI** 兼容性
依赖注入系统如此简洁的特性,让 **FastAPI** 可以与下列系统兼容:
* 关系型数据库
* NoSQL 数据库
* 外部支持库
* 外部 API
* 认证和鉴权系统
* API 使用监控系统
* 响应数据注入系统
* 等等……
## 简单而强大
虽然,**层级式依赖注入系统**的定义与使用十分简单,但它却非常强大。
比如,可以定义依赖其他依赖项的依赖项。
最后,依赖项层级树构建后,**依赖注入系统**会处理所有依赖项及其子依赖项,并为每一步操作提供(注入)结果。
比如,下面有 4 个 API 路径操作(*端点*
* `/items/public/`
* `/items/private/`
* `/users/{user_id}/activate`
* `/items/pro/`
开发人员可以使用依赖项及其子依赖项为这些路径操作添加不同的权限:
```mermaid
graph TB
current_user(["current_user"])
active_user(["active_user"])
admin_user(["admin_user"])
paying_user(["paying_user"])
public["/items/public/"]
private["/items/private/"]
activate_user["/users/{user_id}/activate"]
pro_items["/items/pro/"]
current_user --> active_user
active_user --> admin_user
active_user --> paying_user
current_user --> public
active_user --> private
admin_user --> activate_user
paying_user --> pro_items
```
## 与 **OpenAPI** 集成
在声明需求时,所有这些依赖项还会把参数、验证等功能添加至路径操作。
**FastAPI** 负责把上述内容全部添加到 OpenAPI 概图,并显示在交互文档中。

View File

@@ -0,0 +1,289 @@
# 处理错误
某些情况下,需要向客户端返回错误提示。
这里所谓的客户端包括前端浏览器、其他应用程序、物联网设备等。
需要向客户端返回错误提示的场景主要如下:
- 客户端没有执行操作的权限
- 客户端没有访问资源的权限
- 客户端要访问的项目不存在
- 等等 ...
遇到这些情况时,通常要返回 **4XX**400 至 499**HTTP 状态码**。
**4XX** 状态码与表示请求成功的 **2XX**200 至 299 HTTP 状态码类似。
只不过,**4XX** 状态码表示客户端发生的错误。
大家都知道**「404 Not Found」**错误,还有调侃这个错误的笑话吧?
## 使用 `HTTPException`
向客户端返回 HTTP 错误响应,可以使用 `HTTPException`
### 导入 `HTTPException`
```Python hl_lines="1"
{!../../../docs_src/handling_errors/tutorial001.py!}
```
### 触发 `HTTPException`
`HTTPException` 是额外包含了和 API 有关数据的常规 Python 异常。
因为是 Python 异常,所以不能 `return`,只能 `raise`。
如在调用*路径操作函数*里的工具函数时,触发了 `HTTPException`FastAPI 就不再继续执行*路径操作函数*中的后续代码,而是立即终止请求,并把 `HTTPException` 的 HTTP 错误发送至客户端。
在介绍依赖项与安全的章节中,您可以了解更多用 `raise` 异常代替 `return` 值的优势。
本例中,客户端用 `ID` 请求的 `item` 不存在时,触发状态码为 `404` 的异常:
```Python hl_lines="11"
{!../../../docs_src/handling_errors/tutorial001.py!}
```
### 响应结果
请求为 `http://example.com/items/foo``item_id` 为 `「foo」`)时,客户端会接收到 HTTP 状态码 - 200 及如下 JSON 响应结果:
```JSON
{
"item": "The Foo Wrestlers"
}
```
但如果客户端请求 `http://example.com/items/bar``item_id` `「bar」` 不存在时),则会接收到 HTTP 状态码 - 404「未找到」错误及如下 JSON 响应结果:
```JSON
{
"detail": "Item not found"
}
```
!!! tip "提示"
触发 `HTTPException` 时,可以用参数 `detail` 传递任何能转换为 JSON 的值,不仅限于 `str`。
还支持传递 `dict`、`list` 等数据结构。
**FastAPI** 能自动处理这些数据,并将之转换为 JSON。
## 添加自定义响应头
有些场景下要为 HTTP 错误添加自定义响应头。例如,出于某些方面的安全需要。
一般情况下可能不会需要在代码中直接使用响应头。
但对于某些高级应用场景,还是需要添加自定义响应头:
```Python hl_lines="14"
{!../../../docs_src/handling_errors/tutorial002.py!}
```
## 安装自定义异常处理器
添加自定义处理器,要使用 [Starlette 的异常工具](https://www.starlette.io/exceptions/)。
假设要触发的自定义异常叫作 `UnicornException`。
且需要 FastAPI 实现全局处理该异常。
此时,可以用 `@app.exception_handler()` 添加自定义异常控制器:
```Python hl_lines="5-7 13-18 24"
{!../../../docs_src/handling_errors/tutorial003.py!}
```
请求 `/unicorns/yolo` 时,路径操作会触发 `UnicornException`。
但该异常将会被 `unicorn_exception_handler` 处理。
接收到的错误信息清晰明了HTTP 状态码为 `418`JSON 内容如下:
```JSON
{"message": "Oops! yolo did something. There goes a rainbow..."}
```
!!! note "技术细节"
`from starlette.requests import Request` 和 `from starlette.responses import JSONResponse` 也可以用于导入 `Request` 和 `JSONResponse`。
**FastAPI** 提供了与 `starlette.responses` 相同的 `fastapi.responses` 作为快捷方式,但大部分响应操作都可以直接从 Starlette 导入。同理,`Request` 也是如此。
## 覆盖默认异常处理器
**FastAPI** 自带了一些默认异常处理器。
触发 `HTTPException` 或请求无效数据时,这些处理器返回默认的 JSON 响应结果。
不过,也可以使用自定义处理器覆盖默认异常处理器。
### 覆盖请求验证异常
请求中包含无效数据时,**FastAPI** 内部会触发 `RequestValidationError`。
该异常也内置了默认异常处理器。
覆盖默认异常处理器时需要导入 `RequestValidationError`,并用 `@app.excption_handler(RequestValidationError)` 装饰异常处理器。
这样,异常处理器就可以接收 `Request` 与异常。
```Python hl_lines="2 14-16"
{!../../../docs_src/handling_errors/tutorial004.py!}
```
访问 `/items/foo`,可以看到以下内容替换了默认 JSON 错误信息:
```JSON
{
"detail": [
{
"loc": [
"path",
"item_id"
],
"msg": "value is not a valid integer",
"type": "type_error.integer"
}
]
}
```
以下是文本格式的错误信息:
```
1 validation error
path -> item_id
value is not a valid integer (type=type_error.integer)
```
### `RequestValidationError` vs `ValidationError`
!!! warning "警告"
如果您觉得现在还用不到以下技术细节,可以先跳过下面的内容。
`RequestValidationError` 是 Pydantic 的 <a href="https://pydantic-docs.helpmanual.io/#error-handling" class="external-link" target="_blank">`ValidationError`</a> 的子类。
**FastAPI** 调用的就是 `RequestValidationError` 类,因此,如果在 `response_model` 中使用 Pydantic 模型,且数据有错误时,在日志中就会看到这个错误。
但客户端或用户看不到这个错误。反之,客户端接收到的是 HTTP 状态码为 `500` 的「内部服务器错误」。
这是因为在*响应*或代码(不是在客户端的请求里)中出现的 Pydantic `ValidationError` 是代码的 bug。
修复错误时,客户端或用户不能访问错误的内部信息,否则会造成安全隐患。
### 覆盖 `HTTPException` 错误处理器
同理,也可以覆盖 `HTTPException` 处理器。
例如,只为错误返回纯文本响应,而不是返回 JSON 格式的内容:
```Python hl_lines="3-4 9-11 22"
{!../../../docs_src/handling_errors/tutorial004.py!}
```
!!! note "技术细节"
还可以使用 `from starlette.responses import PlainTextResponse`。
**FastAPI** 提供了与 `starlette.responses` 相同的 `fastapi.responses` 作为快捷方式,但大部分响应都可以直接从 Starlette 导入。
### 使用 `RequestValidationError` 的请求体
`RequestValidationError` 包含其接收到的无效数据请求的 `body` 。
开发时,可以用这个请求体生成日志、调试错误,并返回给用户。
```Python hl_lines="14"
{!../../../docs_src/handling_errors/tutorial005.py!}
```
现在试着发送一个无效的 `item`,例如:
```JSON
{
"title": "towel",
"size": "XL"
}
```
收到的响应包含 `body` 信息,并说明数据是无效的:
```JSON hl_lines="12-15"
{
"detail": [
{
"loc": [
"body",
"size"
],
"msg": "value is not a valid integer",
"type": "type_error.integer"
}
],
"body": {
"title": "towel",
"size": "XL"
}
}
```
### FastAPI `HTTPException` vs Starlette `HTTPException`
**FastAPI** 也提供了自有的 `HTTPException`。
**FastAPI** 的 `HTTPException` 继承自 Starlette 的 `HTTPException` 错误类。
它们之间的唯一区别是,**FastAPI** 的 `HTTPException` 可以在响应中添加响应头。
OAuth 2.0 等安全工具需要在内部调用这些响应头。
因此你可以继续像平常一样在代码中触发 **FastAPI** 的 `HTTPException` 。
但注册异常处理器时,应该注册到来自 Starlette 的 `HTTPException`。
这样做是为了,当 Starlette 的内部代码、扩展或插件触发 Starlette `HTTPException` 时,处理程序能够捕获、并处理此异常。
注意,本例代码中同时使用了这两个 `HTTPException`,此时,要把 Starlette 的 `HTTPException` 命名为 `StarletteHTTPException`
```Python
from starlette.exceptions import HTTPException as StarletteHTTPException
```
### 复用 **FastAPI** 异常处理器
FastAPI 支持先对异常进行某些处理,然后再使用 **FastAPI** 中处理该异常的默认异常处理器。
从 `fastapi.exception_handlers` 中导入要复用的默认异常处理器:
```Python hl_lines="2-5 15 21"
{!../../../docs_src/handling_errors/tutorial006.py!}
```
虽然,本例只是输出了夸大其词的错误信息。
但也足以说明,可以在处理异常之后再复用默认的异常处理器。

View File

@@ -0,0 +1,153 @@
# 请求文件
`File` 用于定义客户端的上传文件。
!!! info "说明"
因为上传文件以「表单数据」形式发送。
所以接收上传文件,要预先安装 <a href="https://andrew-d.github.io/python-multipart/" class="external-link" target="_blank">`python-multipart`</a>。
例如: `pip install python-multipart`
## 导入 `File`
`fastapi` 导入 `File``UploadFile`
```Python hl_lines="1"
{!../../../docs_src/request_files/tutorial001.py!}
```
## 定义 `File` 参数
创建文件(`File`)参数的方式与 `Body` 和 `Form` 一样:
```Python hl_lines="7"
{!../../../docs_src/request_files/tutorial001.py!}
```
!!! info "说明"
`File` 是直接继承自 `Form` 的类。
注意,从 `fastapi` 导入的 `Query`、`Path`、`File` 等项,实际上是返回特定类的函数。
!!! tip "提示"
声明文件体必须使用 `File`否则FastAPI 会把该参数当作查询参数或请求体JSON参数。
文件作为「表单数据」上传。
如果把*路径操作函数*参数的类型声明为 `bytes`**FastAPI** 将以 `bytes` 形式读取和接收文件内容。
这种方式把文件的所有内容都存储在内存里,适用于小型文件。
不过,很多情况下,`UploadFile` 更好用。
## 含 `UploadFile` 的 `File` 参数
定义 `File` 参数时使用 `UploadFile`
```Python hl_lines="12"
{!../../../docs_src/request_files/tutorial001.py!}
```
`UploadFile` 与 `bytes` 相比有更多优势:
* 使用 `spooled` 文件:
* 存储在内存的文件超出最大上限时FastAPI 会把文件存入磁盘;
* 这种方式更适于处理图像、视频、二进制文件等大型文件,好处是不会占用所有内存;
* 可获取上传文件的元数据;
* 自带 <a href="https://docs.python.org/zh-cn/3/glossary.html#term-file-like-object" class="external-link" target="_blank">file-like</a> `async` 接口;
* 暴露的 Python <a href="https://docs.python.org/zh-cn/3/library/tempfile.html#tempfile.SpooledTemporaryFile" class="external-link" target="_blank">`SpooledTemporaryFile`</a> 对象可直接传递给其他预期「file-like」对象的库。
### `UploadFile`
`UploadFile` 的属性如下:
* `filename`:上传文件名字符串(`str`),例如, `myimage.jpg`
* `content_type`内容类型MIME 类型 / 媒体类型)字符串(`str`),例如,`image/jpeg`
* `file` <a href="https://docs.python.org/zh-cn/3/library/tempfile.html#tempfile.SpooledTemporaryFile" class="external-link" target="_blank">`SpooledTemporaryFile`</a> <a href="https://docs.python.org/zh-cn/3/glossary.html#term-file-like-object" class="external-link" target="_blank">file-like</a> 对象)。其实就是 Python文件可直接传递给其他预期 `file-like` 对象的函数或支持库。
`UploadFile` 支持以下 `async` 方法,(使用内部 `SpooledTemporaryFile`)可调用相应的文件方法。
* `write(data)`:把 `data` `str` 或 `bytes`)写入文件;
* `read(size)`:按指定数量的字节或字符(`size` (`int`))读取文件内容;
* `seek(offset)`:移动至文件 `offset` `int`)字节处的位置;
* 例如,`await myfile.seek(0) ` 移动到文件开头;
* 执行 `await myfile.read()` 后,需再次读取已读取内容时,这种方法特别好用;
* `close()`:关闭文件。
因为上述方法都是 `async` 方法要搭配「await」使用。
例如,在 `async` *路径操作函数* 内,要用以下方式读取文件内容:
```Python
contents = await myfile.read()
```
在普通 `def` *路径操作函数* 内,则可以直接访问 `UploadFile.file`,例如:
```Python
contents = myfile.file.read()
```
!!! note "`async` 技术细节"
使用 `async` 方法时,**FastAPI** 在线程池中执行文件方法,并 `awiat` 操作完成。
!!! note "Starlette 技术细节"
**FastAPI** 的 `UploadFile` 直接继承自 **Starlette** 的 `UploadFile`,但添加了一些必要功能,使之与 **Pydantic** 及 FastAPI 的其它部件兼容。
## 什么是 「表单数据」
与 JSON 不同HTML 表单(`<form></form>`)向服务器发送数据通常使用「特殊」的编码。
**FastAPI** 要确保从正确的位置读取数据,而不是读取 JSON。
!!! note "技术细节"
不包含文件时,表单数据一般用 `application/x-www-form-urlencoded`「媒体类型」编码。
但表单包含文件时,编码为 `multipart/form-data`。使用了 `File`**FastAPI** 就知道要从请求体的正确位置获取文件。
编码和表单字段详见 <a href="https://developer.mozilla.org/zh-CN/docs/Web/HTTP/Methods/POST" class="external-link" target="_blank"><abbr title="Mozilla Developer Network">MDN</abbr> Web 文档的 <code>POST </code></a> 小节。
!!! warning "警告"
可在一个*路径操作*中声明多个 `File` 和 `Form` 参数,但不能同时声明要接收 JSON 的 `Body` 字段。因为此时请求体的编码是 `multipart/form-data`,不是 `application/json`。
这不是 **FastAPI** 的问题,而是 HTTP 协议的规定。
## 多文件上传
FastAPI 支持同时上传多个文件。
可用同一个「表单字段」发送含多个文件的「表单数据」。
上传多个文件时,要声明含 `bytes` 或 `UploadFile` 的列表(`List`
```Python hl_lines="10 15"
{!../../../docs_src/request_files/tutorial002.py!}
```
接收的也是含 `bytes` 或 `UploadFile` 的列表(`list`)。
!!! note "笔记"
注意,截至 2019 年 4 月 14 日Swagger UI 不支持在同一个表单字段中上传多个文件。详见 <a href="https://github.com/swagger-api/swagger-ui/issues/4276" class="external-link" target="_blank">#4276</a> 和 <a href="https://github.com/swagger-api/swagger-ui/issues/3641" class="external-link" target="_blank">#3641</a>.
不过,**FastAPI** 已通过 OpenAPI 标准与之兼容。
因此,只要 Swagger UI 或任何其他支持 OpenAPI 的工具支持多文件上传,都将与 **FastAPI** 兼容。
!!! note "技术细节"
也可以使用 `from starlette.responses import HTMLResponse`。
`fastapi.responses` 其实与 `starlette.responses` 相同,只是为了方便开发者调用。实际上,大多数 **FastAPI** 的响应都直接从 Starlette 调用。
## 小结
本节介绍了如何用 `File` 把上传文件声明为(表单数据的)输入参数。

View File

@@ -0,0 +1,38 @@
# 请求表单与文件
FastAPI 支持同时使用 `File``Form` 定义文件和表单字段。
!!! info "说明"
接收上传文件或表单数据,要预先安装 <a href="https://andrew-d.github.io/python-multipart/" class="external-link" target="_blank">`python-multipart`</a>。
例如,`pip install python-multipart`
## 导入 `File` 与 `Form`
```Python hl_lines="1"
{!../../../docs_src/request_forms_and_files/tutorial001.py!}
```
## 定义 `File` 与 `Form` 参数
创建文件和表单参数的方式与 `Body` 和 `Query` 一样:
```Python hl_lines="8"
{!../../../docs_src/request_forms_and_files/tutorial001.py!}
```
文件和表单字段作为表单数据上传与接收。
声明文件可以使用 `bytes` 或 `UploadFile` 。
!!! warning "警告"
可在一个*路径操作*中声明多个 `File` 与 `Form` 参数,但不能同时声明要接收 JSON 的 `Body` 字段。因为此时请求体的编码为 `multipart/form-data`,不是 `application/json`。
这不是 **FastAPI** 的问题,而是 HTTP 协议的规定。
## 小结
在同一个请求中接收数据和文件时,应同时使用 `File` 和 `Form`。

View File

@@ -0,0 +1,63 @@
# 表单数据
接收的不是 JSON而是表单字段时要使用 `Form`
!!! info "说明"
要使用表单,需预先安装 <a href="https://andrew-d.github.io/python-multipart/" class="external-link" target="_blank">`python-multipart`</a>。
例如,`pip install python-multipart`
## 导入 `Form`
`fastapi` 导入 `Form`
```Python hl_lines="1"
{!../../../docs_src/request_forms/tutorial001.py!}
```
## 定义 `Form` 参数
创建表单(`Form`)参数的方式与 `Body` 和 `Query` 一样:
```Python hl_lines="7"
{!../../../docs_src/request_forms/tutorial001.py!}
```
例如OAuth2 规范的 "密码流" 模式规定要通过表单字段发送 `username` 和 `password`。
<abbr title="specification">该规范</abbr>要求字段必须命名为 `username` 和 `password`,并通过表单字段发送,不能用 JSON。
使用 `Form` 可以声明与 `Body` (及 `Query`、`Path`、`Cookie`)相同的元数据和验证。
!!! info "说明"
`Form` 是直接继承自 `Body` 的类。
!!! tip "提示"
声明表单体要显式使用 `Form` 否则FastAPI 会把该参数当作查询参数或请求体JSON参数。
## 关于 "表单字段"
与 JSON 不同HTML 表单(`<form></form>`)向服务器发送数据通常使用「特殊」的编码。
**FastAPI** 要确保从正确的位置读取数据,而不是读取 JSON。
!!! note "技术细节"
表单数据的「媒体类型」编码一般为 `application/x-www-form-urlencoded`。
但包含文件的表单编码为 `multipart/form-data`。文件处理详见下节。
编码和表单字段详见 <a href="https://developer.mozilla.org/zh-CN/docs/Web/HTTP/Methods/POST" class="external-link" target="_blank"><abbr title="Mozilla Developer Network">MDN</abbr> Web 文档的 <code>POST</code></a>小节。
!!! warning "警告"
可在一个*路径操作*中声明多个 `Form` 参数,但不能同时声明要接收 JSON 的 `Body` 字段。因为此时请求体的编码是 `application/x-www-form-urlencoded`,不是 `application/json`。
这不是 **FastAPI** 的问题,而是 HTTP 协议的规定。
## 小结
本节介绍了如何使用 `Form` 声明表单数据输入参数。

View File

@@ -39,8 +39,10 @@ nav:
- FastAPI: index.md
- Languages:
- en: /
- de: /de/
- es: /es/
- fr: /fr/
- id: /id/
- it: /it/
- ja: /ja/
- ko: /ko/
@@ -52,6 +54,7 @@ nav:
- uk: /uk/
- zh: /zh/
- features.md
- fastapi-people.md
- python-types.md
- 教程 - 用户指南:
- tutorial/index.md
@@ -72,6 +75,14 @@ nav:
- tutorial/schema-extra-example.md
- tutorial/extra-data-types.md
- tutorial/cookie-params.md
- tutorial/request-forms.md
- tutorial/request-files.md
- tutorial/request-forms-and-files.md
- tutorial/handling-errors.md
- tutorial/body-updates.md
- 依赖项:
- tutorial/dependencies/index.md
- tutorial/dependencies/global-dependencies.md
- 安全性:
- tutorial/security/index.md
- tutorial/security/get-current-user.md
@@ -114,7 +125,7 @@ extra:
- icon: fontawesome/brands/discord
link: https://discord.gg/VQjSZaeJmf
- icon: fontawesome/brands/twitter
link: https://twitter.com/tiangolo
link: https://twitter.com/fastapi
- icon: fontawesome/brands/linkedin
link: https://www.linkedin.com/in/tiangolo
- icon: fontawesome/brands/dev
@@ -126,10 +137,14 @@ extra:
alternate:
- link: /
name: en - English
- link: /de/
name: de
- link: /es/
name: es - español
- link: /fr/
name: fr - français
- link: /id/
name: id
- link: /it/
name: it - italiano
- link: /ja/

View File

@@ -5,5 +5,5 @@ app = FastAPI()
@app.get("/typer")
async def read_typer():
async def redirect_typer():
return RedirectResponse("https://typer.tiangolo.com")

View File

@@ -0,0 +1,9 @@
from fastapi import FastAPI
from fastapi.responses import RedirectResponse
app = FastAPI()
@app.get("/fastapi", response_class=RedirectResponse)
async def redirect_fastapi():
return "https://fastapi.tiangolo.com"

View File

@@ -0,0 +1,9 @@
from fastapi import FastAPI
from fastapi.responses import RedirectResponse
app = FastAPI()
@app.get("/pydantic", response_class=RedirectResponse, status_code=302)
async def redirect_pydantic():
return "https://pydantic-docs.helpmanual.io/"

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