Complete the code to import the module needed for running tasks concurrently in FastAPI.
from fastapi import FastAPI import [1] app = FastAPI()
The asyncio module is used in FastAPI to run tasks concurrently using async features.
Complete the code to define an async endpoint that runs two tasks concurrently using asyncio.
import asyncio from fastapi import FastAPI app = FastAPI() async def task1(): await asyncio.sleep(1) return "Task 1 done" async def task2(): await asyncio.sleep(1) return "Task 2 done" @app.get("/run-tasks") async def run_tasks(): results = await asyncio.[1](task1(), task2()) return {"results": results}
asyncio.sleep which just pauses execution.asyncio.wait which returns futures, not results directly.asyncio.gather runs multiple async tasks concurrently and waits for all to finish.
Fix the error in the code to correctly run two async tasks concurrently and return their results.
import asyncio from fastapi import FastAPI app = FastAPI() async def task1(): await asyncio.sleep(1) return "Done 1" async def task2(): await asyncio.sleep(1) return "Done 2" @app.get("/tasks") async def tasks(): results = await asyncio.[1](task1(), task2()) return {"results": results}
await before asyncio.gather.asyncio.run inside an async function.To get the results of concurrent tasks, you must await asyncio.gather. The code was missing await, so adding await asyncio.gather(...) fixes it.
Fill both blanks to create a background task in FastAPI that runs concurrently without blocking the response.
from fastapi import FastAPI, BackgroundTasks app = FastAPI() def write_log(message: str): with open("log.txt", "a") as f: f.write(message + "\n") @app.post("/send-message") async def send_message(message: str, background_tasks: [1]): background_tasks.[2](write_log, message) return {"message": "Message received"}
background_tasks lowercase.run_task.The parameter must be typed as BackgroundTasks. To add a background task, use background_tasks.add_task().
Fill all three blanks to create a FastAPI endpoint that runs multiple async tasks concurrently and returns their results as a dictionary.
import asyncio from fastapi import FastAPI app = FastAPI() async def fetch_data1(): await asyncio.sleep(1) return "Data 1" async def fetch_data2(): await asyncio.sleep(1) return "Data 2" @app.get("/fetch-all") async def fetch_all(): results = await asyncio.[1](fetch_data1(), fetch_data2()) return {"first": results[[2]], "second": results[[3]]}
asyncio.wait which returns futures, not results directly.asyncio.gather runs tasks concurrently and returns results in order. Index 0 is the first task's result, index 1 is the second.