带有HTTParty的Ruby灵活客户端类

de90aj5v  于 2022-11-04  发布在  Ruby
关注(0)|答案(1)|浏览(119)

我通常使用法拉第gem连接到外部API,但我想为我的纯Ruby应用程序尝试HTTParty。我的想法是构建灵活的客户端类,类似于made with Faraday中的这个类:

class Client
    API_ENDPOINT = 'https://id.amiqus.co/api/'
    PERSONAL_ACCESS_TOKEN = ENV['personal_access_token']

    def initialize
      @access_token = PERSONAL_ACCESS_TOKEN
    end

    def get(path, options = {})
      client.public_send(:get, path.to_s, options)
    end

    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 #{access_token}" if access_token.present?
        end
    end

如何使用HTTParty构建记忆client方法?

sqxo8psd

sqxo8psd1#

private

def request(method, endpoint, params={} )
  HTTParty.public_send(
    method,
    endpoint,
    headers: {'Content-type': 'application/json', 'Authorization': TOKEN},
    body: params.to_json
  )
end

相关问题