Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

access HTTP PUT data in Symfony2

Via HTTP PUT I send the following json to my webservice, verified by return new Response($request->getContent());:

{"company_id":13}

In my webservice I am trying to retrieve the data by its tag from the request:

var_dump("COMPANY ID ".$request->request->getInt('company_id')); //returns 0

I've also tried:

//the 2 below should only work on GET from what I read
var_dump("COMPANY ID ".$request->get('company_id')); //returns nothing
var_dump("COMPANY ID ".$request->query->getInt('company_id')); //returns 0

The symfony2 book only mentions how to get data from GET and POST, how do I retrieve data from a PUT request?

like image 762
G_V Avatar asked Apr 26 '16 07:04

G_V


2 Answers

You are getting it from $request->getContent(), just json_decode it and you should get an object, so you can access it then. Example:

$data = json_decode($request->getContent());
var_dump("COMPANY ID " . $data->company_id);

Edit to add a little bit more explanation.

Symfony Http Foundations get method is basically just an "alias" for $request->attributes->get, $request->query->get, and $request->request->get, so if one returns 0 or false, or whatever, quite probably the other will too.

Since HTTP PUT sends data as body, the Request object does not try to decode it in any way, because it could have been in multiple different formats(JSON, XML, non-standard,...). If you wish to access it through get method call, you will have to decode it manually and then add it to its request or query properties.

like image 103
slax0r Avatar answered Oct 23 '22 19:10

slax0r


You will never get it as a single parameter, because it is not a parameter. It's a raw content that you have to decode yourself.

HTTP protocol does not know anything about JSON / XML / serializing / whatever.

It only sees a text string.

As @slaxOr said, you'll have to get from the request and decode it yourself (there may be bundles that do it for you, but I am not aware of them).

like image 40
Francesco Abeni Avatar answered Oct 23 '22 19:10

Francesco Abeni