anthropic.APIConnectionError
The Anthropic Python SDK raises APIConnectionError when your request never reaches api.anthropic.com. This is a network-layer failure — DNS, TCP, SSL, or proxy — not an API error. Safe to retry unconditionally.
What it looks like in Python
import anthropic
client = anthropic.Anthropic()
try:
message = client.messages.create(
model="claude-opus-4-5",
max_tokens=1024,
messages=[{"role": "user", "content": "Hello"}]
)
except anthropic.APIConnectionError as e:
print(f"Connection failed: {e}")
# e.__cause__ often has the underlying httpx/ssl error
print(f"Caused by: {e.__cause__}")
Common underlying causes in the traceback:
httpx.ConnectTimeout: timed out connecting to api.anthropic.com:443
httpx.ConnectError: [Errno -2] Name or service not known
ssl.SSLError: CERTIFICATE_VERIFY_FAILED
httpcore.ConnectError: [Errno 111] Connection refused
Fix 1 — Increase timeout (most common fix)
Default timeout is 10 minutes but the connection timeout is 5 seconds. Increase it:
import anthropic
import httpx
# Set a generous timeout for all phases
client = anthropic.Anthropic(
timeout=httpx.Timeout(
connect=10.0, # wait up to 10s to establish TCP
read=600.0, # wait up to 10min for response body
write=10.0,
pool=10.0,
)
)
message = client.messages.create(
model="claude-opus-4-5",
max_tokens=8192,
messages=[{"role": "user", "content": "Long task..."}]
)
Fix 2 — Add retry logic
The SDK retries connection errors automatically. Increase retries for production:
client = anthropic.Anthropic(
max_retries=4, # default is 2
timeout=60.0,
)
# Or catch and retry manually with backoff:
import time
def call_with_retry(client, **kwargs):
for attempt in range(5):
try:
return client.messages.create(**kwargs)
except anthropic.APIConnectionError:
if attempt == 4:
raise
wait = 2 ** attempt # 1, 2, 4, 8 seconds
print(f"Connection failed, retrying in {wait}s...")
time.sleep(wait)
Fix 3 — Corporate proxy / firewall
If you're in a corporate network that requires a proxy:
# Set environment variable before running:
export HTTPS_PROXY=http://your-proxy:8080
export HTTP_PROXY=http://your-proxy:8080
# Or pass directly to the SDK via httpx:
import httpx
import anthropic
proxy_transport = httpx.HTTPTransport(proxy="http://your-proxy:8080")
http_client = httpx.Client(transport=proxy_transport)
client = anthropic.Anthropic(http_client=http_client)
Fix 4 — SSL certificate issues
SSL errors often appear in CI, Docker, or behind SSL-inspection proxies:
# Option A: specify custom CA bundle
import anthropic, httpx, ssl
ctx = ssl.create_default_context(cafile="/path/to/company-ca.pem")
http_client = httpx.Client(verify=ctx)
client = anthropic.Anthropic(http_client=http_client)
# Option B: use certifi (usually pre-installed)
import certifi
http_client = httpx.Client(verify=certifi.where())
client = anthropic.Anthropic(http_client=http_client)
# Option C: disable verification (DEBUG ONLY — never in production)
http_client = httpx.Client(verify=False)
client = anthropic.Anthropic(http_client=http_client)
Fix 5 — TypeScript / Node.js equivalent
import Anthropic from "@anthropic-ai/sdk";
const client = new Anthropic({
timeout: 60 * 1000, // 60 seconds in ms
maxRetries: 4,
// httpAgent: new HttpsProxyAgent("http://proxy:8080"), // if behind proxy
});
try {
const message = await client.messages.create({ ... });
} catch (err) {
if (err instanceof Anthropic.APIConnectionError) {
console.error("Network error — check connectivity:", err.message);
}
}
Diagnosing with curl
Test basic connectivity to the Anthropic API before debugging your code:
# Test DNS + TLS + auth in one command
curl -v --max-time 10 \
-H "x-api-key: $ANTHROPIC_API_KEY" \
-H "anthropic-version: 2023-06-01" \
https://api.anthropic.com/v1/models
# Expected: HTTP/2 200 with model list
# DNS failure: curl: (6) Could not resolve host
# TLS failure: curl: (35) OpenSSL SSL_connect error
Exception hierarchy
anthropic.APIError # base class for all SDK errors
├── anthropic.APIConnectionError # THIS PAGE — network layer
│ └── anthropic.APITimeoutError # connect/read timeout subclass
└── anthropic.APIStatusError # HTTP 4xx/5xx responses
├── anthropic.AuthenticationError # 401
├── anthropic.PermissionDeniedError # 403
├── anthropic.NotFoundError # 404
├── anthropic.UnprocessableEntityError # 422
├── anthropic.RateLimitError # 429
└── anthropic.InternalServerError # 500+