How to send JSON via HTTP to Ruby after conversion from Python?

I concede - I tried to crack this nut for several hours, but I canโ€™t understand. I'm too new to Ruby (and I don't have a Python background!) To translate this, and then post my JSON data to a site that requires a user / password, and then get the response data.

This is the Python code:

r = requests.post('https://keychain.oneid.com/validate/', json.dumps(data), auth=('username', 'password')) r.json() 

where data :

 {"some" => "data", "fun" => "times"} 

I am trying to replicate the functionality of this code in Ruby for use with a Rails application, but between finding out how the Python requests.post() function works and then writing the Ruby code for POST and GET, I got completely lost.

I tried Net :: HTTP, but I donโ€™t understand if I should put the username / password in the body or use the basic_auth method - basic_auth seems to work only inside Net::HTTP.get ... and Net :: HTTP, it seems does not cope with JSON, but then again, I could be completely ready for dinner at this point.

Any suggestions or help would be greatly appreciated!

+6
source share
2 answers

Use the rest-client gem or just use Net::HTTP .

Ruby Code (version 1.9.3):

 require 'net/http' require 'json' require 'uri' uri = URI('https://keychain.oneid.com/validate/') req = Net::HTTP::Post.new uri.path # ruby 2.0: req = Net::HTTP::Post.new uri req.basic_auth 'username', 'password' req.body = {:some => 'data', :fun => 'times'}.to_json res = Net::HTTP.start(uri.host, uri.port, :use_ssl => true) do |http| http.verify_mode = OpenSSL::SSL::VERIFY_NONE http.ssl_version = :SSLv3 http.request req end puts res.body # => {"errorcode": -99, "error": "Invalid API credentials. Please verify and try again"} json = JSON.parse res.body puts json['errorcode'] # => -99 
+16
source

I would recommend taking a look at the RestClient gem. This makes it easier to work with GET / POST, as well as all other REST calls. It also has an IRB shell called restclient , accessible from the command line, which simplifies the experiment with connection settings.

From the documentation:

 RestClient.post "http://example.com/resource", { 'x' => 1 }.to_json, :content_type => :json, :accept => :json 

Looking at this, you can see the similarities with the Python code.

You can add authentication information to the hash:

 require 'restclient' require 'json' require 'base64' RestClient.post( 'https://keychain.oneid.com/validate/', { :authentication => 'Basic ' + Base64.encode64(name + ':' + password), 'some' => 'data', 'fun' => 'times' }.to_json, :content_type => :json, :accept => :json ) 

Alternatively, you can use the Curb gem. Curb uses libcurl, which is the industry standard web connection tool. The documentation shows several ways to send POST requests.

+3
source

Source: https://habr.com/ru/post/944679/


All Articles