Sub topic 10
Finding records with SOQL queries
You can create, read, and update a record when you know its ID. Often you don't. This chapter shows how to find records by their field values with SOQL, the Salesforce Object Query Language, through the REST API query endpoint.
Prerequisites
This chapter assumes you can send authenticated requests as shown in earlier chapters. You need the SF_INSTANCE_URL, SF_ACCESS_TOKEN, and SF_API_VERSION environment variables. You should also know what an sObject, a field, and a record ID are.
How the query endpoint works
SOQL looks like SQL, but it queries one Salesforce object at a time and has no SELECT *. You list each field you want. You send the statement to the query resource in the q parameter of a GET request.
curl -G "$SF_INSTANCE_URL/services/data/$SF_API_VERSION/query" \
-H "Authorization: Bearer $SF_ACCESS_TOKEN" \
--data-urlencode "q=SELECT Id, Name, Industry FROM Account WHERE Industry = 'Banking' LIMIT 10"The -G flag makes curl send the data as a query string on a GET request. --data-urlencode escapes spaces and quotes in the statement. Without that escaping, the request often fails with a malformed query error.
Reading the response
A successful query returns status 200 and a JSON body like this:
{
"totalSize": 1,
"done": true,
"records": [
{
"attributes": {
"type": "Account",
"url": "/services/data/v60.0/sobjects/Account/001xx000003DGb2AAG"
},
"Id": "001xx000003DGb2AAG",
"Name": "Acme Corp",
"Industry": "Banking"
}
]
}| Key | Meaning |
|---|---|
| `totalSize` | Number of records the query matched in total |
| `done` | `true` when this response holds all the results |
| `records` | The matching records, one object each |
| `attributes` | Object type and record URL, added to every record |
| `nextRecordsUrl` | Present only when `done` is `false`. Fetch it to get the next batch. |
Handling large result sets
Salesforce returns results in batches. When there are more records than fit in one response, done is false and nextRecordsUrl holds a path. Request that path on your instance URL until done is true.
import os
import requests
instance_url = os.environ["SF_INSTANCE_URL"]
token = os.environ["SF_ACCESS_TOKEN"]
version = os.environ.get("SF_API_VERSION", "v60.0")
headers = {"Authorization": f"Bearer {token}"}
soql = "SELECT Id, Name, Industry FROM Account WHERE Industry = 'Banking'"
response = requests.get(
f"{instance_url}/services/data/{version}/query",
headers=headers,
params={"q": soql},
timeout=30,
)
response.raise_for_status()
body = response.json()
records = list(body["records"])
while not body["done"]:
response = requests.get(
f"{instance_url}{body['nextRecordsUrl']}",
headers=headers,
timeout=30,
)
response.raise_for_status()
body = response.json()
records.extend(body["records"])
print(f"Fetched {len(records)} accounts")The params argument makes requests URL-encode the statement for you.
Common errors
- Unescaped statement. Building the URL by hand with spaces and quotes in it fails. Use
--data-urlencodeorparams. - Unquoted string values. Text values need single quotes, as in
Industry = 'Banking'. Double quotes are not valid string delimiters in SOQL. - Unknown field or object. The API returns status 400 with the error code
INVALID_FIELDorINVALID_TYPE. Check the spelling against the object's fields. - Expired token. Status 401 with
INVALID_SESSION_IDmeans you need a new access token. - Building a statement from user input. Untrusted text inserted into the
qvalue can change the query, which is called SOQL injection. Validate the input, and escape single quotes and backslashes with a backslash.
Exercise
A query returns "done": false and a nextRecordsUrl value. What should your code do, and why?
Show answer
It should send a GET request to the instance URL plus the nextRecordsUrl path, add the returned records to the ones already collected, and repeat until done is true. Salesforce returns large results in batches, so the first response holds only part of the data.