Creating Web Services with Ruby on Rails

Rails Framework is web services ready and it comes with built-in web services functions and methods that makes it easy for the Rails developer to expose controller’s actions as JSON services. In order to create a service, you need to start with our traditional model.

rails generate resource Item name
rake db:migrate

Next step is to implement actual service interfaces by modifying app/controllers/item_controller.rb

class ItemsController < ApplicationController
 before_action :set_item, only: [:show, :edit, :update, :destroy]

 def  index
  @items = Item.all
  respond_to do |format|
   format.json {render json: @items}
  end
end
def update
 respond_to do |format|
 if @item.update(item_params)
  format.json {render :show, status: :ok, location: @item}
 end
end

 private //callbacks
 def item_params
  params.require(:item).permit(:name)
 end
 def set_item
  @item = Item.find(params[:id])
 end
end

As you can see form the example above, item_controller.rb is used to implement JSON CRUD operations for the items table. It is easy to draw parallels between JSON and HTML controllers if you compare two so there is little learning curve for implementing either one in Rails.

It is not too difficule to query Web Services that we created in our example. In order to do so, you need to include references to

gem “rest-client”
require “rest_client”
RestClient.get “http://localhost:3000/items”
{:params => {:id=1}, :accept=>:json}
RestClient.post “http://localhost:3000/items”
{“name”=>”test”}.to_json, :content_type=>:json, :accept=>:json}

Featured pages

Ruby

Set of Ruby Object Oriented Programming Language tutorials that cover such topics as Ruby strings, …

Rails

Rails Framework tutorial teaches you how to utilize de facto framework of choice for Ruby developme…

Ruby Duck Typing

“If an object quacks like a duck just go ahead and treat it as a duck” – this fun…

Regular Expressions

Ruby uses the =~ operator to check any given string against regular expression. For example, a stri…

Credit Card Number

Every last digit of any credit card is a check sum digit that is determined by all digits in front …

Ruby Arrays

Ruby Programming Language has built in support for Arrays. Arrays help you define some of the compl…

Ruby Hashes

Hashes are very similar to arrays in Ruby and hashes interface is similar to Ruby array interface. …

Ruby Code Block

Ruby is very unique language when it comes to code blocks. You can simply pass a code block to a me…