Alter existing route's output formats? 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-&gt;get('entity.node.canonical')) {
      $route-&gt;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?
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:

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