make a http request with a custom body as json and return a json response in ruby

You can make an HTTP request with a custom JSON body and return a JSON response in Ruby using the following code:

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

url = URI("https://example.com/api/endpoint")

request = Net::HTTP::Post.new(url)
request["Content-Type"] = "application/json"
request.body = { key1: 'value1', key2: 'value2' }.to_json

response = Net::HTTP.start(url.hostname, url.port, use_ssl: url.scheme == 'https') do |http|
  http.request(request)
end

if response.code == '200'
  results = JSON.parse(response.body)
  # Do something with the parsed response data
else
  # Handle errors
end
495 chars
21 lines

In this code, we are using the Net::HTTP library to create a new POST request with a custom body containing JSON data. We set the content-type header to application/json to indicate that we are sending a JSON payload.

Then we send the request using the Net::HTTP.start method and capture the response. If the response code is 200, we can parse the response body as JSON using JSON.parse and then work with the returned data as desired. If the response code is anything other than 200, we will need to handle the error appropriately.

gistlibby LogSnag