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
Siddharth PatniSiddharth Patni 

getting error [{"message" :"This session is not valid for use with the REST API","errorCode":"INVALID_SESSION_ID"}] while calling tooling api from LWC

String baseURL =  'https://' + System.URL.getSalesforceBaseUrl().getHost();
                String queryStr = 'SELECT+NumLinesCovered,ApexClassOrTriggerId,ApexClassOrTrigger.Name,NumLinesUncovered,Coverage+FROM+ApexCodeCoverageAggregate';
                String ENDPOINT = baseURL + '/services/data/v40.0/tooling/';
               
                HttpRequest req = new HttpRequest();
                req.setEndpoint(ENDPOINT + 'query/?q=' + queryStr);
               
                req.setHeader('Authorization', 'Bearer ' + UserInfo.getSessionID() );
                req.setHeader('Content-Type', 'application/json');
                req.setMethod('GET');
                req.setTimeout(80000);
                system.debug('end'+req);
            Http http = new Http();
            HTTPResponse res = http.send(req);
           


getting error  [{"message" :"This session is not valid for use with the REST API","errorCode":"INVALID_SESSION_ID"}] while calling tooling api  from LWC


I have also used Connected app and named credential its not working while called from lwc. but, working as expected while I call it using annoynomous apex  

 
Best Answer chosen by Siddharth Patni
Maharajan CMaharajan C
Hi Siddharth,

Please read the below content from Salesforce Document: 

For security reasons, the Lightning Component framework places restrictions on making API calls from JavaScript code. To call third-party APIs from your component’s JavaScript code, add the API endpoint as a CSP Trusted Site.
To call Salesforce APIs, make the API calls from your component’s Apex controller. Use a named credential to authenticate to Salesforce.

By security policy, sessions created by Lightning components aren’t enabled for API access. This prevents even your Apex code from making API calls to Salesforce. Using a named credential for specific API calls allows you to carefully and selectively bypass this security restriction.
The restrictions on API-enabled sessions aren’t accidental. Carefully review any code that uses a named credential to ensure you’re not creating a vulnerability.

Link : https://developer.salesforce.com/docs/atlas.en-us.lightning.meta/lightning/apex_api_calls.htm

To overcome this use Named Credentials in your Rest API Call to Tooling API as per Salesforce Suggestion.
https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_callouts_named_credentials.htm

Sample Code for Name Creds used in LWC:
https://medium.com/@gurpreetgill.sfdc/how-to-make-a-http-callout-using-lwc-lightning-web-component-3f9294e39115
https://niksdeveloper.com/salesforce/callout-from-lwc-lightning-web-component/

Other reference link:

https://salesforce.stackexchange.com/questions/311507/invalid-session-id-when-using-lwc-to-call-toolingapi-class
https://salesforce.stackexchange.com/questions/218853/lightning-getting-a-401-when-calling-auraenabled-apex-method-to-do-a-rest-call
https://salesforce.stackexchange.com/questions/348575/how-to-resolve-invalid-session-id-error-on-fetching-tooling-api-data


Thanks,
Maharajan.C

All Answers

Maharajan CMaharajan C
Hi Siddharth,

Please read the below content from Salesforce Document: 

For security reasons, the Lightning Component framework places restrictions on making API calls from JavaScript code. To call third-party APIs from your component’s JavaScript code, add the API endpoint as a CSP Trusted Site.
To call Salesforce APIs, make the API calls from your component’s Apex controller. Use a named credential to authenticate to Salesforce.

By security policy, sessions created by Lightning components aren’t enabled for API access. This prevents even your Apex code from making API calls to Salesforce. Using a named credential for specific API calls allows you to carefully and selectively bypass this security restriction.
The restrictions on API-enabled sessions aren’t accidental. Carefully review any code that uses a named credential to ensure you’re not creating a vulnerability.

Link : https://developer.salesforce.com/docs/atlas.en-us.lightning.meta/lightning/apex_api_calls.htm

To overcome this use Named Credentials in your Rest API Call to Tooling API as per Salesforce Suggestion.
https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_callouts_named_credentials.htm

Sample Code for Name Creds used in LWC:
https://medium.com/@gurpreetgill.sfdc/how-to-make-a-http-callout-using-lwc-lightning-web-component-3f9294e39115
https://niksdeveloper.com/salesforce/callout-from-lwc-lightning-web-component/

Other reference link:

https://salesforce.stackexchange.com/questions/311507/invalid-session-id-when-using-lwc-to-call-toolingapi-class
https://salesforce.stackexchange.com/questions/218853/lightning-getting-a-401-when-calling-auraenabled-apex-method-to-do-a-rest-call
https://salesforce.stackexchange.com/questions/348575/how-to-resolve-invalid-session-id-error-on-fetching-tooling-api-data


Thanks,
Maharajan.C
This was selected as the best answer
Siddharth PatniSiddharth Patni
Thank you so much maharajan ! 
The reference you gave was really helpful.

https://salesforce.stackexchange.com/questions/218853/lightning-getting-a-401-when-calling-auraenabled-apex-method-to-do-a-rest-call


I found the simplest solution - get the session id from apex page. Here we go : Create visualforce page name SessionId. Page content :

<apex:page contentType="text/plain">
          <apex:outputText >{!$Api.Session_ID}</apex:outputText>
</apex:page>

Get session id in the lightning component controller :

private static String getApexSessionId(){
     PageReference reportPage = Page.SessionId;
     if (Test.isRunningTest()) {
           sessionId =UserINfo.getSessionId();
      } else {
           sessionId = reportPage.getContent().toString();
      }
      return sessionId;
}

Thank you again