Pages API を使うと、自動化を構築し、Pages を開発ワークフローに組み込めます。大まかには、API エンドポイントでデプロイとビルドの管理、プロジェクトの設定ができます。ヘッドレス CMS のデプロイには、Cloudflare の Deploy Hooks も使えます。オブジェクトの種類とエンドポイントの一覧は、API ドキュメント ↗ を参照してください。
API トークンを作成する手順は次のとおりです。
-
Cloudflare ダッシュボードで Account API tokens ページを開きます。
Account API tokens を開く ↗ -
Create Token を選択します。
-
Edit Cloudflare Workers テンプレート > Use template を選ぶか、Create Custom Token > Get started を選びます。カスタムトークンを作る場合は、Cloudflare Pages の権限に Edit アクセスを追加してください。
トークンを作成したら、リクエストヘッダーに API トークンを付けて認証し、API へリクエストできます。たとえば、次はプロジェクト内のすべてのデプロイを取得する API リクエストです。
Required API token permissions
At least one of the following token permissions is required:Pages ReadPages Write
curl "https://api.cloudflare.com/client/v4/accounts/$ACCOUNT_ID/pages/projects/$PROJECT_NAME/deployments" \
--request GET \
--header "Authorization: Bearer $CLOUDFLARE_API_TOKEN"{account_id}、{project_name}、<API_TOKEN> を自分のプロジェクトの値に置き換えて試してください。詳細は アカウント ID の確認 を参照してください。
API は Cloudflare Workers と組み合わせるとさらに便利です。Workers は Cloudflare のグローバルネットワーク上でサーバーレス関数をデプロイする最も簡単な方法です。次のセクションでは、Pages API の使い方を示す 3 つのコード例を紹介します。これらのサンプルのビルドとデプロイは、はじめにガイド を参照してください。
ライブソースからデータを取得して静的出力を組み立てる CMS があるとします。API で定期的に新しいビルドを起動すれば、静的コンテンツをできるだけ新しく保てます。
const endpoint =
"https://api.cloudflare.com/client/v4/accounts/{account_id}/pages/projects/{project_name}/deployments";
export default {
async scheduled(_, env) {
const init = {
method: "POST",
headers: {
"Content-Type": "application/json;charset=UTF-8",
// We recommend you store the API token as a secret using the Workers dashboard or using Wrangler as documented here: https://developers.cloudflare.com/workers/wrangler/commands/general/#secret
Authorization: `Bearer ${env.API_TOKEN}`,
},
};
await fetch(endpoint, init);
},
};JavaScript Worker をデプロイしたあと、このスクリプトを定期実行する Cron Trigger を Worker に設定します。詳細は Cron Triggers を参照してください。
Cloudflare Pages は、プロジェクトのすべてのデプロイをプレビューリンクでホストして配信します。プロジェクトを非公開にし、古いデプロイへのアクセスを防ぎたい場合があります。API で 1 か月後にデプロイを削除すれば、公開されなくなります。ブランチの最新デプロイは削除できません。
const endpoint =
"https://api.cloudflare.com/client/v4/accounts/{account_id}/pages/projects/{project_name}/deployments";
const expirationDays = 7;
export default {
async scheduled(_, env) {
const init = {
headers: {
"Content-Type": "application/json;charset=UTF-8",
// We recommend you store the API token as a secret using the Workers dashboard or using Wrangler as documented here: https://developers.cloudflare.com/workers/wrangler/commands/general/#secret
Authorization: `Bearer ${env.API_TOKEN}`,
},
};
const response = await fetch(endpoint, init);
const deployments = await response.json();
for (const deployment of deployments.result) {
// Check if the deployment was created within the last x days (as defined by `expirationDays` above)
if (
(Date.now() - new Date(deployment.created_on)) / 86400000 >
expirationDays
) {
// Delete the deployment
await fetch(`${endpoint}/${deployment.id}`, {
method: "DELETE",
headers: {
"Content-Type": "application/json;charset=UTF-8",
Authorization: `Bearer ${env.API_TOKEN}`,
},
});
}
}
},
};JavaScript Worker をデプロイしたあと、このスクリプトを定期実行する Cron Trigger を Worker に設定できます。詳細は Cron Triggers ガイド を参照してください。
Pages で Web サイトを作っている開発チームに所属しているとします。Cloudflare アカウントを共有せずに、デプロイのプレビューリンクとビルド状況を簡単に共有したいでしょう。API を使えば、デプロイ状況やプレビューリンクを含むプロジェクト情報を簡単に共有し、Cloudflare Worker から HTML として配信できます。
const deploymentsEndpoint =
"https://api.cloudflare.com/client/v4/accounts/{account_id}/pages/projects/{project_name}/deployments";
const projectEndpoint =
"https://api.cloudflare.com/client/v4/accounts/{account_id}/pages/projects/{project_name}";
export default {
async fetch(request, env) {
const init = {
headers: {
"content-type": "application/json;charset=UTF-8",
// We recommend you store the API token as a secret using the Workers dashboard or using Wrangler as documented here: https://developers.cloudflare.com/workers/wrangler/commands/general/#secret
Authorization: `Bearer ${env.API_TOKEN}`,
},
};
const style = `body { padding: 6em; font-family: sans-serif; } h1 { color: #f6821f }`;
let content = "<h2>Project</h2>";
let response = await fetch(projectEndpoint, init);
const projectResponse = await response.json();
content += `<p>Project Name: ${projectResponse.result.name}</p>`;
content += `<p>Project ID: ${projectResponse.result.id}</p>`;
content += `<p>Pages Subdomain: ${projectResponse.result.subdomain}</p>`;
content += `<p>Domains: ${projectResponse.result.domains}</p>`;
content += `<a href="${projectResponse.result.canonical_deployment.url}"><p>Latest preview: ${projectResponse.result.canonical_deployment.url}</p></a>`;
content += `<h2>Deployments</h2>`;
response = await fetch(deploymentsEndpoint, init);
const deploymentsResponse = await response.json();
for (const deployment of deploymentsResponse.result) {
content += `<a href="${deployment.url}"><p>Deployment: ${deployment.id}</p></a>`;
}
let html = `
<!DOCTYPE html>
<head>
<title>Example Pages Project</title>
</head>
<body>
<style>${style}</style>
<div id="container">
${content}
</div>
</body>`;
return new Response(html, {
headers: {
"Content-Type": "text/html;charset=UTF-8",
},
});
},
};