Add API Key to Every Request in Activeresource

Add api key to every request in ActiveResource

Use model#prefix_options which is a hash for passing params into query string (or even as substitions for parts of the Model.prefix, e.g. "/myresource/:param/" will be replaced by the value of prefix_options[:param] . Any hash keys not found in the prefix will be added to the query string, which is what we want in your case).

class Model < ActiveResource::Base
class << self
attr_accessor :api_key
end

def save
prefix_options[:api_key] = self.class.api_key
super
end
end

Model.site = 'http://yoursite/'
Model.api_key = 'xyz123'
m = Model.new(:field_1 => 'value 1')
# hits http://yoursite:80/models.xml?api_key=xyz123
m.save

Using ActiveResource::Base to send get requests to API

Since the API does not return the JSON that ActiveResources expects, you would have to implement a new parser.

class Postcode < ActiveResource::Base
self.site = "http://api.postcodeapi.nu/"
headers['Api-Key'] = "495237e793d10330c1db0d57db9d3c7e6e485af7"
self.element_name = ''
self.include_format_in_path = false

class PostcodeParser < ActiveResource::Collection
def initialize(elements = {})
@elements = [elements['resource']]
end
end

self._collection_parser = PostcodeParser
end

This should work for the following query Postcode.find('5041EB'), but not for Postcode.where(id: '5041EB'). The main reason is that the API has a different parameter key for id. The API docs refers to type, but it didn't work.

I am not sure if ActiveResources is the right approach for this case.

Use api key in HTTParty

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

Authenticating requests using ActiveResource and session tokens

Active Resource has undergone quite an update over the past year or so and is now working well in the modern web.

Active Resource supports the token based authentication provided by Rails through the ActionController::HttpAuthentication::Token class using custom headers.

class Person < ActiveResource::Base
self.headers['Authorization'] = 'Token token="abcd"'
end

You can also set any specific HTTP header using the same way. As mentioned above, headers are thread-safe, so you can set headers dynamically, even in a multi-threaded environment:

ActiveResource::Base.headers['Authorization'] = current_session_api_token

I've used an OAuth JWT strategy with Active Resource quite successfully using the second method in an API controller:

ActiveResource::Base.headers['Authorization'] = "Bearer #{jwt.token}"


Related Topics



Leave a reply



Submit