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.
- Create a source directory
src. - Create a build file
buid.sbt. Add following content to this file. -
Create directories
src/main/resourcesandsrc/main/scala undersrcfolder. -
Create the file
src/main/resources/application.conffile fromutil/src/main/resources/application.conf.sampleand 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:
- Load credentials from
application.confinto the appropriate variables and create aloginURL:
- Connect to the OAuth2 token URL: /services/oauth2/token.
- Create a new HTTP Client
client, HttpPostobjectpostand callexecute(post)on this client:
- Get the result body:
- Extract the access_token and return it using
gsonlibrary. We also define a custom classTokeninto 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
- Create an SObject using the
class SObjectwith Object name asAccount. Call the getList() method on the object to get List of Accounts. - Compile the program:
- Run the program.
Create an Account
Create a new method createSObject() in the SObject class. We will do following actions in this method:
- Instantiate Util object and get Access Token
- Create the
urlfor Http Post, create aHttpPostobject - Add Authorization and Content-type headers
- Account name is added in the body of the HttpPost
- 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.
-
Add a Delete Method
deleteSObjecttoSObjectclass. - Implement the following steps in this method
- Get
accessTokenfrom Util classUpdate Account - Create the
urlobject usingobjectIdto be deleted andsObjectName - Create
HttpDeleteobject from theurl - Add Authorization and Content-type headers
- Execute the delete using
DefaultHttpClientinstance
- Get
Code Listing for Delete Account can be found below
Create a DeleteAccount Scala object in DeleteAccount.scala file.
- We will override
def main(args: Array[String]): Unitmethod and create anSObjectinstance. - Set the
objectIdof the Account to be deleted. Please change this to the appropriate value for your environment. - 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:
-
Create a new method
executeSOQL(..)in SObject class -
Get accessToken
-
Create url
-
Create HttpGet request object
-
Add Http headers Authorization and Content-Type
-
Create a new DefaultHttpClient
-
Execute the Get method, handle the response and display JSON
-
Complete Code for executeSOQL() method
- Create a ExecuteSOQLQuery.scala file with ExecuteSOQLQuery object.
-
Create
main()method -
Instantiate
SObjectwith Account as the object name :sObject. -
Create a
jsondata string -
Create a soql String with the query as shown below
-
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.