Search code examples
phpgraphqlphp-curl

How to implement graphQL with PHP curl


Am using Insomnia to test my graphQL queries, and for this one all works fine. However, moving over to PHP am not winning, and my code looks like this using curl:

$data = array ("query" => "{
    viewer {
         zones(filter: { zoneTag: '" . $zone . "' }) {
            httpRequestsAdaptive(
                filter: {
                    datetime_geq: '2023-05-10T08:00:00Z'
                    datetime_lt: '2023-05-10T08:05:00Z'
                }
                limit: 10000
                orderBy: [
                    datetime_DESC
                ]
            ) {
                device: clientDeviceType
                clientIP: clientIP
            }
            }
        }
    }
");

$data = http_build_query($data);
$headers = [];
$headers[] = 'Content-Type: application/json';
$headers[] = "Authorization: Bearer $token";

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "https://api.cloudflare.com/client/v4/graphql");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);

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

curl_close($ch);
$response = $result_plans;

I get the following message when I run the script:

failed to recognize JSON request: 'invalid character 'q' looking for beginning of value'

How can I run this query using PHP curl?


Solution

  • I don't have access to the CF API right now, but I can show you how to do it generally against another one. The trick is to build the query as a string and use the native GraphQL variable syntax for the dynamic portions.

    I think this code pretty much speaks for itself, but if you have any questions just let me know.

    One thing added is that I almost always want the headers, too, so I added the code from here for that. See that for some potential caveats however.

    $query = <<<'GRAPHQL'
    query Film($filmId: ID) {
      film(filmID: $filmId) {
        episodeID
        openingCrawl
      }
    }
    GRAPHQL;
    
    $variables = ['filmId' => "2"];
    
    $payload = json_encode(['query' => $query, 'variables' => $variables], JSON_THROW_ON_ERROR);
    
    $headers = ['Content-Type: application/json'];
    
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, "https://swapi-graphql.netlify.app/.netlify/functions/index");
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $payload);
    curl_setopt($ch, CURLOPT_POST, 1);
    curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
    curl_setopt($ch, CURLOPT_HEADER, 1);
    
    $response = curl_exec($ch);
    
    $header_size = curl_getinfo($ch, CURLINFO_HEADER_SIZE);
    $header = substr($response, 0, $header_size);
    $body = substr($response, $header_size);
    
    echo $body;