1

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?

0

1 Answer 1

1

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\"}"
Sign up to request clarification or add additional context in comments.

2 Comments

I also had to change url = "http://localhost:8000/api/v1/person/?format=json" to url = "http://localhost:8000 and then create the request with a relative path: request = Net::HTTP::Post.new("/api/v1/person/?format=json")
Note you can use this syntax: payload = {firstName: "John", lastName: "Appleseed"} to create the hash.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.