YouTube video list API

from googleapiclient.discovery import build

import pprint

DEVELOPER_KEY = "developer_key"

YOUTUBE_API_SERVICE_NAME = "youtube"

YOUTUBE_API_VERSION = "v3"

youtube = build(YOUTUBE_API_SERVICE_NAME,

                     YOUTUBE_API_VERSION,

            developerKey = DEVELOPER_KEY)

def multiple_video_details():

    list_videos_byid = youtube.videos().list(

             id = 'Ks-_Mh1QhMc, c0KYU2j0TM4',

      part = "id, snippet, contentDetails, statistics",

                                  ).execute()

    results = list_videos_byid.get("items", [])

    videos = []

    n = 1

    for result in results:

        videos.append(" (% s) (% s) (% s) (% s) (% s) (% s) " 

                              % (n, result["snippet"]["title"],

                                    result["snippet"]["tags"],

                                    result['snippet']['description'],

                                    result["snippet"]["publishedAt"],

                                    result['contentDetails'],

                                    result["statistics"]))

        n = n + 1

    print ("Videos:\n", "\n".join(videos), "\n")

if __name__ == "__main__":

    multiple_video_details()

In this guide, we’ll walk through how to pull public video data like views, comments, and likes from the YouTube Public Data API directly into Google Sheets using the API Connector add-on for Sheets.

There are 2 ways to connect to the YouTube Public Data API:

  • Preset “Connect” button (OAuth) premium
  • Personal API key. Please check the appendix for detailed instructions to retrieve your key.

Related article:
Import Private YouTube Analytics Data to Google Sheets

Contents

Before You Begin

Click here to install the API Connector add-on from the Google Marketplace.

Part 1: Connect to the YouTube Data API

If you haven’t connected to the YouTube Data API before, you’ll first need to initiate the connection.

  1. Open up Google Sheets and click Extensions > API Connector > Manage Connections.
  2. In the list of available connections, find YouTube and click Connect.
    YouTube video list API

  3. You will see a couple of screens asking you to log in and approve the connection. Click Allow.
    YouTube video list API

  4. You’ll then be returned to your Google Sheet, and can verify that your YouTube Data connection is active in the Connections screen.

Part 2: Create Your YouTube API Request URL

We’ll start by searching for some cat videos using the “search” endpoint.

  • API root: https://www.googleapis.com/youtube/v3
  • Endpoint: /search
  • Parameters: ?part=snippet&q=cats

Putting this all together, we get the full API Request URL:

https://www.googleapis.com/youtube/v3/search?part=snippet&q=cats

Part 3: Pull YouTube API Data into Sheets

Now let’s enter those values into API Connector.

  1. Open up Google Sheets and click Extensions > API Connector > Open.
  2. In the Create tab, enter the API URL we just created.
    YouTube video list API
  3. Under Authentication, choose YouTube from the dropdown menu. You should see a “Connected” badge.
    YouTube video list API

  4. We don’t need any Headers so just skip that section.
  5. Create a new tab and click Set current to use that tab as your data destination.
  6. Name your request and click Run. A moment later you’ll see some YouTube data populate your spreadsheet:
    YouTube video list API

Part 4: More Example API URLs

YouTube provides a huge number of different data points and functionality in their API. I’ve tried to give a lot of examples and summarize the most useful endpoints below, but for more complete information, please check the full YouTube documentation here.

These sample URLs can also be accessed via API Connector’s API Library (just search for “YouTube” while in the add-on).

  • A list of 50 videos matching a search string (default is 5 results): https://www.googleapis.com/youtube/v3/search?part=snippet&q=google sheets&maxResults=50
  • A list of videos in a playlist (substitute in your own playlist ID):https://www.googleapis.com/youtube/v3/playlistItems?part=snippet&playlistId=RD7nJRGARveVc
  • You can find your playlist ID by clicking into a YouTube video in your playlist and checking the URL. It will be located inside the list parameter.

    YouTube video list API

  • A list of videos you’ve liked:https://www.googleapis.com/youtube/v3/videos?myRating=like&part=snippet&maxResults=50
  • Key statistics (views, likes, dislikes, comments) for a list of videos (substitute in your own video IDs):https://youtube.googleapis.com/youtube/v3/videos?part=statistics&id=Ks-_Mh1QhMc,c0KYU2j0TM4,eIho2S0ZahI
  • Key statistics (view counts, video counts, and subscriber counts) for a channel (substitute in your own channel ID):https://www.googleapis.com/youtube/v3/channels?part=statistics&id=UCR4a2QKvUuLvLGA6M5MM2ewTo get the channel ID, hover over or click the channel name listed under any video, and check the text in the URL after /channel/
    YouTube video list API
  • Key statistics for multiple channels:
  • https://www.googleapis.com/youtube/v3/channels?part=statistics&id=YOUR_CHANNEL_ID1,YOUR_CHANNEL_ID2,YOUR_CHANNEL_ID3...

    (enter your channel IDs as a comma-separated list)

    YouTube video list API

Part 5: Handle Filtering

You can filter your results using the “fields” parameter as described here. For example, this filtered URL will produce a list of metrics like video titles, view counts, like counts, dislike counts, etc. for all the video IDs listed in the id parameter:

https://www.googleapis.com/youtube/v3/videos?part=snippet,contentDetails,statistics&id=qhJOSOBtAlc,4JJd7gmlobY,YVMtL6rexKQ,pJpApDVCXPg,MaeRXppkzdA&fields=items(id),items(snippet(publishedAt,title)),items(contentDetails(duration)),items(statistics(viewCount,likeCount,dislikeCount,commentCount))

YouTube video list API

If you’re using pagination handling, please make sure your field list includes nextPageToken.

You can also filter data through API Connector’s visual field editor (just click Edit Fields to enter).

Part 6: Handle Pagination

By default YouTube limits the number of results in a single response to 5 rows, which can be increased to 50 by adding &maxResults=50 to the end of your API request URL.

If you want to retrieve more than 50 results at a time, you’ll need to traverse the paginated results as described here.

This can be handled automatically by API Connector through the pagination handling feature, like this:

  • API URL: enter your request URL, including &maxResults=50
  • Pagination type: cursor
  • Next token parameter: pageToken
  • Next token path: nextPageToken
  • Run until: choose when to stop fetching data
    YouTube video list API

Part 7: YouTube Compliance

To comply with the terms of YouTube’s API, requests using API Connector’s YouTube OAuth connection are subject to the following conditions:

  1. All saved requests to YouTube will refresh every 30 days, even if you have not set up a scheduled refresh.
  2. All YouTube requests will show only the metric name rather than the full path in the header row.

Relevant Terms:

“API Clients may store all other types of Authorized Data not identified in section (III.E.4.b) for as long as is necessary for the purposes of the specific consent granted by an active user and for no longer than 30 calendar days. After 30 calendar days, the API Client must either delete or refresh the stored data”. (link)

“Your API Clients must not (i) replace API Data with similar, independently calculated data, or (ii) access or use API Data to create new or derived data or metrics.” (link)

Part 8: API Documentation

Official API documentation: https://developers.google.com/youtube/v3/docs/search/list

Appendix: Connect with a YouTube Data API Key

YouTube requires that all API requests are authenticated. This is the detailed, step-by-step process to authenticate with a YouTube API key:

This section is provided as a totally free alternative to the method described above. Instead of clicking Connect you will retrieve your key yourself.

  1. Navigate to https://console.developers.google.com/. If this is your first time accessing this page, you’ll be prompted to accept Google Cloud Platform’s terms of service. Click agree and continue.
    YouTube video list API
  2. Now in the top left, click Select a Project, which will open up a modal. Click New Project
    YouTube video list API
  3. This will open up the New Project modal. You can name your project anything, but let’s call it YouTube API. You’ll also be prompted to browse for a Location (aka folder). For our purposes here, it doesn’t matter which one you pick.
    YouTube video list API
  4. Once you create your project, click on Credentials in the left-hand menu. Next, click the Create credentials dropdown and click ‘API key’.
    YouTube video list API
  5. Your YouTube API key is now ready. You’ll see a screen containing your API key; copy this to your clipboard and click Close.
    YouTube video list API
  6. There’s still one last step: you need to enable the YouTube API in your project. To do this, click Library and search for ‘YouTube Data API’. Alternately, you can navigate there directly with this link: https://console.developers.google.com/apis/library/youtube.googleapis.com. Click Enable as shown:
    YouTube video list API
  7. Congrats, you’re done! You can use this token by appending key=YOUR_API_KEY to any API URL, e.g. https://www.googleapis.com/youtube/v3/search?part=snippet&q=cats&key=YOUR_API_KEY. Since you’re manually including an API key, leave OAuth2 authentication set to None.