applications.py 180 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774
  1. import os
  2. from collections.abc import Awaitable, Callable, Coroutine, Sequence
  3. from enum import Enum
  4. from typing import Annotated, Any, Literal, TypeVar
  5. from annotated_doc import Doc
  6. from fastapi import routing
  7. from fastapi.datastructures import Default, DefaultPlaceholder
  8. from fastapi.exception_handlers import (
  9. http_exception_handler,
  10. request_validation_exception_handler,
  11. websocket_request_validation_exception_handler,
  12. )
  13. from fastapi.exceptions import RequestValidationError, WebSocketRequestValidationError
  14. from fastapi.logger import logger
  15. from fastapi.middleware.asyncexitstack import AsyncExitStackMiddleware
  16. from fastapi.openapi.docs import (
  17. get_redoc_html,
  18. get_swagger_ui_html,
  19. get_swagger_ui_oauth2_redirect_html,
  20. )
  21. from fastapi.openapi.utils import get_openapi
  22. from fastapi.params import Depends
  23. from fastapi.types import DecoratedCallable, IncEx
  24. from fastapi.utils import generate_unique_id
  25. from starlette.applications import Starlette
  26. from starlette.datastructures import State
  27. from starlette.exceptions import HTTPException
  28. from starlette.middleware import Middleware
  29. from starlette.middleware.base import BaseHTTPMiddleware
  30. from starlette.middleware.errors import ServerErrorMiddleware
  31. from starlette.middleware.exceptions import ExceptionMiddleware
  32. from starlette.requests import Request
  33. from starlette.responses import HTMLResponse, JSONResponse, Response
  34. from starlette.routing import BaseRoute
  35. from starlette.types import ASGIApp, ExceptionHandler, Lifespan, Receive, Scope, Send
  36. from typing_extensions import deprecated
  37. AppType = TypeVar("AppType", bound="FastAPI")
  38. class FastAPI(Starlette):
  39. """
  40. `FastAPI` app class, the main entrypoint to use FastAPI.
  41. Read more in the
  42. [FastAPI docs for First Steps](https://fastapi.tiangolo.com/tutorial/first-steps/).
  43. ## Example
  44. ```python
  45. from fastapi import FastAPI
  46. app = FastAPI()
  47. ```
  48. """
  49. def __init__(
  50. self: AppType,
  51. *,
  52. debug: Annotated[
  53. bool,
  54. Doc(
  55. """
  56. Boolean indicating if debug tracebacks should be returned on server
  57. errors.
  58. Read more in the
  59. [Starlette docs for Applications](https://starlette.dev/applications/#starlette.applications.Starlette).
  60. """
  61. ),
  62. ] = False,
  63. routes: Annotated[
  64. list[BaseRoute] | None,
  65. Doc(
  66. """
  67. **Note**: you probably shouldn't use this parameter, it is inherited
  68. from Starlette and supported for compatibility.
  69. ---
  70. A list of routes to serve incoming HTTP and WebSocket requests.
  71. """
  72. ),
  73. deprecated(
  74. """
  75. You normally wouldn't use this parameter with FastAPI, it is inherited
  76. from Starlette and supported for compatibility.
  77. In FastAPI, you normally would use the *path operation methods*,
  78. like `app.get()`, `app.post()`, etc.
  79. """
  80. ),
  81. ] = None,
  82. title: Annotated[
  83. str,
  84. Doc(
  85. """
  86. The title of the API.
  87. It will be added to the generated OpenAPI (e.g. visible at `/docs`).
  88. Read more in the
  89. [FastAPI docs for Metadata and Docs URLs](https://fastapi.tiangolo.com/tutorial/metadata/#metadata-for-api).
  90. **Example**
  91. ```python
  92. from fastapi import FastAPI
  93. app = FastAPI(title="ChimichangApp")
  94. ```
  95. """
  96. ),
  97. ] = "FastAPI",
  98. summary: Annotated[
  99. str | None,
  100. Doc(
  101. """
  102. A short summary of the API.
  103. It will be added to the generated OpenAPI (e.g. visible at `/docs`).
  104. Read more in the
  105. [FastAPI docs for Metadata and Docs URLs](https://fastapi.tiangolo.com/tutorial/metadata/#metadata-for-api).
  106. **Example**
  107. ```python
  108. from fastapi import FastAPI
  109. app = FastAPI(summary="Deadpond's favorite app. Nuff said.")
  110. ```
  111. """
  112. ),
  113. ] = None,
  114. description: Annotated[
  115. str,
  116. Doc(
  117. '''
  118. A description of the API. Supports Markdown (using
  119. [CommonMark syntax](https://commonmark.org/)).
  120. It will be added to the generated OpenAPI (e.g. visible at `/docs`).
  121. Read more in the
  122. [FastAPI docs for Metadata and Docs URLs](https://fastapi.tiangolo.com/tutorial/metadata/#metadata-for-api).
  123. **Example**
  124. ```python
  125. from fastapi import FastAPI
  126. app = FastAPI(
  127. description="""
  128. ChimichangApp API helps you do awesome stuff. 🚀
  129. ## Items
  130. You can **read items**.
  131. ## Users
  132. You will be able to:
  133. * **Create users** (_not implemented_).
  134. * **Read users** (_not implemented_).
  135. """
  136. )
  137. ```
  138. '''
  139. ),
  140. ] = "",
  141. version: Annotated[
  142. str,
  143. Doc(
  144. """
  145. The version of the API.
  146. **Note** This is the version of your application, not the version of
  147. the OpenAPI specification nor the version of FastAPI being used.
  148. It will be added to the generated OpenAPI (e.g. visible at `/docs`).
  149. Read more in the
  150. [FastAPI docs for Metadata and Docs URLs](https://fastapi.tiangolo.com/tutorial/metadata/#metadata-for-api).
  151. **Example**
  152. ```python
  153. from fastapi import FastAPI
  154. app = FastAPI(version="0.0.1")
  155. ```
  156. """
  157. ),
  158. ] = "0.1.0",
  159. openapi_url: Annotated[
  160. str | None,
  161. Doc(
  162. """
  163. The URL where the OpenAPI schema will be served from.
  164. If you set it to `None`, no OpenAPI schema will be served publicly, and
  165. the default automatic endpoints `/docs` and `/redoc` will also be
  166. disabled.
  167. Read more in the
  168. [FastAPI docs for Metadata and Docs URLs](https://fastapi.tiangolo.com/tutorial/metadata/#openapi-url).
  169. **Example**
  170. ```python
  171. from fastapi import FastAPI
  172. app = FastAPI(openapi_url="/api/v1/openapi.json")
  173. ```
  174. """
  175. ),
  176. ] = "/openapi.json",
  177. openapi_tags: Annotated[
  178. list[dict[str, Any]] | None,
  179. Doc(
  180. """
  181. A list of tags used by OpenAPI, these are the same `tags` you can set
  182. in the *path operations*, like:
  183. * `@app.get("/users/", tags=["users"])`
  184. * `@app.get("/items/", tags=["items"])`
  185. The order of the tags can be used to specify the order shown in
  186. tools like Swagger UI, used in the automatic path `/docs`.
  187. It's not required to specify all the tags used.
  188. The tags that are not declared MAY be organized randomly or based
  189. on the tools' logic. Each tag name in the list MUST be unique.
  190. The value of each item is a `dict` containing:
  191. * `name`: The name of the tag.
  192. * `description`: A short description of the tag.
  193. [CommonMark syntax](https://commonmark.org/) MAY be used for rich
  194. text representation.
  195. * `externalDocs`: Additional external documentation for this tag. If
  196. provided, it would contain a `dict` with:
  197. * `description`: A short description of the target documentation.
  198. [CommonMark syntax](https://commonmark.org/) MAY be used for
  199. rich text representation.
  200. * `url`: The URL for the target documentation. Value MUST be in
  201. the form of a URL.
  202. Read more in the
  203. [FastAPI docs for Metadata and Docs URLs](https://fastapi.tiangolo.com/tutorial/metadata/#metadata-for-tags).
  204. **Example**
  205. ```python
  206. from fastapi import FastAPI
  207. tags_metadata = [
  208. {
  209. "name": "users",
  210. "description": "Operations with users. The **login** logic is also here.",
  211. },
  212. {
  213. "name": "items",
  214. "description": "Manage items. So _fancy_ they have their own docs.",
  215. "externalDocs": {
  216. "description": "Items external docs",
  217. "url": "https://fastapi.tiangolo.com/",
  218. },
  219. },
  220. ]
  221. app = FastAPI(openapi_tags=tags_metadata)
  222. ```
  223. """
  224. ),
  225. ] = None,
  226. servers: Annotated[
  227. list[dict[str, str | Any]] | None,
  228. Doc(
  229. """
  230. A `list` of `dict`s with connectivity information to a target server.
  231. You would use it, for example, if your application is served from
  232. different domains and you want to use the same Swagger UI in the
  233. browser to interact with each of them (instead of having multiple
  234. browser tabs open). Or if you want to leave fixed the possible URLs.
  235. If the servers `list` is not provided, or is an empty `list`, the
  236. `servers` property in the generated OpenAPI will be:
  237. * a `dict` with a `url` value of the application's mounting point
  238. (`root_path`) if it's different from `/`.
  239. * otherwise, the `servers` property will be omitted from the OpenAPI
  240. schema.
  241. Each item in the `list` is a `dict` containing:
  242. * `url`: A URL to the target host. This URL supports Server Variables
  243. and MAY be relative, to indicate that the host location is relative
  244. to the location where the OpenAPI document is being served. Variable
  245. substitutions will be made when a variable is named in `{`brackets`}`.
  246. * `description`: An optional string describing the host designated by
  247. the URL. [CommonMark syntax](https://commonmark.org/) MAY be used for
  248. rich text representation.
  249. * `variables`: A `dict` between a variable name and its value. The value
  250. is used for substitution in the server's URL template.
  251. Read more in the
  252. [FastAPI docs for Behind a Proxy](https://fastapi.tiangolo.com/advanced/behind-a-proxy/#additional-servers).
  253. **Example**
  254. ```python
  255. from fastapi import FastAPI
  256. app = FastAPI(
  257. servers=[
  258. {"url": "https://stag.example.com", "description": "Staging environment"},
  259. {"url": "https://prod.example.com", "description": "Production environment"},
  260. ]
  261. )
  262. ```
  263. """
  264. ),
  265. ] = None,
  266. dependencies: Annotated[
  267. Sequence[Depends] | None,
  268. Doc(
  269. """
  270. A list of global dependencies, they will be applied to each
  271. *path operation*, including in sub-routers.
  272. Read more about it in the
  273. [FastAPI docs for Global Dependencies](https://fastapi.tiangolo.com/tutorial/dependencies/global-dependencies/).
  274. **Example**
  275. ```python
  276. from fastapi import Depends, FastAPI
  277. from .dependencies import func_dep_1, func_dep_2
  278. app = FastAPI(dependencies=[Depends(func_dep_1), Depends(func_dep_2)])
  279. ```
  280. """
  281. ),
  282. ] = None,
  283. default_response_class: Annotated[
  284. type[Response],
  285. Doc(
  286. """
  287. The default response class to be used.
  288. Read more in the
  289. [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#default-response-class).
  290. **Example**
  291. ```python
  292. from fastapi import FastAPI
  293. from fastapi.responses import ORJSONResponse
  294. app = FastAPI(default_response_class=ORJSONResponse)
  295. ```
  296. """
  297. ),
  298. ] = Default(JSONResponse),
  299. redirect_slashes: Annotated[
  300. bool,
  301. Doc(
  302. """
  303. Whether to detect and redirect slashes in URLs when the client doesn't
  304. use the same format.
  305. **Example**
  306. ```python
  307. from fastapi import FastAPI
  308. app = FastAPI(redirect_slashes=True) # the default
  309. @app.get("/items/")
  310. async def read_items():
  311. return [{"item_id": "Foo"}]
  312. ```
  313. With this app, if a client goes to `/items` (without a trailing slash),
  314. they will be automatically redirected with an HTTP status code of 307
  315. to `/items/`.
  316. """
  317. ),
  318. ] = True,
  319. docs_url: Annotated[
  320. str | None,
  321. Doc(
  322. """
  323. The path to the automatic interactive API documentation.
  324. It is handled in the browser by Swagger UI.
  325. The default URL is `/docs`. You can disable it by setting it to `None`.
  326. If `openapi_url` is set to `None`, this will be automatically disabled.
  327. Read more in the
  328. [FastAPI docs for Metadata and Docs URLs](https://fastapi.tiangolo.com/tutorial/metadata/#docs-urls).
  329. **Example**
  330. ```python
  331. from fastapi import FastAPI
  332. app = FastAPI(docs_url="/documentation", redoc_url=None)
  333. ```
  334. """
  335. ),
  336. ] = "/docs",
  337. redoc_url: Annotated[
  338. str | None,
  339. Doc(
  340. """
  341. The path to the alternative automatic interactive API documentation
  342. provided by ReDoc.
  343. The default URL is `/redoc`. You can disable it by setting it to `None`.
  344. If `openapi_url` is set to `None`, this will be automatically disabled.
  345. Read more in the
  346. [FastAPI docs for Metadata and Docs URLs](https://fastapi.tiangolo.com/tutorial/metadata/#docs-urls).
  347. **Example**
  348. ```python
  349. from fastapi import FastAPI
  350. app = FastAPI(docs_url="/documentation", redoc_url="redocumentation")
  351. ```
  352. """
  353. ),
  354. ] = "/redoc",
  355. swagger_ui_oauth2_redirect_url: Annotated[
  356. str | None,
  357. Doc(
  358. """
  359. The OAuth2 redirect endpoint for the Swagger UI.
  360. By default it is `/docs/oauth2-redirect`.
  361. This is only used if you use OAuth2 (with the "Authorize" button)
  362. with Swagger UI.
  363. """
  364. ),
  365. ] = "/docs/oauth2-redirect",
  366. swagger_ui_init_oauth: Annotated[
  367. dict[str, Any] | None,
  368. Doc(
  369. """
  370. OAuth2 configuration for the Swagger UI, by default shown at `/docs`.
  371. Read more about the available configuration options in the
  372. [Swagger UI docs](https://swagger.io/docs/open-source-tools/swagger-ui/usage/oauth2/).
  373. """
  374. ),
  375. ] = None,
  376. middleware: Annotated[
  377. Sequence[Middleware] | None,
  378. Doc(
  379. """
  380. List of middleware to be added when creating the application.
  381. In FastAPI you would normally do this with `app.add_middleware()`
  382. instead.
  383. Read more in the
  384. [FastAPI docs for Middleware](https://fastapi.tiangolo.com/tutorial/middleware/).
  385. """
  386. ),
  387. ] = None,
  388. exception_handlers: Annotated[
  389. dict[
  390. int | type[Exception],
  391. Callable[[Request, Any], Coroutine[Any, Any, Response]],
  392. ]
  393. | None,
  394. Doc(
  395. """
  396. A dictionary with handlers for exceptions.
  397. In FastAPI, you would normally use the decorator
  398. `@app.exception_handler()`.
  399. Read more in the
  400. [FastAPI docs for Handling Errors](https://fastapi.tiangolo.com/tutorial/handling-errors/).
  401. """
  402. ),
  403. ] = None,
  404. on_startup: Annotated[
  405. Sequence[Callable[[], Any]] | None,
  406. Doc(
  407. """
  408. A list of startup event handler functions.
  409. You should instead use the `lifespan` handlers.
  410. Read more in the [FastAPI docs for `lifespan`](https://fastapi.tiangolo.com/advanced/events/).
  411. """
  412. ),
  413. ] = None,
  414. on_shutdown: Annotated[
  415. Sequence[Callable[[], Any]] | None,
  416. Doc(
  417. """
  418. A list of shutdown event handler functions.
  419. You should instead use the `lifespan` handlers.
  420. Read more in the
  421. [FastAPI docs for `lifespan`](https://fastapi.tiangolo.com/advanced/events/).
  422. """
  423. ),
  424. ] = None,
  425. lifespan: Annotated[
  426. Lifespan[AppType] | None,
  427. Doc(
  428. """
  429. A `Lifespan` context manager handler. This replaces `startup` and
  430. `shutdown` functions with a single context manager.
  431. Read more in the
  432. [FastAPI docs for `lifespan`](https://fastapi.tiangolo.com/advanced/events/).
  433. """
  434. ),
  435. ] = None,
  436. terms_of_service: Annotated[
  437. str | None,
  438. Doc(
  439. """
  440. A URL to the Terms of Service for your API.
  441. It will be added to the generated OpenAPI (e.g. visible at `/docs`).
  442. Read more at the
  443. [FastAPI docs for Metadata and Docs URLs](https://fastapi.tiangolo.com/tutorial/metadata/#metadata-for-api).
  444. **Example**
  445. ```python
  446. app = FastAPI(terms_of_service="http://example.com/terms/")
  447. ```
  448. """
  449. ),
  450. ] = None,
  451. contact: Annotated[
  452. dict[str, str | Any] | None,
  453. Doc(
  454. """
  455. A dictionary with the contact information for the exposed API.
  456. It can contain several fields.
  457. * `name`: (`str`) The name of the contact person/organization.
  458. * `url`: (`str`) A URL pointing to the contact information. MUST be in
  459. the format of a URL.
  460. * `email`: (`str`) The email address of the contact person/organization.
  461. MUST be in the format of an email address.
  462. It will be added to the generated OpenAPI (e.g. visible at `/docs`).
  463. Read more at the
  464. [FastAPI docs for Metadata and Docs URLs](https://fastapi.tiangolo.com/tutorial/metadata/#metadata-for-api).
  465. **Example**
  466. ```python
  467. app = FastAPI(
  468. contact={
  469. "name": "Deadpoolio the Amazing",
  470. "url": "http://x-force.example.com/contact/",
  471. "email": "dp@x-force.example.com",
  472. }
  473. )
  474. ```
  475. """
  476. ),
  477. ] = None,
  478. license_info: Annotated[
  479. dict[str, str | Any] | None,
  480. Doc(
  481. """
  482. A dictionary with the license information for the exposed API.
  483. It can contain several fields.
  484. * `name`: (`str`) **REQUIRED** (if a `license_info` is set). The
  485. license name used for the API.
  486. * `identifier`: (`str`) An [SPDX](https://spdx.dev/) license expression
  487. for the API. The `identifier` field is mutually exclusive of the `url`
  488. field. Available since OpenAPI 3.1.0, FastAPI 0.99.0.
  489. * `url`: (`str`) A URL to the license used for the API. This MUST be
  490. the format of a URL.
  491. It will be added to the generated OpenAPI (e.g. visible at `/docs`).
  492. Read more at the
  493. [FastAPI docs for Metadata and Docs URLs](https://fastapi.tiangolo.com/tutorial/metadata/#metadata-for-api).
  494. **Example**
  495. ```python
  496. app = FastAPI(
  497. license_info={
  498. "name": "Apache 2.0",
  499. "url": "https://www.apache.org/licenses/LICENSE-2.0.html",
  500. }
  501. )
  502. ```
  503. """
  504. ),
  505. ] = None,
  506. openapi_prefix: Annotated[
  507. str,
  508. Doc(
  509. """
  510. A URL prefix for the OpenAPI URL.
  511. """
  512. ),
  513. deprecated(
  514. """
  515. "openapi_prefix" has been deprecated in favor of "root_path", which
  516. follows more closely the ASGI standard, is simpler, and more
  517. automatic.
  518. """
  519. ),
  520. ] = "",
  521. root_path: Annotated[
  522. str,
  523. Doc(
  524. """
  525. A path prefix handled by a proxy that is not seen by the application
  526. but is seen by external clients, which affects things like Swagger UI.
  527. Read more about it at the
  528. [FastAPI docs for Behind a Proxy](https://fastapi.tiangolo.com/advanced/behind-a-proxy/).
  529. **Example**
  530. ```python
  531. from fastapi import FastAPI
  532. app = FastAPI(root_path="/api/v1")
  533. ```
  534. """
  535. ),
  536. ] = "",
  537. root_path_in_servers: Annotated[
  538. bool,
  539. Doc(
  540. """
  541. To disable automatically generating the URLs in the `servers` field
  542. in the autogenerated OpenAPI using the `root_path`.
  543. Read more about it in the
  544. [FastAPI docs for Behind a Proxy](https://fastapi.tiangolo.com/advanced/behind-a-proxy/#disable-automatic-server-from-root-path).
  545. **Example**
  546. ```python
  547. from fastapi import FastAPI
  548. app = FastAPI(root_path_in_servers=False)
  549. ```
  550. """
  551. ),
  552. ] = True,
  553. responses: Annotated[
  554. dict[int | str, dict[str, Any]] | None,
  555. Doc(
  556. """
  557. Additional responses to be shown in OpenAPI.
  558. It will be added to the generated OpenAPI (e.g. visible at `/docs`).
  559. Read more about it in the
  560. [FastAPI docs for Additional Responses in OpenAPI](https://fastapi.tiangolo.com/advanced/additional-responses/).
  561. And in the
  562. [FastAPI docs for Bigger Applications](https://fastapi.tiangolo.com/tutorial/bigger-applications/#include-an-apirouter-with-a-custom-prefix-tags-responses-and-dependencies).
  563. """
  564. ),
  565. ] = None,
  566. callbacks: Annotated[
  567. list[BaseRoute] | None,
  568. Doc(
  569. """
  570. OpenAPI callbacks that should apply to all *path operations*.
  571. It will be added to the generated OpenAPI (e.g. visible at `/docs`).
  572. Read more about it in the
  573. [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/).
  574. """
  575. ),
  576. ] = None,
  577. webhooks: Annotated[
  578. routing.APIRouter | None,
  579. Doc(
  580. """
  581. Add OpenAPI webhooks. This is similar to `callbacks` but it doesn't
  582. depend on specific *path operations*.
  583. It will be added to the generated OpenAPI (e.g. visible at `/docs`).
  584. **Note**: This is available since OpenAPI 3.1.0, FastAPI 0.99.0.
  585. Read more about it in the
  586. [FastAPI docs for OpenAPI Webhooks](https://fastapi.tiangolo.com/advanced/openapi-webhooks/).
  587. """
  588. ),
  589. ] = None,
  590. deprecated: Annotated[
  591. bool | None,
  592. Doc(
  593. """
  594. Mark all *path operations* as deprecated. You probably don't need it,
  595. but it's available.
  596. It will be added to the generated OpenAPI (e.g. visible at `/docs`).
  597. Read more about it in the
  598. [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#deprecate-a-path-operation).
  599. """
  600. ),
  601. ] = None,
  602. include_in_schema: Annotated[
  603. bool,
  604. Doc(
  605. """
  606. To include (or not) all the *path operations* in the generated OpenAPI.
  607. You probably don't need it, but it's available.
  608. This affects the generated OpenAPI (e.g. visible at `/docs`).
  609. Read more about it in the
  610. [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-parameters-from-openapi).
  611. """
  612. ),
  613. ] = True,
  614. swagger_ui_parameters: Annotated[
  615. dict[str, Any] | None,
  616. Doc(
  617. """
  618. Parameters to configure Swagger UI, the autogenerated interactive API
  619. documentation (by default at `/docs`).
  620. Read more about it in the
  621. [FastAPI docs about how to Configure Swagger UI](https://fastapi.tiangolo.com/how-to/configure-swagger-ui/).
  622. """
  623. ),
  624. ] = None,
  625. generate_unique_id_function: Annotated[
  626. Callable[[routing.APIRoute], str],
  627. Doc(
  628. """
  629. Customize the function used to generate unique IDs for the *path
  630. operations* shown in the generated OpenAPI.
  631. This is particularly useful when automatically generating clients or
  632. SDKs for your API.
  633. Read more about it in the
  634. [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).
  635. """
  636. ),
  637. ] = Default(generate_unique_id),
  638. separate_input_output_schemas: Annotated[
  639. bool,
  640. Doc(
  641. """
  642. Whether to generate separate OpenAPI schemas for request body and
  643. response body when the results would be more precise.
  644. This is particularly useful when automatically generating clients.
  645. For example, if you have a model like:
  646. ```python
  647. from pydantic import BaseModel
  648. class Item(BaseModel):
  649. name: str
  650. tags: list[str] = []
  651. ```
  652. When `Item` is used for input, a request body, `tags` is not required,
  653. the client doesn't have to provide it.
  654. But when using `Item` for output, for a response body, `tags` is always
  655. available because it has a default value, even if it's just an empty
  656. list. So, the client should be able to always expect it.
  657. In this case, there would be two different schemas, one for input and
  658. another one for output.
  659. Read more about it in the
  660. [FastAPI docs about how to separate schemas for input and output](https://fastapi.tiangolo.com/how-to/separate-openapi-schemas)
  661. """
  662. ),
  663. ] = True,
  664. openapi_external_docs: Annotated[
  665. dict[str, Any] | None,
  666. Doc(
  667. """
  668. This field allows you to provide additional external documentation links.
  669. If provided, it must be a dictionary containing:
  670. * `description`: A brief description of the external documentation.
  671. * `url`: The URL pointing to the external documentation. The value **MUST**
  672. be a valid URL format.
  673. **Example**:
  674. ```python
  675. from fastapi import FastAPI
  676. external_docs = {
  677. "description": "Detailed API Reference",
  678. "url": "https://example.com/api-docs",
  679. }
  680. app = FastAPI(openapi_external_docs=external_docs)
  681. ```
  682. """
  683. ),
  684. ] = None,
  685. strict_content_type: Annotated[
  686. bool,
  687. Doc(
  688. """
  689. Enable strict checking for request Content-Type headers.
  690. When `True` (the default), requests with a body that do not include
  691. a `Content-Type` header will **not** be parsed as JSON.
  692. This prevents potential cross-site request forgery (CSRF) attacks
  693. that exploit the browser's ability to send requests without a
  694. Content-Type header, bypassing CORS preflight checks. In particular
  695. applicable for apps that need to be run locally (in localhost).
  696. When `False`, requests without a `Content-Type` header will have
  697. their body parsed as JSON, which maintains compatibility with
  698. certain clients that don't send `Content-Type` headers.
  699. Read more about it in the
  700. [FastAPI docs for Strict Content-Type](https://fastapi.tiangolo.com/advanced/strict-content-type/).
  701. """
  702. ),
  703. ] = True,
  704. **extra: Annotated[
  705. Any,
  706. Doc(
  707. """
  708. Extra keyword arguments to be stored in the app, not used by FastAPI
  709. anywhere.
  710. """
  711. ),
  712. ],
  713. ) -> None:
  714. self.debug = debug
  715. self.title = title
  716. self.summary = summary
  717. self.description = description
  718. self.version = version
  719. self.terms_of_service = terms_of_service
  720. self.contact = contact
  721. self.license_info = license_info
  722. self.openapi_url = openapi_url
  723. self.openapi_tags = openapi_tags
  724. self.root_path_in_servers = root_path_in_servers
  725. self.docs_url = docs_url
  726. self.redoc_url = redoc_url
  727. self.swagger_ui_oauth2_redirect_url = swagger_ui_oauth2_redirect_url
  728. self.swagger_ui_init_oauth = swagger_ui_init_oauth
  729. self.swagger_ui_parameters = swagger_ui_parameters
  730. self.servers = servers or []
  731. self.separate_input_output_schemas = separate_input_output_schemas
  732. self.openapi_external_docs = openapi_external_docs
  733. self.extra = extra
  734. self.openapi_version: Annotated[
  735. str,
  736. Doc(
  737. """
  738. The version string of OpenAPI.
  739. FastAPI will generate OpenAPI version 3.1.0, and will output that as
  740. the OpenAPI version. But some tools, even though they might be
  741. compatible with OpenAPI 3.1.0, might not recognize it as a valid.
  742. So you could override this value to trick those tools into using
  743. the generated OpenAPI. Have in mind that this is a hack. But if you
  744. avoid using features added in OpenAPI 3.1.0, it might work for your
  745. use case.
  746. This is not passed as a parameter to the `FastAPI` class to avoid
  747. giving the false idea that FastAPI would generate a different OpenAPI
  748. schema. It is only available as an attribute.
  749. **Example**
  750. ```python
  751. from fastapi import FastAPI
  752. app = FastAPI()
  753. app.openapi_version = "3.0.2"
  754. ```
  755. """
  756. ),
  757. ] = "3.1.0"
  758. self.openapi_schema: dict[str, Any] | None = None
  759. self._openapi_routes_version: int | None = None
  760. if self.openapi_url:
  761. assert self.title, "A title must be provided for OpenAPI, e.g.: 'My API'"
  762. assert self.version, "A version must be provided for OpenAPI, e.g.: '2.1.0'"
  763. # TODO: remove when discarding the openapi_prefix parameter
  764. if openapi_prefix:
  765. logger.warning(
  766. '"openapi_prefix" has been deprecated in favor of "root_path", which '
  767. "follows more closely the ASGI standard, is simpler, and more "
  768. "automatic. Check the docs at "
  769. "https://fastapi.tiangolo.com/advanced/sub-applications/"
  770. )
  771. self.webhooks: Annotated[
  772. routing.APIRouter,
  773. Doc(
  774. """
  775. The `app.webhooks` attribute is an `APIRouter` with the *path
  776. operations* that will be used just for documentation of webhooks.
  777. Read more about it in the
  778. [FastAPI docs for OpenAPI Webhooks](https://fastapi.tiangolo.com/advanced/openapi-webhooks/).
  779. """
  780. ),
  781. ] = webhooks or routing.APIRouter()
  782. self.root_path = root_path or openapi_prefix
  783. self.state: Annotated[
  784. State,
  785. Doc(
  786. """
  787. A state object for the application. This is the same object for the
  788. entire application, it doesn't change from request to request.
  789. You normally wouldn't use this in FastAPI, for most of the cases you
  790. would instead use FastAPI dependencies.
  791. This is simply inherited from Starlette.
  792. Read more about it in the
  793. [Starlette docs for Applications](https://starlette.dev/applications/#storing-state-on-the-app-instance).
  794. """
  795. ),
  796. ] = State()
  797. self.dependency_overrides: Annotated[
  798. dict[Callable[..., Any], Callable[..., Any]],
  799. Doc(
  800. """
  801. A dictionary with overrides for the dependencies.
  802. Each key is the original dependency callable, and the value is the
  803. actual dependency that should be called.
  804. This is for testing, to replace expensive dependencies with testing
  805. versions.
  806. Read more about it in the
  807. [FastAPI docs for Testing Dependencies with Overrides](https://fastapi.tiangolo.com/advanced/testing-dependencies/).
  808. """
  809. ),
  810. ] = {}
  811. self.router: routing.APIRouter = routing.APIRouter(
  812. routes=routes,
  813. redirect_slashes=redirect_slashes,
  814. dependency_overrides_provider=self,
  815. on_startup=on_startup,
  816. on_shutdown=on_shutdown,
  817. lifespan=lifespan,
  818. default_response_class=default_response_class,
  819. dependencies=dependencies,
  820. callbacks=callbacks,
  821. deprecated=deprecated,
  822. include_in_schema=include_in_schema,
  823. responses=responses,
  824. generate_unique_id_function=generate_unique_id_function,
  825. strict_content_type=strict_content_type,
  826. )
  827. self.exception_handlers: dict[
  828. Any, Callable[[Request, Any], Response | Awaitable[Response]]
  829. ] = {} if exception_handlers is None else dict(exception_handlers)
  830. self.exception_handlers.setdefault(HTTPException, http_exception_handler)
  831. self.exception_handlers.setdefault(
  832. RequestValidationError, request_validation_exception_handler
  833. )
  834. # Starlette still has incorrect type specification for the handlers
  835. self.exception_handlers.setdefault(
  836. WebSocketRequestValidationError,
  837. websocket_request_validation_exception_handler, # type: ignore[arg-type]
  838. ) # ty: ignore[no-matching-overload]
  839. self.user_middleware: list[Middleware] = (
  840. [] if middleware is None else list(middleware)
  841. )
  842. self.middleware_stack: ASGIApp | None = None
  843. self.setup()
  844. def build_middleware_stack(self) -> ASGIApp:
  845. # Duplicate/override from Starlette to add AsyncExitStackMiddleware
  846. # inside of ExceptionMiddleware, inside of custom user middlewares
  847. debug = self.debug
  848. error_handler = None
  849. exception_handlers: dict[Any, ExceptionHandler] = {}
  850. for key, value in self.exception_handlers.items():
  851. if key in (500, Exception):
  852. error_handler = value
  853. else:
  854. exception_handlers[key] = value
  855. middleware = (
  856. [Middleware(ServerErrorMiddleware, handler=error_handler, debug=debug)]
  857. + self.user_middleware
  858. + [
  859. Middleware(
  860. ExceptionMiddleware,
  861. handlers=exception_handlers,
  862. debug=debug,
  863. ),
  864. # Add FastAPI-specific AsyncExitStackMiddleware for closing files.
  865. # Before this was also used for closing dependencies with yield but
  866. # those now have their own AsyncExitStack, to properly support
  867. # streaming responses while keeping compatibility with the previous
  868. # versions (as of writing 0.117.1) that allowed doing
  869. # except HTTPException inside a dependency with yield.
  870. # This needs to happen after user middlewares because those create a
  871. # new contextvars context copy by using a new AnyIO task group.
  872. # This AsyncExitStack preserves the context for contextvars, not
  873. # strictly necessary for closing files but it was one of the original
  874. # intentions.
  875. # If the AsyncExitStack lived outside of the custom middlewares and
  876. # contextvars were set, for example in a dependency with 'yield'
  877. # in that internal contextvars context, the values would not be
  878. # available in the outer context of the AsyncExitStack.
  879. # By placing the middleware and the AsyncExitStack here, inside all
  880. # user middlewares, the same context is used.
  881. # This is currently not needed, only for closing files, but used to be
  882. # important when dependencies with yield were closed here.
  883. Middleware(AsyncExitStackMiddleware),
  884. ]
  885. )
  886. app = self.router
  887. for cls, args, kwargs in reversed(middleware):
  888. app = cls(app, *args, **kwargs)
  889. return app
  890. def openapi(self) -> dict[str, Any]:
  891. """
  892. Generate the OpenAPI schema of the application. This is called by FastAPI
  893. internally.
  894. The first time it is called it stores the result in the attribute
  895. `app.openapi_schema`, and next times it is called, it just returns that same
  896. result. To avoid the cost of generating the schema every time.
  897. If you need to modify the generated OpenAPI schema, you could modify it.
  898. Read more in the
  899. [FastAPI docs for OpenAPI](https://fastapi.tiangolo.com/how-to/extending-openapi/).
  900. """
  901. routes_version = self.router._get_routes_version()
  902. if not self.openapi_schema or self._openapi_routes_version != routes_version:
  903. self.openapi_schema = get_openapi(
  904. title=self.title,
  905. version=self.version,
  906. openapi_version=self.openapi_version,
  907. summary=self.summary,
  908. description=self.description,
  909. terms_of_service=self.terms_of_service,
  910. contact=self.contact,
  911. license_info=self.license_info,
  912. routes=self.routes,
  913. webhooks=self.webhooks.routes,
  914. tags=self.openapi_tags,
  915. servers=self.servers,
  916. separate_input_output_schemas=self.separate_input_output_schemas,
  917. external_docs=self.openapi_external_docs,
  918. )
  919. self._openapi_routes_version = routes_version
  920. return self.openapi_schema
  921. def setup(self) -> None:
  922. if self.openapi_url:
  923. async def openapi(req: Request) -> JSONResponse:
  924. root_path = req.scope.get("root_path", "").rstrip("/")
  925. schema = self.openapi()
  926. if root_path and self.root_path_in_servers:
  927. server_urls = {s.get("url") for s in schema.get("servers", [])}
  928. if root_path not in server_urls:
  929. schema = dict(schema)
  930. schema["servers"] = [{"url": root_path}] + schema.get(
  931. "servers", []
  932. )
  933. return JSONResponse(schema)
  934. self.add_route(self.openapi_url, openapi, include_in_schema=False)
  935. if self.openapi_url and self.docs_url:
  936. async def swagger_ui_html(req: Request) -> HTMLResponse:
  937. root_path = req.scope.get("root_path", "").rstrip("/")
  938. openapi_url = root_path + self.openapi_url
  939. oauth2_redirect_url = self.swagger_ui_oauth2_redirect_url
  940. if oauth2_redirect_url:
  941. oauth2_redirect_url = root_path + oauth2_redirect_url
  942. return get_swagger_ui_html(
  943. openapi_url=openapi_url,
  944. title=f"{self.title} - Swagger UI",
  945. oauth2_redirect_url=oauth2_redirect_url,
  946. init_oauth=self.swagger_ui_init_oauth,
  947. swagger_ui_parameters=self.swagger_ui_parameters,
  948. )
  949. self.add_route(self.docs_url, swagger_ui_html, include_in_schema=False)
  950. if self.swagger_ui_oauth2_redirect_url:
  951. async def swagger_ui_redirect(req: Request) -> HTMLResponse:
  952. return get_swagger_ui_oauth2_redirect_html()
  953. self.add_route(
  954. self.swagger_ui_oauth2_redirect_url,
  955. swagger_ui_redirect,
  956. include_in_schema=False,
  957. )
  958. if self.openapi_url and self.redoc_url:
  959. async def redoc_html(req: Request) -> HTMLResponse:
  960. root_path = req.scope.get("root_path", "").rstrip("/")
  961. openapi_url = root_path + self.openapi_url
  962. return get_redoc_html(
  963. openapi_url=openapi_url, title=f"{self.title} - ReDoc"
  964. )
  965. self.add_route(self.redoc_url, redoc_html, include_in_schema=False)
  966. async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None:
  967. if self.root_path:
  968. scope["root_path"] = self.root_path
  969. await super().__call__(scope, receive, send)
  970. def add_api_route(
  971. self,
  972. path: str,
  973. endpoint: Callable[..., Any],
  974. *,
  975. response_model: Any = Default(None),
  976. status_code: int | None = None,
  977. tags: list[str | Enum] | None = None,
  978. dependencies: Sequence[Depends] | None = None,
  979. summary: str | None = None,
  980. description: str | None = None,
  981. response_description: str = "Successful Response",
  982. responses: dict[int | str, dict[str, Any]] | None = None,
  983. deprecated: bool | None = None,
  984. methods: list[str] | None = None,
  985. operation_id: str | None = None,
  986. response_model_include: IncEx | None = None,
  987. response_model_exclude: IncEx | None = None,
  988. response_model_by_alias: bool = True,
  989. response_model_exclude_unset: bool = False,
  990. response_model_exclude_defaults: bool = False,
  991. response_model_exclude_none: bool = False,
  992. include_in_schema: bool = True,
  993. response_class: type[Response] | DefaultPlaceholder = Default(JSONResponse),
  994. name: str | None = None,
  995. openapi_extra: dict[str, Any] | None = None,
  996. generate_unique_id_function: Callable[[routing.APIRoute], str] = Default(
  997. generate_unique_id
  998. ),
  999. ) -> None:
  1000. self.router.add_api_route(
  1001. path,
  1002. endpoint=endpoint,
  1003. response_model=response_model,
  1004. status_code=status_code,
  1005. tags=tags,
  1006. dependencies=dependencies,
  1007. summary=summary,
  1008. description=description,
  1009. response_description=response_description,
  1010. responses=responses,
  1011. deprecated=deprecated,
  1012. methods=methods,
  1013. operation_id=operation_id,
  1014. response_model_include=response_model_include,
  1015. response_model_exclude=response_model_exclude,
  1016. response_model_by_alias=response_model_by_alias,
  1017. response_model_exclude_unset=response_model_exclude_unset,
  1018. response_model_exclude_defaults=response_model_exclude_defaults,
  1019. response_model_exclude_none=response_model_exclude_none,
  1020. include_in_schema=include_in_schema,
  1021. response_class=response_class,
  1022. name=name,
  1023. openapi_extra=openapi_extra,
  1024. generate_unique_id_function=generate_unique_id_function,
  1025. )
  1026. def frontend(
  1027. self,
  1028. path: Annotated[
  1029. str,
  1030. Doc(
  1031. """
  1032. The URL path prefix where the frontend build should be served.
  1033. """
  1034. ),
  1035. ],
  1036. *,
  1037. directory: Annotated[
  1038. str | os.PathLike[str],
  1039. Doc(
  1040. """
  1041. The directory containing the static frontend build output.
  1042. """
  1043. ),
  1044. ],
  1045. fallback: Annotated[
  1046. Literal["auto", "index.html", "404.html"] | None,
  1047. Doc(
  1048. """
  1049. The fallback file behavior for missing frontend paths.
  1050. """
  1051. ),
  1052. ] = "auto",
  1053. check_dir: Annotated[
  1054. bool | Literal["auto"],
  1055. Doc(
  1056. """
  1057. Check that the frontend directory exists when the app is created. When
  1058. set to `"auto"`, skip the check with a warning when `FASTAPI_ENV` is
  1059. `"development"`, and check it otherwise. The `fastapi dev` command
  1060. sets `FASTAPI_ENV` to `"development"` if it is not already set.
  1061. """
  1062. ),
  1063. ] = "auto",
  1064. ) -> None:
  1065. """
  1066. Serve a static frontend build as low-priority routes.
  1067. Use this for frontend tools that build static files into a directory,
  1068. such as `dist`. **FastAPI** path operations are checked first, and
  1069. the frontend files are checked only if no normal route matched.
  1070. A typical project could look like this:
  1071. ```text
  1072. .
  1073. ├── pyproject.toml
  1074. ├── app
  1075. │ ├── __init__.py
  1076. │ └── main.py
  1077. └── dist
  1078. ├── index.html
  1079. └── assets
  1080. └── app.js
  1081. ```
  1082. Then in `app/main.py`:
  1083. ```python
  1084. from fastapi import FastAPI
  1085. app = FastAPI()
  1086. app.frontend("/", directory="dist")
  1087. ```
  1088. """
  1089. check_dir = routing._resolve_frontend_check_dir(
  1090. directory=directory, check_dir=check_dir
  1091. )
  1092. self.router.frontend(
  1093. path,
  1094. directory=directory,
  1095. fallback=fallback,
  1096. check_dir=check_dir,
  1097. )
  1098. def api_route(
  1099. self,
  1100. path: str,
  1101. *,
  1102. response_model: Any = Default(None),
  1103. status_code: int | None = None,
  1104. tags: list[str | Enum] | None = None,
  1105. dependencies: Sequence[Depends] | None = None,
  1106. summary: str | None = None,
  1107. description: str | None = None,
  1108. response_description: str = "Successful Response",
  1109. responses: dict[int | str, dict[str, Any]] | None = None,
  1110. deprecated: bool | None = None,
  1111. methods: list[str] | None = None,
  1112. operation_id: str | None = None,
  1113. response_model_include: IncEx | None = None,
  1114. response_model_exclude: IncEx | None = None,
  1115. response_model_by_alias: bool = True,
  1116. response_model_exclude_unset: bool = False,
  1117. response_model_exclude_defaults: bool = False,
  1118. response_model_exclude_none: bool = False,
  1119. include_in_schema: bool = True,
  1120. response_class: type[Response] = Default(JSONResponse),
  1121. name: str | None = None,
  1122. openapi_extra: dict[str, Any] | None = None,
  1123. generate_unique_id_function: Callable[[routing.APIRoute], str] = Default(
  1124. generate_unique_id
  1125. ),
  1126. ) -> Callable[[DecoratedCallable], DecoratedCallable]:
  1127. def decorator(func: DecoratedCallable) -> DecoratedCallable:
  1128. self.router.add_api_route(
  1129. path,
  1130. func,
  1131. response_model=response_model,
  1132. status_code=status_code,
  1133. tags=tags,
  1134. dependencies=dependencies,
  1135. summary=summary,
  1136. description=description,
  1137. response_description=response_description,
  1138. responses=responses,
  1139. deprecated=deprecated,
  1140. methods=methods,
  1141. operation_id=operation_id,
  1142. response_model_include=response_model_include,
  1143. response_model_exclude=response_model_exclude,
  1144. response_model_by_alias=response_model_by_alias,
  1145. response_model_exclude_unset=response_model_exclude_unset,
  1146. response_model_exclude_defaults=response_model_exclude_defaults,
  1147. response_model_exclude_none=response_model_exclude_none,
  1148. include_in_schema=include_in_schema,
  1149. response_class=response_class,
  1150. name=name,
  1151. openapi_extra=openapi_extra,
  1152. generate_unique_id_function=generate_unique_id_function,
  1153. )
  1154. return func
  1155. return decorator
  1156. def add_api_websocket_route(
  1157. self,
  1158. path: str,
  1159. endpoint: Callable[..., Any],
  1160. name: str | None = None,
  1161. *,
  1162. dependencies: Sequence[Depends] | None = None,
  1163. ) -> None:
  1164. self.router.add_api_websocket_route(
  1165. path,
  1166. endpoint,
  1167. name=name,
  1168. dependencies=dependencies,
  1169. )
  1170. def websocket(
  1171. self,
  1172. path: Annotated[
  1173. str,
  1174. Doc(
  1175. """
  1176. WebSocket path.
  1177. """
  1178. ),
  1179. ],
  1180. name: Annotated[
  1181. str | None,
  1182. Doc(
  1183. """
  1184. A name for the WebSocket. Only used internally.
  1185. """
  1186. ),
  1187. ] = None,
  1188. *,
  1189. dependencies: Annotated[
  1190. Sequence[Depends] | None,
  1191. Doc(
  1192. """
  1193. A list of dependencies (using `Depends()`) to be used for this
  1194. WebSocket.
  1195. Read more about it in the
  1196. [FastAPI docs for WebSockets](https://fastapi.tiangolo.com/advanced/websockets/).
  1197. """
  1198. ),
  1199. ] = None,
  1200. ) -> Callable[[DecoratedCallable], DecoratedCallable]:
  1201. """
  1202. Decorate a WebSocket function.
  1203. Read more about it in the
  1204. [FastAPI docs for WebSockets](https://fastapi.tiangolo.com/advanced/websockets/).
  1205. **Example**
  1206. ```python
  1207. from fastapi import FastAPI, WebSocket
  1208. app = FastAPI()
  1209. @app.websocket("/ws")
  1210. async def websocket_endpoint(websocket: WebSocket):
  1211. await websocket.accept()
  1212. while True:
  1213. data = await websocket.receive_text()
  1214. await websocket.send_text(f"Message text was: {data}")
  1215. ```
  1216. """
  1217. def decorator(func: DecoratedCallable) -> DecoratedCallable:
  1218. self.add_api_websocket_route(
  1219. path,
  1220. func,
  1221. name=name,
  1222. dependencies=dependencies,
  1223. )
  1224. return func
  1225. return decorator
  1226. def include_router(
  1227. self,
  1228. router: Annotated[routing.APIRouter, Doc("The `APIRouter` to include.")],
  1229. *,
  1230. prefix: Annotated[str, Doc("An optional path prefix for the router.")] = "",
  1231. tags: Annotated[
  1232. list[str | Enum] | None,
  1233. Doc(
  1234. """
  1235. A list of tags to be applied to all the *path operations* in this
  1236. router.
  1237. It will be added to the generated OpenAPI (e.g. visible at `/docs`).
  1238. Read more about it in the
  1239. [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).
  1240. """
  1241. ),
  1242. ] = None,
  1243. dependencies: Annotated[
  1244. Sequence[Depends] | None,
  1245. Doc(
  1246. """
  1247. A list of dependencies (using `Depends()`) to be applied to all the
  1248. *path operations* in this router.
  1249. Read more about it in the
  1250. [FastAPI docs for Bigger Applications - Multiple Files](https://fastapi.tiangolo.com/tutorial/bigger-applications/#include-an-apirouter-with-a-custom-prefix-tags-responses-and-dependencies).
  1251. **Example**
  1252. ```python
  1253. from fastapi import Depends, FastAPI
  1254. from .dependencies import get_token_header
  1255. from .internal import admin
  1256. app = FastAPI()
  1257. app.include_router(
  1258. admin.router,
  1259. dependencies=[Depends(get_token_header)],
  1260. )
  1261. ```
  1262. """
  1263. ),
  1264. ] = None,
  1265. responses: Annotated[
  1266. dict[int | str, dict[str, Any]] | None,
  1267. Doc(
  1268. """
  1269. Additional responses to be shown in OpenAPI.
  1270. It will be added to the generated OpenAPI (e.g. visible at `/docs`).
  1271. Read more about it in the
  1272. [FastAPI docs for Additional Responses in OpenAPI](https://fastapi.tiangolo.com/advanced/additional-responses/).
  1273. And in the
  1274. [FastAPI docs for Bigger Applications](https://fastapi.tiangolo.com/tutorial/bigger-applications/#include-an-apirouter-with-a-custom-prefix-tags-responses-and-dependencies).
  1275. """
  1276. ),
  1277. ] = None,
  1278. deprecated: Annotated[
  1279. bool | None,
  1280. Doc(
  1281. """
  1282. Mark all the *path operations* in this router as deprecated.
  1283. It will be added to the generated OpenAPI (e.g. visible at `/docs`).
  1284. **Example**
  1285. ```python
  1286. from fastapi import FastAPI
  1287. from .internal import old_api
  1288. app = FastAPI()
  1289. app.include_router(
  1290. old_api.router,
  1291. deprecated=True,
  1292. )
  1293. ```
  1294. """
  1295. ),
  1296. ] = None,
  1297. include_in_schema: Annotated[
  1298. bool,
  1299. Doc(
  1300. """
  1301. Include (or not) all the *path operations* in this router in the
  1302. generated OpenAPI schema.
  1303. This affects the generated OpenAPI (e.g. visible at `/docs`).
  1304. **Example**
  1305. ```python
  1306. from fastapi import FastAPI
  1307. from .internal import old_api
  1308. app = FastAPI()
  1309. app.include_router(
  1310. old_api.router,
  1311. include_in_schema=False,
  1312. )
  1313. ```
  1314. """
  1315. ),
  1316. ] = True,
  1317. default_response_class: Annotated[
  1318. type[Response],
  1319. Doc(
  1320. """
  1321. Default response class to be used for the *path operations* in this
  1322. router.
  1323. Read more in the
  1324. [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#default-response-class).
  1325. **Example**
  1326. ```python
  1327. from fastapi import FastAPI
  1328. from fastapi.responses import ORJSONResponse
  1329. from .internal import old_api
  1330. app = FastAPI()
  1331. app.include_router(
  1332. old_api.router,
  1333. default_response_class=ORJSONResponse,
  1334. )
  1335. ```
  1336. """
  1337. ),
  1338. ] = Default(JSONResponse),
  1339. callbacks: Annotated[
  1340. list[BaseRoute] | None,
  1341. Doc(
  1342. """
  1343. List of *path operations* that will be used as OpenAPI callbacks.
  1344. This is only for OpenAPI documentation, the callbacks won't be used
  1345. directly.
  1346. It will be added to the generated OpenAPI (e.g. visible at `/docs`).
  1347. Read more about it in the
  1348. [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/).
  1349. """
  1350. ),
  1351. ] = None,
  1352. generate_unique_id_function: Annotated[
  1353. Callable[[routing.APIRoute], str],
  1354. Doc(
  1355. """
  1356. Customize the function used to generate unique IDs for the *path
  1357. operations* shown in the generated OpenAPI.
  1358. This is particularly useful when automatically generating clients or
  1359. SDKs for your API.
  1360. Read more about it in the
  1361. [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).
  1362. """
  1363. ),
  1364. ] = Default(generate_unique_id),
  1365. ) -> None:
  1366. """
  1367. Include an `APIRouter` in the same app.
  1368. Read more about it in the
  1369. [FastAPI docs for Bigger Applications](https://fastapi.tiangolo.com/tutorial/bigger-applications/).
  1370. ## Example
  1371. ```python
  1372. from fastapi import FastAPI
  1373. from .users import users_router
  1374. app = FastAPI()
  1375. app.include_router(users_router)
  1376. ```
  1377. """
  1378. self.router.include_router(
  1379. router,
  1380. prefix=prefix,
  1381. tags=tags,
  1382. dependencies=dependencies,
  1383. responses=responses,
  1384. deprecated=deprecated,
  1385. include_in_schema=include_in_schema,
  1386. default_response_class=default_response_class,
  1387. callbacks=callbacks,
  1388. generate_unique_id_function=generate_unique_id_function,
  1389. )
  1390. def get(
  1391. self,
  1392. path: Annotated[
  1393. str,
  1394. Doc(
  1395. """
  1396. The URL path to be used for this *path operation*.
  1397. For example, in `http://example.com/items`, the path is `/items`.
  1398. """
  1399. ),
  1400. ],
  1401. *,
  1402. response_model: Annotated[
  1403. Any,
  1404. Doc(
  1405. """
  1406. The type to use for the response.
  1407. It could be any valid Pydantic *field* type. So, it doesn't have to
  1408. be a Pydantic model, it could be other things, like a `list`, `dict`,
  1409. etc.
  1410. It will be used for:
  1411. * Documentation: the generated OpenAPI (and the UI at `/docs`) will
  1412. show it as the response (JSON Schema).
  1413. * Serialization: you could return an arbitrary object and the
  1414. `response_model` would be used to serialize that object into the
  1415. corresponding JSON.
  1416. * Filtering: the JSON sent to the client will only contain the data
  1417. (fields) defined in the `response_model`. If you returned an object
  1418. that contains an attribute `password` but the `response_model` does
  1419. not include that field, the JSON sent to the client would not have
  1420. that `password`.
  1421. * Validation: whatever you return will be serialized with the
  1422. `response_model`, converting any data as necessary to generate the
  1423. corresponding JSON. But if the data in the object returned is not
  1424. valid, that would mean a violation of the contract with the client,
  1425. so it's an error from the API developer. So, FastAPI will raise an
  1426. error and return a 500 error code (Internal Server Error).
  1427. Read more about it in the
  1428. [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/).
  1429. """
  1430. ),
  1431. ] = Default(None),
  1432. status_code: Annotated[
  1433. int | None,
  1434. Doc(
  1435. """
  1436. The default status code to be used for the response.
  1437. You could override the status code by returning a response directly.
  1438. Read more about it in the
  1439. [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/).
  1440. """
  1441. ),
  1442. ] = None,
  1443. tags: Annotated[
  1444. list[str | Enum] | None,
  1445. Doc(
  1446. """
  1447. A list of tags to be applied to the *path operation*.
  1448. It will be added to the generated OpenAPI (e.g. visible at `/docs`).
  1449. Read more about it in the
  1450. [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#tags).
  1451. """
  1452. ),
  1453. ] = None,
  1454. dependencies: Annotated[
  1455. Sequence[Depends] | None,
  1456. Doc(
  1457. """
  1458. A list of dependencies (using `Depends()`) to be applied to the
  1459. *path operation*.
  1460. Read more about it in the
  1461. [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/).
  1462. """
  1463. ),
  1464. ] = None,
  1465. summary: Annotated[
  1466. str | None,
  1467. Doc(
  1468. """
  1469. A summary for the *path operation*.
  1470. It will be added to the generated OpenAPI (e.g. visible at `/docs`).
  1471. Read more about it in the
  1472. [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).
  1473. """
  1474. ),
  1475. ] = None,
  1476. description: Annotated[
  1477. str | None,
  1478. Doc(
  1479. """
  1480. A description for the *path operation*.
  1481. If not provided, it will be extracted automatically from the docstring
  1482. of the *path operation function*.
  1483. It can contain Markdown.
  1484. It will be added to the generated OpenAPI (e.g. visible at `/docs`).
  1485. Read more about it in the
  1486. [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).
  1487. """
  1488. ),
  1489. ] = None,
  1490. response_description: Annotated[
  1491. str,
  1492. Doc(
  1493. """
  1494. The description for the default response.
  1495. It will be added to the generated OpenAPI (e.g. visible at `/docs`).
  1496. """
  1497. ),
  1498. ] = "Successful Response",
  1499. responses: Annotated[
  1500. dict[int | str, dict[str, Any]] | None,
  1501. Doc(
  1502. """
  1503. Additional responses that could be returned by this *path operation*.
  1504. It will be added to the generated OpenAPI (e.g. visible at `/docs`).
  1505. """
  1506. ),
  1507. ] = None,
  1508. deprecated: Annotated[
  1509. bool | None,
  1510. Doc(
  1511. """
  1512. Mark this *path operation* as deprecated.
  1513. It will be added to the generated OpenAPI (e.g. visible at `/docs`).
  1514. """
  1515. ),
  1516. ] = None,
  1517. operation_id: Annotated[
  1518. str | None,
  1519. Doc(
  1520. """
  1521. Custom operation ID to be used by this *path operation*.
  1522. By default, it is generated automatically.
  1523. If you provide a custom operation ID, you need to make sure it is
  1524. unique for the whole API.
  1525. You can customize the
  1526. operation ID generation with the parameter
  1527. `generate_unique_id_function` in the `FastAPI` class.
  1528. Read more about it in the
  1529. [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).
  1530. """
  1531. ),
  1532. ] = None,
  1533. response_model_include: Annotated[
  1534. IncEx | None,
  1535. Doc(
  1536. """
  1537. Configuration passed to Pydantic to include only certain fields in the
  1538. response data.
  1539. Read more about it in the
  1540. [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).
  1541. """
  1542. ),
  1543. ] = None,
  1544. response_model_exclude: Annotated[
  1545. IncEx | None,
  1546. Doc(
  1547. """
  1548. Configuration passed to Pydantic to exclude certain fields in the
  1549. response data.
  1550. Read more about it in the
  1551. [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).
  1552. """
  1553. ),
  1554. ] = None,
  1555. response_model_by_alias: Annotated[
  1556. bool,
  1557. Doc(
  1558. """
  1559. Configuration passed to Pydantic to define if the response model
  1560. should be serialized by alias when an alias is used.
  1561. Read more about it in the
  1562. [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).
  1563. """
  1564. ),
  1565. ] = True,
  1566. response_model_exclude_unset: Annotated[
  1567. bool,
  1568. Doc(
  1569. """
  1570. Configuration passed to Pydantic to define if the response data
  1571. should have all the fields, including the ones that were not set and
  1572. have their default values. This is different from
  1573. `response_model_exclude_defaults` in that if the fields are set,
  1574. they will be included in the response, even if the value is the same
  1575. as the default.
  1576. When `True`, default values are omitted from the response.
  1577. Read more about it in the
  1578. [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).
  1579. """
  1580. ),
  1581. ] = False,
  1582. response_model_exclude_defaults: Annotated[
  1583. bool,
  1584. Doc(
  1585. """
  1586. Configuration passed to Pydantic to define if the response data
  1587. should have all the fields, including the ones that have the same value
  1588. as the default. This is different from `response_model_exclude_unset`
  1589. in that if the fields are set but contain the same default values,
  1590. they will be excluded from the response.
  1591. When `True`, default values are omitted from the response.
  1592. Read more about it in the
  1593. [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).
  1594. """
  1595. ),
  1596. ] = False,
  1597. response_model_exclude_none: Annotated[
  1598. bool,
  1599. Doc(
  1600. """
  1601. Configuration passed to Pydantic to define if the response data should
  1602. exclude fields set to `None`.
  1603. This is much simpler (less smart) than `response_model_exclude_unset`
  1604. and `response_model_exclude_defaults`. You probably want to use one of
  1605. those two instead of this one, as those allow returning `None` values
  1606. when it makes sense.
  1607. Read more about it in the
  1608. [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none).
  1609. """
  1610. ),
  1611. ] = False,
  1612. include_in_schema: Annotated[
  1613. bool,
  1614. Doc(
  1615. """
  1616. Include this *path operation* in the generated OpenAPI schema.
  1617. This affects the generated OpenAPI (e.g. visible at `/docs`).
  1618. Read more about it in the
  1619. [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-parameters-from-openapi).
  1620. """
  1621. ),
  1622. ] = True,
  1623. response_class: Annotated[
  1624. type[Response],
  1625. Doc(
  1626. """
  1627. Response class to be used for this *path operation*.
  1628. This will not be used if you return a response directly.
  1629. Read more about it in the
  1630. [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse).
  1631. """
  1632. ),
  1633. ] = Default(JSONResponse),
  1634. name: Annotated[
  1635. str | None,
  1636. Doc(
  1637. """
  1638. Name for this *path operation*. Only used internally.
  1639. """
  1640. ),
  1641. ] = None,
  1642. callbacks: Annotated[
  1643. list[BaseRoute] | None,
  1644. Doc(
  1645. """
  1646. List of *path operations* that will be used as OpenAPI callbacks.
  1647. This is only for OpenAPI documentation, the callbacks won't be used
  1648. directly.
  1649. It will be added to the generated OpenAPI (e.g. visible at `/docs`).
  1650. Read more about it in the
  1651. [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/).
  1652. """
  1653. ),
  1654. ] = None,
  1655. openapi_extra: Annotated[
  1656. dict[str, Any] | None,
  1657. Doc(
  1658. """
  1659. Extra metadata to be included in the OpenAPI schema for this *path
  1660. operation*.
  1661. Read more about it in the
  1662. [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema).
  1663. """
  1664. ),
  1665. ] = None,
  1666. generate_unique_id_function: Annotated[
  1667. Callable[[routing.APIRoute], str],
  1668. Doc(
  1669. """
  1670. Customize the function used to generate unique IDs for the *path
  1671. operations* shown in the generated OpenAPI.
  1672. This is particularly useful when automatically generating clients or
  1673. SDKs for your API.
  1674. Read more about it in the
  1675. [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).
  1676. """
  1677. ),
  1678. ] = Default(generate_unique_id),
  1679. ) -> Callable[[DecoratedCallable], DecoratedCallable]:
  1680. """
  1681. Add a *path operation* using an HTTP GET operation.
  1682. ## Example
  1683. ```python
  1684. from fastapi import FastAPI
  1685. app = FastAPI()
  1686. @app.get("/items/")
  1687. def read_items():
  1688. return [{"name": "Empanada"}, {"name": "Arepa"}]
  1689. ```
  1690. """
  1691. return self.router.get(
  1692. path,
  1693. response_model=response_model,
  1694. status_code=status_code,
  1695. tags=tags,
  1696. dependencies=dependencies,
  1697. summary=summary,
  1698. description=description,
  1699. response_description=response_description,
  1700. responses=responses,
  1701. deprecated=deprecated,
  1702. operation_id=operation_id,
  1703. response_model_include=response_model_include,
  1704. response_model_exclude=response_model_exclude,
  1705. response_model_by_alias=response_model_by_alias,
  1706. response_model_exclude_unset=response_model_exclude_unset,
  1707. response_model_exclude_defaults=response_model_exclude_defaults,
  1708. response_model_exclude_none=response_model_exclude_none,
  1709. include_in_schema=include_in_schema,
  1710. response_class=response_class,
  1711. name=name,
  1712. callbacks=callbacks,
  1713. openapi_extra=openapi_extra,
  1714. generate_unique_id_function=generate_unique_id_function,
  1715. )
  1716. def put(
  1717. self,
  1718. path: Annotated[
  1719. str,
  1720. Doc(
  1721. """
  1722. The URL path to be used for this *path operation*.
  1723. For example, in `http://example.com/items`, the path is `/items`.
  1724. """
  1725. ),
  1726. ],
  1727. *,
  1728. response_model: Annotated[
  1729. Any,
  1730. Doc(
  1731. """
  1732. The type to use for the response.
  1733. It could be any valid Pydantic *field* type. So, it doesn't have to
  1734. be a Pydantic model, it could be other things, like a `list`, `dict`,
  1735. etc.
  1736. It will be used for:
  1737. * Documentation: the generated OpenAPI (and the UI at `/docs`) will
  1738. show it as the response (JSON Schema).
  1739. * Serialization: you could return an arbitrary object and the
  1740. `response_model` would be used to serialize that object into the
  1741. corresponding JSON.
  1742. * Filtering: the JSON sent to the client will only contain the data
  1743. (fields) defined in the `response_model`. If you returned an object
  1744. that contains an attribute `password` but the `response_model` does
  1745. not include that field, the JSON sent to the client would not have
  1746. that `password`.
  1747. * Validation: whatever you return will be serialized with the
  1748. `response_model`, converting any data as necessary to generate the
  1749. corresponding JSON. But if the data in the object returned is not
  1750. valid, that would mean a violation of the contract with the client,
  1751. so it's an error from the API developer. So, FastAPI will raise an
  1752. error and return a 500 error code (Internal Server Error).
  1753. Read more about it in the
  1754. [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/).
  1755. """
  1756. ),
  1757. ] = Default(None),
  1758. status_code: Annotated[
  1759. int | None,
  1760. Doc(
  1761. """
  1762. The default status code to be used for the response.
  1763. You could override the status code by returning a response directly.
  1764. Read more about it in the
  1765. [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/).
  1766. """
  1767. ),
  1768. ] = None,
  1769. tags: Annotated[
  1770. list[str | Enum] | None,
  1771. Doc(
  1772. """
  1773. A list of tags to be applied to the *path operation*.
  1774. It will be added to the generated OpenAPI (e.g. visible at `/docs`).
  1775. Read more about it in the
  1776. [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#tags).
  1777. """
  1778. ),
  1779. ] = None,
  1780. dependencies: Annotated[
  1781. Sequence[Depends] | None,
  1782. Doc(
  1783. """
  1784. A list of dependencies (using `Depends()`) to be applied to the
  1785. *path operation*.
  1786. Read more about it in the
  1787. [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/).
  1788. """
  1789. ),
  1790. ] = None,
  1791. summary: Annotated[
  1792. str | None,
  1793. Doc(
  1794. """
  1795. A summary for the *path operation*.
  1796. It will be added to the generated OpenAPI (e.g. visible at `/docs`).
  1797. Read more about it in the
  1798. [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).
  1799. """
  1800. ),
  1801. ] = None,
  1802. description: Annotated[
  1803. str | None,
  1804. Doc(
  1805. """
  1806. A description for the *path operation*.
  1807. If not provided, it will be extracted automatically from the docstring
  1808. of the *path operation function*.
  1809. It can contain Markdown.
  1810. It will be added to the generated OpenAPI (e.g. visible at `/docs`).
  1811. Read more about it in the
  1812. [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).
  1813. """
  1814. ),
  1815. ] = None,
  1816. response_description: Annotated[
  1817. str,
  1818. Doc(
  1819. """
  1820. The description for the default response.
  1821. It will be added to the generated OpenAPI (e.g. visible at `/docs`).
  1822. """
  1823. ),
  1824. ] = "Successful Response",
  1825. responses: Annotated[
  1826. dict[int | str, dict[str, Any]] | None,
  1827. Doc(
  1828. """
  1829. Additional responses that could be returned by this *path operation*.
  1830. It will be added to the generated OpenAPI (e.g. visible at `/docs`).
  1831. """
  1832. ),
  1833. ] = None,
  1834. deprecated: Annotated[
  1835. bool | None,
  1836. Doc(
  1837. """
  1838. Mark this *path operation* as deprecated.
  1839. It will be added to the generated OpenAPI (e.g. visible at `/docs`).
  1840. """
  1841. ),
  1842. ] = None,
  1843. operation_id: Annotated[
  1844. str | None,
  1845. Doc(
  1846. """
  1847. Custom operation ID to be used by this *path operation*.
  1848. By default, it is generated automatically.
  1849. If you provide a custom operation ID, you need to make sure it is
  1850. unique for the whole API.
  1851. You can customize the
  1852. operation ID generation with the parameter
  1853. `generate_unique_id_function` in the `FastAPI` class.
  1854. Read more about it in the
  1855. [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).
  1856. """
  1857. ),
  1858. ] = None,
  1859. response_model_include: Annotated[
  1860. IncEx | None,
  1861. Doc(
  1862. """
  1863. Configuration passed to Pydantic to include only certain fields in the
  1864. response data.
  1865. Read more about it in the
  1866. [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).
  1867. """
  1868. ),
  1869. ] = None,
  1870. response_model_exclude: Annotated[
  1871. IncEx | None,
  1872. Doc(
  1873. """
  1874. Configuration passed to Pydantic to exclude certain fields in the
  1875. response data.
  1876. Read more about it in the
  1877. [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).
  1878. """
  1879. ),
  1880. ] = None,
  1881. response_model_by_alias: Annotated[
  1882. bool,
  1883. Doc(
  1884. """
  1885. Configuration passed to Pydantic to define if the response model
  1886. should be serialized by alias when an alias is used.
  1887. Read more about it in the
  1888. [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).
  1889. """
  1890. ),
  1891. ] = True,
  1892. response_model_exclude_unset: Annotated[
  1893. bool,
  1894. Doc(
  1895. """
  1896. Configuration passed to Pydantic to define if the response data
  1897. should have all the fields, including the ones that were not set and
  1898. have their default values. This is different from
  1899. `response_model_exclude_defaults` in that if the fields are set,
  1900. they will be included in the response, even if the value is the same
  1901. as the default.
  1902. When `True`, default values are omitted from the response.
  1903. Read more about it in the
  1904. [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).
  1905. """
  1906. ),
  1907. ] = False,
  1908. response_model_exclude_defaults: Annotated[
  1909. bool,
  1910. Doc(
  1911. """
  1912. Configuration passed to Pydantic to define if the response data
  1913. should have all the fields, including the ones that have the same value
  1914. as the default. This is different from `response_model_exclude_unset`
  1915. in that if the fields are set but contain the same default values,
  1916. they will be excluded from the response.
  1917. When `True`, default values are omitted from the response.
  1918. Read more about it in the
  1919. [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).
  1920. """
  1921. ),
  1922. ] = False,
  1923. response_model_exclude_none: Annotated[
  1924. bool,
  1925. Doc(
  1926. """
  1927. Configuration passed to Pydantic to define if the response data should
  1928. exclude fields set to `None`.
  1929. This is much simpler (less smart) than `response_model_exclude_unset`
  1930. and `response_model_exclude_defaults`. You probably want to use one of
  1931. those two instead of this one, as those allow returning `None` values
  1932. when it makes sense.
  1933. Read more about it in the
  1934. [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none).
  1935. """
  1936. ),
  1937. ] = False,
  1938. include_in_schema: Annotated[
  1939. bool,
  1940. Doc(
  1941. """
  1942. Include this *path operation* in the generated OpenAPI schema.
  1943. This affects the generated OpenAPI (e.g. visible at `/docs`).
  1944. Read more about it in the
  1945. [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-parameters-from-openapi).
  1946. """
  1947. ),
  1948. ] = True,
  1949. response_class: Annotated[
  1950. type[Response],
  1951. Doc(
  1952. """
  1953. Response class to be used for this *path operation*.
  1954. This will not be used if you return a response directly.
  1955. Read more about it in the
  1956. [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse).
  1957. """
  1958. ),
  1959. ] = Default(JSONResponse),
  1960. name: Annotated[
  1961. str | None,
  1962. Doc(
  1963. """
  1964. Name for this *path operation*. Only used internally.
  1965. """
  1966. ),
  1967. ] = None,
  1968. callbacks: Annotated[
  1969. list[BaseRoute] | None,
  1970. Doc(
  1971. """
  1972. List of *path operations* that will be used as OpenAPI callbacks.
  1973. This is only for OpenAPI documentation, the callbacks won't be used
  1974. directly.
  1975. It will be added to the generated OpenAPI (e.g. visible at `/docs`).
  1976. Read more about it in the
  1977. [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/).
  1978. """
  1979. ),
  1980. ] = None,
  1981. openapi_extra: Annotated[
  1982. dict[str, Any] | None,
  1983. Doc(
  1984. """
  1985. Extra metadata to be included in the OpenAPI schema for this *path
  1986. operation*.
  1987. Read more about it in the
  1988. [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema).
  1989. """
  1990. ),
  1991. ] = None,
  1992. generate_unique_id_function: Annotated[
  1993. Callable[[routing.APIRoute], str],
  1994. Doc(
  1995. """
  1996. Customize the function used to generate unique IDs for the *path
  1997. operations* shown in the generated OpenAPI.
  1998. This is particularly useful when automatically generating clients or
  1999. SDKs for your API.
  2000. Read more about it in the
  2001. [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).
  2002. """
  2003. ),
  2004. ] = Default(generate_unique_id),
  2005. ) -> Callable[[DecoratedCallable], DecoratedCallable]:
  2006. """
  2007. Add a *path operation* using an HTTP PUT operation.
  2008. ## Example
  2009. ```python
  2010. from fastapi import FastAPI
  2011. from pydantic import BaseModel
  2012. class Item(BaseModel):
  2013. name: str
  2014. description: str | None = None
  2015. app = FastAPI()
  2016. @app.put("/items/{item_id}")
  2017. def replace_item(item_id: str, item: Item):
  2018. return {"message": "Item replaced", "id": item_id}
  2019. ```
  2020. """
  2021. return self.router.put(
  2022. path,
  2023. response_model=response_model,
  2024. status_code=status_code,
  2025. tags=tags,
  2026. dependencies=dependencies,
  2027. summary=summary,
  2028. description=description,
  2029. response_description=response_description,
  2030. responses=responses,
  2031. deprecated=deprecated,
  2032. operation_id=operation_id,
  2033. response_model_include=response_model_include,
  2034. response_model_exclude=response_model_exclude,
  2035. response_model_by_alias=response_model_by_alias,
  2036. response_model_exclude_unset=response_model_exclude_unset,
  2037. response_model_exclude_defaults=response_model_exclude_defaults,
  2038. response_model_exclude_none=response_model_exclude_none,
  2039. include_in_schema=include_in_schema,
  2040. response_class=response_class,
  2041. name=name,
  2042. callbacks=callbacks,
  2043. openapi_extra=openapi_extra,
  2044. generate_unique_id_function=generate_unique_id_function,
  2045. )
  2046. def post(
  2047. self,
  2048. path: Annotated[
  2049. str,
  2050. Doc(
  2051. """
  2052. The URL path to be used for this *path operation*.
  2053. For example, in `http://example.com/items`, the path is `/items`.
  2054. """
  2055. ),
  2056. ],
  2057. *,
  2058. response_model: Annotated[
  2059. Any,
  2060. Doc(
  2061. """
  2062. The type to use for the response.
  2063. It could be any valid Pydantic *field* type. So, it doesn't have to
  2064. be a Pydantic model, it could be other things, like a `list`, `dict`,
  2065. etc.
  2066. It will be used for:
  2067. * Documentation: the generated OpenAPI (and the UI at `/docs`) will
  2068. show it as the response (JSON Schema).
  2069. * Serialization: you could return an arbitrary object and the
  2070. `response_model` would be used to serialize that object into the
  2071. corresponding JSON.
  2072. * Filtering: the JSON sent to the client will only contain the data
  2073. (fields) defined in the `response_model`. If you returned an object
  2074. that contains an attribute `password` but the `response_model` does
  2075. not include that field, the JSON sent to the client would not have
  2076. that `password`.
  2077. * Validation: whatever you return will be serialized with the
  2078. `response_model`, converting any data as necessary to generate the
  2079. corresponding JSON. But if the data in the object returned is not
  2080. valid, that would mean a violation of the contract with the client,
  2081. so it's an error from the API developer. So, FastAPI will raise an
  2082. error and return a 500 error code (Internal Server Error).
  2083. Read more about it in the
  2084. [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/).
  2085. """
  2086. ),
  2087. ] = Default(None),
  2088. status_code: Annotated[
  2089. int | None,
  2090. Doc(
  2091. """
  2092. The default status code to be used for the response.
  2093. You could override the status code by returning a response directly.
  2094. Read more about it in the
  2095. [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/).
  2096. """
  2097. ),
  2098. ] = None,
  2099. tags: Annotated[
  2100. list[str | Enum] | None,
  2101. Doc(
  2102. """
  2103. A list of tags to be applied to the *path operation*.
  2104. It will be added to the generated OpenAPI (e.g. visible at `/docs`).
  2105. Read more about it in the
  2106. [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#tags).
  2107. """
  2108. ),
  2109. ] = None,
  2110. dependencies: Annotated[
  2111. Sequence[Depends] | None,
  2112. Doc(
  2113. """
  2114. A list of dependencies (using `Depends()`) to be applied to the
  2115. *path operation*.
  2116. Read more about it in the
  2117. [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/).
  2118. """
  2119. ),
  2120. ] = None,
  2121. summary: Annotated[
  2122. str | None,
  2123. Doc(
  2124. """
  2125. A summary for the *path operation*.
  2126. It will be added to the generated OpenAPI (e.g. visible at `/docs`).
  2127. Read more about it in the
  2128. [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).
  2129. """
  2130. ),
  2131. ] = None,
  2132. description: Annotated[
  2133. str | None,
  2134. Doc(
  2135. """
  2136. A description for the *path operation*.
  2137. If not provided, it will be extracted automatically from the docstring
  2138. of the *path operation function*.
  2139. It can contain Markdown.
  2140. It will be added to the generated OpenAPI (e.g. visible at `/docs`).
  2141. Read more about it in the
  2142. [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).
  2143. """
  2144. ),
  2145. ] = None,
  2146. response_description: Annotated[
  2147. str,
  2148. Doc(
  2149. """
  2150. The description for the default response.
  2151. It will be added to the generated OpenAPI (e.g. visible at `/docs`).
  2152. """
  2153. ),
  2154. ] = "Successful Response",
  2155. responses: Annotated[
  2156. dict[int | str, dict[str, Any]] | None,
  2157. Doc(
  2158. """
  2159. Additional responses that could be returned by this *path operation*.
  2160. It will be added to the generated OpenAPI (e.g. visible at `/docs`).
  2161. """
  2162. ),
  2163. ] = None,
  2164. deprecated: Annotated[
  2165. bool | None,
  2166. Doc(
  2167. """
  2168. Mark this *path operation* as deprecated.
  2169. It will be added to the generated OpenAPI (e.g. visible at `/docs`).
  2170. """
  2171. ),
  2172. ] = None,
  2173. operation_id: Annotated[
  2174. str | None,
  2175. Doc(
  2176. """
  2177. Custom operation ID to be used by this *path operation*.
  2178. By default, it is generated automatically.
  2179. If you provide a custom operation ID, you need to make sure it is
  2180. unique for the whole API.
  2181. You can customize the
  2182. operation ID generation with the parameter
  2183. `generate_unique_id_function` in the `FastAPI` class.
  2184. Read more about it in the
  2185. [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).
  2186. """
  2187. ),
  2188. ] = None,
  2189. response_model_include: Annotated[
  2190. IncEx | None,
  2191. Doc(
  2192. """
  2193. Configuration passed to Pydantic to include only certain fields in the
  2194. response data.
  2195. Read more about it in the
  2196. [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).
  2197. """
  2198. ),
  2199. ] = None,
  2200. response_model_exclude: Annotated[
  2201. IncEx | None,
  2202. Doc(
  2203. """
  2204. Configuration passed to Pydantic to exclude certain fields in the
  2205. response data.
  2206. Read more about it in the
  2207. [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).
  2208. """
  2209. ),
  2210. ] = None,
  2211. response_model_by_alias: Annotated[
  2212. bool,
  2213. Doc(
  2214. """
  2215. Configuration passed to Pydantic to define if the response model
  2216. should be serialized by alias when an alias is used.
  2217. Read more about it in the
  2218. [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).
  2219. """
  2220. ),
  2221. ] = True,
  2222. response_model_exclude_unset: Annotated[
  2223. bool,
  2224. Doc(
  2225. """
  2226. Configuration passed to Pydantic to define if the response data
  2227. should have all the fields, including the ones that were not set and
  2228. have their default values. This is different from
  2229. `response_model_exclude_defaults` in that if the fields are set,
  2230. they will be included in the response, even if the value is the same
  2231. as the default.
  2232. When `True`, default values are omitted from the response.
  2233. Read more about it in the
  2234. [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).
  2235. """
  2236. ),
  2237. ] = False,
  2238. response_model_exclude_defaults: Annotated[
  2239. bool,
  2240. Doc(
  2241. """
  2242. Configuration passed to Pydantic to define if the response data
  2243. should have all the fields, including the ones that have the same value
  2244. as the default. This is different from `response_model_exclude_unset`
  2245. in that if the fields are set but contain the same default values,
  2246. they will be excluded from the response.
  2247. When `True`, default values are omitted from the response.
  2248. Read more about it in the
  2249. [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).
  2250. """
  2251. ),
  2252. ] = False,
  2253. response_model_exclude_none: Annotated[
  2254. bool,
  2255. Doc(
  2256. """
  2257. Configuration passed to Pydantic to define if the response data should
  2258. exclude fields set to `None`.
  2259. This is much simpler (less smart) than `response_model_exclude_unset`
  2260. and `response_model_exclude_defaults`. You probably want to use one of
  2261. those two instead of this one, as those allow returning `None` values
  2262. when it makes sense.
  2263. Read more about it in the
  2264. [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none).
  2265. """
  2266. ),
  2267. ] = False,
  2268. include_in_schema: Annotated[
  2269. bool,
  2270. Doc(
  2271. """
  2272. Include this *path operation* in the generated OpenAPI schema.
  2273. This affects the generated OpenAPI (e.g. visible at `/docs`).
  2274. Read more about it in the
  2275. [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-parameters-from-openapi).
  2276. """
  2277. ),
  2278. ] = True,
  2279. response_class: Annotated[
  2280. type[Response],
  2281. Doc(
  2282. """
  2283. Response class to be used for this *path operation*.
  2284. This will not be used if you return a response directly.
  2285. Read more about it in the
  2286. [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse).
  2287. """
  2288. ),
  2289. ] = Default(JSONResponse),
  2290. name: Annotated[
  2291. str | None,
  2292. Doc(
  2293. """
  2294. Name for this *path operation*. Only used internally.
  2295. """
  2296. ),
  2297. ] = None,
  2298. callbacks: Annotated[
  2299. list[BaseRoute] | None,
  2300. Doc(
  2301. """
  2302. List of *path operations* that will be used as OpenAPI callbacks.
  2303. This is only for OpenAPI documentation, the callbacks won't be used
  2304. directly.
  2305. It will be added to the generated OpenAPI (e.g. visible at `/docs`).
  2306. Read more about it in the
  2307. [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/).
  2308. """
  2309. ),
  2310. ] = None,
  2311. openapi_extra: Annotated[
  2312. dict[str, Any] | None,
  2313. Doc(
  2314. """
  2315. Extra metadata to be included in the OpenAPI schema for this *path
  2316. operation*.
  2317. Read more about it in the
  2318. [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema).
  2319. """
  2320. ),
  2321. ] = None,
  2322. generate_unique_id_function: Annotated[
  2323. Callable[[routing.APIRoute], str],
  2324. Doc(
  2325. """
  2326. Customize the function used to generate unique IDs for the *path
  2327. operations* shown in the generated OpenAPI.
  2328. This is particularly useful when automatically generating clients or
  2329. SDKs for your API.
  2330. Read more about it in the
  2331. [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).
  2332. """
  2333. ),
  2334. ] = Default(generate_unique_id),
  2335. ) -> Callable[[DecoratedCallable], DecoratedCallable]:
  2336. """
  2337. Add a *path operation* using an HTTP POST operation.
  2338. ## Example
  2339. ```python
  2340. from fastapi import FastAPI
  2341. from pydantic import BaseModel
  2342. class Item(BaseModel):
  2343. name: str
  2344. description: str | None = None
  2345. app = FastAPI()
  2346. @app.post("/items/")
  2347. def create_item(item: Item):
  2348. return {"message": "Item created"}
  2349. ```
  2350. """
  2351. return self.router.post(
  2352. path,
  2353. response_model=response_model,
  2354. status_code=status_code,
  2355. tags=tags,
  2356. dependencies=dependencies,
  2357. summary=summary,
  2358. description=description,
  2359. response_description=response_description,
  2360. responses=responses,
  2361. deprecated=deprecated,
  2362. operation_id=operation_id,
  2363. response_model_include=response_model_include,
  2364. response_model_exclude=response_model_exclude,
  2365. response_model_by_alias=response_model_by_alias,
  2366. response_model_exclude_unset=response_model_exclude_unset,
  2367. response_model_exclude_defaults=response_model_exclude_defaults,
  2368. response_model_exclude_none=response_model_exclude_none,
  2369. include_in_schema=include_in_schema,
  2370. response_class=response_class,
  2371. name=name,
  2372. callbacks=callbacks,
  2373. openapi_extra=openapi_extra,
  2374. generate_unique_id_function=generate_unique_id_function,
  2375. )
  2376. def delete(
  2377. self,
  2378. path: Annotated[
  2379. str,
  2380. Doc(
  2381. """
  2382. The URL path to be used for this *path operation*.
  2383. For example, in `http://example.com/items`, the path is `/items`.
  2384. """
  2385. ),
  2386. ],
  2387. *,
  2388. response_model: Annotated[
  2389. Any,
  2390. Doc(
  2391. """
  2392. The type to use for the response.
  2393. It could be any valid Pydantic *field* type. So, it doesn't have to
  2394. be a Pydantic model, it could be other things, like a `list`, `dict`,
  2395. etc.
  2396. It will be used for:
  2397. * Documentation: the generated OpenAPI (and the UI at `/docs`) will
  2398. show it as the response (JSON Schema).
  2399. * Serialization: you could return an arbitrary object and the
  2400. `response_model` would be used to serialize that object into the
  2401. corresponding JSON.
  2402. * Filtering: the JSON sent to the client will only contain the data
  2403. (fields) defined in the `response_model`. If you returned an object
  2404. that contains an attribute `password` but the `response_model` does
  2405. not include that field, the JSON sent to the client would not have
  2406. that `password`.
  2407. * Validation: whatever you return will be serialized with the
  2408. `response_model`, converting any data as necessary to generate the
  2409. corresponding JSON. But if the data in the object returned is not
  2410. valid, that would mean a violation of the contract with the client,
  2411. so it's an error from the API developer. So, FastAPI will raise an
  2412. error and return a 500 error code (Internal Server Error).
  2413. Read more about it in the
  2414. [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/).
  2415. """
  2416. ),
  2417. ] = Default(None),
  2418. status_code: Annotated[
  2419. int | None,
  2420. Doc(
  2421. """
  2422. The default status code to be used for the response.
  2423. You could override the status code by returning a response directly.
  2424. Read more about it in the
  2425. [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/).
  2426. """
  2427. ),
  2428. ] = None,
  2429. tags: Annotated[
  2430. list[str | Enum] | None,
  2431. Doc(
  2432. """
  2433. A list of tags to be applied to the *path operation*.
  2434. It will be added to the generated OpenAPI (e.g. visible at `/docs`).
  2435. Read more about it in the
  2436. [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#tags).
  2437. """
  2438. ),
  2439. ] = None,
  2440. dependencies: Annotated[
  2441. Sequence[Depends] | None,
  2442. Doc(
  2443. """
  2444. A list of dependencies (using `Depends()`) to be applied to the
  2445. *path operation*.
  2446. Read more about it in the
  2447. [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/).
  2448. """
  2449. ),
  2450. ] = None,
  2451. summary: Annotated[
  2452. str | None,
  2453. Doc(
  2454. """
  2455. A summary for the *path operation*.
  2456. It will be added to the generated OpenAPI (e.g. visible at `/docs`).
  2457. Read more about it in the
  2458. [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).
  2459. """
  2460. ),
  2461. ] = None,
  2462. description: Annotated[
  2463. str | None,
  2464. Doc(
  2465. """
  2466. A description for the *path operation*.
  2467. If not provided, it will be extracted automatically from the docstring
  2468. of the *path operation function*.
  2469. It can contain Markdown.
  2470. It will be added to the generated OpenAPI (e.g. visible at `/docs`).
  2471. Read more about it in the
  2472. [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).
  2473. """
  2474. ),
  2475. ] = None,
  2476. response_description: Annotated[
  2477. str,
  2478. Doc(
  2479. """
  2480. The description for the default response.
  2481. It will be added to the generated OpenAPI (e.g. visible at `/docs`).
  2482. """
  2483. ),
  2484. ] = "Successful Response",
  2485. responses: Annotated[
  2486. dict[int | str, dict[str, Any]] | None,
  2487. Doc(
  2488. """
  2489. Additional responses that could be returned by this *path operation*.
  2490. It will be added to the generated OpenAPI (e.g. visible at `/docs`).
  2491. """
  2492. ),
  2493. ] = None,
  2494. deprecated: Annotated[
  2495. bool | None,
  2496. Doc(
  2497. """
  2498. Mark this *path operation* as deprecated.
  2499. It will be added to the generated OpenAPI (e.g. visible at `/docs`).
  2500. """
  2501. ),
  2502. ] = None,
  2503. operation_id: Annotated[
  2504. str | None,
  2505. Doc(
  2506. """
  2507. Custom operation ID to be used by this *path operation*.
  2508. By default, it is generated automatically.
  2509. If you provide a custom operation ID, you need to make sure it is
  2510. unique for the whole API.
  2511. You can customize the
  2512. operation ID generation with the parameter
  2513. `generate_unique_id_function` in the `FastAPI` class.
  2514. Read more about it in the
  2515. [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).
  2516. """
  2517. ),
  2518. ] = None,
  2519. response_model_include: Annotated[
  2520. IncEx | None,
  2521. Doc(
  2522. """
  2523. Configuration passed to Pydantic to include only certain fields in the
  2524. response data.
  2525. Read more about it in the
  2526. [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).
  2527. """
  2528. ),
  2529. ] = None,
  2530. response_model_exclude: Annotated[
  2531. IncEx | None,
  2532. Doc(
  2533. """
  2534. Configuration passed to Pydantic to exclude certain fields in the
  2535. response data.
  2536. Read more about it in the
  2537. [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).
  2538. """
  2539. ),
  2540. ] = None,
  2541. response_model_by_alias: Annotated[
  2542. bool,
  2543. Doc(
  2544. """
  2545. Configuration passed to Pydantic to define if the response model
  2546. should be serialized by alias when an alias is used.
  2547. Read more about it in the
  2548. [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).
  2549. """
  2550. ),
  2551. ] = True,
  2552. response_model_exclude_unset: Annotated[
  2553. bool,
  2554. Doc(
  2555. """
  2556. Configuration passed to Pydantic to define if the response data
  2557. should have all the fields, including the ones that were not set and
  2558. have their default values. This is different from
  2559. `response_model_exclude_defaults` in that if the fields are set,
  2560. they will be included in the response, even if the value is the same
  2561. as the default.
  2562. When `True`, default values are omitted from the response.
  2563. Read more about it in the
  2564. [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).
  2565. """
  2566. ),
  2567. ] = False,
  2568. response_model_exclude_defaults: Annotated[
  2569. bool,
  2570. Doc(
  2571. """
  2572. Configuration passed to Pydantic to define if the response data
  2573. should have all the fields, including the ones that have the same value
  2574. as the default. This is different from `response_model_exclude_unset`
  2575. in that if the fields are set but contain the same default values,
  2576. they will be excluded from the response.
  2577. When `True`, default values are omitted from the response.
  2578. Read more about it in the
  2579. [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).
  2580. """
  2581. ),
  2582. ] = False,
  2583. response_model_exclude_none: Annotated[
  2584. bool,
  2585. Doc(
  2586. """
  2587. Configuration passed to Pydantic to define if the response data should
  2588. exclude fields set to `None`.
  2589. This is much simpler (less smart) than `response_model_exclude_unset`
  2590. and `response_model_exclude_defaults`. You probably want to use one of
  2591. those two instead of this one, as those allow returning `None` values
  2592. when it makes sense.
  2593. Read more about it in the
  2594. [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none).
  2595. """
  2596. ),
  2597. ] = False,
  2598. include_in_schema: Annotated[
  2599. bool,
  2600. Doc(
  2601. """
  2602. Include this *path operation* in the generated OpenAPI schema.
  2603. This affects the generated OpenAPI (e.g. visible at `/docs`).
  2604. Read more about it in the
  2605. [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-parameters-from-openapi).
  2606. """
  2607. ),
  2608. ] = True,
  2609. response_class: Annotated[
  2610. type[Response],
  2611. Doc(
  2612. """
  2613. Response class to be used for this *path operation*.
  2614. This will not be used if you return a response directly.
  2615. Read more about it in the
  2616. [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse).
  2617. """
  2618. ),
  2619. ] = Default(JSONResponse),
  2620. name: Annotated[
  2621. str | None,
  2622. Doc(
  2623. """
  2624. Name for this *path operation*. Only used internally.
  2625. """
  2626. ),
  2627. ] = None,
  2628. callbacks: Annotated[
  2629. list[BaseRoute] | None,
  2630. Doc(
  2631. """
  2632. List of *path operations* that will be used as OpenAPI callbacks.
  2633. This is only for OpenAPI documentation, the callbacks won't be used
  2634. directly.
  2635. It will be added to the generated OpenAPI (e.g. visible at `/docs`).
  2636. Read more about it in the
  2637. [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/).
  2638. """
  2639. ),
  2640. ] = None,
  2641. openapi_extra: Annotated[
  2642. dict[str, Any] | None,
  2643. Doc(
  2644. """
  2645. Extra metadata to be included in the OpenAPI schema for this *path
  2646. operation*.
  2647. Read more about it in the
  2648. [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema).
  2649. """
  2650. ),
  2651. ] = None,
  2652. generate_unique_id_function: Annotated[
  2653. Callable[[routing.APIRoute], str],
  2654. Doc(
  2655. """
  2656. Customize the function used to generate unique IDs for the *path
  2657. operations* shown in the generated OpenAPI.
  2658. This is particularly useful when automatically generating clients or
  2659. SDKs for your API.
  2660. Read more about it in the
  2661. [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).
  2662. """
  2663. ),
  2664. ] = Default(generate_unique_id),
  2665. ) -> Callable[[DecoratedCallable], DecoratedCallable]:
  2666. """
  2667. Add a *path operation* using an HTTP DELETE operation.
  2668. ## Example
  2669. ```python
  2670. from fastapi import FastAPI
  2671. app = FastAPI()
  2672. @app.delete("/items/{item_id}")
  2673. def delete_item(item_id: str):
  2674. return {"message": "Item deleted"}
  2675. ```
  2676. """
  2677. return self.router.delete(
  2678. path,
  2679. response_model=response_model,
  2680. status_code=status_code,
  2681. tags=tags,
  2682. dependencies=dependencies,
  2683. summary=summary,
  2684. description=description,
  2685. response_description=response_description,
  2686. responses=responses,
  2687. deprecated=deprecated,
  2688. operation_id=operation_id,
  2689. response_model_include=response_model_include,
  2690. response_model_exclude=response_model_exclude,
  2691. response_model_by_alias=response_model_by_alias,
  2692. response_model_exclude_unset=response_model_exclude_unset,
  2693. response_model_exclude_defaults=response_model_exclude_defaults,
  2694. response_model_exclude_none=response_model_exclude_none,
  2695. include_in_schema=include_in_schema,
  2696. response_class=response_class,
  2697. name=name,
  2698. callbacks=callbacks,
  2699. openapi_extra=openapi_extra,
  2700. generate_unique_id_function=generate_unique_id_function,
  2701. )
  2702. def options(
  2703. self,
  2704. path: Annotated[
  2705. str,
  2706. Doc(
  2707. """
  2708. The URL path to be used for this *path operation*.
  2709. For example, in `http://example.com/items`, the path is `/items`.
  2710. """
  2711. ),
  2712. ],
  2713. *,
  2714. response_model: Annotated[
  2715. Any,
  2716. Doc(
  2717. """
  2718. The type to use for the response.
  2719. It could be any valid Pydantic *field* type. So, it doesn't have to
  2720. be a Pydantic model, it could be other things, like a `list`, `dict`,
  2721. etc.
  2722. It will be used for:
  2723. * Documentation: the generated OpenAPI (and the UI at `/docs`) will
  2724. show it as the response (JSON Schema).
  2725. * Serialization: you could return an arbitrary object and the
  2726. `response_model` would be used to serialize that object into the
  2727. corresponding JSON.
  2728. * Filtering: the JSON sent to the client will only contain the data
  2729. (fields) defined in the `response_model`. If you returned an object
  2730. that contains an attribute `password` but the `response_model` does
  2731. not include that field, the JSON sent to the client would not have
  2732. that `password`.
  2733. * Validation: whatever you return will be serialized with the
  2734. `response_model`, converting any data as necessary to generate the
  2735. corresponding JSON. But if the data in the object returned is not
  2736. valid, that would mean a violation of the contract with the client,
  2737. so it's an error from the API developer. So, FastAPI will raise an
  2738. error and return a 500 error code (Internal Server Error).
  2739. Read more about it in the
  2740. [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/).
  2741. """
  2742. ),
  2743. ] = Default(None),
  2744. status_code: Annotated[
  2745. int | None,
  2746. Doc(
  2747. """
  2748. The default status code to be used for the response.
  2749. You could override the status code by returning a response directly.
  2750. Read more about it in the
  2751. [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/).
  2752. """
  2753. ),
  2754. ] = None,
  2755. tags: Annotated[
  2756. list[str | Enum] | None,
  2757. Doc(
  2758. """
  2759. A list of tags to be applied to the *path operation*.
  2760. It will be added to the generated OpenAPI (e.g. visible at `/docs`).
  2761. Read more about it in the
  2762. [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#tags).
  2763. """
  2764. ),
  2765. ] = None,
  2766. dependencies: Annotated[
  2767. Sequence[Depends] | None,
  2768. Doc(
  2769. """
  2770. A list of dependencies (using `Depends()`) to be applied to the
  2771. *path operation*.
  2772. Read more about it in the
  2773. [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/).
  2774. """
  2775. ),
  2776. ] = None,
  2777. summary: Annotated[
  2778. str | None,
  2779. Doc(
  2780. """
  2781. A summary for the *path operation*.
  2782. It will be added to the generated OpenAPI (e.g. visible at `/docs`).
  2783. Read more about it in the
  2784. [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).
  2785. """
  2786. ),
  2787. ] = None,
  2788. description: Annotated[
  2789. str | None,
  2790. Doc(
  2791. """
  2792. A description for the *path operation*.
  2793. If not provided, it will be extracted automatically from the docstring
  2794. of the *path operation function*.
  2795. It can contain Markdown.
  2796. It will be added to the generated OpenAPI (e.g. visible at `/docs`).
  2797. Read more about it in the
  2798. [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).
  2799. """
  2800. ),
  2801. ] = None,
  2802. response_description: Annotated[
  2803. str,
  2804. Doc(
  2805. """
  2806. The description for the default response.
  2807. It will be added to the generated OpenAPI (e.g. visible at `/docs`).
  2808. """
  2809. ),
  2810. ] = "Successful Response",
  2811. responses: Annotated[
  2812. dict[int | str, dict[str, Any]] | None,
  2813. Doc(
  2814. """
  2815. Additional responses that could be returned by this *path operation*.
  2816. It will be added to the generated OpenAPI (e.g. visible at `/docs`).
  2817. """
  2818. ),
  2819. ] = None,
  2820. deprecated: Annotated[
  2821. bool | None,
  2822. Doc(
  2823. """
  2824. Mark this *path operation* as deprecated.
  2825. It will be added to the generated OpenAPI (e.g. visible at `/docs`).
  2826. """
  2827. ),
  2828. ] = None,
  2829. operation_id: Annotated[
  2830. str | None,
  2831. Doc(
  2832. """
  2833. Custom operation ID to be used by this *path operation*.
  2834. By default, it is generated automatically.
  2835. If you provide a custom operation ID, you need to make sure it is
  2836. unique for the whole API.
  2837. You can customize the
  2838. operation ID generation with the parameter
  2839. `generate_unique_id_function` in the `FastAPI` class.
  2840. Read more about it in the
  2841. [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).
  2842. """
  2843. ),
  2844. ] = None,
  2845. response_model_include: Annotated[
  2846. IncEx | None,
  2847. Doc(
  2848. """
  2849. Configuration passed to Pydantic to include only certain fields in the
  2850. response data.
  2851. Read more about it in the
  2852. [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).
  2853. """
  2854. ),
  2855. ] = None,
  2856. response_model_exclude: Annotated[
  2857. IncEx | None,
  2858. Doc(
  2859. """
  2860. Configuration passed to Pydantic to exclude certain fields in the
  2861. response data.
  2862. Read more about it in the
  2863. [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).
  2864. """
  2865. ),
  2866. ] = None,
  2867. response_model_by_alias: Annotated[
  2868. bool,
  2869. Doc(
  2870. """
  2871. Configuration passed to Pydantic to define if the response model
  2872. should be serialized by alias when an alias is used.
  2873. Read more about it in the
  2874. [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).
  2875. """
  2876. ),
  2877. ] = True,
  2878. response_model_exclude_unset: Annotated[
  2879. bool,
  2880. Doc(
  2881. """
  2882. Configuration passed to Pydantic to define if the response data
  2883. should have all the fields, including the ones that were not set and
  2884. have their default values. This is different from
  2885. `response_model_exclude_defaults` in that if the fields are set,
  2886. they will be included in the response, even if the value is the same
  2887. as the default.
  2888. When `True`, default values are omitted from the response.
  2889. Read more about it in the
  2890. [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).
  2891. """
  2892. ),
  2893. ] = False,
  2894. response_model_exclude_defaults: Annotated[
  2895. bool,
  2896. Doc(
  2897. """
  2898. Configuration passed to Pydantic to define if the response data
  2899. should have all the fields, including the ones that have the same value
  2900. as the default. This is different from `response_model_exclude_unset`
  2901. in that if the fields are set but contain the same default values,
  2902. they will be excluded from the response.
  2903. When `True`, default values are omitted from the response.
  2904. Read more about it in the
  2905. [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).
  2906. """
  2907. ),
  2908. ] = False,
  2909. response_model_exclude_none: Annotated[
  2910. bool,
  2911. Doc(
  2912. """
  2913. Configuration passed to Pydantic to define if the response data should
  2914. exclude fields set to `None`.
  2915. This is much simpler (less smart) than `response_model_exclude_unset`
  2916. and `response_model_exclude_defaults`. You probably want to use one of
  2917. those two instead of this one, as those allow returning `None` values
  2918. when it makes sense.
  2919. Read more about it in the
  2920. [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none).
  2921. """
  2922. ),
  2923. ] = False,
  2924. include_in_schema: Annotated[
  2925. bool,
  2926. Doc(
  2927. """
  2928. Include this *path operation* in the generated OpenAPI schema.
  2929. This affects the generated OpenAPI (e.g. visible at `/docs`).
  2930. Read more about it in the
  2931. [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-parameters-from-openapi).
  2932. """
  2933. ),
  2934. ] = True,
  2935. response_class: Annotated[
  2936. type[Response],
  2937. Doc(
  2938. """
  2939. Response class to be used for this *path operation*.
  2940. This will not be used if you return a response directly.
  2941. Read more about it in the
  2942. [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse).
  2943. """
  2944. ),
  2945. ] = Default(JSONResponse),
  2946. name: Annotated[
  2947. str | None,
  2948. Doc(
  2949. """
  2950. Name for this *path operation*. Only used internally.
  2951. """
  2952. ),
  2953. ] = None,
  2954. callbacks: Annotated[
  2955. list[BaseRoute] | None,
  2956. Doc(
  2957. """
  2958. List of *path operations* that will be used as OpenAPI callbacks.
  2959. This is only for OpenAPI documentation, the callbacks won't be used
  2960. directly.
  2961. It will be added to the generated OpenAPI (e.g. visible at `/docs`).
  2962. Read more about it in the
  2963. [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/).
  2964. """
  2965. ),
  2966. ] = None,
  2967. openapi_extra: Annotated[
  2968. dict[str, Any] | None,
  2969. Doc(
  2970. """
  2971. Extra metadata to be included in the OpenAPI schema for this *path
  2972. operation*.
  2973. Read more about it in the
  2974. [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema).
  2975. """
  2976. ),
  2977. ] = None,
  2978. generate_unique_id_function: Annotated[
  2979. Callable[[routing.APIRoute], str],
  2980. Doc(
  2981. """
  2982. Customize the function used to generate unique IDs for the *path
  2983. operations* shown in the generated OpenAPI.
  2984. This is particularly useful when automatically generating clients or
  2985. SDKs for your API.
  2986. Read more about it in the
  2987. [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).
  2988. """
  2989. ),
  2990. ] = Default(generate_unique_id),
  2991. ) -> Callable[[DecoratedCallable], DecoratedCallable]:
  2992. """
  2993. Add a *path operation* using an HTTP OPTIONS operation.
  2994. ## Example
  2995. ```python
  2996. from fastapi import FastAPI
  2997. app = FastAPI()
  2998. @app.options("/items/")
  2999. def get_item_options():
  3000. return {"additions": ["Aji", "Guacamole"]}
  3001. ```
  3002. """
  3003. return self.router.options(
  3004. path,
  3005. response_model=response_model,
  3006. status_code=status_code,
  3007. tags=tags,
  3008. dependencies=dependencies,
  3009. summary=summary,
  3010. description=description,
  3011. response_description=response_description,
  3012. responses=responses,
  3013. deprecated=deprecated,
  3014. operation_id=operation_id,
  3015. response_model_include=response_model_include,
  3016. response_model_exclude=response_model_exclude,
  3017. response_model_by_alias=response_model_by_alias,
  3018. response_model_exclude_unset=response_model_exclude_unset,
  3019. response_model_exclude_defaults=response_model_exclude_defaults,
  3020. response_model_exclude_none=response_model_exclude_none,
  3021. include_in_schema=include_in_schema,
  3022. response_class=response_class,
  3023. name=name,
  3024. callbacks=callbacks,
  3025. openapi_extra=openapi_extra,
  3026. generate_unique_id_function=generate_unique_id_function,
  3027. )
  3028. def head(
  3029. self,
  3030. path: Annotated[
  3031. str,
  3032. Doc(
  3033. """
  3034. The URL path to be used for this *path operation*.
  3035. For example, in `http://example.com/items`, the path is `/items`.
  3036. """
  3037. ),
  3038. ],
  3039. *,
  3040. response_model: Annotated[
  3041. Any,
  3042. Doc(
  3043. """
  3044. The type to use for the response.
  3045. It could be any valid Pydantic *field* type. So, it doesn't have to
  3046. be a Pydantic model, it could be other things, like a `list`, `dict`,
  3047. etc.
  3048. It will be used for:
  3049. * Documentation: the generated OpenAPI (and the UI at `/docs`) will
  3050. show it as the response (JSON Schema).
  3051. * Serialization: you could return an arbitrary object and the
  3052. `response_model` would be used to serialize that object into the
  3053. corresponding JSON.
  3054. * Filtering: the JSON sent to the client will only contain the data
  3055. (fields) defined in the `response_model`. If you returned an object
  3056. that contains an attribute `password` but the `response_model` does
  3057. not include that field, the JSON sent to the client would not have
  3058. that `password`.
  3059. * Validation: whatever you return will be serialized with the
  3060. `response_model`, converting any data as necessary to generate the
  3061. corresponding JSON. But if the data in the object returned is not
  3062. valid, that would mean a violation of the contract with the client,
  3063. so it's an error from the API developer. So, FastAPI will raise an
  3064. error and return a 500 error code (Internal Server Error).
  3065. Read more about it in the
  3066. [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/).
  3067. """
  3068. ),
  3069. ] = Default(None),
  3070. status_code: Annotated[
  3071. int | None,
  3072. Doc(
  3073. """
  3074. The default status code to be used for the response.
  3075. You could override the status code by returning a response directly.
  3076. Read more about it in the
  3077. [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/).
  3078. """
  3079. ),
  3080. ] = None,
  3081. tags: Annotated[
  3082. list[str | Enum] | None,
  3083. Doc(
  3084. """
  3085. A list of tags to be applied to the *path operation*.
  3086. It will be added to the generated OpenAPI (e.g. visible at `/docs`).
  3087. Read more about it in the
  3088. [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#tags).
  3089. """
  3090. ),
  3091. ] = None,
  3092. dependencies: Annotated[
  3093. Sequence[Depends] | None,
  3094. Doc(
  3095. """
  3096. A list of dependencies (using `Depends()`) to be applied to the
  3097. *path operation*.
  3098. Read more about it in the
  3099. [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/).
  3100. """
  3101. ),
  3102. ] = None,
  3103. summary: Annotated[
  3104. str | None,
  3105. Doc(
  3106. """
  3107. A summary for the *path operation*.
  3108. It will be added to the generated OpenAPI (e.g. visible at `/docs`).
  3109. Read more about it in the
  3110. [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).
  3111. """
  3112. ),
  3113. ] = None,
  3114. description: Annotated[
  3115. str | None,
  3116. Doc(
  3117. """
  3118. A description for the *path operation*.
  3119. If not provided, it will be extracted automatically from the docstring
  3120. of the *path operation function*.
  3121. It can contain Markdown.
  3122. It will be added to the generated OpenAPI (e.g. visible at `/docs`).
  3123. Read more about it in the
  3124. [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).
  3125. """
  3126. ),
  3127. ] = None,
  3128. response_description: Annotated[
  3129. str,
  3130. Doc(
  3131. """
  3132. The description for the default response.
  3133. It will be added to the generated OpenAPI (e.g. visible at `/docs`).
  3134. """
  3135. ),
  3136. ] = "Successful Response",
  3137. responses: Annotated[
  3138. dict[int | str, dict[str, Any]] | None,
  3139. Doc(
  3140. """
  3141. Additional responses that could be returned by this *path operation*.
  3142. It will be added to the generated OpenAPI (e.g. visible at `/docs`).
  3143. """
  3144. ),
  3145. ] = None,
  3146. deprecated: Annotated[
  3147. bool | None,
  3148. Doc(
  3149. """
  3150. Mark this *path operation* as deprecated.
  3151. It will be added to the generated OpenAPI (e.g. visible at `/docs`).
  3152. """
  3153. ),
  3154. ] = None,
  3155. operation_id: Annotated[
  3156. str | None,
  3157. Doc(
  3158. """
  3159. Custom operation ID to be used by this *path operation*.
  3160. By default, it is generated automatically.
  3161. If you provide a custom operation ID, you need to make sure it is
  3162. unique for the whole API.
  3163. You can customize the
  3164. operation ID generation with the parameter
  3165. `generate_unique_id_function` in the `FastAPI` class.
  3166. Read more about it in the
  3167. [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).
  3168. """
  3169. ),
  3170. ] = None,
  3171. response_model_include: Annotated[
  3172. IncEx | None,
  3173. Doc(
  3174. """
  3175. Configuration passed to Pydantic to include only certain fields in the
  3176. response data.
  3177. Read more about it in the
  3178. [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).
  3179. """
  3180. ),
  3181. ] = None,
  3182. response_model_exclude: Annotated[
  3183. IncEx | None,
  3184. Doc(
  3185. """
  3186. Configuration passed to Pydantic to exclude certain fields in the
  3187. response data.
  3188. Read more about it in the
  3189. [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).
  3190. """
  3191. ),
  3192. ] = None,
  3193. response_model_by_alias: Annotated[
  3194. bool,
  3195. Doc(
  3196. """
  3197. Configuration passed to Pydantic to define if the response model
  3198. should be serialized by alias when an alias is used.
  3199. Read more about it in the
  3200. [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).
  3201. """
  3202. ),
  3203. ] = True,
  3204. response_model_exclude_unset: Annotated[
  3205. bool,
  3206. Doc(
  3207. """
  3208. Configuration passed to Pydantic to define if the response data
  3209. should have all the fields, including the ones that were not set and
  3210. have their default values. This is different from
  3211. `response_model_exclude_defaults` in that if the fields are set,
  3212. they will be included in the response, even if the value is the same
  3213. as the default.
  3214. When `True`, default values are omitted from the response.
  3215. Read more about it in the
  3216. [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).
  3217. """
  3218. ),
  3219. ] = False,
  3220. response_model_exclude_defaults: Annotated[
  3221. bool,
  3222. Doc(
  3223. """
  3224. Configuration passed to Pydantic to define if the response data
  3225. should have all the fields, including the ones that have the same value
  3226. as the default. This is different from `response_model_exclude_unset`
  3227. in that if the fields are set but contain the same default values,
  3228. they will be excluded from the response.
  3229. When `True`, default values are omitted from the response.
  3230. Read more about it in the
  3231. [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).
  3232. """
  3233. ),
  3234. ] = False,
  3235. response_model_exclude_none: Annotated[
  3236. bool,
  3237. Doc(
  3238. """
  3239. Configuration passed to Pydantic to define if the response data should
  3240. exclude fields set to `None`.
  3241. This is much simpler (less smart) than `response_model_exclude_unset`
  3242. and `response_model_exclude_defaults`. You probably want to use one of
  3243. those two instead of this one, as those allow returning `None` values
  3244. when it makes sense.
  3245. Read more about it in the
  3246. [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none).
  3247. """
  3248. ),
  3249. ] = False,
  3250. include_in_schema: Annotated[
  3251. bool,
  3252. Doc(
  3253. """
  3254. Include this *path operation* in the generated OpenAPI schema.
  3255. This affects the generated OpenAPI (e.g. visible at `/docs`).
  3256. Read more about it in the
  3257. [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-parameters-from-openapi).
  3258. """
  3259. ),
  3260. ] = True,
  3261. response_class: Annotated[
  3262. type[Response],
  3263. Doc(
  3264. """
  3265. Response class to be used for this *path operation*.
  3266. This will not be used if you return a response directly.
  3267. Read more about it in the
  3268. [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse).
  3269. """
  3270. ),
  3271. ] = Default(JSONResponse),
  3272. name: Annotated[
  3273. str | None,
  3274. Doc(
  3275. """
  3276. Name for this *path operation*. Only used internally.
  3277. """
  3278. ),
  3279. ] = None,
  3280. callbacks: Annotated[
  3281. list[BaseRoute] | None,
  3282. Doc(
  3283. """
  3284. List of *path operations* that will be used as OpenAPI callbacks.
  3285. This is only for OpenAPI documentation, the callbacks won't be used
  3286. directly.
  3287. It will be added to the generated OpenAPI (e.g. visible at `/docs`).
  3288. Read more about it in the
  3289. [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/).
  3290. """
  3291. ),
  3292. ] = None,
  3293. openapi_extra: Annotated[
  3294. dict[str, Any] | None,
  3295. Doc(
  3296. """
  3297. Extra metadata to be included in the OpenAPI schema for this *path
  3298. operation*.
  3299. Read more about it in the
  3300. [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema).
  3301. """
  3302. ),
  3303. ] = None,
  3304. generate_unique_id_function: Annotated[
  3305. Callable[[routing.APIRoute], str],
  3306. Doc(
  3307. """
  3308. Customize the function used to generate unique IDs for the *path
  3309. operations* shown in the generated OpenAPI.
  3310. This is particularly useful when automatically generating clients or
  3311. SDKs for your API.
  3312. Read more about it in the
  3313. [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).
  3314. """
  3315. ),
  3316. ] = Default(generate_unique_id),
  3317. ) -> Callable[[DecoratedCallable], DecoratedCallable]:
  3318. """
  3319. Add a *path operation* using an HTTP HEAD operation.
  3320. ## Example
  3321. ```python
  3322. from fastapi import FastAPI, Response
  3323. app = FastAPI()
  3324. @app.head("/items/", status_code=204)
  3325. def get_items_headers(response: Response):
  3326. response.headers["X-Cat-Dog"] = "Alone in the world"
  3327. ```
  3328. """
  3329. return self.router.head(
  3330. path,
  3331. response_model=response_model,
  3332. status_code=status_code,
  3333. tags=tags,
  3334. dependencies=dependencies,
  3335. summary=summary,
  3336. description=description,
  3337. response_description=response_description,
  3338. responses=responses,
  3339. deprecated=deprecated,
  3340. operation_id=operation_id,
  3341. response_model_include=response_model_include,
  3342. response_model_exclude=response_model_exclude,
  3343. response_model_by_alias=response_model_by_alias,
  3344. response_model_exclude_unset=response_model_exclude_unset,
  3345. response_model_exclude_defaults=response_model_exclude_defaults,
  3346. response_model_exclude_none=response_model_exclude_none,
  3347. include_in_schema=include_in_schema,
  3348. response_class=response_class,
  3349. name=name,
  3350. callbacks=callbacks,
  3351. openapi_extra=openapi_extra,
  3352. generate_unique_id_function=generate_unique_id_function,
  3353. )
  3354. def patch(
  3355. self,
  3356. path: Annotated[
  3357. str,
  3358. Doc(
  3359. """
  3360. The URL path to be used for this *path operation*.
  3361. For example, in `http://example.com/items`, the path is `/items`.
  3362. """
  3363. ),
  3364. ],
  3365. *,
  3366. response_model: Annotated[
  3367. Any,
  3368. Doc(
  3369. """
  3370. The type to use for the response.
  3371. It could be any valid Pydantic *field* type. So, it doesn't have to
  3372. be a Pydantic model, it could be other things, like a `list`, `dict`,
  3373. etc.
  3374. It will be used for:
  3375. * Documentation: the generated OpenAPI (and the UI at `/docs`) will
  3376. show it as the response (JSON Schema).
  3377. * Serialization: you could return an arbitrary object and the
  3378. `response_model` would be used to serialize that object into the
  3379. corresponding JSON.
  3380. * Filtering: the JSON sent to the client will only contain the data
  3381. (fields) defined in the `response_model`. If you returned an object
  3382. that contains an attribute `password` but the `response_model` does
  3383. not include that field, the JSON sent to the client would not have
  3384. that `password`.
  3385. * Validation: whatever you return will be serialized with the
  3386. `response_model`, converting any data as necessary to generate the
  3387. corresponding JSON. But if the data in the object returned is not
  3388. valid, that would mean a violation of the contract with the client,
  3389. so it's an error from the API developer. So, FastAPI will raise an
  3390. error and return a 500 error code (Internal Server Error).
  3391. Read more about it in the
  3392. [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/).
  3393. """
  3394. ),
  3395. ] = Default(None),
  3396. status_code: Annotated[
  3397. int | None,
  3398. Doc(
  3399. """
  3400. The default status code to be used for the response.
  3401. You could override the status code by returning a response directly.
  3402. Read more about it in the
  3403. [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/).
  3404. """
  3405. ),
  3406. ] = None,
  3407. tags: Annotated[
  3408. list[str | Enum] | None,
  3409. Doc(
  3410. """
  3411. A list of tags to be applied to the *path operation*.
  3412. It will be added to the generated OpenAPI (e.g. visible at `/docs`).
  3413. Read more about it in the
  3414. [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#tags).
  3415. """
  3416. ),
  3417. ] = None,
  3418. dependencies: Annotated[
  3419. Sequence[Depends] | None,
  3420. Doc(
  3421. """
  3422. A list of dependencies (using `Depends()`) to be applied to the
  3423. *path operation*.
  3424. Read more about it in the
  3425. [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/).
  3426. """
  3427. ),
  3428. ] = None,
  3429. summary: Annotated[
  3430. str | None,
  3431. Doc(
  3432. """
  3433. A summary for the *path operation*.
  3434. It will be added to the generated OpenAPI (e.g. visible at `/docs`).
  3435. Read more about it in the
  3436. [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).
  3437. """
  3438. ),
  3439. ] = None,
  3440. description: Annotated[
  3441. str | None,
  3442. Doc(
  3443. """
  3444. A description for the *path operation*.
  3445. If not provided, it will be extracted automatically from the docstring
  3446. of the *path operation function*.
  3447. It can contain Markdown.
  3448. It will be added to the generated OpenAPI (e.g. visible at `/docs`).
  3449. Read more about it in the
  3450. [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).
  3451. """
  3452. ),
  3453. ] = None,
  3454. response_description: Annotated[
  3455. str,
  3456. Doc(
  3457. """
  3458. The description for the default response.
  3459. It will be added to the generated OpenAPI (e.g. visible at `/docs`).
  3460. """
  3461. ),
  3462. ] = "Successful Response",
  3463. responses: Annotated[
  3464. dict[int | str, dict[str, Any]] | None,
  3465. Doc(
  3466. """
  3467. Additional responses that could be returned by this *path operation*.
  3468. It will be added to the generated OpenAPI (e.g. visible at `/docs`).
  3469. """
  3470. ),
  3471. ] = None,
  3472. deprecated: Annotated[
  3473. bool | None,
  3474. Doc(
  3475. """
  3476. Mark this *path operation* as deprecated.
  3477. It will be added to the generated OpenAPI (e.g. visible at `/docs`).
  3478. """
  3479. ),
  3480. ] = None,
  3481. operation_id: Annotated[
  3482. str | None,
  3483. Doc(
  3484. """
  3485. Custom operation ID to be used by this *path operation*.
  3486. By default, it is generated automatically.
  3487. If you provide a custom operation ID, you need to make sure it is
  3488. unique for the whole API.
  3489. You can customize the
  3490. operation ID generation with the parameter
  3491. `generate_unique_id_function` in the `FastAPI` class.
  3492. Read more about it in the
  3493. [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).
  3494. """
  3495. ),
  3496. ] = None,
  3497. response_model_include: Annotated[
  3498. IncEx | None,
  3499. Doc(
  3500. """
  3501. Configuration passed to Pydantic to include only certain fields in the
  3502. response data.
  3503. Read more about it in the
  3504. [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).
  3505. """
  3506. ),
  3507. ] = None,
  3508. response_model_exclude: Annotated[
  3509. IncEx | None,
  3510. Doc(
  3511. """
  3512. Configuration passed to Pydantic to exclude certain fields in the
  3513. response data.
  3514. Read more about it in the
  3515. [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).
  3516. """
  3517. ),
  3518. ] = None,
  3519. response_model_by_alias: Annotated[
  3520. bool,
  3521. Doc(
  3522. """
  3523. Configuration passed to Pydantic to define if the response model
  3524. should be serialized by alias when an alias is used.
  3525. Read more about it in the
  3526. [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).
  3527. """
  3528. ),
  3529. ] = True,
  3530. response_model_exclude_unset: Annotated[
  3531. bool,
  3532. Doc(
  3533. """
  3534. Configuration passed to Pydantic to define if the response data
  3535. should have all the fields, including the ones that were not set and
  3536. have their default values. This is different from
  3537. `response_model_exclude_defaults` in that if the fields are set,
  3538. they will be included in the response, even if the value is the same
  3539. as the default.
  3540. When `True`, default values are omitted from the response.
  3541. Read more about it in the
  3542. [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).
  3543. """
  3544. ),
  3545. ] = False,
  3546. response_model_exclude_defaults: Annotated[
  3547. bool,
  3548. Doc(
  3549. """
  3550. Configuration passed to Pydantic to define if the response data
  3551. should have all the fields, including the ones that have the same value
  3552. as the default. This is different from `response_model_exclude_unset`
  3553. in that if the fields are set but contain the same default values,
  3554. they will be excluded from the response.
  3555. When `True`, default values are omitted from the response.
  3556. Read more about it in the
  3557. [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).
  3558. """
  3559. ),
  3560. ] = False,
  3561. response_model_exclude_none: Annotated[
  3562. bool,
  3563. Doc(
  3564. """
  3565. Configuration passed to Pydantic to define if the response data should
  3566. exclude fields set to `None`.
  3567. This is much simpler (less smart) than `response_model_exclude_unset`
  3568. and `response_model_exclude_defaults`. You probably want to use one of
  3569. those two instead of this one, as those allow returning `None` values
  3570. when it makes sense.
  3571. Read more about it in the
  3572. [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none).
  3573. """
  3574. ),
  3575. ] = False,
  3576. include_in_schema: Annotated[
  3577. bool,
  3578. Doc(
  3579. """
  3580. Include this *path operation* in the generated OpenAPI schema.
  3581. This affects the generated OpenAPI (e.g. visible at `/docs`).
  3582. Read more about it in the
  3583. [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-parameters-from-openapi).
  3584. """
  3585. ),
  3586. ] = True,
  3587. response_class: Annotated[
  3588. type[Response],
  3589. Doc(
  3590. """
  3591. Response class to be used for this *path operation*.
  3592. This will not be used if you return a response directly.
  3593. Read more about it in the
  3594. [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse).
  3595. """
  3596. ),
  3597. ] = Default(JSONResponse),
  3598. name: Annotated[
  3599. str | None,
  3600. Doc(
  3601. """
  3602. Name for this *path operation*. Only used internally.
  3603. """
  3604. ),
  3605. ] = None,
  3606. callbacks: Annotated[
  3607. list[BaseRoute] | None,
  3608. Doc(
  3609. """
  3610. List of *path operations* that will be used as OpenAPI callbacks.
  3611. This is only for OpenAPI documentation, the callbacks won't be used
  3612. directly.
  3613. It will be added to the generated OpenAPI (e.g. visible at `/docs`).
  3614. Read more about it in the
  3615. [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/).
  3616. """
  3617. ),
  3618. ] = None,
  3619. openapi_extra: Annotated[
  3620. dict[str, Any] | None,
  3621. Doc(
  3622. """
  3623. Extra metadata to be included in the OpenAPI schema for this *path
  3624. operation*.
  3625. Read more about it in the
  3626. [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema).
  3627. """
  3628. ),
  3629. ] = None,
  3630. generate_unique_id_function: Annotated[
  3631. Callable[[routing.APIRoute], str],
  3632. Doc(
  3633. """
  3634. Customize the function used to generate unique IDs for the *path
  3635. operations* shown in the generated OpenAPI.
  3636. This is particularly useful when automatically generating clients or
  3637. SDKs for your API.
  3638. Read more about it in the
  3639. [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).
  3640. """
  3641. ),
  3642. ] = Default(generate_unique_id),
  3643. ) -> Callable[[DecoratedCallable], DecoratedCallable]:
  3644. """
  3645. Add a *path operation* using an HTTP PATCH operation.
  3646. ## Example
  3647. ```python
  3648. from fastapi import FastAPI
  3649. from pydantic import BaseModel
  3650. class Item(BaseModel):
  3651. name: str
  3652. description: str | None = None
  3653. app = FastAPI()
  3654. @app.patch("/items/")
  3655. def update_item(item: Item):
  3656. return {"message": "Item updated in place"}
  3657. ```
  3658. """
  3659. return self.router.patch(
  3660. path,
  3661. response_model=response_model,
  3662. status_code=status_code,
  3663. tags=tags,
  3664. dependencies=dependencies,
  3665. summary=summary,
  3666. description=description,
  3667. response_description=response_description,
  3668. responses=responses,
  3669. deprecated=deprecated,
  3670. operation_id=operation_id,
  3671. response_model_include=response_model_include,
  3672. response_model_exclude=response_model_exclude,
  3673. response_model_by_alias=response_model_by_alias,
  3674. response_model_exclude_unset=response_model_exclude_unset,
  3675. response_model_exclude_defaults=response_model_exclude_defaults,
  3676. response_model_exclude_none=response_model_exclude_none,
  3677. include_in_schema=include_in_schema,
  3678. response_class=response_class,
  3679. name=name,
  3680. callbacks=callbacks,
  3681. openapi_extra=openapi_extra,
  3682. generate_unique_id_function=generate_unique_id_function,
  3683. )
  3684. def trace(
  3685. self,
  3686. path: Annotated[
  3687. str,
  3688. Doc(
  3689. """
  3690. The URL path to be used for this *path operation*.
  3691. For example, in `http://example.com/items`, the path is `/items`.
  3692. """
  3693. ),
  3694. ],
  3695. *,
  3696. response_model: Annotated[
  3697. Any,
  3698. Doc(
  3699. """
  3700. The type to use for the response.
  3701. It could be any valid Pydantic *field* type. So, it doesn't have to
  3702. be a Pydantic model, it could be other things, like a `list`, `dict`,
  3703. etc.
  3704. It will be used for:
  3705. * Documentation: the generated OpenAPI (and the UI at `/docs`) will
  3706. show it as the response (JSON Schema).
  3707. * Serialization: you could return an arbitrary object and the
  3708. `response_model` would be used to serialize that object into the
  3709. corresponding JSON.
  3710. * Filtering: the JSON sent to the client will only contain the data
  3711. (fields) defined in the `response_model`. If you returned an object
  3712. that contains an attribute `password` but the `response_model` does
  3713. not include that field, the JSON sent to the client would not have
  3714. that `password`.
  3715. * Validation: whatever you return will be serialized with the
  3716. `response_model`, converting any data as necessary to generate the
  3717. corresponding JSON. But if the data in the object returned is not
  3718. valid, that would mean a violation of the contract with the client,
  3719. so it's an error from the API developer. So, FastAPI will raise an
  3720. error and return a 500 error code (Internal Server Error).
  3721. Read more about it in the
  3722. [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/).
  3723. """
  3724. ),
  3725. ] = Default(None),
  3726. status_code: Annotated[
  3727. int | None,
  3728. Doc(
  3729. """
  3730. The default status code to be used for the response.
  3731. You could override the status code by returning a response directly.
  3732. Read more about it in the
  3733. [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/).
  3734. """
  3735. ),
  3736. ] = None,
  3737. tags: Annotated[
  3738. list[str | Enum] | None,
  3739. Doc(
  3740. """
  3741. A list of tags to be applied to the *path operation*.
  3742. It will be added to the generated OpenAPI (e.g. visible at `/docs`).
  3743. Read more about it in the
  3744. [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#tags).
  3745. """
  3746. ),
  3747. ] = None,
  3748. dependencies: Annotated[
  3749. Sequence[Depends] | None,
  3750. Doc(
  3751. """
  3752. A list of dependencies (using `Depends()`) to be applied to the
  3753. *path operation*.
  3754. Read more about it in the
  3755. [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/).
  3756. """
  3757. ),
  3758. ] = None,
  3759. summary: Annotated[
  3760. str | None,
  3761. Doc(
  3762. """
  3763. A summary for the *path operation*.
  3764. It will be added to the generated OpenAPI (e.g. visible at `/docs`).
  3765. Read more about it in the
  3766. [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).
  3767. """
  3768. ),
  3769. ] = None,
  3770. description: Annotated[
  3771. str | None,
  3772. Doc(
  3773. """
  3774. A description for the *path operation*.
  3775. If not provided, it will be extracted automatically from the docstring
  3776. of the *path operation function*.
  3777. It can contain Markdown.
  3778. It will be added to the generated OpenAPI (e.g. visible at `/docs`).
  3779. Read more about it in the
  3780. [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).
  3781. """
  3782. ),
  3783. ] = None,
  3784. response_description: Annotated[
  3785. str,
  3786. Doc(
  3787. """
  3788. The description for the default response.
  3789. It will be added to the generated OpenAPI (e.g. visible at `/docs`).
  3790. """
  3791. ),
  3792. ] = "Successful Response",
  3793. responses: Annotated[
  3794. dict[int | str, dict[str, Any]] | None,
  3795. Doc(
  3796. """
  3797. Additional responses that could be returned by this *path operation*.
  3798. It will be added to the generated OpenAPI (e.g. visible at `/docs`).
  3799. """
  3800. ),
  3801. ] = None,
  3802. deprecated: Annotated[
  3803. bool | None,
  3804. Doc(
  3805. """
  3806. Mark this *path operation* as deprecated.
  3807. It will be added to the generated OpenAPI (e.g. visible at `/docs`).
  3808. """
  3809. ),
  3810. ] = None,
  3811. operation_id: Annotated[
  3812. str | None,
  3813. Doc(
  3814. """
  3815. Custom operation ID to be used by this *path operation*.
  3816. By default, it is generated automatically.
  3817. If you provide a custom operation ID, you need to make sure it is
  3818. unique for the whole API.
  3819. You can customize the
  3820. operation ID generation with the parameter
  3821. `generate_unique_id_function` in the `FastAPI` class.
  3822. Read more about it in the
  3823. [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).
  3824. """
  3825. ),
  3826. ] = None,
  3827. response_model_include: Annotated[
  3828. IncEx | None,
  3829. Doc(
  3830. """
  3831. Configuration passed to Pydantic to include only certain fields in the
  3832. response data.
  3833. Read more about it in the
  3834. [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).
  3835. """
  3836. ),
  3837. ] = None,
  3838. response_model_exclude: Annotated[
  3839. IncEx | None,
  3840. Doc(
  3841. """
  3842. Configuration passed to Pydantic to exclude certain fields in the
  3843. response data.
  3844. Read more about it in the
  3845. [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).
  3846. """
  3847. ),
  3848. ] = None,
  3849. response_model_by_alias: Annotated[
  3850. bool,
  3851. Doc(
  3852. """
  3853. Configuration passed to Pydantic to define if the response model
  3854. should be serialized by alias when an alias is used.
  3855. Read more about it in the
  3856. [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).
  3857. """
  3858. ),
  3859. ] = True,
  3860. response_model_exclude_unset: Annotated[
  3861. bool,
  3862. Doc(
  3863. """
  3864. Configuration passed to Pydantic to define if the response data
  3865. should have all the fields, including the ones that were not set and
  3866. have their default values. This is different from
  3867. `response_model_exclude_defaults` in that if the fields are set,
  3868. they will be included in the response, even if the value is the same
  3869. as the default.
  3870. When `True`, default values are omitted from the response.
  3871. Read more about it in the
  3872. [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).
  3873. """
  3874. ),
  3875. ] = False,
  3876. response_model_exclude_defaults: Annotated[
  3877. bool,
  3878. Doc(
  3879. """
  3880. Configuration passed to Pydantic to define if the response data
  3881. should have all the fields, including the ones that have the same value
  3882. as the default. This is different from `response_model_exclude_unset`
  3883. in that if the fields are set but contain the same default values,
  3884. they will be excluded from the response.
  3885. When `True`, default values are omitted from the response.
  3886. Read more about it in the
  3887. [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).
  3888. """
  3889. ),
  3890. ] = False,
  3891. response_model_exclude_none: Annotated[
  3892. bool,
  3893. Doc(
  3894. """
  3895. Configuration passed to Pydantic to define if the response data should
  3896. exclude fields set to `None`.
  3897. This is much simpler (less smart) than `response_model_exclude_unset`
  3898. and `response_model_exclude_defaults`. You probably want to use one of
  3899. those two instead of this one, as those allow returning `None` values
  3900. when it makes sense.
  3901. Read more about it in the
  3902. [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none).
  3903. """
  3904. ),
  3905. ] = False,
  3906. include_in_schema: Annotated[
  3907. bool,
  3908. Doc(
  3909. """
  3910. Include this *path operation* in the generated OpenAPI schema.
  3911. This affects the generated OpenAPI (e.g. visible at `/docs`).
  3912. Read more about it in the
  3913. [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-parameters-from-openapi).
  3914. """
  3915. ),
  3916. ] = True,
  3917. response_class: Annotated[
  3918. type[Response],
  3919. Doc(
  3920. """
  3921. Response class to be used for this *path operation*.
  3922. This will not be used if you return a response directly.
  3923. Read more about it in the
  3924. [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse).
  3925. """
  3926. ),
  3927. ] = Default(JSONResponse),
  3928. name: Annotated[
  3929. str | None,
  3930. Doc(
  3931. """
  3932. Name for this *path operation*. Only used internally.
  3933. """
  3934. ),
  3935. ] = None,
  3936. callbacks: Annotated[
  3937. list[BaseRoute] | None,
  3938. Doc(
  3939. """
  3940. List of *path operations* that will be used as OpenAPI callbacks.
  3941. This is only for OpenAPI documentation, the callbacks won't be used
  3942. directly.
  3943. It will be added to the generated OpenAPI (e.g. visible at `/docs`).
  3944. Read more about it in the
  3945. [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/).
  3946. """
  3947. ),
  3948. ] = None,
  3949. openapi_extra: Annotated[
  3950. dict[str, Any] | None,
  3951. Doc(
  3952. """
  3953. Extra metadata to be included in the OpenAPI schema for this *path
  3954. operation*.
  3955. Read more about it in the
  3956. [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema).
  3957. """
  3958. ),
  3959. ] = None,
  3960. generate_unique_id_function: Annotated[
  3961. Callable[[routing.APIRoute], str],
  3962. Doc(
  3963. """
  3964. Customize the function used to generate unique IDs for the *path
  3965. operations* shown in the generated OpenAPI.
  3966. This is particularly useful when automatically generating clients or
  3967. SDKs for your API.
  3968. Read more about it in the
  3969. [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).
  3970. """
  3971. ),
  3972. ] = Default(generate_unique_id),
  3973. ) -> Callable[[DecoratedCallable], DecoratedCallable]:
  3974. """
  3975. Add a *path operation* using an HTTP TRACE operation.
  3976. ## Example
  3977. ```python
  3978. from fastapi import FastAPI
  3979. app = FastAPI()
  3980. @app.trace("/items/{item_id}")
  3981. def trace_item(item_id: str):
  3982. return None
  3983. ```
  3984. """
  3985. return self.router.trace(
  3986. path,
  3987. response_model=response_model,
  3988. status_code=status_code,
  3989. tags=tags,
  3990. dependencies=dependencies,
  3991. summary=summary,
  3992. description=description,
  3993. response_description=response_description,
  3994. responses=responses,
  3995. deprecated=deprecated,
  3996. operation_id=operation_id,
  3997. response_model_include=response_model_include,
  3998. response_model_exclude=response_model_exclude,
  3999. response_model_by_alias=response_model_by_alias,
  4000. response_model_exclude_unset=response_model_exclude_unset,
  4001. response_model_exclude_defaults=response_model_exclude_defaults,
  4002. response_model_exclude_none=response_model_exclude_none,
  4003. include_in_schema=include_in_schema,
  4004. response_class=response_class,
  4005. name=name,
  4006. callbacks=callbacks,
  4007. openapi_extra=openapi_extra,
  4008. generate_unique_id_function=generate_unique_id_function,
  4009. )
  4010. def websocket_route(
  4011. self, path: str, name: str | None = None
  4012. ) -> Callable[[DecoratedCallable], DecoratedCallable]:
  4013. def decorator(func: DecoratedCallable) -> DecoratedCallable:
  4014. self.router.add_websocket_route(path, func, name=name)
  4015. return func
  4016. return decorator
  4017. @deprecated(
  4018. """
  4019. on_event is deprecated, use lifespan event handlers instead.
  4020. Read more about it in the
  4021. [FastAPI docs for Lifespan Events](https://fastapi.tiangolo.com/advanced/events/).
  4022. """
  4023. )
  4024. def on_event(
  4025. self,
  4026. event_type: Annotated[
  4027. str,
  4028. Doc(
  4029. """
  4030. The type of event. `startup` or `shutdown`.
  4031. """
  4032. ),
  4033. ],
  4034. ) -> Callable[[DecoratedCallable], DecoratedCallable]:
  4035. """
  4036. Add an event handler for the application.
  4037. `on_event` is deprecated, use `lifespan` event handlers instead.
  4038. Read more about it in the
  4039. [FastAPI docs for Lifespan Events](https://fastapi.tiangolo.com/advanced/events/#alternative-events-deprecated).
  4040. """
  4041. return self.router.on_event(event_type) # ty: ignore[deprecated]
  4042. def middleware(
  4043. self,
  4044. middleware_type: Annotated[
  4045. str,
  4046. Doc(
  4047. """
  4048. The type of middleware. Currently only supports `http`.
  4049. """
  4050. ),
  4051. ],
  4052. ) -> Callable[[DecoratedCallable], DecoratedCallable]:
  4053. """
  4054. Add a middleware to the application.
  4055. Read more about it in the
  4056. [FastAPI docs for Middleware](https://fastapi.tiangolo.com/tutorial/middleware/).
  4057. ## Example
  4058. ```python
  4059. import time
  4060. from typing import Awaitable, Callable
  4061. from fastapi import FastAPI, Request, Response
  4062. app = FastAPI()
  4063. @app.middleware("http")
  4064. async def add_process_time_header(
  4065. request: Request, call_next: Callable[[Request], Awaitable[Response]]
  4066. ) -> Response:
  4067. start_time = time.time()
  4068. response = await call_next(request)
  4069. process_time = time.time() - start_time
  4070. response.headers["X-Process-Time"] = str(process_time)
  4071. return response
  4072. ```
  4073. """
  4074. def decorator(func: DecoratedCallable) -> DecoratedCallable:
  4075. self.add_middleware(BaseHTTPMiddleware, dispatch=func)
  4076. return func
  4077. return decorator
  4078. def exception_handler(
  4079. self,
  4080. exc_class_or_status_code: Annotated[
  4081. int | type[Exception],
  4082. Doc(
  4083. """
  4084. The Exception class this would handle, or a status code.
  4085. """
  4086. ),
  4087. ],
  4088. ) -> Callable[[DecoratedCallable], DecoratedCallable]:
  4089. """
  4090. Add an exception handler to the app.
  4091. Read more about it in the
  4092. [FastAPI docs for Handling Errors](https://fastapi.tiangolo.com/tutorial/handling-errors/).
  4093. ## Example
  4094. ```python
  4095. from fastapi import FastAPI, Request
  4096. from fastapi.responses import JSONResponse
  4097. class UnicornException(Exception):
  4098. def __init__(self, name: str):
  4099. self.name = name
  4100. app = FastAPI()
  4101. @app.exception_handler(UnicornException)
  4102. async def unicorn_exception_handler(request: Request, exc: UnicornException):
  4103. return JSONResponse(
  4104. status_code=418,
  4105. content={"message": f"Oops! {exc.name} did something. There goes a rainbow..."},
  4106. )
  4107. ```
  4108. """
  4109. def decorator(func: DecoratedCallable) -> DecoratedCallable:
  4110. self.add_exception_handler(exc_class_or_status_code, func)
  4111. return func
  4112. return decorator