Syntax for make get request using fetch()

Please can someone help with the syntax I’m suppose to use to make a Get request using fetch() and not curl. I have been struggling to translate the Curl example given in the docs.

If you are not familiar with the javascript fetch API I recommend reading both the Mozilla documents for fetch and also about http Basic (this is how Companies House does the authorization).

If you’re using fetch then you will need to send the appropriate http header for the http Basic authorization yourself. (Lots of other tools will do this for you).

There is an example in the thread here - I’d just add a quick clarification below:

Clarification: where they have:

var key = 'MyApiKey';
var headers = new Headers ({
  'Authorization': 'Basic ' + btoa(key),
  'Content-Type': 'text/json',
  'Origin': 'MyOriginUrl'

… I would spell this out to make it clearer (hopefully):

// spelling it out - API key is the http "username", there is an empty password
var userAndPass = 'MyApiKey' + ':' + '';
// Origin - if e.g. your script was at then this would be
var myOrigin = 'MyOriginUrl';
var headers = new Headers ({
  'Authorization': 'Basic ' + btoa(userAndPass),
  'Content-Type': 'application/json',
  'Origin': myOrigin

I don’t think you need to send the 'Content-Type': 'application/json' either as you’re not sending any data to Companies House in the body. (The appropriate header to say you would be interested in json would be the Accept: header but again not needed here. You may need it for the documents API though).

Good luck.

Note: you also need to ensure you’ve done a couple of other things e.g. you have created a live application not a test one where you have registered this with Companies House. You’ll also need to have the url your javascript will be calling Companies House from in the “javascript urls” section of your Companies House application. If you are running something on a local host then you’ll need to use the workaround for localhost also.

Thank you so much. I have finally got it working. I had to add the headers object with my apikey as the value for the Authorization name key. I didn’t need the ‘Basic’ part.

Also, I have one more question. Please can you let me know how to search for all companies and have it return resulsts. I know it limits to a certain amount to one page, but when I use the ‘/search/companies’ end point. It returns an object with no items I’m the array.

What am I doing wrong?

Answered on your other question.