title: How to validate API request in Node js
body: <p>I have created a simple API which has all verbs GET, PUT, POST, DELETE, but in this, I want to validate POST data.</p>
  
  <p>I have tried Joi Libary but I did not get the proper way to do it.</p>
  
  <blockquote>
    <p>CodeSnippet of POST Method</p>
  </blockquote>
  
  <pre><code>    appRouter.route('/')
          .post(function (req, res) 
          {            
              if (req.body.ProductName) 
              {
                  conn.connect().then(function () {
                      var transaction = new sql.Transaction(conn);
                      transaction.begin().then(function () {
                          var request = new sql.Request(transaction);
                          request.input("ProductName", sql.VarChar(50), req.body.ProductName)
                          request.input("ProductPrice", sql.Decimal(18, 0), req.body.ProductPrice)
                          request.execute("Usp_InsertProduct").then(function () {
                              transaction.commit().then(function (recordSet) {
                                  console.log(recordSet);
                                  conn.close();
                                  res.status(200).send(req.body);
                              }).catch(function (err) {
                                  console.log("Error in Transaction Commit " + err);
                                  conn.close();
                                  res.status(400).send("Error while inserting data");
                              });
                          }).catch(function (err) {
                              console.log("Error in Transaction Begin " + err);
                              conn.close();
                              res.status(400).send("Error while inserting data");
                          });
  
                      }).catch(function (err) {
                          console.log(err);
                          conn.close();
                          res.status(400).send("Error while inserting data");
                      });
                  })
                      .catch(function (err) {
                          console.log(err);
                          conn.close();
                          res.status(400).send("Error while inserting data");
                      });
              }
              else {
                  res.status(400).send("Error while inserting data");
              }
          });
  </code></pre>
  
  <blockquote>
    <p>Snapshot of Controller</p>
  </blockquote>
  
  <p><a href="https://i.stack.imgur.com/iMR4I.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/iMR4I.png" alt="Controller"></a></p>