How to query Github GraphQL API from PHP script?

community-help

#1

Hi,

I am querying Github API for some internal monitoring interface. I came across the new GraphQL implementation in the documentation and decided to use it for my interface.

Accordingly, I prepared this small PHP script to test the GraphQL API which I have pasted below. I always get ‘Problems parsing JSON’ error whenever I run the script. Am I doing something wrong here? Can somebody help me highlight any mistake I am doing?

//GRAPHQL request
$postData =<<<‘JSON’
{
“query”: query{
user(login:“tojochacko”) {
name
}
}
}
JSON;

$json = json_encode($postData);

$chObj = curl_init();
curl_setopt($chObj, CURLOPT_URL, ‘https://api.github.com/graphql’);
curl_setopt($chObj, CURLOPT_RETURNTRANSFER, true);
curl_setopt($chObj, CURLOPT_CUSTOMREQUEST, ‘POST’);
curl_setopt($chObj, CURLOPT_POSTFIELDS, $json);
curl_setopt($chObj, CURLOPT_HEADER, true);
curl_setopt($chObj, CURLOPT_VERBOSE, true);
curl_setopt($chObj, CURLOPT_HTTPHEADER,
array(
‘User-Agent: PHP Script’,
‘Content-Type: application/json’,
'Authorization: bearer '.GITHUB_TOKEN
)
);

$response = curl_exec($chObj);
echo $response;


#2

I found the fix myself. The JSON that I was passing to the Github API was not in correct expected format. Github unfortunately does not have correct documentation on the expected format. I had to read the GraphQL spec and dig through some php client library codes to understand the format. Below is the correct code to query Github GraphQL API. Hope this helps anyone who goes through the same issue.

//GRAPHQL request
$query = <<<'JSON'
query{
   user(login:“tojochacko”) {
       name
   }
}
JSON;
$variables = '';

$json = json_encode(['query' => $query, 'variables' => $variables]);

$chObj = curl_init();
curl_setopt($chObj, CURLOPT_URL, ‘https://api.github.com/graphql’);
curl_setopt($chObj, CURLOPT_RETURNTRANSFER, true);    
curl_setopt($chObj, CURLOPT_CUSTOMREQUEST, 'POST');
curl_setopt($chObj, CURLOPT_HEADER, true);
curl_setopt($chObj, CURLOPT_VERBOSE, true);
curl_setopt($chObj, CURLOPT_POSTFIELDS, $json);
curl_setopt($chObj, CURLOPT_HTTPHEADER,
     array(
            'User-Agent: PHP Script',
            'Content-Type: application/json;charset=utf-8',
            'Authorization: bearer '.GITHUB_TOKEN 
        )
    ); 

$response = curl_exec($chObj);
echo $response;

#3

Would you mind linking to the page that has the incorrect format that you observed? That would help us get the documentation fixed.


#4

@kytrinyx I was referring to this link. If this link contains a few code examples on how to make a request from various languages(PHP, Ruby, Python, Java etc) at least, it would be very helpful for other developers to understand.


#5

Ah, I think I understand. Are you saying that the documentation is missing, not that it is (there but) incorrect?

I completely agree that it would be helpful to have documentation in several common languages.