Thursday, 15 January 2015

API Development Restfull vs Facebook style


In the last months I developed mainly API's using grape gem and their related gems.

In this blog post I will express my opinion how to organise the API which manages the entities.

Generally speaking I like the REST concept and I organize my API to conform that way. For cases when there are no association among the entities this philosophy is good enough and clear.

However I like the API to reflect the associations when we are dealing with has_many or has_and_belongs_to_many associations. Just like in case of  Facebook Graph API. In these cases I find that style more intuitive and I am following that style whenever I deal with associations.

Examples:

Lets suppose that cars and manufacturers can be reviewed.

class Car < ActiveRecord::Base
  has_many :reviews, as: :reviewable

class Manufacturer < ActiveRecord::Base
  has_many :reviews, as: :reviewable

class Review < ActiveRecord::Base
  belongs_to :user
  belongs_to :reviewable, polymorphic: true

In this case the review API would be:
  • creation of reviews:
    POST /api/cars/{id}/reviews
    POST /api/manufacturers/{id}/reviews
  • retrieval of reviews:
    GET /api/cars/{id}/reviews
    GET /api/manufacturers/{id}/reviews
  • deletion of reviews:
    DELETE /api/reviews/{id}


In the classic restful style the review creation would be:

    params do
      requires :comment, type: String, desc: "The comment"
      requires :reviewable_id, type: Integer, desc: "The id of a reviewable entity"
      requires :reviewable_type, type: String, desc: "The type of a reviewable entity"
    end
    POST /api/reviews

Both solutions have pros and cons. The restful style is more DRY. The Facebook Graph Api style relieves more information about the associations ergo it is more intuitive and easier to use.

Happy coding :)