43

I have an API that lets you destroy an object. The part I'm not sure on is what JSON should be rendered after the record has been destroyed. Here are a couple options, but I'm not sure what the best practice is for this.

Version 1:

Return empty object with 204 status

def destroy
  item = current_user.current_cart.items.find(params[:id])
  item.destroy
  render json: {}, status: :no_content
end

Version 2:

Return item, even though it has been destroyed

def destroy
  item = current_user.current_cart.items.find(params[:id])
  item.destroy
  render json: item
end

Is one of these preferred over the other? Is there a version that I have not thought of that might be preferred?

Peter Brown
  • 50,956
  • 18
  • 113
  • 146

2 Answers2

36

For a delete request, http status code 200 or 204 implies resource deleted successfully.

9.7 DELETE

A successful response SHOULD be 200 (OK) if the response includes an entity describing the status, 202 (Accepted) if the action has not yet been enacted, or 204 (No Content) if the action has been enacted but the response does not include an entity.

So you can either return the object with 200 status code or empty response with 204 status code

usha
  • 28,973
  • 5
  • 72
  • 93
33

A success status of 204 (no content) appears appropriate. As implied by 204, there must not be a response body, which can be achieved with render :nothing, status: :no_content or a bit more catchy:

def destroy
  item.destroy
  head :no_content
end

Edit: render :nothing has been deprecated and been removed since Rails 5.1. Instead you could use render body: nil, status: :no_content.

Andreas Baumgart
  • 2,647
  • 1
  • 25
  • 20
  • As the question is about which is the appropriated choice, and not how to achieve a way where, at the same time, the response could be no empty and the status could be :no_content. I suggest @usha aproach. Both says the same, but this one goes to the point, the which choice. – Paulo Felipe Souza Jan 11 '22 at 16:14