Home > Mobile >  Google Script - API headers
Google Script - API headers

Time:09-17

I'm pretty new to APIs, but I was interested in trying to get them to work in Google Sheets. I looked up the documentation at https://www.api-football.com/documentation-v3#section/Sample-Scripts/Javascript. In my Google Sheets script editor, I copied this code and when I ran it (I did put my key in where the xXx was), I got this error: ReferenceError: Headers is not defined

Any help for what I am doing incorrectly? Sorry if this is a dumb question, I'm quite new to this...

function soccer(){
var myHeaders = new Headers();
myHeaders.append("x-rapidapi-key", "XxXxXxXxXxXxXxXxXxXxXxXx");
myHeaders.append("x-rapidapi-host", "v3.football.api-sports.io");

var requestOptions = {
  method: 'GET',
  headers: myHeaders,
  redirect: 'follow'
};

fetch("https://v3.football.api-sports.io/fixtures?league=39&season=2021&timezone=America/New_York", requestOptions)
  .then(response => response.text())
  .then(result => console.log(result))
  .catch(error => console.log('error', error));
}

CodePudding user response:

You should use UrlFetchApp instead of fetch. I can't really try my code since I don't have an API key, but this should work:

function soccer(){

  var requestOptions = {
    "method" : "GET",
    "headers" : {
      "x-rapidapi-key" : "XxXxXxXxXxXxXxXxXxXxXxXx",
      "x-rapidapi-host": "v3.football.api-sports.io"
    },
    "redirect": 'follow'
    };

  let response = UrlFetchApp.fetch("https://v3.football.api-sports.io/fixtures?league=39&season=2021&timezone=America/New_York", requestOptions);

  console.log(response.getContentText());

}

CodePudding user response:

You can use the RapidAPI code snippet generator. It generates simple and more readable code. I have run this code, and it's working fine for me.

Try this code snippet:

fetch("https://api-football-v1.p.rapidapi.com/v3/fixtures?league=39&season=2020", {
    "method": "GET",
    "headers": {
        "x-rapidapi-host": "api-football-v1.p.rapidapi.com",
        "x-rapidapi-key": "XXXXXXXXXXXXXXXXXXX"
    }
})
.then(response => {
    console.log(response);
})
.catch(err => {
    console.error(err);
});
  • Related