各パラメータを暗黙的に述べることなく、Ruby、API要求を形成する

StackOverflow https://stackoverflow.com/questions/6025833

  •  14-11-2019
  •  | 
  •  

質問

私はWebサービスを要求しようとしています( fwix )、そして私のレールでアプリは、次のイニシャライザを作成しました。

  1. 何らかの理由でパラメータの値は一般的なものとして+を持つ必要がある必要がありますが、これは私がRubyで達成できる標準的なものですか?さらに、これはURLを形成するための標準的な方法ですか?私はスペースが%20であると思いました。

  2. 私のコードでは、query_items << "api_key=#{options[:api_key]}" if options[:api_key] のようなものをそれぞれのようなものにしなければならない代わりに、送信されたオプションを使用してください。

    私のコードは、最後のメソッドの各パラメータのquery_itemsから始まる行があるトラブル領域です。

    require 'httparty'
    module Fwix
      class API
        include HTTParty
    
        class JSONParser < HTTParty::Parser
          def json
            JSON.parse(body)
          end
        end
    
        parser JSONParser
        base_uri "http://geoapi.fwix.com"
    
        def self.query(options = {})
          begin
            query_url = query_url(options)
            puts "querying: #{base_uri}#{query_url}"
            response = get( query_url )
          rescue
            raise "Connection to Fwix API failed" if response.nil?
          end
        end
    
        def self.query_url(input_options = {})
          @defaults ||= {
            :api_key => "my_api_key",
          }
    
          options = @defaults.merge(input_options)
          query_url = "/content.json?"
          query_items = []
          query_items << "api_key=#{options[:api_key]}" if options[:api_key]
          query_items << "province=#{options[:province]}" if options[:province]
          query_items << "city=#{options[:city]}" if options[:city]
          query_items << "address=#{options[:address]}" if options[:address]
    
          query_url += query_items.join('&')
          query_url
        end
      end
    end
    
    .

役に立ちましたか?

解決

def self.query_url(input_options = {})
  options = {
    :api_key => "my_api_key",
  }.merge(input_options)

  query_url = "/content.json?"
  query_items = []

  options.each { |k, v| query_items << "#{k}=#{v.gsub(/\s/, '+')}" }

  query_url += query_items.join('&')
end

他のヒント

For 1) You API provider is expecting '+' because the API is expecting in a CGI formatted string instead of URL formatted string.

require 'cgi'
my_query = "hel lo"
CGI.escape(my_query)

this should give you

"hel+lo" 

as you expect

for Question 2) I would do something like

query_items = options.keys.collect { |key| "#{key.to_s}=#{options[key]}" }

I'm a developer at Fwix and wanted to help you with your url escaping issue. However, escaping with %20 works for me:

wget 'http://geoapi.fwix.com/content.xml?api_key=mark&province=ca&city=san%20francisco&query=gavin%20newsom'

I was hoping you could provide me with the specific request you're making that you're unable to escape with %20.

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top