简体   繁体   English

RESTApi - 当操作不确定时应该是什么方法

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

I have 4 Apis that I expose, and I don't know what method should I use for them (POST/PUT/DELETE).我有 4 个公开的 API,但我不知道应该为它们使用什么方法(POST/PUT/DELETE)。

The DB object (let's call it User) contains DB object(我们称之为用户)包含

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

I have 4 methods -我有4种方法-

assignForegin1
unassignForegin1
assignForegin2
unassignForegin2

In each one, I'm getting only 2 parameters - 1 id and 1 foreignId (after that I'm creating a User with the relevant fields out of it).在每一个中,我只得到 2 个参数 - 1 个 id 和 1 个 foreignId(之后我创建了一个包含相关字段的用户)。 Assign - if there is no id, I'm creating a new one with this foreignId, and if it exists, I override/assigning the new foreginId.分配 - 如果没有 id,我将使用这个 foreignId 创建一个新的,如果它存在,我将覆盖/分配新的foreginId。 Unassign - I'm removing the foreginId from this id, and if the id contains no foreginIds, I delete it.取消分配 - 我正在从此 id 中删除foreginId,如果 id 不包含foreginId,我将其删除。

So, assign is half PUT and half POST, and the unassign is half PUT and half DELETE.因此,assign 是一半 PUT 和一半 POST,而 unassign 是一半 PUT 和一半 DELETE。

What will be the best practice in this scenario?在这种情况下,最佳实践是什么?

Thanks谢谢

The API should follow single responsibility , it should only assign the foreign fields and should not create/delete if not present. 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 doesn't exist. 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不存在。 As a best practice, the client of your API shouldn't know about your implementation.作为最佳实践,您的 API 的客户端不应该知道您的实现。

I would suggest you divide the APIs into multiple CRUD APIs.我建议您将 API 分成多个 CRUD API。 Lets call your object as foreign让我们将您的 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

In case the id doesn't exist in case of assignForeignId1 , the API should throw an error and the client should call createForeign API if he wants to create one.如果在assignForeignId1的情况下 id 不存在,API 应该抛出一个错误,如果他想创建一个,客户端应该调用createForeign API。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM