Skip to content

Instantly share code, notes, and snippets.

@dunglas
Last active March 15, 2024 18:04
Show Gist options
  • Star 13 You must be signed in to star a gist
  • Fork 4 You must be signed in to fork a gist
  • Save dunglas/f2e756725b1b842331dc8cdd38b4cc75 to your computer and use it in GitHub Desktop.
Save dunglas/f2e756725b1b842331dc8cdd38b4cc75 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()
;
}
@kovinet
Copy link

kovinet commented Jun 15, 2021

I am getting Variable "$user" is not defined error...

@rccc
Copy link

rccc commented Jul 22, 2021

Hello,

Is there a way to send multiple queries :

https://hasura.io/docs/latest/graphql/core/databases/postgres/mutations/multiple-mutations.html# ?

Many thanks in advance.

@jerhome
Copy link

jerhome commented Sep 3, 2021

<?php
// src/Service/GraphqlClient.php
namespace App\Service;

use Symfony\Contracts\HttpClient\HttpClientInterface;
use Symfony\Component\HttpClient\HttpOptions;
use Symfony\Component\DependencyInjection\ContainerInterface;

class GraphqlClient
{
    private HttpClientInterface $client;
    private ContainerInterface $container;

    public function __construct(HttpClientInterface $client, ContainerInterface $container)
    {
        $this->client = $client;
        $this->container = $container;
    }

    public function query(
        string $query,
        array $variables = [],
        ?string $token = null,
        string $endpoint = null
    ): string|array
    {
        if (is_null($endpoint)) {
            $endpoint = $this->container->getParameter('app.graphql_url');
        }

        $options = (new HttpOptions())
            ->setJson(['query' => $query, 'variables' => $variables])
            ->setHeaders([
                'Content-Type' => 'application/json',
                'User-Agent' => 'Symfony GraphQL client'
            ])
        ;

        if (null !== $token) {
            $options->setAuthBearer($token);
        }
        
        $response = $this->client
            ->request('POST', $endpoint, $options->toArray())
            ->toArray();

        return array_key_exists('errors', $response)
            ? $response['errors'][0]['message']
            : $response;
    }
}

The requests of this example service are profiled in Symfony 5.3 debug toolbar.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment