Posting JSON with headers in Ruby with Net::HTTP

Ok, so bits and pieces of this are spread all over the Internet, but I struggled to find a comprehensive example of:

  1. Using Ruby…
  2. …and Net::HTTP…
  3. …posting JSON…
  4. …with a custom header
  5. …and telling me how to deal with the response

So, here is a comprehensive example of using Ruby and Net::HTTP to POST some JSON with a custom header and looking at the response body:

require 'net/http'
net = Net::HTTP.new("www.myservice.com", 8081)
request = Net::HTTP::Post.new("/some/url/here")
request.set_form_data({"a_named_field" => some_object.to_json})
request.add_field("X-API-KEY", "some api key or custom field")
net.set_debug_output $stdout #useful to see the raw messages going over the wire
net.read_timeout = 10
net.open_timeout = 10

response = net.start do |http|
http.request(request)
end
puts response.code
puts response.read_body

Enjoy!