Here I am going to show how to use FetxhXML query to get the results from CRM Web API. below example shows how to get logged in user Security roles.
function getRoles(token) {
var req = new XMLHttpRequest();
var fetch = “<fetch version=’1.0′ output-format=’xml-platform’ mapping=’logical’ distinct=’true’>” +
“<entity name=’role’>” +
“<attribute name=’name’ />” +
“<attribute name=’businessunitid’ />” +
“<attribute name=’roleid’ />” +
“<order attribute=’name’ descending=’false’ />” +
“<link-entity name=’systemuserroles’ from=’roleid’ to=’roleid’ visible=’false’ intersect=’true’>” +
“<link-entity name=’systemuser’ from=’systemuserid’ to=’systemuserid’ alias=’ad’>” +
“<filter type=’and’>” +
“<condition attribute=’systemuserid’ operator=’eq-userid’ />” +
“</filter>” +
“</link-entity>” +
“</link-entity>” +
“</entity>” +
“</fetch>”;
$.ajax({
type: “GET”,
contentType: “application/json; charset=utf-8”,
datatype: “json”,
url: Xrm.Page.context.getClientUrl() + “/api/data/v8.2/roles?fetchXml=” + fetch,
beforeSend: function (XMLHttpRequest) {
XMLHttpRequest.setRequestHeader(“OData-MaxVersion”, “4.0”);
XMLHttpRequest.setRequestHeader(“OData-Version”, “4.0”);
XMLHttpRequest.setRequestHeader(“Accept”, “application/json”);
XMLHttpRequest.setRequestHeader(“Prefer”, “odata.include-annotations=\”*\””);
},
async: false,
success: function (data, textStatus, xhr) {
var results = data;
for (var i = 0; i < results.value.length; i++) {
var roleid = results.value[i][“roleid”];
var roleName = results.value[i][“name”];
}
},
error: function (xhr, textStatus, errorThrown) {
alert(textStatus + ” ” + errorThrown);
}
});
}