Skip to content

Latest commit

 

History

History
271 lines (173 loc) · 12.2 KB

SalesforceIntegration.md

File metadata and controls

271 lines (173 loc) · 12.2 KB

Salesforce Integration Guide/Notes

  • It's needed when we need to connect 2 or more different systems e.g.; if you wanted to show your dropbox files on your salesforce org page.

UKHzcELU

Web Services

REST

  • Fast

  • Supports all types of devices.

  • Works with JSON, XML, and other formats.

SOAP

  • Slow (compared to REST).

  • Works with XML.

  • It's more secure in comparison to REST.

  • It's mostly used in Enterprise Applications.

  • You get a document called WSDL, which has all the information about requests and responses of any given service. It helps you create request and response classes and methods with a parser (in most cases). In the case of REST, you don't have any such facility.

REST Web Service Methods

  • GET - Retrieve the records.

  • POST - Insert the records.

  • PUT - Insert new records or update existing records.

  • PATCH - Update existing records.

  • Delete - Delete existing records.

Making Request to External Service

Example REST Callout

// Since we are making calls over http, we need an instance of HTTP.
Http http = new Http();

// We also need an instance of HttpRequest, which we will send over http using HTTP instance.
HttpRequest request = new HttpRequest();

// Now we ware adding the information related to request e.g.; Endpoint we are hitting and type of request it's. In this case it's GET.
request.setEndpoint('https://th-apex-http-callout.herokuapp.com/animals');
request.setMethod('GET');

// Here we make a request and expect a response in HttpResponse instance.
HttpResponse response = http.send(request);

// If the request is successful (status code is 200), parse the JSON response.
if(response.getStatusCode() == 200) {
    
    // Deserialize the JSON string into collections of primitive data types.
    Map<String, Object> results = (Map<String, Object>) JSON.deserializeUntyped(response.getBody());
    
    // Cast the values in the 'animals' key as a list
    List<Object> animals = (List<Object>) results.get('animals');
    
    System.debug('Received the following animals:');
    for(Object animal: animals) {
        System.debug(animal);
    }
}

Making Requests Using Developer Console

  • You can run the above code in the developer console. Go to the developer console, and from there, click on Debug -> Open Execute Anonymous Window.

developer-console

debug_window

  • In Anonymous Window, you can execute the code by clicking the Execute button at the bottom of the screen

Execute code

Authorize Endpoint

  • In Salesforce, before making any request to an external API, we need to authorize it. Otherwise, we will get the following error.

System.CalloutException: Unauthorized endpoint, please check Setup->Security->Remote site settings. endpoint = https://api.spoonacular.com/recipes/random

Unauthorized Endpoint Error

  • Now to make a request, you need to add your site in Remote site settings. You can go there by visiting Setup->Security->Remote Site Settings

Remote Site Settings

Add URL FORM

Example SOAP Callout Using WSDL

WSDL

  • A WSDL is an XML document that describes a web service.

  • It talks about the functions that you can implement or expose to the client e.g.; getRecipe etc., request parameters, which are optional, which are required, etc., and also about the response.

  • It actually stands for Web Services Description/Definition Language.

SOAP

  • SOAP is an XML-based protocol that lets you exchange info over a particular protocol (can be HTTP or SMTP, for example) between applications.
  • It stands for Simple Object Access Protocol and uses XML for its messaging format to relay the information.

Real-life analogy to WSDL and SOAP.

WSDL: When we go to a restaurant, we see the Menu Items, those are the WSDLs.

Proxy Classes: Now after seeing the Menu Items we make up our minds. So, basically, we make Proxy classes based on WSDL Document.

SOAP: Then when we actually order the food based on the Menus. Meaning we use proxy classes to call upon the service methods which are done using SOAP.

Generating Proxy files using the WSDL document

You can create Apex classes using the WSDL file but it's no different than making a request to REST base call-in terms of code. In the body of the request, you will have to send XML in SOAP protocol, and in response, you should expect XML in SOAP protocol.

  • Go to Setup -> Apex Classes -> Generate from WSDL

WSDL Apex File Generator

  • Select the WSDL file and click Parse WSDL

Select WSDL File

  • Now you will show the classes extracted from the WSDL file. You get the opportunity to change the name of classes before classes are created.

Classes Extrated

  • For each generated class, a second class is created with the same name and the prefix Async. The CalculatorServices class is for synchronous callouts. The AsyncCalculatorServices class is for asynchronous callouts.

Final output

Example SOAP Callout Using HTTP

        HttpRequest req = new HttpRequest();
        req.setMethod('POST');
        req.setEndpoint('https://th-apex-http-callout.herokuapp.com/animals.asmx');
        req.setHeader('Content-Type', 'text/xml; charset=UTF-8');
        req.setHeader('SOAPAction', 'SomeAction');
        req.setHeader('Content-Length', '0');
        req.setBody('<?xml version="1.0" encoding="utf-8"?>' +
            + '<soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">'
            + '<soap:Body xmlns="">'
            + '</soap:Body></soap:Envelope>');

            System.debug('Request =' + req.getBody().unescapeXml());

            Http http = new Http();
            HttpResponse res = http.send(req);
  • You can expose your Apex class methods as a REST or SOAP web service operation.
  • By making your methods callable through the web, external applications can integrate with Salesforce.

Example Use Case

  • You have an internal app used to make calls to potential leads.

  • You can show the lead data from Salesforce in your app and also get updates on the lead status if any.

  1. Define your class as global.
  2. Define methods as global static.
  3. Add annotations to the class (@RestResource(urlMapping='/Account/*')) and methods (@HttpGet)
@RestResource(urlMapping='/Account/*')
global with sharing class MyRestResource {
    @HttpGet
    global static Account getRecord() {
        // Add your code
    }
}

The following method annotations are available.

method-annoations

  1. Define your class as global.
  2. Add the webservice keyword and the static definition modifier to each method you want to expose.
  3. The webservice keyword provides global access to the method it is added to.
global with sharing class MySOAPWebService {
    webservice static Account getRecord(String id) {
        // Add your code
    }
}
  • The external application can call your custom Apex methods as web service operations by consuming the class WSDL file.

  • You can generate this WSDL for your class from the class detail page, accessed from the Apex Classes page in Setup.

Terminologies

  • OpenAPI: An API for which you don't need to authorize yourself to make the call. Spoonacular is one such example.
  • Request
  • Response
  • Statuscode
  • Endpoint
  • Callout

Reference