RESTful API in Node.js
What is REST architecture?
REST stands for Representational State Tranfer. REST is a web standard based on basic architectures using HTTP protocol. It processes resources, where each component is a resource and this resource can be accessed through common interfaces using standard HTTP methods. REST was first introduced by Roy Fielding in 2000.
Basically, a REST Server provides access to resources and REST Client access and modification of these resources using the HTTP method. Here each resource is identified by a URI. REST uses various representations to represent resources such as text, JSON, and XML, but the most common is JSON.
HTTP method used in REST
Here are the HTTP methods widely used in REST architecture.
GET - Used only to read resources.
PUT - Used to create new resources.
DELETE - Used to delete resources.
POST - Used to update the current record and create new resources.
RESTful Web Service
A web service is a set of protocols and standards used for the purpose of exchanging applications and systems. Software applications written in different languages and run by different platforms can use web service to exchange data over computer networks such as the internet in the same way as exchanging on a computer. .
Web services based on REST architectures are known as RESTful webservice. These webservices use the HTTP method to deploy REST architecture definitions. A RESTful web service is usually defined as a URI (like path), Uniform Resource Identifier as a service.
Create RESTful for a library
Suppose we have a JSON-based database containing information about User, the file name is users.json:
{ "user1" : { "name" : "huong", "password" : "password1", "profession" : "sinhvien", "id": 1 }, "user2" : { "name" : "manh", "password" : "password2", "profession" : "giangvien", "id": 2 }, "user3" : { "name" : "tuyen", "password" : "password3", "profession" : "laptrinhvien", "id": 3 } }
Based on this basic information, we will provide the following RESTful APIs:
SttURIP HTTPPOST body method Result1 listUsers GET empty Display list of user 2 addUser POST JSON String Add a new user 3 deleteUser DELETE JSON String Delete an existing user. 4: id GET empty Displays the details of a userList Users
We together deploy the first RESTful API named listUsers by using the following code:
var express = require ( 'express' ); var app = express (); var fs = require ( "fs" ); app . get ( '/listUsers' , function ( req , res ) { fs . readFile ( __dirname + "/" + "users.json" , 'utf8' , function ( err , data ) { console . log ( data ); res . end ( data ); }); }) var server = app . listen ( 8081 , function () { var host = server . address (). address var port = server . address (). port console . log ( "Ung dung Node.js dang lang nghe tai dia chi: http://%s:%s" , host , port ) })
Now try accessing the API defined above using http://127.0.0.1:8081/listUsers on the local computer. It will produce the following results:
{ "user1" : { "name" : "huong" , "password" : "password1" , "profession" : "sinhvien" , "id" : 1 }, "user2" : { "name" : "manh" , "password" : "password2" , "profession" : "giangvien" , "id" : 2 }, "user3" : { "name" : "tuyen" , "password" : "password3" , "profession" : "laptrinhvien" , "id" : 3 } }
Add a new User
The following API shows how to add a new User to the list. Below is the information of the new User:
user = { "user4" : { "name" : "hoang" , "password" : "password4" , "profession" : "sinhvien" , "id" : 4 } }
You can use Ajax to do this, but for simplicity we will hard code here. Below is the addUser API method to add a new user in the database.
var express = require ( 'express' ); var app = express (); var fs = require ( "fs" ); var user = { "user4" : { "name" : "hoang" , "password" : "password4" , "profession" : "sinhvien" , "id" : 4 } } app . get ( '/addUser' , function ( req , res ) { // Dau tien, doc tat ca cac User dang ton tai. fs . readFile ( __dirname + "/" + "users.json" , 'utf8' , function ( err , data ) { data = JSON . parse ( data ); data [ "user4" ] = user [ "user4" ]; console . log ( data ); res . end ( JSON . stringify ( data )); }); }) var server = app . listen ( 8081 , function () { var host = server . address (). address var port = server . address (). port console . log ( "Ung dung Node.js dang lang nghe tai dia chi: http://%s:%s" , host , port ) })
Now try accessing the API above using http://127.0.0.1:8081/addUsers on the local computer. The results will be displayed as follows:
{ user1 : { name : 'huong' , password : 'password1' , profession : 'sinhvien' , id : 1 }, user2 : { name : 'manh' , password : 'password2' , profession : 'giangvien' , id : 2 }, user3 : { name : 'tuyen' , password : 'password3' , profession : 'laptrinhvien' , id : 3 }, user4 : { name : 'hoang' , password : 'password4' , profession : 'sinhvien' , id : 4 } }
Display User information
Now deploy an API that calls the userID to display the corresponding User information.
var express = require ( 'express' ); var app = express (); var fs = require ( "fs" ); app . get ( '/:id' , function ( req , res ) { // Dau tien, doc tat ca cac User dang ton tai. fs . readFile ( __dirname + "/" + "users.json" , 'utf8' , function ( err , data ) { users = JSON . parse ( data ); var user = users [ "user" + req . params . id ] console . log ( user ); res . end ( JSON . stringify ( user )); }); }) var server = app . listen ( 8081 , function () { var host = server . address (). address var port = server . address (). port console . log ( "Ung dung Node.js dang lang nghe tai dia chi: http://%s:%s" , host , port ) })
Next, you call the service on using the address http://127.0.0.1:8081/2 on the local computer. The result will be as follows:
{
"name": "manh",
"password": "password2",
"profession": "giangvien",
"id": 2
}
Delete User
This API is similar to addUser API, where you can get an input through req.body and then rely on the userID to delete that User from the Database. For simplicity, suppose we delete the user whose ID is 2.
var express = require ( 'express' ); var app = express (); var fs = require ( "fs" ); var id = 2 ; app . get ( '/deleteUser' , function ( req , res ) { // Dau tien, doc tat ca cac User dang ton tai. fs . readFile ( __dirname + "/" + "users.json" , 'utf8' , function ( err , data ) { data = JSON . parse ( data ); delete data [ "user" + 2 ]; console . log ( data ); res . end ( JSON . stringify ( data )); }); }) var server = app . listen ( 8081 , function () { var host = server . address (). address var port = server . address (). port console . log ( "Ung dung Node.js dang lang nghe tai dia chi: http://%s:%s" , host , port ) })
Call the above service using http://127.0.0.1:8081/deleteUser on the local computer. It will produce the following results:
{user1:
{ name: 'huong', {name: 'huong',
password: 'password1', password: 'password1',
profession: 'sinhvien', profession: 'sinhvien',
id: 1 }, id: 1},
user3:
{name: 'tuyen',
password: 'password3', password: 'password3',
profession: 'laptrinhvien', profession: 'laptrinhvien',
id: 3 } id: 3}
}
According to Tutorialspoint
Previous post: Express Framework in Node.js
Next lesson: Request object in Node.js
You should read it
- How to change the browser User Agent without extenstion
- Instructions on how to create, delete user accounts on Windows
- Instructions on how to create a new User on Windows 10
- How to delete search history on Facebook?
- The CREATE USER command in SQL Server
- How to easily add and delete users on Ubuntu
- Find User in SQL Server
- DROP USER command in SQL Server
May be interested
- AZ word about eggs in Pokemon Gothere are many different pokemon eggs that can hatch into many pokemon, but to make these eggs hatch into pokemon, you will have to perform some tasks. each player begins with an egg incubator, which allows the user to incubate an egg after performing certain steps, gps and pedometer tracking on the mobile device of you and the game.
- Things you didn't know about 26 types of Pokéball - Part 1pokéball is the most important item in pokémon go, allowing gamers to quickly catch pokémon back to their team. the higher the pokéball, the more effective the ability to catch pokémon.
- 10 tips to help you become a great Pokemon trainerin the article below, tipsmake.com will introduce to you some tips to easily become a great trainer in this pokemon go game offline ...
- How to use GoChat application in Pokémon GOpokémon go has become a very hot phenomenon since its debut. any information or tricks related to the game are read and applied by players during the process of catching pokémon. and the gochat chat app for pokémon go players brings space to capture pokémon much more interesting.
- How to play Pokemon GO in Landscape Mode on the iPhonealthough players can play pokemon go in portrait mode. however, if you want to watch and play games on a large and eye-catching screen, players can switch to playing games in landscape mode.
- The secret to controlling Pokemon Go employees at workthese days, hr managers are faced with an extremely painful problem that is the status of priority employees playing pokemon go more than work. this has caused a small impact on productivity and efficiency.
- Check out the 'buffalo' Pokémon in Pokémon Goeach type of pokemon has hp, cp, ability to attack and endure differently. based on these indicators, players can determine as well as choosing the most powerful pokemon for their offensive tactics.
- Sitting home can also locate Pokemon around, do you believe it?the tightening of the niantic developers' rules to prevent players from abusing the support tools also brings annoyance, such as those who have no conditions to move much, go away, it is hard to know. get the location of the pokemon around the area they live in
- 5 undeniable benefits when playing Pokemon Goget to know many new people, breathe fresh air, relieve stress, increase concentration thanks to going out for a walk .... are compelling reasons to force you to try pokemon go now .
- Want to earn the fastest Pokécoins in Pokémon Go? So don't miss this article!pokécoins in pokémon go play the role of buying items in the store. the more coins you earn, the more likely you are to buy more items. to earn pokécoins, players will have to complete certain tasks or buy real money.