Ruby send JSON request Ruby send JSON request json json

Ruby send JSON request


uri = URI('https://myapp.com/api/v1/resource')req = Net::HTTP::Post.new(uri, 'Content-Type' => 'application/json')req.body = {param1: 'some value', param2: 'some other value'}.to_jsonres = Net::HTTP.start(uri.hostname, uri.port) do |http|  http.request(req)end


require 'net/http'require 'json'def create_agent    uri = URI('http://api.nsa.gov:1337/agent')    http = Net::HTTP.new(uri.host, uri.port)    req = Net::HTTP::Post.new(uri.path, 'Content-Type' => 'application/json')    req.body = {name: 'John Doe', role: 'agent'}.to_json    res = http.request(req)    puts "response #{res.body}"rescue => e    puts "failed #{e}"end


HTTParty makes this a bit easier I think (and works with nested json etc, which didn't seem to work in other examples I've seen.

require 'httparty'HTTParty.post("http://localhost:3000/api/v1/users", body: {user: {email: 'user1@example.com', password: 'secret'}}).body