How to get salesforce instance url

To access chatter rest api using APEX code, I need salesforce instance server url in following format:

Is there any method which works in all cases

Case 1: Any Development Org

Case 2: My Domain Enabled

Case 3: Sandbox

Case 4: Managed Package


You are looking for URL.getSalesforceBaseUrl().


The Winter 19 release is introducing another method to get the URL, which will give you the canonical URL for your org: URL.getOrgDomainUrl().

Returns the canonical URL for your org. For example, or, for orgs without My Domain enabled,

Both of the above methods return a System.URL. If you would like the string version, simply call .toExternalForm() on that instance. For example:

String baseUrl = URL.getSalesforceBaseUrl().toExternalForm();

Source : Link , Question Author : Ashish Narang , Answer Author : Adrian Larson

Leave a Comment