A text interpretation of a RESTful (rpm)

01 Introduction

Return to the topic, read a lot of articles related RESTful summary, the Senate Qi missing, used in conjunction with work, is necessary to summarize the way on RESTful architecture, an architectural constraints RESTful only way to give a standard agreed fully RESTful strict compliance with standards is not a lot, it is not necessary. But in practice, there may be RESTful standard reference, it is very necessary.

Actually api interface specification, naming the return value, authorized certain validation constraints at work, as long as the general project api easy to test, safe enough, strong style consistent readability, I think there is no ambiguity calls easy enough the interface is for developers to see, nor to the general user to call.

Source 02 RESTful of

REST: Representational State Transfer (state transition layer appearance), if heard REST, you must have thought of this word is rest, first I think so, later found to be an abbreviation of these three words, even if they know these three to understand words is still very obscure. How to understand RESTful architecture, the best way is a deep understanding of Representational State Transfer digest what these three words mean in the end.

1. Each URI representative of a resource;

between the client and the server 2, the performance of certain layers of this transfer of resources;

3. four client via HTTP verbs (get, post, put, delete ), the server end manipulate resources to achieve "the state of the presentation layer transformation."

By American computer scientist Roy Fielding (Baidu Encyclopedia does not describe, really embarrassing). One of the first chief scientist of Adobe, Http agreement, Apache co-founder of the project.

03 RESTful6 principle

Father Roy Fielding described REST six principles of REST architecture in the paper.

1. CS architecture

Server-side data stored in, Client-side just use on the line. Benefits that the complete separation of the two ends of client-side code portability becomes strong, end Server scalability becomes strong. Separate development ends, without disturbing each other.

2. Stateless

http request itself is stateless, CS-based architecture, the client's every request with sufficient information to enable the server to identify. Some of the information needed to query parameters are included in the request URL's, header, body, server requests can be based on various parameters, without having to save the client state, the correct response is returned to the client. Robustness and scalability stateless feature greatly improves the service side.

Of course, this overall stateless constraint is flawed, every client request must be repeated to bring the same information to determine their identity and status (this is required), resulting in the transmission data redundancy, but this for determining the performance and use, it is almost negligible.

3. unified interface

This core is the REST architecture, unified interface is very important for RESTful services. Clients only need to focus on implementing the interface can, readability strengthen the interface, use of personnel to facilitate the call.

4. consistent data format

The server returns the data format is either XML, either Json (data acquisition), or directly return the status code, are interested can look at the open platform of the blog park operation data api, post, put, patch are returned a status code.

Self-describing information, each item of data should be self-describing code to facilitate handling and parsing its contents. For example, by HTTP data returned there [MIME type] information, we can know from the MIME type inside the specific format of data, images, videos or JSON, the client through the body content, query string parameters, request headers and URI (resource name ) to transmit state. By body content server, and the response code in response to the first transfer state to the client. This technique is called hypermedia (or hypertext links).

In addition to the above, HATEOS also means that, when necessary, may also be included in the link returned body (or head), to provide the URI to retrieve the associated object or the object itself. This will be explained in more detail.

Such as a micro-blog information request, the server response should contain information related to this microblogging other URL, clients can further use these URL initiates a request to obtain information of interest, another example, paging can be obtained from the first page of returned data Next the URT is also based on this principle.

4. The system hierarchy

The client usually can not show that they are directly or indirectly connected with the terminal server, the same should be considered when layered security policy.

5. cacheable

On the World Wide Web, the client can cache the response content of the page. Thus the response should be explicitly defined or implicitly to be cached, the cache will have to be avoided if the client can not use the old data or dirty data in response to the multiple requests. Properly managed cache may be partially or completely the interaction between the client and server to remove, to further improve performance and scalability.

6. The coding demand can be custom code (optional)

Choose a temporary server to the client delivers some functional code allows the client to perform, to customize and extend some of the features of the client. For example, the server may return some Javascript code that allows the client to perform, to achieve certain functions.
Tip: REST architecture, design criteria, the only on-demand encoding is optional. If a service violates any of the other criteria, on the strict meaning it can not be called RESTful style.

03 RESTful of 7 Best Practices

1. Version

As github open platform
https://developer.github.com/v3/ 

is to release on the url, concise, this is only used to know, the general project plus version v1, v2, v3? Well, this plus version estimated that only large companies and the project will be to use, say it is not afraid of embarrassment, I really have not used. Some will be placed header inside the version number, but not as url straightforward.

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

2. Parameter naming convention

query parameter can be used hump nomenclature, underscore naming way can also be used, recommended naming underlined the way, is said to recognition of the latter than the former is much higher, perhaps more people use it, vary due to team specifications vary it.

https://example.com/api/users/today_login 获取今天登陆的用户 
https://example.com/api/users/today_login&sort=login_desc 获取今天登陆的用户、登陆时间降序排列

3.url naming convention

API naming convention should adopt the way, keep it simple and clear. In a RESTful architecture, each represents a resource url url so can not have a verb, a noun only, and should also use the plural noun. Implemented should use appropriate verbs Http GET, POST, PUT, PATCH, DELETE, HEAD these resources can be operated

The non-standard url, redundancy does not make sense, form is not fixed, different developers also need to understand the document before calling.

https://example.com/api/getallUsers GET 获取所有用户 
https://example.com/api/getuser/1 GET 获取标识为1用户信息 
https://example.com/api/user/delete/1 GET/POST 删除标识为1用户信息 
https://example.com/api/updateUser/1 POST 更新标识为1用户信息 
https://example.com/api/User/add POST 添加新的用户

After the specification for RESTful url, fixed form, readable, according to http verbs and nouns users can operate these resources

https://example.com/api/users GET 获取所有用户信息 
https://example.com/api/users/1 GET 获取标识为1用户信息 
https://example.com/api/users/1 DELETE 删除标识为1用户信息 
https://example.com/api/users/1 Patch 更新标识为1用户部分信息,包含在body中 
https://example.com/api/users POST 添加新的用户

4. Back unified data format

For legitimate request should return a unified data format, demonstrated here is json

  • code-- integer type comprising a status code of the HTTP response.
  • status-- contains the text: "success", "fail" or "error". HTTP status code in the response between 500-599 as "fail", is between 400-499 "error", others are "success" (e.g.: in response to a status code 1XX, 2XX, and 3XX). This fact is based on the actual situation can not happen in the.
  • message-- state is "fail" and "error" effective when used to display error messages. Referring to international (il8n) standard, which may contain information number or code that may contain only one, or both comprising and separated by separator.
  • data-- body containing the response. When the state is "fail" or "error", data comprising only cause of the error or exception name, or null is also possible

Returns successful response json format

{
  "code": 200,
  "message": "success",
  "data": { "userName": "123456", "age": 16, "address": "beijing" } }

Returns a failure response format json

{
  "code": 401,
  "message": "error  message",
  "data": null }

The following ApiResult generic class is used in the project, strong expansion, easy to use. The return value using a unified ApiResult or ApiResult
error return using ApiResult.Error be returned; successful return, be required to return ApiResult.Ok

public class ApiResult: ApiResult
    {
        public new static ApiResult<T> Error(string message) { return new ApiResult<T> { Code = 1, Message = message, }; } [JsonProperty("data")] public T Data { get; set; } } public class ApiResult { public static ApiResult Error(string message) { return new ApiResult { Code = 1, Message = message, }; } public static ApiResult<T> Ok<T>(T data) { return new ApiResult<T>() { Code = 0, Message = "", Data = data }; } /// <summary> /// 0 是 正常 1 是有错误 /// </summary> [JsonProperty("code")] public int Code { get; set; } [JsonProperty("msg")] public string Message { get; set; } [JsonIgnore] public bool IsSuccess => Code == 0; }

5. http status code

When xamarin android blog park customers before the end of the development, patch, delete, body response which no post operation, with only http status code. HTTP status code meaning in itself sufficient, according to http status code can know delete, add, modify and so successful. (ps: linux design a little taste Oh, no return message is good news, it said that it has succeeded) to return these services segment status code is not a mandatory constraint to the user. Simply put, you can specify these states, but not mandatory. Common HTTP status code table
HTTP status code is a regular

  • 1 ** request did not succeed
  • 2 ** request succeeds, the processing of the status code indicates a successful request.
  • 3 ** request is redirected, to fulfill the request indicates the need for further operations. Typically, these status codes for redirection.
  • 4 ** request error status code indicates the request may be wrong, preventing the processing server.
  • 5 ** (Server Error) These status codes indicate internal server error occurred while trying to process the request. These errors may be wrong server itself, not with the request.

    6. rational use query parameter

    When the requested data, the client will often filter the data and paging requirements, parameters which are recommended manner of HTTP Query Parameter
比如设计一个最近登陆的所有用户
https://example.com/api/users?recently_login_day=3
搜索用户,并按照注册时间降序
https://example.com/api/users?recently_login_day=3
搜索用户,并按照注册时间升序、活跃度降序
https://example.com/api/users?q=key&sort=create_title_asc,liveness_desc
关于分页,看看博客园开放平台分页获取精华区博文列表
https://api.cnblogs.com/api/blogposts/@picked?pageIndex={pageIndex}&pageSize={pageSize} 
返回示例: 
[ 
{ 
“Id”: 1, 
“Title”: “sample string 2”, 
“Url”: “sample string 3”, 
“Description”: “sample string 4”, 
“Author”: “sample string 5”, 
“BlogApp”: “sample string 6”, 
“Avatar”: “sample string 7”, 
“PostDate”: “2017-06-25T20:13:38.892135+08:00”, 
“ViewCount”: 9, 
“CommentCount”: 10, 
“DiggCount”: 11 
}, 
{ 
“Id”: 1, 
“Title”: “sample string 2”, 
“Url”: “sample string 3”, 
“Description”: “sample string 4”, 
“Author”: “sample string 5”, 
“BlogApp”: “sample string 6”, 
“Avatar”: “sample string 7”, 
“PostDate”: “2017-06-25T20:13:38.892135+08:00”, 
“ViewCount”: 9, 
“CommentCount”: 10, 
“DiggCount”: 11 
} 
]

7. multi-table, multi-join queries on how to design parameters URL

This is a more difficult problem, doing a single entity queries easier and standardize operations, but in the actual API is not as simple as that, which are often designed to connect multi-table, multi-condition filter, sort, and so on.
For example, I would like to query a user and obtain the address is greater than $ 500 in June orders in Beijing, users aged 22 to 40 years old, the amount of the purchase order list in descending order of

https://example.com/api/orders?order_month=6&order_amount_greater=500&address_city=北京&sort=order_amount_desc&age_min=22&age_max=40

URL from this point of view, too many parameters have to call up one by one carefully against, and the API itself is very easy to maintain, naming it seems not very easy, not too long, not too casual.

In total we can use .net WebAPI property route, the route is to say route attributes attached to a specific controller or method of operation and use of decorative Controll [the Route] attribute defines the routing method for routing called attributes.

This benefit is the ability to precisely control the URL, rather than the agreed-based routing, this is simply for the multi-table queries like the tailor. From webapi 2 development, the development of RESTful API is now the most preferred route type.
We can mark Route in the Controll

[Route(“api/orders/{address}/{month}”)] 

Action in the amount of query parameters only, sort, age. Reduce the query parameters, API line readability and maintainability is enhanced.

https://example.com/api/orders/beijing/6?order_amount_greater=500&sort=order_amount_desc&age_min=22&age_max=40

This attribute of the route, such as the blog garden open API also has applications in this area, such as access to a personal blog essays List

请求方式:GET 
请求地址:https://api.cnblogs.com/api/blogs/{blogApp}/posts?pageIndex={pageIndex} 
(ps:blogApp:博客名)
 
 

Return to the topic, read a lot of articles related RESTful summary, the Senate Qi missing, used in conjunction with work, is necessary to summarize the way on RESTful architecture, an architectural constraints RESTful only way to give a standard agreed fully RESTful strict compliance with standards is not a lot, it is not necessary. But in practice, there may be RESTful standard reference, it is very necessary.

Actually api interface specification, naming the return value, authorized certain validation constraints at work, as long as the general project api easy to test, safe enough, strong style consistent readability, I think there is no ambiguity calls easy enough the interface is for developers to see, nor to the general user to call.

Source 02 RESTful of

REST: Representational State Transfer (state transition layer appearance), if heard REST, you must have thought of this word is rest, first I think so, later found to be an abbreviation of these three words, even if they know these three to understand words is still very obscure. How to understand RESTful architecture, the best way is a deep understanding of Representational State Transfer digest what these three words mean in the end.

1. Each URI representative of a resource;

between the client and the server 2, the performance of certain layers of this transfer of resources;

3. four client via HTTP verbs (get, post, put, delete ), the server end manipulate resources to achieve "the state of the presentation layer transformation."

By American computer scientist Roy Fielding (Baidu Encyclopedia does not describe, really embarrassing). One of the first chief scientist of Adobe, Http agreement, Apache co-founder of the project.

03 RESTful6 principle

Father Roy Fielding described REST six principles of REST architecture in the paper.

1. CS architecture

Server-side data stored in, Client-side just use on the line. Benefits that the complete separation of the two ends of client-side code portability becomes strong, end Server scalability becomes strong. Separate development ends, without disturbing each other.

2. Stateless

http request itself is stateless, CS-based architecture, the client's every request with sufficient information to enable the server to identify. Some of the information needed to query parameters are included in the request URL's, header, body, server requests can be based on various parameters, without having to save the client state, the correct response is returned to the client. Robustness and scalability stateless feature greatly improves the service side.

Of course, this overall stateless constraint is flawed, every client request must be repeated to bring the same information to determine their identity and status (this is required), resulting in the transmission data redundancy, but this for determining the performance and use, it is almost negligible.

3. unified interface

This core is the REST architecture, unified interface is very important for RESTful services. Clients only need to focus on implementing the interface can, readability strengthen the interface, use of personnel to facilitate the call.

4. consistent data format

The server returns the data format is either XML, either Json (data acquisition), or directly return the status code, are interested can look at the open platform of the blog park operation data api, post, put, patch are returned a status code.

Self-describing information, each item of data should be self-describing code to facilitate handling and parsing its contents. For example, by HTTP data returned there [MIME type] information, we can know from the MIME type inside the specific format of data, images, videos or JSON, the client through the body content, query string parameters, request headers and URI (resource name ) to transmit state. By body content server, and the response code in response to the first transfer state to the client. This technique is called hypermedia (or hypertext links).

In addition to the above, HATEOS also means that, when necessary, may also be included in the link returned body (or head), to provide the URI to retrieve the associated object or the object itself. This will be explained in more detail.

Such as a micro-blog information request, the server response should contain information related to this microblogging other URL, clients can further use these URL initiates a request to obtain information of interest, another example, paging can be obtained from the first page of returned data Next the URT is also based on this principle.

4. The system hierarchy

The client usually can not show that they are directly or indirectly connected with the terminal server, the same should be considered when layered security policy.

5. cacheable

On the World Wide Web, the client can cache the response content of the page. Thus the response should be explicitly defined or implicitly to be cached, the cache will have to be avoided if the client can not use the old data or dirty data in response to the multiple requests. Properly managed cache may be partially or completely the interaction between the client and server to remove, to further improve performance and scalability.

6. The coding demand can be custom code (optional)

Choose a temporary server to the client delivers some functional code allows the client to perform, to customize and extend some of the features of the client. For example, the server may return some Javascript code that allows the client to perform, to achieve certain functions.
Tip: REST architecture, design criteria, the only on-demand encoding is optional. If a service violates any of the other criteria, on the strict meaning it can not be called RESTful style.

03 RESTful of 7 Best Practices

1. Version

As github open platform
https://developer.github.com/v3/ 

is to release on the url, concise, this is only used to know, the general project plus version v1, v2, v3? Well, this plus version estimated that only large companies and the project will be to use, say it is not afraid of embarrassment, I really have not used. Some will be placed header inside the version number, but not as url straightforward.

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

2. Parameter naming convention

query parameter can be used hump nomenclature, underscore naming way can also be used, recommended naming underlined the way, is said to recognition of the latter than the former is much higher, perhaps more people use it, vary due to team specifications vary it.

https://example.com/api/users/today_login 获取今天登陆的用户 
https://example.com/api/users/today_login&sort=login_desc 获取今天登陆的用户、登陆时间降序排列

3.url naming convention

API naming convention should adopt the way, keep it simple and clear. In a RESTful architecture, each represents a resource url url so can not have a verb, a noun only, and should also use the plural noun. Implemented should use appropriate verbs Http GET, POST, PUT, PATCH, DELETE, HEAD these resources can be operated

The non-standard url, redundancy does not make sense, form is not fixed, different developers also need to understand the document before calling.

https://example.com/api/getallUsers GET 获取所有用户 
https://example.com/api/getuser/1 GET 获取标识为1用户信息 
https://example.com/api/user/delete/1 GET/POST 删除标识为1用户信息 
https://example.com/api/updateUser/1 POST 更新标识为1用户信息 
https://example.com/api/User/add POST 添加新的用户

After the specification for RESTful url, fixed form, readable, according to http verbs and nouns users can operate these resources

https://example.com/api/users GET 获取所有用户信息 
https://example.com/api/users/1 GET 获取标识为1用户信息 
https://example.com/api/users/1 DELETE 删除标识为1用户信息 
https://example.com/api/users/1 Patch 更新标识为1用户部分信息,包含在body中 
https://example.com/api/users POST 添加新的用户

4. Back unified data format

For legitimate request should return a unified data format, demonstrated here is json

  • code-- integer type comprising a status code of the HTTP response.
  • status-- contains the text: "success", "fail" or "error". HTTP status code in the response between 500-599 as "fail", is between 400-499 "error", others are "success" (e.g.: in response to a status code 1XX, 2XX, and 3XX). This fact is based on the actual situation can not happen in the.
  • message-- state is "fail" and "error" effective when used to display error messages. Referring to international (il8n) standard, which may contain information number or code that may contain only one, or both comprising and separated by separator.
  • data-- body containing the response. When the state is "fail" or "error", data comprising only cause of the error or exception name, or null is also possible

Returns successful response json format

{
  "code": 200,
  "message": "success",
  "data": { "userName": "123456", "age": 16, "address": "beijing" } }

Returns a failure response format json

{
  "code": 401,
  "message": "error  message",
  "data": null }

The following ApiResult generic class is used in the project, strong expansion, easy to use. The return value using a unified ApiResult or ApiResult
error return using ApiResult.Error be returned; successful return, be required to return ApiResult.Ok

public class ApiResult: ApiResult
    {
        public new static ApiResult<T> Error(string message) { return new ApiResult<T> { Code = 1, Message = message, }; } [JsonProperty("data")] public T Data { get; set; } } public class ApiResult { public static ApiResult Error(string message) { return new ApiResult { Code = 1, Message = message, }; } public static ApiResult<T> Ok<T>(T data) { return new ApiResult<T>() { Code = 0, Message = "", Data = data }; } /// <summary> /// 0 是 正常 1 是有错误 /// </summary> [JsonProperty("code")] public int Code { get; set; } [JsonProperty("msg")] public string Message { get; set; } [JsonIgnore] public bool IsSuccess => Code == 0; }

5. http status code

When xamarin android blog park customers before the end of the development, patch, delete, body response which no post operation, with only http status code. HTTP status code meaning in itself sufficient, according to http status code can know delete, add, modify and so successful. (ps: linux design a little taste Oh, no return message is good news, it said that it has succeeded) to return these services segment status code is not a mandatory constraint to the user. Simply put, you can specify these states, but not mandatory. Common HTTP status code table
HTTP status code is a regular

  • 1 ** request did not succeed
  • 2 ** request succeeds, the processing of the status code indicates a successful request.
  • 3 ** request is redirected, to fulfill the request indicates the need for further operations. Typically, these status codes for redirection.
  • 4 ** request error status code indicates the request may be wrong, preventing the processing server.
  • 5 ** (Server Error) These status codes indicate internal server error occurred while trying to process the request. These errors may be wrong server itself, not with the request.

    6. rational use query parameter

    When the requested data, the client will often filter the data and paging requirements, parameters which are recommended manner of HTTP Query Parameter
比如设计一个最近登陆的所有用户
https://example.com/api/users?recently_login_day=3
搜索用户,并按照注册时间降序
https://example.com/api/users?recently_login_day=3
搜索用户,并按照注册时间升序、活跃度降序
https://example.com/api/users?q=key&sort=create_title_asc,liveness_desc
关于分页,看看博客园开放平台分页获取精华区博文列表
https://api.cnblogs.com/api/blogposts/@picked?pageIndex={pageIndex}&pageSize={pageSize} 
返回示例: 
[ 
{ 
“Id”: 1, 
“Title”: “sample string 2”, 
“Url”: “sample string 3”, 
“Description”: “sample string 4”, 
“Author”: “sample string 5”, 
“BlogApp”: “sample string 6”, 
“Avatar”: “sample string 7”, 
“PostDate”: “2017-06-25T20:13:38.892135+08:00”, 
“ViewCount”: 9, 
“CommentCount”: 10, 
“DiggCount”: 11 
}, 
{ 
“Id”: 1, 
“Title”: “sample string 2”, 
“Url”: “sample string 3”, 
“Description”: “sample string 4”, 
“Author”: “sample string 5”, 
“BlogApp”: “sample string 6”, 
“Avatar”: “sample string 7”, 
“PostDate”: “2017-06-25T20:13:38.892135+08:00”, 
“ViewCount”: 9, 
“CommentCount”: 10, 
“DiggCount”: 11 
} 
]

7. multi-table, multi-join queries on how to design parameters URL

This is a more difficult problem, doing a single entity queries easier and standardize operations, but in the actual API is not as simple as that, which are often designed to connect multi-table, multi-condition filter, sort, and so on.
For example, I would like to query a user and obtain the address is greater than $ 500 in June orders in Beijing, users aged 22 to 40 years old, the amount of the purchase order list in descending order of

https://example.com/api/orders?order_month=6&order_amount_greater=500&address_city=北京&sort=order_amount_desc&age_min=22&age_max=40

URL from this point of view, too many parameters have to call up one by one carefully against, and the API itself is very easy to maintain, naming it seems not very easy, not too long, not too casual.

In total we can use .net WebAPI property route, the route is to say route attributes attached to a specific controller or method of operation and use of decorative Controll [the Route] attribute defines the routing method for routing called attributes.

This benefit is the ability to precisely control the URL, rather than the agreed-based routing, this is simply for the multi-table queries like the tailor. From webapi 2 development, the development of RESTful API is now the most preferred route type.
We can mark Route in the Controll

[Route(“api/orders/{address}/{month}”)] 

Action in the amount of query parameters only, sort, age. Reduce the query parameters, API line readability and maintainability is enhanced.

https://example.com/api/orders/beijing/6?order_amount_greater=500&sort=order_amount_desc&age_min=22&age_max=40

This attribute of the route, such as the blog garden open API also has applications in this area, such as access to a personal blog essays List

请求方式:GET 
请求地址:https://api.cnblogs.com/api/blogs/{blogApp}/posts?pageIndex={pageIndex} 
(ps:blogApp:博客名)

Guess you like

Origin www.cnblogs.com/IT-Evan/p/RESTful.html