Sub topic 14
Running SOSL through the REST API
This chapter assumes you can write a FIND query with a RETURNING clause, that you know the braces form of the search expression, and that you know what an OAuth access token is. You do not need Apex for this chapter. The REST API lets any program that can send an HTTPS request run SOSL. Examples include a script, a middleware service, and a mobile app.
How the search endpoint works
The REST API exposes SOSL at one resource:
GET /services/data/v60.0/search/?q=<URL-encoded SOSL>The version number (v60.0 here) is part of the path. Use a version your org supports. You send the query in the q query-string parameter. The request needs two things:
- The
instance_urlreturned when you authenticated, for examplehttps://yourdomain.my.salesforce.com. - An
Authorization: Bearer <access token>header.
The server runs the search as the authenticated user and returns JSON.
Differences from SOSL in Apex
The query text is mostly the same, but four things change.
| Topic | SOSL in Apex | SOSL through REST |
|---|---|---|
| Search term syntax | Single quotes (`FIND 'Acme*'`) or braces | Braces only (`FIND {Acme*}`) |
| Bind variables | `FIND :term` in static SOSL | Not available. You build the full string. |
| Result shape | `List<List<SObject>>`, one list per RETURNING object | One flat `searchRecords` array |
| Security context | System mode unless you add `WITH SECURITY_ENFORCED` or `WITH USER_MODE` | Runs as the authenticated user |
The last row matters most. A REST search honors the user's object permissions, field-level security, and sharing. You usually do not need to add enforcement clauses for that. It also means the same query can return different rows for different tokens.
A first request
Use curl with --get and --data-urlencode so the tool encodes the query for you. This avoids most manual encoding errors.
curl --get "$INSTANCE_URL/services/data/v60.0/search/" \
-H "Authorization: Bearer $ACCESS_TOKEN" \
--data-urlencode "q=FIND {Acme*} IN NAME FIELDS RETURNING Account(Id, Name), Contact(Id, FirstName, LastName)"A trimmed response looks like this:
{
"searchRecords": [
{
"attributes": {
"type": "Account",
"url": "/services/data/v60.0/sobjects/Account/001000000000001AAA"
},
"Id": "001000000000001AAA",
"Name": "Acme Corp"
},
{
"attributes": {
"type": "Contact",
"url": "/services/data/v60.0/sobjects/Contact/003000000000001AAA"
},
"Id": "003000000000001AAA",
"FirstName": "Wile",
"LastName": "Coyote"
}
]
}Apex gives you separate lists, so you know the type from the index. REST mixes all records into one array. Read attributes.type on each record to learn which object it belongs to. Do not assume the records are grouped by object or ordered the way RETURNING lists them.
Encoding and escaping
Two separate steps protect the query, and each solves a different problem.
- URL encoding makes the query safe to put in a URL. Spaces, braces, and quotes must be percent-encoded.
curl --data-urlencodeand theparamsargument in Python'srequestslibrary do this for you. - SOSL escaping makes user text safe inside the search expression. In the braces form, these characters have special meaning:
? & | ! { } [ ] ( ) ^ ~ * : \ " ' + -To search for one literally, put a backslash in front of it. If you skip this step, a user who types Acme) OR ( can change the meaning of your search or cause a parse error. String.escapeSingleQuotes is for the single-quoted form in Apex. It is not enough for the braces form.
Note that escaping * removes the wildcard. If you want to let users type a trailing wildcard, escape the term first and then append * yourself.
A complete client in Python
This script reads credentials from environment variables, escapes the user's text, and groups the flat result by object type.
import os
import re
from collections import defaultdict
import requests
API_VERSION = "v60.0"
RESERVED = re.compile(r'([?&|!{}\[\]()^~*:\\"\'+\-])')
def escape_sosl(text: str) -> str:
"""Backslash-escape characters that are special inside FIND {...}."""
return RESERVED.sub(r"\\\1", text)
def search_accounts_and_contacts(term: str) -> dict:
instance_url = os.environ["INSTANCE_URL"]
token = os.environ["ACCESS_TOKEN"]
sosl = (
"FIND {" + escape_sosl(term) + "*} IN NAME FIELDS "
"RETURNING Account(Id, Name LIMIT 10), "
"Contact(Id, FirstName, LastName LIMIT 10)"
)
response = requests.get(
f"{instance_url}/services/data/{API_VERSION}/search/",
headers={"Authorization": f"Bearer {token}"},
params={"q": sosl},
timeout=30,
)
response.raise_for_status()
grouped = defaultdict(list)
for record in response.json()["searchRecords"]:
grouped[record["attributes"]["type"]].append(record)
return grouped
if __name__ == "__main__":
results = search_accounts_and_contacts("Acme")
for account in results["Account"]:
print("Account:", account["Name"])
for contact in results["Contact"]:
print("Contact:", contact["FirstName"], contact["LastName"])The requests library URL-encodes params for you, so the script never encodes by hand. The per-object LIMIT 10 keeps one object from using up the whole result budget. This works the same way as in Apex.
Errors you will see
The API reports problems with an HTTP status and a JSON array of error objects.
| Status | Typical cause | What to check |
|---|---|---|
| 400 | Malformed SOSL, such as a missing brace, an unescaped reserved character, or a misspelled field | The `message` text names the problem. Test the query in a SOSL tool first. |
| 401 | Expired or invalid access token | Refresh the token and retry once. |
| 403 | The user lacks API access, or a limit was reached | Check the profile or permission set and the org's API request limit. |
| 404 | Wrong path or an API version that does not exist | Check the URL and version. |
An error body looks like this:
[
{
"message": "\nFIND {Acme) OR (}\n ^\nERROR at Row:1:Column:11\nunexpected token: ')'",
"errorCode": "INVALID_SEARCH"
}
]A 400 on a query that worked yesterday often points to a field or object the user can no longer see. Check permissions before you change the query.
Limits and cost
- Each call counts against the org's daily REST API request allocation. A search is one call, no matter how many objects it covers.
- A SOSL query returns at most 2,000 rows in total. REST has no
queryMore, so you cannot page past that. If you need a stable page, give each object its ownLIMITandOFFSET, as covered in the chapter on per-object filters. - The search index lags behind writes. A record you created a moment ago may not appear yet. This is the same behavior that makes
Test.setFixedSearchResultsnecessary in Apex tests. - Searching many objects with
ALL FIELDScosts more than naming a few objects and a narrow scope. Keep RETURNING short for latency-sensitive callers.
When to use parameterized search instead
For simple lookups, Salesforce also offers a parameterized search resource that takes plain parameters and builds the SOSL for you:
GET /services/data/v60.0/search/parameterizedSearch/?q=Acme&sobject=Account&Account.fields=Id,Name&Account.limit=10You then never write FIND or RETURNING, and the escaping rules are lighter. The trade-off is control. You cannot express arbitrary logical operators or the WHERE filters that SOSL supports, so use the SOSL endpoint when you need them.
Exercise
A web service calls the search endpoint with q=FIND {Acme} RETURNING Account(Id, Name), Contact(Id, LastName). The response has a flat searchRecords array. How does the client tell which records are accounts and which are contacts, and why can't it rely on position in the array?
Show answer
Each record carries an attributes object, and attributes.type holds the object name (Account or Contact). The client reads that value to group the records. It cannot rely on position because REST returns one flat list, not one list per RETURNING object like Apex, so the array is not guaranteed to be grouped or ordered by the RETURNING clause.
Exercise
A user types the text a) OR (b into a search box. Your client builds FIND {a) OR (b*} and gets a 400 INVALID_SEARCH error. What two fixes are needed before the request is sent, and which one should be done by the HTTP library?
Show answer
First, escape SOSL reserved characters in the user's text with backslashes, so the term becomes a\) OR \(b, then append your own wildcard. Second, URL-encode the whole q value. The HTTP library (for example requests with params, or curl with --data-urlencode) should do the URL encoding. The SOSL escaping must be done by your own code.