How to Receive a JSON Object with Rack

How to receive a JSON object with Rack

env['rack.input'].gets

This worked for me. I found that using curl or wget to test POST requests against a Rack (v1.4.1) server required using this code as a fallback to get the request body. POST requests out in the wild (e.g. GitHub WebHooks) didn't have this same problem.

How to response with JSON format using Ruby Rack middleware

Include the "json" gem in your project, and then call #to_json on the Hash:

app = Proc.new do |env| 
[200, { 'Content-Type' => 'application/json' }, [ { :x => 42 }.to_json ]]
end

Note that nil is translated to null in the JSON, if you need null.

How to read POST data in rack request

From reading the docs for POST, looks like it is giving you parsed data based on other content types. If you want to process "application/json", you probably need to

JSON.parse( req.body.read )

instead. To check this, try

puts req.body.read

where you currently have puts req.POST.


req.body is an I/O object, not a string. See the body documentation and view the source. You can see that this is in fact the same as mudasobwa's answer.

Note that other code in a Rack application may expect to read the same I/O, such as the param parsers in Sinatra or Rails. To ensure that they see the same data and not get an error, you may want to call req.body.rewind, possibly both before and after reading the request body in your code. However, if you are in such a situation, you might instead consider whether your framework has options to process JSON directly via some option on the controller or request content-type handler declaration etc - most likely there will be an option to handle this kind of request within the framework.

return json from ruby using rack

You don't have to save the JSON to a file before you can send it. Just send it directly:

[200, {"Content-Type" => "application/json"}, [tempHash.to_json]]

With your current code, you are only sending the String "temp.json".

That said, the rest of your code looks a little bit messy/not conform Ruby coding standards:

  • Start your classnames with an uppercase: class ListImages, not class listImages.
  • Use underscores, not camelcase for variable names: image_dir, not imageDir.
  • The puts "All done!" statement is outside the method definition and will be called early, when the class is loaded.
  • You define a class ListImages but in the last line of your code you refer to MyApp.


Related Topics



Leave a reply



Submit