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.
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.
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.
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With