Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how does rails ActiveModel::Serializers compare to grape?

Can someone explain the difference between ActiveModel::Serializers and Grape. Should I use one or the other or could/should they be used together. Could someone also explain the benefits of using one (or both) of the above versus just using rails by itself for building a restful JSON API?

Thank you in advance

like image 230
monty_lennie Avatar asked Dec 15 '22 19:12

monty_lennie


1 Answers

Grape and ActiveModel Serializers serve different purposes. Grape acts both as controller and router, and allows you to define an API to your application. In the Rails routes.rb file, you include a statement similar to this, to hand off routing to Grape:

mount API::Base, at: '/'

Then, you create classes that inherit from Grape, to define your API interface:

module API
  module V1
    class Companies < Grape::API

There's actually a gem that allows Grape to take advantage of ActiveModel Serializers: http://github.com/jrhe/grape-active_model_serializers

There is nothing you can do in Grape that you can't do in Rails. The reason that Grape is popular is because it is optimized for writing APIs. For example, in Grape, you can declare the required parameters necessary for performing a post, and differentiate them from optional parameters. Obviously, the :id would not be used for creating an item, but it should be mandatory for updating an item. This is but one example. The documentation will better explain this.

ActiveModel Serializers define how an object is presented, when it's requested. It's sort of like a view layer for objects. For example, if you were displaying contacts, you might want the contact's company and phone number (separate, but related objects) to be embedded within the contact object that's returned. There may be situations where you DON'T want certain attributes to be included in your json. The serializer can include logic that protects these attributes, accordingly. One useful feature of ActiveModel Serializers is the ability to embed the IDs of related models.

like image 128
Doug Hall Avatar answered Jan 09 '23 19:01

Doug Hall