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.

API プラットフォームは、Mercure プロトコルを使用して、API によって公開されたリソースの変更されたバージョンを、現在接続されているクライアント (Web アプリケーション、モバイル アプリケーションなど) に自動的にプッシュできます。

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

—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).

API プラットフォームは、Doctrine エンティティに加えられた変更を検出し、更新されたリソースを Mercure ハブに送信します。次に、Mercure ハブは、Server-sent Events (SSE) を使用して、接続されているすべてのクライアントに更新をディスパッチします。

Mercure subscriptions

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.

メルキュール サポートは、API プラットフォーム ディストリビューションで既にインストール、構成、および有効化されています。ディストリビューションを使用する場合は、何もする必要がなく、次のセクションにスキップできます。

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.

別の方法 (composer require api など) を使用して API Platform をインストールした場合は、Mercure ハブと Symfony MercureBundle をインストールする必要があります。

Learn how to install and configure MercureBundle manually on the Symfony website

Symfony Web サイトで MercureBundle を手動でインストールして構成する方法を学ぶ

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:

Mercure 属性を使用して、特定のリソースに関する更新を Mercure ハブにディスパッチする必要があることを API プラットフォームに通知します。

<?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.

次に、このタイプのオブジェクトが作成、更新、または削除されるたびに、新しいバージョンが Mercure ハブを介して接続されているすべてのクライアントに送信されます。リソースが削除されている場合は、リソースの (現在削除されている) IRI のみがに送信されます。クライアント。

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.

さらに、API プラットフォームは、このリソース クラスに関連するすべての応答に Link HTTP ヘッダーを自動的に追加します。このヘッダーにより、スマート クライアントは Mercure ハブを自動的に検出できます。

Mercure subscriptions

Clients generated using Create Client will use this capability to automatically subscribe to Mercure updates when available:

クライアントの作成を使用して生成されたクライアントは、この機能を使用して、Mercure の更新が利用可能になったときに自動的にサブスクライブします。

Screencast

Learn how to use the discovery capabilities of Mercure in your own clients.

自社のクライアントで Mercure の検出機能を使用する方法を学びます。

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.

Mercure では、許可されたクライアントのみが受信する非公開の更新をディスパッチできます。この種の更新を受信するには、更新に一致するターゲット セレクターを少なくとも 1 つ含む JWT をクライアントが保持する必要があります。

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:

オプションを動的に生成するために、(Symfony Expression Language コンポーネントを使用して) 式を実行することもできます。

<?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 format
    data: この更新のコンテンツ。設定されていない場合、コンテンツはデフォルト形式を使用したリソースのシリアル化になります
  • id: the SSE ID of this event, if not set the ID will be generated by the Mercure Hub
    id: このイベントの SSE ID。設定されていない場合、ID は Mercure Hub によって生成されます
  • type: the SSE type of this event, if not set this field is omitted
    type: このイベントの SSE タイプ。設定されていない場合、このフィールドは省略されます
  • retry: the retry field of the SSE, if not set this field is omitted
    retry: 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).

iri (iriConverter) およびエスケープ (rawurlencode) 関数を使用して代替トピックを追加し、topic_selector を使用してサブスクライバーが許可されたパブリケーションのみを受信するように制限します (パートナー マッチ)。

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:

以下は、topics オプションを使用した例です。

<?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:

この場合、サブスクライバーの JWT トークンには以下が含まれている必要があります。

{
  "mercure": {
    "subscribe": ["https://example.com/users/foo/{?topic}"]
  }
}

The subscribe topic should be: https://example.com/books/{id}

サブスクライブのトピックは次のとおりです:https://example.com/books/{id}