Movatterモバイル変換


[0]ホーム

URL:


Skip to content
Join theFastAPI Cloud waiting list 🚀
Follow@fastapi onX (Twitter) to stay updated
FollowFastAPI onLinkedIn to stay updated
Subscribe to theFastAPI and friends newsletter 🎉
sponsor
sponsor
sponsor
sponsor
sponsor
sponsor
sponsor
sponsor
sponsor
sponsor
sponsor

Response Headers

Use aResponse parameter

You can declare a parameter of typeResponse in yourpath operation function (as you can do for cookies).

And then you can set headers in thattemporal response object.

fromfastapiimportFastAPI,Responseapp=FastAPI()@app.get("/headers-and-object/")defget_headers(response:Response):response.headers["X-Cat-Dog"]="alone in the world"return{"message":"Hello World"}

And then you can return any object you need, as you normally would (adict, a database model, etc).

And if you declared aresponse_model, it will still be used to filter and convert the object you returned.

FastAPI will use thattemporal response to extract the headers (also cookies and status code), and will put them in the final response that contains the value you returned, filtered by anyresponse_model.

You can also declare theResponse parameter in dependencies, and set headers (and cookies) in them.

Return aResponse directly

You can also add headers when you return aResponse directly.

Create a response as described inReturn a Response Directly and pass the headers as an additional parameter:

fromfastapiimportFastAPIfromfastapi.responsesimportJSONResponseapp=FastAPI()@app.get("/headers/")defget_headers():content={"message":"Hello World"}headers={"X-Cat-Dog":"alone in the world","Content-Language":"en-US"}returnJSONResponse(content=content,headers=headers)

Technical Details

You could also usefrom starlette.responses import Response orfrom starlette.responses import JSONResponse.

FastAPI provides the samestarlette.responses asfastapi.responses just as a convenience for you, the developer. But most of the available responses come directly from Starlette.

And as theResponse can be used frequently to set headers and cookies,FastAPI also provides it atfastapi.Response.

Custom Headers

Keep in mind that custom proprietary headers can be addedusing theX- prefix.

But if you have custom headers that you want a client in a browser to be able to see, you need to add them to your CORS configurations (read more inCORS (Cross-Origin Resource Sharing)), using the parameterexpose_headers documented inStarlette's CORS docs.


[8]ページ先頭

©2009-2026 Movatter.jp