Creating Classes and Triggers in APEX Using the Tooling API

Have you ever or are you now in a situation where you need to create an Apex class or trigger via Apex code and you are looking for a good way to do so?  Then you have come to right place.  This post will outline a simple and easy way to create these files in your Apex code that can be run from anywhere.

If you have looked into this at all you have probably thought that you can just use the ApexClass or ApexTrigger class to insert or update your new files.  You would be wrong.  While the class docs say that they support create() and update(), it will not work via the API so there is no good way of doing so while using those classes.  The way around this is to simply call the Tooling API from your Apex code.

How do you do this you ask?  First we need to create a Remote Site Setting for your own instance you are working in.  To get the URL you need to use, simply use Execute Anonymous and grab the log of:

System.debug(URL.getSalesforceBaseUrl().toExternalForm());

This just simply uses the URL class to get the base URL.  After the remote site setting is added you are ready to rock with your creation code.  Creation of a trigger will look something like this:

String json = '{ "Name" : "TestAccountTrigger", "TableEnumOrId" : "Account", "Body" : "trigger TestAccountTrigger on Account (before insert) {}" }'; 

Httprequest req = new HttpRequest();
req.setEndpoint(URL.getSalesforceBaseUrl().toExternalForm() + '/services/data/v27.0/sobjects/ApexTrigger');
req.setMethod('POST');
req.setHeader('Content-Type', 'application/json');
req.setHeader('Authorization', 'OAuth ' + UserInfo.getSessionId());
req.setBody(json);

Http httpReq = new Http();
HttpResponse res = httpReq.send(req); 
System.debug(res.getBody());

You can use the ApexClass and ApexTrigger classes to determine what fields to use when generating your JSON object to send for creation.  As you can see from our JSON, we are creating a trigger on Account with an empty body.  The class is very similar.  The only real change is some of the fields and then endpoint:

String json = '{ "Name" : "MyTestClass", "Body" : "public class MyTestClass{}" }'; 

Httprequest req = new HttpRequest();
req.setEndpoint(URL.getSalesforceBaseUrl().toExternalForm() + '/services/data/v27.0/sobjects/ApexClass');
req.setMethod('POST');
req.setHeader('Content-Type', 'application/json');
req.setHeader('Authorization', 'OAuth ' + UserInfo.getSessionId());
req.setBody(json);

Http httpReq = new Http();
HttpResponse res = httpReq.send(req); 
System.debug(res.getBody());

There you have it.  This is how you create a class or trigger from Apex.  One of the only things you need to be cognizant of when doing this is that you cannot create a class or a trigger in a production environment. 

If you have any questions on this feel free to comment below.  Happy Coding!!

Comments

Returning visitor? Please login or register.

Leave A Comment