Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What should I render when destroying a record?

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?

like image 964
Peter Brown Avatar asked Jun 13 '13 17:06

Peter Brown


2 Answers

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

like image 55
usha Avatar answered Nov 13 '22 11:11

usha


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.

like image 28
Andreas Baumgart Avatar answered Nov 13 '22 13:11

Andreas Baumgart