How to Execute Anonymous Apex Using Tooling API in Salesforce

April 14, 2025


 

 

Introduction:

In this blog, we will explore how to execute Anonymous Apex using the Salesforce Tooling API. Simply put, we will store Apex code as a string and run it dynamically through the Tooling API. Additionally, we will retrieve execution results by implementing another Tooling API call to fetch the latest debug log data. This approach is useful for debugging, automation, and seamless Apex execution within Salesforce.

 

Steps to achieve this:

1. Open Developer Console and create a new class called ExecuteApex.

2. Use the following code for the ExecuteApex class:

public class ExecuteApex {
    public static String executeApexMethod () {
        String ApexCode = 'System.debug(\'LogData: \'+\'TESTTEST11112222\');';
        String urlEncodedApexCode = EncodingUtil.urlEncode(ApexCode, 'UTF-8').replace('+', '%20');
        HttpRequest req = new HttpRequest();
        req.setEndpoint(URL.getOrgDomainURL() + '/services/data/v60.0/tooling/executeAnonymous/?anonymousBody=' + urlEncodedApexCode);
        req.setMethod('GET');
        req.setHeader('Authorization', 'Bearer ' + UserInfo.getSessionId());
        Http http = new Http();
        HttpResponse res = http.send(req);
        String result = getLogData();
        System.debug('result: '+result);
        return result;
    }

    public static String getLogData() {
        Id ApexLogId = [SELECT Id, StartTime, Operation, Status FROM ApexLog ORDER BY StartTime desc limit 1].Id;
        HttpRequest req = new HttpRequest();
        req.setEndpoint(URL.getOrgDomainURL() + '/services/data/v60.0/tooling/sobjects/ApexLog/' + ApexLogId + '/Body/');
        req.setMethod('GET');
        req.setHeader('Authorization', 'Bearer ' + UserInfo.getSessionId());
        Http http = new Http();
        HttpResponse res = http.send(req);
        String logData = res.getBody();
        List<String> splittedLogData = logData.split('\n');
        String debugLine;
        for (String line : splittedLogData) {
             List<String> splittedDebugLine = line.split('LogData: ');
            if (line.contains('USER_DEBUG') && !splittedDebugLine.isEmpty()) {
                debugLine = line;
                break;
            }
        }
        return debugLine;
    }
}

and Save it.

3. Now click on Debug and select Open Execute Anonymous Window.

4. If there is already code in the Enter Apex Code window, replace it with this code:

System.assert(false, ExecuteApex.executeApexMethod());
 

5. Click on Execute.

 

Code Summary

The ExecuteApex class enables executing Anonymous Apex using the Salesforce Tooling API and retrieves the latest debug log entry.

Key Functionalities:

  1. Execute Anonymous Apex (executeApexMethod)

    • Stores Apex code as a string and URL-encodes it.
    • Sends an HTTP GET request to the Tooling API to execute the Apex code.
    • Calls getLogData() to fetch the execution logs.
    • Returns the extracted debug log entry.
  2. Retrieve Execution Logs (getLogData)

    • Queries for the most recent Apex Log ID.
    • Makes an HTTP GET request to retrieve the log body.
    • Extracts and returns the debug log entry containing LogData:.

Use Case:

This class is useful for running Apex dynamically, debugging, and automating log retrieval in Salesforce.