2

I'm trying to learn how I can interface with a json api. In the documentation they give me a curl example:

If I run this as a command it works fine, gives me my data in a json format.

I thought I was on the right track with this: PHP + curl, HTTP POST sample code?

but apparently not as I can't figure out what to do with the -H portion of this command.

curl -H "APIKey:My:ApI;key;" -H "Content-Type:.../json" "https://urlofapp.com/API/GetTransaction" -d "{ 'CustomerID':'12345','EndDate':'2018-12-31','StartDate':'2018-01-01'}" > test.json

Trying to get the result into an array that I can sum and show a total of their orders for the year.

From the link I provided above I was trying to start with this:

// set post fields
$post = [
'CustomerID' => 12345,
'StartDate' => 2018-01-01,
'EndDate'   => 2018-12-31,
];

$ch = curl_init('https://urlofapp.com/API/GetTransaction');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post);

// execute!
$response = curl_exec($ch);

// close the connection, release resources used
curl_close($ch);

// do anything you want with your response
var_dump($response);

2 Answers2

3

The -h command refers the header.

Try below code,

// Generated by curl-to-PHP: http://incarnate.github.io/curl-to-php/
$ch = curl_init();

curl_setopt($ch, CURLOPT_URL, 'https://urlofapp.com/API/GetTransaction');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, "{ 'CustomerID':'12345','EndDate':'2018-12-31','StartDate':'2018-01-01'}");
curl_setopt($ch, CURLOPT_POST, 1);

$headers = array();
$headers[] = 'Apikey: My:ApI;key;';
$headers[] = 'Content-Type: application/json';
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);

$result = curl_exec($ch);
if (curl_errno($ch)) {
    echo 'Error:' . curl_error($ch);
}
curl_close ($ch);

I used below to convert the curl command to PHP script,

https://incarnate.github.io/curl-to-php/

Hope it would be useful.

Praneeth Nidarshan
  • 1,704
  • 15
  • 21
  • 1
    To provide some context on -H "Content-Type:.../json". The reason Praneeth put "application/json" as this content type is because you are passing json encoded data to this API (your POST data). If you were to pass XML encoded data you would want to set this to "Content-Type: application/xml". This helps the API know how to parse your data. – Blane Townsend Jan 19 '19 at 06:13
1

Dealing with curl directly usually ends up being a pain. There are a number of libraries that can help making calls like that much simpler.

Here are a few:

Joel Beckham
  • 18,254
  • 3
  • 35
  • 58