Node Js Validate Express Js Rest API Tutorial

This tutorial helps you learn how to effortlessly validate express REST API data in the Node js application with the help of the express validator package.

We will step by step show you how to set up a node js app from scratch not only but also to validate Node js REST API. We will use express, body-parser, cors and express-validator modules.

Express: A minimal, powerful, yet flexible Node.js web application framework that offers a sturdy set of features for empowering web and mobile application development.

Express-validator: It is a set of express.js middlewares that wraps validator.js validator and provides handy sanitizer functions.

Cors: A node js module that enables CORS with various options.

Body-parser: It is an npm library primarily used for processing data sent through an HTTP request body.

How to Validate Express Rest API in Node Js

  • Step 1: Create Node App
  • Step 2: Install Required Packages
  • Step 3: Build Validation in Node
  • Step 4: Configure Server File
  • Step 5: Run Node Server
  • Step 6: Test Rest API Validation

Create Node App

Open terminal, type the following commmand and hit enter.

mkdir node-demo

Move into the folder using given command:

cd node-demo

In the next step, run npm init command. This will generate the package.json file which contains the project related metadata.

npm init

Make sure to create the app.js file in your node project root. After creating the file, ensure that you added it in the package.json file.

{
  "main": "app.js",
}

Install Required Packages

We have told about every module, regarding why they are used for.

Hence, go ahead and type the provided command; this will install the express, body-parser, cors and most importantly, express-validator modules.

npm install express body-parser cors express-validator

We are aslo installing the nodemon module.

It saves your lot of time by restarting the node app, whenever it detects any change in any file of your node app.

npm install nodemon --save-dev

Build Validation in Node

We will create simple REST APIs; our APIs will allow user registration and user login.

Therefore, we require to create an api-validation.js file and make sure to add the given data into the api-validation.js file.

const { check } = require('express-validator')

exports.registerValidation = [
  check('name', 'Name is requied').not().isEmpty(),
  check('email', 'Please provide email')
    .isEmail()
    .normalizeEmail({ gmail_remove_dots: true }),
  check('password', 'Password should be 4 characters long').isLength({
    min: 4,
  }),
]

exports.signinValidation = [
  check('email', 'Please provide email')
    .isEmail()
    .normalizeEmail({ gmail_remove_dots: true }),
  check('password', 'Password should be 4 characters long').isLength({
    min: 4,
  }),
]

Configure Server File

To configure the server, you have to define the required modules, also import the api validation js and define the named modules for validating the apis.

Now we are ready to configure the node js application server. Hence, go ahead and open the app.js file and insert the given code into the file.

const express = require('express')
const bodyParser = require('body-parser')
const cors = require('cors')
const { registerValidation, signinValidation } = require('./api-validation.js')

const app = express()
app.use(cors())
app.use(express.json())
app.use(bodyParser.json())
app.use(
  bodyParser.urlencoded({
    extended: true,
  }),
)

app.get('/', (req, res) => {
  console.log(res)
})

app.post('/signup', registerValidation, (req, res) => {
  // Code goes here
})

app.post('/signin', signinValidation, (req, res, next) => {
  // Code goes here
})

app.use((err, req, res, next) => {
  console.log(err)
  err.statusCode = err.statusCode || 500
  err.message = err.message || 'Server error'
  res.status(err.statusCode).json({
    message: err.message,
  })
})

app.listen(4000, () => console.log('Server connected on port: 4000'))

Run Node Server

We have prepared the express REST API in the node environment; we have to test the APIs.

Therefore, open the terminal, type the command on the command prompt and press enter to start the node server.

nodemon

Test Rest API Validation

Eventually, we are done with all the formalities. We are only left with testing the apis you. can check how node express REST API validation work.

You must have the Postman app installed on your system; make sure to start the postman app.

http://localhost:4000/signup
http://localhost:4000/signin

Node Js Validate Express Js Rest API Tutorial

Summary

Throughout Node express validation rest API example, we have seen how to validate rest API in node js.

Also, we have learned how to create the simple REST API in node using express and validate REST API using the express-validator library.