Google Webmaster Search Console API

Suppose we have web site, and want to grab its page stats via webmaster api

There is dedicated search analytics query which will return top 10 pages sorted by click count

To do so we gonna need to enable Google Search Console API in our project

Then we gonna need to create service account and grab its json key

Put this key somewhere and point GOOGLE_APPLICATION_CREDENTIALS environment variable to its path

Now go to Google Search Console and add email of added service account to your site

After all this steps done we might query our stats:

const { google } = require('googleapis')

const main = async () => {
  const webmasters = google.webmasters('v3')
  const auth = new google.auth.GoogleAuth({
    scopes: ['https://www.googleapis.com/auth/webmasters.readonly']
  })

  google.options({
    auth: await auth.getClient()
  })

  const {
    data: { rows }
  } = await webmasters.searchanalytics.query({
    siteUrl: 'https://mac-blog.org.ua',
    requestBody: {
      startDate: new Date(Date.now() - 8 * 24 * 60 * 60 * 1000).toISOString().split('T').shift(),
      endDate: new Date(Date.now() - 1 * 24 * 60 * 60 * 1000).toISOString().split('T').shift(),
      dimensions: ['page'],
      rowLimit: 5
    }
  })

  return rows
}

main().then(console.log).catch(console.error)

And if everything fine will retrieve our results:

[
  {
    "keys": ["https://mac-blog.org.ua/kafka-command-line-tools/"],
    "clicks": 44,
    "impressions": 1607,
    "ctr": 0.027380211574362167,
    "position": 25.266957062850032
  },
  {
    "keys": ["https://mac-blog.org.ua/wordpress-custom-database-table-example-full/"],
    "clicks": 37,
    "impressions": 958,
    "ctr": 0.038622129436325675,
    "position": 19.04801670146138
  },
  {
    "keys": ["https://mac-blog.org.ua/c-custom-app-config-sections/"],
    "clicks": 33,
    "impressions": 804,
    "ctr": 0.041044776119402986,
    "position": 13.894278606965175
  },
  {
    "keys": ["https://mac-blog.org.ua/rabbitmq-python-example/"],
    "clicks": 33,
    "impressions": 1121,
    "ctr": 0.029438001784121322,
    "position": 11.581623550401428
  },
  {
    "keys": ["https://mac-blog.org.ua/docker-localhost-ssl/"],
    "clicks": 32,
    "impressions": 643,
    "ctr": 0.049766718506998445,
    "position": 20.94090202177294
  }
]