REST API with Express.js
MySQL Example

This Example will show you how to make a REST API using Express.js and MySQL.

The database of the example contains two tables: book and user. The user-table will be used to authorize the REST API users. So, in the exercise you will build a login system, so that the credentials will be checked based on the user.

The example will be based on MVC-model.

The application skeleton will be created using express-genarator (https://expressjs.com/en/starter/generator.html).

In an Express application generated with the Express generator, the files inside the routes folder are not actual controllers, but they do play an important role in defining how the application responds to client requests.

These routes files primarily handle routing, meaning they define which function should be executed when a certain URL path is requested. In smaller applications, you might see the request-handling logic written directly in these files. However, in larger or more structured applications, it's a common best practice to separate the logic into controller files (usually placed in a controllers folder), and have the route files simply call those controller functions.

So, to clarify:

  • routes/ → defines the routes and maps them to specific functions
  • controllers/ → contains the actual logic that runs when a route is accessed
Although the route files define the "entry points" of your app's functionality, the core business logic is typically delegated to controllers, making the architecture cleaner and more maintainable.

If you want to separate the controllers and the routes, you could write a code like this:
inside routes-folder file named book.js

var express = require('express');
var router = express.Router();
var userController = require('../controllers/bookController');

// GET /books
router.get('/', bookController.allBooks);

module.exports = router;
inside controllers-folder file named bookController
exports.allBooks = function(req, res) {
  //call the model to get books from database
};



Toggle Menu