Symfony json response is returning content twice - php

I have been writing an API using Symfony as the backend, a plugin written by a third party is sending certain data to an endpoint, the endpoint is then to return a json encoded response, however following the instructions as set out in the current symfony documaentation(https://symfony.com/doc/current/components/http_foundation.html) the return value is displayed twice and the response is not well formed and outputs like string
The original method that I wrote had calls to a database to validate a token, store a bookmark and display the result of the backend process, however when getting down to brass tacks and removing everything but the response building; it is obvious that this is where the problem lies. The method uses this snippet, though for clarity I have not included the database processing and used the posted values as the return array, the result is the same if it is the post or processed data, the output displays twice.
$token = $request->request->get('token');
$bookmark = $request->request->get('bookmark');
$data = ['token' => $token, 'bookmark' => $bookmark];
$response = new Response();
$response->headers->set('Access-Control-Allow-Origin', '*');
$response->setContent(json_encode($data));
$response->send();
return $response;
What I was expecting was a single json response but what is returned is a double string of the json output
e.g. if I posted these values to the above snippet:
token: ksjdbvqpi8e7rqp7evbprb
bookmark: http://www.google.com
the return result is
{"token":"ksjdbvqpi8e7rqp7evbprb", "bookmark":"http:\/\/www.google.com"}{"token":"ksjdbvqpi8e7rqp7evbprb", "bookmark":"http:\/\/www.google.com"}
when what I was expecting was just
{"token":"ksjdbvqpi8e7rqp7evbprb", "bookmark":"http:\/\/www.google.com"}
I have no idea at the moment why it is displaying twice, any help is as always appreciated.
Thanks

$response->send(); is the line that should be removed.
As you already return object of class Response symfony will take care to output this response to browser, you don't need to do it manually with send().

Related

How to get HTTP status answer from GuzzleHttp response by php Laravel?

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

Get and Send file with PHP and RESTful API

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/

PHP Unirest plugin not working properly

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?

How to access a JSON request body of a POST request in Slim?

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

CakePHP REST Put/Post not accepting data

I am attempting to write a RESTful service using CakePHP 2.3.5. So far I've successfully created the GET functions for the resource I'm working with. I can send a GET request to example.com/areas.json or to example.com/areas/1.json and it returns the data in my database.
However, I started trying to get the edit function working. I wrote a simple edit method that simply saved the incoming data from $this->request->data. I'm using Postman to test the functionality and sending raw JSON over PUT or POST to example.com/areas/1.json returns a message telling me that the data couldn't be saved. I made the method send me more information when it failed and it tells me that there is no incoming data in either $this->request->data or $this->data.
I've been searching the Internet for solutions to this or similar problems, but everything I have tried has failed so far. I've attempted disabling CSRF checks, disabling the SecurityComponent altogether, and multiple other fixes all involving the security. Changing any of those resulted in black holing the request.
Does anyone have any thoughts on what else I could try to get CakePHP to accept the JSON data into a request? I'll include my edit function below in case that helps.
public function edit($id)
{
$this->Area->id = $id;
$message['request-data'] = $this->request->data;
if ($this->Area->save($this->request->data)) {
$message['response'] = $this->Area->findById($id);
} else {
$message['response'] = "Error";
}
$this->set(array(
'message' => $message,
'_serialize' => array('message')
));
}
First, make sure the Content-Type of the request is application/json.
Second, CakePHP doesn't automatically decode the JSON payload; you have to do it manually. From the manual:
// Get JSON encoded data submitted to a PUT/POST action
$data = $this->request->input('json_decode');

Categories