routing.py 168 KB

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