Skip to content

What are Salesforce Apex Callouts?

Apex Callouts

Salesforce callouts enable integration between Salesforce and other external services. Using the Apex programming language, developers can make HTTP requests to external systems to perform CRUD operations, obtain information, and more.

In this guide, we’ll cover:

  • Basics of HTTP Callouts
  • Preparing for Callouts
  • Creating Callouts
  • Handling Responses
  • Testing Callouts

Basics of HTTP Callouts

HTTP callouts are when Salesforce reaches out to an external service using HTTP. This is done using Apex, Salesforce’s proprietary programming language.

Key Concepts:

  • Endpoint: The URL you’re reaching out to.
  • HTTP Method: The kind of request you’re making (GET, POST, etc.)
  • Request Header: Additional parameters passed along with the request.
  • Request Body: Data sent to the server (for POST requests).

Preparing for Callouts

Remote Site Settings

Before you make a callout, you must first whitelist the endpoint by adding it to the Remote Site Settings.

  1. Navigate to Setup.
  2. In the Quick Find box, type Remote Site Settings.
  3. Click on New Remote Site.
  4. Fill in the required details:
    • Remote Site Name: A unique name.
    • Remote Site URL: The endpoint URL.
    • Active: Checked.
  5. Click on Save.

Named Credentials

Instead of hardcoding credentials and endpoints, use Named Credentials. It simplifies callouts by securely storing authentication data and endpoint URLs.

  1. Navigate to Setup.
  2. Search for Named Credentials.
  3. Click on New Named Credential.
  4. Enter the details and click on Save.

Creating Callouts

Simple GET Callout

Here’s an example of a simple GET callout:

HttpRequest req = new HttpRequest();
req.setEndpoint('https://api.example.com/data');
req.setMethod('GET');

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

System.debug(res.getBody());

 

POST Callout with JSON Body

Here’s how to make a POST callout:

HttpRequest req = new HttpRequest();
req.setEndpoint('https://api.example.com/create');
req.setMethod('POST');
req.setHeader('Content-Type', 'application/json');

// JSON body
String jsonData = '{"name":"John Doe", "email":"john@example.com"}';
req.setBody(jsonData);

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

System.debug(res.getBody());

Handling Responses

Once you’ve made a callout, you’ll receive an HttpResponse. You should check the status code and handle it accordingly.

HttpResponse res = http.send(req);
if(res.getStatusCode() == 200) {
    // Success
    System.debug('Received:' + res.getBody());
} else {
    // Error
    System.debug('Error Status Code: ' + res.getStatusCode());
}

Testing Callouts

Testing callouts requires mock classes since Salesforce prevents real callouts in test methods. Here’s how you do it:

Mock Class

@isTest
global class MyMockHttpResponse implements HttpCalloutMock {
    global HTTPResponse respond(HTTPRequest req) {
        HttpResponse res = new HttpResponse();
        res.setHeader('Content-Type', 'application/json');
        res.setBody('{"status":"success"}');
        res.setStatusCode(200);
        return res;
    }
}

Test Class

@isTest
private class MyCalloutTestClass {
    @isTest static void testMyCallout() {
        Test.setMock(HttpCalloutMock.class, new MyMockHttpResponse());
        
        // Your callout method here, e.g., MyCalloutClass.makeCallout();
        
        // Asserts here
    }
}

 

Best Practices

  1. Timeout: Set a timeout for callouts using req.setTimeout().
  2. Error Handling: Always handle possible exceptions using try-catch blocks.
  3. Bulk: Ensure your callouts can handle bulk operations (e.g., if inside a trigger).
  4. Governor Limits: Salesforce has a limit of 100 callouts in a single transaction. Always be aware of this.
  5. Reusability: Create reusable methods or classes for repeated callouts.

Conclusion

Salesforce callouts are powerful tools for integration. Whether you’re fetching data, updating records in an external system, or integrating complex systems, callouts form the bridge. With proper structure, error handling, and testing, you can ensure that your integrations are robust and reliable.

 

Want some Apex learnings? Check out Mid Level Apex Tutorial

 

Salesforce Apex security best practices

Working with Time in Salesforce Apex

Schedule Apex in Salesforce: A Technical Guide for Developers

Common Apex String Methods

Speeding Up Apex Test Execution: A Guide for Faster Salesforce Deployments

Join the conversation

Your email address will not be published. Required fields are marked *

error: Content is protected !!