Authentication: Get Access Token (JavaScript)

View as Markdown

You can script authentication to the Sigma API.

Each section of the script has inline comments provided.

Refer to the Sigma REST API Recipes QuickStart for step-by-step instructions.

Example script

JavaScript
1// This script responds with a bearer token and is called from each of the other scripts in this project.
2// Variables are in .env and need to be updated for your Sigma hosted environment and API keys
3
4
5
6// 1: Load environment variables from a specific .env file for configuration
7require('dotenv').config({ path: 'sigma-api-recipes/.env' });
8
9// 2: Import Axios for making HTTP requests
10const axios = require('axios');
11
12// 4: Load use-case specific variables from environment variables
13const authURL = process.env.authURL; // The URL for your Sigma Instance
14const clientId = process.env.CLIENT_ID; // Your client ID
15const secret = process.env.SECRET; // Your API secret
16
17// Asynchronous function to obtain a bearer token using the credentials grant type
18async function getBearerToken() {
19 try {
20 // Prepare the data for the request using URLSearchParams to encode it as application/x-www-form-urlencoded
21 const requestData = new URLSearchParams({
22 grant_type: 'client_credentials', // Indicates the grant type for OAuth 2.0
23 client_id: clientId, // Your client ID
24 client_secret: secret, // Your client secret
25 });
26
27 // Log the constructed URL before sending the request
28 console.log(`URL sent to Sigma: ${authURL}`);
29
30 // Make a POST request to the authentication URL with the encoded data and headers
31 const response = await axios.post(authURL, requestData, {
32 headers: {
33 'Content-Type': 'application/x-www-form-urlencoded', // Ensure the server treats the sent data as URL-encoded form data
34 },
35 });
36
37 // Log the success message and the obtained bearer token
38 console.log('Bearer token obtained successfully:', response.data.access_token);
39 return response.data.access_token; // Return the obtained token for use in subsequent API requests
40 } catch (error) {
41 // Log any errors that occur during the token acquisition process
42 console.error('Error obtaining Bearer token:', error.response ? error.response.data : error.message);
43 return null; // Return null to indicate that the token acquisition failed
44 }
45}
46
47// Check if this script is being run directly and not imported as a module in another script. This is so we can run standalone and verify we get a token response.
48if (require.main === module) {
49 // Call getBearerToken and handle the promise it returns
50 getBearerToken().then(token => {
51 // Log the acquired token for verification
52 console.log('Token acquired:', token);
53 }).catch(error => {
54 // Log any errors that occur when trying to acquire the token
55 console.error('Failed to acquire token:', error);
56 });
57}
58
59// Export the getBearerToken function to make it available for import in other use-case scripts
60module.exports = getBearerToken;

Endpoints Used

  1. Get authentication token: ${baseURL}/authURL