Search code examples
pythonfastapi

Session object in FastAPI similar to Flask


I am trying to use session to pass variables across view functions in fastapi. However, I do not find any doc which specifically says of about session object. Everywhere I see, cookies are used. Is there any way to convert the below flask code in fastapi? I want to keep session implementation as simple as possible.

from flask import Flask, session, render_template, request, redirect, url_for


app=Flask(__name__)
app.secret_key='asdsdfsdfs13sdf_df%&'   

@app.route('/a')
def a():
    session['my_var'] = '1234'              
    return redirect(url_for('b'))          


@app.route('/b')
def b():
    my_var = session.get('my_var', None)
    return my_var    


if __name__=='__main__':
    app.run(host='0.0.0.0', port=5000, debug = True)

Solution

  • Take a look at Starlette's SessionMiddleware. FastAPI uses Starlette under the hood so it is compatible.

    After you register SessionMiddleware, you can access Request.session, which is a dictionary.

    Documentation: SessionMiddleware

    An implementation in FastAPI may look like:

    @app.route("/a")
    async def a(request: Request) -> RedirectResponse:
    
        request.session["my_var"] = "1234"
    
        return RedirectResponse("/b")
    
    @app.route("/b")
    async def b(request: Request) -> PlainTextResponse:
    
        my_var = request.session.get("my_var", None)
    
        return PlainTextResponse(my_var)