Setup for Player Management Samples

This page describes how the basic samples for the new player are written. This includes details on basic authentication and how AJAX is used in the Player Management API samples.

Introduction

In the Step-by-Step: Player Management document you used curl statements to interact with the API. When an API call was made you were interactively prompted for a password. While this works well for curl, this kind of interactive authentication is not feasible when building an application.

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

Because the Player Management API is CORS-enabled and allows basic authentication using your Brightcove login credentials, it is possible to make API requests directly from a web page, as we do in Player Management API samples. Brightcove's other RESTful APIs require authentication via OAuth. Since the API used to retrieve access tokens is not CORS-enabled (nor are the APIs themselves), you must make requests through a server-side app. 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 approach we recommend for apps using the Player Management API in production as well, because it is more secure, sending no credentials over HTTP connections.

Basic authentication

In the Step-by-Step: Player Management document you used curl statements to interact with the API. When an API call was made you were interactively prompted for a password. While this works well for curl, this kind of interactive authentication is not feasible when building an application.

You can use basic authentication when building an app. In the header you need to send the credentials, encrypted in a base-64 encoded ASCII string. You can use the JavaScript btoa() method to do the encoding. Assuming account_username and account_password are populated from, for example a form, the Authorization header would appear as follows:

     "Authorization": "Basic " + btoa(account_username + ":" + account_password),

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": "Basic " + btoa("username:password"),
        "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": "Basic " + btoa(account_username + ":" + account_password),
                    "Content-Type": "application/json"
                },
                url: callURL,
                data: JSON.stringify(callData),
                success: ajaxSuccess,
                error: ajaxError
            });
        } else {
            $.ajax({
            type: callType,
            headers: {
                "Authorization": "Basic " + btoa(account_username + ":" + account_password),
                "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, account_password and account_username values are all extracted from a form.

    var getPlayerInfo = function () {
        account_id = document.getElementById("account_id").value,
        account_password = document.getElementById("account_password").value,
        account_username = document.getElementById("account_username").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 these from form fields
            // and not hardcode them
            username = 'jane@myplace.com',
            password = 'mypassword',
            responseDecoded;
    
        // set credentials
        options.client_id     = cid.value;
        options.client_secret = secret.value;
    
        switch (type) {
            case 'getPlayers':
                options.url         = ipBaseURL + account_id + '/players';
                options.requestType = 'GET';
                options.username = username;
                options.password = password;
                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.username username for the account
     * @param  {String} options.password password for the account
     * @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", "Basic " + btoa(options.username + ":" + options.password));
        // open and send request
        if (options.requestBody) {
            httpRequest.send(options.requestBody)
        } else {
            httpRequest.send();
        }
    }