Skip to content
Sarj Code Standards

no-per-call-http-client

Inject an HTTPX client instead of opening and closing one inside a single call.

Why

A client opened and closed inside one call builds a new connection pool, TLS handshake and transport configuration on every call, and hides the client from the composition root that should own its settings and lifetime.

Fix

Open the client once at the composition root (application lifespan, worker main or a context-manager factory) and inject it through the constructor or a parameter.

Examples

Before — flagged Do not open a client for one request
app/refresher.py
import httpx
class Refresher:
async def refresh(self, url):
async with httpx.AsyncClient() as client:
response = await client.post(url)
return response.json()
After — preferred Inject a client owned by the composition root
app/refresher.py
import httpx
class Refresher:
def __init__(self, client: httpx.AsyncClient):
self.client = client
async def refresh(self, url):
response = await self.client.post(url)
return response.json()