Streamline API Calls to Your Org from Apex Code
Where: This change applies to Lightning Experience, Salesforce Classic, and all versions of the Salesforce app in Professional, Enterprise, Performance, Unlimited, Developer, and Database.com editions.
Why: Previously, orgs with My Domain enabled could access some API features from Apex code only after setting up remote site settings or named credentials. Some objects, such as DatedExchangeRate, are accessible only through the API. You can now interact with those objects using Apex code, building endpoints with the System.Url.getOrgDomainUrl() method. You can also use the endpoints to access your org’s limits information, invoke flows, interact with list views, and so on. To bypass remote site settings, My Domain must be enabled in your org.
API calls sometimes require a session ID and a URL. You can obtain that session ID using the System.UserInfo.getSessionId() method. This method previously returned null in asynchronous Apex, but it now returns a value whether it’s run synchronously or asynchronously.
How: Use getOrgDomainUrl() in orgs with or without My Domain to retrieve canonical URLs. For example: https://yourDomain.my.salesforce.com, or, for orgs without My Domain enabled https://yourInstance.salesforce.com
Http h = new Http(); HttpRequest req = new HttpRequest(); req.setEndpoint(Url.getOrgDomainUrl().toExternalForm() + '/services/data/v44.0/limits'); req.setMethod('GET'); req.setHeader('Authorization', 'Bearer ' + UserInfo.getSessionId()); HttpResponse res = h.send(req);
You can use getSessionId() both synchronously and asynchronously. In asynchronous Apex (Batch, Future, Queueable, or Scheduled Apex), this method returns the session ID only when the code is run by an active, valid user. When the code is run by an internal user, such as the automated process user or a proxy user, the method returns null.