Get startedGet started for free

Implementing background tasks

Your sentiment analysis API is getting requests to process batch of hundreds of reviews at once. To handle this efficiently without making users wait, you'll implement background task processing so that requests are being processed after sending a response to the client.

This exercise is part of the course

Deploying AI into Production with FastAPI

View Course

Exercise instructions

  • Import the background task class from fastapi.
  • Declare the background_tasks parameter to handle the request as a task running in background.
  • Schedule the processing task of analyzing reviews' texts using the process_reviews function.

Hands-on interactive exercise

Have a go at this exercise by completing this sample code.

# Import the background task class
from fastapi import ____
# Create a background task dependency
@app.post("/analyze_batch")
async def analyze_batch(
    reviews: Reviews,
    background_tasks: ____
):
    async def process_reviews(texts: List[str]):
        for text in texts:
            result = await asyncio.to_thread(sentiment_model, text)
            print(f"Processed: {result[0]['label']}")
    # Add the task of analysing reviews' texts to the background
    background_tasks.____(process_reviews, ____)
    return {"message": "Processing started"}
Edit and Run Code