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.
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.
Mercure は、便利で高速、信頼性が高く、バッテリー効率の良い方法で、データの更新を Web ブラウザーやその他の HTTP クライアントにプッシュできるようにするプロトコルです。 Web API を介して提供されるリソースのリアルタイムの更新をリアクティブな Web およびモバイル アプリに公開することは特に便利です。—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).
Installing Mercure Support
Mercure support is already installed, configured and enabled in the API Platform distribution. If you use the distribution, you have nothing more to do, and you can skip to the next section.
If you have installed API Platform using another method (such as composer require api
), you need to install a Mercure hub and the Symfony MercureBundle.
Learn how to install and configure MercureBundle manually on the Symfony website
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
// api/src/Entity/Book.php
namespace App\Entity;
use ApiPlatform\Metadata\ApiResource;
#[ApiResource(mercure: true)]
class Book
{
// ...
}
Then, every time an object of this type is created, updated or deleted, the new version is sent to all connected clients through the Mercure hub. If the resource has been deleted, only the (now deleted) IRI of the resource is sent to the clients.
In addition, API Platform automatically adds a Link
HTTP header to all responses related to this resource class.
This header allows smart clients to automatically discover the Mercure hub.
Clients generated using Create Client will use this capability to automatically subscribe to Mercure updates when available:
Learn how to use the discovery capabilities of Mercure in your own clients.
Dispatching Private Updates (Authorized Mode)
Mercure allows dispatching private updates, that will be received only by authorized clients. 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
// api/src/Entity/Book.php
namespace App\Entity;
use ApiPlatform\Metadata\ApiResource;
#[ApiResource(mercure: ['private' => true])]
class Book
{
// ...
}
It's also possible to execute an expression (using the Symfony Expression Language component), to generate the options dynamically:
<?php
// api/src/Entity/Book.php
namespace App\Entity;
use ApiPlatform\Metadata\ApiResource;
#[ApiResource(mercure: 'object.mercureOptions')]
class Book
{
public $mercureOptions = ['private' => 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トピック: この更新のトピックのリスト。リソース IRI が使用されていない場合data
: the content of this update, if not set the content will be the serialization of the resource using the default formatdata: この更新のコンテンツ。設定されていない場合、コンテンツはデフォルト形式を使用したリソースのシリアル化になりますid
: the SSE ID of this event, if not set the ID will be generated by the Mercure Hubid: このイベントの SSE ID。設定されていない場合、ID は Mercure Hub によって生成されますtype
: the SSE type of this event, if not set this field is omittedtype: このイベントの SSE タイプ。設定されていない場合、このフィールドは省略されますretry
: theretry
field of the SSE, if not set this field is omittedretry: SSE の再試行フィールド。設定されていない場合、このフィールドは省略されますnormalization_context
: the specific normalization context to use for the update.normalization_context: 更新に使用する特定の正規化コンテキスト。
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.
サブスクライバーが、アクセスできるすべての書籍リソースに関する最新情報を受け取りたいとします。サブスクライバーはトピック セレクター https://example.com/books/{id} をトピック クエリ パラメーターの値として使用できます。この同じ URI テンプレートを、サブスクライバーがハブに提示する JWS の mercure.subscribe クレームに追加すると、このサブスクライバーがすべてのブック リソースのすべての更新を受信できるようにします。ここで必要なのは、このサブスクライバーがこれらのリソースの一部へのアクセスのみを許可されていることです。To solve this problem, the mercure.subscribe claim could contain a topic selector such as: https://example.com/users/foo/{?topic}.
この問題を解決するには、mercure.subscribe クレームに 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://example.com/books/1 を正規のトピックとし、https://example.com/users/foo/?topic=https%3A を持つ非公開の更新を発行することで、前述の動作を利用できます。 %2F%2Fexample.com%2Fbooks%2F1 を代替トピックとして。—https://mercure.rocks/spec#subscribers
—https://mercure.rocks/spec#subscribers
Below is an example using the topics
option:
<?php
// api/src/Entity/Book.php
namespace App\Entity;
use ApiPlatform\Metadata\ApiResource;
use ApiPlatform\Api\UrlGeneratorInterface;
use App\Entity\User;
#[ApiResource(
mercure: [
'private' => 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
// api/src/Entity/Book.php
namespace App\Entity;
use ApiPlatform\Metadata\ApiResource;
use App\Entity\User;
#[ApiResource(
mercure: 'object.getMercureOptions()',
)]
class Book
{
private ?User $owner;
public function getMercureOptions(): array
{
// the '@=' prefix is required when using expressions for arguments in topics
$topic1 = '@=iri(object)';
$topic2 = '@=iri(object.getOwner()) ~ "/?topic=" ~ escape(iri(object))';
$topic3 = '@=iri(object, '.UrlGeneratorInterface::ABS_PATH.')'; // you can also change the reference type
$topic4 = 'https://example.com/books/1';
return [
'private' => true,
'topics' => [$topic1, $topic2, $topic3, $topic4],
];
}
public function getOwner(): ?User
{
return $this->owner;
}
}
In this case, the JWT Token for the subscriber should contain:
{
"mercure": {
"subscribe": ["https://example.com/users/foo/{?topic}"]
}
}
The subscribe topic should be:
https://example.com/books/{id}