简体   繁体   English

DDD 上的 CreateOrUpdate 端点

[英]CreateOrUpdate endpoint on DDD

I have a rest API for an application that I am developing.我有一个 rest API 用于我正在开发的应用程序。 One of the endpoints receives the name, email and phone fields to create a new user (without password).其中一个端点接收名称 email 和电话字段以创建新用户(无密码)。 Obviously the endpoint would be /users [POST] Would it be correct to take advantage of this endpoint to, if the user already exists, update it with the new data?显然端点是 /users [POST] 如果用户已经存在,利用这个端点来用新数据更新它是否正确? Or is it better to create a different endpoint (PUT) to update the user?还是创建一个不同的端点 (PUT) 来更新用户更好? If so I would have to put the business logic outside of this API, and I don't like that idea.如果是这样,我将不得不将业务逻辑放在这个 API 之外,我不喜欢这个想法。

This question is not related to DDD, as DDD does not provide guidance on API design.这个问题与 DDD 无关,因为 DDD 不提供有关 API 设计的指导。

But to answer your question, whether or not you should use PUT or POST will depend on whether or not the action should be idempotent.但是要回答您的问题,您是否应该使用 PUT 或 POST 将取决于操作是否应该是幂等的。

POST is typically used to create a new resource POST 通常用于创建新资源

POST is not idempotent, if the same request is sent multiple times there will be different results (new resource gets created each time). POST 不是幂等的,如果多次发送相同的请求会有不同的结果(每次都会创建新资源)。 The same request sent to POST /users will create a new resource each time.发送到POST /users的相同请求每次都会创建一个新资源。

PUT is used to either create or replace an existing resource (not necessarily update). PUT 用于创建或替换现有资源(不一定更新)。

The PUT method is idempotent, so if the same request is sent multiple times it will be the same as if it is sent once. PUT 方法是幂等的,因此如果多次发送相同的请求,则与发送一次相同。 The same request sent to PUT /users/1 will have the same result.发送到PUT /users/1的相同请求将具有相同的结果。

If you want to update part of the resource (update rather than replace), you can use PATCH.如果要更新部分资源(更新而不是替换),可以使用 PATCH。

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

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