Open In App

FastAPI – Mounting Flask App

Last Updated : 06 Dec, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

A modern framework in Python that is used for building APIs is called FastAPI while a micro web framework written in Python that is used for developing web applications is called Flask. The FastAPI and Flask provide different features. Sometimes, it becomes crucial to use features of both in a single app. This can be possible by mounting the Flask app on the FastAPI app.

Syntax:

  • from fastapi.middleware.wsgi import WSGIMiddleware
  • main_app.mount(“/flask”, WSGIMiddleware(flask_app))

Here,

  • main_app: It is the main app on which you want to mount the Flask app.
  • flask_app: It is the Flask app that has to be mounted on the main app.

FastAPI – Mounting Flask App

In this example, we have created a main app called, app and a flask app called, flaskapp. Then, we mounted a Flask app on the main app using WSGIMiddleware.

main.py: This Python code demonstrates how to combine a FastAPI application with a Flask application using FastAPI’s middleware. It defines two routes:

  1. The FastAPI route at “/app” responds with “Main app called!” when accessed.
  2. The Flask route at “/app2” responds with “Flask app called!” when accessed.

Python3




from fastapi import FastAPI
from flask import Flask
from fastapi.middleware.wsgi import WSGIMiddleware
 
app = FastAPI()
flaskapp = Flask(__name__)
 
@app.get("/app")
def main_app():
    return "Main app called!"
 
@flaskapp.route("/app2")
def flask_app():
    return "Flask app called!"
 
app.mount("/flask", WSGIMiddleware(flaskapp))


For calling the value returned from main app function, we use the following code in test file

Test 1: This code sends an HTTP GET request to the URL “http://127.0.0.1:8000/app” using the requests library. It tries to parse the response as JSON using the .json() method. The output will be the response from the server at that URL in JSON format.

Python3




import requests
print(requests.get("http://127.0.0.1:8000/app").json())


Output:

Screenshot-2023-11-01-161329

Browser Output:

Screenshot-2023-11-01-125442-(1)

For calling the value returned from sub-app function, we use the following code in test file:

Test 1: This code sends an HTTP GET request to the URL “http://127.0.0.1:8000/flask/app2” using the requests library. It fetches the content from that URL and prints it as text. The output will be the text content of the response from the Flask app running at that URL.

Python3




import requests
print(requests.get("http://127.0.0.1:8000/flask/app2").text)


Output

Screenshot-2023-11-01-161205

Output

Screenshot-2023-11-01-161439



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads