create a rails model method to send an http post request with basic authorization in ruby

main.rb
require 'net/http'

class YourModel < ApplicationRecord

  def send_post_request(url, body)
    uri = URI(url)
    http = Net::HTTP.new(uri.host, uri.port)

    request = Net::HTTP::Post.new(uri)
    request.basic_auth('username', 'password')
    request.set_form_data(body)

    response = http.request(request)
    response.body
  end

end
342 chars
18 lines

Explanation:

  • We require the net/http module to make requests to HTTP servers.
  • We define a method called send_post_request that accepts two parameters, the URL we want to send the request to, and the body of our request.
  • We instantiate an instance of the Net::HTTP class with the host and port of the URL we want to send the request to.
  • We create an instance of the Net::HTTP::Post class and pass the URL we want to send the request to as an argument to its constructor.
  • We set basic authentication for our request by calling the basic_auth method on our instance of the Net::HTTP::Post class and passing our username and password as arguments.
  • We set our request's parameters using the set_form_data method and passing our body parameter.
  • We send our request and get a response by calling the request method on our http object with our request object as the argument.
  • We return the response's body.

gistlibby LogSnag