15
votes

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.

2
I come across this interesting topic here http-response-code-for-post-when-resource-already-exists. Which one is desired to use 302 - FOUND, 303 - See Other, 304 - Not Modified. 302 make more sense to me :-)Manjunath Reddy
The RFC link notes that 303 (See Other) should be used.Nullius

2 Answers

12
votes

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

2
votes

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).