I think you all know Google Analytics.
A Google Analytics API has long been one of the most widely anticipated (and wanted from developers) features. On April 21st, 2009 the official blog announced that the Google Analytics Data Export API beta is now publicly available to all Analytics users.
The API will allow developers to extend Google Analytics in new and creative ways and integrate Google Analytics into their existing products and create standalone applications that they sell.
Read more at the official post.
So I think it’s time to play a bit with this new toy.
Today we’ll learn how to autenticate to the service.
I made the script you are about to see reading the information at this page.
Line 3: Setting the header to
text/plain because I am going to output plain text instead of html
Lines 5-6: Assigning to two variables my Analytics email and password. Obviously replace the
xxx with your correct Analytics email and password
Line 8: Initializing a
cURL handle. I am using it to communicate to Google servers using
HTTP protocol and pass variables in
POST mode. More information about the cURL library at this link.
Lines 9-12: Setting some options for the cURL handle.
CURLOPT_URL is the URL to fetch,
CURLOPT_POST to perform a HTTP POST,
CURLOPT_HEADER to include the header in the output and
CURLOPT_POSTFIELDS contains the full data to post in a HTTP “POST” operation.
This way I am simulating an HTML form submission to
Let’s take a look at the variables I am sending:
accountType: Type of account to be authenticated. The default is
Email: The user’s email address.
Passwd: The user’s password.
service: The Analytics service name is
source: A string identifying your client application in the form
companyName-applicationName-versionID (actually you can write whatever you want).
Lines 13 and 14 perform and close the cURL session.
This is the result if everything went fine:
HTTP/1.1 200 OK Content-Type: text/plain Cache-control: no-cache, no-store Pragma: no-cache Expires: Mon, 01-Jan-1990 00:00:00 GMT Date: Sat, 25 Apr 2009 19:02:11 GMT X-Content-Type-Options: nosniff Content-Length: 563 Server: GFE/2.0 SID=DQAAA... LSID=DQAAA... Auth=DQAAA...
Auth code is what we need to retrieve account and report data. I’ll show you how to do it next time.
At the moment I am integrating the Analytics in a control panel we provide to some customers, in order to give them access to all information from a single page.
Do you have a creative use of this API in your mind? Look at some examples at this link and you will agree this is a great feature