0
# Client Classes
1
2
Persistent client instances that provide session-like behavior, connection pooling, and advanced configuration options. HTTP3 offers both synchronous and asynchronous client implementations, enabling efficient resource management and optimal performance for applications making multiple HTTP requests.
3
4
Clients maintain connection pools, handle cookies automatically, support authentication, and provide comprehensive configuration options for timeouts, SSL settings, and connection limits.
5
6
## Capabilities
7
8
### Synchronous Client
9
10
The primary synchronous HTTP client for applications requiring blocking I/O operations.
11
12
```python { .api }
13
class Client:
14
def __init__(self, auth=None, cookies=None, verify=True, cert=None, timeout=DEFAULT_TIMEOUT_CONFIG, pool_limits=DEFAULT_POOL_LIMITS, max_redirects=DEFAULT_MAX_REDIRECTS, base_url=None, dispatch=None, app=None, raise_app_exceptions=True, backend=None):
15
"""
16
Initialize a synchronous HTTP client.
17
18
Parameters:
19
- auth (AuthTypes, optional): Default authentication for all requests
20
- cookies (CookieTypes, optional): Default cookies for all requests
21
- verify (VerifyTypes): SSL certificate verification (default: True)
22
- cert (CertTypes, optional): Client SSL certificate
23
- timeout (TimeoutTypes): Default timeout configuration
24
- pool_limits (PoolLimits): Connection pool limits
25
- max_redirects (int): Maximum number of redirects to follow
26
- base_url (URLTypes, optional): Base URL for relative requests
27
- dispatch (Dispatcher, optional): Custom request dispatcher
28
- app (Callable, optional): WSGI/ASGI app for local testing
29
- raise_app_exceptions (bool): Whether to raise app exceptions
30
- backend (ConcurrencyBackend, optional): Concurrency backend
31
"""
32
33
def request(self, method, url, *, data=None, files=None, json=None, params=None, headers=None, cookies=None, stream=False, auth=None, allow_redirects=True, cert=None, verify=None, timeout=None):
34
"""
35
Send an HTTP request.
36
37
Parameters: Same as module-level request functions
38
Returns: Response object
39
"""
40
41
def get(self, url, **kwargs):
42
"""Send a GET request. Returns Response object."""
43
44
def post(self, url, **kwargs):
45
"""Send a POST request. Returns Response object."""
46
47
def put(self, url, **kwargs):
48
"""Send a PUT request. Returns Response object."""
49
50
def patch(self, url, **kwargs):
51
"""Send a PATCH request. Returns Response object."""
52
53
def delete(self, url, **kwargs):
54
"""Send a DELETE request. Returns Response object."""
55
56
def head(self, url, **kwargs):
57
"""Send a HEAD request. Returns Response object."""
58
59
def options(self, url, **kwargs):
60
"""Send an OPTIONS request. Returns Response object."""
61
62
def close(self):
63
"""Close the client and release all resources."""
64
65
def __enter__(self):
66
"""Context manager entry."""
67
68
def __exit__(self, exc_type, exc_value, traceback):
69
"""Context manager exit with automatic cleanup."""
70
```
71
72
**Usage Example:**
73
74
```python
75
import http3
76
77
# Basic client usage
78
with http3.Client() as client:
79
response = client.get('https://api.example.com/users')
80
users = response.json()
81
82
# Client maintains cookies and connections
83
response = client.post('https://api.example.com/users', json={'name': 'John'})
84
85
# Client with authentication and custom configuration
86
client = http3.Client(
87
auth=('username', 'password'),
88
timeout=30.0,
89
verify=False, # Disable SSL verification
90
base_url='https://api.example.com'
91
)
92
93
try:
94
# Use relative URLs with base_url
95
response = client.get('/users')
96
response = client.post('/users', json={'name': 'Jane'})
97
finally:
98
client.close()
99
100
# Advanced configuration
101
from http3 import PoolLimits, TimeoutConfig
102
103
client = http3.Client(
104
pool_limits=PoolLimits(soft_limit=20, hard_limit=100),
105
timeout=TimeoutConfig(connect_timeout=5.0, read_timeout=30.0),
106
max_redirects=10
107
)
108
```
109
110
### Asynchronous Client
111
112
The asynchronous HTTP client for non-blocking I/O operations and concurrent request handling.
113
114
```python { .api }
115
class AsyncClient:
116
def __init__(self, auth=None, cookies=None, verify=True, cert=None, timeout=DEFAULT_TIMEOUT_CONFIG, pool_limits=DEFAULT_POOL_LIMITS, max_redirects=DEFAULT_MAX_REDIRECTS, base_url=None, dispatch=None, app=None, raise_app_exceptions=True, backend=None):
117
"""
118
Initialize an asynchronous HTTP client.
119
120
Parameters: Same as Client.__init__()
121
"""
122
123
async def request(self, method, url, *, data=None, files=None, json=None, params=None, headers=None, cookies=None, stream=False, auth=None, allow_redirects=True, cert=None, verify=None, timeout=None):
124
"""
125
Send an HTTP request asynchronously.
126
127
Parameters: Same as Client.request()
128
Returns: AsyncResponse object
129
"""
130
131
async def get(self, url, **kwargs):
132
"""Send a GET request asynchronously. Returns AsyncResponse object."""
133
134
async def post(self, url, **kwargs):
135
"""Send a POST request asynchronously. Returns AsyncResponse object."""
136
137
async def put(self, url, **kwargs):
138
"""Send a PUT request asynchronously. Returns AsyncResponse object."""
139
140
async def patch(self, url, **kwargs):
141
"""Send a PATCH request asynchronously. Returns AsyncResponse object."""
142
143
async def delete(self, url, **kwargs):
144
"""Send a DELETE request asynchronously. Returns AsyncResponse object."""
145
146
async def head(self, url, **kwargs):
147
"""Send a HEAD request asynchronously. Returns AsyncResponse object."""
148
149
async def options(self, url, **kwargs):
150
"""Send an OPTIONS request asynchronously. Returns AsyncResponse object."""
151
152
async def close(self):
153
"""Close the client and release all resources asynchronously."""
154
155
async def __aenter__(self):
156
"""Async context manager entry."""
157
158
async def __aexit__(self, exc_type, exc_value, traceback):
159
"""Async context manager exit with automatic cleanup."""
160
```
161
162
**Usage Example:**
163
164
```python
165
import http3
166
import asyncio
167
168
async def main():
169
# Basic async client usage
170
async with http3.AsyncClient() as client:
171
response = await client.get('https://api.example.com/users')
172
users = await response.json()
173
174
# Make concurrent requests
175
tasks = [
176
client.get(f'https://api.example.com/users/{i}')
177
for i in range(1, 11)
178
]
179
responses = await asyncio.gather(*tasks)
180
181
# Client with custom configuration
182
client = http3.AsyncClient(
183
auth=('username', 'password'),
184
timeout=30.0,
185
base_url='https://api.example.com'
186
)
187
188
try:
189
response = await client.get('/users')
190
data = await response.json()
191
finally:
192
await client.close()
193
194
asyncio.run(main())
195
```
196
197
### Client Configuration Options
198
199
#### Authentication
200
201
```python
202
# Basic authentication
203
client = http3.Client(auth=('username', 'password'))
204
205
# Custom authentication callable
206
def custom_auth(request):
207
request.headers['Authorization'] = 'Bearer token'
208
return request
209
210
client = http3.Client(auth=custom_auth)
211
```
212
213
#### Connection Pool Limits
214
215
```python
216
from http3 import PoolLimits
217
218
# Custom pool limits
219
pool_limits = PoolLimits(
220
soft_limit=10, # Preferred number of connections per host
221
hard_limit=50, # Maximum connections per host
222
pool_timeout=5.0 # Timeout waiting for connection from pool
223
)
224
225
client = http3.Client(pool_limits=pool_limits)
226
```
227
228
#### Timeout Configuration
229
230
```python
231
from http3 import TimeoutConfig
232
233
# Granular timeout control
234
timeout = TimeoutConfig(
235
connect_timeout=5.0, # Connection establishment timeout
236
read_timeout=30.0, # Response reading timeout
237
write_timeout=10.0 # Request sending timeout
238
)
239
240
client = http3.Client(timeout=timeout)
241
242
# Simple timeout (applies to all operations)
243
client = http3.Client(timeout=30.0)
244
```
245
246
#### SSL Configuration
247
248
```python
249
# Disable SSL verification
250
client = http3.Client(verify=False)
251
252
# Custom CA bundle
253
client = http3.Client(verify='/path/to/ca-bundle.crt')
254
255
# Client certificate
256
client = http3.Client(cert='/path/to/client-cert.pem')
257
258
# Client certificate with private key
259
client = http3.Client(cert=('/path/to/cert.pem', '/path/to/key.pem'))
260
```
261
262
#### Base URL and Relative Requests
263
264
```python
265
# Set base URL for relative requests
266
client = http3.Client(base_url='https://api.example.com/v1')
267
268
# All requests use the base URL
269
response = client.get('/users') # Requests https://api.example.com/v1/users
270
response = client.post('/posts') # Requests https://api.example.com/v1/posts
271
```
272
273
#### Cookie Persistence
274
275
```python
276
# Initialize with cookies
277
client = http3.Client(cookies={'session': 'abc123'})
278
279
# Cookies are automatically maintained across requests
280
response = client.get('/login') # Server sets cookies
281
response = client.get('/profile') # Cookies sent automatically
282
```
283
284
### WSGI/ASGI Integration
285
286
HTTP3 clients can make requests directly to WSGI or ASGI applications without network overhead:
287
288
```python
289
from flask import Flask
290
291
app = Flask(__name__)
292
293
@app.route('/hello')
294
def hello():
295
return {'message': 'Hello World'}
296
297
# Test Flask app directly
298
client = http3.Client(app=app)
299
response = client.get('/hello')
300
print(response.json()) # {'message': 'Hello World'}
301
```
302
303
### Context Manager Usage
304
305
Both client types support context managers for automatic resource cleanup:
306
307
```python
308
# Synchronous context manager
309
with http3.Client() as client:
310
response = client.get('https://example.com')
311
# Client automatically closed on exit
312
313
# Asynchronous context manager
314
async with http3.AsyncClient() as client:
315
response = await client.get('https://example.com')
316
# Client automatically closed on exit
317
```
318
319
### Error Handling
320
321
Clients may raise these exceptions:
322
323
- **ConnectTimeout**: Connection establishment timeout
324
- **ReadTimeout**: Response reading timeout
325
- **WriteTimeout**: Request sending timeout
326
- **PoolTimeout**: Timeout waiting for connection from pool
327
- **TooManyRedirects**: Exceeded maximum redirect limit
328
- **ProtocolError**: HTTP protocol violation
329
- **InvalidURL**: Malformed URL provided