I am using Tooling API to create a class. Used the following link as reference to create a class and it works fine. But if i try to make it bit more dynamic by putting Apex Class Name in string and using it in the Body it doesn't work. I am getting following Error : "unexpected token: 'MyNewClass'","errorCode":"INVALID_FIELD_FOR_INSERT_UPDATE".
**EDIT
Following is the code snippet which i ran from the developer console.
String salesforceHost = System.Url.getSalesforceBaseURL().toExternalForm();
String url = salesforceHost + '/services/data/v28.0/tooling/sobjects/ApexClass';
String sampleClass = 'MyNewClass';
String classBody = 'public class ' + sampleClass + ' {\\n'
+ ' public ' + sampleClass + ' {\\n'
+ '\\n'
+ ' }\\n'
+ '}';
HttpRequest req = new HttpRequest();
req.setMethod('POST');
req.setEndpoint(url);
req.setHeader('Content-type', 'application/json');
req.setHeader('Authorization', 'OAuth ' + UserInfo.getSessionId());
req.setBody('{'+
'"Body" : "' + classBody +'"'+
'}');
Http http = new Http();
HTTPResponse res = http.send(req);
String resBody = res.getBody();
Note : if i change the first two lines of classBody it will work i.e.
String classBody = 'public class MyNewClass {\\n'
+ ' public MyNewClass {\\n'
Did i miss anything?
UPDATE
Use Double Back Slash by default since it works all the time. if you want to format the body contents by providing space then single slash may not work at times.
Thanks
MyNewClass
doesn't exist before executing this code? Even if it does it should give aDUPLICATE_VALUE
errorCode and not the above one.. – Sam Jan 10 '14 at 10:20req.setHeader('Authorization', 'Bearer ' + UserInfo.getSessionId());
– Sam Jan 10 '14 at 10:30