function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
Jun Gao5Jun Gao5 

Issue with creating apex class using tooling api

I am using Tooling API to create an Apex class, I noticed that if the class body has a reference to any object (standard or custom), it throws a compilation error.

For example, if the class body has:
Account a;

the error is: no access to account. 

How do I get around this?
@LaceySnr - Matt Lacey@LaceySnr - Matt Lacey
Where are you using the tooling API from, is it a custom implementation?

Does the profile for the user you're have permission to access any objects at all?
Jun Gao5Jun Gao5
I write an Apex class, sth. like: 
webservice static String createClass(String sClassName, String sClassBody)
{
        JSONGenerator body = JSON.createGenerator(false);
        body.writeStartObject();
        body.writeStringField('Name', sClassName);
        body.writeStringField('Body', sClassBody);
        body.writeEndObject();
        HttpRequest createReq = new HttpRequest();
        createReq.setEndpoint(URL.getSalesforceBaseUrl().toExternalForm() + '/services/data/v30.0/tooling/sobjects/ApexClass');
        createReq.setBody( body.getAsString() );
        createReq.setHeader('Authorization', 'Bearer ' + UserInfo.getSessionID());
        createReq.setHeader('Content-Type', 'application/json');
        createReq.setMethod('POST');
        createReq.setTimeout(30000);
        Http h = new Http();   
        HttpResponse createRes = h.send(createReq);
        Logger.dbg(createRes.getStatusCode());
}

then call this from a button (OnClick JavaScript), the user who clicks the button is System Administrator


@LaceySnr - Matt Lacey@LaceySnr - Matt Lacey
Hmm, that looks ok to me, might be time to fille a case if you're sure the generated JSON string for the body doesn't contain any (apex) syntax errors.
Jun Gao5Jun Gao5
Yeah, it doesn't contain any syntax error. In fact, even if I simply have a line: 

Account a; 

I get the compilation error. If I manually create the class with the exact same code, it works
@LaceySnr - Matt Lacey@LaceySnr - Matt Lacey
Might be worth cross posting this to Salesforce StackExchange, but seems like a bug to me. Out of interest does changing the API version number make a difference? I'd be surprised if so but it can't hurt to try!
Jun Gao5Jun Gao5
Thanks for the replies. 

I was using 30.0, I just tried 31.0, same behavior...
Jochen HeylJochen Heyl
The issue is most likely the interpretation of the body that is passed in. Try it with the most simple body such as 'class fromToolingAPI{}'

I had a lot of trouble knowing when to use \\n vs\n,etc.