0
# Client API
1
2
Service clients provide direct access to AWS APIs with dynamically generated methods based on service models. Clients handle request construction, response parsing, and service-specific logic for all AWS services.
3
4
## Capabilities
5
6
### Base Client Class
7
8
Foundation class for all AWS service clients with common functionality.
9
10
```python { .api }
11
class BaseClient:
12
def __init__(
13
self,
14
serializer,
15
endpoint,
16
response_parser,
17
event_emitter,
18
request_signer,
19
service_model: ServiceModel,
20
loader,
21
client_config: Config,
22
partition,
23
exceptions_factory,
24
endpoint_ruleset_resolver=None,
25
user_agent_creator=None
26
):
27
"""
28
Initialize AWS service client.
29
30
Note: BaseClient is typically created via session.create_client() rather than direct instantiation.
31
32
Args:
33
serializer: Request serialization handler
34
endpoint: Service endpoint handler
35
response_parser: Response parsing handler
36
event_emitter: Event emission system
37
request_signer: Request signing handler
38
service_model: Service model defining API operations
39
loader: Data loader for service models
40
client_config: Client configuration object
41
partition: AWS partition information
42
exceptions_factory: Exception creation factory
43
endpoint_ruleset_resolver: Endpoint rule resolution
44
user_agent_creator: User agent string creation
45
"""
46
```
47
48
### Client Metadata
49
50
Access client configuration and metadata through the meta property.
51
52
```python { .api }
53
class BaseClient:
54
@property
55
def meta(self) -> ClientMeta:
56
"""Client metadata and configuration access."""
57
58
class ClientMeta:
59
@property
60
def service_model(self) -> ServiceModel:
61
"""Service model defining API operations."""
62
63
@property
64
def region_name(self) -> str:
65
"""AWS region name for this client."""
66
67
@property
68
def client_config(self) -> Config:
69
"""Client configuration object."""
70
71
@property
72
def config(self) -> dict:
73
"""Resolved configuration dictionary."""
74
75
@property
76
def events(self) -> HierarchicalEmitter:
77
"""Event emitter for client events."""
78
```
79
80
### URL Generation
81
82
Generate presigned URLs for direct access to AWS resources.
83
84
```python { .api }
85
class BaseClient:
86
def generate_presigned_url(
87
self,
88
ClientMethod: str,
89
Params: dict = None,
90
ExpiresIn: int = 3600,
91
HttpMethod: str = None
92
) -> str:
93
"""
94
Generate presigned URL for client method.
95
96
Args:
97
ClientMethod: Client method name (e.g., 'get_object')
98
Params: Parameters for the operation
99
ExpiresIn: URL expiration time in seconds
100
HttpMethod: HTTP method for the URL
101
102
Returns:
103
str: Presigned URL
104
"""
105
106
def generate_presigned_post(
107
self,
108
Bucket: str,
109
Key: str,
110
Fields: dict = None,
111
Conditions: List = None,
112
ExpiresIn: int = 3600
113
) -> dict:
114
"""
115
Generate presigned POST for S3 uploads.
116
117
Args:
118
Bucket: S3 bucket name
119
Key: S3 object key
120
Fields: Form fields to include
121
Conditions: Policy conditions
122
ExpiresIn: Expiration time in seconds
123
124
Returns:
125
dict: Presigned POST data with 'url' and 'fields'
126
"""
127
```
128
129
### Pagination Support
130
131
Access and use pagination for operations that return large result sets.
132
133
```python { .api }
134
class BaseClient:
135
def can_paginate(self, operation_name: str) -> bool:
136
"""
137
Check if operation supports pagination.
138
139
Args:
140
operation_name: AWS operation name
141
142
Returns:
143
bool: True if operation supports pagination
144
"""
145
146
def get_paginator(self, operation_name: str) -> Paginator:
147
"""
148
Get paginator for operation.
149
150
Args:
151
operation_name: AWS operation name
152
153
Returns:
154
Paginator: Paginator instance for operation
155
"""
156
```
157
158
### Waiter Support
159
160
Access waiters for polling resource states until desired conditions are met.
161
162
```python { .api }
163
class BaseClient:
164
def get_waiter(self, waiter_name: str) -> Waiter:
165
"""
166
Get waiter for resource state polling.
167
168
Args:
169
waiter_name: Waiter name
170
171
Returns:
172
Waiter: Waiter instance
173
"""
174
```
175
176
### Connection Management
177
178
Manage client HTTP connections and cleanup.
179
180
```python { .api }
181
class BaseClient:
182
def close(self) -> None:
183
"""Close client HTTP connections and cleanup resources."""
184
```
185
186
### Client Factory
187
188
Factory class for creating service clients.
189
190
```python { .api }
191
class ClientCreator:
192
def create_client(
193
self,
194
service_name: str,
195
region_name: str,
196
api_version: str = None,
197
use_ssl: bool = True,
198
verify: Union[bool, str] = None,
199
endpoint_url: str = None,
200
credentials: Credentials = None,
201
scoped_config: dict = None,
202
client_config: Config = None,
203
api_version_override: str = None
204
) -> BaseClient:
205
"""
206
Create AWS service client.
207
208
Args:
209
service_name: AWS service name
210
region_name: AWS region name
211
api_version: API version to use
212
use_ssl: Use SSL/TLS for requests
213
verify: SSL certificate verification
214
endpoint_url: Custom endpoint URL
215
credentials: AWS credentials
216
scoped_config: Configuration dictionary
217
client_config: Client configuration
218
api_version_override: Override API version
219
220
Returns:
221
BaseClient: Configured service client
222
"""
223
```
224
225
## Dynamic Service Methods
226
227
Service clients dynamically generate methods based on service models. Each AWS service operation becomes a client method with the following pattern:
228
229
### Operation Method Pattern
230
231
```python { .api }
232
def operation_name(self, **kwargs) -> dict:
233
"""
234
AWS service operation.
235
236
Args:
237
**kwargs: Operation-specific parameters as defined in service model
238
239
Returns:
240
dict: Operation response data
241
242
Raises:
243
ClientError: Service-specific errors
244
BotoCoreError: Client-level errors
245
"""
246
```
247
248
### Common Operation Categories
249
250
**List Operations**: Return collections of resources
251
```python
252
# Example: S3 list_buckets
253
response = s3_client.list_buckets()
254
buckets = response['Buckets']
255
256
# Example: EC2 describe_instances
257
response = ec2_client.describe_instances()
258
reservations = response['Reservations']
259
```
260
261
**Get Operations**: Retrieve specific resources
262
```python
263
# Example: S3 get_object
264
response = s3_client.get_object(Bucket='mybucket', Key='mykey')
265
body = response['Body'].read()
266
267
# Example: EC2 describe_instance_attribute
268
response = ec2_client.describe_instance_attribute(
269
InstanceId='i-1234567890abcdef0',
270
Attribute='instanceType'
271
)
272
```
273
274
**Create Operations**: Create new resources
275
```python
276
# Example: S3 create_bucket
277
response = s3_client.create_bucket(
278
Bucket='mynewbucket',
279
CreateBucketConfiguration={'LocationConstraint': 'us-west-2'}
280
)
281
282
# Example: EC2 run_instances
283
response = ec2_client.run_instances(
284
ImageId='ami-12345678',
285
MinCount=1,
286
MaxCount=1,
287
InstanceType='t2.micro'
288
)
289
```
290
291
**Update Operations**: Modify existing resources
292
```python
293
# Example: S3 put_object
294
response = s3_client.put_object(
295
Bucket='mybucket',
296
Key='mykey',
297
Body=b'Hello World'
298
)
299
300
# Example: EC2 modify_instance_attribute
301
ec2_client.modify_instance_attribute(
302
InstanceId='i-1234567890abcdef0',
303
InstanceType={'Value': 't2.small'}
304
)
305
```
306
307
**Delete Operations**: Remove resources
308
```python
309
# Example: S3 delete_object
310
s3_client.delete_object(Bucket='mybucket', Key='mykey')
311
312
# Example: EC2 terminate_instances
313
response = ec2_client.terminate_instances(
314
InstanceIds=['i-1234567890abcdef0']
315
)
316
```
317
318
## Usage Examples
319
320
### Basic Client Usage
321
322
```python
323
from botocore.session import get_session
324
325
# Create session and client
326
session = get_session()
327
s3_client = session.create_client('s3', region_name='us-east-1')
328
329
# Use client methods
330
response = s3_client.list_buckets()
331
for bucket in response['Buckets']:
332
print(bucket['Name'])
333
```
334
335
### Client Configuration
336
337
```python
338
from botocore.config import Config
339
340
# Create client with custom configuration
341
config = Config(
342
connect_timeout=30,
343
read_timeout=30,
344
retries={'max_attempts': 3}
345
)
346
347
client = session.create_client(
348
's3',
349
region_name='us-west-2',
350
config=config
351
)
352
```
353
354
### Presigned URL Generation
355
356
```python
357
# Generate presigned URL for S3 object
358
url = s3_client.generate_presigned_url(
359
'get_object',
360
Params={'Bucket': 'mybucket', 'Key': 'myfile.txt'},
361
ExpiresIn=3600 # 1 hour
362
)
363
364
# Generate presigned POST for file uploads
365
presigned_post = s3_client.generate_presigned_post(
366
Bucket='mybucket',
367
Key='uploads/${filename}',
368
ExpiresIn=3600
369
)
370
```
371
372
### Error Handling
373
374
```python
375
from botocore.exceptions import ClientError, NoCredentialsError
376
377
try:
378
response = s3_client.head_bucket(Bucket='nonexistent-bucket')
379
except ClientError as e:
380
error_code = e.response['Error']['Code']
381
if error_code == 'NoSuchBucket':
382
print("Bucket does not exist")
383
elif error_code == 'Forbidden':
384
print("Access denied")
385
except NoCredentialsError:
386
print("AWS credentials not found")
387
```
388
389
### Connection Management
390
391
```python
392
# Close client connections when done
393
try:
394
# Use client for operations
395
response = s3_client.list_buckets()
396
# ... more operations
397
finally:
398
s3_client.close()
399
```