Samyak Jain
Samyak Jain

Reputation: 117

requests library with googleapiclient

Following is the code to access a google storage bucket using the httplib2 library

import json
from httplib2 import Http
from oauth2client.client import SignedJwtAssertionCredentials
from googleapiclient.discovery import build
from pprint import pprint
client_email = 'my.iam.gserviceaccount.com'

json_file = 'services.json'


cloud_storage_bucket = 'my_bucket'

files = 'reviews/reviews_myapp_201603.csv'
private_key = json.loads(open(json_file).read())['private_key']

credentials = SignedJwtAssertionCredentials(client_email, 
private_key,'https://www.googleapis.com/auth/devstorage.read_only')
storage = build('storage', 'v1', http=credentials.authorize(Http()))
pprint(storage.objects().get(bucket=cloud_storage_bucket, object=files).execute())

Can someone tell me if I can make the http request using the Python Requests library here? If yes, how?

Upvotes: 3

Views: 6287

Answers (2)

mohd4482
mohd4482

Reputation: 1918

I suggest to use the official Google Auth library which is already implementing Requests Library. See this link for more information.

Here is a code to try (given that you have a service account file with required permissions):

from google.oauth2 import service_account
from google.auth.transport.requests import AuthorizedSession

service_account_file = 'service_account.json'
scopes = ['https://www.googleapis.com/auth/devstorage.full_control']
credentials = service_account.Credentials.from_service_account_file(
        service_account_file, scopes=scopes)
session = AuthorizedSession(credentials)
bucket_name = 'YOUR-BUCKET-NAME'
response = session.get(f'https://storage.googleapis.com/storage/v1/b/{bucket_name}')

print(response.json())

Upvotes: 2

Calumah
Calumah

Reputation: 2995

Yes, you can use the HTTP header Authorization: Bearer <access_token> with requests or any library you want.

Service account

from google.oauth2 import service_account

credentials = service_account.Credentials.from_service_account_file(
    'services.json',
    scopes=['https://www.googleapis.com/auth/devstorage.read_only'],
)

# Copy access token
bearer_token = credentials.token

User account credentials

import json

from google.oauth2.credentials import Credentials
from google_auth_oauthlib.flow import InstalledAppFlow

flow = InstalledAppFlow.from_client_secrets_file(
    'test.json',
    'https://www.googleapis.com/auth/devstorage.read_only'
)

# Construct cache path for oauth2 token
oauth2_cache_path = 'test-oauth2.json'

credentials = None

try:
    # Try to load existing oauth2 token
    with open(oauth2_cache_path, 'r') as f:
        credentials = Credentials(**json.load(f))
except (OSError, IOError) as e:
    pass

if not credentials or not credentials.valid:
    credentials = flow.run_console()

    with open(oauth2_cache_path, 'w+') as f:
        f.write(json.dumps({
            'token': credentials.token,
            'refresh_token': credentials.refresh_token,
            'token_uri': credentials.token_uri,
            'client_id': credentials.client_id,
            'client_secret': credentials.client_secret,
            'scopes': credentials.scopes,
        }))

# Copy access token
bearer_token = credentials.token

Use requests lib

import requests

# Send request
response = requests.get(
    'https://www.googleapis.com/storage/v1/<endpoint>?access_token=%s'
    % bearer_token)
# OR
response = requests.get(
    'https://www.googleapis.com/storage/v1/<endpoint>',
    headers={'Authorization': 'Bearer %s' % bearer_token})

Use googleapiclient lib

I recommend you to use build() method and not requests directly because the google library do some checks before sending your API call (like checking params, endpoint, auth and the method you use). This library also raise exceptions when error is detected.

from googleapiclient.discovery import build

storage = build('storage', 'v1', credentials=credentials)
print(storage.objects().get(bucket='bucket', object='file_path').execute())

More informations here : https://developers.google.com/identity/protocols/OAuth2WebServer#callinganapi (click on "HTTP/REST" tab)

Upvotes: 11

Related Questions