Fetch API in Apex Salesforce
•23 min read
Here is the clear explanation of how to call a Fetch-like API in Apex (Salesforce) using HttpRequest, because Salesforce does NOT support fetch() directly. Instead, Apex uses the Http and HttpRequest classes.
✅ Fetch API Equivalent in Apex (Salesforce)
In JavaScript, you use:
fetch('https://example.com/api', {
method: 'GET'
})
JavaScriptIn Apex, the equivalent is:
⭐ GET Request (Fetch Equivalent) – Apex Code
public with sharing class FetchLikeCallout {
@future(callout=true)
public static void getCallout() {
Http http = new Http();
HttpRequest req = new HttpRequest();
req.setEndpoint('https://example.com/api');
req.setMethod('GET');
// Optional: Add headers
req.setHeader('Content-Type', 'application/json');
HttpResponse res = http.send(req);
System.debug('STATUS: ' + res.getStatus());
System.debug('BODY: ' + res.getBody());
}
}
JavaScript⭐ POST Request (Fetch POST Equivalent)
JavaScript fetch:
fetch('https://example.com/api', {
method: 'POST',
body: JSON.stringify({name:"ChatGPT"})
})
JavaScriptpublic with sharing class ApexPostCallout {
@future(callout=true)
public static void postCallout() {
Http http = new Http();
HttpRequest req = new HttpRequest();
req.setEndpoint('https://example.com/api');
req.setMethod('POST');
req.setHeader('Content-Type', 'application/json');
// JSON Body
Map<String, Object> body = new Map<String, Object>();
body.put('name', 'ChatGPT');
req.setBody(JSON.serialize(body));
HttpResponse res = http.send(req);
System.debug('STATUS: ' + res.getStatus());
System.debug('BODY: ' + res.getBody());
}
}
JavaScript⭐ Fetch With Authorization Header (Bearer Token)
HttpRequest req = new HttpRequest();
req.setEndpoint('https://example.com/protected/api');
req.setMethod('GET');
req.setHeader('Authorization', 'Bearer YOUR_TOKEN_HERE');
req.setHeader('Content-Type', 'application/json');
Http http = new Http();
HttpResponse res = http.send(req);
System.debug(res.getBody());
JavaScript⭐ If You Need Named Credentials (BEST PRACTICE)
HttpRequest req = new HttpRequest();
req.setEndpoint('callout:My_Named_Credential/api/data');
req.setMethod('GET');
Http http = new Http();
HttpResponse res = http.send(req);
System.debug(res.getBody());
JavaScriptThis avoids storing tokens manually.
⭐ Handling Response JSON in Apex
String jsonBody = res.getBody();
Map<String, Object> data = (Map<String, Object>) JSON.deserializeUntyped(jsonBody);
System.debug('Value: ' + data.get('key'));JavaScriptRelated Posts

How to Automatically create a follow-up Task when a Lead is converted

How You need to update a related child record whenever a parent record’s status changes, but only if the status is “Closed Won.” How would you design this in Apex?
