Skip to content
Advertisement

How to add an API Key to a UrlFetchApp in Google Apps Scripts

Solved Thanks to Dimu Designs for helping out.

The following works.

function myFunction() {
     var url = "https://api.fortnitetracker.com/v1/profile/pc/Ninja";   var apiKey = "xxx-xxx-xxx";

   var res = UrlFetchApp.fetch(
    url,
    {
        "headers":{
            "TRN-Api-Key":apiKey
        }
    } );  var content = res.getContentText();   Logger.log(res);   Logger.log(content);

}

Problem

I’m trying to use Google App Scripts within Google Sheets to call the external Fortnite API to request player data. The bit I’m stuck on how to add an API Key as a header when passing the request.

This is what I’ve built so far (please no laughing)!…

function myFunction() {   
var res =
 UrlFetchApp.fetch("https://api.fortnitetracker.com/v1/profile/PC/Ninja?");
var content = res.getContentText();   Logger.log(res);  
Logger.log(content); 
}

When I try to run this I get back the following error:

Request failed for https://api.fortnitetracker.com/v1/profile/PC/Ninja? returned code 401. Truncated server response: {“message”:”No API key found in request”} (use muteHttpExceptions option to examine full response

I’ve tried adding my API key in a number of ways based on a number of different posts, but it doesn’t work and just confuses me even more (easily done at this point).

Does anyone have any idea how I could go about completing the script to ensure I get information back? 🙂

—Edit—

First of all, thanks for the help guys, here’s where we are at the moment. I’ve now tried the following:

var url = "https://api.fortnitetracker.com/v1/profile/pc/Ninja"; var apiKey = "xxx-xxxx-xxx";

var response = UrlFetchApp.fetch(
    url,
    {
        "headers":{
            "TRN-Api-Key":apiKey
        }
    } );

Rather than a 401 error, this time a 403 error is being returned.

Note, I’ve also tried to authenticate the header using “basic” but that doesn’t work”.

Advertisement

Answer

EDIT I suspect that the API uses a custom header. When you register for an API key you get a string in the following form:

TRN-Api-Key:xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx

I’m guessing here, but the text preceding the colon appears to be a custom header and the string of characters after the colon is the API key.

Without proper documentation this is STILL pretty much a shot in the dark but you can try the following:

var url = "[FORTNITE-API-ENDPOINT]";
var apiKey = "[YOUR-API-KEY]"; // sans header and colon

var response = UrlFetchApp.fetch(
    url,
    {
        "headers":{
            "TRN-Api-Key":apiKey
        }
    }
);

Also, make sure to check out the UrlFetchApp documentation for future reference: https://developers.google.com/apps-script/reference/url-fetch/url-fetch-app

Advertisement