|
GettingStarted
Getting started using the library
Featured IntroductionThis is an overview of the library, how it works, and how the pieces fit together. Let's look at the Moderator sample. This code creates a new Series in Moderator using the Google Moderator API: FLOW = OAuth2WebServerFlow(
client_id='433807057907.apps.googleusercontent.com',
client_secret='jigtZpMApkRxncxikFpR+SFg',
scope='https://www.googleapis.com/auth/moderator',
user_agent='moderator-cmdline-sample/1.0')
gflags.DEFINE_enum('logging_level', 'ERROR',
['DEBUG', 'INFO', 'WARNING', 'ERROR', 'CRITICAL'],
'Set the level of logging detail.')
def main(argv):
try:
argv = FLAGS(argv)
except gflags.FlagsError, e:
print '%s\\nUsage: %s ARGS\\n%s' % (e, argv[0], FLAGS)
sys.exit(1)
logging.getLogger().setLevel(getattr(logging, FLAGS.logging_level))
storage = Storage('moderator.dat')
credentials = storage.get()
if credentials is None or credentials.invalid == True:
credentials = run(FLOW, storage)
http = httplib2.Http(cache=".cache")
http = credentials.authorize(http)
service = build("moderator", "v1", http=http)
series_body = {
"description": "Share and rank tips for eating healthy and cheap!",
"name": "Eating Healthy & Cheap",
"videoSubmissionAllowed": False
}
series = service.series().insert(body=series_body).execute()
print "Created a new series"
# ...
if __name__ == '__main__':
main(sys.argv)WalkthroughLet's look at the code in detail. AuthorizationFirst, we must construct an httplib2.Http() object that we will use to talk the HTTP protocol. Since the Moderator API is protected with authentication we will need to authorize that object with some Credentials. The call to credentials.authorize() modifies the httplib2.Http() object so that it can sign HTTP request with OAuth credentials. See the HowAuthenticationWorks for more details on Credentials, Flows and Storage. Here is the same code with just the authentication pieces: Note: Some APIs don't require per-user authorization but do require the use of a developer key. See the Developer Key documentation. FLOW = OAuth2WebServerFlow(
client_id='433807057907.apps.googleusercontent.com',
client_secret='jigtZpMApkRxncxikFpR+SFg',
scope='https://www.googleapis.com/auth/moderator',
user_agent='moderator-cmdline-sample/1.0')
def main(argv):
storage = Storage('moderator.dat')
credentials = storage.get()
if credentials is None or credentials.invalid == True:
credentials = run(FLOW, storage)
http = httplib2.Http(cache=".cache")
http = credentials.authorize(http)Constructing a ServiceNext we build a service object by calling apiclient.discovery.build. We pass in the name of the API we want to use and the version number along with our authorized http object and the build method will construct a service object that knows how to talk to that API. service = build("moderator", "v1", http=http)Collections and MethodsNow that we have a service object we can add a new series. All of the functionality of a service is broken down into collections. For example, the Moderator API has collections for series, topics, votes and responses. To get to the series collection we call service.series(). The collection object that is returned has all the methods that a collection understands. In this case we want the insert() method which adds new items to the series collection. We construct the item we want to add to the collection and pass that in as the body. The call service.series().insert() doesn't take any action; what it does do is construct an HttpRequest object that encapsulates all the information needed to make the request. If you want to execute the request immediately just call execute() as is done in the example below. You can also gather up a set of HttpRequest objects and execute them asynchronously. See the threadqueue sample for how to process such requests using a thread pool. Finally the return from the execute() is a Python object built from the JSON response if the call was successful. If there was a problem then an exception of type apiclient.Error will be raised. series_body = {
"description": "Share and rank tips for eating healthy and cheap!",
"name": "Eating Healthy & Cheap",
"videoSubmissionAllowed": False
}
series = service.series().insert(body=series_body).execute()
print "Created a new series"DocumentationThe client library is structured to be used in an interactive Python shell to make it easy to explore APIs. You can construct a service object for the API you are interested in and call help on the objects you construct. From the command-line start Python: $ python
Python 2.6.5 (r265:79063, Apr 16 2010, 13:57:41)
[GCC 4.4.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> from apiclient.discovery import build
>>> service = build("prediction", "v1")Get help on the service, or a collection, or a method on a collection: >>> help(service) >>> help(service.training()) >>> help(service.training().insert) In addition you can use the API Client Documentation web application to navigate the documentation for each API. Reading the documentationHere is an example page from that documentation for the Series collection in the Moderator API. This collection has four methods, get, insert, list and update that operate on that collection. It also has sub-collections responses and submissions. Help on Resource in module apiclient.discovery object: For each method the arguments are listed along with their type and a sentence that describes what the argument does. For example, the update method has seriesId and body arguments. The (required) means that the argument must be supplied when calling the method, otherwise an argument is optional. | update = method(self, **kwargs) | Updates the specified series. | | Args: | seriesId: integer, The decimal ID of the Series. (required) | body: object, The request body. (required) Method arguments may also be flagged as (repeated) which means that you may pass in an array of values for that argument. For example, the q argument to the list method in the Google Translate API is repeated: | list = method(self, **kwargs) | Returns text translations from one language to another. | | Args: | q: string, The text to translate (required) (repeated) | source: string, The source language of the text | target: string, The target language into which the text should be translated (required) | format: string, The format of the text | Allowed values | html - Specifies the input is in HTML | text - Specifies the input is in plain textual format It can be called as: def main():
service = build('translate', 'v2',
developerKey='AIzaSyDRRpR3GS1F1_jKNNM9HCNd2wJQyPG3oN0')
service.translations().list(
source='en',
target='fr',
q=['flower', 'car']
).execute()
| |