Skip to content

Instantly share code, notes, and snippets.

@stujo
Last active August 29, 2015 14:07
Show Gist options
  • Save stujo/52df041aadac49444770 to your computer and use it in GitHub Desktop.
Save stujo/52df041aadac49444770 to your computer and use it in GitHub Desktop.
Consuming a REST API with Typhoeus
require 'pwclient'
client = PetWorldClient.new
pets = client.api_call("/pets")
puts "There are #{pets.length} pets"
owner = client.api_call("/owners")[0]
puts "First Owner is #{owner['name']} (id=#{owner['id']})"
duke = client.api_call("/owner/#{owner['id']}/pet",:post, {
name: "Duke", breed: "Bloodhound"
})
if duke
puts "Added #{duke['name']} (id=#{duke['id']}) to #{owner['name']}'s pets"
end
dukes = client.api_call("/pets/search",:post, { q: "Duke"})
puts "Found #{duke['name']} (id=#{duke['id']}) by searching" unless dukes.empty?
delete_duke = client.api_call("/pet/#{duke['id']}",:delete)
puts "Deleted Duke" unless dukes.empty?
require 'typhoeus'
require 'rack/utils'
require 'json'
require 'debugger'
PETWORLD_API_URL_ROOT = 'http://stujopet.herokuapp.com/api/v1'
class PetWorldClientException < StandardError
end
class PetWorldClient
attr_reader :last_response, :last_request
# https://github.com/typhoeus/typhoeus
# Typhoeus.get("www.example.com")
# Typhoeus.head("www.example.com")
# Typhoeus.put("www.example.com/posts/1", body: "whoo, a body")
# Typhoeus.post("www.example.com/posts", body: { title: "test post", content: "this is my test"})
# Typhoeus.delete("www.example.com/posts/1")
def initialize
#Get an API TOKEN
body = Typhoeus.get(PETWORLD_API_URL_ROOT + "/token").body
@token = JSON.parse(body)['token']
raise PetWorldClientException.new("Unable to get API Token") if @token.nil?
puts "Obtained API Token '#{@token}'"
end
def api_call(path, method = :get, params = {}, body = "")
@last_request = Typhoeus::Request.new(
PETWORLD_API_URL_ROOT + path,
method: method,
body: body,
params: params,
headers: { X_PETWORLD_REST_API_KEY: @token }
)
@last_response = @last_request.run
puts "Status Code #{@last_response.code} (#{Rack::Utils::HTTP_STATUS_CODES[@last_response.code]}) from [#{method.upcase}] to #{path}"
payload = JSON.parse(@last_response.body) unless @last_response.code == 204
if @last_response.code > 399
puts "ERROR:" + payload['message']
puts "ERROR:" + payload['errors'].to_s
nil
else
payload
end
end
end
puts <<-USAGE
Usage Notes:
------------
client = PetWorldClient.new
pets = client.api_call("/pets")
puts "There are \#{pets.length} pets"
USAGE
desc "launch the console"
task "console" do
exec 'irb -r ./pwclient.rb'
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment