April 14, 2025
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.
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.
The ExecuteApex
class enables executing Anonymous Apex using the Salesforce Tooling API and retrieves the latest debug log entry.
Execute Anonymous Apex (executeApexMethod
)
getLogData()
to fetch the execution logs.Retrieve Execution Logs (getLogData
)
LogData:
.This class is useful for running Apex dynamically, debugging, and automating log retrieval in Salesforce.