Retrieve Lookup & Option set value from web api mscrm


Hello Experts ,

To retrieve Look up   ( Id  ) from Web api , usually we will be declaring Schema Name ,

But in Web api , there is an minor change in syntax.

Instead of Schema Name we need to declare like below forma.

_prefix_attributename_value. 

Eg: _new_accountid_value

To retrieve Look up (Name , Logical Name ) We need to add below syntax in our Web api Request.

req.setRequestHeader(“Prefer”, “odata.include-annotations=\”*\””);

 

Sample Code For Reference.

Comments : Below example , will retrieve value from lead entity

  • Look Up
  • Money
  • Date Time
  • Option set
  • Decimal

var req = new XMLHttpRequest();

req.open("GET", Xrm.Page.context.getClientUrl() + "/api/data/v8.1/leads()?$select=_accountid_value,budgetamount,_contactid_value,_customerid_value,emailaddress1,modifiedon,salesstage", false);

req.setRequestHeader("OData-MaxVersion", "4.0");

req.setRequestHeader("OData-Version", "4.0");

req.setRequestHeader("Accept", "application/json");

req.setRequestHeader("Content-Type", "application/json; charset=utf-8");

<strong>req.setRequestHeader("Prefer", "odata.include-annotations=\"*\"");</strong> 

req.onreadystatechange = function() {

if (this.readyState === 4) {

req.onreadystatechange = null;

if (this.status === 200) {

var result = JSON.parse(this.response);

var _accountid_value = result["_accountid_value"];

var _accountid_value_formatted = result["_accountid_value@OData.Community.Display.V1.FormattedValue"];

var _accountid_value_lookuplogicalname = result["_accountid_value@Microsoft.Dynamics.CRM.lookuplogicalname"];

var budgetamount = result["budgetamount"];

var budgetamount_formatted = result["budgetamount@OData.Community.Display.V1.FormattedValue"];

var _contactid_value = result["_contactid_value"];

var _contactid_value_formatted = result["_contactid_value@OData.Community.Display.V1.FormattedValue"];

var _contactid_value_lookuplogicalname = result["_contactid_value@Microsoft.Dynamics.CRM.lookuplogicalname"];

var _customerid_value = result["_customerid_value"];

var _customerid_value_formatted = result["_customerid_value@OData.Community.Display.V1.FormattedValue"];

var _customerid_value_lookuplogicalname = result["_customerid_value@Microsoft.Dynamics.CRM.lookuplogicalname"];

var emailaddress1 = result["emailaddress1"];

var modifiedon = result["modifiedon"];

var salesstage = result["salesstage"];

var salesstage_formatted = result["salesstage@OData.Community.Display.V1.FormattedValue"];

} else {

Xrm.Utility.alertDialog(this.statusText);

}

}

};

req.send();

To make it simple , use
CRM REST Builder
  which will generate the complete code, and you can save your time  😉 😉 😉

Advertisements