Search code examples
rubyjsonhttprequestnet-http

Using Ruby's Net/HTTP module, can I ever send raw JSON data?


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?


Solution

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