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
Lightning WarriorLightning Warrior 

How to make callout to tooling api from the queueable apex which is enqueued in scheduler where source and target orgs are same?

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.setEndpoint(endpoint);
req.setMethod('GET'); 
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();
system.debug('dt'+reqresponse);
jsonHelperClass jsonres =  new jsonHelperClass();
jsonres = (jsonHelperClass)JSON.deserialize(reqresponse ,     jsonHelperClass.Class);
public List<RecordWrapper> ListrecordsWrap=new List<RecordWrapper>();
ListrecordsWrap=jsonres.records;
system.debug('jsonres'+ListrecordsWrap[0].MasterLabel);
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.
 
NagendraNagendra (Salesforce Developers) 
Hi Lightning Warrior,

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

Mark this as solved if it's resolved so that it gets removed from the unanswered queue and will become a proper solution for others who are looking for same issue.

Best Regards,
Nagendra.P
SForceBeWithYouSForceBeWithYou

As of API version 44.0, UserInfo.getSessionId() should work in asynchronous Apex contexts.

Thank you sfdcfox, again :-) https://salesforce.stackexchange.com/a/241301/1014