Introduction to REST API in NoSQL Database - NosDB

With the emergence of web services, user applications have been able to communicate with remote data sources without having to rely on discrete platforms. Because of this, numerous clients, irrespective of their environment, are able to update and retrieve user data effectively. One such type of web service is REST. REpresentational State Transfer (REST) uses HTTP as the medium to communicate with a data source and returns results in the form of JSON. It depends on resources which are uniquely represented by URLs and normally supports the four basic HTTP verbs: GET, POST, PUT and DELETE.

Since we want our databases to be easily accessible via applications (like web or mobile) and not be restricted by platform constraints, NosDB provides a ready-to-publish-in-production REST API in addition to the existing NosDB clients (.NET and JAVA). This way, languages like JavaScript, Python, and Ruby-on-Rails can access NosDB without having to implement any communication protocols.

In previous articles, the NosDB client API and server side APIs were described in detail. The goal of this article is to present an introductory walk-through regarding the use of REST with NosDB.

Configuring and Deploying the NosDB REST API

Before delving into the world of REST-based programming, you need to ensure that your environment is suitably configured. Generally, the installation setup of NosDB automatically creates a new application pool and deploys REST API as an application in the default website on your systems provided that the following conditions are duly met:

To verify if the installation has successfully setup the required REST environment, open IIS Manager -> Sites. Under the Default Web Site tab, you should be able to see the following two applications:

  • nosdbdata

  • nosdbmgmt

If you are unable to find the packages as mentioned above, you need to configure a few things and deploy them manually instead.

Manual Deployment

To begin manually deploying the REST API, make sure that your environment is set according to the aforementioned conditions because they are mandatory for installing REST.

You can skip this section if your REST API deployment was successful during the NosDB setup installation process.

Now, follow the example below to deploy the packages manually:

  • Open the IIS Manager and add an application as shown in the screen shot below:



  • A window will appear in response to the actions above, asking for an Alias and the path of the Application. Browse for the desired REST API package in the INSTALLATION DIRECTORY, add an Alias and the Application Pool:


Having done that, you can test the deployed package by right-clicking on the application and opting to Browse. In case you are faced with an error after this step, ensure that the Connection String in the web.config file of the application package has the correct format.

Moreover, you might also need to make sure that the NosDB REST API's application pool does not run on the Local System account to avoid any security error. To resolve this issue, do the following:

  • Open the IIS manager and look for the Application Pools section. Find the NosDBRESTAPIPool from the list of pools that appear and go to the Advanced Settings as shown below:



If your system is running with the LocalSystem identity, it should appear as shown in the screenshot below:



If this is the case, reconfigure the Application Pool Identity by setting the credentials following the steps below:

  • Go to the Identity settings and choose Custom Account:



  • Set the user name and the password for the custom account:

This should resolve the security issues (if any) that may arise.

You can always refer to the REST API logs in the INSTALLATION DIRECTORY in case you come across any other kind of errors while installing the package.

Using NosDB REST API

Once you are done installing and configuring the REST environment, it's time to explore some of the exciting features that NosDB offers. But, before that you need a working database. If you don't have an existing NosDB database, you can create one using either the NosDB Management Studio or PowerShell. If you need help with this process, refer to the Introduction to NoSQL Database with NosDB blog post

Once all is set, you can proceed further to begin using REST. The simplest way to test the REST API is through the web browser using a URL.

A URL consists of the following:

  • The database type (clustered or stand-alone),

  • The database name,

  • The collection name.

For example, if you wish to access the data of the entire 'products' collection from the 'northwind' database, write the following HTTP request in your web browser:

  • http://localhost/nosdbdata/clustered/northwind/products

Or if you are looking for a specific object against a key, try the following:

  • http://localhost/nosdbdata/clustered/northwind/products ('key1')

As mentioned earlier in this article, the REST API works with four verbs (GET, PUT, POST and DELETE) which, if defined in the most general of terms, are the basic CRUD operations imperative for operating on a database.

If we take the POST verb as an example here, its characteristics state that it is vital to add the POST data to the request when making use of this verb. Obviously, using the POST verb without any data doesn't make any sense, does it? Therefore, there are tools and web browser extensions developed for this very purpose which can help test the API by adding headers and post data to your requests.

As you already know that REST is platform independent, select the language of your choice to access the NosDB REST API package. In this tutorial, I am working with Node.js to demonstrate the use of REST API and NosDB. You can, of course, choose whatever language works well for you.

Insert a document in NosDB via REST API:

Since we already discussed the POST verb earlier, let's insert a JSON document into our NosDB database using POST.

First, we construct an HTTP request and add the JSON document for insertion to it:


var httprequest = require('request');
var data = "{'ProductID':1235, 'ProductName': 'Chai', 'UnitPrice': 34.95}";
var options = {
	url: 'http://localhost/nosdbdata/' + collection,
	method: 'POST',
	headers: {
		'Content-Type': 'application/json'
	},
	body: data // this is json data to insert
};

Next, we send the request to the server with a response callback as shown below:


var resp = httprequest.post(options, function(error, response, body) {
    if(!error) {
        console.log(body);
        
        //Send the response back.
        res.writeHead(200, {'Content-Type': 'application/json'});
        res.end(body);
    } else {
    	console.log("Error: " + error);
    }
});

Executing this request as shown in the code snippet above should insert the document into your database.

For help regarding the remaining verbs, you can refer to the CRUD Operations section of REST based APIs in the NosDB Programmer's Guide.

Query NosDB using REST:

It's no fun working with databases, if you can't query your data. Moreover, the GET verb provides limited flexibility in terms of filtering data. Therefore, to enhance productivity, NosDB also supports querying data through REST.

There are two ways provided by NosDB through which you can query your data:

  • Querying through URLs

  • Querying through the POST verb

To query through URLs, use the standard OData operators provided. With the POST verb feature, you can query data using the extended version of SQL that NosDB provides. You can refer to the SQL cheat sheet to explore the features provided by NosDB.

As an example, here is how you can run a simple query using the POST verb. For more in-depth knowledge regarding REST-related querying you can refer to the Querying in REST section of 'REST based APIs' in the NosDB Programmer's Guide.

To add data to the database through querying, you are required to do the following:

  • Create a request with method POST and in the post data add a document with SQL Query in it. Note that you have to use contentType: "application/nosquery", to make the REST API query NosDB.

  • NosDB query result is sent to the client application in the form of chunks; you have to call the Next Chunk call using the REST API with contentType: "application/getchunk" to bring in the next data chunk.

In case the application is unable to get the next reader chunk using the "getchunk" command within 30 seconds, the reader will expire itself and you will have to re-query to get the result. This expiration timeout, however, is configurable through the web.config file of the REST API package.

  • You create an HTTP request as the first step with the desired SQL query as shown:


var httprequest = require('request');
var query = "{'Query':'SELECT CategoryName FROM Categories'}";

var options = {
    url: 'http://localhost/nosdbdata/' + collection,
    method: 'POST',
    headers: {
    	'Content-Type': 'application/nosquery'
    },
    body: data // this is json data to insert
};

Next, we make the request to the server with a response callback:

var resp = httprequest.post(options, function(error, response, body) {
    if(!error) {
    	console.log(body);
    	
        //Send the response back.
    	res.writeHead(200, {'Content-Type': 'application/json'});
    	res.end(body);
    } else {
    	console.log("Error: " + error);
    }
});

This way, your query will be executed and will return the filtered results (if it finds any) in the response variable.

With this, we reach the end of this introductory walk-through. By supporting REST, NosDB provides its users with a great opportunity to explore the database solution features without any platform restrictions. You, as a user, can work with your choice of language and develop various applications using a NosDB database as your primary data storage. For further guidance, you can always refer to the official NosDB product page.