Skip to content

Instantly share code, notes, and snippets.

@jagdeepsingh
Last active October 23, 2018 07:47
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jagdeepsingh/52f949df2dab08fdb058e823a8bb9809 to your computer and use it in GitHub Desktop.
Save jagdeepsingh/52f949df2dab08fdb058e823a8bb9809 to your computer and use it in GitHub Desktop.
Net::HTTP - An HTTP Client API for Ruby

Net::HTTP

1 Request

1.1 GET

Prepare params

If there are any params with an Array value, you need to pass them as { 'foo[]' => [1, 2, 3] }. Below logic does that conversion for you.

params = { foo: 1, bar: [2, 3] }
 
formatted = params.stringify_keys
 => {"foo"=>1, "bar"=>[2, 3]}
 
out = formatted.each_with_object({}) do |(key, value), out|
        if value.is_a?(Array)
          out["#{key}[]"] = value
        else
          out[key] = value
        end
      end
 => {"foo"=>1, "bar[]"=>[2, 3]}

Make request

require 'net/http'

uri = URI('https://www.sample-api.com/v1/users')
 => #<URI::HTTPS:0x007f82cb57ab98 URL:https://www.sample-api.com/v1/users>

params
 => {"foo"=>1, "bar[]"=>[2, 3]}

uri.query = URI.encode_www_form(params)
 => "foo=1&bar%5B%5D=2&bar%5B%5D=3"
 
response = Net::HTTP.get_response(uri)
 => #<Net::HTTPOK 200 OK readbody=true> 

1.2 POST

uri = URI('https://www.sample-api.com/v1/users')

http = Net::HTTP.new(uri.host, uri.port)
http.use_ssl = true

params = { foo: 1, bar: 'baz' }

request = Net::HTTP::Post.new(uri.request_uri)
request.body = params.to_json

response = http.request(request)

Setting headers:

request = Net::HTTP::Post.new(uri.request_uri, 'Content-Type' => 'application/json')

2 Response

2.1 Success

response.is_a?(Net::HTTPSuccess)
 => true

2.2 Extract data

response.body
 => "{\"data\":[]}"

2.3 As an object

document = JSON.parse(response.body, object_class: OpenStruct).data
 => #<OpenStruct id=1, name="Jagdeep Singh", is_active=true>
 
document.id
 => 1
 
document.name
 => "Jagdeep Singh"

3 Read more

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment