WEB API- Part 4 : Get option-set text

Get option-set text and value using Web API

Following code fetches lead source option-set value and text from lead entity.

var req = new XMLHttpRequest();
req.open("GET", Xrm.Page.context.getClientUrl() + "/api/data/v8.0/leads?$select=firstname,leadsourcecode&$filter=fullname eq 'Alex%20Eric'", true);
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");
req.setRequestHeader("Prefer", "odata.include-annotations=\"OData.Community.Display.V1.FormattedValue\"");
req.onreadystatechange = function () {
    if (this.readyState === 4) {
        req.onreadystatechange = null;
        if (this.status === 200) {
            var results = JSON.parse(this.response);
            for (var i = 0; i < results.value.length; i++) {
                 var firstname = results.value[i]["firstname"];
                 var leadsourcecode = results.value[i]["leadsourcecode"];
                 var leadsourcecode_formatted = results.value[i]["leadsourcecode@OData.Community.Display.V1.FormattedValue"];
        else {

Please note the following code

" var leadsourcecode_formatted = results.value[i]["leadsourcecode@OData.Community.Display.V1.FormattedValue"];"

“fields name@OData.Community.Display.V1.FormattedValue” will give you the text value of the filed.

Note : Don’t forget to add req.setRequestHeader(“Prefer”, “odata.include-annotations=\”OData.Community.Display.V1.FormattedValue\””);
in the request header

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s