Sync fastapi docs from 3e8d1526 on 2026-08-11

This commit is contained in:
The Librarian
2026-08-11 04:00:11 +00:00
parent d71a936809
commit 632909b5f6
199 changed files with 16315 additions and 1869 deletions
+6
View File
@@ -126,6 +126,12 @@ In diesem Beispiel werden Frontend-Pfade unter `/app` bereitgestellt.
Alle regulären *Pfadoperationen* in der App haben weiterhin Vorrang, auch in anderen Routern.
## Abhängigkeiten und Middleware { #dependencies-and-middleware }
Frontend-Responses laufen innerhalb der normalen **FastAPI**-Anwendung, daher gilt HTTP-Middleware für sie.
Abhängigkeiten aus der App, aus einem `APIRouter` und aus `include_router()` gelten ebenfalls für Frontend-Responses. Das kann nützlich sein, um ein Frontend mit Cookie-Authentifizierung oder Ähnlichem zu schützen.
## Nur statischer Build-Output { #static-build-output-only }
`app.frontend()` liefert Dateien aus, die bereits von Ihrem Frontend-Build generiert wurden.
+116 -155
View File
@@ -11,9 +11,6 @@ sponsors:
- login: coderabbitai
avatarUrl: https://avatars.githubusercontent.com/u/132028505?v=4
url: https://github.com/coderabbitai
- login: zuplo
avatarUrl: https://avatars.githubusercontent.com/u/85497839?v=4
url: https://github.com/zuplo
- login: blockbee-io
avatarUrl: https://avatars.githubusercontent.com/u/115143449?u=1b8620c2d6567c4df2111a371b85a51f448f9b85&v=4
url: https://github.com/blockbee-io
@@ -23,12 +20,12 @@ sponsors:
- login: railwayapp
avatarUrl: https://avatars.githubusercontent.com/u/66716858?v=4
url: https://github.com/railwayapp
- - login: speakeasy-api
avatarUrl: https://avatars.githubusercontent.com/u/91446104?v=4
url: https://github.com/speakeasy-api
- login: stainless-api
avatarUrl: https://avatars.githubusercontent.com/u/88061651?v=4
url: https://github.com/stainless-api
- - login: dribia
avatarUrl: https://avatars.githubusercontent.com/u/41189616?v=4
url: https://github.com/dribia
- login: BairesDev-LLC
avatarUrl: https://avatars.githubusercontent.com/u/133211198?u=c1462ade28fe251414bfedc28ce3f10242d44843&v=4
url: https://github.com/BairesDev-LLC
- login: svix
avatarUrl: https://avatars.githubusercontent.com/u/80175132?v=4
url: https://github.com/svix
@@ -38,19 +35,22 @@ sponsors:
- login: databento
avatarUrl: https://avatars.githubusercontent.com/u/64141749?v=4
url: https://github.com/databento
- login: tutorcruncher
avatarUrl: https://avatars.githubusercontent.com/u/3341959?v=4
url: https://github.com/tutorcruncher
- - login: LambdaTest-Inc
avatarUrl: https://avatars.githubusercontent.com/u/171592363?u=96606606a45fa170427206199014f2a5a2a4920b&v=4
avatarUrl: https://avatars.githubusercontent.com/u/171592363?u=080d9ba6069d0ff2a0558825ff2f667c45807687&v=4
url: https://github.com/LambdaTest-Inc
- login: Ponte-Energy-Partners
avatarUrl: https://avatars.githubusercontent.com/u/114745848?v=4
url: https://github.com/Ponte-Energy-Partners
- login: BoostryJP
avatarUrl: https://avatars.githubusercontent.com/u/57932412?v=4
url: https://github.com/BoostryJP
- login: acsone
avatarUrl: https://avatars.githubusercontent.com/u/7601056?v=4
url: https://github.com/acsone
- - login: scalar
- - login: manulife-ai
avatarUrl: https://avatars.githubusercontent.com/u/195145621?v=4
url: https://github.com/manulife-ai
- login: scalar
avatarUrl: https://avatars.githubusercontent.com/u/301879?v=4
url: https://github.com/scalar
- login: Trivie
@@ -62,9 +62,6 @@ sponsors:
- login: Doist
avatarUrl: https://avatars.githubusercontent.com/u/2565372?v=4
url: https://github.com/Doist
- - login: mainframeindustries
avatarUrl: https://avatars.githubusercontent.com/u/55092103?v=4
url: https://github.com/mainframeindustries
- - login: alixlahuec
avatarUrl: https://avatars.githubusercontent.com/u/29543316?u=44357eb2a93bccf30fb9d389b8befe94a3d00985&v=4
url: https://github.com/alixlahuec
@@ -77,9 +74,6 @@ sponsors:
- login: ChargeStorm
avatarUrl: https://avatars.githubusercontent.com/u/26000165?v=4
url: https://github.com/ChargeStorm
- login: ibrahimpelumi6142
avatarUrl: https://avatars.githubusercontent.com/u/113442282?v=4
url: https://github.com/ibrahimpelumi6142
- login: nilslindemann
avatarUrl: https://avatars.githubusercontent.com/u/6892179?u=1dca6a22195d6cd1ab20737c0e19a4c55d639472&v=4
url: https://github.com/nilslindemann
@@ -89,33 +83,30 @@ sponsors:
- login: otosky
avatarUrl: https://avatars.githubusercontent.com/u/42260747?u=69d089387c743d89427aa4ad8740cfb34045a9e0&v=4
url: https://github.com/otosky
- login: ramonalmeidam
avatarUrl: https://avatars.githubusercontent.com/u/45269580?u=3358750b3a5854d7c3ed77aaca7dd20a0f529d32&v=4
url: https://github.com/ramonalmeidam
- login: roboflow
avatarUrl: https://avatars.githubusercontent.com/u/53104118?v=4
url: https://github.com/roboflow
- login: dudikbender
avatarUrl: https://avatars.githubusercontent.com/u/53487583?u=3a57542938ebfd57579a0111db2b297e606d9681&v=4
url: https://github.com/dudikbender
- login: ehaca
avatarUrl: https://avatars.githubusercontent.com/u/25950317?u=cec1a3e0643b785288ae8260cc295a85ab344995&v=4
url: https://github.com/ehaca
- login: raphaellaude
avatarUrl: https://avatars.githubusercontent.com/u/28026311?u=91e1c00d9ac4f8045527e13de8050d504531cbc0&v=4
url: https://github.com/raphaellaude
- login: timlrx
avatarUrl: https://avatars.githubusercontent.com/u/28362229?u=9a745ca31372ee324af682715ae88ce8522f9094&v=4
url: https://github.com/timlrx
- login: Leay15
avatarUrl: https://avatars.githubusercontent.com/u/32212558?u=c4aa9c1737e515959382a5515381757b1fd86c53&v=4
url: https://github.com/Leay15
- login: timlrx
avatarUrl: https://avatars.githubusercontent.com/u/28362229?u=9a745ca31372ee324af682715ae88ce8522f9094&v=4
url: https://github.com/timlrx
- login: ehaca
avatarUrl: https://avatars.githubusercontent.com/u/25950317?u=cec1a3e0643b785288ae8260cc295a85ab344995&v=4
url: https://github.com/ehaca
- login: RaamEEIL
avatarUrl: https://avatars.githubusercontent.com/u/20320552?v=4
url: https://github.com/RaamEEIL
- login: ashi-agrawal
avatarUrl: https://avatars.githubusercontent.com/u/17105294?u=99c7a854035e5398d8e7b674f2d42baae6c957f8&v=4
url: https://github.com/ashi-agrawal
- login: mjohnsey
avatarUrl: https://avatars.githubusercontent.com/u/16784016?u=38fad2e6b411244560b3af99c5f5a4751bc81865&v=4
url: https://github.com/mjohnsey
- login: jugeeem
avatarUrl: https://avatars.githubusercontent.com/u/116043716?u=ae590d79c38ac79c91b9c5caa6887d061e865a3d&v=4
avatarUrl: https://avatars.githubusercontent.com/u/116043716?u=e4df530e99a086a1085f3dc125b94783670fb383&v=4
url: https://github.com/jugeeem
- login: Karine-Bauch
avatarUrl: https://avatars.githubusercontent.com/u/90465103?u=7feb1018abb1a5631cfd9a91fea723d1ceb5f49b&v=4
url: https://github.com/Karine-Bauch
- login: Charisn
avatarUrl: https://avatars.githubusercontent.com/u/100683386?u=5a57e569b443a58cb34a32b6cb6ea12c783e14c1&v=4
url: https://github.com/Charisn
- login: kaoru0310
avatarUrl: https://avatars.githubusercontent.com/u/80977929?u=1b61d10142b490e56af932ddf08a390fae8ee94f&v=4
url: https://github.com/kaoru0310
@@ -128,20 +119,17 @@ sponsors:
- login: anthonycepeda
avatarUrl: https://avatars.githubusercontent.com/u/72019805?u=60bdf46240cff8fca482ff0fc07d963fd5e1a27c&v=4
url: https://github.com/anthonycepeda
- login: AalbatrossGuy
avatarUrl: https://avatars.githubusercontent.com/u/68378354?u=0bdeea9356d24f638244131f6d8d1e2d2f3601ca&v=4
url: https://github.com/AalbatrossGuy
- login: patsatsia
avatarUrl: https://avatars.githubusercontent.com/u/61111267?u=3271b85f7a37b479c8d0ae0a235182e83c166edf&v=4
url: https://github.com/patsatsia
- login: oliverxchen
avatarUrl: https://avatars.githubusercontent.com/u/4471774?u=534191f25e32eeaadda22dfab4b0a428733d5489&v=4
url: https://github.com/oliverxchen
- login: jaredtrog
avatarUrl: https://avatars.githubusercontent.com/u/4381365?v=4
url: https://github.com/jaredtrog
- login: dudikbender
avatarUrl: https://avatars.githubusercontent.com/u/53487583?u=3a57542938ebfd57579a0111db2b297e606d9681&v=4
url: https://github.com/dudikbender
- login: roboflow
avatarUrl: https://avatars.githubusercontent.com/u/53104118?v=4
url: https://github.com/roboflow
- login: Ryandaydev
avatarUrl: https://avatars.githubusercontent.com/u/4292423?u=679ff84cb7b988c5795a5fa583857f574a055763&v=4
avatarUrl: https://avatars.githubusercontent.com/u/4292423?u=87b1afc7f4fff933779959270e2d168339e91402&v=4
url: https://github.com/Ryandaydev
- login: gorhack
avatarUrl: https://avatars.githubusercontent.com/u/4141690?u=ec119ebc4bdf00a7bc84657a71aa17834f4f27f3&v=4
@@ -149,9 +137,6 @@ sponsors:
- login: mj0331
avatarUrl: https://avatars.githubusercontent.com/u/3890353?u=1c627ac1a024515b4871de5c3ebbfaa1a57f65d4&v=4
url: https://github.com/mj0331
- login: anomaly
avatarUrl: https://avatars.githubusercontent.com/u/3654837?v=4
url: https://github.com/anomaly
- login: aacayaco
avatarUrl: https://avatars.githubusercontent.com/u/3634801?u=eaadda178c964178fcb64886f6c732172c8f8219&v=4
url: https://github.com/aacayaco
@@ -167,39 +152,24 @@ sponsors:
- login: knallgelb
avatarUrl: https://avatars.githubusercontent.com/u/2358812?u=c48cb6362b309d74cbf144bd6ad3aed3eb443e82&v=4
url: https://github.com/knallgelb
- login: keimos
avatarUrl: https://avatars.githubusercontent.com/u/1723255?u=fb87c72da55f72da6618aa94c8f3791ebab6b68a&v=4
url: https://github.com/keimos
- login: dodo5522
avatarUrl: https://avatars.githubusercontent.com/u/1362607?u=9bf1e0e520cccc547c046610c468ce6115bbcf9f&v=4
url: https://github.com/dodo5522
- login: mintuhouse
avatarUrl: https://avatars.githubusercontent.com/u/769950?u=ecfbd79a97d33177e0d093ddb088283cf7fe8444&v=4
url: https://github.com/mintuhouse
- login: falkben
avatarUrl: https://avatars.githubusercontent.com/u/653031?u=ad9838e089058c9e5a0bab94c0eec7cc181e0cd0&v=4
url: https://github.com/falkben
- login: netsatan
avatarUrl: https://avatars.githubusercontent.com/u/955557?u=cb8fc0ae7f7b06807f0a58e335b1af96c9da0344&v=4
url: https://github.com/netsatan
- login: koxudaxi
avatarUrl: https://avatars.githubusercontent.com/u/630670?u=507d8577b4b3670546b449c4c2ccbc5af40d72f7&v=4
url: https://github.com/koxudaxi
- login: wshayes
avatarUrl: https://avatars.githubusercontent.com/u/365303?u=07ca03c5ee811eb0920e633cc3c3db73dbec1aa5&v=4
url: https://github.com/wshayes
- login: pamelafox
avatarUrl: https://avatars.githubusercontent.com/u/297042?v=4
url: https://github.com/pamelafox
- login: robintw
avatarUrl: https://avatars.githubusercontent.com/u/296686?v=4
url: https://github.com/robintw
- login: jstanden
avatarUrl: https://avatars.githubusercontent.com/u/63288?u=c3658d57d2862c607a0e19c2101c3c51876e36ad&v=4
url: https://github.com/jstanden
- login: RaamEEIL
avatarUrl: https://avatars.githubusercontent.com/u/20320552?v=4
url: https://github.com/RaamEEIL
- login: ashi-agrawal
avatarUrl: https://avatars.githubusercontent.com/u/17105294?u=99c7a854035e5398d8e7b674f2d42baae6c957f8&v=4
url: https://github.com/ashi-agrawal
- login: mjohnsey
avatarUrl: https://avatars.githubusercontent.com/u/16784016?u=38fad2e6b411244560b3af99c5f5a4751bc81865&v=4
url: https://github.com/mjohnsey
- login: khadrawy
avatarUrl: https://avatars.githubusercontent.com/u/13686061?u=59f25ef42ecf04c22657aac4238ce0e2d3d30304&v=4
url: https://github.com/khadrawy
@@ -221,63 +191,63 @@ sponsors:
- login: FernandoCelmer
avatarUrl: https://avatars.githubusercontent.com/u/6262214?u=58ba6d5888fa7f355934e52db19f950e20b38162&v=4
url: https://github.com/FernandoCelmer
- login: geodata-no
avatarUrl: https://avatars.githubusercontent.com/u/5946299?v=4
url: https://github.com/geodata-no
- login: eseglem
avatarUrl: https://avatars.githubusercontent.com/u/5920492?u=208d419cf667b8ac594c82a8db01932c7e50d057&v=4
url: https://github.com/eseglem
- login: ternaus
avatarUrl: https://avatars.githubusercontent.com/u/5481618?u=513a26b02a39e7a28d587cd37c6cc877ea368e6e&v=4
url: https://github.com/ternaus
- - login: Artur-Galstyan
avatarUrl: https://avatars.githubusercontent.com/u/63471891?u=e8691f386037e51a737cc0ba866cd8c89e5cf109&v=4
url: https://github.com/Artur-Galstyan
- login: manoelpqueiroz
- login: jaredtrog
avatarUrl: https://avatars.githubusercontent.com/u/4381365?v=4
url: https://github.com/jaredtrog
- - login: jpfyoder
avatarUrl: https://avatars.githubusercontent.com/u/7548821?u=1683290ed65dae6987d673da044067577ee71521&v=4
url: https://github.com/jpfyoder
- - login: manoelpqueiroz
avatarUrl: https://avatars.githubusercontent.com/u/23669137?u=b12e84b28a84369ab5b30bd5a79e5788df5a0756&v=4
url: https://github.com/manoelpqueiroz
- login: Artur-Galstyan
avatarUrl: https://avatars.githubusercontent.com/u/63471891?u=e8691f386037e51a737cc0ba866cd8c89e5cf109&v=4
url: https://github.com/Artur-Galstyan
- - login: pawamoy
avatarUrl: https://avatars.githubusercontent.com/u/3999221?u=b030e4c89df2f3a36bc4710b925bdeb6745c9856&v=4
url: https://github.com/pawamoy
- login: siavashyj
avatarUrl: https://avatars.githubusercontent.com/u/43583410?u=562005ddc7901cd27a1219a118a2363817b14977&v=4
url: https://github.com/siavashyj
- login: caviri
avatarUrl: https://avatars.githubusercontent.com/u/45425937?u=cab1bb03a0326fe45b2363866b1d78c9bc8055d8&v=4
url: https://github.com/caviri
- login: mobyw
avatarUrl: https://avatars.githubusercontent.com/u/44370805?v=4
url: https://github.com/mobyw
- login: ArtyomVancyan
avatarUrl: https://avatars.githubusercontent.com/u/44609997?v=4
url: https://github.com/ArtyomVancyan
- login: caviri
avatarUrl: https://avatars.githubusercontent.com/u/45425937?u=5f3d66ea5edea94c028c51ebf1c0f3b37e6c3db5&v=4
url: https://github.com/caviri
- login: hgalytoby
avatarUrl: https://avatars.githubusercontent.com/u/50397689?u=6cc9028f3db63f8f60ad21c17b1ce4b88c4e2e60&v=4
url: https://github.com/hgalytoby
- login: johnl28
avatarUrl: https://avatars.githubusercontent.com/u/54412955?u=47dd06082d1c39caa90c752eb55566e4f3813957&v=4
url: https://github.com/johnl28
- login: danielunderwood
avatarUrl: https://avatars.githubusercontent.com/u/4472301?v=4
url: https://github.com/danielunderwood
- login: hoenie-ams
avatarUrl: https://avatars.githubusercontent.com/u/25708487?u=cda07434f0509ac728d9edf5e681117c0f6b818b&v=4
url: https://github.com/hoenie-ams
- login: joerambo
avatarUrl: https://avatars.githubusercontent.com/u/26282974?v=4
url: https://github.com/joerambo
- login: engineerjoe440
avatarUrl: https://avatars.githubusercontent.com/u/33275230?u=eb223cad27017bb1e936ee9b429b450d092d0236&v=4
url: https://github.com/engineerjoe440
- login: bnkc
avatarUrl: https://avatars.githubusercontent.com/u/34930566?u=4771ac4e64066f0847d40e5b29910adabd9b2372&v=4
url: https://github.com/bnkc
- login: siavashyj
avatarUrl: https://avatars.githubusercontent.com/u/43583410?u=562005ddc7901cd27a1219a118a2363817b14977&v=4
url: https://github.com/siavashyj
- login: petercool
avatarUrl: https://avatars.githubusercontent.com/u/37613029?u=75aa8c6729e6e8f85a300561c4dbeef9d65c8797&v=4
url: https://github.com/petercool
- login: PelicanQ
avatarUrl: https://avatars.githubusercontent.com/u/77930606?v=4
url: https://github.com/PelicanQ
- login: PunRabbit
avatarUrl: https://avatars.githubusercontent.com/u/70463212?u=1a835cfbc99295a60c8282f6aa6199d1b42241a5&v=4
url: https://github.com/PunRabbit
- login: bnkc
avatarUrl: https://avatars.githubusercontent.com/u/34930566?u=888af82706afa36727feebce0e62225905926131&v=4
url: https://github.com/bnkc
- login: joerambo
avatarUrl: https://avatars.githubusercontent.com/u/26282974?v=4
url: https://github.com/joerambo
- login: hoenie-ams
avatarUrl: https://avatars.githubusercontent.com/u/25708487?u=cda07434f0509ac728d9edf5e681117c0f6b818b&v=4
url: https://github.com/hoenie-ams
- login: nisutec
avatarUrl: https://avatars.githubusercontent.com/u/25281462?u=e562484c451fdfc59053163f64405f8eb262b8b0&v=4
url: https://github.com/nisutec
- login: joshuatz
avatarUrl: https://avatars.githubusercontent.com/u/17817563?u=f1bf05b690d1fc164218f0b420cdd3acb7913e21&v=4
url: https://github.com/joshuatz
- login: hgalytoby
avatarUrl: https://avatars.githubusercontent.com/u/50397689?u=6cc9028f3db63f8f60ad21c17b1ce4b88c4e2e60&v=4
url: https://github.com/hgalytoby
- login: TheR1D
avatarUrl: https://avatars.githubusercontent.com/u/16740832?u=b0dfdbdb27b79729430c71c6128962f77b7b53f7&v=4
url: https://github.com/TheR1D
- login: my3
avatarUrl: https://avatars.githubusercontent.com/u/1825270?v=4
url: https://github.com/my3
@@ -290,6 +260,9 @@ sponsors:
- login: tochikuji
avatarUrl: https://avatars.githubusercontent.com/u/851759?v=4
url: https://github.com/tochikuji
- login: falkben
avatarUrl: https://avatars.githubusercontent.com/u/653031?u=ad9838e089058c9e5a0bab94c0eec7cc181e0cd0&v=4
url: https://github.com/falkben
- login: ceb10n
avatarUrl: https://avatars.githubusercontent.com/u/235213?u=edcce471814a1eba9f0cdaa4cd0de18921a940a6&v=4
url: https://github.com/ceb10n
@@ -302,24 +275,9 @@ sponsors:
- login: ddanier
avatarUrl: https://avatars.githubusercontent.com/u/113563?u=ed1dc79de72f93bd78581f88ebc6952b62f472da&v=4
url: https://github.com/ddanier
- login: nisutec
avatarUrl: https://avatars.githubusercontent.com/u/25281462?u=e562484c451fdfc59053163f64405f8eb262b8b0&v=4
url: https://github.com/nisutec
- login: joshuatz
avatarUrl: https://avatars.githubusercontent.com/u/17817563?u=f1bf05b690d1fc164218f0b420cdd3acb7913e21&v=4
url: https://github.com/joshuatz
- login: TheR1D
avatarUrl: https://avatars.githubusercontent.com/u/16740832?u=b0dfdbdb27b79729430c71c6128962f77b7b53f7&v=4
url: https://github.com/TheR1D
- login: Zuzah
avatarUrl: https://avatars.githubusercontent.com/u/10934846?u=1ef43e075ddc87bd1178372bf4d95ee6175cae27&v=4
url: https://github.com/Zuzah
- login: mntolia
avatarUrl: https://avatars.githubusercontent.com/u/10390224?v=4
url: https://github.com/mntolia
- login: hard-coders
avatarUrl: https://avatars.githubusercontent.com/u/9651103?u=78d12d1acdf853c817700145e73de7fd9e5d068b&v=4
url: https://github.com/hard-coders
- login: DMantis
avatarUrl: https://avatars.githubusercontent.com/u/9536869?u=652dd0d49717803c0cbcbf44f7740e53cf2d4892&v=4
url: https://github.com/DMantis
@@ -332,9 +290,6 @@ sponsors:
- login: harsh183
avatarUrl: https://avatars.githubusercontent.com/u/7780198?v=4
url: https://github.com/harsh183
- login: katnoria
avatarUrl: https://avatars.githubusercontent.com/u/7674948?u=09767eb13e07e09496c5fee4e5ce21d9eac34a56&v=4
url: https://github.com/katnoria
- login: KentShikama
avatarUrl: https://avatars.githubusercontent.com/u/6329898?u=8b236810db9b96333230430837e1f021f9246da1&v=4
url: https://github.com/KentShikama
@@ -347,42 +302,48 @@ sponsors:
- login: rangulvers
avatarUrl: https://avatars.githubusercontent.com/u/5235430?u=e254d4af4ace5a05fa58372ae677c7d26f0d5a53&v=4
url: https://github.com/rangulvers
- - login: KOZ39
avatarUrl: https://avatars.githubusercontent.com/u/38822500?u=9dfc0a697df1c9628f08e20dc3fb17b1afc4e5a7&v=4
url: https://github.com/KOZ39
- login: danielunderwood
avatarUrl: https://avatars.githubusercontent.com/u/4472301?v=4
url: https://github.com/danielunderwood
- - login: ArtyomVancyan
avatarUrl: https://avatars.githubusercontent.com/u/44609997?v=4
url: https://github.com/ArtyomVancyan
- login: rwxd
avatarUrl: https://avatars.githubusercontent.com/u/40308458?u=cd04a39e3655923be4f25c2ba8a5a07b3da3230a&v=4
url: https://github.com/rwxd
- login: morzan1001
avatarUrl: https://avatars.githubusercontent.com/u/47593005?u=c30ab7230f82a12a9b938dcb54f84a996931409a&v=4
url: https://github.com/morzan1001
- login: Olegt0rr
avatarUrl: https://avatars.githubusercontent.com/u/25399456?u=3e87b5239a2f4600975ba13be73054f8567c6060&v=4
url: https://github.com/Olegt0rr
- login: larsyngvelundin
avatarUrl: https://avatars.githubusercontent.com/u/34173819?u=74958599695bf83ac9f1addd935a51548a10c6b0&v=4
url: https://github.com/larsyngvelundin
- login: KOZ39
avatarUrl: https://avatars.githubusercontent.com/u/38822500?u=9dfc0a697df1c9628f08e20dc3fb17b1afc4e5a7&v=4
url: https://github.com/KOZ39
- login: andrecorumba
avatarUrl: https://avatars.githubusercontent.com/u/37807517?u=9b9be3b41da9bda60957da9ef37b50dbf65baa61&v=4
url: https://github.com/andrecorumba
- login: CoderDeltaLAN
avatarUrl: https://avatars.githubusercontent.com/u/152043745?u=4ff541efffb7d134e60c5fcf2dd1e343f90bb782&v=4
url: https://github.com/CoderDeltaLAN
- login: hippoley
avatarUrl: https://avatars.githubusercontent.com/u/135493401?u=1164ef48a645a7c12664fabc1638fbb7e1c459b0&v=4
url: https://github.com/hippoley
- login: nayasinghania
avatarUrl: https://avatars.githubusercontent.com/u/74111380?u=752e99a5e139389fdc0a0677122adc08438eb076&v=4
url: https://github.com/nayasinghania
- login: Olegt0rr
avatarUrl: https://avatars.githubusercontent.com/u/25399456?u=3e87b5239a2f4600975ba13be73054f8567c6060&v=4
url: https://github.com/Olegt0rr
- login: diogotoporcov
avatarUrl: https://avatars.githubusercontent.com/u/207575398?u=1fa7cf41b4181faa4d27f38bc37a374c17b5163b&v=4
url: https://github.com/diogotoporcov
- login: onestn
avatarUrl: https://avatars.githubusercontent.com/u/62360849?u=746dd21c34e7e06eefb11b03e8bb01aaae3c2a4f&v=4
url: https://github.com/onestn
- login: mohammadi-hadi
avatarUrl: https://avatars.githubusercontent.com/u/50410241?u=1137b5ff9ea8585c0192fe9ddb4ae5e21bc3d2e8&v=4
url: https://github.com/mohammadi-hadi
- login: morzan1001
avatarUrl: https://avatars.githubusercontent.com/u/47593005?u=c30ab7230f82a12a9b938dcb54f84a996931409a&v=4
url: https://github.com/morzan1001
- login: Toothwitch
avatarUrl: https://avatars.githubusercontent.com/u/1710406?u=5eebb23b46cd26e48643b9e5179536cad491c17a&v=4
url: https://github.com/Toothwitch
- login: andreagrandi
avatarUrl: https://avatars.githubusercontent.com/u/636391?u=13d90cb8ec313593a5b71fbd4e33b78d6da736f5&v=4
url: https://github.com/andreagrandi
- login: 0xsummerday
avatarUrl: https://avatars.githubusercontent.com/u/13888940?u=d0d45d5e2d7efd880a32d030fb222a51406c986f&v=4
url: https://github.com/0xsummerday
- login: DaxServer
avatarUrl: https://avatars.githubusercontent.com/u/7479937?u=cf2f97f958e47b209679d6aa2ad8723ef0d1cd0f&v=4
url: https://github.com/DaxServer
- login: msserpa
avatarUrl: https://avatars.githubusercontent.com/u/6334934?u=82c4489eb1559d88d2990d60001901b14f722bbb&v=4
url: https://github.com/msserpa
+9 -9
View File
@@ -2,21 +2,21 @@ members:
- login: tiangolo
avatar_url: https://avatars.githubusercontent.com/u/1326112
url: https://github.com/tiangolo
- login: Kludex
avatar_url: https://avatars.githubusercontent.com/u/7353520
url: https://github.com/Kludex
- login: alejsdev
avatar_url: https://avatars.githubusercontent.com/u/90076947
url: https://github.com/alejsdev
- login: svlandeg
avatar_url: https://avatars.githubusercontent.com/u/8796347
url: https://github.com/svlandeg
- login: YuriiMotov
avatar_url: https://avatars.githubusercontent.com/u/109919500
url: https://github.com/YuriiMotov
- login: svlandeg
avatar_url: https://avatars.githubusercontent.com/u/8796347
url: https://github.com/svlandeg
- login: alejsdev
avatar_url: https://avatars.githubusercontent.com/u/90076947
url: https://github.com/alejsdev
- login: patrick91
avatar_url: https://avatars.githubusercontent.com/u/667029
url: https://github.com/patrick91
- login: luzzodev
avatar_url: https://avatars.githubusercontent.com/u/27291415
url: https://github.com/luzzodev
- login: Kludex
avatar_url: https://avatars.githubusercontent.com/u/7353520
url: https://github.com/Kludex
+1
View File
@@ -1,3 +1,4 @@
users:
- tiangolo
- codecov
- github-actions
+1 -1
View File
@@ -61,6 +61,6 @@ bronze:
# - url: https://testdriven.io/courses/tdd-fastapi/
# title: Learn to build high-quality web apps with best practices
# img: /img/sponsors/testdriven.svg
- url: https://www.testmu.ai/?utm_source=fastapi&utm_medium=partner&utm_campaign=sponsor&utm_term=opensource&utm_content=webpage
- url: https://www.testmuai.com/?utm_source=fastapi&utm_medium=partner&utm_campaign=sponsor&utm_term=opensource&utm_content=webpage
title: TestMu AI. The Native AI-Agentic Cloud Platform to Supercharge Quality Engineering.
img: /img/sponsors/testmu.png
+205 -204
View File
@@ -1,203 +1,214 @@
repos:
- name: headroom
html_url: https://github.com/headroomlabs-ai/headroom
stars: 55017
stars: 65565
owner_login: headroomlabs-ai
owner_html_url: https://github.com/headroomlabs-ai
- name: full-stack-fastapi-template
html_url: https://github.com/fastapi/full-stack-fastapi-template
stars: 43994
stars: 44681
owner_login: fastapi
owner_html_url: https://github.com/fastapi
- name: Hello-Python
html_url: https://github.com/mouredev/Hello-Python
stars: 36226
stars: 36837
owner_login: mouredev
owner_html_url: https://github.com/mouredev
- name: serve
html_url: https://github.com/jina-ai/serve
stars: 21862
stars: 21863
owner_login: jina-ai
owner_html_url: https://github.com/jina-ai
- name: HivisionIDPhotos
html_url: https://github.com/Zeyi-Lin/HivisionIDPhotos
stars: 21212
stars: 21351
owner_login: Zeyi-Lin
owner_html_url: https://github.com/Zeyi-Lin
- name: Douyin_TikTok_Download_API
html_url: https://github.com/Evil0ctal/Douyin_TikTok_Download_API
stars: 18599
stars: 19234
owner_login: Evil0ctal
owner_html_url: https://github.com/Evil0ctal
- name: sqlmodel
html_url: https://github.com/fastapi/sqlmodel
stars: 18156
stars: 18254
owner_login: fastapi
owner_html_url: https://github.com/fastapi
- name: fastapi-best-practices
html_url: https://github.com/zhanymkanov/fastapi-best-practices
stars: 17608
stars: 17860
owner_login: zhanymkanov
owner_html_url: https://github.com/zhanymkanov
- name: SurfSense
html_url: https://github.com/MODSetter/SurfSense
stars: 15161
stars: 15831
owner_login: MODSetter
owner_html_url: https://github.com/MODSetter
- name: machine-learning-zoomcamp
html_url: https://github.com/DataTalksClub/machine-learning-zoomcamp
stars: 13445
stars: 13871
owner_login: DataTalksClub
owner_html_url: https://github.com/DataTalksClub
- name: XHS-Downloader
html_url: https://github.com/JoeanAmier/XHS-Downloader
stars: 12279
owner_login: JoeanAmier
owner_html_url: https://github.com/JoeanAmier
- name: peewee
html_url: https://github.com/coleifer/peewee
stars: 11976
stars: 11980
owner_login: coleifer
owner_html_url: https://github.com/coleifer
- name: fastapi_mcp
html_url: https://github.com/tadata-org/fastapi_mcp
stars: 11932
stars: 11977
owner_login: tadata-org
owner_html_url: https://github.com/tadata-org
- name: XHS-Downloader
html_url: https://github.com/JoeanAmier/XHS-Downloader
stars: 11768
owner_login: JoeanAmier
owner_html_url: https://github.com/JoeanAmier
- name: awesome-fastapi
html_url: https://github.com/mjhea0/awesome-fastapi
stars: 11478
stars: 11583
owner_login: mjhea0
owner_html_url: https://github.com/mjhea0
- name: polar
html_url: https://github.com/polarsource/polar
stars: 9999
stars: 10174
owner_login: polarsource
owner_html_url: https://github.com/polarsource
- name: pycaret
html_url: https://github.com/pycaret/pycaret
stars: 9818
stars: 9835
owner_login: pycaret
owner_html_url: https://github.com/pycaret
- name: FastUI
html_url: https://github.com/pydantic/FastUI
stars: 8970
stars: 8964
owner_login: pydantic
owner_html_url: https://github.com/pydantic
- name: FileCodeBox
html_url: https://github.com/vastsa/FileCodeBox
stars: 8376
stars: 8452
owner_login: vastsa
owner_html_url: https://github.com/vastsa
- name: nonebot2
html_url: https://github.com/nonebot/nonebot2
stars: 7593
owner_login: nonebot
owner_html_url: https://github.com/nonebot
- name: hatchet
html_url: https://github.com/hatchet-dev/hatchet
stars: 7441
stars: 7688
owner_login: hatchet-dev
owner_html_url: https://github.com/hatchet-dev
- name: fastapi-users
html_url: https://github.com/fastapi-users/fastapi-users
stars: 6182
owner_login: fastapi-users
owner_html_url: https://github.com/fastapi-users
- name: Yuxi
html_url: https://github.com/xerrors/Yuxi
stars: 5926
owner_login: xerrors
owner_html_url: https://github.com/xerrors
- name: serge
html_url: https://github.com/serge-chat/serge
stars: 5723
owner_login: serge-chat
owner_html_url: https://github.com/serge-chat
- name: nonebot2
html_url: https://github.com/nonebot/nonebot2
stars: 7657
owner_login: nonebot
owner_html_url: https://github.com/nonebot
- name: honcho
html_url: https://github.com/plastic-labs/honcho
stars: 5680
stars: 6533
owner_login: plastic-labs
owner_html_url: https://github.com/plastic-labs
- name: Yuxi
html_url: https://github.com/xerrors/Yuxi
stars: 6415
owner_login: xerrors
owner_html_url: https://github.com/xerrors
- name: fastapi-users
html_url: https://github.com/fastapi-users/fastapi-users
stars: 6212
owner_login: fastapi-users
owner_html_url: https://github.com/fastapi-users
- name: serge
html_url: https://github.com/serge-chat/serge
stars: 5716
owner_login: serge-chat
owner_html_url: https://github.com/serge-chat
- name: Kokoro-FastAPI
html_url: https://github.com/remsky/Kokoro-FastAPI
stars: 5085
stars: 5304
owner_login: remsky
owner_html_url: https://github.com/remsky
- name: YouDub-webui
html_url: https://github.com/liuzhao1225/YouDub-webui
stars: 5256
owner_login: liuzhao1225
owner_html_url: https://github.com/liuzhao1225
- name: devpush
html_url: https://github.com/hunvreus/devpush
stars: 4693
stars: 4739
owner_login: hunvreus
owner_html_url: https://github.com/hunvreus
- name: strawberry
html_url: https://github.com/strawberry-graphql/strawberry
stars: 4677
stars: 4702
owner_login: strawberry-graphql
owner_html_url: https://github.com/strawberry-graphql
- name: poem
html_url: https://github.com/poem-web/poem
stars: 4415
stars: 4430
owner_login: poem-web
owner_html_url: https://github.com/poem-web
- name: logfire
html_url: https://github.com/pydantic/logfire
stars: 4340
stars: 4416
owner_login: pydantic
owner_html_url: https://github.com/pydantic
- name: dynaconf
html_url: https://github.com/dynaconf/dynaconf
stars: 4310
stars: 4320
owner_login: dynaconf
owner_html_url: https://github.com/dynaconf
- name: chatgpt-web-share
html_url: https://github.com/chatpire/chatgpt-web-share
stars: 4269
owner_login: chatpire
owner_html_url: https://github.com/chatpire
- name: huma
html_url: https://github.com/danielgtaylor/huma
stars: 4203
stars: 4302
owner_login: danielgtaylor
owner_html_url: https://github.com/danielgtaylor
- name: atrilabs-engine
html_url: https://github.com/Atri-Labs/atrilabs-engine
stars: 4071
owner_login: Atri-Labs
owner_html_url: https://github.com/Atri-Labs
- name: mcp-context-forge
html_url: https://github.com/IBM/mcp-context-forge
stars: 3989
stars: 4286
owner_login: IBM
owner_html_url: https://github.com/IBM
- name: chatgpt-web-share
html_url: https://github.com/chatpire/chatgpt-web-share
stars: 4273
owner_login: chatpire
owner_html_url: https://github.com/chatpire
- name: atrilabs-engine
html_url: https://github.com/Atri-Labs/atrilabs-engine
stars: 4068
owner_login: Atri-Labs
owner_html_url: https://github.com/Atri-Labs
- name: datamodel-code-generator
html_url: https://github.com/koxudaxi/datamodel-code-generator
stars: 3952
stars: 4000
owner_login: koxudaxi
owner_html_url: https://github.com/koxudaxi
- name: LitServe
html_url: https://github.com/Lightning-AI/LitServe
stars: 3901
stars: 3923
owner_login: Lightning-AI
owner_html_url: https://github.com/Lightning-AI
- name: fastapi-admin
html_url: https://github.com/fastapi-admin/fastapi-admin
stars: 3799
stars: 3810
owner_login: fastapi-admin
owner_html_url: https://github.com/fastapi-admin
- name: tracecat
html_url: https://github.com/TracecatHQ/tracecat
stars: 3703
stars: 3761
owner_login: TracecatHQ
owner_html_url: https://github.com/TracecatHQ
- name: farfalle
html_url: https://github.com/rashadphz/farfalle
stars: 3535
stars: 3539
owner_login: rashadphz
owner_html_url: https://github.com/rashadphz
- name: Rapid-MLX
html_url: https://github.com/raullenchai/Rapid-MLX
stars: 3155
stars: 3423
owner_login: raullenchai
owner_html_url: https://github.com/raullenchai
- name: dramaclaw
html_url: https://github.com/dramaclaw/dramaclaw
stars: 3373
owner_login: dramaclaw
owner_html_url: https://github.com/dramaclaw
- name: opyrator
html_url: https://github.com/ml-tooling/opyrator
stars: 3133
@@ -205,162 +216,172 @@
owner_html_url: https://github.com/ml-tooling
- name: docarray
html_url: https://github.com/docarray/docarray
stars: 3121
stars: 3123
owner_login: docarray
owner_html_url: https://github.com/docarray
- name: any-auto-register
html_url: https://github.com/lxf746/any-auto-register
stars: 3111
owner_login: lxf746
owner_html_url: https://github.com/lxf746
- name: fastapi-realworld-example-app
html_url: https://github.com/nsidnev/fastapi-realworld-example-app
stars: 3109
stars: 3108
owner_login: nsidnev
owner_html_url: https://github.com/nsidnev
- name: uvicorn-gunicorn-fastapi-docker
html_url: https://github.com/tiangolo/uvicorn-gunicorn-fastapi-docker
stars: 2914
stars: 2915
owner_login: tiangolo
owner_html_url: https://github.com/tiangolo
- name: any-auto-register
html_url: https://github.com/lxf746/any-auto-register
stars: 2832
owner_login: lxf746
owner_html_url: https://github.com/lxf746
- name: FastAPI-template
html_url: https://github.com/s3rius/FastAPI-template
stars: 2810
stars: 2815
owner_login: s3rius
owner_html_url: https://github.com/s3rius
- name: YC-Killer
html_url: https://github.com/sahibzada-allahyar/YC-Killer
stars: 2779
owner_login: sahibzada-allahyar
owner_html_url: https://github.com/sahibzada-allahyar
- name: sqladmin
html_url: https://github.com/smithyhq/sqladmin
stars: 2759
stars: 2808
owner_login: smithyhq
owner_html_url: https://github.com/smithyhq
- name: YC-Killer
html_url: https://github.com/sahibzada-allahyar/YC-Killer
stars: 2792
owner_login: sahibzada-allahyar
owner_html_url: https://github.com/sahibzada-allahyar
- name: best-of-web-python
html_url: https://github.com/ml-tooling/best-of-web-python
stars: 2731
stars: 2750
owner_login: ml-tooling
owner_html_url: https://github.com/ml-tooling
- name: NoteDiscovery
html_url: https://github.com/gamosoft/NoteDiscovery
stars: 2595
stars: 2737
owner_login: gamosoft
owner_html_url: https://github.com/gamosoft
- name: tickflow-stock-panel
html_url: https://github.com/shy3130/tickflow-stock-panel
stars: 2684
owner_login: shy3130
owner_html_url: https://github.com/shy3130
- name: codex-lb
html_url: https://github.com/Soju06/codex-lb
stars: 2641
owner_login: Soju06
owner_html_url: https://github.com/Soju06
- name: fastapi-react
html_url: https://github.com/Buuntu/fastapi-react
stars: 2588
stars: 2583
owner_login: Buuntu
owner_html_url: https://github.com/Buuntu
- name: supabase-py
html_url: https://github.com/supabase/supabase-py
stars: 2530
owner_login: supabase
owner_html_url: https://github.com/supabase
- name: 30-Days-of-Python
html_url: https://github.com/codingforentrepreneurs/30-Days-of-Python
stars: 2483
owner_login: codingforentrepreneurs
owner_html_url: https://github.com/codingforentrepreneurs
- name: RasaGPT
html_url: https://github.com/paulpierre/RasaGPT
stars: 2462
owner_login: paulpierre
owner_html_url: https://github.com/paulpierre
- name: fastapi-langgraph-agent-production-ready-template
html_url: https://github.com/wassim249/fastapi-langgraph-agent-production-ready-template
stars: 2456
stars: 2568
owner_login: wassim249
owner_html_url: https://github.com/wassim249
- name: supabase-py
html_url: https://github.com/supabase/supabase-py
stars: 2555
owner_login: supabase
owner_html_url: https://github.com/supabase
- name: fastapi-best-architecture
html_url: https://github.com/fastapi-practices/fastapi-best-architecture
stars: 2505
owner_login: fastapi-practices
owner_html_url: https://github.com/fastapi-practices
- name: 30-Days-of-Python
html_url: https://github.com/codingforentrepreneurs/30-Days-of-Python
stars: 2501
owner_login: codingforentrepreneurs
owner_html_url: https://github.com/codingforentrepreneurs
- name: AIstudioProxyAPI
html_url: https://github.com/CJackHwang/AIstudioProxyAPI
stars: 2445
stars: 2475
owner_login: CJackHwang
owner_html_url: https://github.com/CJackHwang
- name: RasaGPT
html_url: https://github.com/paulpierre/RasaGPT
stars: 2464
owner_login: paulpierre
owner_html_url: https://github.com/paulpierre
- name: nextpy
html_url: https://github.com/dot-agent/nextpy
stars: 2341
stars: 2343
owner_login: dot-agent
owner_html_url: https://github.com/dot-agent
- name: langserve
html_url: https://github.com/langchain-ai/langserve
stars: 2329
stars: 2331
owner_login: langchain-ai
owner_html_url: https://github.com/langchain-ai
- name: fastapi-best-architecture
html_url: https://github.com/fastapi-practices/fastapi-best-architecture
stars: 2318
owner_login: fastapi-practices
owner_html_url: https://github.com/fastapi-practices
- name: open-wearables
html_url: https://github.com/the-momentum/open-wearables
stars: 2311
owner_login: the-momentum
owner_html_url: https://github.com/the-momentum
- name: fastapi-utils
html_url: https://github.com/fastapiutils/fastapi-utils
stars: 2308
stars: 2305
owner_login: fastapiutils
owner_html_url: https://github.com/fastapiutils
- name: vue-fastapi-admin
html_url: https://github.com/mizhexiaoxiao/vue-fastapi-admin
stars: 2184
stars: 2221
owner_login: mizhexiaoxiao
owner_html_url: https://github.com/mizhexiaoxiao
- name: kiro-gateway
html_url: https://github.com/jwadow/kiro-gateway
stars: 2198
owner_login: jwadow
owner_html_url: https://github.com/jwadow
- name: solara
html_url: https://github.com/widgetti/solara
stars: 2166
stars: 2167
owner_login: widgetti
owner_html_url: https://github.com/widgetti
- name: mangum
html_url: https://github.com/Kludex/mangum
stars: 2125
stars: 2130
owner_login: Kludex
owner_html_url: https://github.com/Kludex
- name: codex-lb
html_url: https://github.com/Soju06/codex-lb
stars: 2122
owner_login: Soju06
owner_html_url: https://github.com/Soju06
- name: kiro-gateway
html_url: https://github.com/jwadow/kiro-gateway
stars: 2068
owner_login: jwadow
owner_html_url: https://github.com/jwadow
- name: open-wearables
html_url: https://github.com/the-momentum/open-wearables
stars: 2036
owner_login: the-momentum
owner_html_url: https://github.com/the-momentum
- name: slowapi
html_url: https://github.com/laurentS/slowapi
stars: 2022
owner_login: laurentS
owner_html_url: https://github.com/laurentS
- name: xhs_ai_publisher
html_url: https://github.com/BetaStreetOmnis/xhs_ai_publisher
stars: 2004
stars: 2053
owner_login: BetaStreetOmnis
owner_html_url: https://github.com/BetaStreetOmnis
- name: FastAPI-boilerplate
html_url: https://github.com/benavlabs/FastAPI-boilerplate
stars: 1984
stars: 2044
owner_login: benavlabs
owner_html_url: https://github.com/benavlabs
- name: slowapi
html_url: https://github.com/laurentS/slowapi
stars: 2041
owner_login: laurentS
owner_html_url: https://github.com/laurentS
- name: openapi-python-client
html_url: https://github.com/openapi-generators/openapi-python-client
stars: 1967
stars: 1979
owner_login: openapi-generators
owner_html_url: https://github.com/openapi-generators
- name: agentkit
html_url: https://github.com/BCG-X-Official/agentkit
stars: 1944
stars: 1948
owner_login: BCG-X-Official
owner_html_url: https://github.com/BCG-X-Official
- name: piccolo
html_url: https://github.com/piccolo-orm/piccolo
stars: 1922
stars: 1936
owner_login: piccolo-orm
owner_html_url: https://github.com/piccolo-orm
- name: Vibe-Research
html_url: https://github.com/simonlin1212/Vibe-Research
stars: 1923
owner_login: simonlin1212
owner_html_url: https://github.com/simonlin1212
- name: manage-fastapi
html_url: https://github.com/ycd/manage-fastapi
stars: 1905
stars: 1909
owner_login: ycd
owner_html_url: https://github.com/ycd
- name: fastapi-cache
@@ -368,69 +389,79 @@
stars: 1866
owner_login: long2ice
owner_html_url: https://github.com/long2ice
- name: WebRPA
html_url: https://github.com/pmh1314520/WebRPA
stars: 1832
owner_login: pmh1314520
owner_html_url: https://github.com/pmh1314520
- name: ormar
html_url: https://github.com/ormar-orm/ormar
stars: 1806
stars: 1804
owner_login: ormar-orm
owner_html_url: https://github.com/ormar-orm
- name: python-week-2022
html_url: https://github.com/rochacbruno/python-week-2022
stars: 1806
stars: 1801
owner_login: rochacbruno
owner_html_url: https://github.com/rochacbruno
- name: WebRPA
html_url: https://github.com/pmh1314520/WebRPA
stars: 1781
owner_login: pmh1314520
owner_html_url: https://github.com/pmh1314520
- name: termpair
html_url: https://github.com/cs01/termpair
stars: 1735
stars: 1775
owner_login: cs01
owner_html_url: https://github.com/cs01
- name: fastapi-crudrouter
html_url: https://github.com/awtkns/fastapi-crudrouter
stars: 1694
owner_login: awtkns
owner_html_url: https://github.com/awtkns
- name: bracket
html_url: https://github.com/evroon/bracket
stars: 1694
stars: 1709
owner_login: evroon
owner_html_url: https://github.com/evroon
- name: full-stack-ai-agent-template
html_url: https://github.com/vstorm-co/full-stack-ai-agent-template
stars: 1697
owner_login: vstorm-co
owner_html_url: https://github.com/vstorm-co
- name: fastapi-crudrouter
html_url: https://github.com/awtkns/fastapi-crudrouter
stars: 1696
owner_login: awtkns
owner_html_url: https://github.com/awtkns
- name: fastapi-pagination
html_url: https://github.com/uriyyo/fastapi-pagination
stars: 1670
stars: 1674
owner_login: uriyyo
owner_html_url: https://github.com/uriyyo
- name: langchain-serve
html_url: https://github.com/jina-ai/langchain-serve
stars: 1640
stars: 1641
owner_login: jina-ai
owner_html_url: https://github.com/jina-ai
- name: awesome-fastapi-projects
html_url: https://github.com/Kludex/awesome-fastapi-projects
stars: 1608
stars: 1615
owner_login: Kludex
owner_html_url: https://github.com/Kludex
- name: docling-api
html_url: https://github.com/drmingler/docling-api
stars: 1570
owner_login: drmingler
owner_html_url: https://github.com/drmingler
- name: coronavirus-tracker-api
html_url: https://github.com/ExpDev07/coronavirus-tracker-api
stars: 1568
stars: 1570
owner_login: ExpDev07
owner_html_url: https://github.com/ExpDev07
- name: fastapi-amis-admin
html_url: https://github.com/amisadmin/fastapi-amis-admin
stars: 1559
stars: 1564
owner_login: amisadmin
owner_html_url: https://github.com/amisadmin
- name: fastcrud
html_url: https://github.com/benavlabs/fastcrud
stars: 1531
stars: 1545
owner_login: benavlabs
owner_html_url: https://github.com/benavlabs
- name: tavily-key-generator
html_url: https://github.com/skernelx/tavily-key-generator
stars: 1526
stars: 1542
owner_login: skernelx
owner_html_url: https://github.com/skernelx
- name: fastapi-boilerplate
@@ -438,58 +469,28 @@
stars: 1491
owner_login: teamhide
owner_html_url: https://github.com/teamhide
- name: full-stack-ai-agent-template
html_url: https://github.com/vstorm-co/full-stack-ai-agent-template
stars: 1484
owner_login: vstorm-co
owner_html_url: https://github.com/vstorm-co
- name: prometheus-fastapi-instrumentator
html_url: https://github.com/trallnag/prometheus-fastapi-instrumentator
stars: 1471
stars: 1478
owner_login: trallnag
owner_html_url: https://github.com/trallnag
- name: awesome-python-resources
html_url: https://github.com/DjangoEx/awesome-python-resources
stars: 1451
owner_login: DjangoEx
owner_html_url: https://github.com/DjangoEx
- name: aktools
html_url: https://github.com/akfamily/aktools
stars: 1431
owner_login: akfamily
owner_html_url: https://github.com/akfamily
- name: RuoYi-Vue3-FastAPI
html_url: https://github.com/insistence/RuoYi-Vue3-FastAPI
stars: 1419
stars: 1478
owner_login: insistence
owner_html_url: https://github.com/insistence
- name: fastapi-tutorial
html_url: https://github.com/liaogx/fastapi-tutorial
stars: 1418
owner_login: liaogx
owner_html_url: https://github.com/liaogx
- name: fastapi-code-generator
html_url: https://github.com/koxudaxi/fastapi-code-generator
stars: 1396
owner_login: koxudaxi
owner_html_url: https://github.com/koxudaxi
- name: yubal
html_url: https://github.com/guillevc/yubal
stars: 1388
stars: 1469
owner_login: guillevc
owner_html_url: https://github.com/guillevc
- name: budgetml
html_url: https://github.com/ebhy/budgetml
stars: 1343
owner_login: ebhy
owner_html_url: https://github.com/ebhy
- name: Chatterbox-TTS-Server
html_url: https://github.com/devnen/Chatterbox-TTS-Server
stars: 1328
owner_login: devnen
owner_html_url: https://github.com/devnen
- name: restish
html_url: https://github.com/rest-sh/restish
stars: 1321
owner_login: rest-sh
owner_html_url: https://github.com/rest-sh
- name: aktools
html_url: https://github.com/akfamily/aktools
stars: 1457
owner_login: akfamily
owner_html_url: https://github.com/akfamily
- name: awesome-python-resources
html_url: https://github.com/DjangoEx/awesome-python-resources
stars: 1455
owner_login: DjangoEx
owner_html_url: https://github.com/DjangoEx
@@ -243,5 +243,5 @@ For example:
To see what exactly you can include in the responses, you can check these sections in the OpenAPI specification:
* [OpenAPI Responses Object](https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.1.0.md#responses-object), it includes the `Response Object`.
* [OpenAPI Response Object](https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.1.0.md#response-object), you can include anything from this directly in each response inside your `responses` parameter. Including `description`, `headers`, `content` (inside of this is that you declare different media types and JSON Schemas), and `links`.
* [OpenAPI Responses Object](https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#responses-object), it includes the `Response Object`.
* [OpenAPI Response Object](https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#response-object), you can include anything from this directly in each response inside your `responses` parameter. Including `description`, `headers`, `content` (inside of this is that you declare different media types and JSON Schemas), and `links`.
+1 -1
View File
@@ -45,7 +45,7 @@ You can run your tests as usual via:
<div class="termy">
```console
$ pytest
$ uv run pytest
---> 100%
```
+5 -5
View File
@@ -33,7 +33,7 @@ If your **server** is behind a trusted **proxy** and only the proxy talks to it,
<div class="termy">
```console
$ fastapi run --forwarded-allow-ips="*"
$ uv run fastapi run --forwarded-allow-ips="*"
<span style="color: green;">INFO</span>: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit)
```
@@ -170,7 +170,7 @@ To achieve this, you can use the command line option `--root-path` like:
<div class="termy">
```console
$ fastapi run main.py --forwarded-allow-ips="*" --root-path /api/v1
$ uv run fastapi run main.py --forwarded-allow-ips="*" --root-path /api/v1
<span style="color: green;">INFO</span>: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit)
```
@@ -200,7 +200,7 @@ Then, if you start Uvicorn with:
<div class="termy">
```console
$ fastapi run main.py --forwarded-allow-ips="*" --root-path /api/v1
$ uv run fastapi run main.py --forwarded-allow-ips="*" --root-path /api/v1
<span style="color: green;">INFO</span>: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit)
```
@@ -253,7 +253,7 @@ In a case like that (without a stripped path prefix), the proxy would listen on
You can easily run the experiment locally with a stripped path prefix using [Traefik](https://docs.traefik.io/).
[Download Traefik](https://github.com/containous/traefik/releases), it's a single binary, you can extract the compressed file and run it directly from the terminal.
[Download Traefik](https://github.com/traefik/traefik/releases), it's a single binary, you can extract the compressed file and run it directly from the terminal.
Then create a file `traefik.toml` with:
@@ -321,7 +321,7 @@ And now start your app, using the `--root-path` option:
<div class="termy">
```console
$ fastapi run main.py --forwarded-allow-ips="*" --root-path /api/v1
$ uv run fastapi run main.py --forwarded-allow-ips="*" --root-path /api/v1
<span style="color: green;">INFO</span>: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit)
```
+2 -2
View File
@@ -6,7 +6,7 @@ But FastAPI also supports using [`dataclasses`](https://docs.python.org/3/librar
{* ../../docs_src/dataclasses_/tutorial001_py310.py hl[1,6:11,18:19] *}
This is still supported thanks to **Pydantic**, as it has [internal support for `dataclasses`](https://docs.pydantic.dev/latest/concepts/dataclasses/#use-of-stdlib-dataclasses-with-basemodel).
This is still supported thanks to **Pydantic**, as it has [internal support for `dataclasses`](https://pydantic.dev/docs/validation/latest/concepts/dataclasses/#usage-of-stdlib-dataclasses-with-basemodel).
So, even with the code above that doesn't use Pydantic explicitly, FastAPI is using Pydantic to convert those standard dataclasses to Pydantic's own flavor of dataclasses.
@@ -88,7 +88,7 @@ Check the in-code annotation tips above to see more specific details.
You can also combine `dataclasses` with other Pydantic models, inherit from them, include them in your own models, etc.
To learn more, check the [Pydantic docs about dataclasses](https://docs.pydantic.dev/latest/concepts/dataclasses/).
To learn more, check the [Pydantic docs about dataclasses](https://pydantic.dev/docs/validation/latest/concepts/dataclasses/).
## Version { #version }
+1 -1
View File
@@ -154,7 +154,7 @@ Underneath, in the ASGI technical specification, this is part of the [Lifespan P
/// note
You can read more about the Starlette `lifespan` handlers in [Starlette's Lifespan' docs](https://www.starlette.dev/lifespan/).
You can read more about the Starlette `lifespan` handlers in [Starlette's Lifespan' docs](https://starlette.dev/lifespan/).
Including how to handle lifespan state that can be used in other areas of your code.
+1 -1
View File
@@ -12,7 +12,7 @@ A versatile option is the [OpenAPI Generator](https://openapi-generator.tech/),
For **TypeScript clients**, [Hey API](https://heyapi.dev/) is a purpose-built solution, providing an optimized experience for the TypeScript ecosystem.
You can discover more SDK generators on [OpenAPI.Tools](https://openapi.tools/#sdk).
You can discover more SDK generators on [OpenAPI.Tools](https://openapi.tools/categories/sdk-generators).
/// tip
+2 -2
View File
@@ -91,7 +91,7 @@ There are many other ASGI middlewares.
For example:
* [Uvicorn's `ProxyHeadersMiddleware`](https://github.com/encode/uvicorn/blob/master/uvicorn/middleware/proxy_headers.py)
* [Uvicorn's `ProxyHeadersMiddleware`](https://github.com/Kludex/uvicorn/blob/main/uvicorn/middleware/proxy_headers.py)
* [MessagePack](https://github.com/florimondmanca/msgpack-asgi)
To see other available middlewares check [Starlette's Middleware docs](https://www.starlette.dev/middleware/) and the [ASGI Awesome List](https://github.com/florimondmanca/awesome-asgi).
To see other available middlewares check [Starlette's Middleware docs](https://starlette.dev/middleware/) and the [ASGI Awesome List](https://github.com/florimondmanca/awesome-asgi).
+3 -3
View File
@@ -35,7 +35,7 @@ This part is pretty normal, most of the code is probably already familiar to you
/// tip
The `callback_url` query parameter uses a Pydantic [Url](https://docs.pydantic.dev/latest/api/networks/) type.
The `callback_url` query parameter uses a Pydantic [Url](https://pydantic.dev/docs/validation/latest/api/pydantic/networks/) type.
///
@@ -106,11 +106,11 @@ It should look just like a normal FastAPI *path operation*:
There are 2 main differences from a normal *path operation*:
* It doesn't need to have any actual code, because your app will never call this code. It's only used to document the *external API*. So, the function could just have `pass`.
* The *path* can contain an [OpenAPI 3 expression](https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.1.0.md#key-expression) (see more below) where it can use variables with parameters and parts of the original request sent to *your API*.
* The *path* can contain an [OpenAPI 3 expression](https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#key-expression) (see more below) where it can use variables with parameters and parts of the original request sent to *your API*.
### The callback path expression { #the-callback-path-expression }
The callback *path* can have an [OpenAPI 3 expression](https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.1.0.md#key-expression) that can contain parts of the original request sent to *your API*.
The callback *path* can have an [OpenAPI 3 expression](https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#key-expression) that can contain parts of the original request sent to *your API*.
In this case, it's the `str`:
+1 -1
View File
@@ -48,4 +48,4 @@ And as the `Response` can be used frequently to set headers and cookies, **FastA
///
To see all the available parameters and options, check the [documentation in Starlette](https://www.starlette.dev/responses/#set-cookie).
To see all the available parameters and options, check the [documentation in Starlette](https://starlette.dev/responses/#set-cookie).
+1 -1
View File
@@ -38,4 +38,4 @@ And as the `Response` can be used frequently to set headers and cookies, **FastA
Keep in mind that custom proprietary headers can be added [using the `X-` prefix](https://developer.mozilla.org/en-US/docs/Web/HTTP/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 CORS configurations (read more in [CORS (Cross-Origin Resource Sharing)](../tutorial/cors.md)), using the parameter `expose_headers` documented in [Starlette's CORS docs](https://www.starlette.dev/middleware/#corsmiddleware).
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 CORS configurations (read more in [CORS (Cross-Origin Resource Sharing)](../tutorial/cors.md)), using the parameter `expose_headers` documented in [Starlette's CORS docs](https://starlette.dev/middleware/#corsmiddleware).
+34 -10
View File
@@ -6,9 +6,13 @@ Most of these settings are variable (can change), like database URLs. And many c
For this reason it's common to provide them in environment variables that are read by the application.
An **environment variable** (also known as an **env var**) is a value that lives outside of the Python code, in the operating system, and can be read by your application and other programs.
You can create an environment variable for a command when you run it. You will see the platform-specific commands below.
/// tip
To understand environment variables you can read [Environment Variables](../environment-variables.md).
Read the [Environment Variables guide](https://tiangolo.com/guides/environment-variables/) for a detailed explanation of how environment variables work.
///
@@ -20,16 +24,16 @@ That means that any value read in Python from an environment variable will be a
## Pydantic `Settings` { #pydantic-settings }
Fortunately, Pydantic provides a great utility to handle these settings coming from environment variables with [Pydantic: Settings management](https://docs.pydantic.dev/latest/concepts/pydantic_settings/).
Fortunately, Pydantic provides a great utility to handle these settings coming from environment variables with [Pydantic: Settings management](https://pydantic.dev/docs/validation/latest/concepts/pydantic_settings/).
### Install `pydantic-settings` { #install-pydantic-settings }
First, make sure you create your [virtual environment](../virtual-environments.md), activate it, and then install the `pydantic-settings` package:
Add the `pydantic-settings` package to your project:
<div class="termy">
```console
$ pip install pydantic-settings
$ uv add pydantic-settings
---> 100%
```
@@ -40,7 +44,7 @@ It also comes included when you install the `all` extras with:
<div class="termy">
```console
$ pip install "fastapi[all]"
$ uv add "fastapi[all]"
---> 100%
```
@@ -76,19 +80,39 @@ Then you can use the new `settings` object in your application:
Next, you would run the server passing the configurations as environment variables, for example you could set an `ADMIN_EMAIL` and `APP_NAME` with:
//// tab | Linux, macOS, Windows Bash
<div class="termy">
```console
$ ADMIN_EMAIL="deadpool@example.com" APP_NAME="ChimichangApp" fastapi run main.py
$ ADMIN_EMAIL="deadpool@example.com" APP_NAME="ChimichangApp" uv run fastapi run main.py
<span style="color: green;">INFO</span>: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit)
```
</div>
////
//// tab | Windows PowerShell
<div class="termy">
```console
$ $Env:ADMIN_EMAIL = "deadpool@example.com"
$ $Env:APP_NAME = "ChimichangApp"
$ uv run fastapi run main.py
<span style="color: green;">INFO</span>: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit)
```
</div>
////
/// tip
To set multiple env vars for a single command just separate them with a space, and put them all before the command.
In Bash, to set multiple env vars for a single command, separate them with a space and put them all before the command.
///
@@ -172,11 +196,11 @@ But a dotenv file doesn't really have to have that exact filename.
///
Pydantic has support for reading from these types of files using an external library. You can read more at [Pydantic Settings: Dotenv (.env) support](https://docs.pydantic.dev/latest/concepts/pydantic_settings/#dotenv-env-support).
Pydantic has support for reading from these types of files using an external library. You can read more at [Pydantic Settings: Dotenv (.env) support](https://pydantic.dev/docs/validation/latest/concepts/pydantic_settings/#dotenv-env-support).
/// tip
For this to work, you need to `pip install python-dotenv`.
For this to work, add `python-dotenv` to your project with `uv add python-dotenv`.
///
@@ -197,7 +221,7 @@ And then update your `config.py` with:
/// tip
The `model_config` attribute is used just for Pydantic configuration. You can read more at [Pydantic: Concepts: Configuration](https://docs.pydantic.dev/latest/concepts/config/).
The `model_config` attribute is used just for Pydantic configuration. You can read more at [Pydantic: Concepts: Configuration](https://pydantic.dev/docs/validation/latest/concepts/config/).
///
+1 -1
View File
@@ -35,7 +35,7 @@ Now, run the `fastapi` command:
<div class="termy">
```console
$ fastapi dev
$ uv run fastapi dev
<span style="color: green;">INFO</span>: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit)
```
+3 -3
View File
@@ -8,12 +8,12 @@ There are utilities to configure it easily that you can use directly in your **F
## Install dependencies { #install-dependencies }
Make sure you create a [virtual environment](../virtual-environments.md), activate it, and install `jinja2`:
Add `jinja2` to your project:
<div class="termy">
```console
$ pip install jinja2
$ uv add jinja2
---> 100%
```
@@ -123,4 +123,4 @@ And because you are using `StaticFiles`, that CSS file would be served automatic
## More details { #more-details }
For more details, including how to test templates, check [Starlette's docs on templates](https://www.starlette.dev/templates/).
For more details, including how to test templates, check [Starlette's docs on templates](https://starlette.dev/templates/).
+1 -1
View File
@@ -5,7 +5,7 @@ When you need `lifespan` to run in your tests, you can use the `TestClient` with
{* ../../docs_src/app_testing/tutorial004_py310.py hl[9:15,18,27:28,30:32,41:43] *}
You can read more details about the ["Running lifespan in tests in the official Starlette documentation site."](https://www.starlette.dev/lifespan/#running-lifespan-in-tests)
You can read more details about the ["Running lifespan in tests in the official Starlette documentation site."](https://starlette.dev/lifespan/#running-lifespan-in-tests)
For the deprecated `startup` and `shutdown` events, you can use the `TestClient` as follows:
+1 -1
View File
@@ -8,6 +8,6 @@ For this, you use the `TestClient` in a `with` statement, connecting to the WebS
/// note
For more details, check Starlette's documentation for [testing WebSockets](https://www.starlette.dev/testclient/#testing-websocket-sessions).
For more details, check Starlette's documentation for [testing WebSockets](https://starlette.dev/testclient/#testing-websocket-sessions).
///
@@ -15,7 +15,7 @@ But there are situations where you might need to access the `Request` object dir
## Details about the `Request` object { #details-about-the-request-object }
As **FastAPI** is actually **Starlette** underneath, with a layer of several tools on top, you can use Starlette's [`Request`](https://www.starlette.dev/requests/) object directly when you need to.
As **FastAPI** is actually **Starlette** underneath, with a layer of several tools on top, you can use Starlette's [`Request`](https://starlette.dev/requests/) object directly when you need to.
It would also mean that if you get data from the `Request` object directly (for example, read the body) it won't be validated, converted or documented (with OpenAPI, for the automatic API user interface) by FastAPI.
@@ -45,7 +45,7 @@ The same way, you can declare any other parameter as normally, and additionally,
## `Request` documentation { #request-documentation }
You can read more details about the [`Request` object in the official Starlette documentation site](https://www.starlette.dev/requests/).
You can read more details about the [`Request` object in the official Starlette documentation site](https://starlette.dev/requests/).
/// note | Technical Details
+6 -6
View File
@@ -4,12 +4,12 @@ You can use [WebSockets](https://developer.mozilla.org/en-US/docs/Web/API/WebSoc
## Install `websockets` { #install-websockets }
Make sure you create a [virtual environment](../virtual-environments.md), activate it, and install `websockets` (a Python library that makes it easy to use the "WebSocket" protocol):
Add `websockets` (a Python library that makes it easy to use the "WebSocket" protocol) to your project:
<div class="termy">
```console
$ pip install websockets
$ uv add websockets
---> 100%
```
@@ -69,7 +69,7 @@ Put your code in a file `main.py` and then run your application:
<div class="termy">
```console
$ fastapi dev
$ uv run fastapi dev
<span style="color: green;">INFO</span>: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit)
```
@@ -126,7 +126,7 @@ Run your application:
<div class="termy">
```console
$ fastapi dev
$ uv run fastapi dev
<span style="color: green;">INFO</span>: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit)
```
@@ -182,5 +182,5 @@ If you need something easy to integrate with FastAPI but that is more robust, su
To learn more about the options, check Starlette's documentation for:
* [The `WebSocket` class](https://www.starlette.dev/websockets/).
* [Class-based WebSocket handling](https://www.starlette.dev/endpoints/#websocketendpoint).
* [The `WebSocket` class](https://starlette.dev/websockets/).
* [Class-based WebSocket handling](https://starlette.dev/endpoints/#websocketendpoint).
+1 -1
View File
@@ -8,7 +8,7 @@ For that, you can use the `WSGIMiddleware` and use it to wrap your WSGI applicat
/// note
This requires installing `a2wsgi` for example with `pip install a2wsgi`.
This requires adding `a2wsgi` to your project, for example with `uv add a2wsgi`.
///
+6 -6
View File
@@ -125,7 +125,7 @@ Adopt and use an open standard for API specifications, instead of a custom schem
And integrate standards-based user interface tools:
* [Swagger UI](https://github.com/swagger-api/swagger-ui)
* [ReDoc](https://github.com/Rebilly/ReDoc)
* [ReDoc](https://github.com/Redocly/redoc)
These two were chosen for being fairly popular and stable, but doing a quick search, you could find dozens of alternative user interfaces for OpenAPI (that you can use with **FastAPI**).
@@ -237,7 +237,7 @@ Generate the OpenAPI schema automatically, from the same code that defines seria
///
### [NestJS](https://nestjs.com/) (and [Angular](https://angular.io/)) { #nestjs-and-angular }
### [NestJS](https://nestjs.com/) (and [Angular](https://angular.dev/)) { #nestjs-and-angular }
This isn't even Python, NestJS is a JavaScript (TypeScript) NodeJS framework inspired by Angular.
@@ -337,7 +337,7 @@ As it is based on the previous standard for synchronous Python web frameworks (W
/// note
Hug was created by Timothy Crosley, the same creator of [`isort`](https://github.com/timothycrosley/isort), a great tool to automatically sort imports in Python files.
Hug was created by Timothy Crosley, the same creator of [`isort`](https://github.com/PyCQA/isort), a great tool to automatically sort imports in Python files.
///
@@ -401,7 +401,7 @@ I consider **FastAPI** a "spiritual successor" to APIStar, while improving and i
## Used by **FastAPI** { #used-by-fastapi }
### [Pydantic](https://docs.pydantic.dev/) { #pydantic }
### [Pydantic](https://pydantic.dev/docs/) { #pydantic }
Pydantic is a library to define data validation, serialization and documentation (using JSON Schema) based on Python type hints.
@@ -417,7 +417,7 @@ Handle all the data validation, data serialization and automatic model documenta
///
### [Starlette](https://www.starlette.dev/) { #starlette }
### [Starlette](https://starlette.dev/) { #starlette }
Starlette is a lightweight <dfn title="The new standard for building asynchronous Python web applications">ASGI</dfn> framework/toolkit, which is ideal for building high-performance asyncio services.
@@ -462,7 +462,7 @@ So, anything that you can do with Starlette, you can do it directly with **FastA
///
### [Uvicorn](https://www.uvicorn.dev/) { #uvicorn }
### [Uvicorn](https://uvicorn.dev) { #uvicorn }
Uvicorn is a lightning-fast ASGI server, built on uvloop and httptools.
+10 -1
View File
@@ -55,10 +55,19 @@
text-align: center;
}
a[data-terminal-control] {
button[data-terminal-control] {
cursor: pointer;
text-align: right;
display: block;
width: 100%;
color: #aebbff;
border: 0;
background: transparent;
font: inherit;
}
button[data-terminal-control]:hover {
color: var(--color-text);
}
[data-ty] {
+15 -19
View File
@@ -105,36 +105,32 @@ This is what you would want to do in **most cases**, for example:
### Package Requirements { #package-requirements }
You would normally have the **package requirements** for your application in some file.
When you manage your project with `uv`, its direct dependencies are declared in `pyproject.toml` and the exact resolved versions are stored in `uv.lock`.
It would depend mainly on the tool you use to **install** those requirements.
The most common way to do it is to have a file `requirements.txt` with the package names and their versions, one per line.
You would of course use the same ideas you read in [About FastAPI versions](versions.md) to set the ranges of versions.
For example, your `requirements.txt` could look like:
```
fastapi[standard]>=0.113.0,<0.114.0
pydantic>=2.7.0,<3.0.0
```
And you would normally install those package dependencies with `pip`, for example:
You can add the packages your application needs with:
<div class="termy">
```console
$ pip install -r requirements.txt
$ uv add "fastapi[standard]" pydantic
---> 100%
Successfully installed fastapi pydantic
```
</div>
/// note
There are other formats and tools to define and install package dependencies.
The Dockerfile below uses `pip` inside the container. You can export the locked dependencies from your uv project to the `requirements.txt` format it expects:
<div class="termy">
```console
$ uv export --format requirements-txt --no-dev --no-emit-project --output-file requirements.txt
```
</div>
The generated `requirements.txt` is an export for the container build. Continue managing dependencies with `uv add` and regenerate it when `uv.lock` changes.
///
@@ -372,7 +368,7 @@ You will see the automatic interactive API documentation (provided by [Swagger U
And you can also go to [http://192.168.99.100/redoc](http://192.168.99.100/redoc) or [http://127.0.0.1/redoc](http://127.0.0.1/redoc) (or equivalent, using your Docker host).
You will see the alternative automatic documentation (provided by [ReDoc](https://github.com/Rebilly/ReDoc)):
You will see the alternative automatic documentation (provided by [ReDoc](https://github.com/Redocly/redoc)):
![ReDoc](https://fastapi.tiangolo.com/img/index/index-02-redoc-simple.png)
+1 -1
View File
@@ -5,7 +5,7 @@ You can deploy your FastAPI app to [FastAPI Cloud](https://fastapicloud.com) wit
<div class="termy">
```console
$ fastapi deploy
$ uv run fastapi deploy
Deploying to FastAPI Cloud...
+5 -5
View File
@@ -52,7 +52,7 @@ The main thing you need to run a **FastAPI** application (or any other ASGI appl
There are several alternatives, including:
* [Uvicorn](https://www.uvicorn.dev/): a high performance ASGI server.
* [Uvicorn](https://uvicorn.dev): a high performance ASGI server.
* [Hypercorn](https://hypercorn.readthedocs.io/): an ASGI server compatible with HTTP/2 and Trio among other features.
* [Daphne](https://github.com/django/daphne): the ASGI server built for Django Channels.
* [Granian](https://github.com/emmett-framework/granian): A Rust HTTP server for Python applications.
@@ -73,14 +73,14 @@ When you install FastAPI, it comes with a production server, Uvicorn, and you ca
But you can also install an ASGI server manually.
Make sure you create a [virtual environment](../virtual-environments.md), activate it, and then you can install the server application.
Add the server application to your project.
For example, to install Uvicorn:
<div class="termy">
```console
$ pip install "uvicorn[standard]"
$ uv add "uvicorn[standard]"
---> 100%
```
@@ -95,7 +95,7 @@ By adding the `standard`, Uvicorn will install and use some recommended extra de
That includes `uvloop`, the high-performance drop-in replacement for `asyncio`, that provides the big concurrency performance boost.
When you install FastAPI with something like `pip install "fastapi[standard]"` you already get `uvicorn[standard]` as well.
When you add FastAPI with something like `uv add "fastapi[standard]"` you already get `uvicorn[standard]` as well.
///
@@ -106,7 +106,7 @@ If you installed an ASGI server manually, you would normally need to pass an imp
<div class="termy">
```console
$ uvicorn main:app --host 0.0.0.0 --port 80
$ uv run uvicorn main:app --host 0.0.0.0 --port 80
<span style="color: green;">INFO</span>: Uvicorn running on http://0.0.0.0:80 (Press CTRL+C to quit)
```
+1 -1
View File
@@ -86,7 +86,7 @@ If you prefer to use the `uvicorn` command directly:
<div class="termy">
```console
$ uvicorn main:app --host 0.0.0.0 --port 8080 --workers 4
$ uv run uvicorn main:app --host 0.0.0.0 --port 8080 --workers 4
<font color="#A6E22E">INFO</font>: Uvicorn running on <b>http://0.0.0.0:8080</b> (Press CTRL+C to quit)
<font color="#A6E22E">INFO</font>: Started parent process [<font color="#A1EFE4"><b>27365</b></font>]
<font color="#A6E22E">INFO</font>: Started server process [<font color="#A1EFE4">27368</font>]
+5 -292
View File
@@ -1,298 +1,11 @@
# Environment Variables { #environment-variables }
/// tip
An **environment variable** (also known as an **env var**) is a value that lives outside of your Python code, in the operating system, and can be read by your application and other programs.
If you already know what "environment variables" are and how to use them, feel free to skip this.
FastAPI applications commonly use environment variables for configuration such as database URLs, email credentials, and secret keys.
///
You will learn how to use them for application configuration in [Settings and Environment Variables](advanced/settings.md).
An environment variable (also known as "**env var**") is a variable that lives **outside** of the Python code, in the **operating system**, and could be read by your Python code (or by other programs as well).
## Learn More { #learn-more }
Environment variables could be useful for handling application **settings**, as part of the **installation** of Python, etc.
## Create and Use Env Vars { #create-and-use-env-vars }
You can **create** and use environment variables in the **shell (terminal)**, without needing Python:
//// tab | Linux, macOS, Windows Bash
<div class="termy">
```console
// You could create an env var MY_NAME with
$ export MY_NAME="Wade Wilson"
// Then you could use it with other programs, like
$ echo "Hello $MY_NAME"
Hello Wade Wilson
```
</div>
////
//// tab | Windows PowerShell
<div class="termy">
```console
// Create an env var MY_NAME
$ $Env:MY_NAME = "Wade Wilson"
// Use it with other programs, like
$ echo "Hello $Env:MY_NAME"
Hello Wade Wilson
```
</div>
////
## Read env vars in Python { #read-env-vars-in-python }
You could also create environment variables **outside** of Python, in the terminal (or with any other method), and then **read them in Python**.
For example you could have a file `main.py` with:
```Python hl_lines="3"
import os
name = os.getenv("MY_NAME", "World")
print(f"Hello {name} from Python")
```
/// tip
The second argument to [`os.getenv()`](https://docs.python.org/3.8/library/os.html#os.getenv) is the default value to return.
If not provided, it's `None` by default, here we provide `"World"` as the default value to use.
///
Then you could call that Python program:
//// tab | Linux, macOS, Windows Bash
<div class="termy">
```console
// Here we don't set the env var yet
$ python main.py
// As we didn't set the env var, we get the default value
Hello World from Python
// But if we create an environment variable first
$ export MY_NAME="Wade Wilson"
// And then call the program again
$ python main.py
// Now it can read the environment variable
Hello Wade Wilson from Python
```
</div>
////
//// tab | Windows PowerShell
<div class="termy">
```console
// Here we don't set the env var yet
$ python main.py
// As we didn't set the env var, we get the default value
Hello World from Python
// But if we create an environment variable first
$ $Env:MY_NAME = "Wade Wilson"
// And then call the program again
$ python main.py
// Now it can read the environment variable
Hello Wade Wilson from Python
```
</div>
////
As environment variables can be set outside of the code, but can be read by the code, and don't have to be stored (committed to `git`) with the rest of the files, it's common to use them for configurations or **settings**.
You can also create an environment variable only for a **specific program invocation**, that is only available to that program, and only for its duration.
To do that, create it right before the program itself, on the same line:
<div class="termy">
```console
// Create an env var MY_NAME in line for this program call
$ MY_NAME="Wade Wilson" python main.py
// Now it can read the environment variable
Hello Wade Wilson from Python
// The env var no longer exists afterwards
$ python main.py
Hello World from Python
```
</div>
/// tip
You can read more about it at [The Twelve-Factor App: Config](https://12factor.net/config).
///
## Types and Validation { #types-and-validation }
These environment variables can only handle **text strings**, as they are external to Python and have to be compatible with other programs and the rest of the system (and even with different operating systems, such as Linux, Windows, and macOS).
That means that **any value** read in Python from an environment variable **will be a `str`**, and any conversion to a different type or any validation has to be done in code.
You will learn more about using environment variables for handling **application settings** in the [Advanced User Guide - Settings and Environment Variables](./advanced/settings.md).
## `PATH` Environment Variable { #path-environment-variable }
There is a **special** environment variable called **`PATH`** that is used by the operating systems (Linux, macOS, Windows) to find programs to run.
The value of the variable `PATH` is a long string that is made of directories separated by a colon `:` on Linux and macOS, and by a semicolon `;` on Windows.
For example, the `PATH` environment variable could look like this:
//// tab | Linux, macOS
```plaintext
/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin
```
This means that the system should look for programs in the directories:
* `/usr/local/bin`
* `/usr/bin`
* `/bin`
* `/usr/sbin`
* `/sbin`
////
//// tab | Windows
```plaintext
C:\Program Files\Python312\Scripts;C:\Program Files\Python312;C:\Windows\System32
```
This means that the system should look for programs in the directories:
* `C:\Program Files\Python312\Scripts`
* `C:\Program Files\Python312`
* `C:\Windows\System32`
////
When you type a **command** in the terminal, the operating system **looks for** the program in **each of those directories** listed in the `PATH` environment variable.
For example, when you type `python` in the terminal, the operating system looks for a program called `python` in the **first directory** in that list.
If it finds it, then it will **use it**. Otherwise it keeps looking in the **other directories**.
### Installing Python and Updating the `PATH` { #installing-python-and-updating-the-path }
When you install Python, you might be asked if you want to update the `PATH` environment variable.
//// tab | Linux, macOS
Let's say you install Python and it ends up in a directory `/opt/custompython/bin`.
If you say yes to update the `PATH` environment variable, then the installer will add `/opt/custompython/bin` to the `PATH` environment variable.
It could look like this:
```plaintext
/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin:/opt/custompython/bin
```
This way, when you type `python` in the terminal, the system will find the Python program in `/opt/custompython/bin` (the last directory) and use that one.
////
//// tab | Windows
Let's say you install Python and it ends up in a directory `C:\opt\custompython\bin`.
If you say yes to update the `PATH` environment variable, then the installer will add `C:\opt\custompython\bin` to the `PATH` environment variable.
```plaintext
C:\Program Files\Python312\Scripts;C:\Program Files\Python312;C:\Windows\System32;C:\opt\custompython\bin
```
This way, when you type `python` in the terminal, the system will find the Python program in `C:\opt\custompython\bin` (the last directory) and use that one.
////
So, if you type:
<div class="termy">
```console
$ python
```
</div>
//// tab | Linux, macOS
The system will **find** the `python` program in `/opt/custompython/bin` and run it.
It would be roughly equivalent to typing:
<div class="termy">
```console
$ /opt/custompython/bin/python
```
</div>
////
//// tab | Windows
The system will **find** the `python` program in `C:\opt\custompython\bin\python` and run it.
It would be roughly equivalent to typing:
<div class="termy">
```console
$ C:\opt\custompython\bin\python
```
</div>
////
This information will be useful when learning about [Virtual Environments](virtual-environments.md).
## Conclusion { #conclusion }
With this you should have a basic understanding of what **environment variables** are and how to use them in Python.
You can also read more about them in the [Wikipedia for Environment Variable](https://en.wikipedia.org/wiki/Environment_variable).
In many cases it's not very obvious how environment variables would be useful and applicable right away. But they keep showing up in many different scenarios when you are developing, so it's good to know about them.
For example, you will need this information in the next section, about [Virtual Environments](virtual-environments.md).
Read the [Environment Variables guide](https://tiangolo.com/guides/environment-variables/) for a detailed, cross-platform explanation, including how to create and read environment variables and how the `PATH` environment variable works.
+1 -1
View File
@@ -23,7 +23,7 @@ But now that FastAPI is the backend framework with the most GitHub stars across
Most starred [GitHub repositories with the topic `fastapi`](https://github.com/topics/fastapi):
{% for repo in topic_repos %}
{% for repo in topic_repos.repos %}
<a href={{repo.html_url}} target="_blank">★ {{repo.stars}} - {{repo.name}}</a> by <a href={{repo.owner_html_url}} target="_blank">@{{repo.owner_login}}</a>.
+8 -4
View File
@@ -2,7 +2,7 @@
**FastAPI <abbr title="command line interface">CLI</abbr>** is a command line program that you can use to serve your FastAPI app, manage your FastAPI project, and more.
When you install FastAPI (e.g. with `pip install "fastapi[standard]"`), it comes with a command line program you can run in the terminal.
When you add FastAPI to your project (e.g. with `uv add "fastapi[standard]"`), it comes with a command line program you can run in the terminal.
To run your FastAPI app for development, you can use the `fastapi dev` command:
@@ -52,7 +52,7 @@ For production you would use `fastapi run` instead of `fastapi dev`. 🚀
///
Internally, **FastAPI CLI** uses [Uvicorn](https://www.uvicorn.dev), a high-performance, production-ready, ASGI server. 😎
Internally, **FastAPI CLI** uses [Uvicorn](https://uvicorn.dev), a high-performance, production-ready, ASGI server. 😎
The `fastapi` CLI will try to detect automatically the FastAPI app to run, assuming it's an object called `app` in a file `main.py` (or a couple other variants).
@@ -100,13 +100,13 @@ from backend.main import app
You can also pass the file path to the `fastapi dev` command, and it will guess the FastAPI app object to use:
```console
$ fastapi dev main.py
$ uv run fastapi dev main.py
```
Or, you can also pass the `--entrypoint` option to the `fastapi dev` command:
```console
$ fastapi dev --entrypoint main:app
$ uv run fastapi dev --entrypoint main:app
```
But you would have to remember to pass the correct path\entrypoint every time you call the `fastapi` command.
@@ -119,6 +119,10 @@ Running `fastapi dev` initiates development mode.
By default, **auto-reload** is enabled, automatically reloading the server when you make changes to your code. This is resource-intensive and could be less stable than when it's disabled. You should only use it for development. It also listens on the IP address `127.0.0.1`, which is the IP for your machine to communicate with itself alone (`localhost`).
Before importing your app, `fastapi dev` sets the `FASTAPI_ENV` environment variable to `development`. If `FASTAPI_ENV` is already set, its existing value is preserved. This lets app startup code choose development-friendly behavior while allowing you to provide an app-specific environment such as `staging`.
The conventional `FASTAPI_ENV` values are `development` and `production`. `fastapi run` currently leaves `FASTAPI_ENV` unchanged, so set it explicitly if your app needs to detect production mode.
## `fastapi run` { #fastapi-run }
Executing `fastapi run` starts FastAPI in production mode.
+34 -135
View File
@@ -1,7 +1,4 @@
---
hide:
- navigation
include_yaml:
github_sponsors: data/github_sponsors.yml
people: data/people.yml
@@ -33,22 +30,6 @@ This is me:
I'm the creator of **FastAPI**. You can read more about that in [Help FastAPI - Follow the author](help-fastapi.md#follow-the-author).
...But here I want to show you the community.
---
**FastAPI** receives a lot of support from the community. And I want to highlight their contributions.
These are the people that:
* [Help others with questions in GitHub](help-fastapi.md#help-others-with-questions-in-github).
* Create or review Pull Requests.
* Help [manage the repository](https://tiangolo.com/open-source/management-tasks/) (team members).
All these tasks help maintain the repository.
A round of applause to them. 👏 🙇
## Team
This is the current list of team members. 😎
@@ -65,113 +46,19 @@ They have different levels of involvement and permissions, they can perform [rep
</div>
Although the team members have the permissions to perform privileged tasks, all the help from others maintaining FastAPI is very much appreciated! 🙇‍♂️
## FastAPI Experts
These are the users that have been [helping others the most with questions in GitHub](help-fastapi.md#help-others-with-questions-in-github). 🙇
For a long time, answering questions from the community in GitHub Discussions was done by other community volunteers.
They have proven to be **FastAPI Experts** by helping many others. ✨
They proved they are **FastAPI Experts** by helping many others. ✨
/// tip
You could become an official FastAPI Expert too!
Just [help others with questions in GitHub](help-fastapi.md#help-others-with-questions-in-github). 🤓
///
You can see the **FastAPI Experts** for:
* [Last Month](#fastapi-experts-last-month) 🤓
* [3 Months](#fastapi-experts-3-months) 😎
* [6 Months](#fastapi-experts-6-months) 🧐
* [1 Year](#fastapi-experts-1-year) 🧑‍🔬
* [**All Time**](#fastapi-experts-all-time) 🧙
### FastAPI Experts - Last Month
These are the users that have been [helping others the most with questions in GitHub](help-fastapi.md#help-others-with-questions-in-github) during the last month. 🤓
Here's the hall of fame of the first FastAPI Experts:
<div class="user-list user-list-center">
{% for user in people.last_month_experts[:10] %}
{% for user in people.experts[:30] %}
{% if user.login not in skip_users %}
<div class="user"><a href="{{ user.url }}"><div class="avatar-wrapper"><img src="{{ user.avatarUrl }}"/></div><div class="title">@{{ user.login }}</div></a> <div class="count">Questions replied: {{ user.count }}</div></div>
{% endif %}
{% endfor %}
</div>
### FastAPI Experts - 3 Months
These are the users that have been [helping others the most with questions in GitHub](help-fastapi.md#help-others-with-questions-in-github) during the last 3 months. 😎
<div class="user-list user-list-center">
{% for user in people.three_months_experts[:10] %}
{% if user.login not in skip_users %}
<div class="user"><a href="{{ user.url }}"><div class="avatar-wrapper"><img src="{{ user.avatarUrl }}"/></div><div class="title">@{{ user.login }}</div></a> <div class="count">Questions replied: {{ user.count }}</div></div>
{% endif %}
{% endfor %}
</div>
### FastAPI Experts - 6 Months
These are the users that have been [helping others the most with questions in GitHub](help-fastapi.md#help-others-with-questions-in-github) during the last 6 months. 🧐
<div class="user-list user-list-center">
{% for user in people.six_months_experts[:10] %}
{% if user.login not in skip_users %}
<div class="user"><a href="{{ user.url }}"><div class="avatar-wrapper"><img src="{{ user.avatarUrl }}"/></div><div class="title">@{{ user.login }}</div></a> <div class="count">Questions replied: {{ user.count }}</div></div>
{% endif %}
{% endfor %}
</div>
### FastAPI Experts - 1 Year
These are the users that have been [helping others the most with questions in GitHub](help-fastapi.md#help-others-with-questions-in-github) during the last year. 🧑‍🔬
<div class="user-list user-list-center">
{% for user in people.one_year_experts[:20] %}
{% if user.login not in skip_users %}
<div class="user"><a href="{{ user.url }}"><div class="avatar-wrapper"><img src="{{ user.avatarUrl }}"/></div><div class="title">@{{ user.login }}</div></a> <div class="count">Questions replied: {{ user.count }}</div></div>
{% endif %}
{% endfor %}
</div>
### FastAPI Experts - All Time
Here are the all time **FastAPI Experts**. 🤓🤯
These are the users that have [helped others the most with questions in GitHub](help-fastapi.md#help-others-with-questions-in-github) through *all time*. 🧙
<div class="user-list user-list-center">
{% for user in people.experts[:50] %}
{% if user.login not in skip_users %}
{% if user.login not in skip_users.users %}
<div class="user"><a href="{{ user.url }}"><div class="avatar-wrapper"><img src="{{ user.avatarUrl }}"/></div><div class="title">@{{ user.login }}</div></a> <div class="count">Questions replied: {{ user.count }}</div></div>
@@ -183,17 +70,19 @@ These are the users that have [helped others the most with questions in GitHub](
## Top Contributors
Here are the **Top Contributors**. 👷
Currently, most of the code changes in FastAPI are done by the team.
These users have created the most Pull Requests that have been *merged*.
But over the years, there have also been many contributions made by others.
They have contributed source code, documentation, etc. 📦
They contributed source code, documentation, etc. 📦
Here's the hall of fame of the first **Top Contributors**. 👷
<div class="user-list user-list-center">
{% for user in (contributors.values() | list)[:50] %}
{% for user in (contributors.values() | list)[:30] %}
{% if user.login not in skip_users %}
{% if user.login not in skip_users.users %}
<div class="user"><a href="{{ user.url }}"><div class="avatar-wrapper"><img src="{{ user.avatarUrl }}"/></div><div class="title">@{{ user.login }}</div></a> <div class="count">Pull Requests: {{ user.count }}</div></div>
@@ -207,14 +96,16 @@ There are hundreds of other contributors, you can see them all in the [FastAPI G
## Top Translation Reviewers
These users are the **Top Translation Reviewers**. 🕵️
Currently, translations are done using AI tools, steered by the FastAPI team and native speakers.
Translation reviewers have the **power to approve translations** of the documentation. Without them, there wouldn't be documentation in several other languages.
At some point, FastAPI had some documentation pages that community members translated into other languages by hand.
Here's the hall of fame of the first **Top Translation Reviewers**. 🕵️
<div class="user-list user-list-center">
{% for user in (translation_reviewers.values() | list)[:50] %}
{% for user in (translation_reviewers.values() | list)[:30] %}
{% if user.login not in skip_users %}
{% if user.login not in skip_users.users %}
<div class="user"><a href="{{ user.url }}"><div class="avatar-wrapper"><img src="{{ user.avatarUrl }}"/></div><div class="title">@{{ user.login }}</div></a> <div class="count">Reviews: {{ user.count }}</div></div>
@@ -226,9 +117,7 @@ Translation reviewers have the **power to approve translations** of the document
## Sponsors
These are the **Sponsors**. 😎
They are supporting my work with **FastAPI** (and others), mainly through [GitHub Sponsors](https://github.com/sponsors/tiangolo).
**Sponsors** support **FastAPI** and friends, mainly through [GitHub Sponsors](https://github.com/sponsors/tiangolo).
{% if sponsors %}
@@ -283,12 +172,22 @@ They are supporting my work with **FastAPI** (and others), mainly through [GitHu
## About the data - technical details
The main intention of this page is to highlight the effort of the community to help others.
The main intention of this page has been to highlight the effort of the community to help others, especially efforts that were normally less visible and, in many cases, more arduous, like helping others with questions and reviewing Pull Requests with translations.
Especially including efforts that are normally less visible, and in many cases more arduous, like helping others with questions and reviewing Pull Requests with translations.
It also highlights contributions from sponsors.
The data is calculated each month, you can read the [source code here](https://github.com/fastapi/fastapi/blob/master/scripts/).
The data used to be calculated continuously, each month.
Here I'm also highlighting contributions from sponsors.
As of July 2026, most of the work has been done by (paid) team members for quite some time.
I also reserve the right to update the algorithm, sections, thresholds, etc (just in case 🤷).
GitHub Discussions are answered mostly by team members.
Most of the code changes are done by team members.
And translations are continuously done for the entire documentation in multiple languages, using AI tools, managed by team members.
Additionally, in recent months, there's been an overwhelming amount of AI spam, mainly to cheat the FastAPI Experts system or to get a PR merged by any means and thereby be considered a contributor. You can read more about the point of view in [Automated Code and AI](https://tiangolo.com/open-source/contributing/#automated-code-and-ai).
Because of this, the data for the FastAPI Experts, Top Contributors, and Top Translation Reviewers is no longer continuously updated.
This section is currently kept as a tribute to the humans that helped shape what FastAPI is today. 🙌
+3 -3
View File
@@ -19,7 +19,7 @@ Interactive API documentation and exploration web user interfaces. As the framew
![Swagger UI interaction](https://fastapi.tiangolo.com/img/index/index-03-swagger-02.png)
* Alternative API documentation with [**ReDoc**](https://github.com/Rebilly/ReDoc).
* Alternative API documentation with [**ReDoc**](https://github.com/Redocly/redoc).
![ReDoc](https://fastapi.tiangolo.com/img/index/index-06-redoc-02.png)
@@ -159,7 +159,7 @@ Any integration is designed to be so simple to use (with dependencies) that you
## Starlette features { #starlette-features }
**FastAPI** is fully compatible with (and based on) [**Starlette**](https://www.starlette.dev/). So, any additional Starlette code you have, will also work.
**FastAPI** is fully compatible with (and based on) [**Starlette**](https://starlette.dev/). So, any additional Starlette code you have, will also work.
`FastAPI` is actually a sub-class of `Starlette`. So, if you already know or use Starlette, most of the functionality will work the same way.
@@ -177,7 +177,7 @@ With **FastAPI** you get all of **Starlette**'s features (as FastAPI is just Sta
## Pydantic features { #pydantic-features }
**FastAPI** is fully compatible with (and based on) [**Pydantic**](https://docs.pydantic.dev/). So, any additional Pydantic code you have, will also work.
**FastAPI** is fully compatible with (and based on) [**Pydantic**](https://pydantic.dev/docs/). So, any additional Pydantic code you have, will also work.
Including external libraries also based on Pydantic, such as <abbr title="Object-Relational Mapper">ORM</abbr>s and <abbr title="Object-Document Mapper">ODM</abbr>s for databases.
+7 -15
View File
@@ -45,20 +45,6 @@ You can follow [me (Sebastián Ramírez / `tiangolo`)](https://tiangolo.com), th
* [@tiangolo.com on **Bluesky**](https://bsky.app/profile/tiangolo.com)
* [@tiangolo on **LinkedIn**](https://www.linkedin.com/in/tiangolo/).
## Help others with questions in GitHub { #help-others-with-questions-in-github }
You can try and help others with their questions in [GitHub Discussions](https://github.com/fastapi/fastapi/discussions/categories/questions?discussions_q=category%3AQuestions+is%3Aunanswered).
In many cases you might already know the answer for those questions. 🤓
If you are helping a lot of people with their questions, you will become an official [FastAPI Expert](fastapi-people.md#fastapi-experts). 🎉
Just remember, the most important point is: try to be kind. 🤗
### How to Help { #how-to-help }
Follow the [guide on how to help](https://tiangolo.com/open-source/help/#help-others-with-questions-in-github) here.
## Ask Questions { #ask-questions }
You can [create a new question](https://github.com/fastapi/fastapi/discussions/new?category=questions) in the GitHub repository, for example to:
@@ -68,7 +54,7 @@ You can [create a new question](https://github.com/fastapi/fastapi/discussions/n
## Join the Chat { #join-the-chat }
Join the 👥 [Discord chat server](https://discord.gg/VQjSZaeJmf) 👥 and hang out with others in the FastAPI community.
Join the 👥 [Discord chat server](https://discord.com/invite/VQjSZaeJmf) 👥 and hang out with others in the FastAPI community.
/// tip
@@ -85,3 +71,9 @@ Keep in mind that as chats allow more "free conversation", it's easy to ask ques
In GitHub, the template will guide you to write the right question so that you can more easily get a good answer, or even solve the problem yourself even before asking.
Conversations in the chat systems are also not as easily searchable as in GitHub, they get lost.
## Try FastAPI Cloud { #try-fastapi-cloud }
The main funding for FastAPI and friends comes from [**FastAPI Cloud**](https://fastapicloud.com), a platform to deploy FastAPI applications in a simple and fast way, with a single command, `fastapi deploy`.
FastAPI Cloud is built by the same team behind FastAPI. You can try it and consider it for your projects.
+2 -2
View File
@@ -54,11 +54,11 @@ All in a way that provided the best development experience for all the developer
## Requirements { #requirements }
After testing several alternatives, I decided that I was going to use [**Pydantic**](https://docs.pydantic.dev/) for its advantages.
After testing several alternatives, I decided that I was going to use [**Pydantic**](https://pydantic.dev/docs/) for its advantages.
Then I contributed to it, to make it fully compliant with JSON Schema, to support different ways to define constraint declarations, and to improve editor support (type checks, autocompletion) based on the tests in several editors.
During the development, I also contributed to [**Starlette**](https://www.starlette.dev/), the other key requirement.
During the development, I also contributed to [**Starlette**](https://starlette.dev/), the other key requirement.
## Development { #development }
@@ -66,7 +66,7 @@ The `scope` `dict` and `receive` function are both part of the ASGI specificatio
And those two things, `scope` and `receive`, are what is needed to create a new `Request` instance.
To learn more about the `Request` check [Starlette's docs about Requests](https://www.starlette.dev/requests/).
To learn more about the `Request` check [Starlette's docs about Requests](https://starlette.dev/requests/).
///
+1 -1
View File
@@ -45,7 +45,7 @@ The parameter `summary` is available in OpenAPI 3.1.0 and above, supported by Fa
Using the information above, you can use the same utility function to generate the OpenAPI schema and override each part that you need.
For example, let's add [ReDoc's OpenAPI extension to include a custom logo](https://github.com/Rebilly/ReDoc/blob/master/docs/redoc-vendor-extensions.md#x-logo).
For example, let's add [ReDoc's OpenAPI extension to include a custom logo](https://github.com/Redocly/redoc/blob/main/docs/redoc-vendor-extensions.md#x-logo).
### Normal **FastAPI** { #normal-fastapi }
+1 -1
View File
@@ -21,7 +21,7 @@ Here are some of the **GraphQL** libraries that have **ASGI** support. You could
* [Strawberry](https://strawberry.rocks/) 🍓
* With [docs for FastAPI](https://strawberry.rocks/docs/integrations/fastapi)
* [Ariadne](https://ariadnegraphql.org/)
* With [docs for FastAPI](https://ariadnegraphql.org/docs/fastapi-integration)
* With [docs for FastAPI](https://ariadnegraphql.org/server/Integrations/fastapi-integration)
* [Tartiflette](https://tartiflette.io/)
* With [Tartiflette ASGI](https://tartiflette.github.io/tartiflette-asgi/) to provide ASGI integration
* [Graphene](https://graphene-python.org/)
@@ -24,7 +24,7 @@ If you have an old FastAPI app with Pydantic v1, here I'll show you how to migra
## Official Guide { #official-guide }
Pydantic has an official [Migration Guide](https://docs.pydantic.dev/latest/migration/) from v1 to v2.
Pydantic has an official [Migration Guide](https://pydantic.dev/docs/validation/latest/get-started/migration/) from v1 to v2.
It also includes what has changed, how validations are now more correct and strict, possible caveats, etc.
+19 -17
View File
@@ -110,7 +110,7 @@ The key features are:
</div>
<div class="fastapi-opinions__panel" id="fo-panel-uber" role="tabpanel" aria-labelledby="fo-tab-uber" tabindex="0" hidden>
<blockquote class="fastapi-opinions__quote">"We adopted the <strong>FastAPI</strong> library to spawn a <strong>REST</strong> server that can be queried to obtain <strong>predictions</strong>." <em>[for Ludwig]</em></blockquote>
<div class="fastapi-opinions__attr">— Piero Molino, Yaroslav Dudin, Sai Sumanth Miryala, <strong>Uber</strong> <a href="https://eng.uber.com/ludwig-v0-2/">(ref)</a></div>
<div class="fastapi-opinions__attr">— Piero Molino, Yaroslav Dudin, Sai Sumanth Miryala, <strong>Uber</strong> <a href="https://www.uber.com/us/en/blog/ludwig-v0-2/">(ref)</a></div>
</div>
<div class="fastapi-opinions__panel" id="fo-panel-netflix" role="tabpanel" aria-labelledby="fo-tab-netflix" tabindex="0" hidden>
<blockquote class="fastapi-opinions__quote">"<strong>Netflix</strong> is pleased to announce the open-source release of our <strong>crisis management</strong> orchestration framework: <strong>Dispatch</strong>!" <em>[built with FastAPI]</em></blockquote>
@@ -133,7 +133,7 @@ The key features are:
"_We adopted the **FastAPI** library to spawn a **REST** server that can be queried to obtain **predictions**. [for Ludwig]_"
<div style="text-align: right; margin-right: 10%;">Piero Molino, Yaroslav Dudin, and Sai Sumanth Miryala - <strong>Uber</strong> <a href="https://eng.uber.com/ludwig-v0-2/"><small>(ref)</small></a></div>
<div style="text-align: right; margin-right: 10%;">Piero Molino, Yaroslav Dudin, and Sai Sumanth Miryala - <strong>Uber</strong> <a href="https://www.uber.com/us/en/blog/ludwig-v0-2/"><small>(ref)</small></a></div>
---
@@ -175,17 +175,17 @@ If you are building a <abbr title="Command Line Interface">CLI</abbr> app to be
FastAPI stands on the shoulders of giants:
* [Starlette](https://www.starlette.dev/) for the web parts.
* [Pydantic](https://docs.pydantic.dev/) for the data parts.
* [Starlette](https://starlette.dev/) for the web parts.
* [Pydantic](https://pydantic.dev/docs/) for the data parts.
## Installation { #installation }
Create and activate a [virtual environment](https://fastapi.tiangolo.com/virtual-environments/) and then install FastAPI:
First, [install `uv`](https://docs.astral.sh/uv/getting-started/installation/), and then add FastAPI to your project:
<div class="termy">
```console
$ pip install "fastapi[standard]"
$ uv add "fastapi[standard]"
---> 100%
```
@@ -194,6 +194,8 @@ $ pip install "fastapi[standard]"
**Note**: Make sure you put `"fastapi[standard]"` in quotes to ensure it works in all terminals.
If you prefer to use `pip`, install `fastapi[standard]` inside a virtual environment. See the [installation guide](tutorial/#install-fastapi) for the alternative steps.
## Example { #example }
### Create it { #create-it }
@@ -250,7 +252,7 @@ Run the server with:
<div class="termy">
```console
$ fastapi dev
$ uv run fastapi dev
╭────────── FastAPI CLI - Development mode ───────────╮
│ │
@@ -277,7 +279,7 @@ INFO: Application startup complete.
<details markdown="1">
<summary>About the command <code>fastapi dev</code>...</summary>
The command `fastapi dev` reads your `main.py` file automatically, detects the **FastAPI** app in it, and starts a server using [Uvicorn](https://www.uvicorn.dev).
The command `fastapi dev` reads your `main.py` file automatically, detects the **FastAPI** app in it, and starts a server using [Uvicorn](https://uvicorn.dev).
By default, `fastapi dev` will start with auto-reload enabled for local development.
@@ -314,7 +316,7 @@ You will see the automatic interactive API documentation (provided by [Swagger U
And now, go to [http://127.0.0.1:8000/redoc](http://127.0.0.1:8000/redoc).
You will see the alternative automatic documentation (provided by [ReDoc](https://github.com/Rebilly/ReDoc)):
You will see the alternative automatic documentation (provided by [ReDoc](https://github.com/Redocly/redoc)):
![ReDoc](https://fastapi.tiangolo.com/img/index/index-02-redoc-simple.png)
@@ -497,7 +499,7 @@ You can optionally deploy your FastAPI app to [FastAPI Cloud](https://fastapiclo
<div class="termy">
```console
$ fastapi deploy
$ uv run fastapi deploy
Deploying to FastAPI Cloud...
@@ -540,7 +542,7 @@ FastAPI depends on Pydantic and Starlette.
### `standard` Dependencies { #standard-dependencies }
When you install FastAPI with `pip install "fastapi[standard]"` it comes with the `standard` group of optional dependencies:
When you install FastAPI with `uv add "fastapi[standard]"` it comes with the `standard` group of optional dependencies:
Used by Pydantic:
@@ -554,17 +556,17 @@ Used by Starlette:
Used by FastAPI:
* [`uvicorn`](https://www.uvicorn.dev) - for the server that loads and serves your application. This includes `uvicorn[standard]`, which includes some dependencies (e.g. `uvloop`) needed for high performance serving.
* [`uvicorn`](https://uvicorn.dev) - for the server that loads and serves your application. This includes `uvicorn[standard]`, which includes some dependencies (e.g. `uvloop`) needed for high performance serving.
* `fastapi-cli[standard]` - to provide the `fastapi` command.
* This includes `fastapi-cloud-cli`, which allows you to deploy your FastAPI application to [FastAPI Cloud](https://fastapicloud.com).
### Without `standard` Dependencies { #without-standard-dependencies }
If you don't want to include the `standard` optional dependencies, you can install with `pip install fastapi` instead of `pip install "fastapi[standard]"`.
If you don't want to include the `standard` optional dependencies, you can install with `uv add fastapi` instead of `uv add "fastapi[standard]"`.
### Without `fastapi-cloud-cli` { #without-fastapi-cloud-cli }
If you want to install FastAPI with the standard dependencies but without the `fastapi-cloud-cli`, you can install with `pip install "fastapi[standard-no-fastapi-cloud-cli]"`.
If you want to install FastAPI with the standard dependencies but without the `fastapi-cloud-cli`, you can install with `uv add "fastapi[standard-no-fastapi-cloud-cli]"`.
### Additional Optional Dependencies { #additional-optional-dependencies }
@@ -572,13 +574,13 @@ There are some additional dependencies you might want to install.
Additional optional Pydantic dependencies:
* [`pydantic-settings`](https://docs.pydantic.dev/latest/usage/pydantic_settings/) - for settings management.
* [`pydantic-extra-types`](https://docs.pydantic.dev/latest/usage/types/extra_types/extra_types/) - for extra types to be used with Pydantic.
* [`pydantic-settings`](https://pydantic.dev/docs/validation/latest/concepts/pydantic_settings/) - for settings management.
* [`pydantic-extra-types`](https://github.com/pydantic/pydantic-extra-types) - for extra types to be used with Pydantic.
Additional optional FastAPI dependencies:
* [`orjson`](https://github.com/ijl/orjson) - Required if you want to use `ORJSONResponse`.
* [`ujson`](https://github.com/esnme/ultrajson) - Required if you want to use `UJSONResponse`.
* [`ujson`](https://github.com/ultrajson/ultrajson) - Required if you want to use `UJSONResponse`.
## License { #license }
+10 -8
View File
@@ -127,27 +127,29 @@ class Termynal {
}
generateRestart() {
const restart = document.createElement('a')
restart.onclick = (e) => {
e.preventDefault()
const restart = document.createElement('button')
restart.type = 'button'
restart.onclick = () => {
this.container.innerHTML = ''
this.init()
}
restart.href = "javascript:void(0)"
restart.setAttribute('data-terminal-control', '')
restart.innerHTML = "restart ↻"
return restart
}
generateFinish() {
const finish = document.createElement('a')
finish.onclick = (e) => {
e.preventDefault()
const finish = document.createElement('button')
finish.type = 'button'
finish.onclick = () => {
this.lineDelay = 0
this.typeDelay = 0
this.startDelay = 0
}
finish.href = "javascript:void(0)"
finish.setAttribute('data-terminal-control', '')
finish.innerHTML = "fast →"
this.finishElement = finish
-10
View File
@@ -13,13 +13,3 @@ I normally give the final review to each PR before merging them. I make the fina
There's a team of people that help manage and maintain the project. 😎
Learn more about it in [tiangolo.com - GitHub FastAPI](https://tiangolo.com/github-fastapi/).
## FastAPI Experts
The people that help others the most in GitHub Discussions can become [**FastAPI Experts**](./fastapi-people.md#fastapi-experts).
This is normally the best way to contribute to the project.
## External Help
External help is very much appreciated. There are many ways to [help](./help-fastapi.md). ☕️
+2 -2
View File
@@ -4,13 +4,13 @@ Templates, while they typically come with a specific setup, are designed to be f
You can use this template to get started, as it includes a lot of the initial setup, security, database and some API endpoints already done for you.
GitHub Repository: [Full Stack FastAPI Template](https://github.com/tiangolo/full-stack-fastapi-template)
GitHub Repository: [Full Stack FastAPI Template](https://github.com/fastapi/full-stack-fastapi-template)
## Full Stack FastAPI Template - Technology Stack and Features { #full-stack-fastapi-template-technology-stack-and-features }
- ⚡ [**FastAPI**](https://fastapi.tiangolo.com) for the Python backend API.
- 🧰 [SQLModel](https://sqlmodel.tiangolo.com) for the Python SQL database interactions (ORM).
- 🔍 [Pydantic](https://docs.pydantic.dev), used by FastAPI, for the data validation and settings management.
- 🔍 [Pydantic](https://pydantic.dev/docs/), used by FastAPI, for the data validation and settings management.
- 💾 [PostgreSQL](https://www.postgresql.org) as the SQL database.
- 🚀 [React](https://react.dev) for the frontend.
- 💃 Using TypeScript, hooks, Vite, and other parts of a modern frontend stack.
+2 -2
View File
@@ -269,7 +269,7 @@ It doesn't mean "`one_person` is the **class** called `Person`".
## Pydantic models { #pydantic-models }
[Pydantic](https://docs.pydantic.dev/) is a Python library to perform data validation.
[Pydantic](https://pydantic.dev/docs/) is a Python library to perform data validation.
You declare the "shape" of the data as classes with attributes.
@@ -285,7 +285,7 @@ An example from the official Pydantic docs:
/// note
To learn more about [Pydantic, check its docs](https://docs.pydantic.dev/).
To learn more about [Pydantic, check its docs](https://pydantic.dev/docs/).
///
+17
View File
@@ -0,0 +1,17 @@
# Server-Sent Events - `EventSourceResponse` and `ServerSentEvent`
To stream Server-Sent Events (SSE), use `yield` in your *path operation function* and set `response_class=EventSourceResponse`.
If you need to set SSE fields like `event`, `id`, `retry`, or `comment`, you can `yield` `ServerSentEvent` objects instead of plain data.
Read more about it in the [FastAPI docs for Server-Sent Events (SSE)](https://fastapi.tiangolo.com/tutorial/server-sent-events/).
You can import them directly from `fastapi.sse`:
```python
from fastapi.sse import EventSourceResponse, ServerSentEvent
```
::: fastapi.sse.EventSourceResponse
::: fastapi.sse.ServerSentEvent
+209 -2
View File
@@ -7,14 +7,221 @@ hide:
## Latest Changes
### Docs
* 🐛 Use buttons for Termynal controls. PR [#16132](https://github.com/fastapi/fastapi/pull/16132) by [@tiangolo](https://github.com/tiangolo).
### Translations
* 🌐 Update translations for ko (update-outdated). PR [#16171](https://github.com/fastapi/fastapi/pull/16171) by [@pr-submit[bot]](https://github.com/apps/pr-submit).
### Internal
* 👷 Remove legacy label check. PR [#16180](https://github.com/fastapi/fastapi/pull/16180) by [@tiangolo](https://github.com/tiangolo).
* ⬆ Bump pymdown-extensions from 11.0 to 11.0.1. PR [#16162](https://github.com/fastapi/fastapi/pull/16162) by [@dependabot[bot]](https://github.com/apps/dependabot).
* ⬆ Bump gitpython from 3.1.57 to 3.1.58. PR [#16157](https://github.com/fastapi/fastapi/pull/16157) by [@dependabot[bot]](https://github.com/apps/dependabot).
* 👥 Update FastAPI People - Sponsors. PR [#16175](https://github.com/fastapi/fastapi/pull/16175) by [@pr-submit[bot]](https://github.com/apps/pr-submit).
* 🐛 Fix Sponsors Git authentication. PR [#16174](https://github.com/fastapi/fastapi/pull/16174) by [@tiangolo](https://github.com/tiangolo).
* 👥 Update FastAPI GitHub topic repositories. PR [#16173](https://github.com/fastapi/fastapi/pull/16173) by [@pr-submit[bot]](https://github.com/apps/pr-submit).
* 🔐 Use PR Submit for automated updates. PR [#16172](https://github.com/fastapi/fastapi/pull/16172) by [@tiangolo](https://github.com/tiangolo).
* 🔐 Use PR Submit for translations. PR [#16168](https://github.com/fastapi/fastapi/pull/16168) by [@tiangolo](https://github.com/tiangolo).
* ⬆️ Raise pytest-xdist minimum. PR [#16170](https://github.com/fastapi/fastapi/pull/16170) by [@tiangolo](https://github.com/tiangolo).
* 🔐 Use PR Submit for pull requests. PR [#16167](https://github.com/fastapi/fastapi/pull/16167) by [@tiangolo](https://github.com/tiangolo).
* 👷 Use GitHub CLI for Git authentication. PR [#16166](https://github.com/fastapi/fastapi/pull/16166) by [@tiangolo](https://github.com/tiangolo).
* 👷 Use PR Push commit identity. PR [#16164](https://github.com/fastapi/fastapi/pull/16164) by [@tiangolo](https://github.com/tiangolo).
* 🔒 Replace pre-commit PAT with PR Push. PR [#16161](https://github.com/fastapi/fastapi/pull/16161) by [@tiangolo](https://github.com/tiangolo).
* 👷 Disable saving Zensical's `.cache` in `build-docs.yml`. PR [#16156](https://github.com/fastapi/fastapi/pull/16156) by [@YuriiMotov](https://github.com/YuriiMotov).
* 🔥 Remove the old Latest Changes workflow. PR [#16148](https://github.com/fastapi/fastapi/pull/16148) by [@tiangolo](https://github.com/tiangolo).
* ⬆ Bump the python-packages group with 12 updates. PR [#16121](https://github.com/fastapi/fastapi/pull/16121) by [@dependabot[bot]](https://github.com/apps/dependabot).
* ⬆ Bump cryptography from 48.0.1 to 50.0.0. PR [#16142](https://github.com/fastapi/fastapi/pull/16142) by [@dependabot[bot]](https://github.com/apps/dependabot).
* ⬆ Bump gitpython from 3.1.54 to 3.1.57. PR [#16141](https://github.com/fastapi/fastapi/pull/16141) by [@dependabot[bot]](https://github.com/apps/dependabot).
* ⬆ Bump the github-actions group with 6 updates. PR [#16120](https://github.com/fastapi/fastapi/pull/16120) by [@dependabot[bot]](https://github.com/apps/dependabot).
* 👥 Update FastAPI GitHub topic repositories. PR [#16122](https://github.com/fastapi/fastapi/pull/16122) by [@tiangolo](https://github.com/tiangolo).
* 👥 Update FastAPI People - Sponsors. PR [#16119](https://github.com/fastapi/fastapi/pull/16119) by [@tiangolo](https://github.com/tiangolo).
## 0.141.1 (2026-07-29)
### Fixes
* 🐛 Fix support for background tasks and headers from dependencies in `app.frontend()`. PR [#16105](https://github.com/fastapi/fastapi/pull/16105) by [@tiangolo](https://github.com/tiangolo).
### Docs
* 📝 Document `FASTAPI_ENV` in FastAPI CLI guide. PR [#16104](https://github.com/fastapi/fastapi/pull/16104) by [@tiangolo](https://github.com/tiangolo).
## 0.141.0 (2026-07-29)
### Features
* ✨ Add `app.frontend(check_dir="auto")`, to make local development more convenient with `fastapi dev`. PR [#16102](https://github.com/fastapi/fastapi/pull/16102) by [@tiangolo](https://github.com/tiangolo).
## 0.140.13 (2026-07-28)
### Fixes
* 🐛 Fix `status_code` being ignored for SSE and JSONL streaming endpoints. PR [#15937](https://github.com/fastapi/fastapi/pull/15937) by [@SAURABHSALVE](https://github.com/SAURABHSALVE).
### Docs
* 📝 Fix `format_sse_event` docstring rendering of `\n\n` terminator. PR [#15613](https://github.com/fastapi/fastapi/pull/15613) by [@AshNicolus](https://github.com/AshNicolus).
* 📝 Add API reference page for fastapi.sse. PR [#15930](https://github.com/fastapi/fastapi/pull/15930) by [@SAURABHSALVE](https://github.com/SAURABHSALVE).
## 0.140.12 (2026-07-28)
### Fixes
* 🐛 Fix line splitting in `format_sse_event` to comply with SSE spec. PR [#15515](https://github.com/fastapi/fastapi/pull/15515) by [@Zawwarsami16](https://github.com/Zawwarsami16).
## 0.140.11 (2026-07-28)
### Fixes
* 🐛 Fix `response_model_*` params ignored for non-generator endpoints with `Iterable[..]` return type. PR [#15093](https://github.com/fastapi/fastapi/pull/15093) by [@YuriiMotov](https://github.com/YuriiMotov).
## 0.140.10 (2026-07-28)
### Fixes
* 🐛 Fix handling sequences with nested Annotated types. PR [#14874](https://github.com/fastapi/fastapi/pull/14874) by [@YuriiMotov](https://github.com/YuriiMotov).
### Internal
* 🐛 Accept any base test failure as regression. PR [#16092](https://github.com/fastapi/fastapi/pull/16092) by [@tiangolo](https://github.com/tiangolo).
* 🐛 Preserve pytest exit code in regression check. PR [#16091](https://github.com/fastapi/fastapi/pull/16091) by [@tiangolo](https://github.com/tiangolo).
* ✅ Test PR regressions against base code. PR [#16090](https://github.com/fastapi/fastapi/pull/16090) by [@tiangolo](https://github.com/tiangolo).
## 0.140.9 (2026-07-28)
### Fixes
* 🐛 Fix `exclude_defaults` not propagated to dict keys and values in `jsonable_encoder`. PR [#16043](https://github.com/fastapi/fastapi/pull/16043) by [@MBGrao](https://github.com/MBGrao).
### Internal
* ⬆ Bump gitpython from 3.1.50 to 3.1.54. PR [#16047](https://github.com/fastapi/fastapi/pull/16047) by [@dependabot[bot]](https://github.com/apps/dependabot).
* ⬆ Bump pymdown-extensions from 10.21.3 to 11.0. PR [#16048](https://github.com/fastapi/fastapi/pull/16048) by [@dependabot[bot]](https://github.com/apps/dependabot).
* ⬆ Bump pyasn1 from 0.6.3 to 0.6.4. PR [#16045](https://github.com/fastapi/fastapi/pull/16045) by [@dependabot[bot]](https://github.com/apps/dependabot).
## 0.140.8 (2026-07-28)
### Fixes
* 🐛 Fix stream item type lost when using `include_router()`. PR [#15077](https://github.com/fastapi/fastapi/pull/15077) by [@alex-raw](https://github.com/alex-raw).
## 0.140.7 (2026-07-27)
### Refactors
* ⚡️ Avoid flattening dependencies for OpenAPI. PR [#16076](https://github.com/fastapi/fastapi/pull/16076) by [@tiangolo](https://github.com/tiangolo).
### Internal
* ⬆️ Upgrade latest-changes to 0.7.1. PR [#16077](https://github.com/fastapi/fastapi/pull/16077) by [@tiangolo](https://github.com/tiangolo).
* 👷 Add OpenAPI dependency benchmarks. PR [#16075](https://github.com/fastapi/fastapi/pull/16075) by [@tiangolo](https://github.com/tiangolo).
## 0.140.6 (2026-07-27)
### Refactors
* ⚡️ Avoid flattening dependencies for request parameters, mainly for OpenAPI. PR [#16073](https://github.com/fastapi/fastapi/pull/16073) by [@tiangolo](https://github.com/tiangolo).
## 0.140.5 (2026-07-27)
### Refactors
* ⚡️ Avoid flattening dependencies for body fields. PR [#16071](https://github.com/fastapi/fastapi/pull/16071) by [@tiangolo](https://github.com/tiangolo).
## 0.140.4 (2026-07-27)
### Refactors
* ⚡️ Skip unused dependency repeat bookkeeping. PR [#16069](https://github.com/fastapi/fastapi/pull/16069) by [@tiangolo](https://github.com/tiangolo).
## 0.140.3 (2026-07-27)
### Refactors
* ⚡️ Avoid repeated dependency flattening in OpenAPI. PR [#16067](https://github.com/fastapi/fastapi/pull/16067) by [@tiangolo](https://github.com/tiangolo).
## 0.140.2 (2026-07-27)
### Refactors
* ⚡️ Stop retaining flat dependency trees. PR [#16065](https://github.com/fastapi/fastapi/pull/16065) by [@tiangolo](https://github.com/tiangolo).
### Internal
* 👷 Add new memory benchmark. PR [#16064](https://github.com/fastapi/fastapi/pull/16064) by [@tiangolo](https://github.com/tiangolo).
## 0.140.1 (2026-07-27)
### Refactors
* ♻️ Update the lru_cache limit for dependencies to account for large apps. PR [#16062](https://github.com/fastapi/fastapi/pull/16062) by [@tiangolo](https://github.com/tiangolo).
## 0.140.0 (2026-07-24)
### Refactors
* ⚡️ Reduce memory usage in dependencies. PR [#16049](https://github.com/fastapi/fastapi/pull/16049) by [@tiangolo](https://github.com/tiangolo).
### Docs
* 📝 Fix links in docs. PR [#15967](https://github.com/fastapi/fastapi/pull/15967) by [@YuriiMotov](https://github.com/YuriiMotov).
* 📝 Add Library Skills documentation. PR [#16041](https://github.com/fastapi/fastapi/pull/16041) by [@tiangolo](https://github.com/tiangolo).
* 📝 Update docs to use uv projects by default. PR [#16032](https://github.com/fastapi/fastapi/pull/16032) by [@tiangolo](https://github.com/tiangolo).
* 📝 Restructure FastAPI People and related pages. PR [#16015](https://github.com/fastapi/fastapi/pull/16015) by [@tiangolo](https://github.com/tiangolo).
### Internal
* 👷 Add CI memory benchmark. PR [#16046](https://github.com/fastapi/fastapi/pull/16046) by [@tiangolo](https://github.com/tiangolo).
* 👥 Update FastAPI People - Sponsors. PR [#16027](https://github.com/fastapi/fastapi/pull/16027) by [@tiangolo](https://github.com/tiangolo).
* 🔥 Remove now-obsolete scripts to generate data for FastAPI People. PR [#16016](https://github.com/fastapi/fastapi/pull/16016) by [@tiangolo](https://github.com/tiangolo).
## 0.139.2 (2026-07-16)
### Fixes
* 🐛 Refactor router route building to make it thread-safe, mainly relevant for tests running in parallel threads (uncommon). PR [#16013](https://github.com/fastapi/fastapi/pull/16013) by [@tiangolo](https://github.com/tiangolo).
## 0.139.1 (2026-07-16)
### Fixes
* 🐛 Fix frontend fallback support for doted paths like `/users/john.doe`. PR [#16011](https://github.com/fastapi/fastapi/pull/16011) by [@tiangolo](https://github.com/tiangolo).
### Docs
* 📝 Fix topic repository list not being displayed and `skip_users` not being applied. PR [#15995](https://github.com/fastapi/fastapi/pull/15995) by [@YuriiMotov](https://github.com/YuriiMotov).
### Translations
* 🌐 Update translations for tr (update-outdated). PR [#16005](https://github.com/fastapi/fastapi/pull/16005) by [@tiangolo](https://github.com/tiangolo).
* 🌐 Update translations for zh-hant (update-outdated). PR [#15996](https://github.com/fastapi/fastapi/pull/15996) by [@tiangolo](https://github.com/tiangolo).
* 🌐 Update translations for fr (update-outdated). PR [#16006](https://github.com/fastapi/fastapi/pull/16006) by [@tiangolo](https://github.com/tiangolo).
* 🌐 Update translations for de (update-outdated). PR [#15999](https://github.com/fastapi/fastapi/pull/15999) by [@tiangolo](https://github.com/tiangolo).
* 🌐 Update translations for ko (update-outdated). PR [#16004](https://github.com/fastapi/fastapi/pull/16004) by [@tiangolo](https://github.com/tiangolo).
* 🌐 Update translations for zh (update-outdated). PR [#16001](https://github.com/fastapi/fastapi/pull/16001) by [@tiangolo](https://github.com/tiangolo).
* 🌐 Update translations for uk (update-outdated). PR [#16003](https://github.com/fastapi/fastapi/pull/16003) by [@tiangolo](https://github.com/tiangolo).
* 🌐 Update translations for ja (update-outdated). PR [#15998](https://github.com/fastapi/fastapi/pull/15998) by [@tiangolo](https://github.com/tiangolo).
* 🌐 Update translations for pt (update-outdated). PR [#16000](https://github.com/fastapi/fastapi/pull/16000) by [@tiangolo](https://github.com/tiangolo).
* 🌐 Update translations for es (update-outdated). PR [#15997](https://github.com/fastapi/fastapi/pull/15997) by [@tiangolo](https://github.com/tiangolo).
* 🌐 Update translations for ru (update-outdated). PR [#16002](https://github.com/fastapi/fastapi/pull/16002) by [@tiangolo](https://github.com/tiangolo).
* 🌐 Update translations for hi (add-missing). PR [#15990](https://github.com/fastapi/fastapi/pull/15990) by [@tiangolo](https://github.com/tiangolo).
* 🌐 Update translations for hi (add-missing). PR [#15925](https://github.com/fastapi/fastapi/pull/15925) by [@tiangolo](https://github.com/tiangolo).
* 🌐 Update translations for hi (add-missing). PR [#15797](https://github.com/fastapi/fastapi/pull/15797) by [@tiangolo](https://github.com/tiangolo).
* 🌐 Update `llm-prompt.md` for Hindi. PR [#15810](https://github.com/fastapi/fastapi/pull/15810) by [@YuriiMotov](https://github.com/YuriiMotov).
* 🌐 Fix language-specific translation prompt for Russian language. PR [#15924](https://github.com/fastapi/fastapi/pull/15924) by [@YuriiMotov](https://github.com/YuriiMotov).
### Internal
* ⬆ Bump the python-packages group across 1 directory with 6 updates. PR [#15981](https://github.com/fastapi/fastapi/pull/15981) by [@dependabot[bot]](https://github.com/apps/dependabot).
* ⬆ Bump typing-extensions from 4.15.0 to 4.16.0. PR [#15982](https://github.com/fastapi/fastapi/pull/15982) by [@dependabot[bot]](https://github.com/apps/dependabot).
* ⬆ Bump the github-actions group across 1 directory with 4 updates. PR [#15983](https://github.com/fastapi/fastapi/pull/15983) by [@dependabot[bot]](https://github.com/apps/dependabot).
* ⬆ Bump pre-commit hooks. PR [#15985](https://github.com/fastapi/fastapi/pull/15985) by [@tiangolo](https://github.com/tiangolo).
* 👷 Use `FASTAPI_LATEST_CHANGES` token in `bump-pre-commit-hooks` workflow. PR [#15984](https://github.com/fastapi/fastapi/pull/15984) by [@YuriiMotov](https://github.com/YuriiMotov).
* 👷 Add GH workflow to bump pre-commit hook versions. PR [#15873](https://github.com/fastapi/fastapi/pull/15873) by [@YuriiMotov](https://github.com/YuriiMotov).
* 🔧 Set Dependabot schedule interval to "monthly". PR [#15874](https://github.com/fastapi/fastapi/pull/15874) by [@YuriiMotov](https://github.com/YuriiMotov).
* ⬆ Bump CodSpeedHQ/action from 4.17.6 to 4.18.1 in the github-actions group. PR [#15950](https://github.com/fastapi/fastapi/pull/15950) by [@dependabot[bot]](https://github.com/apps/dependabot).
* ⬆ Bump the python-packages group with 8 updates. PR [#15952](https://github.com/fastapi/fastapi/pull/15952) by [@dependabot[bot]](https://github.com/apps/dependabot).
* 🔧 Update sponsors: add TutorCruncher. PR [#15947](https://github.com/fastapi/fastapi/pull/15947) by [@tiangolo](https://github.com/tiangolo).
@@ -4048,7 +4255,7 @@ There are **tests for both Pydantic v1 and v2**, and test **coverage** is kept a
* The attribute `schema_extra` for the internal class `Config` has been replaced by the key `json_schema_extra` in the new `model_config` dict.
* You can read more about it in the docs for [Declare Request Example Data](https://fastapi.tiangolo.com/tutorial/schema-extra-example/).
* When you install `"fastapi[all]"` it now also includes:
* [`pydantic-settings`](https://docs.pydantic.dev/latest/usage/pydantic_settings/) - for settings management.
* [`pydantic-settings`](https://pydantic.dev/docs/validation/latest/concepts/pydantic_settings/) - for settings management.
* [`pydantic-extra-types`](https://docs.pydantic.dev/latest/usage/types/extra_types/extra_types/) - for extra types to be used with Pydantic.
* Now Pydantic Settings is an additional optional package (included in `"fastapi[all]"`). To use settings you should now import `from pydantic_settings import BaseSettings` instead of importing from `pydantic` directly.
* You can read more about it in the docs for [Settings and Environment Variables](https://fastapi.tiangolo.com/advanced/settings/).
@@ -6856,7 +7063,7 @@ Note: all the previous parameters are still there, so it's still possible to dec
* Upgrade the compatible version of Starlette to `0.12.0`.
* This includes support for ASGI 3 (the latest version of the standard).
* It's now possible to use [Starlette's `StreamingResponse`](https://www.starlette.dev/responses/#streamingresponse) with iterators, like [file-like](https://docs.python.org/3/glossary.html#term-file-like-object) objects (as those returned by `open()`).
* It's now possible to use [Starlette's `StreamingResponse`](https://starlette.dev/responses/#streamingresponse) with iterators, like [file-like](https://docs.python.org/3/glossary.html#term-file-like-object) objects (as those returned by `open()`).
* It's now possible to use the low level utility `iterate_in_threadpool` from `starlette.concurrency` (for advanced scenarios).
* PR [#243](https://github.com/tiangolo/fastapi/pull/243).
+2 -2
View File
@@ -63,7 +63,7 @@ And then another background task generated at the *path operation function* will
## Technical Details { #technical-details }
The class `BackgroundTasks` comes directly from [`starlette.background`](https://www.starlette.dev/background/).
The class `BackgroundTasks` comes directly from [`starlette.background`](https://starlette.dev/background/).
It is imported/included directly into FastAPI so that you can import it from `fastapi` and avoid accidentally importing the alternative `BackgroundTask` (without the `s` at the end) from `starlette.background`.
@@ -71,7 +71,7 @@ By only using `BackgroundTasks` (and not `BackgroundTask`), it's then possible t
It's still possible to use `BackgroundTask` alone in FastAPI, but you have to create the object in your code and return a Starlette `Response` including it.
You can see more details in [Starlette's official docs for Background Tasks](https://www.starlette.dev/background/).
You can see more details in [Starlette's official docs for Background Tasks](https://starlette.dev/background/).
## Caveat { #caveat }
+2 -2
View File
@@ -487,7 +487,7 @@ That way the `fastapi` command will know where to find your app.
You could also pass the path to the command, like:
```console
$ fastapi dev app/main.py
$ uv run fastapi dev app/main.py
```
But you would have to remember to pass the correct path every time you call the `fastapi` command.
@@ -503,7 +503,7 @@ Now, run your app:
<div class="termy">
```console
$ fastapi dev
$ uv run fastapi dev
<span style="color: green;">INFO</span>: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit)
```
+1 -1
View File
@@ -96,7 +96,7 @@ Again, doing just that declaration, with **FastAPI** you get:
Apart from normal singular types like `str`, `int`, `float`, etc. you can use more complex singular types that inherit from `str`.
To see all the options you have, check out [Pydantic's Type Overview](https://docs.pydantic.dev/latest/concepts/types/). You will see some examples in the next chapter.
To see all the options you have, check out [Pydantic's Type Overview](https://pydantic.dev/docs/validation/latest/concepts/types/). You will see some examples in the next chapter.
For example, as in the `Image` model we have a `url` field, we can declare it to be an instance of Pydantic's `HttpUrl` instead of a `str`:
+1 -1
View File
@@ -6,7 +6,7 @@ A **request** body is data sent by the client to your API. A **response** body i
Your API almost always has to send a **response** body. But clients don't necessarily need to send **request bodies** all the time, sometimes they only request a path, maybe with some query parameters, but don't send a body.
To declare a **request** body, you use [Pydantic](https://docs.pydantic.dev/) models with all their power and benefits.
To declare a **request** body, you use [Pydantic](https://pydantic.dev/docs/) models with all their power and benefits.
/// note
+2 -2
View File
@@ -15,7 +15,7 @@ The main purpose of the `__name__ == "__main__"` is to have some code that is ex
<div class="termy">
```console
$ python myapp.py
$ uv run python myapp.py
```
</div>
@@ -35,7 +35,7 @@ If you run it with:
<div class="termy">
```console
$ python myapp.py
$ uv run python myapp.py
```
</div>
+2 -2
View File
@@ -36,7 +36,7 @@ Here are some of the additional data types you can use:
* `datetime.timedelta`:
* A Python `datetime.timedelta`.
* In requests and responses will be represented as a `float` of total seconds.
* Pydantic also allows representing it as an "ISO 8601 time diff encoding", [see the docs for more info](https://docs.pydantic.dev/latest/concepts/serialization/#custom-serializers).
* Pydantic also allows representing it as an "ISO 8601 time diff encoding", [see the docs for more info](https://pydantic.dev/docs/validation/latest/concepts/serialization/#custom-serializers).
* `frozenset`:
* In requests and responses, treated the same as a `set`:
* In requests, a list will be read, eliminating duplicates and converting it to a `set`.
@@ -49,7 +49,7 @@ Here are some of the additional data types you can use:
* `Decimal`:
* Standard Python `Decimal`.
* In requests and responses, handled the same as a `float`.
* You can check all the valid Pydantic data types here: [Pydantic data types](https://docs.pydantic.dev/latest/usage/types/types/).
* You can check all the valid Pydantic data types here: [Pydantic data types](https://pydantic.dev/docs/validation/latest/concepts/types/).
## Example { #example }
+1 -1
View File
@@ -166,7 +166,7 @@ To do that, use the standard Python type hint [`typing.Union`](https://docs.pyth
/// note
When defining a [`Union`](https://docs.pydantic.dev/latest/concepts/types/#unions), include the most specific type first, followed by the less specific type. In the example below, the more specific `PlaneItem` comes before `CarItem` in `Union[PlaneItem, CarItem]`.
When defining a [`Union`](https://pydantic.dev/docs/validation/latest/concepts/unions/), include the most specific type first, followed by the less specific type. In the example below, the more specific `PlaneItem` comes before `CarItem` in `Union[PlaneItem, CarItem]`.
///
+12 -6
View File
@@ -6,12 +6,18 @@ The simplest FastAPI file could look like this:
Copy that to a file `main.py`.
/// tip
FastAPI has an [official extension for VS Code](https://marketplace.visualstudio.com/items?itemName=FastAPILabs.fastapi-vscode) (and Cursor), which provides a lot of features, including a path operation explorer, path operation search, CodeLens navigation in tests (jump to definition from tests), and FastAPI Cloud deployment and logs, all from your editor.
///
Run the live server:
<div class="termy">
```console
$ <font color="#4E9A06">fastapi</font> dev
$ <font color="#4E9A06">uv run fastapi</font> dev
<span style="background-color:#009485"><font color="#D3D7CF"> FastAPI </font></span> Starting development server 🚀
@@ -78,7 +84,7 @@ You will see the automatic interactive API documentation (provided by [Swagger U
And now, go to [http://127.0.0.1:8000/redoc](http://127.0.0.1:8000/redoc).
You will see the alternative automatic documentation (provided by [ReDoc](https://github.com/Rebilly/ReDoc)):
You will see the alternative automatic documentation (provided by [ReDoc](https://github.com/Redocly/redoc)):
![ReDoc](https://fastapi.tiangolo.com/img/index/index-02-redoc-simple.png)
@@ -185,13 +191,13 @@ from backend.main import app
You can also pass the file path to the `fastapi dev` command, and it will guess the FastAPI app object to use:
```console
$ fastapi dev main.py
$ uv run fastapi dev main.py
```
Or, you can also pass the `--entrypoint` option to the `fastapi dev` command:
```console
$ fastapi dev --entrypoint main:app
$ uv run fastapi dev --entrypoint main:app
```
But you would have to remember to pass the correct path\entrypoint every time you call the `fastapi` command.
@@ -205,7 +211,7 @@ You can optionally deploy your FastAPI app to [FastAPI Cloud](https://fastapiclo
<div class="termy">
```console
$ fastapi deploy
$ uv run fastapi deploy
Deploying to FastAPI Cloud...
@@ -232,7 +238,7 @@ That's it! Now you can access your app at that URL. ✨
`FastAPI` is a class that inherits directly from `Starlette`.
You can use all the [Starlette](https://www.starlette.dev/) functionality with `FastAPI` too.
You can use all the [Starlette](https://starlette.dev/) functionality with `FastAPI` too.
///
+9 -3
View File
@@ -52,7 +52,7 @@ For that, use `fallback="index.html"`:
{* ../../docs_src/frontend/tutorial002_py310.py hl[5] *}
**FastAPI** uses this fallback only for `GET` and `HEAD` requests that look like browser navigation. Missing files like JavaScript, CSS, and images still return `404`.
**FastAPI** uses this fallback only for `GET` and `HEAD` requests that explicitly accept HTML with `Accept: text/html` or `Accept: application/xhtml+xml`, as browser navigation requests normally do. Missing files like JavaScript, CSS, and images still return `404`.
Requests with other methods, like `POST` or `PUT`, to paths that only match the frontend fallback also return `404`. Regular **FastAPI** *path operations* still have higher priority than frontend routes.
@@ -106,9 +106,13 @@ Then missing frontend paths return the normal `404`.
## Check Directory { #check-directory }
By default, `app.frontend()` checks that the directory exists when the app is created.
By default, `app.frontend()` uses `check_dir="auto"`.
This helps catch configuration errors early. For example, if the frontend build output directory is missing, **FastAPI** will raise an error on startup.
When the `FASTAPI_ENV` environment variable is set to `development`, **FastAPI** only shows a warning if the frontend build output directory is missing. The [`fastapi dev` command](https://github.com/fastapi/fastapi-cli#fastapi-dev) sets this environment variable for you if it is not already set. This lets you start the backend before building or starting the frontend during development.
In any other environment, **FastAPI** raises an error when the app is created. This helps catch configuration errors early before deploying an app without its frontend files.
You can also set `check_dir=True` to always check the directory when the app is created.
If your frontend files are created later, for example by a separate build step after the app object is created, set `check_dir=False`:
@@ -132,6 +136,8 @@ Frontend responses run inside the normal **FastAPI** application, so HTTP middle
Dependencies from the app, from an `APIRouter`, and from `include_router()` also apply to frontend responses. This can be useful for protecting a frontend with cookie authentication or similar.
Dependencies can also modify response headers and add background tasks, as with normal *path operations*.
## Static Build Output Only { #static-build-output-only }
`app.frontend()` serves files already generated by your frontend build.
+1 -1
View File
@@ -81,7 +81,7 @@ But in case you needed it for an advanced scenario, you can add custom headers:
## Install custom exception handlers { #install-custom-exception-handlers }
You can add custom exception handlers with [the same exception utilities from Starlette](https://www.starlette.dev/exceptions/).
You can add custom exception handlers with [the same exception utilities from Starlette](https://starlette.dev/exceptions/).
Let's say you have a custom exception `UnicornException` that you (or a library you use) might `raise`.
+55 -15
View File
@@ -10,12 +10,12 @@ It is also built to work as a future reference so you can come back and see exac
All the code blocks can be copied and used directly (they are actually tested Python files).
To run any of the examples, copy the code to a file `main.py`, and start `fastapi dev`:
To run any of the examples, copy the code to a file `main.py`, and start `fastapi dev` with `uv run`:
<div class="termy">
```console
$ <font color="#4E9A06">fastapi</font> dev
$ <font color="#4E9A06">uv run fastapi</font> dev
<span style="background-color:#009485"><font color="#D3D7CF"> FastAPI </font></span> Starting development server 🚀
@@ -60,35 +60,75 @@ Using it in your editor is what really shows you the benefits of FastAPI, seeing
## Install FastAPI { #install-fastapi }
The first step is to install FastAPI.
The first step is to set up your project and add FastAPI.
Make sure you create a [virtual environment](../virtual-environments.md), activate it, and then **install FastAPI**:
Install [`uv`](https://docs.astral.sh/uv/getting-started/installation/), then create a project and add FastAPI:
<div class="termy">
```console
$ pip install "fastapi[standard]"
$ uv init awesome-project --bare
$ cd awesome-project
$ uv add "fastapi[standard]"
---> 100%
```
</div>
`uv add` creates the project's virtual environment in `.venv`, adds FastAPI to `pyproject.toml`, and creates `uv.lock` so the same package versions can be installed later.
/// details | What these commands do
* `uv init`: create a new Python project.
* `awesome-project`: create the project in a new directory with this name.
* `--bare`: create only the minimal `pyproject.toml` file, without generating a sample `main.py`, `README.md`, or other files. You will create the application files yourself in the next steps of this tutorial.
Then `cd awesome-project` enters the new project directory before adding FastAPI.
`uv` will use a compatible Python version already installed on your system, or download one if needed.
When you run `uv add`, it selects compatible versions of FastAPI and all the packages FastAPI depends on. It records the exact versions in `uv.lock`, making it possible to install the same package versions later on another computer or when deploying the application.
Creating or updating this file is called [**locking** the project dependencies](https://docs.astral.sh/uv/concepts/projects/sync/). `uv` does this automatically when you add a package.
///
/// details | FastAPI installation options
When you install with `uv add "fastapi[standard]"` it comes with some default optional standard dependencies, including `fastapi-cloud-cli`, which allows you to deploy to [FastAPI Cloud](https://fastapicloud.com).
If you don't want to have those optional dependencies, you can instead install `uv add fastapi`.
If you want to install the standard dependencies but without the `fastapi-cloud-cli`, you can install with `uv add "fastapi[standard-no-fastapi-cloud-cli]"`.
///
/// details | Using `pip` instead
If you prefer to manage a virtual environment and packages manually, create and activate a virtual environment and then install FastAPI with `pip install "fastapi[standard]"`.
Read the [Virtual Environments guide](https://tiangolo.com/guides/virtual-environments/) for the detailed steps.
///
## AI Agent Skills { #ai-agent-skills }
FastAPI includes an official skill for AI coding agents. It is bundled with the package, so its guidance stays aligned with the version of FastAPI installed in your project and updates when you update FastAPI.
After installing FastAPI in your project, you can install the skill with <a href="https://library-skills.io">Library Skills</a>:
```bash
uvx library-skills
```
/// note
When you install with `pip install "fastapi[standard]"` it comes with some default optional standard dependencies, including `fastapi-cloud-cli`, which allows you to deploy to [FastAPI Cloud](https://fastapicloud.com).
If you don't want to have those optional dependencies, you can instead install `pip install fastapi`.
If you want to install the standard dependencies but without the `fastapi-cloud-cli`, you can install with `pip install "fastapi[standard-no-fastapi-cloud-cli]"`.
`uvx` is an alias for `uv tool run`. It runs Library Skills in a temporary, isolated environment while Library Skills scans the packages installed in your project.
///
/// tip
FastAPI has an [official extension for VS Code](https://marketplace.visualstudio.com/items?itemName=FastAPILabs.fastapi-vscode) (and Cursor), which provides a lot of features, including a path operation explorer, path operation search, CodeLens navigation in tests (jump to definition from tests), and FastAPI Cloud deployment and logs, all from your editor.
///
The skill is compatible with Codex, Claude Code, Cursor, GitHub Copilot, Gemini CLI, Pi, OpenCode, and most other coding agents. For Claude Code, select `.claude/skills` when asked where to install the skill.
## Advanced User Guide { #advanced-user-guide }
+1 -1
View File
@@ -37,7 +37,7 @@ The middleware function receives:
Keep in mind that custom proprietary headers can be added [using the `X-` prefix](https://developer.mozilla.org/en-US/docs/Web/HTTP/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 CORS configurations ([CORS (Cross-Origin Resource Sharing)](cors.md)) using the parameter `expose_headers` documented in [Starlette's CORS docs](https://www.starlette.dev/middleware/#corsmiddleware).
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 CORS configurations ([CORS (Cross-Origin Resource Sharing)](cors.md)) using the parameter `expose_headers` documented in [Starlette's CORS docs](https://starlette.dev/middleware/#corsmiddleware).
///
+2 -2
View File
@@ -92,7 +92,7 @@ Notice that the path parameter is declared to be an integer.
## Standards-based benefits, alternative documentation { #standards-based-benefits-alternative-documentation }
And because the generated schema is from the [OpenAPI](https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.1.0.md) standard, there are many compatible tools.
And because the generated schema is from the [OpenAPI](https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md) standard, there are many compatible tools.
Because of this, **FastAPI** itself provides an alternative API documentation (using ReDoc), which you can access at [http://127.0.0.1:8000/redoc](http://127.0.0.1:8000/redoc):
@@ -102,7 +102,7 @@ The same way, there are many compatible tools. Including code generation tools f
## Pydantic { #pydantic }
All the data validation is performed under the hood by [Pydantic](https://docs.pydantic.dev/), so you get all the benefits from it. And you know you are in good hands.
All the data validation is performed under the hood by [Pydantic](https://pydantic.dev/docs/), so you get all the benefits from it. And you know you are in good hands.
You can use the same type declarations with `str`, `float`, `bool` and many other complex data types.
@@ -370,11 +370,11 @@ There could be cases where you need to do some **custom validation** that can't
In those cases, you can use a **custom validator function** that is applied after the normal validation (e.g. after validating that the value is a `str`).
You can achieve that using [Pydantic's `AfterValidator`](https://docs.pydantic.dev/latest/concepts/validators/#field-after-validator) inside of `Annotated`.
You can achieve that using [Pydantic's `AfterValidator`](https://pydantic.dev/docs/validation/latest/concepts/validators/#field-after-validator) inside of `Annotated`.
/// tip
Pydantic also has [`BeforeValidator`](https://docs.pydantic.dev/latest/concepts/validators/#field-before-validator) and others. 🤓
Pydantic also has [`BeforeValidator`](https://pydantic.dev/docs/validation/latest/concepts/validators/#field-before-validator) and others. 🤓
///
+2 -2
View File
@@ -6,10 +6,10 @@ You can define files to be uploaded by the client using `File`.
To receive uploaded files, first install [`python-multipart`](https://github.com/Kludex/python-multipart).
Make sure you create a [virtual environment](../virtual-environments.md), activate it, and then install it, for example:
Add it to your project:
```console
$ pip install python-multipart
$ uv add python-multipart
```
This is because uploaded files are sent as "form data".
+2 -2
View File
@@ -6,10 +6,10 @@ You can use **Pydantic models** to declare **form fields** in FastAPI.
To use forms, first install [`python-multipart`](https://github.com/Kludex/python-multipart).
Make sure you create a [virtual environment](../virtual-environments.md), activate it, and then install it, for example:
Add it to your project:
```console
$ pip install python-multipart
$ uv add python-multipart
```
///
@@ -6,10 +6,10 @@ You can define files and form fields at the same time using `File` and `Form`.
To receive uploaded files and/or form data, first install [`python-multipart`](https://github.com/Kludex/python-multipart).
Make sure you create a [virtual environment](../virtual-environments.md), activate it, and then install it, for example:
Add it to your project:
```console
$ pip install python-multipart
$ uv add python-multipart
```
///
+2 -2
View File
@@ -6,10 +6,10 @@ When you need to receive form fields instead of JSON, you can use `Form`.
To use forms, first install [`python-multipart`](https://github.com/Kludex/python-multipart).
Make sure you create a [virtual environment](../virtual-environments.md), activate it, and then install it, for example:
Add it to your project:
```console
$ pip install python-multipart
$ uv add python-multipart
```
///
+4 -4
View File
@@ -76,16 +76,16 @@ Here we are declaring a `UserIn` model, it will contain a plaintext password:
To use `EmailStr`, first install [`email-validator`](https://github.com/JoshData/python-email-validator).
Make sure you create a [virtual environment](../virtual-environments.md), activate it, and then install it, for example:
Add it to your project:
```console
$ pip install email-validator
$ uv add email-validator
```
or with:
```console
$ pip install "pydantic[email]"
$ uv add "pydantic[email]"
```
///
@@ -258,7 +258,7 @@ You can also use:
* `response_model_exclude_defaults=True`
* `response_model_exclude_none=True`
as described in [the Pydantic docs](https://docs.pydantic.dev/1.10/usage/exporting_models/#modeldict) for `exclude_defaults` and `exclude_none`.
as described in [the Pydantic docs](https://pydantic.dev/docs/validation/latest/concepts/serialization/#excluding-and-including-fields-based-on-their-value) for `exclude_defaults` and `exclude_none`.
///
@@ -12,7 +12,7 @@ You can declare `examples` for a Pydantic model that will be added to the genera
That extra info will be added as-is to the output **JSON Schema** for that model, and it will be used in the API docs.
You can use the attribute `model_config` that takes a `dict` as described in [Pydantic's docs: Configuration](https://docs.pydantic.dev/latest/api/config/).
You can use the attribute `model_config` that takes a `dict` as described in [Pydantic's docs: Configuration](https://pydantic.dev/docs/validation/latest/api/pydantic/config/).
You can set `"json_schema_extra"` with a `dict` containing any additional data you would like to show up in the generated JSON Schema, including `examples`.
@@ -26,14 +26,14 @@ Copy the example in a file `main.py`:
/// note
The [`python-multipart`](https://github.com/Kludex/python-multipart) package is automatically installed with **FastAPI** when you run the `pip install "fastapi[standard]"` command.
The [`python-multipart`](https://github.com/Kludex/python-multipart) package is automatically installed with **FastAPI** when you run the `uv add "fastapi[standard]"` command.
However, if you use the `pip install fastapi` command, the `python-multipart` package is not included by default.
However, if you use the `uv add fastapi` command, the `python-multipart` package is not included by default.
To install it manually, make sure you create a [virtual environment](../../virtual-environments.md), activate it, and then install it with:
To install it manually, add it to your project with:
```console
$ pip install python-multipart
$ uv add python-multipart
```
This is because **OAuth2** uses "form data" for sending the `username` and `password`.
@@ -45,7 +45,7 @@ Run the example with:
<div class="termy">
```console
$ fastapi dev
$ uv run fastapi dev
<span style="color: green;">INFO</span>: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit)
```
+4 -4
View File
@@ -30,12 +30,12 @@ If you want to play with JWT tokens and see how they work, check [https://jwt.io
We need to install `PyJWT` to generate and verify the JWT tokens in Python.
Make sure you create a [virtual environment](../../virtual-environments.md), activate it, and then install `pyjwt`:
Add `pyjwt` to your project:
<div class="termy">
```console
$ pip install pyjwt
$ uv add pyjwt
---> 100%
```
@@ -72,12 +72,12 @@ It supports many secure hashing algorithms and utilities to work with them.
The recommended algorithm is "Argon2".
Make sure you create a [virtual environment](../../virtual-environments.md), activate it, and then install pwdlib with Argon2:
Add `pwdlib` with Argon2 to your project:
<div class="termy">
```console
$ pip install "pwdlib[argon2]"
$ uv add "pwdlib[argon2]"
---> 100%
```
+4 -4
View File
@@ -34,12 +34,12 @@ This is a very simple and short tutorial, if you want to learn about databases i
## Install `SQLModel` { #install-sqlmodel }
First, make sure you create your [virtual environment](../virtual-environments.md), activate it, and then install `sqlmodel`:
Add `sqlmodel` to your project:
<div class="termy">
```console
$ pip install sqlmodel
$ uv add sqlmodel
---> 100%
```
@@ -152,7 +152,7 @@ You can run the app:
<div class="termy">
```console
$ fastapi dev
$ uv run fastapi dev
<span style="color: green;">INFO</span>: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit)
```
@@ -337,7 +337,7 @@ You can run the app again:
<div class="termy">
```console
$ fastapi dev
$ uv run fastapi dev
<span style="color: green;">INFO</span>: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit)
```
+1 -1
View File
@@ -45,4 +45,4 @@ All these parameters can be different than "`static`", adjust them to the needs
## More info { #more-info }
For more details and options check [Starlette's docs about Static Files](https://www.starlette.dev/staticfiles/).
For more details and options check [Starlette's docs about Static Files](https://starlette.dev/staticfiles/).
+6 -6
View File
@@ -1,6 +1,6 @@
# Testing { #testing }
Thanks to [Starlette](https://www.starlette.dev/testclient/), testing **FastAPI** applications is easy and enjoyable.
Thanks to [Starlette](https://starlette.dev/testclient/), testing **FastAPI** applications is easy and enjoyable.
It is based on [HTTPX](https://www.python-httpx.org), which in turn is designed based on Requests, so it's very familiar and intuitive.
@@ -12,10 +12,10 @@ With it, you can use [pytest](https://docs.pytest.org/) directly with **FastAPI*
To use `TestClient`, first install [`httpx`](https://www.python-httpx.org).
Make sure you create a [virtual environment](../virtual-environments.md), activate it, and then install it, for example:
Add it to your project:
```console
$ pip install httpx
$ uv add httpx
```
///
@@ -156,12 +156,12 @@ If you have a Pydantic model in your test and you want to send its data to the a
After that, you just need to install `pytest`.
Make sure you create a [virtual environment](../virtual-environments.md), activate it, and then install it, for example:
Add it to your project:
<div class="termy">
```console
$ pip install pytest
$ uv add pytest
---> 100%
```
@@ -175,7 +175,7 @@ Run the tests with:
<div class="termy">
```console
$ pytest
$ uv run pytest
================ test session starts ================
platform linux -- Python 3.6.9, pytest-5.3.5, py-1.8.1, pluggy-0.13.1
+10 -839
View File
@@ -1,864 +1,35 @@
# Virtual Environments { #virtual-environments }
When you work in Python projects you probably should use a **virtual environment** (or a similar mechanism) to isolate the packages you install for each project.
When you work with Python projects, you should use a **virtual environment** to isolate the packages installed for each project.
/// note
If you already know about virtual environments, how to create them and use them, you might want to skip this section. 🤓
///
/// tip
A **virtual environment** is different than an **environment variable**.
An **environment variable** is a variable in the system that can be used by programs.
A **virtual environment** is a directory with some files in it.
///
/// note
This page will teach you how to use **virtual environments** and how they work.
If you are ready to adopt a **tool that manages everything** for you (including installing Python), try [uv](https://github.com/astral-sh/uv).
///
For FastAPI projects, I recommend using [uv](https://docs.astral.sh/uv/) to manage the project, its dependencies, and its virtual environment.
## Create a Project { #create-a-project }
First, create a directory for your project.
What I normally do is that I create a directory named `code` inside my home/user directory.
And inside of that I create one directory per project.
Install `uv` using the [official installation guide](https://docs.astral.sh/uv/getting-started/installation/), and then create a project:
<div class="termy">
```console
// Go to the home directory
$ cd
// Create a directory for all your code projects
$ mkdir code
// Enter into that code directory
$ cd code
// Create a directory for this project
$ mkdir awesome-project
// Enter into that project directory
$ uv init awesome-project --bare
$ cd awesome-project
$ uv add "fastapi[standard]"
```
</div>
## Create a Virtual Environment { #create-a-virtual-environment }
`uv` creates a virtual environment for the project automatically. You don't need to create or activate one yourself.
When you start working on a Python project **for the first time**, create a virtual environment **<dfn title="there are other options, this is a simple guideline">inside your project</dfn>**.
/// tip
You only need to do this **once per project**, not every time you work.
///
//// tab | `venv`
To create a virtual environment, you can use the `venv` module that comes with Python.
Run commands inside the project environment with `uv run`, for example:
<div class="termy">
```console
$ python -m venv .venv
$ uv run fastapi dev
```
</div>
/// details | What that command means
## Learn More { #learn-more }
* `python`: use the program called `python`
* `-m`: call a module as a script, we'll tell it which module next
* `venv`: use the module called `venv` that normally comes installed with Python
* `.venv`: create the virtual environment in the new directory `.venv`
///
////
//// tab | `uv`
If you have [`uv`](https://github.com/astral-sh/uv) installed, you can use it to create a virtual environment.
<div class="termy">
```console
$ uv venv
```
</div>
/// tip
By default, `uv` will create a virtual environment in a directory called `.venv`.
But you could customize it by passing an additional argument with the directory name.
///
////
That command creates a new virtual environment in a directory called `.venv`.
/// details | `.venv` or other name
You could create the virtual environment in a different directory, but there's a convention of calling it `.venv`.
///
## Activate the Virtual Environment { #activate-the-virtual-environment }
Activate the new virtual environment so that any Python command you run or package you install uses it.
/// tip
Do this **every time** you start a **new terminal session** to work on the project.
///
//// tab | Linux, macOS
<div class="termy">
```console
$ source .venv/bin/activate
```
</div>
////
//// tab | Windows PowerShell
<div class="termy">
```console
$ .venv\Scripts\Activate.ps1
```
</div>
////
//// tab | Windows Bash
Or if you use Bash for Windows (e.g. [Git Bash](https://gitforwindows.org/)):
<div class="termy">
```console
$ source .venv/Scripts/activate
```
</div>
////
/// tip
Every time you install a **new package** in that environment, **activate** the environment again.
This makes sure that if you use a **terminal (<abbr title="command line interface">CLI</abbr>) program** installed by that package, you use the one from your virtual environment and not any other that could be installed globally, probably with a different version than what you need.
///
## Check the Virtual Environment is Active { #check-the-virtual-environment-is-active }
Check that the virtual environment is active (the previous command worked).
/// tip
This is **optional**, but it's a good way to **check** that everything is working as expected and you are using the virtual environment you intended.
///
//// tab | Linux, macOS, Windows Bash
<div class="termy">
```console
$ which python
/home/user/code/awesome-project/.venv/bin/python
```
</div>
If it shows the `python` binary at `.venv/bin/python`, inside of your project (in this case `awesome-project`), then it worked. 🎉
////
//// tab | Windows PowerShell
<div class="termy">
```console
$ Get-Command python
C:\Users\user\code\awesome-project\.venv\Scripts\python
```
</div>
If it shows the `python` binary at `.venv\Scripts\python`, inside of your project (in this case `awesome-project`), then it worked. 🎉
////
## Upgrade `pip` { #upgrade-pip }
/// tip
If you use [`uv`](https://github.com/astral-sh/uv) you would use it to install things instead of `pip`, so you don't need to upgrade `pip`. 😎
///
If you are using `pip` to install packages (it comes by default with Python), you should **upgrade** it to the latest version.
Many exotic errors while installing a package are solved by just upgrading `pip` first.
/// tip
You would normally do this **once**, right after you create the virtual environment.
///
Make sure the virtual environment is active (with the command above) and then run:
<div class="termy">
```console
$ python -m pip install --upgrade pip
---> 100%
```
</div>
/// tip
Sometimes, you might get a **`No module named pip`** error when trying to upgrade pip.
If this happens, install and upgrade pip using the command below:
<div class="termy">
```console
$ python -m ensurepip --upgrade
---> 100%
```
</div>
This command will install pip if it is not already installed and also ensure that the installed version of pip is at least as recent as the one available in `ensurepip`.
///
## Add `.gitignore` { #add-gitignore }
If you are using **Git** (you should), add a `.gitignore` file to exclude everything in your `.venv` from Git.
/// tip
If you used [`uv`](https://github.com/astral-sh/uv) to create the virtual environment, it already did this for you, you can skip this step. 😎
///
/// tip
Do this **once**, right after you create the virtual environment.
///
<div class="termy">
```console
$ echo "*" > .venv/.gitignore
```
</div>
/// details | What that command means
* `echo "*"`: will "print" the text `*` in the terminal (the next part changes that a bit)
* `>`: anything printed to the terminal by the command to the left of `>` should not be printed but instead written to the file that goes to the right of `>`
* `.gitignore`: the name of the file where the text should be written
And `*` for Git means "everything". So, it will ignore everything in the `.venv` directory.
That command will create a file `.gitignore` with the content:
```gitignore
*
```
///
## Install Packages { #install-packages }
After activating the environment, you can install packages in it.
/// tip
Do this **once** when installing or upgrading the packages your project needs.
If you need to upgrade a version or add a new package you would **do this again**.
///
### Install Packages Directly { #install-packages-directly }
If you're in a hurry and don't want to use a file to declare your project's package requirements, you can install them directly.
/// tip
It's a (very) good idea to put the packages and versions your program needs in a file (for example `requirements.txt` or `pyproject.toml`).
///
//// tab | `pip`
<div class="termy">
```console
$ pip install "fastapi[standard]"
---> 100%
```
</div>
////
//// tab | `uv`
If you have [`uv`](https://github.com/astral-sh/uv):
<div class="termy">
```console
$ uv pip install "fastapi[standard]"
---> 100%
```
</div>
////
### Install from `requirements.txt` { #install-from-requirements-txt }
If you have a `requirements.txt`, you can now use it to install its packages.
//// tab | `pip`
<div class="termy">
```console
$ pip install -r requirements.txt
---> 100%
```
</div>
////
//// tab | `uv`
If you have [`uv`](https://github.com/astral-sh/uv):
<div class="termy">
```console
$ uv pip install -r requirements.txt
---> 100%
```
</div>
////
/// details | `requirements.txt`
A `requirements.txt` with some packages could look like:
```requirements.txt
fastapi[standard]==0.113.0
pydantic==2.8.0
```
///
## Run Your Program { #run-your-program }
After you activated the virtual environment, you can run your program, and it will use the Python inside of your virtual environment with the packages you installed there.
<div class="termy">
```console
$ python main.py
Hello World
```
</div>
## Configure Your Editor { #configure-your-editor }
You would probably use an editor, make sure you configure it to use the same virtual environment you created (it will probably autodetect it) so that you can get autocompletion and inline errors.
For example:
* [VS Code](https://code.visualstudio.com/docs/python/environments#_select-and-activate-an-environment)
* [PyCharm](https://www.jetbrains.com/help/pycharm/creating-virtual-environment.html)
/// tip
You normally have to do this only **once**, when you create the virtual environment.
///
## Deactivate the Virtual Environment { #deactivate-the-virtual-environment }
Once you are done working on your project you can **deactivate** the virtual environment.
<div class="termy">
```console
$ deactivate
```
</div>
This way, when you run `python` it won't try to run it from that virtual environment with the packages installed there.
## Ready to Work { #ready-to-work }
Now you're ready to start working on your project.
/// tip
Do you want to understand what all that above is?
Continue reading. 👇🤓
///
## Why Virtual Environments { #why-virtual-environments }
To work with FastAPI you need to install [Python](https://www.python.org/).
After that, you would need to **install** FastAPI and any other **packages** you want to use.
To install packages you would normally use the `pip` command that comes with Python (or similar alternatives).
Nevertheless, if you just use `pip` directly, the packages would be installed in your **global Python environment** (the global installation of Python).
### The Problem { #the-problem }
So, what's the problem with installing packages in the global Python environment?
At some point, you will probably end up writing many different programs that depend on **different packages**. And some of these projects you work on will depend on **different versions** of the same package. 😱
For example, you could create a project called `philosophers-stone`, this program depends on another package called **`harry`, using the version `1`**. So, you need to install `harry`.
```mermaid
flowchart LR
stone(philosophers-stone) -->|requires| harry-1[harry v1]
```
Then, at some point later, you create another project called `prisoner-of-azkaban`, and this project also depends on `harry`, but this project needs **`harry` version `3`**.
```mermaid
flowchart LR
azkaban(prisoner-of-azkaban) --> |requires| harry-3[harry v3]
```
But now the problem is, if you install the packages globally (in the global environment) instead of in a local **virtual environment**, you will have to choose which version of `harry` to install.
If you want to run `philosophers-stone` you will need to first install `harry` version `1`, for example with:
<div class="termy">
```console
$ pip install "harry==1"
```
</div>
And then you would end up with `harry` version `1` installed in your global Python environment.
```mermaid
flowchart LR
subgraph global[global env]
harry-1[harry v1]
end
subgraph stone-project[philosophers-stone project]
stone(philosophers-stone) -->|requires| harry-1
end
```
But then if you want to run `prisoner-of-azkaban`, you will need to uninstall `harry` version `1` and install `harry` version `3` (or just installing version `3` would automatically uninstall version `1`).
<div class="termy">
```console
$ pip install "harry==3"
```
</div>
And then you would end up with `harry` version `3` installed in your global Python environment.
And if you try to run `philosophers-stone` again, there's a chance it would **not work** because it needs `harry` version `1`.
```mermaid
flowchart LR
subgraph global[global env]
harry-1[<strike>harry v1</strike>]
style harry-1 fill:#ccc,stroke-dasharray: 5 5
harry-3[harry v3]
end
subgraph stone-project[philosophers-stone project]
stone(philosophers-stone) -.-x|⛔️| harry-1
end
subgraph azkaban-project[prisoner-of-azkaban project]
azkaban(prisoner-of-azkaban) --> |requires| harry-3
end
```
/// tip
It's very common in Python packages to try the best to **avoid breaking changes** in **new versions**, but it's better to be safe, and install newer versions intentionally and when you can run the tests to check everything is working correctly.
///
Now, imagine that with **many** other **packages** that all your **projects depend on**. That's very difficult to manage. And you would probably end up running some projects with some **incompatible versions** of the packages, and not knowing why something isn't working.
Also, depending on your operating system (e.g. Linux, Windows, macOS), it could have come with Python already installed. And in that case it probably had some packages pre-installed with some specific versions **needed by your system**. If you install packages in the global Python environment, you could end up **breaking** some of the programs that came with your operating system.
## Where are Packages Installed { #where-are-packages-installed }
When you install Python, it creates some directories with some files on your computer.
Some of these directories are the ones in charge of having all the packages you install.
When you run:
<div class="termy">
```console
// Don't run this now, it's just an example 🤓
$ pip install "fastapi[standard]"
---> 100%
```
</div>
That will download a compressed file with the FastAPI code, normally from [PyPI](https://pypi.org/project/fastapi/).
It will also **download** files for other packages that FastAPI depends on.
Then it will **extract** all those files and put them in a directory on your computer.
By default, it will put those files downloaded and extracted in the directory that comes with your Python installation, that's the **global environment**.
## What are Virtual Environments { #what-are-virtual-environments }
The solution to the problems of having all the packages in the global environment is to use a **virtual environment for each project** you work on.
A virtual environment is a **directory**, very similar to the global one, where you can install the packages for a project.
This way, each project will have its own virtual environment (`.venv` directory) with its own packages.
```mermaid
flowchart TB
subgraph stone-project[philosophers-stone project]
stone(philosophers-stone) --->|requires| harry-1
subgraph venv1[.venv]
harry-1[harry v1]
end
end
subgraph azkaban-project[prisoner-of-azkaban project]
azkaban(prisoner-of-azkaban) --->|requires| harry-3
subgraph venv2[.venv]
harry-3[harry v3]
end
end
stone-project ~~~ azkaban-project
```
## What Does Activating a Virtual Environment Mean { #what-does-activating-a-virtual-environment-mean }
When you activate a virtual environment, for example with:
//// tab | Linux, macOS
<div class="termy">
```console
$ source .venv/bin/activate
```
</div>
////
//// tab | Windows PowerShell
<div class="termy">
```console
$ .venv\Scripts\Activate.ps1
```
</div>
////
//// tab | Windows Bash
Or if you use Bash for Windows (e.g. [Git Bash](https://gitforwindows.org/)):
<div class="termy">
```console
$ source .venv/Scripts/activate
```
</div>
////
That command will create or modify some [environment variables](environment-variables.md) that will be available for the next commands.
One of those variables is the `PATH` variable.
/// tip
You can learn more about the `PATH` environment variable in the [Environment Variables](environment-variables.md#path-environment-variable) section.
///
Activating a virtual environment adds its path `.venv/bin` (on Linux and macOS) or `.venv\Scripts` (on Windows) to the `PATH` environment variable.
Let's say that before activating the environment, the `PATH` variable looked like this:
//// tab | Linux, macOS
```plaintext
/usr/bin:/bin:/usr/sbin:/sbin
```
That means that the system would look for programs in:
* `/usr/bin`
* `/bin`
* `/usr/sbin`
* `/sbin`
////
//// tab | Windows
```plaintext
C:\Windows\System32
```
That means that the system would look for programs in:
* `C:\Windows\System32`
////
After activating the virtual environment, the `PATH` variable would look something like this:
//// tab | Linux, macOS
```plaintext
/home/user/code/awesome-project/.venv/bin:/usr/bin:/bin:/usr/sbin:/sbin
```
That means that the system will now start looking first for programs in:
```plaintext
/home/user/code/awesome-project/.venv/bin
```
before looking in the other directories.
So, when you type `python` in the terminal, the system will find the Python program in
```plaintext
/home/user/code/awesome-project/.venv/bin/python
```
and use that one.
////
//// tab | Windows
```plaintext
C:\Users\user\code\awesome-project\.venv\Scripts;C:\Windows\System32
```
That means that the system will now start looking first for programs in:
```plaintext
C:\Users\user\code\awesome-project\.venv\Scripts
```
before looking in the other directories.
So, when you type `python` in the terminal, the system will find the Python program in
```plaintext
C:\Users\user\code\awesome-project\.venv\Scripts\python
```
and use that one.
////
An important detail is that it will put the virtual environment path at the **beginning** of the `PATH` variable. The system will find it **before** finding any other Python available. This way, when you run `python`, it will use the Python **from the virtual environment** instead of any other `python` (for example, a `python` from a global environment).
Activating a virtual environment also changes a couple of other things, but this is one of the most important things it does.
## Checking a Virtual Environment { #checking-a-virtual-environment }
When you check if a virtual environment is active, for example with:
//// tab | Linux, macOS, Windows Bash
<div class="termy">
```console
$ which python
/home/user/code/awesome-project/.venv/bin/python
```
</div>
////
//// tab | Windows PowerShell
<div class="termy">
```console
$ Get-Command python
C:\Users\user\code\awesome-project\.venv\Scripts\python
```
</div>
////
That means that the `python` program that will be used is the one **in the virtual environment**.
You use `which` in Linux and macOS and `Get-Command` in Windows PowerShell.
The way that command works is that it will go and check in the `PATH` environment variable, going through **each path in order**, looking for the program called `python`. Once it finds it, it will **show you the path** to that program.
The most important part is that when you call `python`, that is the exact "`python`" that will be executed.
So, you can confirm if you are in the correct virtual environment.
/// tip
It's easy to activate one virtual environment, get one Python, and then **go to another project**.
And the second project **wouldn't work** because you are using the **incorrect Python**, from a virtual environment for another project.
It's useful being able to check what `python` is being used. 🤓
///
## Why Deactivate a Virtual Environment { #why-deactivate-a-virtual-environment }
For example, you could be working on a project `philosophers-stone`, **activate that virtual environment**, install packages and work with that environment.
And then you want to work on **another project** `prisoner-of-azkaban`.
You go to that project:
<div class="termy">
```console
$ cd ~/code/prisoner-of-azkaban
```
</div>
If you don't deactivate the virtual environment for `philosophers-stone`, when you run `python` in the terminal, it will try to use the Python from `philosophers-stone`.
<div class="termy">
```console
$ cd ~/code/prisoner-of-azkaban
$ python main.py
// Error importing sirius, it's not installed 😱
Traceback (most recent call last):
File "main.py", line 1, in <module>
import sirius
```
</div>
But if you deactivate the virtual environment and activate the new one for `prisoner-of-azkaban` then when you run `python` it will use the Python from the virtual environment in `prisoner-of-azkaban`.
<div class="termy">
```console
$ cd ~/code/prisoner-of-azkaban
// You don't need to be in the old directory to deactivate, you can do it wherever you are, even after going to the other project 😎
$ deactivate
// Activate the virtual environment in prisoner-of-azkaban/.venv 🚀
$ source .venv/bin/activate
// Now when you run python, it will find the package sirius installed in this virtual environment ✨
$ python main.py
I solemnly swear 🐺
```
</div>
## Alternatives { #alternatives }
This is a simple guide to get you started and teach you how everything works **underneath**.
There are many **alternatives** to managing virtual environments, package dependencies (requirements), projects.
Once you are ready and want to use a tool to **manage the entire project**, package dependencies, virtual environments, etc. I would suggest you try [uv](https://github.com/astral-sh/uv).
`uv` can do a lot of things, it can:
* **Install Python** for you, including different versions
* Manage the **virtual environment** for your projects
* Install **packages**
* Manage package **dependencies and versions** for your project
* Make sure you have an **exact** set of packages and versions to install, including their dependencies, so that you can be sure that you can run your project in production exactly the same as in your computer while developing, this is called **locking**
* And many other things
## Conclusion { #conclusion }
If you read and understood all this, now **you know much more** about virtual environments than many developers out there. 🤓
Knowing these details will most probably be useful in a future time when you are debugging something that seems complex, but you will know **how it all works underneath**. 😎
Read the [Virtual Environments guide](https://tiangolo.com/guides/virtual-environments/) to learn how virtual environments work underneath, including activation and the alternative `python -m venv` and `pip` workflow.
+3 -4
View File
@@ -81,8 +81,6 @@ nav:
- learn/index.md
- python-types.md
- async.md
- environment-variables.md
- virtual-environments.md
- "":
- tutorial/index.md
- tutorial/first-steps.md
@@ -213,6 +211,7 @@ nav:
- reference/httpconnection.md
- reference/response.md
- reference/responses.md
- reference/sse.md
- reference/middleware.md
- "":
- reference/openapi/index.md
@@ -223,9 +222,9 @@ nav:
- reference/staticfiles.md
- reference/templating.md
- reference/testclient.md
- fastapi-people.md
- "":
- resources/index.md
- fastapi-people.md
- help-fastapi.md
- contributing.md
- translations.md
@@ -288,7 +287,7 @@ extra:
- icon: octicons/mark-github-24
link: https://github.com/fastapi/fastapi
- icon: fontawesome/brands/discord
link: https://discord.gg/VQjSZaeJmf
link: https://discord.com/invite/VQjSZaeJmf
- icon: fontawesome/brands/x-twitter
link: https://x.com/fastapi
- icon: fontawesome/brands/bluesky
+6
View File
@@ -126,6 +126,12 @@ En este ejemplo, los paths frontend se sirven bajo `/app`.
Cualquier *path operation* regular en la app seguirá teniendo prioridad, incluso en otros routers.
## Dependencias y Middleware { #dependencies-and-middleware }
Las responses frontend se ejecutan dentro de la aplicación **FastAPI** normal, así que el middleware HTTP se aplica a ellas.
Las dependencias de la app, de un `APIRouter` y de `include_router()` también se aplican a las responses frontend. Esto puede ser útil para proteger un frontend con autenticación por cookie o similar.
## Solo salida estática del build { #static-build-output-only }
`app.frontend()` sirve archivos ya generados por tu build del frontend.
+6
View File
@@ -126,6 +126,12 @@ Dans cet exemple, les chemins frontend sont servis sous `/app`.
Tous les *chemins d'accès* réguliers dans l'application seront toujours prioritaires, y compris dans d'autres routers.
## Dépendances et middleware { #dependencies-and-middleware }
Les réponses frontend s'exécutent au sein de l'application **FastAPI** normale, donc le middleware HTTP s'applique à elles.
Les dépendances de l'application, d'un `APIRouter` et de `include_router()` s'appliquent également aux réponses frontend. Cela peut être utile pour protéger un frontend avec une authentification par cookie ou similaire.
## Sortie de build statique uniquement { #static-build-output-only }
`app.frontend()` sert des fichiers déjà générés par votre build frontend.
+3
View File
@@ -0,0 +1,3 @@
# परिचय { #about }
FastAPI, इसके design, प्रेरणा और और भी बहुत कुछ के बारे में। 🤓
@@ -0,0 +1,247 @@
# OpenAPI में अतिरिक्त Responses { #additional-responses-in-openapi }
/// warning | चेतावनी
यह एक काफ़ी advanced विषय है।
अगर आप **FastAPI** के साथ शुरुआत कर रहे हैं, तो शायद आपको इसकी ज़रूरत न पड़े।
///
आप अतिरिक्त status codes, media types, descriptions आदि के साथ अतिरिक्त responses घोषित कर सकते हैं।
ये अतिरिक्त responses OpenAPI schema में शामिल किए जाएँगे, इसलिए वे API docs में भी दिखाई देंगे।
लेकिन उन अतिरिक्त responses के लिए आपको यह सुनिश्चित करना होगा कि आप अपने status code और content के साथ सीधे `JSONResponse` जैसा कोई `Response` return करें।
## `model` के साथ अतिरिक्त Response { #additional-response-with-model }
आप अपने *path operation decorators* को `responses` parameter दे सकते हैं।
यह एक `dict` प्राप्त करता है: keys प्रत्येक response के status codes होते हैं (जैसे `200`), और values अन्य `dict`s होते हैं जिनमें उनमें से प्रत्येक की जानकारी होती है।
इनमें से प्रत्येक response `dict` में `model` key हो सकती है, जिसमें `response_model` की तरह एक Pydantic model होता है।
**FastAPI** उस model को लेगा, उसका JSON Schema generate करेगा और उसे OpenAPI में सही जगह शामिल करेगा।
उदाहरण के लिए, status code `404` और Pydantic model `Message` के साथ एक और response घोषित करने के लिए, आप लिख सकते हैं:
{* ../../docs_src/additional_responses/tutorial001_py310.py hl[18,22] *}
/// note | नोट
ध्यान रखें कि आपको सीधे `JSONResponse` return करना होगा।
///
/// note | नोट
`model` key OpenAPI का हिस्सा नहीं है।
**FastAPI** वहाँ से Pydantic model लेगा, JSON Schema generate करेगा, और उसे सही जगह रखेगा।
सही जगह है:
* `content` key में, जिसकी value एक और JSON object (`dict`) होती है जिसमें शामिल है:
* media type वाली एक key, जैसे `application/json`, जिसकी value एक और JSON object होती है, जिसमें शामिल है:
* एक key `schema`, जिसकी value model से JSON Schema होती है, यही सही जगह है।
* **FastAPI** इसे सीधे शामिल करने के बजाय आपके OpenAPI में किसी अन्य जगह मौजूद global JSON Schemas का reference यहाँ जोड़ता है। इस तरह, अन्य applications और clients उन JSON Schemas को सीधे उपयोग कर सकते हैं, बेहतर code generation tools प्रदान कर सकते हैं, आदि।
///
इस *path operation* के लिए OpenAPI में generate किए गए responses होंगे:
```JSON hl_lines="3-12"
{
"responses": {
"404": {
"description": "Additional Response",
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/Message"
}
}
}
},
"200": {
"description": "Successful Response",
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/Item"
}
}
}
},
"422": {
"description": "Validation Error",
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/HTTPValidationError"
}
}
}
}
}
}
```
Schemas को OpenAPI schema के अंदर किसी दूसरी जगह reference किया गया है:
```JSON hl_lines="4-16"
{
"components": {
"schemas": {
"Message": {
"title": "Message",
"required": [
"message"
],
"type": "object",
"properties": {
"message": {
"title": "Message",
"type": "string"
}
}
},
"Item": {
"title": "Item",
"required": [
"id",
"value"
],
"type": "object",
"properties": {
"id": {
"title": "Id",
"type": "string"
},
"value": {
"title": "Value",
"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"
}
}
}
}
}
}
}
```
## मुख्य response के लिए अतिरिक्त media types { #additional-media-types-for-the-main-response }
आप इसी `responses` parameter का उपयोग करके उसी मुख्य response के लिए अलग-अलग media types जोड़ सकते हैं।
उदाहरण के लिए, आप `image/png` का एक अतिरिक्त media type जोड़ सकते हैं, यह घोषित करते हुए कि आपका *path operation* एक JSON object (media type `application/json` के साथ) या एक PNG image return कर सकता है:
{* ../../docs_src/additional_responses/tutorial002_py310.py hl[17:22,26] *}
/// note | नोट
ध्यान दें कि आपको image को सीधे `FileResponse` का उपयोग करके return करना होगा।
///
/// note | नोट
जब तक आप अपने `responses` parameter में स्पष्ट रूप से कोई अलग media type specify नहीं करते, FastAPI मान लेगा कि response का media type मुख्य response class (default `application/json`) जैसा ही है।
लेकिन अगर आपने custom response class specify की है जिसका media type `None` है, तो FastAPI किसी भी ऐसे अतिरिक्त response के लिए `application/json` का उपयोग करेगा जिसके साथ कोई associated model है।
///
## जानकारी को मिलाना { #combining-information }
आप कई जगहों से response जानकारी को भी मिला सकते हैं, जिसमें `response_model`, `status_code`, और `responses` parameters शामिल हैं।
आप default status code `200` (या ज़रूरत पड़ने पर custom code) का उपयोग करके `response_model` घोषित कर सकते हैं, और फिर उसी response के लिए अतिरिक्त जानकारी सीधे OpenAPI schema में `responses` के अंदर घोषित कर सकते हैं।
**FastAPI** `responses` से अतिरिक्त जानकारी बनाए रखेगा, और उसे आपके model से JSON Schema के साथ मिला देगा।
उदाहरण के लिए, आप status code `404` वाला एक response घोषित कर सकते हैं जो Pydantic model का उपयोग करता है और जिसमें custom `description` है।
और status code `200` वाला एक response, जो आपके `response_model` का उपयोग करता है, लेकिन जिसमें custom `example` शामिल है:
{* ../../docs_src/additional_responses/tutorial003_py310.py hl[20:31] *}
यह सब मिलाकर आपके OpenAPI में शामिल किया जाएगा, और API docs में दिखाया जाएगा:
<img src="/img/tutorial/additional-responses/image01.png">
## पहले से परिभाषित responses और custom responses को मिलाएँ { #combine-predefined-responses-and-custom-ones }
आप कुछ पहले से परिभाषित responses रखना चाह सकते हैं जो कई *path operations* पर लागू होते हैं, लेकिन आप उन्हें प्रत्येक *path operation* के लिए ज़रूरी custom responses के साथ मिलाना चाहते हैं।
ऐसे मामलों के लिए, आप `**dict_to_unpack` के साथ `dict` को "unpacking" करने की Python technique का उपयोग कर सकते हैं:
```Python
old_dict = {
"old key": "old value",
"second old key": "second old value",
}
new_dict = {**old_dict, "new key": "new value"}
```
यहाँ, `new_dict` में `old_dict` के सभी key-value pairs के साथ नया key-value pair भी होगा:
```Python
{
"old key": "old value",
"second old key": "second old value",
"new key": "new value",
}
```
आप इस technique का उपयोग अपने *path operations* में कुछ पहले से परिभाषित responses को reuse करने और उन्हें अतिरिक्त custom responses के साथ मिलाने के लिए कर सकते हैं।
उदाहरण के लिए:
{* ../../docs_src/additional_responses/tutorial004_py310.py hl[11:15,24] *}
## OpenAPI responses के बारे में अधिक जानकारी { #more-information-about-openapi-responses }
Responses में आप ठीक-ठीक क्या शामिल कर सकते हैं, यह देखने के लिए आप OpenAPI specification में ये sections देख सकते हैं:
* [OpenAPI Responses Object](https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.1.0.md#responses-object), इसमें `Response Object` शामिल है।
* [OpenAPI Response Object](https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.1.0.md#response-object), आप इसमें से कुछ भी सीधे अपने `responses` parameter के अंदर प्रत्येक response में शामिल कर सकते हैं। जिसमें `description`, `headers`, `content` (इसी के अंदर आप अलग-अलग media types और JSON Schemas घोषित करते हैं), और `links` शामिल हैं।
@@ -0,0 +1,41 @@
# अतिरिक्त Status Codes { #additional-status-codes }
default रूप से, **FastAPI** responses को `JSONResponse` का उपयोग करके return करेगा, जिसमें आपके *path operation* से return किया गया content उस `JSONResponse` के अंदर रखा जाएगा।
यह default status code या वह status code उपयोग करेगा जो आपने अपने *path operation* में set किया है।
## अतिरिक्त status codes { #additional-status-codes_1 }
अगर आप मुख्य status code के अलावा अतिरिक्त status codes return करना चाहते हैं, तो आप सीधे `Response`, जैसे `JSONResponse`, return करके और अतिरिक्त status code को सीधे set करके ऐसा कर सकते हैं।
उदाहरण के लिए, मान लीजिए कि आप एक ऐसा *path operation* रखना चाहते हैं जो items को update करने की अनुमति देता है, और सफल होने पर HTTP status code 200 "OK" return करता है।
लेकिन आप यह भी चाहते हैं कि यह नए items को स्वीकार करे। और जब items पहले मौजूद नहीं थे, तो यह उन्हें बनाता है, और HTTP status code 201 "Created" return करता है।
ऐसा करने के लिए, `JSONResponse` import करें, और अपना content वहीं सीधे return करें, साथ में अपनी पसंद का `status_code` set करें:
{* ../../docs_src/additional_status_codes/tutorial001_an_py310.py hl[4,25] *}
/// warning | चेतावनी
जब आप सीधे `Response` return करते हैं, जैसे ऊपर के उदाहरण में, तो वह सीधे return किया जाएगा।
इसे किसी model आदि के साथ serialize नहीं किया जाएगा।
सुनिश्चित करें कि इसमें वही data है जो आप चाहते हैं, और values valid JSON हैं (अगर आप `JSONResponse` उपयोग कर रहे हैं)।
///
/// note | तकनीकी विवरण
आप `from starlette.responses import JSONResponse` भी उपयोग कर सकते हैं।
**FastAPI** आपकी सुविधा के लिए, developer के रूप में, वही `starlette.responses` `fastapi.responses` के रूप में प्रदान करता है। लेकिन उपलब्ध अधिकांश responses सीधे Starlette से आते हैं। `status` के साथ भी यही है।
///
## OpenAPI और API docs { #openapi-and-api-docs }
अगर आप अतिरिक्त status codes और responses सीधे return करते हैं, तो वे OpenAPI schema (API docs) में शामिल नहीं होंगे, क्योंकि FastAPI के पास पहले से यह जानने का तरीका नहीं है कि आप क्या return करने वाले हैं।
लेकिन आप इसे अपने code में document कर सकते हैं, उपयोग करके: [अतिरिक्त Responses](additional-responses.md)।
@@ -0,0 +1,163 @@
# Advanced Dependencies { #advanced-dependencies }
## Parameterized dependencies { #parameterized-dependencies }
अब तक हमने जो भी dependencies देखी हैं, वे एक निश्चित function या class हैं।
लेकिन ऐसे मामले हो सकते हैं जहाँ आप dependency पर parameters सेट कर पाना चाहें, बिना कई अलग-अलग functions या classes declare किए।
कल्पना करें कि हम एक ऐसी dependency रखना चाहते हैं जो जाँचती है कि query parameter `q` में कुछ निश्चित content है या नहीं।
लेकिन हम उस निश्चित content को parameterize कर पाना चाहते हैं।
## एक "callable" instance { #a-callable-instance }
Python में किसी class के instance को "callable" बनाने का एक तरीका है।
खुद class को नहीं (जो पहले से ही callable होती है), बल्कि उस class के एक instance को।
ऐसा करने के लिए, हम एक method `__call__` declare करते हैं:
{* ../../docs_src/dependencies/tutorial011_an_py310.py hl[12] *}
इस मामले में, यही `__call__` है जिसे **FastAPI** अतिरिक्त parameters और sub-dependencies की जाँच के लिए उपयोग करेगा, और बाद में आपकी *path operation function* में parameter को value पास करने के लिए यही call किया जाएगा।
## Instance को parameterize करें { #parameterize-the-instance }
और अब, हम `__init__` का उपयोग करके instance के parameters declare कर सकते हैं जिन्हें हम dependency को "parameterize" करने के लिए उपयोग कर सकते हैं:
{* ../../docs_src/dependencies/tutorial011_an_py310.py hl[9] *}
इस मामले में, **FastAPI** कभी भी `__init__` को छुएगा या उसकी परवाह नहीं करेगा, हम इसे सीधे अपने code में उपयोग करेंगे।
## एक instance बनाएँ { #create-an-instance }
हम इस class का एक instance इस तरह बना सकते हैं:
{* ../../docs_src/dependencies/tutorial011_an_py310.py hl[18] *}
और इस तरह हम अपनी dependency को "parameterize" कर पाते हैं, जिसमें अब `"bar"` उसके अंदर है, attribute `checker.fixed_content` के रूप में।
## Instance को dependency के रूप में उपयोग करें { #use-the-instance-as-a-dependency }
फिर, हम `Depends(FixedContentQueryChecker)` के बजाय इस `checker` को `Depends(checker)` में उपयोग कर सकते हैं, क्योंकि dependency class खुद नहीं, बल्कि instance `checker` है।
और dependency को solve करते समय, **FastAPI** इस `checker` को इस तरह call करेगा:
```Python
checker(q="somequery")
```
...और जो भी यह return करेगा उसे हमारी *path operation function* में dependency की value के रूप में parameter `fixed_content_included` में पास करेगा:
{* ../../docs_src/dependencies/tutorial011_an_py310.py hl[22] *}
/// tip | सुझाव
यह सब थोड़ा बनावटी लग सकता है। और अभी यह बहुत स्पष्ट नहीं हो सकता कि यह कैसे उपयोगी है।
ये उदाहरण जानबूझकर सरल रखे गए हैं, लेकिन दिखाते हैं कि यह सब कैसे काम करता है।
Security वाले chapters में utility functions हैं जिन्हें इसी तरीके से implement किया गया है।
अगर आपने यह सब समझ लिया है, तो आप पहले से जानते हैं कि security के लिए वे utility tools अंदर से कैसे काम करते हैं।
///
## `yield`, `HTTPException`, `except` और Background Tasks वाली Dependencies { #dependencies-with-yield-httpexception-except-and-background-tasks }
/// warning | चेतावनी
सबसे अधिक संभावना है कि आपको इन तकनीकी विवरणों की आवश्यकता नहीं है।
ये विवरण मुख्य रूप से तब उपयोगी हैं जब आपके पास 0.121.0 से पुरानी FastAPI application थी और आपको `yield` वाली dependencies के साथ समस्याएँ आ रही हैं।
///
`yield` वाली dependencies समय के साथ अलग-अलग use cases को संभालने और कुछ समस्याएँ ठीक करने के लिए विकसित हुई हैं, यहाँ बदले हुए व्यवहार का सारांश है।
### `yield` और `scope` वाली Dependencies { #dependencies-with-yield-and-scope }
Version 0.121.0 में, FastAPI ने `yield` वाली dependencies के लिए `Depends(scope="function")` का support जोड़ा।
`Depends(scope="function")` का उपयोग करने पर, `yield` के बाद का exit code *path operation function* के समाप्त होते ही, response client को वापस भेजे जाने से पहले execute होता है।
और `Depends(scope="request")` (default) का उपयोग करने पर, `yield` के बाद का exit code response भेजे जाने के बाद execute होता है।
आप इसके बारे में docs में [Dependencies with `yield` - Early exit and `scope`](../tutorial/dependencies/dependencies-with-yield.md#early-exit-and-scope) में अधिक पढ़ सकते हैं।
### `yield` और `StreamingResponse` वाली Dependencies, तकनीकी विवरण { #dependencies-with-yield-and-streamingresponse-technical-details }
FastAPI 0.118.0 से पहले, यदि आप `yield` वाली dependency उपयोग करते थे, तो यह *path operation function* के return करने के बाद लेकिन response भेजने से ठीक पहले exit code run करती थी।
इरादा यह था कि आवश्यक से अधिक समय तक resources को पकड़े रखने से बचा जाए, response के network से गुजरने की प्रतीक्षा करते हुए।
इस बदलाव का अर्थ यह भी था कि यदि आपने `StreamingResponse` return किया, तो `yield` वाली dependency का exit code पहले ही run हो चुका होता।
उदाहरण के लिए, यदि आपके पास `yield` वाली dependency में database session था, तो `StreamingResponse` data stream करते समय उस session का उपयोग नहीं कर पाता क्योंकि `yield` के बाद वाले exit code में session पहले ही बंद हो चुका होता।
यह व्यवहार 0.118.0 में revert कर दिया गया, ताकि `yield` के बाद का exit code response भेजे जाने के बाद execute हो।
/// note | ध्यान दें
जैसा कि आप नीचे देखेंगे, यह version 0.106.0 से पहले के व्यवहार से बहुत मिलता-जुलता है, लेकिन कई सुधारों और corner cases के लिए bug fixes के साथ।
///
#### Early Exit Code वाले Use Cases { #use-cases-with-early-exit-code }
कुछ specific conditions वाले use cases हैं जिन्हें response भेजने से पहले `yield` वाली dependencies का exit code run करने के पुराने व्यवहार से लाभ हो सकता है।
उदाहरण के लिए, कल्पना करें कि आपके पास ऐसा code है जो `yield` वाली dependency में database session का उपयोग केवल user verify करने के लिए करता है, लेकिन database session फिर *path operation function* में कभी उपयोग नहीं होता, केवल dependency में उपयोग होता है, **और** response भेजे जाने में लंबा समय लेता है, जैसे `StreamingResponse` जो data धीरे-धीरे भेजता है, लेकिन किसी कारण से database का उपयोग नहीं करता।
इस मामले में, database session तब तक पकड़ा रहेगा जब तक response भेजना समाप्त नहीं हो जाता, लेकिन यदि आप इसका उपयोग नहीं करते हैं, तो इसे पकड़े रखना आवश्यक नहीं होगा।
यह इस तरह दिख सकता है:
{* ../../docs_src/dependencies/tutorial013_an_py310.py *}
Exit code, यानी `Session` का automatic closing, यहाँ:
{* ../../docs_src/dependencies/tutorial013_an_py310.py ln[19:21] *}
...response द्वारा slow data भेजना समाप्त करने के बाद run होगा:
{* ../../docs_src/dependencies/tutorial013_an_py310.py ln[30:38] hl[31:33] *}
लेकिन क्योंकि `generate_stream()` database session का उपयोग नहीं करता, response भेजते समय session को खुला रखना वास्तव में आवश्यक नहीं है।
यदि आपके पास SQLModel (या SQLAlchemy) का उपयोग करते हुए यह specific use case है, तो आप session को तब explicit रूप से बंद कर सकते हैं जब आपको इसकी आगे आवश्यकता न हो:
{* ../../docs_src/dependencies/tutorial014_an_py310.py ln[24:28] hl[28] *}
इस तरह session database connection release कर देगा, ताकि अन्य requests उसका उपयोग कर सकें।
यदि आपके पास कोई अलग use case है जिसे `yield` वाली dependency से early exit करने की आवश्यकता है, तो कृपया अपने specific use case और dependencies with `yield` के लिए early closing से आपको क्यों लाभ होगा, इसके साथ एक [GitHub Discussion Question](https://github.com/fastapi/fastapi/discussions/new?category=questions) बनाएँ।
यदि dependencies with `yield` में early closing के लिए compelling use cases होते हैं, तो मैं early closing में opt in करने का नया तरीका जोड़ने पर विचार करूँगा।
### `yield` और `except` वाली Dependencies, तकनीकी विवरण { #dependencies-with-yield-and-except-technical-details }
FastAPI 0.110.0 से पहले, यदि आप `yield` वाली dependency उपयोग करते थे, और फिर उस dependency में `except` के साथ exception capture करते थे, और exception को फिर से raise नहीं करते थे, तो exception automatic रूप से किसी भी exception handlers या internal server error handler को raise/forward कर दिया जाता था।
यह version 0.110.0 में बदला गया ताकि handler के बिना forwarded exceptions (internal server errors) से होने वाली unhandled memory consumption ठीक की जा सके, और इसे regular Python code के व्यवहार के साथ consistent बनाया जा सके।
### Background Tasks और `yield` वाली Dependencies, तकनीकी विवरण { #background-tasks-and-dependencies-with-yield-technical-details }
FastAPI 0.106.0 से पहले, `yield` के बाद exceptions raise करना संभव नहीं था, `yield` वाली dependencies में exit code response भेजे जाने के *बाद* execute होता था, इसलिए [Exception Handlers](../tutorial/handling-errors.md#install-custom-exception-handlers) पहले ही run हो चुके होते।
इसे मुख्य रूप से इस तरह design किया गया था ताकि dependencies द्वारा "yielded" किए गए उन्हीं objects को background tasks के अंदर उपयोग किया जा सके, क्योंकि exit code background tasks के समाप्त होने के बाद execute होता था।
यह FastAPI 0.106.0 में बदला गया, इस इरादे से कि response के network से गुजरने की प्रतीक्षा करते समय resources को पकड़े न रखा जाए।
/// tip | सुझाव
इसके अतिरिक्त, background task सामान्यतः logic का एक independent set होता है जिसे अलग से संभाला जाना चाहिए, अपने स्वयं के resources के साथ (जैसे उसका अपना database connection)।
इसलिए, इस तरह आपके पास शायद अधिक साफ़ code होगा।
///
यदि आप इस व्यवहार पर निर्भर थे, तो अब आपको background tasks के लिए resources background task के अंदर ही बनाने चाहिए, और internally केवल ऐसा data उपयोग करना चाहिए जो `yield` वाली dependencies के resources पर निर्भर न हो।
उदाहरण के लिए, उसी database session का उपयोग करने के बजाय, आप background task के अंदर एक नया database session बनाएँगे, और इस नए session का उपयोग करके database से objects प्राप्त करेंगे। और फिर database से object को background task function में parameter के रूप में पास करने के बजाय, आप उस object की ID पास करेंगे और फिर background task function के अंदर object को फिर से प्राप्त करेंगे।
@@ -0,0 +1,61 @@
# उन्नत Python Types { #advanced-python-types }
Python types के साथ काम करते समय यहाँ कुछ अतिरिक्त विचार हैं जो उपयोगी हो सकते हैं।
## `Union` या `Optional` का उपयोग { #using-union-or-optional }
अगर आपका code किसी कारण से `|` का उपयोग नहीं कर सकता, उदाहरण के लिए अगर यह type annotation में नहीं बल्कि `response_model=` जैसी किसी चीज़ में है, तो vertical bar (`|`) का उपयोग करने के बजाय आप `typing` से `Union` का उपयोग कर सकते हैं।
उदाहरण के लिए, आप declare कर सकते हैं कि कोई चीज़ `str` या `None` हो सकती है:
```python
from typing import Union
def say_hi(name: Union[str, None]):
print(f"Hi {name}!")
```
`typing` में `Optional` के साथ यह declare करने का एक shortcut भी है कि कोई चीज़ `None` हो सकती है।
मेरे बहुत **subjective** दृष्टिकोण से एक tip यहाँ है:
* 🚨 `Optional[SomeType]` का उपयोग करने से बचें
* इसके बजाय ✨ **`Union[SomeType, None]` का उपयोग करें** ✨।
दोनों equivalent हैं और अंदर से वे समान हैं, लेकिन मैं `Optional` के बजाय `Union` की सलाह दूँगा क्योंकि "**optional**" शब्द से ऐसा लग सकता है कि value optional है, जबकि इसका वास्तविक अर्थ है "यह `None` हो सकता है", भले ही यह optional न हो और अभी भी required हो।
मुझे लगता है कि `Union[SomeType, None]` अपने अर्थ के बारे में अधिक explicit है।
यह बस शब्दों और नामों की बात है। लेकिन ये शब्द इस बात को प्रभावित कर सकते हैं कि आप और आपके teammates code के बारे में कैसे सोचते हैं।
एक उदाहरण के रूप में, इस function को लेते हैं:
```python
from typing import Optional
def say_hi(name: Optional[str]):
print(f"Hey {name}!")
```
parameter `name` को `Optional[str]` के रूप में define किया गया है, लेकिन यह **optional नहीं है**, आप function को parameter के बिना call नहीं कर सकते:
```Python
say_hi() # अरे नहीं, यह error throw करता है! 😱
```
`name` parameter **अभी भी required** है (*optional* नहीं) क्योंकि इसमें default value नहीं है। फिर भी, `name` value के रूप में `None` स्वीकार करता है:
```Python
say_hi(name=None) # यह काम करता है, None valid है 🎉
```
अच्छी खबर यह है कि अधिकतर मामलों में, आप types के unions को define करने के लिए बस `|` का उपयोग कर पाएँगे:
```python
def say_hi(name: str | None):
print(f"Hey {name}!")
```
इसलिए, सामान्यतः आपको `Optional` और `Union` जैसे नामों के बारे में चिंता करने की ज़रूरत नहीं होती। 😎
+99
View File
@@ -0,0 +1,99 @@
# Async Tests { #async-tests }
आपने पहले ही देखा है कि दिए गए `TestClient` का उपयोग करके अपनी **FastAPI** applications को कैसे test किया जाता है। अब तक, आपने केवल synchronous tests लिखना देखा है, `async` functions का उपयोग किए बिना।
अपने tests में asynchronous functions का उपयोग कर पाना उपयोगी हो सकता है, उदाहरण के लिए, जब आप अपने database को asynchronously query कर रहे हों। कल्पना करें कि आप अपनी FastAPI application को requests भेजना test करना चाहते हैं और फिर verify करना चाहते हैं कि आपके backend ने async database library का उपयोग करते हुए database में सही data सफलतापूर्वक लिखा है।
आइए देखें कि हम इसे कैसे काम करवा सकते हैं।
## pytest.mark.anyio { #pytest-mark-anyio }
अगर हम अपने tests में asynchronous functions call करना चाहते हैं, तो हमारे test functions asynchronous होने चाहिए। AnyIO इसके लिए एक अच्छा plugin प्रदान करता है, जो हमें specify करने देता है कि कुछ test functions को asynchronously call किया जाना है।
## HTTPX { #httpx }
भले ही आपकी **FastAPI** application `async def` के बजाय सामान्य `def` functions का उपयोग करती हो, यह अंदर से फिर भी एक `async` application होती है।
`TestClient` अंदर कुछ magic करता है ताकि standard pytest का उपयोग करते हुए आपकी सामान्य `def` test functions में asynchronous FastAPI application को call किया जा सके। लेकिन जब हम इसे asynchronous functions के अंदर उपयोग करते हैं, तो वह magic अब काम नहीं करता। अपने tests को asynchronously चलाने पर, हम अपने test functions के अंदर `TestClient` का उपयोग नहीं कर सकते।
`TestClient` [HTTPX](https://www.python-httpx.org) पर आधारित है, और सौभाग्य से, हम API को test करने के लिए इसे सीधे उपयोग कर सकते हैं।
## उदाहरण { #example }
एक सरल उदाहरण के लिए, आइए [बड़ी Applications](../tutorial/bigger-applications.md) और [Testing](../tutorial/testing.md) में वर्णित file structure जैसी एक structure पर विचार करें:
```
.
├── app
│   ├── __init__.py
│   ├── main.py
│   └── test_main.py
```
file `main.py` में यह होगा:
{* ../../docs_src/async_tests/app_a_py310/main.py *}
file `test_main.py` में `main.py` के लिए tests होंगे, यह अब कुछ ऐसा दिख सकता है:
{* ../../docs_src/async_tests/app_a_py310/test_main.py *}
## इसे चलाएँ { #run-it }
आप अपने tests को हमेशा की तरह इस तरह चला सकते हैं:
<div class="termy">
```console
$ pytest
---> 100%
```
</div>
## विस्तार से { #in-detail }
marker `@pytest.mark.anyio` pytest को बताता है कि इस test function को asynchronously call किया जाना चाहिए:
{* ../../docs_src/async_tests/app_a_py310/test_main.py hl[7] *}
/// tip | सुझाव
ध्यान दें कि test function अब पहले की तरह `TestClient` का उपयोग करते समय केवल `def` नहीं, बल्कि `async def` है।
///
फिर हम app के साथ एक `AsyncClient` बना सकते हैं, और `await` का उपयोग करते हुए इसमें async requests भेज सकते हैं।
{* ../../docs_src/async_tests/app_a_py310/test_main.py hl[9:12] *}
यह इसके बराबर है:
```Python
response = client.get('/')
```
...जिसका उपयोग हम `TestClient` के साथ अपनी requests बनाने के लिए करते थे।
/// tip | सुझाव
ध्यान दें कि हम नए `AsyncClient` के साथ async/await का उपयोग कर रहे हैं - request asynchronous है।
///
/// warning | चेतावनी
अगर आपकी application lifespan events पर निर्भर करती है, तो `AsyncClient` इन events को trigger नहीं करेगा। यह सुनिश्चित करने के लिए कि वे trigger हों, [florimondmanca/asgi-lifespan](https://github.com/florimondmanca/asgi-lifespan#usage) से `LifespanManager` का उपयोग करें।
///
## अन्य asynchronous function calls { #other-asynchronous-function-calls }
क्योंकि testing function अब asynchronous है, आप अब अपने tests में अपनी FastAPI application को requests भेजने के अलावा अन्य `async` functions को भी call (और `await`) कर सकते हैं, ठीक वैसे ही जैसे आप उन्हें अपने code में कहीं और call करते हैं।
/// tip | सुझाव
अगर अपने tests में asynchronous function calls integrate करते समय आपको `RuntimeError: Task attached to a different loop` मिलता है (जैसे [MongoDB's MotorClient](https://stackoverflow.com/questions/41584243/runtimeerror-task-attached-to-a-different-loop) का उपयोग करते समय), तो याद रखें कि जिन objects को event loop की जरूरत होती है, उन्हें केवल async functions के भीतर ही instantiate करें, जैसे कि `@app.on_event("startup")` callback।
///
+466
View File
@@ -0,0 +1,466 @@
# Proxy के पीछे { #behind-a-proxy }
कई स्थितियों में, आप अपने FastAPI app के सामने Traefik या Nginx जैसा **proxy** उपयोग करेंगे।
ये proxies HTTPS certificates और दूसरी चीज़ें संभाल सकते हैं।
## Proxy Forwarded Headers { #proxy-forwarded-headers }
आपकी application के सामने मौजूद **proxy** आम तौर पर requests को आपके **server** तक भेजने से पहले तुरंत कुछ headers सेट करेगा, ताकि server को पता चल सके कि request proxy द्वारा **forwarded** की गई थी, उसे मूल (public) URL पता चल सके, जिसमें domain शामिल हो, कि वह HTTPS उपयोग कर रहा है, आदि।
**server** program (उदाहरण के लिए **FastAPI CLI** के जरिए **Uvicorn**) इन headers को समझने में सक्षम है, और फिर वह जानकारी आपकी application को पास कर सकता है।
लेकिन security के लिए, क्योंकि server को यह नहीं पता कि वह किसी trusted proxy के पीछे है, वह उन headers को interpret नहीं करेगा।
/// note | तकनीकी विवरण
Proxy headers हैं:
* [X-Forwarded-For](https://developer.mozilla.org/en-US/docs/Web/HTTP/Reference/Headers/X-Forwarded-For)
* [X-Forwarded-Proto](https://developer.mozilla.org/en-US/docs/Web/HTTP/Reference/Headers/X-Forwarded-Proto)
* [X-Forwarded-Host](https://developer.mozilla.org/en-US/docs/Web/HTTP/Reference/Headers/X-Forwarded-Host)
///
### Proxy Forwarded Headers सक्षम करें { #enable-proxy-forwarded-headers }
आप FastAPI CLI को *CLI Option* `--forwarded-allow-ips` के साथ शुरू कर सकते हैं और वे IP addresses पास कर सकते हैं जिन पर उन forwarded headers को पढ़ने के लिए भरोसा किया जाना चाहिए।
अगर आप इसे `--forwarded-allow-ips="*"` पर सेट करते हैं, तो यह सभी incoming IPs पर भरोसा करेगा।
अगर आपका **server** किसी trusted **proxy** के पीछे है और केवल proxy ही उससे बात करता है, तो इससे वह उस **proxy** का जो भी IP है, उसे accept करेगा।
<div class="termy">
```console
$ fastapi run --forwarded-allow-ips="*"
<span style="color: green;">INFO</span>: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit)
```
</div>
### HTTPS के साथ Redirects { #redirects-with-https }
उदाहरण के लिए, मान लें कि आप एक *path operation* `/items/` define करते हैं:
{* ../../docs_src/behind_a_proxy/tutorial001_01_py310.py hl[6] *}
अगर client `/items` पर जाने की कोशिश करता है, तो default रूप से, उसे `/items/` पर redirect किया जाएगा।
लेकिन *CLI Option* `--forwarded-allow-ips` सेट करने से पहले यह `http://localhost:8000/items/` पर redirect कर सकता है।
लेकिन शायद आपकी application `https://mysuperapp.com` पर hosted है, और redirection `https://mysuperapp.com/items/` पर होना चाहिए।
अब `--proxy-headers` सेट करने से FastAPI सही location पर redirect कर पाएगा। 😎
```
https://mysuperapp.com/items/
```
/// tip | सुझाव
अगर आप HTTPS के बारे में और जानना चाहते हैं, तो guide [HTTPS के बारे में](../deployment/https.md) देखें।
///
### Proxy Forwarded Headers कैसे काम करते हैं { #how-proxy-forwarded-headers-work }
यहाँ client और **application server** के बीच **proxy** द्वारा forwarded headers जोड़ने का एक visual representation है:
```mermaid
sequenceDiagram
participant Client
participant Proxy as Proxy/Load Balancer
participant Server as FastAPI Server
Client->>Proxy: HTTPS Request<br/>Host: mysuperapp.com<br/>Path: /items
Note over Proxy: Proxy adds forwarded headers
Proxy->>Server: HTTP Request<br/>X-Forwarded-For: [client IP]<br/>X-Forwarded-Proto: https<br/>X-Forwarded-Host: mysuperapp.com<br/>Path: /items
Note over Server: Server interprets headers<br/>(if --forwarded-allow-ips is set)
Server->>Proxy: HTTP Response<br/>with correct HTTPS URLs
Proxy->>Client: HTTPS Response
```
**proxy** मूल client request को intercept करता है और request को **application server** तक पास करने से पहले खास *forwarded* headers (`X-Forwarded-*`) जोड़ता है।
ये headers मूल request के बारे में वह जानकारी सुरक्षित रखते हैं जो अन्यथा खो जाती:
* **X-Forwarded-For**: मूल client का IP address
* **X-Forwarded-Proto**: मूल protocol (`https`)
* **X-Forwarded-Host**: मूल host (`mysuperapp.com`)
जब **FastAPI CLI** को `--forwarded-allow-ips` के साथ configured किया जाता है, तो यह इन headers पर भरोसा करता है और उनका उपयोग करता है, उदाहरण के लिए redirects में सही URLs generate करने के लिए।
## Stripped path prefix वाला Proxy { #proxy-with-a-stripped-path-prefix }
आपके पास ऐसा proxy हो सकता है जो आपकी application में एक path prefix जोड़ता हो।
इन मामलों में आप अपनी application configure करने के लिए `root_path` का उपयोग कर सकते हैं।
`root_path` ASGI specification द्वारा प्रदान किया गया एक mechanism है (जिस पर FastAPI, Starlette के जरिए, बना है)।
`root_path` का उपयोग इन specific cases को handle करने के लिए किया जाता है।
और इसका उपयोग sub-applications mount करते समय internally भी किया जाता है।
इस case में, stripped path prefix वाला proxy होने का मतलब है कि आप अपने code में `/app` पर एक path declare कर सकते हैं, लेकिन फिर आप ऊपर एक layer (proxy) जोड़ते हैं जो आपकी **FastAPI** application को `/api/v1` जैसे path के नीचे रखेगी।
इस case में, मूल path `/app` वास्तव में `/api/v1/app` पर serve किया जाएगा।
हालाँकि आपका सारा code यह मानकर लिखा गया है कि सिर्फ `/app` है।
{* ../../docs_src/behind_a_proxy/tutorial001_py310.py hl[6] *}
और proxy app server (शायद FastAPI CLI के जरिए Uvicorn) तक request भेजने से पहले तुरंत **path prefix** को **"strip"** कर देगा, आपकी application को यह भरोसा दिलाते हुए कि वह `/app` पर serve हो रही है, ताकि आपको prefix `/api/v1` शामिल करने के लिए अपना सारा code update न करना पड़े।
यहाँ तक, सब कुछ सामान्य रूप से काम करेगा।
लेकिन फिर, जब आप integrated docs UI (frontend) खोलेंगे, तो वह OpenAPI schema को `/api/v1/openapi.json` के बजाय `/openapi.json` पर पाने की अपेक्षा करेगा।
इसलिए, frontend (जो browser में चलता है) `/openapi.json` तक पहुँचने की कोशिश करेगा और OpenAPI schema प्राप्त नहीं कर पाएगा।
क्योंकि हमारे app के लिए `/api/v1` का path prefix वाला proxy है, frontend को OpenAPI schema `/api/v1/openapi.json` पर fetch करना होगा।
```mermaid
graph LR
browser("Browser")
proxy["Proxy on http://0.0.0.0:9999/api/v1/app"]
server["Server on http://127.0.0.1:8000/app"]
browser --> proxy
proxy --> server
```
/// tip | सुझाव
IP `0.0.0.0` आम तौर पर यह बताने के लिए उपयोग किया जाता है कि program उस machine/server में उपलब्ध सभी IPs पर listen करता है।
///
Docs UI को OpenAPI schema में यह declare करने की भी ज़रूरत होगी कि यह API `server` `/api/v1` (proxy के पीछे) पर स्थित है। उदाहरण के लिए:
```JSON hl_lines="4-8"
{
"openapi": "3.1.0",
// यहाँ और चीज़ें
"servers": [
{
"url": "/api/v1"
}
],
"paths": {
// यहाँ और चीज़ें
}
}
```
इस उदाहरण में, "Proxy" कुछ **Traefik** जैसा हो सकता है। और server **Uvicorn** के साथ FastAPI CLI जैसा हो सकता है, जो आपकी FastAPI application चला रहा है।
### `root_path` प्रदान करना { #providing-the-root-path }
इसे हासिल करने के लिए, आप command line option `--root-path` इस तरह उपयोग कर सकते हैं:
<div class="termy">
```console
$ fastapi run main.py --forwarded-allow-ips="*" --root-path /api/v1
<span style="color: green;">INFO</span>: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit)
```
</div>
अगर आप Hypercorn उपयोग करते हैं, तो उसमें भी option `--root-path` है।
/// note | तकनीकी विवरण
ASGI specification इस use case के लिए `root_path` define करती है।
और `--root-path` command line option वही `root_path` प्रदान करता है।
///
### वर्तमान `root_path` जाँचना { #checking-the-current-root-path }
आप प्रत्येक request के लिए आपकी application द्वारा उपयोग किया गया वर्तमान `root_path` प्राप्त कर सकते हैं, यह `scope` dictionary का हिस्सा है (जो ASGI spec का हिस्सा है)।
यहाँ हम इसे केवल demonstration purposes के लिए message में शामिल कर रहे हैं।
{* ../../docs_src/behind_a_proxy/tutorial001_py310.py hl[8] *}
फिर, अगर आप Uvicorn को इस तरह शुरू करते हैं:
<div class="termy">
```console
$ fastapi run main.py --forwarded-allow-ips="*" --root-path /api/v1
<span style="color: green;">INFO</span>: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit)
```
</div>
Response कुछ ऐसा होगा:
```JSON
{
"message": "Hello World",
"root_path": "/api/v1"
}
```
### FastAPI app में `root_path` सेट करना { #setting-the-root-path-in-the-fastapi-app }
वैकल्पिक रूप से, अगर आपके पास `--root-path` या equivalent जैसा command line option देने का तरीका नहीं है, तो आप अपनी FastAPI app बनाते समय `root_path` parameter सेट कर सकते हैं:
{* ../../docs_src/behind_a_proxy/tutorial002_py310.py hl[3] *}
`root_path` को `FastAPI` में पास करना, Uvicorn या Hypercorn को `--root-path` command line option पास करने के equivalent होगा।
### `root_path` के बारे में { #about-root-path }
ध्यान रखें कि server (Uvicorn) उस `root_path` का उपयोग app को पास करने के अलावा किसी और चीज़ के लिए नहीं करेगा।
लेकिन अगर आप अपने browser में [http://127.0.0.1:8000/app](http://127.0.0.1:8000/app) पर जाते हैं, तो आपको normal response दिखाई देगा:
```JSON
{
"message": "Hello World",
"root_path": "/api/v1"
}
```
इसलिए, यह `http://127.0.0.1:8000/api/v1/app` पर access किए जाने की अपेक्षा नहीं करेगा।
Uvicorn अपेक्षा करेगा कि proxy Uvicorn को `http://127.0.0.1:8000/app` पर access करे, और फिर ऊपर extra `/api/v1` prefix जोड़ना proxy की जिम्मेदारी होगी।
## Stripped path prefix वाले proxies के बारे में { #about-proxies-with-a-stripped-path-prefix }
ध्यान रखें कि stripped path prefix वाला proxy इसे configure करने के तरीकों में से केवल एक है।
शायद कई cases में default यह होगा कि proxy के पास stripped path prefix नहीं होगा।
ऐसे case में (बिना stripped path prefix के), proxy कुछ `https://myawesomeapp.com` जैसा listen करेगा, और फिर अगर browser `https://myawesomeapp.com/api/v1/app` पर जाता है और आपका server (जैसे Uvicorn) `http://127.0.0.1:8000` पर listen करता है, तो proxy (बिना stripped path prefix के) Uvicorn को उसी path पर access करेगा: `http://127.0.0.1:8000/api/v1/app`
## Traefik के साथ local testing { #testing-locally-with-traefik }
आप [Traefik](https://docs.traefik.io/) का उपयोग करके stripped path prefix के साथ experiment आसानी से locally चला सकते हैं।
[Traefik download करें](https://github.com/containous/traefik/releases), यह एक single binary है, आप compressed file extract कर सकते हैं और इसे सीधे terminal से चला सकते हैं।
फिर `traefik.toml` नाम की file बनाएँ जिसमें यह हो:
```TOML hl_lines="3"
[entryPoints]
[entryPoints.http]
address = ":9999"
[providers]
[providers.file]
filename = "routes.toml"
```
यह Traefik को port 9999 पर listen करने और दूसरी file `routes.toml` उपयोग करने के लिए कहता है।
/// tip | सुझाव
हम standard HTTP port 80 के बजाय port 9999 उपयोग कर रहे हैं ताकि आपको इसे admin (`sudo`) privileges के साथ न चलाना पड़े।
///
अब वह दूसरी file `routes.toml` बनाएँ:
```TOML hl_lines="5 12 20"
[http]
[http.middlewares]
[http.middlewares.api-stripprefix.stripPrefix]
prefixes = ["/api/v1"]
[http.routers]
[http.routers.app-http]
entryPoints = ["http"]
service = "app"
rule = "PathPrefix(`/api/v1`)"
middlewares = ["api-stripprefix"]
[http.services]
[http.services.app]
[http.services.app.loadBalancer]
[[http.services.app.loadBalancer.servers]]
url = "http://127.0.0.1:8000"
```
यह file Traefik को path prefix `/api/v1` उपयोग करने के लिए configure करती है।
और फिर Traefik अपनी requests को `http://127.0.0.1:8000` पर चल रहे आपके Uvicorn पर redirect करेगा।
अब Traefik शुरू करें:
<div class="termy">
```console
$ ./traefik --configFile=traefik.toml
INFO[0000] Configuration loaded from file: /home/user/awesomeapi/traefik.toml
```
</div>
और अब `--root-path` option का उपयोग करके अपना app शुरू करें:
<div class="termy">
```console
$ fastapi run main.py --forwarded-allow-ips="*" --root-path /api/v1
<span style="color: green;">INFO</span>: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit)
```
</div>
### Responses जाँचें { #check-the-responses }
अब, अगर आप Uvicorn के port वाले URL पर जाते हैं: [http://127.0.0.1:8000/app](http://127.0.0.1:8000/app), तो आपको normal response दिखाई देगा:
```JSON
{
"message": "Hello World",
"root_path": "/api/v1"
}
```
/// tip | सुझाव
ध्यान दें कि भले ही आप इसे `http://127.0.0.1:8000/app` पर access कर रहे हैं, यह option `--root-path` से लिया गया `/api/v1` का `root_path` दिखाता है।
///
और अब Traefik के port वाले URL को खोलें, जिसमें path prefix शामिल है: [http://127.0.0.1:9999/api/v1/app](http://127.0.0.1:9999/api/v1/app)।
हमें वही response मिलता है:
```JSON
{
"message": "Hello World",
"root_path": "/api/v1"
}
```
लेकिन इस बार proxy द्वारा प्रदान किए गए prefix path वाले URL पर: `/api/v1`
बेशक, यहाँ विचार यह है कि हर कोई app को proxy के जरिए access करेगा, इसलिए path prefix `/api/v1` वाला version "correct" है।
और बिना path prefix वाला version (`http://127.0.0.1:8000/app`), जो सीधे Uvicorn द्वारा प्रदान किया गया है, केवल _proxy_ (Traefik) के access के लिए होगा।
यह दिखाता है कि Proxy (Traefik) path prefix का उपयोग कैसे करता है और server (Uvicorn) option `--root-path` से `root_path` का उपयोग कैसे करता है।
### Docs UI जाँचें { #check-the-docs-ui }
लेकिन यहाँ मज़ेदार हिस्सा है। ✨
App को access करने का "official" तरीका उस path prefix वाले proxy के जरिए होगा जिसे हमने define किया है। इसलिए, जैसा कि हम अपेक्षा करेंगे, अगर आप Uvicorn द्वारा सीधे serve किया गया docs UI try करते हैं, URL में path prefix के बिना, तो यह काम नहीं करेगा, क्योंकि यह proxy के जरिए access किए जाने की अपेक्षा करता है।
आप इसे [http://127.0.0.1:8000/docs](http://127.0.0.1:8000/docs) पर देख सकते हैं:
<img src="/img/tutorial/behind-a-proxy/image01.png">
लेकिन अगर हम port `9999` वाले proxy का उपयोग करके "official" URL पर, `/api/v1/docs` पर docs UI access करते हैं, तो यह सही तरीके से काम करता है! 🎉
आप इसे [http://127.0.0.1:9999/api/v1/docs](http://127.0.0.1:9999/api/v1/docs) पर देख सकते हैं:
<img src="/img/tutorial/behind-a-proxy/image02.png">
बिल्कुल जैसा हम चाहते थे। ✔️
ऐसा इसलिए है क्योंकि FastAPI इस `root_path` का उपयोग OpenAPI में default `server` बनाने के लिए करता है, जिसमें `root_path` द्वारा दिया गया URL होता है।
## अतिरिक्त servers { #additional-servers }
/// warning | चेतावनी
यह एक अधिक advanced use case है। चाहें तो इसे skip कर सकते हैं।
///
Default रूप से, **FastAPI** OpenAPI schema में `root_path` के URL वाला एक `server` बनाएगा।
लेकिन आप अन्य alternative `servers` भी प्रदान कर सकते हैं, उदाहरण के लिए अगर आप चाहते हैं कि *वही* docs UI staging और production environment दोनों के साथ interact करे।
अगर आप `servers` की custom list पास करते हैं और कोई `root_path` है (क्योंकि आपकी API proxy के पीछे रहती है), तो **FastAPI** list की शुरुआत में इस `root_path` के साथ एक "server" insert करेगा।
उदाहरण के लिए:
{* ../../docs_src/behind_a_proxy/tutorial003_py310.py hl[4:7] *}
यह इस तरह का OpenAPI schema generate करेगा:
```JSON hl_lines="5-7"
{
"openapi": "3.1.0",
// यहाँ और चीज़ें
"servers": [
{
"url": "/api/v1"
},
{
"url": "https://stag.example.com",
"description": "Staging environment"
},
{
"url": "https://prod.example.com",
"description": "Production environment"
}
],
"paths": {
// यहाँ और चीज़ें
}
}
```
/// tip | सुझाव
ध्यान दें कि `/api/v1` के `url` value वाला auto-generated server `root_path` से लिया गया है।
///
[http://127.0.0.1:9999/api/v1/docs](http://127.0.0.1:9999/api/v1/docs) पर docs UI में यह ऐसा दिखेगा:
<img src="/img/tutorial/behind-a-proxy/image03.png">
/// tip | सुझाव
Docs UI आपके द्वारा चुने गए server के साथ interact करेगा।
///
/// note | तकनीकी विवरण
OpenAPI specification में `servers` property optional है।
अगर आप `servers` parameter specify नहीं करते और `root_path` `/` के बराबर है, तो generated OpenAPI schema में `servers` property default रूप से पूरी तरह omit कर दी जाएगी, जो `/` के `url` value वाले single server के equivalent है।
///
### `root_path` से automatic server disable करें { #disable-automatic-server-from-root-path }
अगर आप नहीं चाहते कि **FastAPI** `root_path` का उपयोग करके automatic server शामिल करे, तो आप parameter `root_path_in_servers=False` उपयोग कर सकते हैं:
{* ../../docs_src/behind_a_proxy/tutorial004_py310.py hl[9] *}
और फिर यह उसे OpenAPI schema में शामिल नहीं करेगा।
## Sub-application mount करना { #mounting-a-sub-application }
अगर आपको `root_path` वाले proxy का उपयोग करते हुए भी sub-application mount करनी है (जैसा कि [Sub Applications - Mounts](sub-applications.md) में बताया गया है), तो आप इसे सामान्य रूप से कर सकते हैं, जैसा कि आप अपेक्षा करेंगे।
FastAPI internally `root_path` का smart तरीके से उपयोग करेगा, इसलिए यह बस काम करेगा। ✨
+273
View File
@@ -0,0 +1,273 @@
# कस्टम Response - HTML, Stream, File, अन्य { #custom-response-html-stream-file-others }
Default रूप से, **FastAPI** JSON responses लौटाएगा।
आप [सीधे Response लौटाएँ](response-directly.md) में दिखाए गए अनुसार सीधे `Response` लौटाकर इसे override कर सकते हैं।
लेकिन अगर आप सीधे `Response` लौटाते हैं (या कोई subclass, जैसे `JSONResponse`), तो data अपने आप convert नहीं होगा (भले ही आप `response_model` declare करें), और documentation अपने आप generate नहीं होगी (उदाहरण के लिए, generated OpenAPI के हिस्से के रूप में HTTP header `Content-Type` में specific "media type" शामिल करना)।
लेकिन आप *path operation decorator* में `response_class` parameter का उपयोग करके वह `Response` भी declare कर सकते हैं जिसे आप उपयोग करना चाहते हैं (जैसे कोई भी `Response` subclass)।
आप अपनी *path operation function* से जो contents लौटाते हैं, उन्हें उस `Response` के अंदर रख दिया जाएगा।
/// note | नोट
यदि आप बिना media type वाली response class का उपयोग करते हैं, तो FastAPI अपेक्षा करेगा कि आपके response में कोई content न हो, इसलिए यह अपने generated OpenAPI docs में response format को document नहीं करेगा।
///
## JSON Responses { #json-responses }
Default रूप से FastAPI JSON responses लौटाता है।
यदि आप [Response Model](../tutorial/response-model.md) declare करते हैं तो FastAPI Pydantic का उपयोग करके data को JSON में serialize करने के लिए उसका उपयोग करेगा।
यदि आप response model declare नहीं करते हैं, तो FastAPI [JSON Compatible Encoder](../tutorial/encoder.md) में समझाए गए `jsonable_encoder` का उपयोग करेगा और उसे `JSONResponse` में रखेगा।
यदि आप JSON media type (`application/json`) के साथ `response_class` declare करते हैं, जैसा कि `JSONResponse` के साथ होता है, तो आपके द्वारा लौटाया गया data आपकी *path operation decorator* में declare किए गए किसी भी Pydantic `response_model` के साथ अपने आप convert (और filter) हो जाएगा। लेकिन data Pydantic के साथ JSON bytes में serialize नहीं होगा, इसके बजाय इसे `jsonable_encoder` के साथ convert किया जाएगा और फिर `JSONResponse` class को pass किया जाएगा, जो Python की standard JSON library का उपयोग करके इसे bytes में serialize करेगी।
### JSON Performance { #json-performance }
संक्षेप में, यदि आप maximum performance चाहते हैं, तो [Response Model](../tutorial/response-model.md) का उपयोग करें और *path operation decorator* में `response_class` declare न करें।
{* ../../docs_src/response_model/tutorial001_01_py310.py ln[15:17] hl[16] *}
## HTML Response { #html-response }
**FastAPI** से सीधे HTML के साथ response लौटाने के लिए, `HTMLResponse` का उपयोग करें।
* `HTMLResponse` import करें।
* अपने *path operation decorator* के parameter `response_class` के रूप में `HTMLResponse` pass करें।
{* ../../docs_src/custom_response/tutorial002_py310.py hl[2,7] *}
/// note | नोट
Parameter `response_class` का उपयोग response के "media type" को define करने के लिए भी किया जाएगा।
इस मामले में, HTTP header `Content-Type` को `text/html` पर set किया जाएगा।
और इसे OpenAPI में इसी तरह document किया जाएगा।
///
### `Response` लौटाएँ { #return-a-response }
जैसा कि [सीधे Response लौटाएँ](response-directly.md) में देखा गया है, आप अपनी *path operation* में response को सीधे लौटाकर भी override कर सकते हैं।
ऊपर वाला वही उदाहरण, जो `HTMLResponse` लौटाता है, इस तरह दिख सकता है:
{* ../../docs_src/custom_response/tutorial003_py310.py hl[2,7,19] *}
/// warning | चेतावनी
आपकी *path operation function* द्वारा सीधे लौटाया गया `Response` OpenAPI में document नहीं होगा (उदाहरण के लिए, `Content-Type` document नहीं होगा) और automatic interactive docs में visible नहीं होगा।
///
/// note | नोट
बेशक, वास्तविक `Content-Type` header, status code, आदि, आपके द्वारा लौटाए गए `Response` object से आएँगे।
///
### OpenAPI में document करें और `Response` override करें { #document-in-openapi-and-override-response }
यदि आप function के अंदर से response को override करना चाहते हैं लेकिन साथ ही OpenAPI में "media type" document करना चाहते हैं, तो आप `response_class` parameter का उपयोग कर सकते हैं और `Response` object भी लौटा सकते हैं।
तब `response_class` का उपयोग केवल OpenAPI *path operation* को document करने के लिए किया जाएगा, लेकिन आपका `Response` जैसा है वैसा ही उपयोग किया जाएगा।
#### सीधे `HTMLResponse` लौटाएँ { #return-an-htmlresponse-directly }
उदाहरण के लिए, यह कुछ ऐसा हो सकता है:
{* ../../docs_src/custom_response/tutorial004_py310.py hl[7,21,23] *}
इस उदाहरण में, function `generate_html_response()` पहले से ही HTML को `str` में लौटाने के बजाय `Response` generate करके लौटाता है।
`generate_html_response()` को call करने का result लौटाकर, आप पहले से ही एक `Response` लौटा रहे हैं जो default **FastAPI** behavior को override करेगा।
लेकिन क्योंकि आपने `response_class` में भी `HTMLResponse` pass किया है, **FastAPI** को पता होगा कि इसे OpenAPI और interactive docs में `text/html` के साथ HTML के रूप में कैसे document करना है:
<img src="/img/tutorial/custom-response/image01.png">
## उपलब्ध responses { #available-responses }
यहाँ कुछ उपलब्ध responses दिए गए हैं।
ध्यान रखें कि आप कुछ और लौटाने के लिए `Response` का उपयोग कर सकते हैं, या custom sub-class भी बना सकते हैं।
/// note | तकनीकी विवरण
आप `from starlette.responses import HTMLResponse` भी उपयोग कर सकते हैं।
**FastAPI** आपकी सुविधा के लिए, developer के रूप में, वही `starlette.responses` `fastapi.responses` के रूप में प्रदान करता है। लेकिन अधिकांश उपलब्ध responses सीधे Starlette से आते हैं।
///
### `Response` { #response }
मुख्य `Response` class, बाकी सभी responses इससे inherit करते हैं।
आप इसे सीधे लौटा सकते हैं।
यह निम्नलिखित parameters accept करता है:
* `content` - एक `str` या `bytes`
* `status_code` - एक `int` HTTP status code।
* `headers` - strings का एक `dict`
* `media_type` - media type बताने वाला एक `str`। उदाहरण के लिए `"text/html"`
FastAPI (असल में Starlette) अपने आप एक Content-Length header शामिल करेगा। यह `media_type` के आधार पर Content-Type header भी शामिल करेगा और text types के लिए charset append करेगा।
{* ../../docs_src/response_directly/tutorial002_py310.py hl[1,18] *}
### `HTMLResponse` { #htmlresponse }
कुछ text या bytes लेता है और HTML response लौटाता है, जैसा आपने ऊपर पढ़ा।
### `PlainTextResponse` { #plaintextresponse }
कुछ text या bytes लेता है और plain text response लौटाता है।
{* ../../docs_src/custom_response/tutorial005_py310.py hl[2,7,9] *}
### `JSONResponse` { #jsonresponse }
कुछ data लेता है और `application/json` encoded response लौटाता है।
जैसा आपने ऊपर पढ़ा, यह **FastAPI** में उपयोग किया जाने वाला default response है।
/// note | तकनीकी विवरण
लेकिन यदि आप response model या return type declare करते हैं, तो उसका उपयोग सीधे data को JSON में serialize करने के लिए किया जाएगा, और JSON के लिए सही media type वाला response सीधे लौटाया जाएगा, `JSONResponse` class का उपयोग किए बिना।
यह best performance पाने का ideal तरीका है।
///
### `RedirectResponse` { #redirectresponse }
HTTP redirect लौटाता है। Default रूप से 307 status code (Temporary Redirect) का उपयोग करता है।
आप सीधे `RedirectResponse` लौटा सकते हैं:
{* ../../docs_src/custom_response/tutorial006_py310.py hl[2,9] *}
---
या आप इसे `response_class` parameter में उपयोग कर सकते हैं:
{* ../../docs_src/custom_response/tutorial006b_py310.py hl[2,7,9] *}
यदि आप ऐसा करते हैं, तो आप अपनी *path operation* function से URL सीधे लौटा सकते हैं।
इस मामले में, उपयोग किया गया `status_code` `RedirectResponse` के लिए default वाला होगा, जो `307` है।
---
आप `status_code` parameter को `response_class` parameter के साथ combine करके भी उपयोग कर सकते हैं:
{* ../../docs_src/custom_response/tutorial006c_py310.py hl[2,7,9] *}
### `StreamingResponse` { #streamingresponse }
एक async generator या सामान्य generator/iterator (`yield` वाली function) लेता है और response body को stream करता है।
{* ../../docs_src/custom_response/tutorial007_py310.py hl[3,16] *}
/// note | तकनीकी विवरण
एक `async` task केवल तब cancel किया जा सकता है जब वह किसी `await` तक पहुँचता है। यदि कोई `await` नहीं है, तो generator (`yield` वाली function) ठीक से cancel नहीं हो सकता और cancellation request किए जाने के बाद भी चलना जारी रख सकता है।
चूँकि इस छोटे उदाहरण को किसी `await` statement की आवश्यकता नहीं है, हम event loop को cancellation handle करने का अवसर देने के लिए `await anyio.sleep(0)` जोड़ते हैं।
यह बड़े या infinite streams के साथ और भी अधिक महत्वपूर्ण होगा।
///
/// tip | टिप
सीधे `StreamingResponse` लौटाने के बजाय, आपको शायद [Stream Data](./stream-data.md) में दिए गए style का पालन करना चाहिए, यह कहीं अधिक सुविधाजनक है और आपके लिए पर्दे के पीछे cancellation handle करता है।
यदि आप JSON Lines stream कर रहे हैं, तो [Stream JSON Lines](../tutorial/stream-json-lines.md) tutorial का पालन करें।
///
### `FileResponse` { #fileresponse }
एक file को response के रूप में asynchronously stream करता है।
Instantiate करने के लिए अन्य response types की तुलना में अलग set of arguments लेता है:
* `path` - stream की जाने वाली file का file path।
* `headers` - dictionary के रूप में शामिल किए जाने वाले कोई भी custom headers।
* `media_type` - media type बताने वाली string। यदि unset है, तो media type infer करने के लिए filename या path का उपयोग किया जाएगा।
* `filename` - यदि set है, तो इसे response `Content-Disposition` में शामिल किया जाएगा।
File responses में उपयुक्त `Content-Length`, `Last-Modified` और `ETag` headers शामिल होंगे।
{* ../../docs_src/custom_response/tutorial009_py310.py hl[2,10] *}
आप `response_class` parameter का उपयोग भी कर सकते हैं:
{* ../../docs_src/custom_response/tutorial009b_py310.py hl[2,8,10] *}
इस मामले में, आप अपनी *path operation* function से file path सीधे लौटा सकते हैं।
## Custom response class { #custom-response-class }
आप `Response` से inherit करके और उसका उपयोग करके अपनी खुद की custom response class बना सकते हैं।
उदाहरण के लिए, मान लें कि आप कुछ settings के साथ [`orjson`](https://github.com/ijl/orjson) का उपयोग करना चाहते हैं।
मान लें आप चाहते हैं कि यह indented और formatted JSON लौटाए, इसलिए आप orjson option `orjson.OPT_INDENT_2` का उपयोग करना चाहते हैं।
आप `CustomORJSONResponse` बना सकते हैं। आपको मुख्य रूप से `Response.render(content)` method बनाना है जो content को `bytes` के रूप में लौटाता है:
{* ../../docs_src/custom_response/tutorial009c_py310.py hl[9:14,17] *}
अब यह लौटाने के बजाय:
```json
{"message": "Hello World"}
```
...यह response लौटाएगा:
```json
{
"message": "Hello World"
}
```
बेशक, JSON formatting की तुलना में इसका लाभ उठाने के लिए आपको शायद कहीं बेहतर तरीके मिलेंगे। 😉
### `orjson` या Response Model { #orjson-or-response-model }
यदि आप performance खोज रहे हैं, तो शायद `orjson` response की तुलना में [Response Model](../tutorial/response-model.md) का उपयोग करना आपके लिए बेहतर होगा।
Response model के साथ, FastAPI data को JSON में serialize करने के लिए Pydantic का उपयोग करेगा, intermediate steps के बिना, जैसे `jsonable_encoder` के साथ convert करना, जो किसी भी अन्य मामले में होता।
और अंदर से, Pydantic JSON में serialize करने के लिए `orjson` जैसे ही underlying Rust mechanisms का उपयोग करता है, इसलिए response model के साथ आपको पहले से ही best performance मिल जाएगी।
## Default response class { #default-response-class }
**FastAPI** class instance या `APIRouter` बनाते समय आप specify कर सकते हैं कि default रूप से कौन-सी response class उपयोग करनी है।
इसे define करने वाला parameter `default_response_class` है।
नीचे दिए गए उदाहरण में, **FastAPI** सभी *path operations* में JSON के बजाय default रूप से `HTMLResponse` का उपयोग करेगा।
{* ../../docs_src/custom_response/tutorial010_py310.py hl[2,4] *}
/// tip | टिप
आप पहले की तरह *path operations* में अब भी `response_class` override कर सकते हैं।
///
## अतिरिक्त documentation { #additional-documentation }
आप `responses` का उपयोग करके OpenAPI में media type और कई अन्य details भी declare कर सकते हैं: [OpenAPI में अतिरिक्त Responses](additional-responses.md)।
+95
View File
@@ -0,0 +1,95 @@
# Dataclasses का उपयोग { #using-dataclasses }
FastAPI **Pydantic** के ऊपर बनाया गया है, और मैंने आपको दिखाया है कि requests और responses घोषित करने के लिए Pydantic models का उपयोग कैसे करें।
लेकिन FastAPI उसी तरह [`dataclasses`](https://docs.python.org/3/library/dataclasses.html) का उपयोग भी support करता है:
{* ../../docs_src/dataclasses_/tutorial001_py310.py hl[1,6:11,18:19] *}
यह अभी भी **Pydantic** की वजह से support किया जाता है, क्योंकि इसमें [`dataclasses` के लिए internal support](https://docs.pydantic.dev/latest/concepts/dataclasses/#use-of-stdlib-dataclasses-with-basemodel) है।
इसलिए, ऊपर दिए गए code में भी, जो Pydantic का स्पष्ट रूप से उपयोग नहीं करता, FastAPI उन standard dataclasses को Pydantic की अपनी तरह की dataclasses में बदलने के लिए Pydantic का उपयोग कर रहा है।
और निश्चित रूप से, यह इन्हें भी support करता है:
* data validation
* data serialization
* data documentation, आदि।
यह Pydantic models की तरह ही काम करता है। और अंदर से यह वास्तव में उसी तरह, Pydantic का उपयोग करके हासिल किया जाता है।
/// note | नोट
ध्यान रखें कि dataclasses वह सब कुछ नहीं कर सकतीं जो Pydantic models कर सकते हैं।
इसलिए, आपको अभी भी Pydantic models का उपयोग करना पड़ सकता है।
लेकिन अगर आपके पास बहुत सारी dataclasses पहले से मौजूद हैं, तो FastAPI का उपयोग करके web API को power देने के लिए उनका उपयोग करने की यह एक अच्छी तरकीब है। 🤓
///
## `response_model` में Dataclasses { #dataclasses-in-response-model }
आप `response_model` parameter में भी `dataclasses` का उपयोग कर सकते हैं:
{* ../../docs_src/dataclasses_/tutorial002_py310.py hl[1,6:12,18] *}
dataclass अपने आप Pydantic dataclass में बदल जाएगी।
इस तरह, उसका schema API docs के user interface में दिखाई देगा:
<img src="/img/tutorial/dataclasses/image01.png">
## Nested Data Structures में Dataclasses { #dataclasses-in-nested-data-structures }
आप nested data structures बनाने के लिए `dataclasses` को अन्य type annotations के साथ भी जोड़ सकते हैं।
कुछ मामलों में, आपको अभी भी Pydantic के `dataclasses` वाले version का उपयोग करना पड़ सकता है। उदाहरण के लिए, अगर automatically generated API documentation में errors हों।
उस स्थिति में, आप standard `dataclasses` को बस `pydantic.dataclasses` से बदल सकते हैं, जो एक drop-in replacement है:
{* ../../docs_src/dataclasses_/tutorial003_py310.py hl[1,4,7:10,13:16,22:24,27] *}
1. हम अभी भी standard `dataclasses` से `field` import करते हैं।
2. `pydantic.dataclasses`, `dataclasses` के लिए एक drop-in replacement है।
3. `Author` dataclass में `Item` dataclasses की एक list शामिल है।
4. `Author` dataclass को `response_model` parameter के रूप में उपयोग किया गया है।
5. आप request body के रूप में dataclasses के साथ अन्य standard type annotations का उपयोग कर सकते हैं।
इस मामले में, यह `Item` dataclasses की एक list है।
6. यहाँ हम एक dictionary return कर रहे हैं जिसमें `items` है, जो dataclasses की एक list है।
FastAPI अभी भी data को JSON में <dfn title="data को ऐसे format में बदलना जिसे भेजा जा सके">serialize करने</dfn> में सक्षम है।
7. यहाँ `response_model`, `Author` dataclasses की list के type annotation का उपयोग कर रहा है।
फिर से, आप `dataclasses` को standard type annotations के साथ जोड़ सकते हैं।
8. ध्यान दें कि यह *path operation function* `async def` की बजाय सामान्य `def` का उपयोग करता है।
हमेशा की तरह, FastAPI में आप आवश्यकता के अनुसार `def` और `async def` को जोड़ सकते हैं।
अगर आपको यह याद दिलाने की आवश्यकता है कि किसे कब उपयोग करना है, तो [`async` और `await`](../async.md#in-a-hurry) के docs में _"जल्दी में हैं?"_ section देखें।
9. यह *path operation function* dataclasses return नहीं कर रहा है (हालाँकि कर सकता था), बल्कि internal data वाली dictionaries की list return कर रहा है।
FastAPI response को बदलने के लिए `response_model` parameter (जिसमें dataclasses शामिल हैं) का उपयोग करेगा।
आप जटिल data structures बनाने के लिए `dataclasses` को कई अलग-अलग combinations में अन्य type annotations के साथ जोड़ सकते हैं।
अधिक विशिष्ट विवरण देखने के लिए ऊपर दिए गए in-code annotation tips देखें।
## और जानें { #learn-more }
आप `dataclasses` को अन्य Pydantic models के साथ भी जोड़ सकते हैं, उनसे inherit कर सकते हैं, उन्हें अपने models में शामिल कर सकते हैं, आदि।
अधिक जानने के लिए, [dataclasses के बारे में Pydantic docs](https://docs.pydantic.dev/latest/concepts/dataclasses/) देखें।
## Version { #version }
यह FastAPI version `0.67.0` से उपलब्ध है। 🔖
+165
View File
@@ -0,0 +1,165 @@
# Lifespan Events { #lifespan-events }
आप ऐसी logic (code) define कर सकते हैं जिसे application के **starts up** होने से पहले execute किया जाना चाहिए। इसका मतलब है कि यह code application के **requests receive करना शुरू करने से पहले**, **एक बार** execute होगा।
उसी तरह, आप ऐसी logic (code) define कर सकते हैं जिसे application के **shutting down** होने पर execute किया जाना चाहिए। इस मामले में, यह code संभवतः **कई requests** handle करने के **बाद**, **एक बार** execute होगा।
क्योंकि यह code application के requests लेना **शुरू** करने से पहले, और requests handle करना **पूरा** करने के तुरंत बाद execute होता है, यह पूरी application **lifespan** को cover करता है (शब्द "lifespan" थोड़ी देर में महत्वपूर्ण होगा 😉)।
यह उन **resources** को setup करने के लिए बहुत उपयोगी हो सकता है जिनकी आपको पूरी app में जरूरत होती है, और जो requests के बीच **shared** होते हैं, और/या जिन्हें आपको बाद में **clean up** करना होता है। उदाहरण के लिए, database connection pool, या कोई shared machine learning model load करना।
## Use Case { #use-case }
आइए एक उदाहरण **use case** से शुरू करते हैं और फिर देखते हैं कि इसे इससे कैसे solve किया जाए।
मान लीजिए कि आपके पास कुछ **machine learning models** हैं जिन्हें आप requests handle करने के लिए use करना चाहते हैं। 🤖
वही models requests के बीच shared हैं, इसलिए, यह हर request के लिए एक model, या हर user के लिए एक model या ऐसा कुछ नहीं है।
मान लीजिए कि model load करने में **काफी समय लग सकता है**, क्योंकि उसे disk से बहुत सारा **data** read करना होता है। इसलिए आप इसे हर request के लिए नहीं करना चाहते।
आप इसे module/file के top level पर load कर सकते हैं, लेकिन इसका मतलब यह भी होगा कि अगर आप सिर्फ एक simple automated test run कर रहे हैं, तब भी यह **model load** करेगा, और फिर वह test **slow** होगा क्योंकि code के किसी independent part को run कर पाने से पहले उसे model load होने का इंतजार करना पड़ेगा।
यही हम solve करेंगे, चलिए model को requests handle होने से पहले load करते हैं, लेकिन केवल application के requests receive करना शुरू करने से ठीक पहले, code load होते समय नहीं।
## Lifespan { #lifespan }
आप `FastAPI` app के `lifespan` parameter और एक "context manager" (मैं अभी दिखाऊंगा कि यह क्या है) का use करके यह *startup* और *shutdown* logic define कर सकते हैं।
आइए एक उदाहरण से शुरू करते हैं और फिर इसे detail में देखते हैं।
हम `yield` के साथ एक async function `lifespan()` इस तरह create करते हैं:
{* ../../docs_src/events/tutorial003_py310.py hl[16,19] *}
यहां हम `yield` से पहले machine learning models वाली dictionary में (fake) model function रखकर model load करने वाली महंगी *startup* operation को simulate कर रहे हैं। यह code application के **requests लेना शुरू करने से पहले**, *startup* के दौरान execute होगा।
और फिर, `yield` के तुरंत बाद, हम model unload करते हैं। यह code application के **requests handle करना पूरा करने के बाद**, *shutdown* से ठीक पहले execute होगा। उदाहरण के लिए, यह memory या GPU जैसे resources release कर सकता है।
/// tip | सुझाव
`shutdown` तब होगा जब आप application को **stop** कर रहे होंगे।
शायद आपको कोई नया version start करना हो, या आप इसे चलाते-चलाते बस थक गए हों। 🤷
///
### Lifespan function { #lifespan-function }
ध्यान देने वाली पहली चीज यह है कि हम `yield` के साथ एक async function define कर रहे हैं। यह `yield` वाली Dependencies से बहुत मिलता-जुलता है।
{* ../../docs_src/events/tutorial003_py310.py hl[14:19] *}
function का पहला हिस्सा, `yield` से पहले वाला, application start होने से **पहले** execute होगा।
और `yield` के बाद वाला हिस्सा application के finish हो जाने के **बाद** execute होगा।
### Async Context Manager { #async-context-manager }
अगर आप check करें, तो function को `@asynccontextmanager` से decorate किया गया है।
यह function को "**async context manager**" नाम की चीज में convert करता है।
{* ../../docs_src/events/tutorial003_py310.py hl[1,13] *}
Python में एक **context manager** ऐसी चीज है जिसे आप `with` statement में use कर सकते हैं, उदाहरण के लिए, `open()` को context manager की तरह use किया जा सकता है:
```Python
with open("file.txt") as file:
file.read()
```
Python के नए versions में, एक **async context manager** भी है। आप इसे `async with` के साथ use करेंगे:
```Python
async with lifespan(app):
await do_stuff()
```
जब आप ऊपर की तरह कोई context manager या async context manager create करते हैं, तो यह क्या करता है कि `with` block में enter करने से पहले, यह `yield` से पहले वाला code execute करेगा, और `with` block से exit करने के बाद, यह `yield` के बाद वाला code execute करेगा।
ऊपर हमारे code example में, हम इसे सीधे use नहीं करते, बल्कि FastAPI को pass करते हैं ताकि वह इसे use कर सके।
`FastAPI` app का `lifespan` parameter एक **async context manager** लेता है, इसलिए हम अपना नया `lifespan` async context manager उसे pass कर सकते हैं।
{* ../../docs_src/events/tutorial003_py310.py hl[22] *}
## Alternative Events (deprecated) { #alternative-events-deprecated }
/// warning | चेतावनी
*startup* और *shutdown* को handle करने का recommended तरीका ऊपर बताए गए अनुसार `FastAPI` app के `lifespan` parameter का use करना है। अगर आप `lifespan` parameter provide करते हैं, तो `startup` और `shutdown` event handlers अब call नहीं किए जाएंगे। यह पूरा `lifespan` होगा या पूरे events, दोनों नहीं।
आप शायद यह हिस्सा skip कर सकते हैं।
///
इस logic को *startup* के दौरान और *shutdown* के दौरान execute करने के लिए define करने का एक alternative तरीका है।
आप event handlers (functions) define कर सकते हैं जिन्हें application के starts up होने से पहले, या application के shutting down होने पर execute किया जाना चाहिए।
इन functions को `async def` या normal `def` के साथ declare किया जा सकता है।
### `startup` event { #startup-event }
application start होने से पहले run होने वाला function add करने के लिए, इसे event `"startup"` के साथ declare करें:
{* ../../docs_src/events/tutorial001_py310.py hl[8] *}
इस मामले में, `startup` event handler function items "database" (बस एक `dict`) को कुछ values के साथ initialize करेगा।
आप एक से अधिक event handler function add कर सकते हैं।
और आपकी application requests receive करना तब तक शुरू नहीं करेगी जब तक सभी `startup` event handlers complete नहीं हो जाते।
### `shutdown` event { #shutdown-event }
application के shutting down होने पर run होने वाला function add करने के लिए, इसे event `"shutdown"` के साथ declare करें:
{* ../../docs_src/events/tutorial002_py310.py hl[6] *}
यहां, `shutdown` event handler function एक text line `"Application shutdown"` को `log.txt` file में write करेगा।
/// note | नोट
`open()` function में, `mode="a"` का मतलब "append" होता है, इसलिए, line उस file में जो भी है उसके बाद add की जाएगी, पिछले contents को overwrite किए बिना।
///
/// tip | सुझाव
ध्यान दें कि इस मामले में हम एक standard Python `open()` function use कर रहे हैं जो एक file के साथ interact करता है।
इसलिए, इसमें I/O (input/output) शामिल है, जिसके लिए चीजों के disk पर write होने का "waiting" करना पड़ता है।
लेकिन `open()` `async` और `await` use नहीं करता।
इसलिए, हम event handler function को `async def` के बजाय standard `def` के साथ declare करते हैं।
///
### `startup` और `shutdown` साथ में { #startup-and-shutdown-together }
इस बात की काफी संभावना है कि आपके *startup* और *shutdown* की logic connected हो, आप शायद कुछ start करना और फिर उसे finish करना, कोई resource acquire करना और फिर उसे release करना, आदि चाहें।
इसे अलग-अलग functions में करना, जो logic या variables को साथ में share नहीं करते, अधिक कठिन है क्योंकि आपको values को global variables या इसी तरह की tricks में store करना पड़ेगा।
इसी वजह से, अब इसके बजाय ऊपर explain किए गए `lifespan` को use करने की recommendation है।
## Technical Details { #technical-details }
जिज्ञासु nerds के लिए बस एक technical detail। 🤓
अंदर से, ASGI technical specification में, यह [Lifespan Protocol](https://asgi.readthedocs.io/en/latest/specs/lifespan.html) का हिस्सा है, और यह `startup` और `shutdown` नाम के events define करता है।
/// note | नोट
आप Starlette `lifespan` handlers के बारे में [Starlette की Lifespan docs](https://www.starlette.dev/lifespan/) में और पढ़ सकते हैं।
इसमें यह भी शामिल है कि lifespan state को कैसे handle किया जाए जिसे आपके code के अन्य areas में use किया जा सकता है।
///
## Sub Applications { #sub-applications }
🚨 ध्यान रखें कि ये lifespan events (startup और shutdown) केवल main application के लिए execute होंगे, [Sub Applications - Mounts](sub-applications.md) के लिए नहीं।
+192
View File
@@ -0,0 +1,192 @@
# SDKs जेनरेट करना { #generating-sdks }
क्योंकि **FastAPI** **OpenAPI** specification पर आधारित है, इसकी APIs को एक standard format में वर्णित किया जा सकता है जिसे कई tools समझते हैं।
इससे up-to-date **documentation**, कई भाषाओं में client libraries (<abbr title="Software Development Kits - सॉफ़्टवेयर Development Kits">**SDKs**</abbr>), और **testing** या **automation workflows** जेनरेट करना आसान हो जाता है, जो आपके code के साथ sync में रहते हैं।
इस guide में, आप सीखेंगे कि अपने FastAPI backend के लिए **TypeScript SDK** कैसे जेनरेट करें।
## Open Source SDK Generators { #open-source-sdk-generators }
एक versatile विकल्प [OpenAPI Generator](https://openapi-generator.tech/) है, जो **कई programming languages** को support करता है और आपकी OpenAPI specification से SDKs जेनरेट कर सकता है।
**TypeScript clients** के लिए, [Hey API](https://heyapi.dev/) एक purpose-built solution है, जो TypeScript ecosystem के लिए optimized experience प्रदान करता है।
आप [OpenAPI.Tools](https://openapi.tools/#sdk) पर और SDK generators खोज सकते हैं।
/// tip | सुझाव
FastAPI अपने-आप **OpenAPI 3.1** specifications जेनरेट करता है, इसलिए आपके द्वारा उपयोग किया जाने वाला कोई भी tool इस version को support करना चाहिए।
///
## TypeScript SDK बनाएँ { #create-a-typescript-sdk }
आइए एक सरल FastAPI application से शुरू करें:
{* ../../docs_src/generate_clients/tutorial001_py310.py hl[7:9,12:13,16:17,21] *}
ध्यान दें कि *path operations* उन models को define करते हैं जिनका उपयोग वे request payload और response payload के लिए करते हैं, `Item` और `ResponseMessage` models का उपयोग करके।
### API Docs { #api-docs }
यदि आप `/docs` पर जाते हैं, तो आप देखेंगे कि इसमें requests में भेजे जाने और responses में प्राप्त होने वाले data के लिए **schemas** हैं:
<img src="/img/tutorial/generate-clients/image01.png">
आप वे schemas देख सकते हैं क्योंकि उन्हें app में models के साथ declare किया गया था।
वह जानकारी app के **OpenAPI schema** में उपलब्ध होती है, और फिर API docs में दिखाई जाती है।
Models से वही जानकारी जो OpenAPI में शामिल होती है, **client code जेनरेट करने** के लिए उपयोग की जा सकती है।
### Hey API { #hey-api }
जब हमारे पास models के साथ एक FastAPI app हो, तो हम Hey API का उपयोग करके TypeScript client जेनरेट कर सकते हैं। ऐसा करने का सबसे तेज़ तरीका npx के माध्यम से है।
```sh
npx @hey-api/openapi-ts -i http://localhost:8000/openapi.json -o src/client
```
यह `./src/client` में TypeScript SDK जेनरेट करेगा।
आप उनकी website पर [`@hey-api/openapi-ts` install करना](https://heyapi.dev/openapi-ts/get-started) सीख सकते हैं और [generated output](https://heyapi.dev/openapi-ts/output) के बारे में पढ़ सकते हैं।
### SDK का उपयोग करना { #using-the-sdk }
अब आप client code को import करके उपयोग कर सकते हैं। यह कुछ ऐसा दिख सकता है, ध्यान दें कि आपको methods के लिए autocompletion मिलता है:
<img src="/img/tutorial/generate-clients/image02.png">
आपको भेजने के लिए payload के लिए भी autocompletion मिलेगा:
<img src="/img/tutorial/generate-clients/image03.png">
/// tip | सुझाव
`name` और `price` के लिए autocompletion पर ध्यान दें, जिसे FastAPI application में, `Item` model में define किया गया था।
///
आपके द्वारा भेजे जाने वाले data के लिए inline errors होंगे:
<img src="/img/tutorial/generate-clients/image04.png">
Response object में भी autocompletion होगा:
<img src="/img/tutorial/generate-clients/image05.png">
## Tags के साथ FastAPI App { #fastapi-app-with-tags }
कई मामलों में, आपका FastAPI app बड़ा होगा, और आप शायद *path operations* के अलग-अलग groups को separate करने के लिए tags का उपयोग करेंगे।
उदाहरण के लिए, आपके पास **items** के लिए एक section और **users** के लिए दूसरा section हो सकता है, और उन्हें tags द्वारा separate किया जा सकता है:
{* ../../docs_src/generate_clients/tutorial002_py310.py hl[21,26,34] *}
### Tags के साथ TypeScript Client जेनरेट करें { #generate-a-typescript-client-with-tags }
यदि आप tags का उपयोग करने वाले FastAPI app के लिए client जेनरेट करते हैं, तो यह सामान्यतः client code को भी tags के आधार पर separate करेगा।
इस तरह, आप client code के लिए चीज़ों को सही तरह से ordered और grouped रख पाएँगे:
<img src="/img/tutorial/generate-clients/image06.png">
इस मामले में, आपके पास हैं:
* `ItemsService`
* `UsersService`
### Client Method Names { #client-method-names }
अभी, जेनरेट किए गए method names जैसे `createItemItemsPost` बहुत साफ़ नहीं दिखते:
```TypeScript
ItemsService.createItemItemsPost({name: "Plumbus", price: 5})
```
...ऐसा इसलिए है क्योंकि client generator प्रत्येक *path operation* के लिए OpenAPI internal **operation ID** का उपयोग करता है।
OpenAPI required करता है कि प्रत्येक operation ID सभी *path operations* में unique हो, इसलिए FastAPI उस operation ID को जेनरेट करने के लिए **function name**, **path**, और **HTTP method/operation** का उपयोग करता है, क्योंकि इस तरह यह सुनिश्चित कर सकता है कि operation IDs unique हैं।
लेकिन मैं आगे आपको दिखाऊँगा कि इसे कैसे बेहतर बनाया जाए। 🤓
## Custom Operation IDs और बेहतर Method Names { #custom-operation-ids-and-better-method-names }
आप इन operation IDs को **जेनरेट** करने के तरीके को **modify** कर सकते हैं ताकि वे clients में सरल हों और **सरल method names** हों।
इस मामले में, आपको किसी दूसरे तरीके से सुनिश्चित करना होगा कि प्रत्येक operation ID **unique** हो।
उदाहरण के लिए, आप सुनिश्चित कर सकते हैं कि प्रत्येक *path operation* में एक tag हो, और फिर **tag** और *path operation* **name** (function name) के आधार पर operation ID जेनरेट करें।
### Custom Generate Unique ID Function { #custom-generate-unique-id-function }
FastAPI प्रत्येक *path operation* के लिए एक **unique ID** का उपयोग करता है, जिसका उपयोग **operation ID** के लिए और requests या responses के लिए आवश्यक किसी भी custom models के names के लिए भी किया जाता है।
आप उस function को customize कर सकते हैं। यह एक `APIRoute` लेता है और एक string output करता है।
उदाहरण के लिए, यहाँ यह पहले tag (आपके पास शायद केवल एक tag होगा) और *path operation* name (function name) का उपयोग कर रहा है।
फिर आप उस custom function को `generate_unique_id_function` parameter के रूप में **FastAPI** को pass कर सकते हैं:
{* ../../docs_src/generate_clients/tutorial003_py310.py hl[6:7,10] *}
### Custom Operation IDs के साथ TypeScript Client जेनरेट करें { #generate-a-typescript-client-with-custom-operation-ids }
अब, यदि आप client को फिर से जेनरेट करते हैं, तो आप देखेंगे कि इसमें बेहतर method names हैं:
<img src="/img/tutorial/generate-clients/image07.png">
जैसा कि आप देखते हैं, method names में अब tag और फिर function name है, अब वे URL path और HTTP operation की जानकारी शामिल नहीं करते।
### Client Generator के लिए OpenAPI Specification को Preprocess करें { #preprocess-the-openapi-specification-for-the-client-generator }
जेनरेट किए गए code में अभी भी कुछ **duplicated information** है।
हम पहले से जानते हैं कि यह method **items** से संबंधित है क्योंकि वह शब्द `ItemsService` (tag से लिया गया) में है, लेकिन method name में भी tag name prefixed है। 😕
हम शायद इसे सामान्य रूप से OpenAPI के लिए रखना चाहेंगे, क्योंकि यह सुनिश्चित करेगा कि operation IDs **unique** हैं।
लेकिन generated client के लिए, हम clients जेनरेट करने से ठीक पहले OpenAPI operation IDs को **modify** कर सकते हैं, ताकि उन method names को अधिक अच्छे और **cleaner** बनाया जा सके।
हम OpenAPI JSON को `openapi.json` file में download कर सकते हैं और फिर इस तरह के script से **उस prefixed tag को remove** कर सकते हैं:
{* ../../docs_src/generate_clients/tutorial004_py310.py *}
//// tab | Node.js
```Javascript
{!> ../../docs_src/generate_clients/tutorial004.js!}
```
////
इसके साथ, operation IDs को `items-get_items` जैसी चीज़ों से बदलकर सिर्फ़ `get_items` कर दिया जाएगा, इस तरह client generator सरल method names जेनरेट कर सकता है।
### Preprocessed OpenAPI के साथ TypeScript Client जेनरेट करें { #generate-a-typescript-client-with-the-preprocessed-openapi }
क्योंकि अंतिम परिणाम अब `openapi.json` file में है, आपको अपनी input location update करनी होगी:
```sh
npx @hey-api/openapi-ts -i ./openapi.json -o src/client
```
नया client जेनरेट करने के बाद, अब आपके पास **clean method names** होंगे, सभी **autocompletion**, **inline errors**, आदि के साथ:
<img src="/img/tutorial/generate-clients/image08.png">
## लाभ { #benefits }
Automatically generated clients का उपयोग करते समय, आपको इन चीज़ों के लिए **autocompletion** मिलेगा:
* Methods.
* body में request payloads, query parameters, आदि।
* Response payloads.
आपके पास हर चीज़ के लिए **inline errors** भी होंगे।
और जब भी आप backend code update करते हैं, और frontend को **regenerate** करते हैं, तो इसमें methods के रूप में कोई भी नए *path operations* उपलब्ध होंगे, पुराने remove हो जाएँगे, और कोई भी अन्य change generated code में reflect होगा। 🤓
इसका मतलब यह भी है कि यदि कुछ बदलता है, तो वह client code में अपने-आप **reflect** होगा। और यदि आप client को **build** करते हैं, तो यदि उपयोग किए गए data में कोई **mismatch** है, तो यह error देगा।
इसलिए, आप development cycle में बहुत जल्दी **कई errors detect** कर लेंगे, बजाय इसके कि errors के production में आपके अंतिम users को दिखने का इंतज़ार करना पड़े और फिर यह debug करने की कोशिश करनी पड़े कि समस्या कहाँ है। ✨
+21
View File
@@ -0,0 +1,21 @@
# उन्नत उपयोगकर्ता गाइड { #advanced-user-guide }
## अतिरिक्त feature { #additional-features }
मुख्य [ट्यूटोरियल - उपयोगकर्ता गाइड](../tutorial/index.md) आपको **FastAPI** के सभी मुख्य feature का अवलोकन देने के लिए पर्याप्त होना चाहिए।
अगले sections में आप अन्य विकल्प, configurations, और अतिरिक्त feature देखेंगे।
/// tip | सुझाव
अगले sections **ज़रूरी नहीं कि "उन्नत"** हों।
और संभव है कि आपके उपयोग के मामले के लिए समाधान उनमें से किसी एक में हो।
///
## पहले ट्यूटोरियल पढ़ें { #read-the-tutorial-first }
आप मुख्य [ट्यूटोरियल - उपयोगकर्ता गाइड](../tutorial/index.md) से मिली जानकारी के साथ भी **FastAPI** के ज़्यादातर feature का उपयोग कर सकते हैं।
और अगले sections मानते हैं कि आपने इसे पहले ही पढ़ लिया है, और यह भी मानते हैं कि आप उन मुख्य विचारों को जानते हैं।
@@ -0,0 +1,63 @@
# Base64 के रूप में Bytes वाला JSON { #json-with-bytes-as-base64 }
अगर आपके app को JSON data receive और send करना है, लेकिन आपको उसमें binary data शामिल करना है, तो आप उसे base64 के रूप में encode कर सकते हैं।
## Base64 बनाम Files { #base64-vs-files }
पहले यह विचार करें कि क्या आप binary data upload करने के लिए [Request Files](../tutorial/request-files.md) और binary data भेजने के लिए [कस्टम Response - FileResponse](./custom-response.md#fileresponse) का उपयोग कर सकते हैं, बजाय इसके कि उसे JSON में encode किया जाए।
JSON में केवल UTF-8 encoded strings हो सकती हैं, इसलिए उसमें raw bytes नहीं हो सकते।
Base64 binary data को strings में encode कर सकता है, लेकिन ऐसा करने के लिए उसे मूल binary data की तुलना में अधिक characters का उपयोग करना पड़ता है, इसलिए यह सामान्य files की तुलना में आमतौर पर कम efficient होगा।
Base64 का उपयोग केवल तभी करें जब आपको निश्चित रूप से JSON में binary data शामिल करना हो, और आप उसके लिए files का उपयोग नहीं कर सकते।
## Pydantic `bytes` { #pydantic-bytes }
आप `bytes` fields वाला एक Pydantic model declare कर सकते हैं, और फिर model config में `val_json_bytes` का उपयोग करके उसे बता सकते हैं कि input JSON data को *validate* करने के लिए base64 का उपयोग करे; उस validation के हिस्से के रूप में यह base64 string को bytes में decode करेगा।
{* ../../docs_src/json_base64_bytes/tutorial001_py310.py ln[1:9,29:35] hl[9] *}
अगर आप `/docs` देखें, तो वे दिखाएँगे कि field `data` base64 encoded bytes की अपेक्षा करता है:
<div class="screenshot">
<img src="/img/tutorial/json-base64-bytes/image01.png">
</div>
आप इस तरह का request भेज सकते हैं:
```json
{
"description": "Some data",
"data": "aGVsbG8="
}
```
/// tip | सुझाव
`aGVsbG8=` `hello` की base64 encoding है।
///
और फिर Pydantic base64 string को decode करेगा और आपको model के `data` field में मूल bytes देगा।
आपको इस तरह का response मिलेगा:
```json
{
"description": "Some data",
"content": "hello"
}
```
## Output Data के लिए Pydantic `bytes` { #pydantic-bytes-for-output-data }
आप output data के लिए model config में `ser_json_bytes` के साथ `bytes` fields का भी उपयोग कर सकते हैं, और JSON response generate करते समय Pydantic bytes को base64 के रूप में *serialize* करेगा।
{* ../../docs_src/json_base64_bytes/tutorial001_py310.py ln[1:2,12:16,29,38:41] hl[16] *}
## Input और Output Data के लिए Pydantic `bytes` { #pydantic-bytes-for-input-and-output-data }
और बेशक, JSON data receive और send करते समय आप उसी model को base64 उपयोग करने के लिए configure कर सकते हैं, ताकि input (*validate*) को `val_json_bytes` के साथ और output (*serialize*) को `ser_json_bytes` के साथ handle किया जा सके।
{* ../../docs_src/json_base64_bytes/tutorial001_py310.py ln[1:2,19:26,29,44:46] hl[23:26] *}
+97
View File
@@ -0,0 +1,97 @@
# उन्नत Middleware { #advanced-middleware }
मुख्य tutorial में आपने पढ़ा कि अपनी application में [Custom Middleware](../tutorial/middleware.md) कैसे जोड़ें।
और फिर आपने यह भी पढ़ा कि [`CORSMiddleware` के साथ CORS](../tutorial/cors.md) को कैसे handle करें।
इस section में हम देखेंगे कि अन्य middleware का उपयोग कैसे करें।
## ASGI middleware जोड़ना { #adding-asgi-middlewares }
क्योंकि **FastAPI** Starlette पर आधारित है और <abbr title="Asynchronous Server Gateway Interface - asynchronous सर्वर गेटवे इंटरफ़ेस">ASGI</abbr> specification को implement करता है, आप कोई भी ASGI middleware उपयोग कर सकते हैं।
किसी middleware को काम करने के लिए FastAPI या Starlette के लिए बना होना required नहीं है, जब तक वह ASGI spec का पालन करता है।
सामान्यतः, ASGI middleware ऐसी classes होती हैं जो पहले argument के रूप में एक ASGI app प्राप्त करने की अपेक्षा करती हैं।
इसलिए, third-party ASGI middleware के documentation में वे शायद आपको कुछ ऐसा करने के लिए कहेंगे:
```Python
from unicorn import UnicornMiddleware
app = SomeASGIApp()
new_app = UnicornMiddleware(app, some_config="rainbow")
```
लेकिन FastAPI (वास्तव में Starlette) इसे करने का एक सरल तरीका प्रदान करता है, जो सुनिश्चित करता है कि internal middleware server errors को handle करें और custom exception handlers सही तरीके से काम करें।
इसके लिए, आप `app.add_middleware()` का उपयोग करते हैं (जैसे CORS के उदाहरण में)।
```Python
from fastapi import FastAPI
from unicorn import UnicornMiddleware
app = FastAPI()
app.add_middleware(UnicornMiddleware, some_config="rainbow")
```
`app.add_middleware()` पहले argument के रूप में एक middleware class प्राप्त करता है और middleware को pass किए जाने वाले कोई भी अतिरिक्त arguments भी प्राप्त करता है।
## एकीकृत middleware { #integrated-middlewares }
**FastAPI** common use cases के लिए कई middleware शामिल करता है, आगे हम देखेंगे कि उनका उपयोग कैसे करें।
/// note | तकनीकी विवरण
अगले उदाहरणों के लिए, आप `from starlette.middleware.something import SomethingMiddleware` भी उपयोग कर सकते हैं।
**FastAPI** `fastapi.middleware` में कई middleware सिर्फ आपकी, developer की, सुविधा के लिए प्रदान करता है। लेकिन उपलब्ध अधिकांश middleware सीधे Starlette से आते हैं।
///
## `HTTPSRedirectMiddleware` { #httpsredirectmiddleware }
यह enforce करता है कि सभी incoming requests या तो `https` या `wss` हों।
`http` या `ws` पर आने वाली कोई भी incoming request इसके बजाय secure scheme पर redirect कर दी जाएगी।
{* ../../docs_src/advanced_middleware/tutorial001_py310.py hl[2,6] *}
## `TrustedHostMiddleware` { #trustedhostmiddleware }
यह enforce करता है कि सभी incoming requests में `Host` header सही तरीके से set हो, ताकि HTTP Host Header attacks से बचाव हो सके।
{* ../../docs_src/advanced_middleware/tutorial002_py310.py hl[2,6:8] *}
निम्नलिखित arguments supported हैं:
* `allowed_hosts` - domain names की एक सूची जिन्हें hostnames के रूप में allow किया जाना चाहिए। `*.example.com` जैसे Wildcard domains subdomains को match करने के लिए supported हैं। किसी भी hostname को allow करने के लिए या तो `allowed_hosts=["*"]` उपयोग करें या middleware को omit करें।
* `www_redirect` - यदि True पर set किया गया है, तो allowed hosts के non-www versions पर आने वाली requests उनके www counterparts पर redirect कर दी जाएँगी। Default `True` है।
यदि कोई incoming request सही तरीके से validate नहीं होती है तो `400` response भेजा जाएगा।
## `GZipMiddleware` { #gzipmiddleware }
ऐसी किसी भी request के लिए GZip responses handle करता है जिसमें `Accept-Encoding` header में `"gzip"` शामिल हो।
middleware standard और streaming दोनों responses को handle करेगा।
{* ../../docs_src/advanced_middleware/tutorial003_py310.py hl[2,6] *}
निम्नलिखित arguments supported हैं:
* `minimum_size` - इस minimum size से छोटे responses को GZip न करें, size bytes में है। Default `500` है।
* `compresslevel` - GZip compression के दौरान उपयोग किया जाता है। यह 1 से 9 तक की range में एक integer है। Default `9` है। कम value से compression तेज़ होता है लेकिन file sizes बड़ी होती हैं, जबकि अधिक value से compression धीमा होता है लेकिन file sizes छोटी होती हैं।
## अन्य middleware { #other-middlewares }
कई अन्य ASGI middleware हैं।
उदाहरण के लिए:
* [Uvicorn का `ProxyHeadersMiddleware`](https://github.com/encode/uvicorn/blob/master/uvicorn/middleware/proxy_headers.py)
* [MessagePack](https://github.com/florimondmanca/msgpack-asgi)
अन्य उपलब्ध middleware देखने के लिए [Starlette के Middleware docs](https://www.starlette.dev/middleware/) और [ASGI Awesome List](https://github.com/florimondmanca/awesome-asgi) देखें।
+186
View File
@@ -0,0 +1,186 @@
# OpenAPI Callbacks { #openapi-callbacks }
आप एक ऐसी API बना सकते हैं जिसमें एक *path operation* हो जो किसी और के द्वारा बनाई गई *external API* को request trigger कर सके (शायद वही developer जो आपकी API का *उपयोग* करेगा)।
जब आपकी API app *external API* को call करती है, उस प्रक्रिया को "callback" कहा जाता है। क्योंकि external developer द्वारा लिखा गया software आपकी API को request भेजता है और फिर आपकी API *call back* करती है, यानी किसी *external API* को request भेजती है (जो शायद उसी developer द्वारा बनाई गई थी)।
इस स्थिति में, आप यह document करना चाह सकते हैं कि वह external API कैसी *होनी चाहिए*। उसमें कौन-सा *path operation* होना चाहिए, उसे कौन-सा body expect करना चाहिए, उसे कौन-सा response लौटाना चाहिए, आदि।
## Callbacks वाली एक app { #an-app-with-callbacks }
आइए इसे एक उदाहरण के साथ देखते हैं।
कल्पना करें कि आप एक ऐसी app develop करते हैं जो invoices बनाने देती है।
इन invoices में एक `id`, `title` (optional), `customer`, और `total` होगा।
आपकी API का user (एक external developer) आपकी API में POST request के साथ एक invoice बनाएगा।
फिर आपकी API (कल्पना करें):
* invoice को external developer के किसी customer को भेजेगी।
* पैसे collect करेगी।
* API user (external developer) को वापस एक notification भेजेगी।
* यह (*आपकी API* से) उस external developer द्वारा दी गई किसी *external API* को POST request भेजकर किया जाएगा (यही "callback" है)।
## सामान्य **FastAPI** app { #the-normal-fastapi-app }
Callback जोड़ने से पहले, पहले देखते हैं कि सामान्य API app कैसी दिखेगी।
इसमें एक *path operation* होगा जो एक `Invoice` body receive करेगा, और एक query parameter `callback_url` होगा जिसमें callback के लिए URL होगा।
यह हिस्सा काफ़ी सामान्य है, अधिकतर code शायद आपको पहले से परिचित होगा:
{* ../../docs_src/openapi_callbacks/tutorial001_py310.py hl[7:11,34:51] *}
/// tip | सुझाव
`callback_url` query parameter एक Pydantic [Url](https://docs.pydantic.dev/latest/api/networks/) type का उपयोग करता है।
///
केवल नई चीज़ है *path operation decorator* के argument के रूप में `callbacks=invoices_callback_router.routes`। आगे हम देखेंगे कि यह क्या है।
## Callback को document करना { #documenting-the-callback }
वास्तविक callback code आपकी अपनी API app पर बहुत अधिक निर्भर करेगा।
और यह एक app से दूसरी app में काफ़ी अलग हो सकता है।
यह code की सिर्फ़ एक या दो lines भी हो सकती हैं, जैसे:
```Python
callback_url = "https://example.com/api/v1/invoices/events/"
httpx.post(callback_url, json={"description": "Invoice paid", "paid": True})
```
लेकिन संभवतः callback का सबसे महत्वपूर्ण हिस्सा यह सुनिश्चित करना है कि आपका API user (external developer) *external API* को सही तरह से implement करे, उस data के अनुसार जिसे *आपकी API* callback के request body में भेजने वाली है, आदि।
तो, अब हम वह code जोड़ेंगे जो document करेगा कि *आपकी API* से callback receive करने के लिए वह *external API* कैसी दिखनी चाहिए।
यह documentation आपकी API में `/docs` पर Swagger UI में दिखाई देगी, और यह external developers को बताएगी कि *external API* कैसे बनानी है।
यह उदाहरण callback को स्वयं implement नहीं करता (वह केवल code की एक line हो सकती है), केवल documentation वाला हिस्सा करता है।
/// tip | सुझाव
वास्तविक callback सिर्फ़ एक HTTP request है।
Callback को स्वयं implement करते समय, आप [HTTPX](https://www.python-httpx.org) या [Requests](https://requests.readthedocs.io/) जैसी किसी चीज़ का उपयोग कर सकते हैं।
///
## Callback documentation code लिखें { #write-the-callback-documentation-code }
यह code आपकी app में execute नहीं होगा, हमें इसकी आवश्यकता केवल यह *document* करने के लिए है कि वह *external API* कैसी दिखनी चाहिए।
लेकिन, आप पहले से जानते हैं कि **FastAPI** के साथ किसी API के लिए automatic documentation आसानी से कैसे बनाई जाती है।
इसलिए हम उसी ज्ञान का उपयोग करके document करेंगे कि *external API* कैसी दिखनी चाहिए... उन *path operation(s)* को बनाकर जिन्हें external API को implement करना चाहिए (जिन्हें आपकी API call करेगी)।
/// tip | सुझाव
Callback को document करने के लिए code लिखते समय, यह कल्पना करना उपयोगी हो सकता है कि आप वही *external developer* हैं। और इस समय आप *external API* implement कर रहे हैं, *अपनी API* नहीं।
इस दृष्टिकोण को अस्थायी रूप से अपनाना (*external developer* का) आपको यह अधिक स्पष्ट महसूस कराने में मदद कर सकता है कि उस *external API* के लिए parameters, body के लिए Pydantic model, response के लिए model, आदि कहाँ रखने हैं।
///
### Callback `APIRouter` बनाएँ { #create-a-callback-apirouter }
पहले एक नया `APIRouter` बनाएँ जिसमें एक या अधिक callbacks होंगे।
{* ../../docs_src/openapi_callbacks/tutorial001_py310.py hl[1,23] *}
### Callback *path operation* बनाएँ { #create-the-callback-path-operation }
Callback *path operation* बनाने के लिए वही `APIRouter` उपयोग करें जो आपने ऊपर बनाया था।
यह बिल्कुल सामान्य FastAPI *path operation* जैसा दिखना चाहिए:
* इसमें शायद उस body की declaration होनी चाहिए जिसे इसे receive करना है, जैसे `body: InvoiceEvent`
* और इसमें उस response की declaration भी हो सकती है जिसे इसे लौटाना चाहिए, जैसे `response_model=InvoiceEventReceived`
{* ../../docs_src/openapi_callbacks/tutorial001_py310.py hl[14:16,19:20,26:30] *}
सामान्य *path operation* से 2 मुख्य अंतर हैं:
* इसमें कोई वास्तविक code होना required नहीं है, क्योंकि आपकी app इस code को कभी call नहीं करेगी। इसका उपयोग केवल *external API* को document करने के लिए किया जाता है। इसलिए, function में केवल `pass` हो सकता है।
* *path* में एक [OpenAPI 3 expression](https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.1.0.md#key-expression) (नीचे और देखें) हो सकता है, जहाँ यह *आपकी API* को भेजी गई original request के parameters और parts के साथ variables का उपयोग कर सकता है।
### Callback path expression { #the-callback-path-expression }
Callback *path* में एक [OpenAPI 3 expression](https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.1.0.md#key-expression) हो सकता है जो *आपकी API* को भेजी गई original request के parts शामिल कर सकता है।
इस case में, यह `str` है:
```Python
"{$callback_url}/invoices/{$request.body.id}"
```
तो, यदि आपका API user (external developer) *आपकी API* को request भेजता है:
```
https://yourapi.com/invoices/?callback_url=https://www.external.org/events
```
इस JSON body के साथ:
```JSON
{
"id": "2expen51ve",
"customer": "Mr. Richie Rich",
"total": "9999"
}
```
तो *आपकी API* invoice को process करेगी, और बाद में किसी समय, `callback_url` (*external API*) को callback request भेजेगी:
```
https://www.external.org/events/invoices/2expen51ve
```
ऐसे JSON body के साथ जिसमें कुछ इस तरह होगा:
```JSON
{
"description": "Payment celebration",
"paid": true
}
```
और यह उस *external API* से इस तरह के JSON body वाले response की अपेक्षा करेगी:
```JSON
{
"ok": true
}
```
/// tip | सुझाव
ध्यान दें कि उपयोग किए गए callback URL में `callback_url` (`https://www.external.org/events`) में query parameter के रूप में प्राप्त URL और JSON body के अंदर से invoice `id` (`2expen51ve`) दोनों शामिल हैं।
///
### Callback router जोड़ें { #add-the-callback-router }
इस समय आपके पास ऊपर बनाए गए callback router में required *callback path operation(s)* हैं (वे operation जिन्हें *external developer* को *external API* में implement करना चाहिए)।
अब *आपकी API के path operation decorator* में parameter `callbacks` का उपयोग करके उस callback router से attribute `.routes` pass करें:
{* ../../docs_src/openapi_callbacks/tutorial001_py310.py hl[33] *}
/// tip | सुझाव
ध्यान दें कि आप router स्वयं (`invoices_callback_router`) को `callbacks=` में pass नहीं कर रहे हैं, बल्कि उसकी `.routes` को pass कर रहे हैं, जैसे `invoices_callback_router.routes`। FastAPI उन routes का उपयोग callback OpenAPI documentation generate करने के लिए करेगा।
///
### Docs देखें { #check-the-docs }
अब आप अपनी app start कर सकते हैं और [http://127.0.0.1:8000/docs](http://127.0.0.1:8000/docs) पर जा सकते हैं।
आपको अपनी docs में अपने *path operation* के लिए एक "Callbacks" section दिखेगा, जो दिखाता है कि *external API* कैसी दिखनी चाहिए:
<img src="/img/tutorial/openapi-callbacks/image01.png">
+55
View File
@@ -0,0 +1,55 @@
# OpenAPI Webhooks { #openapi-webhooks }
ऐसे मामले होते हैं जहाँ आप अपने API **users** को बताना चाहते हैं कि आपकी app कुछ data के साथ (एक request भेजते हुए) *उनकी* app को कॉल कर सकती है, सामान्यतः किसी प्रकार के **event** की **सूचना** देने के लिए।
इसका मतलब है कि आपके users द्वारा आपकी API को requests भेजने की सामान्य प्रक्रिया के बजाय, **आपकी API** (या आपकी app) **उनके system को requests भेज** सकती है (उनकी API, उनकी app को)।
इसे सामान्यतः **webhook** कहा जाता है।
## Webhooks के चरण { #webhooks-steps }
सामान्यतः प्रक्रिया यह होती है कि **आप अपने code में define करते हैं** कि आप कौन-सा message भेजेंगे, यानी **request का body**
आप यह भी किसी तरीके से define करते हैं कि आपकी app किन **क्षणों** पर वे requests या events भेजेगी।
और **आपके users** किसी तरीके से (उदाहरण के लिए कहीं किसी web dashboard में) वह **URL** define करते हैं जहाँ आपकी app को वे requests भेजनी चाहिए।
Webhooks के लिए URLs को register करने की सारी **logic** और वास्तव में उन requests को भेजने का code आपके ऊपर है। आप इसे **अपने खुद के code** में जैसे चाहें वैसे लिखते हैं।
## **FastAPI** और OpenAPI के साथ webhooks का दस्तावेज़ीकरण { #documenting-webhooks-with-fastapi-and-openapi }
**FastAPI** के साथ, OpenAPI का उपयोग करते हुए, आप इन webhooks के नाम, आपकी app द्वारा भेजे जा सकने वाले HTTP operations के प्रकार (जैसे `POST`, `PUT`, आदि) और आपकी app द्वारा भेजे जाने वाले request **bodies** define कर सकते हैं।
इससे आपके users के लिए आपकी **webhook** requests प्राप्त करने के लिए **अपनी APIs implement करना** बहुत आसान हो सकता है, वे शायद अपने कुछ API code को autogenerate भी कर सकें।
/// note | नोट
Webhooks OpenAPI 3.1.0 और उससे ऊपर में उपलब्ध हैं, और FastAPI `0.99.0` और उससे ऊपर द्वारा समर्थित हैं।
///
## Webhooks वाली app { #an-app-with-webhooks }
जब आप एक **FastAPI** application बनाते हैं, तो एक `webhooks` attribute होता है जिसका उपयोग आप *webhooks* define करने के लिए कर सकते हैं, उसी तरह जैसे आप *path operations* define करते हैं, उदाहरण के लिए `@app.webhooks.post()` के साथ।
{* ../../docs_src/openapi_webhooks/tutorial001_py310.py hl[9:12,15:20] *}
आप जिन webhooks को define करते हैं वे **OpenAPI** schema और automatic **docs UI** में आ जाएँगे।
/// note | नोट
`app.webhooks` object वास्तव में सिर्फ़ एक `APIRouter` है, वही type जिसका उपयोग आप अपनी app को multiple files के साथ structure करते समय करेंगे।
///
ध्यान दें कि webhooks के साथ आप वास्तव में कोई *path* declare नहीं कर रहे हैं (जैसे `/items/`), वहाँ आप जो text pass करते हैं वह केवल webhook का एक **identifier** है (event का नाम), उदाहरण के लिए `@app.webhooks.post("new-subscription")` में, webhook का नाम `new-subscription` है।
ऐसा इसलिए है क्योंकि उम्मीद की जाती है कि **आपके users** उस वास्तविक **URL path** को किसी और तरीके से define करेंगे जहाँ वे webhook request प्राप्त करना चाहते हैं (जैसे कोई web dashboard)।
### Docs देखें { #check-the-docs }
अब आप अपनी app start कर सकते हैं और [http://127.0.0.1:8000/docs](http://127.0.0.1:8000/docs) पर जा सकते हैं।
आप देखेंगे कि आपके docs में सामान्य *path operations* हैं और अब कुछ **webhooks** भी हैं:
<img src="/img/tutorial/openapi-webhooks/image01.png">
@@ -0,0 +1,166 @@
# Path Operation की उन्नत Configuration { #path-operation-advanced-configuration }
## OpenAPI operationId { #openapi-operationid }
/// warning | चेतावनी
अगर आप OpenAPI में "expert" नहीं हैं, तो शायद आपको इसकी ज़रूरत नहीं है।
///
आप अपने *path operation* में उपयोग किए जाने वाले OpenAPI `operationId` को parameter `operation_id` के साथ सेट कर सकते हैं।
आपको यह सुनिश्चित करना होगा कि यह प्रत्येक operation के लिए unique हो।
{* ../../docs_src/path_operation_advanced_configuration/tutorial001_py310.py hl[6] *}
### *path operation function* के नाम को operationId के रूप में उपयोग करना { #using-the-path-operation-function-name-as-the-operationid }
अगर आप अपने APIs के function नामों को `operationId`s के रूप में उपयोग करना चाहते हैं, तो आप `FastAPI` को एक custom `generate_unique_id_function` पास कर सकते हैं।
यह function प्रत्येक `APIRoute` प्राप्त करता है और उस path operation के लिए उपयोग करने वाला `operationId` return करता है।
{* ../../docs_src/path_operation_advanced_configuration/tutorial002_py310.py hl[2,5:6,9] *}
/// warning | चेतावनी
अगर आप ऐसा करते हैं, तो आपको यह सुनिश्चित करना होगा कि आपके प्रत्येक *path operation functions* का नाम unique हो।
भले ही वे अलग-अलग modules (Python files) में हों।
///
## OpenAPI से बाहर रखना { #exclude-from-openapi }
किसी *path operation* को generated OpenAPI schema से बाहर रखने के लिए (और इस प्रकार, automatic documentation systems से भी), parameter `include_in_schema` का उपयोग करें और इसे `False` पर सेट करें:
{* ../../docs_src/path_operation_advanced_configuration/tutorial003_py310.py hl[6] *}
## Docstring से उन्नत description { #advanced-description-from-docstring }
आप OpenAPI के लिए किसी *path operation function* की docstring से उपयोग की जाने वाली lines को सीमित कर सकते हैं।
एक `\f` (एक escaped "form feed" character) जोड़ने से **FastAPI** इस बिंदु पर OpenAPI के लिए उपयोग किए जाने वाले output को truncate कर देता है।
यह documentation में नहीं दिखेगा, लेकिन अन्य tools (जैसे Sphinx) बाकी हिस्से का उपयोग कर सकेंगे।
{* ../../docs_src/path_operation_advanced_configuration/tutorial004_py310.py hl[17:27] *}
## अतिरिक्त Responses { #additional-responses }
आपने शायद देखा होगा कि किसी *path operation* के लिए `response_model` और `status_code` कैसे declare किए जाते हैं।
यह किसी *path operation* के मुख्य response के बारे में metadata define करता है।
आप उनके models, status codes आदि के साथ अतिरिक्त responses भी declare कर सकते हैं।
इसके बारे में documentation में यहाँ एक पूरा chapter है, आप इसे [OpenAPI में अतिरिक्त Responses](additional-responses.md) पर पढ़ सकते हैं।
## OpenAPI Extra { #openapi-extra }
जब आप अपने application में कोई *path operation* declare करते हैं, तो **FastAPI** उस *path operation* के बारे में relevant metadata को automatically generate करता है, जिसे OpenAPI schema में शामिल किया जाता है।
/// note | तकनीकी विवरण
OpenAPI specification में इसे [Operation Object](https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.3.md#operation-object) कहा जाता है।
///
इसमें *path operation* के बारे में सारी जानकारी होती है और इसका उपयोग automatic documentation generate करने के लिए किया जाता है।
इसमें `tags`, `parameters`, `requestBody`, `responses` आदि शामिल होते हैं।
यह *path operation*-specific OpenAPI schema सामान्यतः **FastAPI** द्वारा automatically generate किया जाता है, लेकिन आप इसे extend भी कर सकते हैं।
/// tip | सुझाव
यह एक low level extension point है।
अगर आपको केवल अतिरिक्त responses declare करने की ज़रूरत है, तो ऐसा करने का एक अधिक सुविधाजनक तरीका [OpenAPI में अतिरिक्त Responses](additional-responses.md) के साथ है।
///
आप parameter `openapi_extra` का उपयोग करके किसी *path operation* के लिए OpenAPI schema को extend कर सकते हैं।
### OpenAPI Extensions { #openapi-extensions }
यह `openapi_extra` उपयोगी हो सकता है, उदाहरण के लिए, [OpenAPI Extensions](https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.3.md#specificationExtensions) declare करने के लिए:
{* ../../docs_src/path_operation_advanced_configuration/tutorial005_py310.py hl[6] *}
अगर आप automatic API docs खोलते हैं, तो आपका extension specific *path operation* के नीचे दिखाई देगा।
<img src="/img/tutorial/path-operation-advanced-configuration/image01.png">
और अगर आप resulting OpenAPI (आपकी API में `/openapi.json` पर) देखते हैं, तो आपको अपना extension specific *path operation* के हिस्से के रूप में भी दिखाई देगा:
```JSON hl_lines="22"
{
"openapi": "3.1.0",
"info": {
"title": "FastAPI",
"version": "0.1.0"
},
"paths": {
"/items/": {
"get": {
"summary": "Read Items",
"operationId": "read_items_items__get",
"responses": {
"200": {
"description": "Successful Response",
"content": {
"application/json": {
"schema": {}
}
}
}
},
"x-aperture-labs-portal": "blue"
}
}
}
}
```
### Custom OpenAPI *path operation* schema { #custom-openapi-path-operation-schema }
`openapi_extra` में मौजूद dictionary को *path operation* के लिए automatically generated OpenAPI schema के साथ deeply merge किया जाएगा।
तो, आप automatically generated schema में अतिरिक्त data जोड़ सकते हैं।
उदाहरण के लिए, आप FastAPI की Pydantic के साथ automatic features का उपयोग किए बिना, अपने code से request को read और validate करने का निर्णय ले सकते हैं, लेकिन फिर भी आप OpenAPI schema में request को define करना चाह सकते हैं।
आप यह `openapi_extra` के साथ कर सकते हैं:
{* ../../docs_src/path_operation_advanced_configuration/tutorial006_py310.py hl[19:36, 39:40] *}
इस उदाहरण में, हमने कोई Pydantic model declare नहीं किया। वास्तव में, request body को JSON के रूप में <dfn title="किसी plain format, जैसे bytes, से Python objects में बदला गया">parsed</dfn> भी नहीं किया गया है, इसे सीधे `bytes` के रूप में read किया गया है, और function `magic_data_reader()` किसी तरीके से इसे parse करने का ज़िम्मेदार होगा।
फिर भी, हम request body के लिए expected schema declare कर सकते हैं।
### Custom OpenAPI content type { #custom-openapi-content-type }
इसी trick का उपयोग करके, आप JSON Schema define करने के लिए Pydantic model का उपयोग कर सकते हैं, जिसे फिर *path operation* के लिए custom OpenAPI schema section में शामिल किया जाता है।
और आप ऐसा तब भी कर सकते हैं जब request में data type JSON न हो।
उदाहरण के लिए, इस application में हम Pydantic models से JSON Schema निकालने के लिए FastAPI की integrated functionality या JSON के लिए automatic validation का उपयोग नहीं करते हैं। वास्तव में, हम request content type को JSON नहीं, बल्कि YAML के रूप में declare कर रहे हैं:
{* ../../docs_src/path_operation_advanced_configuration/tutorial007_py310.py hl[15:20, 22] *}
फिर भी, हालांकि हम default integrated functionality का उपयोग नहीं कर रहे हैं, हम अभी भी उस data के लिए JSON Schema manually generate करने के लिए Pydantic model का उपयोग कर रहे हैं जिसे हम YAML में receive करना चाहते हैं।
फिर हम request को सीधे उपयोग करते हैं, और body को `bytes` के रूप में extract करते हैं। इसका मतलब है कि FastAPI request payload को JSON के रूप में parse करने की कोशिश भी नहीं करेगा।
और फिर अपने code में, हम उस YAML content को सीधे parse करते हैं, और फिर हम YAML content को validate करने के लिए फिर से उसी Pydantic model का उपयोग कर रहे हैं:
{* ../../docs_src/path_operation_advanced_configuration/tutorial007_py310.py hl[24:31] *}
/// tip | सुझाव
यहाँ हम उसी Pydantic model को reuse करते हैं।
लेकिन इसी तरह, हम इसे किसी और तरीके से भी validate कर सकते थे।
///
@@ -0,0 +1,31 @@
# Response - Status Code बदलें { #response-change-status-code }
आपने शायद पहले पढ़ा होगा कि आप एक default [Response Status Code](../tutorial/response-status-code.md) सेट कर सकते हैं।
लेकिन कुछ मामलों में आपको default से अलग status code लौटाना पड़ता है।
## उपयोग का मामला { #use-case }
उदाहरण के लिए, कल्पना करें कि आप default रूप से "OK" `200` का HTTP status code लौटाना चाहते हैं।
लेकिन अगर data मौजूद नहीं था, तो आप उसे बनाना चाहते हैं, और "CREATED" `201` का HTTP status code लौटाना चाहते हैं।
लेकिन फिर भी आप `response_model` के साथ लौटाए गए data को filter और convert कर पाने में सक्षम रहना चाहते हैं।
ऐसे मामलों के लिए, आप `Response` parameter का उपयोग कर सकते हैं।
## `Response` parameter का उपयोग करें { #use-a-response-parameter }
आप अपनी *path operation function* में `Response` type का parameter घोषित कर सकते हैं (जैसा कि आप cookies और headers के लिए कर सकते हैं)।
और फिर आप उस *temporary* response object में `status_code` सेट कर सकते हैं।
{* ../../docs_src/response_change_status_code/tutorial001_py310.py hl[1,9,12] *}
और फिर आप अपनी ज़रूरत का कोई भी object लौटा सकते हैं, जैसा कि आप सामान्य रूप से करते हैं (एक `dict`, एक database model, आदि)।
और अगर आपने `response_model` घोषित किया है, तो यह आपके लौटाए गए object को filter और convert करने के लिए अभी भी उपयोग किया जाएगा।
**FastAPI** उस *temporary* response का उपयोग status code (साथ ही cookies और headers) निकालने के लिए करेगा, और उन्हें अंतिम response में डाल देगा जिसमें आपके द्वारा लौटाया गया value होगा, जिसे किसी भी `response_model` द्वारा filter किया गया होगा।
आप dependencies में भी `Response` parameter घोषित कर सकते हैं, और उनमें status code सेट कर सकते हैं। लेकिन ध्यान रखें कि आख़िरी बार जो सेट किया जाएगा, वही प्रभावी होगा।
+51
View File
@@ -0,0 +1,51 @@
# Response Cookies { #response-cookies }
## `Response` parameter का उपयोग करें { #use-a-response-parameter }
आप अपने *path operation function* में `Response` प्रकार का parameter घोषित कर सकते हैं।
और फिर आप उस *temporary* response object में cookies set कर सकते हैं।
{* ../../docs_src/response_cookies/tutorial002_py310.py hl[1, 8:9] *}
और फिर आप अपनी ज़रूरत का कोई भी object return कर सकते हैं, जैसा कि आप सामान्य रूप से करते हैं (एक `dict`, database model, आदि)।
और अगर आपने `response_model` घोषित किया है, तो आपके द्वारा return किए गए object को filter और convert करने के लिए उसका अभी भी उपयोग किया जाएगा।
**FastAPI** उस *temporary* response का उपयोग cookies (साथ ही headers और status code) निकालने के लिए करेगा, और उन्हें final response में डाल देगा जिसमें आपके द्वारा return किया गया value होगा, किसी भी `response_model` द्वारा filter किया हुआ।
आप dependencies में भी `Response` parameter घोषित कर सकते हैं, और उनमें cookies (और headers) set कर सकते हैं।
## सीधे `Response` return करें { #return-a-response-directly }
आप अपने code में सीधे `Response` return करते समय भी cookies बना सकते हैं।
ऐसा करने के लिए, आप [सीधे Response Return करें](response-directly.md) में बताए अनुसार एक response बना सकते हैं।
फिर उसमें Cookies set करें, और फिर उसे return करें:
{* ../../docs_src/response_cookies/tutorial001_py310.py hl[10:12] *}
/// tip | सुझाव
ध्यान रखें कि अगर आप `Response` parameter का उपयोग करने के बजाय सीधे response return करते हैं, तो FastAPI उसे सीधे return करेगा।
इसलिए, आपको यह सुनिश्चित करना होगा कि आपका data सही प्रकार का है। उदाहरण के लिए, अगर आप `JSONResponse` return कर रहे हैं, तो वह JSON के साथ compatible हो।
और यह भी कि आप कोई ऐसा data नहीं भेज रहे हैं जिसे `response_model` द्वारा filter किया जाना चाहिए था।
///
### अधिक जानकारी { #more-info }
/// note | तकनीकी विवरण
आप `from starlette.responses import Response` या `from starlette.responses import JSONResponse` का भी उपयोग कर सकते हैं।
**FastAPI** आपकी सुविधा के लिए, developer के रूप में, वही `starlette.responses` `fastapi.responses` के रूप में प्रदान करता है। लेकिन उपलब्ध अधिकांश responses सीधे Starlette से आते हैं।
और क्योंकि `Response` का उपयोग अक्सर headers और cookies set करने के लिए किया जा सकता है, **FastAPI** इसे `fastapi.Response` पर भी प्रदान करता है।
///
सभी उपलब्ध parameters और options देखने के लिए, [Starlette में documentation](https://www.starlette.dev/responses/#set-cookie) देखें।
@@ -0,0 +1,83 @@
# सीधे एक Response लौटाएँ { #return-a-response-directly }
जब आप **FastAPI** *path operation* बनाते हैं, तो सामान्यतः आप उससे कोई भी data लौटा सकते हैं: एक `dict`, एक `list`, एक Pydantic model, एक database model, आदि।
अगर आप [Response Model](../tutorial/response-model.md) declare करते हैं, तो FastAPI Pydantic का उपयोग करके data को JSON में serialize करने के लिए उसका उपयोग करेगा।
अगर आप response model declare नहीं करते, तो FastAPI [JSON Compatible Encoder](../tutorial/encoder.md) में समझाए गए `jsonable_encoder` का उपयोग करेगा और उसे एक `JSONResponse` में रखेगा।
आप सीधे एक `JSONResponse` भी बना सकते हैं और उसे लौटा सकते हैं।
/// tip | सुझाव
आम तौर पर सीधे `JSONResponse` लौटाने की तुलना में [Response Model](../tutorial/response-model.md) का उपयोग करने पर performance काफी बेहतर होगी, क्योंकि उस तरीके से यह Rust में Pydantic का उपयोग करके data serialize करता है।
///
## एक `Response` लौटाएँ { #return-a-response }
आप एक `Response` या उसकी कोई भी sub-class लौटा सकते हैं।
/// note | नोट
`JSONResponse` खुद `Response` की एक sub-class है।
///
और जब आप एक `Response` लौटाते हैं, तो **FastAPI** उसे सीधे pass कर देगा।
यह Pydantic models के साथ कोई data conversion नहीं करेगा, contents को किसी भी type में convert नहीं करेगा, आदि।
यह आपको बहुत अधिक **flexibility** देता है। आप कोई भी data type लौटा सकते हैं, किसी भी data declaration या validation को override कर सकते हैं, आदि।
यह आपको बहुत अधिक **responsibility** भी देता है। आपको यह सुनिश्चित करना होगा कि आप जो data लौटा रहे हैं वह सही है, सही format में है, वह serialize किया जा सकता है, आदि।
## `Response` में `jsonable_encoder` का उपयोग करना { #using-the-jsonable-encoder-in-a-response }
क्योंकि **FastAPI** आपके लौटाए गए `Response` में कोई बदलाव नहीं करता, आपको सुनिश्चित करना होगा कि उसके contents इसके लिए तैयार हैं।
उदाहरण के लिए, आप किसी Pydantic model को पहले `dict` में convert किए बिना `JSONResponse` में नहीं रख सकते, जिसमें सभी data types (जैसे `datetime`, `UUID`, आदि) JSON-compatible types में convert किए गए हों।
ऐसे मामलों के लिए, response को pass करने से पहले आप अपने data को convert करने के लिए `jsonable_encoder` का उपयोग कर सकते हैं:
{* ../../docs_src/response_directly/tutorial001_py310.py hl[5:6,20:21] *}
/// note | तकनीकी विवरण
आप `from starlette.responses import JSONResponse` का भी उपयोग कर सकते हैं।
**FastAPI** आपकी सुविधा के लिए, developer के रूप में, वही `starlette.responses` `fastapi.responses` के रूप में उपलब्ध कराता है। लेकिन उपलब्ध अधिकांश responses सीधे Starlette से आते हैं।
///
## custom `Response` लौटाना { #returning-a-custom-response }
ऊपर दिया गया उदाहरण वे सभी हिस्से दिखाता है जिनकी आपको जरूरत है, लेकिन यह अभी बहुत उपयोगी नहीं है, क्योंकि आप सीधे `item` लौटा सकते थे, और **FastAPI** उसे आपके लिए `JSONResponse` में रख देता, उसे `dict` में convert करता, आदि। यह सब default रूप से होता है।
अब, देखते हैं कि आप इसका उपयोग custom response लौटाने के लिए कैसे कर सकते हैं।
मान लें कि आप एक [XML](https://en.wikipedia.org/wiki/XML) response लौटाना चाहते हैं।
आप अपना XML content एक string में रख सकते हैं, उसे `Response` में रख सकते हैं, और उसे लौटा सकते हैं:
{* ../../docs_src/response_directly/tutorial002_py310.py hl[1,18] *}
## Response Model कैसे काम करता है { #how-a-response-model-works }
जब आप किसी path operation में [Response Model - Return Type](../tutorial/response-model.md) declare करते हैं, तो **FastAPI** Pydantic का उपयोग करके data को JSON में serialize करने के लिए उसका उपयोग करेगा।
{* ../../docs_src/response_model/tutorial001_01_py310.py hl[16,21] *}
क्योंकि यह Rust side पर होगा, performance regular Python और `JSONResponse` class के साथ किए जाने की तुलना में काफी बेहतर होगी।
`response_model` या return type का उपयोग करते समय, FastAPI data को convert करने के लिए `jsonable_encoder` का उपयोग नहीं करेगा (जो धीमा होता), और न ही `JSONResponse` class का उपयोग करेगा।
इसके बजाय यह response model (या return type) का उपयोग करके Pydantic के साथ generate किए गए JSON bytes लेता है और JSON के लिए सही media type (`application/json`) के साथ सीधे एक `Response` लौटाता है।
## नोट्स { #notes }
जब आप सीधे एक `Response` लौटाते हैं, तो उसका data अपने-आप validate, convert (serialize), या document नहीं किया जाता।
लेकिन आप फिर भी उसे [OpenAPI में अतिरिक्त Responses](additional-responses.md) में बताए अनुसार document कर सकते हैं।
बाद के sections में आप देख सकते हैं कि automatic data conversion, documentation, आदि रखते हुए इन custom `Response`s का उपयोग/declare कैसे करें।
+41
View File
@@ -0,0 +1,41 @@
# Response Headers { #response-headers }
## `Response` parameter का उपयोग करें { #use-a-response-parameter }
आप अपने *path operation function* में `Response` प्रकार का parameter घोषित कर सकते हैं (जैसा कि आप cookies के लिए कर सकते हैं)।
और फिर आप उस *अस्थायी* response object में headers सेट कर सकते हैं।
{* ../../docs_src/response_headers/tutorial002_py310.py hl[1, 7:8] *}
और फिर आप अपनी ज़रूरत का कोई भी object return कर सकते हैं, जैसा कि आप सामान्य रूप से करते हैं (एक `dict`, database model, आदि)।
और अगर आपने `response_model` घोषित किया है, तो वह अब भी आपके return किए गए object को filter और convert करने के लिए उपयोग किया जाएगा।
**FastAPI** headers (साथ ही cookies और status code) निकालने के लिए उस *अस्थायी* response का उपयोग करेगा, और उन्हें अंतिम response में डाल देगा जिसमें आपके द्वारा return किया गया value होता है, जिसे किसी भी `response_model` द्वारा filter किया गया होता है।
आप dependencies में भी `Response` parameter घोषित कर सकते हैं, और उनमें headers (और cookies) सेट कर सकते हैं।
## सीधे `Response` return करें { #return-a-response-directly }
जब आप सीधे `Response` return करते हैं, तब भी आप headers जोड़ सकते हैं।
[सीधे Response Return करें](response-directly.md) में वर्णित तरीके से response बनाएँ और headers को एक अतिरिक्त parameter के रूप में पास करें:
{* ../../docs_src/response_headers/tutorial001_py310.py hl[10:12] *}
/// note | तकनीकी विवरण
आप `from starlette.responses import Response` या `from starlette.responses import JSONResponse` का भी उपयोग कर सकते हैं।
**FastAPI** आपकी, developer की, सुविधा के लिए वही `starlette.responses` `fastapi.responses` के रूप में प्रदान करता है। लेकिन उपलब्ध अधिकांश responses सीधे Starlette से आते हैं।
और क्योंकि `Response` का उपयोग अक्सर headers और cookies सेट करने के लिए किया जा सकता है, **FastAPI** इसे `fastapi.Response` पर भी प्रदान करता है।
///
## Custom Headers { #custom-headers }
ध्यान रखें कि custom proprietary headers को [`X-` prefix का उपयोग करके](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers) जोड़ा जा सकता है।
लेकिन अगर आपके पास custom headers हैं जिन्हें आप चाहते हैं कि browser में कोई client देख सके, तो आपको उन्हें अपनी CORS configurations में जोड़ना होगा ([CORS (Cross-Origin Resource Sharing)](../tutorial/cors.md) में और पढ़ें), इसके लिए [Starlette के CORS docs](https://www.starlette.dev/middleware/#corsmiddleware) में documented parameter `expose_headers` का उपयोग करें।
@@ -0,0 +1,107 @@
# HTTP Basic Auth { #http-basic-auth }
सबसे सरल मामलों के लिए, आप HTTP Basic Auth का उपयोग कर सकते हैं।
HTTP Basic Auth में, application एक header की अपेक्षा करता है जिसमें username और password होता है।
अगर उसे यह नहीं मिलता, तो यह HTTP 401 "Unauthorized" error लौटाता है।
और `WWW-Authenticate` header लौटाता है जिसका value `Basic` होता है, और एक optional `realm` parameter होता है।
यह browser को username और password के लिए integrated prompt दिखाने को कहता है।
फिर, जब आप वह username और password टाइप करते हैं, तो browser उन्हें header में अपने-आप भेज देता है।
## Simple HTTP Basic Auth { #simple-http-basic-auth }
* `HTTPBasic` और `HTTPBasicCredentials` import करें।
* `HTTPBasic` का उपयोग करके एक "`security` scheme" बनाएँ।
* अपने *path operation* में dependency के साथ उस `security` का उपयोग करें।
* यह `HTTPBasicCredentials` type का एक object लौटाता है:
* इसमें भेजे गए `username` और `password` होते हैं।
{* ../../docs_src/security/tutorial006_an_py310.py hl[4,8,12] *}
जब आप पहली बार URL खोलने की कोशिश करते हैं (या docs में "Execute" button पर क्लिक करते हैं), तो browser आपसे आपका username और password पूछेगा:
<img src="/img/tutorial/security/image12.png">
## Username जाँचें { #check-the-username }
यहाँ एक अधिक complete example है।
यह जाँचने के लिए dependency का उपयोग करें कि username और password सही हैं या नहीं।
इसके लिए, username और password जाँचने के लिए Python standard module [`secrets`](https://docs.python.org/3/library/secrets.html) का उपयोग करें।
`secrets.compare_digest()` को `bytes` या ऐसा `str` लेना होता है जिसमें केवल ASCII characters (English वाले) हों, इसका मतलब है कि यह `á` जैसे characters के साथ काम नहीं करेगा, जैसे `Sebastián` में।
इसे handle करने के लिए, हम पहले `username` और `password` को UTF-8 से encode करके `bytes` में convert करते हैं।
फिर हम `secrets.compare_digest()` का उपयोग करके यह सुनिश्चित कर सकते हैं कि `credentials.username` `"stanleyjobson"` है, और `credentials.password` `"swordfish"` है।
{* ../../docs_src/security/tutorial007_an_py310.py hl[1,12:24] *}
यह इसके समान होगा:
```Python
if not (credentials.username == "stanleyjobson") or not (credentials.password == "swordfish"):
# कोई error लौटाएँ
...
```
लेकिन `secrets.compare_digest()` का उपयोग करने से यह "timing attacks" नाम के attacks के एक type के विरुद्ध सुरक्षित रहेगा।
### Timing Attacks { #timing-attacks }
लेकिन "timing attack" क्या होता है?
मान लीजिए कुछ attackers username और password का अनुमान लगाने की कोशिश कर रहे हैं।
और वे username `johndoe` और password `love123` के साथ एक request भेजते हैं।
तब आपकी application में Python code कुछ इस तरह के बराबर होगा:
```Python
if "johndoe" == "stanleyjobson" and "love123" == "swordfish":
...
```
लेकिन जैसे ही Python `johndoe` में पहले `j` की तुलना `stanleyjobson` में पहले `s` से करता है, यह `False` लौटा देगा, क्योंकि उसे पहले से पता है कि ये दोनों strings समान नहीं हैं, यह सोचते हुए कि "बाकी अक्षरों की तुलना करके और computation खर्च करने की जरूरत नहीं है"। और आपकी application कहेगी "Incorrect username or password"।
लेकिन फिर attackers username `stanleyjobsox` और password `love123` के साथ कोशिश करते हैं।
और आपका application code कुछ ऐसा करता है:
```Python
if "stanleyjobsox" == "stanleyjobson" and "love123" == "swordfish":
...
```
Python को यह समझने से पहले कि दोनों strings समान नहीं हैं, `stanleyjobsox` और `stanleyjobson` दोनों में पूरे `stanleyjobso` की तुलना करनी पड़ेगी। इसलिए "Incorrect username or password" का reply वापस देने में कुछ extra microseconds लगेंगे।
#### जवाब देने में लगा समय attackers की मदद करता है { #the-time-to-answer-helps-the-attackers }
उस समय, यह देखकर कि server ने "Incorrect username or password" response भेजने में कुछ microseconds ज्यादा लिए, attackers जान जाएँगे कि उन्होंने _कुछ_ सही पाया है, शुरुआती अक्षरों में से कुछ सही थे।
और फिर वे यह जानते हुए फिर कोशिश कर सकते हैं कि यह शायद `johndoe` की तुलना में `stanleyjobsox` से ज्यादा मिलता-जुलता है।
#### एक "professional" attack { #a-professional-attack }
बेशक, attackers यह सब हाथ से नहीं करेंगे, वे इसे करने के लिए एक program लिखेंगे, संभवतः प्रति सेकंड हजारों या लाखों tests के साथ। और उन्हें एक समय में बस एक extra सही अक्षर मिलेगा।
लेकिन ऐसा करते हुए, कुछ minutes या hours में attackers ने हमारी application की "help" से सही username और password का अनुमान लगा लिया होगा, सिर्फ जवाब देने में लगे समय का उपयोग करके।
#### इसे `secrets.compare_digest()` से ठीक करें { #fix-it-with-secrets-compare-digest }
लेकिन हमारे code में हम वास्तव में `secrets.compare_digest()` का उपयोग कर रहे हैं।
संक्षेप में, `stanleyjobsox` की तुलना `stanleyjobson` से करने में उतना ही समय लगेगा जितना `johndoe` की तुलना `stanleyjobson` से करने में लगता है। और password के लिए भी वही।
इस तरह, अपने application code में `secrets.compare_digest()` का उपयोग करके, यह security attacks की इस पूरी range के विरुद्ध सुरक्षित रहेगा।
### Error लौटाएँ { #return-the-error }
यह detect करने के बाद कि credentials incorrect हैं, status code 401 (वही जो तब लौटाया जाता है जब कोई credentials provide नहीं किए जाते) के साथ एक `HTTPException` लौटाएँ और browser को login prompt फिर से दिखाने के लिए `WWW-Authenticate` header जोड़ें:
{* ../../docs_src/security/tutorial007_an_py310.py hl[26:30] *}
+19
View File
@@ -0,0 +1,19 @@
# उन्नत सुरक्षा { #advanced-security }
## अतिरिक्त Features { #additional-features }
[Tutorial - User Guide: Security](../../tutorial/security/index.md) में शामिल चीज़ों के अलावा सुरक्षा संभालने के लिए कुछ अतिरिक्त features हैं।
/// tip | सुझाव
अगले sections **ज़रूरी नहीं कि "उन्नत" ही हों**
और यह संभव है कि आपके use case के लिए समाधान उनमें से किसी एक में हो।
///
## पहले Tutorial पढ़ें { #read-the-tutorial-first }
अगले sections मानकर चलते हैं कि आपने मुख्य [Tutorial - User Guide: Security](../../tutorial/security/index.md) पहले ही पढ़ लिया है।
वे सभी समान concepts पर आधारित हैं, लेकिन कुछ अतिरिक्त functionalities की अनुमति देते हैं।

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