đź”´ Rest API Tutorial - Creating Dynamic Requests with NodeJS and Express

NodeJs restApi express

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 and static array 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 is assuming you know how to create an Express server and create APIs endpoints with static arrays


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

RESTful Endpoints

GET /api/users

This will return an array of users in our static array.

GET /api/users/:id

This will return one user specified by the:id parameter.

POST /api/users

This will push a user in our static array.

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/).

Once you have Node.js installed, you can create a new project by opening up a terminal and navigating to the directory where you want to store your project. Then, run the following command to create a new Node.js project:

npm init

This command will prompt you to enter some information about your project, such as the name, version, and description. You can accept the default values by pressing Enter, or customize them to your liking. When you’re done, you should see a new file called “package.json” in your project directory. This file contains metadata about your project, including the dependencies (i.e. libraries and frameworks) that you’ll need to install.

Next, we’ll install the Express library, which we’ll use to build our API. To install Express, run the following command in your terminal:

npm install express

This will download and install the latest version of Express, and add it to the “dependencies” section of your package.json file.


After installing all dependencies then create a server.js file on root folder and then following code : 

var express = require('express');
var bodyParser = require('body-parser')
var morgan = require('morgan')
var app = express();
const Users = [{
        id: 1,
        name: "dev",
        email: "dev@gmail.com"
    },
    {
        id: 2,
        name: "hub",
        email: "hub@gmail.com"
    },
    {
        id: 3,
        name: "spot",
        email: "spot@gmail.com"
    },
    {
        id: 4,
        name: "ben",
        email: "ben@gmail.com"
    },
    {
        id: 5,
        name: "jhon",
        email: "jhon@gmail.com"
    },
    {
        id: 6,
        name: "youtube",
        email: "youtube@gmail.com"
    },
    {
        id: 7,
        name: "google",
        email: "google@gmail.com"
    },
    {
        id: 8,
        name: "twitter",
        email: "twitter@gmail.com"
    }
];

//allow cros origin requests
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'
}));

//root path
app.get('/', (req, res, next) => {
    res.send("Nodejs Express sever started...")
});

//get all users
app.get('/users', (req, res, next) => {
    res.json({
        "data": Users,
        "message": "Users fetch succesfully",
        "status": true
    })
});

//get all users by id
app.get('/users/:id', (req, res, next) => {
    var find = Users.find(el => el.id == req.params.id);
    if (find) {
        res.json({
            "data": find,
            "message": "User fetch succesfully",
            "status": true
        })
    } else {
        res.json({
            "data": {},
            "message": "User not found",
            "status": false
        })
    }
});

//Create user
app.post('/users', (req, res, next) => {
    console.log(req.body, "object here");
    Users.push(req.body);
    res.json({
        "data": Users,
        "message": "Users fetch succesfully",
        "status": true
    })
});

//update user name by id
app.put('/users/:id', (req, res, next) => {
    console.log(req.body, "object here");
    var find = Users.find(el => el.id == req.params.id);
    if (find) {
        find['name'] = req.body.name;
        res.json({
            "data": find,
            "message": "User fetch succesfully",
            "status": true
        })
    } else {
        res.json({
            "data": {},
            "message": "User not found",
            "status": false
        })
    }
});

//delete by id
app.delete('/users/:id', (req, res, next) => {
    var find = Users.find(el => el.id == req.params.id);
    if (find) {
        let index = Users.indexOf(find);
        Users.splice(index, 1);
        res.json({
            "data": Users,
            "message": "User fetch succesfully",
            "status": true
        })
    } else {
        res.json({
            "data": {},
            "message": "User not found",
            "status": false
        })
    }
});


app.listen(8699, () => {
    console.log("server running on port 8699")
})


That’s it! You now have a basic API set up using Node.js and Express. You can start the API by running the following command in your terminal:

node app.js

This will start the API server, and you should see the message “API server listening on port [port]” in the terminal.

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!



NodeJs restApi express
Comments

AdBlock Detected!

Our website is made possible by displaying ads to our visitors. Please supporting us by whitelisting our website.