10

How can I set the request body of a CURB request to be my json string? I am trying to do a JSON POST request using Curb.

My code:

require 'rubygems'
require 'curb'
require 'json'

myarray = {}
myarray['key'] = 'value'
json_string = myarray.to_json()

c = Curl::Easy.http_post("https://example.com"

      # how do I set json_string to be the request body?

    ) do |curl|
      curl.headers['Accept'] = 'application/json'
      curl.headers['Content-Type'] = 'application/json'
      curl.headers['Api-Version'] = '2.2'
    end
Marco
  • 4,345
  • 6
  • 43
  • 77

1 Answers1

42

The correct way of doing this is to simply add the content after the URL:

c = Curl::Easy.http_post("https://example.com", json_string_goes_here   
    ) do |curl|
      curl.headers['Accept'] = 'application/json'
      curl.headers['Content-Type'] = 'application/json'
      curl.headers['Api-Version'] = '2.2'
    end

This will set the json_string to be the request body.

Marco
  • 4,345
  • 6
  • 43
  • 77
  • 8
    Nice. Something like this should be included into Curb documentation. – Lukas Stejskal Nov 09 '13 at 21:08
  • 3
    I just experienced some grief with some of the data I was trying to put in the `json_string_goes_here`. Using the ruby json library if you apply `JSON.pretty_generate(object)` it may solve some problems with unescaped characters. – hamitron Dec 15 '15 at 01:01