Skip to content
Namaste Salesforce Namaste Salesforce
Developer Roadmap

REST callouts & named credentials

Call external REST APIs from Apex, and manage endpoints and auth cleanly with named credentials.

Developer Roadmap Article 1 min

REST callouts & named credentials

Salesforce rarely lives alone; it exchanges data with payment systems, ERPs, and countless SaaS tools. The most common outbound pattern is an Apex REST callout — your code makes an HTTP request to an external service. Doing it securely and maintainably hinges on one feature: named credentials.

A raw callout uses HttpRequest and Http. But hard-coding a URL and, worse, credentials into Apex is insecure and brittle. A named credential externalises the endpoint URL and the authentication (Basic, OAuth, and more) into secure configuration. Your Apex then references it by name with the callout: prefix, and Salesforce injects the URL and auth headers at runtime — no secrets in code, and you can point the same code at different environments by changing config.

public with sharing class WeatherService {
    public static String getForecast(String city) {
        HttpRequest req = new HttpRequest();
        // 'Weather_API' is a Named Credential; Salesforce supplies URL + auth
        req.setEndpoint('callout:Weather_API/v1/forecast?city=' + EncodingUtil.urlEncode(city, 'UTF-8'));
        req.setMethod('GET');

        HttpResponse res = new Http().send(req);
        if (res.getStatusCode() == 200) {
            return res.getBody();
        }
        throw new CalloutException('Weather API returned ' + res.getStatusCode());
    }
}

A few essentials. You must register any external site in Remote Site Settings or, better, use a named credential which handles that for you. Callouts cannot run after DML in the same transaction, and cannot run synchronously from a trigger — for that, move the callout into an async context like a Queueable. In tests, real callouts are forbidden, so you supply an HttpCalloutMock to return a canned response.

Design tips: always check the status code and handle failures, set sensible timeouts, and never log secrets. Named credentials plus proper error handling turn a fragile script into a production-ready integration.

As an exercise, create a named credential for a public REST API, write a callout class that consumes it, and cover it with a test using HttpCalloutMock. Next we look at the inbound, event-driven side of integration with Platform Events.

Advertise with us · 728×90