Skip to content
FastAPI

Async and Await

Define async handlers and run blocking work in a thread.

#async#concurrency

Code

fastapi
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}