MartinMoizard
MartinMoizard

Reputation: 6680

Ruby on rails web services with POST request

I've just started learning Ruby on rails and I am wondering how to do something that I know how to easily do in PHP. I want to create some basic web services that can be called with POST parameters and send a JSON as a response. I don't know at all how to start with that using Ruby on rails.

I am sure there are some best practice to do that kind of things, so if you guys could advise me anything, it would be great!

Regards,

Upvotes: 1

Views: 1317

Answers (3)

scaney
scaney

Reputation: 1766

The great thing about rails is that it is based on the principal of REST.

Whenever you create a RESTful resource, you are in fact creating a web service at the same time.

For example. Say you create a resource using a scaffold generator.

rails g scaffold Feed title:string content:string

This will not only create all the view logic in HTML, but also in xml.

Further to your first comment:

If you look in the controller, within the respond_to block you can specify the return type. So you want to hit the xml version of new and return the json version of create.

To render your treated parameters to json, put them in a hash:

js = {:my => {:json => 'hash'}}
render :json => js

Upvotes: 0

Keith Gaddis
Keith Gaddis

Reputation: 4113

To get the POST parameters, you just look into the params hash in your controller, which will have any and all parameters for the request, whether they're coming as POST params, GET params, or as part of the route (e.g. /users/:id/new => params[:id] in the controller)

To return json from the request, you'd just make a render call like this:

render :json => @model

Beyond that, your question is a bit broad for the scope of an answer on SO. I recommend reading Agile Web Development with Rails as a starting point to learn Rails development.

Upvotes: 1

aceofspades
aceofspades

Reputation: 7586

Sounds like a good fit for Sinatra. Check out http://www.sinatrarb.com/

Upvotes: 1

Related Questions