breaking into the unknown…

Sample REST API in Rails


I have tried to define and explain API in this post.  I again, put it in simple words “API is program which let the user to use methods of your application from outside the application“. I will create a REST API here which will implement CRUD ( create, read, update, delete ) operation on users table from outside the application. I assume you all have implemented CRUD for user in your application. The API implementation will remain same, with below difference.

=> In normal case, you have form new.html.erb and edit.html.erb, which provide UI to user to register themselves and edit there profile respectively. But for API you do not need any view as a user do not interact with Your application directly, instead you specify that data, the third party should send to you.

=> There will be no new and edit action in controller, as we do not need any view here

=> In normal application we do user authentication with devise etc, We need to skip that and introduce http authentication

=> We do not do any redirect in our controller action, but just return some data with status code and success or failure message. We may return data in json or xml or any other formate say SOAP. As per convention, you should return data as requested by client calling your API services, so for json request return json data and for xml return xml data

=> API do not have any user interface like navigation link or form to fill up by user etc. So for API you need to document the things, so that third party can use it easily. I will write the documentation for the API we create here in STEP 4

STEP 1: writing the routes

namespace :api do
 resources :users, :defaults => { :format => 'xml' }

I have put the routes, within api namespace, in this way, it will not conflict with users controller of your actual application, if you have one. If you do not have any, you can simply use  resources :users, :defaults => { :format => ‘xml’ } , but I suggest to always use a namespace and group all the controller related to your API in api folder only. Also, I have set the default :formate here as xml . If you do not set it, rails will consider it as a html request if user forget to pass any formate

STEP 2: generating the model

class User < ActiveRecord::Base
  attr_accessible :first_name, :last_name, :email, :password, :password_confirmation, 

  validates :email, :first_name, :last_name, :presence =>true
  validates_uniqueness_of :email


Thus in model we have validated email and other things, the user calling our API must provide these things. Thus while creating a user the caller must pass email, :first_name and :last_name. we will  generate password  dynamically and let him change it later on

STEP 3 : generating the users controller

class Api::UsersController < ApplicationController
  http_basic_authenticate_with :name => "myfinance", :password => "credit123"

  skip_before_filter :authenticate_user! # we do not need devise authentication here
  before_filter :fetch_user, :except => [:index, :create]

 def fetch_user
    @user = User.find_by_id(params[:id])

  def index
    @users = User.all
    respond_to do |format|
      format.json { render json: @users }
      format.xml { render xml: @users }

  def show
    respond_to do |format|
      format.json { render json: @user }
      format.xml { render xml: @user }

  def create
    @user =[:user])
    @user.temp_password = Devise.friendly_token
    respond_to do |format|
        format.json { render json: @user, status: :created }
        format.xml { render xml: @user, status: :created }
        format.json { render json: @user.errors, status: :unprocessable_entity }
        format.xml { render xml: @user.errors, status: :unprocessable_entity }

  def update
    respond_to do |format|
      if @user.update_attributes(params[:user])
        format.json { head :no_content, status: :ok }
        format.xml { head :no_content, status: :ok }
        format.json { render json: @user.errors, status: :unprocessable_entity }
        format.xml { render xml: @user.errors, status: :unprocessable_entity }

  def destroy
    respond_to do |format|
      if @user.destroy
        format.json { head :no_content, status: :ok }
        format.xml { head :no_content, status: :ok }
        format.json { render json: @user.errors, status: :unprocessable_entity }
        format.xml { render xml: @user.errors, status: :unprocessable_entity }

STEP 4 : creating API Documentation

Your API is ready with step 3, but how other people will use it. You need to tell them, how to use it. Let us Document the things

Basic Authentication:
    username: myfinance
    password: credit123

Content Type :
   application/xml or application/json

   You can pass xml or json data in Body
   sample json body

     "email" : "", 
     "first_name" : "arun", 
     "last_name" : "yadav"

   Sample xml body


NOTE : Content Type should be set to application/xml for xml data in body 
and to application/json for json data in body

API Requests:

=> listing users
   url: http://localhost:3000/api/users
   method: GET
   body : not needed

=> Retrieving User detail
  url: http://localhost:3000/api/users/:id 
  method: GET
  body : not needed

=> creating users
   url: http://localhost:3000/api/users
   method: Post
   Body : It can be xml or json

=> Updating User
  url: http://localhost:3000/api/users/:id 
  method: PUT
  Body : It can be xml or json
=> Deleting User 
  url: http://localhost:3000/api/users/:id 
  method: DELETE
  body : not needed

STEP 5: testing the API

You need to write a REST client to use any API. I have explained it in this post. You may also try it out by Installing any REST client in your browser. I have explained installing REST client for Firefox in this post.

You will find method, url, body. header, authentication etc field there, fill the detail from the documentation instep 4. On submitting the detail, you will get back response. Hope it works for you and you get the basic understanding of API creation 🙂


Author: arunyadav4u

over 7 years experience in web development with Ruby on Rails.Involved in all stage of development lifecycle : requirement gathering, planing, coding, deployment & Knowledge transfer. I can adept to any situation, mixup very easily with people & can be a great friend.

23 thoughts on “Sample REST API in Rails

  1. Nice tutorial,getting some concept from your post,Could you explain seperately,how to create post method,while user is posting from client side,it has to display in server side also in Ruby on rails(server side) ,android (client side).

    • Sure Karthick,

      I will write it this weekend,but it will be in Ruby on Rails only. I have never worked on android, so not sure the code will work for android or not. but basically concept is independent of any language or platform, so definitely it will help you in understanding the flow .

      The above post is about API provider (I think you referring it as server side) . You android or any other application who make the call to this will be API consumer (you are calling it client).

      I will write the post on API consumer explaining how to make post get delete or any other call, as soon as possible

    • Are you in any way able to get the client side as android working with ruby on rails at server side… I am caught in the similar situation and could not get it working. plz help

  2. Thank you arunyadav, No no i dont you want to write an android code,i wank you to write,if i will send data from client side,How ruby on rails as server side,can get the data as post method

  3. Hello, Neat post. There’s a problem together with your web site in web explorer, could test this? IE still is the marketplace chief and a big section of folks will miss your excellent writing because of this problem.

  4. I deployed a Rails engine (packed as a gem) that is really useful to debug APIs on rails. You just have to mount the engine and go to the url that you specified, i.e. “localhost:3000/api_explorer” to see it. It’s a way of documenting an API also, reading the webservices specification from a file.

    The gem is named ‘api_explorer’ and the repo is

    Any comments or help improving the api is welcome. 🙂

  5. Can you pl. share the working copy of this code. I am new to Rails api. I am confused with the errors. When i run this code i get Param not found user.

    • Provide me the URL throwing the error.
      above post is about creating the API. How to use it is explained in this post, go through it. It will give you more insight into how to use any API

  6. Very Good Stuff Arun.

  7. Hi Arun,
    It is really a nice post. But I have one question, you have used “http_basic_authenticate_with” in API::user_controller but I am not able to understand , why you used that and if i use same then how can I pass username and password with AJAX(in REST client).

    • You can make a REST API without any authentication, But generally we always need some kind of authentication. The above implementation is just a demo of one of them. say, instead of above basic authentication, you maintain your own database with user name and password. So you create a before filter and write your logic within that, if username password match allow the user to proceed or return “unauthorized message in the response”

  8. And my second question , Username and password looks like STATIC, can these be dynamic? Is this necessary to use this? if yes then how would I pass username and password through AJAX.

  9. @arunyadav4u – very nice tutorial. Looking at building a parallel API alongside our production web app (Heroku/RoR). However, I am not clear on where to jump in as I have a working User MVC code already. in your Controller section above, what would you recommend as far as creating a second User controller? What namespace to use (e.g., api_users_controller.rb, etc.) Thanks in advance for your guidance!

    • If you have followed the principal of “THIN controller FAT modal” i,e your controller have minimum code, I will suggest to create a separate controller for API. You can use the same namespace as above or rename it as you wish. But since it include repeatation of controller code, If your controller code is heavy, you can modify your existing controller and made the rendering conditional.

      just remember that , API just differ in terms of rendering of VIEW. instead of rendering view as in normal website, The API returns json or xml response.

      taking the same example as above, you can ask the consumer to send below payload.

      sample json body

      “email” : “”,
      “first_name” : “arun”,
      “last_name” : “yadav”
      “api_user” : “YES”

      We have asked the API consumer to pass an additional parameter “api_user”. Now, you can write condition as below.

          if params[:api_user] && params[:api_user] == "YES"
             # do stuff related to API
             # do noraml rendering

      In this case you also need to bypass the existing authentication for the API and introduce your own authentication.
      Say your existing users controller using devise authentication, you can bypass it for the API as below.

          skip_before_filter :authenticate_user!,  :if => lambda {|c| request.params["api_user"].present? && request.params["api_user"] == "YES" } 
  10. Hi Arun,
    It is a nice tutorial – thanks for sharing this information.
    I am new to Ruby on Rails.
    I am developing a sample application, I would like to use RoR for implementing REST api.
    In the browser, when user types in the url like http://localhost:3000/myapp/index
    It should hit index.html.erb. In this html file, I am making AJAX call to same url (/myapp/index) and expecting it to return Json string.
    In short,
    – I would like user to see URL as ‘myapp/index’,
    – UI should be able to make a call to REST api for getting the data (lets say using Ajax)
    – The REST Api will be implemented using RoR and exchanging the info in json format.

    Can you suggest me how should I design the flow in RoR.

    • Hi Pankaj,

      I didn’t get what you are trying to do. The confusion is due to your need of hitting the same URL with normal page laod or with ajax call.

      Let me parapharize what I understood :

      => user hit http://localhost:3000/myapp/index . It return data from say your local database
      => On the UI, there is some button or link say “get remote apps” . when user click it, it should again hit http://localhost:3000/myapp/index, but this time you want the controller to return data from some thirdparty API
      => You may want to reload the page or just refresh some partial within the page

      If this is your scenerion. You can use below to distinguish between the noraml and the ajax call

      if request.xhr?
      # code to call thirdparty API. read below about getting data from third party API
      #NOTE : you need to convert data returned by API, in foramte used in your view, say your view use users aboject as array,
      # but the API return json data, the you need to convert this json object into array
      @myapps = MyApps.all

  11. hi Arunyadav sir,
    Actually i am fresher and very new to ROR, Now in my company i need to create API for android app, before the some simple API’s i need to create, can you please help me with this, am not getting anything but if i get some help sure i will create API

    Thank you in Advance..

    • Hi Usha,

      You need to tell me the problem you are facing with your implementation . I know being a fresher jumping directly to API is somewhat confusing, but with your problem description, I can’t help you out . You need to tell me your problem area, so that I can provide you some direction.

      As you have said “Iam not getting anything” 🙂 .
      I suggest you to learn simple CRUD (CREATE READ UPDATE DESTROY) operation of rails first and then revisit this post .

  12. thank you !, really useful, helped me a lot.

  13. Great tutorial. However, below is also a great tutorial to learn making API in Rails for new Rails developer

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s