URI是什么
URI僅僅是一個概念,他規定在網絡上定位一個資源的方式,描述的是一個資源,而url是他的一種實現方式,url是可以訪問的。
URI = scheme “://” authority “/” path [ “?” query ][ “#” fragment ]
scheme: 指底層用的協議,如http、https、ftp
host: 服務器的IP地址或者域名
port: 端口,http中默認80
path: 訪問資源的路徑,就是咱們各種web 框架中定義的route路由
query: 為發送給服務器的參數
fragment: 錨點,定位到頁面的資源,錨點為資源id
資源是什么
在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.
一個資源即可是一個,比如一個客戶,又可以是復數,比如全部客戶。這些都可以看做資源。
一個資源里面可以包含另一個資源。學校里包含班級,班級里有老師同學,這些都是資源。
GitHub restful 接口設計例子
resful資源命名規范
1.用名詞的復數去表示資源
使用名詞的主要原因是名詞跟資源一樣可以有屬性,比如請求方法,傳輸什么格式的規定。
http://api.example.com/device-management/managed-devices
http://api.example.com/device-management/managed-devices/{device-id}
http://api.example.com/user-management/admin
2.命名格式一致
在path里面把版本號寫出來:v1/user-management/admin
使用斜杠“/”來表示分層:user-management/admin
使用"-"來代替一個資源里面的多個單詞:managed-entities/{id}/install-script-location
URI末尾不要有"/"
URI里面不要有文件的類型標識
URI應該是用小寫字母
3.在URI不要用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
4.過濾查詢的話用URI collection
http://api.example.com/device-management/managed-devices?region=USA&brand=XYZ&sort=installation-date
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:刪除某個指定動物園的指定動物