Php cURL with calling an API with GRAPHQL Php cURL with calling an API with GRAPHQL curl curl

Php cURL with calling an API with GRAPHQL


For those wanting to query a GraphQL service WITHOUT a third party library, I basically took Brian's code and tested against a GraphCMS service I had already written Node.js code for. So I knew the url, authorization token, and query all worked.

<?php$endpoint = "https://api-euwest.graphcms.com/v1/[[your id number here]]/master";//this is provided by graphcms$authToken = "[[your auth token]]";//this is provided by graphcms$qry = '{"query":"query {products(where:{status:PUBLISHED}){title,img,description,costPrice,sellPrice,quantity,sku,categories {name},brand {name}}}"}';$headers = array();$headers[] = 'Content-Type: application/json';$headers[] = 'Authorization: Bearer '.$authToken;$ch = curl_init();curl_setopt($ch, CURLOPT_URL, $endpoint);curl_setopt($ch, CURLOPT_RETURNTRANSFER, 0);curl_setopt($ch, CURLOPT_POSTFIELDS, $qry);curl_setopt($ch, CURLOPT_POST, 1);curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);$result = curl_exec($ch);var_dump($result);if (curl_errno($ch)) {    echo 'Error:' . curl_error($ch);}?>

All worked fine.The auth token is a big long character string provided by GraphCMS and only needs to be passed in the header. So no real tricky authentication process - as long as you have the token.


I can recommend using https://github.com/softonic/graphql-client, it has worked great for us.


You can create your own client passing whatever middleware you'd like:

$clientWithMiddleware = \MyGuzzleClientWithMiddlware::build();$graphQLClient = new \Softonic\GraphQL\Client(    $clientWithMiddleware,    new \Softonic\GraphQL\ResponseBuilder());

For an example how to build a Guzzle client with middleware you can check this out:https://github.com/softonic/guzzle-oauth2-middleware/blob/master/src/ClientBuilder.php