'Error: Request failed with status code 403 - Problem with Axios, possible exchange for fetch

I'm using axios in an application Nextjs where I use the Youtube API and the following error occurredErro 403

Below is the code

import React from "react";
import youtube from "./api";
import VideoList from "./VideoList";

class App extends React.Component {
  state = {
    videos: [],
  };
  componentDidMount() {
    this.onTermSubmit("Car");
  }

  onTermSubmit = async (term) => {
    const res = await youtube.get("/search", {
      params: {
        q: term,
      },
    });
    this.setState({ videos: res.data.items });
  };
  render() {
    return (
      <>
        <div>
            <div >
              <VideoList
                videos={this.state.videos}
                
              />
            </div>
        </div>
      </>
    );
  }
}

export default App;

The other

import axios from 'axios';

const KEY = "xxxxx";

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

});

I would like a tip on how to solve this and if the best solution would be to change from Axios to fetch. Problem is, I don't know how to change from Axios to fetch.



Solution 1:[1]

I dont think that is related to package. Because 403 is forbidden response status code which indicates that the server understands the request but refuses to authorize it. Most likely you pass the wrong api key. If you need to fetch the data with fetch, you can write a reusable function:

// genre is like video type. for example Productivity
const videos = async (genre) => {
  const YOUTUBE_API_KEY = process.env.YOUTUBE_API_KEY;
  const BASE_URL = "youtube.googleapis.com/youtube/v3";

  const response = await fetch(
    `https://${BASE_URL}/${genre}&maxResults=25&key=${YOUTUBE_API_KEY}`
  );

  return await response.json();
};

this is from docs

Received a 401 or 403 error

If you're getting a 401 or 403 error when testing a sample, it's likely due to a problem with one of the following:

  • The API isn't enabled for your project. Review instructions for your API on how to create a project and enable an API.
  • You're using the wrong authorization type (API key instead of OAuth 2.0).
  • You're using OAuth 2.0, but with too narrow a scope.
  • When you set up your API key, you set up restrictions to prevent unauthorized use of your credentials. However, the request isn't meeting those restrictions.

Solution 2:[2]

Downgrade to AXIOS 0.26.0

Probably you are using last version automatically.

Related: https://github.com/axios/axios/issues/4638

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Yilmaz
Solution 2 Jorge Bellido