ActiveRestClient API Client
This gem is for accessing REST services in an ActiveRecord style. ActiveResource already exists for this, but it doesn't work where the resource naming doesn't follow Rails conventions, it doesn't have in-built caching and it's not as flexible in general.
This gem isn't being updated here. If you want the functionality of ActiveRestClient you should probably look at this fork, which is being actively maintained by the original author:
(https://github.com/flexirest/flexirest/)
Some background (https://github.com/flexirest/flexirest/blob/master/Migrating-from-ActiveRestClient.md)
Add this line to your application's Gemfile:
gem 'active_rest_client'And then execute:
$ bundleOr install it yourself as:
$ gem install active_rest_clientFirst you need to create your new model class:
# config/environments/production.rb
MyApp::Application.configure do
# ...
config.api_server_url = "https://www.example.com/api/v1"
end
# app/models/person.rb
class Person 1234) # valid
@person = Person.find(:id => 1234, :name => "Billy") # valid
@person = Person.find(1234, :name => "Billy") # invalidYou can also call any mapped method as an instance variable which will pass the current attribute set in as parameters (either GET or POST depending on the mapped method type). If the method returns a single instance it will assign the attributes of the calling object and return itself. If the method returns a list of instances, it will only return the list. So, we could rewrite the create call above as:
@person = Person.new
@person.first_name = "John"
@person.last_name = "Smith"
@person.create
puts @person.idThe response of the #create call set the attributes at that point (any manually set attributes before that point are removed).
If you have attributes beginning with a number, Ruby doesn't like this. So, you can use hash style notation to read/write the attributes:
@tv = Tv.find(model:"UE55U8000") # { "properties" : {"3d" : false} }
puts @tv.properties["3d"]
@tv.properties["3d"] = trueIf you want to debug the response, using inspect on the response object may well be useful. However, if you want a simpler output, then you can call #to_json on the response object:
@person = Person.find(email:"[email protected]")
puts @person.to_jsonActiveRestClient uses Faraday to allow switching HTTP backends, the default is to just use Faraday's default. To change the used backend just set it in the class by setting adapter to a Faraday supported adapter symbol.
ActiveRestClient::Base.adapter = :net_http
# or ...
ActiveRestClient::Base.adapter = :patronIn versions before 1.2.0 the adapter was hardcoded to :patron, so if you want to ensure it still uses Patron, you should set this setting.
If you want more control you can pass a complete configuration block ("complete" means that the block does not override the default configuration, but rather replaces it). For available config variables look into the Faraday documentation.
ActiveRestClient::Base.faraday_config do |faraday|
faraday.adapter(:net_http)
faraday.options.timeout = 10
faraday.headers['User-Agent'] = "ActiveRestClient/#{ActiveRestClient::VERSION}"
endThere are two types of association. One assumes when you call a method you actually want it to call the method on a separate class (as that class has other methods that are useful). The other is lazy loading related classes from a separate URL.
If the call would return a single instance or a list of instances that should be considered another object, you can also specify this when mapping the method using the :has_one or :has_many options respectively. It doesn't call anything on that object except for instantiate it, but it does let you have objects of a different class to the one you initially called.
class Expense {:expenses => Expense}, :has_one => {:address => Address}
end
@person = Person.find(1)
puts @person.expenses.reduce {|e| e.inc_vat}
puts @person.address.full_stringWhen mapping the method, passing a list of attributes will cause any requests for those attributes to mapped to the URLs given in their responses. The response for the attribute may be one of the following:
"attribute" : "URL"
"attribute" : ["URL", "URL"]
"attribute" : { "url" : "URL"}
"attribute" : { "href" : "URL"}
"attribute" : { "something" : "URL"}The difference between the last 3 examples is that a key of url or href signifies it's a single object that is lazy loaded from the value specified. Any other keys assume that it's a nested set of URLs (like in the array situation, but accessible via the keys - e.g. object.attribute.something in the above example).
It is required that the URL is a complete URL including a protocol starting with "http". To configure this use code like:
class Person [:orders, :refunds]
endAnd use it like this:
# Makes a call to /people/1
@person = Person.find(1)
# Makes a call to the first URL found in the "books":[...] array in the article response
# only makes the HTTP request when first used though
@person.books.first.nameYou don't need to define lazy attributes if they are defined using HAL (with an optional embedded representation). If your resource has an _links item (and optionally an _embedded item) then it will automatically treat the linked resources (with the _embedded cache) as if they were defined using :lazy as per type 2 above.
If you need to, you can access properties of the HAL association. By default just using the HAL association gets the embedded resource (or requests the remote resource if not available in the _embedded list).
@person = Person.find(1)
@person.students[0]._hal_attributes("title")It's common to have resources that are logically children of other resources. For example, suppose that your API includes these endpoints:
| HTTP Verb | Path | |
|---|---|---|
| POST | /magazines/:magazine_id/ads | create a new ad belonging to a magazine |
| GET | /magazines/:magazine_id/ads | display a list of all ads for a magazine |
In these cases, your child class will contain the following:
class Ad Image} # ,lazy:[:images] isn't needed as we're using HAL
end
class Image http://cdn.example.com/images/foo.jpg
puts @image.filesize
# => 123456You can also treat @image looks like an Image class (and you should 100% treat it as one) it's technically a lazy loading proxy. So, if you cache the views for your application should only make HTTP API requests when actually necessary.
puts @image.nice_size
# => 121KBExpires and ETag based caching is enabled by default, but with a simple line in the application.rb/production.rb you can disable it:
ActiveRestClient::Base.perform_caching = falseor you can disable it per classes with:
class Person nil
puts @employers #=> nil
end # The requests are all fired in parallel during this end statement
puts @person.name #=> "John"
puts @employers.size #=> 7There are times when an API hasn't been developed yet, so you want to fake the API call response. To do this, you can simply pass a fake option when mapping the call containing the response.
class Person (request) { {result: request.get_params[:id]} }
endSometimes you have have a URL that you just want to force through, but have the response handled in the same way as normal objects or you want to have the filters run (say for authentication). The easiest way to do that is to call _request on the class:
class Person Object" mapping layer ready for use in your application
2. The second option is to save the response from `passthrough` and use `translate` on it to alter the structure.
3. The third option is to use `render` if you want to completely fake an API and return the JSON yourself
To completely fake the API, you can do the following. Note, this is also achievable using the `fake` setting when mapping a method, however by doing it in a Proxy block means you can dynamically generate the JSON rather than just a hard coded string.
```ruby
put "/fake" do
render "{\"id\":1234}"
end
…
ruby
class ArticleTranslator
def self.all(object)
ret = {}
ret["first_name"] = object["name"]
ret
end
end
class Article {:active => true}
end
@people = Person.all(active:false)Sometimes the backend server may respond with a non-200/304 header, in which case the code will raise an ActiveRestClient::HTTPClientException for 4xx errors or an ActiveRestClient::HTTPServerException for 5xx errors. These both have a status accessor and a result accessor (for getting access to the parsed body):
begin
Person.all
rescue ActiveRestClient::HTTPClientException, ActiveRestClient::HTTPServerException => e
Rails.logger.error("API returned #{e.status} : #{e.result.message}")
endIf the response is unparsable (e.g. not in the desired content type), then it will raise an ActiveRestClient::ResponseParseException which has a status accessor for the HTTP status code and a body accessor for the unparsed response body.
You can create validations on your objects just like Rails' built in ActiveModel validations. For example:
class Person
Example Feed
2003-12-13T18:30:02Z
John Doe
urn:uuid:60a76c80-d399-11d9-b93C-0003939e0af6
Atom-Powered Robots Run Amok
urn:uuid:1225c695-cfb8-4ebb-aaaa-80da344efa6a
2003-12-13T18:30:02Z
Some text.
Something else cool happened
urn:uuid:1225c695-cfb8-4ebb-aaaa-80da344efa6b
2015-08-11T18:30:02Z
Some other text.
You can use:
class Feed #{entry.link.href}"
endIf your XML object comes back with a root node and you'd like to ignore it, you can define the mapping as:
class Feed < ActiveRestClient::Base
get :atom, "/atom", ignore_xml_root: "feed"
endFor testing purposes, if you are using a fake content response when defining your endpoint, you should also provide fake_content_type: "application/xml" so that the parser knows to use XML parsing.
git checkout -b my-new-feature)git commit -am 'Add some feature')git push origin my-new-feature)No open issues yet, or sync has not completed.