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);
}
@luisrock
Copy link

Thanks for that

@roshanlabh
Copy link

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

@prokons
Copy link

prokons commented Nov 3, 2020

Great, thank you!

@chrisvoo
Copy link

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
Copy link
Author

dunglas commented Dec 6, 2020

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

@tlcko
Copy link

tlcko commented Feb 19, 2021

i think there is a typo in the line with bearer authorization it should be like this:

$headers[] = "Authorization: Bearer $token";

at least it didn't work for me with "bearer" with all lowercase
otherwise works great thank you very much for this!

@walkthelot
Copy link

Maybe someone can help. I am brand new to GraphQL and having a really hard time formatting the parameters of this function to get a result. Can someone help me figure out how to properly pass the following GraphQL query?

query {
dealerWindowSticker(vin: "1N4AL11DX6N393946", dealerId: "1000")
}

Any help is GREATLY appreciated!!!

@rccc
Copy link

rccc commented Jul 28, 2021

Hello,

When using Hasura server, these line breaks : 'content' => json_encode(['query' => $query, 'variables' => $variables]).

@walkthelot
Copy link

I got it figured out, at least for my unique use case.

' =================
' ASP Code Sample:
' =================

strPayload = "{""query"":""query {" & _
	"dealerWindowSticker(" & _
	"vin: \" & """" & Vehicle_VIN & "\"", " & _
	"dealerId: \" & """" & Vehicle_DealerID & "\""" & _
")}""}"
								
Set XMLHTTP = Server.CreateObject("MSXML2.ServerXMLHTTP")
XMLHTTP.Open "POST", posturl, False
XMLHTTP.setRequestHeader "Content-Type", "application/json"
XMLHTTP.setRequestHeader "Authorization", "Bearer " & authenticate_access_token
XMLHTTP.send strPayload
sticker_response = XMLHTTP.ResponseText
// =================
// PHP Code Sample:
// =================

$headers = ['Content-Type: application/json', 'User-Agent: Your Client User Agent Optional'];
$headers[] = "Authorization: Bearer $authenticate_access_token";
$json = '{"query":"query {\n dealerWindowSticker(vin: \"' . $param_vin . '\", dealerId: \"' . $param_dealer_id . '\") \n}"}';
$chObj = curl_init();
curl_setopt($chObj, CURLOPT_URL, $sticker_api_url);
curl_setopt($chObj, CURLOPT_FRESH_CONNECT, TRUE);
curl_setopt($chObj, CURLOPT_RETURNTRANSFER, true);    
curl_setopt($chObj, CURLOPT_CUSTOMREQUEST, 'POST');
curl_setopt($chObj, CURLOPT_POSTFIELDS, $json);
curl_setopt($chObj, CURLOPT_HTTPHEADER,
     array(
            'User-Agent: Your Client User Agent Optional',
            'Content-Type: application/json',
            'Authorization: Bearer '.$authenticate_access_token 
        )
    ); 
$sticker_response = curl_exec($chObj);

@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