简体   繁体   中英

How do I get Snipe-IT API to retrieve data using a Google App Script and populate it on a Google Sheet?

I am attempting to create a visualization of the data we have on Snipe-IT Asset Management on Google Data Studio. To do so, I am creating a Google Sheets spreadsheet with an App Script extension that will communicate with the Snipe-IT API, retrieve the data, and populate it on the Google Sheet. So far, I've been able to get the API to populate some of our data on the terminal but not on the spreadsheet itself.

I wrote a simple script that should list out the assets assigned to one particular user, for testing purposes. Again, the script works fine, it populates the data I need on the terminal but not on the Google Sheet. Here is my exact code (excluding SETUP section details):


//SETUP
serverURL = 'SERVER-URL'; (ignore)
apiKey = 'API-KEY' (ignore)

function onOpen(e) {
  createCommandsMenu();
}

function createCommandsMenu() {
  var ui = SpreadsheetApp.getUi();
      ui.createMenu('Run Script')
      .addItem('Get Assets By Department', 'runGetAssetsByDepartment')
      .addToUi();
}

function testGetAssetsByUser(){
  getAssetsByUser("1745")
}
//Get assets for a user by id
//Returns a list of assets by id
function getAssetsByUser(userID) {
  
  var url = serverURL + 'api/v1/users/' + userID + '/assets';
  var headers = {
    "Authorization" : "Bearer " + apiKey
  };
  
  var options = {
    "method" : "GET",
    "contentType" : "application/json",
    "headers" : headers
  };
  
  var response = JSON.parse(UrlFetchApp.fetch(url, options));
  var rows = response.rows;
  var assets = []
  
  for (var i=0; i<rows.length; i++) {
    var row = rows[i];
    if (row.category.name == "Laptop" || row.category.name == "Desktop" || row.category.name == "2-in-1") {
      var asset = row.id
      assets.push(asset)
    }
  }
  return assets
}

console.log(getAssetsByUser(1745));

There are several ways to write values into an spreadsheet

The basics

Grab the spreadsheet

var spreadsheet = SpreadsheetApp.getActiveSpreadsheet();

This works in bounded projects and add-ons

Grab the destination sheet

var sheet = spreadsheet.getSheetByName('put here the sheet name');

You might use SpreadsheetApp.getActiveSheet() if your spreadsheet has only one sheet, but for functions being called from a custom menu this one is risky.

Write values into the destination sheet

Preparation: Make a 2D Array

var output = assets.map(v => [v]);

Do: Write values into the destination sheet

sheet.getRange(1,1,output.length, 1).setValues(output);

Resources

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM