JavaScriptやNode.jsのアプリケーションからmicroCMSのAPIと簡単に通信できます。
このSDKの現在の保守レベルはActiveです。
詳細はSDKの保守方針をご覧ください。
公式ドキュメントの チュートリアルをご覧ください。
$ npm install microcms-js-sdk
または
$ yarn add microcms-js-sdkImportant
v3.0.0以上を使用する場合は、Node.jsのv18以上が必要です。
リリースページからmicrocms-js-sdk-x.y.z.tgzをダウンロードして解凍してください。その後、お好みのサーバーにアップロードして使用してください。対象ファイルは ./dist/umd/microcms-js-sdk.js です。
<scriptsrc="./microcms-js-sdk.js"></script>外部プロバイダーが提供するURLを読み込んでご利用ください。
<scriptsrc="https://cdn.jsdelivr.net/npm/microcms-js-sdk@3.1.1/dist/umd/microcms-js-sdk.min.js"></script>または
<scriptsrc="https://cdn.jsdelivr.net/npm/microcms-js-sdk/dist/umd/microcms-js-sdk.min.js"></script>Warning
ホスティングサービス(cdn.jsdelivr.net)はmicroCMSとは関係ありません。本番環境でのご利用には、お客様のサーバーでのセルフホスティングをお勧めします。
const{ createClient }=require('microcms-js-sdk');// CommonJSまたは
import{createClient}from'microcms-js-sdk';//ES6<script>const{ createClient }=microcms;</script>// クライアントオブジェクトを作成します。constclient=createClient({serviceDomain: 'YOUR_DOMAIN',// YOUR_DOMAINはXXXX.microcms.ioのXXXXの部分です。apiKey: 'YOUR_API_KEY',// retry: true // 最大2回まで再試行します。});以下の表は、microCMS JavaScript SDKの各メソッドがリスト形式のAPIまたはオブジェクト形式のAPI、どちらで使用できるかを示しています。
| メソッド | リスト形式 | オブジェクト形式 |
|---|---|---|
| getList | ✔️ | |
| getListDetail | ✔️ | |
| getObject | ✔️ | |
| getAllContentIds | ✔️ | |
| getAllContents | ✔️ | |
| create | ✔️ | |
| update | ✔️ | ✔️ |
| delete | ✔️ |
Note
- 「リスト形式」の✔️は、APIの型がリスト形式に設定されている場合に使用できるメソッドを示します。
- 「オブジェクト形式」の✔️は、APIの型がオブジェクト形式に設定されている場合に使用できるメソッドを示します。
getListメソッドは、指定されたエンドポイントからコンテンツ一覧を取得するために使用します。
client.getList({endpoint: 'endpoint',}).then((res)=>console.log(res)).catch((err)=>console.error(err));queriesプロパティを使用して、特定の条件に一致するコンテンツ一覧を取得できます。利用可能な各プロパティの詳細については、microCMSのドキュメントを参照してください。
client.getList({endpoint: 'endpoint',queries: {draftKey: 'abcd',limit: 100,offset: 1,orders: 'createdAt',q: 'こんにちは',fields: 'id,title',ids: 'foo',filters: 'publishedAt[greater_than]2021-01-01T03:00:00.000Z',depth: 1,}}).then((res)=>console.log(res)).catch((err)=>console.error(err));getListDetailメソッドは、指定されたエンドポイントから、IDで指定された単一コンテンツを取得するために使用します。
client.getListDetail({endpoint: 'endpoint',contentId: 'contentId',}).then((res)=>console.log(res)).catch((err)=>console.error(err));queriesプロパティを使用して、特定の条件に一致する単一コンテンツを取得できます。利用可能な各プロパティの詳細については、microCMSのドキュメントを参照してください。
client.getListDetail({endpoint: 'endpoint',contentId: 'contentId',queries: {draftKey: 'abcd',fields: 'id,title',depth: 1,}}).then((res)=>console.log(res)).catch((err)=>console.error(err));getObjectメソッドは、指定されたエンドポイントからオブジェクト形式のコンテンツを取得するために使用します。
client.getObject({endpoint: 'endpoint',}).then((res)=>console.log(res)).catch((err)=>console.error(err));getAllContentIdsメソッドは、指定されたエンドポイントからコンテンツIDのみを全件取得するために使用します。
client.getAllContentIds({endpoint: 'endpoint',}).then((res)=>console.log(res)).catch((err)=>console.error(err));filtersプロパティを使用することで、条件に一致するコンテンツIDを全件取得できます。
client.getAllContentIds({endpoint: 'endpoint',filters: 'category[equals]uN28Folyn',}).then((res)=>console.log(res)).catch((err)=>console.error(err));draftKeyプロパティを使用することで、下書き中のコンテンツのIDを全件取得できます。
client.getAllContentIds({endpoint: 'endpoint',draftKey: 'draftKey',}).then((res)=>console.log(res)).catch((err)=>console.error(err));alternateFieldプロパティにフィールドIDを指定することで、コンテンツID以外のフィールドの値を全件取得できます。
client.getAllContentIds({endpoint: 'endpoint',alternateField: 'url',}).then((res)=>console.log(res)).catch((err)=>console.error(err));getAllContentsメソッドは、指定されたエンドポイントから、コンテンツを全件取得するために使用します。
client.getAllContents({endpoint: 'endpoint',}).then((res)=>console.log(res)).catch((err)=>console.error(err));queriesプロパティを使用して、特定の条件に一致するすべてのコンテンツを取得できます。利用可能な各プロパティの詳細については、microCMSのドキュメントを参照してください。
client.getAllContents({endpoint: 'endpoint',queries: {filters: 'createdAt[greater_than]2021-01-01T03:00:00.000Z',orders: '-createdAt'},}).then((res)=>console.log(res)).catch((err)=>console.error(err));createメソッドは指定されたエンドポイントにコンテンツを登録するために使用します。
client.create({endpoint: 'endpoint',content: {title: 'タイトル',body: '本文',},}).then((res)=>console.log(res.id)).catch((err)=>console.error(err));contentIdプロパティを使用することで、指定されたIDでコンテンツを登録できます。
client.create({endpoint: 'endpoint',contentId: 'contentId',content: {title: 'タイトル',body: '本文',},}).then((res)=>console.log(res.id)).catch((err)=>console.error(err));isDraftプロパティを使用することで、下書き中のステータスでコンテンツを登録できます。
client.create({endpoint: 'endpoint',content: {title: 'タイトル',body: '本文',},isDraft: true,}).then((res)=>console.log(res.id)).catch((err)=>console.error(err));contentIdプロパティとisDraftプロパティを使用することで、指定されたIDかつ下書き中のステータスでコンテンツを登録できます。
client.create({endpoint: 'endpoint',contentId: 'contentId',content: {title: 'タイトル',body: '本文',},isDraft: true,}).then((res)=>console.log(res.id)).catch((err)=>console.error(err));isClosedプロパティを使用することで、公開終了のステータスでコンテンツを登録できます。
注:
isDraftとisClosedは同時にtrueにできません。両方をtrueで渡すと、SDK はランタイムでエラーとして拒否します。isClosed: trueを使う場合は、isDraftを省略、またはfalseを設定してください。
client.create({endpoint: 'endpoint',content: {title: 'タイトル',body: '本文',},isClosed: true,}).then((res)=>console.log(res.id)).catch((err)=>console.error(err));contentIdプロパティとisClosedプロパティを使用することで、指定されたIDかつ公開終了のステータスでコンテンツを登録できます。上記と同様、isDraft と isClosed を同時に true にすることはできません。
client.create({endpoint: 'endpoint',contentId: 'contentId',content: {title: 'タイトル',body: '本文',},isClosed: true,}).then((res)=>console.log(res.id)).catch((err)=>console.error(err));updateメソッドは特定のコンテンツを編集するために使用します。
client.update({endpoint: 'endpoint',contentId: 'contentId',content: {title: 'タイトル',},}).then((res)=>console.log(res.id)).catch((err)=>console.error(err));isDraft プロパティを指定することで、コンテンツを下書き状態で更新することができます。
client.update({endpoint: 'endpoint',contentId: 'contentId',content: {title: 'タイトル',},isDraft: true,}).then((res)=>console.log(res.id)).catch((err)=>console.error(err));APIの型がオブジェクト形式のコンテンツを編集する場合は、contentIdプロパティを使用せずに、エンドポイントのみを指定します。
client.update({endpoint: 'endpoint',content: {title: 'タイトル',},}).then((res)=>console.log(res.id)).catch((err)=>console.error(err));deleteメソッドは指定されたエンドポイントから特定のコンテンツを削除するために使用します。
client.delete({endpoint: 'endpoint',contentId: 'contentId',}).catch((err)=>console.error(err));getListメソッド、getListDetailメソッド、getObjectメソッドはデフォルトのレスポンスの型を定義しています。
typeContent={text: string,};/** * { * contents: Content[]; // 設定したスキーマの型を格納する配列 * totalCount: number; * limit: number; * offset: number; * } */client.getList<Content>({/* その他のプロパティ */})typeContent={text: string,};/** * { * id: string; * createdAt: string; * updatedAt: string; * publishedAt?: string; * revisedAt?: string; * text: string; // 設定したスキーマの型 * } */client.getListDetail<Content>({/* その他のプロパティ */})typeContent={text: string,};/** * { * createdAt: string; * updatedAt: string; * publishedAt?: string; * revisedAt?: string; * text: string; // 設定したスキーマの型 * } */client.getObject<Content>({/* その他のプロパティ */})/** * string[] */client.getAllContentIds({/* その他のプロパティ */})contentの型はContentであるため、型安全なコンテンツの登録が可能です。
typeContent={title: string;body?: string;};client.create<Content>({endpoint: 'endpoint',content: {title: 'タイトル',body: '本文',},});contentはPartial<Content>型であるため、編集したいプロパティだけを渡せます。
typeContent={title: string;body?: string;};client.update<Content>({endpoint: 'endpoint',content: {body: '本文',},});Next.jsのApp Routerで利用されるfetchのcacheオプションを指定できます。
指定可能なオプションは、Next.jsの公式ドキュメントを参照してください。
constresponse=awaitclient.getList({customRequestInit: {next: {revalidate: 60,},},endpoint: 'endpoint',});fetchリクエストを中断できます。
constcontroller=newAbortController();constresponse=awaitclient.getObject({customRequestInit: {signal: controller.signal,},endpoint: 'config',});setTimeout(()=>{controller.abort();},1000);const{ createManagementClient }=require('microcms-js-sdk');// CommonJSまたは
import{createManagementClient}from'microcms-js-sdk';//ES6<script>const{ createManagementClient }=microcms;</script>constclient=createManagementClient({serviceDomain: 'YOUR_DOMAIN',// YOUR_DOMAINはXXXX.microcms.ioのXXXXの部分です。apiKey: 'YOUR_API_KEY',});メディアに画像やファイルをアップロードできます。
// Blobimport{readFileSync}from'fs';constfile=readFileSync('path/to/file');client.uploadMedia({data: newBlob([file],{type: 'image/png'}),name: 'image.png',}).then((res)=>console.log(res)).catch((err)=>console.error(err));// or ReadableStreamimport{createReadStream}from'fs';import{Stream}from'stream';constfile=createReadStream('path/to/file');client.uploadMedia({data: Stream.Readable.toWeb(file),name: 'image.png',type: 'image/png',}).then((res)=>console.log(res)).catch((err)=>console.error(err));// or URLclient.uploadMedia({data: 'https://example.com/image.png',// name: 'image.png', ← 任意}).then((res)=>console.log(res)).catch((err)=>console.error(err));// Fileconstfile=document.querySelector('input[type="file"]').files[0];client.uploadMedia({data: file,}).then((res)=>console.log(res)).catch((err)=>console.error(err));// or URLclient.uploadMedia({data: 'https://example.com/image.png',// name: 'image.png', ← 任意}).then((res)=>console.log(res)).catch((err)=>console.error(err));typeUploadMediaRequest=|{data: File}|{data: Blob;name: string}|{data: ReadableStream;name: string;type: `image/${string}` }|{data: URL|string;name?: string|null|undefined;customRequestHeaders?: HeadersInit;};functionuploadMedia(params: UploadMediaRequest): Promise<{url: string}>;constreadClient=createClient({serviceDomain: 'serviceDomain',apiKey: 'readApiKey',});constwriteClient=createClient({serviceDomain: 'serviceDomain',apiKey: 'writeApiKey',});Apache-2.0