What is the RESTful API in Node.js?

What is the RESTful API in Node.js?


In the previous articles, Taimienphi.vn introduced you to file read and write (File System) in Node.js as well as Utility Module and Web Module in Node.js? In the following article, Taimienphi.vn will introduce you more about RESTful API in Node.js.


Let’s refer to the following article of Taimienphi.vn to learn more about RESTful API What is in Node.js, how to create RESTful API in Node.js.

What is the RESTful API in Node.js?

Table of Contents:
1. What is REST?
2. Prepare
3. How to create RESTful API with Node.js
4. Setting up the Server
5. Set up schema
6. Set up a route
7. Setting up the Controller
8. Connecting everything together
9. Check through Postman
10. Add middleware

1. What is REST?

REST stands for Representational State Transfer, a standard web structure and HTTP protocol. The type of REST design structure describing the 6 constraints originally presented by Roy Fielding in his doctoral thesis and defining the RESTful basis is:

1. Uniform interface

2. Stateless

3. Cache

4. Client – Server (client – server)

5. Classification system.

6. Code as required (optional)

RESTful applications use HTTP requests to perform four operations called collectively CRUD , Inside: C stands for create, ie create. R stands for read, ie read. U stands for update, ie update and D stands for delete, ie delete.

RESTful includes methods like base URL, URL, media type, etc. In the next section, Betdownload.com will guide you how to create RESTful API using Node.js.

2. Prepare

Before you begin the process of creating a RESTful API, here are the tools you need to prepare in advance:

– Node.js

– MongoDB

– Command line editor (Atom, Sublime, …)

– Postman

3. How to create RESTful API with Node.js

The next section below Taimienphi.vn will guide you how to create RESTful API. To do this, we will first create a RESTful API list (i.e. an endpoint to create the task, receive or read a list of all tasks, read a specific task, delete a task, and update. one action).

Assumptions

Assume that you have set up your environment (i.e., installed Node.js and MongoDB).

Run the commands npm -v and mongo –version To find out information about the NPM and MongoDB versions installed on your computer.

After installing Node and MongoDB, follow the steps below to create RESTful API using Node.js.

Open Terminal, then follow the steps below:

Step 1: Create a new directory named todoListApi, by entering the command mkdir todoListApi.

Step 2: Navigate to the root of the new directory you just created, by entering the command cd todoListApi.

Step 3: Next enter the command npm init to create a package.json file.

The Package.json file provides the information needed for npm, allowing it to identify the project as well as handle project dependencies.

npm init will ask you to enter some information such as application name, description, version, author, keyword.

On the screen you will see the window as shown below:

restful api in node js what is 2

Next enter Yes Click on it and press Enter to complete the package.json creation process. After completing the process, the directory structure looks like this:

restful api in node js what is 3

Step 4: Enter the command touch server.js to create a file named server.js.

In this server, we will write the protocols to create the server.

Step 5 : Create a folder named api – mkdir api.

Within the api directory, create 3 other directories named models, routes, and controllers by running the command mkdir api / controllers api / models api / routes.

restful api in node js what is 4

Step 6: Create todoListController.js in the api / controller directory, todoListRoutes.js in the routes directory and todoListModel in the models directory by running the command: touch api / controllers / todoListController.js api / models / todoListModel.js api / routes / todoListRoutes.js.

The directory structure will look like this:

restful api in node js what is 5

4. Setting up the Server

The next step is to install express and nodmon, express is used to create the server, and nodmon is used to track changes in the application by viewing the changed files and automatically restarting the server. Use the commands below:

npm install –save-dev nodemon

npm install express –save

After installing express and nodmon successfully, the package.json file will be modified to install 2 new packages.

1. Open the package.json file and add this task to the script:

“start”: “nodemon server.js”

What is the restful api in node js 6?

2. Open server.js file and enter the following code:

var express = require (‘express’),

app = express (),

port = process.env.PORT || 3000;

app.listen (port);

console.log (‘todo list RESTful API server started on:’ + port);

restful api in node js what is 7

3. On the Terminal window, run the command npm run start To start the server, on the screen you will see the following message:

todo list RESTful API server started on: 3000

5. Set up schema

The first step is to install mongoose, use the command npm install mongoose –save .

We will use Mongoose to interact with a MongoDB (Database) variant. After installing Mongoose, open the todoListModel.js file in the api / models directory, enter the following code into the file and save it:

‘use strict’;

var mongoose = require (‘mongoose’);

var Schema = mongoose.Schema;

var TaskSchema = new Schema ({

name: {

type: String,

required: ‘Kindly enter the name of the task’

},

Created_date: {

type: Date,

default: Date.now

},

status: {

type:[{[{

type: String,

enum: [‘pending’, ‘ongoing’, ‘completed’]

}],

default: [‘pending’]

}

});

module.exports = mongoose.model (‘Tasks’, TaskSchema);

In the above code add mongoose to the file, then create a model that describes how the collection interface looks like.

As you can see the task collection (table) will contain the name of a string and the date it was created, the task status defined as pending – the default value for each task being created.

6. Set up a route

Route refers to determining how the application responds to client requests at a specific endpoint, a URL (or path) and a specific HTTP request method (GET, POST, etc.). .

Each route has a different handler function, which is executed when the route is matched.

Here are two basic routes ((‘/ tasks’, and ‘/ tasks / taskId’) with different methods.

‘/ tasks’ has to methods (‘GET’ and ‘POST’), while ‘/ tasks / taskId’ has GET, PUT and DELETE.

Next we will ask the controller for each method of the route to be able to call the corresponding handler function.

To do this, open the todoListRoutes.js file in the routes directory and enter the following code:

‘use strict’;

module.exports = function (app) {

var todoList = require (‘../ controllers / todoListController’);

// todoList Routes

app.route (‘/ tasks’)

.get (todoList.list_all_tasks)

.post (todoList.create_a_task);

app.route (‘/ tasks /: taskId’)

.get (todoList.read_a_task)

.put (todoList.update_a_task)

.delete (todoList.delete_a_task);

};

7. Setting up the Controller

Open the todoListController.js file using the command line editor on your computer.

In this Controller, we will write 5 different functions, including: list_all_tasks, create_a_task, read_a_task, update_a_task, delete_a_task. It will then export each function for use in routes.

Each function will use different mongoose methods, including find, findById, findOneAndUpdate, save and remove.

‘use strict’;

var mongoose = require (‘mongoose’),

Task = mongoose.model (‘Tasks’);

exports.list_all_tasks = function (req, res) {

Task.find ({}, function (err, task) {

if (err)

res.send (err);

res.json (task);

});

};

exports.create_a_task = function (req, res) {

var new_task = new Task (req.body);

new_task.save (function (err, task) {

if (err)

res.send (err);

res.json (task);

});

};

exports.read_a_task = function (req, res) {

Task.findById (req.params.taskId, function (err, task) {

if (err)

res.send (err);

res.json (task);

});

};

exports.update_a_task = function (req, res) {

Task.findOneAndUpdate ({_ id: req.params.taskId}, req.body, {new: true}, function (err, task) {

if (err)

res.send (err);

res.json (task);

});

};

exports.delete_a_task = function (req, res) {

Task.remove ({

_id: req.params.taskId

}, function (err, task) {

if (err)

res.send (err);

res.json ({message: ‘Task successfully deleted’});

});

};

8. Connecting everything together

Above we have the code to set up and run the server in the file server.js. In this section, we will set up controller, database, model created, bodyparser and route created together.

Open the server.js file created above and follow the steps below to connect everything.

Basically, we will replace the code in our server.js with the snippet.

1. Connect the database by adding the URLs to the mongoose variant connection.

2. Download the created model – task.

3. Install bodyParser and use.

bodyParser analyzes required elements in the middleware before the handler, available in the req.body attribute.

All middleware will fill req.bodyproperty with bodyParser or an empty object ({}) if no parsing part (or an error is returned).

4. Register the created route in the server.

var express = require (‘express’),

app = express (),

port = process.env.PORT || 3000,

mongoose = require (‘mongoose’),

Task = require (‘./ api / models / todoListModel’), // created model loading here

bodyParser = require (‘body-parser’);

// mongoose instance connection url connection

mongoose.Promise = global.Promise;

mongoose.connect (‘mongodb: // localhost / Tododb’);

app.use (bodyParser.urlencoded ({extended: true}));

app.use (bodyParser.json ())

var routes = require (‘./ api / routes / todoListRoutes’); // importing route

routes (app); // register the route

app.listen (port);

console.log (‘todo list RESTful API server started on:’ + port);

5. Start the MongoDB server.

Open Terminal and run the command mongod.

The above command will start the MongoDB server, after which the server node can connect to the MongoDB variants. After the MongoDB server runs, restart the server node by running the command rs on the Nodemon Terminal window.

9. Check through Postman

After everything is connected, try checking each route and the corresponding methods.

Open postman and enter the following command:

1. Enter http: // localhost: 3000 / tasks Go to the request URL and press enter.

restful api in node js what is 8

At this time, the screen will display “[]”because there is nothing in the database.

2. At the same address, change the method to POST, Click on body and choose “x-www-form-urlencoded”.

Next enter the name in the key and the corresponding task in the value, click the button Send.

restful api in node js what is 9

10. Add middleware

Assume if you enter ‘http: // localhost: 3000 / task , it will respond to the “Cannot GET / task “In this case just add Express Middleware, which is used to respond to interactive messages.

Middleware basically blocks http requests, and you can use it to perform a number of different operations, such as authentication, etc.

To do this, open the server.js file and paste the snippet below:

app.use (function (req, res) {

res.status (404) .send ({url: req.originalUrl + ‘not found’})

});

The snippet above will redirect and respond whenever the error route is entered on the web page.

https://thuthuat.taimienphi.vn/restful-api-trong-node-js-la-gi-43612n.aspx
So the article above Taimienphi.vn has just introduced you about RESTful API in Node.js. In addition, readers can refer to some other articles already on Taimienphi.vn to learn more about the Utility Module and Web Module in Node.js.

.

Related Posts

Leave a Reply

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