Accessing JSON body of POST request in Symfony 2.3 controller

1.3k Views Asked by At

I've spent the past 3 hours attempting to parse the JSON body of an incoming POST request to an API endpoint I've built in Symfony 2.3.3.

I can't for the life of me figure out how to get access to the body, and it is driving me mad. I have a graveyard full of syntaxes I've tried, and none of them have worked. Everything that has not worked is below.

Post request:

app_1    | Accept:          application/json
app_1    | Accept-Encoding: gzip;q=1.0,deflate;q=0.6,identity;q=0.3
app_1    | Connection:      close
app_1    | Content-Length:  19
app_1    | Content-Type:    application/json
app_1    | Host:            localhost
app_1    | User-Agent:      Faraday v0.15.4
app_1    | X-Php-Ob-Level:  1
app_1    |
app_1    | {"hello":"goodbye"}

Inside controller default action (everything that has not worked):

        $request = $this->getRequest();
        $hello = $request->query->get('hello');
        $hello1 = $request->request->get('hello');
        $hello2 = $request->get('hello');

        $json2 = filter_input(INPUT_POST, 'hello', FILTER_DEFAULT);

Whenever I error_log() any of the above variables, I get blank or nil.

What am I doing wrong?

1

There are 1 best solutions below

2
Jimish Gamit On BEST ANSWER
if (0 === strpos($request->headers->get('Content-Type'), 'application/json')) {
      $data = json_decode($request->getContent(), true);
}

You can use php://inputbut it's inefficient.