back to blog
Call External Rest service in Salesforce
June 29 2022 • 15 min read

BUSINESS CHALLENGE

Depending on the requirement we may have to update, delete or fetch some data which resides outside of Salesforce.

One of such services is a REST service. We can call an external REST service and can update, delete or get some data which is required inside Salesforce.

For Explanation we are going to call a currency conversion REST API from Apex and fetch the conversion rate in real time. 

STEPS TO ACHIEVE THE REQUIREMENT

  1. Signup for a REST Service (to make callouts)
  2. Add the REST service Url to Remote Site Settings
  3. Create an Apex class with Invocable method 
  4. Create a screen flow
  5. Write a test class

SIGNUP FOR A REST SERVICE

  • Head to the website https://apilayer.com and click Sign Up Free.
  • Enter email address, passwords, agree to the terms and conditions and click Sign Up. You will be taken to your account information page.
  • Click on API Marketplace at the top and search for Currency using the search box.

screenshot 224

  • Scroll down and you will see three conversion APIs i.e. Exchange Rates Data API, Fixer API, Currency Data API.

screenshot 225

  • The Exchange Rates Data API provides 250 free API calls per month and the other two APIs provide 100 free API calls per month.
  • Select any one of these APIs and click on Subscribe for Free.

screenshot 223

  • Choose a Free plan or any other plan according to your requirement and click subscribe.

screenshot 228

  • Click on profile at the top right corner and select Account.

screenshot 229

  • You will see an API key, copy and save it.

screenshot 230

ADD THE REST SERVICE URL TO REMOTE SITE SETTINGS

  • Go to Setup in your salesforce Org and search for Remote Site Settings in the Quick Find.

screenshot 208

  • Click on New Remote Site.
  • Enter Exchange_Rates_REST as the Remote Site Name, https://apilayer.com as the Remote Site Url, Enter  an optional description and let the Active option be checked.

screenshot 209

  • Click Save.

CREATE AN APEX CLASS WITH INVOCABLE METHOD

  • Here is the Apex class CurrencyExchangeRate. The Remote Site we added is used to set the endpoint Url and the API Key is used to authorize the endpoint access when the external service is called.
public class CurrencyExchangeRate {
    
    @InvocableMethod
	public static List<Decimal> getConversionRate(List<List<String>> strings){
        
        // Endpoint Url using the remote site we added
        String url = 'callout:Exchange_Rates_Rest/fixer/latest?symbols='+strings[0][1]+'&base='+strings[0][0];
        
        // Initial default for the conversion rate
        Decimal ConversionRate = 0.0;
        List<Decimal> ConversionRates = new List<Decimal>();
        
        Http h = new Http();
        
        HttpRequest req = new HttpRequest();
        req.setEndpoint(url);
        req.setMethod('GET');
        // use your API Key here
        req.setHeader('apikey', 'Your_API_Key');
        
        
        // Send the request, and return a response
        HttpResponse res = h.send(req);
        
        // If the request is successful, parse the JSON response.
        if(res.getStatusCode()==200){
            
            // Deserialize the JSON string into collections of primitive data types.
            Map<String,Object> results = (Map<String,Object>)JSON.deserializeUntyped(res.getBody());
            Map<String,Object> value = (Map<String,Object>)results.get('rates');
            ConversionRate = (Decimal)value.get(strings[0][1]);
            System.debug('The Conversion rate is : '+ ConversionRate);
            conversionRates.add(conversionRate);
    	}
    	return conversionRates;
	}
}
  • @Invocable annotation allows the apex method to be called from a flow.
  • When the parameter for the Invocable method is declared as List, It allows only one variable as an Argument to pass in the flow, in order to pass arguments in the flow as a collection of variables we should declare the parameter as List<List> for the invocable method.

CREATE A SCREEN FLOW

  • From Setup, in the Quick Find search for Flows and select it.

screenshot 211

  • Click on New Flow.
  • Select Screen Flow and click on Create.

screenshot 231

  • Click on + and add a Screen element.

screenshot 214

  • Enter the label as Currency Input.

screenshot 232

  • Under Configure Header uncheck the Show Header checkbox.

screenshot 233

  • Under Configure Footer, for “Next or Finish” Button choose Use a custom label and enter Check Conversion Rate as label. Hide Previous and Pause buttons.

screenshot 234

  • Drag and drop two text components from the left pane. Label them as From Currency, To Currency and make the two values as Require. Click Done.

screenshot 235

screenshot 237

screenshot 238

  • Create a New Resource to store From and To currencies.

screenshot 239

  • Choose Variable as Resource Type, Enter strings as the API Name, choose Text as Data Type and check the Allow multiple values checkbox. Click Done.

screenshot 240

  • Click on + icon and add an Assignment element.

screenshot 241

  • Enter the label as Assign Currencies. Under Set Variable Values, choose the variable as strings, select the operator as Add and value as From Currency text value from screen components. The same way add To Currency text value to the strings collection variable and click Done.

screenshot 242

  • Click on + icon and add Action element.

screenshot 243

  • search for Apex and select the invocable method CurrencyExchangeRate that we created. 

screenshot 244

  • Enter the label as Invoke Apex and under Set Input Values switch the toggle to Include and choose the strings collection variable.

screenshot 245

  • Click on Advanced and check the Manually assign variables checkbox. Under Store Output Values, for the output create a new resource. 

screenshot 247

  • Choose Variable as Resource Type, Enter ConversionRate as the API Name, Select Number as Data Type, 2 as Number of decimal places and Click Done.

screenshot 248

  • Now the output variable is set, click Done.

screenshot 249

  • Click on + icon and add a Screen element.

screenshot 250

  •  Enter the label as Display Conversion Rate.

screenshot 251

  • Under Configure Header uncheck the Show Header checkbox. 

screenshot 252

  • Under Configure Footer hide the pause button and use a custom label for the finish button and name it as Convert.

screenshot 253

  • Add a Display Text component and enter the API Name as ConversionRateMessage.

screenshot 255

  • Enter the value as 
The conversion rate from 1{!From_Currency} to {!To_Currency} is {!ConversionRate}

screenshot 256

  • Drag and drop a Number component from the left pane, enter the label as Enter Currency Value to Convert, make it Require and enter 2 as decimal places. Click Done.

screenshot 257

  • Create a New Resource.

screenshot 258

  • Choose Formula as Resource Type. Enter ConvertedCurrency as the API Name, select Number as Data Type, let the decimal places be 2 and enter the formula as given below and click Done.
{!Enter_Currency_Value_to_Convert}*{!ConversionRate}

screenshot 259

  • Click + and add a Screen element.

screenshot 260

  • Label it as Display Converted Currency.

screenshot 261

  • Under Configure Header uncheck the Show Header checkbox.

screenshot 262

  • Under Configure Footer hide the pause button.

screenshot 263

  • Drag and drop a Display Text component from the left pane and enter the API name as DisplayConvertedCurrency.

screenshot 264

  • Enter the value as given below and click Done.
{!Enter_Currency_Value_to_Convert}{!From_Currency} is equal to {!ConvertedCurrency} {!To_Currency}

screenshot 265

  • Click Save at the top right corner

screenshot 266

  • Enter a label for the flow and click Save again.

screenshot 267

  • Activate the flow.

screenshot 268

WRITE A TEST CLASS

  • In order to cover the code for external services a mock class should be written which provides a response whenever the external service is called in the test class.
  • Here is the mock class
@isTest
global class CurrencyExchangeRateMock implements HttpCalloutMock {
    global HttpResponse respond(HttpRequest request){
        HttpResponse response = new HttpResponse();
        response.setHeader('api_key', 'Api_security_token');
        response.setBody('{"success" : true, "base" : "USD" , "rates" : {"INR" : 1}}');
        response.setStatusCode(200);
        return response;
    }
}
  • Here is the test class
@isTest
public class CurrencyExchangeRateTest {
    
    @isTest
    public static void testCurrencyExchangeRate() {
        Test.setMock(HttpCalloutMock.class, new CurrencyExchangeRateMock());
        List<List<String>> strings = new List<List<String>>();
        List<String> values = new List<String>();
        values.add('USD');
        values.add('INR');
        Strings.add(values);
        List<Decimal> ConversionRates = CurrencyExchangeRate.getConversionRate(strings);
        Decimal ConversionRate = conversionRates.get(0);
        System.assertEquals(1, ConversionRate, 'Assertion gone wrong for Conversion Rate');
    }
}

NOTE

  1. The user should have either Run Flows or Manage Flow permission enabled for their profile in order to use the screen flow and access to the Apex class with an invocable method that calls the rest service, in order to invoke it from the screen flow.

HOW IT WORKS

This is how the screen flow looks.

screenshot 276

Enter the values and click on Check Conversion Rate button

screenshot 273

You will see a screen which displays the conversion rate, enter a value and click on Convert.

screenshot 274

You will see the converted currency value

screenshot 275

The Finish button takes you back to the first screen.

WRAPPING IT UP

In this blog we have covered how to use an Apex class to call an External Rest service and get the real time currency conversion rate in a screen flow.

Leave a Comment

Your email address will not be published

© 2024 Digital Biz Tech