Compare commits

...

47 Commits

Author SHA1 Message Date
Sebastián Ramírez
76b6fd5c18 🔖 Release 0.30.0 2019-06-20 12:32:24 +02:00
Sebastián Ramírez
a2fb716035 📝 Update release notes 2019-06-20 12:30:54 +02:00
Sebastián Ramírez
aa84ac8e3e Implement support for Pydantic's ORM mode (#322)
*  Implement support for Pydantic's ORM mode

* 🏗️ Re-structure/augment SQL tutorial source using ORM mode

* 📝 Update SQL docs with SQLAlchemy, ORM mode, relationships

* 🔥 Remove unused util in tutorial

* 📝 Add tutorials for simple dict bodies and responses

* 🔥 Remove old SQL tutorial

*  Add/update tests for SQL tutorial

*  Add tests for simple dicts (body and response)

* 🐛 Fix cloning field from original field
2019-06-20 11:31:32 +02:00
Sebastián Ramírez
4ed2bd1fea 📝 Update release notes 2019-06-18 13:54:36 +02:00
dmontagu
87b7a63ff2 🔥 Remove unused regex in routing.py (#314) 2019-06-18 13:52:34 +02:00
Sebastián Ramírez
06d0918c3d 📝 Update release notes 2019-06-18 09:49:43 +02:00
Eric Du
5b3adfe449 Use default response status reasons in additional responses (#313)
* default the description of additional response to status reason phrase

* fix 404 description

* fix lint warning

* allow custom response status code
2019-06-18 09:46:57 +02:00
Sebastián Ramírez
bdd794a0e6 📝 Update release notes 2019-06-18 09:40:31 +02:00
James Kaplan
f0df79aa91 ⬆️ Upgrade Pydantic to 0.28 (#320) 2019-06-18 09:37:40 +02:00
Sebastián Ramírez
c26f1760d4 🔖 Release 0.29.1 2019-06-13 18:47:43 +02:00
Sebastián Ramírez
e5fa4b0af6 📝 Update release notes 2019-06-13 18:39:17 +02:00
Sebastián Ramírez
a33c299fd7 🔧 Add format-imports script 2019-06-13 18:38:49 +02:00
Sebastián Ramírez
6939621730 bug: Fix handling an empty-body request with a required body param (#311)
* 🐛 Fix solving a required body param from an empty body request

*  Add tests for receiving required body parameters with body not provided
2019-06-13 18:37:48 +02:00
dmontagu
120ab08360 📝 Update response-directly.md, fix link (#306) 2019-06-13 18:34:20 +02:00
Andrew Widdersheim
3f5521fdfb 📝 Fix default response model docs (#288)
Fix a discrepancy in the `tax` parameters default value between the docs
and the code example.
2019-06-13 18:31:48 +02:00
Sebastián Ramírez
7244e4b612 🔖 Release version 0.29.0 2019-06-06 14:31:50 +04:00
Sebastián Ramírez
d329745064 📝 Update release notes 2019-06-06 14:30:28 +04:00
Sebastián Ramírez
5f7fe926ab Add support for Response parameters to set headers, cookies, and status codes (#294)
*  Add support for declaring a Response parameter to set headers and cookies

*  Add source for docs and tests

* 📝 Add docs for setting headers, cookies and status code

* 📝 Add attribution to Hug for inspiring response parameters
2019-06-06 14:29:40 +04:00
Sebastián Ramírez
c8eea09664 📝 Update release notes 2019-06-05 21:20:12 +04:00
Sebastián Ramírez
5700d65188 🔖 Release 0.28.0 2019-06-05 21:13:32 +04:00
Sebastián Ramírez
46178a5347 📝 Update release notes 2019-06-05 21:09:11 +04:00
Sebastián Ramírez
bff5dbbf5d Implement dependency value cache per request (#292)
*  Add dependency cache, with support for disabling it

*  Add tests for dependency cache

* 📝 Add docs about dependency value caching
2019-06-05 21:00:54 +04:00
Sebastián Ramírez
09cd7c47a1 Implement dependency overrides for testing (#291)
*  Implement dependency overrides for testing

*  Add docs source tests and extra tests for dependency overrides

* 📝 Add docs for testing dependencies with overrides
2019-06-05 15:43:18 +04:00
Sebastián Ramírez
e2fadcbc90 🔖 Release version 0.27.2 2019-06-03 22:03:24 +04:00
Sebastián Ramírez
b3bb29afa8 📝 Update relase notes 2019-06-03 22:01:09 +04:00
Sebastián Ramírez
c7db2ff858 🐛 Fix path and query parameters receiving dict as valid (#287)
* 🐛 Fix path and query parameters accepting dict

*  Add several tests to ensure invalid types are not accepted

* 📝 Document (to include tested source) using query params with list

* 🐛 Fix OpenAPI schema in query with list tutorial
2019-06-03 21:59:40 +04:00
Sebastián Ramírez
2a7ef5504a 🔖 Release 0.27.1 2019-06-03 18:44:03 +04:00
Sebastián Ramírez
27964c5ffd 📝 Update release notes 2019-06-01 10:00:26 +04:00
Sebastián Ramírez
d262f6e929 🐛 Fix HTTP Bearer security auto-error (#282) 2019-06-01 09:57:45 +04:00
Sebastián Ramírez
d61f5e4b55 📝 Update release notes 2019-05-30 19:43:32 +04:00
Sebastián Ramírez
3ed112e8a9 🐛 Fix type declaration of HTTPException (#279) 2019-05-30 19:43:02 +04:00
Sebastián Ramírez
9da626eb2c 🔖 Release version 0.27.0 2019-05-30 17:48:52 +04:00
Sebastián Ramírez
6f74c7327b 📝 Update release notes 2019-05-30 17:45:38 +04:00
dmontagu
360a2797c1 🐛 Fix docs link in oauth2-scopes.md (#275)
#274
2019-05-30 17:43:18 +04:00
Sebastián Ramírez
0552977cd6 📝 Update release notes 2019-05-30 17:41:40 +04:00
Sebastián Ramírez
bd407cc4ed Refactor param extraction using Pydantic Field (#278)
*  Refactor parameter dependency using Pydantic Field

* ⬆️ Upgrade required Pydantic version with latest Shape values

*  Add tutorials and code for using Enum and Optional

*  Add tests for tutorials with new types and extra cases

* ♻️ Format, clean, and add annotations to dependencies.utils

* 📝 Update tutorial for query parameters with list defaults

*  Add tests for query param with list default
2019-05-30 17:40:43 +04:00
Sebastián Ramírez
83b1a117cc 🔖 Release version 0.26.0 2019-05-29 19:29:44 +04:00
Sebastián Ramírez
2a1ff213a0 📝 Update release notes 2019-05-29 16:33:19 +04:00
Sebastián Ramírez
62af6e0eeb Separate Pydantic's ValidationError handler and improve docs for error handling (#273)
*  Implement separated ValidationError handlers and custom exceptions

*  Add tutorial source examples and tests

* 📝 Add docs for custom exception handlers

* 📝 Update docs section titles
2019-05-29 16:27:55 +04:00
Sebastián Ramírez
15da01af5c 📝 Update release notes 2019-05-29 13:46:27 +04:00
William Hayes
d544bdf092 📝 Update docs for paths in path params (#256) 2019-05-29 13:43:41 +04:00
Sebastián Ramírez
703ade7967 🐛 Fix path in path parameters (#272) 2019-05-29 13:34:46 +04:00
Sebastián Ramírez
58f135ba2f 📝 Update link in release notes 2019-05-29 11:51:43 +04:00
Sebastián Ramírez
713d374484 📝 Update release notes 2019-05-29 11:47:46 +04:00
Sebastián Ramírez
24e9ea28d3 Update testing docs, examples for testing POST, headers (#271) 2019-05-29 11:47:21 +04:00
Sebastián Ramírez
cae53138b2 📝 Update release notes 2019-05-27 21:56:49 +04:00
Sebastián Ramírez
a49d45eaa9 🐛 Fix response_model type to allow List[Model] (#266) 2019-05-27 21:56:20 +04:00
90 changed files with 4181 additions and 548 deletions

View File

@@ -26,7 +26,7 @@ uvicorn = "*"
[packages]
starlette = "==0.12.0"
pydantic = "==0.26.0"
pydantic = "==0.28.0"
databases = {extras = ["sqlite"],version = "*"}
hypercorn = "*"

159
Pipfile.lock generated
View File

@@ -1,7 +1,7 @@
{
"_meta": {
"hash": {
"sha256": "4a33b47e814fa75533548874ffadbc6163b3058db4d1615ff633512366d72ccb"
"sha256": "14f3b2d3a0457913244d4dc96fbf18ed356fbb43fbd10eae043270531afa61bb"
},
"pipfile-spec": 6,
"requires": {
@@ -56,10 +56,10 @@
},
"h11": {
"hashes": [
"sha256:acca6a44cb52a32ab442b1779adf0875c443c689e9e028f8d831a3769f9c5208",
"sha256:f2b1ca39bfed357d1f19ac732913d5f9faa54a5062eca7d2ec3a916cfb7ae4c7"
"sha256:33d4bca7be0fa039f4e84d50ab00531047e53d6ee8ffbc83501ea602c169cae1",
"sha256:4bc6d6a1238b7615b266ada57e0618568066f57dd6fa967d1290ec9309b2f2f1"
],
"version": "==0.8.1"
"version": "==0.9.0"
},
"h2": {
"hashes": [
@@ -113,11 +113,15 @@
},
"pydantic": {
"hashes": [
"sha256:b72e0df2463cee746cf42639845d4106c19f30136375e779352d710e69617731",
"sha256:dab99d3070e040b8b2e987dfbe237350ab92d5d57a22d4e0e268ede2d85c7964"
"sha256:3aafa1b58181c53a8e2971dc3c6f45945ddd18192b6f9c8e17f5ef2adcdf3987",
"sha256:60fe5aa17ecb5ba949e7e1e1f9b9500dae780d6c79c798bfd78ac5dd9f9d9517",
"sha256:92e4fb2917e4837e53edfee9f99c9075c152f9b9fe2b19d047b8fb25ed9bc089",
"sha256:98c5faf742baee5cbbe9ff609829df6ff4234863c4a992f8d46679df4d68aeab",
"sha256:bc4a051b81f31597efc96b4bf6a3aa75ea95ca0a87c4666ad5638be373e0c66a",
"sha256:d3d29768ae85c1333da5d10cbe793c6a01dcb1ec8ff86f1fbe2c588089bc11ea"
],
"index": "pypi",
"version": "==0.26.0"
"version": "==0.28.0"
},
"pytoml": {
"hashes": [
@@ -127,9 +131,9 @@
},
"sqlalchemy": {
"hashes": [
"sha256:91c54ca8345008fceaec987e10924bf07dcab36c442925357e5a467b36a38319"
"sha256:c30925d60af95443458ebd7525daf791f55762b106049ae71e18f8dd58084c2f"
],
"version": "==1.3.3"
"version": "==1.3.5"
},
"starlette": {
"hashes": [
@@ -148,10 +152,10 @@
},
"wsproto": {
"hashes": [
"sha256:55c3da870460e8838b2fbe4d10f3accc0cea3a13d5e8dbbdc6da5d537d6d44dc",
"sha256:c7f35e0af250b9f25583b090039eb2159a079fbe71b7daf86cc3ddcd2f3a70b3"
"sha256:2b870f5b5b4a6d23dce080a4ee1cbb119b2378f82593bd6d66ae2cbd72a7c0ad",
"sha256:ed222c812aaea55d72d18a87df429cfd602e15b6c992a07a53b495858f083a14"
],
"version": "==0.14.0"
"version": "==0.14.1"
}
},
"develop": {
@@ -215,10 +219,10 @@
},
"certifi": {
"hashes": [
"sha256:59b7658e26ca9c7339e00f8f4636cdfe59d34fa37b9b04f6f9e9926b3cece1a5",
"sha256:b26104d6835d1f5e49452a26eb2ff87fe7090b89dfcaee5ea2212697e1e1d7ae"
"sha256:046832c04d4e752f37383b628bc601a7ea7211496b4638f6514d0e5b9acc4939",
"sha256:945e3ba63a0b9f577b1395204e13c3a231f9bc0223888be653286534e5873695"
],
"version": "==2019.3.9"
"version": "==2019.6.16"
},
"chardet": {
"hashes": [
@@ -327,10 +331,16 @@
},
"h11": {
"hashes": [
"sha256:acca6a44cb52a32ab442b1779adf0875c443c689e9e028f8d831a3769f9c5208",
"sha256:f2b1ca39bfed357d1f19ac732913d5f9faa54a5062eca7d2ec3a916cfb7ae4c7"
"sha256:33d4bca7be0fa039f4e84d50ab00531047e53d6ee8ffbc83501ea602c169cae1",
"sha256:4bc6d6a1238b7615b266ada57e0618568066f57dd6fa967d1290ec9309b2f2f1"
],
"version": "==0.8.1"
"version": "==0.9.0"
},
"htmlmin": {
"hashes": [
"sha256:50c1ef4630374a5d723900096a961cff426dff46b48f34d194a81bbe14eca178"
],
"version": "==0.1.12"
},
"httptools": {
"hashes": [
@@ -345,6 +355,13 @@
],
"version": "==2.8"
},
"importlib-metadata": {
"hashes": [
"sha256:6dfd58dfe281e8d240937776065dd3624ad5469c835248219bd16cf2e12dbeb7",
"sha256:cb6ee23b46173539939964df59d3d72c3e0c1b5d54b84f1d8a7e912fe43612db"
],
"version": "==0.18"
},
"ipykernel": {
"hashes": [
"sha256:346189536b88859937b5f4848a6fd85d1ad0729f01724a411de5cae9b618819c",
@@ -396,6 +413,12 @@
],
"version": "==2.10.1"
},
"jsmin": {
"hashes": [
"sha256:b6df99b2cd1c75d9d342e4335b535789b8da9107ec748212706ef7bbe5c2553b"
],
"version": "==2.2.2"
},
"jsonschema": {
"hashes": [
"sha256:0c0a81564f181de3212efa2d17de1910f8732fa1b71c42266d983cd74304e20d",
@@ -511,11 +534,18 @@
},
"mkdocs-material": {
"hashes": [
"sha256:1c39b6af13a900d9f47ab2b8ac67b3258799f4570b552573e9d6868ad6a438e9",
"sha256:22073941cff7176e810b719aced6a90381e64a96d346b8a6803a06b7192b7ad5"
"sha256:451b949f6c8f0750b937f805e14c5bd40b81c5ff829072a74896efeaa6e8567f",
"sha256:8b5a042a0f2b54e631668e33d6a0777ff2c68331656066e26223c47159a255e1"
],
"index": "pypi",
"version": "==4.3.0"
"version": "==4.4.0"
},
"mkdocs-minify-plugin": {
"hashes": [
"sha256:3000a5069dd0f42f56a8aaf7fd5ea1222c67487949617e39585d6b6434b074b6",
"sha256:d54fdd5be6843dd29fd7af2f7fdd20a9eb4db46f1f6bed914e03b2f58d2d488e"
],
"version": "==0.2.1"
},
"more-itertools": {
"hashes": [
@@ -570,6 +600,13 @@
],
"version": "==5.7.8"
},
"packaging": {
"hashes": [
"sha256:0c98a5d0be38ed775798ece1b9727178c4469d9c3b4ada66e8e6b7849f8732af",
"sha256:9e1cbf8c12b1f1ce0bb5344b8d7ecf66a6f8a6e91bcb0c84593ed6d3ab5c4ab3"
],
"version": "==19.0"
},
"pandocfilters": {
"hashes": [
"sha256:b3dd70e169bb5449e6bc6ff96aea89c5eea8c5f6ab5e207fc2f521a2cf4a0da9"
@@ -600,16 +637,16 @@
},
"pluggy": {
"hashes": [
"sha256:25a1bc1d148c9a640211872b4ff859878d422bccb59c9965e04eed468a0aa180",
"sha256:964cedd2b27c492fbf0b7f58b3284a09cf7f99b0f715941fb24a439b3af1bd1a"
"sha256:0825a152ac059776623854c1543d65a4ad408eb3d33ee114dff91e57ec6ae6fc",
"sha256:b9817417e95936bf75d85d3f8767f7df6cdde751fc40aed3bb3074cbcb77757c"
],
"version": "==0.11.0"
"version": "==0.12.0"
},
"prometheus-client": {
"hashes": [
"sha256:1b38b958750f66f208bcd9ab92a633c0c994d8859c831f7abc1f46724fcee490"
"sha256:ee0c90350595e4a9f36591f291e6f9933246ea67d7cd7d1d6139a9781b14eaae"
],
"version": "==0.6.0"
"version": "==0.7.0"
},
"prompt-toolkit": {
"hashes": [
@@ -650,10 +687,10 @@
},
"pygments": {
"hashes": [
"sha256:31cba6ffb739f099a85e243eff8cb717089fdd3c7300767d9fc34cb8e1b065f5",
"sha256:5ad302949b3c98dd73f8d9fcdc7e9cb592f120e32a18e23efd7f3dc51194472b"
"sha256:71e430bc85c88a430f000ac1d9b331d2407f681d6f6aec95e8bcfbc3df5b0127",
"sha256:881c4c157e45f30af185c1ffe8d549d48ac9127433f2c380c24b84572ad66297"
],
"version": "==2.4.0"
"version": "==2.4.2"
},
"pymdown-extensions": {
"hashes": [
@@ -662,6 +699,13 @@
],
"version": "==6.0"
},
"pyparsing": {
"hashes": [
"sha256:1873c03321fc118f4e9746baf201ff990ceb915f433f23b395f5580d1840cb2a",
"sha256:9b6323ef4ab914af344ba97510e966d64ba91055d6b9afa6b30799340e89cc03"
],
"version": "==2.4.0"
},
"pyrsistent": {
"hashes": [
"sha256:16692ee739d42cf5e39cef8d27649a8c1fdb7aa99887098f1460057c5eb75c3a"
@@ -670,11 +714,11 @@
},
"pytest": {
"hashes": [
"sha256:1a8aa4fa958f8f451ac5441f3ac130d9fc86ea38780dd2715e6d5c5882700b24",
"sha256:b8bf138592384bd4e87338cb0f256bf5f615398a649d4bd83915f0e4047a5ca6"
"sha256:4a784f1d4f2ef198fe9b7aef793e9fa1a3b2f84e822d9b3a64a181293a572d45",
"sha256:926855726d8ae8371803f7b2e6ec0a69953d9c6311fa7c3b6c1b929ff92d27da"
],
"index": "pypi",
"version": "==4.5.0"
"version": "==4.6.3"
},
"pytest-cov": {
"hashes": [
@@ -706,19 +750,19 @@
},
"pyyaml": {
"hashes": [
"sha256:1adecc22f88d38052fb787d959f003811ca858b799590a5eaa70e63dca50308c",
"sha256:436bc774ecf7c103814098159fbb84c2715d25980175292c648f2da143909f95",
"sha256:460a5a4248763f6f37ea225d19d5c205677d8d525f6a83357ca622ed541830c2",
"sha256:5a22a9c84653debfbf198d02fe592c176ea548cccce47553f35f466e15cf2fd4",
"sha256:7a5d3f26b89d688db27822343dfa25c599627bc92093e788956372285c6298ad",
"sha256:9372b04a02080752d9e6f990179a4ab840227c6e2ce15b95e1278456664cf2ba",
"sha256:a5dcbebee834eaddf3fa7366316b880ff4062e4bcc9787b78c7fbb4a26ff2dd1",
"sha256:aee5bab92a176e7cd034e57f46e9df9a9862a71f8f37cad167c6fc74c65f5b4e",
"sha256:c51f642898c0bacd335fc119da60baae0824f2cde95b0330b56c0553439f0673",
"sha256:c68ea4d3ba1705da1e0d85da6684ac657912679a649e8868bd850d2c299cce13",
"sha256:e23d0cc5299223dcc37885dae624f382297717e459ea24053709675a976a3e19"
"sha256:57acc1d8533cbe51f6662a55434f0dbecfa2b9eaf115bede8f6fd00115a0c0d3",
"sha256:588c94b3d16b76cfed8e0be54932e5729cc185caffaa5a451e7ad2f7ed8b4043",
"sha256:68c8dd247f29f9a0d09375c9c6b8fdc64b60810ebf07ba4cdd64ceee3a58c7b7",
"sha256:70d9818f1c9cd5c48bb87804f2efc8692f1023dac7f1a1a5c61d454043c1d265",
"sha256:86a93cccd50f8c125286e637328ff4eef108400dd7089b46a7be3445eecfa391",
"sha256:a0f329125a926876f647c9fa0ef32801587a12328b4a3c741270464e3e4fa778",
"sha256:a3c252ab0fa1bb0d5a3f6449a4826732f3eb6c0270925548cac342bc9b22c225",
"sha256:b4bb4d3f5e232425e25dda21c070ce05168a786ac9eda43768ab7f3ac2770955",
"sha256:cd0618c5ba5bda5f4039b9398bb7fb6a317bb8298218c3de25c47c4740e4b95e",
"sha256:ceacb9e5f8474dcf45b940578591c7f3d960e82f926c707788a570b51ba59190",
"sha256:fe6a88094b64132c4bb3b631412e90032e8cfe9745a58370462240b8cb7553cd"
],
"version": "==5.1"
"version": "==5.1.1"
},
"pyzmq": {
"hashes": [
@@ -752,10 +796,10 @@
},
"qtconsole": {
"hashes": [
"sha256:a667558c7b1e1442a2e5bcef1686c55e096efd0b58d8b2a0a8415f4579991ee3",
"sha256:fdfc6002d9d2834c88f9c92e0f6f590284ff3740fa53016f188a62d58bcca6d8"
"sha256:4af84facdd6f00a6b9b2927255f717bb23ae4b7a20ba1d9ef0a5a5a8dbe01ae2",
"sha256:60d61d93f7d67ba2b265c6d599d413ffec21202fec999a952f658ff3a73d252b"
],
"version": "==4.4.4"
"version": "==4.5.1"
},
"requests": {
"hashes": [
@@ -781,9 +825,9 @@
},
"sqlalchemy": {
"hashes": [
"sha256:91c54ca8345008fceaec987e10924bf07dcab36c442925357e5a467b36a38319"
"sha256:c30925d60af95443458ebd7525daf791f55762b106049ae71e18f8dd58084c2f"
],
"version": "==1.3.3"
"version": "==1.3.5"
},
"terminado": {
"hashes": [
@@ -858,17 +902,17 @@
},
"urllib3": {
"hashes": [
"sha256:a53063d8b9210a7bdec15e7b272776b9d42b2fd6816401a0d43006ad2f9902db",
"sha256:d363e3607d8de0c220d31950a8f38b18d5ba7c0830facd71a1c6b1036b7ce06c"
"sha256:b246607a25ac80bedac05c6f282e3cdaf3afb65420fd024ac94435cabe6e18d1",
"sha256:dbe59173209418ae49d485b87d1681aefa36252ee85884c31346debd19463232"
],
"version": "==1.25.2"
"version": "==1.25.3"
},
"uvicorn": {
"hashes": [
"sha256:c10da7a54a6552279870900c881a2f1726314e2dd6270d4d3f9251683c643783"
"sha256:9114d22a569552258a3f2bf0da57c328049c3dfd428a88230cdf0966229ef180"
],
"index": "pypi",
"version": "==0.7.1"
"version": "==0.7.2"
},
"uvloop": {
"hashes": [
@@ -931,6 +975,13 @@
"sha256:fa618be8435447a017fd1bf2c7ae922d0428056cfc7449f7a8641edf76b48265"
],
"version": "==3.4.2"
},
"zipp": {
"hashes": [
"sha256:8c1019c6aad13642199fbe458275ad6a84907634cc9f0989877ccc4a2840139d",
"sha256:ca943a7e809cc12257001ccfb99e3563da9af99d52f261725e96dfe0f9275bc3"
],
"version": "==0.5.1"
}
}
}

View File

@@ -240,7 +240,7 @@ It was one of the first extremely fast Python frameworks based on `asyncio`. It
Falcon is another high performance Python framework, it is designed to be minimal, and work as the foundation of other frameworks like Hug.
It uses the previous standard for Python web frameworks (WSGI) which is synchronous, so it can't handle Websockets and other use cases. Nevertheless, it also has a very good performance.
It uses the previous standard for Python web frameworks (WSGI) which is synchronous, so it can't handle WebSockets and other use cases. Nevertheless, it also has a very good performance.
It is designed to have functions that receive two parameters, one "request" and one "response". Then you "read" parts from the request, and "write" parts to the response. Because of this design, it is not possible to declare request parameters and bodies with standard Python type hints as function parameters.
@@ -249,6 +249,10 @@ So, data validation, serialization, and documentation, have to be done in code,
!!! check "Inspired **FastAPI** to"
Find ways to get great performance.
Along with Hug (as Hug is based on Falcon) inspired **FastAPI** to declare a `response` parameter in functions.
Although in FastAPI it's optional, and is used mainly to set headers, cookies, and alternative status codes.
### <a href="https://moltenframework.com/" target="_blank">Molten</a>
I discovered Molten in the first stages of building **FastAPI**. And it has quite similar ideas:
@@ -292,6 +296,7 @@ As it is based on the previous standard for synchronous Python web frameworks (W
Hug helped inspiring **FastAPI** to use Python type hints to declare parameters, and to generate a schema defining the API automatically.
Hug inspired **FastAPI** to declare a `response` parameter in functions to set headers and cookies.
### <a href="https://github.com/encode/apistar" target="_blank">APIStar</a> (<= 0.5)

View File

Binary file not shown.

After

Width:  |  Height:  |  Size: 82 KiB

View File

@@ -1,4 +1,103 @@
## Next release
## Latest changes
## 0.30.0
* Add support for Pydantic's ORM mode:
* Updated documentation about SQL with SQLAlchemy, using Pydantic models with ORM mode, SQLAlchemy models with relations, separation of files, simplification of code and other changes. New docs: [SQL (Relational) Databases](https://fastapi.tiangolo.com/tutorial/sql-databases/).
* The new support for ORM mode fixes issues/adds features related to ORMs with lazy-loading, hybrid properties, dynamic/getters (using `@property` decorators) and several other use cases.
* This applies to ORMs like SQLAlchemy, Peewee, Tortoise ORM, GINO ORM and virtually any other.
* If your *path operations* return an arbitrary object with attributes (e.g. `my_item.name` instead of `my_item["name"]`) AND you use a `response_model`, make sure to update the Pydantic models with `orm_mode = True` as described in the docs (link above).
* New documentation about receiving plain `dict`s as request bodies: [Bodies of arbitrary `dict`s](https://fastapi.tiangolo.com/tutorial/body-nested-models/#bodies-of-arbitrary-dicts).
* New documentation about returning arbitrary `dict`s in responses: [Response with arbitrary `dict`](https://fastapi.tiangolo.com/tutorial/extra-models/#response-with-arbitrary-dict).
* **Technical Details**:
* When declaring a `response_model` it is used directly to generate the response content, from whatever was returned from the *path operation function*.
* Before this, the return content was first passed through `jsonable_encoder` to ensure it was a "jsonable" object, like a `dict`, instead of an arbitrary object with attributes (like an ORM model). That's why you should make sure to update your Pydantic models for objects with attributes to use `orm_mode = True`.
* If you don't have a `response_model`, the return object will still be passed through `jsonable_encoder` first.
* When a `response_model` is declared, the same `response_model` type declaration won't be used as is, it will be "cloned" to create an new one (a cloned Pydantic `Field` with all the submodels cloned as well).
* This avoids/fixes a potential security issue: as the returned object is passed directly to Pydantic, if the returned object was a subclass of the `response_model` (e.g. you return a `UserInDB` that inherits from `User` but contains extra fields, like `hashed_password`, and `User` is used in the `response_model`), it would still pass the validation (because `UserInDB` is a subclass of `User`) and the object would be returned as-is, including the `hashed_password`. To fix this, the declared `response_model` is cloned, if it is a Pydantic model class (or contains Pydantic model classes in it, e.g. in a `List[Item]`), the Pydantic model class(es) will be a different one (the "cloned" one). So, an object that is a subclass won't simply pass the validation and returned as-is, because it is no longer a sub-class of the cloned `response_model`. Instead, a new Pydantic model object will be created with the contents of the returned object. So, it will be a new object (made with the data from the returned one), and will be filtered by the cloned `response_model`, containing only the declared fields as normally.
* PR [#322](https://github.com/tiangolo/fastapi/pull/322).
* Remove/clean unused RegEx code in routing. PR [#314](https://github.com/tiangolo/fastapi/pull/314) by [@dmontagu](https://github.com/dmontagu).
* Use default response status code descriptions for additional responses. PR [#313](https://github.com/tiangolo/fastapi/pull/313) by [@duxiaoyao](https://github.com/duxiaoyao).
* Upgrade Pydantic support to `0.28`. PR [#320](https://github.com/tiangolo/fastapi/pull/320) by [@jekirl](https://github.com/jekirl).
## 0.29.1
* Fix handling an empty-body request with a required body param. PR [#311](https://github.com/tiangolo/fastapi/pull/311).
* Fix broken link in docs: [Return a Response directly](https://fastapi.tiangolo.com/tutorial/response-directly/). PR [#306](https://github.com/tiangolo/fastapi/pull/306) by [@dmontagu](https://github.com/dmontagu).
* Fix docs discrepancy in docs for [Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). PR [#288](https://github.com/tiangolo/fastapi/pull/288) by [@awiddersheim](https://github.com/awiddersheim).
## 0.29.0
* Add support for declaring a `Response` parameter:
* This allows declaring:
* [Response Cookies](https://fastapi.tiangolo.com/tutorial/response-cookies/).
* [Response Headers](https://fastapi.tiangolo.com/tutorial/response-headers/).
* An HTTP Status Code different than the default: [Response - Change Status Code](https://fastapi.tiangolo.com/tutorial/response-change-status-code/).
* All of this while still being able to return arbitrary objects (`dict`, DB model, etc).
* Update attribution to Hug, for inspiring the `response` parameter pattern.
* PR [#294](https://github.com/tiangolo/fastapi/pull/294).
## 0.28.0
* Implement dependency cache per request.
* This avoids calling each dependency multiple times for the same request.
* This is useful while calling external services, performing costly computation, etc.
* This also means that if a dependency was declared as a *path operation decorator* dependency, possibly at the router level (with `.include_router()`) and then it is declared again in a specific *path operation*, the dependency will be called only once.
* The cache can be disabled per dependency declaration, using `use_cache=False` as in `Depends(your_dependency, use_cache=False)`.
* Updated docs at: [Using the same dependency multiple times](https://fastapi.tiangolo.com/tutorial/dependencies/sub-dependencies/#using-the-same-dependency-multiple-times).
* PR [#292](https://github.com/tiangolo/fastapi/pull/292).
* Implement dependency overrides for testing.
* This allows using overrides/mocks of dependencies during tests.
* New docs: [Testing Dependencies with Overrides](https://fastapi.tiangolo.com/tutorial/testing-dependencies/).
* PR [#291](https://github.com/tiangolo/fastapi/pull/291).
## 0.27.2
* Fix path and query parameters receiving `dict` as a valid type. It should be mapped to a body payload. PR [#287](https://github.com/tiangolo/fastapi/pull/287). Updated docs at: [Query parameter list / multiple values with defaults: Using `list`](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#using-list).
## 0.27.1
* Fix `auto_error=False` handling in `HTTPBearer` security scheme. Do not `raise` when there's an incorrect `Authorization` header if `auto_error=False`. PR [#282](https://github.com/tiangolo/fastapi/pull/282).
* Fix type declaration of `HTTPException`. PR [#279](https://github.com/tiangolo/fastapi/pull/279).
## 0.27.0
* Fix broken link in docs about OAuth 2.0 with scopes. PR [#275](https://github.com/tiangolo/fastapi/pull/275) by [@dmontagu](https://github.com/dmontagu).
* Refactor param extraction using Pydantic `Field`:
* Large refactor, improvement, and simplification of param extraction from *path operations*.
* Fix/add support for list *query parameters* with list defaults. New documentation: [Query parameter list / multiple values with defaults](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#query-parameter-list-multiple-values-with-defaults).
* Add support for enumerations in *path operation* parameters. New documentation: [Path Parameters: Predefined values](https://fastapi.tiangolo.com/tutorial/path-params/#predefined-values).
* Add support for type annotations using `Optional` as in `param: Optional[str] = None`. New documentation: [Optional type declarations](https://fastapi.tiangolo.com/tutorial/query-params/#optional-type-declarations).
* PR [#278](https://github.com/tiangolo/fastapi/pull/278).
## 0.26.0
* Separate error handling for validation errors.
* This will allow developers to customize the exception handlers.
* Document better how to handle exceptions and use error handlers.
* Include `RequestValidationError` and `WebSocketRequestValidationError` (this last one will be useful once [encode/starlette#527](https://github.com/encode/starlette/pull/527) or equivalent is merged).
* New documentation about exceptions handlers:
* [Install custom exception handlers](https://fastapi.tiangolo.com/tutorial/handling-errors/#install-custom-exception-handlers).
* [Override the default exception handlers](https://fastapi.tiangolo.com/tutorial/handling-errors/#override-the-default-exception-handlers).
* [Re-use **FastAPI's** exception handlers](https://fastapi.tiangolo.com/tutorial/handling-errors/#re-use-fastapis-exception-handlers).
* PR [#273](https://github.com/tiangolo/fastapi/pull/273).
* Fix support for *paths* in *path parameters* without needing explicit `Path(...)`.
* PR [#256](https://github.com/tiangolo/fastapi/pull/256).
* Documented in PR [#272](https://github.com/tiangolo/fastapi/pull/272) by [@wshayes](https://github.com/wshayes).
* New documentation at: [Path Parameters containing paths](https://fastapi.tiangolo.com/tutorial/path-params/#path-parameters-containing-paths).
* Update docs for testing FastAPI. Include using `POST`, sending JSON, testing headers, etc. New documentation: [Testing](https://fastapi.tiangolo.com/tutorial/testing/#testing-extended-example). PR [#271](https://github.com/tiangolo/fastapi/pull/271).
* Fix type declaration of `response_model` to allow generic Python types as `List[Model]`. Mainly to fix `mypy` for users. PR [#266](https://github.com/tiangolo/fastapi/pull/266).
## 0.25.0

View File

@@ -0,0 +1,36 @@
from fastapi import FastAPI, Header, HTTPException
from pydantic import BaseModel
fake_secret_token = "coneofsilence"
fake_db = {
"foo": {"id": "foo", "title": "Foo", "description": "There goes my hero"},
"bar": {"id": "bar", "title": "Bar", "description": "The bartenders"},
}
app = FastAPI()
class Item(BaseModel):
id: str
title: str
description: str = None
@app.get("/items/{item_id}", response_model=Item)
async def read_main(item_id: str, x_token: str = Header(...)):
if x_token != fake_secret_token:
raise HTTPException(status_code=400, detail="Invalid X-Token header")
if item_id not in fake_db:
raise HTTPException(status_code=404, detail="Item not found")
return fake_db[item_id]
@app.post("/items/", response_model=Item)
async def create_item(item: Item, x_token: str = Header(...)):
if x_token != fake_secret_token:
raise HTTPException(status_code=400, detail="Invalid X-Token header")
if item.id in fake_db:
raise HTTPException(status_code=400, detail="Item already exists")
fake_db[item.id] = item
return item

View File

@@ -0,0 +1,65 @@
from starlette.testclient import TestClient
from .main_b import app
client = TestClient(app)
def test_read_item():
response = client.get("/items/foo", headers={"X-Token": "coneofsilence"})
assert response.status_code == 200
assert response.json() == {
"id": "foo",
"title": "Foo",
"description": "There goes my hero",
}
def test_read_item_bad_token():
response = client.get("/items/foo", headers={"X-Token": "hailhydra"})
assert response.status_code == 400
assert response.json() == {"detail": "Invalid X-Token header"}
def test_read_inexistent_item():
response = client.get("/items/baz", headers={"X-Token": "coneofsilence"})
assert response.status_code == 404
assert response.json() == {"detail": "Item not found"}
def test_create_item():
response = client.post(
"/items/",
headers={"X-Token": "coneofsilence"},
json={"id": "foobar", "title": "Foo Bar", "description": "The Foo Barters"},
)
assert response.status_code == 200
assert response.json() == {
"id": "foobar",
"title": "Foo Bar",
"description": "The Foo Barters",
}
def test_create_item_bad_token():
response = client.post(
"/items/",
headers={"X-Token": "hailhydra"},
json={"id": "bazz", "title": "Bazz", "description": "Drop the bazz"},
)
assert response.status_code == 400
assert response.json() == {"detail": "Invalid X-Token header"}
def test_create_existing_token():
response = client.post(
"/items/",
headers={"X-Token": "coneofsilence"},
json={
"id": "foo",
"title": "The Foo ID Stealers",
"description": "There goes my stealer",
},
)
assert response.status_code == 400
assert response.json() == {"detail": "Item already exists"}

View File

@@ -0,0 +1,10 @@
from typing import Dict
from fastapi import FastAPI
app = FastAPI()
@app.post("/index-weights/")
async def create_index_weights(weights: Dict[int, float]):
return weights

View File

@@ -0,0 +1,55 @@
from fastapi import Depends, FastAPI
from starlette.testclient import TestClient
app = FastAPI()
async def common_parameters(q: str = None, skip: int = 0, limit: int = 100):
return {"q": q, "skip": skip, "limit": limit}
@app.get("/items/")
async def read_items(commons: dict = Depends(common_parameters)):
return {"message": "Hello Items!", "params": commons}
@app.get("/users/")
async def read_users(commons: dict = Depends(common_parameters)):
return {"message": "Hello Users!", "params": commons}
client = TestClient(app)
async def override_dependency(q: str = None):
return {"q": q, "skip": 5, "limit": 10}
app.dependency_overrides[common_parameters] = override_dependency
def test_override_in_items():
response = client.get("/items/")
assert response.status_code == 200
assert response.json() == {
"message": "Hello Items!",
"params": {"q": None, "skip": 5, "limit": 10},
}
def test_override_in_items_with_q():
response = client.get("/items/?q=foo")
assert response.status_code == 200
assert response.json() == {
"message": "Hello Items!",
"params": {"q": "foo", "skip": 5, "limit": 10},
}
def test_override_in_items_with_params():
response = client.get("/items/?q=foo&skip=100&limit=200")
assert response.status_code == 200
assert response.json() == {
"message": "Hello Items!",
"params": {"q": "foo", "skip": 5, "limit": 10},
}

View File

@@ -0,0 +1,10 @@
from typing import Dict
from fastapi import FastAPI
app = FastAPI()
@app.get("/keyword-weights/", response_model=Dict[str, float])
async def read_keyword_weights():
return {"foo": 2.3, "bar": 3.4}

View File

@@ -1,15 +1,26 @@
from fastapi import FastAPI
from starlette.exceptions import HTTPException
from starlette.responses import PlainTextResponse
from starlette.requests import Request
from starlette.responses import JSONResponse
class UnicornException(Exception):
def __init__(self, name: str):
self.name = name
app = FastAPI()
@app.exception_handler(HTTPException)
async def http_exception(request, exc):
return PlainTextResponse(str(exc.detail), status_code=exc.status_code)
@app.exception_handler(UnicornException)
async def unicorn_exception_handler(request: Request, exc: UnicornException):
return JSONResponse(
status_code=418,
content={"message": f"Oops! {exc.name} did something. There goes a rainbow..."},
)
@app.get("/")
async def root():
return {"message": "Hello World"}
@app.get("/unicorns/{name}")
async def read_unicorn(name: str):
if name == "yolo":
raise UnicornException(name=name)
return {"unicorn_name": name}

View File

@@ -0,0 +1,23 @@
from fastapi import FastAPI, HTTPException
from fastapi.exceptions import RequestValidationError
from starlette.exceptions import HTTPException as StarletteHTTPException
from starlette.responses import PlainTextResponse
app = FastAPI()
@app.exception_handler(StarletteHTTPException)
async def http_exception_handler(request, exc):
return PlainTextResponse(str(exc.detail), status_code=exc.status_code)
@app.exception_handler(RequestValidationError)
async def validation_exception_handler(request, exc):
return PlainTextResponse(str(exc), status_code=400)
@app.get("/items/{item_id}")
async def read_item(item_id: int):
if item_id == 3:
raise HTTPException(status_code=418, detail="Nope! I don't like 3.")
return {"item_id": item_id}

View File

@@ -0,0 +1,28 @@
from fastapi import FastAPI, HTTPException
from fastapi.exception_handlers import (
http_exception_handler,
request_validation_exception_handler,
)
from fastapi.exceptions import RequestValidationError
from starlette.exceptions import HTTPException as StarletteHTTPException
app = FastAPI()
@app.exception_handler(StarletteHTTPException)
async def custom_http_exception_handler(request, exc):
print(f"OMG! An HTTP error!: {exc}")
return await http_exception_handler(request, exc)
@app.exception_handler(RequestValidationError)
async def validation_exception_handler(request, exc):
print(f"OMG! The client sent invalid data!: {exc}")
return await request_validation_exception_handler(request, exc)
@app.get("/items/{item_id}")
async def read_item(item_id: int):
if item_id == 3:
raise HTTPException(status_code=418, detail="Nope! I don't like 3.")
return {"item_id": item_id}

View File

@@ -0,0 +1,8 @@
from fastapi import FastAPI
app = FastAPI()
@app.get("/files/{file_path:path}")
async def read_user_me(file_path: str):
return {"file_path": file_path}

View File

@@ -0,0 +1,21 @@
from enum import Enum
from fastapi import FastAPI
class ModelName(Enum):
alexnet = "alexnet"
resnet = "resnet"
lenet = "lenet"
app = FastAPI()
@app.get("/model/{model_name}")
async def get_model(model_name: ModelName):
if model_name == ModelName.alexnet:
return {"model_name": model_name, "message": "Deep Learning FTW!"}
if model_name.value == "lenet":
return {"model_name": model_name, "message": "LeCNN all the images"}
return {"model_name": model_name, "message": "Have some residuals"}

View File

@@ -0,0 +1,11 @@
from typing import Optional
from fastapi import FastAPI
app = FastAPI()
@app.get("/items/{item_id}")
async def read_user_item(item_id: str, limit: Optional[int] = None):
item = {"item_id": item_id, "limit": limit}
return item

View File

@@ -0,0 +1,11 @@
from typing import List
from fastapi import FastAPI, Query
app = FastAPI()
@app.get("/items/")
async def read_items(q: List[str] = Query(["foo", "bar"])):
query_items = {"q": q}
return query_items

View File

@@ -0,0 +1,9 @@
from fastapi import FastAPI, Query
app = FastAPI()
@app.get("/items/")
async def read_items(q: list = Query(None)):
query_items = {"q": q}
return query_items

View File

@@ -0,0 +1,15 @@
from fastapi import FastAPI
from starlette.responses import Response
from starlette.status import HTTP_201_CREATED
app = FastAPI()
tasks = {"foo": "Listen to the Bar Fighters"}
@app.put("/get-or-create-task/{task_id}", status_code=200)
def get_or_create_task(task_id: str, response: Response):
if task_id not in tasks:
tasks[task_id] = "This didn't exist before"
response.status_code = HTTP_201_CREATED
return tasks[task_id]

View File

@@ -0,0 +1,10 @@
from fastapi import FastAPI
from starlette.responses import Response
app = FastAPI()
@app.post("/cookie-and-object/")
def create_cookie(response: Response):
response.set_cookie(key="fakesession", value="fake-cookie-session-value")
return {"message": "Come to the dark side, we have cookies"}

View File

@@ -0,0 +1,10 @@
from fastapi import FastAPI
from starlette.responses import Response
app = FastAPI()
@app.get("/headers-and-object/")
def get_headers(response: Response):
response.headers["X-Cat-Dog"] = "alone in the world"
return {"message": "Hello World"}

View File

View File

View File

@@ -0,0 +1,36 @@
from sqlalchemy.orm import Session
from . import models, schemas
def get_user(db: Session, user_id: int):
return db.query(models.User).filter(models.User.id == user_id).first()
def get_user_by_email(db: Session, email: str):
return db.query(models.User).filter(models.User.email == email).first()
def get_users(db: Session, skip: int = 0, limit: int = 100):
return db.query(models.User).offset(skip).limit(limit).all()
def create_user(db: Session, user: schemas.UserCreate):
fake_hashed_password = user.password + "notreallyhashed"
db_user = models.User(email=user.email, hashed_password=fake_hashed_password)
db.add(db_user)
db.commit()
db.refresh(db_user)
return db_user
def get_items(db: Session, skip: int = 0, limit: int = 100):
return db.query(models.Item).offset(skip).limit(limit).all()
def create_user_item(db: Session, item: schemas.ItemCreate, user_id: int):
db_item = models.Item(**item.dict(), owner_id=user_id)
db.add(db_item)
db.commit()
db.refresh(db_item)
return db_item

View File

@@ -0,0 +1,13 @@
from sqlalchemy import create_engine
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker
SQLALCHEMY_DATABASE_URI = "sqlite:///./test.db"
# SQLALCHEMY_DATABASE_URI = "postgresql://user:password@postgresserver/db"
engine = create_engine(
SQLALCHEMY_DATABASE_URI, connect_args={"check_same_thread": False}
)
SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)
Base = declarative_base()

View File

@@ -0,0 +1,64 @@
from typing import List
from fastapi import Depends, FastAPI, HTTPException
from sqlalchemy.orm import Session
from starlette.requests import Request
from starlette.responses import Response
from . import crud, models, schemas
from .database import SessionLocal, engine
models.Base.metadata.create_all(bind=engine)
app = FastAPI()
@app.middleware("http")
async def db_session_middleware(request: Request, call_next):
response = Response("Internal server error", status_code=500)
try:
request.state.db = SessionLocal()
response = await call_next(request)
finally:
request.state.db.close()
return response
# Dependency
def get_db(request: Request):
return request.state.db
@app.post("/users/", response_model=schemas.User)
def create_user(user: schemas.UserCreate, db: Session = Depends(get_db)):
db_user = crud.get_user_by_email(db, email=user.email)
if db_user:
raise HTTPException(status_code=400, detail="Email already registered")
return crud.create_user(db=db, user=user)
@app.get("/users/", response_model=List[schemas.User])
def read_users(skip: int = 0, limit: int = 100, db: Session = Depends(get_db)):
users = crud.get_users(db, skip=skip, limit=limit)
return users
@app.get("/users/{user_id}", response_model=schemas.User)
def read_user(user_id: int, db: Session = Depends(get_db)):
db_user = crud.get_user(db, user_id=user_id)
if db_user is None:
raise HTTPException(status_code=404, detail="User not found")
return db_user
@app.post("/users/{user_id}/items/", response_model=schemas.Item)
def create_item_for_user(
user_id: int, item: schemas.ItemCreate, db: Session = Depends(get_db)
):
return crud.create_user_item(db=db, item=item, user_id=user_id)
@app.get("/items/", response_model=List[schemas.Item])
def read_items(skip: int = 0, limit: int = 100, db: Session = Depends(get_db)):
items = crud.get_items(db, skip=skip, limit=limit)
return items

View File

@@ -0,0 +1,26 @@
from sqlalchemy import Boolean, Column, ForeignKey, Integer, String
from sqlalchemy.orm import relationship
from .database import Base
class User(Base):
__tablename__ = "users"
id = Column(Integer, primary_key=True, index=True)
email = Column(String, unique=True, index=True)
hashed_password = Column(String)
is_active = Column(Boolean, default=True)
items = relationship("Item", back_populates="owner")
class Item(Base):
__tablename__ = "items"
id = Column(Integer, primary_key=True, index=True)
title = Column(String, index=True)
description = Column(String, index=True)
owner_id = Column(Integer, ForeignKey("users.id"))
owner = relationship("User", back_populates="items")

View File

@@ -0,0 +1,37 @@
from typing import List
from pydantic import BaseModel
class ItemBase(BaseModel):
title: str
description: str = None
class ItemCreate(ItemBase):
pass
class Item(ItemBase):
id: int
owner_id: int
class Config:
orm_mode = True
class UserBase(BaseModel):
email: str
class UserCreate(UserBase):
password: str
class User(UserBase):
id: int
is_active: bool
items: List[Item] = []
class Config:
orm_mode = True

View File

@@ -1,76 +0,0 @@
from fastapi import Depends, FastAPI
from sqlalchemy import Boolean, Column, Integer, String, create_engine
from sqlalchemy.ext.declarative import declarative_base, declared_attr
from sqlalchemy.orm import Session, sessionmaker
from starlette.requests import Request
from starlette.responses import Response
# SQLAlchemy specific code, as with any other app
SQLALCHEMY_DATABASE_URI = "sqlite:///./test.db"
# SQLALCHEMY_DATABASE_URI = "postgresql://user:password@postgresserver/db"
engine = create_engine(
SQLALCHEMY_DATABASE_URI, connect_args={"check_same_thread": False}
)
SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)
class CustomBase:
# Generate __tablename__ automatically
@declared_attr
def __tablename__(cls):
return cls.__name__.lower()
Base = declarative_base(cls=CustomBase)
class User(Base):
id = Column(Integer, primary_key=True, index=True)
email = Column(String, unique=True, index=True)
hashed_password = Column(String)
is_active = Column(Boolean(), default=True)
Base.metadata.create_all(bind=engine)
db_session = SessionLocal()
first_user = db_session.query(User).first()
if not first_user:
u = User(email="johndoe@example.com", hashed_password="notreallyhashed")
db_session.add(u)
db_session.commit()
db_session.close()
# Utility
def get_user(db_session: Session, user_id: int):
return db_session.query(User).filter(User.id == user_id).first()
# Dependency
def get_db(request: Request):
return request.state.db
# FastAPI specific code
app = FastAPI()
@app.get("/users/{user_id}")
def read_user(user_id: int, db: Session = Depends(get_db)):
user = get_user(db, user_id=user_id)
return user
@app.middleware("http")
async def db_session_middleware(request: Request, call_next):
response = Response("Internal server error", status_code=500)
try:
request.state.db = SessionLocal()
response = await call_next(request)
finally:
request.state.db.close()
return response

View File

@@ -200,6 +200,35 @@ You couldn't get this kind of editor support if you where working directly with
But you don't have to worry about them either, incoming dicts are converted automatically and your output is converted automatically to JSON too.
## Bodies of arbitrary `dict`s
You can also declare a body as a `dict` with keys of some type and values of other type.
Without having to know beforehand what are the valid field/attribute names (as would be the case with Pydantic models).
This would be useful if you want to receive keys that you don't already know.
---
Other useful case is when you want to have keys of other type, e.g. `int`.
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"
{!./src/body_nested_models/tutorial009.py!}
```
!!! tip
Have in mind that JSON only supports `str` as keys.
But Pydantic has automatic data conversion.
This means that, even though your API clients can only send strings as keys, as long as those strings contain pure integers, Pydantic will convert them and validate them.
And the `dict` you receive as `weights` will actually have `int` keys and `float` values.
## Recap
With **FastAPI** you have the maximum flexibility provided by Pydantic models, while keeping your code simple, short and elegant.

View File

@@ -17,14 +17,12 @@ This is very useful when you need to:
All these, while minimizing code repetition.
## First Steps
Let's see a very simple example. It will be so simple that it is not very useful, for now.
But this way we can focus on how the **Dependency Injection** system works.
### Create a dependency, or "dependable"
Let's first focus on the dependency.
@@ -151,7 +149,6 @@ The simplicity of the dependency injection system makes **FastAPI** compatible w
* response data injection systems
* etc.
## Simple and Powerful
Although the hierarchical dependency injection system is very simple to define and use, it's still very powerful.

View File

@@ -11,6 +11,7 @@ You could create a first dependency ("dependable") like:
```Python hl_lines="6 7"
{!./src/dependencies/tutorial005.py!}
```
It declares an optional query parameter `q` as a `str`, and then it just returns it.
This is quite simple (not very useful), but will help us focus on how the sub-dependencies work.
@@ -43,6 +44,18 @@ Then we can use the dependency with:
But **FastAPI** will know that it has to solve `query_extractor` first, to pass the results of that to `query_or_cookie_extractor` while calling it.
## Using the same dependency multiple times
If one of your dependencies is declared multiple times for the same *path operation*, for example, multiple dependencies have a common sub-dependency, **FastAPI** will know to call that sub-dependency only once per request.
And it will save the returned value in a <abbr title="A utility/system to store computed/generated values, to re-use them instead of computing them again.">"cache"</abbr> and pass it to all the "dependants" that need it in that specific request, instead of calling the dependency multiple times for the same request.
In an advanced scenario where you know you need the dependency to be called at every step (possibly multiple times) in the same request instead of using the "cached" value, you can set the parameter `use_cache=False` when using `Depends`:
```Python hl_lines="1"
async def needy_dependency(fresh_value: str = Depends(get_value, use_cache=False)):
return {"fresh_value": fresh_value}
```
## Recap
@@ -54,7 +67,7 @@ But still, it is very powerful, and allows you to declare arbitrarily deeply nes
!!! tip
All this might not seem as useful with these simple examples.
But you will see how useful it is in the chapters about **security**.
And you will also see the amounts of code it will save you.

View File

@@ -174,6 +174,18 @@ For that, use the standard Python `typing.List`:
{!./src/extra_models/tutorial004.py!}
```
## Response with arbitrary `dict`
You can also declare a response using a plain arbitrary `dict`, declaring just the type of the keys and values, without using a Pydantic model.
This is useful if you don't know the valid field/attribute names (that would be needed for a Pydantic model) beforehand.
In this case, you can use `typing.Dict`:
```Python hl_lines="1 8"
{!./src/extra_models/tutorial005.py!}
```
## Recap
Use multiple Pydantic models and inherit freely for each case.

View File

@@ -68,7 +68,7 @@ But if the client requests `http://example.com/items/bar` (a non-existent `item_
They are handled automatically by **FastAPI** and converted to JSON.
### Adding custom headers
## Add custom headers
There are some situations in where it's useful to be able to add custom headers to the HTTP error. For example, for some types of security.
@@ -76,24 +76,138 @@ You probably won't need to use it directly in your code.
But in case you needed it for an advanced scenario, you can add custom headers:
```Python hl_lines="14"
{!./src/handling_errors/tutorial002.py!}
```
### Installing custom handlers
## Install custom exception handlers
If you need to add other custom exception handlers, or override the default one (that sends the errors as JSON), you can use <a href="https://www.starlette.io/exceptions/" target="_blank">the same exception utilities from Starlette</a>.
You can add custom exception handlers with <a href="https://www.starlette.io/exceptions/" target="_blank">the same exception utilities from Starlette</a>.
For example, you could override the default exception handler with:
Let's say you have a custom exception `UnicornException` that you (or a library you use) might `raise`.
```Python hl_lines="2 3 8 9 10"
And you want to handle this exception globally with FastAPI.
You could add a custom exception handler with `@app.exception_handler()`:
```Python hl_lines="6 7 8 14 15 16 17 18 24"
{!./src/handling_errors/tutorial003.py!}
```
...this would make it return "plain text" responses with the errors, instead of JSON responses.
Here, if you request `/unicorns/yolo`, the *path operation* will `raise` a `UnicornException`.
!!! info
Note that in this example we set the exception handler with Starlette's `HTTPException` instead of FastAPI's `HTTPException`.
But it will be handled by the `unicorn_exception_handler`.
This would ensure that if you use a plug-in or any other third-party tool that raises Starlette's `HTTPException` directly, it will be caught by your exception handler.
So, you will receive a clean error, with an HTTP status code of `418` and a JSON content of:
```JSON
{"message": "Oops! yolo did something. There goes a rainbow..."}
```
## Override the default exception handlers
**FastAPI** has some default exception handlers.
These handlers are in charge or returning the default JSON responses when you `raise` an `HTTPException` and when the request has invalid data.
You can override these exception handlers with your own.
### Override request validation exceptions
When a request contains invalid data, **FastAPI** internally raises a `RequestValidationError`.
And it also includes a default exception handler for it.
To override it, import the `RequestValidationError` and use it with `@app.exception_handler(RequestValidationError)` to decorate the exception handler.
The exception handler will receive a `Request` and the exception.
```Python hl_lines="2 14 15 16"
{!./src/handling_errors/tutorial004.py!}
```
Now, if you go to `/items/foo`, instead of getting the default JSON error with:
```JSON
{
"detail": [
{
"loc": [
"path",
"item_id"
],
"msg": "value is not a valid integer",
"type": "type_error.integer"
}
]
}
```
you will get a text version, with:
```
1 validation error
path -> item_id
value is not a valid integer (type=type_error.integer)
```
#### `RequestValidationError` vs `ValidationError`
!!! warning
These are technical details that you might skip if it's not important for you now.
`RequestValidationError` is a sub-class of Pydantic's <a href="https://pydantic-docs.helpmanual.io/#error-handling" target="_blank">`ValidationError`</a>.
**FastAPI** uses it so that, if you use a Pydantic model in `response_model`, and your data has an error, you will see the error in your log.
But the client/user will not see it. Instead, the client will receive an "Internal Server Error" with a HTTP status code `500`.
It should be this way because if you have a Pydantic `ValidationError` in your *response* or anywhere in your code (not in the client's *request*), it's actually a bug in your code.
And while you fix it, your clients/users shouldn't have access to internal information about the error, as that could expose a security vulnerability.
### Override the `HTTPException` error handler
The same way, you can override the `HTTPException` handler.
For example, you could want to return a plain text response instead of JSON for these errors:
```Python hl_lines="1 3 9 10 11 22"
{!./src/handling_errors/tutorial004.py!}
```
#### FastAPI's `HTTPException` vs Starlette's `HTTPException`
**FastAPI** has its own `HTTPException`.
And **FastAPI**'s `HTTPException` error class inherits from Starlette's `HTTPException` error class.
The only difference, is that **FastAPI**'s `HTTPException` allows you to add headers to be included in the response.
This is needed/used internally for OAuth 2.0 and some security utilities.
So, you can keep raising **FastAPI**'s `HTTPException` as normally in your code.
But when you register an exception handler, you should register it for Starlette's `HTTPException`.
This way, if any part of Starlette's internal code, or a Starlette extension or plug-in, raises an `HTTPException`, your handler will be able to catch handle it.
In this example, to be able to have both `HTTPException`s in the same code, Starlette's exceptions is renamed to `StarletteHTTPException`:
```Python
from starlette.exceptions import HTTPException as StarletteHTTPException
```
### Re-use **FastAPI**'s exception handlers
You could also just want to use the exception somehow, but then use the same default exception handlers from **FastAPI**.
You can import and re-use the default exception handlers from `fastapi.exception_handlers`:
```Python hl_lines="2 3 4 5 15 21"
{!./src/handling_errors/tutorial005.py!}
```
In this example, you are just `print`ing the error with a very expressive notification.
But you get the idea, you can use the exception and then just re-use the default exception handlers.

View File

@@ -35,7 +35,7 @@ If you run this example and open your browser at <a href="http://127.0.0.1:8000/
!!! check
Notice that the value your function received (and returned) is `3`, as a Python `int`, not a string `"3"`.
So, with that type declaration, **FastAPI** gives you automatic request <abbr title="converting the string that comes from an HTTP request into Python data">"parsing"</abbr>.
## Data validation
@@ -61,12 +61,11 @@ because the path parameter `item_id` had a value of `"foo"`, which is not an `in
The same error would appear if you provided a `float` instead of an int, as in: <a href="http://127.0.0.1:8000/items/4.2" target="_blank">http://127.0.0.1:8000/items/4.2</a>
!!! check
So, with the same Python type declaration, **FastAPI** gives you data validation.
Notice that the error also clearly states exactly the point where the validation didn't pass.
Notice that the error also clearly states exactly the point where the validation didn't pass.
This is incredibly helpful while developing and debugging code that interacts with your API.
## Documentation
@@ -96,8 +95,7 @@ All the data validation is performed under the hood by <a href="https://pydantic
You can use the same type declarations with `str`, `float`, `bool` and many other complex data types.
These are explored in the next chapters of the tutorial.
Several of these are explored in the next chapters of the tutorial.
## Order matters
@@ -115,6 +113,109 @@ Because path operations are evaluated in order, you need to make sure that the p
Otherwise, the path for `/users/{user_id}` would match also for `/users/me`, "thinking" that it's receiving a parameter `user_id` with a value of `"me"`.
## Predefined values
If you have a *path operation* that receives a *path parameter*, but you want the possible valid *path parameter* values to be predefined, you can use a standard Python <abbr title="Enumeration">`Enum`</abbr>.
### Create an `Enum` class
Import `Enum` and create a sub-class that inherits from it.
And create class attributes with fixed values, those fixed values will be the available valid values:
```Python hl_lines="1 6 7 8 9"
{!./src/path_params/tutorial005.py!}
```
!!! info
<a href="https://docs.python.org/3/library/enum.html" target="_blank">Enumerations (or enums) are available in Python</a> since version 3.4.
!!! tip
If you are wondering, "AlexNet", "ResNet", and "LeNet" are just names of Machine Learning <abbr title="Technically, Deep Learning model architectures">models</abbr>.
### Declare a *path parameter*
Then create a *path parameter* with a type annotation using the enum class you created (`ModelName`):
```Python hl_lines="16"
{!./src/path_params/tutorial005.py!}
```
### Check the docs
Because the available values for the *path parameter* are specified, the interactive docs can show them nicely:
<img src="/img/tutorial/path-params/image03.png">
### Working with Python *enumerations*
The value of the *path parameter* will be an *enumeration member*.
#### Compare *enumeration members*
You can compare it with the *enumeration member* in your created enum `ModelName`:
```Python hl_lines="17"
{!./src/path_params/tutorial005.py!}
```
#### Get the *enumeration value*
You can get the actual value (a `str` in this case) using `model_name.value`, or in general, `your_enum_member.value`:
```Python hl_lines="19"
{!./src/path_params/tutorial005.py!}
```
!!! tip
You could also access the value `"lenet"` with `ModelName.lenet.value`.
#### Return *enumeration members*
You can return *enum members* from your *path operation*, even nested in a JSON body (e.g. a `dict`).
They will be converted to their corresponding values before returning them to the client:
```Python hl_lines="18 20 21"
{!./src/path_params/tutorial005.py!}
```
## Path parameters containing paths
Let's say you have a *path operation* with a path `/files/{file_path}`.
But you need `file_path` itself to contain a *path*, like `home/johndoe/myfile.txt`.
So, the URL for that file would be something like: `/files/home/johndoe/myfile.txt`.
### OpenAPI support
OpenAPI doesn't support a way to declare a *path parameter* to contain a *path* inside, as that could lead to scenarios that are difficult to test and define.
Nevertheless, you can still do it in **FastAPI**, using one of the internal tools from Starlette.
And the docs would still work, although not adding any documentation telling that the parameter should contain a path.
### Path convertor
Using an option directly from Starlette you can declare a *path parameter* containing a *path* using a URL like:
```
/files/{file_path:path}
```
In this case, the name of the parameter is `file_path`, and the last part, `:path`, tells it that the parameter should match any *path*.
So, you can use it with:
```Python hl_lines="6"
{!./src/path_params/tutorial004.py!}
```
!!! tip
You could need the parameter to contain `/home/johndoe/myfile.txt`, with a leading slash (`/`).
In that case, the URL would be: `/files//home/johndoe/myfile.txt`, with a double slash (`//`) between `files` and `home`.
## Recap
@@ -127,4 +228,4 @@ With **FastAPI**, by using short, intuitive and standard Python type declaration
And you only have to declare them once.
That's probably the main visible advantage of **FastAPI** compared to alternative frameworks (apart from the raw performance).
That's probably the main visible advantage of **FastAPI** compared to alternative frameworks (apart from the raw performance).

View File

@@ -12,7 +12,6 @@ The query parameter `q` is of type `str`, and by default is `None`, so it is opt
We are going to enforce that even though `q` is optional, whenever it is provided, it **doesn't exceed a length of 50 characters**.
### Import `Query`
To achieve that, first import `Query` from `fastapi`:
@@ -29,7 +28,7 @@ And now use it as the default value of your parameter, setting the parameter `ma
{!./src/query_params_str_validations/tutorial002.py!}
```
As we have to replace the default value `None` with `Query(None)`, the first parameter to `Query` serves the same purpose of defining that default value.
As we have to replace the default value `None` with `Query(None)`, the first parameter to `Query` serves the same purpose of defining that default value.
So:
@@ -41,7 +40,7 @@ q: str = Query(None)
```Python
q: str = None
```
```
But it declares it explicitly as being a query parameter.
@@ -53,7 +52,6 @@ q: str = Query(None, max_length=50)
This will validate the data, show a clear error when the data is not valid, and document the parameter in the OpenAPI schema path operation.
## Add more validations
You can also add a parameter `min_length`:
@@ -119,7 +117,7 @@ So, when you need to declare a value as required while using `Query`, you can us
{!./src/query_params_str_validations/tutorial006.py!}
```
!!! info
!!! info
If you hadn't seen that `...` before: it is a a special single value, it is <a href="https://docs.python.org/3/library/constants.html#Ellipsis" target="_blank">part of Python and is called "Ellipsis"</a>.
This will let **FastAPI** know that this parameter is required.
@@ -156,11 +154,48 @@ So, the response to that URL would be:
!!! tip
To declare a query parameter with a type of `list`, like in the example above, you need to explicitly use `Query`, otherwise it would be interpreted as a request body.
The interactive API docs will update accordingly, to allow multiple values:
<img src="/img/tutorial/query-params-str-validations/image02.png">
### Query parameter list / multiple values with defaults
And you can also define a default `list` of values if none are provided:
```Python hl_lines="9"
{!./src/query_params_str_validations/tutorial012.py!}
```
If you go to:
```
http://localhost:8000/items/
```
the default of `q` will be: `["foo", "bar"]` and your response will be:
```JSON
{
"q": [
"foo",
"bar"
]
}
```
#### Using `list`
You can also use `list` directly instead of `List[str]`:
```Python hl_lines="7"
{!./src/query_params_str_validations/tutorial013.py!}
```
!!! note
Have in mind that in this case, FastAPI won't check the contents of the list.
For example, `List[int]` would check (and document) that the contents of the list are integers. But `list` alone wouldn't.
## Declare more metadata
You can add more information about the parameter.

View File

@@ -186,3 +186,39 @@ In this case, there are 3 query parameters:
* `needy`, a required `str`.
* `skip`, an `int` with a default value of `0`.
* `limit`, an optional `int`.
!!! tip
You could also use `Enum`s <a href="https://fastapi.tiangolo.com/tutorial/path-params/#predefined-values" target="_blank">the same way as with *path parameters*</a>.
## Optional type declarations
!!! warning
This might be an advanced use case.
You might want to skip it.
If you are using `mypy` it could complain with type declarations like:
```Python
limit: int = None
```
With an error like:
```
Incompatible types in assignment (expression has type "None", variable has type "int")
```
In those cases you can use `Optional` to tell `mypy` that the value could be `None`, like:
```Python
from typing import Optional
limit: Optional[int] = None
```
In a *path operation* that could look like:
```Python hl_lines="9"
{!./src/query_params/tutorial007.py!}
```

View File

@@ -0,0 +1,31 @@
You probably read before that you can set a <a href="https://fastapi.tiangolo.com/tutorial/response-status-code/" target="_blank">default Response Status Code</a>.
But in some cases you need to return a different status code than the default.
## Use case
For example, imagine that you want to return an HTTP status code of "OK" `200` by default.
But if the data didn't exist, you want to create it, and return an HTTP status code of "CREATED" `201`.
But you still want to be able to filter and convert the data you return with a `response_model`.
For those cases, you can use a `Response` parameter.
## Use a `Response` parameter
You can declare a parameter of type `Response` in your *path operation function* (as you can do for cookies and headers).
And then you can set the `status_code` in that *temporal* response object.
```Python hl_lines="2 11 14"
{!./src/response_change_status_code/tutorial001.py!}
```
And then you can return any object you need, as you normally would (a `dict`, a database model, etc).
And if you declared a `response_model`, it will still be used to filter and convert the object you returned.
**FastAPI** will use that *temporal* response to extract the status code (also cookies and headers), and will put them in the final response that contains the value you returned, filtered by any `response_model`.
You can also declare the `Response` parameter in dependencies, and set the status code in them. But have in mind that the last one to be set will win.

View File

@@ -1,4 +1,24 @@
You can create (set) Cookies in your response.
## Use a `Response` parameter
You can declare a parameter of type `Response` in your *path operation function*, the same way you can declare a `Request` parameter.
And then you can set headers in that *temporal* response object.
```Python hl_lines="2 8 9"
{!./src/response_cookies/tutorial002.py!}
```
And then you can return any object you need, as you normally would (a `dict`, a database model, etc).
And if you declared a `response_model`, it will still be used to filter and convert the object you returned.
**FastAPI** will use that *temporal* response to extract the cookies (also headers and status code), and will put them in the final response that contains the value you returned, filtered by any `response_model`.
You can also declare the `Response` parameter in dependencies, and set cookies (and headers) in them.
## Return a `Response` directly
You can also create cookies when returning a `Response` directly in your code.
To do that, you can create a response as described in <a href="https://fastapi.tiangolo.com/tutorial/response-directly/" target="_blank">Return a Response directly</a>.
@@ -8,6 +28,13 @@ Then set Cookies in it, and then return it:
{!./src/response_cookies/tutorial001.py!}
```
## More info
!!! tip
Have in mind that if you return a response directly instead of using the `Response` parameter, FastAPI will return it directly.
So, you will have to make sure your data is of the correct type. E.g. it is compatible with JSON, if you are returning a `JSONResponse`.
And also that you are not sending any data that should have been filtered by a `response_model`.
### More info
To see all the available parameters and options, check the <a href="https://www.starlette.io/responses/#set-cookie" target="_blank">documentation in Starlette</a>.

View File

@@ -56,7 +56,7 @@ You could put your XML content in a string, put it in a Starlette Response, and
When you return a `Response` directly its data is not validated, converted (serialized), nor documented automatically.
But you can still <a href="tutorial/additional-responses/" target="_blank">document it</a>.
But you can still <a href="https://fastapi.tiangolo.com/tutorial/additional-responses/" target="_blank">document it</a>.
In the next sections you will see how to use/declare these custom `Response`s while still having automatic data conversion, documentation, etc.

View File

@@ -1,4 +1,24 @@
You can add headers to your response.
## Use a `Response` parameter
You can declare a parameter of type `Response` in your *path operation function* (as you can do for cookies), the same way you can declare a `Request` parameter.
And then you can set headers in that *temporal* response object.
```Python hl_lines="2 8 9"
{!./src/response_headers/tutorial002.py!}
```
And then you can return any object you need, as you normally would (a `dict`, a database model, etc).
And if you declared a `response_model`, it will still be used to filter and convert the object you returned.
**FastAPI** will use that *temporal* response to extract the headers (also cookies and status code), and will put them in the final response that contains the value you returned, filtered by any `response_model`.
You can also declare the `Response` parameter in dependencies, and set headers (and cookies) in them.
## Return a `Response` directly
You can also add headers when you return a `Response` directly.
Create a response as described in <a href="https://fastapi.tiangolo.com/tutorial/response-directly/" target="_blank">Return a Response directly</a> and pass the headers as an additional parameter:
@@ -6,7 +26,8 @@ Create a response as described in <a href="https://fastapi.tiangolo.com/tutorial
{!./src/response_headers/tutorial001.py!}
```
!!! tip
Have in mind that custom proprietary headers can be added <a href="https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers" target="_blank">using the 'X-' prefix</a>.
## Custom Headers
But if you have custom headers that you want a client in a browser to be able to see, you need to add them to your <a href="https://fastapi.tiangolo.com/tutorial/cors/" target="_blank">CORS configurations</a>, using the parameter `expose_headers` documented in <a href="https://www.starlette.io/middleware/#corsmiddleware" target="_blank">Starlette's CORS docs</a>.
Have in mind that custom proprietary headers can be added <a href="https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers" target="_blank">using the 'X-' prefix</a>.
But if you have custom headers that you want a client in a browser to be able to see, you need to add them to your <a href="https://fastapi.tiangolo.com/tutorial/cors/" target="_blank">CORS configurations</a>, using the parameter `expose_headers` documented in <a href="https://www.starlette.io/middleware/#corsmiddleware" target="_blank">Starlette's CORS docs</a>.

View File

@@ -93,7 +93,7 @@ Your response model could have default values, like:
```
* `description: str = None` has a default of `None`.
* `tax: float = None` has a default of `None`.
* `tax: float = 10.5` has a default of `10.5`.
* `tags: List[str] = []` has a default of an empty list: `[]`.
but you might want to omit them from the result if they were not actually stored.

View File

@@ -47,7 +47,6 @@ In short:
!!! tip
To know more about each status code and which code is for what, check the <a href="https://developer.mozilla.org/en-US/docs/Web/HTTP/Status" target="_blank"><abbr title="Mozilla Developer Network">MDN</abbr> documentation about HTTP status codes</a>.
## Shortcut to remember the names
Let's see the previous example again:
@@ -69,3 +68,7 @@ You can use the convenience variables from `starlette.status`.
They are just a convenience, they hold the same number, but that way you can use the editor's autocomplete to find them:
<img src="/img/tutorial/response-status-code/image02.png">
## Changing the default
Later, in a more advanced part of the tutorial/user guide, you will see how to <a href="https://fastapi.tiangolo.com/tutorial/response-change-status-code/" target="_blank">return a different status code than the default</a> you are declaring here.

View File

@@ -247,4 +247,4 @@ The most secure is the code flow, but is more complex to implement as it require
## `Security` in decorator `dependencies`
The same way you can define a `list` of <a href="https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-decorator/" target="_blank">`Depends` in the decorator's `dependencies` parameter</a>, you could also use `Security` with `scopes` there.
The same way you can define a `list` of <a href="https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/" target="_blank">`Depends` in the decorator's `dependencies` parameter</a>, you could also use `Security` with `scopes` there.

View File

@@ -25,25 +25,77 @@ Later, for your production application, you might want to use a database server
The **FastAPI** specific code is as small as always.
## Import SQLAlchemy components
## ORMs
For now, don't pay attention to the rest, only the imports:
**FastAPI** works with any database and any style of library to talk to the database.
```Python hl_lines="2 3 4"
{!./src/sql_databases/tutorial001.py!}
A common pattern is to use an "ORM": an "object-relational mapping" library.
An ORM has tools to convert ("*map*") between *objects* in code and database tables ("*relations*").
With an ORM, you normally create a class that represents a table in a SQL database, each attribute of the class represents a column, with a name and a type.
For example a class `Pet` could represent a SQL table `pets`.
And each *instance* object of that class represents a row in the database.
For example an object `mr_furry` (an instance of `Pet`) could have an attribute `mr_furry.type`, for the column `type`. And the value of that attribute could be, e.g. `"cat"`.
These ORMs also have tools to make the connections or relations between tables or entities.
This way, you could also have an attribute `mr_furry.owner` and the owner would contain the data for this pet's owner, taken from the table *owners*.
So, `mr_furry.owner.name` could be the name (from the `name` column in the `owners` table) of this pet's owner.
It could have a value like `"Alice"`.
And the ORM will do all the work to get the information from the corresponding table *owners* when you try to access it from your pet object.
Common ORMs are for example: Django-ORM (part of the Django framework), SQLAlchemy ORM (part of SQLAlchemy, independent of framework) and Peewee (independent of framework), among others.
Here we will see how to work with **SQLAlchemy ORM**.
The same way, you could use Peewee or any other.
## File structure
For these examples, let's say you have a directory `sql_app` with a structure like this:
```
├── sql_app
│   ├── __init__.py
│   ├── crud.py
│   ├── database.py
│   ├── main.py
│   ├── models.py
│   ├── schemas.py
```
## Define the database
The file `__init__.py` is just an empty file, but it tells Python that `sql_app` with all its modules (Python files) is a package.
Define the database that SQLAlchemy should "connect" to:
Now let's see what each file/module does.
```Python hl_lines="9"
{!./src/sql_databases/tutorial001.py!}
## Create the SQLAlchemy parts
Let's see the file `sql_app/database.py`.
### Import the SQLAlchemy parts
```Python hl_lines="1 2 3"
{!./src/sql_databases/sql_app/database.py!}
```
### Create a database URL for SQLAlchemy
```Python hl_lines="5 6"
{!./src/sql_databases/sql_app/database.py!}
```
In this example, we are "connecting" to a SQLite database (opening a file with the SQLite database).
The file will be located at the same directory in the file `test.db`. That's why the last part is `./test.db`.
The file will be located at the same directory in the file `test.db`.
That's why the last part is `./test.db`.
If you were using a **PostgreSQL** database instead, you would just have to uncomment the line:
@@ -54,16 +106,20 @@ SQLALCHEMY_DATABASE_URI = "postgresql://user:password@postgresserver/db"
...and adapt it with your database data and credentials (equivalently for MySQL, MariaDB or any other).
!!! tip
This is the main line that you would have to modify if you wanted to use a different database.
## Create the SQLAlchemy `engine`
### Create the SQLAlchemy `engine`
```Python hl_lines="12 13 14"
{!./src/sql_databases/tutorial001.py!}
The first step is to create a SQLAlchemy "engine".
We will later use this `engine` in other places.
```Python hl_lines="8 9 10"
{!./src/sql_databases/sql_app/database.py!}
```
### Note
#### Note
The argument:
@@ -78,25 +134,302 @@ connect_args={"check_same_thread": False}
That argument `check_same_thread` is there mainly to be able to run the tests that cover this example.
## Create a `SessionLocal` class
### Create a `SessionLocal` class
Each instance of the `SessionLocal` class will have a connection to the database.
Each instance of the `SessionLocal` class will have a session/connection to the database.
This object (class) is not a connection to the database yet, but once we create an instance of this class, that instance will have the actual connection to the database.
This object (class) is not a session/connection to the database yet, but once we create an instance of this class, that instance will have the actual connection to the database.
We name it `SessionLocal` to distinguish it from the `Session` we are importing from SQLAlchemy.
We will use `Session` to declare types later and to get better editor support and completion.
We will use `Session` (the one imported from SQLAlchemy) later.
For now, create the `SessionLocal`:
To create the `SessionLocal` class, use the function `sessionmaker`:
```Python hl_lines="15"
{!./src/sql_databases/tutorial001.py!}
```Python hl_lines="11"
{!./src/sql_databases/sql_app/database.py!}
```
## Create a middleware to handle sessions
### Create a `Base` class
Now let's temporarily jump to the end of the file, to use the `SessionLocal` class we created above.
Now use the function `declarative_base()` that returns a class.
Later we will inherit from this class to create each of the database models or classes (the ORM models):
```Python hl_lines="13"
{!./src/sql_databases/sql_app/database.py!}
```
## Create the database models
Let's now see the file `sql_app/models.py`.
### Create SQLAlchemy models from the `Base` class
We will use this `Base` class we created before to create the SQLAlchemy models.
!!! tip
SQLAlchemy uses the term "**model**" to refer to these classes and instances that interact with the database.
But Pydantic also uses the term "**model**" to refer to something different, the data validation, conversion, and documentation classes and instances.
Import `Base` from `database` (the file `database.py` from above).
Create classes that inherit from it.
These classes are the SQLAlchemy models.
```Python hl_lines="4 7 8 18 19"
{!./src/sql_databases/sql_app/models.py!}
```
The `__tablename__` attribute tells SQLAlchemy the name of the table to use in the database for each of these models.
### Create model attributes/columns
Now create all the model (class) attributes.
Each of these attributes represents a column in its corresponding database table.
We use `Column` from SQLAlchemy as the default value.
And we pass a SQLAlchemy class "type", as `Integer`, `String`, and `Boolean`, that defines the type in the database, as an argument.
```Python hl_lines="1 10 11 12 13 21 22 23 24"
{!./src/sql_databases/sql_app/models.py!}
```
### Create the relationships
Now create the relationships.
For this, we use `relationship` provided by SQLAlchemy ORM.
This will become, more or less, a "magic" attribute that will contain the values from other tables related to this one.
```Python hl_lines="2 15 26"
{!./src/sql_databases/sql_app/models.py!}
```
When accessing the attribute `items` in a `User`, as in `my_user.items`, it will have a list of `Item` SQLAlchemy models (from the `items` table) that have a foreign key pointing to this record in the `users` table.
When you access `my_user.items`, SQLAlchemy will actually go and fetch the items from the database in the `items` table and populate them here.
And when accessing the attribute `owner` in an `Item`, it will contain a `User` SQLAlchemy model from the `users` table. It will use the `owner_id` attribute/column with its foreign key to know which record to get from the `users` table.
## Create the Pydantic models
Now let's check the file `sql_app/schemas.py`.
!!! tip
To avoid confusion between the SQLAlchemy *models* and the Pydantic *models*, we will have the file `models.py` with the SQLAlchemy models, and the file `schemas.py` with the Pydantic models.
These Pydantic models define more or less a "schema" (a valid data shape).
So this will help us avoiding confusion while using both.
### Create initial Pydantic *models* / schemas
Create an `ItemBase` and `UserBase` Pydantic *models* (or let's say "schemas") to have common attributes while creating or reading data.
And create an `ItemCreate` and `UserCreate` that inherit from them (so they will have the same attributes), plus any additional data (attributes) needed for creation.
So, the user will also have a `password` when creating it.
But for security, the `password` won't be in other Pydantic *models*, for example, it won't be sent from the API when reading a user.
```Python hl_lines="3 6 7 8 11 12 23 24 27 28"
{!./src/sql_databases/sql_app/schemas.py!}
```
#### SQLAlchemy style and Pydantic style
Notice that SQLAlchemy *models* define attributes using `=`, and pass the type as a parameter to `Column`, like in:
```Python
name = Column(String)
```
while Pydantic *models* declare the types using `:`, the new type annotation syntax/type hints:
```Python
name: str
```
Have it in mind, so you don't get confused when using `=` and `:` with them.
### Create Pydantic *models* / schemas for reading / returning
Now create Pydantic *models* (schemas) that will be used when reading data, when returning it from the API.
For example, before creating an item, we don't know what will be the ID assigned to it, but when reading it (when returning it from the API) we will already know its ID.
The same way, when reading a user, we can now declare that `items` will contain the items that belong to this user.
Not only the IDs of those items, but all the data that we defined in the Pydantic *model* for reading items: `Item`.
```Python hl_lines="15 16 17 31 32 33 34"
{!./src/sql_databases/sql_app/schemas.py!}
```
!!! tip
Notice that the `User`, the Pydantic *model* that will be used when reading a user (returning it from the API) doesn't include the `password`.
### Use Pydantic's `orm_mode`
Now, in the Pydantic *models* for reading, `Item` and `User`, add an internal `Config` class.
This <a href="https://pydantic-docs.helpmanual.io/#config" target="_blank">`Config`</a> class is used to provide configurations to Pydantic.
In the `Config` class, set the attribute `orm_mode = True`.
```Python hl_lines="15 19 20 31 36 37"
{!./src/sql_databases/sql_app/schemas.py!}
```
!!! tip
Notice it's assigning a value with `=`, like:
`orm_mode = True`
It doesn't use `:` as for the type declarations before.
This is setting a config value, not declaring a type.
Pydantic's `orm_mode` will tell the Pydantic *model* to read the data even if it is not a `dict`, but an ORM model (or any other arbitrary object with attributes).
This way, Instead of only trying to get the `id` value from a `dict`, as in:
```Python
id = data["id"]
```
it will also try to get it from an attribute, as in:
```Python
id = data.id
```
And with this, the Pydantic *model* is compatible with ORMs, and you can just declare it in the `response_model` argument in your *path operations*.
You will be able to return a database model and it will read the data from it.
#### Technical Details about ORM mode
SQLAlchemy and many others are by default "lazy loading".
That means, for example, that they don't fetch the data for relationships from the database unless you try to access the attribute that would contain that data.
For example, accessing the attribute `items`:
```Python
current_user.items
```
would make SQLAlchemy go to the `items` table and get the items for this user, but not before.
Without `orm_mode`, if you returned a SQLAlchemy model from your *path operation*, it wouldn't include the relationship data.
Even if you declared those relationships in your Pydantic models.
But with ORM mode, as Pydantic itself will try to access the data it needs from attributes (instead of assuming a `dict`), you can declare the specific data you want to return and it will be able to go and get it, even from ORMs.
## CRUD utils
Now let's see the file `sql_app/crud.py`.
In this file we will have reusable functions to interact with the data in the database.
**CRUD** comes from: **C**reate, **R**ead, **U**pdate, and **D**elete.
...although in this example we are only creating and reading.
### Read data
Import `Session` from `sqlalchemy.orm`, this will allow you to declare the type of the `db` parameters and have better type checks and completion in your functions.
Import `models` (the SQLAlchemy models) and `schemas` (the Pydantic *models* / schemas).
Create utility functions to:
* Read a single user by ID and by email.
* Read multiple users.
* Read a single item.
```Python hl_lines="1 3 6 7 10 11 14 15 27 28"
{!./src/sql_databases/sql_app/crud.py!}
```
!!! tip
By creating functions that are only dedicated to interacting with the database (get a user or an item) independent of your path operation function, you can more easily reuse them in multiple parts and also add <abbr title="Automated tests, written in code, that check if another piece of code is working correctly.">unit tests</abbr> for them.
### Create data
Now create utility functions to create data.
The steps are:
* Create a SQLAlchemy model *instance* with your data.
* `add` that instance object to your database session.
* `commit` the changes to the database (so that they are saved).
* `refresh` your instance (so that it contains any new data from the database, like the generated ID).
```Python hl_lines="18 19 20 21 22 23 24 31 32 33 34 35 36"
{!./src/sql_databases/sql_app/crud.py!}
```
!!! tip
The SQLAlchemy model for `User` contains a `hashed_password` that should contain a secure hashed version of the password.
But as what the API client provides is the original password, you need to extract it and generate the hashed password in your application.
And then pass the `hashed_password` argument with the value to save.
!!! warning
This example is not secure, the password is not hashed.
In a real life application you would need to hash the password and never save them in plaintext.
For more details, go back to the Security section in the tutorial.
Here we are focusing only on the tools and mechanics of databases.
!!! tip
Instead of passing each of the keyword arguments to `Item` and reading each one of them from the Pydantic *model*, we are generating a `dict` with the Pydantic *model*'s data with:
`item.dict()`
and then we are passing the `dict`'s key-value pairs as the keyword arguments to the SQLAlchemy `Item`, with:
`Item(**item.dict())`
And then we pass the extra keyword argument `owner_id` that is not provided by the Pydantic *model*, with:
`Item(**item.dict(), owner_id=user_id)`
## Main **FastAPI** app
And now in the file `sql_app/main.py` let's integrate and use all the other parts we created before.
### Create the database tables
In a very simplistic way, create the database tables:
```Python hl_lines="11"
{!./src/sql_databases/sql_app/main.py!}
```
#### Alembic Note
Normally you would probably initialize your database (create tables, etc) with <a href="https://alembic.sqlalchemy.org/en/latest/" target="_blank">Alembic</a>.
And you would also use Alembic for "migrations" (that's its main job).
A "migration" is the set of steps needed whenever you change the structure of your SQLAlchemy models, add a new attribute, etc. to replicate those changes in the database, add a new column, a new table, etc.
### Create a middleware to handle sessions
Now use the `SessionLocal` class we created in the `sql_app/databases.py` file.
We need to have an independent database session/connection (`SessionLocal`) per request, use the same session through all the request and then close it after the request is finished.
@@ -108,8 +441,8 @@ A "middleware" is a function that is always executed for each request, and have
This middleware (just a function) will create a new SQLAlchemy `SessionLocal` for each request, add it to the request and then close it once the request is finished.
```Python hl_lines="68 69 70 71 72 73 74 75 76"
{!./src/sql_databases/tutorial001.py!}
```Python hl_lines="16 17 18 19 20 21 22 23 24"
{!./src/sql_databases/sql_app/main.py!}
```
!!! info
@@ -117,15 +450,15 @@ This middleware (just a function) will create a new SQLAlchemy `SessionLocal` fo
And then we close it in the `finally` block.
This way we make sure the database session is always closed after the request. Even if there was an exception in the middle.
This way we make sure the database session is always closed after the request. Even if there was an exception while processing the request.
### About `request.state`
#### About `request.state`
<a href="https://www.starlette.io/requests/#other-state" target="_blank">`request.state` is a property of each Starlette `Request` object</a>, it is there to store arbitrary objects attached to the request itself, like the database session in this case.
For us in this case, it helps us ensuring a single session/database-connection is used through all the request, and then closed afterwards (in the middleware).
## Create a dependency
### Create a dependency
To simplify the code, reduce repetition and get better editor support, we will create a dependency that returns this same database session from the request.
@@ -133,89 +466,21 @@ And when using the dependency in a path operation function, we declare it with t
This will then give us better editor support inside the path operation function, because the editor will know that the `db` parameter is of type `Session`.
```Python hl_lines="54 55 69"
{!./src/sql_databases/tutorial001.py!}
```Python hl_lines="28 29"
{!./src/sql_databases/sql_app/main.py!}
```
!!! info "Technical Details"
The parameter `db` is actually of type `SessionLocal`, but this class (created with `sessionmaker()`) is a "proxy" of a SQLAlchemy `Session`, so, the editor doesn't really know what methods are provided.
But by declaring the type as `Session`, the editor now can know the available methods (`.add()`, `.query()`, `.commit()`, etc) and can provide better support (like completion). The type declaration doesn't affect the actual object.
## Create a `CustomBase` model
### Create your **FastAPI** *path operations*
This is more of a trick to facilitate your life than something required.
Now, finally, here's the standard **FastAPI** *path operations* code.
But by creating this `CustomBase` class and inheriting from it, your models will have automatic `__tablename__` attributes (that are required by SQLAlchemy).
That way you don't have to declare them explicitly in every model.
So, your models will behave very similarly to, for example, Flask-SQLAlchemy.
```Python hl_lines="18 19 20 21 22"
{!./src/sql_databases/tutorial001.py!}
```
## Create the SQLAlchemy `Base` model
```Python hl_lines="25"
{!./src/sql_databases/tutorial001.py!}
```
## Create your application data model
Now this is finally code specific to your app.
Here's a user model that will be a table in the database:
```Python hl_lines="28 29 30 31 32"
{!./src/sql_databases/tutorial001.py!}
```
## Initialize your application
In a very simplistic way, initialize your database (create the tables, etc) and make sure you have a first user:
```Python hl_lines="35 37 39 40 41 42 43 45"
{!./src/sql_databases/tutorial001.py!}
```
!!! info
Notice that we close the session with `db_session.close()`.
We close this session because we only used it to create this first user.
Every new request will get its own new session.
### Note
Normally you would probably initialize your database (create tables, etc) with <a href="https://alembic.sqlalchemy.org/en/latest/" target="_blank">Alembic</a>.
And you would also use Alembic for migrations (that's its main job). For whenever you change the structure of your database, add a new column, a new table, etc.
The same way, you would probably make sure there's a first user in an external script that runs before your application, or as part of the application startup.
In this example we are doing those two operations in a very simple way, directly in the code, to focus on the main points.
Also, as all the functionality is self-contained in the same code, you can copy it and run it directly, and it will work as is.
## Get a user
By creating a function that is only dedicated to getting your user from a `user_id` (or any other parameter) independent of your path operation function, you can more easily re-use it in multiple parts and also add <abbr title="Automated tests, written in code, that check if another piece of code is working correctly.">unit tests</abbr> for it:
```Python hl_lines="49 50"
{!./src/sql_databases/tutorial001.py!}
```
## Create your **FastAPI** code
Now, finally, here's the standard **FastAPI** code.
Create your app and path operation function:
```Python hl_lines="59 62 63 64 65"
{!./src/sql_databases/tutorial001.py!}
```Python hl_lines="32 33 34 35 36 37 40 41 42 43 46 47 48 49 50 51 54 55 56 57 58 61 62 63 64 65"
{!./src/sql_databases/sql_app/main.py!}
```
We are creating the database session before each request, attaching it to the request, and then closing it afterwards.
@@ -226,32 +491,45 @@ Then, in the dependency `get_db()` we are extracting the database session from t
And then we can create the dependency in the path operation function, to get that session directly.
With that, we can just call `get_user` directly from inside of the path operation function and use that session.
With that, we can just call `crud.get_user` directly from inside of the path operation function and use that session.
Having this 3-step process (middleware, dependency, path operation) in this simple example might seem like an overkill. But imagine if you had 20 or 100 path operations, doing this, you would be reducing a lot of code repetition, and getting better support/checks/completion in all those path operation functions.
Having this 3-step process (middleware, dependency, path operation) you get better support/checks/completion in all the path operation functions while reducing code repetition.
## Create the path operation function
!!! tip
Notice that the values you return are SQLAlchemy models, or lists of SQLAlchemy models.
Here we are using SQLAlchemy code inside of the path operation function, and in turn it will go and communicate with an external database.
But as all the *path operations* have a `response_model` with Pydantic *models* / schemas using `orm_mode`, the data declared in your Pydantic models will be extracted from them and returned to the client, with all the normal filtering and validation.
!!! tip
Also notice that there are `response_models` that have standard Python types like `List[schemas.Item]`.
But as the content/parameter of that `List` is a Pydantic *model* with `orm_mode`, the data will be retrieved and returned to the client as normally, without problems.
### About `def` vs `async def`
Here we are using SQLAlchemy code inside of the path operation function, and, in turn, it will go and communicate with an external database.
That could potentially require some "waiting".
But as SQLAlchemy doesn't have compatibility for using `await` directly, as would be with something like:
```Python
user = await get_user(db_session, user_id=user_id)
user = await db.query(User).first()
```
...and instead we are using:
```Python
user = get_user(db_session, user_id=user_id)
user = db.query(User).first()
```
Then we should declare the path operation without `async def`, just with a normal `def`:
Then we should declare the path operation without `async def`, just with a normal `def`, as:
```Python hl_lines="63"
{!./src/sql_databases/tutorial001.py!}
```Python hl_lines="2"
@app.get("/users/{user_id}", response_model=schemas.User)
def read_user(user_id: int, db: Session = Depends(get_db)):
db_user = crud.get_user(db, user_id=user_id)
...
```
!!! note "Very Technical Details"
@@ -261,7 +539,45 @@ Then we should declare the path operation without `async def`, just with a norma
Because we are using SQLAlchemy directly and we don't require any kind of plug-in for it to work with **FastAPI**, we could integrate database <abbr title="Automatically updating the database to have any new column we define in our models.">migrations</abbr> with <a href="https://alembic.sqlalchemy.org" target="_blank">Alembic</a> directly.
You would probably want to declare your database and models in a different file or set of files, this would allow Alembic to import it and use it without even needing to have **FastAPI** installed for the migrations.
And as the code related to SQLAlchemy and the SQLAlchemy models lives in separate independent files, you would even be able to perform the migrations with Alembic without having to install FastAPI, Pydantic, or anything else.
The same way, you would be able to use the same SQLAlchemy models and utilities in other parts of your code that are not related to **FastAPI**.
For example, in a background task worker with <a href="http://www.celeryproject.org/" target="_blank">Celery</a>, <a href="https://python-rq.org/" target="_blank">RQ</a>, or <a href="https://arq-docs.helpmanual.io/" target="_blank">ARQ</a>.
## Review all the files
* `sql_app/__init__.py`: is an empty file.
* `sql_app/database.py`:
```Python hl_lines=""
{!./src/sql_databases/sql_app/database.py!}
```
* `sql_app/models.py`:
```Python hl_lines=""
{!./src/sql_databases/sql_app/models.py!}
```
* `sql_app/schemas.py`:
```Python hl_lines=""
{!./src/sql_databases/sql_app/schemas.py!}
```
* `sql_app/crud.py`:
```Python hl_lines=""
{!./src/sql_databases/sql_app/crud.py!}
```
* `sql_app/main.py`:
```Python hl_lines=""
{!./src/sql_databases/sql_app/main.py!}
```
## Check it
@@ -272,12 +588,12 @@ You can copy this code and use it as is.
In fact, the code shown here is part of the tests. As most of the code in these docs.
You can copy it, let's say, to a file `main.py`.
You can copy it as is.
Then you can run it with Uvicorn:
```bash
uvicorn main:app --reload
uvicorn sql_app.main:app --reload
```
And then, you can open your browser at <a href="http://127.0.0.1:8000/docs" target="_blank">http://127.0.0.1:8000/docs</a>.
@@ -286,27 +602,6 @@ And you will be able to interact with your **FastAPI** application, reading data
<img src="/img/tutorial/sql-databases/image01.png">
## Response schema and security
This section has the minimum code to show how it works and how you can integrate SQLAlchemy with FastAPI.
But it is recommended that you also create a response model with Pydantic, as described in the section about <a href="/tutorial/extra-models/" target="_blank">Extra Models</a>.
That way you will document the schema of the responses of your API, and you will be able to limit/filter the returned data.
Limiting the returned data is important for security, as for example, you shouldn't be returning the `hashed_password` to the clients.
That's something that you can improve in this example application, here's the current response data:
```JSON
{
"is_active": true,
"hashed_password": "notreallyhashed",
"email": "johndoe@example.com",
"id": 1
}
```
## Interact with the database directly
If you want to explore the SQLite database (file) directly, independently of FastAPI, to debug its contents, add tables, columns, records, modify data, etc. you can use <a href="https://sqlitebrowser.org/" target="_blank">DB Browser for SQLite</a>.

View File

@@ -0,0 +1,59 @@
## Overriding dependencies during testing
There are some scenarios where you might want to override a dependency during testing.
You don't want the original dependency to run (nor any of the sub-dependencies it might have).
Instead, you want to provide a different dependency that will be used only during tests (possibly only some specific tests), and will provide a value that can be used where the value of the original dependency was used.
### Use cases: external service
An example could be that you have an external authentication provider that you need to call.
You send it a token and it returns an authenticated user.
This provider might be charging you per request, and calling it might take some extra time than if you had a fixed mock user for tests.
You probably want to test the external provider once, but not necessarily call it for every test that runs.
In this case, you can override the dependency that calls that provider, and use a custom dependency that returns a mock user, only for your tests.
### Use case: testing database
Other example could be that you are using a specific database only for testing.
Your normal dependency would return a database session.
But then, after each test, you could want to rollback all the operations or remove data.
Or you could want to alter the data before the tests run, etc.
In this case, you could use a dependency override to return your *custom* database session instead of the one that would be used normally.
### Use the `app.dependency_overrides` attribute
For these cases, your **FastAPI** application has an attribute `app.dependency_overrides`, it is a simple `dict`.
To override a dependency for testing, you put as a key the original dependency (a function), and as the value, your dependency override (another function).
And then **FastAPI** will call that override instead of the original dependency.
```Python hl_lines="24 25 28"
{!./src/dependency_testing/tutorial001.py!}
```
!!! tip
You can set a dependency override for a dependency used anywhere in your **FastAPI** application.
The original dependency could be used in a *path operation function*, a *path operation decorator* (when you don't use the return value), a `.include_router()` call, etc.
FastAPI will still be able to override it.
Then you can reset your overrides (remove them) by setting `app.dependency_overrides` to be an empty `dict`:
```Python
app.dependency_overrides = {}
```
!!! tip
If you want to override a dependency only during some tests, you can set the override at the beginning of the test (inside the test function) and reset it at the end (at the end of the test function).

View File

@@ -22,12 +22,11 @@ Write simple `assert` statements with the standard Python expressions that you n
!!! tip
Notice that the testing functions are normal `def`, not `async def`.
And the calls to the client are also normal calls, not using `await`.
This allows you to use `pytest` directly without complications.
## Separating tests
In a real application, you probably would have your tests in a different file.
@@ -50,6 +49,51 @@ Then you could have a file `test_main.py` with your tests, and import your `app`
{!./src/app_testing/test_main.py!}
```
## Testing: extended example
Now let's extend this example and add more details to see how to test different parts.
### Extended **FastAPI** app file
Let's say you have a file `main_b.py` with your **FastAPI** app.
It has a `GET` operation that could return an error.
It has a `POST` operation that could return several errors.
Both *path operations* require an `X-Token` header.
```Python
{!./src/app_testing/main_b.py!}
```
### Extended testing file
You could then have a `test_main_b.py`, the same as before, with the extended tests:
```Python
{!./src/app_testing/test_main_b.py!}
```
Whenever you need the client to pass information in the request and you don't know how to, you can search (Google) how to do it in `requests`.
Then you just do the same in your tests.
E.g.:
* To pass a *path* or *query* parameter, add it to the URL itself.
* To pass a JSON body, pass a Python object (e.g. a `dict`) to the parameter `json`.
* If you need to send *Form Data* instead of JSON, use the `data` parameter instead.
* To pass *headers*, use a `dict` in the `headers` parameter.
* For *cookies*, a `dict` in the `cookies` parameter.
For more information about how to pass data to the backend (using `requests` or the `TestClient`) check the <a href="http://docs.python-requests.org" target="_blank">Requests documentation</a>.
!!! info
Note that the `TestClient` receives data that can be converted to JSON, not Pydantic models.
If you have a Pydantic model in your test and you want to send its data to the application during testing, you can use the <a href="https://fastapi.tiangolo.com/tutorial/encoder/" target="_blank">JSON compatible encoder: `jsonable_encoder`</a>.
## Testing WebSockets
You can use the same `TestClient` to test WebSockets.

View File

@@ -1,6 +1,6 @@
"""FastAPI framework, high performance, easy to learn, fast to code, ready for production"""
__version__ = "0.25.0"
__version__ = "0.30.0"
from starlette.background import BackgroundTasks

View File

@@ -1,6 +1,11 @@
from typing import Any, Callable, Dict, List, Optional, Set, Type, Union
from fastapi import routing
from fastapi.exception_handlers import (
http_exception_handler,
request_validation_exception_handler,
)
from fastapi.exceptions import RequestValidationError
from fastapi.openapi.docs import (
get_redoc_html,
get_swagger_ui_html,
@@ -8,7 +13,6 @@ from fastapi.openapi.docs import (
)
from fastapi.openapi.utils import get_openapi
from fastapi.params import Depends
from pydantic import BaseModel
from starlette.applications import Starlette
from starlette.exceptions import ExceptionMiddleware, HTTPException
from starlette.middleware.errors import ServerErrorMiddleware
@@ -17,16 +21,6 @@ from starlette.responses import HTMLResponse, JSONResponse, Response
from starlette.routing import BaseRoute
async def http_exception(request: Request, exc: HTTPException) -> JSONResponse:
headers = getattr(exc, "headers", None)
if headers:
return JSONResponse(
{"detail": exc.detail}, status_code=exc.status_code, headers=headers
)
else:
return JSONResponse({"detail": exc.detail}, status_code=exc.status_code)
class FastAPI(Starlette):
def __init__(
self,
@@ -44,7 +38,9 @@ class FastAPI(Starlette):
**extra: Dict[str, Any],
) -> None:
self._debug = debug
self.router: routing.APIRouter = routing.APIRouter(routes)
self.router: routing.APIRouter = routing.APIRouter(
routes, dependency_overrides_provider=self
)
self.exception_middleware = ExceptionMiddleware(self.router, debug=debug)
self.error_middleware = ServerErrorMiddleware(
self.exception_middleware, debug=debug
@@ -59,6 +55,7 @@ class FastAPI(Starlette):
self.redoc_url = redoc_url
self.swagger_ui_oauth2_redirect_url = swagger_ui_oauth2_redirect_url
self.extra = extra
self.dependency_overrides: Dict[Callable, Callable] = {}
self.openapi_version = "3.0.2"
@@ -120,14 +117,17 @@ class FastAPI(Starlette):
)
self.add_route(self.redoc_url, redoc_html, include_in_schema=False)
self.add_exception_handler(HTTPException, http_exception)
self.add_exception_handler(HTTPException, http_exception_handler)
self.add_exception_handler(
RequestValidationError, request_validation_exception_handler
)
def add_api_route(
self,
path: str,
endpoint: Callable,
*,
response_model: Type[BaseModel] = None,
response_model: Type[Any] = None,
status_code: int = 200,
tags: List[str] = None,
dependencies: List[Depends] = None,
@@ -173,7 +173,7 @@ class FastAPI(Starlette):
self,
path: str,
*,
response_model: Type[BaseModel] = None,
response_model: Type[Any] = None,
status_code: int = 200,
tags: List[str] = None,
dependencies: List[Depends] = None,
@@ -252,7 +252,7 @@ class FastAPI(Starlette):
self,
path: str,
*,
response_model: Type[BaseModel] = None,
response_model: Type[Any] = None,
status_code: int = 200,
tags: List[str] = None,
dependencies: List[Depends] = None,
@@ -295,7 +295,7 @@ class FastAPI(Starlette):
self,
path: str,
*,
response_model: Type[BaseModel] = None,
response_model: Type[Any] = None,
status_code: int = 200,
tags: List[str] = None,
dependencies: List[Depends] = None,
@@ -338,7 +338,7 @@ class FastAPI(Starlette):
self,
path: str,
*,
response_model: Type[BaseModel] = None,
response_model: Type[Any] = None,
status_code: int = 200,
tags: List[str] = None,
dependencies: List[Depends] = None,
@@ -381,7 +381,7 @@ class FastAPI(Starlette):
self,
path: str,
*,
response_model: Type[BaseModel] = None,
response_model: Type[Any] = None,
status_code: int = 200,
tags: List[str] = None,
dependencies: List[Depends] = None,
@@ -424,7 +424,7 @@ class FastAPI(Starlette):
self,
path: str,
*,
response_model: Type[BaseModel] = None,
response_model: Type[Any] = None,
status_code: int = 200,
tags: List[str] = None,
dependencies: List[Depends] = None,
@@ -467,7 +467,7 @@ class FastAPI(Starlette):
self,
path: str,
*,
response_model: Type[BaseModel] = None,
response_model: Type[Any] = None,
status_code: int = 200,
tags: List[str] = None,
dependencies: List[Depends] = None,
@@ -510,7 +510,7 @@ class FastAPI(Starlette):
self,
path: str,
*,
response_model: Type[BaseModel] = None,
response_model: Type[Any] = None,
status_code: int = 200,
tags: List[str] = None,
dependencies: List[Depends] = None,
@@ -553,7 +553,7 @@ class FastAPI(Starlette):
self,
path: str,
*,
response_model: Type[BaseModel] = None,
response_model: Type[Any] = None,
status_code: int = 200,
tags: List[str] = None,
dependencies: List[Depends] = None,

View File

@@ -27,9 +27,12 @@ class Dependant:
call: Callable = None,
request_param_name: str = None,
websocket_param_name: str = None,
response_param_name: str = None,
background_tasks_param_name: str = None,
security_scopes_param_name: str = None,
security_scopes: List[str] = None,
use_cache: bool = True,
path: str = None,
) -> None:
self.path_params = path_params or []
self.query_params = query_params or []
@@ -40,8 +43,14 @@ class Dependant:
self.security_requirements = security_schemes or []
self.request_param_name = request_param_name
self.websocket_param_name = websocket_param_name
self.response_param_name = response_param_name
self.background_tasks_param_name = background_tasks_param_name
self.security_scopes = security_scopes
self.security_scopes_param_name = security_scopes_param_name
self.name = name
self.call = call
self.use_cache = use_cache
# Store the path to be able to re-generate a dependable from it in overrides
self.path = path
# Save the cache key at creation to optimize performance
self.cache_key = (self.call, tuple(sorted(set(self.security_scopes or []))))

View File

@@ -1,8 +1,6 @@
import asyncio
import inspect
from copy import deepcopy
from datetime import date, datetime, time, timedelta
from decimal import Decimal
from typing import (
Any,
Callable,
@@ -14,8 +12,8 @@ from typing import (
Tuple,
Type,
Union,
cast,
)
from uuid import UUID
from fastapi import params
from fastapi.dependencies.models import Dependant, SecurityRequirement
@@ -23,7 +21,7 @@ from fastapi.security.base import SecurityBase
from fastapi.security.oauth2 import OAuth2, SecurityScopes
from fastapi.security.open_id_connect_url import OpenIdConnect
from fastapi.utils import get_path_param_names
from pydantic import BaseConfig, Schema, create_model
from pydantic import BaseConfig, BaseModel, Schema, create_model
from pydantic.error_wrappers import ErrorWrapper
from pydantic.errors import MissingError
from pydantic.fields import Field, Required, Shape
@@ -33,24 +31,24 @@ from starlette.background import BackgroundTasks
from starlette.concurrency import run_in_threadpool
from starlette.datastructures import FormData, Headers, QueryParams, UploadFile
from starlette.requests import Request
from starlette.responses import Response
from starlette.websockets import WebSocket
param_supported_types = (
str,
int,
float,
bool,
UUID,
date,
datetime,
time,
timedelta,
Decimal,
)
sequence_shapes = {Shape.LIST, Shape.SET, Shape.TUPLE}
sequence_shapes = {
Shape.LIST,
Shape.SET,
Shape.TUPLE,
Shape.SEQUENCE,
Shape.TUPLE_ELLIPS,
}
sequence_types = (list, set, tuple)
sequence_shape_to_type = {Shape.LIST: list, Shape.SET: set, Shape.TUPLE: tuple}
sequence_shape_to_type = {
Shape.LIST: list,
Shape.SET: set,
Shape.TUPLE: tuple,
Shape.SEQUENCE: list,
Shape.TUPLE_ELLIPS: list,
}
def get_param_sub_dependant(
@@ -98,7 +96,11 @@ def get_sub_dependant(
security_scheme=dependency, scopes=use_scopes
)
sub_dependant = get_dependant(
path=path, call=dependency, name=name, security_scopes=security_scopes
path=path,
call=dependency,
name=name,
security_scopes=security_scopes,
use_cache=depends.use_cache,
)
if security_requirement:
sub_dependant.security_requirements.append(security_requirement)
@@ -114,6 +116,8 @@ def get_flat_dependant(dependant: Dependant) -> Dependant:
cookie_params=dependant.cookie_params.copy(),
body_params=dependant.body_params.copy(),
security_schemes=dependant.security_requirements.copy(),
use_cache=dependant.use_cache,
path=dependant.path,
)
for sub_dependant in dependant.dependencies:
flat_sub = get_flat_dependant(sub_dependant)
@@ -126,90 +130,116 @@ def get_flat_dependant(dependant: Dependant) -> Dependant:
return flat_dependant
def is_scalar_field(field: Field) -> bool:
return (
field.shape == Shape.SINGLETON
and not lenient_issubclass(field.type_, BaseModel)
and not lenient_issubclass(field.type_, sequence_types + (dict,))
and not isinstance(field.schema, params.Body)
)
def is_scalar_sequence_field(field: Field) -> bool:
if (field.shape in sequence_shapes) and not lenient_issubclass(
field.type_, BaseModel
):
if field.sub_fields is not None:
for sub_field in field.sub_fields:
if not is_scalar_field(sub_field):
return False
return True
if lenient_issubclass(field.type_, sequence_types):
return True
return False
def get_dependant(
*, path: str, call: Callable, name: str = None, security_scopes: List[str] = None
*,
path: str,
call: Callable,
name: str = None,
security_scopes: List[str] = None,
use_cache: bool = True,
) -> Dependant:
path_param_names = get_path_param_names(path)
endpoint_signature = inspect.signature(call)
signature_params = endpoint_signature.parameters
dependant = Dependant(call=call, name=name)
for param_name in signature_params:
param = signature_params[param_name]
dependant = Dependant(call=call, name=name, path=path, use_cache=use_cache)
for param_name, param in signature_params.items():
if isinstance(param.default, params.Depends):
sub_dependant = get_param_sub_dependant(
param=param, path=path, security_scopes=security_scopes
)
dependant.dependencies.append(sub_dependant)
for param_name in signature_params:
param = signature_params[param_name]
if (
(param.default == param.empty) or isinstance(param.default, params.Path)
) and (param_name in path_param_names):
assert (
lenient_issubclass(param.annotation, param_supported_types)
or param.annotation == param.empty
for param_name, param in signature_params.items():
if isinstance(param.default, params.Depends):
continue
if add_non_field_param_to_dependency(param=param, dependant=dependant):
continue
param_field = get_param_field(param=param, default_schema=params.Query)
if param_name in path_param_names:
assert param.default == param.empty or isinstance(
param.default, params.Path
), "Path params must have no defaults or use Path(...)"
assert is_scalar_field(
field=param_field
), f"Path params must be of one of the supported types"
add_param_to_fields(
param_field = get_param_field(
param=param,
dependant=dependant,
default_schema=params.Path,
force_type=params.ParamTypes.path,
)
elif (
param.default == param.empty
or param.default is None
or isinstance(param.default, param_supported_types)
) and (
param.annotation == param.empty
or lenient_issubclass(param.annotation, param_supported_types)
):
add_param_to_fields(
param=param, dependant=dependant, default_schema=params.Query
)
elif isinstance(param.default, params.Param):
if param.annotation != param.empty:
origin = getattr(param.annotation, "__origin__", None)
param_all_types = param_supported_types + (list, tuple, set)
if isinstance(param.default, (params.Query, params.Header)):
assert lenient_issubclass(
param.annotation, param_all_types
) or lenient_issubclass(
origin, param_all_types
), f"Parameters for Query and Header must be of type str, int, float, bool, list, tuple or set: {param}"
else:
assert lenient_issubclass(
param.annotation, param_supported_types
), f"Parameters for Path and Cookies must be of type str, int, float, bool: {param}"
add_param_to_fields(
param=param, dependant=dependant, default_schema=params.Query
)
elif lenient_issubclass(param.annotation, Request):
dependant.request_param_name = param_name
elif lenient_issubclass(param.annotation, WebSocket):
dependant.websocket_param_name = param_name
elif lenient_issubclass(param.annotation, BackgroundTasks):
dependant.background_tasks_param_name = param_name
elif lenient_issubclass(param.annotation, SecurityScopes):
dependant.security_scopes_param_name = param_name
elif not isinstance(param.default, params.Depends):
add_param_to_body_fields(param=param, dependant=dependant)
add_param_to_fields(field=param_field, dependant=dependant)
elif is_scalar_field(field=param_field):
add_param_to_fields(field=param_field, dependant=dependant)
elif isinstance(
param.default, (params.Query, params.Header)
) and is_scalar_sequence_field(param_field):
add_param_to_fields(field=param_field, dependant=dependant)
else:
assert isinstance(
param_field.schema, params.Body
), f"Param: {param_field.name} can only be a request body, using Body(...)"
dependant.body_params.append(param_field)
return dependant
def add_param_to_fields(
def add_non_field_param_to_dependency(
*, param: inspect.Parameter, dependant: Dependant
) -> Optional[bool]:
if lenient_issubclass(param.annotation, Request):
dependant.request_param_name = param.name
return True
elif lenient_issubclass(param.annotation, WebSocket):
dependant.websocket_param_name = param.name
return True
elif lenient_issubclass(param.annotation, Response):
dependant.response_param_name = param.name
return True
elif lenient_issubclass(param.annotation, BackgroundTasks):
dependant.background_tasks_param_name = param.name
return True
elif lenient_issubclass(param.annotation, SecurityScopes):
dependant.security_scopes_param_name = param.name
return True
return None
def get_param_field(
*,
param: inspect.Parameter,
dependant: Dependant,
default_schema: Type[Schema] = params.Param,
default_schema: Type[params.Param] = params.Param,
force_type: params.ParamTypes = None,
) -> None:
) -> Field:
default_value = Required
had_schema = False
if not param.default == param.empty:
default_value = param.default
if isinstance(default_value, params.Param):
if isinstance(default_value, Schema):
had_schema = True
schema = default_value
default_value = schema.default
if getattr(schema, "in_", None) is None:
if isinstance(schema, params.Param) and getattr(schema, "in_", None) is None:
schema.in_ = default_schema.in_
if force_type:
schema.in_ = force_type
@@ -234,43 +264,26 @@ def add_param_to_fields(
class_validators={},
schema=schema,
)
if schema.in_ == params.ParamTypes.path:
if not had_schema and not is_scalar_field(field=field):
field.schema = params.Body(schema.default)
return field
def add_param_to_fields(*, field: Field, dependant: Dependant) -> None:
field.schema = cast(params.Param, field.schema)
if field.schema.in_ == params.ParamTypes.path:
dependant.path_params.append(field)
elif schema.in_ == params.ParamTypes.query:
elif field.schema.in_ == params.ParamTypes.query:
dependant.query_params.append(field)
elif schema.in_ == params.ParamTypes.header:
elif field.schema.in_ == params.ParamTypes.header:
dependant.header_params.append(field)
else:
assert (
schema.in_ == params.ParamTypes.cookie
), f"non-body parameters must be in path, query, header or cookie: {param.name}"
field.schema.in_ == params.ParamTypes.cookie
), f"non-body parameters must be in path, query, header or cookie: {field.name}"
dependant.cookie_params.append(field)
def add_param_to_body_fields(*, param: inspect.Parameter, dependant: Dependant) -> None:
default_value = Required
if not param.default == param.empty:
default_value = param.default
if isinstance(default_value, Schema):
schema = default_value
default_value = schema.default
else:
schema = Schema(default_value)
required = default_value == Required
annotation = get_annotation_from_schema(param.annotation, schema)
field = Field(
name=param.name,
type_=annotation,
default=None if required else default_value,
alias=schema.alias or param.name,
required=required,
model_config=BaseConfig,
class_validators={},
schema=schema,
)
dependant.body_params.append(field)
def is_coroutine_callable(call: Callable) -> bool:
if inspect.isfunction(call):
return asyncio.iscoroutinefunction(call)
@@ -284,28 +297,78 @@ async def solve_dependencies(
*,
request: Union[Request, WebSocket],
dependant: Dependant,
body: Dict[str, Any] = None,
body: Optional[Union[Dict[str, Any], FormData]] = None,
background_tasks: BackgroundTasks = None,
) -> Tuple[Dict[str, Any], List[ErrorWrapper], Optional[BackgroundTasks]]:
response: Response = None,
dependency_overrides_provider: Any = None,
dependency_cache: Dict[Tuple[Callable, Tuple[str]], Any] = None,
) -> Tuple[
Dict[str, Any],
List[ErrorWrapper],
Optional[BackgroundTasks],
Response,
Dict[Tuple[Callable, Tuple[str]], Any],
]:
values: Dict[str, Any] = {}
errors: List[ErrorWrapper] = []
response = response or Response( # type: ignore
content=None, status_code=None, headers=None, media_type=None, background=None
)
dependency_cache = dependency_cache or {}
sub_dependant: Dependant
for sub_dependant in dependant.dependencies:
sub_values, sub_errors, background_tasks = await solve_dependencies(
sub_dependant.call = cast(Callable, sub_dependant.call)
sub_dependant.cache_key = cast(
Tuple[Callable, Tuple[str]], sub_dependant.cache_key
)
call = sub_dependant.call
use_sub_dependant = sub_dependant
if (
dependency_overrides_provider
and dependency_overrides_provider.dependency_overrides
):
original_call = sub_dependant.call
call = getattr(
dependency_overrides_provider, "dependency_overrides", {}
).get(original_call, original_call)
use_path: str = sub_dependant.path # type: ignore
use_sub_dependant = get_dependant(
path=use_path,
call=call,
name=sub_dependant.name,
security_scopes=sub_dependant.security_scopes,
)
solved_result = await solve_dependencies(
request=request,
dependant=sub_dependant,
dependant=use_sub_dependant,
body=body,
background_tasks=background_tasks,
response=response,
dependency_overrides_provider=dependency_overrides_provider,
dependency_cache=dependency_cache,
)
sub_values, sub_errors, background_tasks, sub_response, sub_dependency_cache = (
solved_result
)
sub_response = cast(Response, sub_response)
response.headers.raw.extend(sub_response.headers.raw)
if sub_response.status_code:
response.status_code = sub_response.status_code
dependency_cache.update(sub_dependency_cache)
if sub_errors:
errors.extend(sub_errors)
continue
assert sub_dependant.call is not None, "sub_dependant.call must be a function"
if is_coroutine_callable(sub_dependant.call):
solved = await sub_dependant.call(**sub_values)
if sub_dependant.use_cache and sub_dependant.cache_key in dependency_cache:
solved = dependency_cache[sub_dependant.cache_key]
elif is_coroutine_callable(call):
solved = await call(**sub_values)
else:
solved = await run_in_threadpool(sub_dependant.call, **sub_values)
solved = await run_in_threadpool(call, **sub_values)
if sub_dependant.name is not None:
values[sub_dependant.name] = solved
if sub_dependant.cache_key not in dependency_cache:
dependency_cache[sub_dependant.cache_key] = solved
path_values, path_errors = request_params_to_args(
dependant.path_params, request.path_params
)
@@ -325,7 +388,7 @@ async def solve_dependencies(
errors += path_errors + query_errors + header_errors + cookie_errors
if dependant.body_params:
body_values, body_errors = await request_body_to_args( # type: ignore # body_params checked above
dependant.body_params, body
required_params=dependant.body_params, received_body=body
)
values.update(body_values)
errors.extend(body_errors)
@@ -337,11 +400,13 @@ async def solve_dependencies(
if background_tasks is None:
background_tasks = BackgroundTasks()
values[dependant.background_tasks_param_name] = background_tasks
if dependant.response_param_name:
values[dependant.response_param_name] = response
if dependant.security_scopes_param_name:
values[dependant.security_scopes_param_name] = SecurityScopes(
scopes=dependant.security_scopes
)
return values, errors, background_tasks
return values, errors, background_tasks, response, dependency_cache
def request_params_to_args(
@@ -351,10 +416,10 @@ def request_params_to_args(
values = {}
errors = []
for field in required_params:
if field.shape in sequence_shapes and isinstance(
if is_scalar_sequence_field(field) and isinstance(
received_params, (QueryParams, Headers)
):
value = received_params.getlist(field.alias)
value = received_params.getlist(field.alias) or field.default
else:
value = received_params.get(field.alias)
schema: params.Param = field.schema
@@ -382,7 +447,8 @@ def request_params_to_args(
async def request_body_to_args(
required_params: List[Field], received_body: Dict[str, Any]
required_params: List[Field],
received_body: Optional[Union[Dict[str, Any], FormData]],
) -> Tuple[Dict[str, Any], List[ErrorWrapper]]:
values = {}
errors = []
@@ -392,10 +458,14 @@ async def request_body_to_args(
if len(required_params) == 1 and not embed:
received_body = {field.alias: received_body}
for field in required_params:
if field.shape in sequence_shapes and isinstance(received_body, FormData):
value = received_body.getlist(field.alias)
else:
value = received_body.get(field.alias)
value = None
if received_body is not None:
if field.shape in sequence_shapes and isinstance(
received_body, FormData
):
value = received_body.getlist(field.alias)
else:
value = received_body.get(field.alias)
if (
value is None
or (isinstance(field.schema, params.Form) and value == "")

View File

@@ -0,0 +1,23 @@
from fastapi.exceptions import RequestValidationError
from starlette.exceptions import HTTPException
from starlette.requests import Request
from starlette.responses import JSONResponse
from starlette.status import HTTP_422_UNPROCESSABLE_ENTITY
async def http_exception_handler(request: Request, exc: HTTPException) -> JSONResponse:
headers = getattr(exc, "headers", None)
if headers:
return JSONResponse(
{"detail": exc.detail}, status_code=exc.status_code, headers=headers
)
else:
return JSONResponse({"detail": exc.detail}, status_code=exc.status_code)
async def request_validation_exception_handler(
request: Request, exc: RequestValidationError
) -> JSONResponse:
return JSONResponse(
status_code=HTTP_422_UNPROCESSABLE_ENTITY, content={"detail": exc.errors()}
)

View File

@@ -1,9 +1,20 @@
from typing import Any
from pydantic import ValidationError
from starlette.exceptions import HTTPException as StarletteHTTPException
class HTTPException(StarletteHTTPException):
def __init__(
self, status_code: int, detail: str = None, headers: dict = None
self, status_code: int, detail: Any = None, headers: dict = None
) -> None:
super().__init__(status_code=status_code, detail=detail)
self.headers = headers
class RequestValidationError(ValidationError):
pass
class WebSocketRequestValidationError(ValidationError):
pass

View File

@@ -1,4 +1,5 @@
from typing import Any, Dict, List, Optional, Sequence, Tuple, Type
import http.client
from typing import Any, Dict, List, Optional, Sequence, Tuple, Type, cast
from fastapi import routing
from fastapi.dependencies.models import Dependant
@@ -9,7 +10,7 @@ from fastapi.openapi.models import OpenAPI
from fastapi.params import Body, Param
from fastapi.utils import get_flat_models_from_routes, get_model_definitions
from pydantic.fields import Field
from pydantic.schema import Schema, field_schema, get_model_name_map
from pydantic.schema import field_schema, get_model_name_map
from pydantic.utils import lenient_issubclass
from starlette.responses import JSONResponse
from starlette.routing import BaseRoute
@@ -97,12 +98,8 @@ def get_openapi_operation_request_body(
body_schema, _ = field_schema(
body_field, model_name_map=model_name_map, ref_prefix=REF_PREFIX
)
schema: Schema = body_field.schema
if isinstance(schema, Body):
request_media_type = schema.media_type
else:
# Includes not declared media types (Schema)
request_media_type = "application/json"
body_field.schema = cast(Body, body_field.schema)
request_media_type = body_field.schema.media_type
required = body_field.required
request_body_oai: Dict[str, Any] = {}
if required:
@@ -191,7 +188,10 @@ def get_openapi_path(
response.setdefault("content", {}).setdefault(
"application/json", {}
)["schema"] = response_schema
response.setdefault("description", "Additional Response")
status_text = http.client.responses.get(int(additional_status_code))
response.setdefault(
"description", status_text or "Additional Response"
)
operation.setdefault("responses", {})[
str(additional_status_code)
] = response

View File

@@ -238,11 +238,13 @@ def File( # noqa: N802
)
def Depends(dependency: Callable = None) -> Any: # noqa: N802
return params.Depends(dependency=dependency)
def Depends( # noqa: N802
dependency: Callable = None, *, use_cache: bool = True
) -> Any:
return params.Depends(dependency=dependency, use_cache=use_cache)
def Security( # noqa: N802
dependency: Callable = None, scopes: Sequence[str] = None
dependency: Callable = None, *, scopes: Sequence[str] = None, use_cache: bool = True
) -> Any:
return params.Security(dependency=dependency, scopes=scopes)
return params.Security(dependency=dependency, scopes=scopes, use_cache=use_cache)

View File

@@ -308,11 +308,18 @@ class File(Form):
class Depends:
def __init__(self, dependency: Callable = None):
def __init__(self, dependency: Callable = None, *, use_cache: bool = True):
self.dependency = dependency
self.use_cache = use_cache
class Security(Depends):
def __init__(self, dependency: Callable = None, scopes: Sequence[str] = None):
def __init__(
self,
dependency: Callable = None,
*,
scopes: Sequence[str] = None,
use_cache: bool = True,
):
super().__init__(dependency=dependency, use_cache=use_cache)
self.scopes = scopes or []
super().__init__(dependency=dependency)

View File

@@ -1,7 +1,6 @@
import asyncio
import inspect
import logging
import re
from typing import Any, Callable, Dict, List, Optional, Set, Type, Union
from fastapi import params
@@ -13,6 +12,8 @@ from fastapi.dependencies.utils import (
solve_dependencies,
)
from fastapi.encoders import jsonable_encoder
from fastapi.exceptions import RequestValidationError, WebSocketRequestValidationError
from fastapi.utils import create_cloned_field
from pydantic import BaseConfig, BaseModel, Schema
from pydantic.error_wrappers import ErrorWrapper, ValidationError
from pydantic.fields import Field
@@ -28,7 +29,8 @@ from starlette.routing import (
request_response,
websocket_session,
)
from starlette.status import HTTP_422_UNPROCESSABLE_ENTITY, WS_1008_POLICY_VIOLATION
from starlette.status import WS_1008_POLICY_VIOLATION
from starlette.types import ASGIApp
from starlette.websockets import WebSocket
@@ -41,17 +43,9 @@ def serialize_response(
by_alias: bool = True,
skip_defaults: bool = False,
) -> Any:
encoded = jsonable_encoder(
response,
include=include,
exclude=exclude,
by_alias=by_alias,
skip_defaults=skip_defaults,
)
if field:
errors = []
value, errors_ = field.validate(encoded, {}, loc=("response",))
value, errors_ = field.validate(response, {}, loc=("response",))
if isinstance(errors_, ErrorWrapper):
errors.append(errors_)
elif isinstance(errors_, list):
@@ -66,7 +60,7 @@ def serialize_response(
skip_defaults=skip_defaults,
)
else:
return encoded
return jsonable_encoder(response)
def get_app(
@@ -79,6 +73,7 @@ def get_app(
response_model_exclude: Set[str] = set(),
response_model_by_alias: bool = True,
response_model_skip_defaults: bool = False,
dependency_overrides_provider: Any = None,
) -> Callable:
assert dependant.call is not None, "dependant.call must be a function"
is_coroutine = asyncio.iscoroutinefunction(dependant.call)
@@ -99,14 +94,15 @@ def get_app(
raise HTTPException(
status_code=400, detail="There was an error parsing the body"
) from e
values, errors, background_tasks = await solve_dependencies(
request=request, dependant=dependant, body=body
solved_result = await solve_dependencies(
request=request,
dependant=dependant,
body=body,
dependency_overrides_provider=dependency_overrides_provider,
)
values, errors, background_tasks, sub_response, _ = solved_result
if errors:
errors_out = ValidationError(errors)
raise HTTPException(
status_code=HTTP_422_UNPROCESSABLE_ENTITY, detail=errors_out.errors()
)
raise RequestValidationError(errors)
else:
assert dependant.call is not None, "dependant.call must be a function"
if is_coroutine:
@@ -125,26 +121,32 @@ def get_app(
by_alias=response_model_by_alias,
skip_defaults=response_model_skip_defaults,
)
return response_class(
response = response_class(
content=response_data,
status_code=status_code,
background=background_tasks,
)
response.headers.raw.extend(sub_response.headers.raw)
if sub_response.status_code:
response.status_code = sub_response.status_code
return response
return app
def get_websocket_app(dependant: Dependant) -> Callable:
def get_websocket_app(
dependant: Dependant, dependency_overrides_provider: Any = None
) -> Callable:
async def app(websocket: WebSocket) -> None:
values, errors, _ = await solve_dependencies(
request=websocket, dependant=dependant
solved_result = await solve_dependencies(
request=websocket,
dependant=dependant,
dependency_overrides_provider=dependency_overrides_provider,
)
values, errors, _, _2, _3 = solved_result
if errors:
await websocket.close(code=WS_1008_POLICY_VIOLATION)
errors_out = ValidationError(errors)
raise HTTPException(
status_code=HTTP_422_UNPROCESSABLE_ENTITY, detail=errors_out.errors()
)
raise WebSocketRequestValidationError(errors)
assert dependant.call is not None, "dependant.call must me a function"
await dependant.call(**values)
@@ -152,14 +154,24 @@ def get_websocket_app(dependant: Dependant) -> Callable:
class APIWebSocketRoute(routing.WebSocketRoute):
def __init__(self, path: str, endpoint: Callable, *, name: str = None) -> None:
def __init__(
self,
path: str,
endpoint: Callable,
*,
name: str = None,
dependency_overrides_provider: Any = None,
) -> None:
self.path = path
self.endpoint = endpoint
self.name = get_name(endpoint) if name is None else name
self.dependant = get_dependant(path=path, call=self.endpoint)
self.app = websocket_session(get_websocket_app(dependant=self.dependant))
regex = "^" + path + "$"
regex = re.sub("{([a-zA-Z_][a-zA-Z0-9_]*)}", r"(?P<\1>[^/]+)", regex)
self.app = websocket_session(
get_websocket_app(
dependant=self.dependant,
dependency_overrides_provider=dependency_overrides_provider,
)
)
self.path_regex, self.path_format, self.param_convertors = compile_path(path)
@@ -169,7 +181,7 @@ class APIRoute(routing.Route):
path: str,
endpoint: Callable,
*,
response_model: Type[BaseModel] = None,
response_model: Type[Any] = None,
status_code: int = 200,
tags: List[str] = None,
dependencies: List[params.Depends] = None,
@@ -187,6 +199,7 @@ class APIRoute(routing.Route):
response_model_skip_defaults: bool = False,
include_in_schema: bool = True,
response_class: Type[Response] = JSONResponse,
dependency_overrides_provider: Any = None,
) -> None:
assert path.startswith("/"), "Routed paths must always start with '/'"
self.path = path
@@ -207,8 +220,17 @@ class APIRoute(routing.Route):
model_config=BaseConfig,
schema=Schema(None),
)
# Create a clone of the field, so that a Pydantic submodel is not returned
# as is just because it's an instance of a subclass of a more limited class
# e.g. UserInDB (containing hashed_password) could be a subclass of User
# that doesn't have the hashed_password. But because it's a subclass, it
# would pass the validation and be returned as is.
# By being a new field, no inheritance will be passed as is. A new model
# will be always created.
self.secure_cloned_response_field = create_cloned_field(self.response_field)
else:
self.response_field = None
self.secure_cloned_response_field = None
self.status_code = status_code
self.tags = tags or []
self.dependencies = dependencies or []
@@ -255,34 +277,49 @@ class APIRoute(routing.Route):
assert inspect.isfunction(endpoint) or inspect.ismethod(
endpoint
), f"An endpoint must be a function or method"
self.dependant = get_dependant(path=path, call=self.endpoint)
self.dependant = get_dependant(path=self.path_format, call=self.endpoint)
for depends in self.dependencies[::-1]:
self.dependant.dependencies.insert(
0, get_parameterless_sub_dependant(depends=depends, path=path)
0,
get_parameterless_sub_dependant(depends=depends, path=self.path_format),
)
self.body_field = get_body_field(dependant=self.dependant, name=self.name)
self.dependency_overrides_provider = dependency_overrides_provider
self.app = request_response(
get_app(
dependant=self.dependant,
body_field=self.body_field,
status_code=self.status_code,
response_class=self.response_class,
response_field=self.response_field,
response_field=self.secure_cloned_response_field,
response_model_include=self.response_model_include,
response_model_exclude=self.response_model_exclude,
response_model_by_alias=self.response_model_by_alias,
response_model_skip_defaults=self.response_model_skip_defaults,
dependency_overrides_provider=self.dependency_overrides_provider,
)
)
class APIRouter(routing.Router):
def __init__(
self,
routes: List[routing.BaseRoute] = None,
redirect_slashes: bool = True,
default: ASGIApp = None,
dependency_overrides_provider: Any = None,
) -> None:
super().__init__(
routes=routes, redirect_slashes=redirect_slashes, default=default
)
self.dependency_overrides_provider = dependency_overrides_provider
def add_api_route(
self,
path: str,
endpoint: Callable,
*,
response_model: Type[BaseModel] = None,
response_model: Type[Any] = None,
status_code: int = 200,
tags: List[str] = None,
dependencies: List[params.Depends] = None,
@@ -322,6 +359,7 @@ class APIRouter(routing.Router):
include_in_schema=include_in_schema,
response_class=response_class,
name=name,
dependency_overrides_provider=self.dependency_overrides_provider,
)
self.routes.append(route)
@@ -329,7 +367,7 @@ class APIRouter(routing.Router):
self,
path: str,
*,
response_model: Type[BaseModel] = None,
response_model: Type[Any] = None,
status_code: int = 200,
tags: List[str] = None,
dependencies: List[params.Depends] = None,
@@ -450,7 +488,7 @@ class APIRouter(routing.Router):
self,
path: str,
*,
response_model: Type[BaseModel] = None,
response_model: Type[Any] = None,
status_code: int = 200,
tags: List[str] = None,
dependencies: List[params.Depends] = None,
@@ -495,7 +533,7 @@ class APIRouter(routing.Router):
self,
path: str,
*,
response_model: Type[BaseModel] = None,
response_model: Type[Any] = None,
status_code: int = 200,
tags: List[str] = None,
dependencies: List[params.Depends] = None,
@@ -539,7 +577,7 @@ class APIRouter(routing.Router):
self,
path: str,
*,
response_model: Type[BaseModel] = None,
response_model: Type[Any] = None,
status_code: int = 200,
tags: List[str] = None,
dependencies: List[params.Depends] = None,
@@ -583,7 +621,7 @@ class APIRouter(routing.Router):
self,
path: str,
*,
response_model: Type[BaseModel] = None,
response_model: Type[Any] = None,
status_code: int = 200,
tags: List[str] = None,
dependencies: List[params.Depends] = None,
@@ -627,7 +665,7 @@ class APIRouter(routing.Router):
self,
path: str,
*,
response_model: Type[BaseModel] = None,
response_model: Type[Any] = None,
status_code: int = 200,
tags: List[str] = None,
dependencies: List[params.Depends] = None,
@@ -671,7 +709,7 @@ class APIRouter(routing.Router):
self,
path: str,
*,
response_model: Type[BaseModel] = None,
response_model: Type[Any] = None,
status_code: int = 200,
tags: List[str] = None,
dependencies: List[params.Depends] = None,
@@ -715,7 +753,7 @@ class APIRouter(routing.Router):
self,
path: str,
*,
response_model: Type[BaseModel] = None,
response_model: Type[Any] = None,
status_code: int = 200,
tags: List[str] = None,
dependencies: List[params.Depends] = None,
@@ -759,7 +797,7 @@ class APIRouter(routing.Router):
self,
path: str,
*,
response_model: Type[BaseModel] = None,
response_model: Type[Any] = None,
status_code: int = 200,
tags: List[str] = None,
dependencies: List[params.Depends] = None,

View File

@@ -112,10 +112,13 @@ class HTTPBearer(HTTPBase):
else:
return None
if scheme.lower() != "bearer":
raise HTTPException(
status_code=HTTP_403_FORBIDDEN,
detail="Invalid authentication credentials",
)
if self.auto_error:
raise HTTPException(
status_code=HTTP_403_FORBIDDEN,
detail="Invalid authentication credentials",
)
else:
return None
return HTTPAuthorizationCredentials(scheme=scheme, credentials=credentials)

View File

@@ -1,11 +1,12 @@
import re
from typing import Any, Dict, List, Sequence, Set, Type
from typing import Any, Dict, List, Sequence, Set, Type, cast
from fastapi import routing
from fastapi.openapi.constants import REF_PREFIX
from pydantic import BaseModel
from pydantic import BaseConfig, BaseModel, Schema, create_model
from pydantic.fields import Field
from pydantic.schema import get_flat_models_from_fields, model_process_schema
from pydantic.utils import lenient_issubclass
from starlette.routing import BaseRoute
@@ -28,7 +29,7 @@ def get_flat_models_from_routes(
if route.response_fields:
responses_from_routes.extend(route.response_fields.values())
flat_models = get_flat_models_from_fields(
body_fields_from_routes + responses_from_routes
body_fields_from_routes + responses_from_routes, known_models=set()
)
return flat_models
@@ -49,3 +50,48 @@ def get_model_definitions(
def get_path_param_names(path: str) -> Set[str]:
return {item.strip("{}") for item in re.findall("{[^}]*}", path)}
def create_cloned_field(field: Field) -> Field:
original_type = field.type_
use_type = original_type
if lenient_issubclass(original_type, BaseModel):
original_type = cast(Type[BaseModel], original_type)
use_type = create_model( # type: ignore
original_type.__name__,
__config__=original_type.__config__,
__validators__=original_type.__validators__,
)
for f in original_type.__fields__.values():
use_type.__fields__[f.name] = f
new_field = Field(
name=field.name,
type_=use_type,
class_validators={},
default=None,
required=False,
model_config=BaseConfig,
schema=Schema(None),
)
new_field.has_alias = field.has_alias
new_field.alias = field.alias
new_field.class_validators = field.class_validators
new_field.default = field.default
new_field.required = field.required
new_field.model_config = field.model_config
new_field.schema = field.schema
new_field.allow_none = field.allow_none
new_field.validate_always = field.validate_always
if field.sub_fields:
new_field.sub_fields = [
create_cloned_field(sub_field) for sub_field in field.sub_fields
]
if field.key_field:
new_field.key_field = create_cloned_field(field.key_field)
new_field.validators = field.validators
new_field.whole_pre_validators = field.whole_pre_validators
new_field.whole_post_validators = field.whole_post_validators
new_field.parse_json = field.parse_json
new_field.shape = field.shape
new_field._populate_validators()
return new_field

View File

@@ -51,6 +51,7 @@ nav:
- Additional Responses in OpenAPI: 'tutorial/additional-responses.md'
- Response Cookies: 'tutorial/response-cookies.md'
- Response Headers: 'tutorial/response-headers.md'
- Response - Change Status Code: 'tutorial/response-change-status-code.md'
- Dependencies:
- First Steps: 'tutorial/dependencies/first-steps.md'
- Classes as Dependencies: 'tutorial/dependencies/classes-as-dependencies.md'
@@ -81,6 +82,7 @@ nav:
- WebSockets: 'tutorial/websockets.md'
- 'Events: startup - shutdown': 'tutorial/events.md'
- Testing: 'tutorial/testing.md'
- Testing Dependencies with Overrides: 'tutorial/testing-dependencies.md'
- Debugging: 'tutorial/debugging.md'
- Extending OpenAPI: 'tutorial/extending-openapi.md'
- Concurrency and async / await: 'async.md'

View File

@@ -20,7 +20,7 @@ classifiers = [
]
requires = [
"starlette >=0.11.1,<=0.12.0",
"pydantic >=0.17,<=0.26.0"
"pydantic >=0.28,<=0.28.0"
]
description-file = "README.md"
requires-python = ">=3.6"

6
scripts/format-imports.sh Executable file
View File

@@ -0,0 +1,6 @@
#!/bin/sh -e
set -x
# Sort imports one per line, so autoflake can remove unused imports
isort --recursive --force-single-line-imports --thirdparty fastapi --apply fastapi tests docs/src
sh ./scripts/format.sh

View File

@@ -0,0 +1,68 @@
from fastapi import Depends, FastAPI
from starlette.testclient import TestClient
app = FastAPI()
counter_holder = {"counter": 0}
async def dep_counter():
counter_holder["counter"] += 1
return counter_holder["counter"]
async def super_dep(count: int = Depends(dep_counter)):
return count
@app.get("/counter/")
async def get_counter(count: int = Depends(dep_counter)):
return {"counter": count}
@app.get("/sub-counter/")
async def get_sub_counter(
subcount: int = Depends(super_dep), count: int = Depends(dep_counter)
):
return {"counter": count, "subcounter": subcount}
@app.get("/sub-counter-no-cache/")
async def get_sub_counter_no_cache(
subcount: int = Depends(super_dep),
count: int = Depends(dep_counter, use_cache=False),
):
return {"counter": count, "subcounter": subcount}
client = TestClient(app)
def test_normal_counter():
counter_holder["counter"] = 0
response = client.get("/counter/")
assert response.status_code == 200
assert response.json() == {"counter": 1}
response = client.get("/counter/")
assert response.status_code == 200
assert response.json() == {"counter": 2}
def test_sub_counter():
counter_holder["counter"] = 0
response = client.get("/sub-counter/")
assert response.status_code == 200
assert response.json() == {"counter": 1, "subcounter": 1}
response = client.get("/sub-counter/")
assert response.status_code == 200
assert response.json() == {"counter": 2, "subcounter": 2}
def test_sub_counter_no_cache():
counter_holder["counter"] = 0
response = client.get("/sub-counter-no-cache/")
assert response.status_code == 200
assert response.json() == {"counter": 2, "subcounter": 1}
response = client.get("/sub-counter-no-cache/")
assert response.status_code == 200
assert response.json() == {"counter": 4, "subcounter": 3}

View File

@@ -0,0 +1,313 @@
import pytest
from fastapi import APIRouter, Depends, FastAPI
from starlette.testclient import TestClient
app = FastAPI()
router = APIRouter()
async def common_parameters(q: str, skip: int = 0, limit: int = 100):
return {"q": q, "skip": skip, "limit": limit}
@app.get("/main-depends/")
async def main_depends(commons: dict = Depends(common_parameters)):
return {"in": "main-depends", "params": commons}
@app.get("/decorator-depends/", dependencies=[Depends(common_parameters)])
async def decorator_depends():
return {"in": "decorator-depends"}
@router.get("/router-depends/")
async def router_depends(commons: dict = Depends(common_parameters)):
return {"in": "router-depends", "params": commons}
@router.get("/router-decorator-depends/", dependencies=[Depends(common_parameters)])
async def router_decorator_depends():
return {"in": "router-decorator-depends"}
app.include_router(router)
client = TestClient(app)
async def overrider_dependency_simple(q: str = None):
return {"q": q, "skip": 5, "limit": 10}
async def overrider_sub_dependency(k: str):
return {"k": k}
async def overrider_dependency_with_sub(msg: dict = Depends(overrider_sub_dependency)):
return msg
@pytest.mark.parametrize(
"url,status_code,expected",
[
(
"/main-depends/",
422,
{
"detail": [
{
"loc": ["query", "q"],
"msg": "field required",
"type": "value_error.missing",
}
]
},
),
(
"/main-depends/?q=foo",
200,
{"in": "main-depends", "params": {"q": "foo", "skip": 0, "limit": 100}},
),
(
"/main-depends/?q=foo&skip=100&limit=200",
200,
{"in": "main-depends", "params": {"q": "foo", "skip": 100, "limit": 200}},
),
(
"/decorator-depends/",
422,
{
"detail": [
{
"loc": ["query", "q"],
"msg": "field required",
"type": "value_error.missing",
}
]
},
),
("/decorator-depends/?q=foo", 200, {"in": "decorator-depends"}),
(
"/decorator-depends/?q=foo&skip=100&limit=200",
200,
{"in": "decorator-depends"},
),
(
"/router-depends/",
422,
{
"detail": [
{
"loc": ["query", "q"],
"msg": "field required",
"type": "value_error.missing",
}
]
},
),
(
"/router-depends/?q=foo",
200,
{"in": "router-depends", "params": {"q": "foo", "skip": 0, "limit": 100}},
),
(
"/router-depends/?q=foo&skip=100&limit=200",
200,
{"in": "router-depends", "params": {"q": "foo", "skip": 100, "limit": 200}},
),
(
"/router-decorator-depends/",
422,
{
"detail": [
{
"loc": ["query", "q"],
"msg": "field required",
"type": "value_error.missing",
}
]
},
),
("/router-decorator-depends/?q=foo", 200, {"in": "router-decorator-depends"}),
(
"/router-decorator-depends/?q=foo&skip=100&limit=200",
200,
{"in": "router-decorator-depends"},
),
],
)
def test_normal_app(url, status_code, expected):
response = client.get(url)
assert response.status_code == status_code
assert response.json() == expected
@pytest.mark.parametrize(
"url,status_code,expected",
[
(
"/main-depends/",
200,
{"in": "main-depends", "params": {"q": None, "skip": 5, "limit": 10}},
),
(
"/main-depends/?q=foo",
200,
{"in": "main-depends", "params": {"q": "foo", "skip": 5, "limit": 10}},
),
(
"/main-depends/?q=foo&skip=100&limit=200",
200,
{"in": "main-depends", "params": {"q": "foo", "skip": 5, "limit": 10}},
),
("/decorator-depends/", 200, {"in": "decorator-depends"}),
(
"/router-depends/",
200,
{"in": "router-depends", "params": {"q": None, "skip": 5, "limit": 10}},
),
(
"/router-depends/?q=foo",
200,
{"in": "router-depends", "params": {"q": "foo", "skip": 5, "limit": 10}},
),
(
"/router-depends/?q=foo&skip=100&limit=200",
200,
{"in": "router-depends", "params": {"q": "foo", "skip": 5, "limit": 10}},
),
("/router-decorator-depends/", 200, {"in": "router-decorator-depends"}),
],
)
def test_override_simple(url, status_code, expected):
app.dependency_overrides[common_parameters] = overrider_dependency_simple
response = client.get(url)
assert response.status_code == status_code
assert response.json() == expected
app.dependency_overrides = {}
@pytest.mark.parametrize(
"url,status_code,expected",
[
(
"/main-depends/",
422,
{
"detail": [
{
"loc": ["query", "k"],
"msg": "field required",
"type": "value_error.missing",
}
]
},
),
(
"/main-depends/?q=foo",
422,
{
"detail": [
{
"loc": ["query", "k"],
"msg": "field required",
"type": "value_error.missing",
}
]
},
),
("/main-depends/?k=bar", 200, {"in": "main-depends", "params": {"k": "bar"}}),
(
"/decorator-depends/",
422,
{
"detail": [
{
"loc": ["query", "k"],
"msg": "field required",
"type": "value_error.missing",
}
]
},
),
(
"/decorator-depends/?q=foo",
422,
{
"detail": [
{
"loc": ["query", "k"],
"msg": "field required",
"type": "value_error.missing",
}
]
},
),
("/decorator-depends/?k=bar", 200, {"in": "decorator-depends"}),
(
"/router-depends/",
422,
{
"detail": [
{
"loc": ["query", "k"],
"msg": "field required",
"type": "value_error.missing",
}
]
},
),
(
"/router-depends/?q=foo",
422,
{
"detail": [
{
"loc": ["query", "k"],
"msg": "field required",
"type": "value_error.missing",
}
]
},
),
(
"/router-depends/?k=bar",
200,
{"in": "router-depends", "params": {"k": "bar"}},
),
(
"/router-decorator-depends/",
422,
{
"detail": [
{
"loc": ["query", "k"],
"msg": "field required",
"type": "value_error.missing",
}
]
},
),
(
"/router-decorator-depends/?q=foo",
422,
{
"detail": [
{
"loc": ["query", "k"],
"msg": "field required",
"type": "value_error.missing",
}
]
},
),
("/router-decorator-depends/?k=bar", 200, {"in": "router-decorator-depends"}),
],
)
def test_override_with_sub(url, status_code, expected):
app.dependency_overrides[common_parameters] = overrider_dependency_with_sub
response = client.get(url)
assert response.status_code == status_code
assert response.json() == expected
app.dependency_overrides = {}

View File

@@ -0,0 +1,77 @@
from typing import Dict, List, Tuple
import pytest
from fastapi import FastAPI
from pydantic import BaseModel
def test_invalid_sequence():
with pytest.raises(AssertionError):
app = FastAPI()
class Item(BaseModel):
title: str
@app.get("/items/{id}")
def read_items(id: List[Item]):
pass # pragma: no cover
def test_invalid_tuple():
with pytest.raises(AssertionError):
app = FastAPI()
class Item(BaseModel):
title: str
@app.get("/items/{id}")
def read_items(id: Tuple[Item, Item]):
pass # pragma: no cover
def test_invalid_dict():
with pytest.raises(AssertionError):
app = FastAPI()
class Item(BaseModel):
title: str
@app.get("/items/{id}")
def read_items(id: Dict[str, Item]):
pass # pragma: no cover
def test_invalid_simple_list():
with pytest.raises(AssertionError):
app = FastAPI()
@app.get("/items/{id}")
def read_items(id: list):
pass # pragma: no cover
def test_invalid_simple_tuple():
with pytest.raises(AssertionError):
app = FastAPI()
@app.get("/items/{id}")
def read_items(id: tuple):
pass # pragma: no cover
def test_invalid_simple_set():
with pytest.raises(AssertionError):
app = FastAPI()
@app.get("/items/{id}")
def read_items(id: set):
pass # pragma: no cover
def test_invalid_simple_dict():
with pytest.raises(AssertionError):
app = FastAPI()
@app.get("/items/{id}")
def read_items(id: dict):
pass # pragma: no cover

View File

@@ -0,0 +1,53 @@
from typing import Dict, List, Tuple
import pytest
from fastapi import FastAPI, Query
from pydantic import BaseModel
def test_invalid_sequence():
with pytest.raises(AssertionError):
app = FastAPI()
class Item(BaseModel):
title: str
@app.get("/items/")
def read_items(q: List[Item] = Query(None)):
pass # pragma: no cover
def test_invalid_tuple():
with pytest.raises(AssertionError):
app = FastAPI()
class Item(BaseModel):
title: str
@app.get("/items/")
def read_items(q: Tuple[Item, Item] = Query(None)):
pass # pragma: no cover
def test_invalid_dict():
with pytest.raises(AssertionError):
app = FastAPI()
class Item(BaseModel):
title: str
@app.get("/items/")
def read_items(q: Dict[str, Item] = Query(None)):
pass # pragma: no cover
def test_invalid_simple_dict():
with pytest.raises(AssertionError):
app = FastAPI()
class Item(BaseModel):
title: str
@app.get("/items/")
def read_items(q: dict = Query(None)):
pass # pragma: no cover

View File

@@ -0,0 +1,27 @@
from fastapi import Depends, FastAPI
from starlette.responses import Response
from starlette.testclient import TestClient
app = FastAPI()
async def response_status_setter(response: Response):
response.status_code = 201
async def parent_dep(result=Depends(response_status_setter)):
return result
@app.get("/", dependencies=[Depends(parent_dep)])
async def get_main():
return {"msg": "Hello World"}
client = TestClient(app)
def test_dependency_set_status_code():
response = client.get("/")
assert response.status_code == 201
assert response.json() == {"msg": "Hello World"}

View File

@@ -64,5 +64,5 @@ def test_security_http_bearer_no_credentials():
def test_security_http_bearer_incorrect_scheme_credentials():
response = client.get("/users/me", headers={"Authorization": "Basic notreally"})
assert response.status_code == 403
assert response.json() == {"detail": "Invalid authentication credentials"}
assert response.status_code == 200
assert response.json() == {"msg": "Create an account first"}

View File

@@ -12,7 +12,7 @@ openapi_schema = {
"get": {
"responses": {
"404": {
"description": "Additional Response",
"description": "Not Found",
"content": {
"application/json": {
"schema": {"$ref": "#/components/schemas/Message"}

View File

@@ -0,0 +1,172 @@
import pytest
from starlette.testclient import TestClient
from body_multiple_params.tutorial003 import app
client = TestClient(app)
openapi_schema = {
"openapi": "3.0.2",
"info": {"title": "Fast API", "version": "0.1.0"},
"paths": {
"/items/{item_id}": {
"put": {
"responses": {
"200": {
"description": "Successful Response",
"content": {"application/json": {"schema": {}}},
},
"422": {
"description": "Validation Error",
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/HTTPValidationError"
}
}
},
},
},
"summary": "Update Item",
"operationId": "update_item_items__item_id__put",
"parameters": [
{
"required": True,
"schema": {"title": "Item_Id", "type": "integer"},
"name": "item_id",
"in": "path",
}
],
"requestBody": {
"content": {
"application/json": {
"schema": {"$ref": "#/components/schemas/Body_update_item"}
}
},
"required": True,
},
}
}
},
"components": {
"schemas": {
"Item": {
"title": "Item",
"required": ["name", "price"],
"type": "object",
"properties": {
"name": {"title": "Name", "type": "string"},
"price": {"title": "Price", "type": "number"},
"description": {"title": "Description", "type": "string"},
"tax": {"title": "Tax", "type": "number"},
},
},
"User": {
"title": "User",
"required": ["username"],
"type": "object",
"properties": {
"username": {"title": "Username", "type": "string"},
"full_name": {"title": "Full_Name", "type": "string"},
},
},
"Body_update_item": {
"title": "Body_update_item",
"required": ["item", "user", "importance"],
"type": "object",
"properties": {
"item": {"$ref": "#/components/schemas/Item"},
"user": {"$ref": "#/components/schemas/User"},
"importance": {"title": "Importance", "type": "integer"},
},
},
"ValidationError": {
"title": "ValidationError",
"required": ["loc", "msg", "type"],
"type": "object",
"properties": {
"loc": {
"title": "Location",
"type": "array",
"items": {"type": "string"},
},
"msg": {"title": "Message", "type": "string"},
"type": {"title": "Error Type", "type": "string"},
},
},
"HTTPValidationError": {
"title": "HTTPValidationError",
"type": "object",
"properties": {
"detail": {
"title": "Detail",
"type": "array",
"items": {"$ref": "#/components/schemas/ValidationError"},
}
},
},
}
},
}
def test_openapi_schema():
response = client.get("/openapi.json")
assert response.status_code == 200
assert response.json() == openapi_schema
# Test required and embedded body parameters with no bodies sent
@pytest.mark.parametrize(
"path,body,expected_status,expected_response",
[
(
"/items/5",
{
"importance": 2,
"item": {"name": "Foo", "price": 50.5},
"user": {"username": "Dave"},
},
200,
{
"item_id": 5,
"importance": 2,
"item": {
"name": "Foo",
"price": 50.5,
"description": None,
"tax": None,
},
"user": {"username": "Dave", "full_name": None},
},
),
(
"/items/5",
None,
422,
{
"detail": [
{
"loc": ["body", "item"],
"msg": "field required",
"type": "value_error.missing",
},
{
"loc": ["body", "user"],
"msg": "field required",
"type": "value_error.missing",
},
{
"loc": ["body", "importance"],
"msg": "field required",
"type": "value_error.missing",
},
]
},
),
],
)
def test_post_body(path, body, expected_status, expected_response):
response = client.put(path, json=body)
assert response.status_code == expected_status
assert response.json() == expected_response

View File

View File

@@ -0,0 +1,103 @@
from starlette.testclient import TestClient
from body_nested_models.tutorial009 import app
client = TestClient(app)
openapi_schema = {
"openapi": "3.0.2",
"info": {"title": "Fast API", "version": "0.1.0"},
"paths": {
"/index-weights/": {
"post": {
"responses": {
"200": {
"description": "Successful Response",
"content": {"application/json": {"schema": {}}},
},
"422": {
"description": "Validation Error",
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/HTTPValidationError"
}
}
},
},
},
"summary": "Create Index Weights",
"operationId": "create_index_weights_index-weights__post",
"requestBody": {
"content": {
"application/json": {
"schema": {
"title": "Weights",
"type": "object",
"additionalProperties": {"type": "number"},
}
}
},
"required": True,
},
}
}
},
"components": {
"schemas": {
"ValidationError": {
"title": "ValidationError",
"required": ["loc", "msg", "type"],
"type": "object",
"properties": {
"loc": {
"title": "Location",
"type": "array",
"items": {"type": "string"},
},
"msg": {"title": "Message", "type": "string"},
"type": {"title": "Error Type", "type": "string"},
},
},
"HTTPValidationError": {
"title": "HTTPValidationError",
"type": "object",
"properties": {
"detail": {
"title": "Detail",
"type": "array",
"items": {"$ref": "#/components/schemas/ValidationError"},
}
},
},
}
},
}
def test_openapi_schema():
response = client.get("/openapi.json")
assert response.status_code == 200
assert response.json() == openapi_schema
def test_post_body():
data = {"2": 2.2, "3": 3.3}
response = client.post("/index-weights/", json=data)
assert response.status_code == 200
assert response.json() == data
def test_post_invalid_body():
data = {"foo": 2.2, "3": 3.3}
response = client.post("/index-weights/", json=data)
assert response.status_code == 422
assert response.json() == {
"detail": [
{
"loc": ["body", "weights", "__key__"],
"msg": "value is not a valid integer",
"type": "type_error.integer",
}
]
}

View File

@@ -0,0 +1,44 @@
from starlette.testclient import TestClient
from extra_models.tutorial005 import app
client = TestClient(app)
openapi_schema = {
"openapi": "3.0.2",
"info": {"title": "Fast API", "version": "0.1.0"},
"paths": {
"/keyword-weights/": {
"get": {
"responses": {
"200": {
"description": "Successful Response",
"content": {
"application/json": {
"schema": {
"title": "Response_Read_Keyword_Weights",
"type": "object",
"additionalProperties": {"type": "number"},
}
}
},
}
},
"summary": "Read Keyword Weights",
"operationId": "read_keyword_weights_keyword-weights__get",
}
}
},
}
def test_openapi_schema():
response = client.get("/openapi.json")
assert response.status_code == 200
assert response.json() == openapi_schema
def test_get_items():
response = client.get("/keyword-weights/")
assert response.status_code == 200
assert response.json() == {"foo": 2.3, "bar": 3.4}

View File

@@ -1,6 +1,6 @@
from starlette.testclient import TestClient
from sql_databases.tutorial001 import app
from handling_errors.tutorial003 import app
client = TestClient(app)
@@ -8,7 +8,7 @@ openapi_schema = {
"openapi": "3.0.2",
"info": {"title": "Fast API", "version": "0.1.0"},
"paths": {
"/users/{user_id}": {
"/unicorns/{name}": {
"get": {
"responses": {
"200": {
@@ -26,13 +26,13 @@ openapi_schema = {
},
},
},
"summary": "Read User",
"operationId": "read_user_users__user_id__get",
"summary": "Read Unicorn",
"operationId": "read_unicorn_unicorns__name__get",
"parameters": [
{
"required": True,
"schema": {"title": "User_Id", "type": "integer"},
"name": "user_id",
"schema": {"title": "Name", "type": "string"},
"name": "name",
"in": "path",
}
],
@@ -77,12 +77,15 @@ def test_openapi_schema():
assert response.json() == openapi_schema
def test_first_user():
response = client.get("/users/1")
def test_get():
response = client.get("/unicorns/shinny")
assert response.status_code == 200
assert response.json() == {"unicorn_name": "shinny"}
def test_get_exception():
response = client.get("/unicorns/yolo")
assert response.status_code == 418
assert response.json() == {
"is_active": True,
"hashed_password": "notreallyhashed",
"email": "johndoe@example.com",
"id": 1,
"message": "Oops! yolo did something. There goes a rainbow..."
}

View File

@@ -0,0 +1,100 @@
from starlette.testclient import TestClient
from handling_errors.tutorial004 import app
client = TestClient(app)
openapi_schema = {
"openapi": "3.0.2",
"info": {"title": "Fast API", "version": "0.1.0"},
"paths": {
"/items/{item_id}": {
"get": {
"responses": {
"200": {
"description": "Successful Response",
"content": {"application/json": {"schema": {}}},
},
"422": {
"description": "Validation Error",
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/HTTPValidationError"
}
}
},
},
},
"summary": "Read Item",
"operationId": "read_item_items__item_id__get",
"parameters": [
{
"required": True,
"schema": {"title": "Item_Id", "type": "integer"},
"name": "item_id",
"in": "path",
}
],
}
}
},
"components": {
"schemas": {
"ValidationError": {
"title": "ValidationError",
"required": ["loc", "msg", "type"],
"type": "object",
"properties": {
"loc": {
"title": "Location",
"type": "array",
"items": {"type": "string"},
},
"msg": {"title": "Message", "type": "string"},
"type": {"title": "Error Type", "type": "string"},
},
},
"HTTPValidationError": {
"title": "HTTPValidationError",
"type": "object",
"properties": {
"detail": {
"title": "Detail",
"type": "array",
"items": {"$ref": "#/components/schemas/ValidationError"},
}
},
},
}
},
}
def test_openapi_schema():
response = client.get("/openapi.json")
assert response.status_code == 200
assert response.json() == openapi_schema
def test_get_validation_error():
response = client.get("/items/foo")
assert response.status_code == 400
validation_error_str_lines = [
b"1 validation error",
b"path -> item_id",
b" value is not a valid integer (type=type_error.integer)",
]
assert response.content == b"\n".join(validation_error_str_lines)
def test_get_http_error():
response = client.get("/items/3")
assert response.status_code == 418
assert response.content == b"Nope! I don't like 3."
def test_get():
response = client.get("/items/2")
assert response.status_code == 200
assert response.json() == {"item_id": 2}

View File

@@ -0,0 +1,103 @@
from starlette.testclient import TestClient
from handling_errors.tutorial005 import app
client = TestClient(app)
openapi_schema = {
"openapi": "3.0.2",
"info": {"title": "Fast API", "version": "0.1.0"},
"paths": {
"/items/{item_id}": {
"get": {
"responses": {
"200": {
"description": "Successful Response",
"content": {"application/json": {"schema": {}}},
},
"422": {
"description": "Validation Error",
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/HTTPValidationError"
}
}
},
},
},
"summary": "Read Item",
"operationId": "read_item_items__item_id__get",
"parameters": [
{
"required": True,
"schema": {"title": "Item_Id", "type": "integer"},
"name": "item_id",
"in": "path",
}
],
}
}
},
"components": {
"schemas": {
"ValidationError": {
"title": "ValidationError",
"required": ["loc", "msg", "type"],
"type": "object",
"properties": {
"loc": {
"title": "Location",
"type": "array",
"items": {"type": "string"},
},
"msg": {"title": "Message", "type": "string"},
"type": {"title": "Error Type", "type": "string"},
},
},
"HTTPValidationError": {
"title": "HTTPValidationError",
"type": "object",
"properties": {
"detail": {
"title": "Detail",
"type": "array",
"items": {"$ref": "#/components/schemas/ValidationError"},
}
},
},
}
},
}
def test_openapi_schema():
response = client.get("/openapi.json")
assert response.status_code == 200
assert response.json() == openapi_schema
def test_get_validation_error():
response = client.get("/items/foo")
assert response.status_code == 422
assert response.json() == {
"detail": [
{
"loc": ["path", "item_id"],
"msg": "value is not a valid integer",
"type": "type_error.integer",
}
]
}
def test_get_http_error():
response = client.get("/items/3")
assert response.status_code == 418
assert response.json() == {"detail": "Nope! I don't like 3."}
def test_get():
response = client.get("/items/2")
assert response.status_code == 200
assert response.json() == {"item_id": 2}

View File

View File

@@ -0,0 +1,91 @@
from starlette.testclient import TestClient
from path_params.tutorial004 import app
client = TestClient(app)
openapi_schema = {
"openapi": "3.0.2",
"info": {"title": "Fast API", "version": "0.1.0"},
"paths": {
"/files/{file_path}": {
"get": {
"responses": {
"200": {
"description": "Successful Response",
"content": {"application/json": {"schema": {}}},
},
"422": {
"description": "Validation Error",
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/HTTPValidationError"
}
}
},
},
},
"summary": "Read User Me",
"operationId": "read_user_me_files__file_path__get",
"parameters": [
{
"required": True,
"schema": {"title": "File_Path", "type": "string"},
"name": "file_path",
"in": "path",
}
],
}
}
},
"components": {
"schemas": {
"ValidationError": {
"title": "ValidationError",
"required": ["loc", "msg", "type"],
"type": "object",
"properties": {
"loc": {
"title": "Location",
"type": "array",
"items": {"type": "string"},
},
"msg": {"title": "Message", "type": "string"},
"type": {"title": "Error Type", "type": "string"},
},
},
"HTTPValidationError": {
"title": "HTTPValidationError",
"type": "object",
"properties": {
"detail": {
"title": "Detail",
"type": "array",
"items": {"$ref": "#/components/schemas/ValidationError"},
}
},
},
}
},
}
def test_openapi():
response = client.get("/openapi.json")
assert response.status_code == 200
assert response.json() == openapi_schema
def test_file_path():
response = client.get("/files/home/johndoe/myfile.txt")
print(response.content)
assert response.status_code == 200
assert response.json() == {"file_path": "home/johndoe/myfile.txt"}
def test_root_file_path():
response = client.get("/files//home/johndoe/myfile.txt")
print(response.content)
assert response.status_code == 200
assert response.json() == {"file_path": "/home/johndoe/myfile.txt"}

View File

@@ -0,0 +1,120 @@
import pytest
from starlette.testclient import TestClient
from path_params.tutorial005 import app
client = TestClient(app)
openapi_schema = {
"openapi": "3.0.2",
"info": {"title": "Fast API", "version": "0.1.0"},
"paths": {
"/model/{model_name}": {
"get": {
"responses": {
"200": {
"description": "Successful Response",
"content": {"application/json": {"schema": {}}},
},
"422": {
"description": "Validation Error",
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/HTTPValidationError"
}
}
},
},
},
"summary": "Get Model",
"operationId": "get_model_model__model_name__get",
"parameters": [
{
"required": True,
"schema": {
"title": "Model_Name",
"enum": ["alexnet", "resnet", "lenet"],
},
"name": "model_name",
"in": "path",
}
],
}
}
},
"components": {
"schemas": {
"ValidationError": {
"title": "ValidationError",
"required": ["loc", "msg", "type"],
"type": "object",
"properties": {
"loc": {
"title": "Location",
"type": "array",
"items": {"type": "string"},
},
"msg": {"title": "Message", "type": "string"},
"type": {"title": "Error Type", "type": "string"},
},
},
"HTTPValidationError": {
"title": "HTTPValidationError",
"type": "object",
"properties": {
"detail": {
"title": "Detail",
"type": "array",
"items": {"$ref": "#/components/schemas/ValidationError"},
}
},
},
}
},
}
def test_openapi():
response = client.get("/openapi.json")
assert response.status_code == 200
assert response.json() == openapi_schema
@pytest.mark.parametrize(
"url,status_code,expected",
[
(
"/model/alexnet",
200,
{"model_name": "alexnet", "message": "Deep Learning FTW!"},
),
(
"/model/lenet",
200,
{"model_name": "lenet", "message": "LeCNN all the images"},
),
(
"/model/resnet",
200,
{"model_name": "resnet", "message": "Have some residuals"},
),
(
"/model/foo",
422,
{
"detail": [
{
"loc": ["path", "model_name"],
"msg": "value is not a valid enumeration member",
"type": "type_error.enum",
}
]
},
),
],
)
def test_get_enums(url, status_code, expected):
response = client.get(url)
assert response.status_code == status_code
assert response.json() == expected

View File

@@ -0,0 +1,95 @@
from starlette.testclient import TestClient
from query_params.tutorial007 import app
client = TestClient(app)
openapi_schema = {
"openapi": "3.0.2",
"info": {"title": "Fast API", "version": "0.1.0"},
"paths": {
"/items/{item_id}": {
"get": {
"responses": {
"200": {
"description": "Successful Response",
"content": {"application/json": {"schema": {}}},
},
"422": {
"description": "Validation Error",
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/HTTPValidationError"
}
}
},
},
},
"summary": "Read User Item",
"operationId": "read_user_item_items__item_id__get",
"parameters": [
{
"required": True,
"schema": {"title": "Item_Id", "type": "string"},
"name": "item_id",
"in": "path",
},
{
"required": False,
"schema": {"title": "Limit", "type": "integer"},
"name": "limit",
"in": "query",
},
],
}
}
},
"components": {
"schemas": {
"ValidationError": {
"title": "ValidationError",
"required": ["loc", "msg", "type"],
"type": "object",
"properties": {
"loc": {
"title": "Location",
"type": "array",
"items": {"type": "string"},
},
"msg": {"title": "Message", "type": "string"},
"type": {"title": "Error Type", "type": "string"},
},
},
"HTTPValidationError": {
"title": "HTTPValidationError",
"type": "object",
"properties": {
"detail": {
"title": "Detail",
"type": "array",
"items": {"$ref": "#/components/schemas/ValidationError"},
}
},
},
}
},
}
def test_openapi():
response = client.get("/openapi.json")
assert response.status_code == 200
assert response.json() == openapi_schema
def test_read_item():
response = client.get("/items/foo")
assert response.status_code == 200
assert response.json() == {"item_id": "foo", "limit": None}
def test_read_item_query():
response = client.get("/items/foo?limit=5")
assert response.status_code == 200
assert response.json() == {"item_id": "foo", "limit": 5}

View File

@@ -86,3 +86,10 @@ def test_multi_query_values():
response = client.get(url)
assert response.status_code == 200
assert response.json() == {"q": ["foo", "bar"]}
def test_query_no_values():
url = "/items/"
response = client.get(url)
assert response.status_code == 200
assert response.json() == {"q": None}

View File

@@ -0,0 +1,96 @@
from starlette.testclient import TestClient
from query_params_str_validations.tutorial012 import app
client = TestClient(app)
openapi_schema = {
"openapi": "3.0.2",
"info": {"title": "Fast API", "version": "0.1.0"},
"paths": {
"/items/": {
"get": {
"responses": {
"200": {
"description": "Successful Response",
"content": {"application/json": {"schema": {}}},
},
"422": {
"description": "Validation Error",
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/HTTPValidationError"
}
}
},
},
},
"summary": "Read Items",
"operationId": "read_items_items__get",
"parameters": [
{
"required": False,
"schema": {
"title": "Q",
"type": "array",
"items": {"type": "string"},
"default": ["foo", "bar"],
},
"name": "q",
"in": "query",
}
],
}
}
},
"components": {
"schemas": {
"ValidationError": {
"title": "ValidationError",
"required": ["loc", "msg", "type"],
"type": "object",
"properties": {
"loc": {
"title": "Location",
"type": "array",
"items": {"type": "string"},
},
"msg": {"title": "Message", "type": "string"},
"type": {"title": "Error Type", "type": "string"},
},
},
"HTTPValidationError": {
"title": "HTTPValidationError",
"type": "object",
"properties": {
"detail": {
"title": "Detail",
"type": "array",
"items": {"$ref": "#/components/schemas/ValidationError"},
}
},
},
}
},
}
def test_openapi_schema():
response = client.get("/openapi.json")
assert response.status_code == 200
assert response.json() == openapi_schema
def test_default_query_values():
url = "/items/"
response = client.get(url)
assert response.status_code == 200
assert response.json() == {"q": ["foo", "bar"]}
def test_multi_query_values():
url = "/items/?q=baz&q=foobar"
response = client.get(url)
assert response.status_code == 200
assert response.json() == {"q": ["baz", "foobar"]}

View File

@@ -0,0 +1,91 @@
from starlette.testclient import TestClient
from query_params_str_validations.tutorial013 import app
client = TestClient(app)
openapi_schema = {
"openapi": "3.0.2",
"info": {"title": "Fast API", "version": "0.1.0"},
"paths": {
"/items/": {
"get": {
"responses": {
"200": {
"description": "Successful Response",
"content": {"application/json": {"schema": {}}},
},
"422": {
"description": "Validation Error",
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/HTTPValidationError"
}
}
},
},
},
"summary": "Read Items",
"operationId": "read_items_items__get",
"parameters": [
{
"required": False,
"schema": {"title": "Q", "type": "array", "items": {}},
"name": "q",
"in": "query",
}
],
}
}
},
"components": {
"schemas": {
"ValidationError": {
"title": "ValidationError",
"required": ["loc", "msg", "type"],
"type": "object",
"properties": {
"loc": {
"title": "Location",
"type": "array",
"items": {"type": "string"},
},
"msg": {"title": "Message", "type": "string"},
"type": {"title": "Error Type", "type": "string"},
},
},
"HTTPValidationError": {
"title": "HTTPValidationError",
"type": "object",
"properties": {
"detail": {
"title": "Detail",
"type": "array",
"items": {"$ref": "#/components/schemas/ValidationError"},
}
},
},
}
},
}
def test_openapi_schema():
response = client.get("/openapi.json")
assert response.status_code == 200
assert response.json() == openapi_schema
def test_multi_query_values():
url = "/items/?q=foo&q=bar"
response = client.get(url)
assert response.status_code == 200
assert response.json() == {"q": ["foo", "bar"]}
def test_query_no_values():
url = "/items/"
response = client.get(url)
assert response.status_code == 200
assert response.json() == {"q": None}

View File

@@ -0,0 +1,15 @@
from starlette.testclient import TestClient
from response_change_status_code.tutorial001 import app
client = TestClient(app)
def test_path_operation():
response = client.put("/get-or-create-task/foo")
print(response.content)
assert response.status_code == 200
assert response.json() == "Listen to the Bar Fighters"
response = client.put("/get-or-create-task/bar")
assert response.status_code == 201
assert response.json() == "This didn't exist before"

View File

@@ -0,0 +1,12 @@
from starlette.testclient import TestClient
from response_cookies.tutorial002 import app
client = TestClient(app)
def test_path_operation():
response = client.post("/cookie-and-object/")
assert response.status_code == 200
assert response.json() == {"message": "Come to the dark side, we have cookies"}
assert response.cookies["fakesession"] == "fake-cookie-session-value"

View File

@@ -0,0 +1,12 @@
from starlette.testclient import TestClient
from response_headers.tutorial002 import app
client = TestClient(app)
def test_path_operation():
response = client.get("/headers-and-object/")
assert response.status_code == 200
assert response.json() == {"message": "Hello World"}
assert response.headers["X-Cat-Dog"] == "alone in the world"

View File

@@ -0,0 +1,353 @@
from starlette.testclient import TestClient
from sql_databases.sql_app.main import app
client = TestClient(app)
openapi_schema = {
"openapi": "3.0.2",
"info": {"title": "Fast API", "version": "0.1.0"},
"paths": {
"/users/": {
"get": {
"responses": {
"200": {
"description": "Successful Response",
"content": {
"application/json": {
"schema": {
"title": "Response_Read_Users",
"type": "array",
"items": {"$ref": "#/components/schemas/User"},
}
}
},
},
"422": {
"description": "Validation Error",
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/HTTPValidationError"
}
}
},
},
},
"summary": "Read Users",
"operationId": "read_users_users__get",
"parameters": [
{
"required": False,
"schema": {"title": "Skip", "type": "integer", "default": 0},
"name": "skip",
"in": "query",
},
{
"required": False,
"schema": {"title": "Limit", "type": "integer", "default": 100},
"name": "limit",
"in": "query",
},
],
},
"post": {
"responses": {
"200": {
"description": "Successful Response",
"content": {
"application/json": {
"schema": {"$ref": "#/components/schemas/User"}
}
},
},
"422": {
"description": "Validation Error",
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/HTTPValidationError"
}
}
},
},
},
"summary": "Create User",
"operationId": "create_user_users__post",
"requestBody": {
"content": {
"application/json": {
"schema": {"$ref": "#/components/schemas/UserCreate"}
}
},
"required": True,
},
},
},
"/users/{user_id}": {
"get": {
"responses": {
"200": {
"description": "Successful Response",
"content": {
"application/json": {
"schema": {"$ref": "#/components/schemas/User"}
}
},
},
"422": {
"description": "Validation Error",
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/HTTPValidationError"
}
}
},
},
},
"summary": "Read User",
"operationId": "read_user_users__user_id__get",
"parameters": [
{
"required": True,
"schema": {"title": "User_Id", "type": "integer"},
"name": "user_id",
"in": "path",
}
],
}
},
"/users/{user_id}/items/": {
"post": {
"responses": {
"200": {
"description": "Successful Response",
"content": {
"application/json": {
"schema": {"$ref": "#/components/schemas/Item"}
}
},
},
"422": {
"description": "Validation Error",
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/HTTPValidationError"
}
}
},
},
},
"summary": "Create Item For User",
"operationId": "create_item_for_user_users__user_id__items__post",
"parameters": [
{
"required": True,
"schema": {"title": "User_Id", "type": "integer"},
"name": "user_id",
"in": "path",
}
],
"requestBody": {
"content": {
"application/json": {
"schema": {"$ref": "#/components/schemas/ItemCreate"}
}
},
"required": True,
},
}
},
"/items/": {
"get": {
"responses": {
"200": {
"description": "Successful Response",
"content": {
"application/json": {
"schema": {
"title": "Response_Read_Items",
"type": "array",
"items": {"$ref": "#/components/schemas/Item"},
}
}
},
},
"422": {
"description": "Validation Error",
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/HTTPValidationError"
}
}
},
},
},
"summary": "Read Items",
"operationId": "read_items_items__get",
"parameters": [
{
"required": False,
"schema": {"title": "Skip", "type": "integer", "default": 0},
"name": "skip",
"in": "query",
},
{
"required": False,
"schema": {"title": "Limit", "type": "integer", "default": 100},
"name": "limit",
"in": "query",
},
],
}
},
},
"components": {
"schemas": {
"ItemCreate": {
"title": "ItemCreate",
"required": ["title"],
"type": "object",
"properties": {
"title": {"title": "Title", "type": "string"},
"description": {"title": "Description", "type": "string"},
},
},
"Item": {
"title": "Item",
"required": ["title", "id", "owner_id"],
"type": "object",
"properties": {
"title": {"title": "Title", "type": "string"},
"description": {"title": "Description", "type": "string"},
"id": {"title": "Id", "type": "integer"},
"owner_id": {"title": "Owner_Id", "type": "integer"},
},
},
"User": {
"title": "User",
"required": ["email", "id", "is_active"],
"type": "object",
"properties": {
"email": {"title": "Email", "type": "string"},
"id": {"title": "Id", "type": "integer"},
"is_active": {"title": "Is_Active", "type": "boolean"},
"items": {
"title": "Items",
"type": "array",
"items": {"$ref": "#/components/schemas/Item"},
"default": [],
},
},
},
"UserCreate": {
"title": "UserCreate",
"required": ["email", "password"],
"type": "object",
"properties": {
"email": {"title": "Email", "type": "string"},
"password": {"title": "Password", "type": "string"},
},
},
"ValidationError": {
"title": "ValidationError",
"required": ["loc", "msg", "type"],
"type": "object",
"properties": {
"loc": {
"title": "Location",
"type": "array",
"items": {"type": "string"},
},
"msg": {"title": "Message", "type": "string"},
"type": {"title": "Error Type", "type": "string"},
},
},
"HTTPValidationError": {
"title": "HTTPValidationError",
"type": "object",
"properties": {
"detail": {
"title": "Detail",
"type": "array",
"items": {"$ref": "#/components/schemas/ValidationError"},
}
},
},
}
},
}
def test_openapi_schema():
response = client.get("/openapi.json")
assert response.status_code == 200
assert response.json() == openapi_schema
def test_create_user():
test_user = {"email": "johndoe@example.com", "password": "secret"}
response = client.post("/users/", json=test_user)
assert response.status_code == 200
data = response.json()
assert test_user["email"] == data["email"]
assert "id" in data
response = client.post("/users/", json=test_user)
assert response.status_code == 400
def test_get_user():
response = client.get("/users/1")
assert response.status_code == 200
data = response.json()
assert "email" in data
assert "id" in data
def test_inexistent_user():
response = client.get("/users/999")
assert response.status_code == 404
def test_get_users():
response = client.get("/users/")
assert response.status_code == 200
data = response.json()
assert "email" in data[0]
assert "id" in data[0]
def test_create_item():
item = {"title": "Foo", "description": "Something that fights"}
response = client.post("/users/1/items/", json=item)
assert response.status_code == 200
item_data = response.json()
assert item["title"] == item_data["title"]
assert item["description"] == item_data["description"]
assert "id" in item_data
assert "owner_id" in item_data
response = client.get("/users/1")
assert response.status_code == 200
user_data = response.json()
item_to_check = [it for it in user_data["items"] if it["id"] == item_data["id"]][0]
assert item_to_check["title"] == item["title"]
assert item_to_check["description"] == item["description"]
response = client.get("/users/1")
assert response.status_code == 200
user_data = response.json()
item_to_check = [it for it in user_data["items"] if it["id"] == item_data["id"]][0]
assert item_to_check["title"] == item["title"]
assert item_to_check["description"] == item["description"]
def test_read_items():
response = client.get("/items/")
assert response.status_code == 200
data = response.json()
assert data
first_item = data[0]
assert "title" in first_item
assert "description" in first_item

View File

View File

@@ -0,0 +1,56 @@
from dependency_testing.tutorial001 import (
app,
client,
test_override_in_items,
test_override_in_items_with_params,
test_override_in_items_with_q,
)
def test_override_in_items_run():
test_override_in_items()
def test_override_in_items_with_q_run():
test_override_in_items_with_q()
def test_override_in_items_with_params_run():
test_override_in_items_with_params()
def test_override_in_users():
response = client.get("/users/")
assert response.status_code == 200
assert response.json() == {
"message": "Hello Users!",
"params": {"q": None, "skip": 5, "limit": 10},
}
def test_override_in_users_with_q():
response = client.get("/users/?q=foo")
assert response.status_code == 200
assert response.json() == {
"message": "Hello Users!",
"params": {"q": "foo", "skip": 5, "limit": 10},
}
def test_override_in_users_with_params():
response = client.get("/users/?q=foo&skip=100&limit=200")
assert response.status_code == 200
assert response.json() == {
"message": "Hello Users!",
"params": {"q": "foo", "skip": 5, "limit": 10},
}
def test_normal_app():
app.dependency_overrides = None
response = client.get("/items/?q=foo&skip=100&limit=200")
assert response.status_code == 200
assert response.json() == {
"message": "Hello Items!",
"params": {"q": "foo", "skip": 100, "limit": 200},
}