01 logo

How to implement API request architecture with Joi verification in NodeJS and Express

Here is the step-by-step guide to implement API Request Schema with Joi Validation in NodeJS and Express. Let’s validate the request data using Joi validation

By BacancyPublished 3 years ago 3 min read
Like

When you use an endpoint that anticipates user information, such as username, age, PIN, status, and phone number, the user mistakenly enters numeric data for the user name and expects to use alphabetic data. When expecting a specific data format, enter an invalid PIN or invalid date of birth in the corresponding field. You don't want to create unnecessary data! Therefore, you can perform some data validation to ensure that you get the correct format. To verify the data, you can code all the logic manually or use a verification library/package. This tutorial will help you to know about Joi verification for implementing it in Node.js and Express.

Joi:

Joi is the best known, most efficient and most widely used package for describing and validating object schemas. Joi allows developers to create JavaScript schemes and ensure that the application will accept accurately formatted data.

Some of the benefits that joi has are as follows:

  • Implementation made easy to learn.
  • Data verification package that is well-known and widely used.
  • Support architecture-based verification.

Now we will create a simple demo application.

Implement the steps of the Joi verification API request scheme for Node.js and Express.

1. Initial structure :

Roots should be build in this first step

mkdir JoiValidation

cd JoiValidation

2. Define the package file:

Run the command mentioned below:

npm init

3. Install all the dependencies:

5 dependencies should be installed 1st to install joi validation, and for that, you have to run the command that is mentioned below:

npm install --save bcryptjs dotenv express joi mongoose

These are the 5 dependencies:

  • bcryptjs: Used to store clear text passwords in hashed passwords for security reasons.
  • dotenv: this Module does not need any possession. It is used to fill the environment variables from an .env file into the .env.express
  • Expression: This is a popular Node.js framework for web application development. It has powerful web/mobile application building functions.
  • Joi: This is a target pattern classification language used to verify JS objects. Using Joi, we can quickly create patterns for JS objects and verify essential data.
  • Mongoose: a tool for object modelling designed for asynchronous environments.

4. You can Connect your database by creating a server:

Generate a file in the root directory to store our background variables. Two variables need to be created in this file: the first is PORT, and the other is MONGO_URI for your link to the database. Then enter the relevant value for both variables. When you're done with that, create an src folder in the root directory. It contains various folders such as Drivers, Models, Database, Paths, and Utilities.

5. Connection file:

const mongoose = require('mongoose');

mongoose.connect(process.env.MONGO_URI, {

useNewUrlParser: true,

useUnifiedTopology: true

}).then(() => {

console.log('Connection successful!');

}).catch((e) => {

console.log('Connection failed!');

})

6. Server file creation:

require("dotenv").config();

require('./db/conn');

const express = require("express");

const app = express();

const port = process.env.PORT;

app.use(express.json({ limit: "10MB" }));

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

app.listen(port, () => {

console.log(`Server is running at ${port}`);

});

Now it is time to check whether the connection has established properly or not for that 2 scripts will need to be operated:

Package.json

"dev": "nodemon src/server.js",

"start": "node src/server.js"

dev – in your system you have to pre-installed nodemon and for that dev is useful

Start – when you want to to run a server without using nodemon.

You can test it with the help of this command:

npm start

After this, you will get a message, and thus your connection has been installed successfully.

To conclude, this was the tutorial about implementing Joi Validation in NodeJS and Express. If you want to learn more about this technology or this tutorial, you can always refer to the link mentioned above. For installing node js in your system, you should hire a top-notch development company with dedicated developers and create unique websites for you.

apps
Like

About the Creator

Bacancy

A Leader in Agile and Lean Software Development

Reader insights

Be the first to share your insights about this piece.

How does it work?

Add your insights

Comments

There are no comments for this story

Be the first to respond and start the conversation.

Sign in to comment

    Find us on social media

    Miscellaneous links

    • Explore
    • Contact
    • Privacy Policy
    • Terms of Use
    • Support

    © 2024 Creatd, Inc. All Rights Reserved.