I am trying to create Skills through the REST API (in an apex class) and I am getting a 401 back from salesforce.

Note - Skills are new and cannot be inserted through normal DML operations, hence the need for REST.

Here is the code:

    HttpRequest req = new HttpRequest();
    if(LiveAgentPreChat__c.getInstance('LiveAgentPreChatConfig')!=null) {
        req.setEndpoint(LiveAgentPreChat__c.getInstance('LiveAgentPreChatConfig').WebserviceEndPoint__c +'/services/data/v28.0/sobjects/Skill/');
    req.setHeader('Authorization', 'OAuth ' + UserInfo.getSessionId());
    req.setHeader('Content-Type', 'application/json; charset=UTF-8');
    req.setHeader('Accept', 'application/json');
    req.setBody('{"DeveloperName": "' + DevName + '","MasterLabel": "' + SklLabel + '"}');
    Http http = new Http();
    return req;

EDIT - I have found a solution. Since I am using the session Id I do need to use Bearer instead of OAuth. Also, this method is getting called in a batch class, so UserInfo.getSessionId() returns null in a batch. Just grabbed the session Id from a different spot and passed it to the method and it worked.

  • Shouldn't the authorization be Bearer rather than OAuth? – Doug B Jun 9 '14 at 15:52
  • @DougB Actually that line should be commented out. Technically I already have a session Id since this this is all within the same salesforce instance. – Cup O Noodles Jun 9 '14 at 15:54
  • Does that apply when you are making a callout? Can you try it with the "Authorization" "Bearer <SessionID>" ? – Doug B Jun 9 '14 at 16:17
  • I figured out a solution @DougB - I posted an edit in my question. Your suggestion was part of it. Thanks! – Cup O Noodles Jun 9 '14 at 16:30
  • 1
    I am also in a similar situation. What is your workaround for grabbing the session Id when calling the method from a batch class? Thanks in Advance! – user37897 Oct 3 '16 at 7:43

Your Answer

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

Browse other questions tagged or ask your own question.