Google Analytics API via cURL

I spend a lot of time in Google Analytics creating custom reports for various things. I usually start with Google Analytics Query Explorer to make sure I’m getting the right data before creating a script to pull in the data for the report.

Once I’ve got a good result set, I’ll use cygwin with cURL (and the script below) to grab the xml so I can see how Google actually returns it.

There’s nothing tricky about it & the comments should tell you everything you need to fill in / do. I do use date to get the last 30 days of data, but you can change that to match the range that makes sense for you.


#!/bin/bash
USER_EMAIL="" #Insert your Google Account email address here
USER_PASS="" #Insert your password here
TABLE_ID="" #Insert your table ID here (ie ga:123456)
METRICS="ga:visits" #Required
DIMENSIONS="ga:source" #Optional
SEGMENT="" #Optional. Add to the query below if needed
FILTERS="" #Optional. Add to the query below if needed
SORT="-ga:visits" #Optional
START_DATE=$(date -d "-30 days" +%Y-%m-%d) #Required
END_DATE=$(date -d "-1 day" +%Y-%m-%d) #Required
MAX_RESULTS="10"
#### Get Google Auth Token
googleAuth="$(curl https://www.google.com/accounts/ClientLogin \
-d Email=$USER_EMAIL \
-d Passwd=$USER_PASS \
-d accountType=GOOGLE \
-d source=curl-dataFeed-v2 \
-d service=analytics \
| awk /Auth=.*/)"
##### Send Token & Query to Google
curl -H "Authorization: GoogleLogin $googleAuth" -k \
"https://www.google.com/analytics/feeds/data\
?ids=$TABLE_ID\
&dimensions=$DIMENSIONS\
&metrics=$METRICS\
&sort=$SORT\
&start-date=$START_DATE\
&end-date=$END_DATE\
&max-results=$MAX_RESULTS

This is based on code from ga-api-http-samples for API Version 2 by api.nickm on Dec 14, 2009. It used to be easy to find on the example libraries page, but has been removed for a while.

Leave a Reply