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
Jingli Hu 3Jingli Hu 3 

How to pass session id in trigger?

Hi, 

we have a trigger which has a future method which call an API call out, we need to pass session id (UserInfo.getSessionId) to the API. But API complains invalid session id. Exactly same code( except not in future method) works in controller. Any ideas how to get session id in trigger?

thanks
Alain CabonAlain Cabon
Hi,

For Apex code that is executed asynchronously, such as @future methods, Batch Apex jobs, or scheduled Apex jobs, getSessionId returns null.

So you need to pass the UserInfo.getSessionId as a parameter to the @future method which calls an API call out.

Regards
Jingli Hu 3Jingli Hu 3
Hi Alain,

Thanks for your response! 

We already doing what you suggest. we are in lightning experience. The wired thing is we found out it works in classic but not in lightning. even though we thought the trigger wouldn't matter whether in classic or lightning.
Alain CabonAlain Cabon
Could you post your code here?
Jingli Hu 3Jingli Hu 3
the person from the post had exactly same issue. https://salesforce.stackexchange.com/questions/110515/getting-session-id-in-lightning the solution is kind of hack and I am not sure whether there is more up to date solution for it.

the sample code of future method in trigger like below. again the code is working in classic but not in lightning. we are calling an API of Apttus managed package we installed.

   //Generate UCDP Agreement form
    @future(callout=true)
    public static void generateUCDPForm(string agreementId, string sessionId) {
        if (agreementId != null) {
            APTS_GenerateandSendAPI generateAPI = new APTS_GenerateandSendAPI();
            docId = generateAPI.doGenerate(agreementId, sessionId);
    }
}
Alain CabonAlain Cabon
Ok, that is the API of Apttus managed package that is not "'Lightning ready" perhaps (check in AppExchange).

The hack is heavy because it needs the installation of the Andrew Fawcett's well-known MetadataService
https://salesforce.stackexchange.com/questions/110515/getting-session-id-in-lightning

Apex Wrapper Salesforce Metadata API​: a great tool to provide the metadata features lacking in standard Apex 
https://github.com/financialforcedev/apex-mdapi

I use the Metadataservice (an inescapable popular tool with forks now even if the main site is still up to date)