2

Simple code and straightforward. It works with postman but fails with Apps Script.

function validateAddress () {

  const url = 'https://addressvalidation.googleapis.com/v1:validateAddress?key=';
  const apikey = '...';

  let payload, options, temp;

  payload = JSON.stringify({
    "address": {
      "addressLines": "1600 Amphitheatre Pkwy"
    }
  });

  options = {
    'muteHttpExceptions': true,
    'method': 'POST',
    'Content-Type': 'application/json',
    'body': payload
  }

  temp = UrlFetchApp.fetch(url + apikey, options);
  Logger.log(temp)

}

Error:

{
  "error": {
    "code": 400,
    "message": "Address is missing from request.",
    "status": "INVALID_ARGUMENT"
  }
}

EDIT:

Change options to

  options = {
    'muteHttpExceptions': true,
    'method': 'POST',
    'Content-Type': 'application/json',
    'payload': payload
  }

Gives error:

{
  "error": {
    "code": 400,
    "message": "Invalid JSON payload received. Unknown name \"{\"address\":{\"addressLines\":\"1600 Amphitheatre Pkwy\"}}\": Cannot bind query parameter. Field '{\"address\":{\"addressLines\":\"1600 Amphitheatre Pkwy\"}}' could not be found in request message.",
    "status": "INVALID_ARGUMENT",
    "details": [
      {
        "@type": "type.googleapis.com/google.rpc.BadRequest",
        "fieldViolations": [
          {
            "description": "Invalid JSON payload received. Unknown name \"{\"address\":{\"addressLines\":\"1600 Amphitheatre Pkwy\"}}\": Cannot bind query parameter. Field '{\"address\":{\"addressLines\":\"1600 Amphitheatre Pkwy\"}}' could not be found in request message."
          }
        ]
      }
    ]
  }
}

Documentation: https://developers.google.com/maps/documentation/address-validation/requests-validate-address

MrUpsidown
  • 21,592
  • 15
  • 77
  • 131
sangnandar
  • 47
  • 1
  • 6

2 Answers2

3

From the documentation, it seems that addressLines is an array of string, not a string. Does that change something ? (I don't have a key, so I cannot try myself).

And more important, your options object is incorrect (check doc). It should be

options = {
    'muteHttpExceptions': true,
    'method': 'POST',
    'contentType': 'application/json',
    'payload': payload
  }
ValLeNain
  • 2,232
  • 1
  • 18
  • 37
1

I don't know why it works but changed options to

  options = {
    'muteHttpExceptions': true,
    'method': 'POST',
    'headers': {
      'Content-Type': 'application/json'
      },
    'payload': payload
  }

Solves the problem.

sangnandar
  • 47
  • 1
  • 6
  • in the headers you can write `Content-Type`, in the object `options`(first level of properties) you can have `contentType`. But you can't put one for the other. – ValLeNain Nov 14 '22 at 13:34