v2.3 The Event System

The Event System

API Platform Core implements the Action-Domain-Responder pattern. This implementation is covered in depth in the Creating custom operations and controllers chapter.

Basically, API Platform Core execute an action class that will return an entity or a collection of entities. Then a series of event listeners are executed which validate the data, persist it in database, serialize it (typically in a JSON-LD document) and create an HTTP response that will be sent to the client.

To do so, API Platform Core leverages events triggered by the Symfony HTTP Kernel. You can also hook your own code to those events. They are handy and powerful extension points available at all points of the request lifecycle.

In the following example, we will send a mail each time a new book is created using the API:

<?php
// api/src/EventSubscriber/BookMailSubscriber.php

namespace App\EventSubscriber;

use ApiPlatform\Core\EventListener\EventPriorities;
use App\Entity\Book;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpKernel\Event\GetResponseForControllerResultEvent;
use Symfony\Component\HttpKernel\KernelEvents;

final class BookMailSubscriber implements EventSubscriberInterface
{
    private $mailer;

    public function __construct(\Swift_Mailer $mailer)
    {
        $this->mailer = $mailer;
    }

    public static function getSubscribedEvents()
    {
        return [
            KernelEvents::VIEW => ['sendMail', EventPriorities::POST_WRITE],
        ];
    }

    public function sendMail(GetResponseForControllerResultEvent $event)
    {
        $book = $event->getControllerResult();
        $method = $event->getRequest()->getMethod();

        if (!$book instanceof Book || Request::METHOD_POST !== $method) {
            return;
        }

        $message = (new \Swift_Message('A new book has been added'))
            ->setFrom('[email protected]')
            ->setTo('[email protected]')
            ->setBody(sprintf('The book #%d has been added.', $book->getId()));

        $this->mailer->send($message);
    }
}

If you use the official API Platform distribution, creating the previous class is enough. The Symfony Dependency Injection component will automatically register this subscriber as a service and will inject its dependencies thanks to the autowiring feature.

Alternatively, the subscriber must be registered manually.

Doctrine events are also available (if you use it) if you want to hook at the object lifecycle events.

Built-in event listeners are:

NameEventPre & Post hooksPriorityDescription
AddFormatListenerkernel.requestNone7guess the best response format (content negotiation)
ReadListenerkernel.requestPRE_READ, POST_READ4retrieve data from the persistence system using the data providers (GET, PUT, DELETE)
DeserializeListenerkernel.requestPRE_DESERIALIZE, POST_DESERIALIZE2deserialize data into a PHP entity (GET, POST, DELETE); update the entity retrieved using the data provider (PUT)
ValidateListenerkernel.viewPRE_VALIDATE, POST_VALIDATE64validate data (POST, PUT)
WriteListenerkernel.viewPRE_WRITE, POST_WRITE32persist changes in the persistence system using the data persisters (POST, PUT, DELETE)
SerializeListenerkernel.viewPRE_SERIALIZE, POST_SERIALIZE16serialize the PHP entity in string according to the request format
RespondListenerkernel.viewPRE_RESPOND, POST_RESPOND8transform serialized to a Symfony\Component\HttpFoundation\Response instance
AddLinkHeaderListenerkernel.responseNone0add a Link HTTP header pointing to the Hydra documentation
ValidationExceptionListenerkernel.exceptionNone0serialize validation exceptions in the Hydra format
ExceptionListenerkernel.exceptionNone-96serialize PHP exceptions in the Hydra format (including the stack trace in debug mode)

Those built-in listeners are always executed for routes managed by API Platform. Registering your own event listeners to add extra logic is convenient.

The ApiPlatform\Core\EventListener\EventPriorities class comes with a convenient set of class’s constants corresponding to commonly used priorities:

ConstantEventPriority
PRE_READkernel.request5
POST_READkernel.request3
PRE_DESERIALIZEkernel.request3
POST_DESERIALIZEkernel.request1
PRE_VALIDATEkernel.view65
POST_VALIDATEkernel.view63
PRE_WRITEkernel.view33
POST_WRITEkernel.view31
PRE_SERIALIZEkernel.view17
POST_SERIALIZEkernel.view15
PRE_RESPONDkernel.view9
POST_RESPONDkernel.response0

Some of those built-in listeners can be enabled/disabled by setting request attributes (for instance in the defaults attribute of an operation):

AttributeTypeDefaultDescription
_api_receivebooltrueEnables or disables the ReadListener, DeserializeListener and ValidateListener
_api_respondbooltrueEnables or disables SerializeListener, RespondListener
_api_persistbooltrueEnables or disables WriteListener

You can also help us improve the documentation of this page.

Made with love by

Les-Tilleuls.coop can help you design and develop your APIs and web projects, and train your teams in API Platform, Symfony, Next.js, Kubernetes and a wide range of other technologies.

Learn more

Copyright © 2023 Kévin Dunglas

Sponsored by Les-Tilleuls.coop