Generate token with NodeJS
In this article, we will explain how you can generate a Sonetel access token with NodeJS and how you can use it to interact with our API.
To get started, ensure that you have a free Sonetel account. You will have to use your username and password to acquire an access token.
The following code can be used to generate an OAuth access token for a Sonetel account, using the Sonetel API.
import http from 'https'; import FormData from 'form-data'; export const createAccessToken = (username, password) => { return new Promise(resolve => { const host = 'api.sonetel.com'; const authUri = '/SonetelAuth/beta/oauth/token'; if (!username){ throw Error('Username is reqired to generate access token.'); } if (!password){ throw Error('Password is reqired to generate access token.'); } const requestBody = new FormData(); requestBody.append('grant_type', 'password'); requestBody.append('username', username); requestBody.append('password', password); requestBody.append('refresh', 'yes'); const options = { hostname: host, path: authUri, auth: 'sonetel-api:sonetel-api', method: 'post', headers: requestBody.getHeaders() } const req = http.request(options, (res) => { const { statusCode } = res; if(statusCode >= 500){ throw Error (`Request failed with server error. Status code ${statusCode}`) } res.setEncoding('utf-8'); let rawData = ''; res.on('data', (chunk) => rawData += chunk); res.on('end', async () => { try { let dataToReturn; if (res.headers['content-type'].match(/application\/json/i)) { dataToReturn = JSON.parse(rawData); } else { dataToReturn = rawData; } resolve(dataToReturn); } catch (e) { console.error(e.message); } }); }); req.on('error', (e) => { throw Error(`Request failed. ${e.message}`); }); requestBody.pipe(req); }); }
The function first checks that the username
and password
arguments are provided. It then constructs an HTTP request to the Sonetel API, using the POST
method, the grant_type
, username
, and password
parameters, and basic authentication with the sonetel-api
username and password. The request is sent and the response is handled asynchronously, extracting the access token and resolving it as a Promise.
You can find the full API-documentation here.
Photo by Kelly Sikkema on Unsplash