applications.py 176 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667
  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, ExceptionHandler, Lifespan, Receive, Scope, Send
  45. from typing_extensions import Annotated, Doc, deprecated
  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 `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-parameters-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. openapi_external_docs: Annotated[
  669. Optional[Dict[str, Any]],
  670. Doc(
  671. """
  672. This field allows you to provide additional external documentation links.
  673. If provided, it must be a dictionary containing:
  674. * `description`: A brief description of the external documentation.
  675. * `url`: The URL pointing to the external documentation. The value **MUST**
  676. be a valid URL format.
  677. **Example**:
  678. ```python
  679. from fastapi import FastAPI
  680. external_docs = {
  681. "description": "Detailed API Reference",
  682. "url": "https://example.com/api-docs",
  683. }
  684. app = FastAPI(openapi_external_docs=external_docs)
  685. ```
  686. """
  687. ),
  688. ] = None,
  689. **extra: Annotated[
  690. Any,
  691. Doc(
  692. """
  693. Extra keyword arguments to be stored in the app, not used by FastAPI
  694. anywhere.
  695. """
  696. ),
  697. ],
  698. ) -> None:
  699. self.debug = debug
  700. self.title = title
  701. self.summary = summary
  702. self.description = description
  703. self.version = version
  704. self.terms_of_service = terms_of_service
  705. self.contact = contact
  706. self.license_info = license_info
  707. self.openapi_url = openapi_url
  708. self.openapi_tags = openapi_tags
  709. self.root_path_in_servers = root_path_in_servers
  710. self.docs_url = docs_url
  711. self.redoc_url = redoc_url
  712. self.swagger_ui_oauth2_redirect_url = swagger_ui_oauth2_redirect_url
  713. self.swagger_ui_init_oauth = swagger_ui_init_oauth
  714. self.swagger_ui_parameters = swagger_ui_parameters
  715. self.servers = servers or []
  716. self.separate_input_output_schemas = separate_input_output_schemas
  717. self.openapi_external_docs = openapi_external_docs
  718. self.extra = extra
  719. self.openapi_version: Annotated[
  720. str,
  721. Doc(
  722. """
  723. The version string of OpenAPI.
  724. FastAPI will generate OpenAPI version 3.1.0, and will output that as
  725. the OpenAPI version. But some tools, even though they might be
  726. compatible with OpenAPI 3.1.0, might not recognize it as a valid.
  727. So you could override this value to trick those tools into using
  728. the generated OpenAPI. Have in mind that this is a hack. But if you
  729. avoid using features added in OpenAPI 3.1.0, it might work for your
  730. use case.
  731. This is not passed as a parameter to the `FastAPI` class to avoid
  732. giving the false idea that FastAPI would generate a different OpenAPI
  733. schema. It is only available as an attribute.
  734. **Example**
  735. ```python
  736. from fastapi import FastAPI
  737. app = FastAPI()
  738. app.openapi_version = "3.0.2"
  739. ```
  740. """
  741. ),
  742. ] = "3.1.0"
  743. self.openapi_schema: Optional[Dict[str, Any]] = None
  744. if self.openapi_url:
  745. assert self.title, "A title must be provided for OpenAPI, e.g.: 'My API'"
  746. assert self.version, "A version must be provided for OpenAPI, e.g.: '2.1.0'"
  747. # TODO: remove when discarding the openapi_prefix parameter
  748. if openapi_prefix:
  749. logger.warning(
  750. '"openapi_prefix" has been deprecated in favor of "root_path", which '
  751. "follows more closely the ASGI standard, is simpler, and more "
  752. "automatic. Check the docs at "
  753. "https://fastapi.tiangolo.com/advanced/sub-applications/"
  754. )
  755. self.webhooks: Annotated[
  756. routing.APIRouter,
  757. Doc(
  758. """
  759. The `app.webhooks` attribute is an `APIRouter` with the *path
  760. operations* that will be used just for documentation of webhooks.
  761. Read more about it in the
  762. [FastAPI docs for OpenAPI Webhooks](https://fastapi.tiangolo.com/advanced/openapi-webhooks/).
  763. """
  764. ),
  765. ] = webhooks or routing.APIRouter()
  766. self.root_path = root_path or openapi_prefix
  767. self.state: Annotated[
  768. State,
  769. Doc(
  770. """
  771. A state object for the application. This is the same object for the
  772. entire application, it doesn't change from request to request.
  773. You normally wouldn't use this in FastAPI, for most of the cases you
  774. would instead use FastAPI dependencies.
  775. This is simply inherited from Starlette.
  776. Read more about it in the
  777. [Starlette docs for Applications](https://www.starlette.io/applications/#storing-state-on-the-app-instance).
  778. """
  779. ),
  780. ] = State()
  781. self.dependency_overrides: Annotated[
  782. Dict[Callable[..., Any], Callable[..., Any]],
  783. Doc(
  784. """
  785. A dictionary with overrides for the dependencies.
  786. Each key is the original dependency callable, and the value is the
  787. actual dependency that should be called.
  788. This is for testing, to replace expensive dependencies with testing
  789. versions.
  790. Read more about it in the
  791. [FastAPI docs for Testing Dependencies with Overrides](https://fastapi.tiangolo.com/advanced/testing-dependencies/).
  792. """
  793. ),
  794. ] = {}
  795. self.router: routing.APIRouter = routing.APIRouter(
  796. routes=routes,
  797. redirect_slashes=redirect_slashes,
  798. dependency_overrides_provider=self,
  799. on_startup=on_startup,
  800. on_shutdown=on_shutdown,
  801. lifespan=lifespan,
  802. default_response_class=default_response_class,
  803. dependencies=dependencies,
  804. callbacks=callbacks,
  805. deprecated=deprecated,
  806. include_in_schema=include_in_schema,
  807. responses=responses,
  808. generate_unique_id_function=generate_unique_id_function,
  809. )
  810. self.exception_handlers: Dict[
  811. Any, Callable[[Request, Any], Union[Response, Awaitable[Response]]]
  812. ] = {} if exception_handlers is None else dict(exception_handlers)
  813. self.exception_handlers.setdefault(HTTPException, http_exception_handler)
  814. self.exception_handlers.setdefault(
  815. RequestValidationError, request_validation_exception_handler
  816. )
  817. self.exception_handlers.setdefault(
  818. WebSocketRequestValidationError,
  819. # Starlette still has incorrect type specification for the handlers
  820. websocket_request_validation_exception_handler, # type: ignore
  821. )
  822. self.user_middleware: List[Middleware] = (
  823. [] if middleware is None else list(middleware)
  824. )
  825. self.middleware_stack: Union[ASGIApp, None] = None
  826. self.setup()
  827. def build_middleware_stack(self) -> ASGIApp:
  828. # Duplicate/override from Starlette to add AsyncExitStackMiddleware
  829. # inside of ExceptionMiddleware, inside of custom user middlewares
  830. debug = self.debug
  831. error_handler = None
  832. exception_handlers: dict[Any, ExceptionHandler] = {}
  833. for key, value in self.exception_handlers.items():
  834. if key in (500, Exception):
  835. error_handler = value
  836. else:
  837. exception_handlers[key] = value
  838. middleware = (
  839. [Middleware(ServerErrorMiddleware, handler=error_handler, debug=debug)]
  840. + self.user_middleware
  841. + [
  842. Middleware(
  843. ExceptionMiddleware, handlers=exception_handlers, debug=debug
  844. ),
  845. # Add FastAPI-specific AsyncExitStackMiddleware for closing files.
  846. # Before this was also used for closing dependencies with yield but
  847. # those now have their own AsyncExitStack, to properly support
  848. # streaming responses while keeping compatibility with the previous
  849. # versions (as of writing 0.117.1) that allowed doing
  850. # except HTTPException inside a dependency with yield.
  851. # This needs to happen after user middlewares because those create a
  852. # new contextvars context copy by using a new AnyIO task group.
  853. # This AsyncExitStack preserves the context for contextvars, not
  854. # strictly necessary for closing files but it was one of the original
  855. # intentions.
  856. # If the AsyncExitStack lived outside of the custom middlewares and
  857. # contextvars were set, for example in a dependency with 'yield'
  858. # in that internal contextvars context, the values would not be
  859. # available in the outer context of the AsyncExitStack.
  860. # By placing the middleware and the AsyncExitStack here, inside all
  861. # user middlewares, the same context is used.
  862. # This is currently not needed, only for closing files, but used to be
  863. # important when dependencies with yield were closed here.
  864. Middleware(AsyncExitStackMiddleware),
  865. ]
  866. )
  867. app = self.router
  868. for cls, args, kwargs in reversed(middleware):
  869. app = cls(app, *args, **kwargs)
  870. return app
  871. def openapi(self) -> Dict[str, Any]:
  872. """
  873. Generate the OpenAPI schema of the application. This is called by FastAPI
  874. internally.
  875. The first time it is called it stores the result in the attribute
  876. `app.openapi_schema`, and next times it is called, it just returns that same
  877. result. To avoid the cost of generating the schema every time.
  878. If you need to modify the generated OpenAPI schema, you could modify it.
  879. Read more in the
  880. [FastAPI docs for OpenAPI](https://fastapi.tiangolo.com/how-to/extending-openapi/).
  881. """
  882. if not self.openapi_schema:
  883. self.openapi_schema = get_openapi(
  884. title=self.title,
  885. version=self.version,
  886. openapi_version=self.openapi_version,
  887. summary=self.summary,
  888. description=self.description,
  889. terms_of_service=self.terms_of_service,
  890. contact=self.contact,
  891. license_info=self.license_info,
  892. routes=self.routes,
  893. webhooks=self.webhooks.routes,
  894. tags=self.openapi_tags,
  895. servers=self.servers,
  896. separate_input_output_schemas=self.separate_input_output_schemas,
  897. external_docs=self.openapi_external_docs,
  898. )
  899. return self.openapi_schema
  900. def setup(self) -> None:
  901. if self.openapi_url:
  902. urls = (server_data.get("url") for server_data in self.servers)
  903. server_urls = {url for url in urls if url}
  904. async def openapi(req: Request) -> JSONResponse:
  905. root_path = req.scope.get("root_path", "").rstrip("/")
  906. if root_path not in server_urls:
  907. if root_path and self.root_path_in_servers:
  908. self.servers.insert(0, {"url": root_path})
  909. server_urls.add(root_path)
  910. return JSONResponse(self.openapi())
  911. self.add_route(self.openapi_url, openapi, include_in_schema=False)
  912. if self.openapi_url and self.docs_url:
  913. async def swagger_ui_html(req: Request) -> HTMLResponse:
  914. root_path = req.scope.get("root_path", "").rstrip("/")
  915. openapi_url = root_path + self.openapi_url
  916. oauth2_redirect_url = self.swagger_ui_oauth2_redirect_url
  917. if oauth2_redirect_url:
  918. oauth2_redirect_url = root_path + oauth2_redirect_url
  919. return get_swagger_ui_html(
  920. openapi_url=openapi_url,
  921. title=f"{self.title} - Swagger UI",
  922. oauth2_redirect_url=oauth2_redirect_url,
  923. init_oauth=self.swagger_ui_init_oauth,
  924. swagger_ui_parameters=self.swagger_ui_parameters,
  925. )
  926. self.add_route(self.docs_url, swagger_ui_html, include_in_schema=False)
  927. if self.swagger_ui_oauth2_redirect_url:
  928. async def swagger_ui_redirect(req: Request) -> HTMLResponse:
  929. return get_swagger_ui_oauth2_redirect_html()
  930. self.add_route(
  931. self.swagger_ui_oauth2_redirect_url,
  932. swagger_ui_redirect,
  933. include_in_schema=False,
  934. )
  935. if self.openapi_url and self.redoc_url:
  936. async def redoc_html(req: Request) -> HTMLResponse:
  937. root_path = req.scope.get("root_path", "").rstrip("/")
  938. openapi_url = root_path + self.openapi_url
  939. return get_redoc_html(
  940. openapi_url=openapi_url, title=f"{self.title} - ReDoc"
  941. )
  942. self.add_route(self.redoc_url, redoc_html, include_in_schema=False)
  943. async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None:
  944. if self.root_path:
  945. scope["root_path"] = self.root_path
  946. await super().__call__(scope, receive, send)
  947. def add_api_route(
  948. self,
  949. path: str,
  950. endpoint: Callable[..., Any],
  951. *,
  952. response_model: Any = Default(None),
  953. status_code: Optional[int] = None,
  954. tags: Optional[List[Union[str, Enum]]] = None,
  955. dependencies: Optional[Sequence[Depends]] = None,
  956. summary: Optional[str] = None,
  957. description: Optional[str] = None,
  958. response_description: str = "Successful Response",
  959. responses: Optional[Dict[Union[int, str], Dict[str, Any]]] = None,
  960. deprecated: Optional[bool] = None,
  961. methods: Optional[List[str]] = None,
  962. operation_id: Optional[str] = None,
  963. response_model_include: Optional[IncEx] = None,
  964. response_model_exclude: Optional[IncEx] = None,
  965. response_model_by_alias: bool = True,
  966. response_model_exclude_unset: bool = False,
  967. response_model_exclude_defaults: bool = False,
  968. response_model_exclude_none: bool = False,
  969. include_in_schema: bool = True,
  970. response_class: Union[Type[Response], DefaultPlaceholder] = Default(
  971. JSONResponse
  972. ),
  973. name: Optional[str] = None,
  974. openapi_extra: Optional[Dict[str, Any]] = None,
  975. generate_unique_id_function: Callable[[routing.APIRoute], str] = Default(
  976. generate_unique_id
  977. ),
  978. ) -> None:
  979. self.router.add_api_route(
  980. path,
  981. endpoint=endpoint,
  982. response_model=response_model,
  983. status_code=status_code,
  984. tags=tags,
  985. dependencies=dependencies,
  986. summary=summary,
  987. description=description,
  988. response_description=response_description,
  989. responses=responses,
  990. deprecated=deprecated,
  991. methods=methods,
  992. operation_id=operation_id,
  993. response_model_include=response_model_include,
  994. response_model_exclude=response_model_exclude,
  995. response_model_by_alias=response_model_by_alias,
  996. response_model_exclude_unset=response_model_exclude_unset,
  997. response_model_exclude_defaults=response_model_exclude_defaults,
  998. response_model_exclude_none=response_model_exclude_none,
  999. include_in_schema=include_in_schema,
  1000. response_class=response_class,
  1001. name=name,
  1002. openapi_extra=openapi_extra,
  1003. generate_unique_id_function=generate_unique_id_function,
  1004. )
  1005. def api_route(
  1006. self,
  1007. path: str,
  1008. *,
  1009. response_model: Any = Default(None),
  1010. status_code: Optional[int] = None,
  1011. tags: Optional[List[Union[str, Enum]]] = None,
  1012. dependencies: Optional[Sequence[Depends]] = None,
  1013. summary: Optional[str] = None,
  1014. description: Optional[str] = None,
  1015. response_description: str = "Successful Response",
  1016. responses: Optional[Dict[Union[int, str], Dict[str, Any]]] = None,
  1017. deprecated: Optional[bool] = None,
  1018. methods: Optional[List[str]] = None,
  1019. operation_id: Optional[str] = None,
  1020. response_model_include: Optional[IncEx] = None,
  1021. response_model_exclude: Optional[IncEx] = None,
  1022. response_model_by_alias: bool = True,
  1023. response_model_exclude_unset: bool = False,
  1024. response_model_exclude_defaults: bool = False,
  1025. response_model_exclude_none: bool = False,
  1026. include_in_schema: bool = True,
  1027. response_class: Type[Response] = Default(JSONResponse),
  1028. name: Optional[str] = None,
  1029. openapi_extra: Optional[Dict[str, Any]] = None,
  1030. generate_unique_id_function: Callable[[routing.APIRoute], str] = Default(
  1031. generate_unique_id
  1032. ),
  1033. ) -> Callable[[DecoratedCallable], DecoratedCallable]:
  1034. def decorator(func: DecoratedCallable) -> DecoratedCallable:
  1035. self.router.add_api_route(
  1036. path,
  1037. func,
  1038. response_model=response_model,
  1039. status_code=status_code,
  1040. tags=tags,
  1041. dependencies=dependencies,
  1042. summary=summary,
  1043. description=description,
  1044. response_description=response_description,
  1045. responses=responses,
  1046. deprecated=deprecated,
  1047. methods=methods,
  1048. operation_id=operation_id,
  1049. response_model_include=response_model_include,
  1050. response_model_exclude=response_model_exclude,
  1051. response_model_by_alias=response_model_by_alias,
  1052. response_model_exclude_unset=response_model_exclude_unset,
  1053. response_model_exclude_defaults=response_model_exclude_defaults,
  1054. response_model_exclude_none=response_model_exclude_none,
  1055. include_in_schema=include_in_schema,
  1056. response_class=response_class,
  1057. name=name,
  1058. openapi_extra=openapi_extra,
  1059. generate_unique_id_function=generate_unique_id_function,
  1060. )
  1061. return func
  1062. return decorator
  1063. def add_api_websocket_route(
  1064. self,
  1065. path: str,
  1066. endpoint: Callable[..., Any],
  1067. name: Optional[str] = None,
  1068. *,
  1069. dependencies: Optional[Sequence[Depends]] = None,
  1070. ) -> None:
  1071. self.router.add_api_websocket_route(
  1072. path,
  1073. endpoint,
  1074. name=name,
  1075. dependencies=dependencies,
  1076. )
  1077. def websocket(
  1078. self,
  1079. path: Annotated[
  1080. str,
  1081. Doc(
  1082. """
  1083. WebSocket path.
  1084. """
  1085. ),
  1086. ],
  1087. name: Annotated[
  1088. Optional[str],
  1089. Doc(
  1090. """
  1091. A name for the WebSocket. Only used internally.
  1092. """
  1093. ),
  1094. ] = None,
  1095. *,
  1096. dependencies: Annotated[
  1097. Optional[Sequence[Depends]],
  1098. Doc(
  1099. """
  1100. A list of dependencies (using `Depends()`) to be used for this
  1101. WebSocket.
  1102. Read more about it in the
  1103. [FastAPI docs for WebSockets](https://fastapi.tiangolo.com/advanced/websockets/).
  1104. """
  1105. ),
  1106. ] = None,
  1107. ) -> Callable[[DecoratedCallable], DecoratedCallable]:
  1108. """
  1109. Decorate a WebSocket function.
  1110. Read more about it in the
  1111. [FastAPI docs for WebSockets](https://fastapi.tiangolo.com/advanced/websockets/).
  1112. **Example**
  1113. ```python
  1114. from fastapi import FastAPI, WebSocket
  1115. app = FastAPI()
  1116. @app.websocket("/ws")
  1117. async def websocket_endpoint(websocket: WebSocket):
  1118. await websocket.accept()
  1119. while True:
  1120. data = await websocket.receive_text()
  1121. await websocket.send_text(f"Message text was: {data}")
  1122. ```
  1123. """
  1124. def decorator(func: DecoratedCallable) -> DecoratedCallable:
  1125. self.add_api_websocket_route(
  1126. path,
  1127. func,
  1128. name=name,
  1129. dependencies=dependencies,
  1130. )
  1131. return func
  1132. return decorator
  1133. def include_router(
  1134. self,
  1135. router: Annotated[routing.APIRouter, Doc("The `APIRouter` to include.")],
  1136. *,
  1137. prefix: Annotated[str, Doc("An optional path prefix for the router.")] = "",
  1138. tags: Annotated[
  1139. Optional[List[Union[str, Enum]]],
  1140. Doc(
  1141. """
  1142. A list of tags to be applied to all the *path operations* in this
  1143. router.
  1144. It will be added to the generated OpenAPI (e.g. visible at `/docs`).
  1145. Read more about it in the
  1146. [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).
  1147. """
  1148. ),
  1149. ] = None,
  1150. dependencies: Annotated[
  1151. Optional[Sequence[Depends]],
  1152. Doc(
  1153. """
  1154. A list of dependencies (using `Depends()`) to be applied to all the
  1155. *path operations* in this router.
  1156. Read more about it in the
  1157. [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).
  1158. **Example**
  1159. ```python
  1160. from fastapi import Depends, FastAPI
  1161. from .dependencies import get_token_header
  1162. from .internal import admin
  1163. app = FastAPI()
  1164. app.include_router(
  1165. admin.router,
  1166. dependencies=[Depends(get_token_header)],
  1167. )
  1168. ```
  1169. """
  1170. ),
  1171. ] = None,
  1172. responses: Annotated[
  1173. Optional[Dict[Union[int, str], Dict[str, Any]]],
  1174. Doc(
  1175. """
  1176. Additional responses to be shown in OpenAPI.
  1177. It will be added to the generated OpenAPI (e.g. visible at `/docs`).
  1178. Read more about it in the
  1179. [FastAPI docs for Additional Responses in OpenAPI](https://fastapi.tiangolo.com/advanced/additional-responses/).
  1180. And in the
  1181. [FastAPI docs for Bigger Applications](https://fastapi.tiangolo.com/tutorial/bigger-applications/#include-an-apirouter-with-a-custom-prefix-tags-responses-and-dependencies).
  1182. """
  1183. ),
  1184. ] = None,
  1185. deprecated: Annotated[
  1186. Optional[bool],
  1187. Doc(
  1188. """
  1189. Mark all the *path operations* in this router as deprecated.
  1190. It will be added to the generated OpenAPI (e.g. visible at `/docs`).
  1191. **Example**
  1192. ```python
  1193. from fastapi import FastAPI
  1194. from .internal import old_api
  1195. app = FastAPI()
  1196. app.include_router(
  1197. old_api.router,
  1198. deprecated=True,
  1199. )
  1200. ```
  1201. """
  1202. ),
  1203. ] = None,
  1204. include_in_schema: Annotated[
  1205. bool,
  1206. Doc(
  1207. """
  1208. Include (or not) all the *path operations* in this router in the
  1209. generated OpenAPI schema.
  1210. This affects the generated OpenAPI (e.g. visible at `/docs`).
  1211. **Example**
  1212. ```python
  1213. from fastapi import FastAPI
  1214. from .internal import old_api
  1215. app = FastAPI()
  1216. app.include_router(
  1217. old_api.router,
  1218. include_in_schema=False,
  1219. )
  1220. ```
  1221. """
  1222. ),
  1223. ] = True,
  1224. default_response_class: Annotated[
  1225. Type[Response],
  1226. Doc(
  1227. """
  1228. Default response class to be used for the *path operations* in this
  1229. router.
  1230. Read more in the
  1231. [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#default-response-class).
  1232. **Example**
  1233. ```python
  1234. from fastapi import FastAPI
  1235. from fastapi.responses import ORJSONResponse
  1236. from .internal import old_api
  1237. app = FastAPI()
  1238. app.include_router(
  1239. old_api.router,
  1240. default_response_class=ORJSONResponse,
  1241. )
  1242. ```
  1243. """
  1244. ),
  1245. ] = Default(JSONResponse),
  1246. callbacks: Annotated[
  1247. Optional[List[BaseRoute]],
  1248. Doc(
  1249. """
  1250. List of *path operations* that will be used as OpenAPI callbacks.
  1251. This is only for OpenAPI documentation, the callbacks won't be used
  1252. directly.
  1253. It will be added to the generated OpenAPI (e.g. visible at `/docs`).
  1254. Read more about it in the
  1255. [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/).
  1256. """
  1257. ),
  1258. ] = None,
  1259. generate_unique_id_function: Annotated[
  1260. Callable[[routing.APIRoute], str],
  1261. Doc(
  1262. """
  1263. Customize the function used to generate unique IDs for the *path
  1264. operations* shown in the generated OpenAPI.
  1265. This is particularly useful when automatically generating clients or
  1266. SDKs for your API.
  1267. Read more about it in the
  1268. [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).
  1269. """
  1270. ),
  1271. ] = Default(generate_unique_id),
  1272. ) -> None:
  1273. """
  1274. Include an `APIRouter` in the same app.
  1275. Read more about it in the
  1276. [FastAPI docs for Bigger Applications](https://fastapi.tiangolo.com/tutorial/bigger-applications/).
  1277. ## Example
  1278. ```python
  1279. from fastapi import FastAPI
  1280. from .users import users_router
  1281. app = FastAPI()
  1282. app.include_router(users_router)
  1283. ```
  1284. """
  1285. self.router.include_router(
  1286. router,
  1287. prefix=prefix,
  1288. tags=tags,
  1289. dependencies=dependencies,
  1290. responses=responses,
  1291. deprecated=deprecated,
  1292. include_in_schema=include_in_schema,
  1293. default_response_class=default_response_class,
  1294. callbacks=callbacks,
  1295. generate_unique_id_function=generate_unique_id_function,
  1296. )
  1297. def get(
  1298. self,
  1299. path: Annotated[
  1300. str,
  1301. Doc(
  1302. """
  1303. The URL path to be used for this *path operation*.
  1304. For example, in `http://example.com/items`, the path is `/items`.
  1305. """
  1306. ),
  1307. ],
  1308. *,
  1309. response_model: Annotated[
  1310. Any,
  1311. Doc(
  1312. """
  1313. The type to use for the response.
  1314. It could be any valid Pydantic *field* type. So, it doesn't have to
  1315. be a Pydantic model, it could be other things, like a `list`, `dict`,
  1316. etc.
  1317. It will be used for:
  1318. * Documentation: the generated OpenAPI (and the UI at `/docs`) will
  1319. show it as the response (JSON Schema).
  1320. * Serialization: you could return an arbitrary object and the
  1321. `response_model` would be used to serialize that object into the
  1322. corresponding JSON.
  1323. * Filtering: the JSON sent to the client will only contain the data
  1324. (fields) defined in the `response_model`. If you returned an object
  1325. that contains an attribute `password` but the `response_model` does
  1326. not include that field, the JSON sent to the client would not have
  1327. that `password`.
  1328. * Validation: whatever you return will be serialized with the
  1329. `response_model`, converting any data as necessary to generate the
  1330. corresponding JSON. But if the data in the object returned is not
  1331. valid, that would mean a violation of the contract with the client,
  1332. so it's an error from the API developer. So, FastAPI will raise an
  1333. error and return a 500 error code (Internal Server Error).
  1334. Read more about it in the
  1335. [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/).
  1336. """
  1337. ),
  1338. ] = Default(None),
  1339. status_code: Annotated[
  1340. Optional[int],
  1341. Doc(
  1342. """
  1343. The default status code to be used for the response.
  1344. You could override the status code by returning a response directly.
  1345. Read more about it in the
  1346. [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/).
  1347. """
  1348. ),
  1349. ] = None,
  1350. tags: Annotated[
  1351. Optional[List[Union[str, Enum]]],
  1352. Doc(
  1353. """
  1354. A list of tags to be applied to 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/#tags).
  1358. """
  1359. ),
  1360. ] = None,
  1361. dependencies: Annotated[
  1362. Optional[Sequence[Depends]],
  1363. Doc(
  1364. """
  1365. A list of dependencies (using `Depends()`) to be applied to the
  1366. *path operation*.
  1367. Read more about it in the
  1368. [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/).
  1369. """
  1370. ),
  1371. ] = None,
  1372. summary: Annotated[
  1373. Optional[str],
  1374. Doc(
  1375. """
  1376. A summary for the *path operation*.
  1377. It will be added to the generated OpenAPI (e.g. visible at `/docs`).
  1378. Read more about it in the
  1379. [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).
  1380. """
  1381. ),
  1382. ] = None,
  1383. description: Annotated[
  1384. Optional[str],
  1385. Doc(
  1386. """
  1387. A description for the *path operation*.
  1388. If not provided, it will be extracted automatically from the docstring
  1389. of the *path operation function*.
  1390. It can contain Markdown.
  1391. It will be added to the generated OpenAPI (e.g. visible at `/docs`).
  1392. Read more about it in the
  1393. [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).
  1394. """
  1395. ),
  1396. ] = None,
  1397. response_description: Annotated[
  1398. str,
  1399. Doc(
  1400. """
  1401. The description for the default response.
  1402. It will be added to the generated OpenAPI (e.g. visible at `/docs`).
  1403. """
  1404. ),
  1405. ] = "Successful Response",
  1406. responses: Annotated[
  1407. Optional[Dict[Union[int, str], Dict[str, Any]]],
  1408. Doc(
  1409. """
  1410. Additional responses that could be returned by this *path operation*.
  1411. It will be added to the generated OpenAPI (e.g. visible at `/docs`).
  1412. """
  1413. ),
  1414. ] = None,
  1415. deprecated: Annotated[
  1416. Optional[bool],
  1417. Doc(
  1418. """
  1419. Mark this *path operation* as deprecated.
  1420. It will be added to the generated OpenAPI (e.g. visible at `/docs`).
  1421. """
  1422. ),
  1423. ] = None,
  1424. operation_id: Annotated[
  1425. Optional[str],
  1426. Doc(
  1427. """
  1428. Custom operation ID to be used by this *path operation*.
  1429. By default, it is generated automatically.
  1430. If you provide a custom operation ID, you need to make sure it is
  1431. unique for the whole API.
  1432. You can customize the
  1433. operation ID generation with the parameter
  1434. `generate_unique_id_function` in the `FastAPI` class.
  1435. Read more about it in the
  1436. [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).
  1437. """
  1438. ),
  1439. ] = None,
  1440. response_model_include: Annotated[
  1441. Optional[IncEx],
  1442. Doc(
  1443. """
  1444. Configuration passed to Pydantic to include only certain fields in the
  1445. response data.
  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. ] = None,
  1451. response_model_exclude: Annotated[
  1452. Optional[IncEx],
  1453. Doc(
  1454. """
  1455. Configuration passed to Pydantic to exclude certain fields in the
  1456. response data.
  1457. Read more about it in the
  1458. [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).
  1459. """
  1460. ),
  1461. ] = None,
  1462. response_model_by_alias: Annotated[
  1463. bool,
  1464. Doc(
  1465. """
  1466. Configuration passed to Pydantic to define if the response model
  1467. should be serialized by alias when an alias is used.
  1468. Read more about it in the
  1469. [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).
  1470. """
  1471. ),
  1472. ] = True,
  1473. response_model_exclude_unset: Annotated[
  1474. bool,
  1475. Doc(
  1476. """
  1477. Configuration passed to Pydantic to define if the response data
  1478. should have all the fields, including the ones that were not set and
  1479. have their default values. This is different from
  1480. `response_model_exclude_defaults` in that if the fields are set,
  1481. they will be included in the response, even if the value is the same
  1482. as the default.
  1483. When `True`, default values are omitted from the response.
  1484. Read more about it in the
  1485. [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).
  1486. """
  1487. ),
  1488. ] = False,
  1489. response_model_exclude_defaults: Annotated[
  1490. bool,
  1491. Doc(
  1492. """
  1493. Configuration passed to Pydantic to define if the response data
  1494. should have all the fields, including the ones that have the same value
  1495. as the default. This is different from `response_model_exclude_unset`
  1496. in that if the fields are set but contain the same default values,
  1497. they will be excluded from the response.
  1498. When `True`, default values are omitted from the response.
  1499. Read more about it in the
  1500. [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).
  1501. """
  1502. ),
  1503. ] = False,
  1504. response_model_exclude_none: Annotated[
  1505. bool,
  1506. Doc(
  1507. """
  1508. Configuration passed to Pydantic to define if the response data should
  1509. exclude fields set to `None`.
  1510. This is much simpler (less smart) than `response_model_exclude_unset`
  1511. and `response_model_exclude_defaults`. You probably want to use one of
  1512. those two instead of this one, as those allow returning `None` values
  1513. when it makes sense.
  1514. Read more about it in the
  1515. [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none).
  1516. """
  1517. ),
  1518. ] = False,
  1519. include_in_schema: Annotated[
  1520. bool,
  1521. Doc(
  1522. """
  1523. Include this *path operation* in the generated OpenAPI schema.
  1524. This affects the generated OpenAPI (e.g. visible at `/docs`).
  1525. Read more about it in the
  1526. [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-parameters-from-openapi).
  1527. """
  1528. ),
  1529. ] = True,
  1530. response_class: Annotated[
  1531. Type[Response],
  1532. Doc(
  1533. """
  1534. Response class to be used for this *path operation*.
  1535. This will not be used if you return a response directly.
  1536. Read more about it in the
  1537. [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse).
  1538. """
  1539. ),
  1540. ] = Default(JSONResponse),
  1541. name: Annotated[
  1542. Optional[str],
  1543. Doc(
  1544. """
  1545. Name for this *path operation*. Only used internally.
  1546. """
  1547. ),
  1548. ] = None,
  1549. callbacks: Annotated[
  1550. Optional[List[BaseRoute]],
  1551. Doc(
  1552. """
  1553. List of *path operations* that will be used as OpenAPI callbacks.
  1554. This is only for OpenAPI documentation, the callbacks won't be used
  1555. directly.
  1556. It will be added to the generated OpenAPI (e.g. visible at `/docs`).
  1557. Read more about it in the
  1558. [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/).
  1559. """
  1560. ),
  1561. ] = None,
  1562. openapi_extra: Annotated[
  1563. Optional[Dict[str, Any]],
  1564. Doc(
  1565. """
  1566. Extra metadata to be included in the OpenAPI schema for this *path
  1567. operation*.
  1568. Read more about it in the
  1569. [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema).
  1570. """
  1571. ),
  1572. ] = None,
  1573. generate_unique_id_function: Annotated[
  1574. Callable[[routing.APIRoute], str],
  1575. Doc(
  1576. """
  1577. Customize the function used to generate unique IDs for the *path
  1578. operations* shown in the generated OpenAPI.
  1579. This is particularly useful when automatically generating clients or
  1580. SDKs for your API.
  1581. Read more about it in the
  1582. [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).
  1583. """
  1584. ),
  1585. ] = Default(generate_unique_id),
  1586. ) -> Callable[[DecoratedCallable], DecoratedCallable]:
  1587. """
  1588. Add a *path operation* using an HTTP GET operation.
  1589. ## Example
  1590. ```python
  1591. from fastapi import FastAPI
  1592. app = FastAPI()
  1593. @app.get("/items/")
  1594. def read_items():
  1595. return [{"name": "Empanada"}, {"name": "Arepa"}]
  1596. ```
  1597. """
  1598. return self.router.get(
  1599. path,
  1600. response_model=response_model,
  1601. status_code=status_code,
  1602. tags=tags,
  1603. dependencies=dependencies,
  1604. summary=summary,
  1605. description=description,
  1606. response_description=response_description,
  1607. responses=responses,
  1608. deprecated=deprecated,
  1609. operation_id=operation_id,
  1610. response_model_include=response_model_include,
  1611. response_model_exclude=response_model_exclude,
  1612. response_model_by_alias=response_model_by_alias,
  1613. response_model_exclude_unset=response_model_exclude_unset,
  1614. response_model_exclude_defaults=response_model_exclude_defaults,
  1615. response_model_exclude_none=response_model_exclude_none,
  1616. include_in_schema=include_in_schema,
  1617. response_class=response_class,
  1618. name=name,
  1619. callbacks=callbacks,
  1620. openapi_extra=openapi_extra,
  1621. generate_unique_id_function=generate_unique_id_function,
  1622. )
  1623. def put(
  1624. self,
  1625. path: Annotated[
  1626. str,
  1627. Doc(
  1628. """
  1629. The URL path to be used for this *path operation*.
  1630. For example, in `http://example.com/items`, the path is `/items`.
  1631. """
  1632. ),
  1633. ],
  1634. *,
  1635. response_model: Annotated[
  1636. Any,
  1637. Doc(
  1638. """
  1639. The type to use for the response.
  1640. It could be any valid Pydantic *field* type. So, it doesn't have to
  1641. be a Pydantic model, it could be other things, like a `list`, `dict`,
  1642. etc.
  1643. It will be used for:
  1644. * Documentation: the generated OpenAPI (and the UI at `/docs`) will
  1645. show it as the response (JSON Schema).
  1646. * Serialization: you could return an arbitrary object and the
  1647. `response_model` would be used to serialize that object into the
  1648. corresponding JSON.
  1649. * Filtering: the JSON sent to the client will only contain the data
  1650. (fields) defined in the `response_model`. If you returned an object
  1651. that contains an attribute `password` but the `response_model` does
  1652. not include that field, the JSON sent to the client would not have
  1653. that `password`.
  1654. * Validation: whatever you return will be serialized with the
  1655. `response_model`, converting any data as necessary to generate the
  1656. corresponding JSON. But if the data in the object returned is not
  1657. valid, that would mean a violation of the contract with the client,
  1658. so it's an error from the API developer. So, FastAPI will raise an
  1659. error and return a 500 error code (Internal Server Error).
  1660. Read more about it in the
  1661. [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/).
  1662. """
  1663. ),
  1664. ] = Default(None),
  1665. status_code: Annotated[
  1666. Optional[int],
  1667. Doc(
  1668. """
  1669. The default status code to be used for the response.
  1670. You could override the status code by returning a response directly.
  1671. Read more about it in the
  1672. [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/).
  1673. """
  1674. ),
  1675. ] = None,
  1676. tags: Annotated[
  1677. Optional[List[Union[str, Enum]]],
  1678. Doc(
  1679. """
  1680. A list of tags to be applied to 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/#tags).
  1684. """
  1685. ),
  1686. ] = None,
  1687. dependencies: Annotated[
  1688. Optional[Sequence[Depends]],
  1689. Doc(
  1690. """
  1691. A list of dependencies (using `Depends()`) to be applied to the
  1692. *path operation*.
  1693. Read more about it in the
  1694. [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/).
  1695. """
  1696. ),
  1697. ] = None,
  1698. summary: Annotated[
  1699. Optional[str],
  1700. Doc(
  1701. """
  1702. A summary for the *path operation*.
  1703. It will be added to the generated OpenAPI (e.g. visible at `/docs`).
  1704. Read more about it in the
  1705. [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).
  1706. """
  1707. ),
  1708. ] = None,
  1709. description: Annotated[
  1710. Optional[str],
  1711. Doc(
  1712. """
  1713. A description for the *path operation*.
  1714. If not provided, it will be extracted automatically from the docstring
  1715. of the *path operation function*.
  1716. It can contain Markdown.
  1717. It will be added to the generated OpenAPI (e.g. visible at `/docs`).
  1718. Read more about it in the
  1719. [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).
  1720. """
  1721. ),
  1722. ] = None,
  1723. response_description: Annotated[
  1724. str,
  1725. Doc(
  1726. """
  1727. The description for the default response.
  1728. It will be added to the generated OpenAPI (e.g. visible at `/docs`).
  1729. """
  1730. ),
  1731. ] = "Successful Response",
  1732. responses: Annotated[
  1733. Optional[Dict[Union[int, str], Dict[str, Any]]],
  1734. Doc(
  1735. """
  1736. Additional responses that could be returned by this *path operation*.
  1737. It will be added to the generated OpenAPI (e.g. visible at `/docs`).
  1738. """
  1739. ),
  1740. ] = None,
  1741. deprecated: Annotated[
  1742. Optional[bool],
  1743. Doc(
  1744. """
  1745. Mark this *path operation* as deprecated.
  1746. It will be added to the generated OpenAPI (e.g. visible at `/docs`).
  1747. """
  1748. ),
  1749. ] = None,
  1750. operation_id: Annotated[
  1751. Optional[str],
  1752. Doc(
  1753. """
  1754. Custom operation ID to be used by this *path operation*.
  1755. By default, it is generated automatically.
  1756. If you provide a custom operation ID, you need to make sure it is
  1757. unique for the whole API.
  1758. You can customize the
  1759. operation ID generation with the parameter
  1760. `generate_unique_id_function` in the `FastAPI` class.
  1761. Read more about it in the
  1762. [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).
  1763. """
  1764. ),
  1765. ] = None,
  1766. response_model_include: Annotated[
  1767. Optional[IncEx],
  1768. Doc(
  1769. """
  1770. Configuration passed to Pydantic to include only certain fields in the
  1771. response data.
  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. ] = None,
  1777. response_model_exclude: Annotated[
  1778. Optional[IncEx],
  1779. Doc(
  1780. """
  1781. Configuration passed to Pydantic to exclude certain fields in the
  1782. response data.
  1783. Read more about it in the
  1784. [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).
  1785. """
  1786. ),
  1787. ] = None,
  1788. response_model_by_alias: Annotated[
  1789. bool,
  1790. Doc(
  1791. """
  1792. Configuration passed to Pydantic to define if the response model
  1793. should be serialized by alias when an alias is used.
  1794. Read more about it in the
  1795. [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).
  1796. """
  1797. ),
  1798. ] = True,
  1799. response_model_exclude_unset: Annotated[
  1800. bool,
  1801. Doc(
  1802. """
  1803. Configuration passed to Pydantic to define if the response data
  1804. should have all the fields, including the ones that were not set and
  1805. have their default values. This is different from
  1806. `response_model_exclude_defaults` in that if the fields are set,
  1807. they will be included in the response, even if the value is the same
  1808. as the default.
  1809. When `True`, default values are omitted from the response.
  1810. Read more about it in the
  1811. [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).
  1812. """
  1813. ),
  1814. ] = False,
  1815. response_model_exclude_defaults: Annotated[
  1816. bool,
  1817. Doc(
  1818. """
  1819. Configuration passed to Pydantic to define if the response data
  1820. should have all the fields, including the ones that have the same value
  1821. as the default. This is different from `response_model_exclude_unset`
  1822. in that if the fields are set but contain the same default values,
  1823. they will be excluded from the response.
  1824. When `True`, default values are omitted from the response.
  1825. Read more about it in the
  1826. [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).
  1827. """
  1828. ),
  1829. ] = False,
  1830. response_model_exclude_none: Annotated[
  1831. bool,
  1832. Doc(
  1833. """
  1834. Configuration passed to Pydantic to define if the response data should
  1835. exclude fields set to `None`.
  1836. This is much simpler (less smart) than `response_model_exclude_unset`
  1837. and `response_model_exclude_defaults`. You probably want to use one of
  1838. those two instead of this one, as those allow returning `None` values
  1839. when it makes sense.
  1840. Read more about it in the
  1841. [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none).
  1842. """
  1843. ),
  1844. ] = False,
  1845. include_in_schema: Annotated[
  1846. bool,
  1847. Doc(
  1848. """
  1849. Include this *path operation* in the generated OpenAPI schema.
  1850. This affects the generated OpenAPI (e.g. visible at `/docs`).
  1851. Read more about it in the
  1852. [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-parameters-from-openapi).
  1853. """
  1854. ),
  1855. ] = True,
  1856. response_class: Annotated[
  1857. Type[Response],
  1858. Doc(
  1859. """
  1860. Response class to be used for this *path operation*.
  1861. This will not be used if you return a response directly.
  1862. Read more about it in the
  1863. [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse).
  1864. """
  1865. ),
  1866. ] = Default(JSONResponse),
  1867. name: Annotated[
  1868. Optional[str],
  1869. Doc(
  1870. """
  1871. Name for this *path operation*. Only used internally.
  1872. """
  1873. ),
  1874. ] = None,
  1875. callbacks: Annotated[
  1876. Optional[List[BaseRoute]],
  1877. Doc(
  1878. """
  1879. List of *path operations* that will be used as OpenAPI callbacks.
  1880. This is only for OpenAPI documentation, the callbacks won't be used
  1881. directly.
  1882. It will be added to the generated OpenAPI (e.g. visible at `/docs`).
  1883. Read more about it in the
  1884. [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/).
  1885. """
  1886. ),
  1887. ] = None,
  1888. openapi_extra: Annotated[
  1889. Optional[Dict[str, Any]],
  1890. Doc(
  1891. """
  1892. Extra metadata to be included in the OpenAPI schema for this *path
  1893. operation*.
  1894. Read more about it in the
  1895. [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema).
  1896. """
  1897. ),
  1898. ] = None,
  1899. generate_unique_id_function: Annotated[
  1900. Callable[[routing.APIRoute], str],
  1901. Doc(
  1902. """
  1903. Customize the function used to generate unique IDs for the *path
  1904. operations* shown in the generated OpenAPI.
  1905. This is particularly useful when automatically generating clients or
  1906. SDKs for your API.
  1907. Read more about it in the
  1908. [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).
  1909. """
  1910. ),
  1911. ] = Default(generate_unique_id),
  1912. ) -> Callable[[DecoratedCallable], DecoratedCallable]:
  1913. """
  1914. Add a *path operation* using an HTTP PUT operation.
  1915. ## Example
  1916. ```python
  1917. from fastapi import FastAPI
  1918. from pydantic import BaseModel
  1919. class Item(BaseModel):
  1920. name: str
  1921. description: str | None = None
  1922. app = FastAPI()
  1923. @app.put("/items/{item_id}")
  1924. def replace_item(item_id: str, item: Item):
  1925. return {"message": "Item replaced", "id": item_id}
  1926. ```
  1927. """
  1928. return self.router.put(
  1929. path,
  1930. response_model=response_model,
  1931. status_code=status_code,
  1932. tags=tags,
  1933. dependencies=dependencies,
  1934. summary=summary,
  1935. description=description,
  1936. response_description=response_description,
  1937. responses=responses,
  1938. deprecated=deprecated,
  1939. operation_id=operation_id,
  1940. response_model_include=response_model_include,
  1941. response_model_exclude=response_model_exclude,
  1942. response_model_by_alias=response_model_by_alias,
  1943. response_model_exclude_unset=response_model_exclude_unset,
  1944. response_model_exclude_defaults=response_model_exclude_defaults,
  1945. response_model_exclude_none=response_model_exclude_none,
  1946. include_in_schema=include_in_schema,
  1947. response_class=response_class,
  1948. name=name,
  1949. callbacks=callbacks,
  1950. openapi_extra=openapi_extra,
  1951. generate_unique_id_function=generate_unique_id_function,
  1952. )
  1953. def post(
  1954. self,
  1955. path: Annotated[
  1956. str,
  1957. Doc(
  1958. """
  1959. The URL path to be used for this *path operation*.
  1960. For example, in `http://example.com/items`, the path is `/items`.
  1961. """
  1962. ),
  1963. ],
  1964. *,
  1965. response_model: Annotated[
  1966. Any,
  1967. Doc(
  1968. """
  1969. The type to use for the response.
  1970. It could be any valid Pydantic *field* type. So, it doesn't have to
  1971. be a Pydantic model, it could be other things, like a `list`, `dict`,
  1972. etc.
  1973. It will be used for:
  1974. * Documentation: the generated OpenAPI (and the UI at `/docs`) will
  1975. show it as the response (JSON Schema).
  1976. * Serialization: you could return an arbitrary object and the
  1977. `response_model` would be used to serialize that object into the
  1978. corresponding JSON.
  1979. * Filtering: the JSON sent to the client will only contain the data
  1980. (fields) defined in the `response_model`. If you returned an object
  1981. that contains an attribute `password` but the `response_model` does
  1982. not include that field, the JSON sent to the client would not have
  1983. that `password`.
  1984. * Validation: whatever you return will be serialized with the
  1985. `response_model`, converting any data as necessary to generate the
  1986. corresponding JSON. But if the data in the object returned is not
  1987. valid, that would mean a violation of the contract with the client,
  1988. so it's an error from the API developer. So, FastAPI will raise an
  1989. error and return a 500 error code (Internal Server Error).
  1990. Read more about it in the
  1991. [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/).
  1992. """
  1993. ),
  1994. ] = Default(None),
  1995. status_code: Annotated[
  1996. Optional[int],
  1997. Doc(
  1998. """
  1999. The default status code to be used for the response.
  2000. You could override the status code by returning a response directly.
  2001. Read more about it in the
  2002. [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/).
  2003. """
  2004. ),
  2005. ] = None,
  2006. tags: Annotated[
  2007. Optional[List[Union[str, Enum]]],
  2008. Doc(
  2009. """
  2010. A list of tags to be applied to 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/#tags).
  2014. """
  2015. ),
  2016. ] = None,
  2017. dependencies: Annotated[
  2018. Optional[Sequence[Depends]],
  2019. Doc(
  2020. """
  2021. A list of dependencies (using `Depends()`) to be applied to the
  2022. *path operation*.
  2023. Read more about it in the
  2024. [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/).
  2025. """
  2026. ),
  2027. ] = None,
  2028. summary: Annotated[
  2029. Optional[str],
  2030. Doc(
  2031. """
  2032. A summary for the *path operation*.
  2033. It will be added to the generated OpenAPI (e.g. visible at `/docs`).
  2034. Read more about it in the
  2035. [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).
  2036. """
  2037. ),
  2038. ] = None,
  2039. description: Annotated[
  2040. Optional[str],
  2041. Doc(
  2042. """
  2043. A description for the *path operation*.
  2044. If not provided, it will be extracted automatically from the docstring
  2045. of the *path operation function*.
  2046. It can contain Markdown.
  2047. It will be added to the generated OpenAPI (e.g. visible at `/docs`).
  2048. Read more about it in the
  2049. [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).
  2050. """
  2051. ),
  2052. ] = None,
  2053. response_description: Annotated[
  2054. str,
  2055. Doc(
  2056. """
  2057. The description for the default response.
  2058. It will be added to the generated OpenAPI (e.g. visible at `/docs`).
  2059. """
  2060. ),
  2061. ] = "Successful Response",
  2062. responses: Annotated[
  2063. Optional[Dict[Union[int, str], Dict[str, Any]]],
  2064. Doc(
  2065. """
  2066. Additional responses that could be returned by this *path operation*.
  2067. It will be added to the generated OpenAPI (e.g. visible at `/docs`).
  2068. """
  2069. ),
  2070. ] = None,
  2071. deprecated: Annotated[
  2072. Optional[bool],
  2073. Doc(
  2074. """
  2075. Mark this *path operation* as deprecated.
  2076. It will be added to the generated OpenAPI (e.g. visible at `/docs`).
  2077. """
  2078. ),
  2079. ] = None,
  2080. operation_id: Annotated[
  2081. Optional[str],
  2082. Doc(
  2083. """
  2084. Custom operation ID to be used by this *path operation*.
  2085. By default, it is generated automatically.
  2086. If you provide a custom operation ID, you need to make sure it is
  2087. unique for the whole API.
  2088. You can customize the
  2089. operation ID generation with the parameter
  2090. `generate_unique_id_function` in the `FastAPI` class.
  2091. Read more about it in the
  2092. [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).
  2093. """
  2094. ),
  2095. ] = None,
  2096. response_model_include: Annotated[
  2097. Optional[IncEx],
  2098. Doc(
  2099. """
  2100. Configuration passed to Pydantic to include only certain fields in the
  2101. response data.
  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. ] = None,
  2107. response_model_exclude: Annotated[
  2108. Optional[IncEx],
  2109. Doc(
  2110. """
  2111. Configuration passed to Pydantic to exclude certain fields in the
  2112. response data.
  2113. Read more about it in the
  2114. [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).
  2115. """
  2116. ),
  2117. ] = None,
  2118. response_model_by_alias: Annotated[
  2119. bool,
  2120. Doc(
  2121. """
  2122. Configuration passed to Pydantic to define if the response model
  2123. should be serialized by alias when an alias is used.
  2124. Read more about it in the
  2125. [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).
  2126. """
  2127. ),
  2128. ] = True,
  2129. response_model_exclude_unset: Annotated[
  2130. bool,
  2131. Doc(
  2132. """
  2133. Configuration passed to Pydantic to define if the response data
  2134. should have all the fields, including the ones that were not set and
  2135. have their default values. This is different from
  2136. `response_model_exclude_defaults` in that if the fields are set,
  2137. they will be included in the response, even if the value is the same
  2138. as the default.
  2139. When `True`, default values are omitted from the response.
  2140. Read more about it in the
  2141. [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).
  2142. """
  2143. ),
  2144. ] = False,
  2145. response_model_exclude_defaults: Annotated[
  2146. bool,
  2147. Doc(
  2148. """
  2149. Configuration passed to Pydantic to define if the response data
  2150. should have all the fields, including the ones that have the same value
  2151. as the default. This is different from `response_model_exclude_unset`
  2152. in that if the fields are set but contain the same default values,
  2153. they will be excluded from the response.
  2154. When `True`, default values are omitted from the response.
  2155. Read more about it in the
  2156. [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).
  2157. """
  2158. ),
  2159. ] = False,
  2160. response_model_exclude_none: Annotated[
  2161. bool,
  2162. Doc(
  2163. """
  2164. Configuration passed to Pydantic to define if the response data should
  2165. exclude fields set to `None`.
  2166. This is much simpler (less smart) than `response_model_exclude_unset`
  2167. and `response_model_exclude_defaults`. You probably want to use one of
  2168. those two instead of this one, as those allow returning `None` values
  2169. when it makes sense.
  2170. Read more about it in the
  2171. [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none).
  2172. """
  2173. ),
  2174. ] = False,
  2175. include_in_schema: Annotated[
  2176. bool,
  2177. Doc(
  2178. """
  2179. Include this *path operation* in the generated OpenAPI schema.
  2180. This affects the generated OpenAPI (e.g. visible at `/docs`).
  2181. Read more about it in the
  2182. [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-parameters-from-openapi).
  2183. """
  2184. ),
  2185. ] = True,
  2186. response_class: Annotated[
  2187. Type[Response],
  2188. Doc(
  2189. """
  2190. Response class to be used for this *path operation*.
  2191. This will not be used if you return a response directly.
  2192. Read more about it in the
  2193. [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse).
  2194. """
  2195. ),
  2196. ] = Default(JSONResponse),
  2197. name: Annotated[
  2198. Optional[str],
  2199. Doc(
  2200. """
  2201. Name for this *path operation*. Only used internally.
  2202. """
  2203. ),
  2204. ] = None,
  2205. callbacks: Annotated[
  2206. Optional[List[BaseRoute]],
  2207. Doc(
  2208. """
  2209. List of *path operations* that will be used as OpenAPI callbacks.
  2210. This is only for OpenAPI documentation, the callbacks won't be used
  2211. directly.
  2212. It will be added to the generated OpenAPI (e.g. visible at `/docs`).
  2213. Read more about it in the
  2214. [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/).
  2215. """
  2216. ),
  2217. ] = None,
  2218. openapi_extra: Annotated[
  2219. Optional[Dict[str, Any]],
  2220. Doc(
  2221. """
  2222. Extra metadata to be included in the OpenAPI schema for this *path
  2223. operation*.
  2224. Read more about it in the
  2225. [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema).
  2226. """
  2227. ),
  2228. ] = None,
  2229. generate_unique_id_function: Annotated[
  2230. Callable[[routing.APIRoute], str],
  2231. Doc(
  2232. """
  2233. Customize the function used to generate unique IDs for the *path
  2234. operations* shown in the generated OpenAPI.
  2235. This is particularly useful when automatically generating clients or
  2236. SDKs for your API.
  2237. Read more about it in the
  2238. [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).
  2239. """
  2240. ),
  2241. ] = Default(generate_unique_id),
  2242. ) -> Callable[[DecoratedCallable], DecoratedCallable]:
  2243. """
  2244. Add a *path operation* using an HTTP POST operation.
  2245. ## Example
  2246. ```python
  2247. from fastapi import FastAPI
  2248. from pydantic import BaseModel
  2249. class Item(BaseModel):
  2250. name: str
  2251. description: str | None = None
  2252. app = FastAPI()
  2253. @app.post("/items/")
  2254. def create_item(item: Item):
  2255. return {"message": "Item created"}
  2256. ```
  2257. """
  2258. return self.router.post(
  2259. path,
  2260. response_model=response_model,
  2261. status_code=status_code,
  2262. tags=tags,
  2263. dependencies=dependencies,
  2264. summary=summary,
  2265. description=description,
  2266. response_description=response_description,
  2267. responses=responses,
  2268. deprecated=deprecated,
  2269. operation_id=operation_id,
  2270. response_model_include=response_model_include,
  2271. response_model_exclude=response_model_exclude,
  2272. response_model_by_alias=response_model_by_alias,
  2273. response_model_exclude_unset=response_model_exclude_unset,
  2274. response_model_exclude_defaults=response_model_exclude_defaults,
  2275. response_model_exclude_none=response_model_exclude_none,
  2276. include_in_schema=include_in_schema,
  2277. response_class=response_class,
  2278. name=name,
  2279. callbacks=callbacks,
  2280. openapi_extra=openapi_extra,
  2281. generate_unique_id_function=generate_unique_id_function,
  2282. )
  2283. def delete(
  2284. self,
  2285. path: Annotated[
  2286. str,
  2287. Doc(
  2288. """
  2289. The URL path to be used for this *path operation*.
  2290. For example, in `http://example.com/items`, the path is `/items`.
  2291. """
  2292. ),
  2293. ],
  2294. *,
  2295. response_model: Annotated[
  2296. Any,
  2297. Doc(
  2298. """
  2299. The type to use for the response.
  2300. It could be any valid Pydantic *field* type. So, it doesn't have to
  2301. be a Pydantic model, it could be other things, like a `list`, `dict`,
  2302. etc.
  2303. It will be used for:
  2304. * Documentation: the generated OpenAPI (and the UI at `/docs`) will
  2305. show it as the response (JSON Schema).
  2306. * Serialization: you could return an arbitrary object and the
  2307. `response_model` would be used to serialize that object into the
  2308. corresponding JSON.
  2309. * Filtering: the JSON sent to the client will only contain the data
  2310. (fields) defined in the `response_model`. If you returned an object
  2311. that contains an attribute `password` but the `response_model` does
  2312. not include that field, the JSON sent to the client would not have
  2313. that `password`.
  2314. * Validation: whatever you return will be serialized with the
  2315. `response_model`, converting any data as necessary to generate the
  2316. corresponding JSON. But if the data in the object returned is not
  2317. valid, that would mean a violation of the contract with the client,
  2318. so it's an error from the API developer. So, FastAPI will raise an
  2319. error and return a 500 error code (Internal Server Error).
  2320. Read more about it in the
  2321. [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/).
  2322. """
  2323. ),
  2324. ] = Default(None),
  2325. status_code: Annotated[
  2326. Optional[int],
  2327. Doc(
  2328. """
  2329. The default status code to be used for the response.
  2330. You could override the status code by returning a response directly.
  2331. Read more about it in the
  2332. [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/).
  2333. """
  2334. ),
  2335. ] = None,
  2336. tags: Annotated[
  2337. Optional[List[Union[str, Enum]]],
  2338. Doc(
  2339. """
  2340. A list of tags to be applied to 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/#tags).
  2344. """
  2345. ),
  2346. ] = None,
  2347. dependencies: Annotated[
  2348. Optional[Sequence[Depends]],
  2349. Doc(
  2350. """
  2351. A list of dependencies (using `Depends()`) to be applied to the
  2352. *path operation*.
  2353. Read more about it in the
  2354. [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/).
  2355. """
  2356. ),
  2357. ] = None,
  2358. summary: Annotated[
  2359. Optional[str],
  2360. Doc(
  2361. """
  2362. A summary for the *path operation*.
  2363. It will be added to the generated OpenAPI (e.g. visible at `/docs`).
  2364. Read more about it in the
  2365. [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).
  2366. """
  2367. ),
  2368. ] = None,
  2369. description: Annotated[
  2370. Optional[str],
  2371. Doc(
  2372. """
  2373. A description for the *path operation*.
  2374. If not provided, it will be extracted automatically from the docstring
  2375. of the *path operation function*.
  2376. It can contain Markdown.
  2377. It will be added to the generated OpenAPI (e.g. visible at `/docs`).
  2378. Read more about it in the
  2379. [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).
  2380. """
  2381. ),
  2382. ] = None,
  2383. response_description: Annotated[
  2384. str,
  2385. Doc(
  2386. """
  2387. The description for the default response.
  2388. It will be added to the generated OpenAPI (e.g. visible at `/docs`).
  2389. """
  2390. ),
  2391. ] = "Successful Response",
  2392. responses: Annotated[
  2393. Optional[Dict[Union[int, str], Dict[str, Any]]],
  2394. Doc(
  2395. """
  2396. Additional responses that could be returned by this *path operation*.
  2397. It will be added to the generated OpenAPI (e.g. visible at `/docs`).
  2398. """
  2399. ),
  2400. ] = None,
  2401. deprecated: Annotated[
  2402. Optional[bool],
  2403. Doc(
  2404. """
  2405. Mark this *path operation* as deprecated.
  2406. It will be added to the generated OpenAPI (e.g. visible at `/docs`).
  2407. """
  2408. ),
  2409. ] = None,
  2410. operation_id: Annotated[
  2411. Optional[str],
  2412. Doc(
  2413. """
  2414. Custom operation ID to be used by this *path operation*.
  2415. By default, it is generated automatically.
  2416. If you provide a custom operation ID, you need to make sure it is
  2417. unique for the whole API.
  2418. You can customize the
  2419. operation ID generation with the parameter
  2420. `generate_unique_id_function` in the `FastAPI` class.
  2421. Read more about it in the
  2422. [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).
  2423. """
  2424. ),
  2425. ] = None,
  2426. response_model_include: Annotated[
  2427. Optional[IncEx],
  2428. Doc(
  2429. """
  2430. Configuration passed to Pydantic to include only certain fields in the
  2431. response data.
  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. ] = None,
  2437. response_model_exclude: Annotated[
  2438. Optional[IncEx],
  2439. Doc(
  2440. """
  2441. Configuration passed to Pydantic to exclude certain fields in the
  2442. response data.
  2443. Read more about it in the
  2444. [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).
  2445. """
  2446. ),
  2447. ] = None,
  2448. response_model_by_alias: Annotated[
  2449. bool,
  2450. Doc(
  2451. """
  2452. Configuration passed to Pydantic to define if the response model
  2453. should be serialized by alias when an alias is used.
  2454. Read more about it in the
  2455. [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).
  2456. """
  2457. ),
  2458. ] = True,
  2459. response_model_exclude_unset: Annotated[
  2460. bool,
  2461. Doc(
  2462. """
  2463. Configuration passed to Pydantic to define if the response data
  2464. should have all the fields, including the ones that were not set and
  2465. have their default values. This is different from
  2466. `response_model_exclude_defaults` in that if the fields are set,
  2467. they will be included in the response, even if the value is the same
  2468. as the default.
  2469. When `True`, default values are omitted from the response.
  2470. Read more about it in the
  2471. [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).
  2472. """
  2473. ),
  2474. ] = False,
  2475. response_model_exclude_defaults: Annotated[
  2476. bool,
  2477. Doc(
  2478. """
  2479. Configuration passed to Pydantic to define if the response data
  2480. should have all the fields, including the ones that have the same value
  2481. as the default. This is different from `response_model_exclude_unset`
  2482. in that if the fields are set but contain the same default values,
  2483. they will be excluded from the response.
  2484. When `True`, default values are omitted from the response.
  2485. Read more about it in the
  2486. [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).
  2487. """
  2488. ),
  2489. ] = False,
  2490. response_model_exclude_none: Annotated[
  2491. bool,
  2492. Doc(
  2493. """
  2494. Configuration passed to Pydantic to define if the response data should
  2495. exclude fields set to `None`.
  2496. This is much simpler (less smart) than `response_model_exclude_unset`
  2497. and `response_model_exclude_defaults`. You probably want to use one of
  2498. those two instead of this one, as those allow returning `None` values
  2499. when it makes sense.
  2500. Read more about it in the
  2501. [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none).
  2502. """
  2503. ),
  2504. ] = False,
  2505. include_in_schema: Annotated[
  2506. bool,
  2507. Doc(
  2508. """
  2509. Include this *path operation* in the generated OpenAPI schema.
  2510. This affects the generated OpenAPI (e.g. visible at `/docs`).
  2511. Read more about it in the
  2512. [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-parameters-from-openapi).
  2513. """
  2514. ),
  2515. ] = True,
  2516. response_class: Annotated[
  2517. Type[Response],
  2518. Doc(
  2519. """
  2520. Response class to be used for this *path operation*.
  2521. This will not be used if you return a response directly.
  2522. Read more about it in the
  2523. [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse).
  2524. """
  2525. ),
  2526. ] = Default(JSONResponse),
  2527. name: Annotated[
  2528. Optional[str],
  2529. Doc(
  2530. """
  2531. Name for this *path operation*. Only used internally.
  2532. """
  2533. ),
  2534. ] = None,
  2535. callbacks: Annotated[
  2536. Optional[List[BaseRoute]],
  2537. Doc(
  2538. """
  2539. List of *path operations* that will be used as OpenAPI callbacks.
  2540. This is only for OpenAPI documentation, the callbacks won't be used
  2541. directly.
  2542. It will be added to the generated OpenAPI (e.g. visible at `/docs`).
  2543. Read more about it in the
  2544. [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/).
  2545. """
  2546. ),
  2547. ] = None,
  2548. openapi_extra: Annotated[
  2549. Optional[Dict[str, Any]],
  2550. Doc(
  2551. """
  2552. Extra metadata to be included in the OpenAPI schema for this *path
  2553. operation*.
  2554. Read more about it in the
  2555. [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema).
  2556. """
  2557. ),
  2558. ] = None,
  2559. generate_unique_id_function: Annotated[
  2560. Callable[[routing.APIRoute], str],
  2561. Doc(
  2562. """
  2563. Customize the function used to generate unique IDs for the *path
  2564. operations* shown in the generated OpenAPI.
  2565. This is particularly useful when automatically generating clients or
  2566. SDKs for your API.
  2567. Read more about it in the
  2568. [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).
  2569. """
  2570. ),
  2571. ] = Default(generate_unique_id),
  2572. ) -> Callable[[DecoratedCallable], DecoratedCallable]:
  2573. """
  2574. Add a *path operation* using an HTTP DELETE operation.
  2575. ## Example
  2576. ```python
  2577. from fastapi import FastAPI
  2578. app = FastAPI()
  2579. @app.delete("/items/{item_id}")
  2580. def delete_item(item_id: str):
  2581. return {"message": "Item deleted"}
  2582. ```
  2583. """
  2584. return self.router.delete(
  2585. path,
  2586. response_model=response_model,
  2587. status_code=status_code,
  2588. tags=tags,
  2589. dependencies=dependencies,
  2590. summary=summary,
  2591. description=description,
  2592. response_description=response_description,
  2593. responses=responses,
  2594. deprecated=deprecated,
  2595. operation_id=operation_id,
  2596. response_model_include=response_model_include,
  2597. response_model_exclude=response_model_exclude,
  2598. response_model_by_alias=response_model_by_alias,
  2599. response_model_exclude_unset=response_model_exclude_unset,
  2600. response_model_exclude_defaults=response_model_exclude_defaults,
  2601. response_model_exclude_none=response_model_exclude_none,
  2602. include_in_schema=include_in_schema,
  2603. response_class=response_class,
  2604. name=name,
  2605. callbacks=callbacks,
  2606. openapi_extra=openapi_extra,
  2607. generate_unique_id_function=generate_unique_id_function,
  2608. )
  2609. def options(
  2610. self,
  2611. path: Annotated[
  2612. str,
  2613. Doc(
  2614. """
  2615. The URL path to be used for this *path operation*.
  2616. For example, in `http://example.com/items`, the path is `/items`.
  2617. """
  2618. ),
  2619. ],
  2620. *,
  2621. response_model: Annotated[
  2622. Any,
  2623. Doc(
  2624. """
  2625. The type to use for the response.
  2626. It could be any valid Pydantic *field* type. So, it doesn't have to
  2627. be a Pydantic model, it could be other things, like a `list`, `dict`,
  2628. etc.
  2629. It will be used for:
  2630. * Documentation: the generated OpenAPI (and the UI at `/docs`) will
  2631. show it as the response (JSON Schema).
  2632. * Serialization: you could return an arbitrary object and the
  2633. `response_model` would be used to serialize that object into the
  2634. corresponding JSON.
  2635. * Filtering: the JSON sent to the client will only contain the data
  2636. (fields) defined in the `response_model`. If you returned an object
  2637. that contains an attribute `password` but the `response_model` does
  2638. not include that field, the JSON sent to the client would not have
  2639. that `password`.
  2640. * Validation: whatever you return will be serialized with the
  2641. `response_model`, converting any data as necessary to generate the
  2642. corresponding JSON. But if the data in the object returned is not
  2643. valid, that would mean a violation of the contract with the client,
  2644. so it's an error from the API developer. So, FastAPI will raise an
  2645. error and return a 500 error code (Internal Server Error).
  2646. Read more about it in the
  2647. [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/).
  2648. """
  2649. ),
  2650. ] = Default(None),
  2651. status_code: Annotated[
  2652. Optional[int],
  2653. Doc(
  2654. """
  2655. The default status code to be used for the response.
  2656. You could override the status code by returning a response directly.
  2657. Read more about it in the
  2658. [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/).
  2659. """
  2660. ),
  2661. ] = None,
  2662. tags: Annotated[
  2663. Optional[List[Union[str, Enum]]],
  2664. Doc(
  2665. """
  2666. A list of tags to be applied to 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/#tags).
  2670. """
  2671. ),
  2672. ] = None,
  2673. dependencies: Annotated[
  2674. Optional[Sequence[Depends]],
  2675. Doc(
  2676. """
  2677. A list of dependencies (using `Depends()`) to be applied to the
  2678. *path operation*.
  2679. Read more about it in the
  2680. [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/).
  2681. """
  2682. ),
  2683. ] = None,
  2684. summary: Annotated[
  2685. Optional[str],
  2686. Doc(
  2687. """
  2688. A summary for the *path operation*.
  2689. It will be added to the generated OpenAPI (e.g. visible at `/docs`).
  2690. Read more about it in the
  2691. [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).
  2692. """
  2693. ),
  2694. ] = None,
  2695. description: Annotated[
  2696. Optional[str],
  2697. Doc(
  2698. """
  2699. A description for the *path operation*.
  2700. If not provided, it will be extracted automatically from the docstring
  2701. of the *path operation function*.
  2702. It can contain Markdown.
  2703. It will be added to the generated OpenAPI (e.g. visible at `/docs`).
  2704. Read more about it in the
  2705. [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).
  2706. """
  2707. ),
  2708. ] = None,
  2709. response_description: Annotated[
  2710. str,
  2711. Doc(
  2712. """
  2713. The description for the default response.
  2714. It will be added to the generated OpenAPI (e.g. visible at `/docs`).
  2715. """
  2716. ),
  2717. ] = "Successful Response",
  2718. responses: Annotated[
  2719. Optional[Dict[Union[int, str], Dict[str, Any]]],
  2720. Doc(
  2721. """
  2722. Additional responses that could be returned by this *path operation*.
  2723. It will be added to the generated OpenAPI (e.g. visible at `/docs`).
  2724. """
  2725. ),
  2726. ] = None,
  2727. deprecated: Annotated[
  2728. Optional[bool],
  2729. Doc(
  2730. """
  2731. Mark this *path operation* as deprecated.
  2732. It will be added to the generated OpenAPI (e.g. visible at `/docs`).
  2733. """
  2734. ),
  2735. ] = None,
  2736. operation_id: Annotated[
  2737. Optional[str],
  2738. Doc(
  2739. """
  2740. Custom operation ID to be used by this *path operation*.
  2741. By default, it is generated automatically.
  2742. If you provide a custom operation ID, you need to make sure it is
  2743. unique for the whole API.
  2744. You can customize the
  2745. operation ID generation with the parameter
  2746. `generate_unique_id_function` in the `FastAPI` class.
  2747. Read more about it in the
  2748. [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).
  2749. """
  2750. ),
  2751. ] = None,
  2752. response_model_include: Annotated[
  2753. Optional[IncEx],
  2754. Doc(
  2755. """
  2756. Configuration passed to Pydantic to include only certain fields in the
  2757. response data.
  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. ] = None,
  2763. response_model_exclude: Annotated[
  2764. Optional[IncEx],
  2765. Doc(
  2766. """
  2767. Configuration passed to Pydantic to exclude certain fields in the
  2768. response data.
  2769. Read more about it in the
  2770. [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).
  2771. """
  2772. ),
  2773. ] = None,
  2774. response_model_by_alias: Annotated[
  2775. bool,
  2776. Doc(
  2777. """
  2778. Configuration passed to Pydantic to define if the response model
  2779. should be serialized by alias when an alias is used.
  2780. Read more about it in the
  2781. [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).
  2782. """
  2783. ),
  2784. ] = True,
  2785. response_model_exclude_unset: Annotated[
  2786. bool,
  2787. Doc(
  2788. """
  2789. Configuration passed to Pydantic to define if the response data
  2790. should have all the fields, including the ones that were not set and
  2791. have their default values. This is different from
  2792. `response_model_exclude_defaults` in that if the fields are set,
  2793. they will be included in the response, even if the value is the same
  2794. as the default.
  2795. When `True`, default values are omitted from the response.
  2796. Read more about it in the
  2797. [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).
  2798. """
  2799. ),
  2800. ] = False,
  2801. response_model_exclude_defaults: Annotated[
  2802. bool,
  2803. Doc(
  2804. """
  2805. Configuration passed to Pydantic to define if the response data
  2806. should have all the fields, including the ones that have the same value
  2807. as the default. This is different from `response_model_exclude_unset`
  2808. in that if the fields are set but contain the same default values,
  2809. they will be excluded from the response.
  2810. When `True`, default values are omitted from the response.
  2811. Read more about it in the
  2812. [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).
  2813. """
  2814. ),
  2815. ] = False,
  2816. response_model_exclude_none: Annotated[
  2817. bool,
  2818. Doc(
  2819. """
  2820. Configuration passed to Pydantic to define if the response data should
  2821. exclude fields set to `None`.
  2822. This is much simpler (less smart) than `response_model_exclude_unset`
  2823. and `response_model_exclude_defaults`. You probably want to use one of
  2824. those two instead of this one, as those allow returning `None` values
  2825. when it makes sense.
  2826. Read more about it in the
  2827. [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none).
  2828. """
  2829. ),
  2830. ] = False,
  2831. include_in_schema: Annotated[
  2832. bool,
  2833. Doc(
  2834. """
  2835. Include this *path operation* in the generated OpenAPI schema.
  2836. This affects the generated OpenAPI (e.g. visible at `/docs`).
  2837. Read more about it in the
  2838. [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-parameters-from-openapi).
  2839. """
  2840. ),
  2841. ] = True,
  2842. response_class: Annotated[
  2843. Type[Response],
  2844. Doc(
  2845. """
  2846. Response class to be used for this *path operation*.
  2847. This will not be used if you return a response directly.
  2848. Read more about it in the
  2849. [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse).
  2850. """
  2851. ),
  2852. ] = Default(JSONResponse),
  2853. name: Annotated[
  2854. Optional[str],
  2855. Doc(
  2856. """
  2857. Name for this *path operation*. Only used internally.
  2858. """
  2859. ),
  2860. ] = None,
  2861. callbacks: Annotated[
  2862. Optional[List[BaseRoute]],
  2863. Doc(
  2864. """
  2865. List of *path operations* that will be used as OpenAPI callbacks.
  2866. This is only for OpenAPI documentation, the callbacks won't be used
  2867. directly.
  2868. It will be added to the generated OpenAPI (e.g. visible at `/docs`).
  2869. Read more about it in the
  2870. [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/).
  2871. """
  2872. ),
  2873. ] = None,
  2874. openapi_extra: Annotated[
  2875. Optional[Dict[str, Any]],
  2876. Doc(
  2877. """
  2878. Extra metadata to be included in the OpenAPI schema for this *path
  2879. operation*.
  2880. Read more about it in the
  2881. [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema).
  2882. """
  2883. ),
  2884. ] = None,
  2885. generate_unique_id_function: Annotated[
  2886. Callable[[routing.APIRoute], str],
  2887. Doc(
  2888. """
  2889. Customize the function used to generate unique IDs for the *path
  2890. operations* shown in the generated OpenAPI.
  2891. This is particularly useful when automatically generating clients or
  2892. SDKs for your API.
  2893. Read more about it in the
  2894. [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).
  2895. """
  2896. ),
  2897. ] = Default(generate_unique_id),
  2898. ) -> Callable[[DecoratedCallable], DecoratedCallable]:
  2899. """
  2900. Add a *path operation* using an HTTP OPTIONS operation.
  2901. ## Example
  2902. ```python
  2903. from fastapi import FastAPI
  2904. app = FastAPI()
  2905. @app.options("/items/")
  2906. def get_item_options():
  2907. return {"additions": ["Aji", "Guacamole"]}
  2908. ```
  2909. """
  2910. return self.router.options(
  2911. path,
  2912. response_model=response_model,
  2913. status_code=status_code,
  2914. tags=tags,
  2915. dependencies=dependencies,
  2916. summary=summary,
  2917. description=description,
  2918. response_description=response_description,
  2919. responses=responses,
  2920. deprecated=deprecated,
  2921. operation_id=operation_id,
  2922. response_model_include=response_model_include,
  2923. response_model_exclude=response_model_exclude,
  2924. response_model_by_alias=response_model_by_alias,
  2925. response_model_exclude_unset=response_model_exclude_unset,
  2926. response_model_exclude_defaults=response_model_exclude_defaults,
  2927. response_model_exclude_none=response_model_exclude_none,
  2928. include_in_schema=include_in_schema,
  2929. response_class=response_class,
  2930. name=name,
  2931. callbacks=callbacks,
  2932. openapi_extra=openapi_extra,
  2933. generate_unique_id_function=generate_unique_id_function,
  2934. )
  2935. def head(
  2936. self,
  2937. path: Annotated[
  2938. str,
  2939. Doc(
  2940. """
  2941. The URL path to be used for this *path operation*.
  2942. For example, in `http://example.com/items`, the path is `/items`.
  2943. """
  2944. ),
  2945. ],
  2946. *,
  2947. response_model: Annotated[
  2948. Any,
  2949. Doc(
  2950. """
  2951. The type to use for the response.
  2952. It could be any valid Pydantic *field* type. So, it doesn't have to
  2953. be a Pydantic model, it could be other things, like a `list`, `dict`,
  2954. etc.
  2955. It will be used for:
  2956. * Documentation: the generated OpenAPI (and the UI at `/docs`) will
  2957. show it as the response (JSON Schema).
  2958. * Serialization: you could return an arbitrary object and the
  2959. `response_model` would be used to serialize that object into the
  2960. corresponding JSON.
  2961. * Filtering: the JSON sent to the client will only contain the data
  2962. (fields) defined in the `response_model`. If you returned an object
  2963. that contains an attribute `password` but the `response_model` does
  2964. not include that field, the JSON sent to the client would not have
  2965. that `password`.
  2966. * Validation: whatever you return will be serialized with the
  2967. `response_model`, converting any data as necessary to generate the
  2968. corresponding JSON. But if the data in the object returned is not
  2969. valid, that would mean a violation of the contract with the client,
  2970. so it's an error from the API developer. So, FastAPI will raise an
  2971. error and return a 500 error code (Internal Server Error).
  2972. Read more about it in the
  2973. [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/).
  2974. """
  2975. ),
  2976. ] = Default(None),
  2977. status_code: Annotated[
  2978. Optional[int],
  2979. Doc(
  2980. """
  2981. The default status code to be used for the response.
  2982. You could override the status code by returning a response directly.
  2983. Read more about it in the
  2984. [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/).
  2985. """
  2986. ),
  2987. ] = None,
  2988. tags: Annotated[
  2989. Optional[List[Union[str, Enum]]],
  2990. Doc(
  2991. """
  2992. A list of tags to be applied to 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/#tags).
  2996. """
  2997. ),
  2998. ] = None,
  2999. dependencies: Annotated[
  3000. Optional[Sequence[Depends]],
  3001. Doc(
  3002. """
  3003. A list of dependencies (using `Depends()`) to be applied to the
  3004. *path operation*.
  3005. Read more about it in the
  3006. [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/).
  3007. """
  3008. ),
  3009. ] = None,
  3010. summary: Annotated[
  3011. Optional[str],
  3012. Doc(
  3013. """
  3014. A summary for the *path operation*.
  3015. It will be added to the generated OpenAPI (e.g. visible at `/docs`).
  3016. Read more about it in the
  3017. [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).
  3018. """
  3019. ),
  3020. ] = None,
  3021. description: Annotated[
  3022. Optional[str],
  3023. Doc(
  3024. """
  3025. A description for the *path operation*.
  3026. If not provided, it will be extracted automatically from the docstring
  3027. of the *path operation function*.
  3028. It can contain Markdown.
  3029. It will be added to the generated OpenAPI (e.g. visible at `/docs`).
  3030. Read more about it in the
  3031. [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).
  3032. """
  3033. ),
  3034. ] = None,
  3035. response_description: Annotated[
  3036. str,
  3037. Doc(
  3038. """
  3039. The description for the default response.
  3040. It will be added to the generated OpenAPI (e.g. visible at `/docs`).
  3041. """
  3042. ),
  3043. ] = "Successful Response",
  3044. responses: Annotated[
  3045. Optional[Dict[Union[int, str], Dict[str, Any]]],
  3046. Doc(
  3047. """
  3048. Additional responses that could be returned by this *path operation*.
  3049. It will be added to the generated OpenAPI (e.g. visible at `/docs`).
  3050. """
  3051. ),
  3052. ] = None,
  3053. deprecated: Annotated[
  3054. Optional[bool],
  3055. Doc(
  3056. """
  3057. Mark this *path operation* as deprecated.
  3058. It will be added to the generated OpenAPI (e.g. visible at `/docs`).
  3059. """
  3060. ),
  3061. ] = None,
  3062. operation_id: Annotated[
  3063. Optional[str],
  3064. Doc(
  3065. """
  3066. Custom operation ID to be used by this *path operation*.
  3067. By default, it is generated automatically.
  3068. If you provide a custom operation ID, you need to make sure it is
  3069. unique for the whole API.
  3070. You can customize the
  3071. operation ID generation with the parameter
  3072. `generate_unique_id_function` in the `FastAPI` class.
  3073. Read more about it in the
  3074. [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).
  3075. """
  3076. ),
  3077. ] = None,
  3078. response_model_include: Annotated[
  3079. Optional[IncEx],
  3080. Doc(
  3081. """
  3082. Configuration passed to Pydantic to include only certain fields in the
  3083. response data.
  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. ] = None,
  3089. response_model_exclude: Annotated[
  3090. Optional[IncEx],
  3091. Doc(
  3092. """
  3093. Configuration passed to Pydantic to exclude certain fields in the
  3094. response data.
  3095. Read more about it in the
  3096. [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).
  3097. """
  3098. ),
  3099. ] = None,
  3100. response_model_by_alias: Annotated[
  3101. bool,
  3102. Doc(
  3103. """
  3104. Configuration passed to Pydantic to define if the response model
  3105. should be serialized by alias when an alias is used.
  3106. Read more about it in the
  3107. [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).
  3108. """
  3109. ),
  3110. ] = True,
  3111. response_model_exclude_unset: Annotated[
  3112. bool,
  3113. Doc(
  3114. """
  3115. Configuration passed to Pydantic to define if the response data
  3116. should have all the fields, including the ones that were not set and
  3117. have their default values. This is different from
  3118. `response_model_exclude_defaults` in that if the fields are set,
  3119. they will be included in the response, even if the value is the same
  3120. as the default.
  3121. When `True`, default values are omitted from the response.
  3122. Read more about it in the
  3123. [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).
  3124. """
  3125. ),
  3126. ] = False,
  3127. response_model_exclude_defaults: Annotated[
  3128. bool,
  3129. Doc(
  3130. """
  3131. Configuration passed to Pydantic to define if the response data
  3132. should have all the fields, including the ones that have the same value
  3133. as the default. This is different from `response_model_exclude_unset`
  3134. in that if the fields are set but contain the same default values,
  3135. they will be excluded from the response.
  3136. When `True`, default values are omitted from the response.
  3137. Read more about it in the
  3138. [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).
  3139. """
  3140. ),
  3141. ] = False,
  3142. response_model_exclude_none: Annotated[
  3143. bool,
  3144. Doc(
  3145. """
  3146. Configuration passed to Pydantic to define if the response data should
  3147. exclude fields set to `None`.
  3148. This is much simpler (less smart) than `response_model_exclude_unset`
  3149. and `response_model_exclude_defaults`. You probably want to use one of
  3150. those two instead of this one, as those allow returning `None` values
  3151. when it makes sense.
  3152. Read more about it in the
  3153. [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none).
  3154. """
  3155. ),
  3156. ] = False,
  3157. include_in_schema: Annotated[
  3158. bool,
  3159. Doc(
  3160. """
  3161. Include this *path operation* in the generated OpenAPI schema.
  3162. This affects the generated OpenAPI (e.g. visible at `/docs`).
  3163. Read more about it in the
  3164. [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-parameters-from-openapi).
  3165. """
  3166. ),
  3167. ] = True,
  3168. response_class: Annotated[
  3169. Type[Response],
  3170. Doc(
  3171. """
  3172. Response class to be used for this *path operation*.
  3173. This will not be used if you return a response directly.
  3174. Read more about it in the
  3175. [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse).
  3176. """
  3177. ),
  3178. ] = Default(JSONResponse),
  3179. name: Annotated[
  3180. Optional[str],
  3181. Doc(
  3182. """
  3183. Name for this *path operation*. Only used internally.
  3184. """
  3185. ),
  3186. ] = None,
  3187. callbacks: Annotated[
  3188. Optional[List[BaseRoute]],
  3189. Doc(
  3190. """
  3191. List of *path operations* that will be used as OpenAPI callbacks.
  3192. This is only for OpenAPI documentation, the callbacks won't be used
  3193. directly.
  3194. It will be added to the generated OpenAPI (e.g. visible at `/docs`).
  3195. Read more about it in the
  3196. [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/).
  3197. """
  3198. ),
  3199. ] = None,
  3200. openapi_extra: Annotated[
  3201. Optional[Dict[str, Any]],
  3202. Doc(
  3203. """
  3204. Extra metadata to be included in the OpenAPI schema for this *path
  3205. operation*.
  3206. Read more about it in the
  3207. [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema).
  3208. """
  3209. ),
  3210. ] = None,
  3211. generate_unique_id_function: Annotated[
  3212. Callable[[routing.APIRoute], str],
  3213. Doc(
  3214. """
  3215. Customize the function used to generate unique IDs for the *path
  3216. operations* shown in the generated OpenAPI.
  3217. This is particularly useful when automatically generating clients or
  3218. SDKs for your API.
  3219. Read more about it in the
  3220. [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).
  3221. """
  3222. ),
  3223. ] = Default(generate_unique_id),
  3224. ) -> Callable[[DecoratedCallable], DecoratedCallable]:
  3225. """
  3226. Add a *path operation* using an HTTP HEAD operation.
  3227. ## Example
  3228. ```python
  3229. from fastapi import FastAPI, Response
  3230. app = FastAPI()
  3231. @app.head("/items/", status_code=204)
  3232. def get_items_headers(response: Response):
  3233. response.headers["X-Cat-Dog"] = "Alone in the world"
  3234. ```
  3235. """
  3236. return self.router.head(
  3237. path,
  3238. response_model=response_model,
  3239. status_code=status_code,
  3240. tags=tags,
  3241. dependencies=dependencies,
  3242. summary=summary,
  3243. description=description,
  3244. response_description=response_description,
  3245. responses=responses,
  3246. deprecated=deprecated,
  3247. operation_id=operation_id,
  3248. response_model_include=response_model_include,
  3249. response_model_exclude=response_model_exclude,
  3250. response_model_by_alias=response_model_by_alias,
  3251. response_model_exclude_unset=response_model_exclude_unset,
  3252. response_model_exclude_defaults=response_model_exclude_defaults,
  3253. response_model_exclude_none=response_model_exclude_none,
  3254. include_in_schema=include_in_schema,
  3255. response_class=response_class,
  3256. name=name,
  3257. callbacks=callbacks,
  3258. openapi_extra=openapi_extra,
  3259. generate_unique_id_function=generate_unique_id_function,
  3260. )
  3261. def patch(
  3262. self,
  3263. path: Annotated[
  3264. str,
  3265. Doc(
  3266. """
  3267. The URL path to be used for this *path operation*.
  3268. For example, in `http://example.com/items`, the path is `/items`.
  3269. """
  3270. ),
  3271. ],
  3272. *,
  3273. response_model: Annotated[
  3274. Any,
  3275. Doc(
  3276. """
  3277. The type to use for the response.
  3278. It could be any valid Pydantic *field* type. So, it doesn't have to
  3279. be a Pydantic model, it could be other things, like a `list`, `dict`,
  3280. etc.
  3281. It will be used for:
  3282. * Documentation: the generated OpenAPI (and the UI at `/docs`) will
  3283. show it as the response (JSON Schema).
  3284. * Serialization: you could return an arbitrary object and the
  3285. `response_model` would be used to serialize that object into the
  3286. corresponding JSON.
  3287. * Filtering: the JSON sent to the client will only contain the data
  3288. (fields) defined in the `response_model`. If you returned an object
  3289. that contains an attribute `password` but the `response_model` does
  3290. not include that field, the JSON sent to the client would not have
  3291. that `password`.
  3292. * Validation: whatever you return will be serialized with the
  3293. `response_model`, converting any data as necessary to generate the
  3294. corresponding JSON. But if the data in the object returned is not
  3295. valid, that would mean a violation of the contract with the client,
  3296. so it's an error from the API developer. So, FastAPI will raise an
  3297. error and return a 500 error code (Internal Server Error).
  3298. Read more about it in the
  3299. [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/).
  3300. """
  3301. ),
  3302. ] = Default(None),
  3303. status_code: Annotated[
  3304. Optional[int],
  3305. Doc(
  3306. """
  3307. The default status code to be used for the response.
  3308. You could override the status code by returning a response directly.
  3309. Read more about it in the
  3310. [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/).
  3311. """
  3312. ),
  3313. ] = None,
  3314. tags: Annotated[
  3315. Optional[List[Union[str, Enum]]],
  3316. Doc(
  3317. """
  3318. A list of tags to be applied to 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/#tags).
  3322. """
  3323. ),
  3324. ] = None,
  3325. dependencies: Annotated[
  3326. Optional[Sequence[Depends]],
  3327. Doc(
  3328. """
  3329. A list of dependencies (using `Depends()`) to be applied to the
  3330. *path operation*.
  3331. Read more about it in the
  3332. [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/).
  3333. """
  3334. ),
  3335. ] = None,
  3336. summary: Annotated[
  3337. Optional[str],
  3338. Doc(
  3339. """
  3340. A summary for the *path operation*.
  3341. It will be added to the generated OpenAPI (e.g. visible at `/docs`).
  3342. Read more about it in the
  3343. [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).
  3344. """
  3345. ),
  3346. ] = None,
  3347. description: Annotated[
  3348. Optional[str],
  3349. Doc(
  3350. """
  3351. A description for the *path operation*.
  3352. If not provided, it will be extracted automatically from the docstring
  3353. of the *path operation function*.
  3354. It can contain Markdown.
  3355. It will be added to the generated OpenAPI (e.g. visible at `/docs`).
  3356. Read more about it in the
  3357. [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).
  3358. """
  3359. ),
  3360. ] = None,
  3361. response_description: Annotated[
  3362. str,
  3363. Doc(
  3364. """
  3365. The description for the default response.
  3366. It will be added to the generated OpenAPI (e.g. visible at `/docs`).
  3367. """
  3368. ),
  3369. ] = "Successful Response",
  3370. responses: Annotated[
  3371. Optional[Dict[Union[int, str], Dict[str, Any]]],
  3372. Doc(
  3373. """
  3374. Additional responses that could be returned by this *path operation*.
  3375. It will be added to the generated OpenAPI (e.g. visible at `/docs`).
  3376. """
  3377. ),
  3378. ] = None,
  3379. deprecated: Annotated[
  3380. Optional[bool],
  3381. Doc(
  3382. """
  3383. Mark this *path operation* as deprecated.
  3384. It will be added to the generated OpenAPI (e.g. visible at `/docs`).
  3385. """
  3386. ),
  3387. ] = None,
  3388. operation_id: Annotated[
  3389. Optional[str],
  3390. Doc(
  3391. """
  3392. Custom operation ID to be used by this *path operation*.
  3393. By default, it is generated automatically.
  3394. If you provide a custom operation ID, you need to make sure it is
  3395. unique for the whole API.
  3396. You can customize the
  3397. operation ID generation with the parameter
  3398. `generate_unique_id_function` in the `FastAPI` class.
  3399. Read more about it in the
  3400. [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).
  3401. """
  3402. ),
  3403. ] = None,
  3404. response_model_include: Annotated[
  3405. Optional[IncEx],
  3406. Doc(
  3407. """
  3408. Configuration passed to Pydantic to include only certain fields in the
  3409. response data.
  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. ] = None,
  3415. response_model_exclude: Annotated[
  3416. Optional[IncEx],
  3417. Doc(
  3418. """
  3419. Configuration passed to Pydantic to exclude certain fields in the
  3420. response data.
  3421. Read more about it in the
  3422. [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).
  3423. """
  3424. ),
  3425. ] = None,
  3426. response_model_by_alias: Annotated[
  3427. bool,
  3428. Doc(
  3429. """
  3430. Configuration passed to Pydantic to define if the response model
  3431. should be serialized by alias when an alias is used.
  3432. Read more about it in the
  3433. [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).
  3434. """
  3435. ),
  3436. ] = True,
  3437. response_model_exclude_unset: Annotated[
  3438. bool,
  3439. Doc(
  3440. """
  3441. Configuration passed to Pydantic to define if the response data
  3442. should have all the fields, including the ones that were not set and
  3443. have their default values. This is different from
  3444. `response_model_exclude_defaults` in that if the fields are set,
  3445. they will be included in the response, even if the value is the same
  3446. as the default.
  3447. When `True`, default values are omitted from the response.
  3448. Read more about it in the
  3449. [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).
  3450. """
  3451. ),
  3452. ] = False,
  3453. response_model_exclude_defaults: Annotated[
  3454. bool,
  3455. Doc(
  3456. """
  3457. Configuration passed to Pydantic to define if the response data
  3458. should have all the fields, including the ones that have the same value
  3459. as the default. This is different from `response_model_exclude_unset`
  3460. in that if the fields are set but contain the same default values,
  3461. they will be excluded from the response.
  3462. When `True`, default values are omitted from the response.
  3463. Read more about it in the
  3464. [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).
  3465. """
  3466. ),
  3467. ] = False,
  3468. response_model_exclude_none: Annotated[
  3469. bool,
  3470. Doc(
  3471. """
  3472. Configuration passed to Pydantic to define if the response data should
  3473. exclude fields set to `None`.
  3474. This is much simpler (less smart) than `response_model_exclude_unset`
  3475. and `response_model_exclude_defaults`. You probably want to use one of
  3476. those two instead of this one, as those allow returning `None` values
  3477. when it makes sense.
  3478. Read more about it in the
  3479. [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none).
  3480. """
  3481. ),
  3482. ] = False,
  3483. include_in_schema: Annotated[
  3484. bool,
  3485. Doc(
  3486. """
  3487. Include this *path operation* in the generated OpenAPI schema.
  3488. This affects the generated OpenAPI (e.g. visible at `/docs`).
  3489. Read more about it in the
  3490. [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-parameters-from-openapi).
  3491. """
  3492. ),
  3493. ] = True,
  3494. response_class: Annotated[
  3495. Type[Response],
  3496. Doc(
  3497. """
  3498. Response class to be used for this *path operation*.
  3499. This will not be used if you return a response directly.
  3500. Read more about it in the
  3501. [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse).
  3502. """
  3503. ),
  3504. ] = Default(JSONResponse),
  3505. name: Annotated[
  3506. Optional[str],
  3507. Doc(
  3508. """
  3509. Name for this *path operation*. Only used internally.
  3510. """
  3511. ),
  3512. ] = None,
  3513. callbacks: Annotated[
  3514. Optional[List[BaseRoute]],
  3515. Doc(
  3516. """
  3517. List of *path operations* that will be used as OpenAPI callbacks.
  3518. This is only for OpenAPI documentation, the callbacks won't be used
  3519. directly.
  3520. It will be added to the generated OpenAPI (e.g. visible at `/docs`).
  3521. Read more about it in the
  3522. [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/).
  3523. """
  3524. ),
  3525. ] = None,
  3526. openapi_extra: Annotated[
  3527. Optional[Dict[str, Any]],
  3528. Doc(
  3529. """
  3530. Extra metadata to be included in the OpenAPI schema for this *path
  3531. operation*.
  3532. Read more about it in the
  3533. [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema).
  3534. """
  3535. ),
  3536. ] = None,
  3537. generate_unique_id_function: Annotated[
  3538. Callable[[routing.APIRoute], str],
  3539. Doc(
  3540. """
  3541. Customize the function used to generate unique IDs for the *path
  3542. operations* shown in the generated OpenAPI.
  3543. This is particularly useful when automatically generating clients or
  3544. SDKs for your API.
  3545. Read more about it in the
  3546. [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).
  3547. """
  3548. ),
  3549. ] = Default(generate_unique_id),
  3550. ) -> Callable[[DecoratedCallable], DecoratedCallable]:
  3551. """
  3552. Add a *path operation* using an HTTP PATCH operation.
  3553. ## Example
  3554. ```python
  3555. from fastapi import FastAPI
  3556. from pydantic import BaseModel
  3557. class Item(BaseModel):
  3558. name: str
  3559. description: str | None = None
  3560. app = FastAPI()
  3561. @app.patch("/items/")
  3562. def update_item(item: Item):
  3563. return {"message": "Item updated in place"}
  3564. ```
  3565. """
  3566. return self.router.patch(
  3567. path,
  3568. response_model=response_model,
  3569. status_code=status_code,
  3570. tags=tags,
  3571. dependencies=dependencies,
  3572. summary=summary,
  3573. description=description,
  3574. response_description=response_description,
  3575. responses=responses,
  3576. deprecated=deprecated,
  3577. operation_id=operation_id,
  3578. response_model_include=response_model_include,
  3579. response_model_exclude=response_model_exclude,
  3580. response_model_by_alias=response_model_by_alias,
  3581. response_model_exclude_unset=response_model_exclude_unset,
  3582. response_model_exclude_defaults=response_model_exclude_defaults,
  3583. response_model_exclude_none=response_model_exclude_none,
  3584. include_in_schema=include_in_schema,
  3585. response_class=response_class,
  3586. name=name,
  3587. callbacks=callbacks,
  3588. openapi_extra=openapi_extra,
  3589. generate_unique_id_function=generate_unique_id_function,
  3590. )
  3591. def trace(
  3592. self,
  3593. path: Annotated[
  3594. str,
  3595. Doc(
  3596. """
  3597. The URL path to be used for this *path operation*.
  3598. For example, in `http://example.com/items`, the path is `/items`.
  3599. """
  3600. ),
  3601. ],
  3602. *,
  3603. response_model: Annotated[
  3604. Any,
  3605. Doc(
  3606. """
  3607. The type to use for the response.
  3608. It could be any valid Pydantic *field* type. So, it doesn't have to
  3609. be a Pydantic model, it could be other things, like a `list`, `dict`,
  3610. etc.
  3611. It will be used for:
  3612. * Documentation: the generated OpenAPI (and the UI at `/docs`) will
  3613. show it as the response (JSON Schema).
  3614. * Serialization: you could return an arbitrary object and the
  3615. `response_model` would be used to serialize that object into the
  3616. corresponding JSON.
  3617. * Filtering: the JSON sent to the client will only contain the data
  3618. (fields) defined in the `response_model`. If you returned an object
  3619. that contains an attribute `password` but the `response_model` does
  3620. not include that field, the JSON sent to the client would not have
  3621. that `password`.
  3622. * Validation: whatever you return will be serialized with the
  3623. `response_model`, converting any data as necessary to generate the
  3624. corresponding JSON. But if the data in the object returned is not
  3625. valid, that would mean a violation of the contract with the client,
  3626. so it's an error from the API developer. So, FastAPI will raise an
  3627. error and return a 500 error code (Internal Server Error).
  3628. Read more about it in the
  3629. [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/).
  3630. """
  3631. ),
  3632. ] = Default(None),
  3633. status_code: Annotated[
  3634. Optional[int],
  3635. Doc(
  3636. """
  3637. The default status code to be used for the response.
  3638. You could override the status code by returning a response directly.
  3639. Read more about it in the
  3640. [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/).
  3641. """
  3642. ),
  3643. ] = None,
  3644. tags: Annotated[
  3645. Optional[List[Union[str, Enum]]],
  3646. Doc(
  3647. """
  3648. A list of tags to be applied to 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/#tags).
  3652. """
  3653. ),
  3654. ] = None,
  3655. dependencies: Annotated[
  3656. Optional[Sequence[Depends]],
  3657. Doc(
  3658. """
  3659. A list of dependencies (using `Depends()`) to be applied to the
  3660. *path operation*.
  3661. Read more about it in the
  3662. [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/).
  3663. """
  3664. ),
  3665. ] = None,
  3666. summary: Annotated[
  3667. Optional[str],
  3668. Doc(
  3669. """
  3670. A summary for the *path operation*.
  3671. It will be added to the generated OpenAPI (e.g. visible at `/docs`).
  3672. Read more about it in the
  3673. [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).
  3674. """
  3675. ),
  3676. ] = None,
  3677. description: Annotated[
  3678. Optional[str],
  3679. Doc(
  3680. """
  3681. A description for the *path operation*.
  3682. If not provided, it will be extracted automatically from the docstring
  3683. of the *path operation function*.
  3684. It can contain Markdown.
  3685. It will be added to the generated OpenAPI (e.g. visible at `/docs`).
  3686. Read more about it in the
  3687. [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).
  3688. """
  3689. ),
  3690. ] = None,
  3691. response_description: Annotated[
  3692. str,
  3693. Doc(
  3694. """
  3695. The description for the default response.
  3696. It will be added to the generated OpenAPI (e.g. visible at `/docs`).
  3697. """
  3698. ),
  3699. ] = "Successful Response",
  3700. responses: Annotated[
  3701. Optional[Dict[Union[int, str], Dict[str, Any]]],
  3702. Doc(
  3703. """
  3704. Additional responses that could be returned by this *path operation*.
  3705. It will be added to the generated OpenAPI (e.g. visible at `/docs`).
  3706. """
  3707. ),
  3708. ] = None,
  3709. deprecated: Annotated[
  3710. Optional[bool],
  3711. Doc(
  3712. """
  3713. Mark this *path operation* as deprecated.
  3714. It will be added to the generated OpenAPI (e.g. visible at `/docs`).
  3715. """
  3716. ),
  3717. ] = None,
  3718. operation_id: Annotated[
  3719. Optional[str],
  3720. Doc(
  3721. """
  3722. Custom operation ID to be used by this *path operation*.
  3723. By default, it is generated automatically.
  3724. If you provide a custom operation ID, you need to make sure it is
  3725. unique for the whole API.
  3726. You can customize the
  3727. operation ID generation with the parameter
  3728. `generate_unique_id_function` in the `FastAPI` class.
  3729. Read more about it in the
  3730. [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).
  3731. """
  3732. ),
  3733. ] = None,
  3734. response_model_include: Annotated[
  3735. Optional[IncEx],
  3736. Doc(
  3737. """
  3738. Configuration passed to Pydantic to include only certain fields in the
  3739. response data.
  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. ] = None,
  3745. response_model_exclude: Annotated[
  3746. Optional[IncEx],
  3747. Doc(
  3748. """
  3749. Configuration passed to Pydantic to exclude certain fields in the
  3750. response data.
  3751. Read more about it in the
  3752. [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).
  3753. """
  3754. ),
  3755. ] = None,
  3756. response_model_by_alias: Annotated[
  3757. bool,
  3758. Doc(
  3759. """
  3760. Configuration passed to Pydantic to define if the response model
  3761. should be serialized by alias when an alias is used.
  3762. Read more about it in the
  3763. [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).
  3764. """
  3765. ),
  3766. ] = True,
  3767. response_model_exclude_unset: Annotated[
  3768. bool,
  3769. Doc(
  3770. """
  3771. Configuration passed to Pydantic to define if the response data
  3772. should have all the fields, including the ones that were not set and
  3773. have their default values. This is different from
  3774. `response_model_exclude_defaults` in that if the fields are set,
  3775. they will be included in the response, even if the value is the same
  3776. as the default.
  3777. When `True`, default values are omitted from the response.
  3778. Read more about it in the
  3779. [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).
  3780. """
  3781. ),
  3782. ] = False,
  3783. response_model_exclude_defaults: Annotated[
  3784. bool,
  3785. Doc(
  3786. """
  3787. Configuration passed to Pydantic to define if the response data
  3788. should have all the fields, including the ones that have the same value
  3789. as the default. This is different from `response_model_exclude_unset`
  3790. in that if the fields are set but contain the same default values,
  3791. they will be excluded from the response.
  3792. When `True`, default values are omitted from the response.
  3793. Read more about it in the
  3794. [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).
  3795. """
  3796. ),
  3797. ] = False,
  3798. response_model_exclude_none: Annotated[
  3799. bool,
  3800. Doc(
  3801. """
  3802. Configuration passed to Pydantic to define if the response data should
  3803. exclude fields set to `None`.
  3804. This is much simpler (less smart) than `response_model_exclude_unset`
  3805. and `response_model_exclude_defaults`. You probably want to use one of
  3806. those two instead of this one, as those allow returning `None` values
  3807. when it makes sense.
  3808. Read more about it in the
  3809. [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none).
  3810. """
  3811. ),
  3812. ] = False,
  3813. include_in_schema: Annotated[
  3814. bool,
  3815. Doc(
  3816. """
  3817. Include this *path operation* in the generated OpenAPI schema.
  3818. This affects the generated OpenAPI (e.g. visible at `/docs`).
  3819. Read more about it in the
  3820. [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-parameters-from-openapi).
  3821. """
  3822. ),
  3823. ] = True,
  3824. response_class: Annotated[
  3825. Type[Response],
  3826. Doc(
  3827. """
  3828. Response class to be used for this *path operation*.
  3829. This will not be used if you return a response directly.
  3830. Read more about it in the
  3831. [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse).
  3832. """
  3833. ),
  3834. ] = Default(JSONResponse),
  3835. name: Annotated[
  3836. Optional[str],
  3837. Doc(
  3838. """
  3839. Name for this *path operation*. Only used internally.
  3840. """
  3841. ),
  3842. ] = None,
  3843. callbacks: Annotated[
  3844. Optional[List[BaseRoute]],
  3845. Doc(
  3846. """
  3847. List of *path operations* that will be used as OpenAPI callbacks.
  3848. This is only for OpenAPI documentation, the callbacks won't be used
  3849. directly.
  3850. It will be added to the generated OpenAPI (e.g. visible at `/docs`).
  3851. Read more about it in the
  3852. [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/).
  3853. """
  3854. ),
  3855. ] = None,
  3856. openapi_extra: Annotated[
  3857. Optional[Dict[str, Any]],
  3858. Doc(
  3859. """
  3860. Extra metadata to be included in the OpenAPI schema for this *path
  3861. operation*.
  3862. Read more about it in the
  3863. [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema).
  3864. """
  3865. ),
  3866. ] = None,
  3867. generate_unique_id_function: Annotated[
  3868. Callable[[routing.APIRoute], str],
  3869. Doc(
  3870. """
  3871. Customize the function used to generate unique IDs for the *path
  3872. operations* shown in the generated OpenAPI.
  3873. This is particularly useful when automatically generating clients or
  3874. SDKs for your API.
  3875. Read more about it in the
  3876. [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).
  3877. """
  3878. ),
  3879. ] = Default(generate_unique_id),
  3880. ) -> Callable[[DecoratedCallable], DecoratedCallable]:
  3881. """
  3882. Add a *path operation* using an HTTP TRACE operation.
  3883. ## Example
  3884. ```python
  3885. from fastapi import FastAPI
  3886. app = FastAPI()
  3887. @app.trace("/items/{item_id}")
  3888. def trace_item(item_id: str):
  3889. return None
  3890. ```
  3891. """
  3892. return self.router.trace(
  3893. path,
  3894. response_model=response_model,
  3895. status_code=status_code,
  3896. tags=tags,
  3897. dependencies=dependencies,
  3898. summary=summary,
  3899. description=description,
  3900. response_description=response_description,
  3901. responses=responses,
  3902. deprecated=deprecated,
  3903. operation_id=operation_id,
  3904. response_model_include=response_model_include,
  3905. response_model_exclude=response_model_exclude,
  3906. response_model_by_alias=response_model_by_alias,
  3907. response_model_exclude_unset=response_model_exclude_unset,
  3908. response_model_exclude_defaults=response_model_exclude_defaults,
  3909. response_model_exclude_none=response_model_exclude_none,
  3910. include_in_schema=include_in_schema,
  3911. response_class=response_class,
  3912. name=name,
  3913. callbacks=callbacks,
  3914. openapi_extra=openapi_extra,
  3915. generate_unique_id_function=generate_unique_id_function,
  3916. )
  3917. def websocket_route(
  3918. self, path: str, name: Union[str, None] = None
  3919. ) -> Callable[[DecoratedCallable], DecoratedCallable]:
  3920. def decorator(func: DecoratedCallable) -> DecoratedCallable:
  3921. self.router.add_websocket_route(path, func, name=name)
  3922. return func
  3923. return decorator
  3924. @deprecated(
  3925. """
  3926. on_event is deprecated, use lifespan event handlers instead.
  3927. Read more about it in the
  3928. [FastAPI docs for Lifespan Events](https://fastapi.tiangolo.com/advanced/events/).
  3929. """
  3930. )
  3931. def on_event(
  3932. self,
  3933. event_type: Annotated[
  3934. str,
  3935. Doc(
  3936. """
  3937. The type of event. `startup` or `shutdown`.
  3938. """
  3939. ),
  3940. ],
  3941. ) -> Callable[[DecoratedCallable], DecoratedCallable]:
  3942. """
  3943. Add an event handler for the application.
  3944. `on_event` is deprecated, use `lifespan` event handlers instead.
  3945. Read more about it in the
  3946. [FastAPI docs for Lifespan Events](https://fastapi.tiangolo.com/advanced/events/#alternative-events-deprecated).
  3947. """
  3948. return self.router.on_event(event_type)
  3949. def middleware(
  3950. self,
  3951. middleware_type: Annotated[
  3952. str,
  3953. Doc(
  3954. """
  3955. The type of middleware. Currently only supports `http`.
  3956. """
  3957. ),
  3958. ],
  3959. ) -> Callable[[DecoratedCallable], DecoratedCallable]:
  3960. """
  3961. Add a middleware to the application.
  3962. Read more about it in the
  3963. [FastAPI docs for Middleware](https://fastapi.tiangolo.com/tutorial/middleware/).
  3964. ## Example
  3965. ```python
  3966. import time
  3967. from typing import Awaitable, Callable
  3968. from fastapi import FastAPI, Request, Response
  3969. app = FastAPI()
  3970. @app.middleware("http")
  3971. async def add_process_time_header(
  3972. request: Request, call_next: Callable[[Request], Awaitable[Response]]
  3973. ) -> Response:
  3974. start_time = time.time()
  3975. response = await call_next(request)
  3976. process_time = time.time() - start_time
  3977. response.headers["X-Process-Time"] = str(process_time)
  3978. return response
  3979. ```
  3980. """
  3981. def decorator(func: DecoratedCallable) -> DecoratedCallable:
  3982. self.add_middleware(BaseHTTPMiddleware, dispatch=func)
  3983. return func
  3984. return decorator
  3985. def exception_handler(
  3986. self,
  3987. exc_class_or_status_code: Annotated[
  3988. Union[int, Type[Exception]],
  3989. Doc(
  3990. """
  3991. The Exception class this would handle, or a status code.
  3992. """
  3993. ),
  3994. ],
  3995. ) -> Callable[[DecoratedCallable], DecoratedCallable]:
  3996. """
  3997. Add an exception handler to the app.
  3998. Read more about it in the
  3999. [FastAPI docs for Handling Errors](https://fastapi.tiangolo.com/tutorial/handling-errors/).
  4000. ## Example
  4001. ```python
  4002. from fastapi import FastAPI, Request
  4003. from fastapi.responses import JSONResponse
  4004. class UnicornException(Exception):
  4005. def __init__(self, name: str):
  4006. self.name = name
  4007. app = FastAPI()
  4008. @app.exception_handler(UnicornException)
  4009. async def unicorn_exception_handler(request: Request, exc: UnicornException):
  4010. return JSONResponse(
  4011. status_code=418,
  4012. content={"message": f"Oops! {exc.name} did something. There goes a rainbow..."},
  4013. )
  4014. ```
  4015. """
  4016. def decorator(func: DecoratedCallable) -> DecoratedCallable:
  4017. self.add_exception_handler(exc_class_or_status_code, func)
  4018. return func
  4019. return decorator