Craft CMS の Element API で search パラメータで検索できるようにする

Craft CMS の Element API で search=foo のようなパラメータを付けて検索して結果を絞り込む方法をご紹介します。

Craft CMS Logo

Craft CMS では、自分で自由にエンドポイントを実装できる Element API というプラグインがあります。Twig のテンプレートで JSON を書き出すようにして、擬似的に API を実装することもできますが、こちらの Element API を使った方が楽に実装できるのでおすすめです。

さて、今回は、この Element API で search=foo のようなパラメータを付けて検索して結果を絞り込む方法をご紹介します。

Element API で Entries を取得する

Element API の詳細の使い方はプラグインページの README を見ていただくとして、シンプルに Entries のデータを取得したいときは、下記のように定義します。

return [
 'endpoints' => [
 'client.json' => [
 'elementType' => ElementType::Entry,
 'criteria' => [
 'section' => 'client',
 'order' => 'title',
 ],
 'transformer' => function(EntryModel $entry) {
 requireLogin();
 return [
 'title' => $entry->title,
 'id' => $entry->id,
 'url' => $entry->url,
 ];
 },
 ]
 ]
];

これで、 https://your-host/client.json にアクセスすると client というセクションのエントリーが返ってきます。

search パラメータで検索する

これを search パラメータで検索させるには、 criteria に下記のコードを加えます。

'search' => craft()->request->getParam('search'),

全体を見ると下記のとおりです。

return [
 'endpoints' => [
 'client.json' => [
 'elementType' => ElementType::Entry,
 'criteria' => [
 'section' => 'client',
 'order' => 'title',
 'search' => craft()->request->getParam('search'),
 ],
 'transformer' => function(EntryModel $entry) {
 requireLogin();
 return [
 'title' => $entry->title,
 'id' => $entry->id,
 'url' => $entry->url,
 ];
 },
 ]
 ]
];

これで、

https://your-host/client.json?search=tinybeans

のようにリクエストすると、 tinybeans で検索して絞り込まれた値が返ってきます。

もし検索するフィールドを title だけにしたいときは、

https://your-host/client.json?search=title:tinybeans

とすればOKです。

簡単ですが、以上です。

【追記:2017-11-10】

コード中の getRequiredQuerygetParam に修正しました。 getRequiredQuery だとパラメータが必須扱いになり、パラメータがないと 400 エラーが返ってきます。

Published 2017-11-09
Updated 2019-06-25