Building a client library

Introduction

You can use the Google APIs Discovery Service for building a variety of different tools to use with Google APIs. However, the primary purpose of the Discovery document is to allow Google to create client libraries in various programming languages. This section describes how you could go about building a custom client library for Google APIs.

A stable and feature-complete client library is a complicated tool that can take months to develop. However, the general instructions for building a simple client library for Google APIs can be broken down to three simple steps:

  1. Fetching the Discovery document and constructing API surface
  2. Composing a request
  3. Making a call and fetching the response

These steps are described in more detail in the following sections. You can also have a look at the Simple APIs client sample in the Examples section to see how these instructions map to the code.

Step 1: Fetch the Discovery document

Before you begin implementing a client library, there are some basic requirements that impact how you will proceed down your development path. For example, your programming language of choice may be either typed or untyped; if it is typed it could be either statically or dynamically typed. It may be compiled or interpreted. These requirements will guide your approach to consuming and using the Discovery document.

The first development task is to fetch the Discovery document. Your strategy for exactly when the document is to be fetched is determined by the requirements you identified. For example, in a statically-typed language, you might fetch the Discovery document early in the process and then generate code to handle the specific API described by the Discovery document. For a strongly-typed language, you might generate some code and build a compiled library. For a dynamically typed language, you can lazily construct the programming structures to interface to the API on the fly as the programming surface is used.

Step 2: Compose a request

Composing a requests involves two separate steps:

  1. Composing the request body.
  2. Constructing the request URL.

You need to convert the request body, if any, from a language-appropriate representation into the correct wire format. For example, in a Java client library, there may be a class for each request type that allows type-safe manipulation of the request data and is serializable into JSON.

The construction of the request URL is a slightly more complicated process.

The path property of each method in the API uses URI Template v04 syntax. This property may contain variables, which are surrounded by curly braces. Here is an example of a path property with variables:

/example/path/var

In the path above, var is a variable. The value for this variable comes from the Discovery document’s parameters section for that method. Each variable name has a corresponding value in the parameters object. In the example above, there is a parameter named var in the parameters section (and its location property is path, to indicate that it is a path variable).

When making a request, you should substitute the value for var into the URL. For example, if the user of the library makes a choice that sets var to the value foo, the new URL will be /example/path/foo.

Also note that the path property is a relative URI. In order to calculate the absolute URI, follow these steps:

  1. Grab the rootUrl property from the top level of the Discovery document.
    For example, the rootUrl property in the Discovery document for URL Shortener is:

    https://www.googleapis.com/

  2. Grab the servicePath from the top level of the Discovery document.
    For example, the servicePath property in the Discovery document for URL Shortener is:

    urlshortener/v1/

  3. Concatenate them together to get:

    https://www.googleapis.com/urlshortener/v1/

  4. Grab the path property, expand it as a URI Template, and combine the results of that expansion with the URI from the previous step.
    For example, in URL Shortener's get method, the value of the path property is url. So, the full URI for the method is:

    https://www.googleapis.com/urlshortener/v1/url

Step 3: Make a call and handle the response

After you send the request, the you need to deserialize the response into the appropriate language representation, taking care to handle error conditions that could occur — both in the underlying HTTP transport and error messages generated from the API service. The format of the errors is documented as part of the Google JSON Style Guide.

Examples

For some concrete examples of client libraries and tools that have been implemented using Google APIs Discovery Service, see the Libraries and Samples document. In addition, the following section gives a simple example of an APIs client library.

Simple APIs client

Below is an example of a very simple client library written in Python. The client builds an interface for interacting with the Google URL Shortener API, then shortens a URL using that interface.

Warning: the code below is a significally simplified version of a typical client library. It is an incomplete implementation that is provided to demonstrate some aspects of building a client library. It is not production-ready code.

import httplib2
import json
import uritemplate
import urllib
import urlparse

# Step 1: Fetch Discovery document
DISCOVERY_URI = "https://www.googleapis.com/discovery/v1/apis/urlshortener/v1/rest"
h = httplib2.Http()
resp, content = h.request(DISCOVERY_URI)
discovery = json.loads(content)

# Step 2.a: Construct base URI
BASE_URL = discovery['rootUrl'] + discovery['servicePath']

class Collection(object): pass

def createNewMethod(name, method):
  # Step 2.b Compose request
  def newMethod(**kwargs):
    body = kwargs.pop('body', None)
    url = urlparse.urljoin(BASE_URL, uritemplate.expand(method['path'], kwargs))
    for pname, pconfig in method.get('parameters', {}).iteritems():
      if pconfig['location'] == 'path' and pname in kwargs:
        del kwargs[pname]
    if kwargs:
      url = url + '?' + urllib.urlencode(kwargs)
    return h.request(url, method=method['httpMethod'], body=body,
                     headers={'content-type': 'application/json'})

  return newMethod

# Step 3.a: Build client surface
def build(discovery, collection):
  for name, resource in discovery.get('resources', {}).iteritems():
    setattr(collection, name, build(resource, Collection()))
  for name, method in discovery.get('methods', {}).iteritems():
    setattr(collection, name, createNewMethod(name, method))
  return collection

# Step 3.b: Use the client
service = build(discovery, Collection())
print service.url.insert(body='{"longUrl": "http://www.google.com/"}')

The key components of the client are:

  • Step 1: Fetch the Discovery document.
    The Discovery document for the Google URL Shortener API is retrieved and parsed into a data structure. Since Python is a dynamically typed language, the Discovery document can be fetched at runtime.
  • Step 2.a: Construct the base URI.
    The base URI is calculated.
  • Step 2.b: Compose the request.
    When a method is called on a collection the URI Template is expanded with the parameters passed into the method, and parameters with a location of query are put into the query parameters of the URL. Finally a request is sent to the composed URL using the HTTP method specified in the Discovery document.
  • Step 3.a: Build the client surface.
    The client surface is built by recursively descending over the parsed Discovery document. For each method in the methods section a new method is attached to the Collection object. Because collections can be nested we look for resources and recursively build a Collection object for all of its members if one is found. Each nested collection is also attached as an attribute to the Collection object.
  • Step 3.b: Use the client.
    This demonstrates how the built API surface is used. First a service object is built from the Discovery document, then a new URL is shortened via Google URL Shortener API by inserting a long URL into the url collection.