How to work with JSON in Request Object


I don’t understand, how I have to deal with JSON in a Request Object?
Adding a middleware as described in does not work for me:

    class JsonBodyParser implements MiddlewareInterface

    public function process(Request $request, RequestHandler $handler): Response

        $contentType = $request->getHeaderLine('Content-Type');

        if (strstr($contentType, 'application/json')) {
            $contents = json_decode(file_get_contents('php://input'), true);
            if (json_last_error() === JSON_ERROR_NONE) {
                $request = $request->withParsedBody($contents);
                // this request object contains an array in getParsedBody()
                print_r(['$request' => $request]);

        return $handler->handle($request);


    $app = AppFactory::create();
    $app->add(new JsonBodyParser());
    $app->post('/test/json', function(Request $request, Response $response) {
            '$_POST' => $_POST,
            'getHeader(\'content-type\')' => $request->getHeader('content-type'),
            'getMethod()' => $request->getMethod(),
            'getParsedBody()' => $request->getParsedBody(), // empty 
            'getBody()' => $request->getBody()
        ], true));

curl --header "Content-Type: application/json" --request POST --data '{"name":"xyz"}'
1 Like


You don’t need a custom JsonBodyParser, because you can use the PSR-7 Request object’s getParsedBody() method the get the JSON data as array.

$data = (array)$request->getParsedBody();


thanks, this I tried at first. But it won’t work.

What OS do you use?
Have you tried the same test with Postman?

I am using docker-compose with two containers: PHP 7.4-fpm and nginx. I tried with postman and cUrl.

But…it seems that something else was strange. So I reinstalled all packages by composer and now it works!

Thank’s a lot for your quick help and answers!