where to add API Key to the Curl in php - php

Am trying to leverage the Anvil API for PDF.
Here is their sample request.
curl \
-X POST \
-u YOUR_API_KEY: \
-H 'Content-Type: application/json' \
-d '{ "data": { "someKey": "some data" } }' \
https://app.useanvil.com/api/v1/fill/{pdfTemplateID}.pdf > test.pdf
My problem is where to add the API KEY. I have tried adding it to the header but it throws error {"name":"AuthorizationError","message":"Not logged in."}
Here is the coding so far
$url2="https://app.useanvil.com/api/v1/fill/first.pdf";
$ch2 = curl_init();
curl_setopt($ch2,CURLOPT_URL, $url2);
$apiKey ='my api key goes here';
$post_data ='
{
"data": {
"someName": "Bobby",
"someDate": "2018-10-31",
"anAddress": {
"street1": "123 Main St",
"city": "San Francisco",
"state": "CA",
"zip": "94106"
}
}
}';
curl_setopt($ch2, CURLOPT_HTTPHEADER, array(
//'Content-Type:application/json'
'Authorization: ' . $apiKey
));
curl_setopt($ch2,CURLOPT_CUSTOMREQUEST,'POST');
curl_setopt($ch2,CURLOPT_POSTFIELDS, $post_data);
curl_setopt($ch2,CURLOPT_SSL_VERIFYPEER,0);
curl_setopt($ch2,CURLOPT_SSL_VERIFYHOST,0);
curl_setopt($ch2,CURLOPT_RETURNTRANSFER, true);
echo $response2 = curl_exec($ch2);
curl_close($ch2);

The curl command you provided has option -u, which is expecting data as username:password ,from curl man
-u/--user user:password Specify user and password to use for server authentication. If this option is used several times, the last one
will be used.
which in PHP you have to send headers like below snippet:
CURLOPT_HTTPHEADER => [
'Authorization: Basic ' . $apiKey . ':'
],
or with
curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
curl_setopt($ch, CURLOPT_USERPWD, $apiKey . ":");
related thread
Edit: from your link in comment, they are expecting raw data of your request which you can accomplish by sending it as put request:
curl_setopt($ch,CURLOPT_CUSTOMREQUEST,'PUT');
or with text/plain header

**
- ***UPDATED***
**
are you encoding the API key as "base64" ??
$YOUR_API_KEY = base64_encode("YOUR_API_KEY");
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://app.useanvil.com/api/v1/fill/XnuTZKVZg1Mljsu999od.pdf');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, "{ \"title\": \"Hello\", \"data\": [ { \"label\": \"Hello World\", \"content\": \"I like turtles\" } ] }");
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_USERPWD, $YOUR_API_KEY . ':' . '');
$headers = array();
$headers[] = 'Content-Type: application/json';
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
$result = curl_exec($ch);
if (curl_errno($ch)) {
echo 'Error:' . curl_error($ch);
}
curl_close ($ch);

Easiest way to do add api key in curl request is as follow
// Collection object
$ch = curl_init($url);
$headers = array(
"APIKEY: PUT_HERE_API_KEY",
"Content-type: text/xml;charset=\"utf-8\"",
"Accept: text/xml"
);
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_TIMEOUT, 60);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_HTTPHEADER,$headers);
curl_setopt($ch, CURLOPT_POSTFIELDS, $xmlreq);
$result = curl_exec($ch); // execute
$result;
//show response
curl_close($ch);

curl -X GET -k -H 'Content-Type: application/json' -H 'X-ApiKey : YOUR_APIKEYHERE' -i 'YOUR API RNDPOINT URL HERE'
X-ApiKey is the name of your API key.

Related

Php cURL with calling an API with GRAPHQL

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);
}

Shutter Stock API PHP Post Object formatting

I am talking to the Shutter Stock API. I am certain the problem is not SS but more the formatting of my PHP Curl post as if I send this request via terminal I get a proper response.
The Terminal curl comand is as follows:
curl "https://api.shutterstock.com/v2/images/licenses?subscription_id=$SUBSCRIPTION_ID" \
--header "Authorization: Bearer $ACCESS_TOKEN" \
--header "Content-Type: application/json" \
-X POST \
--data '{
"images": [
{ "image_id": "137111171" }
]
}
so I am playing with sending this as a PHP curl instead and here is what I have:
$url = 'https://api.shutterstock.com/v2/images/licenses?subscription_id='.$SUBSCRIPTION_ID;
$params = new Object();
$params = {
'images' : {'image_id' : '137111171'}
};
$headers = [
'Content-Type: application/json',
'Authorization: Bearer '.$ACCESS_TOKEN
];
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_POST, 2);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_decode($params));
curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_ANY);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch,CURLOPT_USERAGENT,'Butterfly');
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
$response = curl_exec($ch);
curl_close($ch);
/*$json = json_decode($response, true);
if (json_last_error()) {
echo '<span style="font-weight:bold;color:red;">Error: ' . $response . '</span>';
} else {*/
return $response;
The response form Shutter Stock is "Decode body failure" which is a custom error response. I think the problem is in the $params variable and how it is formatted. Problem is that this is a post, I suspect that on the other side SS is decoding this in a specific way. The proper curl parameter is in the bash curl above as:
--data '{
"images": [
{ "image_id": "137111171" }
]
Does anyone have any suggestions about how to properly format this particular --data value so that I can send it as a POST?
Thanks
your PHP code contains invalid syntax, also PHP has no class named Object, but you're probably looking for StdObject, but even that doesn't make much sense here.. also you're not urlencoding $SUBSCRIPTION_ID . remove the invalid syntax parts, and use json_encode, not json_decode..
curl_setopt ( $ch, CURLOPT_POSTFIELDS, json_encode ( array (
'images' => array (
array (
'image_id' => '137111171'
)
)
), JSON_OBJECT_AS_ARRAY ) );
(edit, going by the comments, the api requires applicable data to be an array instead of an object, thus i added the JSON_OBJECT_AS_ARRAY flag.)
I think you pass wrong CURLOPT_POSTFIELDS data. Try:
$url = 'https://api.shutterstock.com/v2/images/licenses?subscription_id='.$SUBSCRIPTION_ID;
$params = [
'images' => ['image_id' => '137111171']
];
$headers = [
'Content-Type: application/json',
'Authorization: Bearer '.$ACCESS_TOKEN
];
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $params);
curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_ANY);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch,CURLOPT_USERAGENT,'Butterfly');
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
$response = curl_exec($ch);
curl_close($ch);
return $response;

Loader.io - PHP, curl and json

I'm evaluating loader.io for a client and I'm having issues getting the APi to work correctly. I'm on PHP 7
http://docs.loader.io/api/v2/post/tests.html#url-options
I'm stuck on 'create test'.
The docs say:
curl -X POST -H 'loaderio-auth: API_KEY' -H 'Content-Type: application/json' --data-binary '{"test_type":"cycling", "total": 6000, "duration":60, "urls": [ {"url": "http://gonnacrushya.com"} ]}' https://api.loader.io/v2/tests
That's great! When I add my APi Key and correct URL, it runs just fine, the test is created.
Buuuut..
I want to do this in ajax via a Symfony2 app.
Here's what I've got that's returning the error:
urls param has incorrect format
function myAjaxCalledFunction() {
$test_data = '{"test_type":"cycling", "total": 10, "duration":5, "urls": [{"url": "http://www.my-configured-url.com"}] }';
return $this->doCurlRequest('tests', 'POST', $test_data);
}
public function doCurlRequest($what_call, $request = 'GET', $post_data = null)
{
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://api.loader.io/v2/' . $what_call);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('loaderio-auth: ' . $this->loader_api_key));
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $request);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1 );
curl_setopt($ch, CURLOPT_POST, 1 );
curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data );
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-type: application/json'));
$response = curl_exec($ch);
return new Response($response);
}
is there a curl_setopt() that I'm missing?
You are setting option CURLOPT_HTTPHEADER twice. That's why it is ignoring the first one. You can push both of them into the array like below example:
curl_setopt($ch, CURLOPT_HTTPHEADER,
array('loaderio-auth: ' . $this->loader_api_key,
'Content-type: application/json'));

LINE BOT API internal error (500) on post event but success on get event

I did many curl format to send message using LINE BOT API, but always get 500 error.
Here is my last post curl code
$apiCall = 'https://trialbot-api.line.me/v1/events';
$params = array();
$params['to'] = ["uf92dfc2702b46be071376c8ff81a4b56"];
$params['toChannel'] = 1383378250;
$params['eventType'] = "138311608800106203";
$params['content'] = [ "contentType" => 1,
"toType" => 1,
"text" => "the text"];
$string_data = json_encode($params)
$headers = array (
"Content-Type: application / json; charset = UTF-8",
"X-Line-ChannelID: 1476460XXX",
"X-Line-ChannelSecret: 6363d24b1e356c77189137b6362XXXXX",
"X-Line-Trusted-User-With-ACL: u54bf222a19fd3114e9eb1a3499dXXXXX"
);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $apiCall);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 20);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_POST, count($params));
curl_setopt($ch, CURLOPT_POSTFIELDS, $string_data);
$jsonData = curl_exec($ch);
curl_close($ch);
$results = json_decode($jsonData,TRUE);
And here is the result
array:2 [
"statusCode" => "500"
"statusMessage" => "internal error."
]
And this is my get code (proccess successfully)
$url = "https://trialbot-api.line.me/v1/profiles?mids=uc02643a656b777f66162e121fa697f82";
$curl = curl_init ($url) ;
curl_setopt($curl, CURLOPT_HTTPHEADER, array(
'Content-Type: application/json; charset = UTF-8',
'X-Line-ChannelID: 1476460XXX',
'X-Line-ChannelSecret: 6363d24b1e356c77189137b6362XXXXX',
'X-Line-Trusted-User-With-ACL: u54bf222a19fd3114e9eb1a3499dXXXXX')
);
curl_setopt ($curl, CURLOPT_RETURNTRANSFER, true );
$output = curl_exec ($curl) ;
curl_close($curl);
The question are :
why my code work successfully on GET event but not on POST event?
is it true that error 500 is the error from the server (LINE server) ?
any advice and answers will really help me.
thanks a lot.
You can try this curl request send messages:
curl -X POST \
-H 'Content-Type: application/json; charset=UTF-8' \
-H 'X-Line-ChannelID: 147XXXX741' \ //your channel ID
-H 'X-Line-ChannelSecret: ff9051XXXXXXb5531e3eb633b24c2e73' \ //Your channel Secret
-H 'X-Line-Trusted-User-With-ACL: uc866bXXXXXX8b4fbc3f4dd43befd66c9' \ //Your channel mid
-d '{
"to":["u004ddf56dXXXXXb2f9760e02f0a7b623"], //List of users MID
"toChannel": 1383378250, //Fixed
"eventType": "138311608800106203", //Fixed
"content":{
"contentType":1,
"toType":1,
"text":"hallo"
}
}' https://trialbot-api.line.me/v1/events

Converting Command line curl to PHP curl functions

I am unable to convert this command line curl to php:
Structure
curl -X POST https://kanbanflow.com/api/v1/tasks -H "Content-type: application/json"
-d '{ "<PROPERTY_1>": <PROPERTY_VALUE_1>, "<PROPERTY_2>": <PROPERTY_VALUE_2>, ... "<PROPERTY_N>": <PROPERTY_VALUE_N> }'
Example in api documentation
curl -X POST https://kanbanflow.com/api/v1/tasks -H "Content-type: application/json"
-d '{ "name": "Write report", "columnId": "7ca19de0403f11e282ebef81383f3229", "color": "red" }'
I can't understand what is -d here? and how to pass data in this format.
so far i reach here but its not working.
Updated Code
$data = json_encode(array('name'=>'Testing of api', 'columnId' =>"xxxxxxxxxxxxxxxxxxx",'color'=>"red"));
$token = base64_encode("apiToken:xxxxxxxxxxxxxxxxxxxxxxxxx");
$headers = array(
"Authorization: Basic " . $token,
"Content-type: application/json"
);
$url = "https://kanbanflow.com/api/v1/tasks";
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
$response = curl_exec($curl);
$status = curl_getinfo($curl, CURLINFO_HTTP_CODE);
curl_close($curl);
echo "<pre>";
print_r($response);
Suggest me where i am wrong..
Update
I want to use https://kanbanflow.com api to add task
Response: {"errors":[{"message":"Unexpected error"}]}
I got solution of my problem i was missing swimlaneId attribute. I am posting code here for future reference so it will help others.
Now sending data using object like following
$object = new stdClass();
$object->name = 'Testing Task';
$object->columnId = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxx';
$object->swimlaneId = 'xxxxxxxxxxxxxxxxxxxxxxxxxxx';
$object->color = 'green';
$url = "https://kanbanflow.com/api/v1/tasks";
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_POSTFIELDS, json_encode($object));
$response = curl_exec($curl);
Array of Json_encode is also working here
$data = json_encode(array('name'=>'Testing of api', 'columnId' =>"f648831061e111e3a41aa3dbd7a40406", 'color'=>'red', 'swimlaneId' => 'd0635fc061e711e3a41aa3dbd7a40406'));
Looks like you forgot to json encode your data
$data = json_encode(array('name'=>'Testing of api', 'columnId' =>"xxxxxxxxxxxxxxxxxxx",'color'=>"red"));

Categories