API's and CORS


#1

Does anyone have a template or basic call to the API? I’ve tried every which way, but seem to only get Error 401 Unauthorized with my Admin account when making a GET request. If I don’t specify JSONP as the dataType, I get a CORS error. I have been at this for hours. I’m posting the code I have used and am pretty sure is correct. Let me know if any of you see anything.

Note that I did change the URL to example and pass to password.

var user = “admin”;
var pass = “password”;
var url = “https://example.sonar.software/api/v1/accounts/734201”;

$.ajax({
url: url,
type: “GET”,
dataType: “jsonp”,
jsonpCallback: ‘callBack’,
contentType: “application/json”,
crossDomain: true,
beforeSend: function (xhr) {
xhr.setRequestHeader(‘Authorization’, makeBaseAuth(user, pass));
},
success: function(msg) {
var msg = $.parseJSON(msg);
console.log(msg);
},
error: function (xhr, ajaxOptions, thrownError) {
alert(xhr.status);
//alert(xhr.responseText);
console.log(xhr.responseText);
var jsonObj = JSON.stringify(xhr.responseText);
$(’.js-my-modal’).text(jsonObj);
},
});


#2

You should never do this in an AJAX request, as you’ll be exposing your credentials in client side Javascript. This should always be called from the serverside.


#3

If you are interested, you can setup a simple node.js environment and make calls from there. This allows you to run JS from the server side. You can also render static HTML pages with a package like express.js. I also created an npm package just for the Sonar API here: node-sonar-api


#4

I will check this out. I ended up installing Composer/Guzzle., This wouldn’t work with my PHP version, and my Debian distro wouldn’t install PHP5.5, so had to go from PHP5.4 and went ahead to PHP7 and Debian 7 to Debian 9 and then had to rebuild my MySQL library calls in my framework because mysql was deprecated and now using mysqli or PDO. Basically, I just broke down and built a new web server and was forced to upgrade my custom framework, but I can pull data from Sonar now…which is nice. Although I don’t like the Composer/Guzzle route as it doesn’t integrate with what I’m doing very well. I wanted a minimum approach and I think Composer is too much and I don’t have very much control of where it goes. Any tips on node.js?

Thanks,

Kenny


#5

There is plenty of documentation online to get started, but if you have any specific questions I should be able to help!


#6

Postman is a great help in doing API work with Sonar.
We have done some integrations and migrations for other Sonar users in C++ and PHP and Postman just makes it easier to get what you are looking for.


#7

@Lee_Barton -> I just want to thank you! We’ve been using your node package for a while now for our own backend systems and it works AMAZING as a reliable connector for us.


#8

Absolutely! I am happy that others find my solution useful.