nackolysis nackolysis - 1 month ago 5
JSON Question

Posting data to sever using PHP and cURL

I have the following data to be posted to server via my API.

Request Body:
{
"nutrients": {
"protein": "beans",
"fats": "oil",
"carbohdrate": "starch"

}
}


Each time I run the script, am getting the following error below

{"errors":[{"status":"400","code":"031","title":"payload not parseable","detail":"Invalid formatting of the request payload."},{"status":"400","code":"026","title":"payload missing","detail":"No payload describing the resource object included in the request."}]}


It seems that it's because am not adding the variable "nutrients" in the data array to be posted.

Can someone help me out. Below is my effort so far. Thanks

<?php
$url = "https://myapi_site.com/server/";
$data = array(
'protein' => 'beans',
'fats' => 'oil',
'carbohdrate' => 'starch'
);
$curl = curl_init($url);
curl_setopt($curl, CURLOPT_HEADER, false);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_HTTPHEADER,
array("Content-type: application/json"));
curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_POSTFIELDS, $data);

$json_response = curl_exec($curl);
$status = curl_getinfo($curl, CURLINFO_HTTP_CODE);
curl_close($curl);
$response = json_decode($json_response, true);
?>

Answer

You are posting a PHP array which hasn't been converted to JSON... you want to post the JSON itself. Here is how you can post the JSON string.

curl_setopt($curl, CURLOPT_POSTFIELDS, json_encode($data));

You can use json_encode to encode the PHP array to JSON:

http://php.net/json_encode

Define your $data variable like so:

$data = array(
  'nutrients' => array(
        'protein' => 'beans',
        'fats' => 'oil',
        'carbohdrate'  => 'starch',
   ),
); 

You can echo $data variable to see that it contains the right JSON data:

echo $data;