-
Notifications
You must be signed in to change notification settings - Fork 5
DataAPI SDK english MT.DataAPI Basic usage
Takeshi Nick Osanai edited this page Jan 29, 2015
·
10 revisions
You can fetch public data (e.g. published entry), without authorization.
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) {
// Handle error
return;
}
for (var i = 0; i < response.items.length; i++) {
var entry = response.items[i];
// Render an entry
}
});
You can fetch private data (e.g. user data), with authorization.
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) {
// You have not been authenticated yet.
// You will return to current URL after authorization succeeded.
document.getElementById('login').href = api.getAuthorizationUrl(location.href);
return;
}
// Handle error
return;
}
var user = response;
document.getElementById('login').style.display = 'none';
document.getElementById('username').textContent = user.displayName;
});
You can use "authorizationRequired" event in order to handle error.
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;
}
// Handle error
});
api.on('authorizationRequired', function(response) {
// You have not been authenticated yet.
// You will return to current URL after authorization succeeded.
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;
// Render created entry
});
}
createEntry();
}
Although some requests are needed before attestation in the previous version, you can also reduce request by writing as follows.
var api = new MT.DataAPI({
baseUrl: "https://your-host/mt/mt-data-api.cgi",
clientId: "your-client-id"
});
function goToAuthorizationUrl() {
// You will return to current URL after authorization succeeded.
document.getElementById('login').href = api.getAuthorizationUrl(location.href);
}
if (! api.getTokenData()) {
// You do not have a token data yet.
goToAuthorizationUrl();
}
api.getUser('me', function(response) {
if (response.error) {
if (response.error.code === 401) {
// Probably, your token has been expired
goToAuthorizationUrl();
return;
}
// Handle error
return;
}
var user = response;
document.getElementById('login').style.display = 'none';
document.getElementById('username').textContent = user.displayName;
});