I'm trying my hand at making a rest full ruby service. The way my program is broken down is 2 applications. One is a web service spider and the other is a web app (yet to be developed) The web app will make requests to the crawler using get post and the usual stuff.
Heres a sample开发者_Python百科 post request using curl\
curl -d 'url=www.whatever.com&depth=10' http://127.0.0.1:8080/requests/new
works fine and seems to post a request.
heres the delete
curl -x DELETE http://127.0.0.1:8080/requests/1 where 1 is id of request.
My question is how do i make it so that If someone does a get reqeust (namely my web app) I can get the spider to respond in JSON
I'm assuming I need to format the @request variable to JSON and then have it be the response but I haven't the foggiest how to go about this.
Also on a side note: is the curl get request modeled in the same way.
On another side note: is there any way to tag code in stack overflow instead of using the four spaces.
If you always want to return JSON no matter where the request comes from (browser or spider), then simply return json data from your controller:
render :json => @object
If you want to support a spider (JSON) and a traditional web request from a browser (HTML), use the normal respond_to (using Rails 2 example..I don't know Rails 3 yet):
respond_to do |format|
format.js { render :json => @object }
format.html
end
And make sure you have the view files in the right place for the html.
You can send your params in Json like this :
curl -d "{ url: \"www.whatever.com\", depth: \"10\"}" -H "Content-Type: application/json" -H "Accept: application/json" http://127.0.0.1:8080/requests/new
For the response you must define your controller to response in Json format with respond_to or respond_with in Rails 3
Well, the response is typically output in plain HTML.
So, what you do is write a view that simply takes the response data, and formats into JSON.
The JSON format is very simple. So, if my GET response was a list of two names, for example, name = 'joe'
and name = 'bob'
The JSON would be: `{ "name":"joe","name":"bob" }
... and the view code would look something like (pseudocode):
{
<% @names.each do |name| %>
"name":"<%=h name %>",
<% end %>
}
精彩评论