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 :)

1

1 Answer 1

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); } 
Sign up to request clarification or add additional context in comments.

3 Comments

Okay this looks pretty good. how does it know where to put $vat ?
Also, how do i handle the return? I expect to get a bunch of json data back from the api

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.