Python Forum

Full Version: Help connecting to Google API
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
I have the following error:


line 57, in <module>
for feed in feedjson['items']:

KeyError: 'items'

My objective is to connect to the Google API and download in a CSV some data of videos in range time.

Thanks in advance.

This is the code:

DEVELOPER_KEY = "xxxxxxxxxxxxxxxxxxxxxxxxxxxx"
import requests
import csv
from datetime import datetime, timedelta, date
datosYT_Ufo=open("datosYT_Ufo2.csv", "w" , encoding='utf-8')
csvwriter = csv.writer(datosYT_Ufo, delimiter=";")
FormatoFecha ='2005-06-01'
FormatoFechaStr = datetime.strptime(FormatoFecha, '%Y-%m-%d')

while FormatoFechaStr < datetime.now():
    yearEnFormatoAdecuado = str(FormatoFechaStr) + "T00:00:00Z"
    url = "https://www.googleapis.com/youtube/v3/search?part=snippet&q=UFO&order=viewCount&regionCode=US&maxResults=50&type=video&snippet.publishedAt&snippet.description&key=xxxxxxxxxxxxxxx&publishedBefore=" + yearEnFormatoAdecuado

    print (url)    
    feed = requests.request(method="GET", url=url)
    feed_json = feed.json()
    print("Vídeos del año: " + str(FormatoFechaStr))

    for feed in feed_json['items']:
        Video_title = feed['snippet']['title']
        Video_description = feed['snippet']['description']
        Video_publishedAt = feed['snippet']['publishedAt']
        print (Video_title)
        csvwriter.writerow([Video_title, Video_description, Video_publishedAt])       

    #year += 1
    FormatoFechaStr += timedelta(days=1)
    print (FormatoFechaStr)
    print ("--------------------------------")
Please use the [python] delimiters to post your code or all the indentation is lost...

For what I managed to read the problem is that the feed_json = feed.json() is returning something that does not contain the key 'items' either because the query URL is incorrect or the result is empty.
You shall check that the result of your GET is what you expect... I suspect you are receiving really something like:
Output:
{ "error": { "errors": [ { "domain": "global", "reason": "badRequest", "message": "Bad Request" } ], "code": 400, "message": "Bad Request" } }
And you might want to remove the key from your post Wink
I have removed your API key in url,as pointed out bye @killerrex.
Your url don't work,so it return what posted bye @killerrex.

Here a test you can do,look also at string formatting(f-string) then can add stuff to url string.
import requests
from pprint import pprint

video_id = 'CUNq2_VjRn4'
your_api_key = 'your_api_key'
url = f'https://www.googleapis.com/youtube/v3/videos?id={video_id}&key={your_api_key}&part=status'
url_get = requests.get(url)
pprint(url_get.json())
print('-----------')
# Is Video public viewable
print(url_get.json()['items'][0]['status']['publicStatsViewable'])
Output:
{'etag': '"95M1zlW0txkV42I4OG1Zscxrg5A/XBA-sYAccdJQD803PbrNziArt-U"', 'items': [{'etag': '"95M1zlW0txkV42I4OG1Zscxrg5A/i4VlXNZUnKWY8OIv_qh-vAbzstI"', 'id': 'CUNq2_VjRn4', 'kind': 'youtube#video', 'status': {'embeddable': True, 'license': 'youtube', 'privacyStatus': 'public', 'publicStatsViewable': True, 'uploadStatus': 'processed'}}], 'kind': 'youtube#videoListResponse', 'pageInfo': {'resultsPerPage': 1, 'totalResults': 1}} ----------- True