I am calling tooling api from my Queueable apex to get information of flow object from my org and scheduling it on daily basis. Now my problem is when I run my code from anonymous window with Authorization header set to 'Bearer '+Userinfo.sessionId(), It works fine. But when i schedule it, it returns error saying :"Session expired or invalid","errorCode":"INVALID_SESSION_ID". I think the reason is scheduler runs in system context and in that case Userinfo.sessionId() is returned as null. So is there any way to make tooling api callouts from scheduler or Queueable? Here is my code-

String endpoint = 'https://lightningwarrior-dev-ed.my.salesforce.com/services/data/v37.0/tooling/query?q=Select+Id,processtype,Description,LastModifiedDate,MasterLabel,Status,LastModifiedById,VersionNumber+From+Flow';

HttpRequest req = new HttpRequest();
req.setHeader('Content-Type', 'application/json');
req.setHeader('Authorization', 'Bearer ' + UserInfo.getSessionID());

Http httpreq = new Http();
HttpResponse res = httpreq.send(req);
String reqresponse = res.getBody();
jsonHelperClass jsonres =  new jsonHelperClass();
jsonres = (jsonHelperClass)JSON.deserialize(reqresponse ,     jsonHelperClass.Class);
public List<RecordWrapper> ListrecordsWrap=new List<RecordWrapper>();
public class jsonHelperClass
    public List<RecordWrapper> records;
    public jsonHelperClass()

public class RecordWrapper
    Public String Id;
    Public String ProcessType;
    Public String Description;
    Public String MasterLabel;
    Public String Status;
    Public Integer VersionNumber;
    public Id LastModifiedById;
    public Datetime LastModifiedDate;
    public RecordWrapper()

Thanks in advance.

  • batch / future, same issue
    – Eric
    Oct 7 '16 at 7:48

I recommend you to use SOAP or REST API to login from your scheduled context and get a SessionId for using in your logic.

Here is an example for you, hope this will help you: https://gist.github.com/richardvanhook/1245068

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