Categories
Codes Javascript MongoDB Node.js Redis

How to Create REST API Using Node.js – Part 1

“The more that you read, the more things you will know. The more that you learn, the more places you’ll go.”

― Dr. Seuss, I Can Read With My Eyes Shut!

Introduction

This month, I want to share a tutorial divided into multiple posts. The topic is about creating REST API with Node.js. I believe that I would improve my knowledge by writing a tutorial, and I also believe that it might help you too. Two birds with one stone.

I divide this topic into multiple posts. Each post will improve the things we have created before, giving more usefulness on the API we will create. And also, for every post I will share the final source code on GitHub, so you can learn more and find out what you missed if you couldn’t make it work by just following the tutorial.

In this first post, we will focus on setting up Node.js, create your first API with a library called Express.

Requirements

If you don’t have Node.js installed yet, here are some links for you:

  • Node.js
    I recommend download the LTS one. Because, well, longer term support. To make sure it works, type node -v on your Terminal after installation:
  • Postman or Insomnia
    To check whether your API is working. Personally, I prefer Postman because of the multiple tabs. To know it’s working, well, just open the app.

Part 1 – Create CRUD API with Node.js and Express

Create A New Project

Let’s start by making a new project in any directory you want, I will name it as cil-nodejs-api. Inside the project, open terminal and type:

npm init

Continue the configuration process and finish. Inside package.json, you can add a new command to start the application using npm. Add this on the scripts property:

...
  "scripts": {
    "start": "node index.js",
    "test": "echo \"Error: no test specified\" && exit 1"
  },
...

Next, we will create a file named index.js. This is the entry point of the application. To test the code, write an example just like the snippet below:

console.log("Hello world!");

Open your terminal and run npm start on the project folder. It should result in something like this:

Hello world!

The screenshot above shows if your Node.js project installation is a success. If you got these messages, you can continue to the next section.

Install Some Libraries
Express

This is one of the popular web frameworks for Node.js, it’s fast and simple to set. On your Terminal, run npm i express. You should see this kind of message if it’s run successfully:

DOTENV

Some variables in a good app are configurable and separated on another file . Because when the app is run on a different environment, some variables will be unique compared to the other environments. For example, host and port. The dotenv library loads the environment variables from the file .env to process.env.

Run npm i dotenv to install. It should show something like this if it’s a success:

Hello World, but from URL

First, we initialize our app. Let’s start with modifying index.js to this:

const express = require('express');
const app = express();
const port = 3000;

app.get('/helloworld', (req, res) => {
    res.send('Hello World!')
});

app.listen(port, () => {
    console.log(`cli-nodejs-api listening at http://localhost:${port}`)
});

Then, on your terminal, run npm start. If the message shows as below, then the app runs successfully:

Run your Postman / Insomnia app, then execute this endpoint: GET localhost:3000/helloworld. If everything goes well, it will result like this:

If you manage to reach this step already, then you can create the other endpoints by yourself and make it work.

CRUD + Login & Logout

Let’s make user-related functions. First, we will declare all the necessary endpoints:

  • Create: POST /user
  • Read:
    • List of users: GET /user
    • Detail user: GET /user/{id}
  • Update: PATCH /user
  • Delete: DELETE /user/{id}
  • Login: POST /login
  • Logout: POST /logout

Then, we add them in the simplest way for now.

Create a new user

The first endpoint is POST /user. We will create new users through this later on. Here is a snippet of the code:

const express = require('express');
const bodyParser = require('body-parser');
const app = express();
const port = 3000;

app.use(bodyParser.json());

app.post('/user', (req, res) => {
    res.send({
        message: 'CREATE NEW USER: POST /user',
        body: req.body
    });
});

app.listen(port, () => {
    console.log(`cli-nodejs-api listening at http://localhost:${port}`)
});

First, we need to install body-parser using npm i body-parser. This library enables us to parse request bodies in the form of JSON. Then, call the library with
const bodyParser = require('body-parser');
Lastly, the library must be configured to be used by Express through this code: app.use(bodyParser.json());

After initiating the body-parser, create a new POST endpoint with app.post(). We will name the address as /user. Upon calling /user, a callback function with the parameters req and res will be executed. To extract the JSON payload sent, we can call req.body in the function. To return the address’ result, simply execute res.send() with any arguments you want.

Run npm start, then open your Postman app to test the endpoint. It should look like this if you succeed:

Get Users List and Detail

Next, let’s create an endpoint to get list of users with GET /user and get a user’s detail with GET /user/:id. And we will add them in index.js also, right after POST /user. See this snippet below:

...

app.post('/user', (req, res) => {...});

app.get('/user', (req, res) => {
    res.send('GET USER LIST: GET /user');
});

app.get('/user/:id', (req, res) => {
    res.send('GET USER: GET /user/' + req.params.id);
});

app.listen(port, () => {...});

Getting a list of users is very straight forward, with app.get('/user', () => {});

What’s interesting here is getting a user’s detail. We use the same address with getting user list, but adding /:id at the end of it. So, we have app.get('/user/:id', () => {});.

Next, to get the id of the user we want to see in detail, we must access req.params. Because we already declared the identifier is id, req.params will have the property id. Hence, we can access req.params.id.

If you added these endpoints correctly, it should result in something like this when you test it:

GET /user
GET /user/:id
Update a user

To fill the need of updating a user, we will make a PATCH /user/:id endpoint. Let’s make it just like the snippet below, just after the GET /user/:id:

...

app.get('/user/:id', (req, res) => {...});

app.patch('/user/:id', (req, res) => {
   const msg = {
       message: 'UPDATE USER: PATCH /user/' + req.params.id,
       body: req.body
   };
   res.send(msg);
});

app.listen(port, () => {...});

We use app.patch('/user/:id') to make the endpoint for updating a user’s data. And it is possible to access both req.params, from on the GET function previously, and req.body, from the POST function, at the same time.

The properties in req.body will be used in the future for updating the user’s data.

Test the code using Postman. You should see something like this:

PATCH /user/:id
Delete a User

Creating an endpoint to delete a user is similar to updating a user from before, but set it as DELETE. You can see it with this snippet:

...

app.patch('/user/:id', (req, res) => {...});

app.delete('/user/:id', (req, res) => {
    res.send('DELETE USER: DELETE /user/' + req.params.id);
});

app.listen(port, () => {...});

Same as patch, we will use app.delete('/user/:id') to enable this endpoint. The detail parts of the code are pretty much the same as the previous ones.

When you run the code and test it, you should see something like this:

DELETE /user/:id
Login

For login, we use username and password as body in JSON. And using the POST request to send the body. Use app.post('/login') to do this. Creating this endpoint is similar to the POST /user previously.

Later on another part of this series, about improving security, we will enhance this function so it will return an authentication token and use the token for every CRUD (Create, Read, Update, Delete) operations in the API.

Logout

Use app.post('/logout'). There are various implementations of logging out a user. Either by removing the binding of a device, forcing to expire or delete the token, or just simply sending a message of logging out.

Conclusion

Okay, that’s all for the first part. In this post, you should have learned:

  • Installing the requirements of a Node.js project
  • Starting a Node.js project
  • Installing dependencies, such as Express and body-parser
  • Creating new endpoints for API

And here is the source code from GitHub. Feel free to clone and check what you missed!

On the second part of the post, we will learn to integrate our API with the database using MongoDB. I should have it posted by next week!

Next post in the series:
Part 2 – Implement MongoDB

“Let the improvement of yourself keep you so busy that you have no time to criticize others.”

― Roy T. Bennett, The Light in the Heart

By Ericko Yap

Just a guy who is obsessed to improve himself. Working as a programmer in a digital banking company. Currently programming himself in calisthenics, reading books, and maintaining a blog.

Leave a Reply

Your email address will not be published. Required fields are marked *