How do I use google.oauth2 python library?

Question:

I’m trying to just make a simple rest call to a secure predict endpoint for a google machine learning project but it can’t find the google.oauth2 module. This is my code:

import urllib2
from google.oauth2 import service_account

# Constants
ENDPOINT_URL = 'ml.googleapis.com/v1/projects/{project}/models/{model}:predict?access_token='
SCOPES = ['https://www.googleapis.com/auth/sqlservice.admin']
SERVICE_ACCOUNT_FILE = 'service.json'

credentials = service_account.Credentials.from_service_account_file(SERVICE_ACCOUNT_FILE, scopes=SCOPES)
access_token=credentials.get_access_token()

opener = urllib2.build_opener(urllib2.HTTPHandler)
request = urllib2.Request(ENDPOINT_URL)
request.get_method = lambda: 'POST'
result = opener.open(request).read()
print(str(result))

When I run this I get this error:

Traceback (most recent call last):
  File "wakeUpMLServer.py", line 30, in <module>
    from google.oauth2 import service_account
ImportError: No module named oauth2

I installed the google-api-python-client library using pip (from instructions here: https://developers.google.com/api-client-library/python/apis/oauth2/v1). The install said it was successful.
Python version: 2.7.6
Pip version: 1.5.4

In case it is somehow conflicting you should know I also do protobuf file processing on the same server, so I have the protobufs library installed as well. When I do pip list it shows both libraries:

google-api-python-client (1.6.7)
protobuf (3.1.0.post1)

Is there some special way I should be installing the module? How do I verify that the module was installed? Is there any simpler way to just make a simple rest call to a secured ml endpoint that just uses the Rest API and no python?

Asked By: Alex Egli

||

Answers:

The google-oauth2 module definitely exists, so maybe it was never installed.

Do you have the google-auth package installed? Try executing

pip install –upgrade google-auth

and then run your code again.

Answered By: bluecereal

Install Google API python packages,

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

then you can use the oauth2 Credentials (make sure service_account.json is in the same directory as your script)

import json
from googleapiclient.discovery import build
from google.oauth2.service_account import Credentials

service_account_info = json.load(open('service_account.json'))
credentials = Credentials.from_service_account_info(
            self.service_account_info, scopes=SCOPES)

drive_service = build('drive', 'v3', credentials=credentials)

For a more complete tutorial visit, https://developers.google.com/docs/api/quickstart/python

Answered By: deirdreamuel

I am recently testing out calling the YouTube API v3 from Python (transitioning from Rust), and I initially struggled with this, as the Google Docs on the usage are not too clear.

I got tips after referencing the Quickstart Section in Python:

Here is my Python version:

$ python
Python 3.11.2

To start out with, first I ran pip install to install the following Python modules:

pip install 
    google-api-python-client~=2.85.0 
    google-auth-oauthlib~=1.0.0 
    google-auth-httplib2~=0.1.0

Once those dependencies are installed (in a virtual environment, preferrably) the rest is rather straightforward.

First set up an OAuth app and ensure you have a client_secret.json file to work with. Place this file in the same directory as the Python script below.

Now, you can use this script to test — replacing VIDEO_ID with the YouTube video ID (visibility: private) under your personal channel or account.

"""
Script to retrieve info on a (Private) video in an owned YT channel.

See:
    https://developers.google.com/docs/api/quickstart/python

"""
from pathlib import 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


# Enter a Video ("Private" visibility) in your YT Channel, for testing purposes
VIDEO_ID = 'REPLACE-ME'

# Parent Folder of this Python Script
SCRIPT_DIR = Path(__file__).parent

# The CLIENT_SECRET_FILE variable specifies the name of a file that contains
# the OAuth 2.0 information for this application, including its client_id and
# client_secret. You can acquire an OAuth 2.0 client ID and client secret from
# the Google API Console at
# https://console.cloud.google.com/.
# Please ensure that you have enabled the YouTube Data API for your project.
# For more information about using OAuth2 to access the YouTube Data API, see:
#   https://developers.google.com/youtube/v3/guides/authentication
# For more information about the client_secrets.json file format, see:
#   https://developers.google.com/api-client-library/python/guide/aaa_client_secrets
CLIENT_SECRET_FILE = str(SCRIPT_DIR / 'client_secret.json')

# The file token.json stores the user's access and refresh tokens.
TOKEN_FILE = SCRIPT_DIR / 'token.json'

# OAuth 2.0 access scopes.
YOUTUBE_READ_ONLY_SCOPE = "https://www.googleapis.com/auth/youtube.readonly"
YOUTUBE_WRITE_SCOPE = "https://www.googleapis.com/auth/youtube.force-ssl"
SCOPES = [YOUTUBE_READ_ONLY_SCOPE, YOUTUBE_WRITE_SCOPE]

# API information
YOUTUBE_API_SERVICE_NAME = "youtube"
YOUTUBE_API_VERSION = "v3"


def main():
    # API client
    youtube = get_authenticated_service()

    # Query for an owned video
    response = youtube.videos().list(
        part="id",
        id=VIDEO_ID,
    ).execute()

    # Print the result
    print(response)


def get_authenticated_service():
    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 TOKEN_FILE.exists():
        creds = Credentials.from_authorized_user_file(str(TOKEN_FILE), 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(
                CLIENT_SECRET_FILE,
                scopes=SCOPES,
            )
            creds = flow.run_local_server(port=0)
        # Save the credentials for the next run
        TOKEN_FILE.write_text(creds.to_json())

    return build(
        YOUTUBE_API_SERVICE_NAME,
        YOUTUBE_API_VERSION,
        credentials=creds,
    )


if __name__ == '__main__':
    main()
Answered By: rv.kvetch