When I make request tooling API from Apex by using lightning component, the error This session is not valid for use with the REST API is responsed. Also, the response status code is 401, and status is Unauthorized.

How can we call tooling API without problem when we use lightning component.

By the way, when I use only "Debug - Open Excute Anonymous Window" in Apex, I can get correct and expected response.

Below is the code that I tried.

req = new HttpRequest();
req.setHeader('Authorization', 'Bearer ' + UserInfo.getSessionID());
req.setHeader('Content-Type', 'application/json');
req.setEndpoint(URL.getSalesforceBaseUrl().toExternalForm()+'/services/data/v39.0/tooling/sobjects/GlobalValueSet/(Here is GlobalPickListId)?_HttpMethod=PATCH');
httpreq = new Http();
res = httpreq.send(req);

Thank you in advance.


From lightning session, you cannot invoke callout directly. You need named credential for that.

req.setEndpoint(URL.getSalesforceBaseUrl().toExternalForm()+'/services/data/v39.0/tooling/sobjects/GlobalValueSet/(Here is GlobalPickListId)?_HttpMethod=PATCH');

Create named credential for endpoint and use it.


Go to setup > Named credential as below:

enter image description here

Now, use the endpoint as below in apex:

enter image description here

You can use req.setHeader('Authorization', 'Bearer ' + UserInfo.getSessionID()); in same method.

For further details you can refer to: https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_callouts_named_credentials.htm

  • Thank you for answer Should I edit endpoint code? – Shinya Jul 29 '19 at 0:43
  • Thank you for quick answer. Should I get permission from salesforce in Named credential to do that? – Shinya Jul 29 '19 at 6:29
  • Not needed..... – salesforce-sas Jul 29 '19 at 6:38

When you are making call outs from lightning context, the session Id you get doesn't have the scope or enough permission to make a callout to apis of Salesforce. You can do it in this way

1) a.Create a connected app and register your own domain, and give auth provider as Salesforce b. Create a named credential, and and register your Salesforce domain

2) Before making a callout to tooling api, get session id by making callout to your Salesforce domain, and then use that session id to make a callout to tooling api

  • if possible, could you tell how to do it by apex code or some saledforce setting? – Shinya Jul 29 '19 at 0:42

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