Introduction
In the Step-by-Step: Player Management document you used curl statements to interact with the API. When building an application, you need to use OAuth 2.0 for authentication.
Here you will learn how you make the API requests using JavaScript and XMLHttpRequest - also known as AJAX - to build web clients for player management operations
The Player Management API requires authentication via OAuth. Since the OAuth API is not CORS-enabled, you must make requests through a server-side app (proxy). See Using the REST APIs for a guide to building hybrid apps with a web UI and proxy to access the REST APIs. This is the recommended approach for production apps using the Player Management API, as it is more secure.
OAuth authentication
The Player Management API requires OAuth 2.0 authentication. To make API calls, you need to obtain an access token from the OAuth API.
For web applications, you should implement a server-side proxy to handle OAuth authentication securely. The proxy will:
- Store your client credentials (client_id and client_secret) securely on the server
- Request access tokens from the OAuth API
- Forward authenticated requests to the Player Management API
When making requests with an access token, the Authorization header should be set as follows:
"Authorization": "Bearer " + access_token
See the OAuth Guide for detailed instructions on obtaining client credentials and access tokens.
AJAX
Instead of using curl statements these samples will use JavaScript to communicate with the API. This means using AJAX to issue the request to the API. A specific example request might look something like this:
$.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
});
Associated success and error handlers could look something like this:
var ajaxSuccess = function (data) {
document.getElementById("jsonResponse").innerHTML = JSON.stringify(data,null,2);
};
var ajaxError = function (data) {
console.log("error data: ");
console.log(data);
};
Of course, you don't want to hard code all the information in the AJAX call as shown above, so it makes sense to abstract the actual call to a function that is reusable, as shown here:
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
});
}
};
You are then ready to call the function. In the following example the account_id and access_token values are extracted from a form.
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);
};
If you have completed the Step-by-Step: Player Management document you know that some processes take multiple API calls, like creating and publishing a player. Also, the logic of some apps may require multiple API calls, like getting a list of all players to display, then deleting players the user marked. In these instances you will most likely need to alter your success handler to perform different logic based on which call was just successfully carried out. In these sample apps the implementation logic for these use cases will be implemented using a flag variable, callPurpose, and a case statement using that flag, as shown here:
var ajaxSuccess = function (data) {
switch (callPurpose) {
case "getPlayers":
createCheckboxes(data);
watchCheckboxes();
break;
case "deletePlayer":
document.getElementById("jsonResponse").textContent += data;
break;
}
};
AJAX without jQuery
If you would rather not use jQuery, making AJAX requests is a little more complex, but not too much. Here is some sample code, with comments, to get you started:
/**
* 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();
}
}