Calling Salesforce API from a Lightning Component?

I need to call the Apex Wrapper Metadata API from a Lightning component. The issue is that there is no native support for acquiring a valid API session ID from an @AuraEnabled
method in a Lightning component’s Apex controller.
Salesforce documentation suggests using a Named Credential to bypass this security restriction. However, when I set up a Named Credential and pass it as the endpoint for the Metadata Service API, I receive the following error:
FATAL_ERROR System.CalloutException: Web service callout failed:
WebService returned a SOAP Fault: INVALID_SESSION_ID:
This session is not valid for use with the API
faultcode=sf:INVALID_SESSION_ID faultactor=""
I found a workaround using Visualforce, but the source does not reference Named Credentials as a solution. Additionally, I have seen other discussions where developers follow the Named Credential approach but still receive the same error.
Why does the Named Credential feature not bypass the session ID security restriction for Lightning components? How can I successfully call the API from my Lightning component?
Answer
The issue occurs because Named Credentials do not automatically pass the session ID for API calls from a Lightning component. To resolve this, you need to explicitly include the OAuth token in the request header for REST calls or in the request body for SOAP calls. Using {!$Credential.OAuthToken}
ensures authentication without manually retrieving a session ID.
Boost your career with CRS Info Solutions’ Salesforce training , offering expert guidance, practical experience, and comprehensive knowledge—enroll for a free demo now!!!
For a REST callout, you can set the Authorization
header with the merge field {!$Credential.OAuthToken}
.
@AuraEnabled
public static String getOrgLimits() {
HTTP http = new HTTP();
HTTPRequest hres = new HTTPRequest();
hres.setEndpoint('callout:OWNINSTANCE/services/data/v39.0/limits');
hres.setMethod('GET');
hres.setHeader('Authorization', 'Bearer {!$Credential.OAuthToken}'); // Magic happens here
HttpResponse response = http.send(hres);
System.debug(response.getBody());
return response.getBody();
}
Explanation: This Apex method, annotated with @AuraEnabled
, allows a Lightning component to fetch org limits via a REST callout. It constructs an HTTPRequest
, sets the endpoint using a Named Credential (OWNINSTANCE
), and includes an authorization header with the OAuth token ({!$Credential.OAuthToken}
). The request is sent, and the response body is returned and logged for debugging.
For a SOAP callout, you need to include the session ID in the request body instead of the header.
public class EchoManager {
public String endpoint_x = 'callout:Echo_Service';
public String echo(String text) {
WSEchoManager.echo_element request_x = new WSEchoManager.echo_element();
request_x.text = text;
this.SessionHeader = new SessionHeader_element();
this.SessionHeader.sessionId = '{!$Credential.OAuthToken}'; // Magic happens here
}
}
Explanation: The EchoManager
class defines a SOAP callout to an external service using a Named Credential (callout:Echo_Service
). In the echo
method, it creates a request object, assigns the input text, and sets the session ID using {!$Credential.OAuthToken}
to authenticate the call. This approach ensures the API call uses the correct authentication token without manually handling session IDs.
Unlock Your Career Potential: Salesforce Training in Jaipur
Transform your career with comprehensive Salesforce training in Jaipur . Our expertly crafted program covers Admin, Developer, and AI tracks, combining in-depth modules, real-world projects, and interactive sessions to help you master Salesforce. Designed to prepare you for certifications, interviews, and a thriving career in the tech industry, our training ensures you’re industry-ready.
Join our free demo class to experience a hands-on, practical approach to learning. Guided by seasoned professionals, you’ll effortlessly navigate even the most advanced Salesforce concepts. Whether you’re a beginner or seeking to elevate your expertise, our training equips you with the skills to solve real-world problems and excel in your field.
Don’t wait—enroll in our free demo today and take the first step toward a successful Salesforce career!!!
Related Posts:
Http call-out in LWC wire function
Lightning Locker Tools in LWC