← Back to Upcase

JSON API Response Formatting/Customization Best Practices

(Alex Bush) #1

I have a question regarding JSON APIs - what is the best practice regarding rendering json in response to .json API calls?

As far as I understand there are 3 options:
1) render @my_models_collection which will call to_json on every object and will collect the return into a json array (no customization here except calling :methods => …)
2) override to_json/as_json on the model this would let me customize the json output when controller’s render method calls to_json on the members of the collection I passed to it
3) use template views something like index.json.rb and than map every element of my collection and call to_json on the result. But this is quickly gets ugly and has some performance implications…

I believe I’m missing something and there is a good and clear solution to this.


(Joel Quenneville) #2

You might want to check out ActiveModel::Serializer. This post explains the basic idea: http://robots.thoughtbot.com/fast-json-apis-in-rails-with-key-based-caches-and

(Alex Bush) #3

@joelq this is an interesting read and I’ll probably use it later but it’s not quite what I’m asking about. I’m trying to figure out what’s the best approach to build/format JSON responses.

(Joel Quenneville) #4

@alexbush, although it may be premature to make the optimizations mentioned in the article, I think that ActiveModel::Serializers is the way you want to go if you have any customizations to make. Rails will automatically look for a serializer when you use render :json as explained in the README. This is what we use at thoughtbot when building JSON APIs for client-side apps built with javascript frameworks such as Backbone or Ember.

More info can be found here:


(Alex Bush) #5

Thanks @joelq! Somehow I missed it when I skimmed the article( duh, silly me, the name is serializers after all :smile: )
This is a great read: https://github.com/rails-api/active_model_serializers

One quick question about testing serializers/json - is it a good idea to unit-test serializers I create?
I believe @benorenstein mentioned something related to testing private methods of a class in the other thread lately.
My gut tells me - serializers are just small components that help you get what your app wants on a higher level(i.e. formatted json when you rendering objects, etc.) therefore I should test either only public methods of serializer classes or even only the behavior/features of my JSON APIs on the higher level. Am I correct?

(Joel Quenneville) #6

That’s what I would do.