API Sample JavaScript
Introduction
We've included complete API examples in JavaScript that show you how to perform basic functions like job submission, deletion, and display. We also included a set of example job JSON files that show different types of jobs. The example job JSON files may be submitted via API calls or they can be submitted via the Hybrik User Interface (UI). In the UI, go to the Active Jobs (or Queued, Completed, or Failed) window and select the "More Actions" dropdown menu. Choose the menu item "Submit Job JSON" and then choose the file you would like to submit. This allows you to test and verify your job JSON separately from your API integration.
The specific example API files are:
- hybrik_connector.js - Performs the basic connection to the Hybrik service.
- submit_job.js - Shows how to submit a single job.
- display_all_jobs.js - Shows how to display all of the jobs (queued, running, and completed).
Download the sample files here:
Sample JavaScript.zip
Submit A Job
This example will submit one job via the API to the Hybrik system. The job JSON is specified in the node.js arguments.
submit_job.js
// import api config. Please edit api_config.js first before running this example.
var api_config = require('./api_config.js');
// the Hybrik Connector lib for submitting POST/GET/DELETE/PUT commands to Hybrik
var HybrikAPI = require('./hybrik_connector.js');
// import shared helpers
var shared = require('./shared.js');
var fs = require('fs');
if (process.argv.length < 3) {
console.log("Usage: node submit_job.js <job_json_file>")
return;
}
// construct an API access object using your Hybrik account info
var hybrik_api = new HybrikAPI(
api_config.HYBRIK_URL,
api_config.HYBRIK_COMPLIANCE_DATE,
api_config.HYBRIK_OAPI_KEY,
api_config.HYBRIK_OAPI_SECRET,
api_config.HYBRIK_AUTH_KEY,
api_config.HYBRIK_AUTH_SECRET
);
// read the JSON job file and parse into object
var job_json_file = process.argv[2];
var job = JSON.parse(fs.readFileSync(job_json_file, 'utf8'));
// submit the job
submitJob(job);
// function to submit a job through the Hybrik API
function submitJob(job) {
// connect to the API
return hybrik_api.connect()
.then(function () {
// submit the job by POSTing the '/jobs' command
return hybrik_api.call_api('POST', '/jobs', null, job)
.then(function (response) {
console.log('Job ID: ' + response.id);
return response.id;
})
.catch(function (err) {
// any error - let it be in the request/network etc. or as a result of the Hybrik API operation, goes here.
shared.print_error(err);
});
})
.catch(function (err) {
// any error - let it be in the request/network etc. or as a result of the Hybrik API operation, goes here.
shared.print_error(err);
});
}
Display All Jobs
This example will display all the jobs currently in the system. By changing the "fields" array you can change which columns of data are returned.
display_all_jobs.js
// import api config. Please edit api_config.js first before running this example.
var api_config = require('./api_config.js');
// the Hybrik Connector lib for submitting POST/GET/DELETE/PUT commands to Hybrik
var HybrikAPI = require('./hybrik_connector.js');
// import shared helpers
var shared = require('./shared.js');
// construct an API access object using your Hybrik account info
var hybrik_api = new HybrikAPI(
api_config.HYBRIK_URL,
api_config.HYBRIK_COMPLIANCE_DATE,
api_config.HYBRIK_OAPI_KEY,
api_config.HYBRIK_OAPI_SECRET,
api_config.HYBRIK_AUTH_KEY,
api_config.HYBRIK_AUTH_SECRET
);
// display the jobs
displayJobList();
function displayJobList() {
// connect to the Hybrik API
return hybrik_api.connect()
.then(function () {
// make a GET call with '/jobs/info' to get a list of all jobs
return hybrik_api.call_api('GET', '/jobs/info', { fields: [ 'id', 'name','progress', 'status','start_time','end_time'], sort_field: 'id', order: 'desc' })
.then(function (response) {
// the response is an array of job objects
var numberOfJobs = response.items.length;
console.log('Number of Jobs: ' + numberOfJobs);
for (var i = 0; i< numberOfJobs; i++) {
console.log('ID: ' + response.items[i].id + ' Name: '+ response.items[i].name + ' Progress: ' + response.items[i].progress + ' Status: ' + response.items[i].status + ' Start: ' + response.items[i].start_time + ' End: ' + response.items[i].end_time);
}
return true;
})
.catch(function (err) {
// any error - let it be in the request/network etc. or as a result of the Hybrik API operation, goes here.
shared.print_error(err);
});
})
.catch(function (err) {
// any error - let it be in the request/network etc. or as a result of the Hybrik API operation, goes here.
shared.print_error(err);
});
}
Delete All Jobs
This example will delete all the jobs currently in the system. There is also an example function to delete only the completed jobs.
delete_all_jobs.js
// import api config. Please edit api_config.js first before running this example.
var api_config = require('./api_config.js');
// the Hybrik Connector lib for submitting POST/GET/DELETE/PUT commands to Hybrik
var HybrikAPI = require('./hybrik_connector.js');
// import shared helpers
var shared = require('./shared.js');
// construct an API access object using your Hybrik account info
var hybrik_api = new HybrikAPI(
api_config.HYBRIK_URL,
api_config.HYBRIK_COMPLIANCE_DATE,
api_config.HYBRIK_OAPI_KEY,
api_config.HYBRIK_OAPI_SECRET,
api_config.HYBRIK_AUTH_KEY,
api_config.HYBRIK_AUTH_SECRET
);
deleteAllJobs();
// and here is an example that only deletes the completed jobs:
// deleteCompletedJobs();
function delete_job_chunk(filters) {
//get a list of the jobs -- this returns a max of 1000 jobs, so as long as jobs are returned, call the delete recursively
var query_args = {
fields: ['id'],
order: 'asc'
};
if (filters) query_args.filters = filters;
return hybrik_api.call_api('GET', '/jobs/info', query_args).then(function (response) {
numberOfJobs = response.items.length;
if (numberOfJobs == 0) {
console.log('No more jobs available to delete');
return true;
}
var jobIDs = [];
for (var i = 0; i < numberOfJobs; i++) {
jobIDs[i] = response.items[i].id;
}
console.log('Deleting ' + numberOfJobs +' jobs...');
//delete the jobs
return hybrik_api.call_api('DELETE', '/jobs', null, {ids: jobIDs}).then(function (response) {
numberOfJobs = response.items.length;
console.log('Number of jobs successfully deleted: ' + numberOfJobs);
//call delete_job_chunks() again
return delete_job_chunk(filters);
}).catch(function (err) {
// any error - let it be in the request/network etc. or as a result of the Hybrik API operation, goes here.
shared.print_error(err);
});
}).catch(function (err) {
// any error - let it be in the request/network etc. or as a result of the Hybrik API operation, goes here.
shared.print_error(err);
});
}
function deleteAllJobs() {
//connect to the Hybrik API
return hybrik_api.connect().then(function () {
return delete_job_chunk();
})
.catch(function (err) {
// any error - let it be in the request/network etc. or as a result of the Hybrik API operation, goes here.
shared.print_error(err);
});
}
// same function as above, but only deletes the jobs marked as 'completed'
function deleteCompletedJobs() {
return hybrik_api.connect().then(function () {
return delete_job_chunk([
{
field: 'status',
values: ['completed']
}
]);
})
.catch(function (err) {
// any error - let it be in the request/network etc. or as a result of the Hybrik API operation, goes here.
shared.print_error(err);
});
}
Hybrik Connector
The hybrik_connector.js example uses promises for its asynchronous functionality. The specific npm libraries used are "request-promise" and "bluebird". The HybrikAPI call expects the following parameters (all required):
Name | Type | Description |
---|---|---|
api_url | string | The URL for the Hybrik API entry. Depending on your Hybrik account, you may have a unique entry point for your company. |
compliance_date | string | The date you start using the API. This ensures that even if we change something, we will stay compatible with you. |
oapi_key | string | Your account OAPI Key. This authenticates you to interface with the API. |
oapi_secret | string | Your account OAPI Secret. |
user_key | string | Your API User account user name. |
user_secret | string | Your API User account password. |
hybrik_connector.js
var requestp = require('request-promise');
var Promise = require('bluebird');
function HybrikAPI(api_url, compliance_date, oapi_key, oapi_secret, user_key, user_secret) {
if (!api_url || api_url.indexOf('http') != 0 || api_url.indexOf(':') < 0 || api_url.indexOf('//') < 0)
throw new Error('HybrikAPI requires a valid API url');
if (!user_key)
throw new Error('HybrikAPI requires a user_key');
if (!user_secret)
throw new Error('HybrikAPI requires a user_secret');
if (!compliance_date || !/^\d{8}$/.test(compliance_date))
throw new Error('HybrikAPI requires a compliance date in "YYYYMMDD" format.');
this.user_key = user_key;
this.user_secret = user_secret;
this.compliance_date = compliance_date;
var url_parts = api_url.split('//');
if (url_parts.length != 2)
throw new Error('HybrikAPI requires a valid API url');
this.oapi_url = url_parts[0] + '//' + oapi_key + ':' + oapi_secret + '@' + url_parts[1];
if (this.oapi_url[this.oapi_url.length - 2] == '/')
this.oapi_url = this.oapi_url.substring(0, this.oapi_url.length - 1);
}
HybrikAPI.prototype.connect = function () {
var self = this;
return requestp({
uri : self.oapi_url + '/login',
method : 'POST',
qs: {
auth_key: self.user_key,
auth_secret: self.user_secret
},
headers: {
'X-Hybrik-Compliance': self.compliance_date
}
})
.then(function (response) {
self.login_data = JSON.parse(response);
return Promise.resolve(true);
})
}
HybrikAPI.prototype.call_api = function (http_method, api_method, url_params, body_params) {
var self = this;
var request_options = {
uri : self.oapi_url + (api_method[0] === '/' ? api_method : api_method.substring(1)),
method : http_method,
headers: {
'X-Hybrik-Sapiauth': self.login_data.token,
'X-Hybrik-Compliance': self.compliance_date
}
};
if (url_params) {
request_options.qs = url_params;
}
if (body_params) {
request_options.headers['Content-Type'] = 'application/json';
request_options.body = JSON.stringify(body_params);
}
return requestp(request_options)
.then(function (response) {
var resp_obj = JSON.parse(response)
return Promise.resolve(resp_obj);
})
}
module.exports = HybrikAPI;