Álvaro
Álvaro

Reputation: 2588

Connect to google search console API from Node.js

I am trying to get data from google search console https://www.googleapis.com/webmasters/v3/sites but from Node backend not the front end, I have created OAuth 2.0 Client IDs and API key on the google api console. But I can find the way to connect.

I am following this guide https://googleapis.dev/nodejs/googleapis/latest/searchconsole/index.html

I just want to be able to make read requests from node.

I tried this

import { google } from 'googleapis'

const auth = new google.auth.OAuth2(
  YOUR_CLIENT_ID,
  YOUR_CLIENT_SECRET,
  YOUR_REDIRECT_URL
);

google.options({ auth })

const searchconsole = google.webmasters({ version: 'v3', auth })

const sites = await searchconsole.sites.list({})
console.log(sites)

I get this error even thou all the credentials are correct

'Error: No access, refresh token, API key or refresh handler callback is set.'

Upvotes: 3

Views: 2012

Answers (1)

Ruben Restrepo
Ruben Restrepo

Reputation: 1196

According to the comments, seems you already got the authorization pieces working, now, if you want to list the sites to get search analytics data for each owned site by the authorizing user, you can do something like the following code:

Use Google Search Console API                                                                                 Run in Fusebit
const webmasters = googleClient.webmasters('v3');

// List the owned sites
const sites = await webmasters.sites.list({});
const sitesAnalytics = [];
  
for await (const site of sites.data.siteEntry) {
  const response = await webmasters.searchanalytics.query({
    siteUrl: site.siteUrl,
    requestBody: {
      startDate: '2021-01-01',
      endDate: new Date().toISOString().split('T')[0],
     },
   });

  sitesAnalytics.push({ site, analytics: response.data});
}

console.log = `Got a successful response from Google Search Console: ${JSON.stringify(sitesAnalytics)}`;


Upvotes: 3

Related Questions