SFC
SFC

Reputation: 793

Connecting to YouTube API and download URLs - getting KeyError

My goal is to connect to Youtube API and download the URLs of specific music producers.I found the following script which I used from the following link: https://www.youtube.com/watch?v=_M_wle0Iq9M. In the video the code works beautifully. But when I try it on python 2.7 it gives me KeyError:'items'.

I know KeyErrors can occur when there is an incorrect use of a dictionary or when a key doesn't exist.

I have tried going to the google developers site for youtube to make sure that 'items' exist and it does.

I am also aware that using get() may be helpful for my problem but I am not sure. Any suggestions to fixing my KeyError using the following code or any suggestions on how to improve my code to reach my main goal of downloading the URLs (I have a Youtube API)?

Here is the code:

#these modules help with HTTP request from Youtube
import urllib 
import urllib2 
import json 


API_KEY = open("/Users/ereyes/Desktop/APIKey.rtf","r") 
API_KEY = API_KEY.read() 

searchTerm = raw_input('Search for a video:')

searchTerm = urllib.quote_plus(searchTerm) 

url = 'https://www.googleapis.com/youtube/v3/search?part=snippet&q='+searchTerm+'&key='+API_KEY  

response = urllib.urlopen(url) 

videos = json.load(response) 

videoMetadata = [] #declaring our list

for video in videos['items']: #"for loop" cycle through json response and searches in items 

    if video['id']['kind'] == 'youtube#video': #makes sure that item we are looking at is only videos
        videoMetadata.append(video['snippet']['title']+ # getting title of video and putting into list
        "\nhttp://youtube.com/watch?v="+video['id']['videoId'])                       

videoMetadata.sort(); # sorts our list alphaetically

print ("\nSearch Results:\n")  #print out search results

for metadata in videoMetadata:
    print (metadata)+"\n"

raw_input('Press Enter to Exit')

Upvotes: 0

Views: 315

Answers (1)

OneCricketeer
OneCricketeer

Reputation: 191671

The problem is most likely a combination of using an RTF file instead of a plain text file for the API key and you seem to be confused whether to use urllib or urllib2 since you imported both.

Personally, I would recommend requests, but I think you need to read() the contents of the request to get a string

response = urllib.urlopen(url).read() 

You can check that by printing the response variable

Upvotes: 1

Related Questions