Remove from Marketing List using WebApi

You can manage adding and removing contacts from Marketing Lists in JavaScript. Reviewing the WebApi documentation showed that this can be done, but there was a contradictory article on an SDK page which stated that removing a record from a marketing list does not work in the WebApi and I had seen some posts also stating this to be the case.

I checked this and it seems that removing a record from a marketing list is supported in the WebApi.

Here is how I achieved both. In the sample JavaScript below, ensure that you set these variables:

  • thisRecordId the Guid of the account, contact or lead record to add or remove
  • clientURL the Server URL for your Dynamics 365 instance
  • MarketingListId the Guid of the Marketing List that the account, contact or lead record is to be added to or removed from

Add to Marketing List

var data = {
           "EntityId": thisRecordId
       };
       
// WebApi call to add record to a Marketing List
var WebApiPath = encodeURI(clientURL + "/api/data/v9.0/lists(" + MarketingListId+ ")/Microsoft.Dynamics.CRM.AddMemberList");
var Req = new XMLHttpRequest();
Req.open("POST", WebApiPath, 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) {
               Req.onreadystatechange = null;
               if (this.status === 200) {
                   //Success
                   alert("Added to list.");
               } else {
                   var errorText = this.responseText;
                   //Error - something went wrong
                   alert(errorText);
               }
           }
       };
Req.send(JSON.stringify(data));

Remove from Marketing List

var data = {
    "ListMember": {
        listmemberid: thisRecordId,
        "@odata.type": "Microsoft.Dynamics.CRM.listmember"
    }
};
 
var WebApiPath = encodeURI(clientURL + "/api/data/v9.0/lists(" + MarketingListId+ ")/Microsoft.Dynamics.CRM.RemoveMemberList");
var Req = new XMLHttpRequest();
Req.open("POST", WebApiPath, 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) {
        Req.onreadystatechange = null;
        if (this.status === 200) 
            //Success 
            alert("Added to list.");
        } else {
            var errorText = this.responseText;
            //Error - something went wrong
            alert(errorText);
        }
    }
};
Req.send(JSON.stringify(data));

Leave a Comment

Your email address will not be published. Required fields are marked *