I'm trying to learn how I can interface with a json api.
In the documentation they give me a curl example:
If I run this as a command it works fine, gives me my data in a json format.
I thought I was on the right track with this: PHP + curl, HTTP POST sample code?
but apparently not as I can't figure out what to do with the -H portion of this command.
curl -H "APIKey:My:ApI;key;" -H "Content-Type:.../json" "https://urlofapp.com/API/GetTransaction" -d "{ 'CustomerID':'12345','EndDate':'2018-12-31','StartDate':'2018-01-01'}" > test.json
Trying to get the result into an array that I can sum and show a total of their orders for the year.
From the link I provided above I was trying to start with this:
// set post fields
$post = [
'CustomerID' => 12345,
'StartDate' => 2018-01-01,
'EndDate' => 2018-12-31,
];
$ch = curl_init('https://urlofapp.com/API/GetTransaction');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post);
// execute!
$response = curl_exec($ch);
// close the connection, release resources used
curl_close($ch);
// do anything you want with your response
var_dump($response);
The -h command refers the header.
Try below code,
// Generated by curl-to-PHP: http://incarnate.github.io/curl-to-php/
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://urlofapp.com/API/GetTransaction');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, "{ 'CustomerID':'12345','EndDate':'2018-12-31','StartDate':'2018-01-01'}");
curl_setopt($ch, CURLOPT_POST, 1);
$headers = array();
$headers[] = 'Apikey: My:ApI;key;';
$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);
I used below to convert the curl command to PHP script,
https://incarnate.github.io/curl-to-php/
Hope it would be useful.
Dealing with curl directly usually ends up being a pain. There are a number of libraries that can help making calls like that much simpler.
Here are a few:
Simple and straighforward: http://requests.ryanmccue.info/
Has everything you could ever possibly want: https://github.com/guzzle/guzzle
Related
$data = [];
$data['ToBinding'] = json_encode(array("binding_type"=>"sms", "address"=>"+19991112222"));
$data['Body'] ="test";
$ch = curl_init("https://notify.twilio.com/v1/Services/ISXXXXXXXXXXXXXXXXXX/Notifications");
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($data));
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_USERPWD,'XXXXXXXXXXXXXXXXXXX:XXXXXXXXXXXXXXXXXXX');
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/x-www-form-urlencoded'));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$resultData = curl_exec($ch);
This code was copied from another post. I am able to get this to work just fine, using real numbers of course. However I cannot populate $data['ToBinding'] with multiple numbers, which is the whole purpose of using Twilio Notify. I have tried many different combinations of code and it blows up, most of the time with "Cannot convert incoming parameters to notification object: Parameter 'ToBinding' is invalid".
I was able to get it to at least execute without errors using this code (real numbers of course):
$data['ToBinding'] = json_encode(array("binding_type"=>"sms", "address"=>"+19991112222","binding_type"=>"sms", "address"=>"+19993334444"));
But it only sends to the first number in the array. Any help on how to populate the array to send to multiple numbers (or maybe another way using cURL) will be appreciated.
==== FULL CODE ====
$query = array("ToBinding" => array(
json_encode(array("binding_type"=>"sms", "address"=>"+19991112222")),
json_encode(array("binding_type"=>"sms", "address"=>"+19993334444"))
));
$data = http_build_query($query);
$data = preg_replace('/%5B[0-9]+%5D/simU', '', $data);
echo $data;
$data['Body'] ="Notify cURL API test";
$ch = curl_init("https://notify.twilio.com/v1/Services/<NOTIFY ID HERE >/Notifications");
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($data));
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_USERPWD,'<ACCT ID HERE>:<TOKEN HERE >');
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/x-www-form-urlencoded'));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$resultData = curl_exec($ch);
===== FINAL WORKING CODE =====
$data['Body'] ="Notify cURL API test";
$data['ToBinding'] = array(
json_encode(array("binding_type"=>"sms","address"=>"+19191112222")),
json_encode(array("binding_type"=>"sms","address"=>"+19193334444"))
);
$query = http_build_query($data);
$string = preg_replace('/%5B(?:[0-9]|[1-9][0-9]+)%5D=/', '=', $query);
$ch = curl_init("https://notify.twilio.com/v1/Services/ISxxxxxxxxxx/Notifications");
curl_setopt($ch, CURLOPT_POSTFIELDS, $string);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_USERPWD,'ACxxxxxxxxxx:xxxxxxxxxxxxxxxxx');
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/x-www-form-urlencoded'));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$resultData = curl_exec($ch);
echo "curl Response=".$resultData."<br>";
$responseHttp = curl_getinfo($ch, CURLINFO_HTTP_CODE);
Twilio developer evangelist here.
The ToBinding parameter is an array of binding objects. Notify implements support for that by decoding multiple ToBinding parameters from the request.
The curl example from the Notify documentation looks like this:
curl -X POST https://notify.twilio.com/v1/Services/ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Notifications \
--data-urlencode 'ToBinding={"binding_type":"sms", "address":"+15555555555"}' \
--data-urlencode 'ToBinding={"binding_type":"facebook-messenger", "address":"123456789123"}' \
-d 'Body=Hello Bob' \
-u 'your_account_sid:your_auth_token'
As you can see, there are two ToBinding parameters included in the data.
As far as I can tell, PHP doesn't support building the body like that. http_build_query appears to be useful, but builds arrays of data using name[index] form, which we don't want. You can strip the [index] out though, with something like the following:
$query = array("ToBinding" => array(
json_encode(array("binding_type"=>"sms", "address"=>"+19991112222")),
json_encode(array("binding_type"=>"sms", "address"=>"+19993334444"))
));
$data = http_build_query($query);
$data = preg_replace('/%5B[0-9]+%5D/simU', '', $data);
echo $data;
# => ToBinding=%7B%22binding_type%22%3A%22sms%22%2C%22address%22%3A%22%2B19991112222%22%7D&ToBinding=%7B%22binding_type%22%3A%22sms%22%2C%22address%22%3A%22%2B19993334444%22%7D
Let me know if this helps at all.
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);
I want the following cURL command to be converted to PHP
curl -X PUT -H 'Content-Type: application/json' -d '{"on":true,"bri":255,"sat":255,"hue":20000}' http://MYSITE:PORT/api/HASH/lights/1/state
I did the following but it is just timing out.
$data_json = '{"on":true,"bri":255,"sat":255,"hue":20000}';
$url = "http://MYSITE:PORT/api/HASH/lights/1/state";
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'PUT');
curl_setopt($ch, CURLOPT_POSTFIELDS,$data_json);
$response = curl_exec($ch);
echo $response;
curl_close($ch);
you can set the curl timeout like so
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT ,0);
curl_setopt($ch, CURLOPT_TIMEOUT, 400); //timeout in seconds
you might want to increase the php timeout in php.ini too
I would try to debug the Curl request using the technique mentioned here, this should give you more information about what Curl is doing.
Also if you are willing to use a library I would recommend using Guzzle, it's well documented and makes these types of operation less painful in my experience.
<?php
use GuzzleHttp\Client;
require 'vendor/autoload.php';
$url = "http://jsonplaceholder.typicode.com/posts";
$client = new Client();
$body['title'] = "json guzzle post";
$body['body'] = "carlton";
$body['userId'] = "109109101";
$res = $client->post($url, [ 'body' => json_encode($body) ]);
$code = $res->getStatusCode();
$result = $res->json();
var_dump($code);
var_dump($result);
I'm having trouble with a REST POST request after the API to which I'm posting published the final release of their API. It was working without incident, and I've been told that with the new version the server is more strict regarding the type being 'application/json'. The following cli curl command works swimmingly:
cat json.txt|curl -v -k -u user:password -F 'exchangeInstance=#-;type=application/json' https://my.url.here
However, I need to execute this in code. Using the php curl libraries I've got a simple test script up that looks like this:
$post = array(
"exchangeInstance" => $json_string,
"type" => "application/json",
);
$url = 'myurlhere';
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
curl_setopt($ch, CURLOPT_USERPWD, "user:pass");
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post);
$result = curl_exec($ch);
$info = curl_getinfo($ch);
var_dump($post);
var_dump($result);
echo $result;
var_dump($info);
As I read the documentation, the Content-type in the header should automatically be set to 'multipart/form' if I pass an array as CURLOPT_POSTFIELDS, and then I'm setting the type for the element pass to 'application/json' in the array.
However, the api has had no POST requests from me. And I'm getting an error from them that clearly indicates that they are receiving a GET request. How can this possibly be? What am I missing?
curl -F !== -d
$post = array(
"exchangeInstance" => sprintf('#%s;type=application/json', $json_string),
);
I'm trying to use Neo4js Traverser via the HTTP API.
If I use it via curl on the command line it works fine, but when I try to use it via curl through PHP I get an error all the time.
This is curl command:
curl -H Accept:application/json -H Content-Type:application/json -X POST -d '{"order":"depth first"}' http://localhost:7474/db/data/node/5/traverse/node
And this is my PHP Code:
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "http://localhost:7474/db/data/node/5/traverse/node");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Accept:application/json',
'Content-Type:application/json'
));
curl_setopt($ch, CURLOPT_POSTFIELDS, '"{"order": "depth first"}"');
$output = curl_exec($ch);
echo '<pre>';
var_dump(curl_getinfo($ch));
var_dump($output);
curl_close($ch);
This is the error I get:
HTTP ERROR 500
Problem accessing
/db/data/node/5/traverse/node. Reason:
java.lang.String cannot be cast to java.util.Map
Any Ideas?
Looks like you have quotes before the JSON string:
curl_setopt($ch, CURLOPT_POSTFIELDS, '"{"order": "depth first"}"');
Might want to try this:
curl_setopt($ch, CURLOPT_POSTFIELDS, '{"order": "depth first"}');
EDIT: Although better yet, I'd use json_encode with an associative array to ensure proper escaping if necessary:
$json_data = array("order" => "depth first");
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($json_data));