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..

2
  • This Q/A May be helpful to use: stackoverflow.com/questions/11079135/… ... if you google "send json data with php curl", you will find a lot of examples and tuts. Commented Dec 10, 2017 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... Commented Dec 10, 2017 at 16:12

1 Answer 1

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

1 Comment

Thank you so much. You saved my day :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.