Google API Client Library for Python that provides discovery-based access to hundreds of Google services with authentication, caching, and media upload/download support.
npx @tessl/cli install tessl/pypi-google-api-python-client@2.181.00
# Google API Python Client
1
2
The Google API Python Client Library provides a comprehensive Python interface for accessing Google's discovery-based APIs. It handles authentication, API discovery, request construction, response processing, and media management for hundreds of Google services including Gmail, Drive, Calendar, YouTube, and many others.
3
4
## Package Information
5
6
- **Package Name**: google-api-python-client
7
- **Language**: Python
8
- **Installation**: `pip install google-api-python-client`
9
- **Dependencies**: google-auth, google-auth-httplib2, google-api-core, httplib2, uritemplate
10
11
## Core Imports
12
13
Primary import for API discovery and service building:
14
15
```python
16
from googleapiclient import discovery
17
```
18
19
Common imports for error handling and HTTP functionality:
20
21
```python
22
from googleapiclient import errors
23
from googleapiclient import http
24
```
25
26
Backward compatibility imports (legacy):
27
28
```python
29
from apiclient import discovery # Same as googleapiclient.discovery
30
from apiclient import errors # Same as googleapiclient.errors
31
```
32
33
## Basic Usage
34
35
```python
36
import google.auth
37
from googleapiclient import discovery
38
from googleapiclient.errors import HttpError
39
40
# Authentication using Application Default Credentials
41
credentials, project = google.auth.default()
42
43
# Build service client for Gmail API
44
service = discovery.build('gmail', 'v1', credentials=credentials)
45
46
try:
47
# List messages in user's inbox
48
results = service.users().messages().list(userId='me', maxResults=10).execute()
49
messages = results.get('messages', [])
50
51
for message in messages:
52
msg = service.users().messages().get(userId='me', id=message['id']).execute()
53
print(f"Subject: {msg['payload']['headers'][0]['value']}")
54
55
except HttpError as error:
56
print(f'An error occurred: {error}')
57
```
58
59
## Architecture
60
61
The library follows a layered architecture:
62
63
- **Discovery Layer**: Dynamically builds service clients from API discovery documents
64
- **Resource Layer**: Provides typed access to API resources and methods
65
- **HTTP Layer**: Handles request construction, authentication, retries, and response processing
66
- **Model Layer**: Manages request/response serialization and media handling
67
- **Cache Layer**: Optimizes performance through discovery document caching
68
69
This design enables the library to support hundreds of Google APIs without requiring individual client implementations.
70
71
## Capabilities
72
73
### API Discovery and Service Building
74
75
Core functionality for discovering Google APIs and building service clients with automatic method generation, authentication integration, and caching support.
76
77
```python { .api }
78
def build(serviceName, version, http=None, discoveryServiceUrl=None,
79
developerKey=None, model=None, requestBuilder=None,
80
credentials=None, cache_discovery=True, cache=None,
81
client_options=None, adc_cert_path=None, adc_key_path=None,
82
num_retries=1, static_discovery=None, always_use_jwt_access=False):
83
"""
84
Construct a Resource for interacting with an API.
85
86
Args:
87
serviceName (str): Name of the service (e.g., 'gmail', 'drive')
88
version (str): Version of the service (e.g., 'v1')
89
http (httplib2.Http, optional): HTTP client instance
90
discoveryServiceUrl (str, optional): URL for discovery service
91
developerKey (str, optional): API key for authentication
92
model (BaseModel, optional): Data model for request/response handling
93
requestBuilder (RequestBuilder, optional): Custom request builder
94
credentials (Credentials, optional): OAuth2 credentials
95
cache_discovery (bool): Whether to cache discovery documents
96
cache (Cache, optional): Custom cache implementation
97
client_options (ClientOptions, optional): Client configuration options
98
adc_cert_path (str, optional): Path to ADC certificate
99
adc_key_path (str, optional): Path to ADC private key
100
num_retries (int): Number of retry attempts for discovery (default: 1)
101
static_discovery (bool, optional): Use static discovery documents (None for auto)
102
always_use_jwt_access (bool): Always use JWT access tokens for service accounts
103
104
Returns:
105
Resource: A Resource object with methods for each API endpoint
106
"""
107
108
def build_from_document(service, base=None, future=None, http=None,
109
developerKey=None, model=None, requestBuilder=None,
110
credentials=None, client_options=None, adc_cert_path=None,
111
adc_key_path=None, always_use_jwt_access=False):
112
"""
113
Create a Resource from a discovery document.
114
115
Args:
116
service (dict or str): The discovery document or JSON string
117
base (str, optional): Base URI for the service (deprecated)
118
future (str, optional): Future version identifier (deprecated)
119
developerKey (str, optional): API key for authentication
120
http (httplib2.Http, optional): HTTP client instance
121
model (BaseModel, optional): Data model for request/response handling
122
requestBuilder (RequestBuilder, optional): Custom request builder
123
credentials (Credentials, optional): OAuth2 credentials
124
client_options (ClientOptions, optional): Client configuration options
125
adc_cert_path (str, optional): Path to ADC certificate
126
adc_key_path (str, optional): Path to ADC private key
127
always_use_jwt_access (bool): Always use JWT for service accounts
128
129
Returns:
130
Resource: A Resource object built from the discovery document
131
"""
132
```
133
134
[API Discovery and Service Building](./discovery.md)
135
136
### HTTP Request Handling
137
138
Comprehensive HTTP functionality including individual requests, batch processing, retry logic, authentication integration, and mock support for testing.
139
140
```python { .api }
141
class HttpRequest:
142
def __init__(self, http, postproc, uri, method='GET', body=None,
143
headers=None, methodId=None, resumable=None): ...
144
145
def execute(self, http=None, num_retries=0):
146
"""
147
Execute the HTTP request.
148
149
Args:
150
http (httplib2.Http, optional): HTTP client to use
151
num_retries (int): Number of retry attempts
152
153
Returns:
154
object: Deserialized response content
155
"""
156
157
class BatchHttpRequest:
158
def __init__(self, callback=None, batch_uri=None): ...
159
160
def add(self, request, callback=None, request_id=None):
161
"""
162
Add a request to the batch.
163
164
Args:
165
request (HttpRequest): Request to add to batch
166
callback (callable, optional): Callback for this request
167
request_id (str, optional): Unique ID for this request
168
"""
169
170
def execute(self, http=None, num_retries=0):
171
"""Execute all requests in the batch."""
172
```
173
174
[HTTP Request Handling](./http.md)
175
176
### Media Upload and Download
177
178
Robust media handling with support for file uploads, in-memory uploads, streaming, progress tracking, resumable transfers, and chunked processing for large files.
179
180
```python { .api }
181
class MediaFileUpload:
182
def __init__(self, filename, mimetype=None, chunksize=DEFAULT_CHUNK_SIZE,
183
resumable=False):
184
"""
185
Upload a file to Google APIs.
186
187
Args:
188
filename (str): Path to the file to upload
189
mimetype (str, optional): MIME type of the file
190
chunksize (int): Size of upload chunks in bytes
191
resumable (bool): Whether upload should be resumable
192
"""
193
194
class MediaIoBaseDownload:
195
def __init__(self, fd, request, chunksize=DEFAULT_CHUNK_SIZE):
196
"""
197
Download media to a file-like object.
198
199
Args:
200
fd (IOBase): File-like object to write download data
201
request (HttpRequest): Request for the media download
202
chunksize (int): Size of download chunks in bytes
203
"""
204
205
def next_chunk(self, num_retries=0):
206
"""
207
Download the next chunk of media.
208
209
Args:
210
num_retries (int): Number of retry attempts
211
212
Returns:
213
tuple: (MediaDownloadProgress, bool) - progress and done status
214
"""
215
```
216
217
[Media Upload and Download](./media.md)
218
219
### Error Handling and Exceptions
220
221
Complete error handling system with structured exceptions, HTTP error details, batch error processing, and integration patterns for robust error management.
222
223
```python { .api }
224
class HttpError(Exception):
225
"""HTTP request failed with error response."""
226
227
def __init__(self, resp, content, uri=None): ...
228
229
@property
230
def error_details(self):
231
"""List of individual error details from the response."""
232
233
def _get_reason(self):
234
"""Get the reason phrase from the HTTP response."""
235
236
class BatchError(HttpError):
237
"""Error occurred in batch request processing."""
238
239
class MediaUploadSizeError(HttpError):
240
"""Media upload size exceeds limits."""
241
```
242
243
[Error Handling and Exceptions](./errors.md)
244
245
### Testing and Mocking
246
247
Comprehensive testing utilities including HTTP mocking, response simulation, sequence testing, and integration with standard testing frameworks.
248
249
```python { .api }
250
class HttpMock:
251
def __init__(self, filename=None, headers=None):
252
"""
253
Mock HTTP responses for testing.
254
255
Args:
256
filename (str, optional): File containing mock response
257
headers (dict, optional): HTTP headers for mock response
258
"""
259
260
def request(self, uri, method='GET', body=None, headers=None,
261
redirections=1, connection_type=None):
262
"""Return mock HTTP response."""
263
264
class HttpMockSequence:
265
def __init__(self, iterable):
266
"""
267
Mock a sequence of HTTP responses.
268
269
Args:
270
iterable: Sequence of (response, content) tuples
271
"""
272
```
273
274
[Testing and Mocking](./testing.md)
275
276
### Authentication Integration
277
278
Authentication helper functions that integrate with google-auth and oauth2client libraries, providing credential management, scope handling, and header application.
279
280
```python { .api }
281
def default_credentials():
282
"""Get default credentials from the environment."""
283
284
def with_scopes(credentials, scopes):
285
"""
286
Add scopes to credentials if supported.
287
288
Args:
289
credentials: OAuth2 credentials object
290
scopes (list): List of OAuth2 scopes to add
291
292
Returns:
293
Credentials with scopes applied
294
"""
295
296
def apply_credentials(credentials, headers):
297
"""
298
Apply credentials to request headers.
299
300
Args:
301
credentials: OAuth2 credentials object
302
headers (dict): HTTP headers to modify
303
"""
304
```
305
306
[Authentication Integration](./auth.md)
307
308
## Common Usage Patterns
309
310
### Service Authentication and Building
311
312
```python
313
import google.auth
314
from googleapiclient import discovery
315
316
# Application Default Credentials
317
credentials, project = google.auth.default()
318
service = discovery.build('gmail', 'v1', credentials=credentials)
319
320
# Service Account Authentication
321
from google.oauth2 import service_account
322
credentials = service_account.Credentials.from_service_account_file(
323
'path/to/service-account-key.json',
324
scopes=['https://www.googleapis.com/auth/gmail.readonly']
325
)
326
service = discovery.build('gmail', 'v1', credentials=credentials)
327
```
328
329
### Error Handling Best Practices
330
331
```python
332
from googleapiclient.errors import HttpError
333
import time
334
335
def make_request_with_retry(service, max_retries=3):
336
for attempt in range(max_retries):
337
try:
338
return service.users().messages().list(userId='me').execute()
339
except HttpError as error:
340
if error.resp.status in [500, 502, 503, 504] and attempt < max_retries - 1:
341
time.sleep(2 ** attempt) # Exponential backoff
342
continue
343
raise
344
```
345
346
### Batch Request Processing
347
348
```python
349
from googleapiclient import http
350
351
def batch_callback(request_id, response, exception):
352
if exception is not None:
353
print(f'Request {request_id} failed: {exception}')
354
else:
355
print(f'Request {request_id} succeeded: {response}')
356
357
batch = http.BatchHttpRequest(callback=batch_callback)
358
batch.add(service.users().messages().get(userId='me', id='msg1'))
359
batch.add(service.users().messages().get(userId='me', id='msg2'))
360
batch.execute()
361
```