Where to put header with API key in React application

Dear All,

I’ve got a bit lost when it comes to API key and where to put in in React application.
Let say I would like to use API from the following website:

  componentDidMount() {
  fetch("https://andruxnet-random-famous-quotes.p.mashape.com/?cat=movies&count=10")
    .then(response => response.json())
    .then((responseData) => {
      this.setState({ author: responseData});
    })
    .catch(error => this.setState({ error }));

}

but I have no idea where to put the key.

Thank you in advance for your suggestions.
Regards,
Ewa

Hi Ewa,

You need to add headers to your fetch Request, like so:

fetch("https://andruxnet-random-famous-quotes.p.mashape.com/?cat=movies&count=10", {
  method: 'POST',
  headers: {  
    'X-Mashape-Key': 'required',
    'Content-Type': 'application/x-www-form-urlencoded',
    'Accept': 'application/json'
  }
})   
  .then(response => response.json())
  .then((responseData) => {
    this.setState({ author: responseData});
  })
  .catch(error => this.setState({ error }));

Hope this will help.

2 Likes

@DanielSubat thank you for your help it was quick and helpful. It was actually header I was not sure where to put :slight_smile:
Funnily enough, some time ago I was doing a React project with fetch request where I used the same solution…

Thank again :slight_smile: