8

I am adding an API on a Rails3 app and its pretty going good. But I saw the following Github api v3 at http://developer.github.com/v3/

HTTP/1.1 422 Unprocessable Entity
 Content-Length: 149

 {
   "message": "Validation Failed",
   "errors": [
     {
       "resource": "Issue",
       "field": "title",
       "code": "missing_field"
     }
   ]
 }

I liked the error messages structure. But couldn't get it to reproduce. How can I make my apis to make the response like it?

millisami
  • 9,931
  • 15
  • 70
  • 112

1 Answers1

2

You could quite easily achieve that error format by adding an ActionController::Responder for your JSON format. See http://api.rubyonrails.org/classes/ActionController/Responder.html for the (extremely vague) documentation on this class, but in a nutshell, you need to override the to_json method.

In the example below I'm calling a private method in an ActionController:Responder which will construct the json response, including the customised error response of your choice; all you have to do is fill in the gaps, really:

def to_json
  json, status = response_data
  render :json => json, :status => status
end

def response_data
  status = options[:status] || 200
  message = options[:notice] || ''
  data = options[:data] || []

  if data.blank? && !resource.blank?
    if has_errors?
      # Do whatever you need to your response to make this happen.
      # You'll generally just want to munge resource.errors here into the format you want.
    else
      # Do something here for other types of responses.
    end
  end

  hash_for_json = { :data => data, :message => message }

  [hash_for_json, status]
end
Nathan Kleyn
  • 5,103
  • 3
  • 32
  • 49
  • @MarkMurphy We had it in the `lib` directory. See http://stackoverflow.com/questions/5995178/where-should-custom-responders-go-in-a-rails-project which confirms this. – Nathan Kleyn Jun 04 '14 at 08:49