Skip to content

Instantly share code, notes, and snippets.

@jgauthi
Forked from dunglas/example.php
Created July 26, 2022 12:49
Show Gist options
  • Save jgauthi/f7977a76c23a2d4a1f2c37b31fa49932 to your computer and use it in GitHub Desktop.
Save jgauthi/f7977a76c23a2d4a1f2c37b31fa49932 to your computer and use it in GitHub Desktop.
A GraphQL client using the Symfony HttpClient component
<?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
// composer require symfony/http-client
require __DIR__.'/vendor/autoload.php';
use Symfony\Component\HttpClient\HttpClient;
use Symfony\Component\HttpClient\HttpOptions;
function graphql_query(string $endpoint, string $query, array $variables = [], ?string $token = null): array
{
$options = (new HttpOptions())
->setJson(['query' => $query, 'variables' => $variables])
->setHeaders([
'Content-Type' => 'application/json',
'User-Agent' => 'Symfony GraphQL client'
])
;
if (null !== $token) {
$options->setAuthBearer($token);
}
return HttpClient::create()
->request('POST', $endpoint, $options->toArray())
->toArray()
;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment