14 Replies Latest reply on Mar 4, 2020 4:25 AM by Vishal Khedkar

    Calling Remedyforce's REST API from Lightning Web Component

    Lior Lavi
      Share This:

      Hi everyone,

      I'm having problem trying to access BMC's Remedyforce REST API from a Lightning web component. According to Salesforce documentation it is not possible to access external APIs using Javascript. Instead, we should use an Apex method with Named Credentials, but when I'm trying to do it I get this error:

       

      [{"message":"This session is not valid for use with the REST API","errorCode":"INVALID_SESSION_ID"}]

       

      This is my JS code which is triggered from button onclick event:

      import { LightningElement } from 'lwc';

      import getAllCategories from '@salesforce/apex/SelfServicePortalLightning.getAllCategories';

      export default class Srdform extends LightningElement {
          getCategories(){
              getAllCategories().then(
                  result =>{
                      console.log(result);
                  }
              );
          }
      }

       

      This is my Apex code:

      @AuraEnabled
          public static String getAllCategories(){

              Http h = new Http();
              HttpRequest req = new HttpRequest();

              req.setEndpoint('callout:Remedyforce');
              req.setHeader('Authorization', 'Bearer ' + UserInfo.getSessionId());
              req.setMethod('GET');
             
              HttpResponse res = h.send(req);
             
              return res.getBody();
          }

       

      This is the error I'm getting in the Chrome Devtools console:

      [{"message":"This session is not valid for use with the REST API","errorCode":"INVALID_SESSION_ID"}]

       

      This is the named credential definition:

       

      Label: Remedyforce

      Name: Remedyforce

      URL: https://menorarf--lightning.cs100.my.salesforce.com/services/apexrest/BMCServiceDesk/1.0/Category

      Identity Type: Anonymous

      Authentication Protocol:  No Authentication

      Generate Authorization Header: true

      Allow Merge Fields in HTTP Header: true

      Allow Merge Fields in HTTP Body: true

       

      I've set all the relevant domains in both CSP Trusted Sites and Remote Site Settings.

       

      When I try to create and use session Id with SOAP UI I'm successful, When I'm trying to get to a public API, not BMC's, with no Authorization header I'm successful. It seems that the session ID Salesforce generates for me while using lightning web component is blocked from being used in REST API, even though I'm using named credentials.