function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
Kiran Jain 15Kiran Jain 15 

getting error while calling from Js to apex method

hello Experts,
I am getting error while calling apex method from Js but working fine while calling from apex another method or anonymous window.
I am trying to get listView records through listView Id.
I am getting this error => [Status=Unauthorized, StatusCode=401]
Below is my Resources.
Here is my Apex Method
@AuraEnabled(cacheable = true)
       public static void getListviewFilters1(String filterId) {
        HttpRequest req = new HttpRequest();
	    String baseUrl = URL.getSalesforceBaseUrl().toExternalForm();
        system.debug('baseUrl : ' + baseUrl);
	   String endPoinURL = baseUrl+'/services/data/v52.0/sobjects/Account/listviews/'+ filterId +'/describe';
	    req.setEndpoint(endPoinURL);
	    req.setMethod('GET');
        system.debug('req BeforeHeader : ' + req);
           req.setHeader('Authorization', 'Bearer ' + UserInfo.getSessionId());
           req.setHeader('Accept', 'application/json');
           system.debug('req afterHeader : ' + req);
        
	       Http http = new Http();
	       HttpResponse response = http.send(req);
        system.debug('response : ' + response);
		
	if( response.getStatusCode() == 200 ) {
		system.debug(response.getBody());
        Map<String, Object> tokenResponse = (Map<String, Object>) JSON.deserializeUntyped(response.getBody());
        String query = (String) tokenResponse.get('query');
		System.debug(query);
        List<Account> AccountList = new List<Account>();
        for(Account accountObj : database.query(query)){
		AccountList.add(accountObj);
		}
    	system.debug(AccountList.size());
     
	}
	   }

Here is my Lightning Resources
<aura:component controller="ListViewNewVersionInLwcCtrl">
    <aura:attribute name="firstName" type="String" default="world"/>
    <lightning:button label="Call server" onclick="{!c.echo}"/>
</aura:component>


-----------------------------------------------------------------

({
    "echo" : function(cmp) {
        var action = cmp.get("c.getListviewFilters1");
        action.setParams({ filterId : '00B5g000002WfNSEA0' });
        action.setCallback(this, function(response) {
            var state = response.getState();
            alert(state);
            if (state === "SUCCESS") {
                alert("From server: " + response.getReturnValue());
       }
            else if (state === "INCOMPLETE") {
            }
            else if (state === "ERROR") {
                var errors = response.getError();
                if (errors) {
                    if (errors[0] && errors[0].message) {
                        console.log("Error message: " + 
                                 errors[0].message);
                    }
                } else {
                    console.log("Unknown error");
                }
            }
        });
      $A.enqueueAction(action);
    }
   
})

Please help to achieve this requirement. It's very urgent.
It will be best markable.

Thanks In advance
 
Sai PraveenSai Praveen (Salesforce Developers) 
Hi Kiran,

we cannot use sessionid in case of lightning component. As we are not getting the sessionid it is throwing an error.
reference document (https://developer.salesforce.com/docs/atlas.en-us.lightning.meta/lightning/apex_api_calls.htm)
Instead of that we should  create Named Credentials and use it as shown in below reference link.
 (http://https://rajvakatidotcom.wordpress.com/2018/01/28/salesforce-ui-api-lightning-examples/)

Other reference link (http://​​​​​​​https://developer.salesforce.com/forums/?id=9062I000000g6asQAA).

If this solution helps, Please mark it as best answer.

​​​​​​​Thanks
Kiran Jain 15Kiran Jain 15
hi say,
still it's throwing error. I have followed above link and created connected app and etc. but still I'm facing error.
Can you give me any example from where I could get listview records. apart getUiList api because it has getListUi (Deprecated).
Thanks