This post is part of the Guide on Google Search Console API
In this post, I will show you the function that I created to authorise requests to the Google Search Console API using OAuth 2.0.
To run this, you will need to get a client_secrets.json
file with your credentials. Check out how you can get Google Search Console OAuth Credentials.
Import Libraries
To run the OAuth 2.0 authentication you will need to install and import all those libraries.
Alternatively, you can clone the Github Repository that I made and run:
$ pip install -r requirements.txt
import argparse import httplib2 import requests from collections import defaultdict from dateutil import relativedelta from googleapiclient.discovery import build from oauth2client import client from oauth2client import file from oauth2client import tools
Define OAuth Function
The authorize_creds()
function will check the credentials file and define a .dat
file to save authorised credentials so you don’t have to go through the login process each time.
def authorize_creds(creds,authorizedcreds='authorizedcreds.dat'): ''' Authorize credentials using OAuth2. ''' print('Authorizing Creds') # Variable parameter that controls the set of resources that the access token permits. SCOPES = ['https://www.googleapis.com/auth/webmasters.readonly'] # Path to client_secrets.json file CLIENT_SECRETS_PATH = creds # Create a parser to be able to open browser for Authorization parser = argparse.ArgumentParser( formatter_class=argparse.RawDescriptionHelpFormatter, parents=[tools.argparser]) flags = parser.parse_args([]) # Creates an authorization flow from a clientsecrets file. # Will raise InvalidClientSecretsError for unknown types of Flows. flow = client.flow_from_clientsecrets( CLIENT_SECRETS_PATH, scope = SCOPES, message = tools.message_if_missing(CLIENT_SECRETS_PATH)) # Prepare credentials and authorize HTTP # If they exist, get them from the storage object # credentials will get written back to the 'authorizedcreds.dat' file. storage = file.Storage(authorizedcreds) credentials = storage.get() # If authenticated credentials don't exist, open Browser to authenticate if credentials is None or credentials.invalid: credentials = tools.run_flow(flow, storage, flags) # Add the valid creds to a variable # Take the credentials and authorize them using httplib2 http = httplib2.Http() # Creates an HTTP client object to make the http request http = credentials.authorize(http=http) # Sign each request from the HTTP client with the OAuth 2.0 access token webmasters_service = build('webmasters', 'v3', http=http) # Construct a Resource to interact with the API using the Authorized HTTP Client. print('Auth Successful') return webmasters_service
Run OAuth 2.0
To run the code, simply add your credentials and run authorize_creds()
. Once this is done you will be able to run Google Search Console API using the webmasters_service
variable.
if __name__ == '__main__': creds = 'client_secrets.json' webmasters_service = authorize_creds(creds)
The if name equals main line checks whether you are running the module or importing it. If you are importing it, authorize_creds()
will not run.
Run a simple GSC API Call
You can try to get verified properties to check whether the authentication with OAuth 2.0 worked or not.
def get_property_list(webmasters_service): ''' Get a list of validated properties from GSC ''' site_list = webmasters_service.sites().list().execute() # Filter for verified websites verified_sites_urls = [s['siteUrl'] for s in site_list['siteEntry'] if s['permissionLevel'] != 'siteUnverifiedUser' and s['siteUrl'][:4] == 'http'] return verified_sites_urls verified_sites_urls = get_property_list(webmasters_service)
The code above comes from the post “How to extract Verified Properties using Google Search Console API and Python“.
Full Code
You can also get the full code on Github.
import argparse import httplib2 import requests from collections import defaultdict from dateutil import relativedelta from googleapiclient.discovery import build from oauth2client import client from oauth2client import file from oauth2client import tools def authorize_creds(creds,authorizedcreds='authorizedcreds.dat'): ''' Authorize credentials using OAuth2. ''' print('Authorizing Creds') # Variable parameter that controls the set of resources that the access token permits. SCOPES = ['https://www.googleapis.com/auth/webmasters.readonly'] # Path to client_secrets.json file CLIENT_SECRETS_PATH = creds # Create a parser to be able to open browser for Authorization parser = argparse.ArgumentParser( formatter_class=argparse.RawDescriptionHelpFormatter, parents=[tools.argparser]) flags = parser.parse_args([]) # Creates an authorization flow from a clientsecrets file. # Will raise InvalidClientSecretsError for unknown types of Flows. flow = client.flow_from_clientsecrets( CLIENT_SECRETS_PATH, scope = SCOPES, message = tools.message_if_missing(CLIENT_SECRETS_PATH)) # Prepare credentials and authorize HTTP # If they exist, get them from the storage object # credentials will get written back to the 'authorizedcreds.dat' file. storage = file.Storage(authorizedcreds) credentials = storage.get() # If authenticated credentials don't exist, open Browser to authenticate if credentials is None or credentials.invalid: credentials = tools.run_flow(flow, storage, flags) # Add the valid creds to a variable # Take the credentials and authorize them using httplib2 http = httplib2.Http() # Creates an HTTP client object to make the http request http = credentials.authorize(http=http) # Sign each request from the HTTP client with the OAuth 2.0 access token webmasters_service = build('webmasters', 'v3', http=http) # Construct a Resource to interact with the API using the Authorized HTTP Client. print('Auth Successful') return webmasters_service if __name__ == '__main__': creds = 'client_secrets.json' webmasters_service = authorize_creds(creds)
Further Considerations
I just stumbled on this video helping understanding the risks of OAuth. In time, I will update it to add CSRF tokens.
For now, here you go for your own interest.
Here you go, you are now authenticated to authorize Requests to the Google Search Console API. Check the full guide on Python for SEO if you want to learn more Python SEO trick.
Sr SEO Specialist at Seek (Melbourne, Australia). Specialized in technical SEO. In a quest to programmatic SEO for large organizations through the use of Python, R and machine learning.