Language: EN

montar-un-api-rest-con-nodejs-y-express

Setting up a REST API with NodeJs and Express

In this post we will learn how to set up a REST API for our Web application quickly and easily with NodeJs and the Express.js module.

If you are not yet familiar with NodeJs, the popular server-side technology in Javascript, you should check out this post What is NodeJs and why you should be using it

On the other hand, Express.js (or simply Express) is one of the most well-known modules of Nodejs. Express is a lightweight Open Source framework that provides us with many useful tools to organize our application.

Designing our REST API

First, we are going to outline a design for a simple REST API, which represents the operations that we could have in a real Web application.

This means that we are interested in performing CRUD (Create, Read, Update, Delete) operations on a data repository, which will normally be a database (MSSQL, MySQL, MariaDB, MongoDB), or any other (files, etc).

To map each operation offered by our REST API, we use a combination of HTTP request types, URL parameters, Query parameters, and parameters in the request body.

The following table shows the functions available in our example REST API, the equivalent to functions, and the parameters received by each request.

OperationFunctionRequestUrlParameters
URLQueryBody
ReadGetAllGET./item
GetFilteredGET./item?filter=ABCFilter
GetByIdGET./item/idId
CreateAddPOST./item
UpdateUpdateByIdPATCH./item/idId
ReplaceReplaceByIdPUT./item/idId
DeleteDeleteByIdDELETE./item/idId

Creating our REST API

We create a folder within our projects folder that we will call, for example, ApiRest. Now we install the Express.js module. To do this, from the command prompt, we navigate to the directory we created previously and write

npm install express

Once Express is installed, we create a new file that we will call, for example, App.js. Inside this file we copy the following content

// Load modules and create new application
var express = require("express"); 
var cors = require('cors')
var app = express();
app.use(cors())

var bodyParser = require('body-parser');
app.use(bodyParser.json()); // support json encoded bodies
app.use(bodyParser.urlencoded({ extended: true })); // support encoded bodies

//GetAll
//Example: GET http://localhost:8080/item
app.get('/item', function(req, res, next) {
  if(req.query.filter) {
  next();
  return;
  }
  res.send('Get all');
  console.log('Get all');
});

//GetById
//Example: GET http://localhost:8080/item/10
app.get('/item/:id', function(req, res, next) {
  var itemId = req.params.id;
  res.send('Get ' + req.params.id);
  console.log('Get ' + req.params.id);
});

//GetFiltered
//Example: GET http://localhost:8080/item?filter=ABC
app.get('/item', function(req, res) {
  var filter = req.query.filter;
  res.send('Get filter ' + filter);
  console.log('Get filter ' + filter);
});

//Create
//Example: POST http://localhost:8080/item
app.post('/item', function(req, res) {
  var data = req.body.data;
  res.send('Add ' + data);
  console.log('Add ' + data);
});

//Replace
//Example: PUT http://localhost:8080/item/10
app.put('/item/:id', function(req, res) {
  var itemId = req.params.id;
  var data = req.body.data;
  res.send('Replace ' + itemId + ' with ' + data);
  console.log('Replace ' + itemId + ' with ' + data);
});

//Update
//Example: PATCH http://localhost:8080/item/10
app.patch('/item/:id', function(req, res) {
  var itemId = req.params.id;
  var data = req.body.data;
  res.send('Update ' + itemId + ' with ' + data);
  console.log('Update ' + itemId + ' with ' + data);
});

//Delete
//Example: DEL http://localhost:8080/item
app.delete('/item/:id', function(req, res) {
  var itemId = req.params.id;
  res.send('Delete ' + itemId);
  console.log('Delete ' + itemId);
});
  
var server = app.listen(8080, function () {
    console.log('Server is running..'); 
});

Finally, we run the application with the following command,

node App.js

And we check that it runs correctly.

api-rest-nodejs-express-running

Explaining our REST API code

Let’s explain the code above. First, we have loaded the necessary modules, and created an Express application.

In the rest of the code, we are defining different routes for our application, according to the definition we made in the previous section.

In these functions, we use the ‘request’ object to obtain the parameters that we have passed to the API in the request. Depending on the type of request, we use the appropriate property (params, query, or body).

On the other hand, we use the ‘response’ object to return the results to the client. In this example, we are simply returning a text informing that the corresponding request has been received correctly.

Obviously, this is a very simple example. In a real application, there would be database queries, data operations, validations, etc. But it is enough to show the fundamental aspects necessary to create a REST API.

Finally, in the last block of code we start the application by listening for requests on localhost, port 80.

Testing our REST API

It’s time to test our example REST API. To do this, we will use the Postman program. If you haven’t used Postman yet, we recommend you to check out the post Postman, make HTTP requests and test your REST APIs.

In each request we have the parameters that are used, and an image of the request in Postman (click on the image to enlarge), so that you can test the example REST API.

GetAll

It is a simple GET request to the URL localhost:8080 api-rest-nodejs-express-getall

GetFiltered

GET request to localhost/item?filter=XXX:8080 api-rest-nodejs-express-getfiltered

GetById

GET request to localhost/item/dd:8080 api-rest-nodejs-express-getbyid

Add

POST request to localhost/item, and in the body we would pass an object encoded as Json. In the example, we simply send a text within the “data” property. In a real application, we would send an object with the appropriate properties. api-rest-nodejs-express-addnew

UpdateById

PUT request to localhost/item, and in the body we would pass the Id to replace and the object encoded as Json. api-rest-nodejs-express-updatebyid

DeleteById

DELETE request to locahost/item/id api-rest-nodejs-express-deletebyid