How to use Service Account OAuth and API with Google API Client for python

0. Introduction

How to use OAuth and API with Google API Client for python. This time, we will authenticate with Service Account, and API will target Calendar.

Explanation page about Google official authentication. Using OAuth 2.0 for Server to Server Applications

1. Preparation

Get Google API Client

I will use this. google/google-api-python-client

Install with pip.

$ pip install --upgrade google-api-python-client

Google Developers Console

First, create a Service Account in the Google Developers Console.

  1. Create a project
  2. Enable Calendar by selecting [API and Authentication] → [API] * Set the OAuth consent screen
  3. Create by [API and Authentication] → [Authentication Information] → [Add Authentication Information] → [Service Account] → [p12] and save the "~ .p12" file * JSON is also acceptable

Management console

Set the API permissions in the Administration Console.

oauth2client.client.AccessTokenRefreshError: access_denied: Requested client not authorized.
  1. [Security] → [More] → [Advanced] → [Manage API Client Access]
  2. Enter the "Client ID" (.apps.googleusercontent.com) created in the Developers Console in [Client Name] * Note that this is not an email address.
  3. Enter "https://www.googleapis.com/auth/calendar, https://www.googleapis.com/auth/calendar.readonly" in One or more API ranges
  4. Press [Approve]

2. Creating a module

google_auth.py



import json

from httplib2 import Http

from oauth2client.client import SignedJwtAssertionCredentials
from googleapiclient.discovery import build

#Service account email address
client_email = '[email protected]'

#p12 version certification
fileName = "./project.p12"

with open(fileName, 'rb') as f:
    private_key = f.read()

credentials = SignedJwtAssertionCredentials(client_email, private_key,
        'https://www.googleapis.com/auth/calendar https://www.googleapis.com/auth/calendar.readonly'
    ,sub='[email protected]')

#json version certification
#fileName = "./project.json"
#json_key = json.load(open(fileName))

#credentials = SignedJwtAssertionCredentials(json_key['client_email'], json_key['private_key'],
#   'https://www.googleapis.com/auth/calendar https://www.googleapis.com/auth/calendar.readonly'
#    ,sub='[email protected]')


http = Http()
credentials.authorize(http)

# Calendar API
from apiclient.discovery import build

calendar_service = build('calendar', 'v3', http=http)

calendar_list = calendar_service.calendarList().get(calendarId='[email protected]').execute()

print calendar_list['summary']

Execution result)

[email protected]

Notes)

  1. If you do not set sub ='email address' in the argument of SignedJwtAssertionCredentials, you will not be able to access the API with the following error.
googleapiclient.errors.HttpError: <HttpError 404 when requesting https://www.googleapis.com/calendar/v3/users/me/calendarList/info%40example.com?alt=json returned "Not Found">

Reference URL

  1. https://developers.google.com/api-client-library/python/auth/service-accounts?hl=ja

  2. http://stackoverflow.com/questions/21407985/google-calendar-api-404-on-calendar-service-account

  3. http://kb.cloudiway.com/errorunauthorized_client-descriptionunauthorized-client-or-scope-in-request-uri/

that's all.

Recommended Posts

How to use Service Account OAuth and API with Google API Client for python
[BigQuery] How to use BigQuery API for Python -Table creation-
Python: How to use async with
How to use OpenPose's Python API
How to use FTP with Python
[Python] How to use Typetalk API
Easy to use Nifty Cloud API with botocore and python
Get data from analytics API with Google API Client for python
Sample to use after OAuth authentication of BOX API with Python
[Python] Organizing how to use for statements
How to use an external editor for Python development with Grasshopper
python: How to use locals () and globals ()
How to use "deque" for Python data
How to use Python zip and enumerate
How to use Python with Jw_cad (Part 2 Command explanation and operation)
How to use is and == in Python
How to deal with OAuth2 error when using Google APIs from Python
Edit Slide (PowerPoint for Google) with Python (Low-cost RPA case with Google API and Python)
How to use the Google Cloud Translation API
How to use tkinter with python in pyenv
[Python] How to use hash function and tuple.
OpenGoddard How to use 2-python library for nonlinear optimal control and orbit generation
Data acquisition from analytics API with Google API Client for python Part 2 Web application
Tips for those who are wondering how to use is and == in Python
How to use OpenGoddard 3-python library for nonlinear optimal control and orbit generation
How to use OpenGoddard 4-python library for nonlinear optimal control and orbit generation
How to use OpenGoddard 1-python library for nonlinear optimal control and orbit generation
[For beginners] How to use say command in python!
[Python] [Django] How to use ChoiceField and how to add options
How to use python interactive mode with git bash
How to analyze with Google Colaboratory using Kaggle API
How to use Django on Google App Engine / Python
Python # How to check type and type for super beginners
How to operate Discord API with Python (bot registration)
Install tweepy with pip and use it for API 1.1
Use Twitter API with Python
[Python] How to use list 1
Check! How to use Azure Key Vault with Azure SDK for Python! (Measures around authentication)
How to use Python argparse
Python: How to use pydub
[Python] How to use checkio
Use subsonic API with python3
[Python] How to use input ()
How to use Python lambda
[Python] How to use virtualenv
python3: How to use bottle (3)
python3: How to use bottle
How to use Google Colaboratory
How to use Python bytes
[python] How to use the library Matplotlib for drawing graphs
How to use Realsense's Python wrapper PyRealsense with Jetson Nano
How to extract any appointment in Google Calendar with Python
[Python] How to play with class variables with decorator and metaclass
[Introduction to Udemy Python 3 + Application] 36. How to use In and Not
How to learn TensorFlow for liberal arts and Python beginners
[Python] Summary of how to use split and join functions
How to use machine learning for work? 03_Python coding procedure
How to do Bulk Update with PyMySQL and notes [Python]
Comparison of how to use higher-order functions in Python 2 and 3
I didn't know how to use the [python] for statement
How to log in to AtCoder with Python and submit automatically