Skip to main content

Create APIs with Express & Mysql database

 In the previous tutorial, your learnt to create models and migrations to generate schemas in Mysql database and insert sample data using Sequelize. Now move on creating APIs in Express to access data from Mysql database.

In the root folder of the Express project (prod_product), create routes folder and add 

product.routes.js file. 

const db = require("../db/models");
const router = require("express").Router();
const {Op } = require("sequelize");

router.get("/products", function(req,res){
  // get search query
  const q = req.query.search; 
  // define matching conditions
  const condition1 = q ? { title: { [Op.like]: `%${q}%` } } : null;
  const condition2 = q ? { description: { [Op.like]: `%${q}%` } } : null;
  const condition=condition1 && condition2? {[Op.or]:[
    condition1,
    condition2,
  ]}:null;

  // offset and limit - paging 
  const sta=parseInt(req.query.start,10);
  const lim=parseInt(req.query.step,10);
  
  db.Product.findAndCountAll(
    { 
      distinct: true,
      col: 'id', // count column
      include: [
        { model: db.Image, as: 'Images'} // also include relation table
      ],
      where: condition,
      offset: sta,
      limit: lim,
    
    },
    
    
    )
    .then(data => { // return success result
     
      res.status(200).send({message:'success', numrow:data.count, data:data.rows});
 
    })
    .catch(err => {
      res.status(500).send({
        message:
          err.message || "Some error occurred while retrieving products"
      });
    });
});
module.exports = router;

We define one route (products) using get method to fetch records from the Products table. Sequelize provides the FindAndCountAll() method. The function returns all rows that match the conditions defined in where clause. Its also counts the matched rows by ignoring offset and limit.
To include the data from relation table, you need to specify "include" parameter to the function. In the code above, we include data from Images table in products query result. 
The products route allows passing in three query parameters: search, start, and step. The search string allows a client app to filter products by title or description. The start, step, and count will be used in paging functionality.
To allow access to the products route, you need to register it in app.js file as shown below:

prod_product/app.js
const express = require('express');
const app = express();
const bodyParser = require('body-parser');
const cors = require('cors');

app.use(cors()); // allow cross domain access
app.use(bodyParser.json()); // parse request JSON objects to body.req
app.use(bodyParser.urlencoded({extended: true})); //accepts only UTF-8 encoding of the body and supports automatic inflation of gzip and deflate encodings

app.use('/api', require('./routes/product.routes')); // register products route

var port = process.env.PORT || 5000; // server running port
app.listen(port, "0.0.0.0", function() { // listen from any host (0.0.0.0)
  console.log("Listening on Port 5000");
});

console.log('Web Server is listening at port '+ (process.env.port || 5000));

Start Mysql server. Then, from the root folder, execute the following command to start Express server:

node app.js

After the server successfully starts, access the products route as below:
http://localhost:5000/api/products?start=0&step=5
Output:



To filter products by title or description, simply add search string to the request url. For example, to fetch products that contain "Metal Cap", append &search=Metal Cap to the url:
http://localhost:5000/api/_products?start=0&step=5&search=Metal Cap

Comments

Popular posts from this blog

Get start with React

To start web development with React, i recommend you install Node. Node comes with NPM (package manager) helps you easy to add dependencies, create, start, and build your React apps. You can download and install NPM from its official web site: Download NPM . Another useful tool for coder is Visual Studio Code . On my Windows machine, i have installed Node version 16.10.0 with NPM 7.14.0. Now create a project folder and name it react_tutorials in Drive D: or other drive of your choice. Then open the folder in Visual Studio COde (VSC). From the VSC editor, select Terminal. In the terminal, enter the following command to create my-app app in the project folder created above. D:\react_tutorials>npm init react-app my-app After the my-app app is created successfully. You change to my-app folder (cd my-app) . Then You run " npm start " command to start your first react app on browser. React automatically starts on port 3000.

Why React?

React is one of the top UI development frameworks. It is very popular today among web developers around the globe. I love React because of the following things: - It is simple to learn and use. - It is JavaScript library. - It effectively applies changes to a web page without reloading the page while data changed. - It is easy to find problems or errors while you are coding.

React Express & Mysql: Sequelize

Now, you have React project in my-app folder and Express project in prod_project folder. We are going to create back-end APIs that will be accessed by our React app. If you don't have React and Express apps set up, you go to the page Product CRUD Project In the prod_project folder, run the following command to install dependencies that are required to create the APIs on Express server. D:\prod_project> npm install sequelize sequelize-cli mysql2 jsonwebtoken cors body-parser bcrypt sequelize helps us synchronize the models (defined later in our project) with Mysql database. From the models, you can create tables in the database, query, add, update, delete data in the tables. sequelize-cli - Sequelize Command Line Interface helps us create models, migrations, and database. mysql2   is a fast mysql driver to work with mysql database from Express. jsonwebtoken works in user authentication by token for securely transmitting data between our back-end Express and front-end...