Home > Back-end >  Wordpress REST API ignoring POST request from Google Apps Script when using 'Body'
Wordpress REST API ignoring POST request from Google Apps Script when using 'Body'

Time:10-19

I am fiddling for the first time with REST APIs so my knowledge is very low. I am using Google Apps Scripts to manage Wordpress data through REST API.

POST Requests are perfectly working when options are passed through the URL parameters, while they are ignored when using body.

I initially thought that this was due to some issues on the Wordpress endpoints, however, as sending requests using Postman the calls are being processed correctly, I suppose data is being sent incorrectly from my Google Apps Script.

Postman will expose sent data, offering an option to generate code for a given language, therefore I have used Javascript Fetch as a starting point.

Following is the Postman-generated code, which is correctly processed by Wordpress:

var myHeaders = new Headers();
myHeaders.append("Authorization", "Bearer some-token-here");
myHeaders.append("Content-Type", "application/json");
myHeaders.append("Cookie", "wordpress_google_apps_login=some-cookie-data-here");

var raw = JSON.stringify({
  "acf": {
    "class": "Nursery"
  }
});

var requestOptions = {
  method: 'POST',
  headers: myHeaders,
  body: raw,
  redirect: 'follow'
};

fetch("https://example.com/wp-json/wp/v2/users/442?context=edit&_fields=acf", requestOptions)
  .then(response => response.text())
  .then(result => console.log(result))
  .catch(error => console.log('error', error));

With the above as a starting point, I have adapted code for Google Apps Script, as follows:

var raw = JSON.stringify({
  "acf": {
    "class": "Nursery"
  }
});

var requestOptions = {
  'method': 'POST',
  'headers': {'Authorization' : 'Bearer some-token-here',
              'contentType' : 'application/json'},
  'body': raw,
  'redirect': 'follow'
};


 var response = UrlFetchApp.fetch("https://example.com/wp-json/wp/v2/users/442?context=edit&_fields=acf",requestOptions); 

Google Apps Script will return a response with code 200, but the requested modifications will not occur. Please notice that the code generated by Postman, uses 'Content-Type', while Google Apps Script should use 'ContentType' parameter. I have tried both, with no success.

Are there some errors in the adapted code, or is there something missing, or even worst, Google Apps Script has some limitations or is it changing somehow the POST request in a way it is not correctly interpreted on the Wordpress end?

CodePudding user response:

To post the body, use payload property instead of body property.

Reference:

  • Related