Performance: Async HTTP client calls
This affects how quickly the server can handle multiple HTTP requests without blocking, improving response time and throughput.
import httpx import asyncio from fastapi import FastAPI app = FastAPI() @app.get('/data') async def get_data(): async with httpx.AsyncClient() as client: response1, response2 = await asyncio.gather( client.get('https://api.example.com/one'), client.get('https://api.example.com/two') ) return {'one': response1.json(), 'two': response2.json()}
import requests from fastapi import FastAPI app = FastAPI() @app.get('/data') def get_data(): response1 = requests.get('https://api.example.com/one') response2 = requests.get('https://api.example.com/two') return {'one': response1.json(), 'two': response2.json()}
| Pattern | DOM Operations | Reflows | Paint Cost | Verdict |
|---|---|---|---|---|
| Synchronous HTTP calls (requests) | N/A (server-side) | Blocks event loop | Delays response rendering | [X] Bad |
| Async HTTP calls with httpx.AsyncClient | N/A (server-side) | Non-blocking event loop | Faster response rendering | [OK] Good |
async HTTP client calls in a FastAPI application?httpx in FastAPI?async with ensures proper resource management for async clients.await to wait for the async HTTP callclient.get() must be awaited to get the response asynchronously.import httpx
from fastapi import FastAPI
app = FastAPI()
@app.get('/data')
async def get_data():
async with httpx.AsyncClient() as client:
response = await client.get('https://httpbin.org/get')
return {'status_code': response.status_code}await with client.get(), so it correctly waits for the response.import httpx
from fastapi import FastAPI
app = FastAPI()
@app.get('/info')
async def get_info():
client = httpx.AsyncClient()
response = client.get('https://httpbin.org/get')
return {'status': response.status_code}client.get() is an async method and must be awaited to get the response.await, the code returns a coroutine object, causing errors when accessing status_code.httpx.AsyncClient?asyncio.gather() to await them together.asyncio.gather() inside async with context, correctly awaiting both calls concurrently.Pass the test and this pattern moves unknown