Sub topic 10
GraphQL API for flexible reads
This chapter covers the Salesforce GraphQL API. It explains how a single request can shape its own response, how to paginate and filter, and how errors differ from REST. It also covers when REST or another API is the better choice. It assumes you know HTTP and JSON, can read a SOQL query, and have an access token from the OAuth chapter.
What the GraphQL API is
The GraphQL API lets a client describe exactly which objects, fields, and related records it wants, then returns that shape in one response. It is part of the Salesforce platform and is built on the same foundation as UI API. It enforces the same object permissions, field-level security, and sharing rules as the other APIs.
There is one endpoint, and every call is a POST:
POST /services/data/v60.0/graphqlThe body is JSON with a query string and an optional variables object. The same endpoint handles reads and, in recent API versions, writes (mutations). Authentication works as with REST: send Authorization: Bearer $ACCESS_TOKEN.
The problem it solves
With REST, reading an account and its contacts and owner usually means one of two things:
- Several calls, one per resource.
- A SOQL query with relationship subqueries, where you parse the nested result.
REST resources also return fixed shapes. You often receive more fields than you need, or too few. GraphQL addresses both problems by letting the client choose the fields and the relationships in a single request.
Your first query
This request returns up to five technology accounts. The $industry variable keeps the query text constant while the value changes.
curl -X POST "https://MyDomain.my.salesforce.com/services/data/v60.0/graphql" \
-H "Authorization: Bearer $ACCESS_TOKEN" \
-H "Content-Type: application/json" \
-d '{
"query": "query accountsByIndustry($industry: String) { uiapi { query { Account(first: 5, where: { Industry: { eq: $industry } }) { edges { node { Id Name { value } Industry { value } } } } } } }",
"variables": { "industry": "Technology" }
}'The response mirrors the query:
{
"data": {
"uiapi": {
"query": {
"Account": {
"edges": [
{ "node": { "Id": "001000000000001AAA", "Name": { "value": "Acme Corp" }, "Industry": { "value": "Technology" } } }
]
}
}
}
},
"errors": []
}Note four things about the shape:
- Queries start under
uiapi { query { ... } }. - Each object returns a connection:
edges, and inside each edge anode. This is the standard GraphQL pagination pattern. - Field values are wrapped as
Name { value }. The wrapper can also exposedisplayValuefor formatted or localized output, such as picklist labels or currency formatting.Idis returned as a plain value. - Only the fields you list come back.
Filtering, sorting, and relationships
Filters use a nested object syntax rather than SOQL text.
| SOQL idea | GraphQL form |
|---|---|
| `WHERE Industry = 'Technology'` | `where: { Industry: { eq: "Technology" } }` |
| `AND` of two conditions | `where: { and: [ { ... }, { ... } ] }` |
| `ORDER BY Name ASC` | `orderBy: { Name: { order: ASC } }` |
| `LIMIT 5` | `first: 5` |
| Parent field, such as `Owner.Name` | `Owner { Name { value } }` inside the node |
| Child subquery, such as contacts | `Contacts { edges { node { ... } } }` |
This query reads accounts with their owner and their contacts together:
query accountDetail {
uiapi {
query {
Account(first: 3, orderBy: { Name: { order: ASC } }) {
edges {
node {
Id
Name { value }
Owner { Name { value } }
Contacts(first: 5) {
edges {
node {
LastName { value }
Email { value }
}
}
}
}
}
}
}
}
}Child relationships are connections too, so they accept first, where, and orderBy. The platform limits how deeply you can nest relationships and how many child levels you can request. Check the current developer guide for the exact numbers, because they change between releases.
Pagination
GraphQL pagination is cursor-based. Request pageInfo and totalCount next to edges, then pass endCursor back as after.
query page($cursor: String) {
uiapi {
query {
Account(first: 200, after: $cursor) {
totalCount
pageInfo {
hasNextPage
endCursor
}
edges {
node {
Id
Name { value }
}
}
}
}
}
}A client loop works like this:
- Send the query with
cursorset to null. - Process the edges.
- If
hasNextPageis true, repeat withvariables.cursorset toendCursor. - Stop when
hasNextPageis false.
Cursors suit browsing and moderate loops. They are not a bulk extract mechanism. Each page is a separate API request, so reading millions of rows this way is slow and expensive. Use Bulk API 2.0 for that.
Writing data with mutations
Recent API versions support create, update, and delete mutations in the same uiapi namespace. Each mutation takes an input and returns the fields you ask for.
mutation createAccount {
uiapi {
AccountCreate(input: { Account: { Name: "Acme Corp", Industry: "Technology" } }) {
Record {
Id
Name { value }
}
}
}
}Mutations run with the caller's permissions, and validation rules and triggers fire as usual. Treat GraphQL writes as record-level operations. They are not a replacement for Composite requests when you need all-or-nothing behavior across several records. Check the developer guide for which mutation types your API version supports and how they handle multiple operations in one request.
Errors behave differently from REST
REST signals problems with HTTP status codes: 400, 401, 403, 404. GraphQL often returns HTTP 200 even when part of the request failed. The response carries an errors array next to data.
A response can therefore contain partial results. For example, one field might be inaccessible to the user while the rest resolves. Your client must check:
- The HTTP status. Authentication failures such as an expired token (401) and malformed requests still use HTTP errors.
- Whether
errorsis non-empty. - Whether
datacontains nulls where you expected values.
A minimal check in JavaScript:
async function runGraphQL(instanceUrl, token, query, variables) {
const res = await fetch(`${instanceUrl}/services/data/v60.0/graphql`, {
method: "POST",
headers: {
Authorization: `Bearer ${token}`,
"Content-Type": "application/json",
},
body: JSON.stringify({ query, variables }),
});
if (!res.ok) {
throw new Error(`HTTP ${res.status}: ${await res.text()}`);
}
const body = await res.json();
if (body.errors && body.errors.length > 0) {
throw new Error(`GraphQL errors: ${JSON.stringify(body.errors)}`);
}
return body.data;
}Whether to throw on any error or accept partial data depends on the application. A dashboard might tolerate a missing widget. A sync job should not.
Limits and cost
GraphQL calls count against the same daily API request allocation as REST. One GraphQL request is one call, even if it replaces five REST calls, which is a real saving. However, a request is not free:
- Large, deeply nested queries take longer and can hit query complexity or timeout limits.
- A page size has a maximum, so you cannot ask for unlimited rows in one response.
- Overly wide queries on objects with many relationships can fail even when each part would work separately.
Keep queries as narrow as the screen or job requires. Select only the fields you use and request only the child records you display.
Discovering the schema
GraphQL APIs are self-describing. The Salesforce endpoint supports introspection, so tools such as GraphiQL-style explorers and code generators can list the objects and fields available to the current user. Because the schema reflects the user's permissions, two users can see different schemas. Custom objects and fields appear after they are deployed, so you can write queries against your own data model without extra setup.
When to choose GraphQL
| Situation | Better fit |
|---|---|
| Screen needs a parent, children, and parent lookups in one read | GraphQL |
| Mobile or low-bandwidth client that needs few fields | GraphQL |
| Simple create, read, update, delete on a known record | REST |
| Complex SOQL with aggregates or features GraphQL lacks | REST query |
| Millions of rows to load or extract | Bulk API 2.0 |
| React to changes as they happen | Event APIs |
| Custom server-side logic in the endpoint | Apex REST |
Some caveats apply:
- GraphQL covers a subset of what SOQL can do, although coverage grows with each release. If you cannot express a query, fall back to REST.
- Debugging is less direct. A failing query returns a message about the GraphQL layer, not a SOQL error you can paste into a console.
- Caching is harder. Every call is a POST to one URL, so standard HTTP caching does not help.
Exercise
A mobile app screen shows an account name, its owner's name, and its five most recent contacts. Today it makes three REST calls. Write the GraphQL selection for the account node, and explain one risk to handle when the response comes back.
Show answer
Inside the node of an Account query, select Name { value }, Owner { Name { value } }, and Contacts(first: 5, orderBy: { CreatedDate: { order: DESC } }) { edges { node { LastName { value } } } }. The risk is that the response can have HTTP 200 and still include an errors array or null fields, for example when field-level security hides a field. The client must check errors and handle null values, not assume success from the status code.
Exercise
Why is cursor pagination with GraphQL a poor way to export 20 million Contact records, and what should you use instead?
Show answer
Each page is a separate synchronous API request, so 20 million rows would need many thousands of calls that consume the daily API allocation and run slowly. Bulk API 2.0 runs the query as an asynchronous job and returns results as files, which is designed for this volume.