I use Unirest for PHP to do some HTTP Requests. Everything works fine, until I want to pass a fairly complex JSON to my Node.js router.
First I do a GET request that returns a JSON Object, then I extend this JSON object (needs to be done, I know it sucks) and want to feed it back into my other http POST request... and here is where the trouble starts:
I echoed the JSON that is returned and copied the output into postman -> works fine. If I want use the JSON directly in PHP in next request:
$teamsMemberOf is the variable which is containing the GET response.
$headers = array("Accept" => "application/json");
$newBody = '{"team":'.$teamsMemberOf->raw_body.'}';
$relevantBoxesAmount = Unirest\Request::post("http://localhost:3001/my/route/".$result['_id']."/get-something-from-server", $headers, $newBody);
and it doesn't work.
Error is 500 and 'Cannot read property '0' of undefined' which is certainly related to something in the JSON object.
Does someone have an idea how to fix it?
Related
I develop at php Laravel.
I receiving GuzzleHttp response from Mailgun as Object and can't to get from it the status.
the Object is:
O:8:"stdClass":2:{s:18:"http_response_body";O:8:"stdClass":2:{s:6:"member";O:8:"stdClass":4:{s:7:"address";s:24:"test_of_json-4#zapara.fr";s:4:"name";s:10:"not filled";s:10:"subscribed";b:1;s:4:"vars";O:8:"stdClass":0:{}}s:7:"message";s:36:"Mailing list member has been created";}s:18:"http_response_code";i:200;}
I need just last data pair:
"http_response_code";i:200;
to get it into variable, like:
$http_response_code = 200;
or even just its value.
To get string as I cited above I use
$result_ser = serialize($result);
but yet can't to extract value of variable.
Also I tried this:
$this->resultString .= \GuzzleHttp\json_decode($result_ser, true);
and get error.
Please, explain me , How to get/extract value I needed?
To take the response status code you can use the function getStatusCode :
$response = $client->request();
$statusCode = $response->getStatusCode();
while to take the body of response you can use :
$contents = $response->getBody()->getContents();
let's consider your request is something like
$response = $client->get("https://example.com");
if ( $object_res->getStatusCode() == 200 ) { // here you are checking your http status code
}
$object_res->getStatusCode() is the method to get http status code.
refer docs, there is simple example in this page.
I found that 'mailgun/mailgun' package uses its own HTTP client which also uses 'RestClient' and these classes are return stdObject.
In that Object there is property 'http_response_code' containing HTTP response code like 200, 400, 401 etc.
This property accessible by standard way $object->property and it's a solution of my query in this case.
For anybody who will read this question and answers I should to explain one thing that I not cleared in question.
I made request to the Mailgun API for subscribing member to mailing list. The API returns stdObject, not JSON or XML data.
But also there is one more strange thing - stdObject returned when request is successful only. If request fails you'll get just Exception thrown with message and without code. This forced me, if fail, to parse message body instead of get and resolve error code.
$responseObj->getStatusCode();
One of my partners has an API service which should send an HTTP POST request whenever a new file is published. This requires me to have an api file which will get the POST this way:
http://myip:port/api/ReciveFile
and requesting that the JSON format request should be:
{
"FILE ":"filename.zip",
"FILE_ID":"123",
"FILE_DESC":"PRUPOUS_FILE",
"EXTRAVAR":"",
"EXTRAVAR2":"",
"USERID":" xxxxxxxxxxxx",
"PASSWORD":"yyyyyyyyyyy"
}
Meanwhile it should issue a response, in JSON format if it got the file or not
{"RESULT_CODE":0,"RESULT_DESCR":""}
{"RESULT_CODE":1001,"RESULT_DESCR":"Bad request"}
And after, when I am finished elaborating the file, I should send back the modified file same way.
The question is, now basically from what I understand he will send me the variables witch I have to read, download the file, and send a response back.
I am not really sure how to do this any sample code would be welcomed!
I'm not sure exactly what the question is, but if you mean creating a success response in JSON for if an action occurred while adding data to it which is what can be understood from the question, just create an array with the values you wish to send back to the provider and do json_encode on the array which should create json and just print it back as a response.
About receiving the information; all you have to do is use the integrated curl functions or use a wrapper (Guzzle, etc) to output the raw JSON or json_decode data into a variable and do whatever you please with it.
From what I read in the question, you wish to modify the contents of it. This can be achieved by just decoding the json and changing the variables in the array, then printing the modified JSON back as a response.
Example (this uses GuzzleHTTP as an example):
$res = $client->request('GET', 'url');
$json = $res->getBody();
$array = json_decode($json, 1); // decode the json
// Start modifying the values or adding
$array['value_to_modify'] = $whatever;
$filename = $array['filename']; // get filename
// make a new request
$res = $client->request('GET', 'url/'.$filename);
// get the body of specified filename
$body = $res->getBody();
// Return the array.
echo json_encode($body);
References:
http://docs.guzzlephp.org/en/latest/
I am using slim php framework for developing REST API. I am successful in implementing POST and GET requests. I am using ContentTypes middleware as well to parse the JSON body in POST and PUT requests however my PUT request always gives empty string on the server. POST just works fine and I can get the parsed JSON as PHP associative array but cant get it in PUT request. I am using application/json in headers and I dont want to use application/x-www-form-urlencoded method.
$app->map('/example/:id', function ($id) use($app, $log) {
//$body = $app->request()->getBody();
//using the above in other POST calls & it works but does not in this case
$body = json_decode($app->request()->getBody()); //tried this. no success
var_dump($body);
} )->via ( 'PUT', 'PATCH' );
I am calling it via CURL like this
$headers = array(
'Content-Type'=>'application/json;charset=utf-8',
);
$id = 123;
$body = array("name"=>"myfirstname","email"=>"myemail");
$json_str = json_encode($body);
$response = Requests::put($base_url.'/api/v1/example/'.$id,$headers,$json_str);
When I try to return the same JSON from the API it returns empty array. I tried POSTMAN on chrome and above code but does not work. What is the issue.
Update: I have verified the same code works on localhost but does not work on remote dev server. What can be the reason? Do I need to alter any settings on server?
Slim reads php://input to get the contents of the request body, so whatever the problem is it has to do with the particulars of that stream.
Do you have some other code that tries to read php://input? If so, note that this is only possible starting from PHP 5.6 (which your local machine may have when your server does not).
Try using getInstance().
$body = json_decode($app->getInstance()->request()->getBody());
I'm just a newbie in the Slim framework. I've written one API using Slim framework.
A POST request is coming to this API from an iPhone app. This POST request is in JSON format.
But I'm not able to access the POST parameters that are sent in a request from iPhone. When I tried to print the POST parameters' values I got "null" for every parameter.
$allPostVars = $application->request->post(); //Always I get null
Then I tried to get the body of a coming request, convert the body into JSON format and sent it back as a response to the iPhone. Then I got the parameters' values but they are in very weird format as follows:
"{\"password\":\"admin123\",\"login\":\"admin#gmail.com\",\"device_type\":\"iphone\",\"device_token\":\"785903860i5y1243i5\"}"
So one thing for sure is POST request parameters are coming to this API file. Though they are not accessible in $application->request->post(), they are coming into request body.
My first issue is how should I access these POST parameters from request body and my second issue is why the request data is getting displayed into such a weird format as above after converting the request body into JSON format?
Following is the necessary code snippet:
<?php
require 'Slim/Slim.php';
\Slim\Slim::registerAutoloader();
//Instantiate Slim class in order to get a reference for the object.
$application = new \Slim\Slim();
$body = $application->request->getBody();
header("Content-Type: application/json");//setting header before sending the JSON response back to the iPhone
echo json_encode($new_body);// Converting the request body into JSON format and sending it as a response back to the iPhone. After execution of this step I'm getting the above weird format data as a response on iPhone.
die;
?>
Generally speaking, you can access the POST parameters individually in one of two ways:
$paramValue = $application->request->params('paramName');
or
$paramValue = $application->request->post('paramName');
More info is available in the documentation: http://docs.slimframework.com/#Request-Variables
When JSON is sent in a POST, you have to access the information from the request body, for example:
$app->post('/some/path', function () use ($app) {
$json = $app->request->getBody();
$data = json_decode($json, true); // parse the JSON into an assoc. array
// do other tasks
});
"Slim can parse JSON, XML, and URL-encoded data out of the box" - http://www.slimframework.com/docs/objects/request.html under "The Request Body".
Easiest way to handle a request in any body form is via the "getParsedBody()". This will do guillermoandrae example but on 1 line instead of 2.
Example:
$allPostVars = $application->request->getParsedBody();
Then you can access any parameters by their key in the array given.
$someVariable = $allPostVars['someVariable'];
Slim will json_decode the post body for you using this middleware
https://www.slimframework.com/docs/v4/middleware/body-parsing.html
I am trying to implement a php client that sends an HTTP GET to the server which sends back a JSON object with the return information. I know how to decode the JSON once my php script has received it, but how would I go about actually getting it?
EDIT: Note - I send the server an HTTP GET, and it generates and sends back a JSON file. It is not a file sitting on the server.
Check out file_get_contents
$json = file_get_contents('http://somesite.com/getjson.php');
Browsers act differently based on what the server responds. It does not matter what type of request you make to the server (be it GET, POST, etc), but to return JSON as a response you have to set the header in the script you make the request to:
header('Content-Type: application/json;charset=utf-8;');
And then echo the JSON string, for example:
//...populating your result data array here...//
// Print out the JSON formatted data
echo json_encode($myData);
User agent will then get the JSON string. If AJAX made the request then you can simply parse that result into a JavaScript object that you can handle, like this:
//...AJAX request here...//
// Parse result to JavaScript object
var myData=JSON.parse(XMLHttp.responseText);
The header itself is not -really- necessary, but is sort-of good practice. JSON.parse() can parse the response regardless.