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:
![](https://i0.wp.com/sakeoflearning.com/wp-content/uploads/2021/04/Screenshot-2021-04-17-at-8.59.31-PM.png?resize=750%2C412&ssl=1)
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:
![](https://i0.wp.com/sakeoflearning.com/wp-content/uploads/2021/04/Screenshot-2021-04-17-at-9.05.25-PM.png?resize=750%2C184&ssl=1)