FastAPI - Mounting Flask App



A WSGI application written in Flask or Django framework can be wrapped in WSGIMiddleware and mounted it on a FastAPI app to make it ASGI compliant.

First install the Flask package in the current FastAPI environment.

pip3 install flask

The following code is a minimal Flask application −

from flask import Flask
flask_app = Flask(__name__)
@flask_app.route("/")
def index_flask():
   return "Hello World from Flask!"

Then declare app as a FastAPI application object and define an operation function for rendering Hello World message.

from fastapi import FastAPI
app = FastAPI()
@app.get("/")
def index():
   return {"message": "Hello World from FastAPI!"}

Next, mount the flask application as a sub application of FastAPI main app using mount() method.

from fastapi.middleware.wsgi import WSGIMiddleware
app.mount("/flask", WSGIMiddleware(flask_app))

Run the Uvicorn development server.

uvicorn flaskapp:app –reload

The main FastAPI application is available at the URL http://localhost:8000/ route.

{"message":"Hello World from FastAPI!"}

The Flask sub application is mounted at the URL http://localhost:8000/flask.

Hello World from Flask!
Advertisements