1. The introduction

Before we look at RESTful apis, let’s look at what REST is. The entire article is mainly illustrated with HTTP

1.1 REST meaning

REST: The full name is Resource Representational State Transfer, or Representational State Transfer. It is an API design concept for Internet applications (urls can be used to locate resources and HTTP verbs to describe operations), a software architecture style, a design style, not a standard.

Resource: An entity or specific piece of information on a network. This may be a piece of text, an image, a video or a service, and we use a URI to uniquely point to a specific representation of a resource: A resource is an information entity that can be represented in various forms, such as JSON and XML. The specific representation of a resource should be specified in the HTTP request header using Accept and Content-Type fields. State Transfer: User access to the website is actually an interactive process between the client and the server. In this process, both sides continue to establish connections for communication, which is bound to involve changes in data and State

1.2 The six Principles of REST

  • C – S architecture

The data is stored on the Server, and the Client only needs to use it. Both ends develop separately without interference

  • stateless

HTTP requests are stateless. Based on the C-S architecture, each request from the client carries sufficient information for the server to recognize. The server can return the correct response to the client based on the various parameters of the request without saving the state of the client.

  • Unified interface

The core content of REST architecture, unified interface can let the client only need to focus on the implementation of the interface, the interface is more readable, easy to use personnel call.

REST interface constraints are defined as: the resource you want to manipulate is identified by a URI, the action you want to perform is identified by a request action (HTTP Method), and the result of the request is represented by a status code returned.

  • Consistent data formats

The data returned by the server is either XML, Json (retrieve data), or simply a status code

  • cacheable

On the World Wide Web, a client can cache the response content of a page. Therefore, responses should be defined as cacheable either implicitly or explicitly. If they are not cacheable, clients should be prevented from responding with old or dirty data after multiple requests.

  • Code as needed, customizable code

REST allows clients to extend client functionality by downloading and executing scripts from the server. This can simplify the development of client functions, such as common mobile webView, Web mini-games and so on. [This principle is optional constraint]

2. What is RESTful architecture/style

An architecture that conforms to REST principles is called a RESTful architecture or style.

In REST design guidelines, only code on demand is optional. If any of the other criteria are violated, it is not technically a RESTful architecture.

RESTFul architecture can be summarized as follows:

Use URIs to locate specific resources. The content-Type field of the HTTP request is used to describe the representation of the resource. The four VERBS of HTTP (GET, POST, PUT, and PATCH) are used to describe specific operations on resources.

3. What is RESTful API

You can think of it as an API built on REST. It’s a concrete implementation of RESTFul architecture.

The biggest benefit of RESTful apis is that when someone else uses your API, they know what to do next, even if they don’t have to look at the documentation

4. Why RESTful apis

In “ancient times”, front-end and back-end were integrated together, such as PHP and JSP before, but with the development of mobile Internet in recent years, various clients emerged in endlessly: Web, IOS and Android. There was a need for a mechanism for various clients to communicate with the server, which made RESTful architecture popular. The RESTful architecture is as follows:

5. How to design RESTful apis

  1. Format specification

As defined by RFC3986, urls are case sensitive. So to avoid ambiguity, use lowercase letters.

RESTful apis should be readable. When a segment in a URL consists of multiple words, use hyphens (-) instead of underscores (_) to separate words.

/api/featured-post/		# GOOD
/api/featured_post/		# WRONG
Copy the code
  1. agreement

Use HTTPs as much as possible to provide apis for users. Using HTTPs or HTTP itself is irrelevant to RESTful apis, but it is important to improve the security of your site

  1. Version control
  • You should put the API version number in the URL: api.example.com/v1/
  • The alternative is to put the version number in the HTTP header, but it’s not as convenient and intuitive as putting it in the URL.
  1. The domain name

The API should be deployed under a private domain as much as possible

https://api.example.com
Copy the code
  1. Use plural nouns in URLS

The nouns used often correspond to the names of tables in a database, which is a collection of records. Therefore, nouns in URLS represent a collection of resources, so nouns in URIs should be plural

  1. Urls cannot use verbs

In a RESTful architecture, each URL represents a resource, so there can be no verbs in a URL, only nouns

  1. Use HTTP verbs correctly
GET: obtains resources from the server. POST: creates a resource on the server. PUT: updates resources on the server (the client provides changed resources) PATCH: updates resources on the server (the client provides changed attributes) DELETE: deletes resources from the serverCopy the code
GET		https://api.example.com/v1/schools 					# List all schools
POST	https://api.example.com/v1/schools 					# Build a new school
GET		https://api.example.com/v1/schools/ID				# list the information of the specified school
DELETE	https://api.example.com/v1/schools/ID				# delete the specified school
GET		https://api.example.com/v1/schools/ID/students		# list all the students in the specified school
DELETE	https://api.example.com/v1/schools/ID/students/ID	Delete a specified student from a specified school
Copy the code
  1. Status code

Status code and prompt message returned by the server to the user

1xx: related information is requested. 2xx: The operation succeeds. 3xx: the redirection is successfulCopy the code

Common ones are as follows:

200 OK - [GET] : the server successfully returns the requested data, which is Idempotent. 201 CREATED - [POST/PUT/PATCH] : Data is CREATED or modified successfully. 202 Accepted - [*] : indicates that a request is queued in the background (an asynchronous task). 204 NO CONTENT - [DELETE] : Indicates that the user deleted data successfully. 400 INVALID REQUEST - [POST/PUT/PATCH] : An error occurs in the REQUEST sent by the user. The server does not create or modify data. The operation is idempotency. 401 Unauthorized - [*] : Indicates that the user does not have permission (the token, user name, or password is incorrect). 403 Forbidden - [*] Indicates that the user is authorized (as opposed to the 401 error), but access is Forbidden. 404 NOT FOUND - [*] : The user requested a record that did NOT exist, the server did NOT perform the operation, the operation is idempotent. 406 Not Acceptable - [GET] : The format requested by the user is Not available (for example, the user requested JSON format, but only XML format). 410 Gone -[GET] : The requested resource is permanently deleted and cannot be retrieved. 422 Unprocesable Entity - [POST/PUT/PATCH] An authentication error occurred while creating an object. 500 INTERNAL SERVER ERROR - [*] : An ERROR occurs on the SERVER, and users cannot determine whether the request is successful.Copy the code
  1. Use query parameters wisely

The parameter specifications are similar to the following

?limit=10: Specifies the number of records to return? Offset =10: Specifies the start of the return record. ? Page =2&per_page=100: Specifies the number of pages and the number of records per page. ? Sortby = name&ORDER = ASC: Specifies by which attribute the return results are sorted, and in what order. ? Animal_type_id =1: Specifies a filter conditionCopy the code
  1. Error handling

If the status code is 4XX, an error message should be returned to the user. In general, error is returned as the key name and the error message as the key value.

{
    error: "Invalid API key"
}
Copy the code

6. Summary

RESTful is an API design style, not a mandatory specification or standard. It is characterized by concise and readable requests and responses.

The main concerns are as follows:

Stateless request URL = Action (GET/POST/PUT/DELETE) + Resource response using exact status code and JSON-formatted dataCopy the code

Use inverse and forward column references:

💣 💣 💣The wrong wayhttp://example.com/api/getallUsers / / http://example.com/api/getuser/1 / GET access to all users/GET access to user information identified as 1 HTTP: / / http://example.com/api/user/delete/1 / / GET/POST to delete logo for 1 user information HTTP: / / http://example.com/api/updateUser/1 / / POST updates are identified as 1 user information HTTP: / / http://example.com/api/User/add / / POST to add a new userCopy the code
👏 👏 👏# Formalized RESTful urls, fixed form, readable, can manipulate these resources according to the Users noun and HTTP verb.http://example.com/api/users / / / / GET access to all the users information http://example.com/api/users/1 GET identified as 1 user information http://example.com/api/users/1 / http://example.com/api/users/1 / DELETE DELETE logo for 1 user information/update/Patch are identified as one of information users, included in the div HTTP: / / http://example.com/api/users / / POST to add a new userCopy the code

References:

  • RESTful API design Guide
  • Do you really understand RESTful apis