{{announcement.body}}
{{announcement.title}}

API Schema Validation Using @Hapi/joi Schema NPM

DZone 's Guide to

API Schema Validation Using @Hapi/joi Schema NPM

In this article, we will see how @hapi/joi can be used to validate the data passed on to the API.

Free Resource

Image title

@Hapi/joi Schema NPM

Many product companies are taking an API First approach. The whole idea is to enable the end product to be consumed by mobile devices or client applications.

It is very important to develop API’s that are consistent and reusable.

We need to ensure that the right data is given as input to the API endpoint. We don’t want bad data to enter into our application.

In this article, we will see how @hapi/joi can be used to validate the data passed on to the API.

You might also like:  Schema Validation Filter (XML Schema Validation)

Note: I assume you have knowledge of API development using Node.js and Express framework.

You can install the package using: npm i @hapi/joi

In your existing Rest API project, Add apiSchema and a middleware folder [Make use of the existing one if you already have]

apiSchema folder is used to collate all the schema files w.r.t each object. These files will be used to validate against the incoming data by passing this schema file as a parameter to the middleware.

Let’s consider we are going to validate inputs for the signup and login API.

  • Create an userSchema.js file within apiSchema folder
const joi = require('@hapi/joi')

module.exports.SignUp = joi.object({
Name: joi.string().required(),
Email: joi.string().required()
});

module.exports.Login = joi.object({
Name: joi.string().required(),
Email: joi.string().required()
});


  • Import hapi/joi.
  • Joi.object will consist of the key and value. This is the place where we say which key, what type of value is allowed, and if it is mandatory or not.
  • All schema validation w.r.t users will be part of the userSchema.

Go to your application’s middleware folder.

Create a file called schemaValidation.js.

  • Import hapi/joi.

We need to implement 2 steps:

  • Take the schema created in apiSchema as input and validate.
  • Respond back by moving to the next middleware or controller or by throwing an error message.

Let’s consider that we take input as part of our request body.

defaultServerResponse: {
status: 400,
message: '',
body: {}
}

module.exports.validateBodySchema = (schema) => {
return (req, res, next) => {
let response = {... defaultServerResponse}
const result = checkSchema(req.body, schema)
if(result){
response.body = result;
response.message = ‘Invalid Fields’;
return res.status(status).send(response)
    }
return next();
}
}


The above code takes schema as an input and calls checkSchema by passing the req.body as well as the input schema.

const checkSchema = (data, schema) => {
const result = schema.validate(data, { convert: false });
if (result.error) {
const errorDetails = result.error.details.map(value => {
return {
error: value.message,
path: value.path
};
});
return errorDetails;
}
return null;
}


In checkSchema, we simply use the .validate method.

The validate method is applied to the userSchema of the apiSchemas folder. Req.body is passed as data.

Note: Hapi/joi considers “1” as Number. If you don’t want any default behavior like that set, {convert: false}); in the validate method.

Finally, we need to ensure that we have included our validation middleware in our routes.

router.post('/signup',joiSchemaValidation.validateBodySchema(userSchema.SignUp),

userController.SignUp);

router.post('/login',joiSchemaValidation.validateBodySchema(userSchema.Login),

userController.Login);

If the validation is successful, it moves to the controller.

Hope this helps.

Further Reading

Mule 4: JSON Schema Validation

Reducing Integration Hassles With JSON Schema Contracts

Topics:
node.js ,api ,npm

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}