Invoke API Callout from Apex

What is API

Application Program Interface, in other words, API is a way to connect your Salesforce org to other systems. This might be the simplest explanation possible, and yet, it kinda explains the whole purpose of APIs.A more scientific definition would be more like that: APIs allow external applications to programmatically access data within your Salesforce org in a simple and secure manner.There are several different types of API that Salesforce offers:REST API is one of the most common APIs used these days. It’s essentially a way of accessing objects via the web. In Salesforce, we can use it to create, read, update, and delete records, search or query data, retrieve object metadata, and access information limits in your org. It supports XML and JSON.SOAP API is an alternative approach to REST, based on the use of queries. Most of its functionality is also available through REST API. It supports XML only.Bulk API is a specialized RESTful API for loading and querying lots of data at once.Streaming API is a specialized API for setting up notifications that trigger when changes are made to your data.There are also other types, such as Chatter REST API, User Interface API, Analytics REST API, Metadata API, or Tooling API. Each serves a specific purpose. Here’s a Trailhead Module on this topic. It provides a good description of all of them, along with explanations on when to use each API.

Create API Callout

Now that we know what API is, it’s time to give it a try.First, let’s create a hypothetical situation, so we can build something that could actually be used in real life. In our scenario, the stakeholders want users to have a handy tool to quickly convert prices. Instead of looking for rates on the web, users should be able to get correct pricing in a matter of seconds inside Salesforce.For this requirement we need to build an automated solution. We are going to create an apex class that converts EUR to USD. But because the rates used in the calculation should always be up-to-date, we’ll need to use REST API callout to get that data from an external system.For the exchange rates we will use be able to call this external API, first we need to provide the URL in the Remote Site Settings in Setup.

remote site settings

Now, open Developer Console, and create a new Apex Class. Let’s go step by step.We’re creating a public class, and a public method that takes a Decimal and returns a Decimal.public class CurrencyConverterClass {public static Decimal convertCurrencyToUSD(Decimal eur) {First, we need a variable to store the final result of the calculation.Decimal usd = 0.0;Now, we use Apex built-in classes to create an HTTP object that initiatesan HTTP request/response, and a HTTPRequest object that we can use to create a request.HTTP h = new HTTP();HTTPRequest req = new HTTPRequest();With the request, we can set up an endpoint.req.setEndpoint('');And set the method to GET to get the data we need.req.setMethod('GET')With that we can send our request to get the response.HTTPResponse res = h.send(req);What we just did was the API Callout. Now, we need to use the getBody() method to retrieve the body returned in the response. Because the information that comes back is in JSON format we parse it with the deserializeUntyped(jsonString) method, and convert it into a Map.Map<String,Object> jsonBody = (Map<String,Object>)Json.deserializeUntyped(res.getBody());We don’t need all the information, just the part that has the exchange rates.Map<String,Object> mRates = (Map<String,Object>) jsonBody.get('rates');Again, we don’t need all the exchange rates. Let’s look for the USD conversion rate and store in a variable.Decimal conversionRate = (Decimal) mRates.get('USD');Now we’ll use that variable to calculate the final result and return it.usd = eur * conversionRate;return usd;And here you go.At the end, your whole code should look like this:


API Callouts are extremely useful, and necessary when you need to integrate, or connect Salesforce with an external application.Remember that to test your callouts, you should use mock callouts by either implementing an interface or using static resources.