# Creating Async APIs using the Mercure Protocol API Platform can automatically push the modified version of the resources exposed by the API to the currently connected clients (webapps, mobile apps...) using [the Mercure protocol](https://mercure.rocks). > _Mercure_ is a protocol allowing to push data updates to web browsers and other HTTP clients in a > convenient, fast, reliable and battery-efficient way. It is especially useful to publish real-time > updates of resources served through web APIs, to reactive web and mobile apps. > > —[https://mercure.rocks](https://mercure.rocks) API Platform detects changes made to your Doctrine entities, and sends the updated resources to the Mercure hub. Then, the Mercure hub dispatches the updates to all connected clients using [Server-sent Events (SSE)](https://developer.mozilla.org/en-US/docs/Web/API/Server-sent_events). ![Mercure subscriptions](images/mercure-subscriptions.png) ## Which Protocol Version Does Your Hub Speak? Mercure has a 1.0 protocol version that changes how subscribers pick which updates to receive: `match=` and `match_urlpattern=` query parameters replace `topic=`. API Platform talks to 0.x hubs by default; switching a hub to 1.0 is done by configuring `protocol_version: '1.0'` on the [MercureBundle](https://symfony.com/doc/current/mercure.html) side, not on this page. The examples below cover both; check with whoever operates your hub if you're not sure which version it runs. ## Installing Mercure Support Mercure support is already installed, configured and enabled in [the API Platform Symfony variant](../symfony/index.md). If you use it, you have nothing more to do, and you can skip to the next section. If you installed API Platform using another method (e.g., `composer require api`), you will need to set up the following: 1. A [Mercure hub](https://mercure.rocks/docs/getting-started). 2. One of the following, depending on your framework: - For Symfony users: the [MercureBundle](https://symfony.com/doc/current/mercure.html). - For Laravel users: the [Laravel Mercure Broadcaster](https://github.com/mvanduijker/laravel-mercure-broadcaster). ## Pushing the API Updates Use the `mercure` attribute to hint API Platform that it must dispatch the updates regarding the given resources to the Mercure hub: ```php ]+)>;\s*rel="mercure"/); const hubUrl = new URL(hubUrlString); hubUrl.searchParams.append("topic", book["@id"]); // Mercure 0.x const eventSource = new EventSource(hubUrl); eventSource.onmessage = (event) => { console.log(JSON.parse(event.data)); }; ``` If your hub speaks the Mercure 1.0 protocol, subscribe with `match` instead of `topic`: ```javascript hubUrl.searchParams.append("match", book["@id"]); // Mercure 1.0 ``` To subscribe to every book instead of a single one, 1.0 hubs also accept `match_urlpattern`, with a [URL Pattern](https://mercure.rocks/docs/1.0/concepts/topics-and-matchers) matching the resources' IRIs: ```javascript hubUrl.searchParams.append("match_urlpattern", "https://api.example.com/books/:id"); // Mercure 1.0 ``` `match_urlpattern` has no 0.x equivalent: under 0.x, subscribing to a family of resources at once means either subscribing to each IRI individually, or using the alternate-topic technique described below. See the [Mercure protocol reference](https://mercure.rocks/docs/1.0/reference/protocol) (1.0) or [the spec's subscribers section](https://mercure.rocks/spec#subscribers) (0.x) for the full `topic`/`match`/`match_urlpattern` semantics. ## Dispatching Private Updates (Authorized Mode) Mercure allows dispatching [private updates, that will be received only by authorized clients](https://mercure.rocks/spec#authorization). To receive this kind of updates, the client must hold a JWT containing at least one _target selector_ matched by the update. Then, use options to mark the published updates as privates: ```php true])] class Book { // ... } ``` It's also possible to execute an _expression_ (using the [Symfony Expression Language component](https://symfony.com/doc/current/components/expression_language.html)), to generate the options dynamically: ```php true]; // ... } ``` ## Available Options In addition to `private`, the following options are available: - `topics`: the list of topics of this update, if not the resource IRI is used - `data`: the content of this update, if not set the content will be the serialization of the resource using the default format - `id`: the SSE ID of this event, if not set the ID will be generated by the Mercure Hub - `type`: the SSE type of this event, if not set this field is omitted - `retry`: the `retry` field of the SSE, if not set this field is omitted - `normalization_context`: the specific normalization context to use for the update. ## Dispatching Restrictive Updates (Security Mode) Use `iri` (iriConverter) and `escape` (rawurlencode) functions to add an alternative topic, in order to restrict a subscriber with `topic_selector` to receive only publications that are authorized (partner match). > Let's say that a subscriber wants to receive updates concerning all book resources it has access > to. The subscriber can use the topic selector `https://example.com/books/{id}` as value of the > topic query parameter. Adding this same URI template to the mercure.subscribe claim of the JWS > presented by the subscriber to the hub would allow this subscriber to receive all updates for all > book resources. It is not what we want here: this subscriber is only authorized to access some of > these resources. > > To solve this problem, the mercure.subscribe claim could contain a topic selector such as: > `https://example.com/users/foo/{?topic}`. > > The publisher could then take advantage of the previously described behavior by publishing a > private update having `https://example.com/books/1` as canonical topic and > `https://example.com/users/foo/?topic=https%3A%2F%2Fexample.com%2Fbooks%2F1` as alternate topic. > > —[https://mercure.rocks/spec#subscribers](https://mercure.rocks/spec#subscribers) Below is an example using the `topics` option: ```php true, // the '@=' prefix is required when using expressions for arguments in topics 'topics' => [ '@=iri(object)', '@=iri(object.getOwner()) ~ "/?topic=" ~ escape(iri(object))', '@=iri(object, '.UrlGeneratorInterface::ABS_PATH.')', // you can also change the reference type 'https://example.com/books/1', ], ], )] class Book { private ?User $owner; public function getOwner(): ?User { return $this->owner; } } ``` Using an _expression_ function: ```php true, 'topics' => [$topic1, $topic2, $topic3, $topic4], ]; } public function getOwner(): ?User { return $this->owner; } } ``` In this case, the JWT Token for the subscriber should contain: ```json { "mercure": { "subscribe": ["https://example.com/users/foo/{?topic}"] } } ``` The subscribe topic should be: `https://example.com/books/{id}`