Response Cookies¶
Use aResponse parameter¶
You can declare a parameter of typeResponse in yourpath operation function.
And then you can set cookies in thattemporal response object.
fromfastapiimportFastAPI,Responseapp=FastAPI()@app.post("/cookie-and-object/")defcreate_cookie(response:Response):response.set_cookie(key="fakesession",value="fake-cookie-session-value")return{"message":"Come to the dark side, we have cookies"}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 cookies (also headers 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 cookies (and headers) in them.
Return aResponse directly¶
You can also create cookies when returning aResponse directly in your code.
To do that, you can create a response as described inReturn a Response Directly.
Then set Cookies in it, and then return it:
fromfastapiimportFastAPIfromfastapi.responsesimportJSONResponseapp=FastAPI()@app.post("/cookie/")defcreate_cookie():content={"message":"Come to the dark side, we have cookies"}response=JSONResponse(content=content)response.set_cookie(key="fakesession",value="fake-cookie-session-value")returnresponseTip
Keep in mind that if you return a response directly instead of using theResponse parameter, FastAPI will return it directly.
So, you will have to make sure your data is of the correct type. E.g. it is compatible with JSON, if you are returning aJSONResponse.
And also that you are not sending any data that should have been filtered by aresponse_model.
More info¶
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.
To see all the available parameters and options, check thedocumentation in Starlette.







