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.rb355 chars15 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.
gistlibby LogSnag