Setting the Content-Type Globally

Is there a way to set the content-type to ‘application/json’ for responses globally in SLIM 3?

I tried the following things which did not work:

$app->contentType(‘application/json’);
$app->response->headers->set(‘Content-Type’, ‘application/json’);

Use middleware:

$app->add(function($request, $response, $next) {
    $response = $next($request, $response);
    return $response->withHeader('Content-Type', 'application/json');
});
1 Like

I hope it’s OK to hijack this post, I didn’t feel it was a good idea to create a whole new one. If I was to use this, is it possible to override that setting for specific routes/groups? I tried adding a specific middleware to a route with a different content-type but it’s still application/json, presumably because of the order they’re run?

Just apply the middleware to the routes/groups that need it? Or am I missing something?

Indeed, but let’s say I had 100 routes and they were all JSON, but I wanted just one to be CSV. The app level middleware seems sensible, but of course only if you could override it from a single route. That would be nice, as opposed to having lots and lots of adds.

Thinking about it, would it be valid to do something like:

$app->add(function($request, $response, $next) {
    if ($request->getPath() != 'something') {
        $response = $next($request, $response);
        return $response->withHeader('Content-Type', 'application/json');
    }
});

You can add middleware via groups.

Example:

$app->group('', function () {
    //json routes
})->add(function($request, $response, $next) {
        $response = $next($request, $response);
        return $response->withHeader('Content-Type', 'application/json');
});

$app->group('', function () {
    //CSVroutes
})->add(function($request, $response, $next) {
        $response = $next($request, $response);
        return $response->withHeader('Content-Type', 'text/csv');
});

1 Like