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.

@tlcko

This comment has been minimized.

Copy link

@tlcko 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

This comment has been minimized.

Copy link

@walkthelot walkthelot commented May 24, 2021

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

This comment has been minimized.

Copy link

@rccc rccc commented Jul 28, 2021

Hello,

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

@walkthelot

This comment has been minimized.

Copy link

@walkthelot walkthelot commented Jul 29, 2021

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);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment