Build a RESTful API using Node.js

REpresentational State Transfer in short REST is web standard based architecture that mainly uses HTTP Protocol. In the RESTful architecture, Server simply provides access to the resources and client accesses them using HTTP protocol. In this article, we will build RESTful API using Node.js

Software used

Read here How to get started with Node.js

Adding Packages

As listed above we are using express to create our webserver, mysql as our database. Also as we are going to process some post request we will add support using body-parser and cors.

For our example, we are trying to use ES6 so we will also add Babel to our dev dependencies.

Creating Server

As we are using Express, we will use an exported express app to the create server.

You can see that we have some imports from api folder and we are using them in our express app. We will get there shortly.

Below is how our server is created. We will use any port that has been configured in system variables or if that is not available then we will use 6001 by default.

Create Database Component

With Mysqljs npm package, connecting to the database is very simple. Below is our database component and a utility method to run a query and send results back.

Please note that we are simply exporting the utility method and not the entire component.

Adding APIs

For our demonstration purpose, we will create table products and perform operations on it like adding a product, deleting a product, listing product etc through our RESTful API using Node.js application.

For simplicity, we will also add a domain object and some utility methods as shown below-

Product API

As shown above, the API defines an express Router. The router is then configured to handle get and post methods for product operations.

If you note, in our app.js we have configured urls to be handled as

This means, all the urls that are like http://localhost:6001/products will be handled by the product API we have imported. The rest of the url is processed and matched in methods defined in the API.

Testing the API

For testing of our API we will use Postman. Check below screens on how our RESTful APIs work.

Adding a Product

Listing Products

Deleting a Product

Find a Product

Conclusion

In this article, we have seen how we build a RESTful API using Node.js. Node.js has made JavaScript programming so popular and implementing full-featured applications using it has become simple and elegant.

The complete code can be downloaded from our git repository. Please feel free to try out and let me know your comments or issues.

Download Code

Add a Comment

Your email address will not be published. Required fields are marked *