Federico Moretti
Federico Moretti

Reputation: 126

Standarize JSON response in Rails API

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.

Upvotes: 1

Views: 153

Answers (1)

ConnorCMcKee
ConnorCMcKee

Reputation: 1645

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.

Upvotes: 1

Related Questions