Within a symfony5 controller, I can return json responses via:
return $this->json(['key' => 'content');
Yet when I throw an HttpException, I see the default html error page in both dev and production.
I want to create a restful api, so I want to convert all HttpExceptions into json.
I want to configure all my controllers to format their response as json. At most, I want to add one Exception handler that would transform the excpetions into proper messages. (In prod it should have less information, in dev it may contain the exception stacktrace.)
How can I achieve this? I thought I could use the format
option of the @Route
annotation but it doesn't work.
This is my example controller:
<?php declare(strict_types=1);
namespace App\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
use Symfony\Component\Routing\Annotation\Route;
class StatusController extends AbstractController
{
/**
* @Route("/status", name="status", format="json")
* @Template
* @return JsonResponse
*/
public function status()
{
if (true) {
// this will render as html, how to serialize it as json?
throw new NotFoundHttpException("This is an example");
}
$ok = new \stdClass();
$ok->status = "OK";
return $this->json($ok);
}
}
While looking for this I came across this PR which seems to achieve what I am trying to do, yet I am unsure what I am missing.
On the symfony blog I found following answer by Yonel Ceruto saying
you will need to install/enable the serializer component,
yet I have no idea what this entails.
In dev and prod I got these html views instead of a json response: