First, concept introduction

1. The concept of REST

REST (Representational State Transfer) is a design style and development method of network applications. It defines a common format for accessing resources.

In terms of concepts, you need to understand the following names:

  1. Resources

Anything that’s retrieved from the server any resource, a user’s record, a user’s password, a picture, whatever.

  1. Representation of resources

Resource formats, HTML, XML, JSON, plain text, images, etc., can be used in a variety of formats to represent the resources you have obtained.

  1. State Transfer

That is, urls locate resources and use HTTP verbs (GET,POST,DELETE,DETC) to describe operations. Operations are verbs, resources are nouns.

  1. Uniform Interface

That is, a unified interface is used to operate resources.

2. The REST

REST is generally based on the use of existing widely popular protocols and standards such as HTTP, URI, and XML and HTML, each URI representing a resource.

REST typically uses a JSON data format.

There are four approaches to the basic REST architecture:

  • GET – Used to GET data

  • PUT – Updates or adds data

  • DELETE – Deletes data

  • POST – Used to add data

The following scenario will be introduced.

3. The REST

  • Caching can be used more efficiently to improve response times
  • The statelessness of communication itself allows different servers to handle different requests in a series of requests, improving server scalability
  • The browser can act as a client, simplifying the software requirements
  • REST is less software dependent than other mechanisms that are superimposed on the HTTP protocol
  • No additional resource discovery mechanism is required
  • Long-term compatibility in software technology evolution is better

2. Introduction of examples

REST defines a common access format for resources. Here is a consumer example of RESTful API definitions:

  1. Get all users
GET /api/users
Copy the code
  1. Gets users with the specified ID
GET /api/users/100
Copy the code
  1. Create a Users record
POST /api/users
Copy the code
  1. Update a Users record
PUT /api/users/100
Copy the code
  1. Delete a users record
DELETE /api/users/100
Copy the code
  1. Gets all the bills for a users account
GET  /api/users/100/bill
Copy the code
  1. Gets a bill for the time specified by the user
GET /api/users/100/bill? from=201910&to=201911Copy the code

Most of the RESTful apis above cover common business situations.

Nodejs implements RESTful apis

1. Initialize mock data

This example uses 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}}Copy the code

We will implement the following RESTful apis:

2. Obtain the user list

In this step we will create /users in the RESTful API and use GET to read the list of users:

// index.js
const express = require('express');
const app = express();
const fs = require("fs");

// Define the interface to read the user's information list
app.get('/users'.(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);
})
Copy the code

3. Add a user

In this step we will create /users in the RESTful API and use POST to add user records:

// index.js
// Omit the previous file to show only the interfaces to be implemented

// Mock a line of data to add
const user = {
   "user4" : {
      "name" : "pingan"."password" : "password4"."profession" : "teacher"."id": 4}}// Define the interface to add user records
app.post('/users'.(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));
   });
})
Copy the code

4. Obtain user details

/users/:id = /users/:id = /users/:id = /users/:id

// index.js
// Omit the previous file to show only the interfaces to be implemented

// Define the interface to get the details of the specified user
app.get('/users/:id'.(req, res) = > {
   // First we read the existing user
   fs.readFile( __dirname + "/" + "users.json".'utf8'.(err, data) = > {
       data = JSON.parse( data );
       const user = data["user" + req.params.id] 
       console.log( user );
       res.end( JSON.stringify(user));
   });
})
Copy the code

5. Delete the specified user

In this step we will create /users in the RESTful API and use DELETE to DELETE the specified user:

// index.js
// Omit the previous file to show only the interfaces to be implemented

// Mock the user ID to delete
const id = 2;

app.delete('/users'.(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));
   });
})
Copy the code

REST best practices

1. The URL design

1.1 Operation instruction structure of “verb + object”

The data manipulation instructions sent by the client are “verb + object” structure.

As mentioned above, GET /user is a command where GET is the verb and /user is the object. According to the HTTP specification, verbs are capitalized.

Verbs usually have the following five HTTP methods:

GET: Read: POST: Create: PUT: Update: PATCH: Update: PATCH: DELETE: DELETE

1.2 The object must be a noun

The object is the API URL, which is the object of the HTTP verb. It should be a noun, not a verb.

For example, /users is correct because the URL is a noun, and the following are all wrong:

/getUsers
/createUsers
/deleteUsers
Copy the code

1.3 Multiple urls are recommended

Since urls are nouns, there is no limit to whether they are singular or plural, but it is advisable to use the plural form if it is a collection. Such as GET /users to read the list of all users.

1.4 Avoiding Multi-level urls

Avoid using multilevel urls for multilevel resources. A common example is to get a certain type of product purchased by a user:

GET /users/100/product/120
Copy the code

The semantics of this URL are unclear, and it is not easy to expand. It is recommended that only the first level be used, and other levels be expressed by query strings:

GET /users/100? product=120Copy the code

2. Accurate status code representation

There are more than 100 types of HTTP status codes, and each type of status code has a standard (or convention) interpretation. The client can determine what is happening simply by looking at the status code, so the server should return the status code as accurately as possible.

Here are some commonly used status codes:

  • 303 See Other: Refers to another URL.

  • 400 Bad Request: The server does not understand the Request from the client and does not perform any processing.

  • 401 Unauthorized: The user does not provide authentication credentials or fails to pass authentication.

  • 403 Forbidden: Users are authenticated but do not have the required permissions to access resources.

  • 404 Not Found: The requested resource does Not exist or is Not available.

  • 405 Method Not Allowed: The user has been authenticated, but the HTTP Method used is Not within his permissions.

  • 410 Gone: The requested resource has been moved from this address and is no longer available.

  • 415 Unsupported Media Type: The return format required by the client is not supported. For example, the API can only return JSON, but the client requires XML.

  • 422 Unprocessable Entity: The request fails because the attachment uploaded by the client cannot be processed.

  • 429 Too Many Requests: The number of Requests from the client exceeded the threshold.

  • 500 Internal Server Error: The client request is valid, but an accident occurs when the Server processes it.

  • 503 Service Unavailable: The server cannot process the request, which is generally used for website maintenance status.

3. The server responds

3.1 Should return a JSON object

The format of the data returned by the API should be JSON as an object.

3.2 Do not return the 200 status code when an error occurs

When an error occurs, if the 200 status code is also returned, the front end will need to parse the returned data to know the error message, which in effect canceles the status code, which is not appropriate.

The correct way to do this is to return the corresponding error status code and return the error message:

HTTP/1.1 400 Bad Request Content-Type: Application /json {"error": "Invalid payoad.", "detail": {"surname": "This field is required." } }Copy the code

The resources

  1. Wikipedia – Presentation Layer State Transitions
  2. RESTful springMVC
  3. Node.js RESTful API
  4. RESTful API Best Practices