Validating POST Request – Building Restful APIs using Express: Part 7

2 min read

As part of best practices in building web services that will be used in production, it is important to have a validation mechanism in place. This mechanism will validate or invalidate inputs from client applications before hitting the server.

In this tutorial, we will explore different ways of validating user inputs when building Restful APIs with the Express Framework.

Using series of ‘if’ statements

Let’s modify our online radio application POST endpoint that we wrote in Part 6 of this series.

app.post('/api/v1/stations', (req, res) => {
    if (!req.body.name || req.body.name.length < 5) {
       return res.status(400).send('Name is required, with a 
       minimum of 5 characters');
    }

    const station = {
       id: stations.length + 1,
       name: req.body.name
    };
    
    stations.push(station);
    res.send(station);
});

The validation logic on line 36 above, checks whether the req.body.name exists or not. It also checks if the number of characters in req.body.name is less than 5 or not. In case the request doesn’t meet the conditions on line 36, the server will respond with a standard status code of 400. This indicates a Bad Request.

image of user input for a post request in postman
image of server response from a bad request

Using a Node Package for Validation

When building real world production applications, it is likely to be working with objects that are more complex than what we have above. Hence, there is a need to leverage on some Node packages that are available on NPM registry, mainly for user input validations. A popular Node package for user input validation is joi. You can read more about the joi package here.

Using the joi Validation Package

In other to make use of the joi package in our node application, we need to install it using the command below. The installation should happen inside the project folder.

npm i joi
image showing the installation of the joi package in node application

Secondly, we need to make few changes to the index.js file of the as follows.

  • Load the joi package using the require function. The joi module returns a class.
  • Store the result in a constant called Joi. We capitalized the constant name (Joi) because classes in javascript follows the pascal naming convention.
  • Next, we need to define a schema. In other words, defining the shape of the object. This includes the object property, type of the property. For example, we need to specify if property will be an email, a string, numbers, required e.t.c. 
const Joi = require('joi');

app.post('/api/v1/stations', (req, res) => {
    const schema = {
       name: Joi.string().min(5).required()
    };

    const result = Joi.validate(req.body, schema);

    if (result.error) {
       return res.status(400).send(result.error);
    }
});

The complete index.js file for our application is shown below, together with the use of the joi package for user input validation.

joi is easy to use and understand. From the above source code, we have a schema stating that the name of the radio station should be a string, with minimum of 5 characters, and should be required. Line 43 validates what is in the request body, using the schema on line 37 – 41. The validate method returns an object, stored in a constant called result. The object consists of two properties: error and value. The error property will be null if the validation is ok.

Testing in PostMan

Now, let’s test our joi schema in PostMan to see the error property when validation isn’t met.

image of a post request by user in postman
server response with an error message from joi user validation package

The response object is too complex and we don’t need to send all those information to the client. Instead, we need to simplify the error response by modifying line 46 to be:

return res.status(400).send(result.error.details[0].message);

With the code above, we are only accessing the first element in the details array; which happens to be the message property. Recall that array element starts from the 0 index.

Let’s test this again in POSTMAN and see the result.

image of a simplified error message from the joi package

HTTP Put and Delete Requests – Building Restful APIs…

In order to update or delete an information, we need have the object ID. Let's analyze the code block below for handling HTTP Put...
appdevchannel
1 min read

Building Restful APIs using Express: Part 6 – POST…

In this section, we will discuss how to use http POST request to create a new radio station. We will test endpoint using the...
appdevchannel
2 min read

Restful APIs using Express: Part 5 – GET Request

In this post, I explained the steps required to handle http GET request in Node - Express application. Learn more as we build an...
appdevchannel
1 min read

Leave a Reply

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

Never miss a tutorial from us, get weekly updates in your inbox.