OAuth2 server-to-server on Google App Engine

95 views
Skip to first unread message

Joshua Smith

unread,
Feb 24, 2017, 1:27:48 PM2/24/17
to Google App Engine
I’m trying to access the Google Analytics API from a Google App Engine app. I got this working a long time ago, before Analytics was one of the APIs you could use server-to-server.

So I have code that works with an administrator user in the middle of the transaction. I used the decorator from oauth2client.appengine import oauth2decorator_from_clientsecrets

What I’d like to do is get this working so my google app engine app (written in Python) can just talk to google analytics without a person in the loop. I can’t find an example of that.

Since all the google services seem to work the same way, I probably don’t need an example of connecting to analytics. Rather, just an example of how to connect to any google service without a user in the middle would be great.

The following code doesn’t work, but hopefully will give you an idea of what I’m trying to do. It is failing because there’s no callback set up.

class StorageDuck():
def put(self, content):
console.log("Pretending to put: "+content)

class GetGAHandler(webapp2.RequestHandler):
def get(self):
from apiclient.discovery import build
from oauth2client import client
from oauth2client import file
from oauth2client import tools
http = httplib2.Http(memcache)
service = build("analytics", "v3", http=http)
flow = client.flow_from_clientsecrets(
CLIENT_SECRETS,
scope='https://www.googleapis.com/auth/analytics.readonly',
message="")
credentials = tools.run(flow, StorageDuck())
chttp = credentials.authorize(http=httplib2.Http())

Any pointers?

-Joshua

Joshua Smith

unread,
Feb 24, 2017, 3:42:06 PM2/24/17
to Google App Engine
Nevermind. I found this:


The code is pretty simple:

class GetGAHandler(webapp2.RequestHandler):
  def get(self):
    from oauth2client.service_account import ServiceAccountCredentials
    from httplib2 import Http
    from apiclient.discovery import build
    credentials = ServiceAccountCredentials.from_json_keyfile_name(
      CLIENT_SECRETS, scopes=['https://www.googleapis.com/auth/analytics.readonly'])
    http_auth = credentials.authorize(Http())
    service = build("analytics", "v3", http=http_auth)

Getting the google-api-python-client installed in a local folder was a nightmare, and convincing GAE to use it wasn’t obvious. However, once I sorted through all that, the above code works like a champ.

Nick (Cloud Platform Support)

unread,
Feb 24, 2017, 4:39:13 PM2/24/17
to Google App Engine
Hey Joshua,

You correctly found that you can use service account credentials from a keyfile. You can also use Application Default Credentials, which will give access to anything that your app's default service account can access. This is good for many API's.

Cheers,

Nick
Cloud Platform Community Support
Reply all
Reply to author
Forward
0 new messages