Web API Data operations Samples (Client-side JavaScript)

This topic provides common understanding about Web API samples using client-side JavaScript. While each sample focuses on a different aspect of Common Data Service Web API, they all follow similar process and structure described in this topic.

Web API Samples using client-side JavaScript

The following samples use the patterns described here:

Sample Sample Group Description
Web API Basic Operations Sample (Client-side JavaScript) Web API Basic Operations Sample Demonstrates how to create, retrieve, update, delete, associate and disassociate Common Data Service entity records.
Web API Query Data Sample (Client-side JavaScript) Web API Query Data Sample Demonstrates how to use OData v4 query syntax and functions as well as Common Data Service query functions. Includes demonstration of working with pre-defined queries and using FetchXML to perform queries.
Web API Conditional Operations Sample (Client-side JavaScript) Web API Conditional Operations Sample Demonstrates how to perform conditional operations. The behavior of these operations depends on criteria you specify.
Web API Functions and Actions Sample (Client-side JavaScript) Web API Functions and Actions Sample Demonstrates how to use bound and unbound functions and actions, including custom actions.

How to download the source code for the sample.

The source code for each sample is available on MSDN Code Gallery. The link to download each sample is included in the individual page for that sample.

After you download the sample, extract the compressed file. Find the Microsoft Visual Studio 2015 solution for each sample within the C# folder because the project is an empty ASP.NET web application project. A Common Data Service solution is also provided in the download that you can import and run.

Note

Neither Visual Studio or ASP.NET is required to develop client-side JavaScript for Common Data Service, however the MSDN Code Gallery site requires files be included in a Visual Studio as a container. However, Visual Studio does provide a good experience for writing JavaScript.

How to import the Common Data Service solution that contains the sample.

Within each project you will find a Common Data Service managed solution file. The name of this file will depend on the sample's project name, but the file name will end with _managed.zip.

To import the Common Data Service solution to your Common Data Service server, do the following:

  1. Extract the contents of the downloaded zip file and locate the Common Data Service solution file, which will also be a zip file. For example, if you downloaded the Basic Operations sample, look for the Common Data Service solution zip file with the name WebAPIBasicOperations\WebAPIBasicOperations_1_0_0_0_managed.zip.

  2. In the Common Data Service UI, go to Settings > Solutions. This page lists all solutions on your Common Data Service server. After you finished importing this solution, the solution name for that sample will appear in this list (e.g.: Web API Basics Operations).

  3. Click Import and follow the instructions on the import dialog to complete this action.

How to run the sample to see the script in action

The sample program runs as a web resource within Common Data Service. The imported solution provides a configuration page that gives you an option to keep or delete sample data and a button to start the sample program.

To run the sample, do the following:

  1. From the All Solutions page in Common Data Service, click the solution name (e.g.: Web API Basics Operations link). This will open the solution's properties in a new window.

  2. From the left navigation menu, click Configuration.

  3. Click Start Sample button to execute the sample code.

Common elements found in each sample

The following list highlights some common elements found in each of these samples.

  • The Sdk.startSample function is called when a user clicks the Start Sample button from the HTML page. The Sdk.startSample function initializes global variables and kicks off the first operation in the chain.

  • Program output and error messages are sent to the browser’s debugger console. To see these output, open the console window first before running the sample. Press F12 to access the developer tools, including the console window, in the Internet Explorer and Microsoft Edge browsers.

  • These samples use the browser native ES6-Promise implementation for modern browsers that support it. For Internet Explorer, this sample uses the ES6-Promise polyfill because Internet Explorer is the only browser supported by Common Data Service which does not have native support for this feature.

    Promises are not required. Similar interactions can be performed using callback functions.

  • The Sdk.request function handles the request based on the information passed in as parameters. Depending on the need of each sample, the parameters passed in may be different. See the source code of that sample for more details.

    /**  
     * @function request  
     * @description Generic helper function to handle basic XMLHttpRequest calls.  
     * @param {string} action - The request action. String is case-sensitive.  
     * @param {string} uri - An absolute or relative URI. Relative URI starts with a "/".  
     * @param {object} data - An object representing an entity. Required for create and update actions.  
     * @returns {Promise} - A Promise that returns either the request object or an error object.  
     */  
    Sdk.request = function (action, uri, data) {  
        if (!RegExp(action, "g").test("POST PATCH PUT GET DELETE")) { // Expected action verbs.  
            throw new Error("Sdk.request: action parameter must be one of the following: " +  
                "POST, PATCH, PUT, GET, or DELETE.");  
        }  
        if (!typeof uri === "string") {  
            throw new Error("Sdk.request: uri parameter must be a string.");  
        }  
        if ((RegExp(action, "g").test("POST PATCH PUT")) && (data === null || data === undefined)) {  
            throw new Error("Sdk.request: data parameter must not be null for operations that create or modify data.");  
        }  
    
        // Construct a fully qualified URI if a relative URI is passed in.  
        if (uri.charAt(0) === "/") {  
            uri = clientUrl + webAPIPath + uri;  
        }  
    
        return new Promise(function (resolve, reject) {  
            var request = new XMLHttpRequest();  
            request.open(action, encodeURI(uri), true);  
            request.setRequestHeader("OData-MaxVersion", "4.0");  
            request.setRequestHeader("OData-Version", "4.0");  
            request.setRequestHeader("Accept", "application/json");  
            request.setRequestHeader("Content-Type", "application/json; charset=utf-8");  
            request.onreadystatechange = function () {  
                if (this.readyState === 4) {  
                    request.onreadystatechange = null;  
                    switch (this.status) {  
                        case 200: // Success with content returned in response body.  
                        case 204: // Success with no content returned in response body.  
                            resolve(this);  
                            break;  
                        default: // All other statuses are unexpected so are treated like errors.  
                            var error;  
                            try {  
                                error = JSON.parse(request.response).error;  
                            } catch (e) {  
                                error = new Error("Unexpected Error");  
                            }  
                            reject(error);  
                            break;  
                    }  
    
                }  
            };  
            request.send(JSON.stringify(data));  
        });  
    };  
    

    The Sdk.request function returns a promise. When the request wrapped by the promise is completed, the promise is either resolved or rejected. If it is resolved, the function in the following then method will be called. If it is rejected, the function in the following catch method will be called. If the function within the then method itself returns a promise, the chain of operations within consecutive then methods can continue. Returning a promise allows us to chain these sample operations together in a way that is preferred by many developers to traditional callback functions. For more information about promise, see JavaScript Promise.

See also

Use the Common Data Service Web API
Web API Samples
Web API Samples (C#)