I am trying to connect to Tableau from a Google Apps Script so that I can get the view data and populate a Google Sheet. Not finding any good examples online however.
I am using this code to connect via a Personal Access Token but I do not know how to parse the auth token which is returned in XML (despite me setting the content type as JSON) and then how to make a second call to query the server?
function tableauAPI() {
const options = {
method: 'post',
muteHttpExceptions: true,
contentType: 'application/json',
accept: 'application/json',
payload: JSON.stringify(
{
credentials: {
personalAccessTokenName: 'TestToken',
personalAccessTokenSecret: '11122223333444455555',
site: {
contentUrl: '',
},
},
}
),
};
const response = UrlFetchApp.fetch(
'https://example.tableau.com/api/3.21/auth/signin',
options
);
console.log(response.getContentText());
}
About your 1st question I do not know how to parse the auth token which is returned in XML (despite me setting the content type as JSON)
, please include "Accept" in the request header. So, when your script is modified, please modify as follows.
function tableauAPI() {
const options = {
method: 'post',
muteHttpExceptions: true,
contentType: 'application/json',
headers: { "Accept": "application/json" }, // Modified
payload: JSON.stringify(
{
credentials: {
personalAccessTokenName: 'TestToken',
personalAccessTokenSecret: '11122223333444455555',
site: {
contentUrl: '',
},
},
}
),
};
const response = UrlFetchApp.fetch('https://example.tableau.com/api/3.21/auth/signin', options);
console.log(response.getContentText());
}
About your 2nd question how to make a second call to query the server
, I cannot understand the method of the API you want to use. So, the following sample script is for using a GET method with the retrieved token. So, please modify this for your actual situation.
function tableauAPI() {
const options = {
method: 'post',
muteHttpExceptions: true,
contentType: 'application/json',
headers: { "Accept": "application/json" }, // Modified
payload: JSON.stringify(
{
credentials: {
personalAccessTokenName: 'TestToken',
personalAccessTokenSecret: '11122223333444455555',
site: {
contentUrl: '',
},
},
}
),
};
const response = UrlFetchApp.fetch('https://example.tableau.com/api/3.21/auth/signin', options);
const text = response.getContentText();
console.log(text);
if (response.getResponseCode() == 200) {
const obj = JSON.parse(text);
const token = obj.credentials.token;
// If it's GET method,
const url = "###"; // Please set your expected URL.
const options = { headers: { "X-Tableau-Auth": token } }; // Here, the token is used in the request header.
const res = UrlFetchApp.fetch(url, options);
console.log(res.getContentText())
}
}