Salesforce Data Access
Data SDK Requirement
All Salesforce data access MUST use the Data SDK (
). The SDK handles authentication, CSRF, and base URL resolution.
typescript
import { createDataSDK, gql } from "@salesforce/sdk-data";
import type { ResponseTypeQuery } from "../graphql-operations-types";
const sdk = await createDataSDK();
// GraphQL for record queries/mutations (PREFERRED)
const response = await sdk.graphql?.<ResponseTypeQuery>(query, variables);
// REST for Connect REST, Apex REST, UI API (when GraphQL insufficient)
const res = await sdk.fetch?.("/services/apexrest/my-resource");
Always use optional chaining (
,
) — these methods may be undefined in some surfaces.
Preconditions — verify before starting
| # | Requirement | How to verify | If missing |
|---|
| 1 | installed | Check in the UI bundle dir | Cannot proceed — tell user to install it |
| 2 | at project root | Check if file exists | Run from UI bundle dir |
| 3 | Custom objects/fields deployed | Run graphql-search.sh <Entity>
— no output means not deployed | Ask user to deploy metadata and assign permission sets |
If preconditions are not met, you may scaffold components, routes, layout, and UI logic, but use empty arrays /
for data and mark query locations with
// TODO: add query after schema verification
and include in the plan to go back, resolve requirements and write the GraphQL. Do not write GraphQL query strings until the schema workflow is complete.
Supported APIs
Only the following APIs are permitted. Any endpoint not listed here must not be used.
| API | Method | Endpoints / Use Case |
|---|
| GraphQL | | All record queries and mutations via namespace |
| UI API REST | | /services/data/v{ver}/ui-api/records/{id}
— record metadata when GraphQL is insufficient |
| Apex REST | | /services/apexrest/{resource}
— custom server-side logic, aggregates, multi-step transactions |
| Connect REST | | /services/data/v{ver}/connect/file/upload/config
— file upload config |
| Einstein LLM | | /services/data/v{ver}/einstein/llm/prompt/generations
— AI text generation |
Not supported:
- Enterprise REST query endpoint ( with SOQL) — blocked at the proxy level. Use GraphQL for record reads; use Apex REST if server-side SOQL aggregates are required.
- Aura-enabled Apex () — an LWC/Aura pattern with no invocation path from React UI bundles.
- Chatter API () — use
uiapi { currentUser { ... } }
in a GraphQL query instead.
- Any other Salesforce REST endpoint not listed in the supported table above.
Decision: GraphQL vs REST
| Need | Method | Example |
|---|
| Query/mutate records | | Account, Contact, custom objects |
| Current user info | | uiapi { currentUser { Id Name { value } } }
|
| UI API record metadata | | |
| Connect REST | | /connect/file/upload/config
|
| Apex REST | | /services/apexrest/auth/login
|
| Einstein LLM | | /einstein/llm/prompt/generations
|
GraphQL is preferred for record operations. Use REST only when GraphQL doesn't cover the use case.
GraphQL Non-Negotiable Rules
These rules exist because Salesforce GraphQL has platform-specific behaviors that differ from standard GraphQL. Violations cause silent runtime failures.
-
HTTP 200 does not mean success — Salesforce returns HTTP 200 even when operations fail.
Always parse the array in the response body.
-
Schema is the single source of truth — Every entity name, field name, and type must be confirmed via the schema search script before use in a query. Never guess — Salesforce field names are case-sensitive, relationships may be polymorphic, and custom objects use suffixes (
,
). Objects added to UI API in v60+ may use a
suffix (e.g.,
instead of
).
-
on all record fields (read queries) — Salesforce field-level security (FLS) causes queries to fail entirely if the user lacks access to even one field. The
directive (v65+) tells the server to omit inaccessible fields instead of failing. Apply it to every scalar field, parent relationship, and child relationship. Consuming code must use optional chaining (
) and nullish coalescing (
).
-
Correct mutation syntax — Mutations wrap under
uiapi(input: { allOrNone: true/false })
, not bare
. Always set
explicitly. Output fields cannot include child relationships or navigated reference fields.
-
Explicit pagination — Always include
in every query. If omitted, the server silently defaults to 10 records. Include
pageInfo { hasNextPage endCursor }
for any query that may need pagination. Forward-only (
/
) —
/
are unsupported.
-
SOQL-derived execution limits — Max 10 subqueries per request, max 5 levels of child-to-parent traversal, max 1 level of parent-to-child (no grandchildren), max 2,000 records per subquery. If a query would exceed these, split into multiple requests.
-
Only requested fields — Only generate fields the user explicitly asked for. Do NOT add extra fields.
-
Compound fields — When filtering or ordering, use constituent fields (e.g.,
,
), not the compound wrapper (
). The compound wrapper is only for selection.
GraphQL Workflow
| Step | Action | Key output |
|---|
| 1 | Acquire schema | exists |
| 2 | Look up entities | Field names, types, relationships confirmed |
| 3 | Generate query | file or inline tag |
| 4 | Generate types | graphql-operations-types.ts
|
| 5 | Validate | Lint + codegen pass |
Step 1: Acquire Schema
The
file (265K+ lines) is the source of truth.
Never open or parse it directly — no cat, less, head, tail, editors, or programmatic parsers.
Verify preconditions 1–3 (see
Preconditions), then proceed to Step 2.
Step 2: Look Up Entity Schema
Map user intent to PascalCase names ("accounts" →
), then
run the search script from the folder (project root):
bash
bash scripts/graphql-search.sh Account
# Multiple entities:
bash scripts/graphql-search.sh Account Contact Opportunity
The script outputs seven sections per entity:
- Type definition — all queryable fields and relationships
- Filter options — available fields for conditions
- Sort options — available fields for
- Create mutation wrapper —
- Create mutation fields —
<Entity>CreateRepresentation
(fields accepted by create mutations)
- Update mutation wrapper —
- Update mutation fields —
<Entity>UpdateRepresentation
(fields accepted by update mutations)
Maximum 2 script runs. If the entity still can't be found, ask the user — the object may not be deployed.
Entity Identification
If a candidate does not match:
- Try suffix for custom objects, for platform events
- Try suffix — objects added in v60+ may use
- If still unresolved, ask the user — do not guess
Iterative Introspection (max 3 cycles)
- Introspect — Run the script for each unresolved entity
- Fields — Extract requested field names and types from the type definition
- References — Identify reference fields. If polymorphic (multiple types), use inline fragments. Add newly discovered entity types to the working list.
- Child relationships — Identify Connection types. Add child entity types to the working list.
- Repeat if unresolved entities remain (max 3 cycles)
Hard stops: If no data returned for an entity, stop — it may not be deployed. If unknown entities remain after 3 cycles, ask the user. Do not generate queries with unconfirmed entities or fields.
Step 3: Generate Query
Every field name must be verified from the script output in Step 2.
Read Query Template
graphql
query QueryName($after: String) {
uiapi {
query {
EntityName(
first: 10
after: $after
where: { ... }
orderBy: { ... }
) {
edges {
node {
Id
FieldName @optional { value }
# Parent relationship (non-polymorphic)
Owner @optional { Name { value } }
# Parent relationship (polymorphic — use fragments)
What @optional {
...WhatAccount
...WhatOpportunity
}
# Child relationship — max 1 level, no grandchildren
Contacts @optional(first: 10) {
edges { node { Name @optional { value } } }
}
}
}
pageInfo { hasNextPage endCursor }
}
}
}
}
fragment WhatAccount on Account {
Id
Name @optional { value }
}
fragment WhatOpportunity on Opportunity {
Id
Name @optional { value }
}
Consuming code must defend against missing fields:
typescript
const name = node.Name?.value ?? "";
const relatedName = node.Owner?.Name?.value ?? "N/A";
Filtering
graphql
# Implicit AND
Account(where: { Industry: { eq: "Technology" }, AnnualRevenue: { gt: 1000000 } })
# Explicit OR
Account(where: { OR: [{ Industry: { eq: "Technology" } }, { Industry: { eq: "Finance" } }] })
# NOT
Account(where: { NOT: { Industry: { eq: "Technology" } } })
# Date literal
Opportunity(where: { CloseDate: { eq: { value: "2024-12-31" } } })
# Relative date
Opportunity(where: { CloseDate: { gte: { literal: TODAY } } })
# Relationship filter (nested objects, NOT dot notation)
Contact(where: { Account: { Name: { like: "Acme%" } } })
# Polymorphic relationship filter
Account(where: { Owner: { User: { Username: { like: "admin%" } } } })
String equality (
) is case-insensitive. Both 15-char and 18-char record IDs are accepted.
Ordering
graphql
Account(
first: 10,
orderBy: { Name: { order: ASC }, CreatedDate: { order: DESC } }
) { ... }
Unsupported for ordering: multi-select picklist, rich text, long text area, encrypted fields. Add
as tie-breaker for deterministic ordering.
UpperBound Pagination (v59+)
For >200 records per page or >4,000 total records, use
.
must be 200–2000 when set.
graphql
Account(first: 2000, after: $cursor, upperBound: 10000) {
edges { node { Id Name @optional { value } } }
pageInfo { hasNextPage endCursor }
}
Semi-Join and Anti-Join
Filter a parent entity by conditions on child entities using
(semi-join) or
(anti-join) on the parent's
. If the only condition is child existence, use
.
graphql
query SemiJoinExample {
uiapi {
query {
Account(where: {
Id: {
inq: {
Contact: { LastName: { like: "Smith%" } }
ApiName: "AccountId"
}
}
}, first: 10) {
edges { node { Id Name @optional { value } } }
}
}
}
}
Replace
with
for anti-join. Restrictions: no
in subquery, no
in subquery, no nesting joins within each other.
Current User
Use
(no arguments) instead of the standard query pattern:
graphql
query CurrentUser {
uiapi { currentUser { Id Name { value } } }
}
Field Value Wrappers
Schema fields use typed wrappers — access via
:
| Wrapper Type | Underlying | Wrapper Type | Underlying |
|---|
| | | |
| | | |
| | | |
| | | |
| | | |
| | | |
| | | |
| | | |
All wrappers also expose
(server-rendered via
/
) — use for UI display instead of formatting client-side.
Mutation Template
Mutations are GA in API v66+. Three operations: Create, Update, Delete.
graphql
# Create
mutation CreateAccount($input: AccountCreateInput!) {
uiapi(input: { allOrNone: true }) {
AccountCreate(input: $input) {
Record { Id Name { value } }
}
}
}
# Update — must include Id
mutation UpdateAccount {
uiapi(input: { allOrNone: true }) {
AccountUpdate(input: { Id: "001xx000003GYkZAAW", Account: { Name: "New Name" } }) {
Record { Id Name { value } }
}
}
}
Input constraints:
- Create: Required fields (unless ), only fields, no child relationships. Reference fields set by (e.g., ).
- Update: Must include , only fields, no child relationships.
- Delete: only.
- type: The field in Update and Delete inputs uses the type, which accepts either a literal record ID (e.g., ) or a mutation chaining reference (). Reference fields in Create inputs (e.g., ) also accept for chaining.
- Raw values: No commas, currency symbols, or locale formatting (e.g., not ).
Output constraints:
- Create/Update: Exclude child relationships, exclude navigated reference fields (only member allowed). Output field is always named .
- Delete: only.
- (default) — All operations succeed or all roll back.
- — Independent operations succeed individually, but dependent operations (using ) still roll back together.
Mutation Chaining
Chain related mutations using
references to
from earlier mutations. Required for parent-child creation (nested child creates are not supported).
graphql
mutation CreateAccountAndContact {
uiapi(input: { allOrNone: true }) {
AccountCreate(input: { Account: { Name: "Acme" } }) {
Record { Id }
}
ContactCreate(input: { Contact: { LastName: "Smith", AccountId: "@{AccountCreate}" } }) {
Record { Id }
}
}
}
Rules:
must come before
in the query.
is always the
from mutation
. Only
or
can be chained from (not
).
Delete Mutation
Delete uses generic
(not entity-specific). Output is
only — no
field.
graphql
mutation DeleteAccount($id: ID!) {
uiapi(input: { allOrNone: true }) {
AccountDelete(input: { Id: $id }) {
Id
}
}
}
Object Metadata & Picklist Values
Use
uiapi { objectInfos(...) }
to fetch field metadata or picklist values. Pass
either or
— never both.
typescript
// Object metadata
const GET_OBJECT_INFO = gql`
query GetObjectInfo($apiNames: [String!]!) {
uiapi {
objectInfos(apiNames: $apiNames) {
ApiName
label
labelPlural
fields { ApiName label dataType updateable createable }
}
}
}
`;
// Picklist values (use objectInfoInputs + inline fragment)
const GET_PICKLIST_VALUES = gql`
query GetPicklistValues($objectInfoInputs: [ObjectInfoInput!]!) {
uiapi {
objectInfos(objectInfoInputs: $objectInfoInputs) {
ApiName
fields {
ApiName
... on PicklistField {
picklistValuesByRecordTypeIDs {
recordTypeID
picklistValues { label value }
}
}
}
}
}
}
`;
Step 4: Generate Types (codegen)
After writing the query (whether in a
file or inline with
), generate TypeScript types:
bash
# Run from UI bundle dir
npm run graphql:codegen
Output:
src/api/graphql-operations-types.ts
Generated type naming conventions:
- / — response types
<OperationName>QueryVariables
/ <OperationName>MutationVariables
— variable types
Always import and use the generated types when calling
:
typescript
import type { GetAccountsQuery, GetAccountsQueryVariables } from "../graphql-operations-types";
const response = await sdk.graphql?.<GetAccountsQuery, GetAccountsQueryVariables>(GET_ACCOUNTS, variables);
Use
to extract the node type from a Connection for cleaner typing:
typescript
import { type NodeOfConnection } from "@salesforce/sdk-data";
type AccountNode = NodeOfConnection<GetAccountsQuery["uiapi"]["query"]["Account"]>;
Step 5: Validate & Test
- Lint: from UI bundle dir
- codegen: from UI bundle dir
Common Error patterns
| Error Contains | Resolution |
|---|
| / | Field name wrong — re-run graphql-search.sh <Entity>
|
| Type name wrong — verify PascalCase entity name via script |
| Argument wrong — check Filter/OrderBy sections in script output |
| / | Fix syntax per error message |
| / | Correct argument type from schema |
invalid cross reference id
| Entity deleted — ask for valid Id |
| Check object availability and API version |
is not currently available in mutation results
| Remove field from mutation output |
Cannot invoke JsonElement.isJsonObject()
| Use API version 64+ for update mutation selection |
On PARTIAL If a mutation returns both data and errors (partial success): Report inaccessible fields, explain they cannot be in mutation output, offer to remove them. Wait for user consent before changing.
UI Bundle Integration (React)
Two integration patterns:
Pattern 1 — External file (complex queries)
One operation per file. Each file contains exactly one
or
(plus its fragments). Do not combine multiple operations in a single file.
typescript
import { createDataSDK, type NodeOfConnection } from "@salesforce/sdk-data";
import MY_QUERY from "./query/myQuery.graphql?raw"; // ?raw suffix required
import type { GetMyDataQuery, GetMyDataQueryVariables } from "../graphql-operations-types";
const sdk = await createDataSDK();
const response = await sdk.graphql?.<GetMyDataQuery, GetMyDataQueryVariables>(MY_QUERY, variables);
After creating/changing
files, run
to generate types into
src/api/graphql-operations-types.ts
.
Pattern 2 — Inline tag (simple queries)
Must use — plain template strings bypass ESLint schema validation.
typescript
import { createDataSDK, gql } from "@salesforce/sdk-data";
import type { GetAccountsQuery } from "../graphql-operations-types";
const GET_ACCOUNTS = gql`
query GetAccounts {
uiapi {
query {
Account(first: 10) {
edges { node { Id Name @optional { value } } }
}
}
}
}
`;
const sdk = await createDataSDK();
const response = await sdk.graphql?.<GetAccountsQuery>(GET_ACCOUNTS);
Error Handling
typescript
// Strict (default) — any errors = failure
if (response?.errors?.length) {
throw new Error(response.errors.map(e => e.message).join("; "));
}
// Tolerant — log errors, use available data
if (response?.errors?.length) {
console.warn("GraphQL partial errors:", response.errors);
}
// Discriminated — fail only when no data returned
if (!response?.data && response?.errors?.length) {
throw new Error(response.errors.map(e => e.message).join("; "));
}
const accounts = response?.data?.uiapi?.query?.Account?.edges?.map(e => e.node) ?? [];
REST API Patterns
Use
when GraphQL is insufficient. See the
Supported APIs table for the full allowlist.
typescript
declare const __SF_API_VERSION__: string;
const API_VERSION = typeof __SF_API_VERSION__ !== "undefined" ? __SF_API_VERSION__ : "65.0";
// Connect — file upload config
const res = await sdk.fetch?.(`/services/data/v${API_VERSION}/connect/file/upload/config`);
// Apex REST (no version in path)
const res = await sdk.fetch?.("/services/apexrest/auth/login", {
method: "POST",
body: JSON.stringify({ email, password }),
headers: { "Content-Type": "application/json" },
});
// UI API — record with metadata (prefer GraphQL for simple reads)
const res = await sdk.fetch?.(`/services/data/v${API_VERSION}/ui-api/records/${recordId}`);
// Einstein LLM
const res = await sdk.fetch?.(`/services/data/v${API_VERSION}/einstein/llm/prompt/generations`, {
method: "POST",
body: JSON.stringify({ promptTextorId: prompt }),
});
Current user: Do not use Chatter (
). Use GraphQL instead:
typescript
const GET_CURRENT_USER = gql`
query CurrentUser {
uiapi { currentUser { Id Name { value } } }
}
`;
const response = await sdk.graphql?.(GET_CURRENT_USER);
Directory Structure
<project-root>/ ← SFDX project root
├── schema.graphql ← grep target (lives here)
├── sfdx-project.json
├── scripts/graphql-search.sh ← schema lookup script
└── force-app/main/default/uiBundles/<app-name>/ ← UI bundle dir
├── package.json ← npm scripts
└── src/
| Command | Run From | Why |
|---|
| UI bundle dir | Script in UI bundle's package.json |
| UI bundle dir | Generate GraphQL types |
| UI bundle dir | Reads eslint.config.js |
bash scripts/graphql-search.sh <Entity>
| project root | Schema lookup |
Quick Reference
Schema Lookup (from project root)
Run the search script to get all relevant schema info in one step:
bash
bash scripts/graphql-search.sh <EntityName>
| Script Output Section | Used For |
|---|
| Type definition | Field names, parent/child relationships |
| Filter options | conditions |
| Sort options | |
| CreateRepresentation | Create mutation field list |
| UpdateRepresentation | Update mutation field list |
Error Categories
| Error Contains | Resolution |
|---|
| Field name is wrong — run graphql-search.sh <Entity>
and use the exact name from the Type definition section |
| Type name is wrong — run graphql-search.sh <Entity>
to confirm the correct PascalCase entity name |
| Argument name is wrong — run graphql-search.sh <Entity>
and check Filter or OrderBy sections |
| Fix syntax per error message |
| Field name is wrong — run graphql-search.sh <Entity>
to verify |
| Correct argument type from schema |
invalid cross reference id
| Entity deleted — ask for valid Id |
Checklist