Back

Step by Step Guide to Building a Salesforce API Integration in JS

Jul 17, 20246 minute read

Introduction

Hey there, fellow developer! Ready to dive into the world of Salesforce API integration? We're going to use the @salesforce/salesforce-sdk package to make our lives easier. Buckle up, because we're about to turbocharge your Salesforce integration skills!

Prerequisites

Before we jump in, make sure you've got:

  • Node.js and npm (you're a pro, so I'm sure you've got this covered)
  • A Salesforce Developer Account (if you don't have one, go grab it – it's free!)
  • Your JavaScript skills (check!) and some Salesforce knowledge (you're good to go!)

Setting up the project

Let's get this party started:

mkdir salesforce-integration && cd salesforce-integration npm init -y npm install @salesforce/salesforce-sdk

Boom! Project initialized and SDK installed. We're on a roll!

Authentication

Time to sweet-talk Salesforce into letting us in:

  1. Head to your Salesforce Developer Account and create a Connected App.
  2. Grab your client ID, client secret, and refresh token.
  3. Now, let's set up OAuth 2.0:
const { OAuth2 } = require('@salesforce/salesforce-sdk'); const oauth2 = new OAuth2({ clientId: 'YOUR_CLIENT_ID', clientSecret: 'YOUR_CLIENT_SECRET', redirectUri: 'http://localhost:3000/oauth2/callback' });

Initializing the Salesforce client

Let's get that Salesforce connection up and running:

const { Connection } = require('@salesforce/salesforce-sdk'); const conn = new Connection({ oauth2: oauth2, instanceUrl: 'https://your-instance.salesforce.com', accessToken: 'YOUR_ACCESS_TOKEN', refreshToken: 'YOUR_REFRESH_TOKEN' });

Making API requests

Now for the fun part – let's play with some data!

Query data (SOQL)

const query = 'SELECT Id, Name FROM Account LIMIT 10'; conn.query(query) .then(result => console.log(result.records)) .catch(err => console.error(err));

Create records

const account = { Name: 'Awesome New Account' }; conn.sobject('Account').create(account) .then(result => console.log(`Account created with Id: ${result.id}`)) .catch(err => console.error(err));

Update records

const updatedAccount = { Id: 'EXISTING_ACCOUNT_ID', Name: 'Updated Account Name' }; conn.sobject('Account').update(updatedAccount) .then(result => console.log(`Account updated: ${result.success}`)) .catch(err => console.error(err));

Delete records

conn.sobject('Account').destroy('ACCOUNT_ID_TO_DELETE') .then(result => console.log(`Account deleted: ${result.success}`)) .catch(err => console.error(err));

Handling responses and errors

Always be prepared:

conn.query('SELECT Id, Name FROM Account LIMIT 10') .then(result => { const accounts = result.records.map(record => ({ id: record.Id, name: record.Name })); console.log(accounts); }) .catch(err => { console.error('Error occurred:', err.message); // Handle specific error types if needed });

Best practices

  • Respect rate limits: Use the Composite API for multiple operations.
  • Bulk API: For large datasets, leverage the Bulk API to process data efficiently.

Testing the integration

Don't forget to test! Here's a quick Jest example:

const { Connection } = require('@salesforce/salesforce-sdk'); jest.mock('@salesforce/salesforce-sdk'); test('query accounts', async () => { const mockQuery = jest.fn().mockResolvedValue({ records: [{ Id: '1', Name: 'Test Account' }] }); Connection.prototype.query = mockQuery; const conn = new Connection({}); const result = await conn.query('SELECT Id, Name FROM Account LIMIT 1'); expect(mockQuery).toHaveBeenCalledWith('SELECT Id, Name FROM Account LIMIT 1'); expect(result.records).toHaveLength(1); expect(result.records[0].Name).toBe('Test Account'); });

Conclusion

And there you have it! You've just built a Salesforce API integration using the @salesforce/salesforce-sdk package. Pretty slick, right? Remember, this is just the tip of the iceberg. There's so much more you can do with Salesforce's powerful API.

Keep exploring, keep coding, and most importantly, keep being awesome! If you want to dive deeper, check out the Salesforce API Documentation for more advanced features and best practices.

Now go forth and integrate like a boss! 🚀