Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to query Github GraphQL API from PHP script?

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 Github 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?

<?php
    //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;
?>
like image 821
Tojo Chacko Avatar asked Dec 08 '22 17:12

Tojo Chacko


1 Answers

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;
like image 124
Tojo Chacko Avatar answered Dec 10 '22 23:12

Tojo Chacko