creatye a method to send an http post request with basic authorization in ruby

To send an HTTP POST request with basic authorization in Ruby, you can use the Net::HTTP module that comes with the standard library. Here's an example method that takes a URL, a payload, a username, and a password:

main.rb
require 'net/http'
require 'uri'

def send_post_request(url, payload, username, password)
  uri = URI.parse(url)
  
  headers = {
    'Authorization' => "Basic " + Base64.strict_encode64("#{username}:#{password}"),
    'Content-Type' => 'application/json'
  }

  http = Net::HTTP.new(uri.host, uri.port)
  http.use_ssl = true if uri.scheme == 'https'

  response = http.post(uri.path, payload.to_json, headers)
  
  if response.code == '200'
    return JSON.parse(response.body)
  else
    raise "Error sending POST request: #{response.code} #{response.body}"
  end
end
570 chars
23 lines

Here's how you can use this method to send a POST request to https://example.com/api with a JSON payload and basic auth credentials 'username' and 'password':

main.rb
url = 'https://example.com/api'
payload = { foo: 'bar' }
username = 'username'
password = 'password'

response = send_post_request(url, payload, username, password)
puts response
179 chars
8 lines

gistlibby LogSnag