Search code examples
jsongoogle-apps-scriptgraphqlgraphql-java

Google Apps Script API Request with GraphQL parse error


I'm trying to make API request with using Apps Script. API is GraphQL based. I'm using JSON.stringify function. But API returns an error.

Request:

payload={"query":"{mutation {change_column_value (board_id: 177955, item_id: 287466289, column_id:\"phone\", value: \"{phone : 15065332974, countryShortName: \"US\" }\") {name column_values{ id value}}}"}}

I'm getting error;

{"errors":[{"message":"Parse error on \" }\" (STRING) at [1, 148]","locations":[{"line":1,"column":148}]}]}

Apps Script Code:

   var us = "US"
   var column_values = '{ \
     mutation {change_column_value (board_id: 177955, item_id: '+ 287466289  +', column_id:"phone", value: "{phone : 15065332974, countryShortName: \"' + us  +'\" }") {name column_values{ id value}} \
   }';    

    settings = {
      "method": "POST",    
      "headers": {"Content-Type" : "application/json","Authorization" : "eyJhbGciOiJIXXXXXXXXXX"},  
      "payload" : JSON.stringify({query:column_values})
    }

    response= UrlFetchApp.fetch(url, settings);  

Solution

  • Brackets in a GraphQL operation indicate a selection set -- one or more fields that are being requested. The operation itself (whether a query or a mutation) is not a field, so you don't wrap the whole operation in brackets.

    Correct:

    mutation {
      doSomething
    }
    

    Incorrect:

    {
      mutation {
        doSomething
      }
    }
    

    The only time you will see brackets that look like they are on the "outside" is when using query shorthand.

    Provided that value is a String, then your use of backslashes to escape the double quotes inside that string should be fine.

    You might also consider using variables, which would clean up your code considerably and make it less error prone.