Need help converting cURL command to Javascipt - javascript

I am trying to get recipe nutritional information from Edamam API. In the API docs, the cURL command is:
curl -d #recipe.json -H "Content-Type: application/json" "https://api.edamam.com/api/nutrition-details?app_id=${YOUR_APP_ID}&app_key=${YOUR_APP_KEY}"
I am using Axios and Javascript to try to access the API with a Post command:
import axios from "axios";
var postData = './recipe.json'
let axiosConfig = {
headers: {
'Content-Type': 'application/json;charset=UTF-8',}
};
axios.post('https://api.edamam.com/api/nutrition-details?app_id=XXXXXXXX&app_key=XXXXXXXXXXXXXXXXXXXXX', postData, axiosConfig)
.then((res) => {
console.log("RESPONSE RECEIVED: ", res);
})
.catch((err) => {
console.log("AXIOS ERROR: ", err);
})
I receive a 400 error back. Any thoughts on what I need to do to make this work would be appreciated.

postData needs to be a string of JSON.
You appear to be passing it a string containing a filename.
You might want to read './recipe.json' with axios.get() to fetch the data from it.

In your cURL the option -d #recipe.json is sending the content of the file recipe.json
But, In your Code postData = './recipe.json', You are just passing the name instead of reading it.
First you need to read the data from recipe.json,Then you need to send it through request.

Related

how to put --data in GET method ? since GET not recieving body parameter

i've given the api endpoint with GET method but i think it needs a body, when i test it on postman it works fine but in react native when i try to fetch it it shows error [TypeError: Body not allowed for GET or HEAD requests]
my backend partner send this curl, how to use the --data since GET are not recieving any body
curl --request GET \
--url http://base_url/api/v2/order/all \
--header 'Content-Type: application/json' \
--cookie 'token=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJwaG9uZU51bWJlciI6IjA4ODc3NzA5MjIxIiwidXNlcm5hbWUiOiJGbG8iLCJpYXQiOjE2NTEwMzIxNTYsImV4cCI6MTY1MTA3NTM1Nn0.JkwTPvjig7bd8Q27MvZ7DsUCz68Qyzh3EctFTRh-m0E; connect.sid=s%253AgtaL-l_60sBGAdEhTiHspbzX3rBBiEFg.O5z0JBi7Oqo1UXSZOxQckm2FNhG3A%252BWZod951CC5Cys' \
--data '{
"userId":"79025884",
"limit":10,
"page":1
}'
this is my function
function GetActivity() {
const url = APIConfig.SERVER.ORDER + "/all";
fetch(url, {
method: "GET",
headers: { "content-type": "application/JSON" },
body: JSON.stringify({
userId: "79025884",
limit: 10,
page: 1,
}),
})
.then((response) => response.json())
.then((data) => {
console.log("GetActivity Order:", data);
setOrderList(data.data);
})
.catch((error) => {
console.error("Error:", error);
});
}
For a GET request, any parameters you want to pass to the API end point will need to be sent as part of the url I believe.
E.g. http://example.com/id/1 (where 1 is the dynamic value for the ID parameter)
I think the error you are seeing is because your trying to set a "body" value for a get request, which would be used with a POST request instead for example.
The same problem I faced several days ago, and I made some research about it. I can say that even though it is possible to use get method with body in postman you can't use get method with body with fetch or axios, because body is not allowed. And I think you should allow post method in your backend if your want to send data. You can read in depth about it here.
You need to add it to the URI or the HTTP request headers depending on the data. Usually URI path for hierarchical resource identification data and URI query for non-hierarchical. There are standard HTTP headers for many things including pagination. https://developer.mozilla.org/en-US/docs/Web/HTTP/Range_requests They are for byte ranges, but you can use custom units like pages. Another way is doing pagination with URI.
GET https://example.com/api/v1/orders/by-user-id/79025884/?page=1&limit=10
GET https://example.com/api/v1/orders/by-user-id/79025884/ "Range: items=1-10"

Getting error 415 - Unsupported media Type in fetch api

Following curl request is working and it's generating token. But when I use it as fetch API, I'm getting 415 error - Unsupported media type.
curl -k -X POST -H "Content-Type: application/x-www-form-urlencoded" -u "Secret_ID:Secret_Key" -d "grant_type=password&username=mahesh#gmail.com&password=Welcome1234&scope=https://si01-test.prod.com/bca/api" "https://identity.com/oauth2/v1/token"
I'm using fetch API like this:
let username = 'Secret_ID';
let password = 'Secret_Key';
let formdata = new FormData();
let headers = new Headers();
formdata.append('Content-Type','application/x-www-form-urlencoded');
formdata.append('grant_type','password');
formdata.append('username','mahesh#gmail.com');
formdata.append('password','Welcome1234');
formdata.append('scope','https://si01-test.prod.com/bca/api');
headers.append('Authorization', 'Basic VGVzdF9zaTAxX0FQUElEOjNkZGI4MmYxLWI5OTktNDlhMy1hMmM5LWQ1OGMyOTU2ODg4Yg=='); // encoded username and password
fetch('https://identity.com/oauth2/v1/token', {
method: 'POST',
headers: headers,
body: formdata
}).then((response) => response.json())
.then((responseJson) => {
console.log(responseJson);
this.setState({
data: responseJson
})
})
.catch((error) => {
console.error(error);
});
What's wrong here? Any suggestion will be appreciable..
So as I mentioned, Request is working fine in CuRL / Postman and it makes my life easier.
If you you have curl command and its working fine then you can just import that command directly in postman and it will work fine.
Now if your request is working fine in postman, then you can just copy code of it in any language that is given in Postman.

Get report for a single node/certname via PuppetDB API using ReactJS

So the API endpoint "reports" does provide this information using curl as below:
curl -X GET http://puppetserver:8080/pdb/query/v4/reports -d 'limit=1' -d 'query=["=", "certname", "node.fqdn"]'
But as I am trying to achieve this using javascript in React, that doesn't seem to work.
Something like this:
let puppetdbUrl = 'http://puppetserver:8080/pdb/query/v4/reports';
getReport = () => {
axios.get(puppetdbUrl, {
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
},
params: {
'certname': 'node.fqdn'
}
})
.then(response => {
this.setState({resultReport: response});
console.log(this.state.resultReport);
})
}
The error I get is:
400 (Bad Request). Unsupported query parameter 'certname'.
The document for puppetdb API does have these query parameters:
https://puppet.com/docs/puppetdb/5.2/api/query/v4/reports.html. Can someone please help?
I get the same error while trying to achieve the same thing using a rest client.

How to send a request like in terminal in react?

I'm trying to send the following request in my react application
curl -H 'Client-ID: p0gch4mp101fy451do9uod1s1x9i4a' \
-X GET 'https://api.twitch.tv/helix/streams?game_id=33214'
I am able to put this exact string into my terminal and receive a response, but how exactly do I go about doing this in JavaScript or REACT?
I have tried using fetch in react but that only allows me to send a get request and that gives me an response of unauthorized access because it only takes a link, and if I send the entire thing as a string it'll just give me a 404 error because it's unrecognized.
In my terminal I can just paste in the whole string and get a valid response back. how do I replicate this in JavaScript or react?
Fetch works with any standard request method and allows for setting headers as below:
const url = 'https://api.twitch.tv/helix/streams?game_id=33214';
const options = {
method: 'GET',
headers: {
'Client-ID': 'p0gch4mp101fy451do9uod1s1x9i4a'
},
//body: JSON.stringify({name:'test'}) //example of how to have a body also
};
fetch(url, options)
.then(res=>{
if(!res.ok)
throw new Error(res.statusText);
return res.json();
})
.then(json => console.log(json))
.catch(err => {
console.error('Request failed', err)
});
for more info read the docs https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API
or check this https://flaviocopes.com/fetch-api/

Using React and axios for curl

Is it possible to make a curl request by using axios?
the curl string is:
curl -v 'https://developer.api.autodesk.com/authentication/v1/authenticate' --data 'client_id=1234&client_secret=1234&grant_type=client_credentials&scope=bucket:create bucket:read data:write data:read viewables:read' --header 'Content-Type: application/x-www-form-urlencoded' -k | jq '.'
I tried to do this:
getToken() {
axios.get({
url: 'https://developer.api.autodesk.com/authentication/v1/authenticate',
data: {
client_id: '1234',
client_secret: '1234',
grant_type : 'client_credentials',
scope: 'data:read data:viewables'
},
beforeSend: function(xhr) {
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded")
}, success: function(data){
console.log(data)
}
})
}
But with no luck - e.g. nothing happens.
I previously used the cygwin-terminal to make the curl-request and I succesfully got the response
{
"token_type": "Bearer",
"expires_in": 1799,
"access_token": "eyJhbGciOiJIUzI1NiIsImtpZCI6Imp3dF9zeW1tZXRyaWNfa2V5X2RldiJ9.eyJjbGllbnRfaWQiOiJjWTFqcm1rQXhPSVptbnNsOVhYN0puVURtVEVETGNGeCIsImV4cCI6MTQ4NzU2NzgwMSwic2NvcGUiOlsiZGF0YTpyZWFkIl0sImF1ZCI6Imh0dHBzOi8vYXV0b2Rlc2suY29tL2F1ZC9qd3RleHAzMCIsImp0aSI6InJZcEZZTURyemtMOWZ1ZFdKSVVlVkxucGNWT29BTDg0dFpKbXlmZ29ORW1MakF0YVVtWktRWU1lYUR2UGlnNGsifQ.uzNexXCeu4efGPKGGhHdKxoJDXHAzLb28B2nSjrq_ys"
}
So, is this possible with React/axios?
In addition to the question, can I pass the received token to another curl request?
Well it's not really "a curl request". It's an HTTP request. Curl is just the tool you use to do HTTP (and other) actions via the command line.
In your HTTP request, I can see you're using axios.get(), however you're trying to do a post request (you've got a data object you're trying to send). So you should be using axios.post(). It'd be best to check out the axios page to see the syntax for HTTP posts, including how to include the data and header objects in the post.
In answer to your second question, yes you can. In the .then() section of your first axios post, you can do another axios post using the response, e.g.
axios.post(
...
).then(response => {
// do another post with response.token or whatever as the data
})
...

Categories

Resources