youtubeAPIspython
Ben Gorman

Ben Gorman

Life's a garden. Dig it.

Skip to the problems! :material-arrow-right-circle:

With the YouTube Data API, you can search for videos matching specific search terms, topics, locations, publication dates, and much more. You can also use the API to upload videos, manage playlists and subscriptions, update channel settings, and more.

!!! important "About this problem set"

YouTube's data API has endpoints for _doing stuff_ (e.g. uploading videos) and endpoints for _fetching stuff_ (e.g. cat videos). In this problem set, we focus on the endpoints for fetching stuff.
 
Our solutions use Python, but the concepts generalize to all programming languages.

Setup

  1. Create a Google account if you don't already have one.

  2. Sign up for Google Cloud if you haven't already.

  3. Create a new Google Cloud Project.

    !!! info "Billing Info"

     You'll need to provide a credit card in order to use Google Cloud. However, **the YouTube data API is 100% free** :smiley:
  4. Search for the YouTube Data API in the cloud console; then enable it.

    ???+ info "Setup Video"

     ![youtube data api setup][setup-gif]
  5. Create credentials > API Key. Keep your API key safe and secret!

    !!! info "API Key vs OAuth client ID"

     In this problem set, we're simply going to fetch public data (videos, channels, comments, etc.), so all we need is an API key. If you'd like to fetch private statics about your own YouTube channel (e.g. a list of your subscribers), you'd need an OAuth client ID.

Pricing

How much does the YouTube data API cost?
It's 100% free 🥳

Quotas and Rate Limits

Each call to the YouTube data API incurs a "quota cost" (even if your API call is invalid!).

How much quota do I get?
10,000 per day.

How much does each request cost?
It varies by resource. Here are some examples.

Resource Quota Cost
videos.list 1
search.list 100
thumbnails.set 50

How much usage do I have remaining? / How much quota have I spent so far?
You can see your quota usage on the Quotas page in the API Console.

YouTube API Quotas

What does 1 quota cost in US dollars?
$0. The API is free to use.

Client Libraries

YouTube has a list of client libraries here. Our solutions will use the Python client library.

Where are the docs for the Python client library?
They're buried here.

What if my preferred language isn't listed as a client library?
That's fine. Most programming languages have an HTTP client library. Use that.

Hello World

=== "Python"

This [_Getting Started_][python-getting-started] guide is helpful.
 
1. Install [google-api-python-client][python-client]
 
    ```python
    pip install google-api-python-client
    ```
 
2. The following Python code fetches details about the [Veritasium] channel.
 
 
    ```python
    from googleapiclient.discovery import build
 
    # Instantiate a googleapiclient.discovery.Resource object for youtube
    youtube = build( # (1)!
      serviceName='youtube', 
      version='v3', 
      developerKey='YOURAPIKEY' # (2)!
    )
 
    # Define the request
    # We'll use his username (Veritasium) to find his channel info
    request = youtube.channels().list( # (3)!
        part="id,snippet", # (4)!
        forUsername="Veritasium"
    )
 
    # Execute the request and save the response
    response = request.execute()
 
    # Display the response
    print(response)
 
    # {
    #   'kind': 'youtube#channelListResponse', 
    #   'etag': '3mtfZtQzsasCJhzfFVesH-H0pek', 
    #   'pageInfo': {
    #     'totalResults': 1, 
    #     'resultsPerPage': 5
    #   }, 
    #   'items': [
    #     {
    #       'kind': 'youtube#channel', 
    #       'etag': '_CgsN32-GJiHYWsqZRcU74jyRqo', 
    #       'id': 'UC-ImLFXGIe2FC4Wo5hOodnw', 
    #       'snippet': {
    #         'title': 'Veritasium', 
    #         'description': '', 
    #         'customUrl': '@veritasium5359', 
    #         'publishedAt': '2009-09-30T15:28:22Z', 
    #         'thumbnails': {
    #           'default': {
    #             'url': 'https://yt3.ggpht.com/ytc/AMLnZu8yO33tg2fvx5qfDZxbcmrcD2u1RB1BGFuhDw=s88-c-k-c0x00ffffff-no-rj', 
    #             'width': 88, 
    #             'height': 88
    #           }, 
    #           'medium': {
    #             'url': 'https://yt3.ggpht.com/ytc/AMLnZu8yO33tg2fvx5qfDZxbcmrcD2u1RB1BGFuhDw=s240-c-k-c0x00ffffff-no-rj', 
    #             'width': 240, 
    #             'height': 240
    #           }, 
    #           'high': {
    #             'url': 'https://yt3.ggpht.com/ytc/AMLnZu8yO33tg2fvx5qfDZxbcmrcD2u1RB1BGFuhDw=s800-c-k-c0x00ffffff-no-rj', 
    #             'width': 800, 
    #             'height': 800
    #           }
    #         }, 
    #         'localized': {
    #           'title': 'Veritasium', 
    #           'description': ''
    #         }
    #       }
    #     }
    #   ]
    # }
 
    # Close the connection to avoid leaving the socket open
    youtube.close() # (5)!
    ```
 
    1. The docs for `build()` are buried [here][build-docs]. You can also find the source code [here][build-source].
    2. You'll need your API key for this code to work. See the [setup guide] for obtaining your API key.
    3. We use the [`channels.list`][channels-list] resource to fetch the details about the channel.
    4. We tell youtube to return the channel's _id_ and _snippet_ in the required [`part`][channels-list-params] parameter of the request.
    5. Alternatively, we could've wrapped all this code into a context manager.
 
        ```python
        from googleapiclient.discovery import build
 
        with build(serviceName='youtube', version='v3', developerKey='YOURAPIKEY') as youtube:
          # ....
        ```