Skip to content

Instantly share code, notes, and snippets.

@joshmcarthur
Created May 29, 2013 08:42
Show Gist options
  • Save joshmcarthur/5668853 to your computer and use it in GitHub Desktop.
Save joshmcarthur/5668853 to your computer and use it in GitHub Desktop.
A one-file adapter for any HTTP basic RESTful API. Uses Faraday for making HTTP requests, and dotenv for keeping your API tokens in a file named '.env'. Simply require this file, and start making requests!
# api.rb
#
# Requirments:
# As a service resource
# I want to be able to make API requests in a consistent manner
# So that results are predicatble and easy to handle.
#
# Synopsis:
# This file sets up a Faraday engine to make HTTP requests with,
# and defines a number of helper methods to make API requests easy.
#
require 'faraday'
require 'faraday_middleware'
require 'json'
require 'dotenv'
Dotenv.load
module MyService
class API
def initialize(host, api_token, api_secret)
@host = host
@api_token = api_token
@api_secret = api_secret
build_engine
end
def build_engine
@engine = Faraday.new(:url => @host) do |faraday|
faraday.request :json
faraday.adapter Faraday.default_adapter
faraday.response :json, :content_type => /\bjson$/
faraday.basic_auth @api_token, @api_secret
end
end
def get(path, params = {})
@engine.get(path, params).body
end
def post(path, params = {})
@engine.post(path, params).body
end
# Public: Perform a get request, assuming API token and secret
# are in the ENV hash.
#
# path - The API path to request
# params - Params to pass through to the API
#
# Returns a Hash of deserialized JSON
def self.get(path, params = {})
self.build_from_env.get(path, params)
end
# Public: Perform a post request, assuming API token and secret
# are in the ENV hash.
#
# path - The API path to request
# params - Params to pass through to the API
#
# Returns a Hash of deserialized JSON
def self.post(path, params = {})
self.build_from_env.post(path, params)
end
def self.build_from_env
self.new(ENV['MY_SERVICE_HOST'], ENV['MY_SERVICE_API_TOKEN'], ENV['MY_SERVICE_API_SECRET'])
end
end
end
@charlespeach
Copy link

Nice. Plug file in, change module name and environment variable references in API.build_from_env and your away.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment