Youtube api: download all videos from channel


Introduction and requirements

In this tutorial, we are going to create a function called download_all_video_in_channel that will download all the videos from a youtube channel id.

For using the code in this tutorial you will require to install requests and get a google API key.

To install requests execute:

pip install requests

For getting the API key follow this google documentation

Source code to download videos from channel

The next python code will scrape all videos from a channel. The final result will be youtube video urls.

import requests

def download_all_video_in_channel(api_key, channel_id):

    base_video_url = ''
    base_search_url = ''

    first_url = base_search_url+ f'key={api_key}&channelId={channel_id}&part=snippet,id&order=date&maxResults=25'

    video_links = []
    url = first_url
    while True:
        resp = requests.get(url).json()

        for i in resp['items']:
            if i['id']['kind'] == "youtube#video":
                video_links.append(base_video_url + i['id']['videoId'])

            next_page_token = resp['nextPageToken']
            url = first_url + '&pageToken={}'.format(next_page_token)
    return video_links

The code uses base_search_url to search for all the videos on a channel. The function has a while True loop that will fetch all the pages of the channel. Since the API could return different objects, before adding the link to the video_links, every result is filtered by kind. The nextPageToken is used to browse in all the pages of the channel.