Use Python to Automagically get your Google Adsense Report – Part 1

I’m a little tired of logging into Google Adsense and Analytics everyday to see how my website is doing. In typical Automate My Life fashion, I wrote a script to automate that so you won’t have to. My first PoC (proof of concept) was to see if I can login to the Google Adsense Management API and print out my account name. I didn’t follow the code there exactly because it didn’t seem to work for me so I simplified into what you’re about to read and it works!



Do These First

Before you get to the code (I know…it’s hard), you need to do a few things with Google’s Console first. Following Steps 1 and 2 from here to get you started. Make sure you download the client_secret.json file and that you also enable the Google Adsense Management API. For the purposes of this post, we will just use AdSense to show the login process. You can pick whatever API you want, just be sure to call the correct “service” later. After you have enabled the correct API and have the JSON file in the same directory as your Python file, read on.

"""--------------The Process------------
0. Go to console.developers.google.com and enable APIs you want
1. Authorize the app by using Flow class
2. Create a service using Google API endpoints
3. Interact with the API library
4. Drink a beer
-------------------------------------
References
-------------------------------------
Oauth2 2.0 Explained: https://developers.google.com/api-client-library/python/guide/aaa_oauth
Scopes: https://developers.google.com/identity/protocols/googlescopes
Adsense API Classes: https://developers.google.com/resources/api-libraries/documentation/adsense/v1.4/python/latest/
Analytics Reporting API: https://developers.google.com/analytics/devguides/reporting/core/v4/
-------------------------------------
"""

Step 1 – Google Flow Thing?

Google has changed their API login since I last played with it. They now use this thing called Flow that seems to have simplified some of the logins for OAuth 2.0. Basically, flow.step1_get_authorize_url(secretJSON,scopes,redirect_uri) sends a information to Google’s servers requesting access to the endpoints you identified in the variable scope and shows it your credentials from client_secret.json. Using the proper Scope is important to authenticate the correct level of access for your app.

    #first step of flow process
#redirect uri can be a custom url for your app
#'urn:ietf:wg:oauth:2.0:oob' is localhost
flow = oauth2client.client.flow_from_clientsecrets(pathToFile,scope,redirect_uri='urn:ietf:wg:oauth:2.0:oob')

The redirect_uri variable is important to note because, depending on where your app is located (either locally or in production), this could be a custom url where the user is prompted to “allow the app” access to their account. We’re using urn:ietf:wg:oauth:2.0:oob (basically localhost) to show that process in our app.

Step 2 – Allow App Access

This step was new to me. If this is your first time getting credentials for your app then you haven’t “saved” any credentials in oauth2client.file.Storage(someFileName) yet. You will be asked to copy/paste some random string to get credentials = flow.step2_exchange(enterRandomStringHere).

        #get authorization url
auth_url = flow.step1_get_authorize_url()
#open the url to get a code since its the first time
#this will default to the redirect_uri you set earlier
webbrowser.open(auth_url)
#enter the code to auth
codeStr = str(raw_input('enter code here:'))
credentials = flow.step2_exchange(codeStr)
#save the code to the dat
storage = oauth2client.file.Storage('MyCreds.dat')
storage.put(credentials)

Oh but you’re not done yet, save those credentials with storage = oauth2client.file.Storage(someFileName) and execute like a SQL query storage.put(credentials). That was a mouthful.

Step 3 – What Service?

This is the flexible part of your credentials “Flow”. A service is essentially any Google API. The information you will need for apiclient.discovery.build(whatService,whatVersion) is located here. I still plan to use Google Analytics Reporting API, but this post is using Adsense v1.4.

def get_AdSense_service():
"""Gets the credentials then Returns api service object"""
credentials = get_credentials()
http = httplib2.Http()
http = credentials.authorize(http)
service = apiclient.discovery.build('adsense', 'v1.4', http=http)
print "Woot! Got Google Adsense service"

Step 4 – Who Am I?

Success!! Now I can write a function that will get my credentials according to the scopes and credentials we defined earlier. All you have to work on now is using the individual API library calls to get the information you need. My next post will be on integrating Google Analytics and mining that data!

#run the main function
whoAmI()

Boom.

-j

2 thoughts on “Use Python to Automagically get your Google Adsense Report – Part 1

Leave a Reply

Your email address will not be published. Required fields are marked *