Home > other >  How to fix Google Indexing API inside loop problem?
How to fix Google Indexing API inside loop problem?

Time:10-21

I have a Google index API code that works. The code is following:

from oauth2client.service_account import ServiceAccountCredentials 
import httplib2 

SCOPES = ["https://www.googleapis.com/auth/indexing"] 
ENDPOINT = "https://indexing.googleapis.com/v3/urlNotifications:publish" 
# service_account_file.json is the private key
# that you created for your service account. 
JSON_KEY_FILE = "/content/astute-tractor-329613-1baed60ec1c0.json" 
credentials = ServiceAccountCredentials.from_json_keyfile_name(JSON_KEY_FILE, scopes=SCOPES) 

http = credentials.authorize(httplib2.Http()) 

content = """{ 
"url": "https://sitename.com/index.php", 
"type": "URL_UPDATED" 
}""" 

response, content = http.request(ENDPOINT, method="POST", body=content)

if response.status == 200:
    print(f'The submission was successful. Google reported a {response.status} response code.')
else:
    print(f'The submission was not successful. Google reported a {response.status} response code, instead of 200.')

I can add URLs one by one with it but I want to feed it a CSV file so it would read it line by line and send it to Google.

I created the following code:

from oauth2client.service_account import ServiceAccountCredentials 
import httplib2 
import csv
 

SCOPES = ["https://www.googleapis.com/auth/indexing"] 
ENDPOINT = "https://indexing.googleapis.com/v3/urlNotifications:publish" 

# service_account_file.json is the private key
# that you created for your service account. 
JSON_KEY_FILE = "/content/astute-tractor-329613-1baed60ec1c0.json" 
credentials = ServiceAccountCredentials.from_json_keyfile_name(JSON_KEY_FILE, scopes=SCOPES) 

http = credentials.authorize(httplib2.Http()) 

with open('/content/indekseerida-1.csv') as csvfile:
    readCSV = csv.reader(csvfile, delimiter=',')
    for row in readCSV:
        content = """{ 
        "url": row[0], 
        "type": "URL_UPDATED" 
        }""" 

        response, content = http.request(ENDPOINT, method="POST", body=content)

        if response.status == 200:
            print(f'The submission was successful. Google reported a {response.status} response code.')
        else:
            print(f'The submission was not successful. Google reported a {response.status} response code, instead of 200.')

This gives me back error response code 400 only. I am pretty new to coding so don't be harsh on me :)

CodePudding user response:

Put a print(content) statement inside your for loop, and I think you'll discover that it doesn't contain what you think it does. The whole string is just the literal stuff you typed there.

You need something like:

        content = f"""{{ 
        "url": {row[0]}, 
        "type": "URL_UPDATED" 
        }}""" 

The f""" creates a string interpolation inside of which things inside {} are evaluated. You then need {{ and }} to get literal braces.

  • Related