外部API集成的Ruby构建查询参数



我想集成Nomics API,从其文档中我了解到所有参数都不是在主体中传递,而是作为查询参数传递,如下所示:

uri = URI("https://api.nomics.com/v1/currencies/ticker?key=your-key-here&ids=BTC,ETH,XRP&interval=1d,30d&convert=EUR&per-page=100&page=1")
puts Net::HTTP.get(uri)

现在我想构建一些灵活的API客户端。我想知道是否有一个聪明的方法来传递这个查询参数在主体json?例如,我不需要像这里的key=your-key-here&一样在路径内传递api_key作为查询参数-如果我像下面这样将其作为承载令牌传递,它也会工作:

class Api
API_KEY = 'some_key'
def get_crypto(id: [])
client.get("currencies/ticker?&ids:#{id}")
end
private
private
def client
@client =
Faraday.new(API_ENDPOINT) do |client|
client.request :url_encoded
client.response :json, content_type: /bjson$/
client.adapter Faraday.default_adapter
client.headers['Accept'] = 'application/json'
client.headers['Content-Type'] = 'application/json'
client.headers['Authorization'] = "Bearer #{API_KEY}"
end
end
end

我是否注定要使用一些中间方法来构建奇怪、复杂的query_params?

我想知道是否有一个聪明的方法来传递这个查询参数在身体作为json?例如,我不需要在路径中传递api_key作为查询参数,如here key=your-key-here&-如果我像下面这样将其作为承载令牌传递,它也会起作用:

这与是否聪明没有任何关系,而是API如何对待身体。如果可以将其作为json body传递,为什么不直接尝试呢?

否则,我建议只使用activessupport实现Hash#to_params

class Api
def get_crypto(params = {})
client.get("currencies/ticker?#{params.to_params}")
end
end
Api.new.get_crypto(ids: [1,2,3]
# currencies/ticker?ids=1,2,3

https://github.com/rails/rails/blob/f95c0b7e96eb36bc3efc0c5beffbb9e84ea664e4/activesupport/lib/active_support/core_ext/object/to_query.rb L61-L89