Loader.io - PHP, curl and json - php

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

Related

where to add API Key to the Curl in 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.

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;

Post the data with header in curl not working in php?

I'm trying to create the box app users using PHP. The curl for create user as follows, and it is working on terminal
curl https://api.box.com/2.0/users \
-H "Authorization: Bearer <Access token>" \
-d '{"name": "New User", "is_platform_access_only": true}' \
-X POST
Same thing I have tried with php But it is giving the following error
{"type":"error","status":400,"code":"invalid_request_parameters","help_url":"http:\/\/developers.box.com\/docs\/#errors","message":"Invalid input parameters in request","request_id":"6688622675982fb5339a37"}
The following one I have tried
$developer_token = "TOKEN" ;
$access_token_url = "https://api.box.com/2.0/users";
$ch = curl_init();
curl_setopt($ch,CURLOPT_URL, $access_token_url);
//Adding Parameters
curl_setopt($ch, CURLOPT_POSTFIELDS, array(
'name'=>'NEW USER',
'is_platform_access_only'=>'true',
));
//Adding Header
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Authorization: Bearer '.$developer_token
));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$response1 = curl_exec($ch);
If I remove the Post parameters, and run with only headers it is give the result of users. But with post it is throws error.
I have rise the same question in Perl tag with Perl code. There I got answer by user #melpomene.
We should encode the data as JSON. It is working,
Then the final code is
$data = array(name=>SOMENAME,is_platform_access_only=>true);
$data = json_encode($data);
$header = array("Authorization: Bearer <TOKEN>");
$ch = curl_init("https://api.box.com/2.0/users/");
curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch,CURLOPT_POSTFIELDS,$data);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$response1 = curl_exec($ch);
curl_close($ch);

Calling Watson API from PHP code

I am trying to call Natural Language Understanding Watson API from my PHP code using curl. I have successfully tried curl from terminal. It gives some result on executing this command:
curl -u "my_username":"my_password" "https://gateway.watsonplatform.net/natural-language-understanding/api/v1/analyze?version=2017-02-27&text=I%20still%20have%20a%20dream.&features=sentiment,keywords"
However when I try to use curl in php using this code:
<?php
$url = "https://gateway.watsonplatform.net/natural-language-understanding/api/v1/analyze?version=2017-02-27&text=I%20still%20have%20a%20dream%2C%20a%20dream%20deeply%20rooted%20in%20the%20American%20dream%20%E2%80%93%20one%20day%20this%20nation%20will%20rise%20up%20and%20live%20up%20to%20its%20creed%2C%20%22We%20hold%20these%20truths%20to%20be%20self%20evident%3A%20that%20all%20men%20are%20created%20equal.&features=sentiment,keywords";
$post_args = array(
'version' => '2017-02-27',
'url' => 'https://davidwalsh.name/curl-post',
'features' => 'sentiment,keywords'
);
$headers = array(
'Content-Type:application/json'
);
$ch = curl_init();
curl_setopt($ch, CURLOPT_USERPWD, "my_username:my_password");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
//curl_setopt($curl, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
//curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
//curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($post_args));
$result = curl_exec($ch);
if ($result === FALSE) {
die('Send Error: ' . curl_error($ch));
}
curl_close($ch);
echo $result;
?>
I get this result:
{
"error": "unsupported media type",
"code": 415
}
What should be done?
I can't believe I was stuck here due to a blank space.
Replacing this:
$headers = array(
'Content-Type:application/json'
);
with
$headers = array(
'Content-Type: application/json'
);
worked. Note the blank space between : and application/json.

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