-1

I am trying to connect to the UK Companies House API. Ideally, I am looking for a JavaScript solution.

But I am trying to get this PHP variant up and running. How do I gain access to the API, with the API key?

PHP:

public function GetCompanyHouse(){

        $int = '00928555';

        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, 'http://data.companieshouse.gov.uk/doc/company/' . $int . '.json'); 
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true); 
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_HEADER, false);
        curl_setopt($ch, CURLOPT_TIMEOUT, '10');

        $result = curl_exec($ch);
        $status = curl_getinfo($ch, CURLINFO_HTTP_CODE);

        curl_close($ch);

        switch($status)
        {
            case '200':
                return json_decode($result);
                break;

            default:
                return false;
                break;
        }


    }

https://developer.companieshouse.gov.uk/api/docs/index/gettingStarted/apikey_authorisation.html

curl -XGET -u my_api_key: 

https://api.companieshouse.gov.uk/company/00000006

Do I set this as a header?

curl_setopt($ch, CURLOPT_HTTPHEADER, array(
    'u: my_api_key'
    ));

Is it possible to just do a JSON call like this? https://api.companieshouse.gov.uk/company/00000006?api_key=xxxxxx

Here is a jQuery model in the works

http://jsfiddle.net/NYEaX/1412/

$(document).ready(function() {
  console.log("api");


xhr = new XMLHttpRequest();

$(document).ready(function() {
  $.ajax({
    url: 'https://api.companieshouse.gov.uk/search?q=subway',
    type: 'GET',
    datatype: 'json',
    success: function() { alert("Success"); },
    error: function() { alert('Failed!'); },
    beforeSend: setHeader       
  });   
});

function setHeader(xhr) {

  xhr.setRequestHeader('Authorization', 'Basic bXlfYXBpX2tleTo=');
//  xhr.setRequestHeader('X-GET', 'xx');
}  

});
halfer
  • 19,824
  • 17
  • 99
  • 186
The Old County
  • 89
  • 13
  • 59
  • 129
  • 1
    You would set the Authorization key into the request header. "is it possible to just do a json call like this -- https://api.companieshouse.gov.uk/company/00000006?api_key=xxxxxx" Only if the endpoint takes an the api_key in the endpoint argument – Jonathan Newton Aug 18 '16 at 09:08
  • that doesn't work - https://api.companieshouse.gov.uk/company/00000006?api_key=*** – The Old County Aug 18 '16 at 09:14
  • ["For an API key of my_api_key, the following curl request demonstrates the setting of the Authorization HTTP request header"](https://developer.companieshouse.gov.uk/api/docs/index/gettingStarted/apikey_authorisation.html) This is in the documentation – Jonathan Newton Aug 18 '16 at 09:15
  • Yes - I have read the documentation - and tried a php approach and a jquery approach - neither works. Have you obtained a company house key to test these – The Old County Aug 18 '16 at 09:19
  • How do we take these authorisation parts and incorporate them as actual working code – The Old County Aug 18 '16 at 09:22
  • -- I have tried adding this to the php variant - still nothing curl_setopt($ch, CURLOPT_USERPWD, 'xxxx:'); – The Old County Aug 18 '16 at 09:31
  • If your present target is to connect via PHP, please remove the JS version from the questio - it isn't relevant to start with, and just muddies the water. It can go into a separate question when your target is to create a JS version. – halfer Aug 18 '16 at 09:34
  • Its purely to connect to the same service and explore ALL and any options – The Old County Aug 18 '16 at 09:36
  • It's also not clear what problem you are having with the PHP. Do you get any outputs or errors? – halfer Aug 18 '16 at 09:41
  • You have a mix of XMLHttpRequest and Ajax you can use one or the other I'm confused why you have used both, if you look in the console you are getting a 401 response could have something to do with your key? http://jsfiddle.net/NYEaX/1414/ @TheOldCounty are you getting any errors in the console? – Jonathan Newton Aug 18 '16 at 09:49
  • I get no connection via php curl -- nothing cames back - I can see the call made in the network -- no data - that's the problem – The Old County Aug 18 '16 at 10:46
  • J Newton - I think your example is getting a "Status Code:401 Unauthorized" -- No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://fiddle.jshell.net' is therefore not allowed access. The response had HTTP status code 401. -- is it possible to bypass this by setting the cors? – The Old County Aug 18 '16 at 10:49
  • _“is it possible to bypass this by setting the cors?”_ – CORS has to be enabled by the party that you want to request data _from_ – you can not enable it on your end. – CBroe Aug 18 '16 at 11:01
  • _“Do I set this as a header?”_ – first of all, you go look up in the cURL documentation, what `-u` does. With that information, you go check the PHP manual page that lists all the cURL options you can set, and look for what might be the appropriate equivalent. – CBroe Aug 18 '16 at 11:03
  • Cheers - do you have a working example for this particular api – The Old County Aug 18 '16 at 11:13
  • A lot of copy and pasting from docs - no actual working solutions. – The Old County Aug 19 '16 at 08:49

3 Answers3

0

for me curl -u "token": https://api.companieshouse.gov.uk/company/SC185088 in command prompt works

Eldhose Abraham
  • 551
  • 3
  • 8
  • Sure - but then how do we do a solution in php - or js -- all I have is an api key - has anyone tried these solutions with their own api key from the company house? – The Old County Aug 18 '16 at 10:58
0

Here is some sample code, modify as needed...

$my_api_key = "blablablablabla";

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://api.company-information.service.gov.uk/company/11263172'); 
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true); 
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_TIMEOUT, '10');
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Authorization: '.$my_api_key
));

$result = curl_exec($ch);

curl_close($ch);
print_r($result);
0

Not an expert but the following has worked for me

    //Function thanks to Stackoverflow member:
    //https://stackoverflow.com/questions/7393719/human-readable-json-aka-add-spaces-and-breaks-to-json-dump
    //https://stackoverflow.com/users/720204/som
    function jsonToReadable($json){
        $tc = 0;        //tab count
        $r = '';        //result
        $q = false;     //quotes
        $t = "\t";      //tab
        $nl = "\n";     //new line

        for($i=0;$i<strlen($json);$i++){
            $c = $json[$i];
            if($c=='"' && $json[$i-1]!='\\') $q = !$q;
            if($q){
                $r .= $c;
                continue;
            }
            switch($c){
                case '{':
                case '[':
                    $r .= $c . $nl . str_repeat($t, ++$tc);
                    break;
                case '}':
                case ']':
                    $r .= $nl . str_repeat($t, --$tc) . $c;
                    break;
                case ',':
                    $r .= $c;
                    if($json[$i+1]!='{' && $json[$i+1]!='[') $r .= $nl . str_repeat($t, $tc);
                    break;
                case ':':
                    $r .= $c . ' ';
                    break;
                default:
                    $r .= $c;
            }
        }
        return $r;
    }

    //I'm searching time company incorporated, adjust your search variables/query to your needs
    //I'm using the Advanced Search here but again adjust to your needs
    //https://developer-specs.company-information.service.gov.uk/companies-house-public-data-api/reference/search/advanced-company-search
    //My main issue was getting connected and rid of "Invalid authorisation" trying to connect to the service.
    //Why they don't just issue a multi language toolkit I'll never know, it may save them some bandwith...

    $incorporated_from= urlencode('2022-11-14');
    $incorporated_to= urlencode('2022-11-14');

    $curl = curl_init("https://api.company-information.service.gov.uk/advanced-search/companies?incorporated_from=".$incorporated_from."&incorporated_to=".$incorporated_to."&size=100");

    //IMPORTANT!!! BASE64 Encode your API key but also add a colon ':' at the end of it before encoding. 
    //I found this finally worked if I pre-prepared the BASE64 encoding of my API key rather than let PHP do it on the fly
    //So your headers variable will look something like 
    //$headers = array('Authorization: Basic BLAHBLAHBLAHBLAHBLAHBLAHUfsd5436ghZWY4Og==');

    $headers = array('Authorization: Basic MY_COMPANIES_HOUSE_REST_API_KEY_WITH_COLON_AT_END_BASE64_ENCODED');

    curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);

    curl_setopt($curl, CURLOPT_HEADER, true); // Comment out or use when debugging to show returning header

    curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);

    $results = curl_exec($curl);

    //Make the JSON returned readable - thanks to Stackoverflow member "som", that created the function!

    echo jsonToReadable($results);

    if(curl_errno($curl))

    {
        echo 'Curl error : ' . curl_error($curl);
    }

    curl_close($curl);
lxjam
  • 1