akaghzi
akaghzi

Reputation: 27

Net::HTTP uri equivalent of curl command

Gurus of Ruby, i have curl command: curl -XGET "http://localhost:9200/ofacname/_search" -H 'Content-Type: application/json' -d'{ "query": { "multi_match" : { "query": "mugabe robert president of zimbabwe", "type": "most_fields", "fields": [ "name", "title", "country" ]}}}'

how to I make a call in Net::HTTP in ruby which would be equivalent to above mentioned command

Upvotes: 1

Views: 166

Answers (1)

Wayne Conrad
Wayne Conrad

Reputation: 107979

This code is not by me, but by a web site that translates curl to Net::HTTP: curl-to-ruby.

require 'net/http'
require 'uri'
require 'json'

uri = URI.parse("http://localhost:9200/ofacname/_search")
request = Net::HTTP::Get.new(uri)
request.content_type = "application/json"
request.body = JSON.dump({
  "query" => {
    "multi_match" => {
      "query" => "mugabe robert president of zimbabwe",
      "type" => "most_fields",
      "fields" => [
        "name",
        "title",
        "country"
      ]
    }
  }
})

req_options = {
  use_ssl: uri.scheme == "https",
}

response = Net::HTTP.start(uri.hostname, uri.port, req_options) do |http|
  http.request(request)
end

# response.code
# response.body

This translator only understands certain curl options, so whenever you use it examine the list of supported options. Any options in your curl command that the translator does not understand, it will be up to you to figure out the translation for. However, all of the options in your query are supported by the translator.

Upvotes: 3

Related Questions