When I am trying to get the sitemap of my website but it's showing me the following error:
{'error': {'code': 401, 'message': 'API keys are not supported by this API. Expected OAuth2 access token or other authentication credentials that assert a principal. See https://cloud.google.com/docs/authentication', 'errors': [{'message': 'Login Required.', 'domain': 'global', 'reason': 'required', 'location': 'Authorization', 'locationType': 'header'}], 'status': 'UNAUTHENTICATED', 'details': [{'@type': 'type.googleapis.com/google.rpc.ErrorInfo', 'reason': 'CREDENTIALS_MISSING', 'domain': 'googleapis.com', 'metadata': {'method': 'google.searchconsole.v1.SitemapsService.List', 'service': 'searchconsole.googleapis.com'}}]}}
It was working when I used Flask and run the project on the browser. I kept the Access token on the flask session as documented by google.
Later I tried to run the app only on the desktop without Flask. So I write an authentication code for the desktop. here is my new code which is not working:
SCOPES = ['https://www.googleapis.com/auth/webmasters']
API_SERVICE_NAME = 'searchconsole'
API_VERSION = 'v1'
def main():
"""Shows basic usage of the People API.
Prints the name of the first 10 connections.
"""
creds = None
# The file token.json stores the user's access and refresh tokens, and is
# created automatically when the authorization flow completes for the first
# time.
if os.path.exists('token.json'):
creds = Credentials.from_authorized_user_file('token.json', SCOPES)
YOUR_ACCESS_TOKEN=creds.token
print(creds.token)
readSiteMap()
# If there are no (valid) credentials available, let the user log in.
if not creds or not creds.valid:
if creds and creds.expired and creds.refresh_token:
creds.refresh(Request())
else:
flow = InstalledAppFlow.from_client_secrets_file(
CLIENT_SECRETS_FILE, SCOPES)
creds = flow.run_local_server(port=0)
# Save the credentials for the next run
with open('token.json', 'w') as token:
token.write(creds.to_json())
YOUR_ACCESS_TOKEN = creds.token
readSiteMap()
The error is coming from this method:
def readSiteMap():
url="https://searchconsole.googleapis.com/webmasters/v3/sites/"+WEBSITE+"/sitemaps?key="+API_KEY
token=YOUR_ACCESS_TOKEN
headers = CaseInsensitiveDict()
headers["Accept"] = "application/json"
headers["Authorization"] = "Bearer "+token
headers["Content-Type"] = "application/json"
sitemap=requests.get(url=url,headers=headers).json()
print(sitemap)
sitemap=sitemap['sitemap'][0]['path']
xml=requests.get(sitemap).text
soup=BeautifulSoup(xml,"xml")
sitemapTags = soup.find_all("sitemap")
print ("The number of sitemaps are {0}".format(len(sitemapTags)))
for sitemap in sitemapTags:
url=sitemap.findNext("loc").text
if("post" in url):
sitemaps.append(url)
print(sitemaps)
Please help me fix this problem. Thank you