I'm sending POST request by postman with 1 header application/json and body
{
"name": "user"
}
And when I try to get this paraneter from request object like
$request->request->get('name')
get null.
But when I use $request->getContent()
I receive raw string.
Looks like my request is not parsing correctly. What is wrong with the request?
Update:
Turned out that docs not clear about that and I need to manually convert body to json. Don't really understand why not do it in framework by default.
And, in Symfony, there is a Request object that holds all of this data. To read POST data, we need to get the Request object! And because needing the request is so common, you can get it in a controller by using its type-hint. Check this out: add Request - make sure you get the one from HttpFoundation - and then $request.
If we send in a POST request with the Content-type header set to application/json, and the request body set to our JSON string, then our Symfony controller will receive the data. Good news. It won't be immediately usable though. Which is bad news. The data will arrive as a raw string. Why bother setting the Content-type then?
Probably the most confusingly named thing that we use most frequently in Symfony is $request->request. From the Request class (or the $request object), we want to access the request body parameters, or what you may simply know as the $_POST superglobal.
Additional useful informations on HTTP requests in Symfony can be found on the HttpFoundation package's documentation. use Symfony\Component\HttpFoundation\Request; public function indexAction (Request $request, $id) { $post = $request->request->all (); $request->request->get ('username'); }
That is the expected behavior. You are sendind a JSON string inside the body of the request.
In this case, you need json_decode to convert the JSON string into an array or object, in order to access the data.
$parameters = json_decode($request->getContent(), true);
echo $parameters['name']; // will print 'user'
Although the accepted answer is correct, I would like to add here that there are 2 ways of doing so.
$payload = json_decode($request->getContent(), true);
echo $payload['name']; // will print 'user'
or
$payload = json_decode($request->getContent(), false);
echo $payload->name; // will print 'user'
By default, the json_decode returns an object unless otherwise specified by the second parameter.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With