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

You’ll learn how to prepare your app to build an API…

Photo by on

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

An API REST (Representational State Transfert) is an application programming interface who respect specific constraints.

This App let two application talk to each other, in fact API are everywhere…

We don’t go deeper here but to understand it in an easy way :

When you are looking for some data with your mobile phone you send a request to a server, the server retrieves your data and do some actions to send back the data you want..(i.e a weather app, you enter a zip code, send it to the server, and send you back the weather in your city/state, that”s a basic exemple of what an API looks like.)

Now let’s try to explain what’s REST is …

When you send a request to an API RESTful you send data with Http protocol in a specific format: JSON, HTML, XLT or plain text. The most commonly used format is the JSON (Javascript Object Notation), who is readable by humans and machines.

Here are the specs for Restful API :

  • 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 on

Let’s initialize our project with :

npm init -y

Here the -y is to say yes to anything, feel free to don’t use it if you want to enter personnal informations for your app.

npm i express nodemon express-validator mysql dotenv body-parser

We’ll use express to build our API and nodemon is used here to reload automatically our server when we modify our files.

Express Validator give us some middlewares to check our incoming data and handle customs error messages.

Mysql is our database language

Dotenv will let us put some sensible variables in a .env files and use them everywhere.

Body-parser is a middleware that will manage the data in our request and put all of them in req.body

Let’s create some files like this :

.env : we’ll put our port connection and database settings in this file :

PORT=3000#Database settings
DB_HOST=localhost
DB_USER=username
DB_PASS=password
DB_NAME=database name

.gitignore : We’ll put all the files that we don”’t want to be visible on our online repo :

.env
node-modules/

db.js : our connection to the database, this files is visible on our repo that’s why we use process.env on it !Antoine Gorenflot

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;

An our index.js, below you find the minimal code to make your server running :

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}`);});

Finally we’ll modify a line into our package.json to start our server :

Here nodemon reload the server when you modify some lines of codes.

"scripts": {
"start": "nodemon index.js"
},

This will let us launch our server with the command: npm start

Here you are, after launch your server you should see those lines in your terminal, you are now able to write some routes to build your CRUD (I’ll explain it in an other article…)

Thanks for reading, if you have any questions or advice feel free to contact me !!

An enthusiastic Javascript developper