首页 > 解决方案 > 使用带有 API 密钥的 HTTParty 请求

问题描述

我正在尝试对此API发出 GET 请求,该请求在 POSTMAN 中运行良好。在我的应用程序中,我使用 HTTParty 发出相同的请求,但未能正确构造请求,导致{"statusCode"=>404, "error"=>"Not Found", "message"=>"Not Found"}返回。我尝试了很多变体,但没有找到正确的结构或参数命名。这是供参考,其中 ENV["X-CMC_PRO_API_KEY"] 是保存我的 api 密钥的环境变量。

url = 'https://pro-api.coinmarketcap.com/v1/cryptocurrency/quotes/latest/'

request = HTTParty.get(url,
  {
    headers: {
    "key": ENV["X-CMC_PRO_API_KEY"],
    "Accept": "application/json"
    },
    data: {
      id: 1
    },
    params: {
      slug: self.slug
    }
  }
)
response = JSON.parse(request.body)

这就是 API 文档建议 cURL 的方式

curl -H "X-CMC_PRO_API_KEY: apikey" -H "Accept: application/json" -d "id=1" -G https://pro-api.coinmarketcap.com/v1/cryptocurrency/quotes/latest

这些是来自 POSTMAN 的屏幕,其中请求返回正确的响应。 图片 1 图片2

对于帮助我完成此请求的任何意见,我表示感谢。我是新手,HTTParty 文档没有帮助,我也没有找到任何其他类似的例子。

标签: rubygemshttprequestapi-keyruby-on-rails-6httparty

解决方案


这对我有用

headers = {
  'X-CMC_PRO_API_KEY' => "xxxxxxxxxxxxxxxxxxxxx"
}

url = 'https://pro-api.coinmarketcap.com/v1/cryptocurrency/quotes/latest'
params = '?&slug=bitcoin'
response = HTTParty.get(url+params,
  :headers => headers
)

推荐阅读