Roggie
Roggie

Reputation: 1217

POST REST API function using Google Scripts errors with exception AD_REQUEST

I am trying to run a POST API request which when call sends an SMS as documented here but I am getting the following error message, even though the messages array is not empty:

Exception: Request failed for https://rest.clicksend.com returned code 400. Truncated server response: {"http_code":400,"response_code":"BAD_REQUEST","response_msg":"The messages array is empty.","data":null} (use muteHttpExceptions option to examine full response) sendSMSViaClickSendUsingRESTAPI @ Code.gs:401

This is my function:

function sendSMSViaClickSendUsingRESTAPI(){

  //Create messages array
  var messages = 
  [
    {
    'to': '+61423424678',
    'source': 'sdk',
    'body': 'A test message via REST API'
    },
    {
    'to': '+61423424678',
    'source': 'sdk',
    'body': 'and another one'
    }
  ];

 // Make a POST request with a JSON payload.
  var options = {
    'method' : 'post',
    'headers': {
        "Authorization": generateAuthHeaderForSendClickRESTAPI()
    },
    'contentType': 'application/json',
    'payload' : JSON.stringify(messages)
  };

//Run API call
UrlFetchApp.fetch('https://rest.clicksend.com/v3/sms/send', options);

}//end function

Upvotes: 0

Views: 219

Answers (1)

TheAddonDepot
TheAddonDepot

Reputation: 8964

Looking at the ClickSend API documentation for that SMS send endpoint it appears your messages payload is not formatted correctly.

Try this instead:

function sendSMSViaClickSendUsingRESTAPI(){
    var payload = {
        messages:[
            {
                'to': '+61423424678',
                'source': 'sdk',
                'body': 'A test message via REST API' 
            },
            {
                'to': '+61423424678',
                'source': 'sdk',
                'body': 'and another one'
            }
        ]
    };


    // Make a POST request with a JSON payload.
    var options = {
        'method' : 'post',
        'headers': {
            "Authorization": generateAuthHeaderForSendClickRESTAPI()
        },
        'contentType': 'application/json',
        'payload' : JSON.stringify(payload)
    };

    //Run API call
    UrlFetchApp.fetch('https://rest.clicksend.com/v3/sms/send', options);

}//end function

Upvotes: 1

Related Questions