StackExchange API authentication in Google Apps Script

175 Views Asked by At

I'm trying to use the V2.2 of StackExchange API in Google Apps Script.

The problem comes in the last step of the explicit OAuth 2.0 flow, when I try to send the POST request to obtain the access token. I receive a 404 error, but making the same request manually (using postman extension) everything is ok.

To simplify the problem, if I send this POST request with no payload I receive the same 404

var response = UrlFetchApp.fetch("https://stackexchange.com/oauth/access_token", {
  method: 'post',
  muteHttpExceptions: true
});
Logger.log(response);

while in postman I receive this 400:

{
   "error": {
       "type": "invalid_request",
       "message": "client_id not provided"
   }
}

I guess this will be a problem with UrlFetchApp, but does anyone know how to solve it? Thanks!

2

There are 2 best solutions below

0
On BEST ANSWER

The problem is related with the Origin header.

You cannot remove from the header directly but you can perform the call via a proxy :)

1
On

You need to provide the data for the post by adding an 'option' object to the call. For example:

var options = { "method" : "post", "payload" : payload };
UrlFetchApp.fetch("https://stackexchange.com/oauth/access_token", options);

Btw, have you tried you use the OAuth that UrlFetch got: https://developers.google.com/apps-script/reference/url-fetch/url-fetch-app#addOAuthService(String) - It might be better way.