Search code examples
rubyrest-clientcurbtyphoeus

Ruby Post Request with Basic Auth and Multiple Params


I'm having a ridiculously hard time doing something presumably simple...

I am trying to run a simple POST request in ruby. I've looked at curb, typhoeus, rest-client, etc... The post request has basic auth (via api key) and two params...

I have the command written out in curl form below, which works perfectly.

curl -X POST https://api.com/v1 -u any_string:abc123 -d var1="help" -d var2="me"

Can anyone help me translate this into ruby? I don't mind using typhoeus, curb, etc... as long as it works...


Solution

  • I've use this tool before with some success. https://jhawthorn.github.io/curl-to-ruby/

    Your curl statement generates this Ruby code.

    require 'net/http'
    require 'uri'
    
    uri = URI.parse("https://api.com/v1")
    request = Net::HTTP::Post.new(uri)
    request.basic_auth("any_string", "abc123")
    request.set_form_data(
      "var1" => "help",
      "var2" => "me",
    )
    
    response = Net::HTTP.start(uri.hostname, uri.port, use_ssl: uri.scheme == "https") do |http|
      http.request(request)
    end
    
    # response.code
    # response.body
    

    There are about a million different HTTP request libraries in Ruby but sometimes its just simple to write it in Net HTTP (Net HTTP is included in the Ruby Standard Library).