pythoncookiesjinja2fastapihttpresponse

How to set cookies on Jinja2 TemplateResponse in FastAPI?


I am using Python FastAPI and Jinja2, all of which I am new to. I am able to set cookies alone or return html templates on their own, but I cannot work out how to do both at once.

Setting cookies only works as expected, but returning a template seems to overwrite that and just returns html with no cookies.

@app.get("/oauth/auth", response_class=HTMLResponse)
async def login_page(request: Request, response: Response):
    client_Code_Req_Schema = ClientCodeReqSchema(client_id=request.query_params.get("client_id"), redirect_uri=request.query_params.get("redirect_uri"), response_type=request.query_params.get("response_type"))
    if check_client(client_Code_Req_Schema):      
        response.set_cookie(key="redirect_uri", value="test")
        return templates.TemplateResponse("authorize.html", {"request": request})
    else:
        raise HTTPException(status_code=400, detail="Invalid request")

Many thanks for any advice. Happy to provide more info if I missed something.


Solution

  • You should set the cookie on the TemplateResponse instead—which is returned from that endpoint—not on the Response object defined in the endpoint's parameters, which could be used when returing JSON data, e.g., return {'msg': 'OK'}.

    Related answers that you might find helpful can be found here, here and here.

    Example

    @app.get("/oauth/auth", response_class=HTMLResponse)
    async def login_page(request: Request):
        if ...     
            response = templates.TemplateResponse("authorize.html", {"request": request})
            response.set_cookie(key="redirect_uri", value="test")
            return response
        else:
            raise HTTPException(status_code=400, detail="Invalid request")