Many services are probably happy when they expose one API to the world. Not Salesforce. Why have just one API when you can have 12?
But the truth is these 12 APIs each serve a specific purpose for developers looking to build on top of the Salesforce platform or interact with Salesforce data. They give developers an immense amount of power to effectively rebuild Salesforce functionality and data anywhere they choose, from a new mobile app to integrating with a legacy ERP. And they can not just get the data, but the UI components, the tooling, and the analytics.
So which should you use and when? That’s what we’re looking into here. The 12 Salesforce APIs we’ll look at today are:
- REST API
- SOAP API
- Connect REST API
- Analytics REST API
- Apex REST API
- Apex SOAP API
- Bulk API 2.0
- GraphQL API
- User Interface API
- Pub/Sub API
- Tooling API
- Metadata API
Let’s go through the use cases for each. First, though, a quick detour to look at the underlying protocols Salesforce is using with their APIs.
SOAP vs. REST
As you look through all the Salesforce APIs, you’ll see some duplication, with only REST or SOAP being the difference, such as the Apex REST API and the Apex SOAP API. What’s the difference here?
SOAP (Simple Object Access Protocol) is a protocol for exchanging structured information in web services using XML and has a strict format definition. SOAP's messaging structure allows for a lot of information in each request and response, but the downside is that each message requires more bandwidth. A benefit of SOAP, especially for larger organizations, is that SOAP comes with built-in WS-Security, offering enterprise-level security features, such as maintaining the confidentiality and integrity of messages. Though SOAP tends to be more complex, it may be a good choice for enterprise applications where robustness, strict contracts, and advanced security features are paramount.
REST (Representational State Transfer), on the other hand, is an architectural style for creating web services, and it works directly over HTTP using standard methods like GET, POST, DELETE, and PUT. REST treats server objects as resources, accessed via URLs. Unlike SOAP, REST can use multiple formats like XML, JSON, and text, with JSON being the most commonly used due to its lightweight nature. REST's stateless nature allows it to be highly scalable and efficient, making it an excellent choice for web and mobile applications. While REST depends on the underlying transport protocol for security, it makes up for it by being simple, requiring fewer resources, and being easy to implement and use.
If you are building something new and for the web, you are probably going to want to use the REST API versions. If you are building an integration for an enterprise system, like an ERP, you might use SOAP.
There are a couple of other types of APIs that are used by Salesforce:
- GraphQL. GraphQL is a query language for APIs and a runtime for executing those queries with your existing data. It offers clients the power to request exactly what they need, reducing the amount of data that needs to be transferred over the network and improving performance.
- gRPC. gRPC (Google Remote Procedure Call) is a high-performance, open-source framework developed by Google. It uses Protocol Buffers as its interface definition language, allowing for easy definition of services and message types, and supports multiple programming languages. gRPC is particularly well-suited for creating scalable microservices due to its support for bidirectional streaming and flow control.
Choosing the right Salesforce API
The choice of which API to use depends less on the protocol you want–SOAP, REST, GraphQL, gRPC–and ultimately what you want to use the API for. Are you accessing CRM data? Trying to understand the analytics of your pipeline? Building a new sales application? Or export all your data to another service? For each problem, Salesforce has an API solution.
Let’s walk through the twelve API options and show why you would choose each.
1. Use the Salesforce REST API if you need to access your Salesforce data in a mobile or web app
The Salesforce REST API offers a simple way to interact with the Salesforce platform. If you are just trying to access your records within Salesforce to read, create or update them, the REST API is a great option:
- It’s easy to use: The REST API is simple to understand and use, which can reduce development time and costs. It uses standard HTTP methods like GET, POST, DELETE, and PATCH which are familiar to most developers.
- It allows for data manipulation: You can perform basic CRUD (Create, Read, Update, Delete) operations on Salesforce records.
- You can use SOQL queries: The Salesforce Object Query Language (SOQL) and Salesforce Object Search Language (SOSL) queries in your API requests to fetch, search, and manipulate data.
Here’s some example code to create a record in Salesforce using the REST API:
const url = 'https://MyDomainName.my.salesforce.com/services/data/v58.0/sobjects/Account/';
const headers = {
'Content-Type': 'application/json',
'Authorization': 'Bearer access_token'
};
const body = JSON.stringify({
'Name': 'Test Account'
});
async function createRecord(url, headers, body) {
const response = await fetch(url, {
method: 'POST',
headers: headers,
body: body
});
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
} else {
const responseBody = await response.json();
return responseBody;
}
}
createRecord(url, headers, body)
.then(response => console.log(response))
.catch(e => console.log('Error:', e));
In this example, we're trying to create a new Account record with the name 'Test Account'. The URL targets the Account object in the Salesforce REST API, and the HTTP method is 'POST' to create a new record. We're passing the access token in the Authorization header for authentication (which we would get from the OAuth authentication flow), and the body contains the data for the new record.
You can also use SOQL (Salesforce Object Query Language) with the REST API, allowing you to directly query your salesforce database:
const url = 'https://MyDomainName.my.salesforce.com/services/data/v58.0/query';
const headers = {
'Content-Type': 'application/json',
'Authorization': 'Bearer access_token'
};
const params = new URLSearchParams({
q: 'SELECT Name, Id FROM Account'
});
async function executeQuery(url, headers, params) {
const response = await fetch(`${url}?${params}`, {
method: 'GET',
headers: headers
});
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
} else {
const responseBody = await response.json();
return responseBody;
}
}
executeQuery(url, headers, params)
.then(response => console.log(response))
.catch(e => console.log('Error:', e));
In this example, we're using the 'query' resource of the Salesforce REST API. The SOQL query is passed as the q parameter in the URL. Our query is SELECT Name, Id FROM Account to select the name and ID of all Account records.
2. Use the Salesforce SOAP API if you need to access your Salesforce data in an ERP or legacy system
SOAP has been around for a while, and many older systems are built with technologies that integrate more easily with SOAP than with REST. This is especially true of financial and ERP systems–exactly the kind of systems you might want to integrate with Salesforce.
These applications are generally written in a compiled language such as Java or C# and you can easily pass them the XML body used with SOAP. SOAP also has functionality that lends itself to enterprise applications:
- WS-Security: If your application needs a high level of security, you might choose SOAP because it supports WS-Security, which includes some enterprise security features that REST APIs do not inherently support, such as message-level security, identity through intermediaries, and security negotiation.
- Transactional: If you want to send multiple requests to the server as part of a single transaction, you might choose SOAP. The Salesforce SOAP API supports sending multiple requests in a single API call, which can make your integration more efficient. The SOAP API also supports queryMore operation which is useful to retrieve larger datasets.
- Stateful Operations: Unlike the REST API, the SOAP API provides the ability to maintain session state between multiple API calls. For instance, if you log in via SOAP API, you receive a sessionId that can be used for subsequent calls until the session is terminated.
- Strong Typing: SOAP uses XML for requests and responses, and XML schemas define the structure of the messages. This enforces strong typing, which can be advantageous in some scenarios.
- Asynchronous Processing: SOAP API supports asynchronous processing, which can be particularly useful when managing or manipulating large amounts of data, as well as for fire-and-forget style invocations.
The choice between SOAP and REST really depends heavily on the requirements of the application you're building.
3. Use the Salesforce Connect REST API if you need to integrate with Salesforce features
The Salesforce Connect REST API is an ideal choice when you need to integrate external systems or applications with a wide range of Salesforce features such as B2B Commerce for Lightning, CMS managed content, Experience Cloud sites, files, notifications, Chatter feeds, users, and groups, among others.
- B2B Commerce for Lightning: The API can be used to fetch details such as the status of a specific order or customer information from the B2B Commerce platform. This helps in maintaining real-time updates and insights on the B2B Commerce operations.
- CMS Managed Content: The Connect API allows you to query the latest articles or content that have been published within Salesforce's Content Management System. This can be useful for content-driven applications, for showcasing updated articles, blogs, etc.
- Experience Cloud Sites: Developers can leverage the API to obtain configuration details or setup information for specific Experience Cloud sites, aiding in effective site management.
- File Management: The API can be used to fetch information about recently uploaded files, their metadata, or the details of who uploaded them. This can be useful in managing document flow and version control in a project.
- Notifications: Keeping users up-to-date, the Connect API can fetch the latest notifications for a user and count unread notifications.
- Chatter Integration: This API can be used to display Chatter feeds, groups, and user activities. It can fetch information like the latest posts in a group, group members, and recent activities of a user. Also, it can be used to understand the trending topics in Chatter, facilitating effective communication within an organization.
Here’s an example of using this API to retrieve a news feed item with the Chatter integration:
async function fetchNewsFeed() {
const url = 'https://MyDomainName.my.salesforce.com/services/data/v58.0/chatter/feeds/news/me/feed-elements';
const options = {
method: 'GET',
headers: {
'Authorization': `Bearer access_token`,
'Content-Type': 'application/json',
},
};
const response = await fetch(url, options);
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
const data = await response.json();
return data;
}
fetchNewsFeed()
.then(response => console.log(response))
.catch(e => console.log('Error:', e));
The JSON data structure returned by this API is lightweight and easy to parse, making it particularly valuable for developers building mobile applications, as it simplifies the process of accessing and interacting with these Salesforce services.
4. Use the Salesforce Analytics API if you need to access analytics about your Salesforce data
The Salesforce Analytics REST API is an invaluable resource when your goal is to programmatically interact with CRM Analytics assets such as datasets, lenses, dashboards, and CRM Analytics applications.
If you're working with data querying, the Analytics API allows you to delve deep into datasets, providing a means to explore the contained data and return specific query results. It serves as a conduit for retrieving detailed information about lenses, and also facilitates manipulation of dashboards to reflect new lenses or data.
For those managing multiple versions of datasets, the API is instrumental in keeping track of available versions and detailing the changes made across them. It aids in managing CRM Analytics applications, providing access to a list of available apps and their specific configurations or setups.
To use this API, you can POST a request to the endpoint, with a SAQL (Salesforce Analytics Query Language) query in the POST body:
async function fetchDataset() {
const url = 'https://MyDomainName.my.salesforce.com/services/data/v58.0/wave/query';
const body = JSON.stringify({
"query" : "q = load \"<datasetId>/<datasetVersionId>\"; q = group q by 'Status'; q = foreach q generate 'Status' as 'Status', count() as 'count'; q = limit q 20;"
}
);
const options = {
method: 'POST',
headers: {
'Authorization': `Bearer ${yourAccessToken}`,
'Content-Type': 'application/json',
},
body: body,
};
const response = await fetch(url, options);
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
const data = await response.json();
return data;
}
fetchDataset().then(data => console.log(data)).catch(error => console.log(error));
Where datasetId and datasetVersionId are specific to the dataset you are querying.
One of the unique benefits of the Salesforce Analytics API is its ability to determine the availability of Analytics features to a specific user, allowing for a customized user experience based on their access level. The API also provides functionalities to work with snapshots, providing details and managing the data they contain.
5 & 6. Use the Salesforce Apex REST/SOAP APIs if you need to work with your Apex classes
The Apex APIs enable you to expose your Apex classes and methods to external applications through REST or SOAP architecture. This is particularly beneficial when you have built custom business logic into your Salesforce org and want to extend that functionality beyond the confines of Salesforce.
Imagine you've built a custom object in Salesforce and created associated Apex methods to manipulate this object. Now, you want an external application to be able to perform these operations too. That's where The Apex API allows the external application to interact with your custom Apex classes and methods, making it an integral part of Salesforce's service-oriented architecture.
If you've defined a specific function, say, a complex calculation or a custom search method in Apex, and want to expose this functionality to an external app, you can do this with Apex REST or SOAP APIs.
7. Use the Salesforce Bulk API if you need to update a lot of data
The Salesforce Bulk API 2.0 is primarily designed for large-scale data operations. Here are some situations in which you might use this API:
- Large Data Operations: When you need to perform create, read, update, or delete (CRUD) operations on a large number of Salesforce records, the Bulk API can handle these tasks efficiently at scale.
- Asynchronous Processing: If your application requires the preparation, execution, and management of an asynchronous workflow that uses a bulk framework, the Bulk API can help you manage this process effectively.
- Data Management: The Bulk API is ideal for applications that need to query, insert, update, upsert, or delete large volumes of records in Salesforce in an asynchronous manner.
- Handling Data Overloads: Operations that involve more than 2,000 records can be handled more efficiently using the Bulk API, compared to regular REST or SOAP APIs.
- High Data Throughput: For applications that need to extract up to 1 TB of data per day from Salesforce, the Bulk API is a highly efficient choice.
- Single sObject Operations: If your task involves bulk operations on a single sObject type, the Bulk API can help you execute these operations efficiently.
Using this API is slightly different from the previous APIs because you have to sequence your calls. For instance, if you are trying to bulk insert data, you first need to create a job:
const createJob = async () => {
const url = 'https://MyDomainName.my.salesforce.com/services/data/v58.0/jobs/ingest/';
const jsonData = json.stringify({ "object" : "Account", "contentType" : "CSV", "operation" : "insert", "lineEnding" : "LF" })
const options = {
method: 'POST',
headers: {
'Authorization': 'Bearer access_token',
'Content-Type': 'application/json',
'Accept': 'application/json',
},
body: jsonData,
};
const response = await fetch(url, options);
if (!response.ok) {
const message = `An error has occurred: ${response.status}`;
throw new Error(message);
}
const json = await response.json();
return json;
};
createJob()
.then(data => console.log(data))
.catch(error => console.error(error));
Then we can upload the data for the job (which here would be in a csv):
const uploadBatch = async () => {
const url = 'https://MyDomainName.my.salesforce.com/services/data/v58.0/jobs/ingest/7505fEXAMPLE4C2AAM/batches/';
const data = await fetch('bulkinsert.csv');
const csvData = await data.text();
const options = {
method: 'PUT',
headers: {
'Authorization': 'Bearer access_token',
'Content-Type': 'text/csv',
'Accept': 'application/json',
},
body: csvData,
};
const response = await fetch(url, options);
if (!response.ok) {
const message = `An error has occurred: ${response.status}`;
throw new Error(message);
}
const json = await response.json();
return json;
};
uploadBatch()
.then(data => console.log(data))
.catch(error => console.error(error));
But using this API you could upload GBs of data per day.
8. Use the Salesforce GraphQL API if you need to make efficient queries
The Salesforce GraphQL API is an ideal choice when you need to build highly responsive and scalable applications that require precise control over the data returned from the server. Unlike traditional REST APIs, GraphQL allows the client to specify exactly what data it needs, which can significantly reduce the size and complexity of the server's response.
Here are some situations where the Salesforce GraphQL API could be beneficial:
- Customized Field Selection: If your application only requires a subset of an object's fields, the GraphQL API allows you to specify exactly which fields to return, helping to decrease the payload size.
- Resource Aggregation: The GraphQL API allows you to retrieve a set of related resources within a single response, thereby reducing the need for multiple round trips between the client and server.
- Schema Introspection: If you need to understand the types, fields, and objects available within your Salesforce instance, the GraphQL API provides built-in introspection capabilities, enabling you to query the schema itself.
- Optimized Performance: By minimizing the amount of data transferred, the GraphQL API helps to improve the responsiveness and performance of your application.
The Salesforce GraphQL API is best suited to scenarios where you need a high degree of flexibility and efficiency in your data retrieval. It requires a different way of thinking compared to traditional REST APIs, but it can provide significant benefits in the right situations.
9. Use the Salesforce User Interface API if you are building a native app using Salesforce functionality
Using the UI API, developers can build user interfaces that facilitate seamless interactions with Salesforce records. The API supports operations such as creating, reading, updating, and deleting records, enabling custom apps to mirror the functionality provided by Salesforce itself. These are the same features the regular REST API provides, but here you get the added benefit of an in-built UI interface for performing the actions.
This is ideal if you are building mobile apps or web apps–in fact, it is the same API Salesforce uses to create their native apps. In addition to record operations, the UI API also provides access to list views. This allows developers to build interfaces that display list views and the records they contain exactly as Salesforce does.
Here’s how you would get a record:
async function fetchSalesforceRecord() {
const url = 'https://MyDomainName.my.salesforce.com/services/data/v58.0/ui-api/record-ui/001R0000003GeJ1IAK';
const options = {
method: 'GET',
headers: {
'Authorization': `Bearer access_token`,
'Content-Type': 'application/json',
},
};
const response = await fetch(url, options);
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
const data = await response.json();
return data;
}
fetchSalesforceRecord()
.then(response => console.log(response))
.catch(e => console.log('Error:', e));
Salesforce is then not just querying the database for that record, but also getting the metadata and theme information and the layout information to return the entire UI to the user.
The Salesforce Pub/Sub API provides the ability to create a high-scale, bi-directional event-driven integration between Salesforce and other external systems. This API is designed for those who need to perform real-time data synchronization in response to specific events occurring within Salesforce.
You should consider the Salesforce Pub/Sub API if you need any of the following:
- Real-time Integration: If you have external systems that need to reflect changes in Salesforce records in near real-time, the Pub/Sub API can be used to receive Change Data Capture events that include all changed fields.
- Custom Event Handling: If your integration scenario requires custom business logic in response to specific events, you can publish and subscribe to Platform Events. These events can carry custom payloads with a predefined schema that fits your specific business needs.
- Efficient Data Synchronization: If you're dealing with high volumes of data changes, the Pub/Sub API enables you to control the subscription flow and efficiently manage binary event messages in the Apache Avro format.
By leveraging the Pub/Sub API, developers can construct efficient and reactive integrations that keep data in sync across multiple systems as events happen in real-time.
The Salesforce Tooling API is a tool for developers to interact with Salesforce metadata and build custom development tools for Force.com applications. Its functionality can be utilized to answer a variety of questions or complete specific tasks:
- Component-Level Metadata Interaction: The Tooling API provides the ability to interact with individual components of complex metadata types. It enables developers to perform operations on a specific sObject that represents a metadata type, providing more granular control over Salesforce metadata.
- Custom Development Tools: If the objective is to create custom tools for Force.com applications, the Tooling API becomes significantly useful. It facilitates managing and deploying working copies of Apex classes and triggers, as well as Visualforce pages and components.
- Debugging and Performance Analysis: The Tooling API is beneficial in the debugging and performance analysis of Salesforce applications. With this API, developers can set checkpoints, create heap dump markers, execute anonymous Apex, and access logging and code coverage information, aiding in debugging and enhancing the overall performance of Salesforce applications.
- Metadata Integration: When there's a need to integrate Salesforce metadata with other systems, the Tooling API is an excellent choice. It provides a systematic approach to ensure seamless integration between Salesforce and external systems.
The Salesforce Metadata API is an essential tool for managing the customization and configuration details of your Salesforce organization. It allows you to handle an array of tasks revolving around the structure and setup of your org, rather than the data contained within it.
The primary function of the Metadata API is to enable the retrieval, deployment, creation, updating, or deletion of Salesforce org customizations. This is particularly useful for the common task of migrating changes from a sandbox or testing environment to a production org.
Furthermore, the Metadata API is a powerful tool for developing custom applications or tools. It enables these custom solutions to interact with the Salesforce metadata model, providing a flexible backbone for more tailored solutions.
Masses of opportunities
Salesforce gives you the ability, through their APIs, to build pretty much what you want. Whether you’re just interested in building better dashboards to understand your organization’s data, or you are a developer building a new sales product and need to integrate fully with a large CRM, there is an API for you.