RESTful POST请求,如果POST数据上已存在记录,我们是返回200 OK还是304 Not Modified? [英] RESTful POST request, If the record already exists on POST data, do we return 200 OK or 304 Not Modified?
问题描述
我有一个POST请求端点,用户重复发布数据。在我将数据插入数据库之前,根据用户请求,我会检查记录是否已存在。
- 如果记录已经存在,我返回200 OK,响应正文包含table_id,状态
- 如果记录不存在,我创建新记录并返回200 OK,响应正文包含table_id和status
I have a POST request endpoint, where user repeatedly post the data. Before I insert the data to database, based on user request,I do check if the record already exists. - If record already exists, I return 200 OK with response body containing the table_id and status - If record does not exists, I create new record and return 200 OK with response body containing table_id and status
基本上在这两种情况下,用户都获得状态200.由于用户无法区分是新记录还是现有记录,因此可能会造成混淆。
Basically in both the cases, user get status 200. As user it might be confusing as one couldn't be able to distinguish whether its a new record or existing record.
我以为我会回复304并附上回复正文,并告知消费者该请求是未修改,这样消费者就会做出决定。
I thought I would return 304 with response body and inform the consumer telling that This request is "Not Modified", in this way consumers would make a decision.
这是一个好习惯,还是在RESTful主体中有替代方法。
Is it a good practice or is there alternative approach in RESTful principals.
推荐答案
304
仅用于 Conditional GET
响应,以表明所请求的自上次客户端要求后,内容未发生变化。它不适合 POST
响应。
304
is intended to be used only for a Conditional GET
response, to indicate that the requested content has not changed since the last time the client asked for it. It is not appropriate for a POST
response.
对于 POST
响应,如果创建了新记录,则使用 201
,否则使用 200
或者 409
而不是。
For a POST
response, use 201
if a new record is created, otherwise use 200
or maybe 409
instead.
有关设计REST API的一些有用提示,请参阅以下内容:
See the following for some helpful tips in designing REST APIs:
这篇关于RESTful POST请求,如果POST数据上已存在记录,我们是返回200 OK还是304 Not Modified?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!