0
# GAPIC Framework
1
2
Generated API Client (GAPIC) infrastructure providing method wrapping, configuration parsing, and enhanced client functionality for Google API clients. This framework transforms low-level gRPC methods into high-level client library methods with automatic retry, timeout, compression, and error handling capabilities.
3
4
## Capabilities
5
6
### Method Wrapping
7
8
Core functionality for wrapping RPC methods with common behaviors including retry logic, timeout handling, compression, and error mapping.
9
10
```python { .api }
11
def wrap_method(
12
func,
13
default_retry=None,
14
default_timeout=None,
15
default_compression=None,
16
client_info=None,
17
*,
18
with_call=False
19
): ...
20
```
21
22
### Async Method Wrapping
23
24
Asynchronous version of method wrapping for async/await based client libraries.
25
26
```python { .api }
27
def wrap_async_method(
28
func,
29
default_retry=None,
30
default_timeout=None,
31
default_compression=None,
32
client_info=None,
33
*,
34
with_call=False
35
): ...
36
```
37
38
### Configuration Parsing
39
40
Parse and process GAPIC configuration data for retry policies, timeout settings, and error handling rules.
41
42
```python { .api }
43
def parse_method_configs(interface_config, client_config=None, calling_form=None): ...
44
45
def _retry_from_retry_config(retry_params, retry_codes, retry_impl=None): ...
46
47
def _timeout_from_retry_config(retry_params, timeout_impl=None): ...
48
```
49
50
### Routing Headers
51
52
Generate routing headers for Google infrastructure to determine request routing, especially for regional services.
53
54
```python { .api }
55
def to_routing_header(params, qualified_enums=True): ...
56
57
def to_grpc_metadata(routing_header): ...
58
59
ROUTING_METADATA_KEY = "x-goog-request-params"
60
```
61
62
### Enhanced Client Information
63
64
Extended client information for API analytics including library versions, runtime information, and user agent details.
65
66
```python { .api }
67
class ClientInfo:
68
def __init__(
69
self,
70
python_version=None,
71
grpc_version=None,
72
api_core_version=None,
73
gapic_version=None,
74
client_library_version=None,
75
user_agent=None,
76
rest_version=None,
77
protobuf_runtime_version=None
78
): ...
79
80
def to_user_agent(self): ...
81
def to_grpc_metadata(self): ...
82
83
METRICS_METADATA_KEY = "x-goog-api-client"
84
DEFAULT_CLIENT_INFO = ClientInfo()
85
```
86
87
## Usage Examples
88
89
### Basic Method Wrapping
90
91
```python
92
from google.api_core.gapic_v1 import method
93
from google.api_core import retry
94
from google.api_core import timeout
95
from grpc import Compression
96
97
# Original RPC method
98
def get_topic(name, timeout=None):
99
request = publisher_v2.GetTopicRequest(name=name)
100
return publisher_stub.GetTopic(request, timeout=timeout)
101
102
# Configure defaults
103
default_retry = retry.Retry(deadline=60)
104
default_timeout = timeout.Timeout(deadline=60)
105
default_compression = Compression.NoCompression
106
107
# Wrap the method
108
wrapped_get_topic = method.wrap_method(
109
get_topic,
110
default_retry=default_retry,
111
default_timeout=default_timeout,
112
default_compression=default_compression
113
)
114
115
# Use wrapped method with defaults
116
response = wrapped_get_topic(name="projects/my-project/topics/my-topic")
117
118
# Override retry behavior
119
custom_retry = retry.Retry(
120
predicate=retry.if_exception_type(exceptions.InternalServerError)
121
)
122
response = wrapped_get_topic(
123
name="projects/my-project/topics/my-topic",
124
retry=custom_retry
125
)
126
127
# Disable retry
128
response = wrapped_get_topic(
129
name="projects/my-project/topics/my-topic",
130
retry=None
131
)
132
```
133
134
### Configuration Parsing
135
136
```python
137
from google.api_core.gapic_v1 import config
138
139
# Parse method configurations from GAPIC config
140
interface_config = {
141
"retry_codes": {
142
"idempotent": ["DEADLINE_EXCEEDED", "UNAVAILABLE"],
143
"non_idempotent": []
144
},
145
"retry_params": {
146
"default": {
147
"initial_retry_delay_millis": 100,
148
"retry_delay_multiplier": 1.3,
149
"max_retry_delay_millis": 60000,
150
"initial_rpc_timeout_millis": 20000,
151
"rpc_timeout_multiplier": 1.0,
152
"max_rpc_timeout_millis": 20000,
153
"total_timeout_millis": 600000
154
}
155
},
156
"methods": {
157
"GetTopic": {
158
"timeout_millis": 60000,
159
"retry_codes_name": "idempotent",
160
"retry_params_name": "default"
161
}
162
}
163
}
164
165
# Parse configurations
166
method_configs = config.parse_method_configs(interface_config)
167
get_topic_config = method_configs["GetTopic"]
168
169
# Access parsed retry and timeout objects
170
retry_policy = get_topic_config.retry
171
timeout_policy = get_topic_config.timeout
172
```
173
174
### Routing Headers
175
176
```python
177
from google.api_core.gapic_v1 import routing_header
178
179
# Create routing parameters
180
params = {
181
"project": "my-project",
182
"location": "us-central1",
183
"instance": "my-instance"
184
}
185
186
# Generate routing header string
187
header_value = routing_header.to_routing_header(params)
188
# Returns: "project=my-project&location=us-central1&instance=my-instance"
189
190
# Convert to gRPC metadata
191
metadata = routing_header.to_grpc_metadata(header_value)
192
# Returns: [("x-goog-request-params", "project=my-project&location=us-central1&instance=my-instance")]
193
```
194
195
### Client Information
196
197
```python
198
from google.api_core.gapic_v1 import client_info
199
200
# Create client info with version details
201
info = client_info.ClientInfo(
202
gapic_version="1.2.0",
203
client_library_version="2.1.0",
204
user_agent="my-application/1.0.0"
205
)
206
207
# Generate user agent string
208
user_agent = info.to_user_agent()
209
# Returns: "my-application/1.0.0 gapic/1.2.0 gax/2.1.0 gl-python/3.9.6"
210
211
# Convert to gRPC metadata
212
metadata = info.to_grpc_metadata()
213
# Returns: [("x-goog-api-client", "my-application/1.0.0 gapic/1.2.0 gax/2.1.0 gl-python/3.9.6")]
214
```
215
216
### Method Configuration Defaults
217
218
```python
219
from google.api_core.gapic_v1.method import DEFAULT
220
221
# Use sentinel value for default behavior
222
wrapped_method = method.wrap_method(
223
original_method,
224
default_retry=retry.Retry(),
225
default_timeout=timeout.Timeout(60)
226
)
227
228
# Call with explicit defaults
229
response = wrapped_method(
230
request,
231
retry=DEFAULT, # Use the default retry policy
232
timeout=DEFAULT, # Use the default timeout
233
compression=DEFAULT # Use default compression
234
)
235
```
236
237
## Framework Architecture
238
239
### Method Decoration Pipeline
240
241
The GAPIC framework applies decorators in a specific order to transform raw RPC methods:
242
243
1. **Error Wrapping**: Maps gRPC status codes to Google API exceptions
244
2. **Retry Logic**: Applies configurable retry policies with exponential backoff
245
3. **Timeout Handling**: Enforces method-level and call-level timeouts
246
4. **Compression**: Applies gRPC compression settings
247
5. **Metadata Injection**: Adds client info and routing headers
248
6. **Instrumentation**: Provides call tracing and metrics collection
249
250
### Configuration Structure
251
252
GAPIC configurations define behavior policies for each RPC method:
253
254
```python
255
{
256
"retry_codes": {
257
"policy_name": ["STATUS_CODE1", "STATUS_CODE2"]
258
},
259
"retry_params": {
260
"policy_name": {
261
"initial_retry_delay_millis": 100,
262
"retry_delay_multiplier": 1.3,
263
"max_retry_delay_millis": 60000,
264
"total_timeout_millis": 600000
265
}
266
},
267
"methods": {
268
"MethodName": {
269
"retry_codes_name": "policy_name",
270
"retry_params_name": "policy_name"
271
}
272
}
273
}
274
```
275
276
### Async Support
277
278
Full support for asyncio-based clients with async method wrapping:
279
280
- **Async Retry**: Non-blocking retry logic using `asyncio.sleep()`
281
- **Async Timeout**: Timeout handling compatible with asyncio event loops
282
- **Context Management**: Proper resource cleanup in async contexts
283
- **Exception Propagation**: Maintains exception semantics across async boundaries
284
285
## Import Patterns
286
287
```python
288
# Method wrapping
289
from google.api_core.gapic_v1 import method
290
from google.api_core.gapic_v1 import method_async
291
292
# Configuration parsing
293
from google.api_core.gapic_v1 import config
294
295
# Routing headers
296
from google.api_core.gapic_v1 import routing_header
297
298
# Client information
299
from google.api_core.gapic_v1 import client_info
300
301
# Access all modules
302
from google.api_core import gapic_v1
303
```
304
305
## Types
306
307
```python { .api }
308
from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union
309
import enum
310
import grpc
311
312
# Method wrapping types
313
WrappedMethod = Callable[..., Any]
314
GrpcMethod = Callable[..., Any]
315
Decorator = Callable[[Callable], Callable]
316
317
# Configuration types
318
RetryConfig = Dict[str, Union[str, int, float]]
319
MethodConfig = Dict[str, Union[str, RetryConfig]]
320
InterfaceConfig = Dict[str, Union[Dict, List]]
321
322
# Routing types
323
RoutingParams = Dict[str, Union[str, bytes, enum.Enum]]
324
GrpcMetadata = List[Tuple[str, str]]
325
326
# Default sentinel
327
class _MethodDefault(enum.Enum):
328
_DEFAULT_VALUE = object()
329
330
DEFAULT = _MethodDefault._DEFAULT_VALUE
331
```
332
333
## Constants and Metadata Keys
334
335
```python { .api }
336
# Routing header metadata key
337
ROUTING_METADATA_KEY = "x-goog-request-params"
338
339
# Client metrics metadata key
340
METRICS_METADATA_KEY = "x-goog-api-client"
341
342
# Cache size for routing parameter computation
343
ROUTING_PARAM_CACHE_SIZE = 32
344
345
# Milliseconds per second conversion
346
_MILLIS_PER_SECOND = 1000.0
347
348
# Sentinel for default metadata behavior
349
USE_DEFAULT_METADATA = object()
350
```
351
352
The GAPIC framework is the foundation for all generated Google API client libraries, providing consistent behavior, configuration management, and enhanced functionality across hundreds of Google Cloud and API services.