write a method to send a post request to the specified endpoint with basic authentication in ruby

You can use the Net::HTTP library in Ruby to send a post request to an endpoint with basic authentication. Here's an example method:

main.rb
require 'net/http'

def post_with_auth(url, data, username, password)
  uri = URI.parse(url)
  http = Net::HTTP.new(uri.host, uri.port)
  request = Net::HTTP::Post.new(uri.request_uri)
  request.basic_auth(username, password)
  request.set_form_data(data)
  response = http.request(request)
  return response.code.to_i, response.body
end
338 chars
12 lines

Explanation of the method:

  • url: URL of the endpoint to send the post request to
  • data: A hash of the data to send in the post request
  • username: Username for basic authentication
  • password: Password for basic authentication

The Net::HTTP library is used to create a connection to the endpoint. A Net::HTTP::Post object is created with the URI of the endpoint. basic_auth is called on the request to add the username and password for basic authentication. The set_form_data method is used to add the data to the post request. The request is then sent using http.request(request) and the response code and body are returned.

Example usage:

main.rb
response_code, response_body = post_with_auth('https://example.com/api/endpoint', { 'param1' => 'value1', 'param2' => 'value2' }, 'username', 'password')
puts "Response code: #{response_code}"
puts "Response body: #{response_body}"
232 chars
4 lines

gistlibby LogSnag