I'm trying to submit a POST request with JSON data to an api endpoint. The endpoint requires a querystring passing the api credentials, but also requires the JSON data to be POSTed.
When I try to do this with PHP cURL as shown below, the querystring is apparently removed - thus the api is rejecting the request due to missing api key.
I can do this easily with Postman when testing access to the api endpoint.
How can I make the cURL request include both the querystring AND the JSON POST body?
Example code:
// $data is previously defined as an array of parameters and values.
$url = "https://api.endpoint.url?api_key=1234567890";
$ch = curl_init();
$json = json_encode($data);
curl_setopt($ch,CURLOPT_URL, $url);
curl_setopt($ch,CURLOPT_POST, true);
curl_setopt($ch,CURLOPT_POSTFIELDS, $json);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, [
'Content-Type: application/json',
'Content-Length: ' . strlen($json)
]
//execute post
$result = curl_exec($ch);
//close connection
curl_close($ch);
You are doing almost right.
Sometimes you need to relax SSL verification.
Otherwise, update php ca bundle:
https://docs.bolt.cm/3.7/howto/curl-ca-certificates
Add the following:
$headers = array(
"Content-type: application/json;charset=UTF-8",
"Accept-Encoding: gzip,deflate",
"Content-length: ".strlen($json),
);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_TIMEOUT, 300);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $json);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_ENCODING, "identity, deflate, gzip");
curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_ANY);
curl_setopt($ch, CURLINFO_HEADER_OUT, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
$result = curl_exec($ch);
$httpcode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
Sometimes you need to change encoding too:
$result = utf8_decode($result);
And check the returning data.
I am using this API
https://market.mashape.com/pareshchouhan/trivia
for making widget in my site but when i am calling this API through CURL it is returning following error:
Any solution for that?
Here my code :
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "https://pareshchouhan-trivia-v1.p.mashape.com/v1/getAllQuizQuestions");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, FALSE);
curl_setopt($ch,CURLOPT_HEADER,FALSE);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
"X-Mashape-Key" => "MY_KEY",
"Accept" => "application/json"
));
$data = curl_exec($ch);
curl_close($ch);
echo $data;
when i execute this PHP file, it is returning "Missing Mashape application key" in return data.
http://i.prntscr.com/5f98b1e8965f42eda29875543b052ec5.png
You are specifying you curl headers incorrectly. Look at the CURLOPT_HTTPHEADER option in the docs at http://php.net/manual/en/function.curl-setopt.php. Your code should look like this:
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "https://pareshchouhan-trivia-v1.p.mashape.com/v1/getAllQuizQuestions");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, false);
curl_setopt($ch, CURLOPT_HEADER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
"X-Mashape-Key: MY_KEY",
"Accept: application/json"
));
$data = curl_exec($ch);
curl_close($ch);
I'm using cURL to get all email from user via Google API. Following https://developers.google.com/admin-sdk/email-audit/#retrieving_all_email_monitors_of_a_source_user.
According this tutorial, the server return '201 Created' status code to successful. But, my result return '200 OK' code.
Here is code Authorization
$data = array(
'accountType' => 'HOSTED_OR_GOOGLE',
'Email' => 'myEmail',
'Passwd' => 'myPassword',
'source'=>'PHP-cUrl-Example',
'service'=>'apps');
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "https://www.google.com/accounts/ClientLogin");
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
$response = curl_exec($ch);
And here is code to Retrieving all email monitors of a source user
preg_match("/Auth=([a-z0-9_-]+)/i", $response, $matches);
$auth = $matches[1];
$header = array('Content-Type: application/atom+xml; charset=utf-8',
'Authorization: GoogleLogin auth='.trim($auth),
);
$url_email ="https://apps-apis.google.com/a/feeds/compliance/audit/mail/monitor/mydomain/username";
curl_setopt($ch, CURLOPT_URL, $url_email);
curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, FALSE);
curl_setopt($ch, CURLOPT_HEADER, false);
$response = curl_exec($ch);
$response = simplexml_load_string($response);
curl_close($ch);
print_r($response);
Help me pls ?
The API allows you to request the status of a single export request with a URL of:
https://apps-apis.google.com/a/feeds/compliance/audit/mail/export/{domain name}/{source user name}/{mailbox requestId}
or of all requests across the domain with a request of:
https://apps-apis.google.com/a/feeds/compliance/audit/mail/export/{domain name}?fromDate={fromDate}
there is no operation to retrieve the status of all requests for a given user like you are trying to do.
I suggest you confirm you've successfully created an audit request by using GAM to create the request. GAM will show you the request ID on success. Then you can try getting the results of the single request with your code.
I've looked around a bit and can't find a solution that solves my problem. I'm getting the following error: "The requested URL returned error: 413."
I'm posting some information via curl and PHP to a URL via HTTPS. I'm told that I have to pass the "Content-Length" along with my request since the destination is https and not http.
Here's the code I'm using:
$user = '11111111111111111';
$books = array(111);
$data = array("action" => "books-shared", "userID" => $user, "bookIDs" => $books);
$data_string = array('json'=>json_encode($data));
$target_url = 'https://www.test.com/test.php'; // fake URL of course
$ch = curl_init();
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
curl_setopt($ch, CURLOPT_URL,$target_url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_FAILONERROR, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-Type: application/json',
'Content-Length: ' . strlen($data_string))
);
$api = curl_exec($ch);
My strlen($data_string) command is returning a value of 5, which is much less than the actual length of the $data_string, which is much longer. I assume this is the problem unless someone thinks it might be being caused by something else.
Here's what I ended up with:
$user = '11111111111111111';
$books = array(111);
$data = array("action" => "books-shared", "userID" => $user, "bookIDs" => $books);
$data_string = array('json'=>json_encode($data));
$target_url = 'https://www.test.com/test.php'; // fake URL of course
$ch = curl_init();
if (!$ch) {
die("Couldn't initialize a cURL handle");
}
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_VERBOSE, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
curl_setopt($ch, CURLOPT_URL, $target_url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_FAILONERROR, true);
$api = curl_exec($ch);
No SSL or size errors and it seems to work fine.
I have the following php code
curl_setopt($ch, CURLOPT_URL, $URL);
curl_setopt($ch, CURLOPT_USERAGENT, $this->_agent);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_AUTOREFERER, true);
curl_setopt($ch, CURLOPT_HEADER, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, $this->_headers);
curl_setopt($ch, CURLOPT_ENCODING , "gzip");
curl_setopt($ch, CURLOPT_VERBOSE, false);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_TIMEOUT, 120);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_COOKIEFILE, $this->_cookie_file_path);
curl_setopt($ch, CURLOPT_COOKIEJAR, $this->_cookie_file_path);
curl_setopt($ch, CURLOPT_POSTFIELDS, '{"folderId":"1","parameters":{"amount":3,"ascending":false,"offset":0,"sort":"date"}}');
curl_setopt($ch, CURLOPT_POST, 1);
But I don't understand why is not working . The API that I'm posting the JSON to says that the parameters were not received . Is there anything wrong in my code ? I think the whole trick is on the JSON parameters... I'm not sure how to send them as I couldn't see any "nave->value" pair with the http analyzer as it usually appears in simple forms ... just that JSON code without any "name".
You can try as follows.
Basically if we have a array of data then it should be json encoded using php json_encode. And you should also add content-type in header which can be defined in curl as curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));
$data = array("country"=>"US","states"=>array("MHASASAS"=>"MH","XYZABABA"=>"XYZ"));
$postdata = json_encode($data);
$ch = curl_init($URL);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $postdata);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));
$result = curl_exec($ch);
curl_close($ch);
you can use this and replace with
curl_setopt($ch, CURLOPT_POSTFIELDS, '{"folderId":"1","parameters":{"amount":3,"ascending":false,"offset":0,"sort":"date"}}');
use this
$Parameters = array(
'MerchantCode' => $MerchantCode,
'PriceValue' => $amount,
'ReturnUrl' => $callback,
'InvoiceNumber' => $resnum,
);
curl_setopt($curl, CURLOPT_POSTFIELDS, json_encode($Parameters));
If:you use post method,you should know that:
CURLOPT_POST TRUE to do a regular HTTP POST. This POST is the normal application/x-www-form-urlencoded kind, most commonly used by HTML forms.
#see http://php.net/manual/en/function.curl-setopt.php
So:you can do like this:
$ar_form = array('name'=>'PHPJungle','age'=>66,'gender'=>'male');
$poststr = http_build_query($ar_form ); # important
$options[CURLOPT_HTTPGET] = false;
$options[CURLOPT_POST] = true;
$options[CURLOPT_POSTFIELDS] = $poststr ; //default type:application/x-www-from-urlencoded
curl_setopt_array ( $ch, $options );
# #todo your other codes
This is my class I have used for a long time.The class is based on PHP cURL.
It supports GET/POST,HTTP/HTTPS.
#see https://github.com/phpjungle/iHttp/
You can post a json data with curl like so:
Using Command Prompt:
curl -X POST -H "Content-Type: application/json" -d '{"folderId":"1","parameters":{"amount":3,"ascending":false,"offset":0,"sort":"date"}}' $url
Using PHP:
$data = array("folderId"=>"1","parameters"=>array("amount"=>3,"ascending"=>false,"offset"=>0,"sort"=>"date"));
$postdata = json_encode($data);
OR
$postdata = '{"folderId":"1","parameters":{"amount":3,"ascending":false,"offset":0,"sort":"date"}}';
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $postdata);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));
$result = curl_exec($ch);
curl_close($ch);
print_r($result);
You haven't set the content type, so the post data is being sent as form data. Try setting the content type to application/json.
If that doesn't work, try wrapping the json string with an array.
$link = "http://test.domain/myquery";
$json = '{"folderId":"1","parameters":{"amount":3,"ascending":false,"offset":0,"sort":"date"}}';
$postdata = json_decode($json);
echo openurl($link, $postdata);
This works as json decode converts a json string into array.
function openurl($url, $postvars = "") {
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $postvars);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_TIMEOUT, '3');
$content = trim(curl_exec($ch));
curl_close($ch);
return $content;
}
if your API endpoint using body for send request using json data may be you can use Guzzle the doc is here doc.
use GuzzleHttp\Client;
$client = new Client();
$request = $this->client->post($url,array(
'content-type' => 'application/json'
),array());
$request->setBody($json_data);
$response = $request->send();
return $response;
hope this work.
You can do it make by steps:
$data = array(
'folderId'=>"1","parameters"=>array(
"amount"=>"3","ascending"=>false,"offset"=>0,"sort"=>"date"
)
);
$data_string = http_build_query($data);
$ch = curl_init();
curl_setopt($ch,CURLOPT_URL, $url);
curl_setopt($ch,CURLOPT_POST, count($data));
curl_setopt($ch,CURLOPT_POSTFIELDS, $data_string);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$result = curl_exec($ch);
curl_close($ch);
$result = json_decode($result,true);
I don't know if you need the header. I think that by default it is already application/x-www-form-urlencode
If it doesn't work, try changing the $data values in array. Think it helps. :)
I'm not sure, that this is the solution but this works for me when posting json, change the json from
'{"folderId":"1","parameters":{"amount":3,"ascending":false,"offset":0,"sort":"date"}}'
to
"{'folderId':'1','parameters':{'amount':3,'ascending':false,'offset':0,'sort':'date'}}"
The only change i made was the double quotes are now on the outside, that works for me but I'm obviously posting to a different server
Only other help I could offer is to download a network debugging tool such as Fiddler or Charles proxy and monitor the requests sent/received, it could be a case that something else is wrong in your code.
Hope i helped :)
first of all
please check the curl http status code
$http_code= curl_get_info($exec_res,CURL_HTTP_CODE);
then modify this request header set with post header API server add a recorder to log those request info.