Sub topic 2
GraphQL essentials you need for Salesforce
This chapter covers the GraphQL ideas you need before you write queries in a Lightning web component. It assumes you can build a basic LWC (a JavaScript class plus an HTML template). It also assumes you know how @wire and reactive properties work, and that you know Salesforce objects, fields, and relationships. You do not need prior GraphQL experience, but you should have seen a query once.
What GraphQL is
GraphQL is a query language for APIs. A client sends one request that describes exactly which data it wants. The server returns JSON in the same shape as the request.
Compared with a typical REST call, this changes three things:
- You choose the fields. The response contains only what you ask for.
- You can fetch related data in the same request, so you avoid a chain of calls.
- The server publishes a typed schema. Every field, argument, and result type is defined, and invalid queries are rejected before any data is read.
Salesforce exposes its data through a GraphQL API that the graphql wire adapter uses. Later chapters cover the Salesforce-specific schema. Here you learn the language itself.
Operations, fields, and selection sets
A GraphQL document contains an operation. In this tutorial you use the query operation, which reads data. (Mutations, which write data, appear in the last chapter.)
A query is a tree of fields. Curly braces open a selection set, which lists the child fields you want from a parent field.
query accountNames {
uiapi {
query {
Account {
edges {
node {
Id
Name {
value
}
}
}
}
}
}
}Read it from the outside in:
query accountNamesstarts a read operation and gives it a name.uiapiis a field. Salesforce groups its record data under it.- Inside it,
queryis another field, andAccountis a field under that. edges,node,Id, andNameeach narrow the selection further.
Every field that returns an object must have a selection set. A field that returns a plain value, such as a string, does not. In the example, Name is an object, so you must select value from it. Writing Name alone is a validation error.
The operation name (accountNames) is optional, but you should always give one. It makes errors and debugging output easier to read.
The response mirrors the query
The server returns JSON under a top-level data key. Each field you selected appears in the same nesting.
{
"data": {
"uiapi": {
"query": {
"Account": {
"edges": [
{ "node": { "Id": "001000000000001AAA", "Name": { "value": "Acme" } } },
{ "node": { "Id": "001000000000002AAA", "Name": { "value": "Globex" } } }
]
}
}
}
}
}This predictability is the main practical benefit. Once you write the query, you already know the shape of the result and the path to each value.
The response can also contain an errors array. A later chapter covers it in detail. For now, remember that a GraphQL response can carry both data and errors at the same time.
Arguments
Fields can take arguments in parentheses. Arguments change what a field returns. In Salesforce queries you use them to limit the number of records, sort, and filter.
query firstFiveAccounts {
uiapi {
query {
Account(first: 5, orderBy: { Name: { order: ASC } }) {
edges {
node {
Id
Name { value }
}
}
}
}
}
}Here first: 5 is an integer argument. orderBy takes an object, written with braces and key: value pairs. Enumerated values such as ASC are written without quotes, while strings use double quotes. Mixing these up is a common source of validation errors.
| Kind of value | Example | Notes |
|---|---|---|
| Integer | `first: 5` | No quotes |
| String | `after: "abc"` | Double quotes only |
| Enum | `order: ASC` | No quotes, fixed set of names |
| Boolean | `isActive: true` | Lowercase |
| Object | `orderBy: { Name: { order: ASC } }` | Braces, no commas required |
| List | `in: ["Acme", "Globex"]` | Square brackets |
Aliases
If you select the same field twice with different arguments, the response keys would collide. An alias renames a field in the response.
query twoAccountSets {
uiapi {
query {
newest: Account(first: 3, orderBy: { CreatedDate: { order: DESC } }) {
edges { node { Name { value } } }
}
oldest: Account(first: 3, orderBy: { CreatedDate: { order: ASC } }) {
edges { node { Name { value } } }
}
}
}
}The result contains data.uiapi.query.newest and data.uiapi.query.oldest instead of two competing Account keys. Aliases are also useful when you want a response key that reads better in your JavaScript.
Variables
Hard-coding values in a query string works for fixed queries. For queries that change at run time, you declare variables instead.
A variable has three parts:
- A declaration in the operation header:
$first: Int. - A use inside the query:
first: $first. - A value, supplied separately as a JSON object:
{ "first": 10 }.
query accountList($first: Int, $after: String) {
uiapi {
query {
Account(first: $first, after: $after) {
edges { node { Id } }
}
}
}
}The type after the colon must match the argument it feeds. Int is an integer and String is text. A trailing exclamation mark, as in Int!, means the variable is required. Without it, the variable is optional, and the server treats a missing value as null or as "not provided".
Variables matter in LWC for two reasons. First, they keep the query text constant while only the values change, which is exactly what the wire service needs to rerun a query when a reactive value changes. Second, they separate data from query structure. You should never build a query by joining user input into the query string. Pass user input through variables.
Types you will meet
The schema is strongly typed. You do not need to memorize it, but you should recognize the categories.
- Scalars are leaf values:
String,Int,Float,Boolean, andID. Salesforce also defines its own scalars for things like dates. - Object types have fields, and you must select some of those fields.
- Enums are a fixed list of names, such as
ASCandDESC. - Input types are the objects you pass as arguments, such as the value of
orderByorwhere. - Lists hold several items of one type. A
!marks a value that cannot be null.
When a query fails validation, the error message normally names the type and field that did not match. Read it literally. It usually tells you exactly what to change.
Fragments and directives
Two other features appear in GraphQL material that you may read elsewhere.
A fragment is a named, reusable group of fields. It avoids repeating the same selection in several places. This tutorial does not rely on them, and you can write every query here without them.
A directive is an annotation that starts with @, for example @include(if: $flag) or @skip(if: $flag). These switch a field on or off based on a Boolean variable. They are valid GraphQL, but check the Salesforce documentation before you depend on a specific directive, since support varies by API.
How GraphQL differs from SOQL
If you know SOQL, you can map most ideas across. The differences affect how you plan queries.
| Idea | SOQL | GraphQL via uiapi |
|---|---|---|
| Choosing fields | `SELECT Id, Name` | Selection set with `Id` and `Name { value }` |
| Limiting rows | `LIMIT 10` | `first: 10` |
| Sorting | `ORDER BY Name ASC` | `orderBy: { Name: { order: ASC } }` |
| Filtering | `WHERE Name = 'Acme'` | `where: { Name: { eq: "Acme" } }` |
| Parent data | `Account.Name` dot path | Nested selection set |
| Result shape | Flat list of records | Nested `edges` and `node` objects |
The largest practical difference is that SOQL runs in Apex on the server, while GraphQL runs from the component through a wire adapter. You get caching and automatic reruns from the wire service, and you do not need to write an Apex class for read-only data.
Reading a query: a checklist
Before you run a query, walk through it with these questions. They catch most errors early.
- Does every object-typed field have a selection set?
- Does each variable you use have a declaration, and does the declared type match the argument?
- Are strings quoted, and enums and booleans left unquoted?
- Are braces balanced? A missing closing brace is the most common syntax error in long queries.
- Do the field names match the Salesforce API names, including the
__csuffix on custom fields?
Common mistakes
- Selecting an object field without a sub-selection.
Namemust becomeName { value }. - Quoting an enum.
order: "ASC"is invalid. Writeorder: ASC. - Mismatched variable types. Declaring
$first: Stringand using it forfirstfails, becausefirstexpectsInt. - Using the wrong field name. GraphQL field names are case-sensitive and follow the Salesforce API name.
- Expecting a flat result. Data sits inside
edgesandnode. Later chapters show how to flatten it for your template.
Exercise
A query declares query list($count: String) and uses Account(first: $count). It fails validation. What is wrong, and how do you fix it?
Show answer
The first argument expects an integer, but the variable is declared as String. Change the declaration to $count: Int, and pass a number such as { "count": 10 } as the variable value.
Exercise
You select Industry on an Account node and get a validation error. The field exists. What do you change?
Show answer
Industry returns an object type, not a plain scalar, so it needs a selection set. Write Industry { value displayValue } or select only value.
Exercise
You want the three newest and the three oldest accounts in one request. Which GraphQL feature prevents the two Account selections from colliding in the response?
Show answer
Aliases. Write newest: Account(...) and oldest: Account(...), so the response has separate newest and oldest keys.