What is the best way to leverage multiple random YouTube v3 API keys simultaneously?

I have the following code snippet and I am looking to randomly select an API key from a list of keys:

function search() {
  // Clear Results
  $('#results').html('');
  $('#buttons').html('');

  // Get Form Input
  q = $('#query').val();

  // Run Get Request on API
  $.get(
    "https://www.googleapis.com/youtube/v3/search", {
      part: 'snippet, id',
      q: q,
      maxResults: 10,
      type: 'video',
      key: 'eeHFSFqK7zw9IrUyNCCuoAIzaSyCGEIc9V4qPKl'
    },
    function(data) {
      var nextPageToken = data.nextPageToken;
      var prevPageToken = data.prevPageToken;
      // Log Data
      console.log(data);
      $.each(data.items, function(i, item) {
        // Get Output
        var output = getOutput(item);
        // Display Results
        $('#results').append(output);
      });
      var buttons = getButtons(prevPageToken, nextPageToken);
      // Display Buttons
      $('#buttons').append(buttons);
    }
  );
}

I would like to change this line of code:

key: 'eeHFSFqK7zw9IrUyNCCuoAIzaSyCGEIc9V4qPKl'},

To use other random API keys listed below:

AIzaSyDIPhJMU8UnT5Ge8rp3OJNsoTvCRVNjngd

AIzaS_nb6cvB8r2MR5ATxOZ4W4yBVRxfGc4xpFm

AIzaSzEmOA7qNfcUxDOdNLNzInuwyCmOcuD-OjB

AIzasMirEprAzJ_egdpumvglEcSyDtyL_PT5PCA

AIzaSP1bObfQTaTel2cADI1UyAdCWLOhkjOAEDS

I attempted the following approach:

 var r_text = new Array();
 r_text[0] = "AIzaSyDIPhJMU8UnT5Ge8rp3OJNsoTvCRVNjngd";
 r_text[1] = "AIzaS_nb6cvB8r2MR5ATxOZ4W4yBVRxfGc4xpFm";
 r_text[2] = "AIzaSzEmOA7qNfcUxDOdNLNzInuwyCmOcuD-OjB";
 r_text[3] = "AIzasMirEprAzJ_egdpumvglEcSyDtyL_PT5PCA";
 r_text[4] = "AIzaSP1bObfQTaTel2cADI1UyAdCWLOhkjOAEDS";
 var nn = Math.floor(5 * Math.random())

     function search() {
   // Clear Results
   $('#results').html('');
   $('#buttons').html');

   // Get Form Input
   q = $('#query').val();

   // Run Get Request on API
   $.get(
     "https://www.googleapis.com/youtube/v3/search", {
       part: 'snippet, id',
       q: q,
       maxResults: 10,
       type: 'video',
       key: r_text[nn]
     },
     function(data) {
       var nextPageToken = data.nextPageToken;
       var prevPageToken = data.prevPageToken;
       // Log Data
       console.log(data);
       $.each(data.items, function(i, item) {
         // Get Output
         var output = getOutput(item);
         // Display Results
         $('#results').append(output);
       });
       var buttons = getButtons(prevPageToken, nextPageToken);
       // Display Buttons
       $('#buttons').append(buttons);
     }
   );
 }

However, it is not functioning as expected :/

Answer №1

To ensure a unique API key is selected each time the search() function is called, consider placing the random number variable within the function itself:

 var r_text = new Array();
 r_text[0] = "AIzaSyDIPhJMU8UnT5Ge8rp3OJNsoTvCRVNjngd";
 r_text[1] = "AIzaS_nb6cvB8r2MR5ATxOZ4W4yBVRxfGc4xpFm";
 r_text[2] = "AIzaSzEmOA7qNfcUxDOdNLNzInuwyCmOcuD-OjB";
 r_text[3] = "AIzasMirEprAzJ_egdpumvglEcSyDtyL_PT5PCA";
 r_text[4] = "AIzaSP1bObfQTaTel2cADI1UyAdCWLOhkjOAEDS";


function search() {
    var nn = Math.floor(5 * Math.random());
   // Clear Results
   $('#results').html('');
   $('#buttons').html('');

   // Get Form Input
   q = $('#query').val();

   // Run Get Request on API
   $.get(
     "https://www.googleapis.com/youtube/v3/search", {
       part: 'snippet, id',
       q: q,
       maxResults: 10,
       type: 'video',
       key: r_text[nn]
     },
     function(data) {
       var nextPageToken = data.nextPageToken;
       var prevPageToken = data.prevPageToken;
       // Log Data
       console.log(data);
       $.each(data.items, function(i, item) {
         // Get Output
         var output = getOutput(item);
         // Display Results
         $('#results').append(output);
       });
       var buttons = getButtons(prevPageToken, nextPageToken);
       // Display Buttons
       $('#buttons').append(buttons);
     }
   );
 }

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Troubles with Angular Js: Issues with using $http.put with absolute URLs

Having an issue with $http.put in AngularJS. My server is built with Node.js and my app is in AngularJS. I am trying to make requests from AngularJS to access data on the Node.js server (same host). This code works: $http.put("/fraisforfait", elements); ...

When testing on jsfiddle, the script functions properly with pure JavaScript. However, when integrating it into my own code, it fails to work unless jQuery is included

Visit this link to access the code snippet. Below is my code: const chk = document.getElementById('chk'); const body = document.body; $(function(){ chk.addEventListener('change', () => { $('.body').toggleClass( ...

Issues with the functionality of minimized AngularJS JavaScript files

I combined all JS files into one and minified them, but now none of the site features are working. There were too many separate JS files to include individually, so I decided to merge them together. Is there a better method to reduce the number of HTTP r ...

Initially, the OWL Carousel image is not displaying correctly due to incorrect sizing

I am currently working with OWL Carousel and have implemented a code that displays one image at a time, with the next image sliding in every 15 seconds. The width is set to occupy 100% of the screen and I have configured the JavaScript accordingly so that ...

The functionality of a Vue custom tooltip behaves strangely after clicking the button multiple times

I created this custom tooltip code that automatically closes after 2 seconds when a user clicks on a button, not just hovers over it. Initially, it works perfectly for the first two clicks, but then starts behaving strangely from the third click onwards. ...

The JQuery datepicker fails to function properly when the input field is modified from read-only

Utilizing the datepicker in conjunction with an MVC3 application. I aim to keep the input field as readonly until triggered by an edit button. Upon focusing on the field, I want the datepicker functionality to be activated. The code snippet below functio ...

Attempting to execute a synchronous delete operation in Angular 6 upon the browser closing event, specifically the beforeunload or unload event

Is there a way to update a flag in the database using a service call (Delete method) when the user closes the browser? I have tried detecting browser close actions using the onbeforeunload and onunload events, but asynchronous calls do not consistently wor ...

The use of script src with vue.js is causing issues

I am looking to move my Vue code into an external .js file. Since I am new to Vue, I am trying to keep it simple without using webpack. However, I have encountered an issue where Vue does not work when using the script src tag in the html file. For instanc ...

Is there a way to continuously submit a form in React every 10 seconds, even if it includes events?

I have a form with input fields where I collect data upon form submission. However, I want the form to submit automatically every 10 seconds without the need to click a button or press enter. I tried using useEffect to create an interval, but it resulted i ...

Reordering items in Angular2 ngFor without having to recreate them

I am facing a unique situation where I must store state within item components (specifically, canvas elements) that are generated through an ngFor loop. Within my list component, I have an array of string ids and I must create a canvas element for each id ...

I'm curious if there is a method to extract and retrieve color text information from JSON using Kotlin

I'm currently working on parsing and extracting data from JSON. However, I would like the respective color to be displayed instead of just the color name. For example: { "id": 1, "name": rose, "color ...

Latest News: The store is now received in the mutation, instead of the state

An update has been made to this post, please refer to the first answer After thorough research, I couldn't find a solution to my issue despite checking several threads. This is my first time using the Quasar framework and it seems like I might have o ...

``When executing the `npm install` command, it does not install the sub-dependencies of a local package

I am facing an issue with my packages. One package named package-a has a dependency on another package called package-b which is not published on npm but resides in my file system. When I try to run npm install from the directory of package-a, the dependen ...

Creating a React component with a column allowing multiple checkbox selections in NextUI table

Setting up multiple "checkbox" columns in a table using the NextUI table has been my current challenge. Each row should have selectable checkboxes, and I want these selections to be remembered when navigating between pages, running searches, or removing co ...

Utilize Node.js to encrypt data from an extensive file

Hello, this is my initial inquiry. English isn't my native language and I need some help. I have a large file with about 800K lines that I need to read and encrypt using the sjcl library. So far, I've only managed to write the following code snip ...

Retrieving a Collection of Items Generated in the Past Day from a Specific Dataset Using JavaScript

I have been tasked with extracting a specific set of arrays from given data based on a 24-hour time frame using the timestamps provided. I initially attempted the code below, but unfortunately, it kept returning the same data to me. I suspect there may be ...

NPM is having trouble locating a shell script

An error is encountered when running npm run build: '.' is not recognized as an internal or external command, operable program or batch file. Here is the npm file that contains relevant scripts: "scripts": { "postinstall": "jspm instal ...

Using Angular 2: A Beginner's Guide to Navigating with the Latest Angular 2.0.0-rc.1 Router

As I embarked on a new Angular 2 project, I was puzzled to discover that I inadvertently installed two different versions of the angular router: "@angular/router": "2.0.0-rc.1", "@angular/router-deprecated": "2.0.0-rc.1", Despite my best efforts, I co ...

Tips for emphasizing a specific cell in a row based on its expiration date

In my quest to find a script that colors dates within two weeks from today in red and past dates in orange, I have tried various methods without success. I am struggling to implement this feature with my current knowledge. <TABLE> <TR><TD&g ...

What is the process of specifying that an Angular directive must act as a child directive within a particular directive in Angular?

I am currently developing a directive for AngularJS. How can I specifically configure it to require being a child of directiveA? For instance, consider the following example: <my-modal> <m-header>Header</m-header> </my-modal> ...