簡體   English   中英

RESTApi - 當操作不確定時應該是什么方法

[英]RESTApi - what should be the method when the actions is not sure

我有 4 個公開的 API,但我不知道應該為它們使用什么方法(POST/PUT/DELETE)。

DB object(我們稱之為用戶)包含

{"id", "foreignId1", "foreignId2"}

我有4種方法-

assignForegin1
unassignForegin1
assignForegin2
unassignForegin2

在每一個中,我只得到 2 個參數 - 1 個 id 和 1 個 foreignId(之后我創建了一個包含相關字段的用戶)。 分配 - 如果沒有 id,我將使用這個 foreignId 創建一個新的,如果它存在,我將覆蓋/分配新的foreginId。 取消分配 - 我正在從此 id 中刪除foreginId,如果 id 不包含foreginId,我將其刪除。

因此,assign 是一半 PUT 和一半 POST,而 unassign 是一半 PUT 和一半 DELETE。

在這種情況下,最佳實踐是什么?

謝謝

API 應該遵循單一職責,它應該只分配外部字段,如果不存在則不應創建/刪除。

In your way, the end-user of the API doesn't know that you will delete the object if the object with id doesn't have that foreignId , he will also not know that a new object will be created if an object with an id不存在。 作為最佳實踐,您的 API 的客戶端不應該知道您的實現。

我建議您將 API 分成多個 CRUD API。 讓我們將您的 object 稱為外國

createForeign
  type: POST
  input: foreignId1, foreignId2
  output: Foreign

assignForeignId1:
  type: PUT
  input: id, foreignId1
  output: Foreign

assignForeignId2:
  type: PUT
  input: id, foreignId2
  output: Foreign

如果在assignForeignId1的情況下 id 不存在,API 應該拋出一個錯誤,如果他想創建一個,客戶端應該調用createForeign API。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM