Understanding the RESTful architecture

Source: Internet
Author: User
Tags representational state transfer

More and more people are beginning to realize that the website is software, and it is a new kind of software.

This "Internet Software" uses the client/server model, which is built on the distributed system and communicates with the Internet, which has the characteristics of high latency (hi latency) and high concurrency.

Website development, can adopt the model of software development completely. But traditionally, the software and the network are two different fields, seldom have the intersection, the software development is mainly for the single machine environment, the network mainly studies the communication between the system. The rise of the Internet has enabled these two areas to converge, and now we have to consider how to develop the software used in the Internet environment.

The restful architecture is one of the most popular Internet software architectures available. Its structure is clear, conforms to the standard, easy to understand, expands conveniently, therefore is getting more and more website adoption.

However, what is a restful architecture is not an easy question to be clear about. Below, I'll talk about the restful architecture I understand.

First, origin

The word rest is from Roy Thomas Fielding in his 2000 doctoral dissertation.

Fielding is a very important person who is the main designer of the HTTP protocol (version 1.0 and 1.1), one of the authors of the Apache server Software, and the first president of the Apache Foundation. As a result, the publication of his paper has attracted much attention and has had a profound impact on the development of the Internet.

He introduces the purpose of writing this paper:

This paper studies the intersection of two frontier----software and network----of computer science. For a long time, software research focuses on the classification of software design, the evolution of design methods, rarely objectively evaluate the impact of different design choices on system behavior. On the contrary, network research focuses on the details of communication behavior between systems, how to improve the performance of specific communication mechanisms, and often ignores the fact that changing the interactive style of the application is more important than changing the interactive protocol and the overall performance. The purpose of my writing is to understand and evaluate the architecture design of Web-based application software in accordance with the principle of architecture, and to obtain a structure with strong function, good performance and suitable communication. "

(This dissertation explores a junction on the frontiers of the both the disciplines in computer Science:software and NETW Orking. Software have long been concerned with the categorization of software designs and the development of design method Ologies, but had rarely been able to objectively evaluate the impact of various design choices on system behavior. Networking, in contrast, was focused on the details of generic communication behavior between systems and Improvin G The performance of particular communication techniques, often ignoring the fact that changing the interaction style of a N application can has more impact on performance than the communication protocols used for that interaction. My work was motivated by the desire to understand and evaluate the architectural design of network-based application Softwa Re through principled use of architectural constraints, thereby obtaining the functional, performance, and social Properti Es desired of an architecture. )

Second, the name

Fielding his architectural principles of Internet software, named rest, the abbreviation of representational state transfer. My translation of this phrase is "presentation layer State transformation".

If a schema conforms to the rest principle, it is called a restful architecture.

The best way to understand the restful architecture is to understand what the phrase representational state transfer means, and what each word represents. If you understand the name, it's easy to see what kind of design rest is.

III. Resource (resources)

The name of rest, "presentation Layer State Transformation", omits the subject. The "presentation layer" actually refers to the "presentation layer" of resources.

The so-called "resources", is an entity on the network, or is a specific information on the network. It can be a piece of text, a picture, a song, a service, in short, is a concrete reality. You can point to it with a URI (Uniform Resource Locator), and each resource corresponds to a specific URI. To get this resource, access its URI so that the URI becomes the address of each resource or a unique identifier.

The so-called "surfing the Internet" is to interact with a series of "resources" on the Internet and invoke its URI.

Iv. Presentation layer (representation)

A "resource" is an information entity that can have a variety of external representations. We take the form of "resources" specifically, called its "presentation Layer" (representation).

For example, text can be expressed in TXT format, can also be used in HTML format, XML format, JSON format, and even binary format can be used, images can be in JPG format, can also be used in PNG format.

The URI represents only the entity of the resource and does not represent its form. Strictly speaking, some URLs last ". html" suffix is unnecessary, because this suffix name represents the format, which belongs to the "presentation layer" category, and the URI should only represent the location of the "resource". Its specific representation should be specified in the header information of the HTTP request with the Accept and Content-type fields, which is the description of the "presentation layer".

V. State transformation (Transfer)

Accessing a Web site represents an interactive process between the client and the server. In this process, data and state changes are bound to be involved.

The Internet Communication Protocol HTTP protocol is a stateless protocol. This means that all States are saved on the server side. Therefore, if the client wants to operate the server, there must be some way to make the server side "state Transfer". And this transformation is based on the expression layer, so is the "Expression Layer state transformation."

The method that the client uses, can only be the HTTP protocol. Specifically, there are four verbs in the HTTP protocol that represent the mode of operation: GET, POST, PUT, DELETE. They correspond to four basic operations: get is used to get a resource, post is used to create a new resource (and can also be used to update resources), put is used to update resources, and delete is used to delete resources.

Vi. Summary of

Combining the above explanations, we summarize what a restful architecture is:

(1) Each URI represents a resource;

(2) between the client and the server, the transmission of such resources of some kind of performance layer;

(3) The client through four HTTP verbs, the server-side resources to operate, to achieve "performance layer State transformation."

Seven, misunderstanding

The restful architecture has some typical design pitfalls.

One of the most common design errors is that the URI contains verbs. Because "resource" represents an entity, it should be a noun, the URI should not have verbs, the verb should be placed in the HTTP protocol.

For example, a URI is/POSTS/SHOW/1, where show is a verb, the URI is wrong, the correct wording should be/posts/1, and then the show is represented by a GET method.

If certain actions are not represented by an HTTP verb, you should make the action a resource. such as online remittance, from account 1 to account 2 remittance 500 yuan, the wrong URI is:

Post/accounts/1/transfer/500/to/2

The correct way of writing is to change the verb transfer to a noun transaction, the resource cannot be a verb, but it can be a service:

Post/transaction http/1.1
host:127.0.0.1
  
from=1&to=2&amount=500.00

Another design mistake is to include the version number in the URI:

Http://www.example.com/app/1.0/foo

Http://www.example.com/app/1.1/foo

Http://www.example.com/app/2.0/foo

Because different versions can be understood as different representations of the same resource, the same URI should be used. The version number can be distinguished in the Accept field of the HTTP request header information (see Versioning REST Services):

Accept:vnd.example-com.foo+json; version=1.0

Accept:vnd.example-com.foo+json; version=1.1

Accept:vnd.example-com.foo+json; version=2.0

=============================================================================================================== ====================

RESTful API Design Guide

The Web application is divided into two parts, front end and back end. The current trend is the emergence of the front-end equipment (mobile phones, tablets, desktop computers, other special equipment ...). )。

Therefore, there must be a unified mechanism to facilitate the communication of different front-end devices to the backend. This led to the popularity of API architecture, and even the "API first" design idea. RESTful API is currently a relatively mature set of Internet Application API design theory. I've written an understanding of the restful architecture and explored how to understand the concept.

Today, I will introduce the design details of the RESTful API and explore how to design a reasonable and usable API. My main reference is two articles.

First, the agreement

The API communicates with the user protocol, always using the HTTPS protocol.

Second, the domain name

The API should be deployed under a dedicated domain name whenever possible.

https://api.example.com

If you determine that the API is simple, there is no further extension, consider placing it under the primary domain name.

https://example.org/api/
Third, version (Versioning)

The version number of the API should be placed in the URL.

https://api.example.com/v1/

Another option is to place the version number in the HTTP header information, but not as convenient and intuitive as placing the URL. GitHub uses this approach.

Iv. Path (Endpoint)

The path is also called the "End point" (endpoint), which represents the specific URL of the API.

In a restful architecture, each URL represents a resource (resource), so there can be no verbs in the URL, only nouns, and nouns often correspond to the table names in the database. In general, the tables in the database are "collections" (collection) of the same record, so nouns in the API should also use complex numbers.

For example, there is an API that provides information about zoos, as well as information about various animals and employees, and its path should be designed as follows.

  • Https://api.example.com/v1/zoos
  • Https://api.example.com/v1/animals
  • Https://api.example.com/v1/employees
V. HTTP verbs

For the specific operation type of the resource, it is represented by an HTTP verb.

The usual HTTP verbs have the following five (the corresponding SQL command in parentheses).

  • GET (SELECT): Remove resources from the server (one or more items).
  • POST (Create): Creates a new resource on the server.
  • PUT (UPDATE): Updates the resource on the server (the client provides a full resource after the change).
  • PATCH (UPDATE): Updates the resource on the server (the client provides changed properties).
  • Delete: Deletes a resource from the server.

There are also two infrequently used HTTP verbs.

  • HEAD: Gets the metadata for the resource.
  • OPTIONS: Gets information about which properties of a resource are available to the client to change.

Here are some examples.

  • Get/zoos: List all Zoos
  • Post/zoos: Create a new zoo
  • GET/ZOOS/ID: Get information about a given zoo
  • PUT/ZOOS/ID: Update information for a designated zoo (all information about the zoo)
  • PATCH/ZOOS/ID: Update information for a given zoo (some information about the zoo)
  • DELETE/ZOOS/ID: Delete a zoo
  • Get/zoos/id/animals: List all animals in a designated zoo
  • DELETE/ZOOS/ID/ANIMALS/ID: Delete a designated animal from a designated zoo
Vi. filtering information (Filtering)

If the number of records is large, the server will not be able to return them to the user. The API should provide parameters to filter the returned results.

The following are some common parameters.

  • ? limit=10: Specifies the number of records returned
  • OFFSET=10: Specifies the start position of the returned record.
  • ? page=2&per_page=100: Specifies the number of pages, and how many records per page.
  • ? SORTBY=NAME&ORDER=ASC: Specifies which property The returned result is sorted by, and the sort order.
  • ? Animal_type_id=1: Specifying Filter criteria

The design of the parameter allows redundancy, which allows the API path and URL parameters to be duplicated occasionally. For example, the meaning of Get/zoo/id/animals and Get/animals?zoo_id=id is the same.

State code (status Codes)

The status code and prompt information returned by the server to the user is usually the following (the HTTP verb corresponding to the status code in square brackets).

  • $ OK-[GET]: The server successfully returns the data requested by the user, the operation is idempotent (idempotent).
  • 201 CREATED-[Post/put/patch]: User new or modified data succeeded.
  • 202 Accepted-[*]: Indicates that a request has entered the background queue (asynchronous task)
  • 204 NO CONTENT-[delete]: User deleted data successfully.
  • INVALID request-[Post/put/patch]: The user has made an error, the server does not make a new or modified data operation, the operation is idempotent.
  • 401 Unauthorized-[*]: Indicates that the user does not have permissions (token, user name, password error).
  • 403 Forbidden-[*] indicates that the user is authorized (as opposed to a 401 error), but access is forbidden.
  • 404 Not FOUND-[*]: The user makes a request against a nonexistent record, the server does not operate, the operation is idempotent.
  • 406 Not acceptable-[GET]: User requested format is not available (such as user request JSON format, but only XML format).
  • 410 Gone-[get]: The resource requested by the user is permanently deleted and will no longer be available.
  • 422 unprocesable Entity-[Post/put/patch] A validation error occurs when an object is created.
  • $ INTERNAL Server Error-[*]: The server is having errors and the user will not be able to determine if the request was successful.

See here for a complete list of status codes.

Viii. error handling (handling)

If the status code is 4xx, you should return an error message to the user. In general, error is used as the key name in the returned information, and error information is used as the key value.

{    error: "Invalid API key"}
Ix. Return of results

For different operations, the results returned by the server to the user should conform to the following specifications.

  • Get/collection: Returns a list of resource objects (arrays)
  • Get/collection/resource: Returns a single Resource object
  • Post/collection: Returns the newly generated resource object
  • Put/collection/resource: Returns the full resource object
  • Patch/collection/resource: Returns the full resource object
  • Delete/collection/resource: Returns an empty document
X. hypermedia API

The RESTful API is best done by hypermedia, which provides links to the returned results, connecting to other API methods, so that users do not look up documents and know what to do next.

For example, when a user makes a request to the root directory of api.example.com, a document is obtained.

{ "link" { "rel" : " collection Https://www.example.com/zoos " :  "Https://api.example.com/zoos"  "title ": " List of zoos ", Span class= "token string" > "type" : }}     

The code above indicates that there is a link property in the document, and the user reads this property and knows what API to call next. Rel represents the relationship between this API and the current URL (collection relationship, and gives the collection URL), the href represents the path to the API, title represents the API's caption, and type represents the return type.

The design of the Hypermedia API is known as Hateoas. The GitHub API is the design that accesses api.github.com to get a list of URLs for all available APIs.

{  "current_user_url": "https://api.github.com/user", "authorizations_url": "https://api.github.com/authorizations",  // ...}

As you can see from the above, if you want to get information about the current user, you should go to the api.github.com/user and get the results below.

{  "message": "Requires authentication", "documentation_url": "https://developer.github.com/v3"}

The above code indicates that the server gives the prompt information and the URL of the document.

Xi. Other

(1) The identity authentication of the API should use the OAuth 2.0 framework.

(2) The data format returned by the server should use JSON as much as possible to avoid using XML.

Finish

Understanding the RESTful architecture

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.