Skip to content
Tutorials Center
My learning

Topics

Lesson 31 of 36 ยท Integration and Deployment

Making REST Callouts from Apex and Mocking Them

Call external REST APIs from Apex with Http, HttpRequest and Named Credentials, parse JSON, handle errors and test with HttpCalloutMock, plus a runnable Java HTTP stand-in.

Salesforce rarely lives alone. You push orders to an ERP, pull exchange rates, or notify a messaging service. From Apex you do that with an HTTP callout: your code sends an HTTP request to an external endpoint and reads the response. This lesson covers the classes, how to keep credentials safe with Named Credentials, how to parse JSON, and how to test code that makes callouts, because tests cannot reach the internet.

Callouts need an org. The Apex listings are read-only with no claimed output. The runnable examples are Java stand-ins: one starts a tiny local HTTP server and calls it, and one shows mock injection.

The three classes

  • HttpRequest: the endpoint, method, headers and body.
  • Http: sends a request.
  • HttpResponse: status code, headers and body.
APEX
public with sharing class ExchangeRateService {

    public class RateException extends Exception { }

    public static Decimal getRate(String currencyCode) {
        HttpRequest req = new HttpRequest();
        req.setEndpoint('callout:Rates_API/v1/rates/' + EncodingUtil.urlEncode(currencyCode, 'UTF-8'));
        req.setMethod('GET');
        req.setHeader('Accept', 'application/json');
        req.setTimeout(10000);

        HttpResponse res = new Http().send(req);

        if (res.getStatusCode() != 200) {
            throw new RateException('Rates API returned ' + res.getStatusCode());
        }
        Map<String, Object> body = (Map<String, Object>) JSON.deserializeUntyped(res.getBody());
        return (Decimal) body.get('rate');
    }
}

Named Credentials

The endpoint callout:Rates_API/... refers to a Named Credential you create in Setup. It stores the base URL and the authentication (a password, an OAuth flow, an API key header) outside your code. Benefits: no secrets in Apex, no hard-coded URLs that differ between sandbox and production, and no need to add a Remote Site Setting. Newer orgs pair a Named Credential with an External Credential for the authentication part, but the callout: syntax is the same. Never put API keys in a custom label or in source control.

Working with JSON

  • JSON.serialize(obj) turns an Apex object, Map or List into a string.
  • JSON.deserializeUntyped(str) returns generic Maps and Lists, useful for a quick read.
  • JSON.deserialize(str, MyClass.class) maps the JSON onto a class whose properties match the keys, which is cleaner for real integrations.
APEX
public class RateResponse {
    public String code;
    public Decimal rate;
}

RateResponse r = (RateResponse) JSON.deserialize(res.getBody(), RateResponse.class);

When the external field name is a reserved word in Apex (such as currency or date), deserialize untyped or rename it with a replace on the string before mapping.

Rules and limits

  • Up to 100 callouts per transaction, each with a timeout of up to 120 seconds and a total of 120 seconds of callout time.
  • Max request and response size is about 6 MB for synchronous and 12 MB for asynchronous Apex.
  • You cannot make a callout after DML in the same transaction has left uncommitted work: do the callout first, then the DML, or move the callout into an async job.
  • Callouts from a trigger must be async.
  • Always check the status code. A 404 or 500 does not throw by itself; only network problems and timeouts raise a CalloutException.

Testing with HttpCalloutMock

Tests cannot make real callouts. Implement HttpCalloutMock and register it:

APEX
@isTest
private class ExchangeRateServiceTest {

    private class RatesMock implements HttpCalloutMock {
        private Integer status;
        private String body;
        RatesMock(Integer status, String body) { this.status = status; this.body = body; }

        public HttpResponse respond(HttpRequest req) {
            HttpResponse res = new HttpResponse();
            res.setStatusCode(status);
            res.setBody(body);
            return res;
        }
    }

    @isTest
    static void parsesRate() {
        Test.setMock(HttpCalloutMock.class, new RatesMock(200, '{"code":"EUR","rate":0.92}'));
        Test.startTest();
        Decimal rate = ExchangeRateService.getRate('EUR');
        Test.stopTest();
        Assert.areEqual(0.92, rate);
    }

    @isTest
    static void serverErrorBecomesException() {
        Test.setMock(HttpCalloutMock.class, new RatesMock(500, ''));
        try {
            ExchangeRateService.getRate('EUR');
            Assert.fail('Expected RateException');
        } catch (ExchangeRateService.RateException e) {
            Assert.isTrue(e.getMessage().contains('500'));
        }
    }
}

For several different responses in one test, use MultiStaticResourceCalloutMock or write a mock that switches on req.getEndpoint().

Try the idea: a real local HTTP call (Java stand-in)

This Java program starts a small HTTP server on the loopback address and calls it with HttpClient, the Java equivalent of Apex's Http. It is a stand-in; the sandbox has no outside network.

Java Stand-in: send a GET request and check the status (Java)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

The missing path returns 404 without throwing, just like Apex, so you must check the status yourself.

Try the idea: injecting a mock transport (Java stand-in)

Java Stand-in: swap the HTTP layer for a fake in a test (Java)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Test.setMock plays the role of the constructor argument here: production code is unchanged and the test controls the response.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What is the benefit of a Named Credential?

    Named Credentials store endpoints and secrets in Setup, so code only mentions callout:Name.
  2. 2. What happens when the server returns HTTP 500 to an Http.send call?

    Only network-level failures and timeouts throw; HTTP error statuses come back in the response.
  3. 3. How do you let a test run code that makes a callout?

    Tests cannot make real callouts; you register a mock that returns a canned response.
  4. 4. Why can't you call out after uncommitted DML in the same transaction?

    The platform raises an error: do the callout first, or move one part to an async job.

Summary

  • Use Http, HttpRequest and HttpResponse; check the status code yourself.
  • Keep endpoints and secrets in Named Credentials, using callout:Name/path.
  • Parse JSON with JSON.deserialize into classes when the shape is stable.
  • Test with HttpCalloutMock and Test.setMock.

Next: Exposing Apex as a REST Service