2015-10-22 58 views
1

如果我想創建(POST)一個鏈接兩個獨立資源的新資源,那麼最恰當的 - 關於HATEOAS和REST原則 - 構造請求實體的方式是什麼?REST風格創建或更新引用的資源

RFC,W3C文檔,Fielding的論文等關於客戶請求兩個獨立資源的正確方法的任何引用都是最有價值的。或者,如果我感興趣的僅僅是REST,HATEOAS的範圍之外,那麼爲什麼也是很好的解釋。

希望我的問題清楚。如果不是,這裏有一個場景和一些背景來解決這個問題。

比方說,我有兩個獨立的資源:/customer/item,第三個資源/order打算這兩個。

如果我代表這些資源在HATEOAS樣的方式在客戶端(與JSON-LD說的),客戶可能(最小)的樣子:

{ 
    "@id": "http://api.example.com/customer/1" 
} 

,同樣一個物品:

{ 
    "@id": "http://api.example.com/item/1" 
} 

我更關心POST請求的實體應具有什麼方案,而不是我正在處理請求的URL。假設我正在處理對/order的請求,會以任何方式發佈以下與HATEOAS和REST原則相違背的內容?

{ 
    "customer": {"@id": "http://api.example.com/customer/1"}, 
    "item": {"@id": "http://api.example.com/item/1"} 
} 

對我來說,這似乎很直觀。但是,我找不到任何關於將兩個獨立資源與POST關聯的正確方式的討論。我發現了LINKUNLINK HTTP方法,但這些對於公共API來說似乎不合適。

回答

2

客戶端不會構建URI,所以這是錯誤的,除非這些資源標識符或至少它們的模板來自服務。直到您在包含POST鏈接的響應中對此進行了描述之後,才使用ID號代替URI。

hydra documentation一個例子:

{ 
    "@context": "http://www.w3.org/ns/hydra/context.jsonld", 
    "@id": "http://api.example.com/doc/#comments", 
    "@type": "Link", 
    "title": "Comments", 
    "description": "A link to comments with an operation to create a new comment.", 
    "supportedOperation": [ 
    { 
     "@type": "CreateResourceOperation", 
     "title": "Creates a new comment", 
     "method": "POST", 
     "expects": "http://api.example.com/doc/#Comment", 
     "returns": "http://api.example.com/doc/#Comment", 
     "possibleStatus": [ 
     ... Statuses that should be expected and handled properly ... 
     ] 
    } 
    ] 
} 

"http://api.example.com/doc/#Comment"包含屬性的描述。

{ 
    "@context": "http://www.w3.org/ns/hydra/context.jsonld", 
    "@id": "http://api.example.com/doc/#Comment", 
    "@type": "Class", 
    "title": "The name of the class", 
    "description": "A short description of the class.", 
    "supportedProperty": [ 
    ... Properties known to be supported by the class ... 
    { 
     "@type": "SupportedProperty", 
     "property": "#property", // The property 
     "required": true, // Is the property required in a request to be valid? 
     "readable": false, // Can the client retrieve the property's value? 
     "writeable": true // Can the client change the property's value? 
    } 
    ] 
} 

受支持的屬性可以有一個rdfs:range,它描述了值約束。就我所知,這是not yet (2015.10.22.) added to the hydra vocab,但我沒有時間去關注這個項目。我認爲你仍然可以使用rdfs:range而不是等待Hydra範圍。

因此,在您的情況下,您可以添加一個item屬性,其範圍爲http://api.example.com/doc/#Item等等。我假設你可以添加替代品的鏈接,如http://api.example.com/items/,所以你可以生成一個選擇輸入框。請注意,這項技術尚不穩定。

因此,您可以發送一個簡單的JSON作爲POST正文{item: {id:1}, customer: {id:1}}或類似的東西,它是基於POST鏈接生成的。 RDF適用於客戶端而不是服務器。服務器可以理解它所需的數據結構,它不需要RDF。你不需要字典來了解你自己...

+0

感謝您的詳細回覆@ inf3rno。我打算讓客戶端只使用由服務器首先提供的URI(我會更新我的問題來澄清)。你的回答對我很有意義,特別是關於「你不需要字典來理解你自己」的部分。我特別喜歡你的第一個例子展示了一種描述POST操作的方式 - 這正是我對了解更多信息的興趣所在。我試圖找到更多這個概念的例子,尤其是如何從初始URL(api.example.com)到通過客戶端發現鏈接兩個資源的示例 – maxenglander

+0

@maxenglander如果您有更多的答案,請檢查郵件列表:https ://www.w3.org/community/hydra/他們對這個話題的瞭解遠遠超過我。 – inf3rno