Force REST APIs using Java

Author : Rajdeep Dua
Last Updated : June 13 2016

Introduction

In this tutorial we will learn how to use Java to make REST APIs calls to Force.com endpoints.

Reference Source Code : force-rest-java

Background

We are planning to use a Force Scala Library which has been published on Maven Central: force-scala-lib

Setup

Structure of the Project

|-- pom.xml
|-- src
|   |-- main
|   |   |-- java
|   |   |   `-- com
|   |   |       `-- mysalesforce
|   |   |
|   |   `-- resources
|   |       |-- application.conf
|   |       `-- application.conf.sample
  1. create a source directory src

  2. Create a pom file pom.xml. Add following content to this file

    <project xmlns="http://maven.apache.org/POM/4.0.0"
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xsi:schemaLocation=
        "http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>com.salesforce</groupId>
    <artifactId>force-rest-java</artifactId>
    <packaging>jar</packaging>
    <version>1.0-SNAPSHOT</version>
    <name>force-rest-java</name>
    <url>http://maven.apache.org</url>
    <dependencies>
      <dependency>
        <groupId>junit</groupId>
        <artifactId>junit</artifactId>
        <version>3.8.1</version>
        <scope>test</scope>
      </dependency>
      <!-- http://mvnrepository.com/artifact/org.apache.httpcomponents/httpclient -->
      <dependency>
        <groupId>org.apache.httpcomponents</groupId>
        <artifactId>httpclient</artifactId>
        <version>4.5.2</version>
      </dependency>
        <dependency>
            <groupId>org.skife.com.typesafe.config</groupId>
            <artifactId>typesafe-config</artifactId>
            <version>0.3.0</version>
        </dependency>
        <!-- http://mvnrepository.com/artifact/com.google.code.gson/gson -->
        <dependency>
            <groupId>com.google.code.gson</groupId>
            <artifactId>gson</artifactId>
            <version>2.6.2</version>
        </dependency>
        <!-- http://mvnrepository.com/artifact/org.salesforce/force-scala-lib_2.11 -->
        <dependency>
            <groupId>org.salesforce</groupId>
            <artifactId>force-scala-lib_2.11</artifactId>
            <version>1.0.2</version>
        </dependency>
        <!-- http://mvnrepository.com/artifact/com.typesafe.play/play-json_2.11 -->
        <dependency>
            <groupId>com.typesafe.play</groupId>
            <artifactId>play-json_2.11</artifactId>
            <version>2.5.3</version>
        </dependency>
        <dependency>
            <groupId>org.json</groupId>
            <artifactId>json</artifactId>
            <version>20160212</version>
        </dependency>
    
    </dependencies>
    </project>
    
  3. Create directories src/main/resources and src/main/java under src folder

  4. Create file src/main/resources/application.conf file from util/src/main/resources/application.conf.sample file and fill in the values appropriately from salesforce.com developer account.

$ cp src/main/resources/application.conf.sample \
 src/main/resources/application.conf
$ cat src/main/resources/application.conf

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

force {
  UserName     = ""
  PassWord     = ""
  LoginURL     = "https://login.salesforce.com"
  GrantService = "/services/oauth2/token?grant_type=password"
  ClientID     = ""
  ClientSecret = ""
  BaseUrl = "/services/data/v35.0/sobjects/"
  Host = "https://ap2.salesforce.com"
  QueryUrl =  "/services/data/v35.0/query/?q="
}

Get Access Token

Access token GET is implemented in method getAccessToken() of the Library.

This access token is obtained from getAccessToken

String accessToken = Util.getAccessToken();

This is used internally by the library within SObject class defined below hence we need not worry about it. Make sure application.conf is in the classpath.

All the methods available under org.salesforce.Util class are shown below

public class org.salesforce.Util {
  public java.lang.String host();
  public void host_$eq(java.lang.String);
  public java.lang.String id();
  public void id_$eq(java.lang.String);
  public java.lang.String baseUrl();
  public void baseUrl_$eq(java.lang.String);
  public java.lang.String queryUrl();
  public void queryUrl_$eq(java.lang.String);
  public java.lang.String waveBaseUrl();
  public void waveBaseUrl_$eq(java.lang.String);
  public java.lang.String accessToken();
  public void accessToken_$eq(java.lang.String);
  public java.lang.String userName();
  public void userName_$eq(java.lang.String);
  public java.lang.String password();
  public void password_$eq(java.lang.String);
  public java.lang.String loginUrl();
  public void loginUrl_$eq(java.lang.String);
  public java.lang.String grantService();
  public void grantService_$eq(java.lang.String);
  public java.lang.String clientId();
  public void clientId_$eq(java.lang.String);
  public java.lang.String clientSecret();
  public void clientSecret_$eq(java.lang.String);
  public java.lang.String key();
  public void key_$eq(java.lang.String);
  public com.typesafe.config.Config conf();
  public java.lang.String getHost();
  public java.lang.String getBaseUrl();
  public java.lang.String getQueryUrl();
  public java.lang.String getWaveBaseUrl();
  public java.lang.String getAccessToken();
  public org.salesforce.Util();
}

Util by default looks for Key force in the application.conf. If there are multiple Salesforce backends which need to be connected then you can set your own key as well

Util util = new Util();
util.key_$eq("my_force")

The application.conf file will look like the listing shown below:

force {
  ..
}
myforce {
  ..
}

SObject Class

org.salesforce.SObject is the class initialized from the library. Various methods available in this class are shown below.

public class org.salesforce.SObject {
  public java.lang.String sObjectName();
  public void sObjectName_$eq(java.lang.String);
  public java.lang.String baseUrl();
  public void baseUrl_$eq(java.lang.String);
  public org.salesforce.Util util();
  public void util_$eq(org.salesforce.Util);
  public java.lang.String getList();
  public java.lang.String getSObjectDetails(java.lang.String);
  public void createSObject(java.lang.String);
  public void deleteSObject(java.lang.String);
  public void patchSObject(java.lang.String, java.lang.String);
  public java.lang.String executeSOQL(java.lang.String);
  public org.salesforce.SObject(java.lang.String, org.salesforce.Util);
}

Constructor of SObject takes two parameters ObjectName and util. Where is the instance of Util.java

Get List of SObjects

List of SObjects can be obtained by following steps

  • Instantiate the SObject instance
  • Call getList() method on it.
  • Parse and Pretty Print the returned JSON

Get Account List

To update an account following the steps listed below.

  1. Create a new instance of Util class

    Util util = new Util();
    
  2. Create a new SObject Instance.

    SObject sObject = new SObject("Account",util);
    
  3. Call getList() on SObject.

    String body = sObject.getList();
    
  4. Post the body and print json

    JSONObject obj = new JSONObject(body);
    JSONArray array = obj.getJSONArray("recentItems");
    System.out.println(array.toString(4));
    

Full code listing can be seen below

package com.mysalesforce;

import org.json.JSONArray;
import org.salesforce.SObject;
import org.salesforce.Util;
import org.json.JSONObject;

public class SObjectList
{
    public static void main( String[] args )
    {
        Util util = new Util();
        SObject sObject = new SObject("Account",util);
        String body = sObject.getList();
        JSONObject obj = new JSONObject(body);
        JSONArray array = obj.getJSONArray("recentItems");
        System.out.println(array.toString(4));
    }
}

Execute the application

$ mvn exec:java -Dexec.mainClass="com.mysalesforce.SObjectList"

Output is similar to listing below

[
  {
      "attributes": {
          "type": "Account",
          "url": "/services/data/v35.0/sobjects/Account/00128000003L9tgAAC"
      },
      "Id": "00128000003L9tgAAC",
      "Name": "sForce_One"
  },
  {
      "attributes": {
          "type": "Account",
          "url": "/services/data/v35.0/sobjects/Account/0012800000dvekHAAQ"
      },
      "Id": "0012800000dvekHAAQ",
      "Name": "TestAccountOne"
  },
  {
      "attributes": {
          "type": "Account",
          "url": "/services/data/v35.0/sobjects/Account/0012800000dvbVGAAY"
      },
      "Id": "0012800000dvbVGAAY",
      "Name": "test_1"
  }
]

Create Account

To Create an account, which is a type of a SObject we will follow the following steps

  1. Create a new instance of Util class

    Util util = new Util();
    
  2. Create a new SObject Instance.

    SObject sObject = new SObject("Account",util);
    
  3. Create json string with appropriate parameter for account

    String json = "{\"name\":\"TestAccountOne\"}";
    
  4. Call createSObject(json) on sObject instance. This creates the SObject which is printed to the console.

Full code listing can be seen below:

package com.mysalesforce;

import org.salesforce.*;
import org.salesforce.Util;

public class CreateSObject {
    public static void main( String[] args ){
        Util util = new Util();
        SObject sObject = new SObject("Account",util);
        String json = "{\"name\":\"TestAccountOne\"}";
        sObject.createSObject(json);
    }
}

Execute the application

$ mvn exec:java -Dexec.mainClass="com.mysalesforce.CreateSObject"

Delete an Account

To Delete an account, follow the following steps listed below:

  1. Create a new instance of Util class

    Util util = new Util();
    
  2. Create a new SObject Instance.

    SObject sObject = new SObject("Account",util);
    
  3. Call deleteObject by giving appropriate id

    sObject.deleteSObject(objectId);
    

Full code listing is given below:

package com.mysalesforce;

import org.salesforce.SObject;
import org.salesforce.Util;

public class DeleteSObject {
    public static void main( String[] args ){
        Util util = new Util();
        SObject sObject = new SObject("Account",util);
        String objectId = "0012800000DR2Ko";
        sObject.deleteSObject(objectId);
    }
}

Execute the application

$ mvn exec:java -Dexec.mainClass="com.mysalesforce.DeleteSObject"

Update Account

To update an account following the steps listed below.

  1. Create a new instance of Util class

    Util util = new Util();
    
  2. Create a new SObject Instance.

    SObject sObject = new SObject("Account",util);
    
  3. Create a variable id assign id of the SObject to be updated

    String id = "00128000003L9tgAAC";
    
  4. Create JSON string with new values of fields to be updated

    String jsonData = "{\"name\":\"sForce_One\"}";
    
  5. Call the created sObject’s patchSObject method as shown below

    sObject.patchSObject(id,jsonData);
    

Full code listing

sObject.patchSObject(id,jsonData);
package com.mysalesforce;

import org.salesforce.SObject;
import org.salesforce.Util;

/**
 * Created by Rajdeep Dua on 27/5/16.
 */
public class UpdateSObject {
    public static void main( String[] args ){
        Util util = new Util();
        SObject sObject = new SObject("Account",util);
        String id = "00128000003L9tgAAC";
        String jsonData = "{\"name\":\"sForce_One\"}";
        sObject.patchSObject(id,jsonData);
    }
}

Execute the application

$ mvn exec:java -Dexec.mainClass="com.mysalesforce.UpdateSObject"

Run SOQL Query

To execute a SOQL query on a SObject we implemented the following steps:

  1. Create a new instance of Util class

    Util util = new Util();
    
  2. Create a new SObject Instance.

    SObject sObject = new SObject("Account",util);
    
  3. Create a variable soql with the actual query

    String soql  = "SELECT+name+from+Account";
    
  4. Call executeSOQL on sObject, parse and print the JSON returned.

    JSONObject obj = new JSONObject(response);
    JSONArray array = obj.getJSONArray("records");
    System.out.println(array.toString(4));
    
package com.mysalesforce;

import org.salesforce.*;

public class QuerySObject {
    public static void main( String[] args ) {
        org.salesforce.Util util = new org.salesforce.Util();
        SObject sObject = new SObject("Account",util);
        String soql  = "SELECT+name+from+Account";
        String response = sObject.executeSOQL(soql);
        JSONObject obj = new JSONObject(response);
        JSONArray array = obj.getJSONArray("records");
        System.out.println(array.toString(4));
  }
    }
}

Execute the application

$ mvn exec:java -Dexec.mainClass="com.mysalesforce.QuerySObject"

Output

[
  {
      "attributes": {
          "type": "Account",
          "url": "/services/data/v35.0/sobjects/Account/00128000005hlZKAAY"
      },
      "Name": "HWAccount"
  },
  {
      "attributes": {
          "type": "Account",
          "url": "/services/data/v35.0/sobjects/Account/00128000003L9tVAAS"
      },
      "Name": "GenePoint"
  },
  ...
]

Summary

In this tutorial we learnt how to use Java to query Force.com REST endpoints using a scala library published on maven. We covered CRUD operations on Salesforce Object Account.