architect, writer, strategist, technologist

Disclaimer: The opinions expressed herein are my own personal opinions and do not represent my employer’s view in any way.

Dev Note - HttpClient in SFRA (Salesforce)

posted on July 27, 2021 by Mark Roxberry
main post image
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);"GET", url, userId, password);

        if (httpClient.statusCode == 200) {
            //confirm response

            // do something with response object
            // var sourceObject = JSON.parse(httpClient.text);

        } else {
            // error handling
                "An error occured with status code " + 

// ...
// var parameters = {
//     url: "",
//     userId: "",
//     password: ""
// }
// callExternalUrl(parameters)