REST中的清除URI

时间:2015-10-30 12:02:52

标签: rest uri

我正在为客户设计一个新的Web API。我之前没有设计过一个所谓的RESTful API,而且我非常怀疑大多数关于"做什么的炒作的有效性"和"什么不该做"。

也许是我,但有一点我不明白为什么如此强调URI的结构。让URI代表资源而不代表资源。

然后,应用程序需要"预测" URI包含什么,有很多有效代码和条件处理不自然的URL结构。

几个世纪以来,我们一直在使用以下内容:

get_all_products.php

get_product.php?id=1234

只要所有内容都有详细记录,我就无法理解为什么我们需要使应用程序更加复杂。

毕竟我们还没有为搜索引擎创建API!

1 个答案:

答案 0 :(得分:2)

Actually most people completely misunderstand what Roy Thomas Fielding originally proposed and very few so-called RESTful applications are really RESTful.

In his blog post REST APIs must be hypertext-driven Roy is expressing his frustration with people calling their HTTP-based interfaces a REST API, when in fact they aren't.

One of the crucial elements of a RESTful application is the point that:

  • A REST API should be entered with no prior knowledge beyond the initial URI (bookmark) and set of standardized media types that are appropriate for the intended audience (i.e., expected to be understood by any client that might use the API). From that point on, all application state transitions must be driven by client selection of server-provided choices that are present in the received representations or implied by the user’s manipulation of those representations. The transitions may be determined (or limited by) the client’s knowledge of media types and resource communication mechanisms, both of which may be improved on-the-fly (e.g., code-on-demand). (Failure here implies that out-of-band information is driving interaction instead of hypertext.)

This is actually how most normal web sites behave.

What he is describing here is not what people believe they implement using URL rewrites and so-called single entry points in application and it has little to do with the subject!

If no representations exist beyond the initial URI, and no further links are provided by the responses of the server, there really is no way to determine how the application state transition can proceed beyond that point. It doesn't matter how you structure your URI and how predictable you make it, you're not creating a truly RESTful application.

Using an URI like:

https://www.example.com/api/1.0/products/

May enable the client to know that if “1234” is entered after the “products/” part, a specific product is fetched. And facilitating the methods of POST, PUT, and DELETE, may further enable the client to determine what actions can be performed on that particular resource, but it is still not a truly RESTful application because beyond that, there is no way to proceed using only server-provided choices.

What you really have is the out-of-band information driving interaction instead of hypertext, period!

Create a HTTP-interface, make sure you document everything with clear copy/paste examples (no assumptions), and just KISS, don't follow the hype!