PHP JSON Request - php

Hi I am trying to make JSON Request to a API but I am not sure how to as I have never worked on something similar ever before. I would really appreciate if someone can help me please.
Below is the request that I need to make:
request payload:
{
"sessionId": "1234567890",
"availabilityRequest": {
"checkInDate": "29042014",
"checkOutDate": "",
"noRooms": 1,
"noNights": 1,
"userType": "leisure",
"rateType": "standard",
"roomPreference": [
{
"noAdult": 1,
"noChild": 0
}
],
"siteCode": [
"GB0758",
"GB0746",
"GB0738",
"GB0755",
"GB0742"
],
"includeDisabled": "F"
}
}
This is what I have done but I am getting error Array ( [error] => Array ( [code] => 4007 [message] => Invalid JSON POST data (unable to decode): ) )
$postData = '{
"sessionId":"1234567890",
"availabilityRequest":
{
"checkInDate": "29042014",
"checkOutDate": "",
"noRooms": 1,
"noNights": 1,
"userType": "leisure",
"rateType": "standard",
"roomPreference":
[
{ "noAdult":1, "noChild":0 }
],
"siteCode":
[
"GB0758","GB0746","GB0738","GB0755","GB0742"
],
"includeDisabled":"F"
}
}';
$ch = curl_init($url);
curl_setopt_array($ch, array(
CURLOPT_POST => TRUE,
CURLOPT_RETURNTRANSFER => TRUE,
CURLOPT_POSTFIELDS => $postData));
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
// Send the request
$response = curl_exec($ch);
// Check for errors
if($response === FALSE){
die(curl_error($ch));
}
// Decode the response
$responseData = json_decode($response, TRUE);
// Print the date from the response
print_r($responseData);
I would be really grateful is someone can help me please. Thank you

Your JSON is invalid. Validate it using a tool such as http://jsonlint.com/
You should add an other } to the end to close it. Then you will have a valid JSON.

I can't really test this because I have no URL to test it with, but you can try to set a header.
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json', 'Content-Length: ' . strlen($postData)));

Related

PATCH call returning "The entity is not a well-formed 'application/json-patch+json' document"

Today I was testing PATCH calls to an API using PHP for the first time and to this moment I have not quite figured how to make them work.
I want to add a new parameter with it's value to an already existing set of parameters, I have set CURLOPT_CUSTOMREQUEST => "PATCH" as option and "Content-Type: application/json-patch+json" as the proper header. Despite my body being an array as the error first indicated when I parsed it into JSON, now it says that the entity is still not a well-formed application/json-patch+json.
I am totally lost as to why this could be, since other examples I have seen do not differ from what I wrote.
This is the existing set of parameters:
{
"ac": "774",
"allowed_clis": [
"34774554114"
],
"cc": "34",
"cli": "34774554114",
"id": 1512,
"subscriber_id": 1512
}
What I am trying to achieve:
{
"ac": "774",
"allowed_clis": [
"34774554114"
],
"cc": "34",
"cli": "34774554114",
"id": 1512,
"e164_to_ruri": true,
"subscriber_id": 1512
}
This is my code:
$dataArray = [
'op' => 'add',
'path' => '/e164_to_ruri',
'value' => true
];
function setPreferences($dataArray, $uri, $token){
$ch= curl_init();
$options = array(
CURLOPT_RETURNTRANSFER => true,
CURLOPT_SSL_VERIFYHOST => false,
CURLOPT_SSL_VERIFYPEER => false,
CURLOPT_CUSTOMREQUEST => "PATCH",
CURLOPT_POSTFIELDS => $dataArray,
CURLOPT_URL => $uri,
CURLOPT_HTTPHEADER => array("Content-Type: application/json-patch+json", "Authorization: Basic ".$token)
);
curl_setopt_array($ch, $options);
$response = curl_exec($ch);
$http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
return $response;
}
$response = setPreferences($dataArray, $uri, $token);
$response = json_decode($response, true);
print_r($response);
And finally, the response I get:
Array
(
[message] => The entity is not a well-formed 'application/json-patch+json' document. Malformed JSON: Expected array or object at line 0, offset 0
[code] => 400
)
To my limited knoledge, $dataArray is a well-formed array. So I don't understand where is this response coming from.
Thank you so much for the help provided!
As #UlrichEckhardt pointed out, all I needed to do is turn my data into a JSON array of JSON objects:
function setPreferences($uri, $token){
$ch= curl_init();
$options = array(
CURLOPT_RETURNTRANSFER => true,
CURLOPT_SSL_VERIFYHOST => false,
CURLOPT_SSL_VERIFYPEER => false,
CURLOPT_CUSTOMREQUEST => "PATCH",
CURLOPT_POSTFIELDS => '[{"op": "add", "path": "/e164_to_ruri", "value":true}]',
CURLOPT_URL => $uri,
CURLOPT_HTTPHEADER => array("Content-Type: application/json-patch+json", "Authorization: Basic ".$token)
);
curl_setopt_array($ch, $options);
$response = curl_exec($ch);
$http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
return $response;
}
$response = setPreferences($dataArray, $uri, $token);
$response = json_decode($response, true);
print_r($response);

Unable to make CURL post request using PHP

I read some Q&As but still struggling with this one. I need to post a specific array to an API and get another array as an answer.
UPDATE
I used :
<?php
echo 'Testing cURL<br>';
// Get cURL resource
$curl = curl_init();
$data=array(array("UserId"=>"xxxx-10100","Password"=>"pass"));
$sendpostdata = json_encode( array( "postdata"=> $data ) );
echo $sendpostdata;
// Set some options - we are passing in a useragent too here
curl_setopt_array($curl, array(
CURLOPT_RETURNTRANSFER => 1,
CURLOPT_URL => 'https://cloud.servicebridge.com/api/v1/Login',
CURLOPT_HTTPHEADER => array('Accept: application/json','Content-Type: application/json'),
CURLOPT_USERAGENT => 'Codular Sample cURL Request',
CURLOPT_POST => 1,
CURLOPT_POSTFIELDS => $sendpostdata
));
// Send the request & save response to $resp
$resp = curl_exec($curl);
echo $resp;
// Close request to clear up some resources
curl_close($curl);
?>
This results in
Testing cURL
{"postdata":[{"UserId":"xxxxx-10100","Password":"pass"}]}
{ "Data": null, "Success": false, "Error": { "Message": "Invalid UserId: ", "Value": "InvalidUserId", "Code": 9001 } }
No console logs, no other messages or clues
I am trying to implement this API https://cloud.servicebridge.com/developer/index#/
to Worpdress.
The API requires a
{
"UserId": "string",
"Password": "string"
}
Can you help me out? What am I doing wrong
Really appreciate this,
Giannis
I have checked the given API and it's REQUEST Parameters to access them and I think your initial data (username and password) is not going correctly. Please use this code:-
<?php
error_reporting(E_ALL); // check all type of errors
ini_set('display_errors',1); // display those errors
// Get cURL resource
$curl = curl_init();
$sendpostdata = json_encode(array("UserId"=>"xxxx-10100","Password"=>"pass"));
// Set some options - we are passing in a useragent too here
curl_setopt_array($curl, array(
CURLOPT_RETURNTRANSFER => 1,
CURLOPT_URL => 'https://cloud.servicebridge.com/api/v1/Login',
CURLOPT_HTTPHEADER => array('Accept: application/json','Content-Type: application/json'),
CURLOPT_USERAGENT => 'Codular Sample cURL Request',
CURLOPT_POST => 1,
CURLOPT_POSTFIELDS => $sendpostdata
));
// Send the request & save response to $resp
$resp = curl_exec($curl);
echo $resp;
// Close request to clear up some resources
curl_close($curl);
?>
Note:- change UserId & Passwordvalues to your real values.Thanks
This might help you in generating proper json. Hope this will work.
use this
$data=array(array("UserId"=>"xxxxx-10100","Password"=>"pass"));
instead of
$data ='[{"UserId":"xxxxx-10100","Password": "pass"}]';

PHP Curl - How to do POST request and the parameters should be in JSON format in the body

I need to replicate the same POST request in PHP curl. The request parameters should be in json in the body and the response too is a json object.
{
"api_key": "scTrCT",
"test": "true",
"service_provider_list": [
{
"facility_name": "ALL YOUR SMILE NEEDS DENTAL CENTERS",
"provider_name": "DRS. HERMAN AND MACK P.C",
"tax_id": "12345678
}
],
"payer_ids": [
"00431"
],
"transaction_type": "270",
"effective_date": "2014-01-12"
}
Please try this:
<?php
$json = array(
"api_key" => "scTrCT",
"test" => "true",
"service_provider_list" => array(
"facility_name" => "ALL YOUR SMILE NEEDS DENTAL CENTERS",
"provider_name" => "DRS. HERMAN AND MACK P.C",
"tax_id" => "12345678"
),
"payer_ids" => array(
"00431"
),
"transaction_type" => "270",
"effective_date" => "2014-01-12"
);
$json = json_encode($json);
$ch = curl_init('http://gds.eligibleapi.com/v1.3/enrollment.json');
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS, $json);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$result = curl_exec($ch);
curl_close($ch);
echo $result;

Parameters missing or not sent as an JSON array with PHP CURL

The error:
{"jsonrpc":"2.0","id":0,"error":{"code":1,"message":"Parameters missing or not sent as an JSON array. "}}
My code:
<?php
$ch = curl_init();
curl_setopt($ch, CURLOPT_HTTPHEADER, array("Content-Type: application/json","Accept: text/plain, */*; q=0.01"));
curl_setopt($ch, CURLOPT_URL, 'http://example.com/rpc/ClientApi?_session=XX');
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode(array('method' => 'AdsApi.giveAdLifeByCategory','params' => '["Ads4Life"]', 'id' => '0')));
curl_setopt($ch, CURLOPT_POST, 1);
$result = curl_exec($ch);
?>
I'm trying to emulate this request:
[{"method":"AdsApi.giveAdLifeByCategory","params":["Ads4Life"],"id":0}]
Correct Response:
[{
"jsonrpc": "2.0",
"id": 0,
"result": {
"status": true,
"timeStamp": 0
}
}]
What could be the problem?
Wrong bracketing:
... 'AdsApi.giveAdLifeByCategory','params' => '["Ads4Life"]', 'id' => '0')));
^--- ^--
your "emulated" sample has braockets around that, but you're embedding them in your array key definition, so when the JSON is produced, it'll actually be:
... "params": "[\"Ads4Life\"]" ...
with the [" and "] embedded within the string.
Probably should be just
... 'AdsApi.giveAdLifeByCategory','params' => array('Ads4Life'), 'id' => '0')));
^^^^^^^^^^

Insert event to Google Calendar using php

I'm trying to perform a cURL request to google calendar api using their guide, that says:
POST https://www.googleapis.com/calendar/v3/calendars/{name_of_my_calendar}/events?sendNotifications=true&pp=1&key={YOUR_API_KEY}
Content-Type: application/json
Authorization: OAuth 1/SuypHO0rNsURWvMXQ559Mfm9Vbd4zWvVQ8UIR76nlJ0
X-JavaScript-User-Agent: Google APIs Explorer
{
"start": {
"dateTime": "2012-06-03T10:00:00.000-07:00"
},
"end": {
"dateTime": "2012-06-03T10:20:00.000-07:00"
},
"summary": "my_summary",
"description": "my_description"
}
How am I supposed to do that in php? I wonder what parameters I should send and what constants I should use. I'm currently doing:
$url = "https://www.googleapis.com/calendar/v3/calendars/".urlencode('{name_of_my_calendar}')."/events?sendNotifications=true&pp=1&key={my_api_key}";
$post_data = array(
"start" => array("dateTime" => "2012-06-01T10:00:00.000-07:00"),
"end" => array("dateTime" => "2012-06-01T10:40:00.000-07:00"),
"summary" => "my_summary",
"description" => "my_description"
);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 1);
// adding the post variables to the request
curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);
$output = curl_exec($ch);
curl_close($ch);
but the response is:
{
error: {
errors: [
{
domain: "global",
reason: "required",
message: "Login Required",
locationType: "header",
location: "Authorization"
}
],
code: 401,
message: "Login Required"
}
}
How should I format my parameters?
I noticed this question is asked quite some time ago, however after figuring out the post-parameter problem after some time I thought it might be useful to others to answer it. First within '$post_data', I switched the 'start' and 'end':
$post_data = array(
"end" => array("dateTime" => "2012-06-01T10:40:00.000-07:00"),
"start" => array("dateTime" => "2012-06-01T10:00:00.000-07:00"),
"summary" => "my_summary",
"description" => "my_description"
);
Secondly, I figured Google Calendar API expected the data to be json, so in curl_setopt:
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($post_data));
This worked perfectly for me, hope it's useful to someone else as well!

Categories