1

How to call the following Curl API request using php ?

curl "https://api.example.com/v2/test" \
  -X "POST" \
  -H "App-Id: APP_ID" -H "App-Key: APP_KEY" \
  -H "Content-Type: application/json" -d '{
    "sex": "male",
    "age": 30,
    "evidence": [
      {"id": "s_1193", "choice_id": "present"},
      {"id": "s_488", "choice_id": "present"},
      {"id": "s_418", "choice_id": "present"}
    ]
  }'

I could only make it till:

$ch = curl_init();
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
    'app_id: '. APP_ID,
    'app_key: '. APP_KEY
));

It is over my head being a newbie. Help requested from experts..

Pamela
  • 684
  • 1
  • 7
  • 21
  • This Q/A May be helpful to use: https://stackoverflow.com/questions/11079135/how-to-post-json-data-with-php-curl ... if you google "send json data with php curl", you will find a lot of examples and tuts. – IncredibleHat Dec 10 '17 at 15:29
  • @IncredibleHat Thank you. I have difficulty in adding the sex": "male", "age": 30, "evidence": [ {"id": "s_1193", "choice_id": "present"}, {"id": "s_488", "choice_id": "present"}, {"id": "s_418", "choice_id": "present"} part... – Pamela Dec 10 '17 at 16:12

1 Answers1

2

I tested this, and it works as you should need:

<?php

define('APP_ID', 'o235oi23h5');
define('APP_KEY', 'o2i3h5oi2h3o5h2o3h5');

$json = '{
    "sex": "male",
    "age": 30,
    "evidence": [
        {"id": "s_1193", "choice_id": "present"},
        {"id": "s_488", "choice_id": "present"},
        {"id": "s_418", "choice_id": "present"}
    ]
}';

//$ch = curl_init('http://localhost.script-library/stacko2.php');
$ch = curl_init('https://api.example.com/v2/test');
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");                                                                     
curl_setopt($ch, CURLOPT_POSTFIELDS, $json);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE); 
curl_setopt($ch, CURLOPT_HTTPHEADER, [
    'Content-Type: application/json',                                                                                
    'Content-Length: ' . strlen($json),
    'app_id: '. APP_ID,
    'app_key: '. APP_KEY
]);                                                                                                                   

$result = curl_exec($ch);

echo '<pre>';
var_dump( $result );
echo '</pre>';
Brian Gottier
  • 4,522
  • 3
  • 21
  • 37