最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Unable to query Google Search Console API using a Service Account - Stack Overflow

programmeradmin1浏览0评论

I need to retrieve some data from Google Search Console (Webmaster Tools) using a service account.

So far I've been able to retrieve an access_token for the service account which I need to append to the url of the request. The problem is that I can't find a way to do so, this is the code i'm using:

function retrieveSearchesByQuery(token)
    {
        gapi.client.webmasters.searchanalytics.query(
        {
            'access_token': token,
            'siteUrl': '',
            'fields': 'responseAggregationType,rows',
            'resource': {
                'startDate': formatDate(cSDate),
                'endDate': formatDate(cEDate),
                'dimensions': [
                    'date'
                ]
            }
        })
        .then(function(response) {
            console.log(response);
        })
        .then(null, function(err) {
            console.log(err);
        });
    }

This is the url called by the function:

.WEBSITE/searchAnalytics/query?fields=responseAggregationType%2Crows&alt=json"

Instead it should be something like this:

.WEBSITE/searchAnalytics/query?fields=responseAggregationType%2Crows&alt=json&access_token=XXX"

The gapi.client.webmasters.searchanalytics.query doesn't recognize 'access_token' as a valid key thus it doesn't append it to the url and that's why I get a 401 Unauthorized as response.

If I use 'key' instead of 'access_token' the parameter gets appended to the url but 'key' is used for OAuth2 authentication so the service account token I pass is not valid.

Does anyone have a solution or a workaround for this?

I need to retrieve some data from Google Search Console (Webmaster Tools) using a service account.

So far I've been able to retrieve an access_token for the service account which I need to append to the url of the request. The problem is that I can't find a way to do so, this is the code i'm using:

function retrieveSearchesByQuery(token)
    {
        gapi.client.webmasters.searchanalytics.query(
        {
            'access_token': token,
            'siteUrl': 'http://www.WEBSITE.',
            'fields': 'responseAggregationType,rows',
            'resource': {
                'startDate': formatDate(cSDate),
                'endDate': formatDate(cEDate),
                'dimensions': [
                    'date'
                ]
            }
        })
        .then(function(response) {
            console.log(response);
        })
        .then(null, function(err) {
            console.log(err);
        });
    }

This is the url called by the function:

https://content.googleapis./webmasters/v3/sites/http%3A%2F%2Fwww.WEBSITE./searchAnalytics/query?fields=responseAggregationType%2Crows&alt=json"

Instead it should be something like this:

https://content.googleapis./webmasters/v3/sites/http%3A%2F%2Fwww.WEBSITE./searchAnalytics/query?fields=responseAggregationType%2Crows&alt=json&access_token=XXX"

The gapi.client.webmasters.searchanalytics.query doesn't recognize 'access_token' as a valid key thus it doesn't append it to the url and that's why I get a 401 Unauthorized as response.

If I use 'key' instead of 'access_token' the parameter gets appended to the url but 'key' is used for OAuth2 authentication so the service account token I pass is not valid.

Does anyone have a solution or a workaround for this?

Share Improve this question edited Jul 29, 2016 at 10:15 LS_ asked Jul 29, 2016 at 7:59 LS_LS_ 7,15711 gold badges57 silver badges93 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 5 +50

If your application requests private data, the request must be authorized by an authenticated user who has access to that data. As specified in the documentation of the Search Console API, your application must use OAuth 2.0 to authorize requests. No other authorization protocols are supported.

If you application is correctly configured, when using the Google API, an authenticated request looks exactly like an unauthenticated request. As stated in the documentation, if the application has received an OAuth 2.0 token, the JavaScript client library includes it in the request automatically.

You're mentioning that you have retrieved an access_token, if correctly received, the API client will automatically send this token for you, you don't have to append it yourself.

A very basic workflow to authenticate and once authenticated, send a request would looks like the following code. The Search Console API can use the following scopes: https://www.googleapis./auth/webmasters and https://www.googleapis./auth/webmasters.readonly.

var clientId = 'YOUR CLIENT ID';
var apiKey = 'YOUR API KEY';
var scopes = 'https://www.googleapis./auth/webmasters';

function auth() {
  // Set the API key.
  gapi.client.setApiKey(apiKey);

  // Start the auth process using our client ID & the required scopes.
  gapi.auth2.init({
      client_id: clientId,
      scope: scopes
  })
  .then(function () {
    // We're authenticated, let's go...
    // Load the webmasters API, then query the API
    gapi.client.load('webmasters', 'v3')
      .then(retrieveSearchesByQuery);
  });
}

// Load the API client and auth library
gapi.load('client:auth2', auth);

At this point, your retrieveSearchesByQuery function will need to be modified since it doesn't need to get a token by argument anymore in order to pass it in the query. The JavaScript client library should include it in the request automatically.

You can also use the API Explorer to check what parameters are supported for a specific query and check the associated request.

If you need to use an externally generated access token, which should be the case with a Service Account, you need to use the gapi.auth.setToken method to sets the OAuth 2.0 token object yourself for the application:

gapi.auth.setToken(token_Object);
发布评论

评论列表(0)

  1. 暂无评论