Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

RESTful POST request, If the record already exists on POST data, do we return 200 OK or 304 Not Modified?

Tags:

rest

http

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.

like image 694
Manjunath Reddy Avatar asked Sep 17 '14 16:09

Manjunath Reddy


People also ask

What is returned by the API after a PUT request is made?

Testing an API with PUT requests Repeatedly calling a PUT request always returns the same result (idempotent). The proper status code is returned when creating and updating a resource (eg, 201 or 200 / 204 ). After updating a resource with a PUT request, a GET request for that resource should return the correct data.

Does put return 200 or 201?

PUT should never return a body, but must return a response code in the header. Just choose 200 if it was successful, and 4xx if not. There is no such thing as a null return code.

Can post method return data?

The method shall return a set (possibly empty) of object headers for the newly posted object. If a URL has been assigned by the server, then that may be included. Similarly, if a URN has been assigned, then that shall be returned. Other things which may be returned include for example the expiry-date if any.

What is the HTTP status code for duplicate record?

409 Conflict - Client attempting to create a duplicate record, which is not allowed. 410 Gone - The requested resource has been deleted. 411 Length Required - The server will not accept the request without the Content-Length Header.


1 Answers

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

like image 86
Remy Lebeau Avatar answered Sep 28 '22 03:09

Remy Lebeau