Get custom domain of an org using API

Get custom domain of an org dynamically and let's also look at some helpful methods in URL Apex class.

Get custom domain of an org using API

Recently, I was working on a project and I had to get the custom domain using the standard API that Salesforce provides.

On fiddling with the documentation for a couple of hours I stumbled upon few very very useful methods which serve as the Swiss Army Knife as far the request URL is concerned.

Let’s start off with a few methods and finally we will look at how to get the custom domain.

1. Get the base URL.

String sfdcBaseURL = URL.getSalesforceBaseUrl().toExternalForm();
System.debug('Base URL: ' + sfdcBaseURL );

2. Get host from the base URL

System.debug('Host: ' + URL.getSalesforceBaseUrl().getHost()); 

3. Get protocol from the base URL.

System.debug('Protocol: ' + URL.getSalesforceBaseUrl().getProtocol());

4. Get the query string of the current request.

System.debug('Query: ' + URL.getCurrentRequestUrl().getQuery()); 

5. Get custom domain.

String customDomain = URL.getSalesforceBaseUrl().toExternalForm()

Hope this is helpful!