LoginSignup
1
2

More than 5 years have passed since last update.

Drupal8 カスタムREST API ~ POST編 ~

Posted at
1 / 2

Drupal8でカスタムのREST APIの作成方法を説明します。

まず、RESTful Web ServicesREST UI の2つのモジュールを利用して、
GUIよりREST APIを定義できるようにインストールします。
詳しくは以下のサイトを参考してください。
https://drupal.studio-umi.jp/blog/drupal8-restui

1.モジュールの設定

新しいディレクトリを作成し、そのモジュールの情報ファイルを追加します。
/modules/custom/sample_rest_api

例:sample_rest_api.info.yml

sample_rest_api.info.yml
name: Sample Rest API
description: sample rest api taxonomy.
package: Custom
type: module
core: 8.x
dependencies:
  - rest

2. リソースプラグインの作成

RESTモジュールでプラグインを実装するために新しいディレクトリを作成し、
ファイルを追加します。
sample_rest_api/src/Plugin/rest/resource/

新しいファイル:SampleResource.php

SampleResource.php
<?php

namespace Drupal\sample_rest_api\Plugin\rest\resource;

use Drupal\rest\Plugin\ResourceBase;
use Drupal\rest\ResourceResponse;

/**
 * Provides a Sample Resource
 *
 * @RestResource(
 *   id = "sample_resource",
 *   label = @Translation("Sample resource"),
 *   uri_paths = {
 *     "canonical" = "/api/sample_resource",
 *     "https://www.drupal.org/link-relations/create" = "/api/sample_resource"
 *   }
 * )
 */
class SampleResource extends ResourceBase
{
   /**
    * Responds to POST requests.
    */
    public function post() {
        return new ResourceResponse("REST State POST!");
    }

}

3.RESTリソースの設定

RESTリソースを設定していくために、新しくディレクトリを作成し、
設定ファイルを追加します。
sample_rest_api/config/install/

新しいファイル:rest.resource.sample_rest_api.yml

rest.resource.sample_rest_api.yml
id: sample_rest_api
plugin_id: sample_rest_api
granularity: method
configuration:
  POST:
    supported_formats:
      - hal_json
      - json
    supported_auth:
      - basic_auth
      - cookie

REST API用のモジュール作成が完了したら、モジュールをインストールして、
RESTリソースと権限の設定を行います。

~ APIを叩く ~

Chrome拡張機能のDHC - REST/HTTP API Client を使って検証していきます。
ヘッダー情報の設定を以下のようにします。
Content-Typeapplication/hal+json
X-CSRF-Token:XXXXXCSRFトークン

APIを叩くと以下のように結果が返ってきます。
METHOD:POST
URL:/api/sample_resource

{
 'REST State POST!'
}

【CSRFトークン】
注意点として、リソースの登録・更新・削除を行う際にリクエストにX-CSRF-TokenヘッダーにCSRFトークンを付与する必要があります。
CSRFトークンは/rest/session/tokenにリクエストを送信することで取得できます。

1
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
2