How to Use Google Search Console API With Python

Share this post

This post is part of the Guide on Python for SEO and the guide on the Google Search Console API

This tutorial is for SEOs that would like to use Google Search Console API with Python.

I will show the steps to connect to the developer console, get your API keys and give you the code to make your first API call.

To learn more, view my complete guide on Python for SEO.

Make Your First Google Search Console API call with Python

There are many things that you can do with the Search Console API like getting search traffic and extracting indexed pages.

In this post, we will make a very basic API call: get validated properties.

The steps to use Google Search Console API in Python are:

  1. Get Your Google Search Console API Key

  2. Import Libraries

  3. Authenticate to the API

  4. Make Your API Call

Step 1: Get Your Google Search Console API Key

You will need an API key to be able to connect to the Google Search Console API.

How to Get Google Search Console API Keys

What is an API Key?

An API key is like your username and password to access the API.

Follow this guide to help you get the detailed steps to get your Google Search Console API key.

Otherwise, here are the simplified steps to get your Google Search Console API keys.

  1. Go to Google’s developers console, and sign-in;
  2. Go to “Dashboard” and click “Enable APIs and Services” ;
  3. Search for “Google Search Console API” and enable the API;
  4. Go to the “credential” tab, click on “create credential” and select “OAuth Client ID”;
  5. Click on “configure the consent screen ” and give a name to your product;
  6. Choose “Other” as the application type and click create;
  7. Copy the client ID and client Secret or go-on and save to download the JSON file.

Download your API key first, and then you’ll be ready to connect to the Search Console API with Python.

Step 2: Import Libraries

To use the API you need to import libraries.

"""
Step 1: Get your JSON API Key
"""
# Make sur the you name you JSON api key client_secrets.json

"""
Step 2: Import Libraries
"""

import pandas as pd
import datetime
import httplib2
from apiclient.discovery import build
from collections import defaultdict
from dateutil import relativedelta
import argparse
from oauth2client import client
from oauth2client import file
from oauth2client import tools

Step 3. Authenticate to the API

Now, we will log in to the API using OAuth. Two options are possible. Using a JSON file (recommended), or using the API client_id and client_secret.

Choose your preferred solution.

Connect Using a JSON API Key

CLIENT_SECRETS_PATH = r'C:\Users\YOUR-PATH\client_secrets.json' # Path to client_secrets.json file.

parser = argparse.ArgumentParser(
    formatter_class=argparse.RawDescriptionHelpFormatter,
    parents=[tools.argparser])
flags = parser.parse_args([])


flow = client.flow_from_clientsecrets(
    CLIENT_SECRETS_PATH, scope=SCOPES,
    message=tools.message_if_missing(CLIENT_SECRETS_PATH))

storage = file.Storage(r'YOUR-PATH\searchconsolereporting.dat')
credentials = storage.get()

if credentials is None or credentials.invalid:
  credentials = tools.run_flow(flow, storage, flags)
http = credentials.authorize(http=httplib2.Http())

webmasters_service = build('webmasters', 'v3', http=http)

Connect Using Client_Id and Client Secrets

Make sure that you don’t forget to add your own client_id and client_secrets. You can view the notebook.

parser = argparse.ArgumentParser(
    formatter_class=argparse.RawDescriptionHelpFormatter,
    parents=[tools.argparser])
flags = parser.parse_args([])

flow = client.OAuth2WebServerFlow(client_id='XXXXXXXXXXXXXXXXXXXXXXXXXX.apps.googleusercontent.com',
                           client_secret='XXXXXXXXXXXXXXXXXXXXX',
                           scope=SCOPES)

storage = file.Storage('searchconsole.dat')

credentials = storage.get()
if credentials is None or credentials.invalid:
  credentials = tools.run_flow(flow, storage, flags)

# Create an httplib2.Http object and authorize it with our credentials
http = credentials.authorize(http=httplib2.Http())

Step 4: Make Your API Call

Now the glory!

Let’s see what websites we have validated in Google Search Console using the API.

site_list = webmasters_service.sites().list().execute()

verified_sites_urls = [s['siteUrl'] for s in site_list['siteEntry']
                       if s['permissionLevel'] != 'siteUnverifiedUser'
                          and s['siteUrl'][:4] == 'http']

for site_url in verified_sites_urls:
  print( site_url)

Full Code

Here is the full code to let you make your first API call with Python.

"""
Step 1: Get your JSON API Key
"""
# Make sur the you name you JSON api key client_secrets.json

"""
Step 2: Import Libraries
"""

import pandas as pd
import datetime
import httplib2
from apiclient.discovery import build
from collections import defaultdict
from dateutil import relativedelta
import argparse
from oauth2client import client
from oauth2client import file
from oauth2client import tools

"""
Step 3: Connect to the API
"""
site = 'https://www.yoursite.com'

SCOPES = ['https://www.googleapis.com/auth/webmasters.readonly']
DISCOVERY_URI = ('https://www.googleapis.com/discovery/v1/apis/customsearch/v1/rest')

"""
CONNECT Using JSON 
"""
CLIENT_SECRETS_PATH = r'C:\Users\YOUR-PATH\client_secrets.json' # Path to client_secrets.json file.

parser = argparse.ArgumentParser(
    formatter_class=argparse.RawDescriptionHelpFormatter,
    parents=[tools.argparser])
flags = parser.parse_args([])


flow = client.flow_from_clientsecrets(
    CLIENT_SECRETS_PATH, scope=SCOPES,
    message=tools.message_if_missing(CLIENT_SECRETS_PATH))

storage = file.Storage(r'YOUR-PATH\searchconsolereporting.dat')
credentials = storage.get()

if credentials is None or credentials.invalid:
  credentials = tools.run_flow(flow, storage, flags)
http = credentials.authorize(http=httplib2.Http())

webmasters_service = build('webmasters', 'v3', http=http)

"""
Step 4 Make your first API Call
"""

site_list = webmasters_service.sites().list().execute()

verified_sites_urls = [s['siteUrl'] for s in site_list['siteEntry']
                       if s['permissionLevel'] != 'siteUnverifiedUser'
                          and s['siteUrl'][:4] == 'http']

for site_url in verified_sites_urls:
  print( site_url)

We are done. You have successfully connected to the Google Search Console API With Python. Now we will learn how to Get All Your Search traffic With Google Search Console API.