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)";
- //activityparty collection
- var activityparties = [];
- //from party
- var from = {};
- from["[email protected]"] = "/systemusers(8D23B2C1-9869-4C3F-9A80-BA51375C1784)";
- from["participationtypemask"] = 1;
- //to party
- var to = {};
- to["[email protected]"] = "/contacts(C41CE33F-D0A0-E611-811E-5065F38C8781)";
- to["participationtypemask"] = 2;
- activityparties.push(to);
- activityparties.push(from);
- //set to and from to email
- 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 /* complete */ ) {
- 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));
- } // This is just a sample script. Paste your real code (javascript or HTML) here.
- if ('this_is' == /an_example/) {
- of_beautifier();
- } else {
- var a = b ? (c % d) : e[f];
- }

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.

Vignesh ManiPosted Nov 15, 2016, 5:44 PM
Nice Article. Thanks to sharing.