Posting Ruby Data in JSON Format with Net/Http

Posting Ruby data in JSON format with Net/http

Make a request object like so:

request = Net::HTTP::Post.new(uri.request_uri, 
'Content-Type' => 'application/json')
request.body = newAcctJson
resp = http.request(request)

Using Ruby's Net/HTTP module, can I ever send raw JSON data?

After reading tadman's answer above, I looked more closely at adding data directly to the body of the HTTP request. In the end, I did exactly that:

require 'uri'
require 'json'
require 'net/http'

jsonbody = '{
"id":50071,"name":"qatest123456","pricings":[
{"id":"dsb","name":"DSB","entity_type":"Other","price":6},
{"id":"tokens","name":"Tokens","entity_type":"All","price":500}
]
}'

# Prepare request
url = server + "/v1/entities"
uri = URI.parse(url)
http = Net::HTTP.new(uri.host, uri.port)
http.set_debug_output( $stdout )

request = Net::HTTP::Put.new(uri )
request.body = jsonbody
request.set_content_type("application/json")

# Send request
response = http.request(request)

If you ever want to debug the HTTP request being sent out, use this code, verbatim: http.set_debug_output( $stdout ). This is probably the easiest way to debug HTTP requests being sent through Ruby and it's very clear what is going on :)

JSON string pulled via net/http to Hash

As you can see, the field you are looking for is into an inner hash. Try

puts json_hash["query"]["results"]["rate"]["Rate"]

Ruby on Rails: How to 1) READ JSON from URL, then 2) GET the desired data, and 3) ADD create new record to the database

you can use httparty gem for making API call and getting results from it as below:

def create
URL = "http://world.openfoodfacts.org/api/v0/product/3661112054465.json"
response = HTTParty.get(url).parsed_response

product_params = {
name: response['product']['product_name'],
image_url = response['product']['image_url'],
description = response['product']['description']
}
@product = Product.new(product_params)
@product.save
end

Please read more about HTTParty Gem

I hope this will help you.



Related Topics



Leave a reply



Submit