【问题标题】:RestClient/HTTParty authentication parameters not being used未使用 RestClient/HTTParty 身份验证参数
【发布时间】:2018-12-19 01:49:06
【问题描述】:

对于我尝试过的 API 调用..

在 RestClient 中

有效但错误:

response = RestClient::Request.execute(
method: :get,
url: 'https://api.data.charitynavigator.org/v2/Organizations?app_id=2b1ffdad&app_key=XXXX',
)

不起作用(403:禁止):

response = ::RestClient::Request.execute(method: :get, url: 'https://api.data.charitynavigator.org/v2/Organizations?app_id=2b1ffdad', 
headers: {app_key: 'XXXX'})

在 HTTParty 中

也不起作用(缺少身份验证参数):

require 'rubygems'
require 'httparty'


class Charity
  include HTTParty

  base_uri 'https://api.data.charitynavigator.org/v2/'

  def posts

    headers = {
      "app_id"  => "2b1ffdad",
      "app_key"  => "XXXX"
    }

    self.class.get("/Organizations/",
    :headers => headers
    )
  end
end


charity = Charity.new
puts charity.posts

供参考:https://charity.3scale.net/docs/data-api/reference

是语法吗?我也研究了法拉第,但在那里遇到了类似的问题。许多带有 Rails 的 3rd 方 API 示例似乎都在使用早已过时的 API,因此很难将所有内容拼凑在一起。

任何见解将不胜感激。真的很想明白这一点。

【问题讨论】:

    标签: ruby-on-rails rest-client httparty


    【解决方案1】:

    我无法理解您的说法有效但错误,但 Charity Navigator Data API 通过参数而不是标头请求发送 app_idapp_key 密钥 .

    您的第一个代码看起来是正确的。

    第二个代码,app_key 键是由标头而不是参数发送的。所以 API 响应 403。

    第三个代码,用 httpart gem 编码,不使用参数,而是使用标题。所以 Charity Navigator Data API 响应 Authentication parameters missing 错误。这很正常。

    require 'httparty'
    
    class StackExchange
      include HTTParty
      base_uri 'https://api.data.charitynavigator.org/v2/'
    
      def posts
        options = { 
          query: {
            app_id: '2b1ffdad',
            app_key: 'XXXX'
          }
        }
    
        self.class.get("/Organizations/", options)
      end
    end
    
    charity = Charity.new
    puts charity.posts
    

    但是你可以在httparty中使用query option的参数。阅读httparty docsthis SO。你也可以在 rest-client gem 中use parameters options。我建议强烈使用它。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-06-25
      • 1970-01-01
      • 2015-09-23
      • 1970-01-01
      • 1970-01-01
      • 2013-10-03
      • 2021-07-05
      • 2011-06-27
      相关资源
      最近更新 更多