Skip to content

DataAPI SDK japanese MT.DataAPI Basic usage

Takeshi Nick Osanai edited this page Jan 29, 2015 · 12 revisions

基本的な使い方

公開されているデータを取得する

ステータスが「公開」にされているブログ記事などのデータは、以下のように簡単に取得することができます。

var api = new MT.DataAPI({
  baseUrl:  "https://your-host/mt/mt-data-api.cgi",
  clientId: "your-client-id"
});

api.listEntries(siteId, function(response) {
  if (response.error) {
    // エラー処理
    return;
  }

  for (var i = 0; i < response.items.length; i++) {
      var entry = response.items[i];
      // ブログ記事を表示
  }
});

閲覧するために認証が必要なデータを取得する

ユーザー自身の情報や、ステータスが「未公開(原稿)」にされているブログ記事などの公開されていないデータは、取得する際に DataAPI の認証画面でユーザー名とパスワードによる認証を得る必要があります。

var api = new MT.DataAPI({
  baseUrl:  "https://your-host/mt/mt-data-api.cgi",
  clientId: "your-client-id"
});

api.getUser('me', function(response) {
  if (response.error) {
    if (response.error.code === 401) {
      // まだ認証されていない場合

      // 認証が成功した場合、現在の URL に戻ってくる
      document.getElementById('login').href = api.getAuthorizationUrl(location.href);
      return;
    }

    // エラー処理
    return;
  }

  var user = response;

  document.getElementById('login').style.display = 'none';
  document.getElementById('username').textContent = user.displayName;
});

「authorizationRequired」イベントを利用する

未認証時の処理をまとめて記述するために、「authorizationRequired」イベントを利用することもできます。

var api = new MT.DataAPI({
  baseUrl:  "https://your-host/mt/mt-data-api.cgi",
  clientId: "your-client-id"
});

if (window.location.hash === '#_login') {
  window.parent.createEntry(window);
}
else {
  api.on('error', function(response) {
    if (response.error.code === 401) {
      return;
    }

    // エラー処理
  });

  api.on('authorizationRequired', function(response) {
    // まだ認証されていない場合

    // 認証が成功した場合、現在の URL に戻ってくる
    window.open(api.getAuthorizationUrl(location.href));
  });
  
  function createEntry(win) {
    api.createEntry(siteId, entryData, function(response) {
      if (response.error) {
        return;
      }

      if (win) {
        win.close();
      }

      var entry = response;
      // 作成されたブログ記事を表示
    });
  }
  createEntry();
}

閲覧するために認証が必要なデータを取得する (リクエスト最小版)

前述の「閲覧するために認証が必要なデータを取得する」のコードとユーザーから見える結果は同じものになりますが、以下のように書くとサーバーへのリクエストを最小限に抑えることができます。

var api = new MT.DataAPI({
  baseUrl:  "https://your-host/mt/mt-data-api.cgi",
  clientId: "your-client-id"
});

function goToAuthorizationUrl() {
  // 認証が成功した場合、現在の URL に戻ってくる
  document.getElementById('login').href = api.getAuthorizationUrl(location.href);
}

if (! api.getTokenData()) {
  // トークンのデータを持っていない
  goToAuthorizationUrl();
}

api.getUser('me', function(response) {
  if (response.error) {
    if (response.error.code === 401) {
      // 以前取得したトークンが期限切れになっているなどの理由で再認証が必要
      goToAuthorizationUrl();
      return;
    }

    // エラー処理
    return;
  }

  var user = response;

  document.getElementById('login').style.display = 'none';
  document.getElementById('username').textContent = user.displayName;
});
Clone this wiki locally