Encountering issues with token header syntax while making an API call in Google Sheets using Apps Script

Uncertain about the correct syntax for the header bearer token section in this code snippet.

...

// --------------------------------------------------------------------------------------------------
//
// iTunes Music Discovery Application in Google Sheets
//
// --------------------------------------------------------------------------------------------------

// custom menu
function onOpen() {
  var ui = SpreadsheetApp.getUi();
  ui.createMenu('iTunes API Call')
      .addItem('Get Artist Data','displayArtistData')
      .addToUi();
}

// function to call iTunes API
function calliTunesAPI(artist) {
  
  // Call the iTunes API
  var response = UrlFetchApp.fetch("https://api.music.apple.com/v1/catalog/us/music-videos/{" + artist + "}");


  --header 'Content-Type:application/json' \
  --header 'Authorization: Bearer eyJhbGciOiJFUzI1NiIsInR5cCI6IkpXVCIsImtpZCI6IjVWNjY3SEZaNjMifQ.eyJpc3MiOiJTOTU0QVE5Q1Q3IieOwO'


 
  // Parse the JSON reply
  var json = response.getContentText();
  return JSON.parse(json);
  
}


function displayArtistData() {
  
  // pick up the search term from the Google Sheet
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var sheet = ss.getActiveSheet();
  
  var artist = sheet.getRange(11,3).getValue();
  
  var tracks = calliTunesAPI(artist);
  
  var results = tracks["results"];
  
  var output = []
  
  results.forEach(function(elem,i) {
    var image = '=image("' + elem["artworkUrl60"] + '",4,60,60)';
    var hyperlink = '=hyperlink("' + elem["previewUrl"] + '","Listen to preview")';
    output.push([elem["artistName"],elem["collectionName"],elem["trackName"],image,hyperlink]);
    sheet.setRowHeight(i+15,65);
  });
  
  // sort by album
  var sortedOutput = output.sort( function(a,b) {
    
    var albumA = (a[1]) ? a[1] : 'Not known';  // in case album name undefined 
    var albumB = (b[1]) ? b[1] : 'Not known';  // in case album name undefined
    
    if (albumA < albumB) { return -1; } else if (albumA > albumB) {
      return 1;
    }
    // names are equal
    return 0;
  });
  
  // adds an index number to the array
  sortedOutput.forEach(function(elem,i) {
    elem.unshift(i + 1);
  });
  
  var len = sortedOutput.length;
  
  // clear any previous content
  sheet.getRange(15,1,500,6).clearContent();
  
  // paste in the values
  sheet.getRange(15,1,len,6).setValues(sortedOutput);
  
  // formatting
  sheet.getRange(15,1,500,6).setVerticalAlignment("middle");
  sheet.getRange(15,5,500,1).setHorizontalAlignment("center");
  sheet.getRange(15,2,len,3).setWrap(true);
  
}

...

This specific part of the code is causing issues:

--header 'Content-Type:application/json'
--header 'Authorization: Bearer eyJhbGciOiJFUzI1NiIsInR5cCI6IkpXVCIsImtpZCI6IjVWNjY3SEZaNjMifQ.eyJpc3MiOiJTOTU0QVE5Q1Q3IieOwO

Unsure of the correct syntax. It seems like basic knowledge, but I need some guidance.

Answer №1

If you're looking to interact with external resources using UrlFetchApp, check out the documentation here.

The main function of UrlFetchApp is to retrieve data from other hosts on the web. To do this, you'll need to include the necessary authentication information like the bearer token and any required headers.

Considering these requirements, here's a revised version of your function:

function calliTunesAPI(artist) {
   var url = "https://api.music.apple.com/v1/catalog/us/music-videos/" + artist;
   var params = {
      "headers": {
         "Content-Type": "application/json",
         "Authorization": "Bearer eyJhbGciOiJFUzI1NiIsInR5cCI6IkpXVCIsImtpZCI6IjVWNjY3SEZaNjMifQ.eyJpc3MiOiJTOTU0QVE5Q1Q3IieOwO"
      }
      "method": "GET"
   }
   var response = UrlFetchApp(url, params);
   var json = response.getContentText();
   return JSON.parse(json);
}

For more information:

Answer №2

By using this code snippet as a reference, you should have no trouble updating your own code. Best of luck!

var endpoint = "https://www.example-api.com"
var headers = {
  "Authorization": "Bearer jdfjwek454jsfs56434",
  "Content-Type": "Application/json"
};

var config = {
  "method" : "post",
  "headers" : headers 
};

var result = fetch(endpoint, config);

REVISION: This modified version should work, but it seems that the API is currently unavailable. You can remove the variable artist. I just needed a placeholder number ;)

function getMusicInfo(artist) { 
  var artistId = 178834;
  var url = "api.music-db.com/v1/catalog/us/music-info?id=" + artistId; 
  var headers = { "Authorization": "Bearer eyJhbGciOiJFUzI1NiIsInR5cCI6IkpXVCIsImtpZCI6IjVWNjY3SEZaNjMifQ.eyJpc3MiOiJTOTU0QVE5Q1Q3IieOwO", 
                  "Content-Type": "Application/json" 
                }; 
  var options = { 
    "method": "get", 
    "headers": headers,
    "muteHttpExceptions": true
  }; 
  var response = fetch(url, options).json(); 
  console.log(response);
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Sending a XML file from a Vue application to an ASP.NET Core backend using axios

I'm encountering difficulties when trying to upload an xml file using axios to my asp .net server. Below is the code snippet I am using on the vue side to retrieve and upload the xml file: uploadXmlFile(file: any) { const rawFile = new XMLHttpRequ ...

Tips for acquiring offspring who are exclusively not descendants of a particular node

Currently, I am utilizing jQuery and my goal is to access all elements of a specific type that are not children of a particular node type. For example, my Document Object Model (DOM) structure looks like this: <div id='idthatiknow'> & ...

Is there a way to turn off vue.js transitions specifically for testing purposes?

I'm utilizing a vue.js component with the <transition> element for show/hide animations. However, I want to disable the animation for faster testing. How can I achieve this? The solution proposed is * { transition: none !important } in this lin ...

Unable to utilize console.log and alert functions within the Next.js application

I'm currently facing a problem in my Next.js application where the console.log and alert functions are not functioning as intended. Despite checking the code, browser settings, and environment thoroughly, pinpointing the root cause of the issue remain ...

The comparison between local variables and data can result in a significant drop in performance

My current project involves VueJS and Cesium, but I'm facing a performance issue with a significant drop in frame rate. While I have identified the problem area, I am unsure of why this is happening and how to resolve it. export default { name: ...

Is it possible to edit YouTube images or embed YouTube iframes without needing an account?

Recently, I developed a YouTube video sharing system but have encountered some uncertainties. My approach involves extracting the YouTube ID and embedding it in an iframe (I wonder if YouTube permits this). To enhance the visual appeal of the posts, especi ...

How can I retrieve all values that share the same reference number as an object in a JSON file using iOS and Objective-C?

This is an excerpt from the JSON response received from a web service. - Books :[ -{ RfNo:"1", SegOrd:"1", LegNo:"1", Title:"Wild Elephants", Author:"Dr. Vijitha Perera", Country:"Sri Lanka", Price:"$8.99" }, -{ ...

What is the best way to divide the Jquery.js file into smaller, separate files?

My web server has a strict file size limit of 64KB and I heavily rely on jQuery for my project. Unfortunately, using any other library like zepto is not an option. The minified size of jQuery alone is 95KB, so I need to split it into two smaller files. C ...

"Implement next-auth alongside a credentials provider and utilize a JWT token as a bearer in order to authenticate access to the API

Currently in the process of developing an application using Next.js and Next-auth with credentials provider. I'm trying to figure out how to secure my APIs within the pages folder by utilizing the JWT token generated by next-auth as a bearer token in ...

Discovering the cities associated with a particular province in ReactJS

Hello, I'm new to reactjs and I am looking for a way to retrieve the cities of a province when it is passed as input. I have tried using npm but haven't had any success so far. Any help would be greatly appreciated. Thank you! ...

Using JavaScript to set attribute values in Python Selenium, these values are cleared after each update

Assuming : for i in list('{}'.format(value)): self.browser.execute_script( "arguments[0].setAttribute('value', '{}');".format(i.replace('&b ...

Having trouble parsing JSON with jQuery?

After running the json_encode PHP function, the output that I receive is as follows: [{"id":"1","size":"124","name":"Team1","picture":1}, {"id":"5","size":"76","name":"Team 4","picture":2}, {"id":"3","size":"25","name":"Team2","picture":3}, {"id":"4","s ...

Is it feasible to model general JSON arrays in a struct using Go?

Is it possible to Marshal/Unmarshal a struct in Go? type MyType struct { Items <What should be included here?> `json:"item"` } An example JSON document that needs to be handled is {"items":["value1", {"x":"y"}, "value3"]} I am new to Go ...

AngularJS provides users with the ability to access additional information by matching specific identification

Is there a simple way in Angular to display the label of an item from an array without looping through it? I have an array of color options: $scope.colors=[ {id:"0",label:"blue"}, {id:"1",label:"red"}, {id:"2",label:"green"} ] And my data object store ...

Is there a way to verify the location of an element?

Currently, I am attempting to monitor the position of the 'car'. When the car reaches a top offset of 200px, I would like to apply a specific property to the 'phone' element. The concept is that as you scroll down, the car will move, an ...

Developing an IF statement in JavaScript that relies on hexadecimal color values

I've created a JavaScript code that changes the background color of my webpage every time it loads: document.getElementById("band").style.background = '#'+(Math.random()*0xFFFFFF<<0).toString(16); To improve visibility, I am aiming t ...

Closing the Material UI Drawer

Having an issue with my material UI drawer - I can open it successfully, but when attempting to close it, the event does not trigger. import React from 'react'; import './App.css'; import { fade, makeStyles } from '@material-ui/co ...

Dealing with a variety of JSON structures in Presto while extracting as a string?

I need help with extracting a string from JSON data in Presto. I have two options for the extracted data format before converting it to a string: JSON_EXTRACT(my_column, '$.my_column_extract') = ["A::1","B::2","C::3","D::4"] JSON_EXTRACT(my_colu ...

Calculate the combined sum of values within dynamic inputs that share a common class, and automatically update the sum whenever input values are altered or new rows are added or removed dynamically

$("#add-btn").click(function() { $("#dynamic").append('<tr>' + '<td class="td">' + '<input type="number" name="Debit" class="form-control Debit"/>' + '</td>' + '<td c ...

Serialize the entity using JSON.NET JsonConvert will result in an empty array being returned

Currently, I am serializing my entity object using JsonConvert.SerializeObject. Here is an example of what I am doing: var test = JsonConvert.SerializeObject(MyEntityObject) The result of this test is : [ { "$id": "1", "Someproperty1": 1, ...