typestar

Async endpoints in Python

An async def handler runs on the event loop, so awaits do not block it.

import asyncio

from fastapi import FastAPI
from fastapi.testclient import TestClient

app = FastAPI()


async def fetch(name: str) -> dict:
    await asyncio.sleep(0.01)
    return {"name": name, "steps": len(name) * 10}


@app.get("/summary")
async def summary():
    tours = await asyncio.gather(fetch("basics"), fetch("pythonic"))
    return {"tours": tours, "total": sum(t["steps"] for t in tours)}


client = TestClient(app)
print(client.get("/summary").json())

How it works

  1. Use async when the work awaits; plain def runs in a threadpool.
  2. asyncio.gather fans out inside one request.
  3. The TestClient drives async handlers the same way.

Keywords and builtins used here

The run, in numbers

Lines
21
Characters to type
451
Tokens
137
Three-star pace
110 tpm

At the three-star pace of 110 tokens a minute, this run takes about 75 seconds.

Type this snippet

Step 2 of 3 in Dependencies & async, step 11 of 19 in Web services & data access.

← Previous Next →