Bhubaneswar, Odisha, India
+91-8328865778
support@softchief.com

Create Record using Web API

Create Record using Web API

Here is a sample snippet which explains how to create entity record in JavaScript using Web API in Dynamics 365.

we.jpg
To use Web API we have to use URL like below

[Organization URI] +”/api/data/v8.1/”

Sample Code for Javascript to retrieve account record.

 var req = new XMLHttpRequest()
 req.open("POST",encodeURI(clientURL + "/api/data/v8.1/accounts"), 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.onreadystatechange = function () {
 if (this.readyState == 4 /* complete */) {
 req.onreadystatechange = null;
 if (this.status == 204) {
 var accountUri = this.getResponseHeader("OData-EntityId");
 console.log("Created account with URI: "+ accountUri);
 }
 else {
 var error = JSON.parse(this.response).error;
 console.log(error.message);
 }
 }
 };
 req.send(JSON.stringify({ name: "Sample account" }));

Retrieve Record

 function retrieveEntity(entityname,id, columnset) {
 var serverURL = Xrm.Page.context.getClientUrl();
 var Query = entityname+ "(" + id + ")" + columnset;
 var req = new XMLHttpRequest();
 req.open("GET", serverURL + "/api/data/v8.0/" + Query, 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.onreadystatechange = function() {
 if (this.readyState == 4 /* complete */ ) {
 req.onreadystatechange = null;
 if (this.status == 200)//to verify result is OK {
 var data = JSON.parse(this.response);
 if(data!=null && data.accountnumber!=null)
 alert(data.accountnumber);
 if(data!=null && data._primarycontactid_value!=null)
 alert(data._primarycontactid_value); //lookup

} else {
 var error = JSON.parse(this.response).error;
 alert(error.message);
 }
 }
 };
 req.send();
 }

Consume as below

 var Id=entityid; //PK(GUID)
 var entityName="accounts";
 var columnSet="?$select=accountnumber,_primarycontactid_value"; //columnset
 retrieveEntity(entityName,Id,columnSet);