9

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.

9

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());
    }
}
  • Thank you @meatadaddy. That helped me to understand the basics on tooling API. – Soberano Aug 26 '13 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 Aug 28 '13 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. – ForceDeveloper Jan 10 '14 at 9:48
  • @ForceDeveloper Ask a new question with more code - it's hard to see what the problem is from one line. – metadaddy Jan 10 '14 at 18:10
  • @metadaddy Thanks for kind words..Posted a question and got the answer also – ForceDeveloper Jan 13 '14 at 3:46

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.