Python Restful API Design Specification

Source: Internet
Author: User
Tags representational state transfer

Understanding RESTful Architecture RESTful API Design Guide

Understanding the RESTful architecture

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:

1 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:

1234 POST /transactionHTTP/1.1Host: 127.0.0.1from=1&to=2&amount=500.00

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

123 http://www.example.com/app/1.0/foohttp://www.example.com/app/1.1/foohttp://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):

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

* Note that although the Restfull specification suggests that the version number be placed in the request header instead of the URL, most developers prefer to place the version number on the URL in order to be easy to use, which makes it easier to visually differentiate

  

Restful API Design Guide

Next I will introduce the design details of the RESTful API and discuss how to design a reasonable and useful API

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.

1 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.

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

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

1 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.

123 https://api.example.com/v1/zooshttps://api.example.com/v1/animalshttps://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).

12345 GET(SELECT):从服务器取出资源(一项或多项)。POST(CREATE):在服务器新建一个资源。PUT(UPDATE):在服务器更新资源(客户端提供改变后的完整资源)。PATCH(UPDATE):在服务器更新资源(客户端提供改变的属性)。DELETE(DELETE):从服务器删除资源。

There are also two infrequently used HTTP verbs.

12 HEAD:获取资源的元数据。OPTIONS:获取信息,关于资源的哪些属性是客户端可以改变的。

Here are some examples.

12345678 GET /zoos:列出所有动物园POST /zoos:新建一个动物园GET /zoos/ID:获取某个指定动物园的信息PUT /zoos/ID:更新某个指定动物园的信息(提供该动物园的全部信息)PATCH /zoos/ID:更新某个指定动物园的信息(提供该动物园的部分信息)DELETE /zoos/ID:删除某个动物园GET /zoos/ID/animals:列出某个指定动物园的所有动物DELETE /zoos/ID/animals/ID:删除某个指定动物园的指定动物
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.

12345 ?limit=10:指定返回记录的数量?offset=10:指定返回记录的开始位置。?page=2&per_page=100:指定第几页,以及每页的记录数。?sortby=name&order=asc:指定返回结果按照哪个属性排序,以及排序顺序。?animal_type_id=1:指定筛选条件

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).

123456789101112 200 OK - [GET]:服务器成功返回用户请求的数据,该操作是幂等的(Idempotent)。201 CREATED - [POST/PUT/PATCH]:用户新建或修改数据成功。202 Accepted - [*]:表示一个请求已经进入后台排队(异步任务)204 NO CONTENT - [DELETE]:用户删除数据成功。400 INVALID REQUEST - [POST/PUT/PATCH]:用户发出的请求有错误,服务器没有进行新建或修改数据的操作,该操作是幂等的。401 Unauthorized - [*]:表示用户没有权限(令牌、用户名、密码错误)。403 Forbidden - [*] 表示用户得到授权(与401错误相对),但是访问是被禁止的。404 NOT FOUND - [*]:用户发出的请求针对的是不存在的记录,服务器没有进行操作,该操作是幂等的。406 Not Acceptable - [GET]:用户请求的格式不可得(比如用户请求JSON格式,但是只有XML格式)。410 Gone -[GET]:用户请求的资源被永久删除,且不会再得到的。422 Unprocesable entity - [POST/PUT/PATCH] 当创建一个对象时,发生一个验证错误。500 INTERNAL SERVER ERROR - [*]:服务器发生错误,用户将无法判断发出的请求是否成功。

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.

123 {    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.

123456 GET /collection:返回资源对象的列表(数组)GET /collection/resource:返回单个资源对象POST /collection:返回新生成的资源对象PUT /collection/resource:返回完整的资源对象PATCH /collection/resource:返回完整的资源对象DELETE /collection/resource:返回一个空文档
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.

123456 {"link": {  "rel":   "collection https://www.example.com/zoos",  "href":  "https://api.example.com/zoos",  "title""List of zoos",  "type":  "application/vnd.yourformat+json"}}

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.

12345 {  "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.

1234 {  "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.

  

  

12. Django Rest Framework Best Practices

http://www.cnblogs.com/alex3714/articles/7131523.html

  

  

This article is reproduced from http://www.ruanyifeng.com/blog/2014/05/restful_api.html

Python Restful API Design Specification

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.