Slim - How to send response with "Content-Type: application/json" header? Slim - How to send response with "Content-Type: application/json" header? php php

Slim - How to send response with "Content-Type: application/json" header?


So, instead of this:

if($student) {            $response->withHeader('Content-Type', 'application/json');            $response->write(json_encode($student));            return $response;        } else { throw new PDOException('No records found');}

Do like this:

if($student) {    return $response->withStatus(200)        ->withHeader('Content-Type', 'application/json')        ->write(json_encode($student));} else { throw new PDOException('No records found');}

And all is well and good.


For V3, withJson() is available.

So you can do something like:

return $response->withStatus(200)                ->withJson(array($request->getAttribute("route")                ->getArgument("someParameter")));

Note: Make sure you return the $response because if you forget, the response will still come out but it will not be application/json.


For V3, the simplest method as per the Slim docs is:

$data = array('name' => 'Rob', 'age' => 40);return $response->withJson($data, 201);

This automatically sets the Content-Type to application/json;charset=utf-8 and lets you set a HTTP status code too (defaults to 200 if omitted).