Skip to content
Search

Google Drive

lastmod 2025-10-28created 2016-06-0221 edits

Google Drive.

Categories

OAuth registration procedure for API use

  • Go to the Google Cloud Console at https://console.cloud.google.com/.
  • Select a project (create one if you don't have one)
  • Press the "Navigation" button (hamburger icon) at the top and click "APIs & Services" > "Library".
  • Type "Google Drive API" in the "Search for APIs & Services" box and open it.
  • Click the "Enable" button. (If you have already clicked it, it changes to a "Manage" button)
  • If you have not configured the "OAuth consent screen", click "Configure consent screen" and configure it.
  • Click "Credentials", then "Create credentials" > "OAuth client ID".
  • For the application type, click "Web application".
  • Enter a name for the web client
Google_Drive_API_OAuth_Register_-_01.png
Google_Drive_API_OAuth_Register_-_02.png
Google_Drive_API_OAuth_Register_-_03.png
Google_Drive_API_OAuth_Register_-_04.png

Python OAuth Example

Authorize credentials for a desktop application

To authenticate as an end user and access user data in your app, you need to create one or more OAuth 2.0 client IDs. A client ID is used to identify a single app to Google's OAuth servers. If your app runs on multiple platforms, you must create a separate client ID for each platform.

  1. In the Google Cloud console, go to Menu menu > APIs & Services > Credentials.
  2. Go to Credentials
  3. Click Create Credentials > OAuth client ID.
  4. Click Application type > Desktop app.
  5. In the Name field, type a name for the credential. This name is only shown in the Google Cloud Console.
  6. Click Create. The OAuth client created screen appears, showing your new Client ID and Client secret.
  7. Click OK. The newly created credential appears under OAuth 2.0 Client IDs.
  8. Save the downloaded JSON file as credentials.json, and move the file to your working directory.

Install the Google client library

pip install --upgrade google-api-python-client google-auth-httplib2 google-auth-oauthlib

Sample code

In your working directory, create a file named quickstart.py:

from __future__ import print_function

import os.path

from google.auth.transport.requests import Request
from google.oauth2.credentials import Credentials
from google_auth_oauthlib.flow import InstalledAppFlow
from googleapiclient.discovery import build
from googleapiclient.errors import HttpError

# If modifying these scopes, delete the file token.json.
SCOPES = ['https://www.googleapis.com/auth/drive.metadata.readonly']


def main():
    """Shows basic usage of the Drive v3 API.
    Prints the names and ids of the first 10 files the user has access to.
    """
    creds = None
    # The file token.json stores the user's access and refresh tokens, and is
    # created automatically when the authorization flow completes for the first
    # time.
    if os.path.exists('token.json'):
        creds = Credentials.from_authorized_user_file('token.json', SCOPES)
    # If there are no (valid) credentials available, let the user log in.
    if not creds or not creds.valid:
        if creds and creds.expired and creds.refresh_token:
            creds.refresh(Request())
        else:
            flow = InstalledAppFlow.from_client_secrets_file(
                'credentials.json', SCOPES)
            creds = flow.run_local_server(port=0)
        # Save the credentials for the next run
        with open('token.json', 'w') as token:
            token.write(creds.to_json())

    try:
        service = build('drive', 'v3', credentials=creds)

        # Call the Drive v3 API
        results = service.files().list(
            pageSize=10, fields="nextPageToken, files(id, name)").execute()
        items = results.get('files', [])

        if not items:
            print('No files found.')
            return
        print('Files:')
        for item in items:
            print(u'{0} ({1})'.format(item['name'], item['id']))
    except HttpError as error:
        # TODO(developer) - Handle errors from drive API.
        print(f'An error occurred: {error}')


if __name__ == '__main__':
    main()

Run

The output looks something like this:

Please visit this URL to authorize this application: https://accounts.google.com/o/oauth2/auth?response_type=code&client_id=310991267121-amtie57drl8o3dheg6m4uk4mcuj1rr15.apps.googleusercontent.com&redirect_uri=http%3A%2F%2Flocalhost%3A51797%2F&scope=https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fdrive.metadata.readonly&state=M4ldK0mAqqWsn15uUwbeU10FIQS4iq&access_type=offline

Open that URL in a browser and press OK, and the file list is printed. From the second run on, the token.json file exists, so authentication is skipped.

Next steps

File Upload/Download

See also

Favorite site

API

Guide

author Zer0 sitemap