How do I call the Salesforce API from a Lightning Component?

When working with Lightning Components, you may run into scenarios where you need to make API calls to Salesforce itself, such as calling the Metadata API or querying org limits. A common issue developers face is that there is no direct way to acquire a valid API session ID from an @AuraEnabled
method in the Apex controller. Even though Salesforce documentation suggests using Named Credentials to bypass this restriction, developers often encounter the INVALID_SESSION_ID
error when attempting to call the API through a Named Credential inside a Lightning component.
The root of the issue is that while Named Credentials are meant to handle authentication seamlessly, they still require you to explicitly pass the session token in the request header or body. Simply referencing the Named Credential as the endpoint is not enough. The workaround is to leverage the special merge fields that Salesforce provides within Named Credentials, particularly {!$Credential.OAuthToken}
. This ensures that the system injects a valid session token into your callout request dynamically.
One approach is to use REST API calls. For example, if you want to fetch the current org limits, you can write an Apex method like this:
@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();
}
In this code, a simple REST GET request is sent to the limits
endpoint of your org. The critical part is the Authorization
header, where instead of manually passing a session ID, you inject {!$Credential.OAuthToken}
. This placeholder is automatically replaced with a valid access token from the Named Credential. As a result, you do not need to worry about session expiration or invalid session issues.
If you are calling a SOAP API, the same principle applies, but instead of passing the token in the header, you embed it in the request body. Consider this SOAP example:
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
// SOAP callout logic continues here
}
}
Here, the SessionHeader
object requires a sessionId
. Instead of retrieving the session manually, you once again use {!$Credential.OAuthToken}
, which Salesforce replaces with the active token at runtime. For REST APIs, the merge field goes in the header, while for SOAP APIs, you inject it into the body as part of the SessionHeader
.
Therefore, the solution to bypassing the INVALID_SESSION_ID
issue in Lightning components when using Named Credentials is to explicitly replace the session ID using merge fields. For REST calls, you add it in the header as a Bearer
token, and for SOAP calls, you include it in the body. This ensures that every API request is authenticated properly without exposing or hardcoding sensitive session details.
Aspect | REST API Approach | SOAP API Approach |
---|---|---|
Where to place token | In the HTTP Header as Authorization: Bearer {!$Credential.OAuthToken} | In the Request Body as SessionHeader.sessionId = '{!$Credential.OAuthToken}' |
Ease of implementation | Easier, since headers are simpler to set in Apex HTTPRequest | Slightly more complex, since you must modify the request body with the session ID |
Example use case | Fetching org limits, records, or other standard Salesforce REST endpoints | Calling Metadata API or custom SOAP web services |
Recommended when | Using lightweight data calls or when Salesforce provides REST endpoints | Required if the API is only available as a SOAP service |
Security advantage | Session is automatically injected into headers via Named Credential | Session is automatically injected into body via Named Credential |
Here are the pros and cons of both approaches to help decide which to use:
REST API with Merge Fields
Pros: Very easy to implement with fewer lines of code. Most Salesforce standard APIs provide REST support. Headers are straightforward to manage and work well in Apex. Lightweight and faster compared to SOAP.
Cons: Not all Salesforce APIs are available as REST. Some metadata operations may not be supported. Limited in handling very complex structured data compared to SOAP.
SOAP API with Merge Fields
Pros: Required for APIs like the Metadata API that are only SOAP-based. Supports more complex operations where REST may not provide endpoints. Works seamlessly once {!$Credential.OAuthToken}
is injected in the request body.
Cons: More verbose and complex to implement. Requires additional WSDL-based generated classes. Slightly harder to debug due to SOAP envelope structures. Performance can be slower compared to REST.

Here’s the final recommendation flowchart that guides decision-making for choosing between REST and SOAP. The process is simple:
Start by checking if the API provides a REST endpoint. If yes, choose REST since it’s lightweight, faster, and easier to use.
If REST is not available, check for a SOAP API. If yes, then use SOAP, which is more structured and supports metadata or complex integrations.
If neither REST nor SOAP exists, the integration is not possible without custom solutions.
This gives you a REST-first, fallback to SOAP decision-making framework.
Enroll for Career-Building Salesforce Training with Real-Time Projects
Our Salesforce Course is structured to provide a deep understanding of the Salesforce platform, equipping you with the essential skills to excel in the CRM industry. This program covers fundamental modules like Salesforce Admin, Developer, and AI, combining theoretical knowledge with hands-on practice. By engaging in real-world projects and practical assignments, you’ll develop the expertise to solve complex business challenges using Salesforce solutions. Our expert trainers ensure you gain both technical proficiency and industry insights to succeed in the Salesforce ecosystem.
Beyond technical learning, our Salesforce Training in Canada includes personalized mentorship, certification assistance, and interview preparation to enhance your career prospects. You’ll have access to extensive study resources, real-world project experience, and dedicated support throughout the program. By the end of the course, you’ll be fully prepared for certification exams and possess the problem-solving skills that employers seek. Start your Salesforce journey with us and unlock new career opportunities—Sign up for a Free Demo today!