Salesforce REST API callout to consume an external REST API | CYUKT

Salesforce REST API callout to consume an external REST API

 

Basic information required to write Apex code to call external REST API from Salesforce

  1. External REST API end point URL
  2. XML or JSON format
  3. Salesforce generated certificate for two-way SSL authentication

Step#1: Configure Remote Site Settings

Before any Visualforce page, Apex callout, or JavaScript code using XmlHttpRequest in an s-control or custom button can call an external site, that site must be registered in the Remote Site Settings page, or the call will fail.

From Setup, click Security Controls | Remote Site Settings.

For security reasons, Salesforce restricts the outbound ports you may specify to one of the following:

  • 80: This port only accepts HTTP connections.
  • 443: This port only accepts HTTPS connections.
  • 1024–66535 (inclusive): These ports accept HTTP or HTTPS connections.

To register a new site:

  1. Click New Remote Site.
  2. Enter a descriptive term for the Remote Site Name.
  3. Enter the URL for the remote site. Ex: https://samplesite.com
  4. Check Active checkbox and save
Salesforce | Cyukt.com

Remote Site Settings

Step#2: Generate Salesforce certificate

Salesforce currently providing two types of certificates for use. Based on your client requirement you can choose certificate type.

To generate a certificate for a callout:

  1. From Setup, click Security Controls | Certificate and Key Management.
  2. Select either Create Self-Signed Certificate or Create CA-Signed Certificate
  3. Enter all required details based on certificate selected
  4. Select a Key Size for your generated certificate and keys. Salesforce recommends default key size of 2048 for security reasons. Selecting 2048 generates a certificate using 2048-bit keys and is valid for two years.
  5. After save, Self-Signed Certificate can download and use directly. In case of CA-Signed Certificate after uploading of signed certificate you can use.

Self-Signed Certificate: This is Salesforce signed certificate. No external authorization needed.

Salesforce | Cyukt.com

Self Signed Certificate Salesforce | Cyukt.com

CA-Signed Certificate: Create this certificate, send the certificate to Certificate Authority of your choice. After Certificate Authority sends back the signed certificate, upload the signed certificate. After successful upload only status would become active.

 

Salesforce | Cyukt.com

CA signed Certificate 1 Salesforce | Cyukt.com

CA signed Certificate 2

CA signed Certificate 2

 

Use Upload Signed Certificate button to upload certificate after signed by Certification Authority.

 

 

Share the downloaded certificate with external REST API team to place the certificate in keystore of server. They have to manually import certificate based on environment. If external REST API is built in java and using Tomcat as server they need to run this type of command at their end to import certificate

keytool -importcert -trustcacerts -alias my_ca -keystore $HOME/tomcat/conf/tomcat.keystore -file cacert.pem

 Note: Using certificate is optional.

Step#3: Apex code to invoke external REST API

For example, client provided following details

End-point URL : https://samplesite.com/samplerest

JSON format: [{“Name”: “John Carter”,”Email”: “john.carter@basoom.com”,”Age”: “35”}, {“Name”: “Bruce Wayne”,”Email”: “bruce@wayne.com”,”Age”: “29”}]

Certificate: Generate Self-Signed Certificate and name it as ‘Sample-Rest-Self-Signed’

After above two steps, write Apex class to call API

  /**
    * This is future method to call external REST API
    * @Param jsonString
  **/
  @future(callout=true)
  public static void sendCalloutREST(String jsonString){
    try{
      String endPointURL = 'https://samplesite.com/samplerest';
      String userName = 'samuser';
      String password = 'Sam@789';
      
      // Specify the required user name and password to access the endpoint 
      // As well as the header and header information 
      Blob headerValue = Blob.valueOf(userName + ':' + password);
      String authorizationHeader = 'BASIC ' +
      EncodingUtil.base64Encode(headerValue);

      Httprequest request = new HttpRequest();
      Http http = new Http();

          request.setMethod('POST');
          request.setEndpoint(endPointURL);
      request.setHeader('Content-Type', 'application/json');
      // Header info with remote server user name and password
      request.setHeader('Authorization', authorizationHeader);
      //Check the client certificate
      request.setClientCertificateName('Sample-Rest-Self-Signed');
      // timeout in milliseconds       
      request.setTimeout(120000); 
          request.setBody(jsonString);          
          
          //Making call to external REST API
          HttpResponse response = http.send(request);  

          System.debug('responseBody: '+response.getBody());
      }catch(Exception e){
      System.debug('Error::'+e.getMessage());
    }
  }
									

 

Tips:

  1. Postman – REST Client extension on Google Chrome help you to check manually external REST API.
  2. Check Callout limits on Salesforce.com online help
This post was written by , posted on July 26, 2014 Saturday at 2:52 pm

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>

Visit Us On FacebookVisit Us On Twitter