Sub topic 7
Reading usage from the REST Limits resource
This chapter assumes you can send authenticated HTTP requests to the Salesforce REST API and already have an access token and instance URL. You should also know why the daily API request limit exists, which an earlier chapter covered. Here you will read your org's current limit usage on demand.
What the Limits resource returns
The Limits resource is a REST endpoint at /services/data/vXX.X/limits. A GET request returns one JSON object. Each key is a limit name, and each value holds two numbers:
Maxis the ceiling for the org.Remainingis how much is left right now.
The limit for daily API calls is named DailyApiRequests. The same response also covers other limits, such as DailyBulkApiBatches, DailyAsyncApexExecutions, DataStorageMB, and FileStorageMB. The exact list depends on the API version and your edition, so don't hard-code the list of keys.
To get the usage so far, subtract Remaining from Max.
A first call with curl
The quickest check is a single request.
curl -s -H "Authorization: Bearer $ACCESS_TOKEN" \
"$INSTANCE_URL/services/data/v60.0/limits"
# The response is a JSON object keyed by limit name. For example:
# { "DailyApiRequests": { "Max": 15000, "Remaining": 14980 }, ... }The numbers above are illustrative. Your org's maximum depends on its edition and licenses.
The response is large, so pipe it through jq '.DailyApiRequests' if you only want one entry.
Computing a percentage in Python
A raw count is hard to judge. A percentage works better as an alert input, because it means the same thing in every org. The script below reads both the resource and the Sforce-Limit-Info header.
import os
import requests
instance_url = os.environ["INSTANCE_URL"]
token = os.environ["ACCESS_TOKEN"]
resp = requests.get(
f"{instance_url}/services/data/v60.0/limits",
headers={"Authorization": f"Bearer {token}"},
timeout=30,
)
resp.raise_for_status()
daily = resp.json()["DailyApiRequests"]
used = daily["Max"] - daily["Remaining"]
percent = 100 * used / daily["Max"]
print(f"Daily API requests used: {used}/{daily['Max']} ({percent:.1f}%)")
# Every API response also carries the usage header, e.g. "api-usage=25/15000"
header = resp.headers.get("Sforce-Limit-Info", "")
if "api-usage=" in header:
current, maximum = header.split("api-usage=")[1].split("/")[:2]
print(f"From header: {current} of {maximum}")The script does three things:
- It sends the request with a timeout, so a stalled connection cannot hang your monitor.
- It calls
raise_for_status(), so an expired token or an exceeded limit stops the script instead of producing a confusingKeyError. - It reads
Sforce-Limit-Info, which carries the same daily figure on every API response. The next chapter covers that header in detail.
Common errors
- 401 Unauthorized. The access token has expired or is invalid. Refresh it and retry once.
- 403 Forbidden. The user's profile or permission set lacks "API Enabled". This is also the error you may see when the user cannot use the API at all.
- 404 Not Found. The version in the path doesn't exist, or you used the login URL instead of your instance URL. Use the
instance_urlreturned by authentication. - A missing key. A limit you expect isn't in the JSON. Use
.get()and handleNoneinstead of indexing directly. - Using stale numbers. The values are a snapshot. Other integrations and users keep consuming calls, so don't cache the result for long.
When to use this resource
The Limits resource suits scheduled checks, dashboards, and pre-flight checks before a large job. For example, a batch loader can read Remaining first and stop if it cannot finish. It tells you how much is left. It doesn't tell you who used it. For that you need the Setup pages or Event Monitoring, covered in later chapters.
Exercise
Your org's response shows "DailyApiRequests": { "Max": 200000, "Remaining": 50000 }. How many requests have been used, and what percentage of the limit is that?
Show answer
Used = 200000 - 50000 = 150000 requests. Percentage = 100 * 150000 / 200000 = 75%.
Exercise
A monitoring script gets a 403 from the Limits resource, although the same token works in a browser session for other tasks. Name one likely cause.
Show answer
The integration user probably lacks the "API Enabled" permission, so it can't call the REST API. Another possible cause is a connected app or IP restriction that blocks the request. Check the user's profile or permission sets first.