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.

Revisions

  1. joshmcarthur created this gist May 29, 2013.
    74 changes: 74 additions & 0 deletions api.rb
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,74 @@
    # 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