Reading Time: < 1 minute

The aim of this article is to experiment with what I have learned and use it for my own reference. Following this article, I tried to consume the GraphQL API. I used Guzzle, PHP HTTP client library to request API.

Query

To fetch the data we need to use query as root type.

$query = <<<GQL
  query {
    users {
      name
      email
      created_at
    }
  }
GQL;

$graphqlEndpoint = 'http://localhost:8001/graphql';
$client = new \GuzzleHttp\Client();

$response = $client->request('POST', $graphqlEndpoint, [
  'headers' => [
    'Content-Type' => 'application/json',
    // include any auth tokens here
  ],
  'json' => [
    'query' => $query
  ]
]);

$json = $response->getBody()->getContents();
$body = json_decode($json);
$data = $body->data;

print_r($data);exit;

Output:

Mutation

For mutation, we need to update the query like below and the rest part of the guzzle code will be the same as the above code snippet.

$query = <<<GQL
	mutation {
		createUser(name: "Tanmaya Biswal", email: "tanmayabiswal@mailinator.com", password: "secret") {
			id
			name
		}
	}
GQL;

Output: