Apex Callouts

Apex Callouts (GET/POST APIs)

What Are Apex Callouts?

An Apex callout allows your Salesforce org to connect to external systems using HTTP to send or receive data. You can call REST or SOAP APIs using GET, POST, PUT, DELETE, etc.

Prerequisites for Callouts

1. Remote Site Settings

   • Go to: Setup → Remote Site Settings

   • Add the external URL (without the path)

2. Named Credentials (recommended)

   • Setup → Named Credentials

   • Stores endpoint URL and credentials securely

GET Request (Fetch Data)

Example1:

Use case: Get the public IP of your org from an external API like https://api.ipify.org?format=json.

public class GetPublicIP {

public static String getIP() {

Http http = new Http();

HttpRequest req = new HttpRequest();

req.setEndpoint(‘ https://publicapi.dev/’);

req.setMethod(‘GET’);

 

HttpResponse res = http.send(req);

return res.getBody(); // e.g. {“ip”:”123.123.123.123″}

}

}

Explanation:

This sends a GET request to a free IP API and returns your IP in JSON.

Step 1: Add Remote Site Setting

1. Go to Setup → search Remote Site Settings.
2. Click New Remote Site.

    • Name : PublicIPAPI

    • URL : e.g., https://publicapi.dev/

    • Click Save.

3. Open Developer Console → Press Ctrl + E.

4. Paste and run:

String myIP = GetPublicIP.getIP();

System.debug(‘My Public IP: ‘ + myIP);

• Check the box “Open Log” before clicking Execute.

• After execution, go to the Logs tab → click on the latest log.

• Use CTRL + F to search for My Public IP.

Example2:

Use case: Fetch user data from https://jsonplaceholder.typicode.com/users/1

public class DummyUserFetcher {

public static String getUser() {

Http http = new Http();

HttpRequest req = new HttpRequest();

req.setEndpoint(‘https://jsonplaceholder.typicode.com/users/1’);

req.setMethod(‘GET’);

 

HttpResponse res = http.send(req);

return res.getBody(); // returns JSON user object

}

}

Explanation:

Fetches dummy user data with fields like name, email, and company.

Step 1: Add Remote Site Setting

1. Go to Setup → search Remote Site Settings.

2. Click New Remote Site.

3. Name : JsonPlaceholder

4. URL : e.g., https://jsonplaceholder.typicode.com/users/1

    • Click Save.

5. Open Developer Console → Press Ctrl + E.

6. Paste and run:

String userInfo = DummyUserFetcher.getUser();

System.debug(‘Dummy User Info: ‘ + userInfo);

Sample Output

Dummy User Info: {

“id”: 1,

“name”: “Leanne Graham”,

“username”: “Bret”,

“email”: “Sincere@april.biz”,

“address”: {

“street”: “Kulas Light”,

“city”: “Gwenborough”

},

“company”: {

“name”: “Romaguera-Crona”

}

}

Example3:

Use Case: Display real-time Bitcoin price from CoinDesk API.

public class BitcoinPriceFetcher {

public static String getPrice() {

Http http = new Http();

HttpRequest req = new HttpRequest();

req.setEndpoint(‘ https://www.coinapi.io’);

req.setMethod(‘GET’);

HttpResponse res = http.send(req);

return res.getBody();

}

}

Explanation: Fetches current Bitcoin price like :

{

“bpi”: {

“USD”: {

“rate”: “27,684.1450”,

“description”: “United States Dollar”

}

}

}

Step 1: Add Remote Site Setting

1. Go to Setup → search Remote Site Settings.

2. Click New Remote Site.

3. Name : CoinDeskAPI

    • URL : e.g., https://www.coinapi.io

    • Click Save.

4. Open Developer Console → Press Ctrl + E.

5. Paste and run:

String price = BitcoinPriceFetcher.getPrice();

System.debug(price);

POST Request

Example1:

Use case: Send a contact’s name and email to another system.

public class SendContactData {

public static String postContact(String name, String email) {

Http http = new Http();

HttpRequest req = new HttpRequest();

req.setEndpoint(‘https://httpbin.org/post’);

req.setMethod(‘POST’);

req.setHeader(‘Content-Type’, ‘application/json’);

String body = ‘{“name”:”‘ + name + ‘”, “email”:”‘ + email + ‘”}’;

req.setBody(body);

HttpResponse res = http.send(req);

return res.getBody(); // Response from external system

}

}

Explanation:

Sends a JSON payload to an API and returns the response.

Step-by-Step: How to Run This POST Request

Step 1: Add Remote Site Setting

1. Go to Setup → search Remote Site Settings.

2. Click New Remote Site.

3. Name : CoinDeskAPI

URL : e.g., https://www.coinapi.io

Click Save.

4. Open Developer Console → Press Ctrl + E.

5. Paste and run:

String response = SendContactData.postContact(‘John Doe’, ‘john@example.com’); 

System.debug(‘Response: ‘ + response); 

Check “Open Log” before clicking Execute

Example2:

Use case: Send a new task to a task management system.

public class TaskSender {

public static String sendTask(String title) {

Http http = new Http();

HttpRequest req = new HttpRequest();

req.setEndpoint(‘https://jsonplaceholder.typicode.com/posts’);

req.setMethod(‘POST’);

req.setHeader(‘Content-Type’, ‘application/json’);

req.setBody(‘{“title”:”‘ + title + ‘”, “body”:”From Salesforce”, “userId”: 1}’);

HttpResponse res = http.send(req);

return res.getBody();
}

}

Explanation:

Uses a dummy API to simulate creating a new post (like a task).

Step-by-Step: How to Run This POST Request

Step 1: Add Remote Site Setting

To allow Salesforce to make external callouts:
1. Go to Setup → search Remote Site Settings.

2. Click New Remote Site.
3. Name : JsonPlaceholderAPI

• URL : e.g., https://jsonplaceholder.typicode.com

• Click Save.

Step 2: Run the Code in Developer Console

1. Open Developer Console → Debug → Open Execute Anonymous Window (or press Ctrl + E).

2. Paste and run this:

String result = TaskSender.sendTask(‘Finish Apex Tutorial’);

System.debug(‘Response: ‘ + result);

Expected Output

Even though no actual task is created (since it’s a dummy API), the response will look like this:

{

“title”: “Finish Apex Tutorial”,

“body”: “From Salesforce”,

“userId”: 1,

“id”: 101

}

The “id”: 101 is a simulated ID — this means the POST was accepted successfully.

Example 3:

Use case: Send feedback from Salesforce to a form API.

public class FeedbackSender {

public static String sendFeedback(String message) {

Http http = new Http();

HttpRequest req = new HttpRequest();

req.setEndpoint(‘https://httpbin.org/post’);

req.setMethod(‘POST’);

req.setHeader(‘Content-Type’, ‘application/json’);

String json = ‘{“feedback”:”‘ + message + ‘”}’;

req.setBody(json);

HttpResponse res = http.send(req);

return res.getStatusCode() == 200 ? ‘Sent successfully’ : ‘Error’;

}

}

Explanation:

Sends user feedback to an API and checks if the response status is 200.

Step-by-Step: How to Run This POST Request

Step 1: Add Remote Site Setting

1. Go to Setup → search Remote Site Settings.

2. Click New Remote Site.
Name : FeedbackAPI

URL : e.g., https://httpbin.org

Click Save.

Execute in Developer Console

1. Go to Developer Console → Debug → Open Execute Anonymous Window.

2. Paste and run:

String response = FeedbackSender.sendFeedback(‘This app is amazing!’);

System.debug(‘Feedback Status: ‘ + response);

EnableOpen Logto see the debug output.

Expected Output

If you’re using httpbin.org, status code will be 200, so the debug log shows:

Feedback Status: Sent successfully

If you use an invalid or offline endpoint, you’ll get:

Feedback Status: Error

Tasks :

1- Call a public weather API (like https://api.weatherapi.com/) to fetch current weather details for a given city.

• Write an Apex GET method that accepts a city name and returns temperature and condition.

• Parse JSON response and return only required fields.

2. Simulate sending a Salesforce Lead’s name and email to an external CRM system using a POST request.

• Send data as JSON.

• Handle response status and return success/failure message.

3. Build a POST callout that updates product inventory on an external system. 

• Send product ID and quantity.

• Create proper JSON body.

• Parse and log the response.

4. Use a news API (like NewsAPI.org) to fetch the top 5 headlines.

• Write a GET callout.

• Parse the response to extract headlines.

• Return a list of headline strings.

5. Write a test class for any of your callout classes using HttpCalloutMock.

• Create mock response JSON. 
• Verify that your class correctly handles the response. 

6. Create a batch Apex class that sends multiple records in chunks to an external API.

• Handle chunking of records.

• Make callouts for each batch.

• Log success and failures.