Design a solid MVC REST API with node.js express and ORM Part 1

What will we cover up?

  1. Basic Infrastructure:
  • Create the app.
  • Define folder structure.
  • Implement REST API.
  • Test our API with Postman.
  • Add logs to our server.
  • Add configuration file and .env file.
  • Add DB connection (SQL).
  • Add ORM to our project (sequelize).
  • Define controllers and Models.

Prerequisites

  • Node.js installed on your machine- download from here (I’m using version 12+)
  • Your favorite IDE (I’m using Intellij).
  • npm -node package manager installed (yarn is fine too but I’ll be using npm commands).
  • Postman-like app for testing our API.

Let’s get started…

1. Create a Node app

npm init -y
npm install express
npm install --save-dev nodemon

2. Create our folder structure

  • Create src folder in our root folder.
  • Inside src folder create index.js file and routes folder.
  • Inside routes folder we will create a route for a resource named users by creating a users.js file.
it should look like this
  • Change “main” to point to our API’s entry point by pointing it to:
"main": "./src/index.js",
  • Add start command that will execute our code:
"scripts": {
"start": "nodemon",
}
// package.json{
"name": "mvc-rest-api",
"version": "1.0.0",
"description": "",
"main": "./src/index.js",
"scripts": {
"start": "nodemon",
"test": "echo \"Error: no test specified\" && exit 1"
},
"keywords": [],
"author": "",
"license": "ISC",
"dependencies": {
"express": "^4.17.1"
},
"devDependencies": {
"nodemon": "^2.0.3"
}
}

3. Implementing our API

//src/index.jsconst express = require('express');
const app = express();

const PORT = 3000;


function onStart(){
console.log(`Server running on port ${PORT}`);
}

app.listen(PORT, onStart);

module.exports = app;
//src/index.js
...
const PORT = 3000

/**
* Express middleware.
*/
// parses incoming requests with JSON payloads
app.use(express.json());
// parses incoming requests with urlencoded payloads
// extended: true - parsing the URL-encoded data with the querystring library
app.use(express.urlencoded({extended: true}));
...
npm start
//src/routes/users.jsconst router = require('express').Router();router.route('/users')
// to create new resources
.post(function(req, res, next) {

})
// to retrieve resource
.get(function(req, res, next) {

})
;
router.route('/users/:userId')
// to retrieve a single resource
.get(function(req, res, next) {

})
module.exports = router;
//src/index.js...
const PORT = 3000;
/**
* Routes.
*/
const usersRouter = require('./routes/users');
...
// Add this after the middleware part
app.use('/api', usersRouter);
localhost:3000/api/users
localhost:3000/api/v1/users

4. Now lets test our API.

//src/routes/users.js...const usersData = {
1: {id:1, firstName: 'Ralph', lastName: 'Woods'},
2: {id:2, firstName: 'Ronnie', lastName: 'Moore'},
3: {id:3, firstName: 'Koko', lastName: 'Kennedy'}
}
router.route('/users')
// to create new resources
.post(function(req, res, next) {
// Return our request body and return status OK
res.json(req.body).status(200).send();
})
// to retrieve resource
.get(function(req, res, next) {
// Respond with some data and return status OK
res.json(usersData);
res.status(200).send();
});
router.route('/users/:userId').get(function(req, res, next) {
const id = req.params.userId;
if(id && usersData[id]) {
res.json(usersData[id]);
res.status(200).send();
} else {
// Not Found
res.status(404).send();
}
})
...
Get all resources

--

--

--

Software Developer

Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

ReactJS Todo app tutorial with Redux

Getting Started with Arrow Functions in Javascript

Writing Scripts As Frontend With Es6 And Jest

React JS Password Generator — Beginners

CONUN Group introduction video

Variable Declarations in JavaScript

Microrequest

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Elia Bar

Elia Bar

Software Developer

More from Medium

Server Backend Concepts (NodeJS, ExpressJS)

The Power Of Node.js Series 📽️

Modern React and NodeJS Development Course Update

Introduction to Sequelize, a popular ORM for Node.js