http_api_builder 0.2.0

Sign up to get free protection for your applications and to get access to all the features.
checksums.yaml ADDED
@@ -0,0 +1,7 @@
1
+ ---
2
+ SHA1:
3
+ metadata.gz: 8bb6287229132caf42b05f3b4fd2d7d0c0886979
4
+ data.tar.gz: 8dc6d07fa9706a1d3dac2b8342c149e7ca12fc2a
5
+ SHA512:
6
+ metadata.gz: a96b2a7f66eea0ddc60bf6b66a240658a5ae483ae3958b4e64504dce81354cf8094b509428df12e3cc214cf6e59d462bcb9b648bbd14cd8ac8d142e8959159b8
7
+ data.tar.gz: 8907e1793fc829b2d3a1cd097090b277e301e527c29c528367cc26260771e4cf25c84f06cb47e8499f4ddc2df7cb41f5b39e4eba34781582f3c3d1c144c1e57a
data/.gitignore ADDED
@@ -0,0 +1,10 @@
1
+ /.bundle/
2
+ /.yardoc
3
+ /Gemfile.lock
4
+ /_yardoc/
5
+ /coverage/
6
+ /doc/
7
+ /pkg/
8
+ /spec/reports/
9
+ /tmp/
10
+ vendor
data/.rspec ADDED
@@ -0,0 +1,2 @@
1
+ --format documentation
2
+ --color
data/.rubocop.yml ADDED
@@ -0,0 +1,4 @@
1
+ AllCops:
2
+ TargetRubyVersion: 2.2
3
+ Metrics/LineLength:
4
+ Enabled: false
data/.travis.yml ADDED
@@ -0,0 +1,4 @@
1
+ language: ruby
2
+ rvm:
3
+ - 2.3.0
4
+ before_install: gem install bundler -v 1.11.2
data/Gemfile ADDED
@@ -0,0 +1,4 @@
1
+ source 'https://rubygems.org'
2
+
3
+ # Specify your gem's dependencies in http_api_builder.gemspec
4
+ gemspec
data/LICENSE.txt ADDED
@@ -0,0 +1,21 @@
1
+ The MIT License (MIT)
2
+
3
+ Copyright (c) 2016 Jeff Sandberg
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in
13
+ all copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
21
+ THE SOFTWARE.
data/README.md ADDED
@@ -0,0 +1,75 @@
1
+ # HttpApiBuilder
2
+ A simple tool for building API clients that use HTTP.
3
+
4
+ This is for **clients** as in *consumers*, not for servers. Look into things like Rails-api or Grape for those.
5
+
6
+ [![Code Climate](https://codeclimate.com/github/paradox460/http_api_builder/badges/gpa.svg)](https://codeclimate.com/github/paradox460/http_api_builder)
7
+
8
+ ## Installation
9
+
10
+ Add this line to your application's Gemfile:
11
+
12
+ ```ruby
13
+ gem 'http_api_builder'
14
+ ```
15
+
16
+ And then execute:
17
+
18
+ $ bundle
19
+
20
+ Or install it yourself as:
21
+
22
+ $ gem install http_api_builder
23
+
24
+ ## Usage
25
+
26
+ ```ruby
27
+ require 'http_api_builder/client/http_rb'
28
+
29
+ class ElGoog < HttpApiBuilder::BaseClient
30
+ include HttpApiBuilder::Client::HttpRb
31
+
32
+ base_url 'https://google.com'
33
+
34
+ get '/', as: :search, params: {required: :q}
35
+ end
36
+ ```
37
+
38
+ You can then use the API as such:
39
+
40
+ ```ruby
41
+ g = ElGoog.new
42
+
43
+ g.search(q: 'ruby')
44
+ ```
45
+
46
+ See the wiki for more details.
47
+
48
+ ## License
49
+
50
+ The gem is available as open source under the terms of the [MIT License](http://opensource.org/licenses/MIT).
51
+
52
+
53
+ ```
54
+ The MIT License (MIT)
55
+
56
+ Copyright (c) 2016 Jeff Sandberg
57
+
58
+ Permission is hereby granted, free of charge, to any person obtaining a copy
59
+ of this software and associated documentation files (the "Software"), to deal
60
+ in the Software without restriction, including without limitation the rights
61
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
62
+ copies of the Software, and to permit persons to whom the Software is
63
+ furnished to do so, subject to the following conditions:
64
+
65
+ The above copyright notice and this permission notice shall be included in
66
+ all copies or substantial portions of the Software.
67
+
68
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
69
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
70
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
71
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
72
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
73
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
74
+ THE SOFTWARE.
75
+ ```
data/Rakefile ADDED
@@ -0,0 +1,6 @@
1
+ require 'bundler/gem_tasks'
2
+ require 'rspec/core/rake_task'
3
+
4
+ RSpec::Core::RakeTask.new(:spec)
5
+
6
+ task default: :spec
data/bin/console ADDED
@@ -0,0 +1,14 @@
1
+ #!/usr/bin/env ruby
2
+
3
+ require 'bundler/setup'
4
+ require 'http_api_builder'
5
+
6
+ # You can add fixtures and/or initialization code here to make experimenting
7
+ # with your gem easier. You can also use a different console, if you like.
8
+
9
+ # (If you use this, don't forget to add pry to your Gemfile!)
10
+ # require "pry"
11
+ # Pry.start
12
+
13
+ require 'pry'
14
+ Pry.start
data/bin/setup ADDED
@@ -0,0 +1,8 @@
1
+ #!/usr/bin/env bash
2
+ set -euo pipefail
3
+ IFS=$'\n\t'
4
+ set -vx
5
+
6
+ bundle install
7
+
8
+ # Do any other automated setup that you need to do here
@@ -0,0 +1,31 @@
1
+ # coding: utf-8
2
+ lib = File.expand_path('../lib', __FILE__)
3
+ $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
4
+ require 'http_api_builder/version'
5
+
6
+ Gem::Specification.new do |spec|
7
+ spec.name = 'http_api_builder'
8
+ spec.version = HttpApiBuilder::VERSION
9
+ spec.authors = ['Jeff Sandberg']
10
+ spec.email = ['paradox460@gmail.com']
11
+
12
+ spec.summary = 'A utility gem providing a DSL for building HTTP api wrappers.'
13
+ spec.description = 'A gem providing a nice DSL for building HTTP api wrappers.'
14
+ spec.homepage = 'https://github.com/paradox460/http_api_builder'
15
+ spec.license = 'MIT'
16
+
17
+ spec.files = `git ls-files -z`.split("\x0").reject { |f| f.match(%r{^(test|spec|features)/}) }
18
+ spec.bindir = 'exe'
19
+ spec.executables = spec.files.grep(%r{^exe/}) { |f| File.basename(f) }
20
+ spec.require_paths = ['lib']
21
+
22
+ spec.required_ruby_version = ">= 2.2"
23
+
24
+ spec.add_development_dependency 'bundler', '~> 1.11'
25
+ spec.add_development_dependency 'rake', '~> 10.0'
26
+ spec.add_development_dependency 'rspec', '~> 3.0'
27
+ spec.add_development_dependency 'pry'
28
+ spec.add_development_dependency 'pry-stack_explorer'
29
+ spec.add_development_dependency 'pry-byebug'
30
+ spec.add_development_dependency 'http'
31
+ end
@@ -0,0 +1,15 @@
1
+ require 'http'
2
+
3
+ module HttpApiBuilder
4
+ module Client
5
+ # A demonstration implementation, using HTTP.rb
6
+ # This is functional and pretty much production ready, but you can
7
+ # easily rewrite it to use curb or typhoeus or anything else really
8
+ module HttpRb
9
+ def request(verb, path, form:, query:, body:, json:) # rubocop:disable Metrics/ParameterLists
10
+ url = URI.join(self.class.base_url || '', path)
11
+ HTTP.send(verb, url, form: form, params: query, body: body, json: json)
12
+ end
13
+ end
14
+ end
15
+ end
@@ -0,0 +1,95 @@
1
+ require 'forwardable'
2
+
3
+ module HttpApiBuilder
4
+ # Module for restful api dsl commands
5
+ module Dsl
6
+ VERBS =
7
+ %i(get head post put delete trace options connect) + # HTTP 1.1
8
+ %i(propfind proppatch mkcol copy move lock unlock) + # WebDAV
9
+ %i(orderpatch) + # WebDAV Ordered Collections protocol
10
+ %i(acl) + # WebDAV Access Control protocol
11
+ %i(patch) + # PATCH method for HTTP
12
+ %i(search) # WebDAV search
13
+
14
+ # Set the initial URL used by the gem
15
+ def base_url(value = nil)
16
+ value.nil? ? @base_url : (@base_url = value)
17
+ end
18
+
19
+ protected
20
+
21
+ # Generate whiny and quiet API consumer methods.
22
+ #
23
+ # Whiny methods have a bang suffix and raise errors if they fail
24
+ # Quiet methods do not have the bang suffix and return nil if they fail
25
+ #
26
+ # eg:
27
+ # endpoint '/path', as: :mymethod
28
+ # results in:
29
+ # mymethod! <-- whiny
30
+ # mymethod <-- quiet
31
+ def endpoint(path, as:, using: :get, params: nil, form: nil, body: nil, processors: nil, json: nil) # rubocop:disable Metrics/ParameterLists
32
+ def_whiny_method as, path, using, processors, params, form, body, json
33
+ def_quiet_method as
34
+ end
35
+
36
+ VERBS.each do |v|
37
+ define_method v do |path, **opts|
38
+ consume path, using: v, **opts
39
+ end
40
+ end
41
+
42
+ private
43
+
44
+ # Generate a consumer method that raises exceptions when requests raise an error
45
+ #
46
+ def def_whiny_method(name, path, using, processors, params, form, body, json) # rubocop:disable Metrics/ParameterLists, Metrics/AbcSize, Metrics/MethodLength
47
+ required, optional = requirements(path, params)
48
+
49
+ define_method :"#{name}!" do |opts = {}|
50
+ validate_args! opts.keys, required, optional
51
+
52
+ reqpath = interpolate_path(path, opts)
53
+ query = query_params(path, opts, required, optional)
54
+
55
+ form = Hash(form).merge(Hash(opts[:form]))
56
+ json = opts[:json] || json
57
+ body = opts[:body] || body
58
+ perform(using, reqpath, form: form, query: query, body: body, json: json) do |resource, *_|
59
+ run_processors resource, processors
60
+ end
61
+ end
62
+ end
63
+
64
+ # Generate a consumer method that returns nil when requests raise errors
65
+ #
66
+ def def_quiet_method(name)
67
+ define_method name do |opts = {}|
68
+ begin
69
+ send(:"#{name}!", opts)
70
+ rescue StandardError
71
+ nil
72
+ end
73
+ end
74
+ end
75
+
76
+ # Extract param segments from a path, paperclip style. Returns an array of symbols matching the names of the param segments.
77
+ #
78
+ # Param segments are sections of the path that begin with `:`, and run to the next /
79
+ def interpolated_params(path)
80
+ path.split('/').reject { |i| i.length.zero? || i !~ /^:/ }.uniq.map { |i| i[1..-1].to_sym }
81
+ end
82
+
83
+ # Parse out and return the required and optional arguments
84
+ #
85
+ # Required are any that are in the URL or in the required hash
86
+ # Optional are any other arguments.
87
+ def requirements(path, params)
88
+ required, optional = Hash(params).values_at(*%i(required optional)).map { |list| Array(list) }
89
+
90
+ required += interpolated_params(path)
91
+
92
+ [required, optional]
93
+ end
94
+ end
95
+ end
@@ -0,0 +1,75 @@
1
+ module HttpApiBuilder
2
+ # Helper methods
3
+ module Helpers
4
+ protected
5
+
6
+ # Validates arguments and ensures that required and optional are present.
7
+ # Also validates that all args are expected
8
+ #
9
+ # @param [Array] actual The args (or keys of args) we've received
10
+ # @param [Array] required Args we are required to have, will raise error if not present
11
+ # @param [Array] optional Optional args.
12
+ def validate_args!(actual, required, optional)
13
+ validate_required_arguments(actual, required)
14
+ validate_valid_arguments(actual, required, optional)
15
+ end
16
+
17
+ private
18
+
19
+ # Start the processing chain for the response object
20
+ # Processors work in a chain, meaning order of operations is important.
21
+ # The first processor gets the raw result, the second processor the first's
22
+ # output and so forth.
23
+ # The last processor's output is the return of the method
24
+ # processors: [processor1, processor2] yields this pipeline:
25
+ # request -> processor1 -> processor2 -> output
26
+ def run_processors(resource, processors)
27
+ Array(processors).reduce(resource) do |data, processor|
28
+ if processor.respond_to?(:call)
29
+ processor.call(data)
30
+ else
31
+ send(processor, data)
32
+ end
33
+ end
34
+ end
35
+
36
+ # Build the path, filling in any interpolation tokens
37
+ #
38
+ # @param [String] path
39
+ # @param [Hash] values Key-value {interpolation: value}
40
+ # @return [String] interpolated string
41
+ def interpolate_path(path, values)
42
+ result = path.dup
43
+ values.each do |token, value|
44
+ token = ":#{token}"
45
+ result.gsub!(token, value)
46
+ end
47
+ result
48
+ end
49
+
50
+ # Get the non-interpolating query parameters
51
+ def query_params(path, params, required, optional)
52
+ path_params = self.class.send(:interpolated_params, path)
53
+ query_keys = (required + (optional - [:data])) - path_params
54
+ params.select { |k, _| query_keys.include? k }
55
+ end
56
+
57
+ # Raise an ArgumentError if not everything listed as required is not listed in supplied.
58
+ #
59
+ def validate_required_arguments(supplied, required)
60
+ missing = supplied & required
61
+ return if missing.sort == required.sort
62
+
63
+ raise ArgumentError, "missing required arguments: #{missing.join(', ')}"
64
+ end
65
+
66
+ # Raise an ArgumentError if not everything listed in supplied appear in either the required or optional list.
67
+ #
68
+ def validate_valid_arguments(supplied, required, optional)
69
+ unrecognized = supplied - (required + optional).uniq
70
+ return if unrecognized.empty?
71
+
72
+ raise ArgumentError, "unrecognized arguments: #{unrecognized.join(', ')}"
73
+ end
74
+ end
75
+ end
@@ -0,0 +1,3 @@
1
+ module HttpApiBuilder
2
+ VERSION = '0.2.0'.freeze
3
+ end
@@ -0,0 +1,34 @@
1
+ require 'http_api_builder/version'
2
+ require 'http_api_builder/dsl'
3
+ require 'http_api_builder/helpers'
4
+
5
+ module HttpApiBuilder
6
+ # A basic HTTP client. Meant to be extended from.
7
+ class BaseClient
8
+ extend Dsl
9
+ include Helpers
10
+
11
+ def initialize(); end
12
+
13
+ # Perform the request, post processors, and return the result
14
+ def perform(method, path, form: nil, query: nil, body: nil, json: nil, &_block) # rubocop:disable Metrics/ParameterLists
15
+ response = request(method, path, form: form, query: query, body: body, json: json)
16
+ status = response.status
17
+ resource = response.body
18
+ block_given? ? yield(resource, status, response) : resource
19
+ end
20
+
21
+ # Placeholder for your request method.
22
+ # Accepts these params, for you to do whatever you like with. See the HTTPrb_client implementation
23
+ #
24
+ # @param [Symbol] method The HTTP VERB to use
25
+ # @param [String, URI] path The path, excluding base_url, which should be prepended inside your implementation
26
+ # @param [Hash] form: nil Form data, for encoding into HTTP form encoding
27
+ # @param [Hash] query: nil Query key/value pairs
28
+ # @param [String] body: nil A raw body
29
+ # @param [Hash, Array] json: nil Hash/Array data to be encoded as JSON.
30
+ def request(*)
31
+ raise 'HttpApiBuilder::BaseClient#request must be implemented, see documentation'
32
+ end
33
+ end
34
+ end
metadata ADDED
@@ -0,0 +1,158 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: http_api_builder
3
+ version: !ruby/object:Gem::Version
4
+ version: 0.2.0
5
+ platform: ruby
6
+ authors:
7
+ - Jeff Sandberg
8
+ autorequire:
9
+ bindir: exe
10
+ cert_chain: []
11
+ date: 2016-04-05 00:00:00.000000000 Z
12
+ dependencies:
13
+ - !ruby/object:Gem::Dependency
14
+ name: bundler
15
+ requirement: !ruby/object:Gem::Requirement
16
+ requirements:
17
+ - - "~>"
18
+ - !ruby/object:Gem::Version
19
+ version: '1.11'
20
+ type: :development
21
+ prerelease: false
22
+ version_requirements: !ruby/object:Gem::Requirement
23
+ requirements:
24
+ - - "~>"
25
+ - !ruby/object:Gem::Version
26
+ version: '1.11'
27
+ - !ruby/object:Gem::Dependency
28
+ name: rake
29
+ requirement: !ruby/object:Gem::Requirement
30
+ requirements:
31
+ - - "~>"
32
+ - !ruby/object:Gem::Version
33
+ version: '10.0'
34
+ type: :development
35
+ prerelease: false
36
+ version_requirements: !ruby/object:Gem::Requirement
37
+ requirements:
38
+ - - "~>"
39
+ - !ruby/object:Gem::Version
40
+ version: '10.0'
41
+ - !ruby/object:Gem::Dependency
42
+ name: rspec
43
+ requirement: !ruby/object:Gem::Requirement
44
+ requirements:
45
+ - - "~>"
46
+ - !ruby/object:Gem::Version
47
+ version: '3.0'
48
+ type: :development
49
+ prerelease: false
50
+ version_requirements: !ruby/object:Gem::Requirement
51
+ requirements:
52
+ - - "~>"
53
+ - !ruby/object:Gem::Version
54
+ version: '3.0'
55
+ - !ruby/object:Gem::Dependency
56
+ name: pry
57
+ requirement: !ruby/object:Gem::Requirement
58
+ requirements:
59
+ - - ">="
60
+ - !ruby/object:Gem::Version
61
+ version: '0'
62
+ type: :development
63
+ prerelease: false
64
+ version_requirements: !ruby/object:Gem::Requirement
65
+ requirements:
66
+ - - ">="
67
+ - !ruby/object:Gem::Version
68
+ version: '0'
69
+ - !ruby/object:Gem::Dependency
70
+ name: pry-stack_explorer
71
+ requirement: !ruby/object:Gem::Requirement
72
+ requirements:
73
+ - - ">="
74
+ - !ruby/object:Gem::Version
75
+ version: '0'
76
+ type: :development
77
+ prerelease: false
78
+ version_requirements: !ruby/object:Gem::Requirement
79
+ requirements:
80
+ - - ">="
81
+ - !ruby/object:Gem::Version
82
+ version: '0'
83
+ - !ruby/object:Gem::Dependency
84
+ name: pry-byebug
85
+ requirement: !ruby/object:Gem::Requirement
86
+ requirements:
87
+ - - ">="
88
+ - !ruby/object:Gem::Version
89
+ version: '0'
90
+ type: :development
91
+ prerelease: false
92
+ version_requirements: !ruby/object:Gem::Requirement
93
+ requirements:
94
+ - - ">="
95
+ - !ruby/object:Gem::Version
96
+ version: '0'
97
+ - !ruby/object:Gem::Dependency
98
+ name: http
99
+ requirement: !ruby/object:Gem::Requirement
100
+ requirements:
101
+ - - ">="
102
+ - !ruby/object:Gem::Version
103
+ version: '0'
104
+ type: :development
105
+ prerelease: false
106
+ version_requirements: !ruby/object:Gem::Requirement
107
+ requirements:
108
+ - - ">="
109
+ - !ruby/object:Gem::Version
110
+ version: '0'
111
+ description: A gem providing a nice DSL for building HTTP api wrappers.
112
+ email:
113
+ - paradox460@gmail.com
114
+ executables: []
115
+ extensions: []
116
+ extra_rdoc_files: []
117
+ files:
118
+ - ".gitignore"
119
+ - ".rspec"
120
+ - ".rubocop.yml"
121
+ - ".travis.yml"
122
+ - Gemfile
123
+ - LICENSE.txt
124
+ - README.md
125
+ - Rakefile
126
+ - bin/console
127
+ - bin/setup
128
+ - http_api_builder.gemspec
129
+ - lib/http_api_builder.rb
130
+ - lib/http_api_builder/client/http_rb.rb
131
+ - lib/http_api_builder/dsl.rb
132
+ - lib/http_api_builder/helpers.rb
133
+ - lib/http_api_builder/version.rb
134
+ homepage: https://github.com/paradox460/http_api_builder
135
+ licenses:
136
+ - MIT
137
+ metadata: {}
138
+ post_install_message:
139
+ rdoc_options: []
140
+ require_paths:
141
+ - lib
142
+ required_ruby_version: !ruby/object:Gem::Requirement
143
+ requirements:
144
+ - - ">="
145
+ - !ruby/object:Gem::Version
146
+ version: '2.2'
147
+ required_rubygems_version: !ruby/object:Gem::Requirement
148
+ requirements:
149
+ - - ">="
150
+ - !ruby/object:Gem::Version
151
+ version: '0'
152
+ requirements: []
153
+ rubyforge_project:
154
+ rubygems_version: 2.5.1
155
+ signing_key:
156
+ specification_version: 4
157
+ summary: A utility gem providing a DSL for building HTTP api wrappers.
158
+ test_files: []