Search code examples
phpjsoncurlgraphqlphp-curl

Why is my GraphQL Query using curlopt_postfields returning a json error?


I'm trying to get some code of mine to work. but I keep getting the following error. Any thoughts on what's going wrong here? I think I have all the quoatations escaped correctly

{"errors":[{"message":"json body could not be decoded: invalid character 'L' after object key:value pair"}],"data":null}

I know my query is correct as I can run it in the graphQL playground and get the data.

$ch = curl_init();

curl_setopt($ch, CURLOPT_URL, 'https://xxxxxxxxxxxx.com/api/v4/endpoint');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, "{\"query\":\"{ search(q: \"LM123\") { results { part { mpn manufacturer { name }}}}\"}");
curl_setopt($ch, CURLOPT_ENCODING, 'gzip, deflate');

$headers = array();
$headers[] = 'Accept-Encoding: gzip, deflate';
$headers[] = 'Content-Type: application/json';
$headers[] = 'Accept: application/json';
$headers[] = 'Connection: keep-alive';
$headers[] = 'Dnt: 1';
$headers[] = 'Origin: https://xxxxxxxxxxxxx.com';
$headers[] = 'Token: xxxxxxxxxxxxxxxxxxxxxxxx';
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);

$result = curl_exec($ch);
if (curl_errno($ch)) {
    echo 'Error:' . curl_error($ch);
}
curl_close($ch);
echo $result; 

If I run a simple query that doesn't search for a term it works perfectly. Like:

curl_setopt($ch, CURLOPT_POSTFIELDS, "{\"query\":\"{ categories { name }}\"}");

Solution

  • You have a problem with using double quotes here \"LM123\". When your JSON is parsing, the parser expects, that this \" ends your value and then you will have , \"other_key\": \"...\" in your JSON, but you have LM123... instead.

    You can try something like this:

    curl_setopt($ch, CURLOPT_POSTFIELDS, '{"query":"{ search(q: \"LM123\") { results { part { mpn manufacturer { name }}}}"}');