Hit the Salesforce REST API from Java

Introduction

This article is a reminder of the source code that hits Salesforce's REST API from Java. Since there are many parts that are omitted such as property files, it does not work even if you write it as it is.

For the time being, I would like to know the following three points.

  1. How to write to send / receive a request in JSON format
  2. How to write to send / receive response in JSON format
  3. How to create an array type JSON

Request / response format

request

JSON


{
 "request" : [
   [
      "id" : "000",
      "name" : "sample0"
   ]
   [
      "id" : "001",
      "name" : "sample1"
   ]
 ]
}

response

JSON


{
 "results" : [
   [
      "id" : "000",
      "name" : "sample0",
      "status" : "200"
   ]
   [
      "id" : "001",
      "name" : "sample1",
      "status" : "200"
   ]
 ]
}

Sample code

Java side

ConnectApiLogic.java


public class ConnectApiLogic {

    private static final String LOGIN_URL                   = PropertyUtil.getProperty("SF_LOGIN_URL");
    private static final String GRANT_TYPE                  = PropertyUtil.getProperty("SF_GRANT_TYPE");
    private static final String CLIENT_ID                   = PropertyUtil.getProperty("SF_CLIENT_ID");
    private static final String CLIENT_SECRET               = PropertyUtil.getProperty("SF_CLIENT_SECRET");
    private static final String USERNAME                    = PropertyUtil.getProperty("SF_USERNAME");
    private static final String PASSWORD_AND_SECURITY_TOKEN = PropertyUtil.getProperty("SF_PASSWORD_AND_SECURITY_TOKEN");
    private static String url                               = PropertyUtil.getProperty("SF_RESTPASS") + PropertyUtil.getProperty("SF_UPDATE_USERMST");

    RestTemplate restTemplate = new RestTemplate();

    /**Method to give a list and get the request result*/
    public ResponseDTO getResults(List<RequestChildDTO> requestList) {

        //Get authentication token
        ResponseEntity<ApiTokenResponseDto> apiTokenResponse = doPostAccess(CLIENT_ID, CLIENT_SECRET);
        String authToken = apiTokenResponse.getBody().getAccessToken();
        if (authToken.isBlank()) {
            System.exit(1);
        }

        RequestParentDTO requestDTO = new RequestUserMstDTO();
        requestDTO.request = requestList;

        //Header creation
        MultiValueMap<String, String> headers = new LinkedMultiValueMap<String, String>();
        headers.add("Authorization","Bearer "+authToken);
        headers.add("Content-Type", "application/json");

        restTemplate.getMessageConverters().add(new MappingJackson2HttpMessageConverter());

        HttpEntity<RequestParentDTO> request = new HttpEntity<RequestParentDTO>(requestDTO, headers);

        return restTemplate.postForObject(url, request, ResponseParentDTO.class);
    }



    /**Access token acquisition method*/
    private ResponseEntity<ApiTokenResponseDto> doPostAccess(String cliendId, String clientSecret) {

        MultiValueMap<String, String> request = new LinkedMultiValueMap<String, String>();
        request.add("grant_type", GRANT_TYPE);
        request.add("client_id", cliendId);
        request.add("client_secret", clientSecret);
        request.add("username", USERNAME);
        request.add("password", PASSWORD_AND_SECURITY_TOKEN);

        RequestEntity requestEntity = null;
        ResponseEntity<ApiTokenResponseDto> response = null;

        try {
            requestEntity = RequestEntity.post(new URI(LOGIN_URL)).contentType(MediaType.APPLICATION_FORM_URLENCODED).body(request);
            response = restTemplate.exchange(requestEntity, ApiTokenResponseDto.class);
        } catch (URISyntaxException e) {
            e.printStackTrace();
            return response;
        } catch (HttpClientErrorException e) {
            e.printStackTrace();
            return response;
        }
        return response;
    }
}

RequestParentDTO.java


public class RequestParentDTO {
    public List<RequestChildDTO> request;

    public RequestUserMstDTO(){
        request = new ArrayList<>();
    }
}

RequestChildDTO.java


public class RequestChildDTO {

    public String id;
    public String name;

}

ResponseParentDTO.java


@JsonInclude(JsonInclude.Include.NON_NULL)
@JsonPropertyOrder({
    "results"
})
public class ResponseParentDTO {

    @JsonProperty("results")
    public List<ResponseChild> results = null;

    public ResponseDTO(){}

}

ResponseChild.java


@JsonInclude(JsonInclude.Include.NON_NULL)
@JsonPropertyOrder({
    "id",
    "name",
    "status",
})
public class ResponseChild {

    @JsonProperty("id")
    public String id;
    @JsonProperty("name")
    public String name;
    @JsonProperty("status")
    public String status;

    public Result(){}

}

Salesforce side

PostApi.cls


@RestResource(urlMapping='/sample/*')
global without sharing class PostApi {

    @HttpPost
    global static DT_ResponseParentDto doPost() {
        //Parameter acquisition
        RestRequest req = RestContext.request;
        List<InnerRequest> innnerRequestList = setRequest(req);
        //Return response
        return setResponse(innnerRequestList);
    }



    /**Request parameter acquisition method*/
    private static List<InnerRequest> setRequest(RestRequest req) {
        Map<String, Object> requestParams = (Map<String, Object>) JSON.deserializeUntyped(req.requestBody.ToString());
        List<Object> requestList = (List<Object>) requestParams.get('request');
        List<InnerRequest> innerRequestList = new List<InnerRequest>();
        for (Object obj : requestList) {
            Map<String, Object> params = (Map<String, Object>) obj;
            InnerRequest inner       = new InnerRequest();
            inner.id   = (String) params.get('id');
            inner.name = (String) params.get('name');
            innerRequestList.add(inner);
        }
        return innerRequestList;
    }



    /**Response creation method*/
    private static DT_ResponseParentDto setResponse(List<InnerRequest> innnerRequestList) {
        DT_ResponseParentDto response = new DT_ResponseParentDto();
        //Set the status code in the success list
        if (innnerRequestList.size() > 0) {
            for (InnerRequest inner : innnerRequestList) {
                DT_ResponseChildDto child = new DT_ResponseChildDto();
                child.id                  = inner.id;
                child.name                = inner.name;
                child.status              = "200";
                response.results.add(child);
            }
        }
        return response;
    }



    /**Inner class for request storage*/
    public class InnerRequest {
        public String id;
        public String name;
    }
}

DT_ResponseParentDto.cls


public class DT_ResponseParentDto{

    public List<DT_ResponseChildDto> results;

    public DT_ResponseParentDto() {
        results = new List<DT_ResponseChildDto>();
    }

}

DT_ResponseChildDto.cls


public class DT_ResponseChildDto{

    public String id;
    public String name;
    public String status;

}

Recommended Posts

Hit the Salesforce REST API from Java
[java8] To understand the Stream API
[Parse] Hit the API using callFunctionInBackground
Hit Zaim's API (OAuth 1.0) in Java
Parsing the COTOHA API in Java
Hit the Docker API in Rust
The road from JavaScript to Java
Call TensorFlow Java API from Scala
[Swift] Hit the API using Decodable / Generics
Data processing using stream API from Java 8
Call GitHub's Rest API from Java's Socket API
Call GitHub API from Java Socket API part2
API integration from Java with Jersey Client
Try using the Stream API in Java
Call the Windows Notification API in Java
Kick ShellScript on the server from Java
The Java EE Security API is here!
Try using the Emotion API from Android
[Java] Generate a narrowed list from multiple lists using the Stream API
Call the Microsoft Emotion API by sending image data directly from Java.
ChatWork4j for using the ChatWork API in Java
[Java] Set the time from the browser with jsoup
Java Stream API
Try accessing the dataset from Java using JZOS
Try using the COTOHA API parsing in Java
Generate Java client code for Salesforce SOAP API
Output the maximum value from the array using Java standard output
[Java] I want to calculate the difference from the date
How to write Scala from the perspective of Java
[Java] How to extract the file name from the path
Use Java lambda expressions outside of the Stream API
Java language from the perspective of Kotlin and C #
Try calling IBM Watson Assistant 2018-07-10 from the Java SDK.
Using the database (SQL Server 2014) from a Java program 2018/01/04
New topics from the Java SE 11 Programmer II exam
Changes from Java 8 to Java 11
Sum from Java_1 to 100
[Java] Stream API / map
Eval Java source from Java
Access API.AI from Java
Java8 Stream API practice
From Java to Ruby !!
Zabbix API in Java
Find the address class and address type from the IP address with Java
JSON in Java and Jackson Part 1 Return JSON from the server
[JDBC] I tried to access the SQLite3 database from Java.
Get to the abbreviations from 5 examples of iterating Java lists
[MT] Specify the article category from Android with Data API
I want to use the Java 8 DateTime API slowly (now)
Elasticsearch Operation via REST API using Apache HttpClient in Java
How to disable Set-Cookie from API on the front side
Correct the character code in Java and read from the URL
What I was addicted to with the Redmine REST API
[MT] Specify the article category from Android with Data API
Tips for using Salesforce SOAP and Bulk API in Java
[Java] Delete the specified number of characters from the end of StringBuilder
How to play MIDI files using the Java Sound API
Call API [Call]
Call API [Preparation]
Call API [Handling]
Call TensorFlow Java API from Scala
Call GitHub's Rest API from Java's Socket API
Call GitHub API from Java Socket API part2
Call the Windows Notification API in Java