Skip to main content

JavaScript: Working with Web API Functions in Dynamics 365

Welcome to my blog! In this post, we'll explore how you can work with the Dynamics 365 Web API to interact with records and data. The Web API provides a standard, RESTful way to create, retrieve, update, and delete data within Dynamics 365. It is crucial for integrating external systems or when you're developing custom solutions.


If you find this post useful, please follow and support me on LinkedIn!


What is the Web API in Dynamics 365?


The Web API in Dynamics 365 is a powerful, REST-based API that allows external applications or client-side code to interact with the data stored in Dynamics 365. You can use it to perform CRUD operations (Create, Retrieve, Update, and Delete), trigger business logic, and integrate third-party services. It’s designed to simplify integration and extend the capabilities of Dynamics 365.


How to Work with Web API Functions in Dynamics 365


Let’s dive into some common examples of how to interact with Dynamics 365 data using Web API functions.


1. Retrieving Data (Read Operations)


You can retrieve records from Dynamics 365 using the Web API by sending an HTTP GET request to the entity endpoint. You can specify query parameters to filter or limit the data.


Example: Retrieve a single Account record:


var accountId = "12345"; // Use a valid Account ID

var query = "/accounts(" + accountId + ")?$select=name,telephone1,emailaddress1"; // Specify the fields you need


Xrm.WebApi.retrieveRecord("account", accountId, query).then(

  function success(result) {

    console.log("Account Name: " + result.name);

    console.log("Telephone: " + result.telephone1);

    console.log("Email: " + result.emailaddress1);

  },

  function (error) {

    console.log("Error: " + error.message);

  }

);


In this example, we're retrieving a specific account using its ID and selecting a few fields (name, telephone1, emailaddress1) from the account.


2. Creating Data (Create Operation)


To create a new record, send an HTTP POST request with the entity data in the body. The Web API will create the record and return the newly created record’s ID.


Example: Create a new Account record:


var accountData = {

  "name": "New Business Account",

  "telephone1": "+1 555-5555",

  "emailaddress1": "business@example.com"

};


Xrm.WebApi.createRecord("account", accountData).then(

  function success(result) {

    console.log("Account Created with ID: " + result.id);

  },

  function (error) {

    console.log("Error: " + error.message);

  }

);


Here, we're creating a new account by passing the name, telephone1, and emailaddress1 fields as part of the request body.


3. Updating Data (Update Operation)


Updating an existing record involves sending an HTTP PATCH request to the entity’s record endpoint, including only the fields that need updating.


Example: Update an Account record:


var accountId = "12345"; // Use the ID of the Account you want to update

var updatedData = {

  "telephone1": "+1 555-1234",

  "emailaddress1": "updatedemail@example.com"

};


Xrm.WebApi.updateRecord("account", accountId, updatedData).then(

  function success(result) {

    console.log("Account Updated");

  },

  function (error) {

    console.log("Error: " + error.message);

  }

);


This example updates the telephone1 and emailaddress1 fields for the specified account record.


4. Deleting Data (Delete Operation)


To delete a record, send an HTTP DELETE request to the entity’s record endpoint.


Example: Delete an Account record:


var accountId = "12345"; // Use the Account ID to delete


Xrm.WebApi.deleteRecord("account", accountId).then(

  function success(result) {

    console.log("Account Deleted");

  },

  function (error) {

    console.log("Error: " + error.message);

  }

);


This will remove the account with the specified accountId from the system.


5. Retrieving Multiple Records (Bulk Retrieval)


The Web API also allows you to retrieve multiple records using an HTTP GET request. You can apply various query parameters like $filter, $orderby, and $top to customize your results.


Example: Retrieve all Accounts with a specific name:


var query = "/accounts?$filter=name eq 'Contoso'&$select=name,accountnumber";


Xrm.WebApi.retrieveMultipleRecords("account", query).then(

  function success(result) {

    result.entities.forEach(function (account) {

      console.log("Account Name: " + account.name);

      console.log("Account Number: " + account.accountnumber);

    });

  },

  function (error) {

    console.log("Error: " + error.message);

  }

);


In this example, we are retrieving all accounts where the name is "Contoso" and logging the name and accountnumber fields.


6. Using Query Options for Advanced Queries


The Web API supports advanced query options to filter and sort the data. Some of the most commonly used options are:


$select: Specifies the fields to return.


$filter: Filters records based on a condition.


$orderby: Orders the records.


$top: Limits the number of records returned.



Example: Retrieve the top 5 most recent Accounts:


var query = "/accounts?$orderby=createdon desc&$top=5";


Xrm.WebApi.retrieveMultipleRecords("account", query).then(

  function success(result) {

    result.entities.forEach(function (account) {

      console.log("Account Name: " + account.name);

      console.log("Created On: " + account.createdon);

    });

  },

  function (error) {

    console.log("Error: " + error.message);

  }

);


This example retrieves the top 5 most recently created accounts and logs their names and creation dates.


Conclusion


The Dynamics 365 Web API is a powerful tool for interacting with data, whether you're integrating external systems, writing custom JavaScript code, or automating tasks. By understanding how to use the Web API for basic CRUD operations and how to apply query options, you can significantly extend the functionality of Dynamics 365.


I hope this post has helped you understand how to work with the Web API in Dynamics 365. If you found it useful, please consider following me on LinkedIn for more updates and posts.

https://in.linkedin.com/in/pavan-kumar-vuyyuru

Comments

Popular posts from this blog

Powerapps: Collections in Canvas Apps | Collect, ClearCollect, Clear in Powerapps

Collections : Collections are special types of variables or data storage mechanism which can be used to manipulate the data within Power Apps.  Collections are usually a group of similar items which acts like a table of values with columns and rows.  We can create, update, delete, use it as the data source for a gallery to view the items within Power App.  Collect, Clear, and ClearCollect functions:   Collect : In Power Apps, the Collect function is used to create or update a collection in your app.  Collections are temporary data sources that allow you to store and work with data within your app.  The Collect function is versatile and can be used in various scenarios to add, modify, or remove records from a collection.  Syntax : Collect( IceCream, { Flavor: "Pistachio", Quantity: 40 }, { Flavor: "Orange", Quantity: 200 } )   Adds two records to the IceCream collection that includes a quantity of pistachio and orange ice cream.  Clear : In Po...

Understanding the Basics of C# Plugins in Dynamics 365: A Simple Account Update Example

Welcome to my blog! Today, we’ll dive into the world of C# plugins in Dynamics 365. If you're working with Dynamics 365, you’ve likely heard of plugins, which allow you to extend the platform's functionality and automate various processes. In this post, I’ll walk you through the parts of a plugin, using a simple example of updating an account record. What Is a C# Plugin? A plugin in Dynamics 365 is a custom business logic component that responds to specific events in the system. Plugins are executed in response to a trigger event, like creating or updating a record, and can be used to modify data or integrate with other systems. Written in C#, they are powerful tools for customizing and extending the functionality of Dynamics 365. The Structure of a C# Plugin A plugin typically consists of several parts: Plugin Registration – You register the plugin in Dynamics 365 to define what event triggers the plugin (create, update, delete) and which entity it will affect (e.g., A...

Essential Dynamics 365 Plugins for Sales & Customer Service

Introduction In Dynamics 365, plugins automate business processes, enforce rules, and ensure data integrity. Whether in Sales or Customer Service , plugins help streamline workflows by executing logic at the right time in the pipeline. This post covers key plugin scenarios , detailing: ✅ Execution pipeline stage (Pre-Validation, Pre-Operation, Post-Operation) ✅ Synchronous or Asynchronous execution ✅ Pre-Image / Post-Image usage ✅ Rollback handling Rollback Handling in Plugins When Does a Plugin Rollback? A plugin automatically rolls back if: An exception is thrown in a synchronous plugin. A transaction fails in a Pre-Validation or Pre-Operation stage. How to Handle Rollbacks? Use Try-Catch Blocks : Prevent unwanted failures by catching errors and logging details. Throw an Exception When Needed : Stop invalid data changes (e.g., prevent closing an Opportunity without a Quote). Compensating Logic in Async Plugins : Since Post-Operation Async plugins do not par...