How to use a key in an esriRequest call

1329
4
07-01-2019 08:18 AM
JustinBridwell2
Occasional Contributor II

I have been making calls to a previously free API using esriRequest

var layersRequest = esriRequest({     
   url: base_url,     
   content: { 
      "latitude": lat,                 
      "longitude": long,                 
      "riskCategory": risk,                 
      "siteClass": siteClass,                 
      "title":"Default"},     
   dataType:'jsonp',     
   handleAs: "json",     
   callbackParamName: "callback" }); ...

Now the API requires a key; which I have:

const key = 'xI234fg543example23';

The above is just an **example key; not real

The API documentation says to "Include your key in the api-key field of your request headers to authenticate like this:

curl --header "api-key: [your_api_key]" -X GET "https://api-hazards.atcouncil.org/public/v1/[load_category].json?lat=[lat]&lng=[lng]"

How do I correctly apply this using esriRequest? I believe the generic javascript equivalent would be 

layerRequest.setRequestHeader
0 Kudos
4 Replies
ReneRubalcava
Frequent Contributor II

You would want to use a request interceptor.

https://developers.arcgis.com/javascript/latest/api-reference/esri-config.html#request

This is a property you can set on "esri/config".

There is an option to provide additional headers to requests that are made to specific URLs.

https://developers.arcgis.com/javascript/latest/api-reference/esri-config.html#RequestInterceptor

Your case may look something link this.

esriConfig.request.interceptors.push({
  urls: "https://api-hazards.atcouncil.org",
  headers: {
    "api=key": "xI234fg543example23"
  }
});

That should give you the results you are looking for.

ReneRubalcava
Frequent Contributor II

Realized you might be using 3x. In 3x, there is a method on esriRequest you can use to do something similar.

https://developers.arcgis.com/javascript/3/jsapi/esri.request-amd.html#esrirequest.setrequestprecall...

esriRequest.setRequestPreCallback(function(ioArgs) {
    if (ioArgs.url.indexOf("https://api-hazards.atcouncil.org") > -1) {
      ioArgs.headers = ioArgs.headers || {}; // make sure headers are not null
      ioArgs.headers["api-key"] = "xI234fg543example23" // add custom headers
    }
    return ioArgs;
});
JustinBridwell2
Occasional Contributor II

OK, I am trying to apply setRequestPreCallback to my situation based on the documentation. First, created a function:

    

function myCallbackFunction(ioArgs){
      if (ioArgs.url.indexOf("https://api-hazards.atcouncil.org") > -1) {
              ioArgs.headers = ioArgs.headers || {}; // make sure headers are not null
              ioArgs.headers["api-key"] = "xI234fg543example23" // add custom headers
            }
            return ioArgs;
    }

Then I tried calling the function before I make my esriRequest (which is inside a button click event).

var seis_data;
    //Get Seismic Data button click function
    document.getElementById("btnGetSeismic").onclick = function () {
      if (additionalInfo["pointGeomOfInterest"] !== undefined) {
        var lat = additionalInfo["pointGeomOfInterest"].y;
        var long = additionalInfo["pointGeomOfInterest"].x;
      }
      if (risk == "" || siteClass == "" || reference == "" || additionalInfo["pointGeomOfInterest"] === undefined)
      {
        alert("Choose a Reference, Risk Category, Site Class, and location!");
      } else if (siteClass == "F")
      {
        alert("Site class F temporarily unavaliable. Please select an alternate site class and consult the ASCE/SEI 7-16 reference document for more information on the seismic design parameters for Site Class F - Site Response Analysis.");
      } else {
        var base_url = seismic_url + reference + ".json";
        var lat = additionalInfo["pointGeomOfInterest"].y;
        var long = additionalInfo["pointGeomOfInterest"].x;
        esriRequest.setRequestPreCallback(myCallbackFunction);
        var layersRequest = esriRequest({
        url: base_url,
        content: { "latitude": lat,
                  "longitude": long,
                  "riskCategory": risk,
                  "siteClass": siteClass,
                  "title":"Default"},
        dataType:'jsonp',
        handleAs: "json",
        callbackParamName: "callback"
        });
        layersRequest.then(
          function(response) {
            seis_data = response.response.data;
            console.log("Success: ", seis_data);
            // populate_table();
            addSeismicTable(seis_data);
            populateAddSeismicTableResults(seis_data);
        }, function(error) {
            console.log("Error: ", error.message);
        });
      };
    }

Right now I am getting a net::ERR_ABORTED 401 (Unauthorized) error. I tested the API Key in Postman and it worked. Do you see anything I am doing incorrectly in applying this?

0 Kudos
ThanHtetAung_EsriAu
Esri Regular Contributor

Hi Justin,

You might want to use Fiddler or Chrome developer windows at network tab, check the network traffic.

And find out whether esriRequest object is performing your expected http request to the destination.

Check that whether there is header, params you want.

Step to do:

Open your page in chrome, press f12, break point on the code before it is called.

And switch to network tab and check the network traffic

0 Kudos