Blog |
Guides

5 best practices for API consumption with SSJS

19/7/2023

5 good practices for the consumption of APIs with SSJS in Salesforce Marketing Cloud

Salesforce Marketing Cloud (SFMC) is a Marketing Automation tool used by organizations. It has several tools, both declarative (point-and-click) and programmatic (with code). Among the languages exclusive to Marketing Cloud is Server Side Javascript. This language is the best option if AMPscript does not meet the requirements for the use case to be developed, including the consumption of APIs, either from Salesforce Marketing Cloud or external APIs.

Being an ideal programming language for these cases, it is necessary to take into account the best practices when developing it. In this blog we will explore 5 best practices that you can implement in your Marketing Cloud development team.

1. Secure your credentials

Building applications within Marketing Cloud represents a challenge, since it does not have an adequate infrastructure to generate credentials. However, there are tools that allow us to overcome this limitation through "workarounds". As it is not a tool 100 percent dedicated to the applications generated in Cloud Pages, we must take certain precautions, such as the use of credentials, use the appropriate ones and store them in a secure and effective way.

For this, we recommend the following:

  1. Create a Data Extensions with your credentials for server-to-server integrations.
  2. Use the AMPscript EncryptSymmetric function to store them in the same Data Extension.
  3. To obtain the token (or keys to request a token) you can use the Lookup functions to search the same Data Extension from step 1 and DecryptSymmetric to decrypt.
%%[
SET @lookUp = LookupRows('API_Integrations','Name','JourneyAPI')
SET @rowResult = Row(@lookup,1)
SET @clientId = DecryptSymmetric(Field(@rowResult,'Client Id'),'aes', 'INT_PWD', @null, 'INT_SALT', @null, 'INT_IV', @null)
SET @clientSecret = DecryptSymmetric(Field(@rowResult,'Client Secret'),'aes', 'INT_PWD', @null, 'INT_SALT', @null, 'INT_IV', @null)
SET @tenantId = Field(@rowResult,'Tenant Id')
SET @oldToken = DecryptSymmetric(Field(@rowResult,'Token'),'aes', 'INT_PWD', @null, 'INT_SALT', @null, 'INT_IV', @null)
SET @expirationDate = Field(@rowResult,'ExpirationDate')
]%%

2. Use try... catch

Whenever we are going to query any API via SSJS, we have the advantage of try...catch blocks. This practice helps us to generate an error log (as we will see later) and do a correct error handling, like sending to an errorpage to our users. 

It is important to note that not all code should be wrapped in a try...catch, but, only what may represent a risk to our code or logic.‍‍‍‍‍
‍‍
//Código para preparar nuestro llamado
var req = new Script.Util.HttpRequest("http://www.example.com/");
req.emptyContentHandling = 0;
req.retries = 2;
req.continueOnError = true;
req.setHeader("headerTest", "test header value");
req.method = "POST";
req.postData = "testing=testValue1";
try {
//Llamado API
var resp = req.send();
} catch (e) {
SendLog(e.message)
Redirect(errorPage, true)
}

Generate an error log

Another good practice is to have a Data Extension that contains at least the following data:

  1. Id column
  2. Error date and time column
  3. Identifier column of the script that presented the error (this allows scalability in the development).
  4. Emergency column
  5. Text column that allows to save a JSON with variable information, depending on the API or script call to have the full context of the error.

This Data Extension can also be linked to a backup process through Automation Studio and e-mail alerts can be set up.

4. Use the HttpRequest object

Within SSJS we have three ways to make HTTP calls: 

  1. HTTP.Post and HTTP.Get
  2. Platform.Function.HTTPGet and Platform.Function.HTTPPost
  3. Script.Util.HttpRequest

To make API calls, it is recommended to use Script.Util.HttpRequest since it has the advantage of having a better error handling and the object construction is easier and very flexible, compared to the other two options. 

Script.Util.HttpRequest has other HTTP methods such as Delete, Put, Patch, Head and Options, besides having the continueOnError property that allows us an optimal handling of errors and new attempts for API queries, which can be configured with the retries property.

Still, HTTP.Post, HTTP.Get, Platform.Function.HTTPGet and Platform.Function.HTTPPost are good choices for simple calls or scripts that have a short lifetime and/or require time maximization when developing.

5. Use the JSON Code Resource

One of the big differences between Sales Cloud and SFMC development is the possibility of exposing web services and extending integrations. In SFMC, there is no standard way, however, there are some workarounds through SSJS and AMPscript, one of those is the use of JSON Code Resources, which can execute SSJS, and therefore, write a JSON as a response that allows communication with various systems, both as a webhook and as a custom endpoint in SFMC.

By following these 5 best practices for API consumption with SSJS at Salesforce Marketing Cloud, you will be able to optimize your developments and ensure reliable operation of your integrations. Secure your credentials, use try...catch blocks to handle errors, log and manage errors in a Data Extension, leverage the HttpRequest object to make API calls and explore the use of the JSON Code Resource to extend your integrations.

Want to know more? contact us!

Alfredo Ledesma

6x Salesforce Certified

RECENT ENTRIES

News

MTY '26: How Monterrey is Preparing for the World Cup with Marketing Strategies

The "Road to MTY 26" talk at MKT Fest explored how Monterrey is preparing to be one of the venues for the 2026 World Cup, highlighting its role in the organization of this mega-event. With the participation of representatives from Rayados, the Monterrey FWC26 organizing committee, and the Nuevo León Ministry of Tourism, the plans to welcome millions of visitors, the preparations for the BBVA Stadium and the city's tourism positioning strategy were discussed. Key details of the tournament were shared, including the expansion to 48 national teams and 104 matches, as well as opportunities to boost tourism and the local economy.
Announcements

Being Part is Beautiful: Sephora's Commitment to Inclusion at MKT Fest 2024

At MKT Fest, Sephora highlighted its commitment to inclusion and diversity as central to its marketing strategy. Through its manifesto, the brand seeks not only to promote beauty, but to do so in a way that celebrates authenticity and empowers all people to express themselves. During the talk, they discussed how Sephora has integrated these values into its campaigns and activities, ensuring that each action reinforces its mission to be an inclusive brand.
News

Unhinged Marketing: Duolingo at MKT Fest 2024

At MKT Fest, Kim de Anda, Regional Marketing Manager for Duolingo Latin America, shared how "unhinged marketing" has redefined the way the brand communicates on social media. Through authentic and unconventional strategies, such as the use of its famous Duo bot on TikTok, Duolingo has been able to connect with audiences by showing a fun and real approach. Kim explained that the key to their content is not to drive immediate downloads, but to stay in users' minds for when they decide to learn a new language.