如何连接到公司的房子API -特定的卷曲头和API密钥要求

How to connect to the Companies House API - with specific curl header and API key requirements?

本文关键字:API 密钥 连接 公司 房子 何连接      更新时间:2023-09-26

我正在尝试连接到英国公司的API。理想情况下,我正在寻找一个JavaScript解决方案。

但是我正试图让这个PHP变体启动和运行。如何使用API密钥访问API ?

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

我把这个设置为标题吗?

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

是可能的只是做一个JSON调用这样吗?https://api.companieshouse.gov.uk/company/00000006?api_key=xxxxxx

这是一个正在工作的jQuery模型

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');
}  
});

给我curl -u "token": https://api.companieshouse.gov.uk/company/SC185088

下面是一些示例代码,根据需要修改…

$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);

不是专家,但以下方法对我有用

    //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);