A Comprehensive Guide to Using REST and SOAP APIs in Salesforce with Node.js

Written by Sandeep KumarApril 4th, 2023
A Comprehensive Guide to Using REST and SOAP APIs in Salesforce with Node.jsA Comprehensive Guide to Using REST and SOAP APIs in Salesforce with Node.js

Salesforce provides a variety of APIs to interact with its platform and data, including REST and SOAP APIs. These APIs allow developers to access, manipulate, and integrate data from Salesforce with external systems. In this blog post, we'll provide a comprehensive guide to using REST and SOAP APIs in Salesforce with Node.js and their key differences.

Understanding REST and SOAP APIs

REST API:

  • REST stands for Representational State Transfer, which is a software architecture style that uses HTTP methods and URLs to manipulate resources.
  • REST API is a web service that uses HTTP methods such as GET, POST, PUT, PATCH, and DELETE to perform CRUD (Create, Read, Update, Delete) operations on Salesforce objects.
  • REST API returns data in JSON format by default, but it can also return data in XML format if requested.

SOAP API:

  • SOAP stands for Simple Object Access Protocol, which is a messaging protocol that uses XML format to send and receive messages.
  • SOAP API is a web service that uses the SOAP protocol to perform CRUD operations on Salesforce objects.
  • SOAP API requires a WSDL (Web Services Description Language) file to describe the operations and data types available in the API.
  • SOAP API returns data in XML format.

Key differences between REST and SOAP APIs:

  • REST API is lightweight and flexible, while SOAP API is more structured and standardized.
  • REST API uses HTTP methods and URLs, while SOAP API uses XML messages and WSDL files.
  • REST API is faster and more efficient for simple CRUD operations, while SOAP API is better for complex operations and enterprise-level integrations.

When to use REST and SOAP APIs in Salesforce:

  • Use REST API for simple CRUD operations and lightweight integrations.
  • Use SOAP API for complex operations, enterprise-level integrations, and when the integration requires a formal contract with a WSDL file.

REST API in Salesforce with Node.js

REST API basics: To use the REST API in Salesforce, you need to:

  • Authenticate and authorize REST API access using OAuth 2.0.
  • Use HTTP methods such as GET, POST, PUT, PATCH, and DELETE to perform CRUD operations on Salesforce objects.
  • Use SOQL (Salesforce Object Query Language) to query data from Salesforce objects.
  • Use SOSL (Salesforce Object Search Language) to search data across multiple objects.

Authenticating and authorizing REST API access: To authenticate and authorize REST API access, you can follow these steps:

  • Create a connected app in Salesforce and obtain the client ID and client secret.
  • Use the client ID and client secret to obtain an access token using OAuth 2.0.
  • Use the access token in the HTTP headers of REST API requests.

Here's an example code snippet to obtain an access token using the Node.js axios library:

1const axios = require('axios');
2
3const clientId = '<your_client_id>';
4const clientSecret = '<your_client_secret>';
5const username = '<your_salesforce_username>';
6const password = '<your_salesforce_password>';
7
8const loginUrl = 'https://login.salesforce.com/services/oauth2/token';
9const data = `grant_type=password&client_id=${clientId}&client_secret=${clientSecret}&username=${username}&password=${password}`;
10
11axios.post(loginUrl, data, { headers: { 'Content-Type': 'application/x-www-form-urlencoded' } })
12  .then((response) => {
13    const accessToken = response.data.access_token;
14    console.log(`Access token: ${accessToken}`);
15  })
16  .catch((error) => {
17    console.error(error);
18  });

In this code, we use the axios.post method to send a POST request to the Salesforce OAuth token endpoint with the required parameters in the request body. We also set the Content-Type header to application/x-www-form-urlencoded, which is required by Salesforce.

The response from Salesforce includes the access token, which we can extract from the response.data object and store in a variable for later use. Finally, we log the access token to the console.

Note that this code is only an example and should not be used in production without proper security measures and error handling.

REST API query examples with Node.js

1const axios = require('axios');
2
3const accessToken = '<your_access_token>';
4const instanceUrl = '<your_salesforce_instance_url>';
5const objectName = '<your_salesforce_object_name>';
6const query = '<your_salesforce_query>';
7
8const url = `${instanceUrl}/services/data/v52.0/sobjects/${objectName}/?q=${query}`;
9const headers = { Authorization: `Bearer ${accessToken}` };
10
11axios.get(url, { headers })
12  .then((response) => {
13    console.log(response.data);
14  })
15  .catch((error) => {
16    console.error(error);
17  });

In this example, we first define the accessToken, instanceUrl, objectName, and query variables to specify the Salesforce object and query to retrieve. We then construct the REST API query URL using these variables and the Salesforce API endpoint. We also include the access token in the Authorization header.

We use the axios.get method to send a GET request to the URL and log the response data to the console.

REST API update and create examples with Node.js

1const axios = require('axios');
2
3const accessToken = '<your_access_token>';
4const instanceUrl = '<your_salesforce_instance_url>';
5const objectName = '<your_salesforce_object_name>';
6const data = {
7  field1: 'value1',
8  field2: 'value2',
9  // Add more fields as needed
10};
11
12const url = `${instanceUrl}/services/data/v52.0/sobjects/${objectName}/`;
13const headers = {
14  Authorization: `Bearer ${accessToken}`,
15  'Content-Type': 'application/json',
16};
17
18axios.post(url, data, { headers })
19  .then((response) => {
20    console.log(response.data);
21  })
22  .catch((error) => {
23    console.error(error);
24  });

In this example, we first define the accessToken, instanceUrl, objectName, and data variables to specify the Salesforce object and record data to create. We then construct the REST API URL for creating a record using these variables and the Salesforce API endpoint. We also include the access token in the Authorization header and set the Content-Type header to application/json.

REST API bulk examples with Node.js

1const axios = require('axios');
2
3const accessToken = '<your_access_token>';
4const instanceUrl = '<your_salesforce_instance_url>';
5const objectName = '<your_salesforce_object_name>';
6const records = [
7  {
8    field1: 'value1',
9    field2: 'value2',
10    // Add more fields as needed
11  },
12  {
13    field1: 'value3',
14    field2: 'value4',
15    // Add more fields as needed
16  },
17  // Add more records as needed
18];
19
20const url = `${instanceUrl}/services/data/v52.0/composite/sobjects`;
21const headers = {
22  Authorization: `Bearer ${accessToken}`,
23  'Content-Type': 'application/json',
24};
25
26const payload = {
27  allOrNone: true,
28  records: records.map((record) => {
29    return {
30      attributes: {
31        type: objectName,
32      },
33      ...record,
34    };
35  }),
36};
37
38axios.post(url, payload, { headers })
39  .then((response) => {
40    console.log(response.data);
41  })
42  .catch((error) => {
43    console.error(error);
44  });
45

We then construct the REST API URL for creating multiple records using the composite/sobjects endpoint.

We set the allOrNone attribute of the payload to true to indicate that all records should be created or none of them should be created. We also format each record with the appropriate type attribute for the Salesforce object using the spread operator.

SOAP API in Salesforce:

The Salesforce SOAP API is a web services-based API that allows external applications to query, create, update, and delete records in Salesforce. The API uses the SOAP protocol, which is a message-based protocol for exchanging structured data over the web. The Salesforce SOAP API supports both XML and JSON formats.

The SOAP API provides access to most standard and custom objects in Salesforce, and allows for complex queries and data manipulation. It is useful for integrating Salesforce with other enterprise systems that use SOAP protocols.

SOAP API Example:

Here is an example of using the Salesforce SOAP API with Node.js to create a new Contact record:

1const soap = require('soap');
2
3const username = '<your_salesforce_username>';
4const password = '<your_salesforce_password>';
5const securityToken = '<your_salesforce_security_token>';
6const wsdlUrl = '<your_salesforce_wsdl_url>';
7
8const contact = {
9  FirstName: 'John',
10  LastName: 'Doe',
11  Email: 'johndoe@example.com',
12};
13
14soap.createClient(wsdlUrl, (err, client) => {
15  if (err) {
16    console.error(err);
17    return;
18  }
19
20  client.login({ username, password + securityToken }, (err, result) => {
21    if (err) {
22      console.error(err);
23      return;
24    }
25
26    const sessionId = result.sessionId;
27    const serverUrl = result.serverUrl;
28
29    client.create(
30      {
31        sObjects: [
32          {
33            type: 'Contact',
34            fieldsToNull: [],
35            Id: null,
36            ...contact,
37          },
38        ],
39      },
40      { sessionHeader: { sessionId } },
41      (err, result) => {
42        if (err) {
43          console.error(err);
44          return;
45        }
46
47        console.log(result);
48      },
49      serverUrl
50    );
51  });
52});

In this example, we first define the username, password, securityToken, and wsdlUrl variables to specify the Salesforce login credentials and the SOAP WSDL URL.

We then define the contact variable to specify the field values for the new Contact record.

We use the soap.createClient method to create a SOAP client and pass in the WSDL URL. We use the client.login method to log in to Salesforce and obtain a session ID and server URL.

We format the contact object with the appropriate type attribute and field values using the spread operator. We use the client.create method to create the new Contact record and log the response to the console.

Best Practices for Using REST and SOAP APIs:

  1. Use Bulk APIs for Large Data Loads: When working with large data sets, use the Bulk API to load or delete data. This API is optimized for large data loads and is faster than the standard REST API or SOAP API.
  2. Use API Versioning: Salesforce introduces new features and changes to APIs in each release, so it's important to use API versioning to ensure compatibility and consistency. Use the latest stable API version that supports your integration needs and make sure to update your code to use a new API version before the old version is retired.
  3. Implement Proper Error Handling: Make sure to handle API errors properly in your code. Check for error responses and handle them accordingly to prevent unexpected behavior and improve the user experience. You can use try-catch blocks or error callbacks to handle API errors.
  4. Use Query and Search Limits: REST API and SOAP API have limits on the number of queries and search requests that can be made per day. Monitor your API usage and make sure you are staying within the limits to avoid unexpected service interruptions.
  5. Use Appropriate Authentication Methods: Use the appropriate authentication method for your integration needs. OAuth 2.0 is recommended for web and mobile applications, while SOAP headers are recommended for enterprise applications.
  6. Implement Caching: Use caching mechanisms to improve performance and reduce API calls. Cache frequently accessed data to reduce network latency and API call overhead. Use caching libraries like Redis or Memcached to implement caching in your code.
  7. Use Secure Connections: Use HTTPS for all API requests and responses to ensure data security and privacy. Do not use HTTP, as it does not provide encryption and is vulnerable to data interception and manipulation.
  8. Use Named Credentials: Use Named Credentials to securely store and manage authentication information and avoid hard-coding credentials in your code. Named Credentials are easy to configure and provide a secure way to access external APIs.

Integrating REST and SOAP APIs with External Systems:

  1. Choose the Right Integration Pattern: When integrating REST and SOAP APIs with external systems, it's important to choose the right integration pattern based on your specific use case. Some common patterns include request/response, publish/subscribe, and batch processing.
  2. Use Integration Tools: Salesforce provides several integration tools that can simplify the process of integrating with external systems. These tools include the Salesforce Connect, Salesforce Platform Events, and MuleSoft Anypoint Platform.
  3. Map Data Fields: When integrating with external systems, make sure to map data fields between systems to ensure proper data synchronization and accuracy. Use tools like Salesforce's Data Integration to map data fields and automate data synchronization.
  4. Monitor Integration Performance: Monitor integration performance to ensure that data is being transferred between systems efficiently and effectively. Use tools like Salesforce's Integration Monitoring to monitor integration performance and identify issues or bottlenecks.
  5. Implement Error Handling: Implement proper error handling mechanisms to ensure that errors are captured and resolved quickly. Use Salesforce's Error Handling Framework to handle errors in real-time and trigger alerts or notifications when errors occur.
  6. Test and Validate Integrations: Test and validate integrations thoroughly before deploying them in production environments. Use Salesforce's Integration Testing Framework to test integrations and validate data transfers between systems.
  7. Ensure Security and Compliance: Ensure that integrations comply with security and compliance requirements. Use Salesforce's Shield Platform Encryption to encrypt sensitive data and comply with data protection regulations like GDPR and CCPA.

Conclusion

Integrating REST and SOAP APIs with external systems can help organizations streamline business processes and improve data accuracy and synchronization. Choosing the right integration pattern, using integration tools, mapping data fields, monitoring integration performance, implementing error handling mechanisms, testing and validating integrations, and ensuring security and compliance are all critical to the success of the integration. By following these best practices, organizations can build robust and efficient integrations with external systems in Salesforce.