Java developers are quickly moving to Scala, because it’s easier and faster to write, but compiles into Java-compatible byte code. Scala is like Python, but as fast as Java, and allows you to use existing Java libraries. To use Scala with Salesforce, you use the REST API, which allows you to access any object within Salesforce and access its data.

In this blog post you will learn how to use Scala language to make REST APIs calls to Salesforce. The samples are designed to quickly ramp up your team, and are structured to be generic enough that they can be used with any standard object in Salesforce.

The instructions below guide you through the steps of creating the project from scratch, but if you want to cheat you can clone the repository on Github: force-rest-scala.

Setting Up the Directory Structure for Scala

To build and run Scala with SBT, you need a formal directory structure, which takes the following format.

  1. Create a source directory src.
  2. Create a build file buid.sbt. Add following content to this file.
  3. Create directories src/main/resources and src/main/scala under src folder.

  4. Create the file src/main/resources/application.conf file from util/src/main/resources/application.conf.sample and fill in the values appropriately from your Salesforce organization (for testing purposes like this, you should always use Developer Edition first).

Update the "" with appropriate values for ClientId, ClientSecret, UserName, PassWord,LoginURL and GrantService.

Common Methods

The src/main/scala/Util.scala file provides common methods for getting access tokens from the REST Endpoints.

Get an Access Token for Authentication

Access token GET is implemented in the getAccessToken() method of Util.scala. We define a class Util in this file and add a method getAccesssToken().

Getting an access token consists of following steps:

  1. Load credentials from application.conf into the appropriate variables and create a loginURL:
  1. Connect to the OAuth2 token URL: /services/oauth2/token.
  2. Create a new HTTP Client client, HttpPost object post and call execute(post) on this client:
  1. Get the result body:
  1. Extract the access_token and return it using gson library. We also define a custom class Token into which the access_token is parsed:

Reference Source Code can be found at http://clouddatafacts.com/force.com/code-force-rest-scala/code-getAccessToken.html

Create a Generic SObject Class to Encapsulate CRUD Methods

Create a generic SObject class which can be used to encapsulate CRUD operations for the SObject. This is created under the path src/main/scala

Get a List of SObjects

The URL used to make request depends on the instance where your account was created ( na1, na2, ap1, ap2 etc.) as well the version of the API being used. For this example, we’re using the base URL https://ap2.salesforce.com/services/data/v35.0/sobjects/.

The function getList() will be added to the SObject class created above. An HTTPs GET request is made to the URL listed above appended by the object_name. The header of the HTTP request has Access token set in the HTTP request header.

The complete code listing looks like this:

Content-type is set to application/json.

This method is called from objects Account get_list function to get a list of Accounts.

Get a List of Accounts

    1. Create an SObject using the class SObject with Object name as Account. Call the getList() method on the object to get List of Accounts.
    2. Compile the program:
    3. Run the program.

Create an Account

Create a new method createSObject() in the SObject class. We will do following actions in this method:

  1. Instantiate Util object and get Access Token
  2. Create the url for Http Post, create a HttpPost object
  3. Add Authorization and Content-type headers
  4. Account name is added in the body of the HttpPost
  5. Execute the Http Request

The code listing for the steps defined above can be seen below:

Compile and Run the Program

Delete Account

In this section we look at how to use Scala to make a Delete call.

  1. Add a Delete Method deleteSObject to SObject class.

  2. Implement the following steps in this method
    • Get accessToken from Util classUpdate Account
    • Create the url object using objectId to be deleted and sObjectName
    • Create HttpDelete object from the url
    • Add Authorization and Content-type headers
    • Execute the delete using DefaultHttpClient instance

Code Listing for Delete Account can be found below

Create a DeleteAccount Scala object in DeleteAccount.scala file.

        1. We will override def main(args: Array[String]): Unit method and create an SObjectinstance.
        2. Set the objectId of the Account to be deleted. Please change this to the appropriate value for your environment.
        3. call sObject.deleteSObject(objectId)

Code listing below shows how the actual SObject is instantiates and deleteSObject method is called on it.

Compile and Run the Program

Run SOQL Query

To run a SOQL Query to get data from a SObject follow the steps listed below:

  1. Create a new method executeSOQL(..) in SObject class

  2. Get accessToken

  3. Create url

  4. Create HttpGet request object

  5. Add Http headers Authorization and Content-Type

  6. Create a new DefaultHttpClient

  7. Execute the Get method, handle the response and display JSON

  8. Complete Code for executeSOQL() method

  1.  Create a ExecuteSOQLQuery.scala file with ExecuteSOQLQuery object.
    1. Create main() method

    2. Instantiate SObject with Account as the object name : sObject.

    3. Create a json data string

    4. Create a soql String with the query as shown below

    5. Call sObject.executeSOQL(soql)

Compile and Run the Program

Summary

In this blog I showed you how to use Scala and access Salesforce data using REST. The sample code enables you to do Create, Delete and Query actions using Force.com REST APIs, and should get you and your team started quickly. Enjoy!

About the Author

Rajdeep Dua is Director Developer Relations at Salesforce. He is passionate about helping developers learn about Cloud Computing and Salesforce. He has over 16 years of experience in Software Product Development and Developer Relations.

Get the latest Salesforce Developer blog posts and podcast episodes via Slack or RSS.

Add to Slack Subscribe to RSS