How to set cookies with fastapi for cross-origin requests?

by darrion.kuhn , in category: Javascript , 3 months ago

How to set cookies with fastapi for cross-origin requests?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by elisha_langworth , 3 months ago

@darrion.kuhn 

To set cookies with FastAPI for cross-origin requests, you need to include the appropriate headers in your responses. Here is an example of how to set cookies with FastAPI for cross-origin requests:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
from fastapi import FastAPI, Response
from fastapi.middleware.cors import CORSMiddleware

app = FastAPI()

app.add_middleware(
    CORSMiddleware,
    allow_origins=["http://example.com"],  # add the origin of your cross-origin request
    allow_credentials=True,
    allow_methods=["GET", "POST"],
    allow_headers=["*"],
)

@app.get("/")
async def set_cookie(response: Response):
    response.set_cookie(key="example_cookie", value="example_value", domain="example.com", httponly=True)
    return {"message": "Cookie set"}


In this example, we use the fastapi.middleware.cors.CORSMiddleware middleware to allow cross-origin requests from http://example.com. We also set the allow_credentials parameter to True to allow sending cookies with cross-origin requests.


Inside the set_cookie handler function, we use the response.set_cookie() method to set a cookie with the key example_cookie and value example_value. We also specify the domain for which the cookie is valid and set the httponly parameter to True for added security.


By including the appropriate CORS headers and setting cookies with the response.set_cookie() method, you can handle cross-origin requests with cookies in FastAPI.

Related Threads:

How to access onfocus event from iframe (cross-origin)?
How to check multiple cookies are set in .htaccess?
How to set focus on an iframe that is cross-domain?
How to check if a cookie is set in fastapi?
How to set response class in fastapi?
How to set "/*" path to capture all routes in fastapi?