Sub topic 14
Tooling API for development tools
This chapter assumes you can call the REST API with a bearer token, write basic SOQL, and read simple Apex. It also assumes you have seen the Metadata API chapter. The Tooling API is the API that development tools use to inspect and change code and configuration at a finer grain than the Metadata API allows.
What the Tooling API is
The Tooling API is a REST and SOAP API for building custom development tools for Salesforce. It exposes metadata as individual records that you can query and modify. Examples are Apex classes, triggers, Visualforce pages, Lightning components, debug logs, and code coverage results.
The Metadata API works with whole components packaged in files, and you retrieve or deploy them in bulk. The Tooling API works with one component at a time and returns small, targeted results. This makes it a good fit for editors, IDE extensions, and diagnostic scripts, where speed on small operations matters more than moving a full deployment.
The Tooling API is not meant for business data. Use the REST API for Accounts, Contacts, and other records.
Where it sits among the APIs
| Question | Metadata API | Tooling API | REST API |
|---|---|---|---|
| What does it work with? | Configuration as files and packages | Individual development components as records | Business data records |
| Typical operation | Retrieve or deploy a set of components | Query, create, or update one component | CRUD on records |
| Typical client | Deployment tools, CI pipelines | IDEs, code analysis, log tools | Integrations and apps |
| Granularity | Coarse | Fine | Per record |
Endpoint and authentication
The Tooling API uses the same OAuth 2.0 access tokens as the REST API. The REST resources live under a separate path:
https://MyDomain.my.salesforce.com/services/data/v60.0/tooling/
The user behind the token needs permissions that match the work. For example, querying or editing Apex generally requires the "Author Apex" permission, and some operations require "View All Data" or "Modify Metadata" style permissions. If a call fails with an insufficient-access error, check the profile or permission sets of the integration user first.
Querying with the Tooling API
The Tooling API has its own query endpoint, and it queries Tooling objects, not standard objects. The SOQL looks familiar, but the set of objects and some of the supported clauses differ from the REST API.
curl -G "https://MyDomain.my.salesforce.com/services/data/v60.0/tooling/query" \
--data-urlencode "q=SELECT Id, Name, ApiVersion, Status FROM ApexClass WHERE Name LIKE 'Account%' LIMIT 10" \
-H "Authorization: Bearer $ACCESS_TOKEN"The response has the same shape as a REST query response: totalSize, done, and a records array. Each record carries an attributes block with its type and url.
To see which Tooling objects exist, call the describe resource:
curl "https://MyDomain.my.salesforce.com/services/data/v60.0/tooling/sobjects" \
-H "Authorization: Bearer $ACCESS_TOKEN"Common Tooling objects
| Object | Purpose |
|---|---|
| ApexClass | Source and metadata of an Apex class |
| ApexTrigger | Source and metadata of an Apex trigger |
| ApexLog | Debug log entries |
| TraceFlag | Turns on debug logging for a user or class |
| DebugLevel | Defines how detailed logging is |
| ApexCodeCoverageAggregate | Lines covered and uncovered per class or trigger |
| ApexTestResult | Outcome of individual test methods |
| CustomField | Field definitions, including some detail not exposed in standard describe calls |
| MetadataContainer, ContainerAsyncRequest | Save and compile groups of components |
Executing anonymous Apex
The Tooling API includes a resource that runs an Apex snippet and returns compile and run results. This is what the "Execute Anonymous" feature in developer consoles relies on.
curl -G "https://MyDomain.my.salesforce.com/services/data/v60.0/tooling/executeAnonymous" \
--data-urlencode "anonymousBody=System.debug('Hello from the Tooling API');" \
-H "Authorization: Bearer $ACCESS_TOKEN"The response contains compiled, success, compileProblem, exceptionMessage, and exceptionStackTrace. A script that calls this resource should check compiled first and then success, because a compile failure and a runtime failure are reported in different fields.
Treat this resource with care. It runs arbitrary code with the permissions of the calling user, so restrict it to sandboxes and development orgs.
Saving code with a container
Changing the body of an Apex class is not a simple PATCH in most orgs. Production orgs block direct edits of Apex through the API. In sandboxes and developer orgs, the usual pattern uses a container so that several components compile together:
- Create a
MetadataContainer. - Add one or more member records, such as
ApexClassMember, that point to the component and hold the new body. - Create a
ContainerAsyncRequestthat references the container. Salesforce compiles and saves the members asynchronously. - Poll the request until its
StateisCompleted,Failed,Invalidated, orError. If it is notCompleted, readCompilerErrors.
The following Python script follows these steps. It assumes requests is installed and that the environment variables hold a valid instance URL, token, and class Id. Run it in a sandbox.
import os
import time
import requests
BASE = os.environ["INSTANCE_URL"] + "/services/data/v60.0/tooling"
HEADERS = {
"Authorization": "Bearer " + os.environ["ACCESS_TOKEN"],
"Content-Type": "application/json",
}
CLASS_ID = os.environ["APEX_CLASS_ID"]
def post(path, body):
r = requests.post(BASE + path, headers=HEADERS, json=body)
r.raise_for_status()
return r.json()
container = post("/sobjects/MetadataContainer", {"Name": "demo_container"})
new_body = "public class Greeter { public static String hi() { return 'hi'; } }"
post("/sobjects/ApexClassMember", {
"MetadataContainerId": container["id"],
"ContentEntityId": CLASS_ID,
"Body": new_body,
})
request = post("/sobjects/ContainerAsyncRequest", {
"MetadataContainerId": container["id"],
"IsCheckOnly": True,
})
while True:
r = requests.get(
BASE + "/sobjects/ContainerAsyncRequest/" + request["id"],
headers=HEADERS,
)
r.raise_for_status()
state = r.json()
if state["State"] != "Queued":
break
time.sleep(2)
print(state["State"], state.get("CompilerErrors"))
requests.delete(BASE + "/sobjects/MetadataContainer/" + container["id"], headers=HEADERS)IsCheckOnly set to True compiles without saving, which is a safe way to validate a change. Set it to False to save. The script deletes the container at the end because unused containers accumulate and are easy to forget.
Debug logs and test coverage
Two common uses need no code changes.
To capture a log, create a DebugLevel and a TraceFlag for a user. Then query ApexLog and fetch a log body with GET /tooling/sobjects/ApexLog/{id}/Body. Trace flags expire, so set StartDate and ExpirationDate and renew them if your tool runs for a long time.
To read coverage, run tests, then query coverage:
curl -G "https://MyDomain.my.salesforce.com/services/data/v60.0/tooling/query" \
--data-urlencode "q=SELECT ApexClassOrTrigger.Name, NumLinesCovered, NumLinesUncovered FROM ApexCodeCoverageAggregate" \
-H "Authorization: Bearer $ACCESS_TOKEN"Coverage reflects the most recent test runs. Compute a percentage as NumLinesCovered / (NumLinesCovered + NumLinesUncovered), and handle the case where both are zero.
Common errors and gotchas
- Wrong path. Calling
/services/data/v60.0/queryfor a Tooling object fails. Use/tooling/query. - Production edits blocked. Saving Apex directly in production returns an error. Deploy through the Metadata API or a change set instead.
- Missing permission. An integration user without "Author Apex" or related access cannot read or write code.
- Ignoring async state. A
ContainerAsyncRequestthat has not finished has no useful compiler errors. Wait for the final state. - Treating it as a deployment tool. The Tooling API can change single components, but it does not give you the dependency handling, ordering, and test-run controls of a Metadata API deployment.
- Stale API versions. Some Tooling objects and fields appear only from a given API version. Use a version your org supports.
When to choose it
Choose the Tooling API when you build or script a developer workflow: an editor plugin, a log viewer, a coverage report, a code-analysis job, or a check for field usage. Choose the Metadata API when you move configuration between orgs. Choose the REST API when the data is business data.
Exercise
A team wants a nightly script that lists every Apex class in a sandbox whose test coverage is below 75 percent. Which API should it use, which endpoint and object, and why not the REST API's standard query endpoint?
Show answer
Use the Tooling API. Query ApexCodeCoverageAggregate (with ApexClassOrTrigger.Name, NumLinesCovered, NumLinesUncovered) through /services/data/v60.0/tooling/query, then compute the percentage in the script. Coverage data is a development artifact exposed only as a Tooling object. The standard /query endpoint serves business objects and does not know this object.
Exercise
Your tool submits a ContainerAsyncRequest and immediately reads CompilerErrors, which is empty, so it reports success. What is wrong and how do you fix it?
Show answer
The request is asynchronous and was probably still Queued. Poll the record until State is no longer Queued. Report success only when State is Completed, and read CompilerErrors when State is Failed or another non-Completed final state.