• Stars
    star
    153
  • Rank 243,368 (Top 5 %)
  • Language
    Ruby
  • License
    MIT License
  • Created over 12 years ago
  • Updated 7 months ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

HyperClient is a Ruby Hypermedia API client.

Hyperclient

Gem Version Build Status Code Climate 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 Splines Demo API running here. 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.

API Client

Create an API client.

require 'hyperclient'

api = Hyperclient.new('https://grape-with-roar.herokuapp.com/api')

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('https://grape-with-roar.herokuapp.com/api') 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('https://grape-with-roar.herokuapp.com/api') 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('https://grape-with-roar.herokuapp.com/api') 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('https://grape-with-roar.herokuapp.com/api') 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('https://grape-with-roar.herokuapp.com/api') do |client|
  client.connection(default: false) do |conn|
    conn.request :json
    conn.response :json, content_type: /\bjson$/
    conn.adapter :net_http
  end
end

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('https://grape-with-roar.herokuapp.com/api') 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('https://grape-with-roar.herokuapp.com/api')
api.connection.use :http_cache

Resources and Attributes

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

api.splines.each do |spline|
  puts "A spline with ID #{spline.uuid}."
end

Other methods, including [] and fetch are also available

api.splines.each do |spline|
  puts "A spline with ID #{spline[:uuid]}."
  puts "Maybe with reticulated: #{spline.fetch(:reticulated, '-- no reticulated')}"
end

Links and Embedded Resources

The splines example above followed a link called "splines". While you can, you do not need to specify the HAL navigational structure, including links or embedded resources. Hyperclient will resolve these for you. If you prefer, you can explicitly navigate the link structure via _links. In the following example the "splines" link leads to a collection of embedded splines. Invoking api.splines is equivalent to api._links.splines._embedded.splines.

api._links.splines

Templated Links

Templated links require variables to be expanded. For example, the demo API has a link called "spline" that requires a spline "uuid".

spline = api.spline(uuid: 'uuid')
puts "Spline #{spline.uuid} is #{spline.reticulated ? 'reticulated' : 'not reticulated'}."

Invoking api.spline(uuid: 'uuid').reticulated is equivalent to api._links.spline._expand(uuid: 'uuid')._resource._attributes.reticulated.

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.

Curies

Curies are a suggested means by which to link documentation of a given resource. For example, the demo API contains very long links to images that use an "images" curie.

puts spline['image:thumbnail'] # => https://grape-with-roar.herokuapp.com/api/splines/uuid/images/thumbnail.jpg
puts spline.links._curies['image'].expand('thumbnail') # => /docs/images/thumbnail

Attributes

Resource attributes can also be accessed as a hash.

puts spline.to_h # => {"uuid" => "uuid", "reticulated" => true}

The above is equivalent to spline._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.

spline = api.spline(uuid: 'uuid')
spline._head
spline._options

Invoke _post to create resources.

splines = api.splines
splines._post(uuid: 'new uuid', reticulated: false)

Invoke _put or _patch to update resources.

spline = api.spline(uuid: 'uuid')
spline._put(reticulated: true)
spline._patch(reticulated: true)

Invoke _delete to destroy a resource.

spline = api.spline(uuid: 'uuid')
spline._delete

HTTP methods always return a new instance of 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 'splines returns 3 splines by default' do
    expect(client.splines.count).to eq 3
  end
end

For a complete example refer to this Splines Demo API 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

More Repositories

1

spinach

Spinach is a BDD framework on top of Gherkin.
Ruby
580
star
2

date_validator

A simple, ORM agnostic, Ruby >=2.2 compatible date validator for Rails, based on ActiveModel.
Ruby
493
star
3

pelusa

Static analysis Lint-type tool to improve your OO Ruby code
Ruby
438
star
4

rack-webconsole

Rack-based interactive console (ร  la Rails console) for your web application's front-end
Ruby
251
star
5

vim-codereview

GItHub Pull Request-based Code Reviews
Ruby
239
star
6

futuroscope

Yet another Futures implementation in Ruby
Ruby
209
star
7

resort

Positionless model sorting for Rails
Ruby
103
star
8

spinach-rails

Spinach-rails is a compatibility layer on top of Spinach to provide rails support.
Ruby
62
star
9

vimfiles

Codegram vimfiles
Vim Script
44
star
10

ember-forms

Easy forms for ember.js
JavaScript
36
star
11

gherkin-ruby

gherkin-ruby is a Gherkin parser in pure Ruby using Parslet.
Ruby
33
star
12

markdownizer

Render any text as markdown, with code highlighting and all!
Ruby
30
star
13

colorblind

Extend your ActiveSupport logger with trendy colorschemes from the 90's!
Ruby
27
star
14

live-rust

Rust
27
star
15

haml-jekyll-extension

Jekyll extension to easly use HAML instead of plain HTML
Ruby
21
star
16

jamstack-cfp

Run your call for papers using JAMStack + GitHub Actions
Vue
20
star
17

simple_currency

A really simple currency converter using XavierMedia API. Compatible with Ruby 1.8, 1.9, JRuby 1.5.3 and Rubinius 1.1
Ruby
17
star
18

colorant

A small utility to get the colors of an image.
Ruby
15
star
19

bankr

A bank accoount data gathering gem
Ruby
14
star
20

sass-images

Sass extensions to deal with images
Ruby
14
star
21

cheezburger

BDD for lolcats!
Ruby
13
star
22

guard-spinach

Guard-spinach is a guard plugin for spinach
Ruby
13
star
23

calbert

Catalan ALBERT (A Lite BERT for self-supervised learning of language representations)
Python
13
star
24

dialog-example

Repository with Angular project to show how we use Dialogs and Templates at Empresaula
TypeScript
12
star
25

rpg

RPG game to learn Ruby.
Ruby
9
star
26

dotfiles

Dotfiles used by Codegram team!
Emacs Lisp
8
star
27

spinach-rails-demo

Ruby
8
star
28

vim-todo

Easy peasy TODO list manager for VIM!
Vim Script
8
star
29

acts_as_decimal

Rails 3 plugin to store decimal numbers in the database as integers.
Ruby
7
star
30

pinky

[EXPERIMENTAL] Composable promises for Elixir.
Elixir
7
star
31

useful-github-workflows

Useful GitHub Workflows we use at Codegram
6
star
32

trace

Trace Ruby method calls inside a block of code
Ruby
6
star
33

urania.ex

Efficient and elegant data access for Elixir
Elixir
6
star
34

robinhood

Robin hood leverages celluloid actors to distribute long-lived processes across multiple servers using redis as a locking mechanism.
Ruby
6
star
35

timetable

Timetable is a tool to organize structured content (sections of a workshop, or due tasks), schedule it along time and let you know about current and next sections/tasks.
Ruby
6
star
36

tasca-spinach-demo

Simple todo application as a Spinach demo
Ruby
5
star
37

hypermodel

Rails Responder to generate an automagic JSON HAL representation for your models
Ruby
5
star
38

lastfm

A rather minimal Last.fm client for Ruby.
Ruby
5
star
39

talks

Monday Talks at Codegram
JavaScript
5
star
40

spex

Validate your Elixir values against value-based schemas
Elixir
5
star
41

status-notify-slack

A simple docker image to check if an application status is 200 OK
Shell
3
star
42

hey-mate

A Slack bot to recognize and reward your team's work ๐Ÿง‰
Elixir
3
star
43

vim-haml2slim

A small VIm plugin that helps you convert your Haml views to Slim
Vim Script
3
star
44

phoenix_starter

Elixir
3
star
45

heroku-nginx-proxy

Herouk application that runs a proxy
HTML
3
star
46

dm-machinist

dm-machinist is a datamapper adapter for machinist 2.0
Ruby
3
star
47

course_scraper

A course scraper that gets all the vocational training courses in Catalonia and Spain.
Ruby
2
star
48

full_stack_bot

Full Stack Fest's amazing bot.
Elixir
2
star
49

spinach-sinatra-demo

Spinach working with sinatra
Ruby
2
star
50

deepspain

Deep Spain is a language model fine-tuned on the Spanish state's official bulletin documents
Python
2
star
51

webservice-clj

Example webservice in Clojure for a talk.
Clojure
2
star
52

decidim-barcelona-graphql-api

Simple GraphQL API for decidim.barcelona using Absinthe
Elixir
2
star
53

decidim-deploy-heroku

Opinionated Rails generator for `decidim` apps.
Ruby
2
star
54

decidim-monitor

A tool to monitor instances of decidim.
Elixir
2
star
55

serve-template

Ruby
2
star
56

spinach_helpers

Support helpers to include in Spinach
2
star
57

faye-websockets-heroku-test

Websockets test (a realtime auction app).
JavaScript
2
star
58

codegram.github.io

Codegram Blog
Clojure
2
star
59

gram

Gram is an internal administration tool for Codegram
Ruby
1
star
60

decidim-staging

Demo application to try Codegram's unreleased features of Decidim
HTML
1
star
61

rubocop-decidim

Rubocop custom cops for decidim/decidim
Ruby
1
star
62

spinach-presentation

Showoff presentation for Spinach
1
star
63

button_form

button_form replaces all <input type="submit"/> tags with <button/> in your forms
Ruby
1
star
64

sonic-client

Sonic Client for Elixir
Elixir
1
star
65

serverless-ruby-circleci

A CircleCI orb to build and deploy serverless ruby apps
1
star
66

wasm-tree

HTML
1
star
67

codeborg

A Hubot for Codegram
CoffeeScript
1
star
68

docker-images

A collection of useful docker images for development
Shell
1
star
69

elixir_starter

Elixir
1
star
70

full-stack-fest-sponsor-handbook

Full Stack Fest's sponsor handbook
CSS
1
star
71

rails-templates

Ruby
1
star
72

vim-numberlock

Map your numbers to their corresponding Shift+Number symbol for faster typing.
Vim Script
1
star
73

nuxt-starter

JavaScript
1
star
74

autility

Download utility invoices from some of the popular utility vendors in Spain (Endesa, Vodafone).
Ruby
1
star
75

decidim-electionguard

Python
1
star
76

globalize2_home_page_redirect-radiant-extension

self explanatory
Ruby
1
star
77

hackershout

Shout your hackerness to the world!
Ruby
1
star
78

sass-compass-exercises

Exercises for the sass-compass workshop
Ruby
1
star
79

awesome-mixins

Awesome compass mixins
1
star
80

confs-client

Client for Codegram Conferences
Ruby
1
star