<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Patrick Hartman &#187; google analytics</title>
	<atom:link href="http://www.patrickhartman.com/category/google-analytics/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.patrickhartman.com</link>
	<description>web development, photoshop scripting and other thoughts</description>
	<lastBuildDate>Thu, 18 Feb 2010 06:57:13 +0000</lastBuildDate>
	<generator>http://wordpress.org/?v=2.9.2</generator>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
			<item>
		<title>Using Perl for Google Analytics API</title>
		<link>http://www.patrickhartman.com/2009/08/10/using-perl-for-google-analytics-api/</link>
		<comments>http://www.patrickhartman.com/2009/08/10/using-perl-for-google-analytics-api/#comments</comments>
		<pubDate>Tue, 11 Aug 2009 01:47:46 +0000</pubDate>
		<dc:creator>Patrick</dc:creator>
				<category><![CDATA[google analytics]]></category>
		<category><![CDATA[perl]]></category>

		<guid isPermaLink="false">http://www.patrickhartman.com/?p=13</guid>
		<description><![CDATA[We use Google Analytics at work, and it has always been painful to create any kind of automated reports using that data. To date I have had to setup scheduled .csv reports to myself, parse them and import the into a database. It was definitely a pain to setup and maintain, so I was thrilled [...]]]></description>
			<content:encoded><![CDATA[<p>We use Google Analytics at work, and it has always been painful to create any kind of automated reports using that data. To date I have had to setup scheduled .csv reports to myself, parse them and import the into a database. It was definitely a pain to setup and maintain, so I was thrilled to see Google finally released a <a href="http://code.google.com/apis/analytics/docs/">API for Google Analytics</a>. I decided to put this together to help give people a starting point for using their Google Analytics information in their Perl programs.</p>
<p>The first thing you will need to do is request a token from Google. This is what you will use to authenticate yourself on all data feed requests for your session. </p>
<pre class="brush: perl;">
#!/usr/bin/perl -w
use strict;
use LWP::UserAgent;
use XML::Simple;

# this sub will return the token you need to authenticate api requests
# you need to pass your ga login and password to it
sub gaGetToken {
    # arguments passed to this function
    my $user = $_[0];
    my $pass = $_[1];

    # create user agent object
    my $ua = LWP::UserAgent->new;
    $ua->agent("MyApp/0.1 ");

    # Create a request
    my $req = HTTP::Request->new(POST => 'https://www.google.com/accounts/ClientLogin');
    $req->content_type('application/x-www-form-urlencoded');
    $req->content("accountType=GOOGLE&#038;Email=$user&#038;Passwd=$pass&#038;service=analytics&#038;source=companyName-applicationName-versionID");

    # Pass request to the user agent and get a response back
    my $res = $ua->request($req);

    # declare variable
    my $token;

    # Check the outcome of the response
    if ($res->is_success) {
        # look at the result
        if ($res->content =~ m/(?<=Auth=).*/im) {
            # store token so it can be used in subsequent requests
            $token = $&#038;;
        }
    }
    else {
        # return the error if there was a problem
        return "error: ". $res->status_line;
        die;
    }

    # return the token
    return $token;
}

# authenticate with the API to receive token
my $token = &#038;gaGetToken('username','password');
</pre>
<p>This will give you the token you need to make other requests. Now you have the token, you can request a data feed of the analytics account information that is tied to your Google account. The way I chose to handle this is the parse the feed and return an array of account names and account numbers.</p>
<pre class="brush: perl; first-line: 48;">
# this sub will return an array of all your ga accounts
# you need to pass your token to it
sub gaAccounts {
    # the token you passed to this sub
    my $token = $_[0];

    # create user agent object
    my $ua = LWP::UserAgent->new;
    $ua->agent("MyApp/0.1 ");

    # add authorization to headers
    my @headers = (Authorization => "GoogleLogin Auth=$token");

    # request the accounts feed
    my $res = $ua->get("https://www.google.com/analytics/feeds/accounts/default", @headers);

    # define accounts array
    my @accounts;

    # if the request was successful...
    if ($res->is_success) {
        # declare variables
        my ($content, $e);

        # this is the xml it returns
        $content = $res->content;

        # create a xml object for the response
        my $xml = new XML::Simple(KeyAttr=>[]);
        my $tree = $xml->XMLin($content);

        # iterate through each entry
        my $x = 0;
        foreach $e (@{$tree->{entry}})
        {
            # add the account to the array
            $accounts[$x][0] = $e->{title}->{content};
            $accounts[$x][1] = $e->{'dxp:tableId'};
            $x++
        }
    } else {
        # return the error if there was a problem
        return "error: ". $res->status_line;
        die;
    }

    # return the array of accounts
    return @accounts;
}

# get array of all sites in your account
my @sites = &#038;gaAccounts($token);

# list all the sites in the array
foreach(@sites) {
    print $_->[0] ." => ". $_->[1] ."\n";
}

# going forward, we will use the first account number
my $website = $sites[0][1];
</pre>
<p>Now you have a token and account number, you have everything you need to make data feed requests for the Google Analytics information for that account. Here is a example of getting visits by day:</p>
<pre class="brush: perl; first-line: 108;">
# this sub will return the xml from a datafeed request
# you need to pass your token to it
sub gaDataFeed {
    # arguments passed to this function
    my $url = $_[0];
    my $token = $_[1];    

    # create user agent object
    my $ua = LWP::UserAgent->new;
    $ua->agent("MyApp/0.1 ");

    # add authorization to headers
    my @headers = (Authorization => "GoogleLogin Auth=$token");

    # request page
    my $res = $ua->get($url, @headers);

    my $content;

    # if the request was successful...
    if ($res->is_success) {
        # this is the xml response
        $content = $res->content;
    } else {
        # return the error if there was a problem
        return "error: ". $res->status_line;
        die;
    }

    # return the xml
    return $content;
}

# to test, lets request visit by day
my $pageviews = &#038;gaDataFeed("https://www.google.com/analytics/feeds/data?ids=$website&#038;dimensions=ga%3Adate&#038;metrics=ga%3Avisits&#038;start-date=2009-07-27&#038;end-date=2009-08-10&#038;max-results=365", $token);

# create a xml object for the response
my $xml = new XML::Simple(KeyAttr=>[]);
my $tree = $xml->XMLin($pageviews);

# iterate through each entry in the xml
foreach my $e (@{$tree->{entry}})
{
    # date value
    print $e->{'dxp:dimension'}->{value};
    print " : ";
    # visitors value
    print $e->{'dxp:metric'}->{value};
    print "\n";
}
</pre>
<p>That is the basics, you can use the above to access just about anything in your Google Analytics account. There is a good <a href="http://code.google.com/apis/analytics/docs/gdata/gdataExplorer.html">query explorer</a> that you can use to generate and test data feed request URI&#8217;s. I hope this helps you get started with Google Analytics and Perl.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.patrickhartman.com/2009/08/10/using-perl-for-google-analytics-api/feed/</wfw:commentRss>
		<slash:comments>11</slash:comments>
		</item>
	</channel>
</rss>
