I made an external adapter from the Javascript External Adapter Template from Chainlink, trying to use the Client Credentials flow for Spotify's API to return artist data, documentation listed below.
https://developer.spotify.com/documentation/general/guides/authorization-guide/#client-credentials-flow
https://developer.spotify.com/console/get-artist/
and I am able to make the call just fine with this code through Axios
but when I try to run the same call through the External Adapter which uses Axios for it's API calls as well, I get this error.
Here is a snippet of the main code of the external adapter from index.js
const customParams = {
artist: [''],
endpoint: false
}
const createRequest = (input, callback) => {
// The Validator helps you validate the Chainlink request data
const apiID = process.env.API_ID
const apiKey = process.env.API_KEY
let token = 'BQDlkzka093OuR4tL7XyaI-Tag4R166FQGBSogBP6hEBxhsCjH8XfMRqs_apKFk0T87FGIrwPtT1bkuGCeE';
const validator = new Validator(callback, input, customParams)
const jobRunID = validator.validated.id
const endpoint = validator.validated.data.endpoint
const artistID = validator.validated.data.artist.toUpperCase()
const url = `https://api.spotify.com/v1/artists/${artistID}`
const params = {
artistID
}
// curl -X "GET" "https://api.spotify.com/v1/artists/5K4W6rqBFWDnAN6FQUkS6x" -H "Accept: application/json" -H "Content-Type: application/json" -H "Authorization: Bearer authtoken"
// This is where you would add method and headers
// you can add method like GET or POST and add it to the config
// The default is GET requests
// method = 'get'
// headers = 'headers.....'
const head = {
'Accept' : 'application/json',
'Content-Type' : 'application/json',
'Authorization' : 'Bearer ' + token
}
const config = {
url,
headers: head
}
console.log("config:", config)
and this is the command I am running in the terminal to pass in the Spotify Artist ID
curl -X POST -H "content-type:application/json" "http://localhost:8080/" --data '{ "id": 0, "data": { "": "5K4W6rqBFWDnAN6FQUkS6x"} }'
-Edit-
Just to show that the code isn't all totally wrong, I am able to make a call through the external adapter to this url https://jsonplaceholder.typicode.com/posts/5, passing in the 5 with this command.
curl -X POST -H "content-type:application/json" "http://localhost:8080/" --data '{ "id": 0, "data": { "": "5"} }'
The issue was with this line, making the artist ID all uppercase.
const artistID = validator.validated.data.artist.toUpperCase() // Changed this
const artistID = validator.validated.data.artist // To this
Related
I'm trying to call an API using javascript that contains a file in the POST request. The file is located at another URL that I have to grab before calling the API. I think I need to use a fetch to get the file data as a blob and then pass it along to the post request.
I have a working example in CURL but can't work out the syntax to translate it into JS.
Working example in CURL:
curl -X POST -H 'Authorization: Token token=****' -H 'Content-Type: multipart/form-data'
-H 'content-type: multipart/form-data; boundary=----WebKitFormBoundary7MA4YWxkTrZu0gW' -F file=#/User/somefile.pdf -F file_name=nameForFile
-F is_shared=true -F targetable_id=1 -F targetable_type=Lead -X POST "https://endpoint.com/api/documents"
Javascript:
var formData = new FormData();
fetch("http://wheremyfileis.com/file.pdf")
.then(response => response.blob())
.then(fileData => {
var fileBlob = new Blob((fileData );
formData.append("targetable_id", 1);
formData.append("targetable_type", "Lead");
formData.append("file", fileBlob);
var headers = {"Authorization": "Token token=***", "Content-Type":"multipart/form-data"};
var options = { headers: headers, body: "Hello world"};
var url = "https://endpoint.com/api/documents";
client.request.post(url, options)
.then (
function(data) { console.log(data); },
function(error) {console.log(error);}
);
I am trying to register a new user in OKTA in Javascript with a curl mentioned here
.
I want to make a curl format like this
curl -v -X POST \
-H "Accept: application/json" \
-H "Content-Type: application/json" \
-H "Authorization: SSWS ${api_token}" \
-d '{
"profile": {
"firstName": "Isaac",
"lastName": "Brock",
"email": "isaac.brock#example.com",
"login": "isaac.brock#example.com",
"mobilePhone": "555-415-1337"
},
"credentials": {
"password" : { "value": "tlpWENT2m" }
}
}' "https://dev-662976.oktapreview.com/api/v1/users?activate=false"
This is part of code I write
handleSubmit(e){
e.preventDefault();
var data = {};
var profile = {};
var credentials = {};
profile['firstName'] = document.getElementById('firstName').value;
profile['lastName'] = document.getElementById('lastName').value;
profile['email'] = document.getElementById('email').value;
profile["login"] = document.getElementById('email').value;
profile['mobliePhone'] = "555-415-1337";
data['profile'] = profile;
credentials['password'] = {"value":document.getElementById('password').value};
data["credentials"] = credentials;
this.registrationApiCall(data);
//console.log(data);
//registrationApiCall(data);
}
registrationApiCall(data){
return axios({
method: 'post',
url: 'https://dev-662976.oktapreview.com/api/v1/users?activate=false',
data: data,
config: {
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
"Authorization": "SSWS <my_ssws_token>"
}
}
}).then(function(value) {
console.log(value);
}).catch(function(err) {
console.log(err);
});
}
I get a 403 error like this:
POST https://dev-662976.oktapreview.com/api/v1/users?activate=false 403 (Forbidden)
Register.js:72 Error: Request failed with status code 403
at createError (createError.js:16)
at settle (settle.js:18)
at XMLHttpRequest.handleLoad (xhr.js:77)
From the console of chrome, I can see two requests. They have same request url but the first is 200 and doesn't include any payload and the second include my data which is a 403 error.
I write this code referring this dude but I think his format is not correct, but it works well on his demo. Could you tell me how to make it correct?
I have no idea if I should use axios, if there is some better idea. Please tell me.
I have a django backend that will save / remove image when receiving request from API. I have succesfully delete the saved image if i using swagger / postman to call the API (sending the parameter null object). But i can't get it work via Axios.
The CURL from Swagger :
curl -X PUT --header 'Content-Type: application/json'
--header 'Accept: application/json'
--header 'Authorization: JWT eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoxLCJ1c2VybmFtZSI6IlNZU0FETUlOQFRSRUVTLkhBUlBBLkNPTSIsImV4cCI6MTUxNTAzNTU1MiwidXNlcl9uYW1lIjoiU1lTQURNSU5AVFJFRVMuSEFSUEEuQ09NIiwib3JpZ19pYXQiOjE1MTQ5NDkxMDR9.oz3_2fGKlOCesmU_RmSRJZOifZeFFQO1nwAWzyD6BYc'
-d '{ \
"menu_type": 255, \
"icon": null, \
"login_id": 1 \
}'
My axios sample code :
formData.append('menu_type', 255)
formData.append('login_id', 1)
formData.append('icon', null)
const config = {
headers: {
'content-type': 'application/json'
}
}
return new Promise(resolve => {
axios.put(url + form.menu_uuid + "/", formData, config)
.then(function (response) {
resolve(response);
})
.catch(function (error) {
resolve(error.response);
});
});
My request payload screenshot :
Is there something that i missing that makes this axios request won't work ?
i have succesfully deleted image at the API by using this axios code :
formData.append('icon', null, '')
maybe this answer will be useful for other person..
I'm getting an error from dropbox api:
Error in call to API function "files/download": HTTP header "Dropbox-API-Arg": could not decode input as JSON.
let url = 'https://content.dropboxapi.com/2/files/download'
let headers = new Headers({ });
headers.append('Authorization', 'Bearer ...');
headers.append('Dropbox-API-Arg', '/readme.txt');
let options = new RequestOptions({ headers: headers });
this.http
.get(url, options)
.subscribe(this.fileContent)
this is the example they put on their api:
curl -X POST https://content.dropboxapi.com/2/files/download \
--header "Authorization: Bearer <get access token>" \
--header "Dropbox-API-Arg: {\"path\": \"/Homework/math/Prime_Numbers.txt\"}"
I might have gotten the headers wrong in angular I've never used them before.
Edit: path variable is a string equal to a file path. i.e. "readme.txt"
Did a quick google and found this: https://www.dropboxforum.com/t5/API-support/HTTP-header-quot-Dropbox-API-Arg-quot-could-not-decode-input-as/td-p/173822
Essentially the format for the variable path isn't in accordance to what the api expects.
I've added the utility function the link provides:
var charsToEncode = /[\u007f-\uffff]/g;
function http_header_safe_json(v) {
return JSON.stringify(v).replace(charsToEncode,
function(c) {
return '\\u'+('000'+c.charCodeAt(0).toString(16)).slice(-4);
}
);
}
EDIT
Your path variable should look like this:
var path = {
path: '/readme.txt'
};
I am trying to set up public forms on a wp site so people can schedule an exam without a login, which is supposed to link to the clients salesforce desk app. the Desk API docs recommend this.
$ curl https://yoursite.desk.com/api/v2/cases \
-u email:password \
-X POST \
-H 'Content-Type: application/json' \
-H 'Accept: application/json' \
-d '{"subject":"Test"}'
I admittedly have relied on es6 syntax for my inexperience with rest api calls and am having trouble validating my POST request. My javascript looks like so, but I get a 404 as well as a "Response to preflight check doesn't pass access control check." I'm assuming I am missing some credentials.
document.querySelector('#submitDesk').addEventListener('click', schedule);
function schedule() {
var firstname = document.querySelector('#firstname').value;
var lastname = document.querySelector('#lastname').value;
var email = document.querySelector('#email').value;
fetch('https://foo.desk.com/api/v2/cases', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Accept' : 'application/json'
},
body: {
'firstname': firstname,
'lastname': lastname,
'email': email
}
})
.then(function(response) {
return response.json();
})
.then(function(response) {
console.log(response);
})
}