Yelp API Authorization using JavaScript - javascript

I am still learning to work with different APIs, and have been working with JavaScript and the Yelp API. I have tried using Ajax, as well as the code I have posted here, but I continue to get the error of:
"code": "TOKEN_MISSING",
"description": "An access token must be supplied in order to use this endpoint."
I will continue to search through other posts, but if anyone could point out to me what I am doing incorrectly and how to fix it, I would really appreciate it?
var URL = 'https://api.yelp.com/v3/businesses/search?location=40515&term&categories=vet&limit=10';
var API_KEY = 'xxxxxxxxxxxxxxxxxxxxxxxxxx';
var req = new Request(url, {
method: 'GET',
headers: new Headers({
'Authorization: Bearer', API_KEY,
'Content-Type': 'application/json'
})
mode: 'no-cors'
});
fetch (req)
.then((response) => {
if(response.ok){
return response.json();
}else{ssss
throw new Error();
}
})
.then((jsonData) => {
console.log(jsonData);
})
.catch((err) => {
console.log('ERROR: ', err.message);
});

I think you just need to fix up:
'Authorization: Bearer', API_KEY,
to be something like:
'Authorization': `Bearer ${API_KEY}`,
or:
'Authorization': 'Bearer ' + API_KEY,
And if this line isn't just redacted for posting here:
var API_KEY = 'xxxxxxxxxxxxxxxxxxxxxxxxxx';
then you would need to actually get an API key from yelp as 'xxxxxxxxxxxxxxxxxxxxxxxxxx' would not be a valid key

I think an answer I posted before to a similar question with a full code sample may lead you in the right direction:
https://stackoverflow.com/a/51461033/9525657
Have a look, it’s an easy and simple process of pulling from the service :)

Related

How can I update the message body using gmail API in javascript

I have got the message body. Now I want to update it according to my needs. I am using this login/code. but it says 400 error. I think issue is in body parameter of the request. Would you please help me there?
var token = localStorage.getItem("accessToken");
var messageId = "18514426e2b99017";
async function updateMessageBody() {
var updatedBody = "Hello,\n\nThis is the UPDATED message body.\n\nBest regards,\nJohn";
const API_KEY = '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-CXIk';
const headers = {
'Authorization': `Bearer ${token}`,
'Content-Type': 'application/json'
};
const response = await fetch(`https://gmail.googleapis.com/gmail/v1/users/me/messages/18514426e2b99017/modify?key=['API_KEY']`, {
method: 'POST',
headers: headers,
body: JSON.stringify({
raw: window.btoa(unescape(encodeURIComponent(updatedBody)))
})
});
if (!response.ok) {
// throw new Error(`Request failed with status code ${response.status}`);
}
return await response.json();
}
updateMessageBody()
.then(response => {
console.log('Message body updated successfully:', response);
})
.catch(error => {
});
Checking the documentation, it states that a message body can't be altered once it has been created, meaning that once you have already created an email this message can't be changed. You can verify this here.
You can instead update a message draft which is possibly what you are trying to do, however using the endpoint you have in your code this won't be possible and will lead to the error message you are getting, try using instead the users.draft.update method that allows you to modify the content of the draft sitting in your mailbox. Please note as well that using the method users.messages does not have any update method as they only have the modify one's, those methods can only update the labels though so please be aware of that.

Getting CORS Error when using fetch to get data

I am trying to access the API to get some data however i keep getting this CORS error. I have checked my code for any syntax errors but i can't find any. I have attached a picture of the error and my function which is supposed to get the data.
async function getData(){
const request = await fetch('https://api.igdb.com/v4/games', {
method: 'POST',
headers: {
'Client-ID': 'jglmao8u28qo1p9wltqne325i7xh3u',
'Authorization': 'Bearer 4xau27m6liukizor4z2l8mlb7vbpjk',
}
})
const response = await request.json();
console.log(response);
}
There is a great proxy out there used just for this - bypassing a CORS block. The source code is here: https://github.com/Rob--W/cors-anywhere, and you would use it like this:
https://cors-anywhere.herokuapp.com/https://api.igdb.com/v4/games
basically just adding the CORS-Anywhere URL before your actual image URL.
In your situation, it would be
async function getData(){
const request = await fetch('https://cors-anywhere.herokuapp.com/https://api.igdb.com/v4/games', {
method: 'POST',
headers: {
'Client-ID': 'jglmao8u28qo1p9wltqne325i7xh3u',
'Authorization': 'Bearer 4xau27m6liukizor4z2l8mlb7vbpjk',
}
})
const response = await request.json();
console.log(response);
}
If you get rate limited by that website, try https://circumvent-cors.herokuapp.com/, this is one that I have deployed from the GitHub source code, no modifications and I do not think it should rate limit you.
Cheers, and let me know if this works.

Why do i get "Must provide query string" on fetch API but not on cURL or Postman?

I am trying to use the graphbrainz library on a React app with fetch API, but however I format my request body, this error shows:
BadRequestError: Must provide query string. at graphqlMiddleware (C:\Users\User\Desktop\project\node_modules\express-graphql\index.js:76:44) at processTicksAndRejections (internal/process/task_queues.js:95:5)
The call is being made like this:
let myHeaders = new Headers();
myHeaders.append("Content-Type", "application/json");
const raw = "{ \"query\": \"{ lookup { releaseGroup(mbid: \\\"99599db8-0e36-4a93-b0e8-350e9d7502a9\\\") { title } }}\"}";
const requestOptions = {
method: 'POST',
headers: myHeaders,
body: raw,
redirect: 'follow',
mode: 'no-cors'
};
fetch("http://localhost:3000", requestOptions)
.then(response => response.json())
.then(result => console.log(result))
.catch(error => console.log('error', error));
I have tried making the same call on Postman and cURL and it works successfully.
The graphbrainz instance is being run as a standalone node server.
Can anyone guide me how to proceed with this or what am I doing wrong? I have exhausted almost all stackoverflow questions and GitHub threads. I have the idea that it must be the bodyParser on the express-graphql server that it is causing this, but I can't see how to change/modify it since it comes from the package I am using.
I think you might be escaping inner quotes in the query incorrectly. Try replacing \"99599db8-0e36-4a93-b0e8-350e9d7502a9\" with \\\"99599db8-0e36-4a93-b0e8-350e9d7502a9\\\".
Can you try to stringify your body payload before sending it.
const raw = JSON.stringify({
"query": "{ lookup { releaseGroup(mbid: \"99599db8-0e36-4a93-b0e8-350e9d7502a9\") { title } }}"
});
doing this will stringify your payload to
"{\"query\":\"{ lookup { releaseGroup(mbid: \\\"99599db8-0e36-4a93-b0e8-350e9d7502a9\\\") { title } }}\"}"

IGDB API Axios request returning undefined

I building a Discord bot, and I want to query IGDB for the searched game and return some information. I'm currently just getting 'undefined' no matter what I search or change.
I'm using CORS-anywhere as a proxy. Not sure if that's the issue. How can I get the response to show data in the console like it does in Postman?
Here's my code:
client.on('message', (message) => {
if (message.author.bot) return;
if (message.content.startsWith(PREFIX)) {
const [CMD_NAME, ...args] = message.content
.trim()
.substring(PREFIX.length)
.split(/\s+/);
if (CMD_NAME === 'search') {
if (args.length === 0) return message.reply('Please provide a game.');
// Perform a GET request from the IGDB API through the cors-anywhere proxy.
const proxyUrl = 'https://cors-anywhere.herokuapp.com/'
axios({
url: `${proxyUrl}https://api-v3.igdb.com/games`,
method: 'POST',
headers: {
'Origin': 'https://api-v3.igdb.com/games',
'Accept': 'application/json',
'user-key': process.env.IGDB_USER_KEY
},
data: `fields name,first_release_date,platforms,cover,summary;search ${args};sort popularity desc;limit 1;`
})
.then(response => {
console.log(response.data);
})
.catch(err => {
console.log(err.response.request._response);
})
}
}
})```
I am also working on igdb and pretty new with it. If I'm wrong let me know and i'll remove this :D
I think the headers should be different now that twitch auth is required.
You must call https://id.twitch.tv/oauth2/token? in order for you to get a access_token that you can then pass in your request's headers together with your client_id.
Now that you have a Client ID and Client Secret you will be
authenticating as a Twitch Developer using oauth2. Detailed
information can be found on the Twitch Developer Docs.
Doing so will give you an access token that is used for future
requests to our API.
Make a POST request to https://id.twitch.tv/oauth2/token with the
following query string parameters, substituting your Client ID and
Client Secret accordingly.
client_id=Client ID
client_secret=Client Secret
grant_type=client_credentials
headers: {
'Accept': 'application/json',
'Client-ID':'your_client_id',
'Authorization':'Bearer access_token'
},
https://api-docs.igdb.com/?javascript#about

React Native - Fetch POST not working

I am having huge troubles getting my fetch POST calls to work on iOS. My standard Fetch calls work and the Fetch POST calls work fine on android but not iOS.
The error that comes up is "Possible Unhandled Promise Rejection (id: 0): Unexpected token < in JSON at position 0"
It actually saves the post data to my server but throws that error.
I tried debugging the network request using GLOBAL.XMLHttpRequest = GLOBAL.originalXMLHttpRequest || GLOBAL.XMLHttpRequest; before the API call coupled with using CORS in my chrome debug tools. From there I can see that it is making two post calls one after the other. The first one has type "OPTIONS" while the second one has type "POST". It should probably be noted that the call works in the App while using CORS and the line of code above.
I'm very confused and have exhausted all avenues.
My code im using for refrence is as follows.
return fetch(url,{
method: 'post',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify(data)
}).then((res) => res.json());
If JSON.stringify is not working, then try to use FormData.
import FormData from 'FormData';
var formData = new FormData();
formData.append('key1', 'value');
formData.append('key2', 'value');
let postData = {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'multipart/form-data'
},
body: formData
}
fetch(api_url, postData)
.then((response) => response.json())
.then((responseJson) => { console.log('response:', responseJson); })
.catch((error) => { console.error(error); });
You use the following code for POST request in react native easily. You need to only
replace the parameter name and value and your URL only.
var details = {
'userName': 'test#gmail.com',
'password': 'Password!',
'grant_type': 'password'
};
var formBody = [];
for (var property in details) {
var encodedKey = encodeURIComponent(property);
var encodedValue = encodeURIComponent(details[property]);
formBody.push(encodedKey + "=" + encodedValue);
}
formBody = formBody.join("&");
fetch('http://identity.azurewebsites.net' + '/token', {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/x-www-form-urlencoded'
},
body: formBody
}).
.then((response) => response.json())
.then((responseData) => {
console.log("Response:",responseData);
}).catch((error) => {
Alert.alert('problem while adding data');
})
.done();
I would guess the response you are receiving is in HTML. Try:
console.warn(xhr.responseText)
Then look at the response.
Also, IOS requires HTTPS.
Edit: Possible duplicate: "SyntaxError: Unexpected token < in JSON at position 0" in React App
Here is an example with date that works for me!
The trick was the "=" equal and "&" sign and has to be in a string format in the body object.
Find a way to create that string and pass it to the body.
====================================
fetch('/auth/newdate/', {
method: 'POST',
mode: 'cors',
redirect: 'follow',
body: "start="+start.toLocaleString()+"&end="+end.toLocaleString()+"",
headers: new Headers({
"Content-Type": "application/x-www-form-urlencoded;charset=UTF-8"
})
}).then(function(response) {
/* handle response */
if(response.ok) {
response.json().then(function(json) {
let releasedate = json;
//sucess do something with places
console.log(releasedate);
});
} else {
console.log('Network failed with response ' + response.status + ': ' + response.statusText);
}
}).catch(function(resp){ console.log(resp) });
server node.js?
npm i cors --save
var cors = require('cors');
app.use(cors());
res.header("Access-Control-Allow-Origin: *");

Categories

Resources