routing.py 170 KB

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