How to query Github GraphQL API from PHP script? - php

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

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;

Related

How to access API in R with API documentation in PHP?

I am a complete beginner when it comes to APIs. I would like to access the API of https://foundico.com, I even received a public and a private key, however, the documentation is quite sparse and only provides the code in PHP (can be found here https://foundico.com/developers/)
The code is as follows:
$privateKey = 'privateKey';
$publicKey = 'publicKey';
$parameters = array('status' => 'upcoming');
$postData = json_encode($parameters);
$accessKey = base64_encode(hash_hmac('sha256', $postData, $privateKey, true));
$ch = curl_init('https://foundico.com/api/v1/icos/');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'POST');
curl_setopt($ch, CURLOPT_POSTFIELDS, $postData);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_HTTPHEADER, [
'Content-Type: application/json',
'X-Foundico-Public-Key: '.$publicKey,
'X-Foundico-Access-Key: '.$accessKey
]);
$response = curl_exec($ch);
curl_close($ch);
echo $response;
I would like to access the API in R so that I can directly use the data in my code. How would I translate this into R?

Cloudflare API issue put request ("code":9020,"message":"Invalid DNS record type")

I am having issue while using cloudflare APIv4. Trying to update a dns record and not sure why am I receiving following error:
           
{"success":false,"errors":[{"code":1004,"message":"DNS Validation Error","error_chain":[{"code":9020,"message":"Invalid DNS record type"}]}],"messages":[],"result":null}
Here is the PHP function:          
function updateCloudflareDNS($zone_id,$dns_id, $updatedata){
$updatedata = '[{"name":"**.****.com"},{"type":"A"},{"ttl":"1"},{"content":"8.8.8.8"},{"proxied":"true"}]';
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "https://api.cloudflare.com/client/v4/zones/".$zone_id."/dns_records/".$dns_id);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-Type: application/json; charset=utf-8',
'X-Auth-Email: **********',
'X-Auth-Key: ***********'
));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($ch, CURLOPT_HEADER, FALSE);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "PUT");
curl_setopt($ch, CURLOPT_POSTFIELDS, $updatedata);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
$response = curl_exec($ch);
curl_close($ch);
return $response;
}
Also, I am putting record type "A" correctly as mentioned on the Cloudflare API documentation
Could someone help me out with this issue?
Thanks
You're sending a payload of:
[{"name":"**.****.com"},{"type":"A"},{"ttl":"1"},{"content":"8.8.8.8"},{"proxied":"true"}]
Here's what the API expects:
{"type":"A", "name":"example.com", "content":"127.0.0.1", "ttl":120, "priority":10,"proxied":false}
And this is how you properly construct JSON in PHP:
$POST = json_encode(array(
"type" => "A",
"name" => "...",
...
));

Web API - HTTP Post Request That Includes Header & Body

I just got API access for one of the website on the internet, and as a new api developer i got into troubles understanding how should i start and with what, So hope you guys guide me . They don't have Documents or tutorials Yet.
If anyone can give me a small example on how to send Http post request that includes Header and body? As what they are mentioning in the API page:
All requests must include an Authorization header with siteid and
apikey (with a colon in between) and it must match with the siteid and
apikey in the request body
In the body the Parameter content type will be application/json. They have also provided a Base URL.
The response will be as application/json.
What should i do? is the request can be sent using AJAX? or there is PHP code for this? i have been reading a lot about this subject but none enter my head. Really hope you guys help me out .
Please let me know if you need more information so i can provide it to you.
EDIT : Problem solved and just posting the small editing that i did to the code that was provided in the correct answer that i marked .
Thanks to Mr. Anonymous for the big help that he gave me . His answer was so so close, all what i had to do is just edit his code a little bit and everything went good .
I will list the finial code down bellow in case any other developer had this issue or wanted to do an HTTP request .
First what i did is that i stored the data that i wanted to send over the HTTP in a file with a JSON type :
{
"criteria": {
"landmarkId": 181,
"checkInDate": "2018-02-25",
"checkOutDate": "2018-02-30"
}
}
Second thing as what guys can see what Mr. Anonymous posted .
<?php
header('Access-Control-Allow-Origin: *');
$SiteID= 'My Site Id';
$ApiId= 'My Api Id';
$url = 'Base URL';
// Here i will get the data that i created in Json data type
$data = file_get_contents("data.json");
// I guess this step in not required cause the data are already in JSON but i had to do it for myself
$arrayData = json_decode($data, true);
$ch = curl_init();
//curl_setopt($ch, CURLOPT_HEADER, true);
curl_setopt($ch, CURLOPT_URL,$url);
curl_setopt($ch, CURLOPT_POST, TRUE);
curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
curl_setopt($ch, CURLOPT_USERPWD, "$SiteID:$ApiID");
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-Type: application/json',
'Connection: Keep-Alive',
'Authorization: $SiteID:$ApiId'
));
curl_setopt($ch, CURLOPT_POSTFIELDS,json_encode($arrayData));
$result = curl_exec($ch);
curl_close($ch);
print_r($result);
?>
Try this
$site_id = 'your_site_id';
$api_key = 'your_api_key';
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'http://api-connect-url');
curl_setopt($ch, CURLOPT_POST, 1);
############ Only one of the statement as per condition ###########
//if they have asked for post
curl_setopt($ch, CURLOPT_POSTFIELDS, "$site_id=$api_key" );
//or if they have asked for raw post
curl_setopt($ch, CURLOPT_POSTFIELDS, "$site_id:$api_key" );
####################################################################
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, ["$site_id:$api_key"] );
$api_response = curl_exec ($ch);
curl_close ($ch);
As asker need to send JSON Payload to API
$site_id = 'your_site_id';
$api_key = 'your_api_key';
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'http://api-connect-url');
curl_setopt($ch, CURLOPT_POST, 1);
//send json payload
curl_setopt($ch, CURLOPT_POSTFIELDS, "{
"criteria":{
"cityId":9395,
"area":{
"id":0,
"cityId":0
},
"landmarkId":0,
"checkInDate":"2017-09-02",
"checkOutDate":"2017-09-03",
"additional":{
"language":"en-us",
"sortBy":"PriceAsc",
"maxResult":10,
"discountOnly":false,
"minimumStarRating":0,
"minimumReviewScore":0,
"dailyRate":{
"minimum":1,
"maximum":10000
},
"occupancy":{
"numberOfAdult":2,
"numberOfChildren":1
},
"currency":"USD"
}
}
}"
);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, ["$site_id:$api_key", 'Content-Type:application/json'] );
$api_response = curl_exec ($ch);
curl_close ($ch);

PHP I want to send the post data by Codeigniter, How to make the post request?

I am developing the web server using other service by CodeIgniter.
So I am going to send the data to the service using api calling.
But I have a issue to make the request.
This is the data what I want to send.
$datastr = 'proc_name=customer_upd&params={
"proc_info":
{
"proc_division":"U"
},
"data":[{
"table_name":"Customer",
"rows":[ {
"itemId" : "12231551",
"lastName" : "ads",
"firstName" : "fds"
} ]
}]
}'
I made my code for this.
$curl = curl_init('https://webapi.ooo.com/access/');
curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($curl, CURLOPT_HTTPHEADER, array('Content-Type: application/x-www-form-urlencoded;charset=UTF-8'));
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_POSTFIELDS, $datastr);
curl_exec($curl);
But this is not work.
I am tested by postman, but it works well.
I think there is a issue to make the post request.
Please help me.
Thank you.
I think you are sending query string, instead, send only data in the key-value pair to the web service you are consuming. Check in which form web service is accepting the data. First, check web service from postman
Here is an example,
$data = array("key_1" =>value_1 , "key_2" =>"value_2" , "key_3" =>"value_3" , "key_4" =>"value_4" , "key_5" =>"value_5" );
function api($url,$api,$data)
{
$ch = curl_init();
$webservicelink = $url.$api;
curl_setopt($ch, CURLOPT_URL, $webservicelink);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-Type: application/json'));
$result = curl_exec($ch);
return json_decode($result, true);
}

How to add Companies in bullhorn using Rest Api?

I am developing php application for submitting my Employers data into bullhorn using rest api.
I have bullhorn account and client id and client secret
I read documentation and also see question in
[Insert candidate with categories + BullHorn
one of stack overflow but not find any solution
Can any one help me how to use api for php??
Thanks in advance
Below Code I used to Create an company in BullHorn CRM using RESTAPI
Here Use Company as ClientCorporation object.
$url = 'https://rest2.bullhornstaffing.com/rest-services/rggmp/entity/ClientCorporation?BhRestToken=09c4822e-04e7-40d8-9570-addc5c447aa7';
$params =array("name"=> "Maha","fax"=>231312313 );
$post_params = json_encode($params);
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_CUSTOMREQUEST,$method); // for Create -> "PUT" & Update ->"POST" //
curl_setopt($curl, CURLOPT_HTTPHEADER, array('Content-Type: application/json', 'Content-Length: '.strlen($post_params));
curl_setopt($curl, CURLOPT_POSTFIELDS, $post_params);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
$result = curl_exec($curl);
$response = json_decode($result, true);
print_r($response);
curl_close($curl);
Output :
(
[changedEntityType] => ClientCorporation
[changedEntityId] => 304
[changeType] => INSERT
)

Categories