Go to main content

Request Kontent.ai Delivery API in Node.js

I've already done a few websites with Kontent.ai in Node.js and I would like to share my experience. In this article, I will show you how to request Kontent.ai Delivery API in Node.js and provide you with a fully functioning code example.

Request Kontent.ai Delivery API in Node.js

See live demo on Runkit.

Step by step tutorial

We will use promises in this example. What we need first are npm packages that will help us with that:

  • request
  • request-promise
npm install request
npm install request-promise

Then require both packages in your code:

const request = require('request'),
    requestPromise = require("request-promise");

Now we define a class with Project ID and Preview API Key that represent your Kontent.ai project:

class Delivery {
    constructor(projectID, previewKey) {
        this.projectID = projectID;
        this.previewKey = typeof previewKey === 'undefined' ? null : previewKey;
    }
}

The class will contain the getContent method that requests the Kontent.ai storage and gets content from your project:

class Delivery {
    constructor(projectID, previewKey) {
        this.projectID = projectID;
        this.previewKey = typeof previewKey === 'undefined' ? null : previewKey;
    }
    
    // Param represents Kentico Kontent filtering url parameters 
    // isPreview represents boolean flag that defines whether you want preview content or not
    getContent(param, isPreview) {
        // Set default state if parameters are not provided
        if (typeof param === 'undefined') {
            param = '';
        }

        if (typeof isPreview === 'undefined') {
            isPreview = false;
        }
        
         // Create options that will represent your request to the Kentico Kontent storage
        let options = Delivery.getOptions(param, this.projectID, this.previewKey, isPreview);

        // Request the Kentico Kontent storage and get content from it
        return Delivery.getRawData(options);
    }
}

We call 2 helper methods in the getContent method:

  • getRawData
  • getOptions

 Let's see what they do:

class Delivery {
    constructor(projectID, previewKey) {
        this.projectID = projectID;
        this.previewKey = typeof previewKey === 'undefined' ? null : previewKey;
    }
    
    getContent(param, isPreview) {
        // Set default state if parameters are not provided
        if (typeof param === 'undefined') {
            param = '';
        }

        if (typeof isPreview === 'undefined') {
            isPreview = false;
        }
        
        let options = Delivery.getOptions(param, this.projectID, this.previewKey, isPreview);

        return Delivery.getRawData(options);
    }

    // Return promise with object obtained from the Kentico Kontent storage
    static getRawData(options) {
        return requestPromise(options).catch(console.error);
    }

    // Return options for the request
    // Structure of the options object is defined by the request-promise package (https://www.npmjs.com/package/request-promise)
    static getOptions(param, projectID, previewKey, isPreview) {
        let options = {
            uri: Delivery.getDeliveryUrl(projectID, isPreview) + param,
            json: true,
            simple: false
        };

        // If we want to preview our content we need to send an authorization header as well
        if (isPreview && previewKey !== null) {
            options.headers = {
                Authorization: 'Bearer ' + previewKey
            }
        }

        return options;
    }
}

In the getOptions method, we call one more helper method - getDeliveryUrl. Let's complete that:

class Delivery {
    constructor(projectID, previewKey) {
        this.projectID = projectID;
        this.previewKey = typeof previewKey === 'undefined' ? null : previewKey;
    }
    
    getContent(param, isPreview) {
        if (typeof param === 'undefined') {
            param = '';
        }

        if (typeof isPreview === 'undefined') {
            isPreview = false;
        }
        
        let options = Delivery.getOptions(param, this.projectID, this.previewKey, isPreview);

        return Delivery.getRawData(options);
    }

    static getRawData(options) {
        return requestPromise(options).catch(console.error);
    }

    static getOptions(param, projectID, previewKey, isPreview) {
        let options = {
            uri: Delivery.getDeliveryUrl(projectID, isPreview) + param,
            json: true,
            simple: false
        };

        if (isPreview && previewKey !== null) {
            options.headers = {
                Authorization: 'Bearer ' + previewKey
            }
        }

        return options;
    }

    // Return Kentico Kontent url that should be requested
    static getDeliveryUrl(projectID, isPreview) {
        let url = '';
        
        // If we want to preview our content we need request a slightly different url
        if (isPreview) {
            url = 'https://preview-deliver.kontent.ai/' + projectID + '/items';
        } else {
            url ='https://deliver.kontent.ai/' + projectID + '/items';
        }
        
        return url;
    }
}

At this stage, we have the class and all methods in place. See the usage:

// Initialize Delivery with Project ID and Preview API Key
let kenticoKontentProject = new Delivery('2548121d-cad8-4458-a910-5e4b54cb0956', 'ew0KICAiYWxnIjogIkhTMjU2IiwNCiAgInR5cCI6ICJKV1QiDQp9.ew0KICAidWlkIjogInVzcl8wdlVJVzkwTnRQSVNxNm1GSDN2ZFhiIiwNCiAgImVtYWlsIjogImhlbGxvQG1pbGFubHVuZC5jb20iLA0KICAicHJvamVjdF9pZCI6ICIyNTQ4MTIxZC1jYWQ4LTQ0NTgtYTkxMC01ZTRiNTRjYjA5NTYiLA0KICAianRpIjogInhrU1BLUjlzbzgxSV9rel8iLA0KICAidmVyIjogIjEuMC4wIiwNCiAgImdpdmVuX25hbWUiOiAiTWlsYW4iLA0KICAiZmFtaWx5X25hbWUiOiAiTHVuZCIsDQogICJhdWQiOiAicHJldmlldy5kZWxpdmVyLmtlbnRpY29jbG91ZC5jb20iDQp9.PpBh6wTk57e1_tPHzROiqWPTpr3IjrEoGN8J4rtfPIg');

// Request the Kentico Kontent storage with filtering url parameters and a boolean flag defining whether you want preview content or not
kenticoKontentProject.getContent('?system.type=hello_world', true)
    .then(console.log) // Show results
    .catch(console.error); // Or error

Full code example

Just copy and paste it into your project.  Happy requesting! 

const request = require('request'),
    requestPromise = require("request-promise");

'use strict';

/**
 * Initilizes class with Project ID and Preview API Key that represent a Kentico Kontent project.
 * @constructor Delivery
 * @param {string} projectID Project ID.
 * @param {string} previewKey Preview API Key.
 * @example
 * var project = new Delivery('82594550-e25c-8219-aee9-677f600bad53', 'ew0KICAiYWxnIjo...QvV8puicXQ');
 */
class Delivery {
    constructor(projectID, previewKey) {
        this.projectID = projectID;
        this.previewKey = typeof previewKey === 'undefined' ? null : previewKey;
    }
    
    /**
     * Returns promise with data from the Kentico Kontent storage specified by the passed query string.
     * @method getContent
     * @param {string} params string that contains filtering URL parameters that are used for requesting Kentico Kontent storage,
     * @param {boolean} isPreview Flag that controls whether only published or all items should be requested.
     * @return {promise} with object obtained from the Kentico Kontent storage.
     * @example
     * // returns
     * // {items: [...], modular_content: {...}, pagination: {...}}
     * project.getContent('?system.type=homepage')
     */
    getContent(param, isPreview) {
        if (typeof param === 'undefined') {
            param = '';
        }

        if (typeof isPreview === 'undefined') {
            isPreview = false;
        }

        let options = Delivery.getOptions(param, this.projectID, this.previewKey, isPreview);

        return Delivery.getRawData(options);
    }
    
    
    /*
     * Helper methods section
     */
    
    // Returns promise with object obtained from the Kentico Kontent storage.
    static getRawData(options) {
        return requestPromise(options).catch(console.error);
    }
    
    // Returns URL that should be requested.
    static getDeliveryUrl(projectID, isPreview) {
        let url = '';
        
        if (isPreview) {
            url = 'https://preview-deliver.kontent.ai/' + projectID + '/items';
        } else {
            url ='https://deliver.kontent.ai/' + projectID + '/items';
        }
        
        return url;
    }
    
    //Returns options for the request.
    static getOptions(param, projectID, previewKey, isPreview) {
        let options = {
            uri: Delivery.getDeliveryUrl(projectID, isPreview) + param,
            json: true,
            simple: false
        };

        if (isPreview && previewKey !== null) {
            options.headers = {
                Authorization: 'Bearer ' + previewKey
            }
        }

        return options;
    }
};


/*
 * Usage
 */
     
// Initialize Delivery with Project ID and Preview API Key
let kenticoKontentProject = new Delivery('2548121d-cad8-4458-a910-5e4b54cb0956', 'ew0KICAiYWxnIjogIkhTMjU2IiwNCiAgInR5cCI6ICJKV1QiDQp9.ew0KICAidWlkIjogInVzcl8wdlVJVzkwTnRQSVNxNm1GSDN2ZFhiIiwNCiAgImVtYWlsIjogImhlbGxvQG1pbGFubHVuZC5jb20iLA0KICAicHJvamVjdF9pZCI6ICIyNTQ4MTIxZC1jYWQ4LTQ0NTgtYTkxMC01ZTRiNTRjYjA5NTYiLA0KICAianRpIjogInhrU1BLUjlzbzgxSV9rel8iLA0KICAidmVyIjogIjEuMC4wIiwNCiAgImdpdmVuX25hbWUiOiAiTWlsYW4iLA0KICAiZmFtaWx5X25hbWUiOiAiTHVuZCIsDQogICJhdWQiOiAicHJldmlldy5kZWxpdmVyLmtlbnRpY29jbG91ZC5jb20iDQp9.PpBh6wTk57e1_tPHzROiqWPTpr3IjrEoGN8J4rtfPIg');

// Request the Kentico Kontent storage with filtering url parameters and a boolean flag defining whether you want preview content or not
kenticoKontentProject.getContent('?system.type=hello_world', true)
    .then(console.log) // Show results
    .catch(console.error); // Or error

Or see the live demo on Runkit.

If you are looking for code that is able to make multiple requests at a time read the following article: Multiple requests to Kontent.ai Delivery API in Node.js

Further reading

all posts