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.

What you'll learn

What you'll need

How will you use this codelab tutorial?

Read it through only Read it and complete the exercises

How would rate your experience with G Suite developer tools & APIs?

Novice Intermediate Proficient

In this codelab, you will learn how to:

  1. Download the Google APIs client library for Python
  2. Create a new project in the Google/Cloud Developers Console
  3. Obtain the necessary credentials and download them for your app
  4. Use those credentials to access the Google Drive API

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!

  1. Navigate to console.developers.google.com/start/api?id=drive and login to your Google account.
  2. If you don't have any projects yet, you'll see this screen to accept the Google APIs Terms of Service:


    Once you accept the terms, a new project named "My Project" will be created, and the Drive API automatically enabled.
  3. If instead, you've already created a project (perhaps your previous codelab?), you'll get this screen instead:

    When you click the Create a project pulldown, choose an existing project or really create a new project.

    Once you've made your selection (new or existing project), the Drive API will be automatically enabled for you.
  4. You'll know the Drive API has been enabled with this confirmation:
  5. Click Go to credentials to move to the next step.
  1. On the Credentials screen, you'll see the Drive API listed as what you're using, and then you're asked, Where will you be calling the API from?
  2. Select the Choose... pulldown:
  3. Our application will be a simple Python command-line interface (CLI) tool, so select the Other UI option.
  4. Next we're asked, What data will you be accessing? Choose User data (since your Drive files are user data).

    Now click What credentials do I need? to move to the next step.
  5. On the following screen, you're told to create an OAuth2.0 client ID which you need to name (pick the default or something better like "Drive API demo tool"), then click Create client ID:
  6. Some gears will whirl around on Google servers, and voilá, your credentials are created, and you're prompted to Download so please do that now.
  7. This causes a file named 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'])

Application structure

There are three main sections to this application:

  1. Python imports to bring in library functionality
  2. Obtaining application credentials
  3. Fetch file & folder names & MIMEtypes in user's Google Drive & display

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.

Running the application

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.

Documentation

Related and general videos

News & updates

Other codelabs

Introductory

Intermediate

Reference apps

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.

Python imports to bring in library functionality

from __future__ import print_function

from apiclient import discovery
from httplib2 import Http
from oauth2client import file, client, tools

Authorization and obtaining application credentials

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()))
SCOPES = 'https://www.googleapis.com/auth/drive.readonly.metadata'
store = file.Storage('storage.json')
creds = store.get()
if not creds or creds.invalid:
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()))

Fetch & display first 100 Drive files/folders & MIMEtypes)

files = DRIVE.files().list().execute().get('files', [])
for f in files:
    print(f['name'], f['mimeType'])

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.

Using more than one Google API in an app

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.

Create project in Developers Console in general

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:

  1. Navigate to console.developers.google.com and login with your Google credentials.
  2. If you don't have any projects yet, you may be taken to...
  1. the Dashboard page:
  2. the Library page:
  3. or a completely blank page:

    If this 3rd one happens to you, just refresh the browser to be taken to the Library page.
  1. Whether you're on the Dashboard or Library pages, click the project selector at the top of the page:
  2. Next, you'll get the selector dialog. Click on the "+" on the right-hand side to create a new project:
  3. After you click the "+", a New Project page will appear. All consumer accounts get 12 projects by default. Before creating your first project, you'll have to accept the Google APIs Terms of Service:


    After you've done this, the email solicitation and Terms of Service questions go away when creating future projects:

  4. If you've created at least one project in the past, after login, you'll be taken to the dashboard of the last project you worked on. From there, create a new project as you would be choosing Select a project > +.
  5. Once your new project has been created, you'll be back on the Dashboard page:

You've now created a project successfully and are ready to move on by choosing the APIs you wish to use for your project.

Enable APIs in general (example: Google Drive API)

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:

  1. Click Enable APIs and Services, which takes you to the Library page.
  2. Now look for Drive API. You can either look for the G Suite APIs collection—in the dashboard image above, they're by the Gmail icon. The easier way out is to just type "Drive" in the search bar at the top and select the desired result.
  3. Click on Drive API, then Enable the Google Drive API for your project.

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.

Obtain project credentials

  1. Select Credentials in the left-nav:


    There are two sections, one for API keys, and one for OAuth 2.0 client IDs. We're only concerned with the latter. API keys are only for accessing public data such as searching for YouTube videos or public Google+ posts. Since looking through someone's (your's) Google Drive files is not public data, we need authorized access, and that's provided by OAuth 2.0 client IDs.
  1. Click the Create credentials pulldown and select OAuth client ID.



    Later on, you can go back and try the wizard ("Help me choose") to learn about the different credential types.

    NOTE: selecting the wizard takes you to the same flow as if you selected Create credentials after enabling the Drive API.
  2. If you have not set a consent screen, you will need to do so now as you will be presented with this inline dialog:
  3. Go ahead and configure the consent screen. The only thing you need at this time is just an application name so pick one then click Save:


  4. Once you've configured the Consent screen, you'll be able create an OAuth2 client ID. Here you'll see a variety of OAuth client IDs you can create:



    We're developing a command-line tool, which is Other, so choose that then click the Create button. Name your new client ID logically, i.e., "command-line Google Drive tool" which is preferred over the default name, "Other client 1".
  5. A small dialog with the client ID & secret pair then pops up; click OK to close that dialog.
  6. Download these credentials to the folder where your application code will go. Find the download icon to the far right bottom of your OAuth client and select it.
  7. This will download a file named 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.