Configuring api errors for Rails 3 like Github api v3

I am adding an API to a Rails3 application, and that is pretty 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 structure of the error messages. But he could not reproduce it. How can I make my apis to make an answer like this?

+8
ruby api ruby-on-rails-3
source share
1 answer

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

In the example below, I call a private method in ActionController: Responder, which will build a json response, including a custom error response of your choice; all you have to do is fill in the blanks, 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 
+2
source share

All Articles