Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I get rails to parse params from CURL as JSON or XML instead of a string?

How do I get rails to parse params as JSON or XML instead of a string? I'm using rails 3.0.7.

Here's what I want to happen.

Parameters: {"user"=>{"email"=>"[email protected]", "password"=>"[FILTERED]"}}

Here's what happens

# controller
def create
  logger.debug params
end

# curl from command line
curl -i -H 'Content-Type:application/xml' -H 'Accept:application/xml' -X POST -d "<user><email>[email protected]</email><password>password</password></user>" http://localhost:3000/api/v1/sessions.xml

# response
Started POST "/api/v1/sessions" for 127.0.0.1 at 2011-05-14 02:16:23 -0700
Processing by Api::V1::SessionsController#create as XML
Parameters: {"<user><email>[email protected]</email><password>password</password></user>"}
{"<user><email>[email protected]</email><password>password</password></user>", "action"=>"create", "controller"=>"api/v1/sessions", "format"=>"xml"}

Same thing happens with JSON.

like image 529
Dan Avatar asked Dec 27 '22 20:12

Dan


2 Answers

An HTTP POST is typically name/value pairs.

Rails is doing its best try and figure out what you've passed it and turn it into a params hash, but it doesn't really make sense.

You can access the request directly:

def create
  string = request.body.read
  # if string is xml
  object = Hash.from_xml(string)
  # elsif string is JSON
  object = ActiveSupport::JSON.decode(string)
end
like image 88
Simon Avatar answered Jan 13 '23 12:01

Simon


Run rake middleware, check that the ActionDispatch::ParamsParser is used. Take a look at actionpack-3.0.7/lib/action_dispatch/middleware/params_parser.rb This is the middleware that's parsing the providing data to params hash. My guess is that the problem is with curl, as it doesn't post the request as you think it should. Maybe it needs a space after a colon (in headers), I don't know. I found this on google: http://snippets.dzone.com/posts/show/181.

like image 21
Roman Avatar answered Jan 13 '23 12:01

Roman