Last active
April 24, 2016 03:34
-
-
Save microamp/dc60788407b0928c6b6b to your computer and use it in GitHub Desktop.
Calling Google API call in Python
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#-*- coding: utf-8 -*- | |
from pprint import pprint | |
import json | |
import os | |
from oauth2client.client import SignedJwtAssertionCredentials | |
import httplib2 | |
ENV_SERVICE_ACCOUNT = "GAPI_SERVICE_ACCOUNT" | |
ENV_PEM_FILE_PATH = "GAPI_PEM_FILE_PATH" | |
SCOPES = ("https://www.googleapis.com/auth/admin.directory.group", | |
"https://www.googleapis.com/auth/admin.directory.orgunit", | |
"https://www.googleapis.com/auth/admin.directory.user", | |
"https://www.googleapis.com/auth/drive",) | |
ADMIN_ACCOUNT = "admin@example.com" | |
def _auth(service_account, private_key, scopes, **kwargs): | |
credentials = SignedJwtAssertionCredentials(service_account, | |
private_key, | |
scopes, | |
**kwargs) | |
credentials.refresh(httplib2.Http()) | |
return credentials.authorize(httplib2.Http()) | |
def _list_users(http): | |
fields = {"domain": "example.com", | |
"maxResults": 1, | |
"projection": "full"} | |
url = "https://www.googleapis.com/admin/directory/v1/users?%s" % \ | |
"&".join("%s=%s" % (k, v) for k, v in fields.iteritems()) | |
return url, http.request(url) | |
def main(): | |
service_account = os.environ.get(ENV_SERVICE_ACCOUNT, "") | |
pem_file_path = os.environ.get(ENV_PEM_FILE_PATH, "") | |
if not service_account: | |
print("Error: Env not set (%s)" % ENV_SERVICE_ACCOUNT) | |
return | |
if not pem_file_path: | |
print("Error: Env not set (%s)" % ENV_PEM_FILE_PATH) | |
return | |
print("Service account: %s" % service_account) | |
with open(pem_file_path, "r") as f: | |
private_key = f.read() | |
# Do auth | |
http = _auth(service_account, private_key, SCOPES, sub=ADMIN_ACCOUNT) | |
# List users | |
url, (headers, body) = _list_users(http) | |
print("GET %s" % url) | |
print("====headers====") | |
pprint(headers) | |
print("====body====") | |
pprint(json.loads(body)) | |
if __name__ == "__main__": | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment