routing.py 174 KB

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