FastAPI
Async and Await
Define async handlers and run blocking work in a thread.
By EZ4Code Team
asyncconcurrency
Code
import asyncio
from fastapi import FastAPI
import httpx
app = FastAPI()
@app.get("/async")
async def fetch():
async with httpx.AsyncClient() as client:
r = await client.get("https://api.github.com")
return {"status": r.status_code}
@app.get("/parallel")
async def parallel():
async with httpx.AsyncClient() as client:
a, b = await asyncio.gather(
client.get("https://api.github.com"),
client.get("https://httpbin.org/get"),
)
return {"a": a.status_code, "b": b.status_code}
@app.get("/sync")
def sync_handler():
return {"ok": True}Explanation
Async handlers run on the event loop and should await other async work such as httpx requests. asyncio.gather runs multiple coroutines concurrently to cut total latency. Plain def handlers run in a threadpool so they don't block the loop during CPU-bound or sync I/O.
More FastAPI Snippets
Path Parameters
Capture typed path segments with validation.
Query Parameters
Parse query strings with defaults and validation.
Pydantic Request Body
Validate JSON bodies with Pydantic models.
Dependency Injection
Share logic via Depends and yield-based dependencies.
Response Model
Shape and filter responses with response_model.
JWT Auth
Issue and verify JSON Web Tokens with OAuth2.