3

I am getting invalid session Id when i try to perform callout using continuation api . If i remove continuation api code and perform a normal callout the the same code is working.

Below is the code

@AuraEnabled(continuation=true cacheable=true)
    public static Object continuationapi(){
        list<account> ListAccount=new List<account>();
        String endPoint = 'callout:SFDC_SRC/services/apexrest/v1/getAccounts/';
        Http h2 = new Http();
        HttpRequest req1 = new HttpRequest();

        req1.setMethod('GET');
        req1.setEndpoint(endPoint);
        Continuation con = new Continuation(40);
        con.continuationMethod='processResponse';
        con.state='Hello, World!';    
            con.addHttpRequest(req1);
        system.debug('Action Mehtod con ---'+ con);
        return con;

    }

    @AuraEnabled(cacheable=true)
    public static Object processResponse(List<String> labels, Object state) {  
    HttpResponse response = Continuation.getResponse(labels[0]);
        Integer statusCode = response.getStatusCode();
        system.debug('Location Details'+response.getHeader('Location'));
            system.debug('Status code ----'+ statusCode);
        String result = response.getBody();
    system.debug('Call back method result --- ' + result);
        return result;

    }

Target org code

@RestResource(urlMapping='/v1/getAccounts/')
global class FetchAccounts {
    @HttpGet
    global static list<account> fetchAccount(){

    RestRequest req = RestContext.request;
    RestResponse res = Restcontext.response;
    List<account> listAccount =[Select Id , Name,Industry,Type,AccountNumber from Account LIMIT 3 ];
        return listAccount ;
    }
}

1 Answer 1

1

As you are declaring endpoint directly in class String endPoint = 'callout:SFDC_SRC/services/apexrest/v1/getAccounts/';, you are getting invalid session Id error. Refer to this document: (Holds true for lightning - Aura or LWC)

By security policy, sessions created by Lightning components aren’t enabled for API access. This restriction prevents even your Apex code from making API calls to Salesforce. Using a named credential for specific API calls allows you to carefully and selectively bypass this security restriction.
The restrictions on API-enabled sessions aren’t accidental. Carefully review any code that uses a named credential to ensure you’re not creating a vulnerability.

Create a named credential and use it as end-point.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .