Wednesday, November 30, 2011

Handle JSON or XML request and response

Hello Guys,
        Some time we required to pass the request in particular format and get response back in same format. 

1. Consider the request and response format as JSON

Request:
curl -H "Accept: application/json" -i -X GET http://DOMAIN:PORT/controller/action/parameters
eg. curl -H "Accept: application/json" -i -X GET http://127.0.0.1:3000/posts/show/1

Response:
In the show method of posts controller we have to check whether request type is JSON than return response back to JSON format.

def show
  if request.format == Mime::JSON 
     post = Post.find_by_id(params[:id])
     render :json => post.to_json, :status => 200
  end
end

Now we get response as the requested post in .json. we will parse the json by JSON::load(response)

2. Consider the request and response format as XML

Request:
curl -H "Accept: application/xml" -i -X GET http://DOMAIN:PORT/controller/action/parameters
eg. curl -H "Accept: application/xml" -i -X GET http://127.0.0.1:3000/posts/show/1

Response:
In the show method of posts controller we have to check whether request type is XML than return response back to XML format

def show
  if request.format == Mime::XML
     post = Post.find_by_id(params[:id])
     render :xml => post, :status => 200
  end
end

Now we get response as the requested post in .xml. we will parse the xml using Hpricot or any other parser.

Hope this post will help you to deal with json and xml format.

No comments:

Post a Comment