I am calling a method imperatively from lwc and its not giving the same result when I am calling same code though anonymous block. Below is my class and when I am calling the method from anonymous block its giving response as System.HttpResponse[Status=OK, StatusCode=200] but while running from lwc its giving System.HttpResponse[Status=Unauthorized, StatusCode=401].

public with sharing class MessageController {
    public static Integer fetchUnreadMessages(){
        Http http = new Http();
        HttpRequest request = new HttpRequest();
        HttpResponse response = new HttpResponse();
        string autho = 'Bearer '+userInfo.getSessionId();
        request.setHeader('Authorization', autho);
        response = http.send(request);
        if (response.getStatusCode() == 200) {
            Map<String, Object> results = (Map<String, Object>) JSON.deserializeUntyped(response.getBody());
            return Integer.valueOf(results.get('unreadCount'));
        return 0;

2 Answers 2


The Lightning Session ID doesn't include REST API privileges, except for a few UI-API calls. You should be able to use the ConnectApi classes to get the information you want for Chatter, or you can use a Named Credential to allow Apex access to the API.


You also have the option to get sessionId from VF page.

Define a VF page

<apex:page contentType="application/json">

then in your apex add a method to get the session id from the vf page

   public static String getSessionIdFromVFP() {
        return Page.SessionIdFromVFP.getContent().toString();

And in your fetchUnreadMessages method call getSessionIdFromVFP to get the session id.

    string autho = 'Bearer '+getSessionIdFromVFP();
    request.setHeader('Authorization', autho);
    response = http.send(request);

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.