REST 資源命名規則

REST Resource Naming Guide

文檔鏈接: resource-naming

In REST, primary data representation is called Resource. Having a strong and consistent REST resource naming strategy – will definitely prove one of the best design decisions in the long term.

在REST中,初始的數據表現被叫做資源。從長期來看,擁有一個強壯的一致的資源命名規則理所當然的會是一個極好的設計決定。

The key abstraction of information in REST is a resource. Any information that can be named can be a resource: a document or image, a temporal service (e.g. “today’s weather in Los Angeles”), a collection of other resources, a non-virtual object (e.g., a person), and so on. In other words, any concept that might be the target of an author’s hypertext reference must fit within the definition of a resource. A resource is a conceptual mapping to a set of entities, not the entity that corresponds to the mapping at any particular point in time.

——Roy Fielding’s dissertation

A resource can be a singleton or a collection. For example, “customers” is a collection resource and “customer” is a singleton resource (in a banking domain). We can identify “customers” collection resource using the URI “/customers”. We can identify a single “customer” resource using the URI “/customers/{customerId}”.

一個資源可以是單個的,也可以是個集合。例如,在銀行系統中,“customers”表示資源集合,而"customer"只是一個單獨的資源。我們可以通過uri
"/customers"來確定“customers”,我們可以通過uri“/customers/{customerId}”來確定一個“customer”資源。

A resource may contain sub-collection resources also. For example, sub-collection resource “accounts” of a particular “customer” can be identified using the URN “/customers/{customerId}/accounts” (in a banking domain). Similarly, a singleton resource “account” inside the sub-collection resource “accounts” can be identified as follows: “/customers/{customerId}/accounts/{accountId}”.

一個資源也許包含了子資源集合,例如,某個特定“customer”的子集合資源“accounts”,可以通過URN
“/customers/{customerId}/accounts”來確定(在銀行系統中),類似的,在子資源集合中的一個子資源可以通過“/customers/{customerId}/accounts/{accountId}”來確認。

REST APIs use Uniform Resource Identifiers (URIs) to address resources. REST API designers should create URIs that convey a REST API’s resource model to its potential client developers. When resources are named well, an API is intuitive and easy to use. If done poorly, that same API can feel difficult to use and understand.

REST APIs用URIs(統一資源身份id)來定位資源,REST
APIs設計者應當設計那些可以傳遞一個REST
APIs資源模型給那些潛在的客戶端開發者的URIs。當資源被命名的很好的話,一個API會很好的理解和使用,反之則難以理解。

The constraint of uniform interface is partially addressed by the
combination of URIs and HTTP verbs and using them in line with the
standards and conventions.

統一接口的約束通過URIs 和HTTP
動詞結合並且通過一些標準和規則使他們整合在一條線上來解決

Below are a few tips to get you going when creating the resource URIs
for your new API.

如下是一些生成resource URIs的小技巧

REST Resource Naming Best Practices

Use nouns to represent resources

通過名詞來展示資源

RESTful URI should refer to a resource that is a thing
(noun) instead of referring to an action (verb) because nouns have
properties which verbs do not have – similar to resources have
attributes. Some examples of a resource are:

RESTful
URI應當關聯一個事情(名詞)而非一個動作,因爲名詞有一些動詞沒有的特性,類似資源有屬性。例子如下:

  • Users of the system
  • User Accounts
  • Network Devices etc.

and their resource URIs can be designed as below:

然後它們的URIs可被設計成如下:

http://api.example.com/device-management/managed-devices 
http://api.example.com/device-management/managed-devices/{device-id} 
http://api.example.com/user-management/users/
http://api.example.com/user-management/users/{id}

For more clarity, let’s divide the resource archetypes into four categories (document, collection, store and controller) and then you should always target to put a resource into one archetype and then use it’s naming convention consistently. For uniformity’s sake, resist the temptation to design resources that are hybrids of more than one archetype.

爲了更好的說明,我們把資源原型分爲四個類型(文檔,集合,存儲和控制)並且你應該確保把資源放在某個層次上去並且統一使用命名規則。出於統一考慮,
請抵制混雜多個類型的混合命名的誘惑

  1. document

A document resource is a singular concept that is akin to an object instance or database record. In REST, you can view it as a single resource inside resource collection. A document’s state representation typically includes both fields with values and links to other related resources.

一個文檔資源是一個單獨概念,它類似於一個對象實例或者數據庫的記錄。在REST,你可以把它看做是集合中的一個對象。一個文檔的表現包含了帶值的屬性和只想其他相關資源的鏈接

Use “singular” name to denote document resource archetype.

使用“單數”名稱去描述文檔資源類型

http://api.example.com/device-management/managed-devices/{device-id}
http://api.example.com/user-management/users/{id}
http://api.example.com/user-management/users/admin
  1. collection

A collection resource is a server-managed directory of resources. Clients may propose new resources to be added to a collection. However, it is up to the collection to choose to create a new resource or not. A collection resource chooses what it wants to contain and also decides the URIs of each contained resource.

集合資源是服務器管理的資源目錄。客戶端也許會提出添加一個資源到集合,但是,由集合決定是否創建新資源,集合資源決定它包含什麼和它下面每個資源的URIs。

Use “plural” name to denote collection resource archetype.

使用“複數”去展示集合資源的類型

http://api.example.com/device-management/managed-devices
http://api.example.com/user-management/users
http://api.example.com/user-management/users/{id}/accounts
  1. store

A store is a client-managed resource repository. A store resource lets an API client put resources in, get them back out, and decide when to delete them. A store never generates new URIs. Instead, each stored resource has a URI that was chosen by a client when it was initially put into the store.

一個store是一個客戶端管理的資源倉庫。一個store資源讓一個API客戶端保存資源,拿出資源,並且決定什麼時候去刪除資源。一個store資源從不生成新的URIs。
相反,每個被保存的資源有一個當資源被放進store後被關閉的URI。

Use “plural” name to denote store resource archetype.

使用“複數”去展示集合資源的類型

http://api.example.com/cart-management/users/{id}/carts
http://api.example.com/song-management/users/{id}/playlists
  1. controller

A controller resource models a procedural concept. Controller resources are like executable functions, with parameters and return values; inputs and outputs.

控制器資源闡釋了程序概念。Controller資源就像可運行的函數,有參數,返回值,輸入和輸出。

Use “plural” name to denote collection resource archetype.

使用“複數”去展示集合資源的類型

http://api.example.com/cart-management/users/{id}/cart/checkout
http://api.example.com/song-management/users/{id}/playlist/play
Consistency is the key

Use consistent resource naming conventions and URI formatting for minimum ambiguily and maximum readability and maintainability. You may implement below design hints to achieve consistency:

使用一直的資源命名規則和URI格式去最小化不清楚,最大化可讀性和可讀性。可以遵循以下的設計提示去保持一致性

  1. Use forward slash (/) to indicate hierarchical relationships(使用正斜槓來分層)

The forward slash (/) character is used in the path portion of the URI to indicate a hierarchical relationship between resources. e.g.

在URI路徑部分通過正斜槓來表示各個級別的關係,如:

http://api.example.com/device-management
http://api.example.com/device-management/managed-devices
http://api.example.com/device-management/managed-devices/{id}
http://api.example.com/device-management/managed-devices/{id}/scripts
http://api.example.com/device-management/managed-devices/{id}/scripts/{id}
  1. Do not use trailing forward slash (/) in URIs(不要在末尾使用正斜槓)

As the last character within a URI’s path, a forward slash (/) adds no semantic value and may cause confusion. It’s better to drop them completely.

最爲URI的路徑的最後一個字符,正斜槓沒有意義而且可能會然人迷惑,最好是把它刪除。

http://api.example.com/device-management/managed-devices/
http://api.example.com/device-management/managed-devices 	/*This is much better version*/
  1. Use hyphens (-) to improve the readability of URIs(使用連接符號)

To make your URIs easy for people to scan and interpret, use the hyphen (-) character to improve the readability of names in long path segments.

爲了使URIs讓人更容易讀和理解,在長路徑中使用連字號(-)去增加名字的可讀性

http://api.example.com/inventory-management/managed-entities/{id}/install-script-location  //More readable
http://api.example.com/inventory-management/managedEntities/{id}/installScriptLocation  //Less readable
  1. Do not use underscores ( _ )(不要使用下劃線符號)

It’s possible to use an underscore in place of a hyphen to be used as separator – But depending on the application’s font, it’s possible that the underscore (_) character can either get partially obscured or completely hidden in some browsers or screens.

在使用連字號(-)作爲分隔符的情形下,使用下劃線()字符也是很有可能的-但是這取決於應用的字體,在某些瀏覽器或屏幕中,下劃線()字符可能會被部分掩蓋或完全隱藏。

To avoid this confusion, use hyphens (-) instead of underscores ( _ ).

爲了避免混淆,使用連字符(-)代替下劃線符號( _ )

http://api.example.com/inventory-management/managed-entities/{id}/install-script-location  //More readable
http://api.example.com/inventory_management/managed_entities/{id}/install_script_location  //More error prone
  1. Use lowercase letters in URIs(使用小寫)

When convenient, lowercase letters should be consistently preferred in URI paths.
RFC 3986 defines URIs as case-sensitive except for the scheme and host components. e.g.

如果可以,在URI路徑中小寫是被推薦的,RFC 3986規範中定義了URIs除了scheme和host部分其他是大小寫敏感的。

http://api.example.org/my-folder/my-doc  //1
HTTP://API.EXAMPLE.ORG/my-folder/my-doc  //2
http://api.example.org/My-Folder/my-doc  //3

In above examples, 1 and 2 are same but 3 is not as it uses My-Folder in capital letters.

在上面,1和2是相同的,但是和3是不同的,因爲3中My-Folder使用了首部大寫。

  1. Do not use file extenstions(不要增加文件後綴)

File extensions look bad and do not add any advantage. Removing them decreases the length of URIs as well. No reason to keep them.
Apart from above reason, if you want to highlight the media type of API using file extenstion then you should rely on the media type, as communicated through the Content-Type header, to determine how to process the body’s content.

文件擴展看起來很不好並且沒有任何優勢,移除可以減少URIs的長度。沒有任何理由去用它。除了上述的理由,如果你想強調使用了文件擴展名的API的媒體類型,你應當用媒體類型,通過“Content-Type”請求頭來交互,
去說明如何處理請求內容。

http://api.example.com/device-management/managed-devices.xml  /*Do not use it*/
http://api.example.com/device-management/managed-devices 	/*This is correct URI*/
Never use CRUD function names in URIs

URIs should not be used to indicate that a CRUD function is performed. URIs should be used to uniquely identify resources and not any action upon them. HTTP request methods should be used to indicate which CRUD function is performed.

URIs不應當被使用去表明一個CRUD函數被執行。URIs應當僅僅被使用爲確定資源,並且在裏面不應該包含任何動作。HTTP請求方法纔是應當被使用去說明什麼CRUD被執行。

HTTP GET http://api.example.com/device-management/managed-devices  //Get all devices
HTTP POST http://api.example.com/device-management/managed-devices  //Create new Device

HTTP GET http://api.example.com/device-management/managed-devices/{id}  //Get device for given Id
HTTP PUT http://api.example.com/device-management/managed-devices/{id}  //Update device for given Id
HTTP DELETE http://api.example.com/device-management/managed-devices/{id}  //Delete device for given Id
Use query component to filter URI collection

Many times, you will come across requirements where you will need a collection of resources sorted, filtered or limited based on some certain resource attribute. For this, do not create new APIs – rather enable sorting, filtering and pagination capabilities in resource collection API and pass the input parameters as query parameters. e.g.

很多時候,你會遇到這些請求,你需要通過資源的某些屬性去排序,過濾或者限制資源集合。爲了實現這個,不要生成一個新的api,因爲在資源集合API中可以實現排序,過濾和分頁,並且
傳入參數作爲查詢參數。

http://api.example.com/device-management/managed-devices
http://api.example.com/device-management/managed-devices?region=USA
http://api.example.com/device-management/managed-devices?region=USA&brand=XYZ
http://api.example.com/device-management/managed-devices?region=USA&brand=XYZ&sort=installation-date
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章