applications.py 179 KB

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