DEV Community

Free Python Code
Free Python Code

Posted on

How to set cookies in a web browser in FastAPI

Hi πŸ™‚πŸ–

Welcome to a new post, Today I will share with you how to set cookies in a web browser in FastAPI and Python in an easy way.

step 1

Import modules

from fastapi import FastAPI, Response, Request, Depends
from fastapi.responses import HTMLResponse
from secrets import token_hex
Enter fullscreen mode Exit fullscreen mode

step 2

Create HTML file for test

<html>
    <head></head>
    <body>
        <h1>This is test</h1>
    </body>
</html>
Enter fullscreen mode Exit fullscreen mode

step 3

Create test route

app = FastAPI()

@app.get('/test')
async def test(response: Response):
    response = HTMLResponse(open('test.html', 'r').read())
    response.set_cookie(key="fakesession", value=token_hex(20))

    return response

Enter fullscreen mode Exit fullscreen mode

run the API

uvicorn main:app --reload
Enter fullscreen mode Exit fullscreen mode

it's working 😎
we have cookie

Image description

If you want to confirm if it really working πŸ™ƒ

you can delete the cookie and reload the page πŸ™‚

Read the cookie from another page

async def read_token(request : Request):
    token = request.cookies.get('fakesession')
    if not token:
        return False

    return token

@app.get('/protected')
async def protected(token : str = Depends(read_token)):
   return {'token': token}
Enter fullscreen mode Exit fullscreen mode

result

Image description

Now we're done πŸ€—

Don't forget to like and follow πŸ™‚

Support me on PayPal πŸ€—
https://www.paypal.com/paypalme/amr396

Top comments (0)