Search code examples
phpjsoncurlpostrequest

php CURL Error: Request payload is not JSON


I am trying to interact with an Api using php's CURL library

this is my code:

$fields = array(
    'aaaaa' => 'aaaaa', 
    'bbbbb' => 'bbbbb', 
    'ccccc' => 'ccccc', 
    'ddddd' => 'ddddd'
);

$fields_json = json_encode($fields);

$ch = curl_init();

curl_setopt($ch, CURLOPT_URL, $this->api_url);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $fields_json);

// var_dump($fields_json);

curl_setopt($ch, CURLOPT_HTTPHEADER, array(
    "Content-Type" => "application/json"
));

curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); 

$result = json_decode(curl_exec($ch), true);

since the function returned NULL, I tried to var_dump the variable $result and this is what i got:

array(1) { ["message"]=> string(27) "Request payload is not JSON" }

I tried searching for solutions but every page I've seen said that this is the correct way, what am I missing?

Thank You!

(17/01/2024 11:00:00) EDIT:

I've also tried to make the same request with ThunderClient extension for VSCode, same url, same body and it works fine


Solution

  • As noted by @C3roe:

    You're passing the header in the wrong format. Quote PHP docs on curl_setopt: "CURLOPT_HTTPHEADER: An array of HTTP header fields to set, in the format array('Content-type: text/plain', 'Content-length: 100')"

    This is the code i fixed:

    curl_setopt($ch, CURLOPT_HTTPHEADER, array(
            "Content-Type: application/json"
        ));