4

I have a trigger on a custom object which on certain conditions call a future method. The future method calls a Salesforce REST function. This rest function calls a PDF VF page, stores the body as an Attachment under the custom object. Since a REST function requires a session ID, we pass the Session ID using the UserInfo.getSessionId() function.

Everything works fine and the attachment is generated and attached with the proper details. However, when the record for the custom object is generated via Bulk API, the webservice call method gives an error called Unauthorized. The reason for this is I believe that the function doesn't get the proper SessionId.

Does the Bulk API do not generate a session Id which can be used again?

  • Interesting. So the call to UserInfo.getSessionId() isn't returning null in the Bulk API derived trigger context? (It will be null in future, batch and scheduled contexts) Can you see anything related to it under Administration Setup > Security Controls > Session Management? – Daniel Ballinger Jul 5 '15 at 9:21
3

I just tested a very basic Bulk API Job to insert two new contacts. At the same time I created a new trigger for before insert on contacts that contained the following:

string sessionId = UserInfo.getSessionId();
System.debug(LoggingLevel.Error, 'UserInfo.getSessionId(): ' + sessionId);
System.assert(!string.isBlank(sessionId), 'Expected sessionId');

The assertion failed due to the sessionId being null.

From the documentation for UserInfo.getSessionId():

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

As a best practice, ensure that your code handles both cases – when a session ID is or is not available.

It would appear this extends to bulk API DML as well.

You will probably need another method to get a valid session ID in this case.

For example: Session ID from scheduled jobs.

  • Thanks Daniel for the assertion. For now, I have exposed the Rest class on our force.com site. That way I will not need the sessionId to process the request. – RajeshShah Jul 6 '15 at 5:15

Your Answer

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

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