Make a simple API call in Salesforce Marketing Cloud using AMPscript

In this tutorial, I would like to show you how to make a simple API call using the HTTPGet function. In AMPscript, there are three HTTP functions used to interact with third-party APIs (HTTPGet, HTTPPost, HTTPPostTo). The HTTPGet function retrieves content from a publicly accessible URL. In the ampscript.guide, you can see an example of the HTTPGet function that pulls the content from httpbin.org, a simple HTTP request and response service that doesn’t require any authentication. In this tutorial, we are going to connect to NASA’a open API and display the Astronomy Picture of the Day on our CloudPage.

NASA’s Astronomy Picture of the Day website

Get your NASA API key

The first thing that you will need to do, is to sign up to receive your own API key to access and use NASA’s APIs: get your NASA API key. After you sign up, you will get your api_key in the email, along with the URL used to make the request. When you click the URL with your api_key appended, you will get a response in JSON format with all the details about today’s image, including a URL to the image itself:


"date":"2019-08-14",
"explanation":"What's that next to the Moon? Saturn. In its monthly trip around the Earth - and hence Earth's sky - our Moon passed nearly in front of Sun-orbiting Saturn earlier this week.",
"hdurl":"https://apod.nasa.gov/apod/image/1908/MoonSaturn_Patonai_1280.jpg",
"media_type":"image",
"service_version":"v1",
"title":"Saturn Behind the Moon",
"url":"https://apod.nasa.gov/apod/image/1908/MoonSaturn_Patonai_960.jpg"
}

Create a CloudPage

Now let’s create a CloudPage where we will make the API call and display the APOD image. In your CloudPage, you will need to include three variables: @apikey, @url and @response. For the purpose of this tutorial, you can hardcode the @apikey into your CloudPage, but as a good practice, it’s better to store any Keys, IDs or Secrets outside of CloudPages and reference them in your AMPscript. The @url we are going to use is the same as the one you got in your email: https://api.nasa.gov/planetary/apod and we are going to append the @apikey to it. The third variable, @response, is the response in JSON format with the details of today’s image. Your code should now look like this:

%%[
var @apikey, @url, @response
set @apikey = Lookup("NASAapi","apikey","id","apod") // keep your apikey in a Data Extension
set @apikey = "7Apb3QN7qVsXPuPDcSZBKAPf8twca03C5w4Oxuyc" // or hardcode it into your CloudPage
set @url = concat('https://api.nasa.gov/planetary/apod?api_key=',@apikey)
set @response = HTTPGET(@url,false,0,@CallStatus)
]%%

The parameters used in the HTTPGet call are:

HTTPGet(1,2,3,4)

  1. String with URL used to retrieve content
  2. True/false string that controls whether the process continues on an error
  3. String that defines whether the function allows empty content
  4. String which outputs the function status (a value of 0 indicates the status is successful). You can display the status inline after you make the call by adding %%=v(@CallStatus)=%% to the script.

Source: https://ampscript.guide/httpget/

Let’s now add an inline output of the response and publish the CloudPage. Your code should now look like this:

%%[
var @apikey, @url, @response
set @apikey = Lookup("NASAapi","apikey","id","apod") // keep your apikey in a Data Extension
set @apikey = "7Apb3QN7qVsXPuPDcSZBKAPf8twca03C5w4Oxuyc" // or hardcode it into your CloudPage
set @url = concat('https://api.nasa.gov/planetary/apod?api_key=',@apikey)
set @response = HTTPGET(@url,false,0,@CallStatus)
]%%
@response: %%=v(@response)=%%

When you publish the CloudPage, you will see the response in JSON format, that contains the details about the image, along with the image URL, which we now need to extract in order to display the image in our CloudPage.

Parse JSON using Server-Side JavaScript

Unfortunately, AMPscript doesn’t have a function that we could use to parse JSON. If you know the format of the response, you could use the Substring function to extract the URL, but this would be a very clumsy solution – that’s why it’s much better to use the Server-Side JavaScript ParseJSON function. We will first have to pass the @response from AMPscript to SSJS using Variable.GetValue function, then parse it and pass the URL of the high definition image back to AMPscript using Variable.SetValue function. This is the script that you need to add to your CloudPage:

<script runat="server" language="javascript">
Platform.Load("Core","1");
//Get the @response variable from AMPscript
var response = Variable.GetValue("@response");
//Parse JSON
var json = Platform.Function.ParseJSON(response);
//Set the @hdurl variable to be accessible in AMPscript
Variable.SetValue("@hdurl",json.hdurl);
</script>
view raw parse-json.js hosted with ❤ by GitHub

Display the image in HTML

Now it’s time to add one final line of code to your CloudPage. We are passing the URL of the high definition image from SSJS to AMPscript in the @hdurl variable and now we need to display it. You can use the HTML image tag:

<img style="height:100vh" src="%%=v(@hdurl)=%%">

The complete code on your CloudPage should now look like this:

%%[
var @apikey, @url, @response
set @apikey = Lookup("NASAapi","apikey","id","apod") // keep your apikey in a Data Extension
set @apikey = "7Apb3QN7qVsXPuPDcSZBKAPf8twca03C5w4Oxuyc" // or hardcode it into your CloudPage
set @url = concat('https://api.nasa.gov/planetary/apod?api_key=&#39;,@apikey)
set @response = HTTPGET(@url,false,0,@CallStatus)
]%%
<script runat="server" language="javascript">
Platform.Load("Core","1");
//Get the @response variable from AMPscript
var response = Variable.GetValue("@response");
//Parse JSON
var json = Platform.Function.ParseJSON(response);
//Set the @hdurl variable to be accessible in AMPscript
Variable.SetValue("@hdurl",json.hdurl);
</script>
<img style="height:100vh" src="%%=v(@hdurl)=%%">

Publish your CloudPage and enjoy!

Here’s the link to my CloudPage with the Astronomy Picture of the Day: https://pub.s10.exacttarget.com/c1my0fe3fjn

3 thoughts on “Make a simple API call in Salesforce Marketing Cloud using AMPscript

  1. Chandu

    This code doesnt work for me in my Marketing cloud. When I create a cloud page and put this code and see the preview or publish the page, it keeps buffering.

    Like

    1. Richard

      For me it worked like this:

      %%[
      var @apikey, @url, @response
      set @apikey = “7Apb3QN7qVsXPuPDcSZBKAPf8twca03C5w4Oxuyc” // or hardcode it into your CloudPage
      set @url = concat(‘https://api.nasa.gov/planetary/apod?api_key=’,@apikey)
      set @response = HTTPGET(@url,false,0,@CallStatus)
      ]%%

      @response: %%=v(@response)=%%

      @CallStatus: %%=v(@CallStatus)=%%

      Platform.Load(“Core”,”1″);

      //Get the @response variable from AMPscript
      var response = Variable.GetValue(“@response”);

      //Parse JSON
      var json = Platform.Function.ParseJSON(response);

      //Set the @hdurl variable to be accessible in AMPscript
      Variable.SetValue(“@hdurl”,json.hdurl);

      Like

  2. Roger Crnkovic

    Hi Zuzanna,
    How would someone modify the Variable.SetValue to extract and display nested json values or is there more involved than that?

    Thank you

    Like

Leave a comment