- 
                Notifications
    You must be signed in to change notification settings 
- Fork 5
DataAPI SDK japanese MT.DataAPI Basic usage
        Taku AMANO edited this page Feb 25, 2014 
        ·
        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」イベントを利用することもできます。
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 (! this.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;
});