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
- Signup for a REST Service (to make callouts)
- Add the REST service Url to Remote Site Settings
- Create an Apex class with Invocable method
- Create a screen flow
- 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.
- Scroll down and you will see three conversion APIs i.e. Exchange Rates Data API, Fixer API, Currency Data API.
- 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.
- Choose a Free plan or any other plan according to your requirement and click subscribe.
- Click on profile at the top right corner and select Account.
- You will see an API key, copy and save it.
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.
- 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.
- 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.
- Click on New Flow.
- Select Screen Flow and click on Create.
- Click on + and add a Screen element.
- Enter the label as Currency Input.
- Under Configure Header uncheck the Show Header checkbox.
- 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.
- 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.
- Create a New Resource to store From and To currencies.
- 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.
- Click on + icon and add an Assignment element.
- 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.
- Click on + icon and add Action element.
- search for Apex and select the invocable method CurrencyExchangeRate that we created.
- Enter the label as Invoke Apex and under Set Input Values switch the toggle to Include and choose the strings collection variable.
- Click on Advanced and check the Manually assign variables checkbox. Under Store Output Values, for the output create a new resource.
- 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.
- Now the output variable is set, click Done.
- Click on + icon and add a Screen element.
- Enter the label as Display Conversion Rate.
- Under Configure Header uncheck the Show Header checkbox.
- Under Configure Footer hide the pause button and use a custom label for the finish button and name it as Convert.
- Add a Display Text component and enter the API Name as ConversionRateMessage.
- Enter the value as
The conversion rate from 1{!From_Currency} to {!To_Currency} is {!ConversionRate}
- 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.
- Create a New Resource.
- 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}
- Click + and add a Screen element.
- Label it as Display Converted Currency.
- Under Configure Header uncheck the Show Header checkbox.
- Under Configure Footer hide the pause button.
- Drag and drop a Display Text component from the left pane and enter the API name as DisplayConvertedCurrency.
- Enter the value as given below and click Done.
{!Enter_Currency_Value_to_Convert}{!From_Currency} is equal to {!ConvertedCurrency} {!To_Currency}
- Click Save at the top right corner
- Enter a label for the flow and click Save again.
- Activate the flow.
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
- 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.
Enter the values and click on Check Conversion Rate button
You will see a screen which displays the conversion rate, enter a value and click on Convert.
You will see the converted currency value
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