Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby: How do I send a JSON POST request using Curb?

Tags:

post

ruby

curb

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
like image 337
Marco Avatar asked Oct 03 '10 20:10

Marco


1 Answers

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.

like image 130
Marco Avatar answered Sep 23 '22 02:09

Marco