1. Introduction to concepts
1. REST concepts
REST: (Representational State Transfer) Representational State Transfer, which defines a common access format for resources, is a style of design and development for network applications.
Conceptually, you need to understand the following names:
- Resource s
That is, anything you get on the server, a user record, a user's password, a picture, and so on.
- Representation of resources
That is, the resource format, which is HTML, XML, JSON, plain text, pictures, and so on, can express the resources you get in a variety of formats.
- State Transfer
That is, URL s locate resources and describe operations with HTTP verbs (GET,POST,DELETE,DETC).Operations are verbs and resources are nouns.
- Uniform Interface
That is, resources are operated on through a unified interface.
2. REST features
REST is typically based on existing, widely popular protocols and standards that use HTTP, URI s, and XML as well as HTML, each representing a resource.
REST usually uses JSON data format.
Four approaches to the basic REST architecture:
- GET - Used to get data
- PUT - For updating or adding data
- DELETE - Used to delete data
- POST - For adding data
A scenario is presented below.
3. REST Advantages
- Cache can be used more efficiently to improve response speed
- Statelessness of communication itself allows different servers to handle different requests in a series of requests, which improves server scalability
- Browsers act as clients to simplify software requirements
- REST has less software dependency than other mechanisms that overlay the HTTP protocol
- No additional resource discovery mechanism is required
- Better long-term compatibility in software technology evolution
2. Introduction of Examples
REST defines a common access format for resources, and the next consumer example describes the RESTful API definition:
- Get all user s
GET /api/user
- Gets the user of the specified id
GET /api/user/100
- Create a new user record
POST /api/user
- Update a user record
PUT /api/user/100
- Delete a user record
DELETE /api/user/100
- Get all the expense bills for a user
GET /api/user/100/bill
- Get a user's bills for consumption at a specified time
GET /api/user/100/bill?from=201910&to=201911
The RESTful style API above contains almost common business situations.
3. Nodejs Implements RESTful API
1. Initialize mock data
This case demonstrates using mock data as follows:
{ "user1" : { "name" : "leo", "password" : "123456", "profession" : "teacher", "id": 1 }, "user2" : { "name" : "pingan8787", "password" : "654321", "profession" : "librarian", "id": 2 }, "user3" : { "name" : "robin", "password" : "888888", "profession" : "clerk", "id": 3 } }
We will implement the following RESTful API:
2. Get a list of users
In this step, we will create listUsers in the RESTful API to read a list of users'information:
// index.js const express = require('express'); const app = express(); const fs = require("fs"); // Define an interface for reading the user's information list app.get('/listUsers', (req, res) => { fs.readFile( __dirname + "/" + "users.json", 'utf8', (err, data) => { console.log( data ); res.end( data ); }); }) const server = app.listen(8081, function () { const {address, port} = server.address(); console.log("server run in: http://%s:%s", address, port); })
3. Add Users
In this step, we will create an addUser in the RESTful API to add user records:
// index.js // Omitting the previous file only shows the interfaces that need to be implemented // mock A new piece of data to add const user = { "user4" : { "name" : "pingan", "password" : "password4", "profession" : "teacher", "id": 4 } } // Define an interface for adding user records app.get('/addUser', (req, res) => { // Read existing data fs.readFile( __dirname + "/" + "users.json", 'utf8', (err, data) => { data = JSON.parse( data ); data["user4"] = user["user4"]; console.log( data ); res.end( JSON.stringify(data)); }); })
4. Get user details
In this step, we append: id to the URI in the RESTful API to get specific user details:
// index.js // Omitting the previous file only shows the interfaces that need to be implemented // Define an interface to get specific user details app.get('/:id', (req, res) => { // First we read existing users fs.readFile( __dirname + "/" + "users.json", 'utf8', (err, data) => { data = JSON.parse( data ); var user = data["user" + req.params.id] console.log( user ); res.end( JSON.stringify(user)); }); })
5. Delete the specified user
In this step, we will create a deleteUser in the RESTful API to delete the specified user:
// index.js // Omitting the previous file only shows the interfaces that need to be implemented // mock A user id to delete const id = 2; app.get('/deleteUser', (req, res) => { fs.readFile( __dirname + "/" + "users.json", 'utf8', (err, data) => { data = JSON.parse( data ); delete data["user" + id]; console.log( data ); res.end( JSON.stringify(data)); }); })
Reference material
About me
This article was first published in Pingan 8787 Personal Blog If you need to reprint it, please contact me.
Author | Wang Ping'an |
---|---|
pingan8787@qq.com | |
Blog | www.pingan8787.com |
pingan8787 | |
Daily article recommendation | https://github.com/pingan8787... |
ES Brochure | js.pingan8787.com |