0

The following code returns a 200 response when run from Classic (via a js button call to a webservice)

but the same code fails when the webservice method is called from an aura controller I get a 401 response code

    HttpRequest request = new HttpRequest();
    HttpResponse response = null;
    Http http = new Http();

    request.setMethod('GET');
    request.setHeader('Authorization', 'Bearer ' + UserInfo.getSessionId());
    request.setEndpoint(URL.getSalesforceBaseUrl().toExternalForm() + '/services/data/v31.0/analytics/reports/' + this.ReportId + '/describe');

    response = http.send(request);

    if(response.getStatusCode() != 200) {

        throw new InvalidOperationException('ReportFilterQueryBuilder::GetReportFilterFromMetadata Exception Error=Could not access Report Analytics API.');
    }

Should I be constructing a different URL when in LEX?

Any help would be appreciated!

1 Answers1

1

Lightning Aura controllers do not receive an API-enabled Session Id. You won't be able to directly call any REST API from an Aura Apex controller without otherwise acquiring access to an API-enabled session.

The documented solution is to use Named Credentials:

To call Salesforce APIs, make the API calls from your component’s Apex controller. Use a named credential to authenticate to Salesforce.

Because you're calling the Reports and Dashboards API, this may be undesirable (since the results are typically user context-specific). There is a popular work-around that involves rendering a Visualforce page to extract an API-enabled session Id from its content. It's laid out on SFSE in an answer here.

David Reed
  • 92,733
  • 13
  • 84
  • 157