parm530
4/6/2018 - 5:33 PM

Converting App to an API

How to convert app to API using serialization

API

  • Application Programming Interface
  • Way in which one system interacts with another system via a well defined interface
    • An interface is any endpoint that can be used to take actions and consume data on a given application
    • An example of an interface is the web interface. It is a combination of data and presentation (HTML/CSS and JavaScript effects) that is consumed by the web browser. Beneficial for end users.
    • An API is beneficial for being used other systems (for example code) to consume.
  • A web interface provides HTML, an API provides JSON (ruby hash)

  • To see one of your model turned into json:

    • Install JSONViewer (for chrome), not needed but helps display the JSON better)
    • In the index action, instead of rendering a view, render:
    def index
      @objects = Object.all
      render json: @objects.to_json(:include => :another_object)
    end
    
    • Visit the route in your browser and see the results in JSON!
    • The above code displays all attributes from the object, to limit the response value:
    render json: @objects.to_json(only: [:title, :name, :created_at], 
                                  include: [author: {only: [:name]}])
    
    • only can be used on the main object and the referenced object!
    • However, because we specified that we want this action to render JSON, we can't render HTML to our end users. We could create another route, but that is not DRY.

respond_to

  • Within the action that you want to display both HTML and JSON, use the following code:
def index
  @objects = Object.all
  respond_to do |format|
    format.html {render :show}
    format.json {render json: @objects.to_json(only: [:title, :name, :created_at], 
                                               include: [author: {only: [:name]}])}
  end
end

Active Model Serializer

  • Easier to serialize your models for API conversion
  • Add to Gemfile: gem 'active_model_serializers'
  • bundle install
  • Generate the serializer for your model: rails g serializer model
  • All serializers will be loccated in app/serializers
  • attributes are added to give the serializer more info to return in the JSON response
  • Now you can remove all the .toJSON... code and just use render json: @objects and that will call your serializer for that model and display the specified JSON.
  • To add the relationship to a serializer, just follow the same convention, under the attributes , belongs_to @model
    • Remember you will need to create another serializer for that model in order to limit the JSON returned value!