applications.py 175 KB

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