DEV Community

Cover image for Node.js : REST API part 1
Ridha Mezrigui
Ridha Mezrigui

Posted on • Updated on

Node.js : REST API part 1

Hello community,

in this tutorial, I'll teach you how to make REST API using Node.js.
we will cover all these topics :

  • REST API: What is it, and what are its advantages?
  • the idea of our project
  • set up the environment
  • choose the best structure for our project
  • Build our REST API

So let's get started

REST API: What is it, and what are its advantages?

REST API completely changed software engineering after 2000. This new approach to developing web projects and services was defined by Roy Fielding, father of the HTTP specification and one of the leading international authorities on everything to do with Network Architecture, in his dissertation entitled "Architectural Styles and the Design of Network-based Software Architectures".

Today, there are no projects or applications that don't have a REST API for the creation of professional services based on this software. Twitter, YouTube, Facebook identification systems… hundreds of companies generate business thanks to REST and REST APIs. Without them, any horizontal growth would be practically impossible. This is because REST is the most logical, efficient and widespread standard in the creation of APIs for Internet services.

the idea of our project

in this tutorial, we will build a movies API :

  • Register user
  • Login user
  • create new movie (part 2)
  • get all movies (part 2)
  • get movie by ID (part 2)
  • add movie (part 2)
  • update movie (part 2)
  • delete movie (part 2)

set up the environment

technologies that we will use to build our API :

  • Express : a Node.js framework
  • MongoDB : NoSQL database and we will use mongoose package

open your cmd and type

mkdir movies-api //create an empty folder
cd movies-api //navigate to our project 
npm init --yes //create package.json file 
npm i --save express
npm i --save mongoose 
npm i --save-dev nodemon 
Enter fullscreen mode Exit fullscreen mode

choose the best structure for our project

movies-api:
├───controllers
├───middleware
├───models
└───routes
so create these folders and let's get started the real work

the real work

first, we need to create the index.js file
go to your terminal and type

touch index.js
Enter fullscreen mode Exit fullscreen mode

create our server

//index.js
const express = require('express');

const app = express();

const PORT = process.env.PORT || 5000;

app.listen(PORT, () => {
    console.log('server is running')
});
Enter fullscreen mode Exit fullscreen mode

to run the server type in the terminal

nodemon
Enter fullscreen mode Exit fullscreen mode

you have to see something like that
Alt Text

now it's the time to connect our project with database and for that i will use mongoDB atlas you can check it and make a free account

//index.js
const express = require('express');
const mongoose = require('mongoose');

const app = express();

const PORT = process.env.PORT || 5000;


mongoose
  .connect(
    "your mongoDB atlas database url connection",
    { useUnifiedTopology: true, 
      useNewUrlParser: true, 
      useCreateIndex: true })
  .then(() => {
    app.listen(PORT, () =>console.log('server is running'))
  })
  .catch(err => {
    console.log(err);
  });
Enter fullscreen mode Exit fullscreen mode

with this approach our server will run only if there is no error in the database connection.

the next step is to build the user model so create file in the models folder user-model.js

//user-model.js
const mongoose = require('mongoose');

const Schema = mongoose.Schema;

const userSchema = new Schema({
  name: { type: String, required: true },
  email: { type: String, required: true, unique: true },
  password: { type: String, required: true, minlength: 6 }
});

module.exports = mongoose.model('User', userSchema);
Enter fullscreen mode Exit fullscreen mode

now let's make our user-controller in controllers folder we create file with name "user-controller.js" will contain two functions register and login.
But first we need three packages bcryptjs, jsonwebtoken and express-validator

  • bcryptjs : will help us to crypt the user password before store it in the database
  • jsonwebtoken : A JWT technically is a mechanism to verify the owner of some JSON data. It’s an encoded string, which is URL safe, that can contain an unlimited amount of data (unlike a cookie), and it’s cryptographically signed.
  • express-validator : we need this package to test the data before we store it in the database.
npm i --save bcryptjs
npm i --save jsonwebtoken
npm i --save express-validator
Enter fullscreen mode Exit fullscreen mode

note : you can install the three packages by one command

npm i --save becryptjs jsonwebtoken express-validator
Enter fullscreen mode Exit fullscreen mode

let's import our packages

//user-controller
const { validationResult } = require('express-validator');
const User = require('../models/user');
const bcrypt = require('bcryptjs');
const jwt = require('jsonwebtoken');
Enter fullscreen mode Exit fullscreen mode

register function

//user-controller.js
const register = async (req,res) => {
 const errors = validationResult(req);

  if (!errors.isEmpty()) 
   return res.status(400).json("check your data");

  const { name, email, password } = req.body;
   let  existingUser = await User.findOne({ email: email });
   if (existingUser)
     return res.status(400).json("user exist");

  let hashedPassword = await bcrypt.hash(password, 12);

  const createdUser = new User({
    name,
    email,
    password: hashedPassword
});

  try { await createdUser.save() } catch (err) {}

  let token;
  token = jwt.sign(
    { userId: createdUser.id, email: createdUser.email },
    'supersecretkey',
    { expiresIn: '1h' });
    res.status(201).json({ token: token, userId: createdUser.id });
}


Enter fullscreen mode Exit fullscreen mode

login function

//user-controller.js
const login = async (req, res) => {
  const { email, password } = req.body;
  let existingUser;

  try {
    existingUser = await User.findOne({ email: email });
  } catch (err) { }

  if (!existingUser) 
    return res.status(200).json('Invalid credentials, could not log you in');

 let isValidPassword = await bcrypt.compare(password, existingUser.password);

  if (!isValidPassword) 
    return res.status(400).json('Invalid credentials, could not log you in.');

  let token;
  token = jwt.sign(
    { userId: existingUser.id, email: existingUser.email },
    'supersecretkey',
    { expiresIn: '1h' }
  );
  res.status(200).json({ token: token, userId: existingUser.id });
}
Enter fullscreen mode Exit fullscreen mode

we need to export these two functions

//user-controller.js
exports.register= register;
exports.login = login;
Enter fullscreen mode Exit fullscreen mode

with that we can start making the user routes so in the routes folder create new file "user-routes.js" this file will contain two routes one for register user and one for login user.

first let's import what we need

//user-rotes.js
const { check } = require('express-validator');
const usersController = require('../controllers/user-controller');
const express = require('express');
const router = express.Router();
Enter fullscreen mode Exit fullscreen mode

Register Route

router.post('/register',
  [ check('name').not().isEmpty(),
    check('email').normalizeEmail().isEmail(),
    check('password').isLength({ min: 6 })],
usersController.register)
Enter fullscreen mode Exit fullscreen mode

login Route

router.post('/login',
  [ check('email').normalizeEmail().isEmail(),
    check('password').isLength({ min: 6 })],
usersController.login)
Enter fullscreen mode Exit fullscreen mode

export routes

module.exports = router;
Enter fullscreen mode Exit fullscreen mode

the last thing we need to do is to import user-routes to index.js and test our API with postman

//index.js
const express = require('express');
const mongoose = require('mongoose');
const usersRoutes = require('./routes/user-routes');
const bodyParser = require('body-parser');

const app = express();
app.use(bodyParser.json());

app.use('/api/users', usersRoutes);

const PORT = process.env.PORT || 5000;
mongoose
  .connect(
    "your mongoDB atlas database url connection",
    { useUnifiedTopology: true, 
      useNewUrlParser: true, 
      useCreateIndex: true })
  .then(() => {
    app.listen(PORT, () =>console.log('server is running'))
  })
  .catch(err => {
    console.log(err);
  });
Enter fullscreen mode Exit fullscreen mode

now open postman and start test login and register routes

Register

choose the post method and type "localhost:5000/api/users/register" then go to body choose "row" then choose "json" finally enter your data and click send

Alt Text

Login

Alt Text

open your database, you have to see a new user in users collection
Alt Text

We can say that our part 1 is done, we will continue in the next part.
Thank you.

Oldest comments (11)

Collapse
 
gmcamposano profile image
gmcamposano

Nice. Thank you

Collapse
 
ridhamz profile image
Ridha Mezrigui

you can check the part 2

Collapse
 
malditochecho profile image
Sergio Rodriguez

You misspelled bcrypt as becrypt at the installation step.

Beside that, great article. It help me to think on a different approach. Thanks!

Collapse
 
ridhamz profile image
Ridha Mezrigui

happy to hear that from you 😉

Collapse
 
ridhamz profile image
Ridha Mezrigui

thanks bro 🥰

Collapse
 
kyawarkar profile image
Kyaw.Arkar

i cant post to api with POSTMAN with post method!
How can i fix

Collapse
 
kyawarkar profile image
Kyaw.Arkar

when i upload to api. then

Collapse
 
ridhamz profile image
Ridha Mezrigui

what do you mean?

Collapse
 
kyawarkar profile image
Kyaw.Arkar

this is screenshot

Collapse
 
sakthi profile image
Sakthivel

const User = require('../models/user');
we have file user-model but why you are import only user

Collapse
 
sakthi profile image
Sakthivel

Hello brother am getting mongodb connection error can you help to me