2

I am trying to automate the following curl command line into Ruby Curb:

curl -H "Content-Type:application/json" -X POST -d \
 '{"approvalType": "auto", 
  "displayName": "Free API Product",
  "name": "weather_free",
  "proxies": [ "weatherapi" ],
  "environments": [ "test" ]}' \
-u myname:mypass https://api.jupiter.apigee.net/v1/o/{org_name}/apiproducts

Where myname, mypass and {org name} are filled in prior to running the script.

I don't know how to do a http post with the JSON payload using basic authentication using Ruby Curb. I tried the following:

require 'json'
require 'curb'

payload = '{"approvalType": "auto", 
  "displayName": "Test API Product Through Ruby1",
  "name": "test_ruby1",
  "proxies": [ "weather" ],
  "environments": [ "test" ]}'

uri = 'https://api.jupiter.apigee.net/v1/o/apigee-qe/apiproducts'
c = Curl::Easy.new(uri)
c.http_auth_types = :basic
c.username = 'myusername'
c.password = 'mypassword'
c.http_post(uri, payload) do |curl| 
    curl.headers["Content-Type"] = ["application/json"]
end

puts c.body_str
puts c.response_code

The result is an empty body and a 415 response code. I verified that the curl command works perfectly fine.

Any help would be greatly appreciated because it would solve a whole class of problems I'm working on now.

Mike Malloy
  • 1,520
  • 1
  • 15
  • 19

2 Answers2

3

I used Curb (0.8.5) and found out, that if I reused curl instance over multiple requests (get request to save cookies and then post data) and http_post method was used like

http_post(uri, payload) 

it would actually send uri and payload combined into single json request ( which of course resulted in errors like "Unexpected character ('h'..." or "Bad Request" ).

I managed to get it working, but I had to use the method with payload as a single argument:

c =Curl::Easy.new
url = "http://someurl.com"
headers={}
headers['Content-Type']='application/json'
headers['X-Requested-With']='XMLHttpRequest'
headers['Accept']='application/json'
payload = "{\"key\":\"value\"}"

c.url = url
c.headers=headers
c.verbose=true
c.http_post(payload)

Hope this helps.

denvazh
  • 31
  • 4
0

A 415 response code indicates "server does not support media type". Does it work if you set the Content-Type like this instead (without the brackets)?

curl.headers["Content-Type"] = "application/json"
Wally Altman
  • 3,535
  • 3
  • 25
  • 33