0

UPDATE

This comprehensive answer resolved my issue:

https://stackoverflow.com/a/29112224/1045794


I am looking at https://developer.salesforce.com/docs/atlas.en-us.api_rest.meta/api_rest/quickstart_code.htm

After getting the Salesforce Version, I am try trying to get a list of resources.

This is the normal way I would access a 3rd party API, but is resulting in a 401 error as if I am unauthorised. I believe I am using the correct token but perhaps this is actually a bad request.

var url = 'https://company.lightning.force.com/services/data/v51.0/';

var myBody = '';
var headers = {"Authorization" : 'Bearer ' + 'my_token'};

var params = {
   'method': 'GET',
   //'muteHttpExceptions': true,
   'headers': headers,
   'contentType': 'application/json',
   //'payload': myBody
};

var res = UrlFetchApp.fetch(url, params);

var myObj = JSON.parse(res.getContentText());

Logger.log(myObj)

Edit - I know the URL is correct because testing https://company.lightning.force.com/services/data/ does return the version numbers

Edit 2 - Changing URL to https://company.my.salesforce.com/services/data/v50.0/ results in the same error

redditor
  • 4,196
  • 1
  • 19
  • 40
  • Have you tried with company.salesforce.com/services/data/v51.0/ URL in place of company.lightning.force.com? – वरुण Feb 22 '21 at 14:13
  • @वरुण DNS error – redditor Feb 22 '21 at 14:22
  • Are you refreshing the token?, as a token is valid for some time. You need to get a refresh token. https://salesforce.stackexchange.com/questions/73512/oauth-access-token-expiration – वरुण Feb 22 '21 at 14:35
  • Thanks @वरुण, I guess my question is, does this look like a valid method of accessing the API. If it does, then it must be the token. I will look into that also. – redditor Feb 22 '21 at 14:40
  • It looks like a valid method to access the API. If you are not refreshing the token that may be causing you the issue. – वरुण Feb 22 '21 at 14:45
  • @वरुण Confirmed I am using valid token – redditor Feb 22 '21 at 15:18
  • Although I'm not sure whether I could correctly understand about the API you want to use, when I saw the official document in your question, it seems that `X-PrettyPrint:1` is used in the request header. How about this? By the way, `'contentType': 'application/json'` is not required to use for GET method. – Tanaike Feb 23 '21 at 01:01

1 Answers1

0

I believe you should pass Headers instead of plain object to fetch params:

var params = {
   'method': 'GET',
   //'muteHttpExceptions': true,
   'headers': new Headers(headers),
   'contentType': 'application/json',
   //'payload': myBody
};
Maria Piaredryj
  • 1,584
  • 3
  • 16
  • 35