401 Unauthorised when calling API through JavaScript

Hi,

Can I please get help with the following code, which is resulting in 401 code.

$(document).ready(function() {
 console.log("api");
xhr = new XMLHttpRequest();
$(document).ready(function() {
 $.ajax({
   url: 'https://api.companieshouse.gov.uk/company/05961102',
   type: 'GET',
   datatype: 'json',
   success: function() { alert('Success'); },
   error: function() { alert('Failed!' + xhr.readyStatus ); },
   beforeSend: function (xhr) {
					   xhr.withCredentials = true;
        	
            var key = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx:';
            key = btoa(key);
        xhr.setRequestHeader('Authorization', 'Basic ' + encodeURIComponent(key));
            alert(encodeURIComponent(key));
           },
 });   
});
});

When running this in developer tool I am getting 401 authorised error. My understanding is that it might something to do with encoding of the key but not sure.

Thanks in advance.

Encoding looks OK (base64 of (user ID + ‘:’) ).

Since the request you’ll be making is a CORS (cross-origin) one CH checks the “Origin” header sent by the javascript client.

  • The location of your javascript code calling the API should be in one of the domains you registered with Companies House.
  • The protocol used to access your code also should be the one you registered e.g. if you registered https://yourdomain/ then if you are accessing your javascript via e.g. http://yourdomain/mytest.html the call will fail.

For some examples of people debugging AJAX calls to CH see:

For a more in-depth work-through of this see:

If I read correctly jQuery ajax call syntax for headers has changed a bit between the various versions so it might be worth confirming you’re setting that correctly for the version you’re using. Also if you think that’s not working you could try the URL basic authentication e.g.

var testUserName={your CH user ID};
var testKey=testUserName + ':'; // password part is blank
var testURL='https://'+testKey+'@'+'api.companieshouse.gov.uk/company/05961102';

Good luck.