Event-driven architecture helps your app react to actions or changes instantly. It makes your app more flexible and easier to manage by focusing on events.
Event-driven architecture in FastAPI
from fastapi import FastAPI from fastapi import BackgroundTasks app = FastAPI() @app.post("/items/") async def create_item(item: dict, background_tasks: BackgroundTasks): background_tasks.add_task(process_item, item) return {"message": "Item received"} def process_item(item: dict): # handle the event here print(f"Processing item: {item}")
Use BackgroundTasks to run functions after the main request finishes.
Define event handlers as normal functions and add them to background tasks.
from fastapi import FastAPI, BackgroundTasks app = FastAPI() @app.post("/send-email/") async def send_email(background_tasks: BackgroundTasks): background_tasks.add_task(send_welcome_email) return {"message": "Email will be sent"} def send_welcome_email(): print("Sending welcome email...")
from fastapi import FastAPI, BackgroundTasks app = FastAPI() @app.post("/log-action/") async def log_action(action: str, background_tasks: BackgroundTasks): background_tasks.add_task(log_to_file, action) return {"message": "Action logged"} def log_to_file(action: str): with open("actions.log", "a") as f: f.write(f"Action: {action}\n")
This FastAPI app accepts data and immediately returns a response. Meanwhile, it processes the data in the background as an event.
from fastapi import FastAPI, BackgroundTasks from fastapi.responses import JSONResponse app = FastAPI() @app.post("/process-data/") async def process_data(data: dict, background_tasks: BackgroundTasks): background_tasks.add_task(handle_event, data) return JSONResponse(content={"status": "Data received"}) def handle_event(data: dict): print(f"Event received with data: {data}") # Imagine processing or notifying other services here
Background tasks run after the response is sent, so users don't wait.
Use event-driven design to keep your app responsive and scalable.
FastAPI's BackgroundTasks is a simple way to start with event-driven patterns.
Event-driven architecture lets your app react to actions as they happen.
FastAPI uses BackgroundTasks to handle events without blocking users.
This approach makes your app faster and easier to maintain.
Practice
Solution
Step 1: Understand event-driven architecture
Event-driven architecture lets the app respond to events as they happen, improving responsiveness.Step 2: Connect to FastAPI's use of BackgroundTasks
FastAPI uses BackgroundTasks to handle events without blocking the main user request, enabling immediate reactions.Final Answer:
It allows the app to react to actions immediately without waiting. -> Option AQuick Check:
Event-driven = Immediate reaction [OK]
- Thinking event-driven means single-threaded only
- Believing no code is needed for requests
- Assuming background tasks are disabled
Solution
Step 1: Recall FastAPI import syntax
FastAPI uses standard Python import syntax: from module import class/function.Step 2: Identify correct module and class
The BackgroundTasks class is imported from fastapi directly, so the correct syntax is 'from fastapi import BackgroundTasks'.Final Answer:
from fastapi import BackgroundTasks -> Option CQuick Check:
Correct import syntax = from fastapi import BackgroundTasks [OK]
- Using wrong import order or syntax
- Trying to import from a non-existent submodule
- Using dot notation incorrectly in import
from fastapi import FastAPI, BackgroundTasks
app = FastAPI()
results = []
def write_log(message: str):
results.append(message)
@app.post('/send')
async def send_message(background_tasks: BackgroundTasks):
background_tasks.add_task(write_log, 'Message sent')
return {'status': 'ok'}
# After calling POST /send once, what is the value of results?Solution
Step 1: Understand BackgroundTasks behavior
BackgroundTasks run after the response is sent, but in testing or immediate inspection, the task may not have run yet.Step 2: Check when results list updates
The results list is updated inside the background task, which runs asynchronously after returning the response, so immediately after the call, results is still empty.Final Answer:
[] (empty list) -> Option BQuick Check:
Background task runs after response = empty results [OK]
- Assuming background task runs before return
- Expecting results updated synchronously
- Confusing background_tasks parameter usage
from fastapi import FastAPI, BackgroundTasks
app = FastAPI()
@app.post('/notify')
async def notify():
background_tasks.add_task(print, 'Notify event')
return {'message': 'Notification sent'}Solution
Step 1: Check function parameters for BackgroundTasks
The function uses background_tasks but does not declare it as a parameter, so it is undefined inside the function.Step 2: Confirm correct usage of BackgroundTasks
BackgroundTasks must be accepted as a parameter in the endpoint function to be used, e.g., 'async def notify(background_tasks: BackgroundTasks)'.Final Answer:
background_tasks parameter missing in function definition -> Option DQuick Check:
Missing parameter = background_tasks parameter missing in function definition [OK]
- Forgetting to add background_tasks parameter
- Thinking print can't be used in background tasks
- Adding await to add_task (it's not a coroutine)
Solution
Step 1: Understand the goal of non-blocking email sending
We want the user to get a quick response while the email sends in the background.Step 2: Match FastAPI's event-driven feature
BackgroundTasks lets you schedule tasks to run after the response, perfect for sending emails without delay.Final Answer:
Use BackgroundTasks to send the email after returning the response -> Option AQuick Check:
BackgroundTasks = non-blocking post-response tasks [OK]
- Sending email synchronously causing delay
- Using global variables for task management
- Manually managing threads without FastAPI support
Ready to prove it?
Pass the test and this pattern moves unknown
