Question

I am trying to access a service which uses the url format. www.example.com/api/API_KEY/action

The below code is a small example of what I'm trying to achieve.

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

The server request:

MyAPI.new('apikey').statistics

comes out as

GET /api//statistics

I knew it was optimistic but I put the api_key variable in the base_uri. How do I make it so that the url uses the dynamic api_key?

Was it helpful?

Solution

You are missing a reader method for @api_key.

Add the following to your class to allow the setting of @api_key after initialization.

attr_accessor :api_key

Or add to allow it to be read, but not set later.

attr_reader :api_key
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top