I have been trying to figure out how to acquire an access token from Reddit API in Google Apps Script. I have below code written so far:
function main() {
var username = 'myredditusername';
var pwd = 'myredditpassword';
var client_id = 'myredditclientid';
var client_secret = 'myredditclientsecret';
var access_token_url = 'https://www.reddit.com/api/v1/access_token';
var api_url = 'https://oauth.reddit.com/';
var user_agent = 'MySideProjectUserAgent';
var data = {
'grant_type': 'password',
'username': username,
'password': pwd
};
var options = {
'method' : 'post',
'contentType': 'application/json',
'payload' : JSON.stringify(data),
'headers': {'User-Agent': user_agent},
// what do I enter here to pass my client_id and client_secret?
};
var resp = UrlFetchApp.fetch(access_token_url, options);
console.log(resp.getContentText());
}
Running the above code receives an error like below (not surprising because I still need to figure out how to pass in my client_id
and client_secret
):
Exception: Request failed for https://www.reddit.com returned code 401. Truncated server response: {"message": "Unauthorized", "error": 401} (use muteHttpExceptions option to examine full response)
When using curl
, I was able to acquire the token successfully with this command:
curl -X POST -A 'KeywordTrackAgent' -d "grant_type=password&username=myredditusername&password=myredditpassword" --user 'client_id:client_secret' https://www.reddit.com/api/v1/access_token
From reaching around (example post), I figured that if I were to translate this curl
request to a POST
request, I'd need to add Authorization
field to my headers
parameter with the format like below:
function main() {
var username = 'myredditusername';
var pwd = 'myredditpassword';
var client_id = 'myredditclientid';
var client_secret = 'myredditclientsecret';
var access_token_url = 'https://www.reddit.com/api/v1/access_token';
var api_url = 'https://oauth.reddit.com/';
var user_agent = 'MySideProjectUserAgent';
var data = {
'grant_type': 'password',
'username': username,
'password': pwd
};
var options = {
'method' : 'post',
'contentType': 'application/json',
'payload' : JSON.stringify(data),
'headers': {
'User-Agent': user_agent,
// Below, I decided to encode my client_id and client_secret in base64 with the prefix 'Basic '
'Authorization': 'Basic clientIdAndClientSecretInBase64',
},
};
var resp = UrlFetchApp.fetch(access_token_url, options);
console.log(JSON.parse(resp.getContentText()));
}
I'm still receiving { error: 'unsupported_grant_type' }.
Could anyone--who has successfully fetched Reddit access token using JavaScript and preferably, using Google Apps Script--share some suggestion/insight on this? Thank you in advance for your answers!