This codelab introduces you to using G Suite (REST/HTTP) APIs. The example will be done in Python for brevity and wide availability, but you can also choose to use your favorite development language. You'll learn how to use the developer console to create and manage projects, including obtaining the credentials you'll need in your app. With the formalities taken care of, you'll write an app to display the first 100 files & folders in your Google Drive by using the Drive API.
In this codelab, you will learn how to:
If you prefer not to use Python, you're welcome to implement the codelab in your favorite development tool (supported languages' client libraries are available here) and simply refer to the Python examples as (executable) pseudocode.
This codelab supports either Python 2 or 3, and the terminal/command window output represent those on POSIX-compliant systems such as Linux or Mac OS X. Please this guide if you're using a Windows environment. If you're unsure of which Python version you have, bring up a terminal, and issue the following command:
$ python --version
Python 2.7.13
You can also use the python2
and python3
commands to startup an explicit version (see below). The remainder of the codelab assumes you're using Python 3—specific instructions will be provided for Python 2 if they differ significantly from 3.x.
$ python2
Python 2.7.13 (default, Dec 17 2016, 23:03:43)
[GCC 4.2.1 Compatible Apple LLVM 8.0.0 (clang-800.0.42.1)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>>
$
$ python3
Python 3.6.1 (default, Mar 23 2017, 16:49:06)
[GCC 4.2.1 Compatible Apple LLVM 8.0.0 (clang-800.0.42.1)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>>
The codelab also assumes you have the pip
installation tool (Python package manager and dependency resolver). It comes bundled with versions 2.7.9 and newer, and 3.4 and newer. If you have an older Python version, see this guide for installation instructions. Depending on your permissions you may need to have sudo
or superuser access, but generally this isn't the case.
Once you have pip
working on your system, install the Google APIs client and OAuth2 libraries for Python with the command below.
$ pip install -U google-api-python-client oauth2client
Depending on how Python is installed on your system, like with Python versions above, you can explicitly request a specific version with pip2
or pip3
.
This command installs the client library as well as any packages it depends on. You'll know everything is working when you can: 1) start up the Python interpreter and 2) run the import
command below successfully (without errors):
$ python3 # or 'python' for those still on 2.x
Python 3.6.1 (default, Mar 23 2017, 16:49:06)
[GCC 4.2.1 Compatible Apple LLVM 8.0.0 (clang-800.0.42.1)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import apiclient, httplib2, oauth2client
>>>
An application using Google APIs requires a project. Those are managed in the Google Cloud Developers Console or simply, "devconsole." In this codelab, we're only going to use the Google Drive API, so we have a magic link (below in Step 1) that:
Let do it!
client_id.json
to be downloaded, likely to your Downloads folder. Move it to the folder where you're building your app. Note, this file is often named instead as client_secret.json
, for example in our documentation and in many of our videos, so you can choose to use either name.That's it as far as credentials go. You're now set to work on your application!
NOTE: More details about creating projects, enabling APIs, and obtaining credentials, manually, i.e., without the use of the "wizard" above, is available after the conclusion of this codelab for further study.
In the same directory where you downloaded client_id.json
, create a new Python file named drive_list.py
and add these lines of code. Believe it or not, this code is the entire application! After this step, we'll run the script then provide into how it works.
from __future__ import print_function
from apiclient import discovery
from httplib2 import Http
from oauth2client import file, client, tools
SCOPES = 'https://www.googleapis.com/auth/drive.readonly.metadata'
store = file.Storage('storage.json')
creds = store.get()
if not creds or creds.invalid:
flow = client.flow_from_clientsecrets('client_id.json', SCOPES)
creds = tools.run_flow(flow, store)
DRIVE = discovery.build('drive', 'v3', http=creds.authorize(Http()))
files = DRIVE.files().list().execute().get('files', [])
for f in files:
print(f['name'], f['mimeType'])
There are three main sections to this application:
NOTE: A deeper dive into the code and review a line-by-line explanation is available after the conclusion of this codelab for further study.
Name this file something like drive_list.py. To run it, go to your command-line terminal and issue the following command (or python
if you're still on Python 2):
$ python3 ./drive_list.py
The first time you run it, your code will output the lines that look like this and execution is paused:
$ python3 ./drive_list.py
/usr/local/lib/python3.6/site-packages/oauth2client/_helpers.py:255: UserWarning: Cannot access storage.json: No such file or directory
warnings.warn(_MISSING_FILE_MESSAGE.format(filename))
Your browser has been opened to visit:
https://accounts.google.com/o/oauth2/auth?client_id=LONG-STRING.apps.googleusercontent.com&redirect_uri=http%3A%2F%2Flocalhost%3A8080%2F&scope=https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fdrive.readonly.metadata&access_type=offline&response_type=code
If your browser is on a different machine then exit and re-run this
application with the command-line parameter
--noauth_local_webserver
The command-line script is paused as a browser window opens and presents you with the OAuth2 permissions dialog:
This is where the application asks the user for the permissions the code is requesting (via the SCOPES
variable). In this case, it's the ability to view the file metadata from the user's Google Drive. You need to give explicit authorization for the requested permission(s) requested, else the app won't run.
NOTE: Some users have multiple browsers, and the authorization request may be popping up on a non-preferred browser. If that's the case, just copy the entire URL from the browser window you don't want to use and paste into the address bar of a browser you do wish to use.
Once the user clicks allow, the app will (continue to) run so expect to see output consisting of Drive files/folders and their MIMEtypes. Here's an example from one of our test accounts:
$ python3 ./drive_list.py
Travel expenses application/vnd.google-apps.spreadsheet
Gmail Add-ons codelab application/vnd.google-apps.script
G Suite Developer Intro application/vnd.google-apps.presentation
Baseball Sheets application/vnd.google-apps.folder
My Resume application/vnd.google-apps.document
. . .
If you run the script again, it'll reuse your credentials and go straight to output. Isn't it exciting to see your documents in a terminal for the first time? We think so!
Now you're ready to learn more features about the Drive API or explore other G Suite and Google APIs. Congrats for making it all the way to the end!
The code featured in this codelab is also available at its GitHub repo at github.com/googlecodelabs/gsuite-apis-intro. (We aim to keep this codelab in-sync with the repo.) Ready to move on? Below are various resources you can access to help you dig into the material covered in this codelab more, or if you want to stretch your mind and explore other ways of accessing Google technologies programmatically.
As hinted earlier, if you're not a regular Python developer, we invite you to redo this codelab example in your favorite development language. Client libraries for supported languages are available here.
This optional section is to be used as self-study after the session concludes to fill-in any gaps which may have arose or for further research.
from __future__ import print_function
from apiclient import discovery
from httplib2 import Http
from oauth2client import file, client, tools
import
statement enables this code to run on Python 2—it can be dropped completely if you're solely using Python 3.apiclient
focuses on connecting Google APIshttplib2
provides an HTTP client for the app to useoauth2client
helps us manage OAuth2 credentialsSCOPES = 'https://www.googleapis.com/auth/drive.readonly.metadata'
store = file.Storage('storage.json')
creds = store.get()
if not creds or creds.invalid:
flow = client.flow_from_clientsecrets('client_id.json', SCOPES)
creds = tools.run_flow(flow, store)
DRIVE = discovery.build('drive', 'v3', http=creds.authorize(Http()))
SCOPES
are the permissions an app will ask of the user running it. To keep user data secure, apps can't run without being granted permissionSCOPES = 'https://www.googleapis.com/auth/drive.readonly.metadata'
storage.json
. If you don't save these tokens, you'll have to re-authorize your app each time you run it.store = file.Storage('storage.json')
if
statement conditional).creds = store.get()
if not creds or creds.invalid:
oauth2client.client.flow_from_clientsecrets()
] from your OAuth client ID & secret in client_id.json
file that you downloaded].if not creds or creds.invalid:
flow = client.flow_from_clientsecrets('client_id.json', SCOPES)
oauth2client.tools.run_flow()
] described and illustrated above. creds = tools.run_flow(flow, store)
creds
and cached in the storage.json
file.apiclient.discovery.build()
creates a service endpoint to the API you're using.build()
, pass in the API name ('drive'
) & version desired (currently 'v3'
).DRIVE = discovery.build('drive', 'v3', http=creds.authorize(Http()))
files = DRIVE.files().list().execute().get('files', [])
for f in files:
print(f['name'], f['mimeType'])
list()
method in the files()
collection for the Drive API to build the request, which is immediately called with execute()
. A Python dict
is returned from which we ask for the 'files'
key to get the 100 file & folder names from the user's Google Drive (or less if you have fewer files).DRIVE.files().list()
. If you want to change this number, say to only 10 files or 1000, add the pageSize
parameter to your request: DRIVE.files().list(pageSize=10)
. Here's the documentation for more options.You've now written your first application that uses a Google REST API... congratulations! Aside from the imports and authorization code, this script really is just a couple of lines of code (what you see above). Most Google APIs work in a similar manner and you would only need to create service endpoints for each one you want to use.
Yes, you can certainly use more than one API in the same app! Here's a Python code snippet for an app that reuses the same HTTP client and creates service endpoints to three Google APIs (yes, also with 3 different SCOPES
):
SCOPES = (
'https://www.googleapis.com/auth/drive',
'https://www.googleapis.com/auth/spreadsheets.readonly',
'https://www.googleapis.com/auth/presentations',
)
. . .
HTTP = creds.authorize(Http())
DRIVE = discovery.build('drive', 'v3', http=HTTP)
SHEETS = discovery.build('sheets', 'v4', http=HTTP)
SLIDES = discovery.build('slides', 'v1', http=HTTP)
We imagine this code can be part of an app that generates multiple slide decks (Slides API) based upon spreadsheet data (Sheets API) and uses a slide template which is copied (Drive API) for each deck generated. While such an app doesn't exist, you should be able to build something similar by using two existing samples that G Suite team has created as building blocks:
Your challenge: build that app!
In this optional section, we describe how to create projects in the devconsole, enable APIs, and obtain credentials, all without using the wizard as above in the codelab. This is for intermediate users comfortable enough to do it manually or wish to learn how to do so.
Any time you write an application using Google APIs, you need to create a new project. That happens in the Google/Cloud Developers Console. Earlier in this codelab, we provided a magic link (i.e., like a setup wizard) gets you going quickly, skipping many of the required steps. How would this work in a more general situation where you're creating your own projects and enabling desired APIs on your own? Let's walk through how you'd do that now:
You've now created a project successfully and are ready to move on by choosing the APIs you wish to use for your project.
To help track usage and ensure adequate resources for API users, Google requires you enable the APIs you want to use. In this codelab, we're only using the Drive API, so to enable it, follow these steps:
In this codelab, we're only going to use the Google Drive API, but once you're done with the codelab, you can select any others you'd like to experiment with or use for real. Be aware that some Google Cloud Platform APIs may be enabled by default—you can disable those if desired. Note that some APIs require billing (and adding your credit card), but not the Drive API—it is free up to certain limits (which we don't publish).
The next step is to create your project credentials. Before we move on to that topic, note that if you don't have any credentials created, you'll likely get this inline dialog once you've enabled the Drive API:
We're going to follow a slightly different path, so skip this step for now—do not click Create credentials. Instead, click the blue back arrow to return to the Library, then move to the next step.
client_secret_
LONG-STRING
.apps.googleusercontent.com.json
to your local disk, likely in your Downloads folder. Move it to the folder where you're building your app and rename that file to an easier name like client_secret.json
.