Thursday, August 9, 2018

How to get User Session Id in Future Method or Batch Class

Sometime it is required to perform Callout in future method and Batch apex class. If we use UserInfo.getsessionId() method inside the future method or batch apex, then it will return null.

Below are different option to get sessionId:

Option 1:

We can either pass sessionId as parameter to future method or to batch apex class.

Option 2:

Create a VF page and use {!$Api.Session_ID} in body.  In apex, get VF page content which will contain session Id.

Below is code snippet explaining the Option 2 by using future method. Same can be used in Batch Apex.

Run below code snippet in execute anonymous to check the output in debug logs:


Hope this help!!!

No comments:

Post a Comment