Sending a body in a GET request with UrlFetchApp?

35 Views Asked by At

Is there a way to make this request with UrlFetchApp in app script?

curl -X GET http://test.com/api/demo -H 'Content-Type: application/json' -d '{"data": ["words"]}'

I attempted it with this code:

const API_URL = "http://test.com/api/demo";
const payload = { data: ["words"] };
const response = UrlFetchApp.fetch(API_URL, {
    method: "GET",
    headers: { "Content-Type": "application/json" },
    payload: JSON.stringify(payload)
});

The payload and the endpoint are the exact same as the curl request which I tested

However I got this error "Failed to deserialize the JSON body into the target type: missing field `name` at line 1 column 88".

1

There are 1 best solutions below

0
Umar Farooq On

In a typical HTTP GET request, the request parameters are sent as part of the URL query string, and there is no request body. However, if you need to send a body with a GET request, you can technically include it, but it's not recommended as it goes against the HTTP specification.

Here's how you could technically include a body in a GET request using UrlFetchApp in Google Apps Script:

function sendGetRequestWithBody() {
  var url = 'https://example.com/api/resource';
  var payload = {
    key1: 'value1',
    key2: 'value2'
  };

  var options = {
    method: 'GET',
    payload: JSON.stringify(payload),
    contentType: 'application/json'
  };

  var response = UrlFetchApp.fetch(url, options);
  Logger.log(response.getContentText());
}

However, note that while this might work in some cases, it's not standard practice and may not be supported or behave as expected by all servers. It's generally better to use POST requests for sending data in the request body, as that aligns with HTTP standards and server expectations.