Search code examples
google-apps-scripturlfetch

Need to convert this curl to Google apps script Urlfetch


I’m trying to convert this curl to Google apps script but I’m getting 400 bad request

Here’s the curl command

curl --include \
     --header "Authorization: Basic YXBpLXVzZXJuYW1lOmFwaS1wYXNzd29yZA=="  \
     --request POST \
     --header "Content-Type: application/json" \

     --data-binary "    {
        \"messages\":[
            {
                \"source\":\"php\",
                \"body\":\"Jelly liquorice marshmallow candy carrot cake 4Eyffjs1vL.\",
                \"to\":\"+61411111111\"
            },
            {
                \"source\":\"php\",
                \"body\":\"Chocolate bar icing icing oat cake carrot cake jelly cotton MWEvciEPIr.\",
                \"to\":\"+61422222222\"
            }
        ]
    }" \
'https://rest.clicksend.com/v3/sms/send'

Solution

  • I believe your goal as follows.

    • You want to convert the curl command in your question to Google Apps Script.

    Sample script:

    function myFunction() {
      const url = "https://rest.clicksend.com/v3/sms/send";
      const params = {
        method: "post",
        headers: { Authorization: "Basic YXBpLXVzZXJuYW1lOmFwaS1wYXNzd29yZA==" },
        contentType: "application/json",
        payload: JSON.stringify({
          "messages": [
            {
              "body": "Jelly liquorice marshmallow candy carrot cake 4Eyffjs1vL.",
              "source": "php",
              "to": "+61411111111"
            },
            {
              "body": "Chocolate bar icing icing oat cake carrot cake jelly cotton MWEvciEPIr.",
              "source": "php",
              "to": "+61422222222"
            }
          ]
        })
      };
      const res = UrlFetchApp.fetch(url, params);
      console.log(res.getContentText());
    }
    

    Note:

    • In this sample script, it supposes that your curl command works fine. Please be careful this.
    • If you want to see the response header, you can also use getAllHeaders(). Ref

    Reference: