📌

Drupal: カスタムRESTリソースを作成する

2023/04/20に公開

概要

以下を参考に、カスタムRESTリソースを作成しました。

https://www.drupal.org/docs/drupal-apis/restful-web-services-api/custom-rest-resources

上記の記事の通り進めることで、以下のURLから、JSONの結果を得ることができました。

/demo_rest_api/demo_resource

{
  "message": "Hello, this is a rest service"
}

REST UIモジュール

上記の記事において、以下の記載がありました。

If you are using the REST UI contrib module, you should now be able to see it in the list of available endpoints and you should be able to configure the GET method.

この点については、以下の記事を参考に、REST UIモジュールを有効化しました。

https://www.studio-umi.jp/blog/12/357

IIIF Presentation APIの試作

次に、コンテンツ毎にJSON作成に取り組みます。具体的には、/iiif/3/{id}/manifestというパスにアクセスすると、IIIF Presentation API v3に基づく情報を出力するようにしてみます。

以下の記事が参考になりました。

https://medium.com/drupaljournal/create-custom-rest-resource-for-get-and-post-method-in-drupal-8-e445330be3ff

以下のようなファイルを作成します。以下の例では、とりあえず$nodeからtitleを取得しています。これを応用することで、他のフィールドの情報も取得することができそうです。

/home/bitnami/stack/drupal/modules/custom/demo_rest_api/src/Plugin/rest/resource/Presentation3.php
<?php
namespace Drupal\demo_rest_api\Plugin\rest\resource;
use Drupal\node\Entity\Node;
use Drupal\node\NodeInterface;
use Drupal\rest\Plugin\ResourceBase;
use Drupal\rest\ResourceResponse;
/**
 * Annotation for get method
 *
 * @RestResource(
 *   id = "iiif_presentation_3",
 *   label = @Translation("IIIF Presentation API v3"),
 *   uri_paths = {
 *     "canonical" = "/iiif/3/{id}/manifest"
 *   }
 * )
 */
class Presentation3 extends ResourceBase {
/**
   * Responds to GET requests. It will return serialize json format of node
   * object.
   *
   * @param $id
   *   Node id.
   */
  public function get($id) {
    if ($id) {
      // Load node
      $node = Node::load($id);
      if ($node instanceof NodeInterface) {

        $manifest = [
            "@context" => "http://iiif.io/api/presentation/3/context.json",
            "type" => "Manifest",
            "label" => [
                "none" => [
                    $node->get("title")[0]->get("value")->getValue()
                ]
            ]
        ];

        $response = new ResourceResponse($manifest);
        // Configure caching for results
        if ($response instanceof CacheableResponseInterface) {
          $response->addCacheableDependency($node);
        }
        return $response;
      }
      return new ResourceResponse('Article doesn\'t exist', 400);
    }
    return new ResourceResponse('Article Id is required', 400);
  }
}

パーミッションの許可

以下のページで、Anonymous userにチェックを入れて、外部からのアクセスを許可します。

/admin/people/permissions#module-rest

結果、/iiif/3/5070/manifestのようなURLにアクセスすることで、非ログインユーザでも、以下のようなjsonファイルを取得することができました。

{
  "@context": "http://iiif.io/api/presentation/3/context.json",
  "type": "Manifest",
  "label": {
    "none": [
      "中村覚"
    ]
  }
}

まとめ

DrupalでカスタムRESTリソースを作成する一例を紹介しました。カスタムリソースを作成する際の参考になりましたら幸いです。

また引き続きIIIF Presentation APIに関する実装を進めて、Omeka SのIIIF Serverと同様のモジュールを作成したいと思います。

Discussion