Retrieve tracking data since account inception using WSProxy

Whether you’re building a data warehouse or are dealing with a legal compliance issue, access to historical tracking data from your Salesforce Marketing Cloud account using the out-of-the-box features is limited.

Data Views are powerful, but only allow you to query for up to six months of subscriber and tracking information.

Tracking extracts provide granular tracking data regarding several different aspects of email send jobs, such as clicks, bounces and unsubscribes. They are not time-restricted like Data Views, but if you want to get tracking data from a specific time range, the start and end dates can only be up to 30 days apart.

The third option to access historical data is to reach out to Salesforce support and ask them for a data export for a specific time range, but this service will come at a hefty price.

The method of retrieving tracking data using SOAP API and WSProxy also has some limitations, mostly related to performance when working with big data volumes, but it can be very useful in many cases where using Data Views or Tracking Extracts is not enough.

Retrieve Tracking Data with SOAP API

To retrieve tracking data using the SOAP API, we will call the SentEvent, OpenEvent, ClickEvent, BounceEvent and UnsubEvent objects, which will allow us to create a structure similar to the one we know from Data Views. Each of those objects has a persistent set of properties, which include: BatchID, ClientID, EventDate, SendID, SubscriberKey and TriggeredSendDefinitionObjectID.

Here is an example SOAP envelope that you could use in Postman to retrieve data from any of the tracking event objects:

Interact with SOAP API using WSProxy

To retrieve data from the tracking event objects using WSProxy, we will have to specify the properties to retrieve and perform the retrieve on each of the objects we are interested in. Here’s an example of retrieving data from the SentEvent object:

We can also add a filter to narrow down the results. You can filter the results by JobID, SubscriberKey or any other object property. Here, we are going to filter by EventDate, which will show us all the events that took place in the given timeframe:

If you run the above script in an account that sends large volumes of emails, you will notice that it only pulls a part of the results and displays a status message: MoreDataAvailable. That’s because the SOAP API returns up to 2500 records at a time per retrieve call. To retrieve all available data for a given timeframe, we need to include pagination of retrieves in our script. Let’s also add an HTML table, so that data is displayed in a more accessible way:

You can do the same with the remaining objects, here are the scripts:

Write retrieved data into a Data Extension

Although this will increase the processing time of the call, it will allow you to have the data ready for further processing without any additional preparations. Below script will create a new Data Extension called 01_SentEvent in your main Data Extensions folder and insert all the retrieved data.

Here are the scripts that will do the same for the remaining objects:

Performance of the retrieve calls

The official Marketing Cloud SOAP API documentation states the following:

In most production implementations, data volume in the account requires you to include specific JobIDs in the filter criteria of the request. If requests that don’t specify a JobID time out during processing, add a JobID in the filter. If specifying a JobID is not possible, or if your implementation requires a broad range of JobIDs, use a data extract-based procedure instead.

Above is true if you are sending heavy volumes of emails each month, but you are not limited to filtering by JobID. You can include any of the object properties in filter criteria. You can, for example, retrieve all send and tracking history for a specific subscriber if you use the SubscriberKey in the filter: filter = {Property: "SubscriberKey", SimpleOperator: "equals", Value: "{{SubscriberKey}}"}

If you’re experiencing time outs when working with the script, try narrowing down the amount of retrieved data by using filters.

Security

Last but not least, always remember to put security measures into practice when setting up this kind of functionality on a CloudPage to prevent your data from being exposed in a breach. For the script to run and either return results onscreen or insert them into a Data Extension, you don’t have to actually publish the CloudPage – just press “Publish”, without further saving it. Or, to be completely safe – create a Script Activity in Automation Studio and run it from there.

Retrieve client IP address and geolocation in CloudPages

There are many reasons for checking the client IP address, most common include tracking and personalization. What can you find out about the visitors of a webpage from their IP address? You can identify their ISP, figure out approximately where they’re located and see how often they (or someone else sharing their router) visit your website.

In the context of CloudPages, we most often see IP tracking for personalization purposes. By identifying the visitor’s location, you can automatically display text in their local language and control what kind of content they see.

Identify client IP using AMPscript

The X-Forwarded-For (XFF) HTTP header is a standard header for identifying the originating IP address of a client connecting to a web server. You can easily access this header by using the AMPscript HTTPRequestHeader function, which will return a specified header from an HTTP request. Here’s how to retrieve an IP address on a CloudPage using AMPscript:

Identify client IP using SSJS

There are dedicated Server-Side JavaScript HTTP Properties Functions, that allow you to retrieve various types of HTTP Request object properties and platform application values. The client browser passes this information to the server during an HTTP interaction, so this object contains information regarding the browser and session. One of the available properties to use with the HTTP Request object is ClientIP, which returns the IP address of the requesting client as a string value. Here’s how to retrieve an IP address on a CloudPage using SSJS:

This is the preferred way to retrieve the client IP, as Request.ClientIP() is a dedicated and supported function, while using the XFF HTTP header proved to be unreliable in the past.

HTTP Properties Functions allow you to retrieve other useful information, for example, browser metadata or the URL of the referring web address.

Discover the precise physical location of a given IP address

The functionality of identifying a physical location of a given IP address requires using a third party API service. There are many IP Geolocation API providers and most of them have a free plan available, as well as paid plans for bigger enterprises. My preferred one is ipify.org, which allows you to run up to 1000 queries per month for free. Once you register, you will obtain your personal apiKey, that will be used for making the calls:

The response will contain information about the country, region, city, latitude, longitude, postal code, timezone and GeoNames Id. Additionally, it will also show autonomous system (AS) info if available.

Click here to see this script in action.

As a side-note, remember that under GDPR, IP addresses are considered personal data. Tracking the IPs of your EEA based users without their consent falls under the rules of GDPR.

Send a triggered email using WSProxy

Triggered sends allow you to automatically send personalized and timely messages to your subscribers. They are sent to an individual subscriber in response to a subscriber action. If you would like to find out more about creating a Triggered Email Message Interaction, check out my other article here.

TriggeredSend object

The TriggeredSend object represents a specific instance of a triggered email send. A typical SOAP envelope consists of the Triggered Send CustomerKey (External Key of the Triggered Email Message Interaction), Subscribers associated with the send and optionally, their Attributes. Here’s an example:

Create a TriggeredSend using WSProxy

WSProxy is a new object for Server-Side JavaScript, introduced by Salesforce in 2018. It acts as a proxy between the Marketing Cloud SOAP Web Service and SSJS. The WSProxy object is native to the platform and simpler to use than the SSJS methods, that’s why it reduces overhead and increases the speed of API calls. WSProxy uses JSON to pass object properties instead of SOAP’s native XML, which makes it much easier to read and write.

To create a new TriggeredSend, we will use the createItem WSProxy function, which has three parameters:

  • The first parameter is the object type to perform the action on – here, we will use previously mentioned TriggeredSend object
  • The second parameter is a JavaScript object which represents the fields and values to set on the object when created – in below example, we will call it tsDef and use it to define the CustomerKey, Subscribers and optionally, their Attributes
  • The third parameter is optional and includes any properties to be set using the SOAP CreateOptions object

Here’s the full script:

In the above script, you will need to provide the Triggered Send External Key and pass an Email Address and Subscriber Key.

If you are using personalization strings in your Triggered Email, you can pass them as name and value pairs in the Attributes object. Here’s an example of passing additional attributes in the WSProxy call:

The results of the call contain three properties from the SOAP CreateResult object: Status, RequestID, and Results. Here’s an example response:

To see how this script works in action, visit the CloudPage that I created and submit your email address here.

Here are additional resources to learn more about Triggered Sends and WSProxy:

Find a Data Extension and it’s folder path using SSJS

If you work with a lot of Data Extensions in multiple folders, you know the pain of using the built-in search feature. It only searches the folder that you’re in, with the exclusion of any sub-folders, which is simply impractical.

Below, I would like to show you how to find a Data Extension and it’s path using Server-Side JavaScript: which functions to use and how to iterate through them.

If you’re not interested in the technical part and want to jump straight into building the search app, click here.

SSJS Data Extension and Folder Functions

In order to find a Data Extension, we will use two SSJS Core functions: DataExtension.Retrieve and Folder.Retrieve. The first function will help us identify the Data Extension, either by its name or the External Key. The second function retrieves an array of folders based on the specified criteria. It also retrieves details regarding the parent folder of a given folder if one exists, and that’s what we will use to build the Data Extension path.

In the above script, you will need to define two variables, DEprop and DEval, depending on whether you have the name or the External Key of the Data Extension. You can paste the script on a CloudPage, define the two variables, and once you click on the “Publish” button, the script will be executed and results will be visible on-screen, without the need to actually publish the CloudPage:

Create a simple Data Extension search app

If users of your instance of Salesforce Marketing Cloud often struggle with finding Data Extensions, you can create an app on a CloudPage to help them navigate the folders. By adding a simple form, you can enable the users to perform a search from a CloudPage:

Paste the below code onto a CloudPage and publish it. Anyone with access to the link will be able to search for Data Extensions located in the Business Unit where the CloudPage was created. If the CloudPage has been created in the Parent Business Unit, they will also be able to search the Shared Data Extensions folder.

Last but not least, always remember to put security measures into practice when setting up this kind of functionality on a CloudPage, to prevent your data from being exposed in a breach.

PS. There is a free tool available called SFMC Object Finder. It’s a Chrome extension that lets you search for a variety of objects, like images, data extensions and other assets, in your instance of Salesforce Marketing Cloud. All it requires is that you have an active session of Salesforce Marketing Cloud open in your Chrome browser. However, if you cannot install this extension or need to be able to find Data Extensions programmatically, you can use Server-Side JavaScript to achieve it!

Unsubscribe and Log an UnsubEvent with a LogUnsubEvent Execute Call

The LogUnsubEvent provides a convenient way of handling unsubscribes when you create your own unsubscribe landing page or profile center functionality. This call allows you to unsubscribe a subscriber and log an UnsubEvent that is tracked against a specific Job, which means that you will be able to track from which email they unsubscribed and see the results on the tracking dashboard. You can configure the call to either unsubscribe a subscriber from a specific list, publication list, or all subscribers, which will effectively unsubscribe them from receiving any emails.

What’s more important, if you’re using Marketing Cloud Connect to connect with your Salesforce Sales or Service Cloud org, the unsubscribe will be captured on the subscriber record in Sales/Service Cloud. It will automatically check the Email Opt Out (HasOptedOutOfEmail) flag and will also be visible in the Individual Email Results for the corresponding email send.

The LogUnsubEvent Execute call uses the following parameters:

  • SubscriberID – The Marketing Cloud generated ID that uniquely identifies a subscriber.
  • SubscriberKey – The client supplied ID that uniquely identifies a subscriber.
  • EmailAddress – The email address of the subscriber.
  • JobID – The ID of the Job that sent the message.
  • ListID – The ID of the List that the subscriber belonged to. You can use subscriber or publication lists (not suppression lists).
  • BatchID – The ID of the Batch within the Job.
  • Reason – (Optional) The reason the subscriber is being unsubscribed.

The parameters can be divided into 3 sections:

  1. Subscriber context
  2. Job context
  3. Unsub reason

If you make this call from the parent unit of an Enterprise 2.0 account, ensure that you include the ClientID of the child business account to return information specific to that business unit.

Subscriber Context

The Subscriber Context is defined by the SubscriberID, SubscriberKey and EmailAddress parameters. You must supply at least one of these parameters. If you provide more than one of these parameters, we retrieve the Subscriber using one of the values and validate that the other values match the retrieved Subscriber. If they don’t match, an error returns.

If the SubscriberKey permission is turned on and you supply the EmailAddress parameter, you must supply either the SubscriberID or the SubscriberKey.

Job Context

The Job Context is defined by the JobID, ListID and BatchID parameters. These values are used to determine which Job the UnsubEvent is tracked against. The subscriber is also unsubscribed from the List that the Job was sent to. You don’t need to supply all three values. The system looks up any missing values using the following rules:

  1. If the JobID is supplied, we can lookup a missing ListID and/or BatchID.
  2. If the ListID is supplied, we can lookup a missing JobID and/or BatchID.
    1. If the JobID is missing, we use the most recent JobID that the subscriber was sent to.
    2. This may not be the Job that the Subscriber is acting upon.
  3. If only the BatchID is supplied, we cannot lookup the remaining information and the job context is not defined.

If the job context cannot be established because you did not supply any of these parameters or only supplied the BatchID, the UnsubEvent is not created. The subscriber is also Master Unsubscribed from the system of being unsubscribed from a particular list. Remove the ListID to address the All Subscribers list in an account.

Unsub Reason

This is used to specify the reason the subscriber is being unsubscribed from the system. If the reason is not supplied, the default value is used: Unsubscribed via Log Unsub Event Execute call.

Here is an example SOAP Request envelope:

We will now look at three different ways to implement this solution on a CloudPage.

LogUnsubEvent using AMPscript

This is probably the most common way to use the LogUnsubEvent call. Below script will retrieve the SubscriberKey, JobId, ListId and BatchId if you link to the unsubscribe page from your email using the CloudPagesURL function. Depending on whether a list/publication list was selected for the send, it will unsubscribe a subscriber from that particular list, or it will unsubscribe the subscriber from all emails if you used All Subscribers.

LogUnsubEvent using Server-Side JavaScript

The implementation of the LogUnsubEvent call in SSJS will be almost identical to the AMPscript solution, as the methods for accessing SOAP object data with SSJS are primarily wrappers around AMPScript functions.

Like in the previous example, the script will retrieve the SubscriberKey, JobId, ListId and BatchId if you link to the unsubscribe page from your email using the CloudPagesURL function and will unsubscribe a subscriber either from a list or All Subscribers, depending on which one you use at send time.

LogUnsubEvent using WSProxy

WSProxy is a new object for Server-Side JavaScript, introduced by Salesforce in 2018. It acts as a proxy between the Marketing Cloud SOAP Web Service and SSJS. The WSProxy object is native to the platform and simpler to use than the SSJS methods. The object reduces overhead and increases the speed of your API calls.

Therefore, the below script is the most simple, and what’s more important, the fastest way to execute the LogUnsubEvent API call. In a speed test ran using the Chrome DevTools, it proved to be the fastest one to load on a CloudPage, with AMPscript just slightly slower and SSJS the slowest one, taking twice as much time to load.

Just like in the previous examples, the script will retrieve the SubscriberKey, JobId, ListId and BatchId if you link to the unsubscribe page from your email using the CloudPagesURL function and will unsubscribe a subscriber either from a list or All Subscribers, depending on which one you use at send time.

If you would like to find out more about logging an UnsubEvent or WSProxy, check out the following articles:

Salesforce Marketing Cloud API Authentication using Server-Side JavaScript

In order to interact with Salesforce Marketing Cloud APIs you need to create an installed package in your Marketing Cloud account first. Marketing Cloud uses installed packages to help authenticate users and API requests. To create and install packages you must have the Administrator or Marketing Cloud Administrator role assigned to your profile.

Marketing Cloud has two types of installed packages: packages with enhanced functionality (v2) and packages with legacy functionality (v1). If you’re not sure which package has been installed in your account, check the “Details” tab of your installed package – all legacy packages have a banner at the top indicating that it’s a legacy package and a Licenses tab. Enhanced packages have an Access tab.

Note the Authentication Base URI , Client Id and Client Secret as you will need them to authenticate. Below code examples are meant for Server-to-Server Integrations with Client Credentials Grant Type.

Request access token for a Legacy Package

The following script will allow you to authenticate if you’re using the Legacy Package. As of August 1, 2019, Marketing Cloud has removed the ability to create legacy packages, but you can still use legacy authentication and API requests with existing legacy packages.

You will need to insert the Client Id and Client Secret and your tenant-specific authentication endpoint (Authentication Base URI). Bare in mind, that it is not a good idea to publish Client credentials on a CloudPage.

The access token will be valid for 60 minutes and it is issued with the scopes specified on the API integration in Installed Packages. With Legacy Packages, the access token can only be used in the context of the business unit that created the integration.

Request access token for Enhanced Packages

For this package, you will need to insert the Client Id and Client Secret, your tenant-specific authentication endpoint (Authentication Base URI) and define grant_type as "client_credentials" for server-to-server integrations. You can also specify two optional parameters, scope and account_id. If you don’t include the scope parameter in the request, the token is issued with the scopes specified on the API integration in Installed Packages. For a full list of permissions click here. Account ID is the MID of the target business unit. Use this parameter to switch between business units. If you don’t specify account_id, the returned access token is in the context of the business unit that created the integration. Again, bare in mind, that it is not a good idea to publish Client credentials on a CloudPage.

The access token has a lifetime of 20 minutes. In the response you will also see the scope, rest_instance_url (your tenant’s REST base URL for making REST API calls) and soap_instance_url (your tenant’s SOAP base URL for making SOAP API calls).

Token type will always be “Bearer”, regardless of the package you are using.

To learn more about Marketing Cloud APIs, visit the Trailhead module Marketing Cloud APIs and the official documentation: Intro to Marketing Cloud APIs.

Create a Sales Cloud-integrated lead capture form using AMPscript

SmartCapture forms provide a quick, user-friendly way to create simple forms and use them in Salesforce Marketing Cloud journeys, but they are not very versatile and often can create more problems than they actually solve.

In this tutorial, you will learn how to create a form using HTML and AMPscript and include functions that will let you quickly push the collected data into your instance of Sales/Service Cloud.

Create an HTML form

First, let’s create a very simple HTML form. If you’ve never created forms in HTML, you can start with reading this short overview on w3schools. The form action method attribute specifies how to send form-data. In this case, we are using post, which appends form-data inside the body of the HTTP request (data is not shown is in URL).

The RequestParameter('PAGEURL') function reloads the page when the form is submitted, posting the form parameters back to the same page, which are then retrieved by the RequestParameter() AMPscript functions. The form has a hidden submitted field. If this value is present, which it would be after submitting the form, it will trigger the evaluation of the AMPscript functions. Let’s add them to the form now.

Create form logic using AMPscript

Let’s start simple with creating a Sales Cloud Lead using the data collected in the form. The AMPscript needs to be placed at the top, as it should be evaluated upon form submission and prevent the form fields from being displayed after it’s been submitted. In the below script, we use the CreateSalesforceObject function to create a new Lead:

We can extend the logic a bit by checking first if the Lead with the given email address already exists in Sales Cloud, and if yes – updating their data, or if not – creating a new Lead:

Let’s now add the Lead to a Campaign in Sales Cloud. You will need to hardcode the Campaign Id into the script. Note that you cannot add the same Lead to a campaign twice, so if the Lead has already been added to the campaign, you will get an error. Let’s add creating a new Campaign Member to the script:

And now, let’s put the icing on the cake and send a confirmation email to the Lead. You will need to create a Triggered Send beforehand – if you’re not sure how, read my blog post: Send a triggered email using AMPscript. We will hardcode the Triggered Send external key as @ts_extkey, pass the Lead ID and Email Address to a new Subscriber object and invoke creation of a new Triggered Send object:

You now have a fully functional lead capture form integrated with Sales Cloud!

If you’d like to see this in action, fill in this example form that I created to receive a confirmation email:
https://pub.s10.exacttarget.com/bhu3kciqhjk.

Send a triggered email using AMPscript

Triggered sends allow you to automatically send personalized and timely messages to your subscribers. They are sent to an individual subscriber in response to a subscriber action. Common use cases include sending welcome emails to new subscribers, service case notifications or post-purchase thank you notes to clients. They can be personalized just as any other email sent from Salesforce Marketing Cloud and triggered in various ways, among others, using AMPscript. You can read more about Triggered Sends in Salesforce Marketing Cloud here: Triggered Emails.

Create a Triggered Email Message Interaction

In order to create a Triggered Email Message Interaction, we need all the elements that we would use for a user-initiated email: an email, a sender profile and a list for managing subscriber statuses. Once you have all of the above ready, you can create a Triggered Send:

  • Go to Email Studio > Interactions > Triggered Sends
  • Click on Create
  • Provide a name, select your sender profile, email and list used for subscriber management
  • Save your Triggered Send
  • Check the checkbox on the list of your Triggered Sends and click on “Start/Restart”

Now copy the “External Key” of the Triggered Send you just created, you will need to insert it into the script in the next step.

Trigger the email using AMPscript

In order to trigger the email, we will use the InvokeCreate function, which invokes the Create method on an API object. The following script uses the CreateObject function to create the TriggeredSend and TriggeredSendDefinition objects as @ts and @tsDef, and to create a new Subscriber record as @ts_sub. We will specify the attributes of the Triggered Send object and the Subscriber object using the SetObjectProperty function. The AddObjectArrayItem function is used to add the object attributes, and everything is then passed into the InvokeCreate function. The InvokeCreate function returns a status code and a status message, by which exception handling can be built using the RaiseError function.

In the above script, replace ExternalKey with the External Key of the Triggered Send you created earlier and replace email@example.com with your email address. You are now ready to run this script on a CloudPage by publishing it. Upon success, you should be able to see the following values:

Triggered Send status code: OK
Triggered Send status message: Created TriggeredSend
Triggered Send error code: 0

The above script is simplified, as it uses the email address of a subscriber as the subscriber key. If you would like to pass the subscriber key separately, you will need to add one more variable @ts_subkey and change the SetObjectProperty for the Subscriber record:

To see how this script works in action, visit the CloudPage that I created and submit your email address here.

The delivery speed for Triggered Send emails is usually quicker than for user-initiated emails, so if the email doesn’t make it into your inbox in a couple of minutes, check your spam folder.

Here are additional resources to learn more about Triggered Sends:

Create a SmartCapture form prefilled (prepopulated) with Salesforce data

Smart Capture allows you to easily create forms on your Cloud Pages to collect information about your subscribers and then use that data for future sends and campaigns. While creating a Smart Capture form doesn’t require any coding skills and can be done using only the drag-and-drop editor, adding a simple script to your form can significantly increase the user experience. Forms prepopulated with data can be used for any type of campaign, as long as you already have some data about your subscriber in your database. Subscribers are more likely to register for an event or a raffle when they don’t need to manually fill in all the form fields, and the only thing they have to do is to submit the form.

Create a SmartCapture form

The first thing you will have to do is to create a Smart Capture form on your Cloud Page. Depending on your requirements, you can either create your own Data Extension to collect data submitted by your subscribers or use the system Data Extension called CloudPages_DataExtension.

For the purpose of this tutorial, let’s use the system data extension and create a very simple form with three fields: First Name, Last Name and Email Address.

SmartCapture form on a CloudPage

Add AMPscript to retrieve Salesforce data

In this example, we will be retrieving Sales Cloud data to prepopulate the form using the RetrieveSalesforceObjects function. We will be looking up Contacts in Sales Cloud based on the Subscriber Key. Add the following code in a separate content area, above your Smart Capture form:

If you’re using Campaigns in Sales Cloud, which can admit both Contacts and Leads, you can extend your code with a Substring function, so that it’s able to correctly process both:

You can also use data stored in Marketing Cloud to prefill the form – just remember, that you will need to use the LookupRows function instead of RetrieveSalesforceObjects.

Prepopulate the data in the form

In order to add the data retrieved from Salesforce to your form, you will have to modify each of the form input fields separately. Click once on the Smart Capture form, and then once again on the field you wish to modify.

Now edit the field in the HTML view and add an inline display of the adequate field retrieved from Sales Cloud as the default value at the end of the HTML input tag:

Do this for all the fields that should be prepopulated with data. Publish your CloudPage and test it – the fastest way to test the form is to create an email with a button leading to your CloudPage and previewing the email against a subscriber, who is present in your Salesforce database.

You can also connect this form to a journey in Journey Builder to send a confirmation email to anyone who filled it in, update their Salesforce data or add them to a consecutive campaign.

Read more here about Using a Smart Capture Form as a Journey Builder Entry Event.

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:

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:

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:

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:

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

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