Getting KeyError: 'viewCount' for using Youtube API in Python

Viewed 145

I'm trying to get the view count for a list of videos from a channel. I've written a function and when I try to run it with just 'video_id', 'title' & 'published date' I get the output. However, when I want the view count or anything from statistics part of API, then it is giving a Key Error.

Here's the code:

def get_video_details(youtube, video_ids):
    
    all_video_stats = []
    
    for i in range(0, len(video_ids), 50):
        request = youtube.videos().list(
                        part='snippet,statistics',
                        id = ','.join(video_ids[i:i+50]))
        response = request.execute()
        
        for video in response['items']:
            video_stats = dict(
                            Video_id = video['id'],
                            Title = video['snippet']['title'],
                            Published_date = video['snippet']['publishedAt'],
                            Views = video['statistics']['viewCount'])

            all_video_stats.append(video_stats)

    return all_video_stats

get_video_details(youtube, video_ids)

And this is the error message:

---------------------------------------------------------------------------
KeyError                                  Traceback (most recent call last)
~\AppData\Local\Temp/ipykernel_18748/3337790216.py in <module>
----> 1 get_video_details(youtube, video_ids)

~\AppData\Local\Temp/ipykernel_18748/1715852978.py in get_video_details(youtube, video_ids)
     14                             Title = video['snippet']['title'],
     15                             Published_date = video['snippet']['publishedAt'],
---> 16                             Views = video['statistics']['viewCount'])
     17 
     18             all_video_stats.append(video_stats)

KeyError: 'viewCount'

I was referencing this Youtube video to write my code.

Thanks in advance.

1 Answers

I got it.

I had to use .get() to avoid the KeyErrors. It will return None for KeyErrors.

Replaced this code to get the solution.

Views = video['statistics'].get('viewCount')
Related