Authenticating against the NL API in Javascript

  • 4 November 2021
  • 0 replies

Userlevel 4
Badge +2
  • Community Manager
  • 16 replies

Copy and paste are two of the most important things to a developer, and it’s not something to be ashamed of.  Why waste time when something already exists to do what you need?  In that vein, I thought I’d share a bit of code for you javascript developers out there which will help you to easily authenticate against the NL API.

The NL API uses the bearer token method where the username and password is sent to the proper endpoint and a bearer token is returned that is then used in all further API calls.  This snippet shows how to set a variable to the bearer token value for use in all further NL API calls.

A VERY IMPORTANT note is that your username and password are of course visible in this javascript code, so it is highly recommended that this code is run server-side on node.js.

I’m not exactly splitting the atom here, but I thought it would be useful to copy and paste as your start your javascript projects. 

var uname = "username@faketest.com";
var pass = "fakePassword";

// Get a token from the NL API by creating a promise that retrieves the token when needed.
const token = new Promise((resolve, reject) => { //we're setting the variable 'token' to the value that is returned
var jsonBody = { "username": uname, "password": pass };
fetch("https://developer.expert.ai/oauth2/token", { //send the username and password to the auth endpoint
method: "POST",
headers: {
"Content-Type": "application/json; charset=utf-8"
body: JSON.stringify(jsonBody) //get the response which contains the token text
.then((response) => response.text()) // the response from the API is in plain text
.then((res) => resolve(res)); // resolve the promise with the value of the token returned

I’ve also put it into a Github Gist for easy reference:



0 replies

Be the first to reply!