Quickstart: QnA Maker REST APIs for Node.js

Get started with the QnA Maker REST APIs for Node.js. Follow these steps to try out the example code for basic tasks. QnA Maker enables you to power a question-and-answer service from your semi-structured content like FAQ documents, URLs, and product manuals.

Use the QnA Maker REST APIs for Node.js to:

  • Create a knowledge base
  • Replace a knowledge base
  • Publish a knowledge base
  • Delete a knowledge base
  • Download a knowledge base
  • Get status of an operation

Reference documentation | Node.js Samples

Prerequisites

Setting up

Create a QnA Maker Azure resource

Azure Cognitive Services are represented by Azure resources that you subscribe to. Create a resource for QnA Maker using the Azure portal or Azure CLI on your local machine.

After getting a key from your resource, create environment variables for the resource, named QNAMAKER_RESOURCE_KEY and QNAMAKER_AUTHORING_ENDPOINT. Use the key and host values found in the Resource's Quickstart page in the Azure portal.

Create a new Node.js application

In a console window (such as cmd, PowerShell, or Bash), create a new directory for your app, and navigate to it.

mkdir myapp && cd myapp

Run the npm init -y command to create a node package.json file.

npm init -y

Add the reqeuestretry and request NPM packages:

npm install requestretry request --save

Code examples

These code snippets show you how to do the following with the QnA Maker REST APIs for Node.js:

Add the dependencies

Create a file named rest-apis.js and add the following requires statement to make HTTP requests.

const request = require("requestretry");

Add Azure resource information

Create variables for your resource's Azure endpoint and key. If you created the environment variable after you launched the application, you will need to close and reopen the editor, IDE, or shell running it to access the variable.

const resourceKey = process.env.QNAMAKER_RESOURCE_KEY;

// "https://{region}.api.cognitive.microsoft.com/qnamaker/v4.0"
const resourceAuthoringEndpoint = process.env.QNAMAKER_AUTHORING_ENDPOINT;

Create a knowledge base

A knowledge base stores question and answer pairs, created from a JSON object of:

  • Editorial content.
  • Files - local files that do not require any permissions.
  • URLs - publicly available URLs.

Use the REST API to create a knowledge base.

const createKb = async () => {

    try{
  
        // Dictionary that holds the knowledge base.
        // The data source includes a QnA pair with metadata, the URL for the
        // QnA Maker FAQ article, and the URL for the Azure Bot Service FAQ article.
        const kb_model = {
            "name": "QnA Maker FAQ",
            "qnaList": [
                {
                    "id": 0,
                    "answer": "You can use our REST APIs to manage your Knowledge Base. See here for details: https://westus.dev.cognitive.microsoft.com/docs/services/58994a073d9e04097c7ba6fe/operations/58994a073d9e041ad42d9baa",
                    "source": "Custom Editorial",
                    "questions": [
                        "How do I programmatically update my Knowledge Base?"
                    ],
                    "metadata": [
                        {
                            "name": "category",
                            "value": "api"
                        }
                    ]
                }
            ],
            "urls": [
                "https://docs.microsoft.com/en-in/azure/cognitive-services/qnamaker/faqs"
            ],
            "files": []
        };        

        const request_params = {
            method: 'POST',
            uri: resourceAuthoringEndpoint + "/knowledgebases/create",
            headers: {
                'Content-Type': 'application/json',
                'Content-Length': kb_model.length,
                'Ocp-Apim-Subscription-Key': resourceKey
            },
            body: kb_model,
            json: true
        };

        const response = await request(request_params);

        if(response.statusCode != "202") throw Error(response.statusCode);

        console.log(response.body.operationId);
        console.log(response.body.operationState); 
        console.log(pretty_print(response.body));

        return response.body;

    } catch(err) {
        console.log(err);
    }
}

Replace a knowledge base

Use the REST API to replace a knowledge base.

const replaceKb = async (kbId) => {

    try{
        const newKbDefinition = {
            'qnaList': [
            {
                'id': 0,
                'answer': 'You can use our REST APIs to manage your Knowledge Base. See here for details: https://westus.dev.cognitive.microsoft.com/docs/services/5a93fcf85b4ccd136866eb37/operations/5ac266295b4ccd1554da7600',
                'source': 'Custom Editorial',
                'questions': [
                'How do I programmatically update my Knowledge Base?'
                ],
                'metadata': [
                {
                    'name': 'category',
                    'value': 'api'
                }
                ]
            }
            ]
        };

        const request_params = {
            method : 'PUT',
            uri: resourceAuthoringEndpoint + "/knowledgebases/" + kbId,
            headers : {
                'Content-Type' : 'application/json',
                'Content-Length' : JSON.stringify(newKbDefinition).length,
                'Ocp-Apim-Subscription-Key' : resourceKey,
            },
            body: JSON.stringify(newKbDefinition),
            resolveWithFullResponse: true
        };
    
        return await request(request_params);

    } catch (err){
        throw err;
    }    
}      

Publish a knowledge base

Publish the knowledge base. This process makes the knowledge base available from an HTTP query prediction endpoint.

Use the REST API to publish a knowledge base.

var publishKb = async (kbId) => {

    try{

        var options = {
            uri: resourceAuthoringEndpoint + "/knowledgebases/" + kbId,
            method: 'POST',
            headers: {
                'Ocp-Apim-Subscription-Key': resourceKey
            },
            resolveWithFullResponse: true
        };

        return await request(options);

    } catch (err){
        throw err;
    }
};

Download the knowledge base

Use the REST API to download a knowledge base.

const downloadKb = async (kbId) => {

    try{

        // slots: 'test' or 'prod'
        const slot = "test";

        const request_params = {
            method: 'GET',
            uri: resourceAuthoringEndpoint + "/knowledgebases/" + kbId + "/" + slot + "/qna/" ,
            headers: {
                'Ocp-Apim-Subscription-Key': resourceKey,
            },
            resolveWithFullResponse: true
        };


        return await request(request_params);

    } catch (err){
        throw err;
    }
}

Delete a knowledge base

When you are done using the knowledge base, delete it.

Use the REST API to delete a knowledge base.

const deleteKb = async (kbId) => {

    try{
        const request_params = {
            method: 'DELETE',
            uri: resourceAuthoringEndpoint + "/knowledgebases/" + kbId,
            headers: {
                'Content-Type': 'application/json',
                'Ocp-Apim-Subscription-Key': resourceKey,
            },
            resolveWithFullResponse: true
        };

        return await request(request_params);
        
    } catch (err){
        throw err;
    }
}

Get status of an operation

Long running processes such as the creation process returns an operation ID, which needs to be checked with a separate REST API call. This function takes the body of the create response. The important key is the operationState, which determines if you need to continue polling.

Use the REST API to monitor operations on a knowledge base.

const getOperationStatus = async (result) => {

    try{
    
        let response;
        let state = result.operationState;

        while( state==="Running" || state==="NotStarted"){

            const options = {
                method: 'GET',
                uri: resourceAuthoringEndpoint + "/operations/" + result.operationId,
                headers: {
                    'Ocp-Apim-Subscription-Key': resourceKey
                },
                resolveWithFullResponse: true
            };

            let responseFull = await request(options);
            response = JSON.parse(responseFull.body);
            state = response.operationState;

            // artificial retry
            await sleep(3000);
        }

        return response;

    } catch(err) {
        console.log(err);
    }
}

Run the application

Run the application with node rest-apis.js command from your application directory.

node rest-apis.js

Clean up resources

If you want to clean up and remove a Cognitive Services subscription, you can delete the resource or resource group. Deleting the resource group also deletes any other resources associated with it.

Next steps