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 GemI hope this will help you.
Related Topics
Is 'Respond_To_Missing''s Second Argument Useful for Anything
Get Route for Base Class of Sti Class in Rails
When Is The Enumerator::Yielder#Yield Method Useful
Difference Between Render and Yield in Rails
How to "Break" Out of a Case...While in Ruby
How to Have Two Columns in One Table Point to The Same Column in Another with Activerecord
Static Page Routing in Sinatra (Ruby)
Get Value from String Representing Local Variable
Bundler Using Wrong Ruby Version
Ruby Readline Fails If Process Started with Arguments
Cucumber Embed for Screenshots Not Linking to Screenshot
How to Resize Image Only If Width Exceeds with Graphics/Image Magick
Access Rake Task Description from Within Task
Having Problems with Railsinstaller
Ruby Symbols Are Not Garbage Collected!? Then, Isn't It Better to Use a String