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");
}