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}