Tooling API Named Credential Setup
Salesforce Tooling API can be used to build custom development tools or apps for Lightning Platform applications. I stumbled upon this when I had to build a Lightning App for finding field dependencies.
This blog outlines the steps needed as a prerequisite for using Tooling API in APEX.
Connected App
First, we begin by creating a connected app. We use Connected app to get Client Id and Secret. We need this to setup Auth. Provider in the next step. We also select OAuth Scopes here.
From setup go to App Manager and click the New Connected App button.
Type in App Name, API Name & Email.
For Callback URL enter https://login.salesforce.com/services/authcallback for now. We will update this URL after creating Auth. Provider.
Auth. Provider
Before proceeding to create the Auth. Provider first go to the Connected app we created in previous step. Copy and keep handy the Consumer Key and Consumer Secret.
Configure a Salesforce authentication provider. This auth provider will be used by Named Credential for authentication.
From setup go to Auth. Providers and click the New button.
Fill in following fields and click Save:
Provider Type : Salesforce
Name : PREFERED NAME
URL Suffix : PREFERED NAME
Consumer Key : COPIED FROM CONNECTED APP
Consumer Secret : COPIED FROM CONNECTED APP
Default Scopes : full refresh_token
After you save the Auth. Provider you will get the URLs. Copy Callback URL and replace the dummy callback URL in connected app with the newly generated one.
Named Credential
This is the final step in Tooling API setup. A named credential specifies the URL of a callout endpoint and its required authentication parameters in one definition. We can use this named credential from our APEX code to make the Tooling API callouts.
From setup go to Named Credentials and click the New Legacy button.
Fill in following fields and click Save:
Label : PREFERED LABEL
Name : PREFERED NAME
URL : INSTANCE URL
Identity Type : Named Principal
Authentication Protocol : OAuth 2.0
Authentication Provider : SELECT AUTH. PROVIDER CREATED IN PREVIOUS STEP
Scope : full refresh_token
Notice that the Authentication Status is Pending before the Save.
Save action will redirect you to a login page. Login with the user you want to complete the authentication with. Ideally in a production org this user should be a service account user like integration_user or admin_user.
After successful authentication the Authentication Status for the Named Credential will change to Authenticated as <user_name>.
This completes the setup for Tooling API.
We can now proceed to use this named credential in our APEX code to make API calls to the tooling API.