Including WSGI - Flask, Django, others¶
You can mount WSGI applications as you saw withSub Applications - Mounts,Behind a Proxy.
For that, you can use theWSGIMiddleware and use it to wrap your WSGI application, for example, Flask, Django, etc.
UsingWSGIMiddleware¶
Info
This requires installinga2wsgi for example withpip install a2wsgi.
You need to importWSGIMiddleware froma2wsgi.
Then wrap the WSGI (e.g. Flask) app with the middleware.
And then mount that under a path.
froma2wsgiimportWSGIMiddlewarefromfastapiimportFastAPIfromflaskimportFlask,requestfrommarkupsafeimportescapeflask_app=Flask(__name__)@flask_app.route("/")defflask_main():name=request.args.get("name","World")returnf"Hello,{escape(name)} from Flask!"app=FastAPI()@app.get("/v2")defread_main():return{"message":"Hello World"}app.mount("/v1",WSGIMiddleware(flask_app))Note
Previously, it was recommended to useWSGIMiddleware fromfastapi.middleware.wsgi, but it is now deprecated.
It’s advised to use thea2wsgi package instead. The usage remains the same.
Just ensure that you have thea2wsgi package installed and importWSGIMiddleware correctly froma2wsgi.
Check it¶
Now, every request under the path/v1/ will be handled by the Flask application.
And the rest will be handled byFastAPI.
If you run it and go tohttp://localhost:8000/v1/ you will see the response from Flask:
Hello, World from Flask!And if you go tohttp://localhost:8000/v2 you will see the response from FastAPI:
{"message":"Hello World"}






