Using curl command for react native to fetch api - ios

I'm trying to use the petfinder APi for an app I'm creating and following the API documentation which can be found here : https://www.petfinder.com/developers/v2/docs/#developer-resources.
It gives the command : curl -d "grant_type=client_credentials&client_id={CLIENT-ID}&client_secret={CLIENT-SECRET}" https://api.petfinder.com/v2/oauth2/token
Im trying to translate this for react native and used the following code:
getAdopt1 = async() => {
fetch('https://api.petfinder.com/v2/oauth2/token', {
method: 'POST',
headers: {
Accept: 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify({
firstParam: "grant_type=client_credentials&client_id={CLIENT-ID}&client_secret={CLIENT-SECRET}"
}),
}).then((response) => response.json())
.then((responseJson) => {
let res = JSON.stringify(responseJson)
console.log("Response: "+res)
return responseJson;
})
.catch((error) => {
console.error(error);
})
}
However I get the following error:
Response: {"type":"https://httpstatus.es/400","status":400,"title":"unsupported_grant_type","detail":"The authorization grant type is not supported by the authorization server.","errors":[{"code":"unsupported_grant_type","title":"Unauthorized","message":"The authorization grant type is not supported by the authorization server. - Check that all required parameters have been provided","details":"The authorization grant type is not supported by the authorization server. - Check that all required parameters have been provided","href":"http://developer.petfinder.com/v2/errors.html#unsupported_grant_type"}],"hint":"Check that all required parameters have been provided"}
What am I doing wrong here ?

You are sending a JSON request but what the API expects is a Form-Data request.
Try with something like this:
var form = new FormData();
form.append('grant_type', 'client_credentials');
form.append('client_id', '{CLIENT-ID}');
form.append('client_secret', '{CLIENT-SECRET}');
fetch('https://api.petfinder.com/v2/oauth2/token', {
method: 'POST',
body: form,
}).then(response => {
console.log(response)
}).catch(error => {
console.error(error);
})

Related

OAuth2 Discord 'unsupported_grant_type'

So, I was making a website and I needed Discord's OAuth2
However, this error keeps popping up for me:
data: { error: 'unsupported_grant_type' }
This here is my code:
function getToken(code) {
const data = new URLSearchParams({
client_id: 'ops',
client_secret: 'ops',
code: code,
grant_type: 'authorization_code',
redirect_uri: 'http://localhost:5500/callback',
scope: 'identify'
})
axios({
url: 'https://discord.com/api/oauth2/token',
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
},
body: data.toString()
}).then(response => {
return response.data
})
}
Just tried looking it up on the internet about. Since I was used to the old OAuth, I tried the old way. As I couldn't, I went after information in the Discord documentation. And I got this information.
However, without success.

How to add a BearerToken to React API Requests?

newbie to React looking for some help... I'm using React to make API requests like so:
class CatsApi {
static createCat(cat) {
const request = new Request('http://localhost:4300/api/v1/cats', {
method: 'POST',
headers: new Headers({
'Content-Type': 'application/json'
}),
body: JSON.stringify(cat)
});
return fetch(request).then(response => {
return response.json();
}).catch(error => {
return error;
});
}
Meanwhile, I have authentication to my API via react-devise:
https://github.com/timscott/react-devise
Which has a method getBearerToken like so: https://github.com/timscott/react-devise/blob/master/src/actions/authTokenStore.js
How do I use getBearerToken to pass the API the token so API requests are authenticated with the token?
Thank you!
You can use the Authorization header like:
{ 'Authorization': `Bearer ${authToken}` }
Using fetch you could try with something like:
fetch('http://localhost:4300/api/v1/cats', {
method: 'POST',
headers: {
'Authorization': `Bearer ${token}`
'Accept' : 'application/json',
'Content-Type' : 'application/json',
},
body: JSON.stringify({
cat : cat_value,
})
})
.then((response) => response.json())
.then((responseData) => { console.log(responseData) })
.catch((error) => { console.log(error) })
.done()
Also, it'd be great to see what's the Rails output in the console when you make a request, or the browser console.

How to implement OAuth2 authorization with the server in react native?

I want to implement OAuth2 authorization in react native.I implemented code the following way.
const HOST_ADRESS = "192.168.173.1"; //change with your own host
const client_id = "app";
const username = "balan#gmail.com";
const password = "12345";
fetch('https://'+HOST_ADRESS+"/oauth/token", {
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
'Cache-Control': 'no-cache'
},
body: "client_id=app&client_secret=app1234&grant_type=pass&username="+username+"&password="+password
})
.then((response) => response.json())
.then((responseJson) => {
console.log("******* RESPONSE ********* "+ JSON.stringify(responseJson));
})
.then((response) => response.text())
.then((responseText) => {
console.log("--------------responseText"+responseText);
console.log("******* RESPONSE ********* "+ JSON.stringify(responseJson));
})
.catch((error) => {
const data = {error: "A error happened"};
//redux error.
//dispatch(actionsCreators.errorLogin(data));
console.log("+++++++++++++++++++error"+error);
console.warn(error);
});
But it always get an error like
{"error":"unauthorized","error_description":"Full authentication is required to access this resource"}

How to use 'fetchData' method in react native with authentication header and body with POST method for iOS

In my current iOS project I need to fetch data from api call with POST method along with login credentials(userName & Password) as authentication header in react native javaScript file.
Can someone Please help me on that.
refernce screen shot
Just set the fetch method to 'POST', add in headers and body as key-value pairs and process response. Here is an example.
var bodyMap = {};
// fill in the body map with keyvalue pair
fetch(POST_URL, {
method: 'POST',
headers: {
'Accept': 'application/json',
'Authorization': authValue,
'Content-Type': 'application/json',
},
body: JSON.stringify(bodyMap)
}).then((response) => response.json())
.then((responseData) => {
console.log(responseData);
//process response
})
.catch((error) => {
console.warn(error);
});

React Native fetch "unsupported BodyInit type"

I'm trying to send a POST request to the OneSignal REST API using fetch:
var obj = {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify({
'app_id': '(API KEY)',
'contents': {"en": "English Message"},
'app_ids': ["APP IDS"],
'data': {'foo': 'bar'}
})
}
fetch('https://onesignal.com/api/v1/notifications', obj)
I know you're not really supposed to put your API key in client code, but this is just a test to see if it would work. Besides, the error I'm getting isn't a bad response from the server, it's:
Possible Unhandled Promise Rejection (id: 0):
unsupported BodyInit type
I've tried putting a catch method on the fetch, but it doesn't get called.
At a bit of a loss, not really sure how to proceed.
Thanks in advance!
Even I tried the same POST request for One-Signal REST API for creating notifications,the below worked for me fine.
const bodyObj = {
app_id: "**********",
included_segments: ["All"],
data: {"foo": "bar"},
contents: {"en": "Hi good morning"}
}
fetch('https://onesignal.com/api/v1/notifications',{
method:'POST',
headers:{
'Authorization':'Basic **********',
'Content-Type':'application/json'
},
body:JSON.stringify(bodyObj)
})
.then((response) => response.json())
.then((responseJson) => {
console.log("success api call");
})
.catch((error) => {
console.error(error);
});
Have you tried to change your json to the one below?
JSON.stringify({
app_id: '(API KEY)',
contents: {en: "English Message"},
app_ids: ["APP IDS"],
data: {foo: 'bar'}
})
Or even tried a simpler json?

Resources