I have created a custom service and have hooked into the "event_subscriber" via tags in my custom service.yml

      class: Drupal\demo_api\Response\Handler
          - { name: 'event_subscriber' }

With in this custom service I'm listening into KernelEvents::RESPONSE

public static function getSubscribedEvents()
    // For this example I am using KernelEvents constants (see below a full list).
    $events[KernelEvents::RESPONSE][] = ['onResponse'];
    return $events;

The problem is I have some API request and I'm modifying the response for these request and returning a modified json format.

public function onResponse(FilterResponseEvent $event)
    $response = $event->getResponse();
    $apiFormatter = new ApiFormatter();

This is causing any web pages to respond as json.

I would like to limit this service to these API calls only and not be called on each request.

Any advice would be grateful.


If you want to restrict the event subscriber to a route then check for the route name:

public function onResponse(FilterResponseEvent $event) {

  $route_name = $event->getRequest()->attributes->get('_route');
  if ($route_name !== 'my.route.name') {



Although in Drupal it might be best practice to get the route name from the current_route_match service:

$route_name = $this->routeMatch->getRouteName();

which you then need to inject in the event subscriber.

|improve this answer|||||

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.