Using Google REST API for Analytics

If you are not a Google Engineer, OAuth2 for Google APIs can be a nightmare without good examples.  Here is an example of using OAuth2 and Google Analytics API. 

I assume you have curl installed, and here is a step-by-step guide on how to retrieve Google Analytics data using curl, which for me remains the best way to test any API.

  1. A good place to start is reading the Core Reporting API (v4)
  2. On your browser, log-in at Google with the account you want to use to access Analytics info
  3. Go to the APIs console and create a "project"
  4. On the very top, use the search form and looks for "Analytics API", and chose it
  5. Enable them
  6. Go to "Credentials" and then, for OAuth2, click on "client ID"
  7. Fill all non optional forms. NB You need to have a privacy page, to which users will eventually be sent.
  8. On "application type" select "other" and name it "curl client"

You should, at this point, get a pop-up window with the credentials:

Pop-up with the client ID and client secret (key).

=== updated up to here ===

  1. Put "status on" for Analytics. Possibly rename the project going to the left menu "API Project" –the name given by default to the project;
  2. Click on "API Access". Click on "Create an OAuth 2.0 client ID". Give any name (this name is the one which would be seen by users, but here the only user will be you, downloading your data). Chose "Installed Application" and then "Create ID". These infos will appear:Client ID for installed applications Client ID: 1234567890.apps.googleusercontent.com Client secret: xywzxywzxywzxywzxywz Redirect URIs: urn:ietf:wg:oauth:2.0:oob
    http://localhost
  3. Go to Using OAuth 2.0 for Installed Apps (hardly useful), form the following URL and visit it with the browser where you logged in with your Analytics account (I had to guess the scope, could not find a page where all scope values are listed!): https://accounts.google.com/o/oauth2/auth? scope=https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fanalytics& redirect_uri=urn:ietf:wg:oauth:2.0:oob& response_type=code& client_id=1234567890.apps.googleusercontent.com
  4. Allow the access, of course, and copy the code which should look like
  5. Go to the terminal and use the command below using your own "code" from above, "client_id" etc: curl  -H "Content-Type: application/x-www-form-urlencoded" -d 'code=4/v6xr77ewYqjkslsdUOKwAzu &client_id=1234567890.apps.googleusercontent.com &client_secret=xywzxywzxywzxywzxywz &redirect_uri=urn:ietf:wg:oauth:2.0:oob &grant_type=authorization_code' https://accounts.google.com/o/oauth2/token
  6. You'll get a JSON like this one: { "access_token" : "ya29.AHES6Zkjhkjhahskjhskkskjh", "token_type" : "Bearer", "expires_in" : 3600, "refresh_token" : "1/HH9E7k5D0jakjhsd7askdjh7899a8sd989" }
  7. If you curl: curl 'https://www.googleapis.com/oauth2/v1/tokeninfo? access_token=ya29.AHES6Zkjhkjhahskjhskkskjh' you'll get something like: { "issued_to": "562211803675.apps.googleusercontent.com", "audience": "562211803675.apps.googleusercontent.com", "scope": "https://www.googleapis.com/auth/analytics", "expires_in": 3556 } (see below how to renew the token without having to go to ask for another "code" as in point 5)
  8. Done curl 'https://www.googleapis.com/analytics/v3/management/ accounts?access_token=ya29.AHES6Zkjhkjhahskjhskkskjh' will give you all info about your accounts, more info on the Management API REST page.
  9. How to get the data? A nice hint I could not find anywhere is that the URL of the new Analytics Dashboard provides account, web property and profile: https://google.com/analytics/web/#dashboard/default/ aACCOUNTwWEBPROPERTYpPROFILE/
  10. Which means you can get the data with the following address: curl 'https://www.googleapis.com/analytics/v3/data/ga? ids=ga:PROFILE&metrics=ga:visits&start-date=2011-12-01& end-date=2011-12-08& access_token=ya29.AHES6Zkjhkjhahskjhskkskjh'

Renew the token

You have to use the "refresh_token" received in point 8:

curl -d "client_id=562211803675.apps.googleusercontent.com
&client_secret=ZQxoOBGbvMGnZOYUrVIDXrgl
&refresh_token=1/HH9E7k5D0jakjhsd7askdjh7899a8sd989
&grant_type=refresh_token" 
https://accounts.google.com/o/oauth2/token

and you'll get a new access_token.

Below a few books on the subject from the greatest IT publisher 🙂

[amazon_link asins='0596158009,1119053064,1449358063,1491950358' template='ProductGrid' store='visualab-20' marketplace='US' link_id='82e86d83-8da5-11e7-8bf9-d7d2f8b9cb1f']

28 thoughts on “Using Google REST API for Analytics

  1. Hi,

    It is really excellent articlae. However, In above with scope "https://www.googleapis.com/auth/analytics" gave me "Invalid Credential" response while accessing Managment API. When I have changed the scope to "https://www.googleapis.com/auth/analytics.readonly" it worked well and got account informations.

  2. Hi, I know it's a while since this article was written but I really want to say how much I appreciated finding it the other day. Although what I am doing with the google API is slightly different (domain admin stuff rather than analytics), this article helped me get my head round the basics and get to a position where I could use the API at all rather than just feeling defeated. That google documentation, wow, it was like going round and around in a subway system where all the signs are in ancient Ugaritic and every station looks similar but not quire the same and you can never be sure if you're back where you started. Saved me, dude.

  3. Hello,

    First of all thanks for this useful artice, but I have a problem... when I try to get the datas (step 12) I always get this message: {"error":{"errors":[{"domain":"global","reason":"insufficientPermissions","message":"User does not have permission to perform this operation"}],"code":403,"message":"User does not have permission to perform this operation"}}

    Do you have any idea about it...?

    Regards!

    1. Are you maybe using an expired token? Or are you trying to look at analytics data you don't have permissions for?

  4. Very nice article ... even in Nov 2013. I hope the GA team takes notice of the continuing requests for correct/complete documentation, decent examples in more than just java, etc. I hope they set aside the chagrin undoubtedly felt and just address the issues.

  5. Thank you really much for this blog post, it worked like a charm for me! It amazes me that almost 3 years later this is the best documentation out there for dealing with the OAuth + Analytics report API.
    I mean, how on earth where we supposed to find out how to generate the token and all that stuff? It literally isn't explained anywhere in the documentation, they just assume you know how to generate it.

  6. Thank you so very much. Like JPT, I spent the afternoon banging my head against the keyboard.

    Google should hire you to write useful documentation

  7. Just what I have been after and being a software tester trying to expand my wings, this was truly helpful. As another person commented, I have spent all afternoon trying to find out how to extract data from GA using curl. Thank you, thank you, thank you.

    The google documents are truly confusing and not explicit at all.

  8. Thanks A LOT for this blogpost. I wasn't able to auth with OAUTH at a webserver without browser and this helped me to solve the auth problem (after spending countless hours with the useless documentation @ Google). One little question: Do you see any disadvantage when I request every time a new token instead using a token till it's invalid? (I run my scrips only a low count of time a day)

    Best regards from Switzerland 🙂

    1. Andy, thank you for the comment! If it is for testing, I see no problem –but for production I'd use the same token till it's valid...

  9. All I needed was some simple page-view queries.. how hard can it be? 8 hours later and nothing but pain. Screw OAuth2 and all the scrappy Python3 libs.

    Then I found this post, got my stuff working in an hour. You're my hero of the day.

    Once you get the access_token it's easy to use HTTP call you make in the GA Query Explorer: https://ga-dev-tools.appspot.com/query-explorer/ It has a widget where it outputs the URL, just replace the access_token param and we're good.

  10. This is really cool! I was up and running with my own cURL based wrapper in no time. You are a life saver!

  11. I would like to say thank you for the write-up.

    Google Analytic's API isn't exactly easy to automate with this has helped me a lot!

  12. Funny how I keep finding my way back to this article over the years. It's like meeting an old lover; instantly memorize the good times, and the bad. Glad to chat up, glad to move along. Thanks 😀

    1. Funny how Google still hasn't improved its documentation, or improved the API, or whatever! Every year I expect this post to become obsolete, and yet... here it is! Thanks for commenting:)

  13. For some reason I'm not having success with this.
    I'm trying to get the Google Drive API up and running.

    I'm able to get through 6 if and only if I exclude "redirect_url".
    So it's...
    curl -d 'client_id=[client_id] \
    &scope=https://www.googleapis.com/auth/drive.file \ (from https://stackoverflow.com/questions/19193031/google-drive-not-listing-files-in-folder)
    &response_type=code' \
    'https://accounts.google.com/o/oauth2/device/code'

    At that point the return is...
    {
    "device_code": "[device_code]",
    "user_code": "[user_code]",
    "expires_in": 1800,
    "interval": 5,
    "verification_url": "https://www.google.com/device"
    }

    So far so good. Then I'm stuck at step
    Tried various iterations of the following:
    curl -H 'Content-Type: application/x-www-form-urlencoded' \
    -d 'client_id=[client_id] \
    &client_secret=[client_secret] \
    &grant_type=authorization_code \
    &redirect_uri=urn:ietf:wg:oauth:2.0:oob
    &code=[device_code_from_above]' \
    'https://accounts.google.com/o/oauth2/token'

    The above returns {"error" : "invalid_grant", "error_description" : "Malformed auth code."}
    If 'grant_type' is changed to 'http://oauth.net/grant_type/device/1.0', response is {"error" : "invalid_request", "error_description" : "Parameter not allowed for this message type: redirect_uri"}
    If 'redirect_uri' is removed the response is {"error" : "authorization_pending"}

    That's just a sampling of the attempts. Stymied.

Leave a Reply

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.