【问题标题】:Use api key in HTTParty在 HTTParty 中使用 api 密钥
【发布时间】:2011-09-10 15:44:38
【问题描述】:

我正在尝试访问使用 url 格式的服务。 www.example.com/api/API_KEY/action

下面的代码是我想要实现的一个小例子。

require 'httparty'

class MyAPI
  include HTTParty
  debug_output $stdout

  base_uri "example.com/api/#{@api_key}"

  def initialize(api_key)
     @api_key = api_key
  end

  def statistics
    return self.class.get("/statistics")
  end
end

服务器请求:

MyAPI.new('apikey').statistics

出来

GET /api//statistics

我知道这是乐观的,但我将 api_key 变量放在 base_uri 中。如何使 url 使用动态 api_key?

【问题讨论】:

    标签: ruby ruby-on-rails-3 api rest httparty


    【解决方案1】:

    您缺少@api_key 的读取器方法。

    将以下内容添加到您的类中以允许在初始化后设置@api_key。

    attr_accessor :api_key
    

    或添加以允许读取,但以后不设置。

    attr_reader :api_key
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-09-28
      • 1970-01-01
      • 2016-12-27
      • 2018-03-31
      • 2019-02-18
      • 2016-03-23
      相关资源
      最近更新 更多