Dynamics 365 released some new enhancements to Web API. If you are new to Web API, I will suggest you refer to our earlier articles for Web API. In this release, create and update Web API requests are enhanced to return an entity object after the record is created or updated. Let’s understand this enhancement, using create request example, mentioned below.
Let's say, we want to create an E-mail activity record, using Web API. The example is mentioned below of using create Web API request , which is used before Dynamics 365.
- function createEmail() {
- var serverURL = Xrm.Page.context.getClientUrl();
- var email = {};
- email["subject"] = "Email demo from Web API";
- email["description"] = "This a web api test";
- email["[email protected]"] = "/contacts(C41CE33F-D0A0-E611-811E-5065F38C8781)";
-
- var activityparties = [];
-
-
- var from = {};
- from["[email protected]"] = "/systemusers(8D23B2C1-9869-4C3F-9A80-BA51375C1784)";
- from["participationtypemask"] = 1;
-
-
- var to = {};
- to["[email protected]"] = "/contacts(C41CE33F-D0A0-E611-811E-5065F38C8781)";
- to["participationtypemask"] = 2;
-
- activityparties.push(to);
- activityparties.push(from);
-
-
-
- email["email_activity_parties"] = activityparties;
- var req = new XMLHttpRequest();
- req.open("POST", serverURL + "/api/data/v8.0/emails", true);
- req.setRequestHeader("Accept", "application/json");
- req.setRequestHeader("Content-Type", "application/json; charset=utf-8");
- req.setRequestHeader("OData-MaxVersion", "4.0");
- req.setRequestHeader("OData-Version", "4.0");
- req.setRequestHeader("Prefer", "return=representation");
- req.onreadystatechange = function() {
- if (this.readyState == 4 ) {
- req.onreadystatechange = null;
- if (this.status == 201) {
- var emailUri = this.getResponseHeader("OData-EntityId");
- } else {
- var error = JSON.parse(this.response).error;
- alert(error.message);
- }
- }
- };
- req.send(JSON.stringify(email));
- }
-
- if ('this_is' == /an_example/) {
- of_beautifier();
- } else {
- var a = b ? (c % d) : e[f];
- }
When we will execute this request, we can see the screenshot of the watch Window, where we are not getting any reponse, as it’s blank. Older request only returns responseheader, which contains URL of the new record created. You can also see, if it’s returning the status as 204.
Using new Web API enhancement, we can now include additional preference (return=representation) in the header of the request to get an entity object, which is just created, as shown below.
req.setRequestHeader("Prefer”,”return=representation");
Thus, after adding this addition header request, we will get a response, as shown below, and it will also return the status as 201 instead of 204.
We can get an entity object from the response and process fields accordingly, if required.
Stay tuned for more Dynamics 365 new features.