I'm trying to use cURL POST to get some data from an endpoint:
Here is what the documentation says to authenticate and get data:
"...uses a combination of OAuth2 grant_types and JWT tokens
To authorize, use this code:
curl -X POST \
'http://api.example.com/v1/api/auth/login?grant_type=client_id' \
-H 'Authorization: Basic cHVibGljX2tleTpwddl2YXRJX2xleQzd'
"
Based on the info above, I built this code for the request:
$handle = curl_init('http://api.example.com/v1/api/auth/login?
grant_type=client_id');
$header = array();
$header[] = 'Content-Type: application/json';
$header[] = 'Authorization: Basic DdJfd1Bxx2NxMkYwNjzzdl9mejJZIFKVQlBc';
curl_setopt($handle, CURLOPT_POST, true);
curl_setopt($handle, CURLOPT_POSTFIELDS, $header);
$resp = curl_exec($handle);
var_dump($resp);
When I execute the code, it runs in an endless loop and eventually times out.
Is the format of the code correct or is it a problem with the authorization key I provided? The key is a Base64 representation.
Thanks!
UPDATE: I've tried the following also:
$header[] = 'Content-Type: application/json';
$header[] = 'Authorization: Basic adfsidfosfosfodsofs';
$content = "grant_type=client_id";
$curl = curl_init();
curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_HTTPHEADER, $header);
curl_setopt($curl, CURLOPT_POSTFIELDS, $content);
maybe try this:
$handle = curl_init('http://api.example.com/v1/api/auth/login?grant_type=client_id');
$header = array();
$header[] = 'Content-Type: application/json';
$header[] = 'Authorization: Basic DdJfd1Bxx2NxMkYwNjzzdl9mejJZIFKVQlBc';
curl_setopt($handle, CURLOPT_HTTPHEADER, $header);
$resp = curl_exec($handle);
var_dump(curl_error($handle));
Related
I'm trying to get some code of mine to work. but I keep getting the following error. Any thoughts on what's going wrong here? I think I have all the quoatations escaped correctly
{"errors":[{"message":"json body could not be decoded: invalid
character 'L' after object key:value pair"}],"data":null}
I know my query is correct as I can run it in the graphQL playground and get the data.
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://xxxxxxxxxxxx.com/api/v4/endpoint');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, "{\"query\":\"{ search(q: \"LM123\") { results { part { mpn manufacturer { name }}}}\"}");
curl_setopt($ch, CURLOPT_ENCODING, 'gzip, deflate');
$headers = array();
$headers[] = 'Accept-Encoding: gzip, deflate';
$headers[] = 'Content-Type: application/json';
$headers[] = 'Accept: application/json';
$headers[] = 'Connection: keep-alive';
$headers[] = 'Dnt: 1';
$headers[] = 'Origin: https://xxxxxxxxxxxxx.com';
$headers[] = 'Token: xxxxxxxxxxxxxxxxxxxxxxxx';
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
$result = curl_exec($ch);
if (curl_errno($ch)) {
echo 'Error:' . curl_error($ch);
}
curl_close($ch);
echo $result;
If I run a simple query that doesn't search for a term it works perfectly. Like:
curl_setopt($ch, CURLOPT_POSTFIELDS, "{\"query\":\"{ categories { name }}\"}");
You have a problem with using double quotes here \"LM123\". When your JSON is parsing, the parser expects, that this \" ends your value and then you will have , \"other_key\": \"...\" in your JSON, but you have LM123... instead.
You can try something like this:
curl_setopt($ch, CURLOPT_POSTFIELDS, '{"query":"{ search(q: \"LM123\") { results { part { mpn manufacturer { name }}}}"}');
In an attempt to replicate the following cURL:
curl -X POST --header 'Content-Type: multipart/form-data' --header 'Accept: application/json' --header 'Authorization: Bearer XXXXXXXXXX-XXXXXXXXXXX' 'https://XXXXXXXXX.XXX.com/api/v3/assets/76c860cd184ae4adfa105d46135c9b27.json' -F 'name=fileupdate99.pdf' -F 'description=curlviaphp'
The purpose of the call is to update the two fields (name & description) at this specific end point.
I used https://incarnate.github.io/curl-to-php/ to get the bulk of the conversion. However, I appear to be stuck on passing the data.
From what I can tell, it looks like the -F flag is expected (also used to upload files) and I can't make a swap to -d (I tried running call in the command line and -d wasn't accepted).
<?php
$subdomain = "XXXXXXXX";
$name = "fileupdate4.pdf";
$description = "curlviaphp";
$auth = "XXXXXXXXXX-XXXXXXXXXXX";
$asset = "76c860cd184ae4adfa105d46135c9b27";
$ch = curl_init();
$curlurl = "https://" . $subdomain . ".XXX.com/api/v3/assets/" . $asset . ".json' ";
$variables = array(
"name" => $name,
"description" => $description,
);
curl_setopt($ch, CURLOPT_URL, $curlurl);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $variables);
curl_setopt($ch, CURLOPT_POST, 1);
$headers = array();
$headers[] = "Content-Type: multipart/form-data";
$headers[] = "Accept: application/json";
$headers[] = "Authorization: Bearer " . $auth;
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
$result = curl_exec($ch);
if (curl_errno($ch)) {
echo "Error:" . curl_error($ch);
}
curl_close($ch);
echo $result;
?>
When I execute, the code runs and I get a blank page (no return and no change on the receiving end).
What am I missing?
I am trying to call an api called Wave I have used cURL before but never with GRAPHQL queries. I am wondering what is wrong with the below when using cURL. I get an error Bad Request Below is an exmple of my code.
This is what the API cURL is
curl -X POST "https://reef.waveapps.com/graphql/public" \
-H "Authorization: Bearer <ACCESS_TOKEN>" \
-H "Content-Type: application/json" \
-d '{ "query": "query { user { id defaultEmail } }" }'
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://reef.waveapps.com/graphql/public');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 0);
curl_setopt($ch, CURLOPT_POSTFIELDS, '{ "query": "query { user { id defaultEmail } }');
curl_setopt($ch, CURLOPT_POST, 1);
$headers = array();
$headers[] = 'Content-Type: application/json';
$headers[] = 'Authorization: Bearer 1212121';
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
$result = curl_exec($ch);
var_dump($result);
if (curl_errno($ch)) {
echo 'Error:' . curl_error($ch);
}
Any help would be helpful.
For those wanting to query a GraphQL service WITHOUT a third party library, I basically took Brian's code and tested against a GraphCMS service I had already written Node.js code for. So I knew the url, authorization token, and query all worked.
<?php
$endpoint = "https://api-euwest.graphcms.com/v1/[[your id number here]]/master";//this is provided by graphcms
$authToken = "[[your auth token]]";//this is provided by graphcms
$qry = '{"query":"query {products(where:{status:PUBLISHED}){title,img,description,costPrice,sellPrice,quantity,sku,categories {name},brand {name}}}"}';
$headers = array();
$headers[] = 'Content-Type: application/json';
$headers[] = 'Authorization: Bearer '.$authToken;
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $endpoint);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 0);
curl_setopt($ch, CURLOPT_POSTFIELDS, $qry);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
$result = curl_exec($ch);
var_dump($result);
if (curl_errno($ch)) {
echo 'Error:' . curl_error($ch);
}
?>
All worked fine.
The auth token is a big long character string provided by GraphCMS and only needs to be passed in the header. So no real tricky authentication process - as long as you have the token.
I can recommend using https://github.com/softonic/graphql-client, it has worked great for us.
A way easier way to go about doing this is by using an API platform. I often use Postman, the platform have the functionality to give you the PHP cURL code for a GraphQL request in the GraphQl tools part of the application.
You can create your own client passing whatever middleware you'd like:
$clientWithMiddleware = \MyGuzzleClientWithMiddlware::build();
$graphQLClient = new \Softonic\GraphQL\Client(
$clientWithMiddleware,
new \Softonic\GraphQL\ResponseBuilder()
);
For an example how to build a Guzzle client with middleware you can check this out:
https://github.com/softonic/guzzle-oauth2-middleware/blob/master/src/ClientBuilder.php
If there is no authentication
You can use file_get_contents instead of curl
$url = http://myapi/graphql?query={me{name}}
$html =file_get_contents($url);
echo $html;
use json in query paramter for graphql;
Bit late but I made this code
$endpoint = "https://gql.waveapps.com/graphql/public";
$authToken = ""; //Your Bearer code
$qry = '{"query": "query {user {id firstName lastName defaultEmail createdAt modifiedAt}}"}';
$headers = array();
$headers[] = 'Content-Type: application/json';
$headers[] = 'Authorization: Bearer '.$authToken;
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $endpoint);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $qry);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
$result = curl_exec($ch);
var_dump($result);
if (curl_errno($ch)) {
echo 'Error:' . curl_error($ch);
}
$headers = array();
$headers[] = 'Authorization: hmac ' .$websiteKey.':'.$hmac .':'.$nonce . ':'.$time;
$curl = curl_init();
curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($curl,CURLOPT_POSTFIELDS, $post);
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
$result = curl_exec($curl);
var_dump($result);
curl_close($curl);
I have the code above, i want to post to an api. Somehow its not working. I tried using a var_dump on the result variable. The result is:
string(117) "{"Message":"The request entity's media type 'application/x-www-form-urlencoded' is not supported for this resource."}"
Any idea why its not posting to the api?
The value of the $post=
{"AmountDebit":10,"Currency":"EUR","Invoice":"testinvoice 123","Services":{"ServiceList":[{"Action":"Pay","Name":"ideal","Parameters":[{"Name":"issuer","Value":"ABNANL2A"}]}]}}
Headers:
$headers[] = 'Authorization: hmac ' .$websiteKey.':'.$hmac .':'.$nonce . ':'.$time;
If you don't specify a Content-Type header when making a POST call with Curl, it will add one in with the value application/x-www-form-urlencoded.
From the Everything Curl book:
POSTing with curl's -d option will make it include a default header that looks like Content-Type: application/x-www-form-urlencoded. That's what your typical browser will use for a plain POST.
Many receivers of POST data don't care about or check the Content-Type header.
If that header is not good enough for you, you should, of course, replace that and instead provide the correct one.
Judging by your request, I imagine you'll need to add the following to the top of your script:
$headers[] = 'Content-Type: application/json';
But depending on the exact API you're posting to, this might need to be different.
Have You installed curl before using it.
If it not install try google for Curl installation
and use my curl function for post request its 100% working-
public function curlPostJson() {
$headers = [];
$headers[] = 'Content-Type: application/json';
$headers[] = 'Content-Length: ' .strlen(json_encode($paramdata));
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($paramdata));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER,$headers);
$server_output = curl_exec($ch);
curl_close($ch);
return json_decode($server_output);
}
I want use php curl to interact with coinbase api. Simple API calls that does not require data to be passed are successful. What I want to do is create address.
CLI curl works. The command line curl command sample is below:
curl https://api.coinbase.com/v2/accounts/82de7fcd-db72-5085-8ceb-bee19303080b/addresses \
-X POST \
-H 'Content-Type: application/json' \
-H 'Authorization: Bearer abd90df5f27a7b170cd775abf89d632b350b7c1c9d53e08b340cd9832ce52c2c' \
-d '{"name": "New receive address"}'
}
My php code excerpt
$apiurl = "https://api.coinbase.com";
$secret = "coinbase api secret";
$method = "POST";
$requestPath = "/v2/accounts/actualAccountID/addresses";
$body = "";
$url = $apiurl.$requestPath;
$data["name"] = "curl smj6 ary";
$body=json_encode($data);
$string = $timestamp.$method.$requestPath.$body;
$sig = hash_hmac('sha256', $string, $secret);
$ch = curl_init();
// Disable SSL verification
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
// Will return the response, if false it print the response
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
// Set the url
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_VERBOSE, true);
if($method == "POST"){
curl_setopt($ch, CURLOPT_POST, TRUE);
curl_setopt($ch, CURLOPT_POSTFIELDS, $body);
}
$headers = [
"CB-ACCESS-KEY: xxx",
"CB-ACCESS-SIGN:$sig",
"CB-ACCESS-TIMESTAMP: $timestamp",
"CB-VERSION: 2018-03-21",
"accept: application/json;charset=utf-8"
];
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
// Execute
$result_json = curl_exec($ch);
It returns
{"errors":[{"id":"authentication_error","message":"invalid signature"}]}
Since it works with listing user. I guess th error occurs the way iam passing post data to curl.
Similar Questions that I found on SO but none solves my issue. Please help!
Invalid Signature Coinbase
CoinBase "invalid signature" PHP Buy API Request
How to declare CURL body for CoinBase API call
Api key authentication for coinbase
UPDATE:
$apiurl = "https://api.coinbase.com/v2/";
$requestPath = "accounts/$accountid/addresses";
returns same error
There are sites that convert the command line cURL syntax to PHP, like https://incarnate.github.io/curl-to-php/
I just pasted your command and:
// Generated by curl-to-PHP: http://incarnate.github.io/curl-to-php/
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "https://api.coinbase.com/v2/accounts/82de7fcd-db72-5085-8ceb-bee19303080b/addresses");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, "{\"name\": \"New receive address\"}");
curl_setopt($ch, CURLOPT_POST, 1);
$headers = array();
$headers[] = "Content-Type: application/json";
$headers[] = "Authorization: Bearer abd90df5f27a7b170cd775abf89d632b350b7c1c9d53e08b340cd9832ce52c2c";
$headers[] = "CB-ACCESS-KEY: <your api key>";
$headers[] = "CB-ACCESS-SIGN: <the user generated message signature>";
$headers[] = "CB-ACCESS-TIMESTAMP: <a timestamp for your request>";
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
$result = curl_exec($ch);
if (curl_errno($ch)) {
echo 'Error:' . curl_error($ch);
}
curl_close ($ch);