A RESTful architecture

I. Overview:

  1. RESTful architecture is the most popular Internet software architecture at present. REST is short for the phrase Representational State Transfer, or “Representational State transformation.” Represents (Internet resources) state transformation at the presentation level.

  2. REST was first mentioned by Dr. Roy Fielding in his paper in 2000 and attracted attention because he was an important figure in the Internet industry (the main designer of the HTTP 1.0/1.1 protocol and the first president of the Apache Open Source Foundation). And it has had a profound impact on the Internet.

  3. RESTful is not a standard, but a specification. Now many software use the application structure of the front and back end separation, which is clear, standard, easy to understand, easy to expand. The front end (H5, Android, iPhone, applets) often exchanges data with the back end by calling apis. Then, apis for software architectures that conform to RESTful specifications can be called RESTful APl. For example, weibo open API and Github open API strictly follow the RESTful specification.

That’s an overview of RESTful architecture. In this article, I’ll use my understanding to fully describe the RESTful specification and how to design apis that conform to it. In fact, in the understanding of computer technology, a hundred people may have a hundred ways of understanding, although different opinions, but our purpose is to use technology as a tool to achieve our program functions. If the description in this article is wrong, or you are confused, feel free to leave a comment!

The following will be divided into three contents to describe my understanding of RESTful:

1. Understand RESTful APIS 2.RESTful API architecture specifications 3

2. RESTful

To understand RESTful, we need to start with every word. Roy Fielding named his architectural principles for Internet software REST, which stands for Representational State Transfer, representing Representational layer State transitions. A software architecture is RESTful if it conforms to REST principles.

1. Resources

In Internet software development, the “resource” we say refers to the specific information of a node in the Internet, such as a text, a picture, a video, a compressed package, a program installation package and so on. In the Internet, we can use a URI (Uniform resource Locator) to represent each specific resource. Therefore, each Internet resource has a unique URI address.

2. Representational

“Resource” is an entity of information. In fact, resources have many forms, such as a piece of text, which can be expressed in the common TXT format, JSON format, or XML format. The specific expression form of “resource” is called the expression layer. In THE HTTP protocol, the content-Type field in the header is specified to describe the specific resource representation. For example, Content-type: text/ HTML indicates text data in HTML format, and Content-Type: text/json indicates text data in JSON format.

1. State Transfer

HTTP is a stateless network protocol. If a client wants to operate a server, it must notify the server of a “state transition”, and this state change is built on the “presentation layer”, which is called “presentation layer state transition”. In THE HTTP protocol, the client notifies the server of a state change by sending a corresponding request. The client uses GET, POST, PUT, and deleteverbs to operate on server resources.

In summary, we can summarize the features of RESTful: a. Each Internet resource has a unique URI address; B. Manipulate resources by manipulating their representation; C. Generally, specific data is expressed in JSON format. C. HTTP is used for the interaction between the client and the server. Each request from the client to the server must contain information necessary to understand the request. D. The client uses GET, POST, PUT, and DELETE to perform status operations on server resources.

RESTful API architecture specifications

REST has no specific design standards, but RESTful is a normalization of design styles. In RESTful API design, different organizations may have different design style specifications, but the overall RESTful style specifications are consistent.

It is also because of this consistent style specification that the API reader can better understand the API, without even reading the documentation, to know a certain “state transition” of a resource that the API is intended to achieve. According to the design style of Github open API or Weibo open API. Here is my summary of the style specification for RESTful apis that I will use for API development in the future.

1. The agreement

The client communicates with the server using HTTP or HTTPS.

2. The domain name

Whenever possible, API applications should be deployed under a proprietary domain name, such as:

https://api.demo.com
Copy the code

If the API is simple, or extension is not considered, it should be placed in a submodule of the project, such as:

https://demo.com/api/
Copy the code

3. API version

You should put the VERSION of the API in the URL. For example, the Weibo open API puts the version number in the URL:

http://api.weibo.com/2/
Copy the code

If we understand the version number as a different representation of the resource, the API version should be placed in the HTTP request header Accept field, such as the open API on Github

Accept: application/vnd.github.v3
Copy the code

Github may have taken a number of factors into account and put the API version of the request at the head of the HTTP request. In fact, if we want to develop an API quickly, using the first form is more intuitive and convenient.

4. The path

For different resources, there is a unique URL, each URL represents a resource, so the URL should be a name, not a verb, and the noun should correspond to the database table name. In general, databases hold collections of data, so the corresponding resources in urls should be plural nouns.

As in Github open API, list an organization’s collection of projects:

https://api.github.com/orgs/:org/projects
Copy the code

In the above URL, orgs represents a collection of organizations, while :org represents the organization name of the collective, and projects represents a specific resource

5. HTTP verbs

Specific types of operations on resources require different HTTP actions from the client. The five commonly used HTTP verbs already correspond to the following:

* GET (Retrieve) : Retrieve resources (one or more items) from the server; * POST (CREATE) : Creates a new resource on the server; * PUT (UPDATE) : Updates the resource on the server (the client provides the full resource after the change); * PATCH (UPDATE) : Updates resources on the server (client provides changed properties); * DELETE (DELETE) : deletes resources from the server.Copy the code

In fact, there are only four most commonly used HTTP verbs originally, namely GET, POST, PUT, and DELETE. PATCH method is newly introduced as a supplement to PUT method, which is used to locally update known resources.

Sometimes, only one property needs to be modified, and developers usually (to save trouble) pass a complete update to the backend with the complete information of the change. In practice, however, partial updates are necessary if performance optimization is to be considered.

6. The filter

In most cases, filtering is required when retrieving server resources, rather than retrieving a complete collection in the database. In this case, filter conditions need to be set. We can concatenate filter conditions into the URL as parameters. As follows:

?limit= 10Get 10 sets of information? page=1&limit= 10# specify 10 messages per page, get page 1 information set
?limit=10&deleted=true  Get the set of 10 items in the database that have been marked for deletion
Copy the code

7. Return

The corresponding HTTP status code is used to inform the client of the result. The following are commonly used HTTP status codes and their description:

Status code describe note
200 OK – success
204 NO CONTENT – NO CONTENT DELETE Returns 204 status code, indicating that the resource does not exist
303 See Other Indicates a reference to another URL, in which case the URL link should be returned
400 Bad request – The server does not understand the client’s request (for example, the parameter is wrong)
401 Unauthorized – No authentication is passed
403 Forbidden-have no access permission
404 Not Found – The resource does Not exist or is unavailable
405 Method Not Allowed – You do Not have permission for this HTTP Method
409 Conflict – Generic conflict If the requested resource conflicts with its current state, the request cannot be completed
410 Gone – The resource does not exist or is unavailable
415 Unsupported media type – Indicates the unsupported media type For example, the server needs the client to make a request using JSON data, and the client uses XML to make the request
429 Too Many Requests – The number of Requests exceeded the limit
500 Internal server error – Server general error If the client request is valid, an accident occurs while the server processes it
503 Service Unavailable – The server is currently unable to process the request If the site is being maintained, the server cannot handle requests
  • Normal: If the data is returned normally, it should be returned to the client using MSG or other keywords as the key name, as follows:
{
"data": ["user_id": 1,"name":"Zhang"."token":"csdcnsdvndsijudsao",]."message":"OK"."code":200
}
Copy the code
  • Error: If an error occurs, you should return the error message to the client using error as the key name
{
"error":"Unauthorized"."code":401
}
Copy the code

For different operations, the server should return results to the user that conform to the following specifications:

GET/Collection: returns a list (array) of resource objects. GET/Collection/Resource: returns a single resource object. POST/Collection: Returns a newly generated resource object. PATCH /collection/resource: Returns the full resource object DELETE /collection/resource: returns an empty documentCopy the code

8.Hypermedia API

A RESTful API is best done with Hypermedia, which provides links to other API methods or to some document in the result so that the user knows what to do next without looking up the document. Github, for example, has done Hypermedia by requesting api.github.com with GET, which returns a list of link locations:

{
  "current_user_url": "https://api.github.com/user"."current_user_authorizations_html_url": "https://github.com/settings/connections/applications{/client_id}"."authorizations_url": "https://api.github.com/authorizations"."code_search_url": "https://api.github.com/search/code?q={query}{&page,per_page,sort,order}"."commit_search_url": "https://api.github.com/search/commits?q={query}{&page,per_page,sort,order}".Copy the code

4. RESTful API Design Examples

The RESTful API style is mainly reflected in the URL. Next, let’s use an example to complete the URL formulation of the RESful API. Suppose we want to develop a simple blogging system that provides a unified interface for H5, Android, iPhone, and applets. Then the default function and the corresponding URL have been requested as follows:

The module function URL HTTP Request Mode
The user User registration Api.demo.com/1.0/users/r… POST
The user The user login Api.demo.com/1.0/users/l… POST
The article Published an article Api.demo.com/1.0/article… POST
The article To view the article Api.demo.com/1.0/article… GET
The article Modify the article Api.demo.com/1.0/article… PUT
The article Delete articles Api.demo.com/1.0/aritcle… DELETE

That’s it.

This article is an original article by the author, no reprint, original author: PHy.XYZ