Reputation: 300
I have a Slim 3 route: $app->get('/calendar/{date}', 'CalendarCtrl:getSchedule');
This route can return the same schedule by simple HTML list, json or xml format.
Now I'm looking for a simple REST solution based on Accept
(or more headers) HTTP header.
For example:
Request:
GET /calendar/2017-01-01
Accept: application/json
Response:
Content-Type: application/json
Body: {json schedule}
So a route should be smth like this: $app->get('/calendar/{date}', {Accept: application/json}, 'CalendarCtrl:getScheduleJson');
I know I can check for that header in a route handler. But I'm looking for a simple declarative solution.
Upvotes: 1
Views: 1164
Reputation: 542
Add a middleware to check for that header before sending the response from your API
$app->add(function ($req, $res, $next) {
//Checking for $req content-type here then send the response with the same one
//example
$headerValue= $req->getHeader('Accept');
if($headerValue=='application/json')
{
$response = $next($req, $res);
return $response
->withHeader('Content-type', 'application/json');
}
else{
//check for other header here
}
});
Upvotes: 3