1
votes

I'm currently building an API using Rails. All the responses are in JSON. As an example, my controllers use:

render json: @users, status: :ok

or, when I set respond_to :json, I use:

respond_with @users, status: :ok

I want to know what is the best way of standarizing my responses. Like:

{
  error_code: 0,
  content: ... (@users as JSON)
}

I've tried using JBuilder and also serializers (https://github.com/rails-api/active_model_serializers), but I have to add the template to each view/serializer.

I want an elegant way of doing this so any controller that calls render or respond_with has the same template.

1
Why do you have to add a template to the serializer? Don't forget you can call to_json and the as_json method can be customized to remap or omit fields. - tadman
I don't actually need to add a template, I want to now what is the best way of standarizing the response regardless the gem I use (serializers, jbuilder, etc). - Federico Moretti

1 Answers

1
votes

Perhaps not what you're looking for, but when I have to code these sorts of APIs, I simply define a method somewhere all my controllers can access it, and then always call render/redirect on that.

Controller

render json: formatted( @user, :ok )

Method

def formatted( obj, status )
  { error_code: status, content: obj }
end

Not necessarily "elegant," but it's readable, effective, easily maintainable, and will render properly however you want to output the results (plus it doesn't involve hacking on existing methods, which I tend to feel is sloppy).

Apologies if you were looking for something completely different.