π΄ Sequelize MySQL Node Express REST API | Babel | Devhubspot
Introduction
In this article, we will discuss what an API is, what it means to be RESTful, and how to implement these using Node.js. The Node.js packages we will be using will be Express for our API endpoints to manage responses and requests.
Learning how to create an API is a delicate process. Developers just want to build endpoints fast, so they can quickly get something ready for a webpage to consume. However, learning how to make things RESTful will make your API more consistent, predictable, and scalable.
This article assumes you know how to create an Express server and create APIs endpoints.
What is NodeJS?
Node.js is open-source: This means that the source code for Node.js is publicly available. And it's maintained by contributors from all over the world.
Node.js is cross-platform: Node.js is not dependent on any operating system software. It can work on Linux, macOS, or Windows.
Node.js is a JavaScript runtime environment: When you write JavaScript code in your text editor, that code cannot perform any task unless you execute (or run) it. And to run your code, you need a runtime environment.
Browsers like Chrome and Firefox have runtime environments. That is why they can run JavaScript code. Before Node.js was created, JavaScript could only run in a browser. And it was used to build only front-end applications.
What is Express JS?
Express is a node js web application framework that provides broad features for building web and mobile applications. It is used to build a single page, multipage, and hybrid web application.It's a layer built on the top of the Node js that helps manage servers and routes.
- Express was created to make APIs and web applications with ease,
- It saves a lot of coding time almost by half and still makes web and
- mobile applications are efficient.
- Another reason for using express is that it is written in javascript as javascript is an easy language even if you don't have a previous
- knowledge of any language. Express lets so many new developers enter the field of web development.
The reason behind creating an express framework for node js is:
- Time-efficient
- Fast
- Economical
- Easy to learn
- Asynchronous
What is Sequelize?
Sequelize is a modern TypeScript and Node.js ORM for Oracle, Postgres, MySQL, MariaDB, SQLite SQL Server, and more. It features solid transaction support, relations, eager and lazy loading, read replication, and more.
What is Mysql?
MySQL is one of the most recognizable technologies in the modern big data ecosystem. Often called the most popular database and currently enjoying widespread, effective use regardless of industry, itβs clear that anyone involved with enterprise data or general IT should at least aim for a basic familiarity of MySQL.
RESTful Endpoints
GET /api/users
This will return an array of users in our DB.
GET /api/users/:id
This will return one user specified by the:id parameter.
POST /api/users
This will push a user in our DB.
PUT /api/users/:id
This will update a user specified by the:id parameter.
DELETE /api/users/:id
This will delete a user specified by the:id parameter.
The above link goes over what each HTTP method is and what its intention is. Letβs quickly go over what HTTP methods we will be using.
GET: This HTTP method will return a resource located on a server.
POST: This HTTP method will create a resource.
PUT: This HTTP method will update a resource.
DELETE: This HTTP method will delete a resource.
Setting up the project
Now that we have a good understanding of what a REST API is and why we might want to build one, itβs time to get our hands dirty and start setting up our project.
The first thing weβll need to do is install Node.js on our machine. Node.js is a JavaScript runtime that allows us to run JavaScript on the server side, which is necessary for building our API. You can download and install the latest version of Node.js from the official website (https://nodejs.org/).
Project Structure :
node_modules
// node packages
SQL
// db.sql
src
controllers
// user.controller.js
database
// database.js
models
// user.js
routes
// user.js
app.js
server.js
.babelrc
package.json
package-lock.json
Create a new directory, we can run the following command:
mkdir <project name>
then move into the newly created directory:
cd <project name>
then run this command :
npm init
and fill this information like this:
package name: (project name) version: (1.0.0) description: entry point: (index.js) server.js test command: git repository: keywords: author: license: (ISC)
After creating project install node package run command:
npm install --save @babel/polyfill body-parser express morgan mysql2 sequelize
install node dev dependencies package run command:
npm install --save-dev @babel/core @babel/cli @babel/preset-env @babel/node nodemon
create the .babelrc file and add this code :
{ "presets": [ "@babel/preset-env" ] }
open package.json and change "scripts"
"scripts": { "dev": "nodemon src/server.js --exec babel-node", "build": "babel src --out-dir dist", "start": "node dist/server.js", "test": "echo \"Error: no test specified\" && exit 1" }
create the server.js file and add this code :
import app from './app'; import "@babel/polyfill" async function main(){ await app.listen(process.env.PORT || 7557); console.log("server run on 7557"); } main();
create the app.js file and add this code :
import express from 'express'; import bodyParser from 'body-parser'; import morgan from 'morgan'; //Importing Routes import UserRoutes from './routes/user'; const app = express(); //middlewares app.all('*', function(req, res, next) { res.setHeader("Access-Control-Allow-Origin", "*"); res.header("Access-Control-Allow-Methods", "POST, PUT, OPTIONS, DELETE, GET"); res.header("Access-Control-Max-Age", "3600"); res.header("Access-Control-Allow-Headers", "Content-Type, Access-Control-Allow-Headers, Authorization, X-Requested-With, x-access-token"); next(); }); app.use(bodyParser.json({limit: '100mb'})); app.use(bodyParser.urlencoded({limit: '50mb','extended': 'true'})); app.use(bodyParser.json({type: 'application/vnd.api+json'})); //routes app.use('/api/user', UserRoutes) export default app;
Create user.js in routes folder <project name>/src/routes/user.js and add this code :
import { Router } from 'express'; const router = Router(); import "@babel/polyfill" import { createUser, getUser, getUsers, deleteUser, updateUsers } from '../controllers/users.controller'; router.post('/getUsers', getUsers); router.post('/getUser', getUser); router.post('/create', createUser); router.delete('/removeUser', deleteUser); router.put('/updateUser', updateUsers); export default router;
Create user.js in models folder <project name>/src/models/user.js and add this code :
import Sequelize from 'sequelize'; import { sequelize } from '../database/database' const User = sequelize.define('users', { id:{ type:Sequelize.INTEGER, primaryKey:true }, name:{ type: Sequelize.STRING }, email:{ type: Sequelize.STRING, unique: true }, password:{ type: Sequelize.STRING }, phone:{ type: Sequelize.STRING, unique: true }, profile_pic:{ type: Sequelize.STRING } },{ timestamps:false }); export default User;
Create users.controller.js in models folder <project name>/src/models/users.controller.js and add this code :
import User from '../models/users'; import Sequelize from 'sequelize'; const Op = Sequelize.Op; export async function getUsers(req, res) { try{ let getdata = await User.findAll(req.body); if(getdata){ res.json({ success: true, message:"User Fetch Successfully", data:getdata }); } }catch(err){ console.log(err); res.status(500).json({ success: false, message:"Something went wrong!" }) } } export async function getUser(req, res) { try{ let createdata = await User.findOne({ where: req.body}); if(createdata){ res.json({ success: true, message:"User fetch Successfully", data:createdata }); } }catch(err){ console.log(err); res.status(500).json({ success: false, message:"Something went wrong!" }) } } export async function createUser(req, res) { try{ let checkdata = await User.findOne({where:{email:req.body.email}}); if(checkdata){ res.json({ message:"Already Exist", data:checkdata }); }else{ let createdata = await User.create(req.body, {fields: ['name', 'email', 'password', 'phone', 'profile_pic']}); if(createdata){ res.json({ success: true, message:"User Created Successfully", data:createdata }); } } }catch(err){ console.log(err); res.status(500).json({ success: false, message:"Something went wrong!" }) } } export async function deleteUser(req, res) { try{ let deletedata = await User.destroy({where:{id:req.body.id}}); if(deletedata){ res.json({ success: true, message:"User Created Successfully", data:deletedata }); } }catch(err){ res.status(500).json({ success: false, message:"Something went wrong!" }) } } export async function updateUsers(req, res) { try{ let finddata = await User.findAll({where:{id:req.body.id}}); if(finddata.length > 0){ finddata.forEach(async data =>{await data.update(req.body)}) } return res.json({ success: true, message:"User Created Successfully", data:finddata }); }catch(err){ console.log(err); res.status(500).json({ success: false, message:"Something went wrong!" }) } }
Create database.js in models folder <project name>/src/models/database.js and add this code :
import Sequelize from 'sequelize'; export const sequelize = new Sequlize('restapinodejs', 'root', '88571288', { host:'localhost', dialect:'mysql', login:false, logginf:false }) sequelize.authenticate().then(()=>{ console.log("Connection has been established successfully."); }).catch(err =>{ console.log("Unable to connect to the database", err); });
Rest API Using Sequelize, Babel, and ES6 in NodeJs with PostgreSQL database Done.
Run command
npm run dev // development server with babel-node npm start // development server npm test // testing server npm run build // create dist folder for producation
Thank you
Now, if you open up a web browser and navigate to http://localhost:[port]
, you should see the message "Hello, World!" displayed in the browser. Congratulations, you have a working REST API!