routing.py 172 KB

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