breaking into the unknown…

Sample API consumer or API client


The people who make API call are API consumer or API client. Those who build the API to expose there application, making it interact with other application are called API provider. I have created a sample API in this post . Any other application(the consumer) can make call to this API to register, update or delete the user on API provider database.

You can see that the API provider has documented the url, authentication, expected data type and data required to fulfil your request. Provided, you fulfil, those criteria  , you can write your API consumer code in any language. Here, we will stick to Ruby.

Ruby has inbuilt library, to manage , making API calls, retrieving the returned response and parsing it to  reuse it in your own application. Below are those library.

You may directly, use the above two library, to write your API consumer class. But, being part of ruby community, you do not need to go in much depth 🙂 as a no of Gem are available, there : – rest-client , faraday , httparty . I am not in position, to make a comment on which one is best or advantage and disadvantage of them, as I have tried only rest-client.

Now Let us make a Application which will consume the API,  I have developed in this post. The API, provide functionality to manage user, so in our application we will not store user in our own database, but will register it , update and delete them with the API provider.

I am assuming that, you all have implemented users controller at some point of time, where you have implemented index , new, create, edit, update and destroy method. Here, the view, routes and everything remain same, only the Users controller code will change, as now, it will interact, not with your Databse, but with the API provider Database .

Let us create our Rails Apllication, which will consume the user management API

STEP 1: generate the rails app

we will call it api_consumer

$ rails new api_consumer

STEP 2: add rest-client gems to your Gemfile

gem ‘rest-client’

run bundle install on the terminal

$ bundle install

STEP 3: generate the user controller

$ rails g controller users

STEP 4: add the routes for users resource in your routes

ApiConsumer::Application.routes.draw do
resources :users

STEP 5: Write the users controller code.

Users controller will have, the same actions and flow as you have seen in your, users controller, except that, here you interact with API provider database, thorugh its API call. IF you see the API provider document, you can see that they have provided you the authentication, url and expected data format.

You just have to make a call to these URL and handle the returned data in your application. API now a days return, data in XML or json format in general, but in case they return data in some other format say SOAP, then you have to adjust your code accordingly. The API provider whose service we are going to use return XML data by default i,e if you do not provide format in URL, they will return XML data. But, I found it easy to handle json data, So while making the call, we will specifically ask for json data.

So below is our controller code :

NOTE : see the use of get post put and delete call of the REST client. It will decide which action of API provider will be called for certain URL

class UsersController < ApplicationController
  require 'rest_client'

  USERNAME = "myfinance" # needed to access the APi
  PASSWORD = "credit123" # needed to access the APi
  API_BASE_URL = "http://localhost:3000/api" # base url of the API

  def index
    uri = "#{API_BASE_URL}/users.json" # specifying json format in the URl
    rest_resource =, USERNAME, PASSWORD) # It will create
    new rest-client resource so that we can call different methods of it
    users = rest_resource.get # will get back you all the detail in json format, but it
    will we wraped as string, so we will parse it in the next step.
    @users = JSON.parse(users, :symbolize_names => true) # we will convert the return 
    data into array of hash.see json data parsing here

  def new


  NOTE :  see below how we are passing the payload and content type while making the post call
  def create
    uri = "#{API_BASE_URL}/users"
    payload = params.to_json # converting the params to json
    rest_resource =, USERNAME, PASSWORD)
    begin payload , :content_type => "application/json"
      flash[:notice] = "User Saved successfully"
      redirect_to users_path # take back to index page, which now list the newly created user also
    rescue Exception => e
     flash[:error] = "User Failed to save"
     render :new

  def edit
    uri = "#{API_BASE_URL}/users/#{params[:id]}.json" # specifying format as json so that 
                                                      #json data is returned 
    rest_resource =, USERNAME, PASSWORD)
    users = rest_resource.get
    @user = JSON.parse(users, :symbolize_names => true)

  def update
    uri = "#{API_BASE_URL}/users/#{params[:id]}"
    payload = params.to_json
    rest_resource =, USERNAME, PASSWORD)
      rest_resource.put payload , :content_type => "application/json"
      flash[:notice] = "User Updated successfully"
    rescue Exception => e
      flash[:error] = "User Failed to Update"
    redirect_to users_path

  def destroy
    uri = "#{API_BASE_URL}/users/#{params[:id]}"
    rest_resource =, USERNAME, PASSWORD)
     flash[:notice] = "User Deleted successfully"
    rescue Exception => e
     flash[:error] = "User Failed to Delete"
    redirect_to users_path

STEP 6 : Create the corresponding views to the controller action


It will list all the user detail returned by the API, it will as usual, provide “create new user” link to create a new user, also each record will have a Edit | Delete link. clicking the edit link will take the user to edit page where they will modify there detail and the Delete action will delete the user.

<%= link_to "Create New User", new_user_path %>
<%if @users.present? %>
  <p>Below is the list of users</p>
  <table width="100%">
    NOTE : the @users object in our index action is array of hash, which is generated 
    when be passed return data to JSON.parse method. If you handled data in some other
    way, modify the code below accordingly. say for xml data you have to use something like
    u.xpath("id").text instead of u[:id]
    <%@users.each do |u|%>
        <%= link_to "Edit", edit_user_path(u[:id]) %> | 
        <%= link_to "Delete", user_path(u[:id]), :method => :delete %>
  <p>No User is Found</p>


Here, as usual, user will fill up his detail and on submit it will go to create action, which will call create action of API to create the new user.

<%= form_tag users_path, :method => :post do %>
   email : <%=text_field_tag :email%><br />
   first_name :<%=text_field_tag :first_name%><br />
   last_name :<%=text_field_tag :last_name%><br/><br/>
   <%=submit_tag "save"%>

User will modify, there detail and submit to update action, which in turn update the record on API provider data base.

<%= form_tag user_path, :method => :put do %>
   email : <%=text_field_tag :email, @user[:email]%><br />
   first_name :<%=text_field_tag :first_name, @user[:first_name]%><br />
   last_name :<%=text_field_tag :last_name, @user[:last_name]%><br/><br/>
   <%=submit_tag "update"%>

STEP 7 : see it working

both the API provider and API consumer are sample application running on my own local machine. I have fixed the port 3000 for the API provider application. so start the API provider application on 3000, which is by default

$ cd to_api_provider_folder

$ rails s # will start the API provider service ast 3000

NOTE : for API consumer code to work, The API provider application must be up and running

Start the API consumer application on some other port, say 3030

$ cd api_consumer

$ rails s -p 3030

Go to the index page of the application:

http://localhost:3030/users # it will show you all users with edit | delete link and also a create new user link. So remaining things are self explainatory, try it out  yourself


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.

26 thoughts on “Sample API consumer or API client

  1. Hi there, just wanted to say, I liked this blog post. It was
    fun. Keep on posting!

  2. Hello! I just would like to offer you a huge thumbs up for your great info you’ve got right here on this post. I’ll be coming back to your web site for more soon.

  3. you are really a good webmaster. The site loading speed is amazing.
    It kind of feels that you are doing any distinctive trick.
    Also, The contents are masterpiece. you’ve done a great activity on this topic!

  4. Thanks for this post man, Awesome stuff! I like how clearly and easily you explain stuff. Cheers!

  5. It is appropriate time to make some plans for the longer
    term and it’s time to be happy. I have learn this put up and if I may I wish to suggest you some interesting issues or advice.
    Maybe you can write next articles referring to this article.
    I desire to learn more issues approximately it!

  6. Hello, I really love your work so for. Keep it going!
    I just have one “minor” question. I’m trying to build two Rails apps: one that accepts and returns JSONs (server side) and one that renders views and such for the user (client side).
    I’ve managed to build the User registration part in the same way as you did above.
    However, I’m having issues in the whole Sessions part of the application. I’m not sure how to keep the user signed in across the app or how to even use the “token” that was sent from the server side.
    Have you ever encountered such issues?


    • Hi Sebastine,

      I think, you are trying to authenticate users on application-1 from application-2.
      Iam using similer flow for one of my project .

      => sunpower is application-1 for me
      => When user click on Login button, he is taken to OpenAm i,e application-2 for me.
      the OpenAm do the user authentication, once user login successfully to it, it redirect the user back to application-1, with user detail.I have introduced SAML SSO logic to interect between the two application. In your case, keeping the thing simple, your application-2 should return user_id or anyother identifier for user who successfully get authenticated
      => You need to capture the identifier return from application-2 in application-1 and using that find that user from db and login that user from your controller using devise sigin_in method

      Note : In my case Application-1 database hold all the user details while Application-2 contain basic authentication detail like user_id, email, username, password etc.

      In case you do not want to keep any user detail on application-1, but all the details including authentication on application-2 itself, your application-2 should return the user object instead of just a token or user_id and then you need to keep that user object in a session variable of application-1.Here also you can use sigin_in method of devise for creating the session.So, you need to do something like below in application-1 controller action where user is returned back

      @user = user_object # user_object returned by application-2
      sigin_in @user

  7. It’s really a cool and useful piece of information. I am happy that
    you shared this useful information with us. Please keep us up to date like this.
    Thanks for sharing.

  8. Wow! At last I got a blog from where I can truly get helpful facts
    regarding my study and knowledge.

  9. Heya! I understand this is sort of off-topic but I needed to ask.
    Does building a well-established blog such as yours take a lot of
    work? I am brand new to operating a blog however I do write
    in my diary everyday. I’d like to start a
    blog so I can share my personal experience and views online.
    Please let me know if you have any ideas or tips for
    new aspiring blog owners. Thankyou!

    • Hi Kristal,

      If you have good content, You do not have to worry much about structure of your blog. WordPress doing great service for all enthusiastic blogger for free . Just create a free account on wordpress and you are ready to go.

  10. I learned a lot from this post. Awesome post. Many thanks.

  11. Hi Arun,
    I am using a REST Client in firefox to send xml data to my Rails Controller. But I am not getting the XML as expected in the controller. My params contains only this much {“format”=>”xml”, “action”=>”create”, “controller”=>”api/restusers”}.

    From my Rest Client i passed

    • Hi Sachi,
      Sorry for the so late reply…actually I missed the notification of your comment.

      If you had set contentType as xml, you need to pass XML in the body not plain data as you have mentioned above

  12. Thanks for sharing your thoughts about klicken.

  13. I need to pass userId in header, how can I pass it in this example (userId – testUser)

  14. What if I need a ORM style of API client?
    Do I need to use another gem or I can do it with rest-client? Thanks!

  15. Hello man I had this problem : “Missing template users/index, application/index with {:locale=>[:en], :formats=>[:html], :variants=>[], :handlers=>[:erb, :builder, :raw, :ruby, :coffee, :jbuilder]}. Searched in: * “/Users/juanxps/api_consumer/app/views””

    Can you help me please?

  16. Thank god. I swear this is the only rails specific tutorial on rest-client. I love you.

  17. Pingback: Building a RESTful API in a Rails Application | MK(Ruby on Rails developer)

  18. I am getting error 422 while posting the data in json format in create function. I have modified the code into a ruby script .

    • `exception_with_response’: 422 Unprocessable Entity (RestClient::UnprocessableEntity)
      This is the error which i am getting

      • It is difficult for me to get the problem you are facing with above information.

        are you wrapping your code in begin rescue block i,e rescuing the exception . If yes then remove it, so that you get more detail about the problem in your code.

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