Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

How To Build A Basic Salesforce Rest API Integration

DZone's Guide to

How To Build A Basic Salesforce Rest API Integration

Let's take a look at a tutorial that explains how to build a basic Salesforce REST API integration.

· Integration Zone ·
Free Resource

SnapLogic is the leading self-service enterprise-grade integration platform. Download the 2018 GartnerMagic Quadrant for Enterprise iPaaS or play around on the platform, risk free, for 30 days.

Getting your app listed in the Salesforce AppExchange provides you with the ability to build your product into the Salesforce platform promptly. Though the benefits of being present within this ecosystem are evident, it is crucial to acknowledge the costs associated along. A Rest API integration revolves around sending data from your app and collecting data from Salesforce.

salesforce integration

What we will be discussing here is a basic REST API integration where the app is going to have customer data to be sent to Salesforce, and customer data in Salesforce is to be retrieved. The three important features of the app will be:

  • Authorization
  • Users’ data push
  • Users’ data retrieval

The Set-Up

The first step to follow is to sign in to a free Salesforce developer account (https://developer.salesforce.com/signup). The integration will take place when the connected app sits on Salesforce’s infrastructure. Connected apps are able to offer multiple functionalities. They are responsible for administering the routing and authentication requests to applicable clients.

Now, for setting up the application, you can click on the Setup icon on the navigation menu (top-right corner) and click Setup.

In the ‘Quick Find’ box, enter ‘App Manager’ and then select it.

1. Click on ‘New Connected App.’

2. Fill in the form in the following manner:

[Basic Information section]

Connected App Name: AppName.

API Name: this will instantly turn to ‘AppName.’

Contact Email: enter your e-mail address.

[In the API (Enable OAuth Settings) section]

Check Enable OAuth Settings.

Callback URL: enter your callback URL, example:

https://www.appname.com/api/callback

This URL will comprise of the Access token and Request token.

Under Selected OAuth Scopes:

1. Select Access and manage your data (API).

2. Click on ‘Add.’

Once you set up a connected app, you will be provided with a Consumer Secret and a Consumer Key.

Let us now move forward:

1. Salesforce OAuth Data Flow

In order to gather customer data, you will require users visiting your website to make actions like browsing, scrolling, watching videos, clicking on call-to-action buttons, etc. All the recorded customer data will then be redirected to a Salesforce.com auth endpoint where the access will be granted to you through an endpoint. The idea revolves around customers transferring their Salesforce data on their own behalf.

Salesforce will send a reply with an Access and Refresh token once the authentication with an endpoint is successful. The Access token holds an expiry duration of 15 minutes. Refresh token assists you with getting in when the Access lapses.

Image title

Here is the API call sample:

curl https://login.salesforce.com/services/oauth2/authorize?response_type=code&client_id=YOURCONSUMERID&redirect_uri=https://www.appname.com/api/callback

If you want a user to grant you access to their data, the above-mentioned request is what you will make as an initial authorization. The client_id mentioned in the call will be your consumer ID from the connected app, whereas, the redirect_uri mentioned in the call will be the Callback URL. After you get a successful response, you will be redirected to a Salesforce login page. That’s where the user will log in and authenticate.

After the data authorization, an authorization code will be added by Salesforce to the URL which will create a request. This is how the request will look like:

https://www.appname.com/api/callback?code=aWekysIEeqM9PiThEfm0Cnr6MoLIfwWyRJcqOqHdF8f9INokharAS09ia7UNP6RiVScerfhc4w%3D%3D

To receive your Access and Refresh Token, this is the code parameter you will use as the value while making a request to Salesforce token endpoint.

Here’s an example request:

curl login.salesforce.com/services/oauth2/token?grant_type=authorization_code&redirect_uri=https://www.appname.com/api/callback&client_id=YOUR_CONSUMER_ID&client_secret=YOUR_CONSUMER_SECRET&code=aWekysIEeqM9PiThEfm0Cnr6MoLIfwWyRJcqOqHdF8f9INokharAS09ia7UNP6RiVScerfhc4w%3D%3D

And an example response:

{
  "access_token": "YOUR_ACCESS_TOKEN",
  "refresh_token": "YOUR_REFRESH_TOKEN",
  "signature": "signature",
  "scope": "refresh_token api id",
  "instance_url": "https://instance.salesforce.com",
  "id": "https://login.salesforce.com/id/id,
  "token_type": "Bearer",
  "issued_at": "timestamp"
} 

With these requests and responses, you will build a base for further API calls via URL. Since you want access to the users’ data on their behalf, you can form requests and get responses in return, acknowledging the Refresh token that will help you keep authenticated.

Refresh token example call:

curl https://login.salesforce.com/services/oauth2/token?grant_type=refresh_token&client_id=YOUR_CONSUMER__ID&client_secret=YOUR_CONSUMER__SECRET&refresh_token=YOUR_REFRESH_TOKEN

Refresh token example response:

{
  "access_token": "REFRESHED_ACCESS_TOKEN",
  "signature": "signature",
  "scope": "refresh_token id api",
  "instance_url": "https://INSTANCE.salesforce.com",
  "id": "https://login.salesforce.com/id/idE",
  "token_type": "Bearer",
  "issued_at": "timestamp"
}

Following this, you will now be set to work with sObjects (Salesforce objects), sObjects are database tables that comprise of company’s data (contacts, accounts, tasks, leads).

2. Data Transfer From the App to Salesforce

How do we create a contact in Salesforce? Using the instance from the Access token response, you will be required to build the API URL. Here’s how:

Mark Woods example request:

curl https://INSTANCE.salesforce.com/services/data/v42.0/sobjects/Contact -H "Authorization: Bearer YOUR_ACCESS_TOKEN" -H "Content-Type: application/json" -d '{"FirstName" : "Mark", "LastName" : "Woods"}'

To successfully create the entry, the contact needs a last name as the minimum.

The response you receive will be the ID of the contact.

{"id":"0031r000029NDckAAG","success":true,"errors":[]}

This will let you create a link to the contact directly.

https://INSTANCE.salesforce.com/0031r000029NDckAAG

3. Data retrieval from Salesforce to the app

This is the next phase where you can retrieve a list of contacts with their individual data. This can be done by making a request to a describe endpoint as the author suggests, focusing on accessing fields to be populated by the data of the users.

Example request:

curl https://INSTANCE.salesforce.com/services/data/v20.0/sobjects/Contact/describe -H "Authorization: Bearer YOUR_ACCESS_TOKEN"

You will get a response of all the fields available in detail. It will look like this:

{
  "autoNumber": false,
  "byteLength": 120,
  "calculated": false,
  "calculatedFormula": null,
  "caseSensitive": false,
  "controllerName": null,
  "createable": true,
  "custom": false,
  "defaultValue": null,
  "defaultValueFormula": null,
  "defaultedOnCreate": false,
  "dependentPicklist": false,
  "deprecatedAndHidden": false,
  "digits": 0,
  "externalId": false,
  "filterable": true,
  "groupable": true,
  "htmlFormatted": false,
  "idLookup": false,
  "inlineHelpText": null,
  "label": "First Name",
  "length": 40,
  "name": "FirstName",
  "nameField": false,
  "namePointing": false,
  "nillable": true,
  "picklistValues": [],
  "precision": 0,
  "referenceTo": [],
  "relationshipName": null,
  "relationshipOrder": null,
  "restrictedPicklist": false,
  "scale": 0,
  "soapType": "xsd:string",
  "sortable": true,
  "type": "string",
  "unique": false,
  "updateable": true,
  "writeRequiresMasterRead": false
}

After this, what you can do is, you can use the fields to create a custom query:

curl https://INstance.salesforce.com/services/data/v42.0/query/?q=SELECT+id,name,email,phone+from+Contact -H 'Authorization: Bearer YOUR_ACCESS_TOKEN'

This will return all the contacts with the related properties.

{
  "totalSize": 1,
  "done": true,
  "records": [
    {
      "attributes": {
        "type": "Contact",
        "url": "/services/data/v42.0/sobjects/Contact/id"
      },
      "Id": "id",
      "Name": "Mark Woods",
      "Email": "mark.woods@myfriend.com",
      "Phone": "555-555-555"
    }
  ]
}

Download A Buyer's Guide to Application and Data Integration, your one-stop-shop for research, checklists, and explanations for an application and data integration solution.

Topics:
salesforce ,salesforce app development ,salesforce integration ,salesforce app exchange ,api integration ,api ,salesforce best crm software ,rest api ,integration

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}