Search code examples
ruby-on-railsjsonruby-on-rails-5active-model-serializersrails-api

Rails 5 JSON API with custom JSON response


I'm battling with my JSON rendering. I want to comply with the simple JSend response format.

Basically what I want is the status and the data in my response.

I've set up my Serializer default adapter to json :

ActiveModelSerializers.config.adapter = :json

My serializer is simple :

class RecordSerializer < ActiveModel::Serializer
  attributes :id, :raw
end

So when I do this :

record_list = @current_user.records
render json: record_list

I got this :

{
    "records": [
        {
            "id": 1,
            "raw": "aaa"
        },
        {
            "id": 2,
            "raw": "bbb"
        }
    ]
}

Now the tricky part, if I want to add a data key on top, it override my records key instead of adding it on top.

render json: record_list, root: "data"

Give this :

{
    "data": [
        {
            "id": 1,
            "raw": "aaa"
        },
        {
            "id": 2,
            "raw": "bbb"
        }
    ]
}

Also, how can I add other keys like the status key ? As soon as I create a custom Hash, the serializer is ignored. So for example this :

render json: {:status=>"success", :code=>200, :message=>"Hello", data: record_list}

Will returns this :

{
    "status": "success",
    "code": 200,
    "message": "Hello",
    "data": [
        {
            "id": 1,
            "raw": "aaa",
            "created_at": "2018-07-16T19:49:32.960Z",
            "updated_at": "2018-07-16T19:49:32.960Z",
        },
        {
            "id": 2,
            "raw": "bbb",
            "created_at": "2018-07-16T20:01:55.804Z",
            "updated_at": "2018-07-16T20:01:55.804Z",
        }
    ]
}

So I think I understand that render json: my_variable alone will understand to transform my_variable into the choosen json serializer adapter but cannot with a custom Hash ?

Of course I could do this :

record_list = {}
record_list["records"] = @current_user.records.select(:id, :raw)

But I feel like this is not the right way and then the Serializer would be useless.

Thanks !


Solution

  • I've chosen to give it a try to the Fast JSON API gem from the Netflix team. Great customisation possible, fast and lightweight.