14

I am trying all my level best to know how the Tooling API is used. Can someone suggest or show me with a small example on how do I create a apexClass in a controller method.

I have already generated metadataservice from WSDL.

1

1 Answer 1

16

I prefer the REST flavor of the Tooling API. Here's a sample method to create a class:

// Class variable for Tooling API base URL
// you'll need to add the base URL as a Remote Site in the org
private static String baseUrl = URL.getSalesforceBaseUrl().toExternalForm() 
    + '/services/data/v28.0/tooling/';

public static void createClass() {
    // Note the escaping on newlines and quotes
    String classBody = 'public class MyNewClass {\\n'
        + ' public string SayHello() {\\n'
        + '  return \'Hello\';\\n' 
        + ' }\\n'
        + '}';

    HTTPRequest req = new HTTPRequest();
    req.setEndpoint(baseUrl + 'sobjects/ApexClass');
    req.setMethod('POST');
    // OAuth header
    req.setHeader('Authorization', 'Bearer ' + UserInfo.getSessionId());
    req.setHeader('Content-Type', 'application/json');
    req.setBody('{'+
        '"Body" : "' + classBody +'"'+
    '}');

    Http h = new Http();
    HttpResponse res = h.send(req);
    // Response to a create should be 201
    if (res.getStatusCode() != 201) {
        System.debug(res.getBody());
        throw new MyException(res.getStatus());
    }
}
5
  • Thank you @meatadaddy. That helped me to understand the basics on tooling API.
    – Soberano
    Commented Aug 26, 2013 at 13:33
  • can some one show me usage of SOAP API for the same. I am not getting any push on how to proceed on the Tooling API SOAP flavour. Thanks in advance.
    – Soberano
    Commented Aug 28, 2013 at 9:10
  • Hi @metadaddy..If i try to create a apex class by using String sampleClass = 'MyNewClass'; String classBody = 'public class ' + sampleClass + ' {\\n' + ' public ' + sampleClass + ' {\\n' + '\\n' + ' }\\n' + '}'; it doesn't work. Throws an SOAP error INVALID_FIELD_FOR_INSERT_UPDATE"..How can i achieve something like that. Commented Jan 10, 2014 at 9:48
  • @ForceDeveloper Ask a new question with more code - it's hard to see what the problem is from one line.
    – metadaddy
    Commented Jan 10, 2014 at 18:10
  • 1
    @metadaddy Thanks for kind words..Posted a question and got the answer also Commented Jan 13, 2014 at 3:46

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .