Can Anyone Explain Why I'm Getting a 400 Response Code with this JS Code?

Hello,

Not sure why I’m getting a 400 bad request status code from the below, when the endpoint I’m trying to access in the below code works with the python wrapper I wrote for the api. Can anyone help with this? Code below.

var request = new XMLHttpRequest()

request.open(‘GET’, ‘https://api.companieshouse.gov.uk/company/00197009/’, true)
request.setRequestHeader(“Content-Type”, “application/json”)
request.setRequestHeader(“Authorization”, “Basic my_key”)
request.onload = function() {
var data = JSON.parse(this.response)

if (request.status >= 200 && request.status < 400) {
console.log(date)
} else {
console.log(‘error’)
}
}

request.send()

Thanks in advance,

Ciaran

I don’t know but guess is - since you’re using js where before you used python - you now need to set the correct data in the http Basic header and this may differ from how you do in python e.g. you can either use (spelling it out):

var user = "MY_API_KEY";
var password = "";
request.open('GET', 'https://api.companieshouse.gov.uk/company/00197009', true, user, password);
// No need to send Authorization header now - see https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/open

OR

var user = "MY_API_KEY";
var password = "";
request.open('GET', 'https://api.companieshouse.gov.uk/company/00197009', true);
request.setRequestHeader("Authorization", "Basic " + btoa(username + ":" + password));

You don’t need the trailing “/” after the company number (but it works with this).
I don’t think you need:

request.setRequestHeader("Content-Type", "application/json") 

You’re not sending any http body (and the standard API doesn’t have endpoints which do). You might want:

request.setRequestHeader("Accept", "application/json") 

See https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Accept

If that wasn’t the issue it might be you’re running the javascript on a server you’ve not registered with CH - but I think you’d expect a different error in that case? There’s a checklist for different error types towards the end of this thread:

Works with Python wrapper
So likely totally different parameters for the function for http than javascript.