Home > database >  call an API from App script and send binary data as a POST parameter
call an API from App script and send binary data as a POST parameter

Time:11-29

I'm trying to use an API, the CURL command is this one :

curl --user "<your-client-id>:<your-client-secret>" "https://api.everypixel.com/v1/faces?url=https://labs.everypixel.com/api/static/i/estest_sample3.jpg"

In my use case, I'm sending images from those type of urls : https://media-exp1.licdn.com/dms/image/C5603AQFLzBsLRsZBXQ/profile-displayphoto-shrink_800_800/0/1652669513751?e=1674086400&v=beta&t=-NC598zxFjG9fDOMJeqmLuYrP0e9NnCv92aup4MK2Wk

My problem is handling the image as the image url is not a jpg / png like the example in the CRUL command.

My script looks like this :

  var url = "https://api.everypixel.com/v1/faces";

  const response = UrlFetchApp.fetch(url, {
    "method": "POST",
    "headers": {
      "Cache-Control": "no-cache",
      "Content-Type": "application/json",
      "user": "<your-client-id>:<your-client-secret>"
    },
    "muteHttpExceptions": true,
    "followRedirects": true,
    "validateHttpsCertificates": true,
    "contentType": "application/json",
    "payload": JSON.stringify({
      "url": "https://media-exp1.licdn.com/dms/image/C4D03AQEnKuhl53UqCA/profile-displayphoto-shrink_800_800/0/1563935310527?e=2147483647&v=beta&t=8x-OjnqJCg6U7jt9Zm2rRscO22pG5C5QvgSh7H9lfSI"
    })
  });

  var data = JSON.parse(response.getContentText());

Thanks for the help

CodePudding user response:

I believe your goal is as follows.

  • You want to convert the following curl command to Google Apps Script.

      curl --user "<your-client-id>:<your-client-secret>" "https://api.everypixel.com/v1/faces?url=https://labs.everypixel.com/api/static/i/estest_sample3.jpg"
    

In this case, how about the following modification?

Modified script:

function myFunction() {
  const url = `https://api.everypixel.com/v1/faces?url=${encodeURIComponent("https://labs.everypixel.com/api/static/i/estest_sample3.jpg")}`;
  const response = UrlFetchApp.fetch(url, {
    "headers": { "Authorization": "Basic "   Utilities.base64Encode("<your-client-id>:<your-client-secret>") },
    "muteHttpExceptions": true,
  });
  const data = JSON.parse(response.getContentText());
}
  • The sample curl command is the GET method.
  • url=https://labs.everypixel.com/api/static/i/estest_sample3.jpg is the query parameter.
  • --user "<your-client-id>:<your-client-secret>" is the basic authorization.

Note:

  • I think that the request of this modified script is the same as the curl command. But, if an error occurs, please confirm the values of <your-client-id>:<your-client-secret> and the URL again.

Reference:

  • Related