I want to alter the entity.node.canonical route so that when it is accessed using ?_format=json it will return the rendered node in JSON.

So far I have created a RouteSubscriber that alters the route like this:

use Drupal\Core\Routing\RouteSubscriberBase;
use Symfony\Component\Routing\RouteCollection;

class RouteSubscriber extends RouteSubscriberBase {

   * {@inheritdoc}
  protected function alterRoutes(RouteCollection $collection) {
    if ($route = $collection->get('entity.node.canonical')) {
      $route->setRequirement('_format', 'json|html');


Ideally I want to have a seperate controller that is called when the format is JSON and otherwise use the default controller from core.

Is this possible, and how would I have to code it?

If that's not possible how can I override the default controller then?

  • Are you using the core REST module, or are you doing this custom? – mpdonadio Aug 19 at 18:23
  • I’m doing it custom. – Jdrupal Aug 19 at 18:24

I found the solution myself.

I just created a new route with the requirement _format: json and the path /node/{node} just like entity.node.canonical. Then I could set a controller that is only called when the node is being output in JSON format.

My route definition looks like this:

  path: '/node/{node}'
    _controller: '\Drupal\my_module\Controller\NodeViewController::json'
    _title_callback: '\Drupal\node\Controller\NodeViewController::title'
    _entity_access: 'node.view'
    _format: 'json'

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.