0

I am trying to implement an API call from my system, and the API has an example that looks like this:

curl -u "<brugernavn>:<password>" -XPOST http://distribution.virk.dk/cvr-permanent/_search -d'
{ "from" : 0, "size" : 1,
  "query": {
    "term": {
      "cvrNummer": 10961211
    }
  }
}
'

Now i want to turn this in to php code. Im thinking it will look something like this:

        public function requestApiV2($vat){

     // Start cURL
     $ch = curl_init();

     // Determine protocol
     $protocol = 'http';
     $parameters = json(
        { "from" : 0, "size" : 1,
            "query": {
              "term": {
                "cvrNummer": $vat
              }
            }
          }
     );
     // Set cURL options
    curl_setopt($ch, CURLOPT_URL, $protocol . '://distribution.virk.dk/cvr-permanent/_search' . http_build_query($parameters));
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
      // Parse result
    $result = curl_exec($ch);
    // Close connection when done
    curl_close($ch);

    // Parse from json to array
    $data = json_decode($result, true);

}

I can't test this yet, as I still need to acquire username and password from the API, but I am also uncertain about how I send the username and password along with the request in the correct way. Is there a CURLOPT for this as well? I am also uncertain about if my parameters are implemented the right way with the json like that.

thank you :)

Lin Du
  • 88,126
  • 95
  • 281
  • 483
Mike Nor
  • 227
  • 1
  • 9
  • 18
  • 2
    Possible duplicate of [How to use basic authorization in PHP curl](https://stackoverflow.com/questions/20064271/how-to-use-basic-authorization-in-php-curl) – Chris White Apr 29 '19 at 14:12

1 Answers1

1

use Guzzle library. Laravel has included the Guzzle library so you dont need to install it

With Guzzle, the below will do

use GuzzleHttp\Client;

public function requestApiV2($vat){

$client = new Client([
    // Base URI is used with relative requests
    'base_uri' => 'http://distribution.virk.dk/,
]);


$response = $client->post('cvr-permanent/_search', [
    'auth' => ['username', 'password'],
    'json' => [
        'from' => 0,
        'size' => 1,
        'query' => [
            'term' => [ 
                'cvrNumber' => $vat
            ]
        ]
    ]
]);

$body = $response->getBody();
dd($body);
}
Michael Nguyen
  • 1,691
  • 2
  • 18
  • 33