0
# Configuration API
1
2
Timeout, connection limits, proxy, and SSL configuration options for customizing httpx client behavior.
3
4
## Overview
5
6
httpx provides comprehensive configuration options for timeouts, connection pooling, proxy settings, and SSL/TLS handling. These can be set as defaults for clients or overridden per request.
7
8
## Capabilities
9
10
### Timeout Configuration
11
12
```python { .api }
13
class Timeout:
14
"""
15
Timeout configuration for HTTP requests.
16
17
Supports granular timeout control for different phases of the request.
18
"""
19
20
def __init__(self, timeout=5.0, *, connect=None, read=None, write=None, pool=None):
21
"""
22
Initialize timeout configuration.
23
24
Args:
25
timeout (float | None): Default timeout for all operations (default: 5.0)
26
connect (float | None): Connection timeout (default: uses timeout)
27
read (float | None): Read timeout (default: uses timeout)
28
write (float | None): Write timeout (default: uses timeout)
29
pool (float | None): Pool acquisition timeout (default: uses timeout)
30
31
Special values:
32
- None: No timeout (wait indefinitely)
33
- 0.0: No timeout (same as None)
34
- Positive float: Timeout in seconds
35
"""
36
37
def as_dict(self):
38
"""
39
Convert timeout to dictionary format.
40
41
Returns:
42
dict[str, float | None]: Timeout configuration as dict
43
"""
44
```
45
46
### Connection Limits
47
48
```python { .api }
49
class Limits:
50
"""
51
Connection pool limits configuration.
52
53
Controls the number of concurrent connections and keep-alive behavior.
54
"""
55
56
def __init__(self, *, max_connections=100, max_keepalive_connections=20, keepalive_expiry=5.0):
57
"""
58
Initialize connection limits.
59
60
Args:
61
max_connections (int | None): Maximum concurrent connections (default: 100)
62
max_keepalive_connections (int | None): Maximum keep-alive connections (default: 20)
63
keepalive_expiry (float | None): Keep-alive connection timeout in seconds (default: 5.0)
64
65
Notes:
66
- max_connections includes both active and keep-alive connections
67
- Keep-alive connections are reused for better performance
68
- None means no limit (use with caution)
69
"""
70
```
71
72
### Proxy Configuration
73
74
```python { .api }
75
class Proxy:
76
"""
77
Proxy configuration for HTTP requests.
78
79
Supports HTTP, HTTPS, and SOCKS5 proxies with authentication.
80
"""
81
82
def __init__(self, url, *, auth=None, headers=None):
83
"""
84
Initialize proxy configuration.
85
86
Args:
87
url (str | URL): Proxy URL (e.g., 'http://proxy.example.com:8080')
88
auth (tuple[str, str], optional): Proxy authentication (username, password)
89
headers (dict, optional): Additional headers to send to proxy
90
91
Supported schemes:
92
- http://: HTTP proxy
93
- https://: HTTPS proxy (proxy connection is encrypted)
94
- socks5://: SOCKS5 proxy
95
- socks5h://: SOCKS5 proxy with hostname resolution through proxy
96
"""
97
98
@property
99
def url(self):
100
"""Proxy URL."""
101
return self._url
102
103
@property
104
def auth(self):
105
"""Proxy authentication credentials."""
106
return self._auth
107
108
@property
109
def headers(self):
110
"""Proxy headers."""
111
return self._headers
112
```
113
114
## Usage Examples
115
116
### Basic Timeout Configuration
117
118
```python
119
import httpx
120
121
# Simple timeout (applies to all operations)
122
response = httpx.get('https://example.com', timeout=10.0)
123
124
# No timeout
125
response = httpx.get('https://example.com', timeout=None)
126
127
# Client with default timeout
128
with httpx.Client(timeout=30.0) as client:
129
response = client.get('https://example.com')
130
```
131
132
### Granular Timeout Control
133
134
```python
135
import httpx
136
137
# Different timeouts for different phases
138
timeout = httpx.Timeout(
139
timeout=30.0, # Default for all operations
140
connect=5.0, # Connection timeout
141
read=10.0, # Read timeout
142
write=5.0, # Write timeout
143
pool=2.0 # Pool acquisition timeout
144
)
145
146
with httpx.Client(timeout=timeout) as client:
147
response = client.get('https://example.com')
148
```
149
150
### Connection Limits
151
152
```python
153
import httpx
154
155
# Custom connection limits
156
limits = httpx.Limits(
157
max_connections=50, # Total connections
158
max_keepalive_connections=10, # Keep-alive connections
159
keepalive_expiry=30.0 # Keep-alive timeout
160
)
161
162
with httpx.Client(limits=limits) as client:
163
# Client will maintain at most 50 concurrent connections
164
# with up to 10 keep-alive connections reused for 30 seconds
165
response = client.get('https://example.com')
166
```
167
168
### HTTP Proxy
169
170
```python
171
import httpx
172
173
# Simple HTTP proxy
174
with httpx.Client(proxy='http://proxy.example.com:8080') as client:
175
response = client.get('https://example.com')
176
177
# Proxy with authentication
178
proxy = httpx.Proxy(
179
'http://proxy.example.com:8080',
180
auth=('username', 'password')
181
)
182
183
with httpx.Client(proxy=proxy) as client:
184
response = client.get('https://example.com')
185
```
186
187
### SOCKS Proxy
188
189
```python
190
import httpx
191
192
# SOCKS5 proxy
193
with httpx.Client(proxy='socks5://proxy.example.com:1080') as client:
194
response = client.get('https://example.com')
195
196
# SOCKS5 with hostname resolution through proxy
197
with httpx.Client(proxy='socks5h://proxy.example.com:1080') as client:
198
response = client.get('https://example.com')
199
```
200
201
### Multiple Proxies
202
203
```python
204
import httpx
205
206
# Different proxies for different protocols
207
proxies = {
208
'http://': 'http://proxy.example.com:8080',
209
'https://': 'https://secure-proxy.example.com:8443'
210
}
211
212
with httpx.Client(proxies=proxies) as client:
213
# HTTP requests use first proxy, HTTPS use second
214
http_response = client.get('http://example.com')
215
https_response = client.get('https://example.com')
216
```
217
218
### SSL/TLS Configuration
219
220
```python
221
import httpx
222
import ssl
223
224
# Disable SSL verification (not recommended for production)
225
with httpx.Client(verify=False) as client:
226
response = client.get('https://self-signed.example.com')
227
228
# Custom SSL context
229
ssl_context = ssl.create_default_context()
230
ssl_context.check_hostname = False
231
ssl_context.verify_mode = ssl.CERT_NONE
232
233
with httpx.Client(verify=ssl_context) as client:
234
response = client.get('https://example.com')
235
236
# Custom CA bundle
237
with httpx.Client(verify='/path/to/ca-bundle.crt') as client:
238
response = client.get('https://example.com')
239
```
240
241
### Client Certificates
242
243
```python
244
import httpx
245
246
# Client certificate for mutual TLS
247
with httpx.Client(cert='/path/to/client.pem') as client:
248
response = client.get('https://api.example.com')
249
250
# Separate cert and key files
251
with httpx.Client(cert=('/path/to/client.crt', '/path/to/client.key')) as client:
252
response = client.get('https://api.example.com')
253
```
254
255
### HTTP/2 Configuration
256
257
```python
258
import httpx
259
260
# Enable HTTP/2
261
with httpx.Client(http2=True) as client:
262
response = client.get('https://http2.example.com')
263
print(response.http_version) # "HTTP/2"
264
265
# HTTP/1.1 only
266
with httpx.Client(http1=True, http2=False) as client:
267
response = client.get('https://example.com')
268
print(response.http_version) # "HTTP/1.1"
269
```
270
271
### Combined Configuration
272
273
```python
274
import httpx
275
276
# Comprehensive client configuration
277
timeout = httpx.Timeout(
278
timeout=30.0,
279
connect=5.0,
280
read=10.0
281
)
282
283
limits = httpx.Limits(
284
max_connections=100,
285
max_keepalive_connections=20
286
)
287
288
proxy = httpx.Proxy(
289
'http://proxy.example.com:8080',
290
auth=('user', 'pass')
291
)
292
293
with httpx.Client(
294
timeout=timeout,
295
limits=limits,
296
proxy=proxy,
297
http2=True,
298
verify=True,
299
headers={'User-Agent': 'MyApp/1.0'}
300
) as client:
301
response = client.get('https://api.example.com/data')
302
```
303
304
### Environment Variable Support
305
306
```python
307
import httpx
308
309
# httpx automatically uses these environment variables when trust_env=True:
310
# - HTTP_PROXY, HTTPS_PROXY: Proxy URLs
311
# - NO_PROXY: Comma-separated list of hosts to bypass proxy
312
# - SSL_CERT_FILE, SSL_CERT_DIR: SSL certificate locations
313
# - REQUESTS_CA_BUNDLE, CURL_CA_BUNDLE: CA bundle file
314
315
with httpx.Client(trust_env=True) as client:
316
# Uses proxy from HTTP_PROXY/HTTPS_PROXY if set
317
response = client.get('https://example.com')
318
319
# Disable environment variable usage
320
with httpx.Client(trust_env=False) as client:
321
# Ignores proxy environment variables
322
response = client.get('https://example.com')
323
```
324
325
### Per-Request Overrides
326
327
```python
328
import httpx
329
330
# Client with default 5-second timeout
331
with httpx.Client(timeout=5.0) as client:
332
# Use default timeout
333
response1 = client.get('https://fast.example.com')
334
335
# Override timeout for slow endpoint
336
response2 = client.get('https://slow.example.com', timeout=30.0)
337
338
# No timeout for this request
339
response3 = client.get('https://example.com', timeout=None)
340
```
341
342
### Async Configuration
343
344
```python
345
import httpx
346
import asyncio
347
348
async def main():
349
timeout = httpx.Timeout(10.0)
350
limits = httpx.Limits(max_connections=50)
351
352
async with httpx.AsyncClient(
353
timeout=timeout,
354
limits=limits,
355
http2=True
356
) as client:
357
response = await client.get('https://example.com')
358
print(response.status_code)
359
360
asyncio.run(main())
361
```
362
363
### Default Configurations
364
365
```python
366
import httpx
367
368
# httpx provides these defaults:
369
DEFAULT_TIMEOUT_CONFIG = httpx.Timeout(timeout=5.0)
370
DEFAULT_LIMITS = httpx.Limits(
371
max_connections=100,
372
max_keepalive_connections=20,
373
keepalive_expiry=5.0
374
)
375
DEFAULT_MAX_REDIRECTS = 20
376
377
# These are used when not explicitly specified
378
with httpx.Client() as client:
379
# Uses default timeout of 5 seconds
380
# Uses default connection limits
381
# Follows up to 20 redirects
382
response = client.get('https://example.com')
383
```