Package googleapiclient :: Module discovery
[hide private]
[frames] | no frames]

Module discovery

source code

Client for discovery based APIs.

A client library for Google's discovery based APIs.


Author: jcgregorio@google.com (Joe Gregorio)

Classes [hide private]
  _BytesGenerator
  ResourceMethodParameters
Represents the parameters associated with a method.
  Resource
A class for interacting with a resource.
Functions [hide private]
 
fix_method_name(name)
Fix method names to avoid '$' characters and reserved word conflicts.
source code
 
key2param(key)
Converts key names into parameter names.
source code
 
build(serviceName, version, http=None, discoveryServiceUrl=DISCOVERY_URI, developerKey=None, model=None, requestBuilder=HttpRequest, credentials=None, cache_discovery=True, cache=None, client_options=None, adc_cert_path=None, adc_key_path=None, num_retries=1)
Construct a Resource for interacting with an API.
source code
 
_discovery_service_uri_options(discoveryServiceUrl, version)
Returns Discovery URIs to be used for attemnting to build the API Resource.
source code
 
_retrieve_discovery_doc(url, http, cache_discovery, cache=None, developerKey=None, num_retries=1)
Retrieves the discovery_doc from cache or the internet.
source code
 
build_from_document(service, base=None, future=None, http=None, developerKey=None, model=None, requestBuilder=HttpRequest, credentials=None, client_options=None, adc_cert_path=None, adc_key_path=None)
Create a Resource for interacting with an API.
source code
 
_cast(value, schema_type)
Convert value to a string based on JSON Schema type.
source code
 
_media_size_to_long(maxSize)
Convert a string media size, such as 10GB or 3TB into an integer.
source code
 
_media_path_url_from_info(root_desc, path_url)
Creates an absolute media path URL.
source code
 
_fix_up_parameters(method_desc, root_desc, http_method, schema)
Updates parameters of an API method with values specific to this library.
source code
 
_fix_up_media_upload(method_desc, root_desc, path_url, parameters)
Adds 'media_body' and 'media_mime_type' parameters if supported by method.
source code
 
_fix_up_method_description(method_desc, root_desc, schema)
Updates a method description in a discovery document.
source code
 
_urljoin(base, url)
Custom urljoin replacement supporting : before / in url.
source code
 
createMethod(methodName, methodDesc, rootDesc, schema)
Creates a method for attaching to a Resource.
source code
 
createNextMethod(methodName, pageTokenName="pageToken", nextPageTokenName="nextPageToken", isPageTokenParameter=True)
Creates any _next methods for attaching to a Resource.
source code
 
_findPageTokenName(fields)
Search field names for one like a page token.
source code
 
_methodProperties(methodDesc, schema, name)
Get properties of a field in a method description.
source code
Variables [hide private]
  google_auth_httplib2 = None
  logger = logging.getLogger(__name__)
  URITEMPLATE = re.compile("{[^}]*}")
  VARNAME = re.compile("[a-zA-Z0-9_-]+")
  DISCOVERY_URI = "https://www.googleapis.com/discovery/v1/apis/...
  V1_DISCOVERY_URI = "https://www.googleapis.com/discovery/v1/ap...
  V2_DISCOVERY_URI = "https://{api}.googleapis.com/$discovery/re...
  DEFAULT_METHOD_DOC = "A description of how to use this function"
  HTTP_PAYLOAD_METHODS = frozenset(["PUT", "POST", "PATCH"])
  _MEDIA_SIZE_BIT_SHIFTS = {"KB": 10, "MB": 20, "GB": 30, "TB": 40}
  BODY_PARAMETER_DEFAULT_VALUE = {"description": "The request bo...
  MEDIA_BODY_PARAMETER_DEFAULT_VALUE = {"description":("The file...
  MEDIA_MIME_TYPE_PARAMETER_DEFAULT_VALUE = {"description":("The...
  _PAGE_TOKEN_NAMES = "pageToken", "nextPageToken"
  GOOGLE_API_USE_CLIENT_CERTIFICATE = "GOOGLE_API_USE_CLIENT_CER...
  GOOGLE_API_USE_MTLS_ENDPOINT = "GOOGLE_API_USE_MTLS_ENDPOINT"
  STACK_QUERY_PARAMETERS = frozenset(["trace", "pp", "userip", "...
  STACK_QUERY_PARAMETER_DEFAULT_VALUE = {"type": "string", "loca...
  RESERVED_WORDS = frozenset(["body"])
Function Details [hide private]

fix_method_name(name)

source code 
Fix method names to avoid '$' characters and reserved word conflicts.

Args:
  name: string, method name.

Returns:
  The name with '_' appended if the name is a reserved word and '$' and '-'
  replaced with '_'.

key2param(key)

source code 
Converts key names into parameter names.

For example, converting "max-results" -> "max_results"

Args:
  key: string, the method key name.

Returns:
  A safe method name based on the key name.

build(serviceName, version, http=None, discoveryServiceUrl=DISCOVERY_URI, developerKey=None, model=None, requestBuilder=HttpRequest, credentials=None, cache_discovery=True, cache=None, client_options=None, adc_cert_path=None, adc_key_path=None, num_retries=1)

source code 
Construct a Resource for interacting with an API.

Construct a Resource object for interacting with an API. The serviceName and
version are the names from the Discovery service.

Args:
  serviceName: string, name of the service.
  version: string, the version of the service.
  http: httplib2.Http, An instance of httplib2.Http or something that acts
    like it that HTTP requests will be made through.
  discoveryServiceUrl: string, a URI Template that points to the location of
    the discovery service. It should have two parameters {api} and
    {apiVersion} that when filled in produce an absolute URI to the discovery
    document for that service.
  developerKey: string, key obtained from
    https://code.google.com/apis/console.
  model: googleapiclient.Model, converts to and from the wire format.
  requestBuilder: googleapiclient.http.HttpRequest, encapsulator for an HTTP
    request.
  credentials: oauth2client.Credentials or
    google.auth.credentials.Credentials, credentials to be used for
    authentication.
  cache_discovery: Boolean, whether or not to cache the discovery doc.
  cache: googleapiclient.discovery_cache.base.CacheBase, an optional
    cache object for the discovery documents.
  client_options: Mapping object or google.api_core.client_options, client
    options to set user options on the client.
    (1) The API endpoint should be set through client_options. If API endpoint
    is not set, `GOOGLE_API_USE_MTLS_ENDPOINT` environment variable can be used
    to control which endpoint to use.
    (2) client_cert_source is not supported, client cert should be provided using
    client_encrypted_cert_source instead. In order to use the provided client
    cert, `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable must be
    set to `true`.
    More details on the environment variables are here:
    https://google.aip.dev/auth/4114
  adc_cert_path: str, client certificate file path to save the application
    default client certificate for mTLS. This field is required if you want to
    use the default client certificate. `GOOGLE_API_USE_CLIENT_CERTIFICATE`
    environment variable must be set to `true` in order to use this field,
    otherwise this field doesn't nothing.
    More details on the environment variables are here:
    https://google.aip.dev/auth/4114
  adc_key_path: str, client encrypted private key file path to save the
    application default client encrypted private key for mTLS. This field is
    required if you want to use the default client certificate.
    `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable must be set to
    `true` in order to use this field, otherwise this field doesn't nothing.
    More details on the environment variables are here:
    https://google.aip.dev/auth/4114
  num_retries: Integer, number of times to retry discovery with
    randomized exponential backoff in case of intermittent/connection issues.

Returns:
  A Resource object with methods for interacting with the service.

Raises:
  google.auth.exceptions.MutualTLSChannelError: if there are any problems
    setting up mutual TLS channel.

Decorators:
  • @positional(2)

_discovery_service_uri_options(discoveryServiceUrl, version)

source code 

  Returns Discovery URIs to be used for attemnting to build the API Resource.

Args:
  discoveryServiceUrl:
      string, the Original Discovery Service URL preferred by the customer.
  version:
      string, API Version requested

Returns:
    A list of URIs to be tried for the Service Discovery, in order.
  

_retrieve_discovery_doc(url, http, cache_discovery, cache=None, developerKey=None, num_retries=1)

source code 
Retrieves the discovery_doc from cache or the internet.

Args:
  url: string, the URL of the discovery document.
  http: httplib2.Http, An instance of httplib2.Http or something that acts
    like it through which HTTP requests will be made.
  cache_discovery: Boolean, whether or not to cache the discovery doc.
  cache: googleapiclient.discovery_cache.base.Cache, an optional cache
    object for the discovery documents.
  developerKey: string, Key for controlling API usage, generated
    from the API Console.
  num_retries: Integer, number of times to retry discovery with
    randomized exponential backoff in case of intermittent/connection issues.

Returns:
  A unicode string representation of the discovery document.

build_from_document(service, base=None, future=None, http=None, developerKey=None, model=None, requestBuilder=HttpRequest, credentials=None, client_options=None, adc_cert_path=None, adc_key_path=None)

source code 
Create a Resource for interacting with an API.

Same as `build()`, but constructs the Resource object from a discovery
document that is it given, as opposed to retrieving one over HTTP.

Args:
  service: string or object, the JSON discovery document describing the API.
    The value passed in may either be the JSON string or the deserialized
    JSON.
  base: string, base URI for all HTTP requests, usually the discovery URI.
    This parameter is no longer used as rootUrl and servicePath are included
    within the discovery document. (deprecated)
  future: string, discovery document with future capabilities (deprecated).
  http: httplib2.Http, An instance of httplib2.Http or something that acts
    like it that HTTP requests will be made through.
  developerKey: string, Key for controlling API usage, generated
    from the API Console.
  model: Model class instance that serializes and de-serializes requests and
    responses.
  requestBuilder: Takes an http request and packages it up to be executed.
  credentials: oauth2client.Credentials or
    google.auth.credentials.Credentials, credentials to be used for
    authentication.
  client_options: Mapping object or google.api_core.client_options, client
    options to set user options on the client.
    (1) The API endpoint should be set through client_options. If API endpoint
    is not set, `GOOGLE_API_USE_MTLS_ENDPOINT` environment variable can be used
    to control which endpoint to use.
    (2) client_cert_source is not supported, client cert should be provided using
    client_encrypted_cert_source instead. In order to use the provided client
    cert, `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable must be
    set to `true`.
    More details on the environment variables are here:
    https://google.aip.dev/auth/4114
  adc_cert_path: str, client certificate file path to save the application
    default client certificate for mTLS. This field is required if you want to
    use the default client certificate. `GOOGLE_API_USE_CLIENT_CERTIFICATE`
    environment variable must be set to `true` in order to use this field,
    otherwise this field doesn't nothing.
    More details on the environment variables are here:
    https://google.aip.dev/auth/4114
  adc_key_path: str, client encrypted private key file path to save the
    application default client encrypted private key for mTLS. This field is
    required if you want to use the default client certificate.
    `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable must be set to
    `true` in order to use this field, otherwise this field doesn't nothing.
    More details on the environment variables are here:
    https://google.aip.dev/auth/4114

Returns:
  A Resource object with methods for interacting with the service.

Raises:
  google.auth.exceptions.MutualTLSChannelError: if there are any problems
    setting up mutual TLS channel.

Decorators:
  • @positional(1)

_cast(value, schema_type)

source code 
Convert value to a string based on JSON Schema type.

See http://tools.ietf.org/html/draft-zyp-json-schema-03 for more details on
JSON Schema.

Args:
  value: any, the value to convert
  schema_type: string, the type that value should be interpreted as

Returns:
  A string representation of 'value' based on the schema_type.

_media_size_to_long(maxSize)

source code 
Convert a string media size, such as 10GB or 3TB into an integer.

Args:
  maxSize: string, size as a string, such as 2MB or 7GB.

Returns:
  The size as an integer value.

_media_path_url_from_info(root_desc, path_url)

source code 
Creates an absolute media path URL.

Constructed using the API root URI and service path from the discovery
document and the relative path for the API method.

Args:
  root_desc: Dictionary; the entire original deserialized discovery document.
  path_url: String; the relative URL for the API method. Relative to the API
      root, which is specified in the discovery document.

Returns:
  String; the absolute URI for media upload for the API method.

_fix_up_parameters(method_desc, root_desc, http_method, schema)

source code 
Updates parameters of an API method with values specific to this library.

Specifically, adds whatever global parameters are specified by the API to the
parameters for the individual method. Also adds parameters which don't
appear in the discovery document, but are available to all discovery based
APIs (these are listed in STACK_QUERY_PARAMETERS).

SIDE EFFECTS: This updates the parameters dictionary object in the method
description.

Args:
  method_desc: Dictionary with metadata describing an API method. Value comes
      from the dictionary of methods stored in the 'methods' key in the
      deserialized discovery document.
  root_desc: Dictionary; the entire original deserialized discovery document.
  http_method: String; the HTTP method used to call the API method described
      in method_desc.
  schema: Object, mapping of schema names to schema descriptions.

Returns:
  The updated Dictionary stored in the 'parameters' key of the method
      description dictionary.

_fix_up_media_upload(method_desc, root_desc, path_url, parameters)

source code 
Adds 'media_body' and 'media_mime_type' parameters if supported by method.

SIDE EFFECTS: If there is a 'mediaUpload' in the method description, adds
'media_upload' key to parameters.

Args:
  method_desc: Dictionary with metadata describing an API method. Value comes
      from the dictionary of methods stored in the 'methods' key in the
      deserialized discovery document.
  root_desc: Dictionary; the entire original deserialized discovery document.
  path_url: String; the relative URL for the API method. Relative to the API
      root, which is specified in the discovery document.
  parameters: A dictionary describing method parameters for method described
      in method_desc.

Returns:
  Triple (accept, max_size, media_path_url) where:
    - accept is a list of strings representing what content types are
      accepted for media upload. Defaults to empty list if not in the
      discovery document.
    - max_size is a long representing the max size in bytes allowed for a
      media upload. Defaults to 0L if not in the discovery document.
    - media_path_url is a String; the absolute URI for media upload for the
      API method. Constructed using the API root URI and service path from
      the discovery document and the relative path for the API method. If
      media upload is not supported, this is None.

_fix_up_method_description(method_desc, root_desc, schema)

source code 
Updates a method description in a discovery document.

SIDE EFFECTS: Changes the parameters dictionary in the method description with
extra parameters which are used locally.

Args:
  method_desc: Dictionary with metadata describing an API method. Value comes
      from the dictionary of methods stored in the 'methods' key in the
      deserialized discovery document.
  root_desc: Dictionary; the entire original deserialized discovery document.
  schema: Object, mapping of schema names to schema descriptions.

Returns:
  Tuple (path_url, http_method, method_id, accept, max_size, media_path_url)
  where:
    - path_url is a String; the relative URL for the API method. Relative to
      the API root, which is specified in the discovery document.
    - http_method is a String; the HTTP method used to call the API method
      described in the method description.
    - method_id is a String; the name of the RPC method associated with the
      API method, and is in the method description in the 'id' key.
    - accept is a list of strings representing what content types are
      accepted for media upload. Defaults to empty list if not in the
      discovery document.
    - max_size is a long representing the max size in bytes allowed for a
      media upload. Defaults to 0L if not in the discovery document.
    - media_path_url is a String; the absolute URI for media upload for the
      API method. Constructed using the API root URI and service path from
      the discovery document and the relative path for the API method. If
      media upload is not supported, this is None.

createMethod(methodName, methodDesc, rootDesc, schema)

source code 
Creates a method for attaching to a Resource.

Args:
  methodName: string, name of the method to use.
  methodDesc: object, fragment of deserialized discovery document that
    describes the method.
  rootDesc: object, the entire deserialized discovery document.
  schema: object, mapping of schema names to schema descriptions.

createNextMethod(methodName, pageTokenName="pageToken", nextPageTokenName="nextPageToken", isPageTokenParameter=True)

source code 
Creates any _next methods for attaching to a Resource.

The _next methods allow for easy iteration through list() responses.

Args:
  methodName: string, name of the method to use.
  pageTokenName: string, name of request page token field.
  nextPageTokenName: string, name of response page token field.
  isPageTokenParameter: Boolean, True if request page token is a query
      parameter, False if request page token is a field of the request body.

_findPageTokenName(fields)

source code 
Search field names for one like a page token.

Args:
  fields: container of string, names of fields.

Returns:
  First name that is either 'pageToken' or 'nextPageToken' if one exists,
  otherwise None.

_methodProperties(methodDesc, schema, name)

source code 
Get properties of a field in a method description.

Args:
  methodDesc: object, fragment of deserialized discovery document that
    describes the method.
  schema: object, mapping of schema names to schema descriptions.
  name: string, name of top-level field in method description.

Returns:
  Object representing fragment of deserialized discovery document
  corresponding to 'properties' field of object corresponding to named field
  in method description, if it exists, otherwise empty dict.


Variables Details [hide private]

DISCOVERY_URI

Value:
"https://www.googleapis.com/discovery/v1/apis/" "{api}/{apiVersion}/re\
st"

V1_DISCOVERY_URI

Value:
"https://www.googleapis.com/discovery/v1/apis/" "{api}/{apiVersion}/re\
st"

V2_DISCOVERY_URI

Value:
"https://{api}.googleapis.com/$discovery/rest?" "version={apiVersion}"

BODY_PARAMETER_DEFAULT_VALUE

Value:
{"description": "The request body.", "type": "object"}

MEDIA_BODY_PARAMETER_DEFAULT_VALUE

Value:
{"description":("The filename of the media request body, or an instanc\
e " "of a MediaUpload object."), "type": "string", "required": False,}

MEDIA_MIME_TYPE_PARAMETER_DEFAULT_VALUE

Value:
{"description":("The MIME type of the media request body, or an instan\
ce " "of a MediaUpload object."), "type": "string", "required": False,\
}

GOOGLE_API_USE_CLIENT_CERTIFICATE

Value:
"GOOGLE_API_USE_CLIENT_CERTIFICATE"

STACK_QUERY_PARAMETERS

Value:
frozenset(["trace", "pp", "userip", "strict"])

STACK_QUERY_PARAMETER_DEFAULT_VALUE

Value:
{"type": "string", "location": "query"}