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
Michał PiątekMichał Piątek 

Internall callout with SessionId Authorization works only in anonymous apex or if SessionId hardcoded

Hello Saleforce community!

I have encountered really weird problem and can not move forward.

I am making internal callout to /services/data/v51.0/composite/tree/ContentDistribution to create ContentDistribution objects. This is workaround becasue I need these records before making callout,which causes uncommited work pending error.

This code does not work when used inside Apex and I am obtaining erorr message "This session is not valid for use with the REST API":

String baseUrl = URL.getSalesforceBaseUrl().toExternalForm();
        Http h = new Http();
        Httprequest req = new Httprequest();
        req.setMethod('POST');
        
        //req.setHeader('Authorization', 'OAuth' + UserInfo.getSessionId());       
		req.setHeader('Authorization', 'Bearer ' + UserInfo.getSessionId()); 
       
        
req.setHeader('ContentType','application/json');

req.setBody(JSON.serialize(new Map<String,List<DistClass>>{'records' => linksToInsert}));
req.setEndpoint(baseUrl + '/services/data/v51.0/composite/tree/ContentDistribution');

HttpResponse response = h.send(req);
However exact same code works just fine when:
-called from anonymous window
or
- when I print sessionId
System.debug(UserInfo.getOrganizationId().substring(0, 15) + ' ' +  UserInfo.getSessionId().substring(15));
and hardcode it like:
req.setHeader('Authorization', 'Bearer ' + '00D3A0000000001!ARkAQApQe_Omitted_yGifr.u7.';
I was not able to resolve that issue for 2 days. What is wrong here?

 
Vishwajeet kumarVishwajeet kumar
Hello,
I'm not sure if you need to do REST Api call if you are already logged inside salesforce as an user (and authenticated). Please create the object like any other object can be created.

It works from "Developer Console" since "Developer Console" is kind off external tool and uses API's to communicate with salesforce using current user session.

Example :  
ContentDistribution v_record = new ContentDistribution();
//populate fields data
insert v_record;          //bulkify insert if needed

Thanks
Michał PiątekMichał Piątek
In my class I am doint series of callouts to external APIs. At some point I need to have Content Distribution object to use it in callout. Doing DML before callout results in error.
Vishwajeet kumarVishwajeet kumar
Yes, that's salesforce limitation. Is it possible to create 'Content Distribution' object in sepearate transaction (, by some other process like trigger or flow may be) and just query in callout transaction to use it's data.


Thanks