lexiconkatu
lexiconkatu

Reputation: 43

Send POST request in Google Apps Script with Headers and Body

I am trying to send a POST request in order to receive an Access Token in return.

The documentation is as follows:

Client Credentials

This is your first route to obtain an access_token to communicate with the API.

Route : POST https://api.helloasso.com/oauth2/token

Headers

Content-Type = application/x-www-form-urlencoded

Body

client_id = Your Client Id

client_secret = Your Client Secret

grant_type = client_credentials

Solution I tried

Based on this post, I tried the following code:

function qwe()
{
  
  const url = 'https://api.helloasso.com/oauth2/token';

  const headers = { 
      "client_id": "Your Client Id",
      "client_secret": "Your Client Secret",
      "grant_type": "client_credentials"
    };

  const options = { 
    'method' : 'post',
    'contentType': 'application/x-www-form-urlencoded',
    'headers': headers
  };

  const response = UrlFetchApp.fetch(url, options);
  var data = JSON.parse(response);

  Logger.log(data);
  
}

Upon running this, I get an error "Exception: Request failed for https://api.helloasso.com returned code 400. Truncated server response: {"error":"unauthorized_client","error_description":"client_id is not set"}".

I am a beginner, and would appreciate any help on this! Thank you in advance

Upvotes: 2

Views: 5593

Answers (2)

Someone
Someone

Reputation: 19

Need to make it stringify first

'payload' : JSON.stringify(data)

Upvotes: 1

Tanaike
Tanaike

Reputation: 201603

Modification points:

  • In the case of UrlFetchApp, the default content type is application/x-www-form-urlencoded.
  • From your question and situation, I guessed that your Body might be required to be sent as form data.

If those points are reflected in your script, it becomes as follows.

Modified script:

function qwe() {
  const url = 'https://api.helloasso.com/oauth2/token';
  const data = {
    "client_id": "Your Client Id",
    "client_secret": "Your Client Secret",
    "grant_type": "client_credentials"
  };
  const options = {
    'method': 'post',
    'payload': data
  };
  const response = UrlFetchApp.fetch(url, options);
  console.log(response.getContentText())
}

Note:

  • If you tested this modified script, when an error occurs, please show the detailed error message and provide the official document. By this, I would like to confirm it.

Reference:

Upvotes: 5

Related Questions