Google Indexing API Batch request python

675 views Asked by At

I'm trying to prepare script to minimize the number of requests with batch method. In the example of my code, 5 URLs are requested, for this I spent 5 publish requests. How can I change the code to update 5 urls in one request?

enter image description here

https://googleapis.github.io/google-api-python-client/docs/batch.html

from oauth2client.service_account import ServiceAccountCredentials
from googleapiclient.discovery import build 
from googleapiclient.http import BatchHttpRequest
import httplib2
import json
 
requests = {'https://test.com/1': 'URL_UPDATED',
                'https://test.com/2': 'URL_UPDATED',
                'https://test.com/3': 'URL_UPDATED',
                'https://test.com/4': 'URL_UPDATED',
                'https://test.com/5': 'URL_UPDATED',
           }
 
JSON_KEY_FILE = "credentials.json"
 
SCOPES = [ "https://www.googleapis.com/auth/indexing" ]
ENDPOINT = "https://indexing.googleapis.com/v3/urlNotifications:publish"
 
# Authorize credentials
credentials = ServiceAccountCredentials.from_json_keyfile_name(JSON_KEY_FILE, scopes=SCOPES)
http = credentials.authorize(httplib2.Http())
 
# Build service
service = build('indexing', 'v3', credentials=credentials)
 
def insert_event(request_id, response, exception):
    if exception is not None:
        print(exception)
    else:
        print(response)

#batch = service.new_batch_http_request(callback=insert_event)
batch = service.new_batch_http_request()

for url, api_type in requests.items():
    batch.add(service.urlNotifications().publish(
        body={"url": url, "type": api_type}), callback=insert_event)

batch.execute()
1

There are 1 answers

0
Se7enDays On

To do a batch request replace your ENDPOINT with

ENDPOINT = "https://indexing.googleapis.com/batch"

However, 200 is the limit of "publish" requests daily. The batch API allows sending up to 100 "publish" requests in one HTTP request, but still will count towards 100 in your quota. Using Batch doesn't give you more requests.