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?

2 Answers 2

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'
)
Sign up to request clarification or add additional context in comments.

Comments

2

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 :)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.