async def
noun
say it: “AY-sink DEF” /ˈeɪsɪŋk ˈdɛf/
A FastAPI route written as async def, which can await slow work such as outside requests while the server answers other requests.
What does async def do?
Declare endpoints with async def when they await things like database or HTTP calls, so the server can handle other requests while waiting. Plain def works too.
@app.get('/weather/{city}')
async def weather(city: str):
async with httpx.AsyncClient() as client:
response = await client.get(f'https://api.weather.example.com/{city}')
return response.json()
In a sentence
- “The movie route is an async def, so it awaits httpx while other requests are served.”
- “A route with no awaits works fine as a plain def instead of async def.”
Level: Apprentice · More FastAPI terms at this level
Updated