make a http request with a custom body in ruby

To make an HTTP request with a custom body in Ruby, you can use the Net::HTTP library, which is included in the Ruby standard library. Here's an example for making a POST request with a JSON body:

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

uri = URI.parse("https://example.com/api/endpoint")
headers = {'Content-Type' => 'application/json'}

body = {"name" => "John", "age" => 30}.to_json

http = Net::HTTP.new(uri.host, uri.port)
http.use_ssl = true # if making an HTTPS request
response = http.post(uri.path, body, headers)

puts response.body
355 chars
15 lines

In this example, we first require the necessary libraries: uri for parsing the request URL, net/http for making HTTP requests, and json for encoding our request body as JSON.

We then create a URI object for the endpoint that we want to hit, and define a hash of headers for our request. In this case, we set the Content-Type header to application/json.

We create our request body as a hash, and then use to_json to encode it as a JSON string. We then create a Net::HTTP object and use the post method to make our POST request with the URL path, request body, and headers as arguments.

Finally, we print out the response body.

related categories

gistlibby LogSnag