python-2.7google-admin-sdkgoogle-admin-settings-api

AdminSettings API using service account auth/keyword failures


Trying to retreive domain number of users, 'GetCurrentNumberOfUsers()', using AdminSettings API via a Service Account in Python. Enabled delegation wide authority and scope, but getting errors. I have used service account for Calendar API, Directory API, EmailSettings API, but not working for AdminSettings. Tried sample code at: github.com/Khan/gdata-python-client/blob/master/samples/apps/adminsettings_example.py but get 'Authorization required' error while using correct credentials for admin account: API Client Acccess

from oauth2client.client import SignedJwtAssertionCredentials
import gdata.gauth
import gdata.apps.service
import gdata.apps.adminsettings.service

SERVICE_ACCOUNT_EMAIL = "XXXXXXXXXXXXX-ebirq08jvhldahbb482u8a1otu9n3l8p.apps.googleusercontent.com"
SERVICE_ACCOUNT_PKCS12_FILE_PATH = 'gapi_admin/privatekey.p12'
f = file(SERVICE_ACCOUNT_PKCS12_FILE_PATH, 'rb')
key = f.read()
f.close()
credentials = SignedJwtAssertionCredentials(SERVICE_ACCOUNT_EMAIL, key, scope='https://apps-apis.google.com/a/feeds/domain/', sub='admin@xxxtestmail.edu')
auth2token = gdata.gauth.OAuth2TokenFromCredentials(credentials)
service = gdata.apps.adminsettings.service.AdminSettingsService(source="testApp", domain='xxxtestmail.edu')
service = auth2token.authorize(service)

print service.GetCurrentNumberOfUsers()

#output
#TypeError: new_request() takes exactly 1 non-keyword argument (2 given)

works fine in OAuth2 Playground, view Screenshot.


Solution

  • The old GData Python library service objects don't actually support OAuth 2.0 which is what you need to be using. However you can hack a access token on there. Try something like:

    credentials = SignedJwtAssertionCredentials(SERVICE_ACCOUNT_EMAIL, key, scope='https://apps-apis.google.com/a/feeds/domain/', sub='admin@xxxtestmail.edu')
    credentials.refresh(httplib2.Http())
    service = gdata.apps.adminsettings.service.AdminSettingsService(source="testApp", domain='xxxtestmail.edu')
    service.additional_headers[u'Authorization'] = u'Bearer {0}'.format(credentials.access_token)
    
    print service.GetCurrentNumberOfUsers()