Call Google G Suite APIs (Sheets / Slides, etc.) with Python

Overview

In this article, I will explain the setup of authentication information and communication confirmation required when operating Google Slides / Spread Sheets / Documentation / Gmail with API in Python. (Time required about 20 minutes)

Please note that the architecture of Google Cloud Platform itself is constantly updated, so this article may differ from the actual GUI and UX. (Latest as of November 4, 2019)

Procedure (Download Credentials)

In this article, as a representative of G Suite API, we will use the Sheets API that calls Spread Sheets as an example.

  1. Access the page on the right. Sheets API Python Quick Start

  2. Click "Login" at the top right of the screen to log in with your Google account. Quick Start.png

  3. Click "Enable the Google Sheets API" to enable the API. Enable API.png

  4. Confirm the agreement, check the radio button "Yes", and press "NEXT". The project name defaults to "Quickstart", but it can be anything you like. Activation.png

  5. Click "DOWNLOAD CLIENT CONFIGRATION". Download Config.png

  6. credentials.json will be downloaded.

This completes the authentication information setup. If you want to confirm the communication of authentication, please follow the steps below.

Procedure (communication of authentication)

Install the required libraries with pip install.

b. Create a py file called quickstart.py in any directory and copy and paste the following code.

--Caution (1): Enter the information of your Spread Sheet in the following two parameters. --SAMPLE_SPREADSHEET_ID ='' --SAMPLE_RANGE_NAME ='' --Caution (2): The Script written on Google's official website has been slightly modified. (print (row) part)

quickstart.py


from __future__ import print_function
import pickle
import os.path
from googleapiclient.discovery import build
from google_auth_oauthlib.flow import InstalledAppFlow
from google.auth.transport.requests import Request

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

# The ID and range of a sample spreadsheet.
SAMPLE_SPREADSHEET_ID = '1BxiMVs0XRA5nFMdKvBdBZjgmUUqptlbs74OgvE2upms'
SAMPLE_RANGE_NAME = 'Class Data!A2:E'

def main():
    """Shows basic usage of the Sheets API.
    Prints values from a sample spreadsheet.
    """
    creds = None
    # The file token.pickle 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.pickle'):
        with open('token.pickle', 'rb') as token:
            creds = pickle.load(token)
    # 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.pickle', 'wb') as token:
            pickle.dump(creds, token)

    service = build('sheets', 'v4', credentials=creds)

    # Call the Sheets API
    sheet = service.spreadsheets()
    result = sheet.values().get(spreadsheetId=SAMPLE_SPREADSHEET_ID,
                                range=SAMPLE_RANGE_NAME).execute()
    values = result.get('values', [])

    if not values:
        print('No data found.')
    else:
        print('Name, Major:')
        for row in values:
            # Print columns A and E, which correspond to indices 0 and 4.
            print(row)

if __name__ == '__main__':
    main()

c. Place the downloaded credentials.json in the same directory as the quickstart.py you created.

d. Change to the directory where quickstart.py exists and execute it with the following command.

python quickstart.py


e. When the screen that allows access to the Web Browser appears, allow authentication.

許可2.png

f. If the result is output on the execution screen of the py file, it is successful.

Postscript

2019/11/08: The title has been edited

Recommended Posts

Call Google G Suite APIs (Sheets / Slides, etc.) with Python
Edit Google Spread Sheets with Python (Low-cost RPA case with Google APIs and Python)
Play with Google Spread Sheets in python (OAuth)
Study Python with Google Colaboratory
Call the API with python3.
Access Google Drive with Python
Low Cost RPA with Google APIs and Python -Post Table Data to Slides: Use Case Overview-
Call C from Python with DragonFFI
Call python from nim with Nimpy
How to deal with OAuth2 error when using Google APIs from Python
I tried updating Google Calendar with CSV appointments using Python and Google APIs
[google-oauth] [python] Google APIs Client Library for Python
How to update Google Sheets from Python
Try using Python with Google Cloud Functions
[GCP] Operate Google Cloud Storage with Python
Register users with Google Admin SDK (python)
Call APIGateWay with APIKey in python requests
Upload images to Google Drive with Python