Duplicate Matching Rules via rest API

The link which you have shared allows the user to bypass the duplicate matching rule defined in salesforce. In REST API, the method will be same. Sharing a code snippet here for enforcing the insertion of duplicate records and fetching the already existing duplicate records.

The method simply creates an Account and returns the list of duplicate accounts existing in the database.

@HttpPost
global static List<Id> fetchDuplicates(String name, String phone, String website) {

    Set<Id> setDuplicateIds = new Set<id>();
    Account account = new Account(Name = name, phone = phone, website = website);
    Database.SaveResult sr = Database.insert(account, false);

    if (!sr.isSuccess()) {

        Datacloud.DuplicateResult duplicateResult;

        // Insertion failed due to duplicate detected
        for(Database.Error duplicateError : sr.getErrors()){

            duplicateResult = ((Database.DuplicateError)duplicateError).getDuplicateResult();
        }

    // Fetch the Ids of the existing duplicate records
        for(Datacloud.MatchResult duplicateMatchResult : duplicateResult.getMatchResults()) {

            for(Datacloud.MatchRecord duplicateMatchRecord : duplicateMatchResult.getMatchRecords()) {

                setDuplicateIds.add(duplicateMatchRecord.getRecord().Id);
            }
        }

        System.debug('Duplicate records ' + setDuplicateIds);

        // If the duplicate rule is an alert rule, we can try to bypass it
        Database.DMLOptions dml = new Database.DMLOptions(); 
        dml.DuplicateRuleHeader.AllowSave = true;
        Database.SaveResult sr2 = Database.insert(account, dml);

        if (sr2.isSuccess()) {
            System.debug('Duplicate account has been inserted in Salesforce!');
        }
    }

// Return the existing duplicate records Ids
    List<Id> lstDuplicateIds = new List<Id>();
    lstDuplicateIds.addAll(setDuplicateIds);
    return lstDuplicateIds;
}

Hope this helps!


My answer here is the same one I gave on Is it possible to leverage SFDC Duplicate Matching fuzzy algorithm's within APEX code?

But for posterity, I figured it should be marked as the correct answer for this question too:

Winter '18 promises to bring the findDuplicates() method to Apex -- this has been available to the SOAP API for some time but now you can access the list of duplicate candidates in Apex.

https://developer.salesforce.com/docs/atlas.en-us.210.0.apexcode.meta/apexcode/apex_class_Datacloud_FindDuplicates.htm#apex_class_Datacloud_FindDuplicates

There were some previous 'workarounds' that involved trying to INSERT a record and inspect the Exception class to see if it was rejected due to a Duplicate Rule being violated. The findDuplicates() method is far cleaner