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?
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));
}
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());
}
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
I'm Using vue for the clientside. And somehow the Authorization is not working with Get method in axios. I tried using POSTMAN and it's working like it should be. Is there any chance that I missed something?
getCurrentPeriode() {
return new Promise((resolve, reject) => {
axios.get(TABLE_NAME,{params: {"X-API-KEY": API_KEY, command:"getCurrent"}}, {
headers:{
'Authorization': `Basic ${token}`
}
})
.then((response) => {
resolve(response.data[0])
}) .catch(err => {
reject(err.response.data)
})
})
}
The token:
const token = Buffer.from(`${username}:${password}`, 'utf8').toString('base64')
I get this error: Uncaught (in promise) {status: false, error: "Unauthorized"}
In postman (it's worked):
I've tried with post method in axios and it's working. Yes I've set up CORS. Yes I've allowed Get method in my server side (coz it's working in postman)
Post method is working like normal, here's the code:
postNewPeriode(date) {
return new Promise((resolve, reject) => {
const data = new FormData()
data.append("dateStart", date.dateStart)
data.append("dateEnd", date.dateEnd)
data.append("X-API-KEY",API_KEY)
axios.post(TABLE_NAME,data, {
headers:{
"Content-Type": "application/x-www-form-urlencoded",
"Authorization": `Basic ${token}`
}
})
.then((response) => {
resolve(response)
}) .catch(err => {
reject(err.response.data)
})
})
},
Am I missing something in my axios get or I should use different approach? Thanks for the answer
For Axios GET, the headers should be the second argument, while for PUT and POST the body is the second and the headers the third, as you did.
Try using the headers as the second argument on GET.
This should work:
axios.get( TABLE_NAME,
{
headers:{'Authorization': `Basic ${token}`},
params: {"X-API-KEY": API_KEY, command:"getCurrent"}
}
)
I successfully triggered POST request via Postman to retrieve mobileSession key. But when I tried the same from React Native app (via Axios), I get error that some params are missing. Can someone tell me what is wrong in Axios according to Postman request which is working?
Postman:
And Axios code:
export function getMobileSession() {
let requestOptions = {
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
}
};
let body = {
username: 'myusername',
password: 'mypw',
api_key: 'apikey',
api_sig: 'signature',
method: 'auth.getMobileSession',
format: 'json'
};
return axios.post('Lastfm_API_URL', JSON.stringify(body), requestOptions)
.then(response => {
return response;
})
.catch(err => {
throw err;
});
}
Try this,
return axios.post(`https://ws/audioscrobbler.com/2.0/`, JSON.stringify(body), requestOptions)
.then(response => {
return response;
})
.catch(err => {
throw err;
});
For more refer here to know about back tick.
I am waiting for successful JSON from server:
{"...."}
Actual Behavior
I get
SyntaxError: Unexpected token b in JSON at position 0
b is the first letter of word "badlogin". It responds server when sent wrong combination of userName and password. But when I use Postman with the same key values combination on the same address I get correct rosponse from the server.
Steps to Reproduce
fetch('http://....', {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify({
userName: "react",
password: "123",
})
}).then((response) => response.json())
.then((responseJson) => {
console.log(responseJson.message);
if(responseJson.success === true) {
alert('successufuly loged');
}
else{
console.log(responseJson.message);
alert(responseJson.message);
}
})
}
}
You are trying to parse a string. This is the error. Instead of always parse the json, just add a clausule to check if the request was made with success
}).then((response) => {
if(!response.ok) {
// handle your error here and return to avoid to parse the string
return
}
return response.json()
})
.then()
Look like the response you got is not json
Try to check what is the response you are getting first:
.then((response) => response.text())
.then((responseJson) => {
console.log(responseJson);
}
I solved this issue by using FormData to prepare data for sending:
......
login = () => {
var formData = new FormData();
formData.append('username', 'react');
formData.append('password', '123');
fetch('http://......', {
method: 'POST',
body: formData
........
I'm new with react-native. I'm trying to satisfy the devise_token_auth requirement of send in every request the authetication headers. To do so, I'm trying something like this:
export const scheduleFetch = (auth) => {
return (dispatch) => {
fetch(URL, {
method: 'GET',
headers: {
'Content-Type': 'application/json; charset=utf-8',
'access-token': auth['acessToken'],
'token-type': auth['tokenType'],
'client': auth['client'],
'uid': auth['uid']
}
})
.then((response) => {
console.log(response)
response.json()
})
.catch((error) => console.log(error))
}
}
My back-end is receiving the request, all headers are fill. However, I still receiving the message "_bodyText":"{\"errors\":[\"You need to sign in or sign up before continuing.\"]}".
How can I make that work? Am I jumping any step?
I've been banging my head against fetch-client for too long and I need some help.
I'm getting some data from Skyscanner. The request hits their API and Chrome's dev tools list it in the network tab as a complete fetch request with code 200 and the correct response body.
import {inject} from 'aurelia-framework';
import {HttpClient} from 'aurelia-fetch-client';
#inject(HttpClient)
export class Flights {
constructor(http){
http.configure(config => {
config
.withBaseUrl('http://partners.api.skyscanner.net/apiservices/')
.withDefaults({
mode: 'no-cors',
headers: {
'Accept': 'application/json',
'Content-type' : 'application/json'
}
});
});
this.data = "";
this.http = http;
}
activate() {
this.http.fetch('browsequotes/v1.0/GB/GBP/en-GB/UK/anywhere/anytime/anytime?apiKey=MYAPIKEYGOESHERE')
.then(response => {
console.log(response);
console.log(response.response);
console.log(response.content);
console.log(response.data);
})
.catch(ex => {
console.log(ex);
});
}
}
But when the response object is printed it has NOTHING in it:
Response {}
body: null
bodyUsed: false
headers: Headers
__proto__: Headers
ok: false
status: 0
statusText: ""
type: "opaque"
url: ""
__proto__: Response
All of the remaining console.log's produce undefined
Am I using fetch-client incorrectly? What am I missing?
Notice you're receiving an opaque response (type: "opaque"). Opaque responses does not allow you to read them. This is due to the no-cors mode you set before. You should use the cors mode and SkyScanner should provide the proper headers for your API key which is something I think they don't do.
I fixed my issue which can fall under same heading so leaving an answer here as I couldn't find anything on the net. May be I'm just stupid but i was doing this before...
.then(response => {response.json()})
.then(data => console.log(data))
Banged my head against this for a day and turned out the fix is:
.then(response => response.json())
.then(data => console.log(data))
Or
.then(response => { return response.json()})
.then(data => console.log(data))
Simple really and nothing to do with Aurelia or Fetch but understanding of Javascript syntax.