### Complete OAuth 2.0 installed app example for Google Drive Source: https://googleapis.github.io/google-api-python-client/docs/oauth-installed.html Complete example for OAuth 2.0 installed app flow. It uses InstalledAppFlow.from_client_secrets_file with a client_secret.json file and the drive.metadata.readonly scope. The flow.run_console() method prompts the user to authorize, then the code lists the five most recently modified Drive files. Note the local-only OAUTHLIB_INSECURE_TRANSPORT environment variable setting. ```python import os import pprint import google.oauth2.credentials from googleapiclient.discovery import build from googleapiclient.errors import HttpError from google_auth_oauthlib.flow import InstalledAppFlow pp = pprint.PrettyPrinter(indent=2) # The CLIENT_SECRETS_FILE variable specifies the name of a file that contains # the OAuth 2.0 information for this application, including its client_id and # client_secret. CLIENT_SECRETS_FILE = "client_secret.json" # This access scope grants read-only access to the authenticated user's Drive # account. SCOPES = ['https://www.googleapis.com/auth/drive.metadata.readonly'] API_SERVICE_NAME = 'drive' API_VERSION = 'v3' def get_authenticated_service(): flow = InstalledAppFlow.from_client_secrets_file(CLIENT_SECRETS_FILE, SCOPES) credentials = flow.run_console() return build(API_SERVICE_NAME, API_VERSION, credentials = credentials) def list_drive_files(service, **kwargs): results = service.files().list( **kwargs ).execute() pp.pprint(results) if __name__ == '__main__': # When running locally, disable OAuthlib's HTTPs verification. When # running in production *do not* leave this option enabled. os.environ['OAUTHLIB_INSECURE_TRANSPORT'] = '1' service = get_authenticated_service() list_drive_files(service, orderBy='modifiedByMeTime desc', pageSize=5) ``` -------------------------------- ### MediaFileUpload usage example Source: https://googleapis.github.io/google-api-python-client/docs/epy/googleapiclient.http.MediaFileUpload-class.html Example of constructing a MediaFileUpload and using it as the media_body parameter for an API call. ```python media = MediaFileUpload('cow.png', mimetype='image/png', chunksize=1024*1024, resumable=True) farm.animals().insert( id='cow', name='cow.png', media_body=media).execute() ``` -------------------------------- ### Complete example: print Cloud SQL instances Source: https://googleapis.github.io/google-api-python-client/docs/oauth-server.html A complete example that authenticates with a service account file, builds the service object, lists instances in a project, and prints the JSON-formatted response. ```python from google.oauth2 import service_account import googleapiclient.discovery SCOPES = ['https://www.googleapis.com/auth/sqlservice.admin'] SERVICE_ACCOUNT_FILE = '/path/to/service.json' credentials = service_account.Credentials.from_service_account_file( SERVICE_ACCOUNT_FILE, scopes=SCOPES) sqladmin = googleapiclient.discovery.build('sqladmin', 'v1beta3', credentials=credentials) response = sqladmin.instances().list(project='exemplary-example-123').execute() print(response) ``` -------------------------------- ### MediaIoBaseDownload class definition and usage example Source: https://googleapis.github.io/google-api-python-client/docs/epy/googleapiclient.http-pysrc.html Downloads media resources in chunks. The example shows creating a request, opening a file handle, and looping over next_chunk() until done, printing progress. ```python class MediaIoBaseDownload(object): """"Download media resources. Note that the Python file object is compatible with io.Base and can be used with this class also. Example: request = farms.animals().get_media(id='cow') fh = io.FileIO('cow.png', mode='wb') downloader = MediaIoBaseDownload(fh, request, chunksize=1024*1024) done = False while done is False: status, done = downloader.next_chunk() if status: print "Download %d%%." % int(status.progress() * 100) print "Download Complete!" """ @util.positional(3) def __init__(self, fd, request, chunksize=DEFAULT_CHUNK_SIZE): """Constructor. Args: fd: io.Base or file object, The stream in which to write the downloaded bytes. request: googleapiclient.http.HttpRequest, the media request to perform in chunks. chunksize: int, File will be downloaded in chunks of this many bytes. """ self._fd = fd self._request = request self._uri = request.uri self._chunksize = chunksize self._progress = 0 self._total_size = None self._done = False # Stubs for testing. self._sleep = time.sleep self._rand = random.random self._headers = {} for k, v in six.iteritems(request.headers): # allow users to supply custom headers by setting them on the request # but strip out the ones that are set by default on requests generated by # API methods like Drive's files().get(fileId=...) if not k.lower() in ("accept", "accept-encoding", "user-agent"): self._headers[k] = v @util.positional(1) def next_chunk(self, num_retries=0): ``` -------------------------------- ### client_secrets.json for Installed Application Source: https://googleapis.github.io/google-api-python-client/docs/client-secrets.html Example client_secrets.json file for an installed application. Contains the mandatory members: client_id, client_secret, redirect_uris, auth_uri, and token_uri. ```json { "installed": { "client_id": "837647042410-75ifg...usercontent.com", "client_secret":"asdlkfjaskd", "redirect_uris": ["http://localhost", "urn:ietf:wg:oauth:2.0:oob"], "auth_uri": "https://accounts.google.com/o/oauth2/auth", "token_uri": "https://accounts.google.com/o/oauth2/token" } } ``` -------------------------------- ### Install required libraries for OAuth 2.0 Source: https://googleapis.github.io/google-api-python-client/docs/oauth-server.html Install the necessary Python libraries for using OAuth 2.0 with Google APIs. ```bash pip install google-auth google-auth-httplib2 google-api-python-client ``` -------------------------------- ### Run local server flow to get credentials Source: https://googleapis.github.io/google-api-python-client/docs/oauth-installed.html Opens the authorization URL in the user's browser and starts a local web server to listen for the authorization response. After the user completes the flow, the server exchanges the code for an access token. ```python credentials = flow.run_local_server(host='localhost', port=8080, authorization_prompt_message='Please visit this URL: {url}', success_message='The auth flow is complete; you may close this window.', open_browser=True) ``` -------------------------------- ### MediaIoBaseUpload Source: https://googleapis.github.io/google-api-python-client/docs/epy/googleapiclient.http.MediaIoBaseUpload-class.html Documentation for the MediaIoBaseUpload class, including its constructor, methods, and usage example. ```APIDOC ## Class MediaIoBaseUpload ### Description A MediaUpload for io.Base objects. It allows uploading data from a file-like object (such as BytesIO) to Google APIs, supporting both resumable and single-request uploads. ### Constructor #### `__init__(fd, mimetype, chunksize=None, resumable=None)` - **fd** (io.Base or file object) - Required - The source of the bytes to upload. Must be opened in blocking mode and be seekable. - **mimetype** (string) - Required - Mime-type of the file. - **chunksize** (int) - Optional - File will be uploaded in chunks of this many bytes. Only used if resumable=True. Pass -1 to upload as a single chunk. Note: Google App Engine has a 5MB limit on request size. - **resumable** (bool) - Optional - True if this is a resumable upload. False means upload in a single request. ### Methods #### `chunksize()` Returns the chunk size for resumable uploads. - **Returns**: int - Chunk size in bytes. #### `mimetype()` Returns the mime type of the body. - **Returns**: string - Mime type. #### `size()` Returns the size of the upload. - **Returns**: int or None - Size of the body, or None if the size is unknown. #### `resumable()` Returns whether this upload is resumable. - **Returns**: bool - True if resumable upload, False otherwise. #### `getbytes(begin, length)` Get bytes from the media. - **begin** (int) - Required - Offset from beginning of file. - **length** (int) - Required - Number of bytes to read, starting at begin. - **Returns**: string - A string of bytes read. May be shorter than length if EOF was reached first. #### `has_stream()` Does the underlying upload support a streaming interface. - **Returns**: bool - True if the call to stream() will return an instance of a seekable io.Base subclass. #### `stream()` A stream interface to the data being uploaded. - **Returns**: io.IOBase - An io.IOBase subclass that supports seek. #### `to_json()` This upload type is not serializable. ### Example Usage ```python from io import BytesIO from googleapiclient.http import MediaIoBaseUpload fh = BytesIO(b'...Some data to upload...') media = MediaIoBaseUpload(fh, mimetype='image/png', chunksize=1024*1024, resumable=True) # Use media in an API call, e.g., farm.animals().insert(media_body=media).execute() ``` ``` -------------------------------- ### List Cloud SQL instances using the service object Source: https://googleapis.github.io/google-api-python-client/docs/oauth-server.html Make a request to the API service using the interface provided by the service object. This example lists instances in the 'example-123' project by calling instances().list() and executing the request. ```python response = sqladmin.instances().list(project='example-123').execute() ``` -------------------------------- ### Run console flow to get credentials Source: https://googleapis.github.io/google-api-python-client/docs/oauth-installed.html Instructs the user to open the authorization URL in their browser, then paste the authorization code back into the application. The library automatically exchanges the code for an access token. ```python credentials = flow.run_console() ``` -------------------------------- ### InstalledAppFlow: from_client_secrets_file and run_local_server Source: https://googleapis.github.io/google-api-python-client/docs/oauth.html Use for installed applications (local development or desktop). Creates a flow from a client secrets file and runs a local server to complete the OAuth 2.0 authorization flow. ```python from google_auth_oauthlib.flow import InstalledAppFlow flow = InstalledAppFlow.from_client_secrets_file( 'client_secrets.json', scopes=['profile', 'email']) flow.run_local_server() ``` -------------------------------- ### InstalledAppFlow.from_client_secrets_file() Source: https://googleapis.github.io/google-api-python-client/docs/oauth.html Creates an InstalledAppFlow instance from a client secrets file for installed applications. This flow is useful for local development or desktop applications. ```APIDOC ## [InstalledAppFlow] from_client_secrets_file() ### Description Creates an InstalledAppFlow instance from a client secrets file for installed applications. This flow is useful for local development or desktop applications. ### Method from_client_secrets_file() ### Parameters - **client_secrets_file** (string) - Required - Path to the client secrets JSON file. - **scopes** (list of strings) - Required - List of OAuth 2.0 scopes to request. ### Request Example ```python from google_auth_oauthlib.flow import InstalledAppFlow flow = InstalledAppFlow.from_client_secrets_file( 'client_secrets.json', scopes=['profile', 'email']) ``` ### Response Returns an InstalledAppFlow object. ### Response Example ```python flow = InstalledAppFlow.from_client_secrets_file( 'client_secrets.json', scopes=['profile', 'email']) ``` ``` -------------------------------- ### HttpMockSequence usage example Source: https://googleapis.github.io/google-api-python-client/docs/epy/googleapiclient.http.HttpMockSequence-class.html Shows how to instantiate HttpMockSequence with a list of (headers, body) pairs and use it as an httplib2.Http instance. Special content values like 'echo_request_headers', 'echo_request_headers_as_json', 'echo_request_body', and 'echo_request_uri' trigger testing behaviors. ```python Mock of httplib2.Http Mocks a sequence of calls to request returning different responses for each call. Create an instance initialized with the desired response headers and content and then use as if an httplib2.Http instance. http = HttpMockSequence([ ({'status': '401'}, ''), ({'status': '200'}, '{"access_token":"1/3w","expires_in":3600}'), ({'status': '200'}, 'echo_request_headers'), ]) resp, content = http.request("http://examples.com") There are special values you can pass in for content to trigger behaviours that are helpful in testing. 'echo_request_headers' means return the request headers in the response body 'echo_request_headers_as_json' means return the request headers in the response body 'echo_request_body' means return the request body in the response body 'echo_request_uri' means return the request uri in the response body ``` -------------------------------- ### Flow.authorization_url() Source: https://googleapis.github.io/google-api-python-client/docs/oauth.html Generates the authorization server URI. Redirect the user to this URI to start the authorization process. If the user has previously granted access, the server redirects immediately to redirect_uri; otherwise it asks for consent. ```python auth_uri = flow.authorization_url() # Redirect the user to auth_uri on your platform. ``` -------------------------------- ### Execute a request and handle HttpError Source: https://googleapis.github.io/google-api-python-client/docs/start.html Execute a request and handle errors. The first example shows a try/except block that catches `HttpError` and prints the status code and error details. The second combines building the service, creating a request, and executing it in a single line. ```python try: response = request.execute() except HttpError as e: print('Error response status code : {0}, reason : {1}'.format(e.status_code, e.error_details)) ``` ```python response = service.stamps().list(cents=5).execute() ``` -------------------------------- ### BatchHttpRequest usage example from docstring Source: https://googleapis.github.io/google-api-python-client/docs/epy/googleapiclient.http-pysrc.html Shows how to use BatchHttpRequest to batch multiple API calls. It defines callback functions for handling responses and exceptions, creates a batch, adds requests, and executes them with a shared HTTP object. ```python from googleapiclient.http import BatchHttpRequest def list_animals(request_id, response, exception): """Do something with the animals list response.""" if exception is not None: # Do something with the exception. pass else: # Do something with the response. pass def list_farmers(request_id, response, exception): """Do something with the farmers list response.""" if exception is not None: # Do something with the exception. pass else: # Do something with the response. pass service = build('farm', 'v2') batch = BatchHttpRequest() batch.add(service.animals().list(), list_animals) batch.add(service.farmers().list(), list_farmers) batch.execute(http=http) ``` -------------------------------- ### Build a service object with build() and close it Source: https://googleapis.github.io/google-api-python-client/docs/start.html Build a service object for the Drive API v3. The first example closes the service explicitly with `service.close()`, while the second uses a context manager to automatically close it. Both are necessary to avoid leaving sockets open because httplib2 makes connections persistent by default. ```python from googleapiclient.discovery import build service = build('drive', 'v3') # ... service.close() ``` ```python from googleapiclient.discovery import build with build('drive', 'v3') as service: # ... ``` -------------------------------- ### Simulate a sequence of HTTP responses with HttpMockSequence Source: https://googleapis.github.io/google-api-python-client/docs/mocks.html Simulates a sequence of HTTP responses using HttpMockSequence. The mock returns the discovery document first, then the result of the 'android' query. The content objects can be file references, inline JSON-like structures, or special keywords like echo_request_headers. The example combines the two HTTP call simulations from the previous snippet into a single mock object. ```python from googleapiclient.discovery import build from googleapiclient.http import HttpMockSequence books_discovery = # Saved data from a build response books_android = # Saved data from a request to list android volumes http = HttpMockSequence([ ({'status': '200'}, books_discovery), ({'status': '200'}, books_android)]) api_key = 'your_api_key' service = build('books', 'v1', http=http, developerKey=your_api_key) request = service.volumes().list(source='public', q='android') response = request.execute() ``` -------------------------------- ### MediaFileUpload.__init__ Source: https://googleapis.github.io/google-api-python-client/docs/epy/googleapiclient.http.MediaFileUpload-class.html Constructor for MediaFileUpload. Initializes the upload with a filename, optional mimetype, chunksize, and resumable flag. ```APIDOC ## MediaFileUpload.__init__ ### Description Constructor for MediaFileUpload. Initializes the upload with a filename, optional mimetype, chunksize, and resumable flag. ### Method Constructor ### Parameters - **filename** (string) - Required - Name of the file. - **mimetype** (string) - Optional - Mime-type of the file. If None then a mime-type will be guessed from the file extension. - **chunksize** (int) - Optional - File will be uploaded in chunks of this many bytes. Only used if resumable=True. Pass in a value of -1 if the file is to be uploaded in a single chunk. Note that Google App Engine has a 5MB limit on request size, so you should never set your chunksize larger than 5MB, or to -1. - **resumable** (bool) - Optional - True if this is a resumable upload. False means upload in a single request. ### Request Example ```python media = MediaFileUpload('cow.png', mimetype='image/png', chunksize=1024*1024, resumable=True) ``` ### Response No return value. ``` -------------------------------- ### Create Flow for Installed App Source: https://googleapis.github.io/google-api-python-client/docs/client-secrets.html Creates a Flow object for an installed application using the InstalledAppFlow class and a client_secrets.json file. The scopes parameter specifies the required OAuth 2.0 scopes. ```python from google_auth_oauthlib.flow import InstalledAppFlow ... flow = InstalledAppFlow.from_client_secrets_file( 'path_to_directory/client_secret.json', scopes=['https://www.googleapis.com/auth/calendar']) ``` -------------------------------- ### Create credentials from service account file Source: https://googleapis.github.io/google-api-python-client/docs/oauth-server.html Create a Credentials object from a service account key file using service_account.Credentials.from_service_account_file(). ```python from google.oauth2 import service_account SCOPES = ['https://www.googleapis.com/auth/sqlservice.admin'] SERVICE_ACCOUNT_FILE = '/path/to/service.json' credentials = service_account.Credentials.from_service_account_file( SERVICE_ACCOUNT_FILE, scopes=SCOPES) ``` -------------------------------- ### get_credentials_from_http(http) Source: https://googleapis.github.io/google-api-python-client/docs/epy/googleapiclient._auth-module.html Gets credentials from an HTTP client. ```APIDOC ## get_credentials_from_http(http) ### Description Gets credentials from an HTTP client. ### Method Function ### Signature get_credentials_from_http(http) ### Parameters - **http** - Required - The HTTP client. ``` -------------------------------- ### HttpMockSequence __init__ arguments Source: https://googleapis.github.io/google-api-python-client/docs/epy/googleapiclient.http.HttpMockSequence-class.html Constructor documentation for HttpMockSequence.__init__, which takes an iterable of (headers, body) pairs. ```text Args: iterable: iterable, a sequence of pairs of (headers, body) ``` -------------------------------- ### build_http timeout override example Source: https://googleapis.github.io/google-api-python-client/docs/epy/googleapiclient.http-module.html Shows how to override the default timeout for the httplib2.Http object built by build_http(). Call socket.setdefaulttimeout before interacting with build_http(). ```python socket.setdefaulttimeout(timeout_in_sec) ``` -------------------------------- ### Use user credentials with InstalledAppFlow and build Source: https://googleapis.github.io/google-api-python-client/docs/oauth.html Obtains user credentials via an installed-app flow, runs a local server for authorization, and passes the credentials to the build function. Optionally retrieves and prints the authenticated user's email. ```python from google_auth_oauthlib.flow import InstalledAppFlow from googleapiclient.discovery import build flow = InstalledAppFlow.from_client_secrets_file( 'client_secrets.json', scopes=['openid', 'https://www.googleapis.com/auth/userinfo.email', 'https://www.googleapis.com/auth/userinfo.profile']) flow.run_local_server() credentials = flow.credentials service = build('calendar', 'v3', credentials=credentials) # Optionally, view the email address of the authenticated user. user_info_service = build('oauth2', 'v2', credentials=credentials) user_info = user_info_service.userinfo().get().execute() print(user_info['email']) ``` -------------------------------- ### MediaInMemoryUpload.__init__(*args, **kwargs) Source: https://googleapis.github.io/google-api-python-client/docs/epy/googleapiclient.http.MediaInMemoryUpload-class.html Constructor for MediaInMemoryUpload. Creates a new media upload from a chunk of bytes. Deprecated: use MediaIoBaseUpload with io.TextIOBase or StringIO. ```APIDOC ## MediaInMemoryUpload.__init__(*args, **kwargs) ### Description Create a new MediaInMemoryUpload. Deprecated: Use MediaIoBaseUpload with either io.TextIOBase or StringIO for the stream. ### Method Constructor ### Signature `__init__(*args, **kwargs)` ### Parameters - **body** (string) - Required - Bytes of body content. - **mimetype** (string) - Optional - Mime-type of the file or default of 'application/octet-stream'. - **chunksize** (int) - Optional - File will be uploaded in chunks of this many bytes. Only used if resumable=True. - **resumable** (bool) - Optional - True if this is a resumable upload. False means upload in a single request. ### Decorators - `@util.positional(2)` ### Overrides - object.__init__ ### Inherited Methods - From MediaIoBaseUpload: `chunksize`, `getbytes`, `has_stream`, `mimetype`, `resumable`, `size`, `stream`, `to_json` - From MediaUpload: `new_from_json` (class method) ``` -------------------------------- ### client_secrets.json for Web Application Source: https://googleapis.github.io/google-api-python-client/docs/client-secrets.html Example client_secrets.json file for a web application. Contains the mandatory members: client_id, client_secret, redirect_uris, auth_uri, and token_uri. ```json { "web": { "client_id": "asdfjasdljfasdkjf", "client_secret": "1912308409123890", "redirect_uris": ["https://www.example.com/oauth2callback"], "auth_uri": "https://accounts.google.com/o/oauth2/auth", "token_uri": "https://accounts.google.com/o/oauth2/token" } } ``` -------------------------------- ### set_user_agent example Source: https://googleapis.github.io/google-api-python-client/docs/epy/googleapiclient.http-module.html Shows how to set a custom user-agent on an httplib2.Http instance. The function returns the modified http object. Typically user-agent is set during auth, but this is for unauthenticated endpoints. ```python h = httplib2.Http() h = set_user_agent(h, "my-app-name/6.0") ``` -------------------------------- ### Use Application Default Credentials Source: https://googleapis.github.io/google-api-python-client/docs/oauth-server.html Automatically determine credentials from the environment using google.auth.default(). Works on Google Cloud hosting or locally with Google Cloud SDK installed. ```python import google.auth SCOPES = ['https://www.googleapis.com/auth/sqlservice.admin'] credentials, project = google.auth.default(scopes=SCOPES) ``` -------------------------------- ### Build a service object for Cloud SQL Administration API Source: https://googleapis.github.io/google-api-python-client/docs/oauth-server.html Use googleapiclient.discovery.build to create a service object for the 'sqladmin' API version 'v1beta3', passing the authorized credentials. This is the first step to call a Google API. ```python import googleapiclient.discovery sqladmin = googleapiclient.discovery.build('sqladmin', 'v1beta3', credentials=credentials) ``` -------------------------------- ### MediaFileUpload constructor docstring Source: https://googleapis.github.io/google-api-python-client/docs/epy/googleapiclient.http.MediaFileUpload-class.html Docstring for the MediaFileUpload constructor, describing the parameters: filename, mimetype, chunksize, and resumable. ```text Constructor. Args: filename: string, Name of the file. mimetype: string, Mime-type of the file. If None then a mime-type will be guessed from the file extension. chunksize: int, File will be uploaded in chunks of this many bytes. Only used if resumable=True. Pass in a value of -1 if the file is to be uploaded in a single chunk. Note that Google App Engine has a 5MB limit on request size, so you should never set your chunksize larger than 5MB, or to -1. resumable: bool, True if this is a resumable upload. False means upload in a single request. ``` -------------------------------- ### Media Upload with media_body Source: https://googleapis.github.io/google-api-python-client/docs/media.html Demonstrates how to use the media_body parameter to upload a file with an API method call. ```APIDOC ## [POST] farm.animals().insert ### Description Adds an animal to the farm. Supports uploading a media file (e.g., an image) along with the request body. ### Method POST ### Endpoint farm.animals().insert ### Parameters #### Request Body - **body** (object) - Required - The request body. - **media_body** (string or MediaUpload) - Optional - Picture of the animal. Can be a filename string or a MediaUpload object. ### Request Example ```python response = farm.animals().insert(media_body='pig.png', body={'name': 'Pig'}).execute() ``` ### Response #### Success Response (200) - **response** (object) - The response object created once the upload is complete. #### Response Example ```python response = farm.animals().insert(media_body='pig.png', body={'name': 'Pig'}).execute() ``` ``` -------------------------------- ### Notification.__init__(*args, **kwargs) Source: https://googleapis.github.io/google-api-python-client/docs/epy/googleapiclient.channel.Notification-class.html Constructor for the Notification class. It initializes a Notification object with the provided message number, state, resource URI, and resource ID. ```APIDOC ## Notification.__init__(*args, **kwargs) ### Description Constructor for a Notification object. Notifications are not usually constructed directly, but are returned from functions like notification_from_headers(). ### Method Constructor ### Parameters - **message_number** (int) - Required - The unique id number of this notification. - **state** (str) - Required - The state of the resource being monitored. Can be one of "exists", "not_exists", or "sync". - **resource_uri** (str) - Required - The address of the resource being monitored. - **resource_id** (str) - Required - The identifier of the watched resource. ### Decorators - @util.positional(5) ### Overrides - object.__init__ ``` -------------------------------- ### credentials_from_file(filename, scopes=None, quota_project_id=None) Source: https://googleapis.github.io/google-api-python-client/docs/epy/googleapiclient._auth-module.html Loads credentials from a file. ```APIDOC ## credentials_from_file(filename, scopes=None, quota_project_id=None) ### Description Returns credentials loaded from a file. ### Method Function ### Signature credentials_from_file(filename, scopes=None, quota_project_id=None) ### Parameters - **filename** (str) - Required - The path to the credentials file. - **scopes** (Sequence[str]) - Optional - The list of scopes. - **quota_project_id** (str) - Optional - The quota project ID. ### Returns Credentials object loaded from the file. ``` -------------------------------- ### Print and access response JSON Source: https://googleapis.github.io/google-api-python-client/docs/start.html Work with the JSON response. The first block prints the response as pretty-printed JSON. The second shows an example of the printed JSON structure. The third accesses specific fields from the response object. ```python import json ... print(json.dumps(response, sort_keys=True, indent=4)) ``` ```json { "count": 2, "items": [ { "cents": 5, "name": "#586 1923-26 5-cent blue Theodore Roosevelt MLH perf 10" }, { "cents": 5, "name": "#628 1926 5-cent Ericsson Memorial MLH" } ] } ``` ```python print('Num 5 cent stamps: %d'.format(response['count'])) print('First stamp name: %s'.format(response['items'][0]['name'])) ``` -------------------------------- ### HttpMock.__init__(filename=None, headers=None) Source: https://googleapis.github.io/google-api-python-client/docs/epy/googleapiclient.http.HttpMock-class.html Constructor for the HttpMock class, which mocks httplib2.Http. It reads response data from a file and optionally sets headers to return with the response. ```APIDOC ## HttpMock.__init__(filename=None, headers=None) ### Description Constructor for the HttpMock class. Initializes a mock HTTP object that reads responses from a file. ### Method Constructor ### Parameters - **filename** (string) - Optional - Absolute filename to read response from - **headers** (dict) - Optional - Header to return with response ### Request Example ```python mock = HttpMock(filename='response.json', headers={'Content-Type': 'application/json'}) ``` ``` -------------------------------- ### Create collection objects: service.stamps() and nested Source: https://googleapis.github.io/google-api-python-client/docs/start.html Create a collection object from a service. The first example accesses a top-level collection named `stamps`. The second shows nested collections, where `featured()` returns a collection that itself has a `stamps()` method. ```python collection = service.stamps() ``` ```python nested_collection = service.featured().stamps() ```