Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
A minimalist GraphQL client for PHP
<?php
$query = <<<'GRAPHQL'
query GetUser($user: String!) {
user (login: $user) {
name
email
repositoriesContributedTo {
totalCount
}
}
}
GRAPHQL;
graphql_query('https://api.github.com/graphql', $query, ['user' => 'dunglas'], 'my-oauth-token');
<?php
function graphql_query(string $endpoint, string $query, array $variables = [], ?string $token = null): array
{
$headers = ['Content-Type: application/json', 'User-Agent: Dunglas\'s minimal GraphQL client'];
if (null !== $token) {
$headers[] = "Authorization: bearer $token";
}
if (false === $data = @file_get_contents($endpoint, false, stream_context_create([
'http' => [
'method' => 'POST',
'header' => $headers,
'content' => json_encode(['query' => $query, 'variables' => $variables]),
]
]))) {
$error = error_get_last();
throw new \ErrorException($error['message'], $error['type']);
}
return json_decode($data, true);
}
@rameshdahiya

This comment has been minimized.

Copy link

@rameshdahiya rameshdahiya commented Oct 21, 2019

Nice work

@mavrosxristoforos

This comment has been minimized.

Copy link

@mavrosxristoforos mavrosxristoforos commented Dec 12, 2019

Excellent! Exactly what I was looking for!

@luisrock

This comment has been minimized.

Copy link

@luisrock luisrock commented Jan 16, 2020

Thanks for that

@roshanlabh

This comment has been minimized.

Copy link

@roshanlabh roshanlabh commented Jul 6, 2020

Query/Mutation is working perfectly fine by using graphql_query.
But how can we use GraphQL subscription? Any idea?

@prokons

This comment has been minimized.

Copy link

@prokons prokons commented Nov 3, 2020

Great, thank you!

@chrisvoo

This comment has been minimized.

Copy link

@chrisvoo chrisvoo commented Dec 5, 2020

Query/Mutation is working perfectly fine by using graphql_query.
But how can we use GraphQL subscription? Any idea?

You need WebSocket support, like this: https://siler.leocavalcante.dev/graphql#graphql-subscriptions

@dunglas

This comment has been minimized.

Copy link
Owner Author

@dunglas dunglas commented Dec 6, 2020

Regarding subscriptions you can also use Mercure as done in API Platform.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.