3

I've been doing a lot of research on the topic of sending JSON data through Ruby HTTP requests, compared to sending data and requests through Fiddler. My primary goal is to find a way to send a nested hash of data in an HTTP request using Ruby.

In Fiddler, you can specify a JSON in the request body and add the header "Content-Type: application/json".

In Ruby, using Net/HTTP, I'd like to do the same thing if it's possible. I have a hunch that it isn't possible, because the only way to add JSON data to an http request in Ruby is by using set_form_data, which expects data in a hash. This is fine in most cases, but this function does not properly handle nested hashes (see the comments in this article).

Any suggestions?

Max
  • 808
  • 11
  • 25

2 Answers2

3

Although using something like Faraday is often a lot more pleasant, it's still doable with the Net::HTTP library:

require 'uri'
require 'json'
require 'net/http'

url = URI.parse("http://example.com/endpoint")

http = Net::HTTP.new(url.host, url.port)

content = { test: 'content' }

http.post(
  url.path,
  JSON.dump(content),
  'Content-type' => 'application/json',
  'Accept' => 'text/json, application/json'
)
tadman
  • 208,517
  • 23
  • 234
  • 262
1

After reading tadman's answer above, I looked more closely at adding data directly to the body of the HTTP request. In the end, I did exactly that:

require 'uri'
require 'json'
require 'net/http'

jsonbody = '{
             "id":50071,"name":"qatest123456","pricings":[
              {"id":"dsb","name":"DSB","entity_type":"Other","price":6},
              {"id":"tokens","name":"Tokens","entity_type":"All","price":500}
              ]
            }'

# Prepare request
url = server + "/v1/entities"
uri = URI.parse(url)  
http = Net::HTTP.new(uri.host, uri.port)
http.set_debug_output( $stdout )

request = Net::HTTP::Put.new(uri )
request.body = jsonbody
request.set_content_type("application/json")

# Send request
response = http.request(request)

If you ever want to debug the HTTP request being sent out, use this code, verbatim: http.set_debug_output( $stdout ). This is probably the easiest way to debug HTTP requests being sent through Ruby and it's very clear what is going on :)

Max
  • 808
  • 11
  • 25