0

I'm now testing a new method to create a data extension field automatically through REST API calling,referring to this developer DOC It's operated by POST method, and I think I wrote all of the elements(token access body, payload and endpoint etc) properly but still the code doesn't work. Would there be problem with 'Script.Util.HttpRequest' function? The request worked properly as I tried on the postman, so I think there's nothing wrong with the payload or request body itself. Here's the code, and it would be greatly helpful it you guys can give me some feedback on this. I filled out the variable properly when I tried out on my own account.

<script runat="server">
Platform.Load("Core", "1.1.1");

try {
    // TOKEN ACCESS
    var authEndpoint = 'HERE'S THE authEndpoint  ';
    var url = authEndpoint + '/v2/token';
    var payload = {
        "grant_type": "client_credentials",
        "client_id": {{client_id}},
        "client_secret": {{client_secret}},
        "account_id": {{account_id}}
    };
    var contentType = 'application/json';
    var accessTokenRequest = HTTP.Post(url, contentType, Stringify(payload));
    var accessToken;

    if (accessTokenRequest.StatusCode == 200) {
        var tokenResponse = Platform.Function.ParseJSON(accessTokenRequest.Response);
        accessToken = tokenResponse.access_token;
        var rows = Platform.Function.InsertData("API_createfields",["TOKEN"],[accessToken]);
    } else {
        Write("Failed to obtain access token. Status code: " + accessTokenRequest.StatusCode);
        throw new Error("Failed to obtain access token.");
    }

    // Define fields payload
    var payload2 = {
        "fields": [
            {
                "description": "Unique Contact Identifier",
                "isActive": true,
                "isHidden": false,
                "isInheritable": false,
                "isNullable": false,
                "isOverridable": false,
                "isPrimaryKey": false,
                "isReadOnly": false,
                "ordinal": 5,
                "isTemplateField": false,
                "length": 50,
                "maskType": "None",
                "mustOverride": false,
                "name": "ContactKey",
                "storageType": "Plain",
                "type": "Text"
            }
        ]
    };

    // API calling
    var deurl = 'https://{{restendpoint}}.rest.marketingcloudapis.com/data/v1/customobjectsasync/b979adcc-094f-ef11-b860-48df37d082c9/fields';
    var req = new Script.Util.HttpRequest(deurl);
    req.emptyContentHandling = 0;
    req.retries = 2;
    req.continueOnError = true;
    req.contentType = "application/json";
    req.setHeader("Authorization", "Bearer " + accessToken);
    req.method = "POST";
    req.postData = Stringify(payload2);
    var response = req.send();

    if (response.StatusCode < 200 || response.StatusCode >= 300) {
        Write("Error");
    } else {
        Write("Successful");
    }

} catch (e) {
    Write("error");
}

1 Answer 1

0

There are a couple mistakes here:

The response from your authenticate call should be a string so it can be parsed

var tokenResponse = Platform.Function.ParseJSON(String(accessTokenRequest.Response));

The status code for the 2nd call should be statusCode not StatusCode since you are using Script.Util.HttpRequest.

Also the status code = 202 means you successfully issued the HTTP request, it doesn't mean the request applied successfully on the DE.

You put the field attribute with "isNullable": false it may have the conflict if the DE already has some records there.

Here is my version:

<script runat="server">
Platform.Load("Core", "1.1.1");
// TOKEN ACCESS

var url = 'https://SubDomain.auth.marketingcloudapis.com/v2/token';
var payload = {
    "grant_type": "client_credentials",
    "client_id": 'Client ID',
    "client_secret": 'Client Secret'
};
var contentType = 'application/json';
var accessToken;

var accessTokenRequest = HTTP.Post(url, contentType, Stringify(payload));

if (accessTokenRequest.StatusCode == 200) {
    var tokenResponse = Platform.Function.ParseJSON(String(accessTokenRequest.Response));
    accessToken = tokenResponse.access_token;
} else {
    Write("Failed to obtain access token. Status code: " + accessTokenRequest.StatusCode);
}


// Define fields payload
var payload2 = {
    "fields": [
        {
            "description": "Unique Contact Identifier",
            "isActive": true,
            "isHidden": false,
            "isInheritable": false,
            "isNullable": true,
            "isOverridable": false,
            "isPrimaryKey": false,
            "isReadOnly": false,
            "ordinal": 5,
            "isTemplateField": false,
            "length": 50,
            "maskType": "None",
            "mustOverride": false,
            "name": "ContactKey",
            "storageType": "Plain",
            "type": "Text"
        }
    ]
};

// API calling
var deurl = 'https://SubDomain.rest.marketingcloudapis.com/data/v1/customobjectsasync/Data Extension ID/fields';
var req = new Script.Util.HttpRequest(deurl);
req.emptyContentHandling = 0;
req.retries = 2;
req.continueOnError = true;
req.contentType = "application/json";
req.setHeader("Authorization", "Bearer " + accessToken);
req.method = "POST";
req.postData = Stringify(payload2);
var response = req.send();

if (response.statusCode == 202){
    Write("Call API Successful");
} else {
    Write("Error");
}
</script>
2
  • IT WORKED!! Thanks a lot :) Authenticate call part was a problem I guess. Commented Aug 1, 2024 at 2:26
  • @SuejinMin If you find it useful, can you mark it as an accepted answer then? Thanks. Commented Aug 1, 2024 at 2:30

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.