Posting JSON with Net::HTTP
Recently I’ve been working on a gem that serves as a proxy between the app that includes it and an external service. It adds a route and forwards GET and POST requests to the service and then returns the responses. The gem includes a simple Rails engine and we are using Net::HTTP from Ruby’s standard library to forward the requests. I’ll got into more depth about building the gem later, but for now just wanted to offer a quick tip on posting with Net::HTTP.
The GET request with Net::HTTP is very simple and only requires a couple of lines. The URI module is included as part of Net::HTTP and is often used to build the Uniform Resource Identifier objects for requests.
uri = URI('http://www.your-url.com/stuff')
response = Net::HTTP.get_response(uri)
Sending a POST can also be pretty straightforward:
uri = URI('http://www.your-url.com/stuff')
response = Net::HTTP.post_form(uri, 'param1' => 'info', 'param2' => 'more info')
However, the external service that we are posting to is expecting JSON so we needed to configure our request to send appropriate headers. Unfortunately Net::HTTP’s post_form
method doesn’t support headers. Figuring out the process to do that was a little cumbersome so I figured I’d document it here.
The key to sending JSON is to create a new Net::HTTP object and then send the headers hash as a third argument to its post
method. Unfortunately, that’s not included in the documentation, but once we figured that out it’s pretty simple. (Props to this guy for a little extra googling-fu.) Here’s an example of what it looks like:
params = {'param1' => 'info', 'param2' => 'more info'}
json_headers = {"Content-Type" => "application/json",
"Accept" => "application/json"}
uri = URI.parse('http://www.your-url.com/stuff')
http = Net::HTTP.new(uri.host, uri.port)
response = http.post(uri.path, params.to_json, json_headers)
And voila, you have a response object at your disposal.