Open In App

FastAPI – Mounting A Sub-App

Last Updated : 27 Nov, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

A Python web framework that is used for building APIs is called FastAPI. The creation of two or more APIs and using them in a project consumes more memory. The more efficient way is to mount the APIs on each other, which will consume less memory and give a different path to each API.

Syntax of FastAPI mounted sub-applications

Syntax:

main_app.mount(“/subapp”, sub_app)

Here,

  • main_app: It is the main app n which you want to mount other app.
  • sub_app: It is the app which has to be mounted on the main app.

FastAPI – Mounting A Sub-App

In this example, we have created a main app called, app and a sub-app called, subapp. Then, we mounted a sub-app on the main app.

main.py

A FastAPI application (app) defines a route at “/app” that responds with “Main app called!” when a GET request is made. Another FastAPI sub-application (subapp) defines a route at “/app2” that responds with “Sub-app called!” The sub-application is mounted as a sub-route under “/subapp” in the main application, allowing you to structure routes using sub-applications.

Python3




from fastapi import FastAPI
app = FastAPI()
 
 
@app.get("/app")
def main_app():
    return "Main app called!"
 
 
subapp = FastAPI()
 
 
@subapp.get("/app2")
def sub_app():
    return "Sub-app called!"
 
 
app.mount("/subapp", subapp)


Output:

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

Test Without Mounting

The code sends a GET request to “http://127.0.0.1:8000/app” and expects a JSON response from the FastAPI route defined at “/app”. It then prints the JSON response to the console.

Python3




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


Pycharm Output:

Screenshot-2023-11-01-125201

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 With Mounting

The code sends a GET request to “http://127.0.0.1:8000/subapp/app2” and expects a JSON response from the FastAPI route defined at “/subapp/app2”. It then prints the JSON response to the console.

Python3




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


Pycharm Output:Screenshot-2023-11-01-124950

Browser Output:

Screenshot-2023-11-01-125817



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads