📖 Scenario: You are building a simple web API that accepts user requests to send welcome emails. Sending emails can take time, so you want to handle this task in the background without making the user wait.
🎯 Goal: Create a FastAPI app that accepts a POST request with a user's email. The app should start a background task to simulate sending a welcome email, then immediately respond to the user.
📋 What You'll Learn
Create a FastAPI app instance named app
Define a POST endpoint at /send-email/ that accepts a JSON body with an email field
Use FastAPI's BackgroundTasks to run a function called send_welcome_email in the background
The send_welcome_email function should accept an email parameter and simulate sending an email by printing a message
The endpoint should return a JSON response immediately confirming the email is being sent
💡 Why This Matters
🌍 Real World
Background tasks are useful in web apps to handle slow operations like sending emails, processing files, or calling external APIs without making users wait.
💼 Career
Understanding background tasks is important for backend developers to build responsive and scalable APIs.
Progress0 / 4 steps
1
Create FastAPI app and email data model
Import FastAPI and BaseModel from fastapi and pydantic respectively. Create a FastAPI app instance called app. Define a Pydantic model called EmailRequest with one field email of type str.
FastAPI
Hint
Use app = FastAPI() to create the app. Define EmailRequest as a class inheriting from BaseModel with an email string field.
2
Add background task function
Define a function called send_welcome_email that takes one parameter email. Inside the function, add a print statement that says Sending welcome email to {email} using an f-string.
FastAPI
Hint
Define a simple function that prints the welcome email message using the email parameter.
3
Create POST endpoint with background task
Import BackgroundTasks from fastapi. Create a POST endpoint at /send-email/ using @app.post. The endpoint function should be called send_email and accept two parameters: request of type EmailRequest and background_tasks of type BackgroundTasks. Inside the function, add the background task send_welcome_email with the email from request.email. Return a dictionary with the key message and value "Email is being sent to {request.email}".
FastAPI
Hint
Use background_tasks.add_task() to schedule the email sending function. Return a confirmation message immediately.
4
Add type hints and finalize code
Ensure the send_welcome_email function has a return type hint of None. Also, add a type hint request: EmailRequest and background_tasks: BackgroundTasks in the send_email function signature. Confirm the full code includes all imports, the app instance, the data model, the background task function, and the POST endpoint.
FastAPI
Hint
Add -> None to the background task function and -> dict to the endpoint function for clarity.
Practice
(1/5)
1. What is the main purpose of using BackgroundTasks in FastAPI?
easy
A. To handle database connections synchronously
B. To replace the main event loop in FastAPI
C. To block the request until a task finishes
D. To run code after sending the response without delaying the user
Solution
Step 1: Understand what BackgroundTasks do
BackgroundTasks allow running code after the response is sent, so the user is not delayed.
Step 2: Compare options with this behavior
Only To run code after sending the response without delaying the user describes running code after response without delay; others describe blocking or unrelated tasks.
Final Answer:
To run code after sending the response without delaying the user -> Option D
Quick Check:
BackgroundTasks run code after response = B [OK]
Hint: BackgroundTasks run after response to avoid user wait [OK]
Common Mistakes:
Thinking BackgroundTasks block the response
Confusing BackgroundTasks with synchronous code
Assuming BackgroundTasks replace main event loop
2. Which of the following is the correct way to add a background task in a FastAPI endpoint?
easy
A. Import BackgroundTasks but do not use it
B. Call your_function() directly inside the endpoint
C. Use background_tasks.add_task(your_function, arg1, arg2) inside the endpoint
D. Use await your_function() inside the endpoint
Solution
Step 1: Recall how to add background tasks in FastAPI
You add tasks by calling background_tasks.add_task(function, args) inside the endpoint function.
Step 2: Check each option
Use background_tasks.add_task(your_function, arg1, arg2) inside the endpoint correctly uses add_task. Call your_function() directly inside the endpoint calls function immediately, blocking. Use await your_function() inside the endpoint awaits function, blocking. Import BackgroundTasks but do not use it does nothing.
Final Answer:
Use background_tasks.add_task(your_function, arg1, arg2) inside the endpoint -> Option C
Quick Check:
Use add_task to schedule background work = D [OK]
Hint: Use add_task method on BackgroundTasks instance [OK]
Common Mistakes:
Calling the function directly instead of scheduling
Awaiting the function which blocks response
Importing BackgroundTasks but not using it
3. Given this FastAPI code snippet, what will be printed after the response is sent?
A. Missing argument when adding task to background_tasks
B. BackgroundTasks should not be a parameter
C. send_email should be async
D. Email parameter must be inside the function send_email
Solution
Step 1: Check how add_task is called
The function send_email requires an argument email, but add_task is called without arguments.
Step 2: Identify the missing argument
The call should be background_tasks.add_task(send_email, email) to pass the email parameter.
Final Answer:
Missing argument when adding task to background_tasks -> Option A
Quick Check:
add_task needs function arguments = A [OK]
Hint: Pass all function args in add_task call [OK]
Common Mistakes:
Forgetting to pass required arguments to add_task
Thinking BackgroundTasks can't be a parameter
Assuming send_email must be async
5. You want to log user activity and send a welcome email after a user registers. Which is the best way to do this using FastAPI background tasks?
hard
A. Call logging and email functions directly inside the endpoint synchronously
B. Add two background tasks: one for logging, one for sending email, both added via background_tasks.add_task
C. Use await on both logging and email functions inside the endpoint
D. Run logging in background task but send email synchronously
Solution
Step 1: Understand the goal
We want to run both logging and sending email after response without delaying user.
Step 2: Evaluate options
Add two background tasks: one for logging, one for sending email, both added via background_tasks.add_task schedules both tasks as background tasks, so they run after response. Options B and C block response. Run logging in background task but send email synchronously delays sending email.
Final Answer:
Add two background tasks: one for logging, one for sending email, both added via background_tasks.add_task -> Option B
Quick Check:
Schedule all post-response tasks with add_task = A [OK]
Hint: Add all post-response jobs as background tasks [OK]
Common Mistakes:
Running tasks synchronously blocking response
Mixing sync and async incorrectly
Scheduling only one task in background
Recommended
Ready to prove it?
Pass the test and this pattern moves unknownstrongwhile earning +1 Grip toward your certificate.