Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I create a web service with rails?

I have a silverlight application that needs to talk to a rails app to add a record. I have been able to get the silverlight app to successfully do the POST assuming everything goes good. Now, however, I need to be able to make it more robust and have the rails app return error/success messages to the silverlight app in a format it can read (xml maybe?). I can modify the rails app and silverlight app as needed.

What is the best way to accomplish this with rails?

like image 960
NotDan Avatar asked Feb 02 '26 06:02

NotDan


2 Answers

Rails handles most of this out-of-the-box.

You need to have a look at respond_to

This will return the records in @list as XML:

@list = Model.find(:all)
respond_to do |format|           
  format.html { render :action => "index" }
  format.xml  { render :xml => @list }
end             

You can set status using http headers (for actions that don't return anything):

format.xml  { head :ok }

And you can provide more complex messages, in this case returning Active Record errors and a status message:

format.xml  { render :xml => @model.errors, :status => :unprocessable_entity }
like image 111
Toby Hede Avatar answered Feb 04 '26 18:02

Toby Hede


This would be pretty much the same as any typical Rails app.

The only difference is that you'd be responding with xml (or json, or anything else Silverlight can parse) to any relevant actions. (Rather than rendering a page of HTML.)


Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!