How to start a project to build an API REST with NodeJS and Express

Photo by Joshua Aragon on Unsplash

Let’s explain what’s an API REST(ful) is ..

  • It uses a client server architecture with HTTP request.
  • Stateless communication, client informations are send independently and separately.
  • Ability to use cache to minimize interactions between client and server.
  • Uniform interface between components which standardize informations transfert.
  • Prioritization between each different server (security, load balancing etc…)

Ok for the theory now, let’s practice !!

Photo by Brett Jordan on Unsplash
npm init -y
npm i express nodemon express-validator mysql dotenv body-parser
PORT=3000#Database settings
DB_HOST=localhost
DB_USER=username
DB_PASS=password
DB_NAME=database name
.env
node-modules/
const mysql = require('mysql');const connection = mysql.createConnection({
host: process.env.DB_HOST,
user: process.env.DB_USER,
password: process.env.DB_PASS,
database: process.env.DB_NAME,
});
module.exports = connection;
require('dotenv').config();
const express = require('express');
const bodyParser = require('body-parser');
const { check, validationResult } = require('express-validator');
const connection = require('./db');const app = express();app.use(bodyParser.json());app.use(bodyParser.urlencoded({ extended: false }));app.listen(process.env.PORT, (err) => {
if (err) {
throw new Error('Something bad happened...');
}
console.log(`Server is listening on ${process.env.PORT}`);});
"scripts": {
"start": "nodemon index.js"
},

--

--

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