Dev Note - HttpClient in SFRA (Salesforce)
SFRA HttpClient Code
Using HttpClient in Salesforce Commerce Cloud
I needed a quick way to get a model for a view. For our API calls, I created services, profiles and credentials that are managed by SFCC. But that's overkill for a one off call. HttpClient is a way to make external calls, in SFCC/SFRA there's a little twist. Code to use the TypeScript HTTPClient in cartridge code:
function callExternalUrl(parameters) {
var HTTPClient = require('dw/net/HTTPClient');
var Logger = require('dw/system/Logger');
if (!empty(parameters)) {
var url = parameters.url;
var userId = parameters.userId;
var password = parameters.password;
var httpClient = new HTTPClient();
httpClient.setTimeout(2000);
httpClient.open("GET", url, userId, password);
httpClient.send();
if (httpClient.statusCode == 200) {
//confirm response
Logger.getLogger("shop").info(
httpClient.text
);
// do something with response object
// var sourceObject = JSON.parse(httpClient.text);
}
} else {
// error handling
Logger.getLogger("shop").error(
"An error occured with status code " +
httpClient.statusCode
);
}
}
// ...
// var parameters = {
// url: "",
// userId: "",
// password: ""
// }
// callExternalUrl(parameters)
This post and/or images used in it may have been created or enhanced using generative AI tools for clarity and organization. However, all ideas, technical work, solutions, integrations, and other aspects described here are entirely my own.