The request is missing a Valid API Key while using Youtube Data API v3

Viewed 3834

I am trying to get the key and show the result on console but its not working. I am using React.js for this purpose.

import axios from "axios";

const KEY = "MY_Key Here";

export default axios.create({
 baseURL: "https://www.googleapis.com/youtube/v3",
  params: {
   part: "snippet",
   maxResults: 5,
   key: KEY,
  },
});

and App.js contain this

onTermSubmit = async (term) => {
  const response = await youtube.get("/search", {
    params: {
      q: term
    },
  });
  console.log(response);
};

Everytime i execute this it says "the request is missing valid api key" domain="Global" reason-"forbidden" and status="Denied".

4 Answers

make sure you add all those params: { part: "snippet", maxResults: 5, key: KEY, }

in your App.js and remove it from youtube.js params: { q: term },

here,

and end code of your App.js gonna look like

params: { part: "snippet", maxResults: 5, key: KEY, q: term }

its because after your baseURl from youtube.js it directly go for your App.js params which consist of only one thing thats {q} so pgm never gets a chance to actually read the key

Try this!

const result = await youtube.get("/search", {
      params: {
        part: "snippet",
        maxResults: 5,
        key: KEY,
        q: term,
      },
    });

The problem is with the params part, it can't parse params from two different file I think.

There is no need to create a new component for your api key the code bellow worked for me!

import React from "react";
import SearchBar from "./SearchBar";
import axios from "axios";
const KEY = "Your API_KEY";

class App extends React.Component {
  onTermSubmit = async (term) => {
    axios.get("https://www.googleapis.com/youtube/v3/search", {
      params: {
        part: "snippet",
        maxResult: 5,
        key: KEY,
        q: term,
      },
    });
  };

  render() {
    return (
      <div className="ui container">
        <SearchBar onFormSubmit={this.onTermSubmit} />
      </div>
    );
  }
}

export default App;

This is most probably in your current project axios is not installed as a dependency. Therefore, you are using an old version of axios which does not support setting multiple params. I suggest you check package.json and install axios by npm install --save axios. I understand the application works by moving params into app.js but it is not the solution of the problem but a workaround.

Related