How to get live (spot) energy price using API in Node.js?

< Back to Guides

Node.js is an open-source, cross-platform, back-end JavaScript runtime environment that runs on the V8 engine and executes JavaScript code outside a web browser. To get live energy price using Node.js, we offer sample code snippets using different methods. Methods include using Axios, Native, Request, and Unirest.

For the pure Javascript tutorial, please check out this link.

Instructions

  1. Get a free API key to use by signing up at energypriceapi.com and replace REPLACE_ME with your API key.
  2. Update base value to a currency or remove this query param.
  3. Update currencies value to a list of values or remove this query param. Below is an example usage for energy price API in use.

For 2 and 3, you can find this documented at Offical Documentation

 

Using Axios to fetch live energy price in Node.js

var axios = require('axios');

var config = {
  method: 'get',
  url: 'https://api.energypriceapi.com/v1/latest?api_key=REPLACE_ME&base=USD&currencies=BRENT,WTI,NATURALGAS',
  headers: { }
};

axios(config)
.then(function (response) {
  console.log(JSON.stringify(response.data));
})
.catch(function (error) {
  console.log(error);
});

 

Using Native to fetch live energy price in Node.js

var https = require('follow-redirects').https;
var fs = require('fs');

var options = {
  'method': 'GET',
  'hostname': 'api.energypriceapi.com',
  'path': '/v1/latest?api_key=REPLACE_ME&base=USD&currencies=BRENT,WTI,NATURALGAS',
  'headers': {
  },
  'maxRedirects': 20
};

var req = https.request(options, function (res) {
  var chunks = [];

  res.on("data", function (chunk) {
    chunks.push(chunk);
  });

  res.on("end", function (chunk) {
    var body = Buffer.concat(chunks);
    console.log(body.toString());
  });

  res.on("error", function (error) {
    console.error(error);
  });
});

req.end();

 

Using Request to fetch live energy price in Node.js

var request = require('request');
var options = {
  'method': 'GET',
  'url': 'https://api.energypriceapi.com/v1/latest?api_key=REPLACE_ME&base=USD&currencies=BRENT,WTI,NATURALGAS',
  'headers': {
  }
};
request(options, function (error, response) {
  if (error) throw new Error(error);
  console.log(response.body);
});

 

Using Unirest to fetch live energy price in Node.js

var unirest = require('unirest');
var req = unirest('GET', 'https://api.energypriceapi.com/v1/latest?api_key=REPLACE_ME&base=USD&currencies=BRENT,WTI,NATURALGAS')
  .end(function (res) {
    if (res.error) throw new Error(res.error);
    console.log(res.raw_body);
  });