GraphQL API In Salesforce

Rahul Dey
Globant
Published in
8 min readMar 29, 2024
GraphQL in Salesforce

Hey there! In this tutorial, we’ll dive into the world of GraphQL API and its applications within Salesforce. GraphQL is a powerful query language that allows you to request only the data you need, making it efficient and flexible for accessing Salesforce data. We’ll explore how to leverage GraphQL to build robust and dynamic applications, enhancing the way we interact with Salesforce. Let’s get started!

What is GraphQL?

GraphQL is a query language for APIs. It’s also a runtime for fulfilling queries with existing data. Facebook developed it in 2012. It was released to the public in 2015 and has since gained popularity as an alternative to REST APIs.

Facebook originally developed GraphQL to simplify data fetching for their mobile applications. They needed a way to make complex data requests from the server. This way, we had to avoid causing performance issues or over-fetching data.

Salesforce GraphQL API is available in Enterprise, Performance, Unlimited, and Developer Editions.

Why use GraphQL?

We have an organized REST API for sharing data. It follows a clear approach centered around resources. It offers benefits like simplicity and organized data access. However, it can be a bit tricky to adjust quickly to changing client needs. In this case, when the data gets more complex, the routes get longer. Sometimes, it is challenging to fetch the data with a single request. That’s why we use GraphQL.

Benefits of using GraphQL API

There are some advantages of using GraphQL API in Salesforce, such as:

  • Field selection: In GraphQL, when we make a query, we have to specify what information we want in the response. They call this “field selection.” This reduces payload size, as the client only receives fields included in the query.
  • Resource aggregation makes things easier. It exchanges back-and-forth communication between the client and server. They give you a bunch of related stuff all at once in a single response.
  • Schema introspection can send a query to the GraphQL server. It gives information about the types, fields, and relationships within the schema. Combining all these patterns results in more responsive, higher-quality applications.

Quick Starts: GraphQL API

For illustrative purposes, We used the Altair GraphQL client to call upon the GraphQL API. Altair GraphQL Client is an open-source tool. It provides an easy-to-use interface that helps us debug GraphQL queries and implementations.

Prerequisites

  • Install the Altair GraphQL client based on your OS.
  • Create a connected application in Salesforce. Use “Manage user data via Web browsers (web)” OAuth Scopes.

Step 1: Get an Access Token

GraphQL API uses OAuth 2.0, like other Salesforce REST APIs. We generated an Access Token using the Postman client by providing the below values:

Token Name — Give a desired token name

Grant Type — Authorization Code

Callback URL — The one we set on our connected app in Salesforce

Auth URL — https://login.salesforce.com/services/oauth2/authorize

Access Token URL — https://login.salesforce.com/services/oauth2/token

Client ID — Available in Connected App

Client Secret — Available in Connected App

Client Authentication — Send as Basic Auth Header

Snapshot for visualization-

Access token generation
Access Token Generation in Postman

It will generate an access token like below

Generated sample access token
Generated Access Token

Note: There are many ways we can generate access tokens. When we authorize our org from Salesforce IDE (VS Code), it will automatically create a connected application within Salesforce. For example. To display org details, use the command [SFDX: Display Org Details for Default Org] in the command palette. Visual Studio Code shows org details, like Access Token, Alias, API Version, and more.

Getting Access Token in VS Code

Step 2: Send a Request from Altair GraphQL Client

  1. Open the Altair GraphQL client.
  2. Next to the POST option, enter the endpoint. Use this format: https://{MyDomainName}.my.salesforce.com/services/data/v{version}/graphql. For example, https://empathetic-wolf-mtogzq-dev-ed.my.salesforce.com/services/data/v57.0/graphql
  3. Edit the HTTP headers.
  • Click the Set Headers icon (a gear icon) on the sidebar. The Headers prompt appears.
  • For the Header key field, enter Authorization.
  • For the Header value field, enter the access token you generated in step 1. The format is [Bearer access_token]. For example, [Bearer 00DRM000000LnTv!AREAQN.therestofyourtokenhere].
  • Click Save.

4. Back in the main client window, we enter an example query into the query section in the left panel.

# SELECT Id, Name, Website, Phone, Industry FROM Account
query allAccounts {
uiapi {
query {
Account {
edges {
node {
Id
Name {
value
}
Website {
value
}
Phone{
value
}
Industry{
value
}
}
}
}
}
}
}

5. Click Send Request to run the GraphQL query. The response will be populated immediately in the resulting window on the right side. It will have a status of [200 OK].

✅ Tip
Explore and learn GraphQL API using Altair GraphQL Client or using Postman Collection.

Query Records with GraphQL

To perform the query, we are using the Salesforce standard object Account & Contact.

Example 1, Basic GraphQL query

# SOQL Query-> [SELECT Id, Name, Website, Phone, Industry FROM Account]
query allAccounts {
uiapi {
query {
Account {
edges {
node {
Id
Name {
value
}
Website {
value
}
Phone{
value
}
Industry{
value
}
}
}
}
}
}
}
uiapi — It’s a top-level API family
Account — Object to retrieve data
edges / node — These are relay cursor connections spec
value — This is actual data to fetch from each field.

Response

Example 1, Result

Example 2, GraphQL query with filter criteria

#SOQL Query: [SELECT Id, Name, Website, Phone, Industry FROM Account WHERE Name = 'Edge Communications']
query allAccounts {
uiapi {
query {
Account (
where: {
Name: {eq: "Edge Communications"}
}
){
edges {
node {
Id
Name {
value
}
Website {
value
}
Phone{
value
}
Industry{
value
}
}
}
}
}
}
}

Response

Example 2, Result

Example 3, Child to Parent relationship query in GraphQL

#SOQL Query: [SELECT Id, FirstName, LastName, Phone, Account.Name, Account.Industry FROM Contact]
query ContactWithAccount {
uiapi {
query {
Contact {
edges {
node {
Id
FirstName {
value
}
LastName {
value
}
Phone{
value
}
Account{
Name{
value
}
Industry{
value
}
}
}
}
}
}
}
}
Note: As you can see in the above query, we defined the parent object and its fields inside the child object edges and node to get the data. The same goes for the custom objects as well, just need to append with __r.
For example, if Contact has a custom parent object with the API name Account__c. Then in our GraphQL query, we need to define the parent object as Account__r inside the child object edges & node.

Response

Example 3, Result

Example 4, Parent to Child relationship query in GraphQL

#SOQL Query: [SELECT Id, Name, (SELECT FirstName, LastName, Phone FROM Contacts) FROM Account]
query ContactWithAccount {
uiapi {
query {
Account {
edges {
node {
Id
Name {
value
}
Contacts {
edges {
node {
FirstName{
value
}
LastName{
value
}
Phone{
value
}
}
}
}
}
}
}
}
}
}
Note: To query the child object from the parent, specify the child object relationship name, such as Contacts inside the parent object edges and node. Then, inside the relationship, define edges & nodes, and finally, define child object fields to get the results.

Response

Example 4, Result

Example 5, GraphQL query from different tables at once (We query the data from Account, Contact, and Case objects)

query AccountsAndContacts {
uiapi {
query {
Account {
edges {
node {
Id
Name {
value
}
}
}
}
Contact {
edges {
node {
Id
FirstName {
value
}
LastName {
value
}
Phone {
value
}
}
}
}
Case {
edges {
node {
Id
CaseNumber {
value
}
Subject {
value
}
Status {
value
}
}
}
}
}
}
}
Note: GraphQL has a special capability of returning data from multiple tables at once. This is not possible using SOQL query. There doesn’t need to be a relationship between the tables.

Response

Example 5, Result

GraphQL API Query Limitations

Some query limitations need to be considered when using GraphQL API-

  1. GraphQL is bound by the same limitations as SOQL. When working with GraphQL API queries, consider the following limitations.

→ Each GraphQL query can contain many subqueries.
→ Each subquery counts as one request for rate limiting.
→ Each subquery can return up to 2000 records within the same GraphQL query.
→ By default, the first 10 records are returned. We can use pagination information to retrieve additional records.
→ We can query objects that are supported by the User Interface API only.

2. Child-to-parent relationships follow these limits.

→ A query can specify up to 55 child-to-parent relationships. A custom object allows up to 40 relationships.
→ We can specify up to five levels in a child-to-parent relationship.
→ A child relationship name can't be the same as a parent relationship name within an object.

3. Parent-to-child relationships follow these limits.

→ A query can specify up to 20 parent-to-child relationships.
→ We can specify up to five levels in a parent-to-child relationship.
→ A parent relationship name can't be the same as a child relationship name within an object.

4. Additionally, consider these differences between API versions.

→ In API version 57.0 and earlier, we can specify up to two levels of parent-to-child relationship in a query.
→ In API version 58.0 and later, we can specify up to five levels of parent-to-child relationship for standard and custom objects.

Resources

Get Started with GraphQL API

Quick Starts: GraphQL API

Query Records with GraphQL

GraphQL

Paginate Results

GraphQL Wire Adapter for LWC

GraphQL API Wire Adapters and Functions (Beta)

Wrapping Up

Integrating GraphQL into Salesforce has paved the way for developers and enterprises to leverage more effective and adaptable strategies for handling data. GraphQL API facilitates tailored data requests, minimizes excess data retrieval, and offers instant updates, thus enriching the Salesforce environment and elevating the performance of applications.

If you read until now, I trust you found the article enjoyable and gained some new insights.

Certainly! You’re welcome to connect with me on LinkedIn. See you in the next one!

Thank You!!

--

--