'Symfony post request body parameters?
I'm sending POST request by postman with header application/json
and the body:
{
"name": "user"
}
And when I try to get this parameter from the request object
$request->request->get('name')
I got null.
But when I use $request->getContent()
I receive raw string.
Looks like my request is not parsed 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 to do it in framework by default.
Solution 1:[1]
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'
Solution 2:[2]
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.
- true: array
- false: object (default)
Solution 3:[3]
Answer from Cacanode is correct - you can decode json from the $request->getContent()
However, if you want to make your live easier you can consider using FOSRestBundle. Specifically the "body_listener" funcationality: https://symfony.com/doc/master/bundles/FOSRestBundle/body_listener.html
This bundle has both JSON and XML decoders already installed - and you can add some new custom decoder if you want.
Solution 4:[4]
Using Symfony 4.3 you could use the component:
...
use Symfony\Component\HttpFoundation\Request;
...
public function doSomething(Request $request){
$a = json_decode($request->getContent(), true);
return $this->json($a);
}
This will return the same json object you sent.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Caconde |
Solution 2 | yorgos |
Solution 3 | domis86 |
Solution 4 | Julio Gonzalez Rios |