Let's Build Rails API


A few day ago when I do a short review on rails 5 new feature. And one of those feature which interested me is rails api, so I take a little time to read about it. Today I am going to share all about what I know on rails and show you how to use it. But, what is web API?

1.What is a web API?

A web API is an application programming interface (API) for either a web server or a web browser. It is a web development term is usually provide limited data to its client-side. Data format can be JSON, XML or whatever format follow the user requirement.

2.Why use rails api?

We can can build a web api from many differences web technology like RAILS, PHP, .NET.etc. It is depend on which technology you are good at. Todays, I am going to talk about using RAILS to build web API since I am familiar with RAILS.

There are many difference way to build a web API by using RAILS such use some gem link rails-api, jbuilder, grape, rabl .etc. And all of those are really great gem for provide json or other format data need for their client. However, I am talk only rails-api in these article since it has merged in to rails 5. There are some reason which make rails-api is great for build a web API because it is:

  • lighter: rails-api will generate files, folders and require classes which we need for providing data to client only such as no folder views, stylesheets, or javascipts .etc. So it make rails-api's application lighter than the rails app.
  • faster: Since rails-api use only what it need so the time it toke to laod and generate file also faster than normal rails app. It also fast on respond data to client because sever no need to generate any views file for its application.
  • customizable: rals-api is customizable when we need to customize our application to meet our need. By default rails-api generate and require minimum classes, but we can add more middleware when we need.
  • and for more reason you can find here

3.Scenario for build rails api

I want to build a mobile app which use for show the information of plants such as name, scientist name, group, and description .etc. Moreover, user also can add new plant in database, comment, and rate from their phone.

Since I want to build mobile app only, but I need a place where I can keep and shared my data to all device which installed my app. Therefore, we need a web API which provide some json data for our app, and I am going chose rails as my web api since I used to know rails before.

4.Set up application

On the time I write this article rails 5 has not officialy release yet. Therefor, in this demo I am going to use rails-api gem instead. So let get start:

  • First we need to install rails-api gem:
   gem install rails-api
  • let's generate our project by using rails-api:
    rails-api new plantlover
  • let's take a look what rails-api generate:

    Like what you can see in the image above that there is no stylesheets, javascripts, or views folder, and the application_controller does not inherit from ActionController::Base anymore. Therefor, our application is lighter and faster than normal rails application.

    Screenshot from 2016-03-25 18:02:47.png

  • let's generate some model and controller so that we have something to work with:

    rails g scaffold Plant name:string scientific_name:string description:text

rails-api generate will skip some not use file such as style, script and views to minimum the size of our project.

Screenshot from 2016-03-25 18:24:04.png

  • let's take a look on what rails scaffolding generate:

    rails api make scaffold to generate code in controller for servering only json data to its client.

    class PlantsController < ApplicationController
      before_action :set_plant, only: [:show, :update, :destroy]

      # GET /plants
      # GET /plants.json
      def index
        @plants = Plant.all

        render json: @plants

      # GET /plants/1
      # GET /plants/1.json
      def show
        render json: @plant

      # POST /plants
      # POST /plants.json
      def create
        @plant = Plant.new(plant_params)

        if @plant.save
          render json: @plant, status: :created, location: @plant
          render json: @plant.errors, status: :unprocessable_entity

      # PATCH/PUT /plants/1
      # PATCH/PUT /plants/1.json
      def update
        @plant = Plant.find(params[:id])

        if @plant.update(plant_params)
          head :no_content
          render json: @plant.errors, status: :unprocessable_entity

      # DELETE /plants/1
      # DELETE /plants/1.json
      def destroy

        head :no_content


        def set_plant
          @plant = Plant.find(params[:id])

        def plant_params
          params.require(:plant).permit(:name, :scientific_name, :description)

  • let's check is it work?

    To test, we need some sample data, so let's generate some from seed.


        20.times do |n|
            Plant.create name: "sample tree name #{n}",
               scientific_name: "sample tree scientific name #{n}",
               description: "sample tree description #{n}"

Then run

      rake db:seed

Now let's start server and try to test the respond of our api

      rails s
     curl -X GET http://localhost:3000/plants/1

Screenshot from 2016-03-25 23-59-06.png

     curl -X GET http://localhost:3000/plants

Screenshot from 2016-03-25 23-58-13.png


Since rails api has remove some middlewares to minimum the application, then our application can miss some functionality which we might need for our application. So we can add those middleware to meet our application requirement, and for information of which middleware you can check it out from here



In this article, we start from definetion of web api, and vary technologies which we can use to build web api application. Then we talk about the reason why we should use rails 5 new feature which is rails api to build web api only. After that, We give you a scanario which web api is needed for providing data. Finally, we guide you on how to set it up. We hope after finish read this article, you have an idea of what/why/when is rails api good for you.

All Rights Reserved

Let's register a Viblo Account to get more interesting posts.