Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Symfony post request body parameters?

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.

like image 568
ogbofjnr Avatar asked Jul 30 '19 22:07

ogbofjnr


People also ask

How do I read post data in Symfony controller?

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.

Should I set content-type for POST request in Symfony?

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?

What is $request->request in Symfony?

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.

Where can I find information on HTTP requests in Symfony?

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'); }


2 Answers

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'
like image 119
Caconde Avatar answered Oct 06 '22 08:10

Caconde


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)
like image 27
yorgos Avatar answered Oct 06 '22 10:10

yorgos