RESTful POST request, If the record already exists

2019-04-06 01:36发布

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

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.

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.

Is it a good practice or is there alternative approach in RESTful principals.

标签: rest http
2条回答
不美不萌又怎样
2楼-- · 2019-04-06 02:23

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.

For a POST response, use 201 if a new record is created, otherwise use 200 or maybe 409 instead.

See the following for some helpful tips in designing REST APIs:

Using HTTP 304 in response to POST

HTTP response code for POST when resource already exists

Creating an efficient REST API with HTTP

REST lesson learned: Avoid 204 responses

查看更多
三岁会撩人
3楼-- · 2019-04-06 02:28

304 Not Modified is to be used when HTTP caching headers are in play, so this doesn't apply to your case.

I would use 422 Unprocessable Entity that is for validation errors, when the request is well-formed but there are semantic errors.

And if the record did not previously exist, you should answer with 201 Created (rather than 200 OK) that is the standard response to a successful resource creation (following a POST creation request).

查看更多
登录 后发表回答