From charlesreid1

Overview

On this page we attempt to cover the basics of using the Google Drive API.

Steps:

  • Enable Google Drive API in Google Cloud Console
  • Download client_secrets.json which contains credentials to make requests as your application
  • Run your application and present the user with a unique login link
  • They log in, you end up with credentials.json which contain credentials to do things on behalf of that user
  • Use credentials.json when making API calls

Create Project in Google Cloud Console

Start at the Getting Started Page for the Google Python API Client.

Docs: https://cloud.google.com/resource-manager/docs/creating-managing-projects?visit_id=636702350209334473-4073010966&rd=1

Start by going to the manage resources page: https://console.cloud.google.com/cloud-resource-manager?pli=1

Click the Create Project button

Enable Drive API in Google Cloud Console

Enable the Google Drive API for the project you just created at the Google Cloud Console API Dashboard: https://console.developers.google.com/apis/dashboard

Search for the Drive API and enable it.

Download Client Secret

Now you are ready to download client_secret.json.

Go to the credentials section of the Google Cloud Console: https://console.cloud.google.com/apis/credentials

Pick your project, and you should see a list of existing OAuth 2 credentials. If you don't, click the blue "Creaate Credentials" button and create new OAuth 2 credentials.

When you create OAuth 2 credentials, you are implicitly choosing to implement an app with an architecture where your app asks a user for a certain permission level on their account, and the user approves or denies, and is authorized, entirely through the third-party service (Google).

Authenticate with Python

Now you can authenticate as the user, and obtain credentials.json containing credentials to take actions on that user's account, using a Python program:

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

# Setup the Drive v3 API
#
# Give it access to all the things (files plus metadata) but read-only
#
# https://developers.google.com/identity/protocols/googlescopes#drivev3
#
SCOPES = 'https://www.googleapis.com/auth/drive.readonly'
store = file.Storage('nihdatacommons_credentials.json')
creds = store.get()
if not creds or creds.invalid:
    flow = client.flow_from_clientsecrets('client_secrets.json', SCOPES)
    creds = tools.run_flow(flow, store)
service = build('drive', 'v3', http=creds.authorize(Http()))

This script requires client_secrets.json to be in the same directory. It will build a Google Drive service, which will automatically open a browser and visit a URL with a unique login token specific to this OAuth app. The user then logs in, and it closes the browser window and creates credentials.json, user-account-specific credentials.