Open In App

Optimizing FastAPI with Multiple Workers for Background Tasks

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

A modern web-framework in Python which is used for building APIs is called FastAPI. There are some circumstances when the user wants a specific action to be performed in the background after the raise of a request. This is possible by utilizing multiple workers in a background task while using FastAPI. In this article, we will discuss the same.

FastAPI with Multiple Workers for Background Tasks

Syntax: background_tasks.add_task(function_background)

Here,

  • function_background: It is the function to be called for a background task to be performed.

In this example, we have created two functions call_main_task and call_background_task. The call_main_task will be called when the user requests for /app, while the call_background_task will be called automatically on the call of the call_main_task.

main.py: In this file, have imported BackgroundTasks and called FastAPI task using Pydantic.

Python3




# Import the FastAPI and BackgroundTasks libraries
from fastapi import FastAPI, BackgroundTasks
 
# Create a main FastAPI application
app = FastAPI()
 
# Call main FastAPI task using Pydantic
@app.get("/app")
async def call_main_task(background_tasks: BackgroundTasks):
    background_tasks.add_task(call_background_task)
    return "Main task called!"
 
# Call background FastAPI task using Pydantic
def call_background_task():
    print(f"Background Task called!")


Output

For starting the FastAPI app, use the following code in terminal. This is the place where you will see the background task being performed.

uvicorn main:app --reload

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

test.py: 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 the requests library
import requests
 
# Call FastAPI main task using requests library
print(requests.get("http://127.0.0.1:8000/app").json())


Pycharm Output

ezgifcom-resize

Browser Output



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads