make a http request with a custom body as json in ruby

To make an HTTP request with a custom body as JSON in Ruby, you can use the built-in Net::HTTP library along with the json library to encode your data as JSON. Here's an example code snippet:

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

uri = URI('https://example.com/api/endpoint')
data = { key1: 'value1', key2: 'value2' } # Your custom data to send as JSON

# Build the HTTP request
req = Net::HTTP::Post.new(uri, 'Content-Type' => 'application/json')
req.body = data.to_json

# Send the request
res = Net::HTTP.start(uri.hostname, uri.port, use_ssl: uri.scheme == 'https') do |http|
  http.request(req)
end

# Handle the response
puts res.body
446 chars
18 lines

In this example, we create a Net::HTTP::Post object with the URI of our endpoint and set the Content-Type header to application/json to indicate that we are sending JSON data. We then encode our custom data as JSON using to_json and set it as the body of the request.

We send the request using Net::HTTP.start with the hostname, port, and SSL settings of our URI, and handle the response as desired (in this case, simply printing the response body).

related categories

gistlibby LogSnag