Skip to content

About

HyperClient is a Ruby Hypermedia API client.

Resources

Contributing

Stars

153 stars

Watchers

12 watching

Forks

Repository files navigation

Hyperclient

Gem Version Build Status Coverage Status

Hyperclient is a Hypermedia API client written in Ruby. It fully supports JSON HAL.

Table of Contents

Usage

The examples in this README use the local Oxford HAL demo, based on historical Oxford place facts. Start it with bundle exec ruby examples/oxford/server.rb, then run bundle exec ruby -Ilib examples/oxford/client.rb in another terminal. No external service is needed. Use version 1.x with Faraday 1.x, and version 2.x with Faraday 2.x. If you're upgrading from a previous version, please make sure to read UPGRADING.

Hyperclient is tested with JSON 2.x on Ruby 2.7, both JSON 2.x and 3.x on Ruby 3.2, and JSON 3.x on newer Rubies. JSON 3.x requires a Faraday release with keyword parser options support (2.14.4+).

API Client

Create an API client.

require 'hyperclient'

api = Hyperclient.new('http://127.0.0.1:9292/')

By default, Hyperclient adds application/hal+json as Content-Type and Accept headers. It will also send requests as JSON and parse JSON responses. Specify additional headers or authentication if necessary.

api = Hyperclient.new('http://127.0.0.1:9292/') do |client|
  client.headers['Access-Token'] = 'token'
end

Hyperclient constructs a connection using typical Faraday middleware for handling JSON requests and responses. You can specify additional Faraday middleware if necessary.

api = Hyperclient.new('http://127.0.0.1:9292/') do |client|
  client.connection do |conn|
    conn.use Faraday::Request::Instrumentation
  end
end

You can pass options to the Faraday connection block in the connection block:

api = Hyperclient.new('http://127.0.0.1:9292/') do |client|
  client.connection(ssl: { verify: false }) do |conn|
    conn.use Faraday::Request::Instrumentation
  end
end

Or when using the default connection configuration you can use faraday_options:

api = Hyperclient.new('http://127.0.0.1:9292/') do |client|
  client.faraday_options = { ssl: { verify: false } }
end

You can build a new Faraday connection block without inheriting default middleware by specifying default: false in the connection block.

api = Hyperclient.new('http://127.0.0.1:9292/') do |client|
  client.connection(default: false) do |conn|
    conn.request :json
    conn.response :json, content_type: /\bjson$/
    conn.adapter :net_http
  end
end

By default, Hyperclient requires responses to have a Content-Type of application/hal+json, and raises Hyperclient::InvalidRepresentationError otherwise. If your API sometimes returns responses that aren't hal+json (e.g. an empty body with a 201 Created, or a plain application/json response), broaden the response middleware's content_type matcher as shown above (content_type: /\bjson$/) instead of the default, which only matches hal+json.

You can modify headers or specify authentication after a connection has been created. Hyperclient supports Basic, Token or Digest auth as well as many other Faraday extensions.

require 'faraday/digestauth'

api = Hyperclient.new('http://127.0.0.1:9292/') do |client|
  client.connection(default: false) do |conn|
    conn.request :digest, 'username', 'password'
    conn.request :json
    conn.response :json, content_type: /\bjson$/
    conn.adapter :net_http
  end
end

You can access the Faraday connection directly after it has been created and add middleware to it. As an example, you could use the faraday-http-cache-middleware.

api = Hyperclient.new('http://127.0.0.1:9292/')
api.connection.use :http_cache

Resources and Attributes

Hyperclient will fetch and discover the resources from your API and automatically paginate when possible.

api.places.each do |place|
  puts "#{place.name} has ID #{place.id}."
end

Other methods, including [] and fetch are also available

api.places.each do |place|
  puts "A place with ID #{place[:id]}."
  puts "Address: #{place.fetch(:address, '-- no address')}"
end

Links and Embedded Resources

The example above follows the places link to a collection of embedded places. Hyperclient resolves links and embedded resources automatically. You can also navigate explicitly:

api._links.places._embedded.places.each do |place|
  puts place.name
end

place = api.place(id: 'oxpoints:23232339')
puts place.primary_place.name # follows a relative link to Balliol College
puts place._embedded.files.first.url # reads embedded metadata, without fetching the image

Templated Links

Templated links require variables to be expanded. The local demo adds a place link that accepts an Oxford place ID.

place = api.place(id: 'oxpoints:23232339')
puts place.name # => Balliol College

Invoking api.place(id: 'oxpoints:23232339').name is equivalent to api._links.place._expand(id: 'oxpoints:23232339')._resource._attributes.name.

The client is responsible for supplying all the necessary parameters. Templated links don't do any strict parameter name checking and don't support required vs. optional parameters. Parameters not declared by the API will be dropped and will not have any effect when passed to _expand.

Query Parameters

HAL APIs declare the query parameters they accept in templated links, and _expand only fills in those. To send query parameters that a link doesn't declare, or to add them to a link that isn't templated, use _query. It returns a new link with the parameters appended to its URL, after any existing query string.

api._links.places._query(sort: 'name')._get # GET /places/?sort=name
api._links.place._expand(id: 'oxpoints:23232339')._query(fields: 'name')._get # GET /places/oxpoints%3A23232339?fields=name

Array values are sent as repeated parameters, and parameters with nil values are dropped.

Link Properties

HAL links can carry optional properties besides href and templated. Hyperclient exposes them as _type, _deprecation, _name, _profile, _title, and _hreflang, each returning nil when the property is absent. The local demo gives its places link a title and a profile.

puts api._links.places._title # => Oxford places
puts api._links.places._profile # => /docs/places

A profile is a URI that documents the semantics of the target resource, beyond what the media type describes. Hyperclient returns it as-is and doesn't follow it, since a profile isn't necessarily a HAL resource. Fetch it with the client's Faraday connection if you need it.

puts api.connection.get(api._links.places._profile).body['description'] # => Archived Oxford place facts in a local HAL collection.

A link with a deprecation property will be removed in the future, and _deprecation returns a URL with more information about the deprecation.

Curies

Curies provide compact names for relation documentation. The local demo adds an oxford CURIE and an oxford:places relation.

puts api._links['oxford:places']._embedded.places.first.name # => Balliol College
puts api._links._curies['oxford'].expand('places') # => /docs/places

Attributes

Resource attributes can also be accessed as a hash.

puts place.to_h['name'] # => Balliol College

place.to_h is equivalent to place._attributes.to_h.

HTTP

Hyperclient uses Faraday under the hood to perform HTTP calls. You can call any valid HTTP method on any resource.

For example, you can examine the API raw JSON by invoking _get and examining the _response.body hash.

api._get
api._response.body

Other methods, including _head or _options are also available.

place = api.place(id: 'oxpoints:23232339')
place._head

The Oxford demo is read-only and rejects writes with HTTP 405. On a writable API, invoke _post to create resources:

api.places._post(name: 'New place')

Invoke _put or _patch to update resources.

place._put(name: 'Updated place')
place._patch(name: 'Updated place')

Invoke _delete to destroy a resource.

place._delete

HTTP methods always return a new instance of Resource.

Allowed Methods

Hyperclient remembers the Allow header of the most recent response on the link that made the request, including a 405 Method Not Allowed response, whose Allow header lists the methods the server supports. Each response replaces what the link knows. Use _allow and _allow? to check before sending a request.

order = api.order(id: 1) # a server responding with "Allow: GET, HEAD, OPTIONS"
order._get
order._allow # => ["GET", "HEAD", "OPTIONS"], or nil without an Allow header
order._allow?(:delete) # => false

By default, Hyperclient still sends any method and leaves it to the server to refuse it. Set enforce_allowed_methods to have links refuse to send a method that their most recent Allow header doesn't list, raising Hyperclient::MethodNotAllowedError without contacting the server. A response without an Allow header lifts the restriction, and _options is always sent so you can rediscover the allowed methods.

api = Hyperclient.new('http://127.0.0.1:9292/') do |client|
  client.enforce_allowed_methods = true
end

order = api.order(id: 1) # a server responding with "Allow: GET, HEAD, OPTIONS"
order._get

begin
  order._delete
rescue Hyperclient::MethodNotAllowedError => e
  e.message # => "DELETE is not allowed on /orders/1, the server allows only GET, HEAD, OPTIONS."
  e.allowed # => ["GET", "HEAD", "OPTIONS"]
end

Methods are compared case-insensitively, an empty Allow header means no methods are allowed, and HEAD is only allowed when listed. A resource also exposes the Allow header of the response that created it with _allow and _allow?. Hyperclient never sends extra OPTIONS requests.

There is no method to clear or override what a link remembers. With enforce_allowed_methods on, the remembered Allow header is replaced by the link's next response, so call _options to ask the server again. Alternatively, use a new link object, which starts without restrictions, such as link._expand or a link from a freshly fetched resource.

Testing Using Hyperclient

You can combine RSpec, Faraday::Adapter::Rack and Hyperclient to test your HAL API without having to ever examine the raw JSON response.

describe Acme::Api do
  def app
    Acme::App.instance
  end

  let(:client) do
    Hyperclient.new('http://example.org/api') do |client|
      client.headers['Content-Type'] = 'application/json'
      client.connection(default: false) do |conn|
        conn.request :json
        conn.response :json
        conn.use Faraday::Adapter::Rack, app
      end
    end
  end

  it 'returns a place' do
    expect(client.places.first.name).to eq 'Balliol College'
  end
end

For a complete offline example, see the Oxford demo smoke test.

Reference

Hyperclient API Reference.

Hyperclient Users

Using Hyperclient? Add your project to our wiki, please: https://github.com/codegram/hyperclient/wiki.

Contributing

Hyperclient is work of many people. You're encouraged to submit pull requests, propose features and discuss issues. See CONTRIBUTING for details.

License

MIT License, see LICENSE for details.

Copyright (c) 2012-2018 Oriol Gual, Codegram Technologies and Contributors

About

HyperClient is a Ruby Hypermedia API client.

Resources

Contributing

Stars

153 stars

Watchers

12 watching

Forks

Releases

Packages

Used by

Contributors

Languages