Skip to content

Instantly share code, notes, and snippets.

@dunglas
Created April 19, 2018 06:25
Show Gist options
  • Save dunglas/05d901cb7560d2667d999875322e690a to your computer and use it in GitHub Desktop.
Save dunglas/05d901cb7560d2667d999875322e690a to your computer and use it in GitHub Desktop.
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);
}
@bhaktvanti
Copy link

bhaktvanti commented Mar 8, 2023

Somehow, I get this errors. Any help is GREATLY appreciated.

( ! ) Fatal error: Uncaught ErrorException: file_get_contents(xxxxx): Failed to open stream: HTTP request failed! HTTP/1.1 400 Bad Request in C:\wamp6433\www\research-portal\importAuthor.php on line 19

( ! ) ErrorException: file_get_contents(xxxxx): Failed to open stream: HTTP request failed! HTTP/1.1 400 Bad Request in C:\wamp6433\www\research-portal\importAuthor.php on line 19

This is my query that works just fine under the API Playground but not via code.

$query = <<<'GRAPHQL'
mutation { 
  createAuthor ( data: { username:"test", name:"test",email:"test@test.com", role:"Editor", client:"" } )  
  {  
    username
    name
    email
    role
    client   
  }
}
GRAPHQL;
graphql_query($endpoint, $query, array(), $accessToken);

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