Поделиться через


Web API Samples (Client-side JavaScript)

 

Applies To: Dynamics 365 (online), Dynamics 365 (on-premises), Dynamics CRM 2016, Dynamics CRM Online

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

In this topic

Web API Samples using client-side JavaScript

How to download the source code for the sample.

How to import the Dynamics 365 solution that contains the sample.

How to run the sample to see the script in action

Common elements found in each sample

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 Dynamics 365 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 Microsoft Dynamics 365 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 Visual Studio 2015 solution for each sample within the C# folder because the project is an empty ASP.NET web application project. A Dynamics 365 solution is also provided in the download that you can import and run.

Note

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

How to import the Dynamics 365 solution that contains the sample.

Within each project you will find a Microsoft Dynamics 365 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 Dynamics 365 solution to your Dynamics 365 server, do the following:

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

  2. In the Dynamics 365 UI, go to Settings > Solutions. This page lists all solutions on your Dynamics 365 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 Dynamics 365. 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. For the Basic Operations sample, this interface looks like the following.

CRM Web API Sample Configuration page

To run the sample, do the following:

  1. From the All Solutions page in Dynamics 365, 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 Windows Internet Explorer and Microsoft Edge browsers.

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

    Promises are not required. Similar interactions can be performed using callback functions. For more information, see Create a re-usable function using promises.

  • 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 Microsoft Dynamics 365 Web API
Web API Samples
Web API Samples (C#)
Web API Basic Operations Sample (Client-side JavaScript)
Web API Query Data Sample (Client-side JavaScript)
Web API Conditional Operations Sample
Web API Functions and Actions Sample (Client-side JavaScript)

Microsoft Dynamics 365

© 2016 Microsoft. All rights reserved. Copyright