routing.py 193 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956
  1. import contextlib
  2. import email.message
  3. import functools
  4. import inspect
  5. import json
  6. import types
  7. from collections.abc import (
  8. AsyncIterator,
  9. Awaitable,
  10. Callable,
  11. Collection,
  12. Coroutine,
  13. Generator,
  14. Iterator,
  15. Mapping,
  16. Sequence,
  17. )
  18. from contextlib import (
  19. AbstractAsyncContextManager,
  20. AbstractContextManager,
  21. AsyncExitStack,
  22. asynccontextmanager,
  23. )
  24. from enum import Enum, IntEnum
  25. from typing import (
  26. Annotated,
  27. Any,
  28. TypeVar,
  29. cast,
  30. )
  31. import anyio
  32. from annotated_doc import Doc
  33. from anyio.abc import ObjectReceiveStream
  34. from fastapi import params
  35. from fastapi._compat import (
  36. ModelField,
  37. Undefined,
  38. lenient_issubclass,
  39. )
  40. from fastapi.datastructures import Default, DefaultPlaceholder
  41. from fastapi.dependencies.models import Dependant
  42. from fastapi.dependencies.utils import (
  43. _should_embed_body_fields,
  44. get_body_field,
  45. get_dependant,
  46. get_flat_dependant,
  47. get_parameterless_sub_dependant,
  48. get_stream_item_type,
  49. get_typed_return_annotation,
  50. solve_dependencies,
  51. )
  52. from fastapi.encoders import jsonable_encoder
  53. from fastapi.exceptions import (
  54. EndpointContext,
  55. FastAPIError,
  56. RequestValidationError,
  57. ResponseValidationError,
  58. WebSocketRequestValidationError,
  59. )
  60. from fastapi.sse import (
  61. _PING_INTERVAL,
  62. KEEPALIVE_COMMENT,
  63. EventSourceResponse,
  64. ServerSentEvent,
  65. format_sse_event,
  66. )
  67. from fastapi.types import DecoratedCallable, IncEx
  68. from fastapi.utils import (
  69. create_model_field,
  70. generate_unique_id,
  71. get_value_or_default,
  72. is_body_allowed_for_status_code,
  73. )
  74. from starlette import routing
  75. from starlette._exception_handler import wrap_app_handling_exceptions
  76. from starlette._utils import is_async_callable
  77. from starlette.concurrency import iterate_in_threadpool, run_in_threadpool
  78. from starlette.datastructures import FormData
  79. from starlette.exceptions import HTTPException
  80. from starlette.requests import Request
  81. from starlette.responses import JSONResponse, Response, StreamingResponse
  82. from starlette.routing import (
  83. BaseRoute,
  84. Match,
  85. compile_path,
  86. get_name,
  87. )
  88. from starlette.routing import Mount as Mount # noqa
  89. from starlette.types import AppType, ASGIApp, Lifespan, Receive, Scope, Send
  90. from starlette.websockets import WebSocket
  91. from typing_extensions import deprecated
  92. # Copy of starlette.routing.request_response modified to include the
  93. # dependencies' AsyncExitStack
  94. def request_response(
  95. func: Callable[[Request], Awaitable[Response] | Response],
  96. ) -> ASGIApp:
  97. """
  98. Takes a function or coroutine `func(request) -> response`,
  99. and returns an ASGI application.
  100. """
  101. f: Callable[[Request], Awaitable[Response]] = (
  102. func # type: ignore[assignment] # ty: ignore[unused-ignore-comment]
  103. if is_async_callable(func)
  104. else functools.partial(run_in_threadpool, func) # type: ignore[call-arg] # ty: ignore[unused-ignore-comment]
  105. ) # ty: ignore[invalid-assignment]
  106. async def app(scope: Scope, receive: Receive, send: Send) -> None:
  107. request = Request(scope, receive, send)
  108. async def app(scope: Scope, receive: Receive, send: Send) -> None:
  109. # Starts customization
  110. response_awaited = False
  111. async with AsyncExitStack() as request_stack:
  112. scope["fastapi_inner_astack"] = request_stack
  113. async with AsyncExitStack() as function_stack:
  114. scope["fastapi_function_astack"] = function_stack
  115. response = await f(request)
  116. await response(scope, receive, send)
  117. # Continues customization
  118. response_awaited = True
  119. if not response_awaited:
  120. raise FastAPIError(
  121. "Response not awaited. There's a high chance that the "
  122. "application code is raising an exception and a dependency with yield "
  123. "has a block with a bare except, or a block with except Exception, "
  124. "and is not raising the exception again. Read more about it in the "
  125. "docs: https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-with-yield/#dependencies-with-yield-and-except"
  126. )
  127. # Same as in Starlette
  128. await wrap_app_handling_exceptions(app, request)(scope, receive, send)
  129. return app
  130. # Copy of starlette.routing.websocket_session modified to include the
  131. # dependencies' AsyncExitStack
  132. def websocket_session(
  133. func: Callable[[WebSocket], Awaitable[None]],
  134. ) -> ASGIApp:
  135. """
  136. Takes a coroutine `func(session)`, and returns an ASGI application.
  137. """
  138. # assert asyncio.iscoroutinefunction(func), "WebSocket endpoints must be async"
  139. async def app(scope: Scope, receive: Receive, send: Send) -> None:
  140. session = WebSocket(scope, receive=receive, send=send)
  141. async def app(scope: Scope, receive: Receive, send: Send) -> None:
  142. async with AsyncExitStack() as request_stack:
  143. scope["fastapi_inner_astack"] = request_stack
  144. async with AsyncExitStack() as function_stack:
  145. scope["fastapi_function_astack"] = function_stack
  146. await func(session)
  147. # Same as in Starlette
  148. await wrap_app_handling_exceptions(app, session)(scope, receive, send)
  149. return app
  150. _T = TypeVar("_T")
  151. # Vendored from starlette.routing to avoid importing private symbols
  152. class _AsyncLiftContextManager(AbstractAsyncContextManager[_T]):
  153. """
  154. Wraps a synchronous context manager to make it async.
  155. This is vendored from Starlette to avoid importing private symbols.
  156. """
  157. def __init__(self, cm: AbstractContextManager[_T]) -> None:
  158. self._cm = cm
  159. async def __aenter__(self) -> _T:
  160. return self._cm.__enter__()
  161. async def __aexit__(
  162. self,
  163. exc_type: type[BaseException] | None,
  164. exc_value: BaseException | None,
  165. traceback: types.TracebackType | None,
  166. ) -> bool | None:
  167. return self._cm.__exit__(exc_type, exc_value, traceback)
  168. # Vendored from starlette.routing to avoid importing private symbols
  169. def _wrap_gen_lifespan_context(
  170. lifespan_context: Callable[[Any], Generator[Any, Any, Any]],
  171. ) -> Callable[[Any], AbstractAsyncContextManager[Any]]:
  172. """
  173. Wrap a generator-based lifespan context into an async context manager.
  174. This is vendored from Starlette to avoid importing private symbols.
  175. """
  176. cmgr = contextlib.contextmanager(lifespan_context)
  177. @functools.wraps(cmgr)
  178. def wrapper(app: Any) -> _AsyncLiftContextManager[Any]:
  179. return _AsyncLiftContextManager(cmgr(app))
  180. return wrapper
  181. def _merge_lifespan_context(
  182. original_context: Lifespan[Any], nested_context: Lifespan[Any]
  183. ) -> Lifespan[Any]:
  184. @asynccontextmanager
  185. async def merged_lifespan(
  186. app: AppType,
  187. ) -> AsyncIterator[Mapping[str, Any] | None]:
  188. async with original_context(app) as maybe_original_state:
  189. async with nested_context(app) as maybe_nested_state:
  190. if maybe_nested_state is None and maybe_original_state is None:
  191. yield None # old ASGI compatibility
  192. else:
  193. yield {**(maybe_nested_state or {}), **(maybe_original_state or {})}
  194. return merged_lifespan # type: ignore[return-value]
  195. class _DefaultLifespan:
  196. """
  197. Default lifespan context manager that runs on_startup and on_shutdown handlers.
  198. This is a copy of the Starlette _DefaultLifespan class that was removed
  199. in Starlette. FastAPI keeps it to maintain backward compatibility with
  200. on_startup and on_shutdown event handlers.
  201. Ref: https://github.com/Kludex/starlette/pull/3117
  202. """
  203. def __init__(self, router: "APIRouter") -> None:
  204. self._router = router
  205. async def __aenter__(self) -> None:
  206. await self._router._startup()
  207. async def __aexit__(self, *exc_info: object) -> None:
  208. await self._router._shutdown()
  209. def __call__(self: _T, app: object) -> _T:
  210. return self
  211. # Cache for endpoint context to avoid re-extracting on every request
  212. _endpoint_context_cache: dict[int, EndpointContext] = {}
  213. def _extract_endpoint_context(func: Any) -> EndpointContext:
  214. """Extract endpoint context with caching to avoid repeated file I/O."""
  215. func_id = id(func)
  216. if func_id in _endpoint_context_cache:
  217. return _endpoint_context_cache[func_id]
  218. try:
  219. ctx: EndpointContext = {}
  220. if (source_file := inspect.getsourcefile(func)) is not None:
  221. ctx["file"] = source_file
  222. if (line_number := inspect.getsourcelines(func)[1]) is not None:
  223. ctx["line"] = line_number
  224. if (func_name := getattr(func, "__name__", None)) is not None:
  225. ctx["function"] = func_name
  226. except Exception:
  227. ctx = EndpointContext()
  228. _endpoint_context_cache[func_id] = ctx
  229. return ctx
  230. async def serialize_response(
  231. *,
  232. field: ModelField | None = None,
  233. response_content: Any,
  234. include: IncEx | None = None,
  235. exclude: IncEx | None = None,
  236. by_alias: bool = True,
  237. exclude_unset: bool = False,
  238. exclude_defaults: bool = False,
  239. exclude_none: bool = False,
  240. is_coroutine: bool = True,
  241. endpoint_ctx: EndpointContext | None = None,
  242. dump_json: bool = False,
  243. ) -> Any:
  244. if field:
  245. if is_coroutine:
  246. value, errors = field.validate(response_content, {}, loc=("response",))
  247. else:
  248. value, errors = await run_in_threadpool(
  249. field.validate, response_content, {}, loc=("response",)
  250. )
  251. if errors:
  252. ctx = endpoint_ctx or EndpointContext()
  253. raise ResponseValidationError(
  254. errors=errors,
  255. body=response_content,
  256. endpoint_ctx=ctx,
  257. )
  258. serializer = field.serialize_json if dump_json else field.serialize
  259. return serializer(
  260. value,
  261. include=include,
  262. exclude=exclude,
  263. by_alias=by_alias,
  264. exclude_unset=exclude_unset,
  265. exclude_defaults=exclude_defaults,
  266. exclude_none=exclude_none,
  267. )
  268. else:
  269. return jsonable_encoder(response_content)
  270. async def run_endpoint_function(
  271. *, dependant: Dependant, values: dict[str, Any], is_coroutine: bool
  272. ) -> Any:
  273. # Only called by get_request_handler. Has been split into its own function to
  274. # facilitate profiling endpoints, since inner functions are harder to profile.
  275. assert dependant.call is not None, "dependant.call must be a function"
  276. if is_coroutine:
  277. return await dependant.call(**values)
  278. else:
  279. return await run_in_threadpool(dependant.call, **values)
  280. def _build_response_args(
  281. *, status_code: int | None, solved_result: Any
  282. ) -> dict[str, Any]:
  283. response_args: dict[str, Any] = {
  284. "background": solved_result.background_tasks,
  285. }
  286. # If status_code was set, use it, otherwise use the default from the
  287. # response class, in the case of redirect it's 307
  288. current_status_code = (
  289. status_code if status_code else solved_result.response.status_code
  290. )
  291. if current_status_code is not None:
  292. response_args["status_code"] = current_status_code
  293. if solved_result.response.status_code:
  294. response_args["status_code"] = solved_result.response.status_code
  295. return response_args
  296. def get_request_handler(
  297. dependant: Dependant,
  298. body_field: ModelField | None = None,
  299. status_code: int | None = None,
  300. response_class: type[Response] | DefaultPlaceholder = Default(JSONResponse),
  301. response_field: ModelField | None = None,
  302. response_model_include: IncEx | None = None,
  303. response_model_exclude: IncEx | None = None,
  304. response_model_by_alias: bool = True,
  305. response_model_exclude_unset: bool = False,
  306. response_model_exclude_defaults: bool = False,
  307. response_model_exclude_none: bool = False,
  308. dependency_overrides_provider: Any | None = None,
  309. embed_body_fields: bool = False,
  310. strict_content_type: bool | DefaultPlaceholder = Default(True),
  311. stream_item_field: ModelField | None = None,
  312. is_json_stream: bool = False,
  313. ) -> Callable[[Request], Coroutine[Any, Any, Response]]:
  314. assert dependant.call is not None, "dependant.call must be a function"
  315. is_coroutine = dependant.is_coroutine_callable
  316. is_body_form = body_field and isinstance(body_field.field_info, params.Form)
  317. if isinstance(response_class, DefaultPlaceholder):
  318. actual_response_class: type[Response] = response_class.value
  319. else:
  320. actual_response_class = response_class
  321. is_sse_stream = lenient_issubclass(actual_response_class, EventSourceResponse)
  322. if isinstance(strict_content_type, DefaultPlaceholder):
  323. actual_strict_content_type: bool = strict_content_type.value
  324. else:
  325. actual_strict_content_type = strict_content_type
  326. async def app(request: Request) -> Response:
  327. response: Response | None = None
  328. file_stack = request.scope.get("fastapi_middleware_astack")
  329. assert isinstance(file_stack, AsyncExitStack), (
  330. "fastapi_middleware_astack not found in request scope"
  331. )
  332. # Extract endpoint context for error messages
  333. endpoint_ctx = (
  334. _extract_endpoint_context(dependant.call)
  335. if dependant.call
  336. else EndpointContext()
  337. )
  338. if dependant.path:
  339. # For mounted sub-apps, include the mount path prefix
  340. mount_path = request.scope.get("root_path", "").rstrip("/")
  341. endpoint_ctx["path"] = f"{request.method} {mount_path}{dependant.path}"
  342. # Read body and auto-close files
  343. try:
  344. body: Any = None
  345. if body_field:
  346. if is_body_form:
  347. body = await request.form()
  348. file_stack.push_async_callback(body.close)
  349. else:
  350. body_bytes = await request.body()
  351. if body_bytes:
  352. json_body: Any = Undefined
  353. content_type_value = request.headers.get("content-type")
  354. if not content_type_value:
  355. if not actual_strict_content_type:
  356. json_body = await request.json()
  357. else:
  358. message = email.message.Message()
  359. message["content-type"] = content_type_value
  360. if message.get_content_maintype() == "application":
  361. subtype = message.get_content_subtype()
  362. if subtype == "json" or subtype.endswith("+json"):
  363. json_body = await request.json()
  364. if json_body != Undefined:
  365. body = json_body
  366. else:
  367. body = body_bytes
  368. except json.JSONDecodeError as e:
  369. validation_error = RequestValidationError(
  370. [
  371. {
  372. "type": "json_invalid",
  373. "loc": ("body", e.pos),
  374. "msg": "JSON decode error",
  375. "input": {},
  376. "ctx": {"error": e.msg},
  377. }
  378. ],
  379. body=e.doc,
  380. endpoint_ctx=endpoint_ctx,
  381. )
  382. raise validation_error from e
  383. except HTTPException:
  384. # If a middleware raises an HTTPException, it should be raised again
  385. raise
  386. except Exception as e:
  387. http_error = HTTPException(
  388. status_code=400, detail="There was an error parsing the body"
  389. )
  390. raise http_error from e
  391. # Solve dependencies and run path operation function, auto-closing dependencies
  392. errors: list[Any] = []
  393. async_exit_stack = request.scope.get("fastapi_inner_astack")
  394. assert isinstance(async_exit_stack, AsyncExitStack), (
  395. "fastapi_inner_astack not found in request scope"
  396. )
  397. solved_result = await solve_dependencies(
  398. request=request,
  399. dependant=dependant,
  400. body=cast(dict[str, Any] | FormData | bytes | None, body),
  401. dependency_overrides_provider=dependency_overrides_provider,
  402. async_exit_stack=async_exit_stack,
  403. embed_body_fields=embed_body_fields,
  404. )
  405. errors = solved_result.errors
  406. assert dependant.call # For types
  407. if not errors:
  408. # Shared serializer for stream items (JSONL and SSE).
  409. # Validates against stream_item_field when set, then
  410. # serializes to JSON bytes.
  411. def _serialize_data(data: Any) -> bytes:
  412. if stream_item_field:
  413. value, errors_ = stream_item_field.validate(
  414. data, {}, loc=("response",)
  415. )
  416. if errors_:
  417. ctx = endpoint_ctx or EndpointContext()
  418. raise ResponseValidationError(
  419. errors=errors_,
  420. body=data,
  421. endpoint_ctx=ctx,
  422. )
  423. return stream_item_field.serialize_json(
  424. value,
  425. include=response_model_include,
  426. exclude=response_model_exclude,
  427. by_alias=response_model_by_alias,
  428. exclude_unset=response_model_exclude_unset,
  429. exclude_defaults=response_model_exclude_defaults,
  430. exclude_none=response_model_exclude_none,
  431. )
  432. else:
  433. data = jsonable_encoder(data)
  434. return json.dumps(data).encode("utf-8")
  435. if is_sse_stream:
  436. # Generator endpoint: stream as Server-Sent Events
  437. gen = dependant.call(**solved_result.values)
  438. def _serialize_sse_item(item: Any) -> bytes:
  439. if isinstance(item, ServerSentEvent):
  440. # User controls the event structure.
  441. # Serialize the data payload if present.
  442. # For ServerSentEvent items we skip stream_item_field
  443. # validation (the user may mix types intentionally).
  444. if item.raw_data is not None:
  445. data_str: str | None = item.raw_data
  446. elif item.data is not None:
  447. if hasattr(item.data, "model_dump_json"):
  448. data_str = item.data.model_dump_json()
  449. else:
  450. data_str = json.dumps(jsonable_encoder(item.data))
  451. else:
  452. data_str = None
  453. return format_sse_event(
  454. data_str=data_str,
  455. event=item.event,
  456. id=item.id,
  457. retry=item.retry,
  458. comment=item.comment,
  459. )
  460. else:
  461. # Plain object: validate + serialize via
  462. # stream_item_field (if set) and wrap in data field
  463. return format_sse_event(
  464. data_str=_serialize_data(item).decode("utf-8")
  465. )
  466. if dependant.is_async_gen_callable:
  467. sse_aiter: AsyncIterator[Any] = gen.__aiter__()
  468. else:
  469. sse_aiter = iterate_in_threadpool(gen)
  470. @asynccontextmanager
  471. async def _sse_producer_cm() -> AsyncIterator[
  472. ObjectReceiveStream[bytes]
  473. ]:
  474. # Use a memory stream to decouple generator iteration
  475. # from the keepalive timer. A producer task pulls items
  476. # from the generator independently, so
  477. # `anyio.fail_after` never wraps the generator's
  478. # `__anext__` directly - avoiding CancelledError that
  479. # would finalize the generator and also working for sync
  480. # generators running in a thread pool.
  481. #
  482. # This context manager is entered on the request-scoped
  483. # AsyncExitStack so its __aexit__ (which cancels the
  484. # task group) is called by the exit stack after the
  485. # streaming response completes — not by async generator
  486. # finalization via GeneratorExit.
  487. # Ref: https://peps.python.org/pep-0789/
  488. send_stream, receive_stream = anyio.create_memory_object_stream[
  489. bytes
  490. ](max_buffer_size=1)
  491. async def _producer() -> None:
  492. async with send_stream:
  493. async for raw_item in sse_aiter:
  494. await send_stream.send(_serialize_sse_item(raw_item))
  495. send_keepalive, receive_keepalive = (
  496. anyio.create_memory_object_stream[bytes](max_buffer_size=1)
  497. )
  498. async def _keepalive_inserter() -> None:
  499. """Read from the producer and forward to the output,
  500. inserting keepalive comments on timeout."""
  501. async with send_keepalive, receive_stream:
  502. try:
  503. while True:
  504. try:
  505. with anyio.fail_after(_PING_INTERVAL):
  506. data = await receive_stream.receive()
  507. await send_keepalive.send(data)
  508. except TimeoutError:
  509. await send_keepalive.send(KEEPALIVE_COMMENT)
  510. except anyio.EndOfStream:
  511. pass
  512. async with anyio.create_task_group() as tg:
  513. tg.start_soon(_producer)
  514. tg.start_soon(_keepalive_inserter)
  515. yield receive_keepalive
  516. tg.cancel_scope.cancel()
  517. # Enter the SSE context manager on the request-scoped
  518. # exit stack. The stack outlives the streaming response,
  519. # so __aexit__ runs via proper structured teardown, not
  520. # via GeneratorExit thrown into an async generator.
  521. sse_receive_stream = await async_exit_stack.enter_async_context(
  522. _sse_producer_cm()
  523. )
  524. # Ensure the receive stream is closed when the exit stack
  525. # unwinds, preventing ResourceWarning from __del__.
  526. async_exit_stack.push_async_callback(sse_receive_stream.aclose)
  527. async def _sse_with_checkpoints(
  528. stream: ObjectReceiveStream[bytes],
  529. ) -> AsyncIterator[bytes]:
  530. async for data in stream:
  531. yield data
  532. # Guarantee a checkpoint so cancellation can be
  533. # delivered even when the producer is faster than
  534. # the consumer and receive() never suspends.
  535. await anyio.sleep(0)
  536. sse_stream_content: AsyncIterator[bytes] | Iterator[bytes] = (
  537. _sse_with_checkpoints(sse_receive_stream)
  538. )
  539. response = StreamingResponse(
  540. sse_stream_content,
  541. media_type="text/event-stream",
  542. background=solved_result.background_tasks,
  543. )
  544. response.headers["Cache-Control"] = "no-cache"
  545. # For Nginx proxies to not buffer server sent events
  546. response.headers["X-Accel-Buffering"] = "no"
  547. response.headers.raw.extend(solved_result.response.headers.raw)
  548. elif is_json_stream:
  549. # Generator endpoint: stream as JSONL
  550. gen = dependant.call(**solved_result.values)
  551. def _serialize_item(item: Any) -> bytes:
  552. return _serialize_data(item) + b"\n"
  553. if dependant.is_async_gen_callable:
  554. async def _async_stream_jsonl() -> AsyncIterator[bytes]:
  555. async for item in gen:
  556. yield _serialize_item(item)
  557. # To allow for cancellation to trigger
  558. # Ref: https://github.com/fastapi/fastapi/issues/14680
  559. await anyio.sleep(0)
  560. jsonl_stream_content: AsyncIterator[bytes] | Iterator[bytes] = (
  561. _async_stream_jsonl()
  562. )
  563. else:
  564. def _sync_stream_jsonl() -> Iterator[bytes]:
  565. for item in gen: # ty: ignore[not-iterable]
  566. yield _serialize_item(item)
  567. jsonl_stream_content = _sync_stream_jsonl()
  568. response = StreamingResponse(
  569. jsonl_stream_content,
  570. media_type="application/jsonl",
  571. background=solved_result.background_tasks,
  572. )
  573. response.headers.raw.extend(solved_result.response.headers.raw)
  574. elif dependant.is_async_gen_callable or dependant.is_gen_callable:
  575. # Raw streaming with explicit response_class (e.g. StreamingResponse)
  576. gen = dependant.call(**solved_result.values)
  577. if dependant.is_async_gen_callable:
  578. async def _async_stream_raw(
  579. async_gen: AsyncIterator[Any],
  580. ) -> AsyncIterator[Any]:
  581. async for chunk in async_gen:
  582. yield chunk
  583. # To allow for cancellation to trigger
  584. # Ref: https://github.com/fastapi/fastapi/issues/14680
  585. await anyio.sleep(0)
  586. gen = _async_stream_raw(gen)
  587. response_args = _build_response_args(
  588. status_code=status_code, solved_result=solved_result
  589. )
  590. response = actual_response_class(content=gen, **response_args)
  591. response.headers.raw.extend(solved_result.response.headers.raw)
  592. else:
  593. raw_response = await run_endpoint_function(
  594. dependant=dependant,
  595. values=solved_result.values,
  596. is_coroutine=is_coroutine,
  597. )
  598. if isinstance(raw_response, Response):
  599. if raw_response.background is None:
  600. raw_response.background = solved_result.background_tasks
  601. response = raw_response
  602. else:
  603. response_args = _build_response_args(
  604. status_code=status_code, solved_result=solved_result
  605. )
  606. # Use the fast path (dump_json) when no custom response
  607. # class was set and a response field with a TypeAdapter
  608. # exists. Serializes directly to JSON bytes via Pydantic's
  609. # Rust core, skipping the intermediate Python dict +
  610. # json.dumps() step.
  611. use_dump_json = response_field is not None and isinstance(
  612. response_class, DefaultPlaceholder
  613. )
  614. content = await serialize_response(
  615. field=response_field,
  616. response_content=raw_response,
  617. include=response_model_include,
  618. exclude=response_model_exclude,
  619. by_alias=response_model_by_alias,
  620. exclude_unset=response_model_exclude_unset,
  621. exclude_defaults=response_model_exclude_defaults,
  622. exclude_none=response_model_exclude_none,
  623. is_coroutine=is_coroutine,
  624. endpoint_ctx=endpoint_ctx,
  625. dump_json=use_dump_json,
  626. )
  627. if use_dump_json:
  628. response = Response(
  629. content=content,
  630. media_type="application/json",
  631. **response_args,
  632. )
  633. else:
  634. response = actual_response_class(content, **response_args)
  635. if not is_body_allowed_for_status_code(response.status_code):
  636. response.body = b""
  637. response.headers.raw.extend(solved_result.response.headers.raw)
  638. if errors:
  639. validation_error = RequestValidationError(
  640. errors, body=body, endpoint_ctx=endpoint_ctx
  641. )
  642. raise validation_error
  643. # Return response
  644. assert response
  645. return response
  646. return app
  647. def get_websocket_app(
  648. dependant: Dependant,
  649. dependency_overrides_provider: Any | None = None,
  650. embed_body_fields: bool = False,
  651. ) -> Callable[[WebSocket], Coroutine[Any, Any, Any]]:
  652. async def app(websocket: WebSocket) -> None:
  653. endpoint_ctx = (
  654. _extract_endpoint_context(dependant.call)
  655. if dependant.call
  656. else EndpointContext()
  657. )
  658. if dependant.path:
  659. # For mounted sub-apps, include the mount path prefix
  660. mount_path = websocket.scope.get("root_path", "").rstrip("/")
  661. endpoint_ctx["path"] = f"WS {mount_path}{dependant.path}"
  662. async_exit_stack = websocket.scope.get("fastapi_inner_astack")
  663. assert isinstance(async_exit_stack, AsyncExitStack), (
  664. "fastapi_inner_astack not found in request scope"
  665. )
  666. solved_result = await solve_dependencies(
  667. request=websocket,
  668. dependant=dependant,
  669. dependency_overrides_provider=dependency_overrides_provider,
  670. async_exit_stack=async_exit_stack,
  671. embed_body_fields=embed_body_fields,
  672. )
  673. if solved_result.errors:
  674. raise WebSocketRequestValidationError(
  675. solved_result.errors,
  676. endpoint_ctx=endpoint_ctx,
  677. )
  678. assert dependant.call is not None, "dependant.call must be a function"
  679. await dependant.call(**solved_result.values)
  680. return app
  681. class APIWebSocketRoute(routing.WebSocketRoute):
  682. def __init__(
  683. self,
  684. path: str,
  685. endpoint: Callable[..., Any],
  686. *,
  687. name: str | None = None,
  688. dependencies: Sequence[params.Depends] | None = None,
  689. dependency_overrides_provider: Any | None = None,
  690. ) -> None:
  691. self.path = path
  692. self.endpoint = endpoint
  693. self.name = get_name(endpoint) if name is None else name
  694. self.dependencies = list(dependencies or [])
  695. self.path_regex, self.path_format, self.param_convertors = compile_path(path)
  696. self.dependant = get_dependant(
  697. path=self.path_format, call=self.endpoint, scope="function"
  698. )
  699. for depends in self.dependencies[::-1]:
  700. self.dependant.dependencies.insert(
  701. 0,
  702. get_parameterless_sub_dependant(depends=depends, path=self.path_format),
  703. )
  704. self._flat_dependant = get_flat_dependant(self.dependant)
  705. self._embed_body_fields = _should_embed_body_fields(
  706. self._flat_dependant.body_params
  707. )
  708. self.app = websocket_session(
  709. get_websocket_app(
  710. dependant=self.dependant,
  711. dependency_overrides_provider=dependency_overrides_provider,
  712. embed_body_fields=self._embed_body_fields,
  713. )
  714. )
  715. def matches(self, scope: Scope) -> tuple[Match, Scope]:
  716. match, child_scope = super().matches(scope)
  717. if match != Match.NONE:
  718. child_scope["route"] = self
  719. return match, child_scope
  720. class APIRoute(routing.Route):
  721. def __init__(
  722. self,
  723. path: str,
  724. endpoint: Callable[..., Any],
  725. *,
  726. response_model: Any = Default(None),
  727. status_code: int | None = None,
  728. tags: list[str | Enum] | None = None,
  729. dependencies: Sequence[params.Depends] | None = None,
  730. summary: str | None = None,
  731. description: str | None = None,
  732. response_description: str = "Successful Response",
  733. responses: dict[int | str, dict[str, Any]] | None = None,
  734. deprecated: bool | None = None,
  735. name: str | None = None,
  736. methods: set[str] | list[str] | None = None,
  737. operation_id: str | None = None,
  738. response_model_include: IncEx | None = None,
  739. response_model_exclude: IncEx | None = None,
  740. response_model_by_alias: bool = True,
  741. response_model_exclude_unset: bool = False,
  742. response_model_exclude_defaults: bool = False,
  743. response_model_exclude_none: bool = False,
  744. include_in_schema: bool = True,
  745. response_class: type[Response] | DefaultPlaceholder = Default(JSONResponse),
  746. dependency_overrides_provider: Any | None = None,
  747. callbacks: list[BaseRoute] | None = None,
  748. openapi_extra: dict[str, Any] | None = None,
  749. generate_unique_id_function: Callable[["APIRoute"], str]
  750. | DefaultPlaceholder = Default(generate_unique_id),
  751. strict_content_type: bool | DefaultPlaceholder = Default(True),
  752. ) -> None:
  753. self.path = path
  754. self.endpoint = endpoint
  755. self.stream_item_type: Any | None = None
  756. if isinstance(response_model, DefaultPlaceholder):
  757. return_annotation = get_typed_return_annotation(endpoint)
  758. if lenient_issubclass(return_annotation, Response):
  759. response_model = None
  760. else:
  761. stream_item = get_stream_item_type(return_annotation)
  762. if stream_item is not None:
  763. # Extract item type for JSONL or SSE streaming when
  764. # response_class is DefaultPlaceholder (JSONL) or
  765. # EventSourceResponse (SSE).
  766. # ServerSentEvent is excluded: it's a transport
  767. # wrapper, not a data model, so it shouldn't feed
  768. # into validation or OpenAPI schema generation.
  769. if (
  770. isinstance(response_class, DefaultPlaceholder)
  771. or lenient_issubclass(response_class, EventSourceResponse)
  772. ) and not lenient_issubclass(stream_item, ServerSentEvent):
  773. self.stream_item_type = stream_item
  774. response_model = None
  775. else:
  776. response_model = return_annotation
  777. self.response_model = response_model
  778. self.summary = summary
  779. self.response_description = response_description
  780. self.deprecated = deprecated
  781. self.operation_id = operation_id
  782. self.response_model_include = response_model_include
  783. self.response_model_exclude = response_model_exclude
  784. self.response_model_by_alias = response_model_by_alias
  785. self.response_model_exclude_unset = response_model_exclude_unset
  786. self.response_model_exclude_defaults = response_model_exclude_defaults
  787. self.response_model_exclude_none = response_model_exclude_none
  788. self.include_in_schema = include_in_schema
  789. self.response_class = response_class
  790. self.dependency_overrides_provider = dependency_overrides_provider
  791. self.callbacks = callbacks
  792. self.openapi_extra = openapi_extra
  793. self.generate_unique_id_function = generate_unique_id_function
  794. self.strict_content_type = strict_content_type
  795. self.tags = tags or []
  796. self.responses = responses or {}
  797. self.name = get_name(endpoint) if name is None else name
  798. self.path_regex, self.path_format, self.param_convertors = compile_path(path)
  799. if methods is None:
  800. methods = ["GET"]
  801. self.methods: set[str] = {method.upper() for method in methods}
  802. if isinstance(generate_unique_id_function, DefaultPlaceholder):
  803. current_generate_unique_id: Callable[[APIRoute], str] = (
  804. generate_unique_id_function.value
  805. )
  806. else:
  807. current_generate_unique_id = generate_unique_id_function
  808. self.unique_id = self.operation_id or current_generate_unique_id(self)
  809. # normalize enums e.g. http.HTTPStatus
  810. if isinstance(status_code, IntEnum):
  811. status_code = int(status_code)
  812. self.status_code = status_code
  813. if self.response_model:
  814. assert is_body_allowed_for_status_code(status_code), (
  815. f"Status code {status_code} must not have a response body"
  816. )
  817. response_name = "Response_" + self.unique_id
  818. self.response_field = create_model_field(
  819. name=response_name,
  820. type_=self.response_model,
  821. mode="serialization",
  822. )
  823. else:
  824. self.response_field = None # type: ignore # ty: ignore[unused-ignore-comment]
  825. if self.stream_item_type:
  826. stream_item_name = "StreamItem_" + self.unique_id
  827. self.stream_item_field: ModelField | None = create_model_field(
  828. name=stream_item_name,
  829. type_=self.stream_item_type,
  830. mode="serialization",
  831. )
  832. else:
  833. self.stream_item_field = None
  834. self.dependencies = list(dependencies or [])
  835. self.description = description or inspect.cleandoc(self.endpoint.__doc__ or "")
  836. # if a "form feed" character (page break) is found in the description text,
  837. # truncate description text to the content preceding the first "form feed"
  838. self.description = self.description.split("\f")[0].strip()
  839. response_fields = {}
  840. for additional_status_code, response in self.responses.items():
  841. assert isinstance(response, dict), "An additional response must be a dict"
  842. model = response.get("model")
  843. if model:
  844. assert is_body_allowed_for_status_code(additional_status_code), (
  845. f"Status code {additional_status_code} must not have a response body"
  846. )
  847. response_name = f"Response_{additional_status_code}_{self.unique_id}"
  848. response_field = create_model_field(
  849. name=response_name, type_=model, mode="serialization"
  850. )
  851. response_fields[additional_status_code] = response_field
  852. if response_fields:
  853. self.response_fields: dict[int | str, ModelField] = response_fields
  854. else:
  855. self.response_fields = {}
  856. assert callable(endpoint), "An endpoint must be a callable"
  857. self.dependant = get_dependant(
  858. path=self.path_format, call=self.endpoint, scope="function"
  859. )
  860. for depends in self.dependencies[::-1]:
  861. self.dependant.dependencies.insert(
  862. 0,
  863. get_parameterless_sub_dependant(depends=depends, path=self.path_format),
  864. )
  865. self._flat_dependant = get_flat_dependant(self.dependant)
  866. self._embed_body_fields = _should_embed_body_fields(
  867. self._flat_dependant.body_params
  868. )
  869. self.body_field = get_body_field(
  870. flat_dependant=self._flat_dependant,
  871. name=self.unique_id,
  872. embed_body_fields=self._embed_body_fields,
  873. )
  874. # Detect generator endpoints that should stream as JSONL or SSE
  875. is_generator = (
  876. self.dependant.is_async_gen_callable or self.dependant.is_gen_callable
  877. )
  878. self.is_sse_stream = is_generator and lenient_issubclass(
  879. response_class, EventSourceResponse
  880. )
  881. self.is_json_stream = is_generator and isinstance(
  882. response_class, DefaultPlaceholder
  883. )
  884. self.app = request_response(self.get_route_handler())
  885. def get_route_handler(self) -> Callable[[Request], Coroutine[Any, Any, Response]]:
  886. return get_request_handler(
  887. dependant=self.dependant,
  888. body_field=self.body_field,
  889. status_code=self.status_code,
  890. response_class=self.response_class,
  891. response_field=self.response_field,
  892. response_model_include=self.response_model_include,
  893. response_model_exclude=self.response_model_exclude,
  894. response_model_by_alias=self.response_model_by_alias,
  895. response_model_exclude_unset=self.response_model_exclude_unset,
  896. response_model_exclude_defaults=self.response_model_exclude_defaults,
  897. response_model_exclude_none=self.response_model_exclude_none,
  898. dependency_overrides_provider=self.dependency_overrides_provider,
  899. embed_body_fields=self._embed_body_fields,
  900. strict_content_type=self.strict_content_type,
  901. stream_item_field=self.stream_item_field,
  902. is_json_stream=self.is_json_stream,
  903. )
  904. def matches(self, scope: Scope) -> tuple[Match, Scope]:
  905. match, child_scope = super().matches(scope)
  906. if match != Match.NONE:
  907. child_scope["route"] = self
  908. return match, child_scope
  909. class APIRouter(routing.Router):
  910. """
  911. `APIRouter` class, used to group *path operations*, for example to structure
  912. an app in multiple files. It would then be included in the `FastAPI` app, or
  913. in another `APIRouter` (ultimately included in the app).
  914. Read more about it in the
  915. [FastAPI docs for Bigger Applications - Multiple Files](https://fastapi.tiangolo.com/tutorial/bigger-applications/).
  916. ## Example
  917. ```python
  918. from fastapi import APIRouter, FastAPI
  919. app = FastAPI()
  920. router = APIRouter()
  921. @router.get("/users/", tags=["users"])
  922. async def read_users():
  923. return [{"username": "Rick"}, {"username": "Morty"}]
  924. app.include_router(router)
  925. ```
  926. """
  927. def __init__(
  928. self,
  929. *,
  930. prefix: Annotated[str, Doc("An optional path prefix for the router.")] = "",
  931. tags: Annotated[
  932. list[str | Enum] | None,
  933. Doc(
  934. """
  935. A list of tags to be applied to all the *path operations* in this
  936. router.
  937. It will be added to the generated OpenAPI (e.g. visible at `/docs`).
  938. Read more about it in the
  939. [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).
  940. """
  941. ),
  942. ] = None,
  943. dependencies: Annotated[
  944. Sequence[params.Depends] | None,
  945. Doc(
  946. """
  947. A list of dependencies (using `Depends()`) to be applied to all the
  948. *path operations* in this router.
  949. Read more about it in the
  950. [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).
  951. """
  952. ),
  953. ] = None,
  954. default_response_class: Annotated[
  955. type[Response],
  956. Doc(
  957. """
  958. The default response class to be used.
  959. Read more in the
  960. [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#default-response-class).
  961. """
  962. ),
  963. ] = Default(JSONResponse),
  964. responses: Annotated[
  965. dict[int | str, dict[str, Any]] | None,
  966. Doc(
  967. """
  968. Additional responses to be shown in OpenAPI.
  969. It will be added to the generated OpenAPI (e.g. visible at `/docs`).
  970. Read more about it in the
  971. [FastAPI docs for Additional Responses in OpenAPI](https://fastapi.tiangolo.com/advanced/additional-responses/).
  972. And in the
  973. [FastAPI docs for Bigger Applications](https://fastapi.tiangolo.com/tutorial/bigger-applications/#include-an-apirouter-with-a-custom-prefix-tags-responses-and-dependencies).
  974. """
  975. ),
  976. ] = None,
  977. callbacks: Annotated[
  978. list[BaseRoute] | None,
  979. Doc(
  980. """
  981. OpenAPI callbacks that should apply to all *path operations* in this
  982. router.
  983. It will be added to the generated OpenAPI (e.g. visible at `/docs`).
  984. Read more about it in the
  985. [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/).
  986. """
  987. ),
  988. ] = None,
  989. routes: Annotated[
  990. list[BaseRoute] | None,
  991. Doc(
  992. """
  993. **Note**: you probably shouldn't use this parameter, it is inherited
  994. from Starlette and supported for compatibility.
  995. ---
  996. A list of routes to serve incoming HTTP and WebSocket requests.
  997. """
  998. ),
  999. deprecated(
  1000. """
  1001. You normally wouldn't use this parameter with FastAPI, it is inherited
  1002. from Starlette and supported for compatibility.
  1003. In FastAPI, you normally would use the *path operation methods*,
  1004. like `router.get()`, `router.post()`, etc.
  1005. """
  1006. ),
  1007. ] = None,
  1008. redirect_slashes: Annotated[
  1009. bool,
  1010. Doc(
  1011. """
  1012. Whether to detect and redirect slashes in URLs when the client doesn't
  1013. use the same format.
  1014. """
  1015. ),
  1016. ] = True,
  1017. default: Annotated[
  1018. ASGIApp | None,
  1019. Doc(
  1020. """
  1021. Default function handler for this router. Used to handle
  1022. 404 Not Found errors.
  1023. """
  1024. ),
  1025. ] = None,
  1026. dependency_overrides_provider: Annotated[
  1027. Any | None,
  1028. Doc(
  1029. """
  1030. Only used internally by FastAPI to handle dependency overrides.
  1031. You shouldn't need to use it. It normally points to the `FastAPI` app
  1032. object.
  1033. """
  1034. ),
  1035. ] = None,
  1036. route_class: Annotated[
  1037. type[APIRoute],
  1038. Doc(
  1039. """
  1040. Custom route (*path operation*) class to be used by this router.
  1041. Read more about it in the
  1042. [FastAPI docs for Custom Request and APIRoute class](https://fastapi.tiangolo.com/how-to/custom-request-and-route/#custom-apiroute-class-in-a-router).
  1043. """
  1044. ),
  1045. ] = APIRoute,
  1046. on_startup: Annotated[
  1047. Sequence[Callable[[], Any]] | None,
  1048. Doc(
  1049. """
  1050. A list of startup event handler functions.
  1051. You should instead use the `lifespan` handlers.
  1052. Read more in the [FastAPI docs for `lifespan`](https://fastapi.tiangolo.com/advanced/events/).
  1053. """
  1054. ),
  1055. ] = None,
  1056. on_shutdown: Annotated[
  1057. Sequence[Callable[[], Any]] | None,
  1058. Doc(
  1059. """
  1060. A list of shutdown event handler functions.
  1061. You should instead use the `lifespan` handlers.
  1062. Read more in the
  1063. [FastAPI docs for `lifespan`](https://fastapi.tiangolo.com/advanced/events/).
  1064. """
  1065. ),
  1066. ] = None,
  1067. # the generic to Lifespan[AppType] is the type of the top level application
  1068. # which the router cannot know statically, so we use typing.Any
  1069. lifespan: Annotated[
  1070. Lifespan[Any] | None,
  1071. Doc(
  1072. """
  1073. A `Lifespan` context manager handler. This replaces `startup` and
  1074. `shutdown` functions with a single context manager.
  1075. Read more in the
  1076. [FastAPI docs for `lifespan`](https://fastapi.tiangolo.com/advanced/events/).
  1077. """
  1078. ),
  1079. ] = None,
  1080. deprecated: Annotated[
  1081. bool | None,
  1082. Doc(
  1083. """
  1084. Mark all *path operations* in this router as deprecated.
  1085. It will be added to the generated OpenAPI (e.g. visible at `/docs`).
  1086. Read more about it in the
  1087. [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).
  1088. """
  1089. ),
  1090. ] = None,
  1091. include_in_schema: Annotated[
  1092. bool,
  1093. Doc(
  1094. """
  1095. To include (or not) all the *path operations* in this router in the
  1096. generated OpenAPI.
  1097. This affects the generated OpenAPI (e.g. visible at `/docs`).
  1098. Read more about it in the
  1099. [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-parameters-from-openapi).
  1100. """
  1101. ),
  1102. ] = True,
  1103. generate_unique_id_function: Annotated[
  1104. Callable[[APIRoute], str],
  1105. Doc(
  1106. """
  1107. Customize the function used to generate unique IDs for the *path
  1108. operations* shown in the generated OpenAPI.
  1109. This is particularly useful when automatically generating clients or
  1110. SDKs for your API.
  1111. Read more about it in the
  1112. [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).
  1113. """
  1114. ),
  1115. ] = Default(generate_unique_id),
  1116. strict_content_type: Annotated[
  1117. bool,
  1118. Doc(
  1119. """
  1120. Enable strict checking for request Content-Type headers.
  1121. When `True` (the default), requests with a body that do not include
  1122. a `Content-Type` header will **not** be parsed as JSON.
  1123. This prevents potential cross-site request forgery (CSRF) attacks
  1124. that exploit the browser's ability to send requests without a
  1125. Content-Type header, bypassing CORS preflight checks. In particular
  1126. applicable for apps that need to be run locally (in localhost).
  1127. When `False`, requests without a `Content-Type` header will have
  1128. their body parsed as JSON, which maintains compatibility with
  1129. certain clients that don't send `Content-Type` headers.
  1130. Read more about it in the
  1131. [FastAPI docs for Strict Content-Type](https://fastapi.tiangolo.com/advanced/strict-content-type/).
  1132. """
  1133. ),
  1134. ] = Default(True),
  1135. ) -> None:
  1136. # Determine the lifespan context to use
  1137. if lifespan is None:
  1138. # Use the default lifespan that runs on_startup/on_shutdown handlers
  1139. lifespan_context: Lifespan[Any] = _DefaultLifespan(self)
  1140. elif inspect.isasyncgenfunction(lifespan):
  1141. lifespan_context = asynccontextmanager(lifespan)
  1142. elif inspect.isgeneratorfunction(lifespan):
  1143. lifespan_context = _wrap_gen_lifespan_context(lifespan)
  1144. else:
  1145. lifespan_context = lifespan
  1146. self.lifespan_context = lifespan_context
  1147. super().__init__(
  1148. routes=routes,
  1149. redirect_slashes=redirect_slashes,
  1150. default=default,
  1151. lifespan=lifespan_context,
  1152. )
  1153. if prefix:
  1154. assert prefix.startswith("/"), "A path prefix must start with '/'"
  1155. assert not prefix.endswith("/"), (
  1156. "A path prefix must not end with '/', as the routes will start with '/'"
  1157. )
  1158. # Handle on_startup/on_shutdown locally since Starlette removed support
  1159. # Ref: https://github.com/Kludex/starlette/pull/3117
  1160. # TODO: deprecate this once the lifespan (or alternative) interface is improved
  1161. self.on_startup: list[Callable[[], Any]] = (
  1162. [] if on_startup is None else list(on_startup)
  1163. )
  1164. self.on_shutdown: list[Callable[[], Any]] = (
  1165. [] if on_shutdown is None else list(on_shutdown)
  1166. )
  1167. self.prefix = prefix
  1168. self.tags: list[str | Enum] = tags or []
  1169. self.dependencies = list(dependencies or [])
  1170. self.deprecated = deprecated
  1171. self.include_in_schema = include_in_schema
  1172. self.responses = responses or {}
  1173. self.callbacks = callbacks or []
  1174. self.dependency_overrides_provider = dependency_overrides_provider
  1175. self.route_class = route_class
  1176. self.default_response_class = default_response_class
  1177. self.generate_unique_id_function = generate_unique_id_function
  1178. self.strict_content_type = strict_content_type
  1179. def route(
  1180. self,
  1181. path: str,
  1182. methods: Collection[str] | None = None,
  1183. name: str | None = None,
  1184. include_in_schema: bool = True,
  1185. ) -> Callable[[DecoratedCallable], DecoratedCallable]:
  1186. def decorator(func: DecoratedCallable) -> DecoratedCallable:
  1187. self.add_route(
  1188. path,
  1189. func,
  1190. methods=methods,
  1191. name=name,
  1192. include_in_schema=include_in_schema,
  1193. )
  1194. return func
  1195. return decorator
  1196. def add_api_route(
  1197. self,
  1198. path: str,
  1199. endpoint: Callable[..., Any],
  1200. *,
  1201. response_model: Any = Default(None),
  1202. status_code: int | None = None,
  1203. tags: list[str | Enum] | None = None,
  1204. dependencies: Sequence[params.Depends] | None = None,
  1205. summary: str | None = None,
  1206. description: str | None = None,
  1207. response_description: str = "Successful Response",
  1208. responses: dict[int | str, dict[str, Any]] | None = None,
  1209. deprecated: bool | None = None,
  1210. methods: set[str] | list[str] | None = None,
  1211. operation_id: str | None = None,
  1212. response_model_include: IncEx | None = None,
  1213. response_model_exclude: IncEx | None = None,
  1214. response_model_by_alias: bool = True,
  1215. response_model_exclude_unset: bool = False,
  1216. response_model_exclude_defaults: bool = False,
  1217. response_model_exclude_none: bool = False,
  1218. include_in_schema: bool = True,
  1219. response_class: type[Response] | DefaultPlaceholder = Default(JSONResponse),
  1220. name: str | None = None,
  1221. route_class_override: type[APIRoute] | None = None,
  1222. callbacks: list[BaseRoute] | None = None,
  1223. openapi_extra: dict[str, Any] | None = None,
  1224. generate_unique_id_function: Callable[[APIRoute], str]
  1225. | DefaultPlaceholder = Default(generate_unique_id),
  1226. strict_content_type: bool | DefaultPlaceholder = Default(True),
  1227. ) -> None:
  1228. route_class = route_class_override or self.route_class
  1229. responses = responses or {}
  1230. combined_responses = {**self.responses, **responses}
  1231. current_response_class = get_value_or_default(
  1232. response_class, self.default_response_class
  1233. )
  1234. current_tags = self.tags.copy()
  1235. if tags:
  1236. current_tags.extend(tags)
  1237. current_dependencies = self.dependencies.copy()
  1238. if dependencies:
  1239. current_dependencies.extend(dependencies)
  1240. current_callbacks = self.callbacks.copy()
  1241. if callbacks:
  1242. current_callbacks.extend(callbacks)
  1243. current_generate_unique_id = get_value_or_default(
  1244. generate_unique_id_function, self.generate_unique_id_function
  1245. )
  1246. route = route_class(
  1247. self.prefix + path,
  1248. endpoint=endpoint,
  1249. response_model=response_model,
  1250. status_code=status_code,
  1251. tags=current_tags,
  1252. dependencies=current_dependencies,
  1253. summary=summary,
  1254. description=description,
  1255. response_description=response_description,
  1256. responses=combined_responses,
  1257. deprecated=deprecated or self.deprecated,
  1258. methods=methods,
  1259. operation_id=operation_id,
  1260. response_model_include=response_model_include,
  1261. response_model_exclude=response_model_exclude,
  1262. response_model_by_alias=response_model_by_alias,
  1263. response_model_exclude_unset=response_model_exclude_unset,
  1264. response_model_exclude_defaults=response_model_exclude_defaults,
  1265. response_model_exclude_none=response_model_exclude_none,
  1266. include_in_schema=include_in_schema and self.include_in_schema,
  1267. response_class=current_response_class,
  1268. name=name,
  1269. dependency_overrides_provider=self.dependency_overrides_provider,
  1270. callbacks=current_callbacks,
  1271. openapi_extra=openapi_extra,
  1272. generate_unique_id_function=current_generate_unique_id,
  1273. strict_content_type=get_value_or_default(
  1274. strict_content_type, self.strict_content_type
  1275. ),
  1276. )
  1277. self.routes.append(route)
  1278. def api_route(
  1279. self,
  1280. path: str,
  1281. *,
  1282. response_model: Any = Default(None),
  1283. status_code: int | None = None,
  1284. tags: list[str | Enum] | None = None,
  1285. dependencies: Sequence[params.Depends] | None = None,
  1286. summary: str | None = None,
  1287. description: str | None = None,
  1288. response_description: str = "Successful Response",
  1289. responses: dict[int | str, dict[str, Any]] | None = None,
  1290. deprecated: bool | None = None,
  1291. methods: list[str] | None = None,
  1292. operation_id: str | None = None,
  1293. response_model_include: IncEx | None = None,
  1294. response_model_exclude: IncEx | None = None,
  1295. response_model_by_alias: bool = True,
  1296. response_model_exclude_unset: bool = False,
  1297. response_model_exclude_defaults: bool = False,
  1298. response_model_exclude_none: bool = False,
  1299. include_in_schema: bool = True,
  1300. response_class: type[Response] = Default(JSONResponse),
  1301. name: str | None = None,
  1302. callbacks: list[BaseRoute] | None = None,
  1303. openapi_extra: dict[str, Any] | None = None,
  1304. generate_unique_id_function: Callable[[APIRoute], str] = Default(
  1305. generate_unique_id
  1306. ),
  1307. ) -> Callable[[DecoratedCallable], DecoratedCallable]:
  1308. def decorator(func: DecoratedCallable) -> DecoratedCallable:
  1309. self.add_api_route(
  1310. path,
  1311. func,
  1312. response_model=response_model,
  1313. status_code=status_code,
  1314. tags=tags,
  1315. dependencies=dependencies,
  1316. summary=summary,
  1317. description=description,
  1318. response_description=response_description,
  1319. responses=responses,
  1320. deprecated=deprecated,
  1321. methods=methods,
  1322. operation_id=operation_id,
  1323. response_model_include=response_model_include,
  1324. response_model_exclude=response_model_exclude,
  1325. response_model_by_alias=response_model_by_alias,
  1326. response_model_exclude_unset=response_model_exclude_unset,
  1327. response_model_exclude_defaults=response_model_exclude_defaults,
  1328. response_model_exclude_none=response_model_exclude_none,
  1329. include_in_schema=include_in_schema,
  1330. response_class=response_class,
  1331. name=name,
  1332. callbacks=callbacks,
  1333. openapi_extra=openapi_extra,
  1334. generate_unique_id_function=generate_unique_id_function,
  1335. )
  1336. return func
  1337. return decorator
  1338. def add_api_websocket_route(
  1339. self,
  1340. path: str,
  1341. endpoint: Callable[..., Any],
  1342. name: str | None = None,
  1343. *,
  1344. dependencies: Sequence[params.Depends] | None = None,
  1345. ) -> None:
  1346. current_dependencies = self.dependencies.copy()
  1347. if dependencies:
  1348. current_dependencies.extend(dependencies)
  1349. route = APIWebSocketRoute(
  1350. self.prefix + path,
  1351. endpoint=endpoint,
  1352. name=name,
  1353. dependencies=current_dependencies,
  1354. dependency_overrides_provider=self.dependency_overrides_provider,
  1355. )
  1356. self.routes.append(route)
  1357. def websocket(
  1358. self,
  1359. path: Annotated[
  1360. str,
  1361. Doc(
  1362. """
  1363. WebSocket path.
  1364. """
  1365. ),
  1366. ],
  1367. name: Annotated[
  1368. str | None,
  1369. Doc(
  1370. """
  1371. A name for the WebSocket. Only used internally.
  1372. """
  1373. ),
  1374. ] = None,
  1375. *,
  1376. dependencies: Annotated[
  1377. Sequence[params.Depends] | None,
  1378. Doc(
  1379. """
  1380. A list of dependencies (using `Depends()`) to be used for this
  1381. WebSocket.
  1382. Read more about it in the
  1383. [FastAPI docs for WebSockets](https://fastapi.tiangolo.com/advanced/websockets/).
  1384. """
  1385. ),
  1386. ] = None,
  1387. ) -> Callable[[DecoratedCallable], DecoratedCallable]:
  1388. """
  1389. Decorate a WebSocket function.
  1390. Read more about it in the
  1391. [FastAPI docs for WebSockets](https://fastapi.tiangolo.com/advanced/websockets/).
  1392. **Example**
  1393. ## Example
  1394. ```python
  1395. from fastapi import APIRouter, FastAPI, WebSocket
  1396. app = FastAPI()
  1397. router = APIRouter()
  1398. @router.websocket("/ws")
  1399. async def websocket_endpoint(websocket: WebSocket):
  1400. await websocket.accept()
  1401. while True:
  1402. data = await websocket.receive_text()
  1403. await websocket.send_text(f"Message text was: {data}")
  1404. app.include_router(router)
  1405. ```
  1406. """
  1407. def decorator(func: DecoratedCallable) -> DecoratedCallable:
  1408. self.add_api_websocket_route(
  1409. path, func, name=name, dependencies=dependencies
  1410. )
  1411. return func
  1412. return decorator
  1413. def websocket_route(
  1414. self, path: str, name: str | None = None
  1415. ) -> Callable[[DecoratedCallable], DecoratedCallable]:
  1416. def decorator(func: DecoratedCallable) -> DecoratedCallable:
  1417. self.add_websocket_route(path, func, name=name)
  1418. return func
  1419. return decorator
  1420. def include_router(
  1421. self,
  1422. router: Annotated["APIRouter", Doc("The `APIRouter` to include.")],
  1423. *,
  1424. prefix: Annotated[str, Doc("An optional path prefix for the router.")] = "",
  1425. tags: Annotated[
  1426. list[str | Enum] | None,
  1427. Doc(
  1428. """
  1429. A list of tags to be applied to all the *path operations* in this
  1430. router.
  1431. It will be added to the generated OpenAPI (e.g. visible at `/docs`).
  1432. Read more about it in the
  1433. [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).
  1434. """
  1435. ),
  1436. ] = None,
  1437. dependencies: Annotated[
  1438. Sequence[params.Depends] | None,
  1439. Doc(
  1440. """
  1441. A list of dependencies (using `Depends()`) to be applied to all the
  1442. *path operations* in this router.
  1443. Read more about it in the
  1444. [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).
  1445. """
  1446. ),
  1447. ] = None,
  1448. default_response_class: Annotated[
  1449. type[Response],
  1450. Doc(
  1451. """
  1452. The default response class to be used.
  1453. Read more in the
  1454. [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#default-response-class).
  1455. """
  1456. ),
  1457. ] = Default(JSONResponse),
  1458. responses: Annotated[
  1459. dict[int | str, dict[str, Any]] | None,
  1460. Doc(
  1461. """
  1462. Additional responses to be shown in OpenAPI.
  1463. It will be added to the generated OpenAPI (e.g. visible at `/docs`).
  1464. Read more about it in the
  1465. [FastAPI docs for Additional Responses in OpenAPI](https://fastapi.tiangolo.com/advanced/additional-responses/).
  1466. And in the
  1467. [FastAPI docs for Bigger Applications](https://fastapi.tiangolo.com/tutorial/bigger-applications/#include-an-apirouter-with-a-custom-prefix-tags-responses-and-dependencies).
  1468. """
  1469. ),
  1470. ] = None,
  1471. callbacks: Annotated[
  1472. list[BaseRoute] | None,
  1473. Doc(
  1474. """
  1475. OpenAPI callbacks that should apply to all *path operations* in this
  1476. router.
  1477. It will be added to the generated OpenAPI (e.g. visible at `/docs`).
  1478. Read more about it in the
  1479. [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/).
  1480. """
  1481. ),
  1482. ] = None,
  1483. deprecated: Annotated[
  1484. bool | None,
  1485. Doc(
  1486. """
  1487. Mark all *path operations* in this router as deprecated.
  1488. It will be added to the generated OpenAPI (e.g. visible at `/docs`).
  1489. Read more about it in the
  1490. [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).
  1491. """
  1492. ),
  1493. ] = None,
  1494. include_in_schema: Annotated[
  1495. bool,
  1496. Doc(
  1497. """
  1498. Include (or not) all the *path operations* in this router in the
  1499. generated OpenAPI schema.
  1500. This affects the generated OpenAPI (e.g. visible at `/docs`).
  1501. """
  1502. ),
  1503. ] = True,
  1504. generate_unique_id_function: Annotated[
  1505. Callable[[APIRoute], str],
  1506. Doc(
  1507. """
  1508. Customize the function used to generate unique IDs for the *path
  1509. operations* shown in the generated OpenAPI.
  1510. This is particularly useful when automatically generating clients or
  1511. SDKs for your API.
  1512. Read more about it in the
  1513. [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).
  1514. """
  1515. ),
  1516. ] = Default(generate_unique_id),
  1517. ) -> None:
  1518. """
  1519. Include another `APIRouter` in the same current `APIRouter`.
  1520. Read more about it in the
  1521. [FastAPI docs for Bigger Applications](https://fastapi.tiangolo.com/tutorial/bigger-applications/).
  1522. ## Example
  1523. ```python
  1524. from fastapi import APIRouter, FastAPI
  1525. app = FastAPI()
  1526. internal_router = APIRouter()
  1527. users_router = APIRouter()
  1528. @users_router.get("/users/")
  1529. def read_users():
  1530. return [{"name": "Rick"}, {"name": "Morty"}]
  1531. internal_router.include_router(users_router)
  1532. app.include_router(internal_router)
  1533. ```
  1534. """
  1535. assert self is not router, (
  1536. "Cannot include the same APIRouter instance into itself. "
  1537. "Did you mean to include a different router?"
  1538. )
  1539. if prefix:
  1540. assert prefix.startswith("/"), "A path prefix must start with '/'"
  1541. assert not prefix.endswith("/"), (
  1542. "A path prefix must not end with '/', as the routes will start with '/'"
  1543. )
  1544. else:
  1545. for r in router.routes:
  1546. path = getattr(r, "path") # noqa: B009
  1547. name = getattr(r, "name", "unknown")
  1548. if path is not None and not path:
  1549. raise FastAPIError(
  1550. f"Prefix and path cannot be both empty (path operation: {name})"
  1551. )
  1552. if responses is None:
  1553. responses = {}
  1554. for route in router.routes:
  1555. if isinstance(route, APIRoute):
  1556. combined_responses = {**responses, **route.responses}
  1557. use_response_class = get_value_or_default(
  1558. route.response_class,
  1559. router.default_response_class,
  1560. default_response_class,
  1561. self.default_response_class,
  1562. )
  1563. current_tags = []
  1564. if tags:
  1565. current_tags.extend(tags)
  1566. if route.tags:
  1567. current_tags.extend(route.tags)
  1568. current_dependencies: list[params.Depends] = []
  1569. if dependencies:
  1570. current_dependencies.extend(dependencies)
  1571. if route.dependencies:
  1572. current_dependencies.extend(route.dependencies)
  1573. current_callbacks = []
  1574. if callbacks:
  1575. current_callbacks.extend(callbacks)
  1576. if route.callbacks:
  1577. current_callbacks.extend(route.callbacks)
  1578. current_generate_unique_id = get_value_or_default(
  1579. route.generate_unique_id_function,
  1580. router.generate_unique_id_function,
  1581. generate_unique_id_function,
  1582. self.generate_unique_id_function,
  1583. )
  1584. self.add_api_route(
  1585. prefix + route.path,
  1586. route.endpoint,
  1587. response_model=route.response_model,
  1588. status_code=route.status_code,
  1589. tags=current_tags,
  1590. dependencies=current_dependencies,
  1591. summary=route.summary,
  1592. description=route.description,
  1593. response_description=route.response_description,
  1594. responses=combined_responses,
  1595. deprecated=route.deprecated or deprecated or self.deprecated,
  1596. methods=route.methods,
  1597. operation_id=route.operation_id,
  1598. response_model_include=route.response_model_include,
  1599. response_model_exclude=route.response_model_exclude,
  1600. response_model_by_alias=route.response_model_by_alias,
  1601. response_model_exclude_unset=route.response_model_exclude_unset,
  1602. response_model_exclude_defaults=route.response_model_exclude_defaults,
  1603. response_model_exclude_none=route.response_model_exclude_none,
  1604. include_in_schema=route.include_in_schema
  1605. and self.include_in_schema
  1606. and include_in_schema,
  1607. response_class=use_response_class,
  1608. name=route.name,
  1609. route_class_override=type(route),
  1610. callbacks=current_callbacks,
  1611. openapi_extra=route.openapi_extra,
  1612. generate_unique_id_function=current_generate_unique_id,
  1613. strict_content_type=get_value_or_default(
  1614. route.strict_content_type,
  1615. router.strict_content_type,
  1616. self.strict_content_type,
  1617. ),
  1618. )
  1619. elif isinstance(route, routing.Route):
  1620. methods = list(route.methods or [])
  1621. self.add_route(
  1622. prefix + route.path,
  1623. route.endpoint,
  1624. methods=methods,
  1625. include_in_schema=route.include_in_schema,
  1626. name=route.name,
  1627. )
  1628. elif isinstance(route, APIWebSocketRoute):
  1629. current_dependencies = []
  1630. if dependencies:
  1631. current_dependencies.extend(dependencies)
  1632. if route.dependencies:
  1633. current_dependencies.extend(route.dependencies)
  1634. self.add_api_websocket_route(
  1635. prefix + route.path,
  1636. route.endpoint,
  1637. dependencies=current_dependencies,
  1638. name=route.name,
  1639. )
  1640. elif isinstance(route, routing.WebSocketRoute):
  1641. self.add_websocket_route(
  1642. prefix + route.path, route.endpoint, name=route.name
  1643. )
  1644. for handler in router.on_startup:
  1645. self.add_event_handler("startup", handler)
  1646. for handler in router.on_shutdown:
  1647. self.add_event_handler("shutdown", handler)
  1648. self.lifespan_context = _merge_lifespan_context(
  1649. self.lifespan_context,
  1650. router.lifespan_context,
  1651. )
  1652. def get(
  1653. self,
  1654. path: Annotated[
  1655. str,
  1656. Doc(
  1657. """
  1658. The URL path to be used for this *path operation*.
  1659. For example, in `http://example.com/items`, the path is `/items`.
  1660. """
  1661. ),
  1662. ],
  1663. *,
  1664. response_model: Annotated[
  1665. Any,
  1666. Doc(
  1667. """
  1668. The type to use for the response.
  1669. It could be any valid Pydantic *field* type. So, it doesn't have to
  1670. be a Pydantic model, it could be other things, like a `list`, `dict`,
  1671. etc.
  1672. It will be used for:
  1673. * Documentation: the generated OpenAPI (and the UI at `/docs`) will
  1674. show it as the response (JSON Schema).
  1675. * Serialization: you could return an arbitrary object and the
  1676. `response_model` would be used to serialize that object into the
  1677. corresponding JSON.
  1678. * Filtering: the JSON sent to the client will only contain the data
  1679. (fields) defined in the `response_model`. If you returned an object
  1680. that contains an attribute `password` but the `response_model` does
  1681. not include that field, the JSON sent to the client would not have
  1682. that `password`.
  1683. * Validation: whatever you return will be serialized with the
  1684. `response_model`, converting any data as necessary to generate the
  1685. corresponding JSON. But if the data in the object returned is not
  1686. valid, that would mean a violation of the contract with the client,
  1687. so it's an error from the API developer. So, FastAPI will raise an
  1688. error and return a 500 error code (Internal Server Error).
  1689. Read more about it in the
  1690. [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/).
  1691. """
  1692. ),
  1693. ] = Default(None),
  1694. status_code: Annotated[
  1695. int | None,
  1696. Doc(
  1697. """
  1698. The default status code to be used for the response.
  1699. You could override the status code by returning a response directly.
  1700. Read more about it in the
  1701. [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/).
  1702. """
  1703. ),
  1704. ] = None,
  1705. tags: Annotated[
  1706. list[str | Enum] | None,
  1707. Doc(
  1708. """
  1709. A list of tags to be applied to the *path operation*.
  1710. It will be added to the generated OpenAPI (e.g. visible at `/docs`).
  1711. Read more about it in the
  1712. [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#tags).
  1713. """
  1714. ),
  1715. ] = None,
  1716. dependencies: Annotated[
  1717. Sequence[params.Depends] | None,
  1718. Doc(
  1719. """
  1720. A list of dependencies (using `Depends()`) to be applied to the
  1721. *path operation*.
  1722. Read more about it in the
  1723. [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/).
  1724. """
  1725. ),
  1726. ] = None,
  1727. summary: Annotated[
  1728. str | None,
  1729. Doc(
  1730. """
  1731. A summary for the *path operation*.
  1732. It will be added to the generated OpenAPI (e.g. visible at `/docs`).
  1733. Read more about it in the
  1734. [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).
  1735. """
  1736. ),
  1737. ] = None,
  1738. description: Annotated[
  1739. str | None,
  1740. Doc(
  1741. """
  1742. A description for the *path operation*.
  1743. If not provided, it will be extracted automatically from the docstring
  1744. of the *path operation function*.
  1745. It can contain Markdown.
  1746. It will be added to the generated OpenAPI (e.g. visible at `/docs`).
  1747. Read more about it in the
  1748. [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).
  1749. """
  1750. ),
  1751. ] = None,
  1752. response_description: Annotated[
  1753. str,
  1754. Doc(
  1755. """
  1756. The description for the default response.
  1757. It will be added to the generated OpenAPI (e.g. visible at `/docs`).
  1758. """
  1759. ),
  1760. ] = "Successful Response",
  1761. responses: Annotated[
  1762. dict[int | str, dict[str, Any]] | None,
  1763. Doc(
  1764. """
  1765. Additional responses that could be returned by this *path operation*.
  1766. It will be added to the generated OpenAPI (e.g. visible at `/docs`).
  1767. """
  1768. ),
  1769. ] = None,
  1770. deprecated: Annotated[
  1771. bool | None,
  1772. Doc(
  1773. """
  1774. Mark this *path operation* as deprecated.
  1775. It will be added to the generated OpenAPI (e.g. visible at `/docs`).
  1776. """
  1777. ),
  1778. ] = None,
  1779. operation_id: Annotated[
  1780. str | None,
  1781. Doc(
  1782. """
  1783. Custom operation ID to be used by this *path operation*.
  1784. By default, it is generated automatically.
  1785. If you provide a custom operation ID, you need to make sure it is
  1786. unique for the whole API.
  1787. You can customize the
  1788. operation ID generation with the parameter
  1789. `generate_unique_id_function` in the `FastAPI` class.
  1790. Read more about it in the
  1791. [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).
  1792. """
  1793. ),
  1794. ] = None,
  1795. response_model_include: Annotated[
  1796. IncEx | None,
  1797. Doc(
  1798. """
  1799. Configuration passed to Pydantic to include only certain fields in the
  1800. response data.
  1801. Read more about it in the
  1802. [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).
  1803. """
  1804. ),
  1805. ] = None,
  1806. response_model_exclude: Annotated[
  1807. IncEx | None,
  1808. Doc(
  1809. """
  1810. Configuration passed to Pydantic to exclude certain fields in the
  1811. response data.
  1812. Read more about it in the
  1813. [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).
  1814. """
  1815. ),
  1816. ] = None,
  1817. response_model_by_alias: Annotated[
  1818. bool,
  1819. Doc(
  1820. """
  1821. Configuration passed to Pydantic to define if the response model
  1822. should be serialized by alias when an alias is used.
  1823. Read more about it in the
  1824. [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).
  1825. """
  1826. ),
  1827. ] = True,
  1828. response_model_exclude_unset: Annotated[
  1829. bool,
  1830. Doc(
  1831. """
  1832. Configuration passed to Pydantic to define if the response data
  1833. should have all the fields, including the ones that were not set and
  1834. have their default values. This is different from
  1835. `response_model_exclude_defaults` in that if the fields are set,
  1836. they will be included in the response, even if the value is the same
  1837. as the default.
  1838. When `True`, default values are omitted from the response.
  1839. Read more about it in the
  1840. [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).
  1841. """
  1842. ),
  1843. ] = False,
  1844. response_model_exclude_defaults: Annotated[
  1845. bool,
  1846. Doc(
  1847. """
  1848. Configuration passed to Pydantic to define if the response data
  1849. should have all the fields, including the ones that have the same value
  1850. as the default. This is different from `response_model_exclude_unset`
  1851. in that if the fields are set but contain the same default values,
  1852. they will be excluded from the response.
  1853. When `True`, default values are omitted from the response.
  1854. Read more about it in the
  1855. [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).
  1856. """
  1857. ),
  1858. ] = False,
  1859. response_model_exclude_none: Annotated[
  1860. bool,
  1861. Doc(
  1862. """
  1863. Configuration passed to Pydantic to define if the response data should
  1864. exclude fields set to `None`.
  1865. This is much simpler (less smart) than `response_model_exclude_unset`
  1866. and `response_model_exclude_defaults`. You probably want to use one of
  1867. those two instead of this one, as those allow returning `None` values
  1868. when it makes sense.
  1869. Read more about it in the
  1870. [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none).
  1871. """
  1872. ),
  1873. ] = False,
  1874. include_in_schema: Annotated[
  1875. bool,
  1876. Doc(
  1877. """
  1878. Include this *path operation* in the generated OpenAPI schema.
  1879. This affects the generated OpenAPI (e.g. visible at `/docs`).
  1880. Read more about it in the
  1881. [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-parameters-from-openapi).
  1882. """
  1883. ),
  1884. ] = True,
  1885. response_class: Annotated[
  1886. type[Response],
  1887. Doc(
  1888. """
  1889. Response class to be used for this *path operation*.
  1890. This will not be used if you return a response directly.
  1891. Read more about it in the
  1892. [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse).
  1893. """
  1894. ),
  1895. ] = Default(JSONResponse),
  1896. name: Annotated[
  1897. str | None,
  1898. Doc(
  1899. """
  1900. Name for this *path operation*. Only used internally.
  1901. """
  1902. ),
  1903. ] = None,
  1904. callbacks: Annotated[
  1905. list[BaseRoute] | None,
  1906. Doc(
  1907. """
  1908. List of *path operations* that will be used as OpenAPI callbacks.
  1909. This is only for OpenAPI documentation, the callbacks won't be used
  1910. directly.
  1911. It will be added to the generated OpenAPI (e.g. visible at `/docs`).
  1912. Read more about it in the
  1913. [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/).
  1914. """
  1915. ),
  1916. ] = None,
  1917. openapi_extra: Annotated[
  1918. dict[str, Any] | None,
  1919. Doc(
  1920. """
  1921. Extra metadata to be included in the OpenAPI schema for this *path
  1922. operation*.
  1923. Read more about it in the
  1924. [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema).
  1925. """
  1926. ),
  1927. ] = None,
  1928. generate_unique_id_function: Annotated[
  1929. Callable[[APIRoute], str],
  1930. Doc(
  1931. """
  1932. Customize the function used to generate unique IDs for the *path
  1933. operations* shown in the generated OpenAPI.
  1934. This is particularly useful when automatically generating clients or
  1935. SDKs for your API.
  1936. Read more about it in the
  1937. [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).
  1938. """
  1939. ),
  1940. ] = Default(generate_unique_id),
  1941. ) -> Callable[[DecoratedCallable], DecoratedCallable]:
  1942. """
  1943. Add a *path operation* using an HTTP GET operation.
  1944. ## Example
  1945. ```python
  1946. from fastapi import APIRouter, FastAPI
  1947. app = FastAPI()
  1948. router = APIRouter()
  1949. @router.get("/items/")
  1950. def read_items():
  1951. return [{"name": "Empanada"}, {"name": "Arepa"}]
  1952. app.include_router(router)
  1953. ```
  1954. """
  1955. return self.api_route(
  1956. path=path,
  1957. response_model=response_model,
  1958. status_code=status_code,
  1959. tags=tags,
  1960. dependencies=dependencies,
  1961. summary=summary,
  1962. description=description,
  1963. response_description=response_description,
  1964. responses=responses,
  1965. deprecated=deprecated,
  1966. methods=["GET"],
  1967. operation_id=operation_id,
  1968. response_model_include=response_model_include,
  1969. response_model_exclude=response_model_exclude,
  1970. response_model_by_alias=response_model_by_alias,
  1971. response_model_exclude_unset=response_model_exclude_unset,
  1972. response_model_exclude_defaults=response_model_exclude_defaults,
  1973. response_model_exclude_none=response_model_exclude_none,
  1974. include_in_schema=include_in_schema,
  1975. response_class=response_class,
  1976. name=name,
  1977. callbacks=callbacks,
  1978. openapi_extra=openapi_extra,
  1979. generate_unique_id_function=generate_unique_id_function,
  1980. )
  1981. def put(
  1982. self,
  1983. path: Annotated[
  1984. str,
  1985. Doc(
  1986. """
  1987. The URL path to be used for this *path operation*.
  1988. For example, in `http://example.com/items`, the path is `/items`.
  1989. """
  1990. ),
  1991. ],
  1992. *,
  1993. response_model: Annotated[
  1994. Any,
  1995. Doc(
  1996. """
  1997. The type to use for the response.
  1998. It could be any valid Pydantic *field* type. So, it doesn't have to
  1999. be a Pydantic model, it could be other things, like a `list`, `dict`,
  2000. etc.
  2001. It will be used for:
  2002. * Documentation: the generated OpenAPI (and the UI at `/docs`) will
  2003. show it as the response (JSON Schema).
  2004. * Serialization: you could return an arbitrary object and the
  2005. `response_model` would be used to serialize that object into the
  2006. corresponding JSON.
  2007. * Filtering: the JSON sent to the client will only contain the data
  2008. (fields) defined in the `response_model`. If you returned an object
  2009. that contains an attribute `password` but the `response_model` does
  2010. not include that field, the JSON sent to the client would not have
  2011. that `password`.
  2012. * Validation: whatever you return will be serialized with the
  2013. `response_model`, converting any data as necessary to generate the
  2014. corresponding JSON. But if the data in the object returned is not
  2015. valid, that would mean a violation of the contract with the client,
  2016. so it's an error from the API developer. So, FastAPI will raise an
  2017. error and return a 500 error code (Internal Server Error).
  2018. Read more about it in the
  2019. [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/).
  2020. """
  2021. ),
  2022. ] = Default(None),
  2023. status_code: Annotated[
  2024. int | None,
  2025. Doc(
  2026. """
  2027. The default status code to be used for the response.
  2028. You could override the status code by returning a response directly.
  2029. Read more about it in the
  2030. [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/).
  2031. """
  2032. ),
  2033. ] = None,
  2034. tags: Annotated[
  2035. list[str | Enum] | None,
  2036. Doc(
  2037. """
  2038. A list of tags to be applied to the *path operation*.
  2039. It will be added to the generated OpenAPI (e.g. visible at `/docs`).
  2040. Read more about it in the
  2041. [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#tags).
  2042. """
  2043. ),
  2044. ] = None,
  2045. dependencies: Annotated[
  2046. Sequence[params.Depends] | None,
  2047. Doc(
  2048. """
  2049. A list of dependencies (using `Depends()`) to be applied to the
  2050. *path operation*.
  2051. Read more about it in the
  2052. [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/).
  2053. """
  2054. ),
  2055. ] = None,
  2056. summary: Annotated[
  2057. str | None,
  2058. Doc(
  2059. """
  2060. A summary for the *path operation*.
  2061. It will be added to the generated OpenAPI (e.g. visible at `/docs`).
  2062. Read more about it in the
  2063. [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).
  2064. """
  2065. ),
  2066. ] = None,
  2067. description: Annotated[
  2068. str | None,
  2069. Doc(
  2070. """
  2071. A description for the *path operation*.
  2072. If not provided, it will be extracted automatically from the docstring
  2073. of the *path operation function*.
  2074. It can contain Markdown.
  2075. It will be added to the generated OpenAPI (e.g. visible at `/docs`).
  2076. Read more about it in the
  2077. [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).
  2078. """
  2079. ),
  2080. ] = None,
  2081. response_description: Annotated[
  2082. str,
  2083. Doc(
  2084. """
  2085. The description for the default response.
  2086. It will be added to the generated OpenAPI (e.g. visible at `/docs`).
  2087. """
  2088. ),
  2089. ] = "Successful Response",
  2090. responses: Annotated[
  2091. dict[int | str, dict[str, Any]] | None,
  2092. Doc(
  2093. """
  2094. Additional responses that could be returned by this *path operation*.
  2095. It will be added to the generated OpenAPI (e.g. visible at `/docs`).
  2096. """
  2097. ),
  2098. ] = None,
  2099. deprecated: Annotated[
  2100. bool | None,
  2101. Doc(
  2102. """
  2103. Mark this *path operation* as deprecated.
  2104. It will be added to the generated OpenAPI (e.g. visible at `/docs`).
  2105. """
  2106. ),
  2107. ] = None,
  2108. operation_id: Annotated[
  2109. str | None,
  2110. Doc(
  2111. """
  2112. Custom operation ID to be used by this *path operation*.
  2113. By default, it is generated automatically.
  2114. If you provide a custom operation ID, you need to make sure it is
  2115. unique for the whole API.
  2116. You can customize the
  2117. operation ID generation with the parameter
  2118. `generate_unique_id_function` in the `FastAPI` class.
  2119. Read more about it in the
  2120. [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).
  2121. """
  2122. ),
  2123. ] = None,
  2124. response_model_include: Annotated[
  2125. IncEx | None,
  2126. Doc(
  2127. """
  2128. Configuration passed to Pydantic to include only certain fields in the
  2129. response data.
  2130. Read more about it in the
  2131. [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).
  2132. """
  2133. ),
  2134. ] = None,
  2135. response_model_exclude: Annotated[
  2136. IncEx | None,
  2137. Doc(
  2138. """
  2139. Configuration passed to Pydantic to exclude certain fields in the
  2140. response data.
  2141. Read more about it in the
  2142. [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).
  2143. """
  2144. ),
  2145. ] = None,
  2146. response_model_by_alias: Annotated[
  2147. bool,
  2148. Doc(
  2149. """
  2150. Configuration passed to Pydantic to define if the response model
  2151. should be serialized by alias when an alias is used.
  2152. Read more about it in the
  2153. [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).
  2154. """
  2155. ),
  2156. ] = True,
  2157. response_model_exclude_unset: Annotated[
  2158. bool,
  2159. Doc(
  2160. """
  2161. Configuration passed to Pydantic to define if the response data
  2162. should have all the fields, including the ones that were not set and
  2163. have their default values. This is different from
  2164. `response_model_exclude_defaults` in that if the fields are set,
  2165. they will be included in the response, even if the value is the same
  2166. as the default.
  2167. When `True`, default values are omitted from the response.
  2168. Read more about it in the
  2169. [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).
  2170. """
  2171. ),
  2172. ] = False,
  2173. response_model_exclude_defaults: Annotated[
  2174. bool,
  2175. Doc(
  2176. """
  2177. Configuration passed to Pydantic to define if the response data
  2178. should have all the fields, including the ones that have the same value
  2179. as the default. This is different from `response_model_exclude_unset`
  2180. in that if the fields are set but contain the same default values,
  2181. they will be excluded from the response.
  2182. When `True`, default values are omitted from the response.
  2183. Read more about it in the
  2184. [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).
  2185. """
  2186. ),
  2187. ] = False,
  2188. response_model_exclude_none: Annotated[
  2189. bool,
  2190. Doc(
  2191. """
  2192. Configuration passed to Pydantic to define if the response data should
  2193. exclude fields set to `None`.
  2194. This is much simpler (less smart) than `response_model_exclude_unset`
  2195. and `response_model_exclude_defaults`. You probably want to use one of
  2196. those two instead of this one, as those allow returning `None` values
  2197. when it makes sense.
  2198. Read more about it in the
  2199. [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none).
  2200. """
  2201. ),
  2202. ] = False,
  2203. include_in_schema: Annotated[
  2204. bool,
  2205. Doc(
  2206. """
  2207. Include this *path operation* in the generated OpenAPI schema.
  2208. This affects the generated OpenAPI (e.g. visible at `/docs`).
  2209. Read more about it in the
  2210. [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-parameters-from-openapi).
  2211. """
  2212. ),
  2213. ] = True,
  2214. response_class: Annotated[
  2215. type[Response],
  2216. Doc(
  2217. """
  2218. Response class to be used for this *path operation*.
  2219. This will not be used if you return a response directly.
  2220. Read more about it in the
  2221. [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse).
  2222. """
  2223. ),
  2224. ] = Default(JSONResponse),
  2225. name: Annotated[
  2226. str | None,
  2227. Doc(
  2228. """
  2229. Name for this *path operation*. Only used internally.
  2230. """
  2231. ),
  2232. ] = None,
  2233. callbacks: Annotated[
  2234. list[BaseRoute] | None,
  2235. Doc(
  2236. """
  2237. List of *path operations* that will be used as OpenAPI callbacks.
  2238. This is only for OpenAPI documentation, the callbacks won't be used
  2239. directly.
  2240. It will be added to the generated OpenAPI (e.g. visible at `/docs`).
  2241. Read more about it in the
  2242. [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/).
  2243. """
  2244. ),
  2245. ] = None,
  2246. openapi_extra: Annotated[
  2247. dict[str, Any] | None,
  2248. Doc(
  2249. """
  2250. Extra metadata to be included in the OpenAPI schema for this *path
  2251. operation*.
  2252. Read more about it in the
  2253. [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema).
  2254. """
  2255. ),
  2256. ] = None,
  2257. generate_unique_id_function: Annotated[
  2258. Callable[[APIRoute], str],
  2259. Doc(
  2260. """
  2261. Customize the function used to generate unique IDs for the *path
  2262. operations* shown in the generated OpenAPI.
  2263. This is particularly useful when automatically generating clients or
  2264. SDKs for your API.
  2265. Read more about it in the
  2266. [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).
  2267. """
  2268. ),
  2269. ] = Default(generate_unique_id),
  2270. ) -> Callable[[DecoratedCallable], DecoratedCallable]:
  2271. """
  2272. Add a *path operation* using an HTTP PUT operation.
  2273. ## Example
  2274. ```python
  2275. from fastapi import APIRouter, FastAPI
  2276. from pydantic import BaseModel
  2277. class Item(BaseModel):
  2278. name: str
  2279. description: str | None = None
  2280. app = FastAPI()
  2281. router = APIRouter()
  2282. @router.put("/items/{item_id}")
  2283. def replace_item(item_id: str, item: Item):
  2284. return {"message": "Item replaced", "id": item_id}
  2285. app.include_router(router)
  2286. ```
  2287. """
  2288. return self.api_route(
  2289. path=path,
  2290. response_model=response_model,
  2291. status_code=status_code,
  2292. tags=tags,
  2293. dependencies=dependencies,
  2294. summary=summary,
  2295. description=description,
  2296. response_description=response_description,
  2297. responses=responses,
  2298. deprecated=deprecated,
  2299. methods=["PUT"],
  2300. operation_id=operation_id,
  2301. response_model_include=response_model_include,
  2302. response_model_exclude=response_model_exclude,
  2303. response_model_by_alias=response_model_by_alias,
  2304. response_model_exclude_unset=response_model_exclude_unset,
  2305. response_model_exclude_defaults=response_model_exclude_defaults,
  2306. response_model_exclude_none=response_model_exclude_none,
  2307. include_in_schema=include_in_schema,
  2308. response_class=response_class,
  2309. name=name,
  2310. callbacks=callbacks,
  2311. openapi_extra=openapi_extra,
  2312. generate_unique_id_function=generate_unique_id_function,
  2313. )
  2314. def post(
  2315. self,
  2316. path: Annotated[
  2317. str,
  2318. Doc(
  2319. """
  2320. The URL path to be used for this *path operation*.
  2321. For example, in `http://example.com/items`, the path is `/items`.
  2322. """
  2323. ),
  2324. ],
  2325. *,
  2326. response_model: Annotated[
  2327. Any,
  2328. Doc(
  2329. """
  2330. The type to use for the response.
  2331. It could be any valid Pydantic *field* type. So, it doesn't have to
  2332. be a Pydantic model, it could be other things, like a `list`, `dict`,
  2333. etc.
  2334. It will be used for:
  2335. * Documentation: the generated OpenAPI (and the UI at `/docs`) will
  2336. show it as the response (JSON Schema).
  2337. * Serialization: you could return an arbitrary object and the
  2338. `response_model` would be used to serialize that object into the
  2339. corresponding JSON.
  2340. * Filtering: the JSON sent to the client will only contain the data
  2341. (fields) defined in the `response_model`. If you returned an object
  2342. that contains an attribute `password` but the `response_model` does
  2343. not include that field, the JSON sent to the client would not have
  2344. that `password`.
  2345. * Validation: whatever you return will be serialized with the
  2346. `response_model`, converting any data as necessary to generate the
  2347. corresponding JSON. But if the data in the object returned is not
  2348. valid, that would mean a violation of the contract with the client,
  2349. so it's an error from the API developer. So, FastAPI will raise an
  2350. error and return a 500 error code (Internal Server Error).
  2351. Read more about it in the
  2352. [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/).
  2353. """
  2354. ),
  2355. ] = Default(None),
  2356. status_code: Annotated[
  2357. int | None,
  2358. Doc(
  2359. """
  2360. The default status code to be used for the response.
  2361. You could override the status code by returning a response directly.
  2362. Read more about it in the
  2363. [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/).
  2364. """
  2365. ),
  2366. ] = None,
  2367. tags: Annotated[
  2368. list[str | Enum] | None,
  2369. Doc(
  2370. """
  2371. A list of tags to be applied to the *path operation*.
  2372. It will be added to the generated OpenAPI (e.g. visible at `/docs`).
  2373. Read more about it in the
  2374. [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#tags).
  2375. """
  2376. ),
  2377. ] = None,
  2378. dependencies: Annotated[
  2379. Sequence[params.Depends] | None,
  2380. Doc(
  2381. """
  2382. A list of dependencies (using `Depends()`) to be applied to the
  2383. *path operation*.
  2384. Read more about it in the
  2385. [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/).
  2386. """
  2387. ),
  2388. ] = None,
  2389. summary: Annotated[
  2390. str | None,
  2391. Doc(
  2392. """
  2393. A summary for the *path operation*.
  2394. It will be added to the generated OpenAPI (e.g. visible at `/docs`).
  2395. Read more about it in the
  2396. [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).
  2397. """
  2398. ),
  2399. ] = None,
  2400. description: Annotated[
  2401. str | None,
  2402. Doc(
  2403. """
  2404. A description for the *path operation*.
  2405. If not provided, it will be extracted automatically from the docstring
  2406. of the *path operation function*.
  2407. It can contain Markdown.
  2408. It will be added to the generated OpenAPI (e.g. visible at `/docs`).
  2409. Read more about it in the
  2410. [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).
  2411. """
  2412. ),
  2413. ] = None,
  2414. response_description: Annotated[
  2415. str,
  2416. Doc(
  2417. """
  2418. The description for the default response.
  2419. It will be added to the generated OpenAPI (e.g. visible at `/docs`).
  2420. """
  2421. ),
  2422. ] = "Successful Response",
  2423. responses: Annotated[
  2424. dict[int | str, dict[str, Any]] | None,
  2425. Doc(
  2426. """
  2427. Additional responses that could be returned by this *path operation*.
  2428. It will be added to the generated OpenAPI (e.g. visible at `/docs`).
  2429. """
  2430. ),
  2431. ] = None,
  2432. deprecated: Annotated[
  2433. bool | None,
  2434. Doc(
  2435. """
  2436. Mark this *path operation* as deprecated.
  2437. It will be added to the generated OpenAPI (e.g. visible at `/docs`).
  2438. """
  2439. ),
  2440. ] = None,
  2441. operation_id: Annotated[
  2442. str | None,
  2443. Doc(
  2444. """
  2445. Custom operation ID to be used by this *path operation*.
  2446. By default, it is generated automatically.
  2447. If you provide a custom operation ID, you need to make sure it is
  2448. unique for the whole API.
  2449. You can customize the
  2450. operation ID generation with the parameter
  2451. `generate_unique_id_function` in the `FastAPI` class.
  2452. Read more about it in the
  2453. [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).
  2454. """
  2455. ),
  2456. ] = None,
  2457. response_model_include: Annotated[
  2458. IncEx | None,
  2459. Doc(
  2460. """
  2461. Configuration passed to Pydantic to include only certain fields in the
  2462. response data.
  2463. Read more about it in the
  2464. [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).
  2465. """
  2466. ),
  2467. ] = None,
  2468. response_model_exclude: Annotated[
  2469. IncEx | None,
  2470. Doc(
  2471. """
  2472. Configuration passed to Pydantic to exclude certain fields in the
  2473. response data.
  2474. Read more about it in the
  2475. [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).
  2476. """
  2477. ),
  2478. ] = None,
  2479. response_model_by_alias: Annotated[
  2480. bool,
  2481. Doc(
  2482. """
  2483. Configuration passed to Pydantic to define if the response model
  2484. should be serialized by alias when an alias is used.
  2485. Read more about it in the
  2486. [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).
  2487. """
  2488. ),
  2489. ] = True,
  2490. response_model_exclude_unset: Annotated[
  2491. bool,
  2492. Doc(
  2493. """
  2494. Configuration passed to Pydantic to define if the response data
  2495. should have all the fields, including the ones that were not set and
  2496. have their default values. This is different from
  2497. `response_model_exclude_defaults` in that if the fields are set,
  2498. they will be included in the response, even if the value is the same
  2499. as the default.
  2500. When `True`, default values are omitted from the response.
  2501. Read more about it in the
  2502. [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).
  2503. """
  2504. ),
  2505. ] = False,
  2506. response_model_exclude_defaults: Annotated[
  2507. bool,
  2508. Doc(
  2509. """
  2510. Configuration passed to Pydantic to define if the response data
  2511. should have all the fields, including the ones that have the same value
  2512. as the default. This is different from `response_model_exclude_unset`
  2513. in that if the fields are set but contain the same default values,
  2514. they will be excluded from the response.
  2515. When `True`, default values are omitted from the response.
  2516. Read more about it in the
  2517. [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).
  2518. """
  2519. ),
  2520. ] = False,
  2521. response_model_exclude_none: Annotated[
  2522. bool,
  2523. Doc(
  2524. """
  2525. Configuration passed to Pydantic to define if the response data should
  2526. exclude fields set to `None`.
  2527. This is much simpler (less smart) than `response_model_exclude_unset`
  2528. and `response_model_exclude_defaults`. You probably want to use one of
  2529. those two instead of this one, as those allow returning `None` values
  2530. when it makes sense.
  2531. Read more about it in the
  2532. [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none).
  2533. """
  2534. ),
  2535. ] = False,
  2536. include_in_schema: Annotated[
  2537. bool,
  2538. Doc(
  2539. """
  2540. Include this *path operation* in the generated OpenAPI schema.
  2541. This affects the generated OpenAPI (e.g. visible at `/docs`).
  2542. Read more about it in the
  2543. [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-parameters-from-openapi).
  2544. """
  2545. ),
  2546. ] = True,
  2547. response_class: Annotated[
  2548. type[Response],
  2549. Doc(
  2550. """
  2551. Response class to be used for this *path operation*.
  2552. This will not be used if you return a response directly.
  2553. Read more about it in the
  2554. [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse).
  2555. """
  2556. ),
  2557. ] = Default(JSONResponse),
  2558. name: Annotated[
  2559. str | None,
  2560. Doc(
  2561. """
  2562. Name for this *path operation*. Only used internally.
  2563. """
  2564. ),
  2565. ] = None,
  2566. callbacks: Annotated[
  2567. list[BaseRoute] | None,
  2568. Doc(
  2569. """
  2570. List of *path operations* that will be used as OpenAPI callbacks.
  2571. This is only for OpenAPI documentation, the callbacks won't be used
  2572. directly.
  2573. It will be added to the generated OpenAPI (e.g. visible at `/docs`).
  2574. Read more about it in the
  2575. [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/).
  2576. """
  2577. ),
  2578. ] = None,
  2579. openapi_extra: Annotated[
  2580. dict[str, Any] | None,
  2581. Doc(
  2582. """
  2583. Extra metadata to be included in the OpenAPI schema for this *path
  2584. operation*.
  2585. Read more about it in the
  2586. [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema).
  2587. """
  2588. ),
  2589. ] = None,
  2590. generate_unique_id_function: Annotated[
  2591. Callable[[APIRoute], str],
  2592. Doc(
  2593. """
  2594. Customize the function used to generate unique IDs for the *path
  2595. operations* shown in the generated OpenAPI.
  2596. This is particularly useful when automatically generating clients or
  2597. SDKs for your API.
  2598. Read more about it in the
  2599. [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).
  2600. """
  2601. ),
  2602. ] = Default(generate_unique_id),
  2603. ) -> Callable[[DecoratedCallable], DecoratedCallable]:
  2604. """
  2605. Add a *path operation* using an HTTP POST operation.
  2606. ## Example
  2607. ```python
  2608. from fastapi import APIRouter, FastAPI
  2609. from pydantic import BaseModel
  2610. class Item(BaseModel):
  2611. name: str
  2612. description: str | None = None
  2613. app = FastAPI()
  2614. router = APIRouter()
  2615. @router.post("/items/")
  2616. def create_item(item: Item):
  2617. return {"message": "Item created"}
  2618. app.include_router(router)
  2619. ```
  2620. """
  2621. return self.api_route(
  2622. path=path,
  2623. response_model=response_model,
  2624. status_code=status_code,
  2625. tags=tags,
  2626. dependencies=dependencies,
  2627. summary=summary,
  2628. description=description,
  2629. response_description=response_description,
  2630. responses=responses,
  2631. deprecated=deprecated,
  2632. methods=["POST"],
  2633. operation_id=operation_id,
  2634. response_model_include=response_model_include,
  2635. response_model_exclude=response_model_exclude,
  2636. response_model_by_alias=response_model_by_alias,
  2637. response_model_exclude_unset=response_model_exclude_unset,
  2638. response_model_exclude_defaults=response_model_exclude_defaults,
  2639. response_model_exclude_none=response_model_exclude_none,
  2640. include_in_schema=include_in_schema,
  2641. response_class=response_class,
  2642. name=name,
  2643. callbacks=callbacks,
  2644. openapi_extra=openapi_extra,
  2645. generate_unique_id_function=generate_unique_id_function,
  2646. )
  2647. def delete(
  2648. self,
  2649. path: Annotated[
  2650. str,
  2651. Doc(
  2652. """
  2653. The URL path to be used for this *path operation*.
  2654. For example, in `http://example.com/items`, the path is `/items`.
  2655. """
  2656. ),
  2657. ],
  2658. *,
  2659. response_model: Annotated[
  2660. Any,
  2661. Doc(
  2662. """
  2663. The type to use for the response.
  2664. It could be any valid Pydantic *field* type. So, it doesn't have to
  2665. be a Pydantic model, it could be other things, like a `list`, `dict`,
  2666. etc.
  2667. It will be used for:
  2668. * Documentation: the generated OpenAPI (and the UI at `/docs`) will
  2669. show it as the response (JSON Schema).
  2670. * Serialization: you could return an arbitrary object and the
  2671. `response_model` would be used to serialize that object into the
  2672. corresponding JSON.
  2673. * Filtering: the JSON sent to the client will only contain the data
  2674. (fields) defined in the `response_model`. If you returned an object
  2675. that contains an attribute `password` but the `response_model` does
  2676. not include that field, the JSON sent to the client would not have
  2677. that `password`.
  2678. * Validation: whatever you return will be serialized with the
  2679. `response_model`, converting any data as necessary to generate the
  2680. corresponding JSON. But if the data in the object returned is not
  2681. valid, that would mean a violation of the contract with the client,
  2682. so it's an error from the API developer. So, FastAPI will raise an
  2683. error and return a 500 error code (Internal Server Error).
  2684. Read more about it in the
  2685. [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/).
  2686. """
  2687. ),
  2688. ] = Default(None),
  2689. status_code: Annotated[
  2690. int | None,
  2691. Doc(
  2692. """
  2693. The default status code to be used for the response.
  2694. You could override the status code by returning a response directly.
  2695. Read more about it in the
  2696. [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/).
  2697. """
  2698. ),
  2699. ] = None,
  2700. tags: Annotated[
  2701. list[str | Enum] | None,
  2702. Doc(
  2703. """
  2704. A list of tags to be applied to the *path operation*.
  2705. It will be added to the generated OpenAPI (e.g. visible at `/docs`).
  2706. Read more about it in the
  2707. [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#tags).
  2708. """
  2709. ),
  2710. ] = None,
  2711. dependencies: Annotated[
  2712. Sequence[params.Depends] | None,
  2713. Doc(
  2714. """
  2715. A list of dependencies (using `Depends()`) to be applied to the
  2716. *path operation*.
  2717. Read more about it in the
  2718. [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/).
  2719. """
  2720. ),
  2721. ] = None,
  2722. summary: Annotated[
  2723. str | None,
  2724. Doc(
  2725. """
  2726. A summary for the *path operation*.
  2727. It will be added to the generated OpenAPI (e.g. visible at `/docs`).
  2728. Read more about it in the
  2729. [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).
  2730. """
  2731. ),
  2732. ] = None,
  2733. description: Annotated[
  2734. str | None,
  2735. Doc(
  2736. """
  2737. A description for the *path operation*.
  2738. If not provided, it will be extracted automatically from the docstring
  2739. of the *path operation function*.
  2740. It can contain Markdown.
  2741. It will be added to the generated OpenAPI (e.g. visible at `/docs`).
  2742. Read more about it in the
  2743. [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).
  2744. """
  2745. ),
  2746. ] = None,
  2747. response_description: Annotated[
  2748. str,
  2749. Doc(
  2750. """
  2751. The description for the default response.
  2752. It will be added to the generated OpenAPI (e.g. visible at `/docs`).
  2753. """
  2754. ),
  2755. ] = "Successful Response",
  2756. responses: Annotated[
  2757. dict[int | str, dict[str, Any]] | None,
  2758. Doc(
  2759. """
  2760. Additional responses that could be returned by this *path operation*.
  2761. It will be added to the generated OpenAPI (e.g. visible at `/docs`).
  2762. """
  2763. ),
  2764. ] = None,
  2765. deprecated: Annotated[
  2766. bool | None,
  2767. Doc(
  2768. """
  2769. Mark this *path operation* as deprecated.
  2770. It will be added to the generated OpenAPI (e.g. visible at `/docs`).
  2771. """
  2772. ),
  2773. ] = None,
  2774. operation_id: Annotated[
  2775. str | None,
  2776. Doc(
  2777. """
  2778. Custom operation ID to be used by this *path operation*.
  2779. By default, it is generated automatically.
  2780. If you provide a custom operation ID, you need to make sure it is
  2781. unique for the whole API.
  2782. You can customize the
  2783. operation ID generation with the parameter
  2784. `generate_unique_id_function` in the `FastAPI` class.
  2785. Read more about it in the
  2786. [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).
  2787. """
  2788. ),
  2789. ] = None,
  2790. response_model_include: Annotated[
  2791. IncEx | None,
  2792. Doc(
  2793. """
  2794. Configuration passed to Pydantic to include only certain fields in the
  2795. response data.
  2796. Read more about it in the
  2797. [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).
  2798. """
  2799. ),
  2800. ] = None,
  2801. response_model_exclude: Annotated[
  2802. IncEx | None,
  2803. Doc(
  2804. """
  2805. Configuration passed to Pydantic to exclude certain fields in the
  2806. response data.
  2807. Read more about it in the
  2808. [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).
  2809. """
  2810. ),
  2811. ] = None,
  2812. response_model_by_alias: Annotated[
  2813. bool,
  2814. Doc(
  2815. """
  2816. Configuration passed to Pydantic to define if the response model
  2817. should be serialized by alias when an alias is used.
  2818. Read more about it in the
  2819. [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).
  2820. """
  2821. ),
  2822. ] = True,
  2823. response_model_exclude_unset: Annotated[
  2824. bool,
  2825. Doc(
  2826. """
  2827. Configuration passed to Pydantic to define if the response data
  2828. should have all the fields, including the ones that were not set and
  2829. have their default values. This is different from
  2830. `response_model_exclude_defaults` in that if the fields are set,
  2831. they will be included in the response, even if the value is the same
  2832. as the default.
  2833. When `True`, default values are omitted from the response.
  2834. Read more about it in the
  2835. [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).
  2836. """
  2837. ),
  2838. ] = False,
  2839. response_model_exclude_defaults: Annotated[
  2840. bool,
  2841. Doc(
  2842. """
  2843. Configuration passed to Pydantic to define if the response data
  2844. should have all the fields, including the ones that have the same value
  2845. as the default. This is different from `response_model_exclude_unset`
  2846. in that if the fields are set but contain the same default values,
  2847. they will be excluded from the response.
  2848. When `True`, default values are omitted from the response.
  2849. Read more about it in the
  2850. [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).
  2851. """
  2852. ),
  2853. ] = False,
  2854. response_model_exclude_none: Annotated[
  2855. bool,
  2856. Doc(
  2857. """
  2858. Configuration passed to Pydantic to define if the response data should
  2859. exclude fields set to `None`.
  2860. This is much simpler (less smart) than `response_model_exclude_unset`
  2861. and `response_model_exclude_defaults`. You probably want to use one of
  2862. those two instead of this one, as those allow returning `None` values
  2863. when it makes sense.
  2864. Read more about it in the
  2865. [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none).
  2866. """
  2867. ),
  2868. ] = False,
  2869. include_in_schema: Annotated[
  2870. bool,
  2871. Doc(
  2872. """
  2873. Include this *path operation* in the generated OpenAPI schema.
  2874. This affects the generated OpenAPI (e.g. visible at `/docs`).
  2875. Read more about it in the
  2876. [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-parameters-from-openapi).
  2877. """
  2878. ),
  2879. ] = True,
  2880. response_class: Annotated[
  2881. type[Response],
  2882. Doc(
  2883. """
  2884. Response class to be used for this *path operation*.
  2885. This will not be used if you return a response directly.
  2886. Read more about it in the
  2887. [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse).
  2888. """
  2889. ),
  2890. ] = Default(JSONResponse),
  2891. name: Annotated[
  2892. str | None,
  2893. Doc(
  2894. """
  2895. Name for this *path operation*. Only used internally.
  2896. """
  2897. ),
  2898. ] = None,
  2899. callbacks: Annotated[
  2900. list[BaseRoute] | None,
  2901. Doc(
  2902. """
  2903. List of *path operations* that will be used as OpenAPI callbacks.
  2904. This is only for OpenAPI documentation, the callbacks won't be used
  2905. directly.
  2906. It will be added to the generated OpenAPI (e.g. visible at `/docs`).
  2907. Read more about it in the
  2908. [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/).
  2909. """
  2910. ),
  2911. ] = None,
  2912. openapi_extra: Annotated[
  2913. dict[str, Any] | None,
  2914. Doc(
  2915. """
  2916. Extra metadata to be included in the OpenAPI schema for this *path
  2917. operation*.
  2918. Read more about it in the
  2919. [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema).
  2920. """
  2921. ),
  2922. ] = None,
  2923. generate_unique_id_function: Annotated[
  2924. Callable[[APIRoute], str],
  2925. Doc(
  2926. """
  2927. Customize the function used to generate unique IDs for the *path
  2928. operations* shown in the generated OpenAPI.
  2929. This is particularly useful when automatically generating clients or
  2930. SDKs for your API.
  2931. Read more about it in the
  2932. [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).
  2933. """
  2934. ),
  2935. ] = Default(generate_unique_id),
  2936. ) -> Callable[[DecoratedCallable], DecoratedCallable]:
  2937. """
  2938. Add a *path operation* using an HTTP DELETE operation.
  2939. ## Example
  2940. ```python
  2941. from fastapi import APIRouter, FastAPI
  2942. app = FastAPI()
  2943. router = APIRouter()
  2944. @router.delete("/items/{item_id}")
  2945. def delete_item(item_id: str):
  2946. return {"message": "Item deleted"}
  2947. app.include_router(router)
  2948. ```
  2949. """
  2950. return self.api_route(
  2951. path=path,
  2952. response_model=response_model,
  2953. status_code=status_code,
  2954. tags=tags,
  2955. dependencies=dependencies,
  2956. summary=summary,
  2957. description=description,
  2958. response_description=response_description,
  2959. responses=responses,
  2960. deprecated=deprecated,
  2961. methods=["DELETE"],
  2962. operation_id=operation_id,
  2963. response_model_include=response_model_include,
  2964. response_model_exclude=response_model_exclude,
  2965. response_model_by_alias=response_model_by_alias,
  2966. response_model_exclude_unset=response_model_exclude_unset,
  2967. response_model_exclude_defaults=response_model_exclude_defaults,
  2968. response_model_exclude_none=response_model_exclude_none,
  2969. include_in_schema=include_in_schema,
  2970. response_class=response_class,
  2971. name=name,
  2972. callbacks=callbacks,
  2973. openapi_extra=openapi_extra,
  2974. generate_unique_id_function=generate_unique_id_function,
  2975. )
  2976. def options(
  2977. self,
  2978. path: Annotated[
  2979. str,
  2980. Doc(
  2981. """
  2982. The URL path to be used for this *path operation*.
  2983. For example, in `http://example.com/items`, the path is `/items`.
  2984. """
  2985. ),
  2986. ],
  2987. *,
  2988. response_model: Annotated[
  2989. Any,
  2990. Doc(
  2991. """
  2992. The type to use for the response.
  2993. It could be any valid Pydantic *field* type. So, it doesn't have to
  2994. be a Pydantic model, it could be other things, like a `list`, `dict`,
  2995. etc.
  2996. It will be used for:
  2997. * Documentation: the generated OpenAPI (and the UI at `/docs`) will
  2998. show it as the response (JSON Schema).
  2999. * Serialization: you could return an arbitrary object and the
  3000. `response_model` would be used to serialize that object into the
  3001. corresponding JSON.
  3002. * Filtering: the JSON sent to the client will only contain the data
  3003. (fields) defined in the `response_model`. If you returned an object
  3004. that contains an attribute `password` but the `response_model` does
  3005. not include that field, the JSON sent to the client would not have
  3006. that `password`.
  3007. * Validation: whatever you return will be serialized with the
  3008. `response_model`, converting any data as necessary to generate the
  3009. corresponding JSON. But if the data in the object returned is not
  3010. valid, that would mean a violation of the contract with the client,
  3011. so it's an error from the API developer. So, FastAPI will raise an
  3012. error and return a 500 error code (Internal Server Error).
  3013. Read more about it in the
  3014. [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/).
  3015. """
  3016. ),
  3017. ] = Default(None),
  3018. status_code: Annotated[
  3019. int | None,
  3020. Doc(
  3021. """
  3022. The default status code to be used for the response.
  3023. You could override the status code by returning a response directly.
  3024. Read more about it in the
  3025. [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/).
  3026. """
  3027. ),
  3028. ] = None,
  3029. tags: Annotated[
  3030. list[str | Enum] | None,
  3031. Doc(
  3032. """
  3033. A list of tags to be applied to the *path operation*.
  3034. It will be added to the generated OpenAPI (e.g. visible at `/docs`).
  3035. Read more about it in the
  3036. [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#tags).
  3037. """
  3038. ),
  3039. ] = None,
  3040. dependencies: Annotated[
  3041. Sequence[params.Depends] | None,
  3042. Doc(
  3043. """
  3044. A list of dependencies (using `Depends()`) to be applied to the
  3045. *path operation*.
  3046. Read more about it in the
  3047. [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/).
  3048. """
  3049. ),
  3050. ] = None,
  3051. summary: Annotated[
  3052. str | None,
  3053. Doc(
  3054. """
  3055. A summary for the *path operation*.
  3056. It will be added to the generated OpenAPI (e.g. visible at `/docs`).
  3057. Read more about it in the
  3058. [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).
  3059. """
  3060. ),
  3061. ] = None,
  3062. description: Annotated[
  3063. str | None,
  3064. Doc(
  3065. """
  3066. A description for the *path operation*.
  3067. If not provided, it will be extracted automatically from the docstring
  3068. of the *path operation function*.
  3069. It can contain Markdown.
  3070. It will be added to the generated OpenAPI (e.g. visible at `/docs`).
  3071. Read more about it in the
  3072. [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).
  3073. """
  3074. ),
  3075. ] = None,
  3076. response_description: Annotated[
  3077. str,
  3078. Doc(
  3079. """
  3080. The description for the default response.
  3081. It will be added to the generated OpenAPI (e.g. visible at `/docs`).
  3082. """
  3083. ),
  3084. ] = "Successful Response",
  3085. responses: Annotated[
  3086. dict[int | str, dict[str, Any]] | None,
  3087. Doc(
  3088. """
  3089. Additional responses that could be returned by this *path operation*.
  3090. It will be added to the generated OpenAPI (e.g. visible at `/docs`).
  3091. """
  3092. ),
  3093. ] = None,
  3094. deprecated: Annotated[
  3095. bool | None,
  3096. Doc(
  3097. """
  3098. Mark this *path operation* as deprecated.
  3099. It will be added to the generated OpenAPI (e.g. visible at `/docs`).
  3100. """
  3101. ),
  3102. ] = None,
  3103. operation_id: Annotated[
  3104. str | None,
  3105. Doc(
  3106. """
  3107. Custom operation ID to be used by this *path operation*.
  3108. By default, it is generated automatically.
  3109. If you provide a custom operation ID, you need to make sure it is
  3110. unique for the whole API.
  3111. You can customize the
  3112. operation ID generation with the parameter
  3113. `generate_unique_id_function` in the `FastAPI` class.
  3114. Read more about it in the
  3115. [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).
  3116. """
  3117. ),
  3118. ] = None,
  3119. response_model_include: Annotated[
  3120. IncEx | None,
  3121. Doc(
  3122. """
  3123. Configuration passed to Pydantic to include only certain fields in the
  3124. response data.
  3125. Read more about it in the
  3126. [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).
  3127. """
  3128. ),
  3129. ] = None,
  3130. response_model_exclude: Annotated[
  3131. IncEx | None,
  3132. Doc(
  3133. """
  3134. Configuration passed to Pydantic to exclude certain fields in the
  3135. response data.
  3136. Read more about it in the
  3137. [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).
  3138. """
  3139. ),
  3140. ] = None,
  3141. response_model_by_alias: Annotated[
  3142. bool,
  3143. Doc(
  3144. """
  3145. Configuration passed to Pydantic to define if the response model
  3146. should be serialized by alias when an alias is used.
  3147. Read more about it in the
  3148. [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).
  3149. """
  3150. ),
  3151. ] = True,
  3152. response_model_exclude_unset: Annotated[
  3153. bool,
  3154. Doc(
  3155. """
  3156. Configuration passed to Pydantic to define if the response data
  3157. should have all the fields, including the ones that were not set and
  3158. have their default values. This is different from
  3159. `response_model_exclude_defaults` in that if the fields are set,
  3160. they will be included in the response, even if the value is the same
  3161. as the default.
  3162. When `True`, default values are omitted from the response.
  3163. Read more about it in the
  3164. [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).
  3165. """
  3166. ),
  3167. ] = False,
  3168. response_model_exclude_defaults: Annotated[
  3169. bool,
  3170. Doc(
  3171. """
  3172. Configuration passed to Pydantic to define if the response data
  3173. should have all the fields, including the ones that have the same value
  3174. as the default. This is different from `response_model_exclude_unset`
  3175. in that if the fields are set but contain the same default values,
  3176. they will be excluded from the response.
  3177. When `True`, default values are omitted from the response.
  3178. Read more about it in the
  3179. [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).
  3180. """
  3181. ),
  3182. ] = False,
  3183. response_model_exclude_none: Annotated[
  3184. bool,
  3185. Doc(
  3186. """
  3187. Configuration passed to Pydantic to define if the response data should
  3188. exclude fields set to `None`.
  3189. This is much simpler (less smart) than `response_model_exclude_unset`
  3190. and `response_model_exclude_defaults`. You probably want to use one of
  3191. those two instead of this one, as those allow returning `None` values
  3192. when it makes sense.
  3193. Read more about it in the
  3194. [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none).
  3195. """
  3196. ),
  3197. ] = False,
  3198. include_in_schema: Annotated[
  3199. bool,
  3200. Doc(
  3201. """
  3202. Include this *path operation* in the generated OpenAPI schema.
  3203. This affects the generated OpenAPI (e.g. visible at `/docs`).
  3204. Read more about it in the
  3205. [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-parameters-from-openapi).
  3206. """
  3207. ),
  3208. ] = True,
  3209. response_class: Annotated[
  3210. type[Response],
  3211. Doc(
  3212. """
  3213. Response class to be used for this *path operation*.
  3214. This will not be used if you return a response directly.
  3215. Read more about it in the
  3216. [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse).
  3217. """
  3218. ),
  3219. ] = Default(JSONResponse),
  3220. name: Annotated[
  3221. str | None,
  3222. Doc(
  3223. """
  3224. Name for this *path operation*. Only used internally.
  3225. """
  3226. ),
  3227. ] = None,
  3228. callbacks: Annotated[
  3229. list[BaseRoute] | None,
  3230. Doc(
  3231. """
  3232. List of *path operations* that will be used as OpenAPI callbacks.
  3233. This is only for OpenAPI documentation, the callbacks won't be used
  3234. directly.
  3235. It will be added to the generated OpenAPI (e.g. visible at `/docs`).
  3236. Read more about it in the
  3237. [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/).
  3238. """
  3239. ),
  3240. ] = None,
  3241. openapi_extra: Annotated[
  3242. dict[str, Any] | None,
  3243. Doc(
  3244. """
  3245. Extra metadata to be included in the OpenAPI schema for this *path
  3246. operation*.
  3247. Read more about it in the
  3248. [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema).
  3249. """
  3250. ),
  3251. ] = None,
  3252. generate_unique_id_function: Annotated[
  3253. Callable[[APIRoute], str],
  3254. Doc(
  3255. """
  3256. Customize the function used to generate unique IDs for the *path
  3257. operations* shown in the generated OpenAPI.
  3258. This is particularly useful when automatically generating clients or
  3259. SDKs for your API.
  3260. Read more about it in the
  3261. [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).
  3262. """
  3263. ),
  3264. ] = Default(generate_unique_id),
  3265. ) -> Callable[[DecoratedCallable], DecoratedCallable]:
  3266. """
  3267. Add a *path operation* using an HTTP OPTIONS operation.
  3268. ## Example
  3269. ```python
  3270. from fastapi import APIRouter, FastAPI
  3271. app = FastAPI()
  3272. router = APIRouter()
  3273. @router.options("/items/")
  3274. def get_item_options():
  3275. return {"additions": ["Aji", "Guacamole"]}
  3276. app.include_router(router)
  3277. ```
  3278. """
  3279. return self.api_route(
  3280. path=path,
  3281. response_model=response_model,
  3282. status_code=status_code,
  3283. tags=tags,
  3284. dependencies=dependencies,
  3285. summary=summary,
  3286. description=description,
  3287. response_description=response_description,
  3288. responses=responses,
  3289. deprecated=deprecated,
  3290. methods=["OPTIONS"],
  3291. operation_id=operation_id,
  3292. response_model_include=response_model_include,
  3293. response_model_exclude=response_model_exclude,
  3294. response_model_by_alias=response_model_by_alias,
  3295. response_model_exclude_unset=response_model_exclude_unset,
  3296. response_model_exclude_defaults=response_model_exclude_defaults,
  3297. response_model_exclude_none=response_model_exclude_none,
  3298. include_in_schema=include_in_schema,
  3299. response_class=response_class,
  3300. name=name,
  3301. callbacks=callbacks,
  3302. openapi_extra=openapi_extra,
  3303. generate_unique_id_function=generate_unique_id_function,
  3304. )
  3305. def head(
  3306. self,
  3307. path: Annotated[
  3308. str,
  3309. Doc(
  3310. """
  3311. The URL path to be used for this *path operation*.
  3312. For example, in `http://example.com/items`, the path is `/items`.
  3313. """
  3314. ),
  3315. ],
  3316. *,
  3317. response_model: Annotated[
  3318. Any,
  3319. Doc(
  3320. """
  3321. The type to use for the response.
  3322. It could be any valid Pydantic *field* type. So, it doesn't have to
  3323. be a Pydantic model, it could be other things, like a `list`, `dict`,
  3324. etc.
  3325. It will be used for:
  3326. * Documentation: the generated OpenAPI (and the UI at `/docs`) will
  3327. show it as the response (JSON Schema).
  3328. * Serialization: you could return an arbitrary object and the
  3329. `response_model` would be used to serialize that object into the
  3330. corresponding JSON.
  3331. * Filtering: the JSON sent to the client will only contain the data
  3332. (fields) defined in the `response_model`. If you returned an object
  3333. that contains an attribute `password` but the `response_model` does
  3334. not include that field, the JSON sent to the client would not have
  3335. that `password`.
  3336. * Validation: whatever you return will be serialized with the
  3337. `response_model`, converting any data as necessary to generate the
  3338. corresponding JSON. But if the data in the object returned is not
  3339. valid, that would mean a violation of the contract with the client,
  3340. so it's an error from the API developer. So, FastAPI will raise an
  3341. error and return a 500 error code (Internal Server Error).
  3342. Read more about it in the
  3343. [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/).
  3344. """
  3345. ),
  3346. ] = Default(None),
  3347. status_code: Annotated[
  3348. int | None,
  3349. Doc(
  3350. """
  3351. The default status code to be used for the response.
  3352. You could override the status code by returning a response directly.
  3353. Read more about it in the
  3354. [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/).
  3355. """
  3356. ),
  3357. ] = None,
  3358. tags: Annotated[
  3359. list[str | Enum] | None,
  3360. Doc(
  3361. """
  3362. A list of tags to be applied to the *path operation*.
  3363. It will be added to the generated OpenAPI (e.g. visible at `/docs`).
  3364. Read more about it in the
  3365. [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#tags).
  3366. """
  3367. ),
  3368. ] = None,
  3369. dependencies: Annotated[
  3370. Sequence[params.Depends] | None,
  3371. Doc(
  3372. """
  3373. A list of dependencies (using `Depends()`) to be applied to the
  3374. *path operation*.
  3375. Read more about it in the
  3376. [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/).
  3377. """
  3378. ),
  3379. ] = None,
  3380. summary: Annotated[
  3381. str | None,
  3382. Doc(
  3383. """
  3384. A summary for the *path operation*.
  3385. It will be added to the generated OpenAPI (e.g. visible at `/docs`).
  3386. Read more about it in the
  3387. [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).
  3388. """
  3389. ),
  3390. ] = None,
  3391. description: Annotated[
  3392. str | None,
  3393. Doc(
  3394. """
  3395. A description for the *path operation*.
  3396. If not provided, it will be extracted automatically from the docstring
  3397. of the *path operation function*.
  3398. It can contain Markdown.
  3399. It will be added to the generated OpenAPI (e.g. visible at `/docs`).
  3400. Read more about it in the
  3401. [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).
  3402. """
  3403. ),
  3404. ] = None,
  3405. response_description: Annotated[
  3406. str,
  3407. Doc(
  3408. """
  3409. The description for the default response.
  3410. It will be added to the generated OpenAPI (e.g. visible at `/docs`).
  3411. """
  3412. ),
  3413. ] = "Successful Response",
  3414. responses: Annotated[
  3415. dict[int | str, dict[str, Any]] | None,
  3416. Doc(
  3417. """
  3418. Additional responses that could be returned by this *path operation*.
  3419. It will be added to the generated OpenAPI (e.g. visible at `/docs`).
  3420. """
  3421. ),
  3422. ] = None,
  3423. deprecated: Annotated[
  3424. bool | None,
  3425. Doc(
  3426. """
  3427. Mark this *path operation* as deprecated.
  3428. It will be added to the generated OpenAPI (e.g. visible at `/docs`).
  3429. """
  3430. ),
  3431. ] = None,
  3432. operation_id: Annotated[
  3433. str | None,
  3434. Doc(
  3435. """
  3436. Custom operation ID to be used by this *path operation*.
  3437. By default, it is generated automatically.
  3438. If you provide a custom operation ID, you need to make sure it is
  3439. unique for the whole API.
  3440. You can customize the
  3441. operation ID generation with the parameter
  3442. `generate_unique_id_function` in the `FastAPI` class.
  3443. Read more about it in the
  3444. [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).
  3445. """
  3446. ),
  3447. ] = None,
  3448. response_model_include: Annotated[
  3449. IncEx | None,
  3450. Doc(
  3451. """
  3452. Configuration passed to Pydantic to include only certain fields in the
  3453. response data.
  3454. Read more about it in the
  3455. [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).
  3456. """
  3457. ),
  3458. ] = None,
  3459. response_model_exclude: Annotated[
  3460. IncEx | None,
  3461. Doc(
  3462. """
  3463. Configuration passed to Pydantic to exclude certain fields in the
  3464. response data.
  3465. Read more about it in the
  3466. [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).
  3467. """
  3468. ),
  3469. ] = None,
  3470. response_model_by_alias: Annotated[
  3471. bool,
  3472. Doc(
  3473. """
  3474. Configuration passed to Pydantic to define if the response model
  3475. should be serialized by alias when an alias is used.
  3476. Read more about it in the
  3477. [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).
  3478. """
  3479. ),
  3480. ] = True,
  3481. response_model_exclude_unset: Annotated[
  3482. bool,
  3483. Doc(
  3484. """
  3485. Configuration passed to Pydantic to define if the response data
  3486. should have all the fields, including the ones that were not set and
  3487. have their default values. This is different from
  3488. `response_model_exclude_defaults` in that if the fields are set,
  3489. they will be included in the response, even if the value is the same
  3490. as the default.
  3491. When `True`, default values are omitted from the response.
  3492. Read more about it in the
  3493. [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).
  3494. """
  3495. ),
  3496. ] = False,
  3497. response_model_exclude_defaults: Annotated[
  3498. bool,
  3499. Doc(
  3500. """
  3501. Configuration passed to Pydantic to define if the response data
  3502. should have all the fields, including the ones that have the same value
  3503. as the default. This is different from `response_model_exclude_unset`
  3504. in that if the fields are set but contain the same default values,
  3505. they will be excluded from the response.
  3506. When `True`, default values are omitted from the response.
  3507. Read more about it in the
  3508. [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).
  3509. """
  3510. ),
  3511. ] = False,
  3512. response_model_exclude_none: Annotated[
  3513. bool,
  3514. Doc(
  3515. """
  3516. Configuration passed to Pydantic to define if the response data should
  3517. exclude fields set to `None`.
  3518. This is much simpler (less smart) than `response_model_exclude_unset`
  3519. and `response_model_exclude_defaults`. You probably want to use one of
  3520. those two instead of this one, as those allow returning `None` values
  3521. when it makes sense.
  3522. Read more about it in the
  3523. [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none).
  3524. """
  3525. ),
  3526. ] = False,
  3527. include_in_schema: Annotated[
  3528. bool,
  3529. Doc(
  3530. """
  3531. Include this *path operation* in the generated OpenAPI schema.
  3532. This affects the generated OpenAPI (e.g. visible at `/docs`).
  3533. Read more about it in the
  3534. [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-parameters-from-openapi).
  3535. """
  3536. ),
  3537. ] = True,
  3538. response_class: Annotated[
  3539. type[Response],
  3540. Doc(
  3541. """
  3542. Response class to be used for this *path operation*.
  3543. This will not be used if you return a response directly.
  3544. Read more about it in the
  3545. [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse).
  3546. """
  3547. ),
  3548. ] = Default(JSONResponse),
  3549. name: Annotated[
  3550. str | None,
  3551. Doc(
  3552. """
  3553. Name for this *path operation*. Only used internally.
  3554. """
  3555. ),
  3556. ] = None,
  3557. callbacks: Annotated[
  3558. list[BaseRoute] | None,
  3559. Doc(
  3560. """
  3561. List of *path operations* that will be used as OpenAPI callbacks.
  3562. This is only for OpenAPI documentation, the callbacks won't be used
  3563. directly.
  3564. It will be added to the generated OpenAPI (e.g. visible at `/docs`).
  3565. Read more about it in the
  3566. [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/).
  3567. """
  3568. ),
  3569. ] = None,
  3570. openapi_extra: Annotated[
  3571. dict[str, Any] | None,
  3572. Doc(
  3573. """
  3574. Extra metadata to be included in the OpenAPI schema for this *path
  3575. operation*.
  3576. Read more about it in the
  3577. [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema).
  3578. """
  3579. ),
  3580. ] = None,
  3581. generate_unique_id_function: Annotated[
  3582. Callable[[APIRoute], str],
  3583. Doc(
  3584. """
  3585. Customize the function used to generate unique IDs for the *path
  3586. operations* shown in the generated OpenAPI.
  3587. This is particularly useful when automatically generating clients or
  3588. SDKs for your API.
  3589. Read more about it in the
  3590. [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).
  3591. """
  3592. ),
  3593. ] = Default(generate_unique_id),
  3594. ) -> Callable[[DecoratedCallable], DecoratedCallable]:
  3595. """
  3596. Add a *path operation* using an HTTP HEAD operation.
  3597. ## Example
  3598. ```python
  3599. from fastapi import APIRouter, FastAPI
  3600. from pydantic import BaseModel
  3601. class Item(BaseModel):
  3602. name: str
  3603. description: str | None = None
  3604. app = FastAPI()
  3605. router = APIRouter()
  3606. @router.head("/items/", status_code=204)
  3607. def get_items_headers(response: Response):
  3608. response.headers["X-Cat-Dog"] = "Alone in the world"
  3609. app.include_router(router)
  3610. ```
  3611. """
  3612. return self.api_route(
  3613. path=path,
  3614. response_model=response_model,
  3615. status_code=status_code,
  3616. tags=tags,
  3617. dependencies=dependencies,
  3618. summary=summary,
  3619. description=description,
  3620. response_description=response_description,
  3621. responses=responses,
  3622. deprecated=deprecated,
  3623. methods=["HEAD"],
  3624. operation_id=operation_id,
  3625. response_model_include=response_model_include,
  3626. response_model_exclude=response_model_exclude,
  3627. response_model_by_alias=response_model_by_alias,
  3628. response_model_exclude_unset=response_model_exclude_unset,
  3629. response_model_exclude_defaults=response_model_exclude_defaults,
  3630. response_model_exclude_none=response_model_exclude_none,
  3631. include_in_schema=include_in_schema,
  3632. response_class=response_class,
  3633. name=name,
  3634. callbacks=callbacks,
  3635. openapi_extra=openapi_extra,
  3636. generate_unique_id_function=generate_unique_id_function,
  3637. )
  3638. def patch(
  3639. self,
  3640. path: Annotated[
  3641. str,
  3642. Doc(
  3643. """
  3644. The URL path to be used for this *path operation*.
  3645. For example, in `http://example.com/items`, the path is `/items`.
  3646. """
  3647. ),
  3648. ],
  3649. *,
  3650. response_model: Annotated[
  3651. Any,
  3652. Doc(
  3653. """
  3654. The type to use for the response.
  3655. It could be any valid Pydantic *field* type. So, it doesn't have to
  3656. be a Pydantic model, it could be other things, like a `list`, `dict`,
  3657. etc.
  3658. It will be used for:
  3659. * Documentation: the generated OpenAPI (and the UI at `/docs`) will
  3660. show it as the response (JSON Schema).
  3661. * Serialization: you could return an arbitrary object and the
  3662. `response_model` would be used to serialize that object into the
  3663. corresponding JSON.
  3664. * Filtering: the JSON sent to the client will only contain the data
  3665. (fields) defined in the `response_model`. If you returned an object
  3666. that contains an attribute `password` but the `response_model` does
  3667. not include that field, the JSON sent to the client would not have
  3668. that `password`.
  3669. * Validation: whatever you return will be serialized with the
  3670. `response_model`, converting any data as necessary to generate the
  3671. corresponding JSON. But if the data in the object returned is not
  3672. valid, that would mean a violation of the contract with the client,
  3673. so it's an error from the API developer. So, FastAPI will raise an
  3674. error and return a 500 error code (Internal Server Error).
  3675. Read more about it in the
  3676. [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/).
  3677. """
  3678. ),
  3679. ] = Default(None),
  3680. status_code: Annotated[
  3681. int | None,
  3682. Doc(
  3683. """
  3684. The default status code to be used for the response.
  3685. You could override the status code by returning a response directly.
  3686. Read more about it in the
  3687. [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/).
  3688. """
  3689. ),
  3690. ] = None,
  3691. tags: Annotated[
  3692. list[str | Enum] | None,
  3693. Doc(
  3694. """
  3695. A list of tags to be applied to the *path operation*.
  3696. It will be added to the generated OpenAPI (e.g. visible at `/docs`).
  3697. Read more about it in the
  3698. [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#tags).
  3699. """
  3700. ),
  3701. ] = None,
  3702. dependencies: Annotated[
  3703. Sequence[params.Depends] | None,
  3704. Doc(
  3705. """
  3706. A list of dependencies (using `Depends()`) to be applied to the
  3707. *path operation*.
  3708. Read more about it in the
  3709. [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/).
  3710. """
  3711. ),
  3712. ] = None,
  3713. summary: Annotated[
  3714. str | None,
  3715. Doc(
  3716. """
  3717. A summary for the *path operation*.
  3718. It will be added to the generated OpenAPI (e.g. visible at `/docs`).
  3719. Read more about it in the
  3720. [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).
  3721. """
  3722. ),
  3723. ] = None,
  3724. description: Annotated[
  3725. str | None,
  3726. Doc(
  3727. """
  3728. A description for the *path operation*.
  3729. If not provided, it will be extracted automatically from the docstring
  3730. of the *path operation function*.
  3731. It can contain Markdown.
  3732. It will be added to the generated OpenAPI (e.g. visible at `/docs`).
  3733. Read more about it in the
  3734. [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).
  3735. """
  3736. ),
  3737. ] = None,
  3738. response_description: Annotated[
  3739. str,
  3740. Doc(
  3741. """
  3742. The description for the default response.
  3743. It will be added to the generated OpenAPI (e.g. visible at `/docs`).
  3744. """
  3745. ),
  3746. ] = "Successful Response",
  3747. responses: Annotated[
  3748. dict[int | str, dict[str, Any]] | None,
  3749. Doc(
  3750. """
  3751. Additional responses that could be returned by this *path operation*.
  3752. It will be added to the generated OpenAPI (e.g. visible at `/docs`).
  3753. """
  3754. ),
  3755. ] = None,
  3756. deprecated: Annotated[
  3757. bool | None,
  3758. Doc(
  3759. """
  3760. Mark this *path operation* as deprecated.
  3761. It will be added to the generated OpenAPI (e.g. visible at `/docs`).
  3762. """
  3763. ),
  3764. ] = None,
  3765. operation_id: Annotated[
  3766. str | None,
  3767. Doc(
  3768. """
  3769. Custom operation ID to be used by this *path operation*.
  3770. By default, it is generated automatically.
  3771. If you provide a custom operation ID, you need to make sure it is
  3772. unique for the whole API.
  3773. You can customize the
  3774. operation ID generation with the parameter
  3775. `generate_unique_id_function` in the `FastAPI` class.
  3776. Read more about it in the
  3777. [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).
  3778. """
  3779. ),
  3780. ] = None,
  3781. response_model_include: Annotated[
  3782. IncEx | None,
  3783. Doc(
  3784. """
  3785. Configuration passed to Pydantic to include only certain fields in the
  3786. response data.
  3787. Read more about it in the
  3788. [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).
  3789. """
  3790. ),
  3791. ] = None,
  3792. response_model_exclude: Annotated[
  3793. IncEx | None,
  3794. Doc(
  3795. """
  3796. Configuration passed to Pydantic to exclude certain fields in the
  3797. response data.
  3798. Read more about it in the
  3799. [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).
  3800. """
  3801. ),
  3802. ] = None,
  3803. response_model_by_alias: Annotated[
  3804. bool,
  3805. Doc(
  3806. """
  3807. Configuration passed to Pydantic to define if the response model
  3808. should be serialized by alias when an alias is used.
  3809. Read more about it in the
  3810. [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).
  3811. """
  3812. ),
  3813. ] = True,
  3814. response_model_exclude_unset: Annotated[
  3815. bool,
  3816. Doc(
  3817. """
  3818. Configuration passed to Pydantic to define if the response data
  3819. should have all the fields, including the ones that were not set and
  3820. have their default values. This is different from
  3821. `response_model_exclude_defaults` in that if the fields are set,
  3822. they will be included in the response, even if the value is the same
  3823. as the default.
  3824. When `True`, default values are omitted from the response.
  3825. Read more about it in the
  3826. [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).
  3827. """
  3828. ),
  3829. ] = False,
  3830. response_model_exclude_defaults: Annotated[
  3831. bool,
  3832. Doc(
  3833. """
  3834. Configuration passed to Pydantic to define if the response data
  3835. should have all the fields, including the ones that have the same value
  3836. as the default. This is different from `response_model_exclude_unset`
  3837. in that if the fields are set but contain the same default values,
  3838. they will be excluded from the response.
  3839. When `True`, default values are omitted from the response.
  3840. Read more about it in the
  3841. [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).
  3842. """
  3843. ),
  3844. ] = False,
  3845. response_model_exclude_none: Annotated[
  3846. bool,
  3847. Doc(
  3848. """
  3849. Configuration passed to Pydantic to define if the response data should
  3850. exclude fields set to `None`.
  3851. This is much simpler (less smart) than `response_model_exclude_unset`
  3852. and `response_model_exclude_defaults`. You probably want to use one of
  3853. those two instead of this one, as those allow returning `None` values
  3854. when it makes sense.
  3855. Read more about it in the
  3856. [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none).
  3857. """
  3858. ),
  3859. ] = False,
  3860. include_in_schema: Annotated[
  3861. bool,
  3862. Doc(
  3863. """
  3864. Include this *path operation* in the generated OpenAPI schema.
  3865. This affects the generated OpenAPI (e.g. visible at `/docs`).
  3866. Read more about it in the
  3867. [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-parameters-from-openapi).
  3868. """
  3869. ),
  3870. ] = True,
  3871. response_class: Annotated[
  3872. type[Response],
  3873. Doc(
  3874. """
  3875. Response class to be used for this *path operation*.
  3876. This will not be used if you return a response directly.
  3877. Read more about it in the
  3878. [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse).
  3879. """
  3880. ),
  3881. ] = Default(JSONResponse),
  3882. name: Annotated[
  3883. str | None,
  3884. Doc(
  3885. """
  3886. Name for this *path operation*. Only used internally.
  3887. """
  3888. ),
  3889. ] = None,
  3890. callbacks: Annotated[
  3891. list[BaseRoute] | None,
  3892. Doc(
  3893. """
  3894. List of *path operations* that will be used as OpenAPI callbacks.
  3895. This is only for OpenAPI documentation, the callbacks won't be used
  3896. directly.
  3897. It will be added to the generated OpenAPI (e.g. visible at `/docs`).
  3898. Read more about it in the
  3899. [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/).
  3900. """
  3901. ),
  3902. ] = None,
  3903. openapi_extra: Annotated[
  3904. dict[str, Any] | None,
  3905. Doc(
  3906. """
  3907. Extra metadata to be included in the OpenAPI schema for this *path
  3908. operation*.
  3909. Read more about it in the
  3910. [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema).
  3911. """
  3912. ),
  3913. ] = None,
  3914. generate_unique_id_function: Annotated[
  3915. Callable[[APIRoute], str],
  3916. Doc(
  3917. """
  3918. Customize the function used to generate unique IDs for the *path
  3919. operations* shown in the generated OpenAPI.
  3920. This is particularly useful when automatically generating clients or
  3921. SDKs for your API.
  3922. Read more about it in the
  3923. [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).
  3924. """
  3925. ),
  3926. ] = Default(generate_unique_id),
  3927. ) -> Callable[[DecoratedCallable], DecoratedCallable]:
  3928. """
  3929. Add a *path operation* using an HTTP PATCH operation.
  3930. ## Example
  3931. ```python
  3932. from fastapi import APIRouter, FastAPI
  3933. from pydantic import BaseModel
  3934. class Item(BaseModel):
  3935. name: str
  3936. description: str | None = None
  3937. app = FastAPI()
  3938. router = APIRouter()
  3939. @router.patch("/items/")
  3940. def update_item(item: Item):
  3941. return {"message": "Item updated in place"}
  3942. app.include_router(router)
  3943. ```
  3944. """
  3945. return self.api_route(
  3946. path=path,
  3947. response_model=response_model,
  3948. status_code=status_code,
  3949. tags=tags,
  3950. dependencies=dependencies,
  3951. summary=summary,
  3952. description=description,
  3953. response_description=response_description,
  3954. responses=responses,
  3955. deprecated=deprecated,
  3956. methods=["PATCH"],
  3957. operation_id=operation_id,
  3958. response_model_include=response_model_include,
  3959. response_model_exclude=response_model_exclude,
  3960. response_model_by_alias=response_model_by_alias,
  3961. response_model_exclude_unset=response_model_exclude_unset,
  3962. response_model_exclude_defaults=response_model_exclude_defaults,
  3963. response_model_exclude_none=response_model_exclude_none,
  3964. include_in_schema=include_in_schema,
  3965. response_class=response_class,
  3966. name=name,
  3967. callbacks=callbacks,
  3968. openapi_extra=openapi_extra,
  3969. generate_unique_id_function=generate_unique_id_function,
  3970. )
  3971. def trace(
  3972. self,
  3973. path: Annotated[
  3974. str,
  3975. Doc(
  3976. """
  3977. The URL path to be used for this *path operation*.
  3978. For example, in `http://example.com/items`, the path is `/items`.
  3979. """
  3980. ),
  3981. ],
  3982. *,
  3983. response_model: Annotated[
  3984. Any,
  3985. Doc(
  3986. """
  3987. The type to use for the response.
  3988. It could be any valid Pydantic *field* type. So, it doesn't have to
  3989. be a Pydantic model, it could be other things, like a `list`, `dict`,
  3990. etc.
  3991. It will be used for:
  3992. * Documentation: the generated OpenAPI (and the UI at `/docs`) will
  3993. show it as the response (JSON Schema).
  3994. * Serialization: you could return an arbitrary object and the
  3995. `response_model` would be used to serialize that object into the
  3996. corresponding JSON.
  3997. * Filtering: the JSON sent to the client will only contain the data
  3998. (fields) defined in the `response_model`. If you returned an object
  3999. that contains an attribute `password` but the `response_model` does
  4000. not include that field, the JSON sent to the client would not have
  4001. that `password`.
  4002. * Validation: whatever you return will be serialized with the
  4003. `response_model`, converting any data as necessary to generate the
  4004. corresponding JSON. But if the data in the object returned is not
  4005. valid, that would mean a violation of the contract with the client,
  4006. so it's an error from the API developer. So, FastAPI will raise an
  4007. error and return a 500 error code (Internal Server Error).
  4008. Read more about it in the
  4009. [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/).
  4010. """
  4011. ),
  4012. ] = Default(None),
  4013. status_code: Annotated[
  4014. int | None,
  4015. Doc(
  4016. """
  4017. The default status code to be used for the response.
  4018. You could override the status code by returning a response directly.
  4019. Read more about it in the
  4020. [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/).
  4021. """
  4022. ),
  4023. ] = None,
  4024. tags: Annotated[
  4025. list[str | Enum] | None,
  4026. Doc(
  4027. """
  4028. A list of tags to be applied to the *path operation*.
  4029. It will be added to the generated OpenAPI (e.g. visible at `/docs`).
  4030. Read more about it in the
  4031. [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#tags).
  4032. """
  4033. ),
  4034. ] = None,
  4035. dependencies: Annotated[
  4036. Sequence[params.Depends] | None,
  4037. Doc(
  4038. """
  4039. A list of dependencies (using `Depends()`) to be applied to the
  4040. *path operation*.
  4041. Read more about it in the
  4042. [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/).
  4043. """
  4044. ),
  4045. ] = None,
  4046. summary: Annotated[
  4047. str | None,
  4048. Doc(
  4049. """
  4050. A summary for the *path operation*.
  4051. It will be added to the generated OpenAPI (e.g. visible at `/docs`).
  4052. Read more about it in the
  4053. [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).
  4054. """
  4055. ),
  4056. ] = None,
  4057. description: Annotated[
  4058. str | None,
  4059. Doc(
  4060. """
  4061. A description for the *path operation*.
  4062. If not provided, it will be extracted automatically from the docstring
  4063. of the *path operation function*.
  4064. It can contain Markdown.
  4065. It will be added to the generated OpenAPI (e.g. visible at `/docs`).
  4066. Read more about it in the
  4067. [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).
  4068. """
  4069. ),
  4070. ] = None,
  4071. response_description: Annotated[
  4072. str,
  4073. Doc(
  4074. """
  4075. The description for the default response.
  4076. It will be added to the generated OpenAPI (e.g. visible at `/docs`).
  4077. """
  4078. ),
  4079. ] = "Successful Response",
  4080. responses: Annotated[
  4081. dict[int | str, dict[str, Any]] | None,
  4082. Doc(
  4083. """
  4084. Additional responses that could be returned by this *path operation*.
  4085. It will be added to the generated OpenAPI (e.g. visible at `/docs`).
  4086. """
  4087. ),
  4088. ] = None,
  4089. deprecated: Annotated[
  4090. bool | None,
  4091. Doc(
  4092. """
  4093. Mark this *path operation* as deprecated.
  4094. It will be added to the generated OpenAPI (e.g. visible at `/docs`).
  4095. """
  4096. ),
  4097. ] = None,
  4098. operation_id: Annotated[
  4099. str | None,
  4100. Doc(
  4101. """
  4102. Custom operation ID to be used by this *path operation*.
  4103. By default, it is generated automatically.
  4104. If you provide a custom operation ID, you need to make sure it is
  4105. unique for the whole API.
  4106. You can customize the
  4107. operation ID generation with the parameter
  4108. `generate_unique_id_function` in the `FastAPI` class.
  4109. Read more about it in the
  4110. [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).
  4111. """
  4112. ),
  4113. ] = None,
  4114. response_model_include: Annotated[
  4115. IncEx | None,
  4116. Doc(
  4117. """
  4118. Configuration passed to Pydantic to include only certain fields in the
  4119. response data.
  4120. Read more about it in the
  4121. [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).
  4122. """
  4123. ),
  4124. ] = None,
  4125. response_model_exclude: Annotated[
  4126. IncEx | None,
  4127. Doc(
  4128. """
  4129. Configuration passed to Pydantic to exclude certain fields in the
  4130. response data.
  4131. Read more about it in the
  4132. [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).
  4133. """
  4134. ),
  4135. ] = None,
  4136. response_model_by_alias: Annotated[
  4137. bool,
  4138. Doc(
  4139. """
  4140. Configuration passed to Pydantic to define if the response model
  4141. should be serialized by alias when an alias is used.
  4142. Read more about it in the
  4143. [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).
  4144. """
  4145. ),
  4146. ] = True,
  4147. response_model_exclude_unset: Annotated[
  4148. bool,
  4149. Doc(
  4150. """
  4151. Configuration passed to Pydantic to define if the response data
  4152. should have all the fields, including the ones that were not set and
  4153. have their default values. This is different from
  4154. `response_model_exclude_defaults` in that if the fields are set,
  4155. they will be included in the response, even if the value is the same
  4156. as the default.
  4157. When `True`, default values are omitted from the response.
  4158. Read more about it in the
  4159. [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).
  4160. """
  4161. ),
  4162. ] = False,
  4163. response_model_exclude_defaults: Annotated[
  4164. bool,
  4165. Doc(
  4166. """
  4167. Configuration passed to Pydantic to define if the response data
  4168. should have all the fields, including the ones that have the same value
  4169. as the default. This is different from `response_model_exclude_unset`
  4170. in that if the fields are set but contain the same default values,
  4171. they will be excluded from the response.
  4172. When `True`, default values are omitted from the response.
  4173. Read more about it in the
  4174. [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).
  4175. """
  4176. ),
  4177. ] = False,
  4178. response_model_exclude_none: Annotated[
  4179. bool,
  4180. Doc(
  4181. """
  4182. Configuration passed to Pydantic to define if the response data should
  4183. exclude fields set to `None`.
  4184. This is much simpler (less smart) than `response_model_exclude_unset`
  4185. and `response_model_exclude_defaults`. You probably want to use one of
  4186. those two instead of this one, as those allow returning `None` values
  4187. when it makes sense.
  4188. Read more about it in the
  4189. [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none).
  4190. """
  4191. ),
  4192. ] = False,
  4193. include_in_schema: Annotated[
  4194. bool,
  4195. Doc(
  4196. """
  4197. Include this *path operation* in the generated OpenAPI schema.
  4198. This affects the generated OpenAPI (e.g. visible at `/docs`).
  4199. Read more about it in the
  4200. [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-parameters-from-openapi).
  4201. """
  4202. ),
  4203. ] = True,
  4204. response_class: Annotated[
  4205. type[Response],
  4206. Doc(
  4207. """
  4208. Response class to be used for this *path operation*.
  4209. This will not be used if you return a response directly.
  4210. Read more about it in the
  4211. [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse).
  4212. """
  4213. ),
  4214. ] = Default(JSONResponse),
  4215. name: Annotated[
  4216. str | None,
  4217. Doc(
  4218. """
  4219. Name for this *path operation*. Only used internally.
  4220. """
  4221. ),
  4222. ] = None,
  4223. callbacks: Annotated[
  4224. list[BaseRoute] | None,
  4225. Doc(
  4226. """
  4227. List of *path operations* that will be used as OpenAPI callbacks.
  4228. This is only for OpenAPI documentation, the callbacks won't be used
  4229. directly.
  4230. It will be added to the generated OpenAPI (e.g. visible at `/docs`).
  4231. Read more about it in the
  4232. [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/).
  4233. """
  4234. ),
  4235. ] = None,
  4236. openapi_extra: Annotated[
  4237. dict[str, Any] | None,
  4238. Doc(
  4239. """
  4240. Extra metadata to be included in the OpenAPI schema for this *path
  4241. operation*.
  4242. Read more about it in the
  4243. [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema).
  4244. """
  4245. ),
  4246. ] = None,
  4247. generate_unique_id_function: Annotated[
  4248. Callable[[APIRoute], str],
  4249. Doc(
  4250. """
  4251. Customize the function used to generate unique IDs for the *path
  4252. operations* shown in the generated OpenAPI.
  4253. This is particularly useful when automatically generating clients or
  4254. SDKs for your API.
  4255. Read more about it in the
  4256. [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).
  4257. """
  4258. ),
  4259. ] = Default(generate_unique_id),
  4260. ) -> Callable[[DecoratedCallable], DecoratedCallable]:
  4261. """
  4262. Add a *path operation* using an HTTP TRACE operation.
  4263. ## Example
  4264. ```python
  4265. from fastapi import APIRouter, FastAPI
  4266. from pydantic import BaseModel
  4267. class Item(BaseModel):
  4268. name: str
  4269. description: str | None = None
  4270. app = FastAPI()
  4271. router = APIRouter()
  4272. @router.trace("/items/{item_id}")
  4273. def trace_item(item_id: str):
  4274. return None
  4275. app.include_router(router)
  4276. ```
  4277. """
  4278. return self.api_route(
  4279. path=path,
  4280. response_model=response_model,
  4281. status_code=status_code,
  4282. tags=tags,
  4283. dependencies=dependencies,
  4284. summary=summary,
  4285. description=description,
  4286. response_description=response_description,
  4287. responses=responses,
  4288. deprecated=deprecated,
  4289. methods=["TRACE"],
  4290. operation_id=operation_id,
  4291. response_model_include=response_model_include,
  4292. response_model_exclude=response_model_exclude,
  4293. response_model_by_alias=response_model_by_alias,
  4294. response_model_exclude_unset=response_model_exclude_unset,
  4295. response_model_exclude_defaults=response_model_exclude_defaults,
  4296. response_model_exclude_none=response_model_exclude_none,
  4297. include_in_schema=include_in_schema,
  4298. response_class=response_class,
  4299. name=name,
  4300. callbacks=callbacks,
  4301. openapi_extra=openapi_extra,
  4302. generate_unique_id_function=generate_unique_id_function,
  4303. )
  4304. # TODO: remove this once the lifespan (or alternative) interface is improved
  4305. async def _startup(self) -> None:
  4306. """
  4307. Run any `.on_startup` event handlers.
  4308. This method is kept for backward compatibility after Starlette removed
  4309. support for on_startup/on_shutdown handlers.
  4310. Ref: https://github.com/Kludex/starlette/pull/3117
  4311. """
  4312. for handler in self.on_startup:
  4313. if is_async_callable(handler):
  4314. await handler()
  4315. else:
  4316. handler()
  4317. # TODO: remove this once the lifespan (or alternative) interface is improved
  4318. async def _shutdown(self) -> None:
  4319. """
  4320. Run any `.on_shutdown` event handlers.
  4321. This method is kept for backward compatibility after Starlette removed
  4322. support for on_startup/on_shutdown handlers.
  4323. Ref: https://github.com/Kludex/starlette/pull/3117
  4324. """
  4325. for handler in self.on_shutdown:
  4326. if is_async_callable(handler):
  4327. await handler()
  4328. else:
  4329. handler()
  4330. # TODO: remove this once the lifespan (or alternative) interface is improved
  4331. def add_event_handler(
  4332. self,
  4333. event_type: str,
  4334. func: Callable[[], Any],
  4335. ) -> None:
  4336. """
  4337. Add an event handler function for startup or shutdown.
  4338. This method is kept for backward compatibility after Starlette removed
  4339. support for on_startup/on_shutdown handlers.
  4340. Ref: https://github.com/Kludex/starlette/pull/3117
  4341. """
  4342. assert event_type in ("startup", "shutdown")
  4343. if event_type == "startup":
  4344. self.on_startup.append(func)
  4345. else:
  4346. self.on_shutdown.append(func)
  4347. @deprecated(
  4348. """
  4349. on_event is deprecated, use lifespan event handlers instead.
  4350. Read more about it in the
  4351. [FastAPI docs for Lifespan Events](https://fastapi.tiangolo.com/advanced/events/).
  4352. """
  4353. )
  4354. def on_event(
  4355. self,
  4356. event_type: Annotated[
  4357. str,
  4358. Doc(
  4359. """
  4360. The type of event. `startup` or `shutdown`.
  4361. """
  4362. ),
  4363. ],
  4364. ) -> Callable[[DecoratedCallable], DecoratedCallable]:
  4365. """
  4366. Add an event handler for the router.
  4367. `on_event` is deprecated, use `lifespan` event handlers instead.
  4368. Read more about it in the
  4369. [FastAPI docs for Lifespan Events](https://fastapi.tiangolo.com/advanced/events/#alternative-events-deprecated).
  4370. """
  4371. def decorator(func: DecoratedCallable) -> DecoratedCallable:
  4372. self.add_event_handler(event_type, func)
  4373. return func
  4374. return decorator