Example YouTube JSON File

Share this article

This article series was rewritten in mid 2017 with up-to-date information and fresh examples.

YouTube is an online video sharing service, created by former employees of PayPal in 2005. Today, it operates as a subsidiary of Google and it currently stands as the second most popular website globally according to Alexa.

In this example, I’ll show you how to use the YouTube Data API. The API allows you to integrate YouTube functionality to a website. It also gives developers access to a search.list method that supports searching of videos, playlists, and channels. The API has multiple client libraries targeting different platforms which include Android, Go, Java, JavaScript, NodeJS, .NET, PHP, Python, and Ruby.

Let’s see how to perform a simple search using JavaScript in four steps:

  1. Clone the project as outlined on the intro page, if you haven’t already done so.

  2. Install the http-server package in your machine globally.

    $ npm i -g http-server
    
  3. Acquire your YouTube API key using this link. Once you have acquired that, open the src/youtube-example.html file and replace undefined with your api key.

    HTML/JS code:

    <!DOCTYPE html>
    <html>
    <head>
    <title>YouTube JSON Example</title>
    
    <script type="text/javascript">
      const api = undefined; // Specify your api key here
    
      // Load API library
      function onLoad() {
        if(api) {
          gapi.client.load('youtube', 'v3', loadYouTubeApi);
        } else {
          document.getElementById('output').innerHTML += 'API key has not been specified!';
        }
      }
    
      // Set API Key
      function loadYouTubeApi() {
        gapi.client.setApiKey(api);
        search('sitepoint');
      }
    
      // Call the search.list()
      function search(queryTerm) {
        let request = gapi.client.youtube.search.list({
            part: 'id',
            q: queryTerm
        });
        // Execute the request call and output it in HTML view
        request.execute((response) => {
          const responseString = JSON.stringify(response, '', 2);
          document.getElementById('output').innerHTML += responseString;
        })
      }
    </script>
    <script src="https://apis.google.com/js/client.js?onload=onLoad" type="text/javascript"></script>
    </head>
    <body>
    <h1>YouTube Search Results</h1>
    <pre id="output"></pre>
    </body>
    </html>
    
  4. To run the html code, you’ll need to load it via a server. Opening it directly with your browser won’t work. Navigate to the src folder and start the http-server we just installed.

    $ http-server
    
    Starting up http-server, serving ./
    Available on:
    http://127.0.0.1:8080
    http://10.0.2.15:8080
    

Once the server is up and running, you can open your browser and access the page using the URL: http://127.0.0.1:8080/youtube-example.html. After a few seconds, the page will be populated with some JSON data that looks like this:

YouTube API JSON Response (partial results):

{
  "kind": "youtube#searchListResponse",
  "etag": "\"m2yskBQFythfE4irbTIeOgYYfBU/PaiEDiVxOyCWelLPuuwa9LKz3Gk\"",
  "nextPageToken": "CAUQAA",
  "regionCode": "KE",
  "pageInfo": {
    "totalResults": 4249,
    "resultsPerPage": 5
  },
  "items": [
    {
      "kind": "youtube#searchResult",
      "etag": "\"m2yskBQFythfE4irbTIeOgYYfBU/QpOIr3QKlV5EUlzfFcVvDiJT0hw\"",
      "id": {
        "kind": "youtube#channel",
        "channelId": "UCJowOS1R0FnhipXVqEnYU1A"
      }
    },
    {
      "kind": "youtube#searchResult",
      "etag": "\"m2yskBQFythfE4irbTIeOgYYfBU/AWutzVOt_5p1iLVifyBdfoSTf9E\"",
      "id": {
        "kind": "youtube#video",
        "videoId": "Eqa2nAAhHN0"
      }
    },
    {
      "kind": "youtube#searchResult",
      "etag": "\"m2yskBQFythfE4irbTIeOgYYfBU/2dIR9BTfr7QphpBuY3hPU-h5u-4\"",
      "id": {
        "kind": "youtube#video",
        "videoId": "IirngItQuVs"
      }
    }
  ]
}
Here are the other examples in this series:

Frequently Asked Questions (FAQs) about YouTube JSON

What is YouTube JSON and how does it work?

YouTube JSON, also known as JavaScript Object Notation, is a lightweight data-interchange format that is easy for humans to read and write and easy for machines to parse and generate. It is a text format that is completely language independent but uses conventions that are familiar to programmers of the C-family of languages, including C, C++, C#, Java, JavaScript, Perl, Python, and many others. These properties make JSON an ideal data-interchange language.

How can I use YouTube JSON to fetch data from YouTube?

YouTube provides a Data API that allows developers to fetch data in JSON format. This data can include video details, channel information, playlists, and more. To use the API, you need to create a project in the Google Developers Console, enable the YouTube Data API, and obtain an API key. You can then use this key to make requests to the API and fetch data in JSON format.

What are the benefits of using YouTube JSON?

YouTube JSON provides a simple and efficient way to fetch data from YouTube. It is lightweight, easy to understand, and can be parsed and generated by many programming languages. This makes it an ideal choice for developers who want to integrate YouTube data into their applications or websites.

Can I use YouTube JSON to upload videos to YouTube?

Yes, you can use the YouTube Data API to upload videos to YouTube. The API provides methods for uploading videos, setting video metadata, and managing video settings. You can use these methods in conjunction with JSON data to upload videos to YouTube.

How can I parse YouTube JSON data in JavaScript?

Parsing YouTube JSON data in JavaScript is straightforward. You can use the JSON.parse() method to parse the JSON data into a JavaScript object. This object can then be used to access the data contained in the JSON.

Can I use YouTube JSON to fetch comments from YouTube videos?

Yes, the YouTube Data API provides methods for fetching comments from YouTube videos. You can use these methods in conjunction with JSON data to fetch comments from YouTube videos.

How can I handle errors when using YouTube JSON?

When using YouTube JSON, errors can be handled by checking the status code and error message returned by the API. The API returns a 200 status code for successful requests and a different status code for each type of error. The error message provides more information about the error.

Can I use YouTube JSON to fetch live stream data from YouTube?

Yes, the YouTube Data API provides methods for fetching live stream data from YouTube. You can use these methods in conjunction with JSON data to fetch live stream data from YouTube.

How can I use YouTube JSON to fetch playlist data from YouTube?

The YouTube Data API provides methods for fetching playlist data from YouTube. You can use these methods in conjunction with JSON data to fetch playlist data from YouTube.

Can I use YouTube JSON to fetch channel data from YouTube?

Yes, the YouTube Data API provides methods for fetching channel data from YouTube. You can use these methods in conjunction with JSON data to fetch channel data from YouTube.

Michael WanyoikeMichael Wanyoike
View Author

I write clean, readable and modular code. I love learning new technologies that bring efficiencies and increased productivity to my workflow.

jQueryjsonnilsonjYoutube
Share this article
Read Next
Get the freshest news and resources for developers, designers and digital creators in your inbox each week