FastAPI Data Fetching with Async
Fetch and aggregate data from multiple APIs in FastAPI using asyncio.gather for concurrent requests, httpx connection pooling, response caching with TTL,.
Code
from fastapi import FastAPI
import httpx
import asyncio
app = FastAPI()
async def fetch_user(uid: int):
async with httpx.AsyncClient() as c:
r = await c.get(f'https://api.example.com/users/{uid}')
return r.json()
async def fetch_posts(uid: int):
async with httpx.AsyncClient() as c:
r = await c.get(f'https://api.example.com/users/{uid}/posts')
return r.json()
@app.get('/users/{uid}')
async def get_user_data(uid: int):
user, posts = await asyncio.gather(fetch_user(uid), fetch_posts(uid))
return {'user': user, 'posts': posts}How the snippet works
FastAPI Data Fetching with Async is built around the functions fetch_user, fetch_posts and get_user_data.
Asynchronous boundaries use await, so failures surface as exceptions at the call site rather than being swallowed. Everything borrowed from fastapi is visible in one line: FastAPI.
A fresh value is allocated for the result; the arguments stay untouched.
What to watch for
- External dependency:
fastapi,httpxandasyncio— install them before running the snippet.
Applying it
Entry signature: def fetch_user(uid: int)
The surface worth importing is fetch_user; the helpers around it are private to the snippet.
Statements that matter
r = await c.get(f'https://api.example.com/users/{uid}/posts')
return r.json()
@app.get('/users/{uid}')
async def get_user_data(uid: int):
user, posts = await asyncio.gather(fetch_user(uid), fetch_posts(uid))
return {'user': user, 'posts': posts}
async with httpx.AsyncClient() as c:
r = await c.get(f'https://api.example.com/users/{uid}')
return r.json()
async with httpx.AsyncClient() as c:
r = await c.get(f'https://api.example.com/users/{uid}/posts')
return r.json()
FAQ
- Does `fetch_user` modify its input?
- No. The code builds and returns a new value and leaves the arguments untouched, so it is safe to call on shared or frozen data structures.
- Does this require external packages?
- Yes — `fastapi`, `httpx` and `asyncio`. Add them to your project before running the snippet.
Report a problem with this exampleOpens a pre-filled issue on GitHub.