Search code examples
javascriptjqueryapiyoutube-data-api

Is there was way to limit the number of queries from youtube api?


I am creating a tampermonkey script that will read a line of text that contains an artist and song title from a webpage and will create a link that will open a new tab to the first result that is returned from the youtube api. My issue is that when the page is loaded and say there are 5 songs on this particular page, according to my youtube api dashboard, I am making about 1200 api requests for that single page. Im guessing that its because when I query a single artist/song, its getting every result on its server. I tried limiting my maxResults to 1, but this doesn't help. Since youtube decreased the number of queries a single API gets, I would like to know if there is a way to reduce the number of queries it makes. Realistically, I just need the first result from the GET request, since chances are that will be the correct video.

here is a snippet of my code that parses through the json data:

function getLink(artist, song){

    // API Key
    var key = "MY_KEY";

    // Setup url for api
    var url = 'https://www.googleapis.com/youtube/v3/search?part=id&q=' + artist + "-" + song + '&maxResults=1&key=' + key;

    // call api and get videoId
    var xhReq = new XMLHttpRequest();
    xhReq.open("GET", url, false);
    xhReq.send(null);
    var id = JSON.parse(xhReq.responseText);

    return id.items[0].id.videoId;
}

Solution

  • I'm not sure if I'm looking at the same Google doc, but it says the part parameter should be snippet for a Search:list call. I know different calls take up different quota amounts. Using the query below I get only one song returned. It seems to use only the normal 100 units of quota required for Search:list:

    https://www.googleapis.com/youtube/v3/search?part=snippet&maxResults=1&q=Adele+Hello&fields=items(id(videoId))&key=API_key

    It returns:

    {
     "items": [
      {
       "id": {
        "videoId": "YQHsXMglC9A"
       }
      }
     ]
    }