Skip to content
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