Issue
I am trying to get a simple user by ID. In my case the field is called userID and the ID is 150. I know from the server, that this user exists. I also get returned all users, so the connection is fine.
This is what I tried:
var dict = new Object();
var dict = {
"userID": "150"
};
fetch(url,
{method:'POST',
headers: { 'Authorization': 'Basic ' + btoa(username+ ":" + password), },
body: JSON.stringify(dict),
})
.then(response => response.json())
.then(json => console.log(json));
But no matter, I will always receive a payload of 0.
From the official docs of the server it says:
"You need to send a params dictionary in the POST body. This is a key, value pair array of your method’s input parameters. If you’re unsure of what these are, they can be seen when you run a method in Kumulos’ control panel".
They even post an example:
curl -X POST
-H "Content-Type: application/x-www-form-urlencoded"
-H "Accept: application/json"
-H "Authorization: Basic base64EncodedUsername:Password"
-H "Cache-Control: no-cache"
-d 'params[photos]=1
¶ms[timeCreated]=1462060800'
"https://api.kumulos.com/b2.2/yourAPIKey/getNewPhotographers.json"
Saying they gave as parameters "timeCreated".
Even in PHP, they claim this would work:
CURLOPT_POSTFIELDS => "params[photos]=1¶ms[timeCreated]=1462060800",
is my "translation" to javascript that wrong?
Only from what the docs say, would you agree that my code is correct, or is the issue with me? I also havent been able to get the correct results from postman with these parameters.
Thank you !
EDIT:
I was however able to get the correct data doing it the old way:
var xhr = new XMLHttpRequest();
xhr.open("POST", url);
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xhr.setRequestHeader("Accept", "application/json");
xhr.setRequestHeader("Authorization", 'Basic ' + btoa(username+ ":" + password));
xhr.onreadystatechange = function () {
if (xhr.readyState === 4) {
console.log(xhr.status);
console.log(xhr.responseText);
}};
var data = `params[userID]=150`;
xhr.send(data);
Solution
The example shows that the API expects URL-encoded parameters, not JSON. And the parameter names need to be enclosed in params[...]
.
The equivalent JS is
let body = Object.entries(dict).map(([key, value]) =>
encodeURIComponent(`params[${key}]`) + '=' + encodeURIComponent(value)).join('&');
fetch(url, {
method: 'POST',
headers: {
Authorization: 'Basic ' + btoa(username+ ":" + password),
"Content-Type": "application/x-www-form-urlencoded"
},
body: body
}).then(response => response.json())
.then(json => console.log(json));
Answered By - Barmar