a blog for those who code

Wednesday, 3 February 2016

Simple RESTful API in Nodejs

In this post we are going to discuss about how to create simple RESTful API in Node.js. REST stands for Representational State Transfer. REST is an architecture that allows communication between client and server through a uniform interface. RESTful applications use HTTP requests to post data, get data or delete data.

We will be using Express framework to create RESTful API. Express is a minimal and flexible Node.js web application framework that provides a robust set of features to develop web and mobile applications. It is one of the most used web framework and some of the popular web application are using this framework. For installation and setup please refer - Getting Started with Express - Installation and Setup. We will also install body-parser module which will allow our API to process POST requests.

Now lets create our app.js file which is a wrapper for all server configuration as shown below

var express = require('express');
var bodyParser = require('body-parser');
var app = express();

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));

var routes = require('./routes/index')(app);

var server = app.listen(5000, function () {
  console.log('Listening on port ' + server.address().port)
});

In the above code we are including two packages and configuring express to be used in our code. Then we are configuring body-parser to accept JSON and URL encoded values. We are then referring to /routes/index where we will have all the API endpoints. At last we are starting the server which will listen for requests on port 5000.

Now lets create our index.js file

var router = function (app) {
  app.get('/', function(request, response) {
    response.send('Creating RESTful API');
  })
}
module.exports = router;

In the above code we at first getting app variable which is being passed from app.js and using it to create routes and then we are exporting the router variable to be used anywhere in t project. So when the root of the application i.e. (http://localhost:5000/) is requested the text "Creating RESTful API" will be returned.

Now we will create some routes which are actually helpful and can be tested through Postman.

var router = function (app) {
  app.get('/user', function(request, response) {
    response.send({"user": "CodingDefined", "url": "www.codingdefined.com"});
  })
}
module.exports = router;

Now we will test our API using Postman.It will simply send HTTP requests to a URL. All we need to do is to enter your route URL and select an HTTP verb. You will get an output as shown below


In our next post we will show you how to create RESTful API using MongoDB database. Please Like and Share the CodingDefined Blog, if you find it interesting and helpful.

No comments:

Post a Comment

Contact Us

Name

Email *

Message *

Sponsers

Best Hosting Plans

CC License