MrTechie MrTechie - 2 months ago 7
JSON Question

How to set the request body in a json format

I'm trying to send a request body in a json format to an API. The docs state the body needs to be formatted like so:

//Request body needs to the contain a JSON object in the following format:

{
"delete_list":[
"8fcd1d68c82dd39d65ef8ea9a7948bbe",
"8bca1d68c92dd39d65ef8ea9a7948bbe",
"8bca1d69c82d939d65ef8ea9a7948bbe",
"8bca1d69c82d939d65ef8ea9a7947bbe"
]
}


My attempted code seems to fail and I am not sure why. I've tried quite a few adjustments and nothing seems to work:

$del = array("delete_list" => "[8bca1d69c82d939d65ef8ea9a7947bbe]");
$j = json_encode($del);


$apiToken = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx';

$httpHeadersArray = Array();
$httpHeadersArray[] = 'Authorization: key='.$apiToken;
$httpHeadersArray[] = 'Content-Type: application/json';


//open connection
$ch = curl_init();

//set the url, number of POST vars, POST data
curl_setopt($ch, CURLOPT_URL, $curlUrl);
#curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "PUT");
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($j));
curl_setopt($ch, CURLOPT_HTTPHEADER, $httpHeadersArray);


$res = curl_exec($ch);


echo "<pre>";
print_r($res);
echo "</pre>";


My end result that I get back from the API is as follows:

{"status":"failure","message":"JSON malformed"}


Any suggestions as to what I am doing wrong with the code? It would be greatly appreciated. Thanks!

Answer

Two things:

1) You're json encoding an object with a single string but you need to encode an object with an array.

2) You're using http_build_query which will urlencode the array arguments and break the JSON structure.

Do this:

    $del = array("delete_list" => [ "8bca1d69c82d939d65ef8ea9a7947bbe" ]);
    $j = json_encode($del);


    $apiToken = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx';

    $httpHeadersArray = Array();
    $httpHeadersArray[] = 'Authorization: key='.$apiToken;
    $httpHeadersArray[] = 'Content-Type: application/json';


    //open connection
    $ch = curl_init();

    //set the url, number of POST vars, POST data
    curl_setopt($ch, CURLOPT_URL, $curlUrl);
    #curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "PUT");
    curl_setopt($ch, CURLOPT_POSTFIELDS, $j);
    curl_setopt($ch, CURLOPT_HTTPHEADER, $httpHeadersArray);


    $res = curl_exec($ch);


    echo "<pre>";
    print_r($res);
    echo "</pre>";