简体   繁体   中英

Google Apps Script GraphQL API Call

I've been working with the Canvas REST API and ran into some limitations and was directed to their experimental GraphQL API. Given its experimental nature, they have little to no documentation on it. Despite its advantages for what I'm building, I can't find a whole lot on the inte.net either. As of right now, I can't even get a basic query to work.

function testsendgraphql() {
  const url = "https://hsccsd.beta.instructure.com:443/api/graphql";
  const payload = `
  query {
    course(id: 1234) {
      {
        name
      }
    }
  }`;

  const options = {
  "method": "POST",
  "headers": { "Content-Type": "application/json", "Authorization": "Bearer "+getcanvasaccesstoken() },
  "body": payload
  };
  Logger.log(query);
  apiresponse = UrlFetchApp.fetch(url,options);
  var head = apiresponse.getAllHeaders();
  var data = JSON.parse(apiresponse.getContentText());
  Logger.log(data);
  Logger.log(head);
}

Running the above gets a response code of 200 but gives the following message:

{errors=[{message=No query string was present}]}

Something with my formatting of the payload seems to be off. Any help would be greatly appreciated.

I recently had success with the following GraphQL query using Google Apps Script:

function test(query) {
  var url = "https://gql.waveapps.com/graphql/public";
  var options = {"headers": {"Authorization": "Bearer " + getAccessToken(),
                             "Content-Type": "application/json"
                            },
                 "payload": JSON.stringify({query}),
                 "method": "POST"
                }
  var response = UrlFetchApp.fetch(url, options);
  Logger.log(response);
  return;
}

where the query that was passed into the function was formatted as follows:

var query = "query { user { id defaultEmail } }";

You must JSON.stringify your query and post it as payload.

I had a similar error to yours, that there was no query string present. It may be because GraphQL is looking in the URL arguments for the query, not in the HTTP request payload.

For example, get rid of the payload and change your URL to:

 var url = encodeURI("https://gql.waveapps.com/graphql/public?query=query{course(id:1234){{name}}}");

Or maybe

 var url = encodeURI("https://gql.waveapps.com/graphql/public?query={course(id:1234){{name}}}");

This was brought to my attention by this answer .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM