Using API Key to authenticate a request generates a 401 error

44258 views
Skip to first unread message

Matteo Galli

unread,
Dec 14, 2011, 6:49:57 AM12/14/11
to google-analytics...@googlegroups.com
Hi

it is my understand that I can append &key=API_KEY to each REST request in order to authenticate my request instead of going with the OAuth way.

Unfortunately when I try fetch this url

https://www.googleapis.com/analytics/v3/data/ga?ids=ga:12345&start-date=2008-10-01&end-date=2008-10-31&metrics=ga:visits,ga:bounces&key=API_KEY (where API_KEY is a key generated through the API console and is a "Key for server apps (with IP locking)")

the server replies with a 

{"error":{"errors":[{"domain":"global","reason":"required","message":"Login Required","locationType":"header","location":"Authorization"}],"code":401,"message":"Login Required"}}

(of course I do change the ids parameter as well)

what's wrong with this?

thanks in advance for any help!

abeautifulsite

unread,
Dec 14, 2011, 7:13:21 AM12/14/11
to google-analytics-api - GA Data Export API
I believe you still need to pass "Authorization: Oauth {access token}"
in your headers.

On Dec 14, 6:49 am, Matteo Galli <m...@troublezine.it> wrote:
> Hi
>
> it is my understand that I can append &key=API_KEY to each REST request in
> order to authenticate my request instead of going with the OAuth way.
>
> Unfortunately when I try fetch this url
>

> https://www.googleapis.com/analytics/v3/data/ga?ids=ga:12345&start-da...

Matteo Galli

unread,
Dec 14, 2011, 7:18:42 AM12/14/11
to google-analytics...@googlegroups.com
Hi 

thank you for your help. However, I can't understand why I must indicate the access token when the documentation states in several places that I can either use the OAuth mechanism or the &key=API_KEY parameter in the request URL.

Matteo

Nick

unread,
Jan 3, 2012, 8:38:43 PM1/3/12
to google-analytics-api - GA Data Export API
Hi,

You can continue to use OAuth 1.0a when migrating between version 2.3
and 2.4 by appending the ?key= paramater.

Buth OAuth requires a scope and the scope has changed between
versions. So you will need to also update the scope of your auth token
and get a new token.

-Nick

On Dec 14 2011, 3:49 am, Matteo Galli <m...@troublezine.it> wrote:
> Hi
>
> it is my understand that I can append &key=API_KEY to each REST request in
> order to authenticate my request instead of going with the OAuth way.
>
> Unfortunately when I try fetch this url
>
> https://www.googleapis.com/analytics/v3/data/ga?ids=ga:12345&start-da...

Benefits.gov

unread,
Jan 11, 2012, 3:02:35 PM1/11/12
to google-analytics...@googlegroups.com
I am also having this exact same problem. I use the Data Feed Query Explorer to generate a URI then append the browser API key to the URL. I get the following message -


Authorization required

Error 401



I just started using this w/ the new version, I need to get data without authorization.

Nick

unread,
Jan 12, 2012, 4:25:02 PM1/12/12
to google-analytics-api - GA Data Export API
Hi,

So there are 3 parts to building queries with our API
1 - registering for an app ID and specifying it as a query parameter
called "key"
2 - authenticating and passing an access token in the header or as a
query parameter called "access_token"
3 - building a GA query with the required query parameters

If you use OAuth 2.0, the app ID in part 1 is part of the access token
so you don't need to use a key.

If you use any other Auth mechanism, then you must specify the app ID
in the key parameter as well as passing the authorization token in a
header or via a query parameter.

So unfortunately, you can't just copy / paste the URL from the query
explorer to get data.

-Nick

On Jan 11, 12:02 pm, "Benefits.gov" <govbenef...@live.com> wrote:
> I am also having this exact same problem. I use the *Data Feed Query
> Explorer* to generate a URI then append the browser API key to the URL. I

FM_Flame

unread,
Jan 16, 2012, 7:45:37 PM1/16/12
to google-analytics...@googlegroups.com
Hi Nick, I see you have an understanding of how things work and while it should be easy to do this, I already wasted a lot of hours reading and getting nowhere to get 1 stupid piece of data.

All I need to get from my google analytics profile is the number of unique events for a specific event label. In this case the event label is a video_title and the unique events represent how many times the video has been played. Simple heh ?

So I need to get this number so I can show in my web page next to my video how many times this video has been watched. That's it... I can't force users to authenticate every time they want to see a simple thing as that so authentication should be automatic and the webpage should be able to get that small piece of data of its own.

Like the rest of the guys I've read this page:
http://code.google.com/apis/analytics/docs/gdata/home.html
and for the php client:
http://code.google.com/p/google-api-php-client/

On several places I've read I can use only the API key to avoid authentication and I've found NOWHERE and example of how to do that except, which is from 2009 but seems to do the trick and has nothing to do with this undocumented with no example new Google Analytics API stuff and oAuth...
http://code.google.com/p/gapi-google-analytics-php-interface/

So... the big question is... could you please please please give us a small example (I'm hoping php) of how the hell do we get some google analytic data with automatic authentication (no user interaction) ?



Panayotis Matsinopoulos

unread,
Jan 18, 2012, 2:48:19 AM1/18/12
to google-analytics...@googlegroups.com
Hi FM_Flame and others,

It is not OAuth, it is not OAuth 2.0, it is not authorization token, it is not access token....that you need to pass. It is pure and simply login info.

The documentation says that you can query using the API Key alone. However, up to my knowledge and what I have tried yesterday, this is almost true. Not entirely true. The truth is that 

1) You need to send a request to login to Google Analytics. This will return to you an authentication token. Note that the credentials you use are any username/password that has access to the analytics that you want to retrieve. A hint that I can give you here is that the login url for Google Analytics is 'https://www.google.com/accounts/ClientLogin'.

2) You use this authentication token in an 'Authorization' header with value 'GoogleLogin auth=auth_token' (where you replace auth_token with what you got from response 1) in every subsequent request to get Google Analytics data, together with the 'key' parameter you got from Google APIs Console for your registered application.

I have done it yesterday using ruby, not php, and it works. If you know how to do GET and POSTS then with little work you can done. I plan to publish code when I have it polished. It is not ready to be published now, that is why I do not post it here.

I hope that these notes will help you somehow

Panayotis


FM_Flame

unread,
Jan 18, 2012, 5:41:23 AM1/18/12
to google-analytics...@googlegroups.com
Hi, thanks for sharing!

Anyways I've managed to solve this myself. I used the official php example and replaced the session with mysql -> saved the token there and from then on I retrieve it and use it to authenticate indefinitely, since it appears that the token that you get this way contains the access and the refresh token. So the authorization happens just once from an admin page I've created for myself and the users just use that token when they view the page to get the data from my google analytics profile.

Now it seems very simple and logical... but hey... you can read 50 pages of docs but you won't read about that simply put and explained...

Anyway, I hope that info helps someone else ;)

Panayotis Matsinopoulos

unread,
Jan 18, 2012, 5:57:00 AM1/18/12
to google-analytics...@googlegroups.com
Ok. Maybe you need to take care of expirations of the token that you have been given. I think they do not last forever.
BTW, yes, sometimes the Google documentation is frustrating.

Nick

unread,
Jan 18, 2012, 11:12:02 AM1/18/12
to google-analytics-api - GA Data Export API
Right,

We don't support Client Login for v3 due to security issues of passing
user name and passwords in API requests.

Instead we support OAuth. Which means users should only use their
Google credentials on a domain owned by Google.

If you need to automate requesting data, you should be able to hard
code a valid refresh token in your app, then use that token to get new
access tokens.

-Nick



On Jan 18, 8:48 am, Panayotis Matsinopoulos

Goss Development

unread,
Jun 19, 2012, 10:43:09 AM6/19/12
to google-analytics...@googlegroups.com
Hi Nick,
 
That's what I want to do, But.... i am struggling to get it to work in Java. This is what I tried so far:
1. obntained an access token and refresh token using Oauth Playground, and cut and pasted them into my Java program.
2. Used the access token to retrieve data from Google Analytics.
 
It works for a while, until it expires. All efforts made to get a fresh access token using the refresh token failed. Can you please pass me a code snippet to do this (in Java).
 
Best
 
Gossdev

Nick

unread,
Jun 19, 2012, 7:39:28 PM6/19/12
to google-analytics...@googlegroups.com
The access token can be copied and pasted...but it will expire after an hour.

The refresh token is tied to the credentials, client ID and Redirect URI obtained in the APIs Console. So you will nee to write your own logic to get, save, and reuse your own refresh token.

-Nick

pembo13

unread,
Sep 14, 2012, 1:31:47 PM9/14/12
to google-analytics...@googlegroups.com
What is the solution for creating automated utilities using the new v3 APIs?

I have apiKey, clientId, clientSecret, what else do I need? 

I was using what apparently was an older library with no issue, but it just suddenly stopped working today. So now my utlity is dead, and the upgrade path has no documentation for automated use.

SimplePoint

unread,
Sep 21, 2012, 4:31:33 PM9/21/12
to google-analytics...@googlegroups.com
I include my access token in the url but I get an error "Invalid Credentials".  So other than taking the steps that it takes to be able to get an authorization token, and keeping it refreshed automatically, and including it in the url, what else do I need to do?

SimplePoint

unread,
Sep 26, 2012, 3:44:35 PM9/26/12
to google-analytics...@googlegroups.com
I am still having no luck here.  I have an access token, I am refreshing it automatically when needed, I send this token to get a list of calendar events and it works, immediately afterwards I call for an insert and I get the following:

{  "error": {   "errors": [    {     "domain": "global",     "reason": "required",     "message": "Login Required",     "locationType": "header",     "location": "Authorization"    }   ],   "code": 401,   "message": "Login Required"  } }

I put add the Header  "Authorization", "OAuth <my access token>"  but still I get the above error.  Anyone have any ideas?  Nothing I try is working and I am having a ton of difficulty finding someone else in my situation that has posted a solution before.

Brian White

unread,
Sep 26, 2012, 5:53:46 PM9/26/12
to google-analytics...@googlegroups.com
I could really use some help here.  I am just stuck and been that way for a week.  Please have pity on me :)

--
 
 

John Jones

unread,
Sep 27, 2012, 9:13:42 AM9/27/12
to google-analytics...@googlegroups.com
Here is my working v3 code:
Report API 3.0 Working Example coded using private key / access token / service account

Brian White

unread,
Sep 27, 2012, 9:26:30 AM9/27/12
to google-analytics...@googlegroups.com
Hey John thanks for this.  Unfortunately I think I am doing something a bit different.  I am using C# to make REST calls.  And all of my reads are successful (but I think that's only because I publicly shared my calendar for read-only purposes).  It's updates that I can't do.  I've looked to see if I didn't include the right scope but I am sure I have.  My question though is that maybe I don't have things set up correctly between the API Console and the Application Control Panel.  Until last night I thought they were the same thing but apparently not.  Anyone know what I need to check for in the Application Control Panel?

--
 
 

chris@shufflepoint

unread,
Sep 28, 2012, 11:22:10 AM9/28/12
to google-analytics...@googlegroups.com
This is the Google Analytics group not the Calendar group.
Message has been deleted

Brice Bottegal

unread,
Nov 13, 2012, 11:41:18 AM11/13/12
to google-analytics...@googlegroups.com
You can also put the token in a txt file and get the token when wanted like that in PHP :

    require_once('google-api-php-client/src/Google_Client.php');
    require_once('google-api-php-client/src/contrib/Google_AnalyticsService.php');
   
    $client = new Google_Client();
    $client->setApplicationName('');
    $client->setClientId('');
    $client->setClientSecret('');
    $client->setScopes(array('https://www.googleapis.com/auth/analytics.readonly'));

    $client->setUseObjects(true);

    $fichier = 'token.txt';
   
    if ($handle = fopen($fichier, 'r')) {
        $token = fread($handle, filesize($fichier));
        fclose($handle);
    }
   
    $client->setAccessToken($token);
   
    $analytics = new Google_AnalyticsService($client);

shyam habarakada

unread,
Apr 30, 2013, 9:17:20 PM4/30/13
to google-analytics...@googlegroups.com
Matteo, were you able to figure this out? I assume you are trying to use what the google docs call a "Simple API key" for your scenario. I'm trying to use it to access reporting data, and getting the same error.

I'm doing a curl to test like below:

Reply all
Reply to author
Forward
0 new messages