Baike.dev
All toolsOnline toolsAI codingTrendingOpen sourceNewsSubmit
Log in
< Back to tools
A

active-rest-client

> 编程语言
Open source

ActiveRestClient API Client

384 stars0 likes1 views
WebsiteGitHub

About

ActiveRestClient API Client

ActiveRestClient

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.

Deprecation Note for non-Which? Users

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)

Installation

Add this line to your application's Gemfile:

ruby
gem 'active_rest_client'

And then execute:

$ bundle

Or install it yourself as:

$ gem install active_rest_client

Usage

First you need to create your new model class:

ruby
# 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")  # invalid

You 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:

ruby
@person = Person.new
@person.first_name = "John"
@person.last_name  = "Smith"
@person.create
puts @person.id

The 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:

ruby
@tv = Tv.find(model:"UE55U8000") # { "properties" : {"3d" : false} }
puts @tv.properties["3d"]
@tv.properties["3d"] = true

If 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:

ruby
@person = Person.find(email:"[email protected]")
puts @person.to_json

Advanced Features

Faraday Configuration

ActiveRestClient 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.

ruby
ActiveRestClient::Base.adapter = :net_http
# or ...
ActiveRestClient::Base.adapter = :patron

In 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.

ruby
ActiveRestClient::Base.faraday_config do |faraday|
  faraday.adapter(:net_http)
  faraday.options.timeout       = 10
  faraday.headers['User-Agent'] = "ActiveRestClient/#{ActiveRestClient::VERSION}"
end

Associations

There 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.

Association Type 1 - Loading Other Classes

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.

ruby
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_string

Association Type 2 - Lazy Loading From Other URLs

When 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:

ruby
"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:

ruby
class Person  [:orders, :refunds]
end

And use it like this:

ruby
# 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.name

Association Type 3 - HAL Auto-loaded Resources

You 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).

ruby
@person = Person.find(1)
@person.students[0]._hal_attributes("title")

Association Type 4 - Nested Resources

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:

ruby
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
# => 123456

You 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.

ruby
puts @image.nice_size
# => 121KB

Caching

Expires and ETag based caching is enabled by default, but with a simple line in the application.rb/production.rb you can disable it:

ruby
ActiveRestClient::Base.perform_caching = false

or you can disable it per classes with:

ruby
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 #=> 7

Faking Calls

There 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.

ruby
class Person (request) { {result: request.get_params[:id]} }
end

Raw Requests

Sometimes 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:

ruby
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)

HTTP/Parse Error Handling

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):

ruby
begin
  Person.all
rescue ActiveRestClient::HTTPClientException, ActiveRestClient::HTTPServerException => e
  Rails.logger.error("API returned #{e.status} : #{e.result.message}")
end

If 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.

Validation

You can create validations on your objects just like Rails' built in ActiveModel validations. For example:

ruby
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:

ruby
class Feed  #{entry.link.href}"
end

If your XML object comes back with a root node and you'd like to ignore it, you can define the mapping as:

ruby
class Feed < ActiveRestClient::Base
  get :atom, "/atom", ignore_xml_root: "feed"
end

For 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.

Contributing

  1. Fork it
  2. Create your feature branch (git checkout -b my-new-feature)
  3. Commit your changes (git commit -am 'Add some feature')
  4. Push to the branch (git push origin my-new-feature)
  5. Create new Pull Request

Issues· 0 open

View all issuesOpen on GitHub

No open issues yet, or sync has not completed.

> Tags

Ruby

No comments yet. Be the first to share.

> Details

PublishedAug 1, 2026
UpdatedSep 17, 2026
Category编程语言
PricingOpen source

> Related tools

T
TypeScript
JavaScript 的超集,为前端与全栈提供静态类型
P
Python
通用编程语言,广泛用于 Web、数据与 AI
G
Go
Google 推出的简洁高效系统语言