I'm trying to retrieve emails and their associated templates using the Content Builder API. In Postman, I can find the template name field, but I can't access it using SSJS. Does anyone know how this can be done?
This is the code I'm using:
<script runat="server">
Platform.Load("core", "1");
var accessToken; // Define accessToken variable outside try block
var restInstanceUrl = "https://{{et_subdomain}}.rest.marketingcloudapis.com/"; // Define restInstanceUrl
try {
// Config
var authUrl = "https://{{et_subdomain}}.auth.marketingcloudapis.com";
var clientId = "";
var clientSecret = "";
var result = HTTP.Post(authUrl + "/v2/token", 'application/json', Stringify({
"grant_type": "client_credentials",
"client_id": clientId,
"client_secret": clientSecret,
"account_id":""
}));
if (result.StatusCode == 200) {
var responseJson = Platform.Function.ParseJSON(result.Response[0]);
accessToken = responseJson.access_token; // Assign value to accessToken
} else {
throw "Failed to obtain access token. StatusCode: " + result.StatusCode;
}
} catch (error) {
Write('Authentication error: ' + error);
}
try {
var payload = {
page: {
page: 1,
pageSize: 50
},
query: {
property: "assetType.id",
simpleOperator: "IN",
value: ["207"]
},
sort: [
{
property: "id",
direction: "ASC"
}
]
}
var endpoint = restInstanceUrl + "asset/v1/content/assets/query";
var request = new Script.Util.HttpRequest(endpoint);
request.emptyContentHandling = 0;
request.retries = 2;
request.continueOnError = true;
request.setHeader("Authorization", "Bearer " + accessToken);
request.method = "POST";
request.contentType = "application/json";
request.postData = Stringify(payload);
var results = request.send();
var result = Platform.Function.ParseJSON(String(results.content));
var items = [];
for (var i = 0; i < result.items.length; i++) {
var asset = result.items[i];
items.push({
name: asset.name,
templateName: asset.content.template.name
});
}
Write(Stringify(items));
} catch(error) {
Write(Stringify(error));
}
</script>