JavaScript・PHP から REST API を呼ぶ


この機能は Ver. 3.3.0 で追加予定の、リリース前の機能です

このページは、アルファ版(Ver. 3.3.0-alpha.1)時点の内容です。正式版までに仕様や設定項目が変わる可能性があります。本番サイトでは使わず、検証環境でお試しください。

サーバーやバッチ処理から REST API を呼ぶ例です。どちらも、トークンとベースの URL を環境変数で受け取ります。トークンをコードに直接書かないでください。

環境変数

値の例

ACMS_API_BASE

https://example.com/rest-api/acms/v1(末尾の / は付けない)

ACMS_API_TOKEN

acms_ で始まるトークン

JavaScript(Node.js の fetch)

Node.js 18 以降の組み込みの fetch を使います。追加のパッケージは要りません。ファイル名は acms-api.mjs とします。

// acms-api.mjs
// 使い方: ACMS_API_BASE=https://example.com/rest-api/acms/v1 ACMS_API_TOKEN=acms_... node acms-api.mjs
import { randomUUID } from 'node:crypto';

const BASE = process.env.ACMS_API_BASE; // 末尾の / は付けない
const TOKEN = process.env.ACMS_API_TOKEN;

class AcmsApiError extends Error {
  constructor(problem) {
    super(`${problem.status} ${problem.code}: ${problem.title}`);
    this.problem = problem;
  }
}

async function request(method, path, { query, body, headers = {} } = {}, retry = 0) {
  const url = new URL(`${BASE}${path}`);
  for (const [key, value] of Object.entries(query ?? {})) {
    url.searchParams.set(key, String(value));
  }
  const response = await fetch(url, {
    method,
    headers: {
      Authorization: `Bearer ${TOKEN}`,
      Accept: 'application/json',
      ...(body !== undefined ? { 'Content-Type': 'application/json' } : {}),
      ...headers,
    },
    body: body !== undefined ? JSON.stringify(body) : undefined,
  });

  // 429 は Retry-After の秒数だけ待って、3 回まで送り直す
  if (response.status === 429 && retry < 3) {
    const wait = Number(response.headers.get('Retry-After') ?? '1');
    await new Promise((resolve) => setTimeout(resolve, wait * 1000));
    return request(method, path, { query, body, headers }, retry + 1);
  }
  if (response.status === 204) {
    return { status: 204, headers: response.headers, data: null };
  }
  const data = await response.json();
  if (!response.ok) {
    // application/problem+json。分岐には status と code を使う
    throw new AcmsApiError(data);
  }
  return { status: response.status, headers: response.headers, data };
}

// 一覧を links.next でたどって全件を取り出す
async function* listAll(path, query = {}) {
  let next = null;
  let page = await request('GET', path, { query: { ...query, limit: 100 } });
  while (true) {
    yield* page.data.items;
    next = page.data.links.next;
    if (!next) break;
    const url = new URL(next);
    page = await request('GET', url.pathname.replace(new URL(BASE).pathname, ''), {
      query: Object.fromEntries(url.searchParams),
    });
  }
}

try {
  const me = await request('GET', '/me/');
  console.log('トークンの持ち主:', me.data.user.name, 'スコープ:', me.data.scopes.join(' '));

  for await (const entry of listAll('/entries/', { status: 'draft', fields: 'id,title' })) {
    console.log('下書き:', entry.id, entry.title);
  }

  const created = await request('POST', '/entries/', {
    headers: { 'Idempotency-Key': randomUUID() },
    body: {
      title: 'fetch から作成したエントリー',
      status: 'draft',
      body_html: '<p>fetch で送った本文です。</p>',
    },
  });
  console.log('作成しました:', created.data.id, created.headers.get('Location'));
} catch (error) {
  if (error instanceof AcmsApiError) {
    console.error(error.message);
    for (const item of error.problem.errors ?? []) {
      console.error(' -', item.pointer ?? item.parameter, item.code, item.detail);
    }
    process.exitCode = 1;
  } else {
    throw error;
  }
}
ACMS_API_BASE=https://example.com/rest-api/acms/v1 ACMS_API_TOKEN=acms_xxxxxxxx node acms-api.mjs

実行すると、トークンの持ち主とスコープ、下書きのエントリーの一覧を表示し、下書きのエントリーを 1 件作ります。サイトに必須のカスタムフィールドがあるなど、入力の誤りがあると、次のように errors を表示して終わります。

422 validation_failed: 入力内容にエラーがあります。
 - #/fields/event_date required このカスタムフィールドは入力が必要です。
  • エラーの判定は response.ok と、本文の code で行います。title の文言では分岐しません。

  • 一覧は links.next をたどって全件を読みます。limit は最大の 100 にしています。

  • 作成には Idempotency-Key(crypto.randomUUID())を付けています。通信の失敗で送り直すときは、同じキーを使ってください。

ブラウザの JavaScript から呼ばないでください

この例はサーバー(Node.js)で動かすものです。トークンを公開側のページに置くと、そのユーザーの権限で誰でも操作できてしまいます。REST API は CORS のヘッダーを出さないため、別のオリジンのページからは呼べません。管理画面に組み込むプラグインの JavaScript から呼ぶ方法は、プラグインから REST API を拡張する を参照してください。

PHP(curl 拡張)

PHP 8.3〜8.5 の curl 拡張で動きます。画像をメディアとして登録し、そのメディアを使ったユニットの本文で下書きのエントリーを作ります。ファイル名は acms-api.php とします。

<?php
// acms-api.php
// 使い方: ACMS_API_BASE=https://example.com/rest-api/acms/v1 ACMS_API_TOKEN=acms_... php acms-api.php photo.jpg

declare(strict_types=1);

$base = rtrim((string) getenv('ACMS_API_BASE'), '/');
$token = (string) getenv('ACMS_API_TOKEN');
$imagePath = $argv[1] ?? '';

/**
 * REST API を呼んで [ステータス, 本文の配列, ヘッダーの配列] を返す
 *
 * @param array<string, mixed>|null $json JSON で送る本文
 * @param array<string, mixed>|null $multipart multipart/form-data で送る項目(ファイルは CURLFile)
 * @param array<string, string> $headers 追加のヘッダー
 * @return array{0: int, 1: array<string, mixed>|null, 2: array<string, string>}
 */
function acmsApi(string $method, string $url, string $token, ?array $json = null, ?array $multipart = null, array $headers = []): array
{
    $curl = curl_init($url);
    $requestHeaders = ['Authorization: Bearer ' . $token, 'Accept: application/json'];
    foreach ($headers as $name => $value) {
        $requestHeaders[] = $name . ': ' . $value;
    }
    if ($json !== null) {
        $requestHeaders[] = 'Content-Type: application/json';
        curl_setopt($curl, CURLOPT_POSTFIELDS, json_encode($json, JSON_UNESCAPED_UNICODE | JSON_THROW_ON_ERROR));
    } elseif ($multipart !== null) {
        // Content-Type(multipart/form-data; boundary=...)は curl が付ける
        curl_setopt($curl, CURLOPT_POSTFIELDS, $multipart);
    }
    $responseHeaders = [];
    curl_setopt_array($curl, [
        CURLOPT_CUSTOMREQUEST => $method,
        CURLOPT_HTTPHEADER => $requestHeaders,
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_HEADERFUNCTION => static function ($curl, string $line) use (&$responseHeaders): int {
            $parts = explode(':', $line, 2);
            if (count($parts) === 2) {
                $responseHeaders[strtolower(trim($parts[0]))] = trim($parts[1]);
            }
            return strlen($line);
        },
    ]);
    $body = curl_exec($curl);
    if ($body === false) {
        throw new RuntimeException(curl_error($curl));
    }
    $status = (int) curl_getinfo($curl, CURLINFO_RESPONSE_CODE);
    $data = $body === '' ? null : json_decode($body, true, 512, JSON_THROW_ON_ERROR);
    return [$status, $data, $responseHeaders];
}

// 1. 画像をメディアとして登録する
[$status, $media] = acmsApi('POST', $base . '/media/', $token, null, [
    'file' => new CURLFile($imagePath),
    'alt' => 'PHP から登録した画像',
]);
if ($status !== 201) {
    fwrite(STDERR, "メディアの登録に失敗しました: {$status} {$media['code']}\n");
    exit(1);
}
echo "メディア ID: {$media['id']}\n";

// 2. 見出し・段落・画像のユニットでエントリーを作る(下書き)
[$status, $entry, $headers] = acmsApi('POST', $base . '/entries/', $token, [
    'title' => 'PHP から作成したエントリー',
    'status' => 'draft',
    'units' => [
        ['type' => 'text', 'attributes' => ['text_tag' => 'h2', 'text_text' => '見出し']],
        ['type' => 'text', 'attributes' => ['text_tag' => 'p', 'text_text' => '本文です。']],
        ['type' => 'media', 'attributes' => ['media_id' => (string) $media['id']]],
    ],
], null, ['Idempotency-Key' => bin2hex(random_bytes(16))]);

if ($status !== 201) {
    fwrite(STDERR, "エントリーの作成に失敗しました: {$status} {$entry['code']}\n");
    foreach ($entry['errors'] ?? [] as $error) {
        fwrite(STDERR, " - {$error['pointer']} {$error['code']} {$error['detail']}\n");
    }
    exit(1);
}
echo "エントリー ID: {$entry['id']}({$headers['location']})\n";
ACMS_API_BASE=https://example.com/rest-api/acms/v1 ACMS_API_TOKEN=acms_xxxxxxxx php acms-api.php photo.jpg
メディア ID: 38
エントリー ID: 248(https://example.com/rest-api/acms/v1/entries/248/)
  • メディアのアップロードは CURLFile を CURLOPT_POSTFIELDS に渡します。Content-Type: multipart/form-data は curl が boundary 付きで付けるため、自分では付けません。

  • ユニットの attributes の値は文字列です。メディア ID も (string) で文字列にしています。

  • 応答の Location ヘッダーは、ヘッダーの関数で小文字のキーにして取り出しています。

よくある質問・つまずき

Node.js で SSL の証明書のエラーになります

開発環境の自己署名の証明書などで起きます。本番では正しい証明書を使ってください。NODE_TLS_REJECT_UNAUTHORIZED=0 のような検証を無効にする設定を、本番のプログラムに入れないでください。PHP の CURLOPT_SSL_VERIFYPEER も同じです。

PHP で 401 missing_token になります

Authorization のヘッダーの書き方('Authorization: Bearer ' . $token)と、サイトの .htaccess の設定(REST API を有効にする)を確かめてください。

日本語が文字化けします

本文は UTF-8 の JSON で送ります。PHP では json_encode() に JSON_UNESCAPED_UNICODE を付けなくても正しく届きます(付けると読みやすくなるだけです)。