入門
ステップバイステップで:API と対話するために curl ステートメントを使用したプレーヤー管理ドキュメント。API 呼び出しが行われると、対話的にパスワードの入力を求められました。これはカールにはうまく機能しますが、アプリケーションの構築時にはこのような対話型認証は実行できません。
ここでは、JavaScriptとXMLHttpRequest(AJAXとも呼ばれます)を使用してAPIリクエストを作成し、プレーヤー管理操作用のWebクライアントを構築する方法を学習します。
Player ManagementAPIはCORS対応また、OAuth認証が必要であるため、Player Management APIサンプルの場合と同様に、Webページから直接APIリクエストを行うことができます。Brightcoveの他のRESTfulAPIには、 OAuth。アクセストークンの取得に使用されるAPIはCORS対応ではないため(API自体も対応していないため)、サーバー側のアプリを介してリクエストを行う必要があります。見るRESTAPIの使用 RESTAPIにアクセスするためのWebUIとプロキシを使用してハイブリッドアプリを構築するためのガイド。これは、本番環境でもPlayer Management APIを使用するアプリに推奨されるアプローチです。これは、HTTP接続を介して認証情報を送信しないため、より安全であるためです。
OAuth認証
Player Management APIはOAuth 2.0認証が必要です。API呼び出しを行うには、OAuth APIからアクセストークンを取得する必要があります。
Webアプリケーションの場合、OAuth認証を安全に処理するためにサーバー側プロキシを実装する必要があります。プロキシは次のことを行います。
- クライアント認証情報(client_idとclient_secret)をサーバー上に安全に保存する
- OAuth APIからアクセストークンをリクエストする
- 認証されたリクエストをPlayer Management APIに転送する
アクセストークンを使用してリクエストを行う場合、Authorizationヘッダーは次のように設定する必要があります。
"Authorization": "Bearer " + access_token
クライアント認証情報とアクセストークンの取得に関する詳細な手順については、OAuthガイドを参照してください。
AJAX
これらのサンプルでは、curlステートメントを使用する代わりに、JavaScriptを使用してAPIと通信します。これは、AJAXを使用してAPIにリクエストを発行することを意味します。特定のリクエスト例は次のようになります。
$.ajax({
type: "DELETE",
headers: {
"Authorization": "Bearer " + access_token,
"Content-Type": "application/json"
},
url: "https://players.api.brightcove.com/v2/accounts/123456789/players/478772a5-a2f2-44c6-a26b-2d7234bd97f5",
success: ajaxSuccess,
error: ajaxError
});
関連successそしてerrorハンドラーは次のようになります。
var ajaxSuccess = function (data) {
document.getElementById("jsonResponse").innerHTML = JSON.stringify(data,null,2);
};
var ajaxError = function (data) {
console.log("error data: ");
console.log(data);
};
もちろん、上記のようにAJAX呼び出しのすべての情報をハードコーディングする必要はないため、次に示すように、再利用可能な関数への実際の呼び出しを抽象化することは理にかなっています。
var makeAjaxCall = function (callURL, callType, callData) {
if (callData) {
$.ajax({
type: callType,
headers: {
"Authorization": "Bearer " + access_token,
"Content-Type": "application/json"
},
url: callURL,
data: JSON.stringify(callData),
success: ajaxSuccess,
error: ajaxError
});
} else {
$.ajax({
type: callType,
headers: {
"Authorization": "Bearer " + access_token,
"Content-Type": "application/json"
},
url: callURL,
success: ajaxSuccess,
error: ajaxError
});
}
};
これで、関数を呼び出す準備ができました。次の例では、account_id、account_passwordそしてaccount_username値はすべてフォームから抽出されます。
var getPlayerInfo = function () {
account_id = document.getElementById("account_id").value,
access_token = document.getElementById("access_token").value;
call_url = "https://players.api.brightcove.com/v2/accounts/" + account_id + "/players";
makeAjaxCall(call_url, "GET", null);
};
ステップバイステップを完了した場合:プレーヤーの作成や公開など、一部のプロセスで複数のAPI呼び出しが必要になることを知っているプレーヤー管理ドキュメント。また、一部のアプリのロジックでは、表示するすべてのプレーヤーのリストを取得し、ユーザーがマークしたプレーヤーを削除するなど、複数のAPI呼び出しが必要になる場合があります。このような場合、おそらく変更する必要がありますsuccessどの呼び出しが正常に実行されたかに基づいて、さまざまなロジックを実行するハンドラー。これらのサンプルアプリでは、これらのユースケースの実装ロジックはフラグ変数を使用して実装されます。callPurpose、およびcase次に示すように、そのフラグを使用するステートメント:
var ajaxSuccess = function (data) {
switch (callPurpose) {
case "getPlayers":
createCheckboxes(data);
watchCheckboxes();
break;
case "deletePlayer":
document.getElementById("jsonResponse").textContent += data;
break;
}
};
jQueryなしのAJAX
jQueryを使用したくない場合は、AJAXリクエストの作成は少し複雑ですが、それほど多くはありません。開始するためのコメント付きのサンプルコードを次に示します。
/**
* createRequest sets up requests, send them to makeRequest(), and handles responses
* @param {string} type the request type
*/
function createRequest(type) {
var options = {},
baseURL = 'https://players.api.brightcove.com/v2/accounts/',
account_id = '1234567890',
// would be better to get the access token from a form field
// or obtain it from your server-side proxy
access_token = 'your-access-token-here',
responseDecoded;
switch (type) {
case 'getPlayers':
options.url = baseURL + account_id + '/players';
options.requestType = 'GET';
options.access_token = access_token;
makeRequest(options, function(response) {
// use try catch in case something went wrong
try {
responseDecoded = JSON.parse(response);
// now do whatever you want with the response
}
catch (e) {
console.log('something went wrong - this was the JSON.parse error: ' + e);
}
});
break;
// additional cases
default:
console.log('Should not be getting to the default case - bad request type sent');
break;
}
}
/**
* send API request
* @param {Object} options for the request
* @param {String} options.url the full API request URL
* @param {String="GET","POST","PATCH","PUT","DELETE"} requestData [options.requestType="GET"] HTTP type for the request
* @param {String} options.access_token OAuth access token for authentication
* @param {JSON} [options.requestBody] Data (if any) to be sent in the request body in the form of a JSON string
* @param {Function} [callback] callback function that will process the response
*/
function makeRequest(options, callback) {
var httpRequest = new XMLHttpRequest(),
response,
requestParams,
dataString,
// response handler
getResponse = function() {
try {
if (httpRequest.readyState === 4) {
// don't just check for status = 200
// some requests return other 2xx codes
if (httpRequest.status >= 200 && httpRequest.status < 300) {
response = httpRequest.responseText;
// return the response to the callback
callback(response);
} else {
alert('There was a problem with the request. Request returned ' + httpRequest.status);
}
}
} catch (e) {
alert('Caught Exception: ' + e);
}
};
/**
* set up request data
*/
// set response handler
httpRequest.onreadystatechange = getResponse;
// open the request
httpRequest.open(options.requestType, options.url);
// set headers
httpRequest.setRequestHeader("Content-Type", "application/json");
httpRequest.setRequestHeader("Authorization", "Bearer " + options.access_token);
// open and send request
if (options.requestBody) {
httpRequest.send(options.requestBody)
} else {
httpRequest.send();
}
}