Question

I need to send some POST data through a ruby script. I've been able to send it through python, using requests, with the following code:

payload = {"firstName": "John", "lastName": "Appleseed"}
headers = {'content-type': 'application/json'}
r = requests.post ("http://localhost:8000/api/v1/person/?format=json",data=json.dumps(payload), headers = headers)

Now, I tried to translate it into ruby with net/http:

url = "http://localhost:8000/api/v1/person/?format=json"
payload = {:firstName => 'John', :lastName => 'Appleseed'}.to_s

request = Net::HTTP::Post.new(url)
request.add_field('content-type', 'application/json')
request.body = payload

uri = URI.parse(url)
http = Net::HTTP.new(uri.host, uri.port)
response = http.request(request)

But I'm getting 404 from the server. Any idea what I might be doing wrong with the ruby code?

Was it helpful?

Solution

Look at what payload looks like:

>> {:firstName => 'John', :lastName => 'Appleseed'}.to_s
=> "firstNameJohnlastNameAppleseed"

json.dumps doesn't produce that output. You want to use to_json instead:

>> require "json"
=> true
>> {:firstName => 'John', :lastName => 'Appleseed'}.to_json
=> "{\"firstName\":\"John\",\"lastName\":\"Appleseed\"}"
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top