rest_api_builder 0.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,7 @@
1
+ ---
2
+ SHA256:
3
+ metadata.gz: 1ffe941de96bc46453108079ed3dce2d654947b2930f2127c2e18737c9b00199
4
+ data.tar.gz: 59665b1e50fe3a2ab479d73dd549a2369718f6f2ba7adc02b66399b1a6c32a24
5
+ SHA512:
6
+ metadata.gz: cf33cca8a23fdfe9302e0fd6e9fabfddb4b67bc73c762f91689f1bf0130d6827c5545f5eb9ee3e4dda639f053fdc07a9ab92c175463b370ee2884e52c6ea3dbe
7
+ data.tar.gz: 8a70a3bbf1b7cd2c83b5ad65c45b98191a32daf864ac826fa40920f30a4f423169e9bfbadd6896eee2f6796b886f4caeabe65fa90fad834ff8d1b9b7ca574e1b
data/LICENSE ADDED
@@ -0,0 +1,20 @@
1
+ Copyright (c) 2020 Alexey D
2
+
3
+ Permission is hereby granted, free of charge, to any person obtaining
4
+ a copy of this software and associated documentation files (the
5
+ "Software"), to deal in the Software without restriction, including
6
+ without limitation the rights to use, copy, modify, merge, publish,
7
+ distribute, sublicense, and/or sell copies of the Software, and to
8
+ permit persons to whom the Software is furnished to do so, subject to
9
+ the following conditions:
10
+
11
+ The above copyright notice and this permission notice shall be
12
+ included in all copies or substantial portions of the Software.
13
+
14
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
15
+ EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
16
+ MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
17
+ NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
18
+ LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
19
+ OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
20
+ WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
@@ -0,0 +1,132 @@
1
+ # RestAPIBuilder
2
+
3
+ A simple wrapper for rest-client aiming to make creation and testing of API clients easier.
4
+
5
+ ## Why?
6
+ RestClient is great, but after building a few API clients with it you will almost inevitably find yourself re-implementing certain basic things such as:
7
+ - Compiling and parsing basic JSON requests/responses
8
+ - Handling and extracting details from non-200 responses
9
+ - Creating testing interfaces for your API clients
10
+
11
+ This library's tries to solve these and similar issues by providing a thin wrapper around [rest-client](https://github.com/rest-client/rest-client) and an optional [webmock](https://github.com/bblimke/webmock) testing interface for it.
12
+
13
+ ## Installation
14
+ ```
15
+ gem install rest_api_builder
16
+ ```
17
+
18
+ ## WebMock interface installation
19
+ Simply require webmock interface before your test, for example in your `test_helper.rb`:
20
+ ```rb
21
+ # test_helper.rb
22
+ require "webmock"
23
+ require "rest_api_builder/webmock_request_expectations"
24
+
25
+ WebMock.enable!
26
+
27
+ # my_spec.rb
28
+ require 'test_helper'
29
+
30
+ describe 'my test' do
31
+ it 'performs a request' do
32
+ RestAPIBuilder::WebMockRequestExpectations.expect_execute(...).to_return(body: "hi!")
33
+ result = RestAPIBuilder::Request.execute(...)
34
+
35
+ # some assertions
36
+ end
37
+ end
38
+ ```
39
+
40
+ `RestAPIBuilder::WebMockRequestExpectations` expects that you have WebMock installed as a dependency.
41
+
42
+ ## Usage
43
+ ```rb
44
+ require "rest_api_builder"
45
+
46
+ Request = RestAPIBuilder::Request
47
+
48
+ # Simple request:
49
+ response = Request.execute(base_url: "example.com", method: :get)
50
+ response[:success] #=> true
51
+ response[:status] #=> 200
52
+ response[:body] #=> "<!doctype html>\n<html>..."
53
+ response[:headers] #=> {:accept_ranges=>"bytes", ...}
54
+
55
+ # Non-200 responses:
56
+ response = Request.execute(base_url: "example.com", path: "/foo", method: :get)
57
+ response[:success] #=> false
58
+ response[:status] #=> 404
59
+ response[:body] #=> "<!doctype html>\n<html>..."
60
+
61
+ # JSON requests:
62
+ response = Request.json_execute(base_url: "api.github.com", path: "/users/octocat/orgs", method: :get)
63
+ response[:success] #=> true
64
+ response[:body] #=> []
65
+ ```
66
+
67
+ ## WebMock Expectations
68
+ ```rb
69
+ require "rest_api_builder"
70
+ require "webmock"
71
+ require "rest_api_builder/webmock_request_expectations"
72
+
73
+ WebMock.disable_net_connect!
74
+
75
+ Request = RestAPIBuilder::Request
76
+ Expectations = RestAPIBuilder::WebMockRequestExpectations
77
+
78
+ # Simple expectation
79
+ Expectations.expect_execute(base_url: "test.com", method: :get)
80
+ response = Request.execute(base_url: "test.com", method: :get)
81
+
82
+ response[:success] #=> true
83
+ response[:status] #=> 200
84
+ response[:body] #=> ''
85
+ response[:headers] #=> {}
86
+
87
+ # Specifying response details
88
+ Expectations
89
+ .expect_execute(base_url: "test.com", method: :get)
90
+ .to_return(status: 404, body: "not found")
91
+ response = Request.execute(base_url: "test.com", method: :get)
92
+
93
+ response[:success] #=> false
94
+ response[:status] #=> 404
95
+ response[:body] #=> "not found"
96
+ ```
97
+
98
+ ## Request API
99
+ ### RestAPIBuilder::Request.execute(options)
100
+ Performs a HTTP request via `RestClient::Request.execute`.\
101
+ Returns ruby hash with following keys: `:success`, `:status`, `:body`, `:headers`\
102
+ Does not throw on non-200 responses like RestClient does, but will throw on any error without defined response(e.g server timeout)
103
+
104
+ #### Options:
105
+ * **base_url**: Base URL of the request. Required.
106
+ * **method**: HTTP method of the request(e.g :get, :post, :patch). Required.
107
+ * **path**: Path to be appended to the :base_url. Optional.
108
+ * **body**: Request Body. Optional.
109
+ * **headers**: Request Headers. Optional.
110
+ * **query**: Query hash to be appended to the resulting url. Optional.
111
+ * **logger**: A `Logger` instance to be passed to RestClient in `log` option. Will also log response details as RestClient does not do this by default. Optional
112
+ * **parse_json**: Boolean. If `true`, will attempt to parse the response body as JSON. Will return the response body unchanged if it does not contain valid JSON. `false` by default.
113
+ * **rest_client_options**: Any additional options to be passed to `RestClient::Request.execute` unchanged. **Any option set here will completely overwrite all custom options**. For example, if you call `RestAPIBuilder::Request.execute(method: :post, rest_client_options: {method: :get})`, the resulting request will be sent as GET. Optional.
114
+
115
+ ### RestAPIBuilder::Request.json_execute(options)
116
+ A convenience shortcut for `#execute` which will also:
117
+ - Add `Content-Type: 'application/json'` to request `headers`
118
+ - Convert request `body` to JSON
119
+ - Set `parse_json` option to `true`
120
+
121
+
122
+ ## WebMockRequestExpectations API
123
+ ### RestAPIBuilder::WebMockRequestExpectations.expect_execute(options)
124
+ Defines a request expectation using WebMock's `stub_request`. Returns an instance of `WebMock::RequestStub` on which methods such as `with`, `to_return`, `to_timeout` can be called
125
+
126
+ #### Options:
127
+ * **base_url**: Base URL of the request. Required.
128
+ * **method**: HTTP method of the request(e.g :get, :post, :patch). Required.
129
+ * **path**: Path to be appended to the :base_url. Optional.
130
+
131
+ ## License
132
+ MIT
@@ -0,0 +1 @@
1
+ require 'rest_api_builder/request'
@@ -0,0 +1,52 @@
1
+ require 'rest-client'
2
+ require 'rest_api_builder/url_helper'
3
+ require 'rest_api_builder/rest_client_response_parser'
4
+
5
+ module RestAPIBuilder
6
+ class RequestSingleton
7
+ include RestAPIBuilder::UrlHelper
8
+
9
+ def json_execute(headers: {}, body: nil, **options)
10
+ headers = headers.merge(content_type: :json)
11
+ body &&= JSON.generate(body)
12
+ execute(**options, parse_json: true, headers: headers, body: body)
13
+ end
14
+
15
+ def execute(
16
+ base_url:,
17
+ method:,
18
+ body: nil,
19
+ headers: {},
20
+ query: nil,
21
+ path: nil,
22
+ logger: nil,
23
+ parse_json: false,
24
+ rest_client_options: {}
25
+ )
26
+ if method == :get && body
27
+ raise ArgumentError, 'GET requests do not support body'
28
+ end
29
+
30
+ response_parser = RestAPIBuilder::RestClientResponseParser.new(logger: logger, parse_json: parse_json)
31
+ headers = headers.merge(params: query) if query
32
+
33
+ begin
34
+ response = RestClient::Request.execute(
35
+ method: method,
36
+ url: full_url(base_url, path),
37
+ payload: body,
38
+ headers: headers,
39
+ log: logger,
40
+ **rest_client_options
41
+ )
42
+ response_parser.parse_response(response, success: true)
43
+ rescue RestClient::RequestFailed => e
44
+ raise e unless e.response
45
+
46
+ response_parser.parse_response(e.response, success: false)
47
+ end
48
+ end
49
+ end
50
+
51
+ Request = RequestSingleton.new
52
+ end
@@ -0,0 +1,35 @@
1
+ require 'json'
2
+
3
+ module RestAPIBuilder
4
+ class RestClientResponseParser
5
+ def initialize(logger:, parse_json:)
6
+ @logger = logger
7
+ @parse_json = parse_json
8
+ end
9
+
10
+ def parse_response(response, success:)
11
+ body = @parse_json ? parse_json(response.body) : response.body
12
+ result = {
13
+ success: success,
14
+ status: response.code,
15
+ body: body,
16
+ headers: response.headers
17
+ }
18
+ maybe_log_result(result)
19
+
20
+ result
21
+ end
22
+
23
+ private
24
+
25
+ def parse_json(json)
26
+ JSON.parse(json)
27
+ rescue JSON::ParserError
28
+ json
29
+ end
30
+
31
+ def maybe_log_result(result)
32
+ @logger && @logger << "# => Response: #{result}"
33
+ end
34
+ end
35
+ end
@@ -0,0 +1,11 @@
1
+ module RestAPIBuilder
2
+ module UrlHelper
3
+ def full_url(url, path)
4
+ if path
5
+ File.join(url, path)
6
+ else
7
+ url
8
+ end
9
+ end
10
+ end
11
+ end
@@ -0,0 +1,15 @@
1
+ require 'webmock'
2
+ require 'rest_api_builder/url_helper'
3
+
4
+ module RestAPIBuilder
5
+ class WebMockRequestExpectationsSingleton
6
+ include WebMock::API
7
+ include RestAPIBuilder::UrlHelper
8
+
9
+ def expect_execute(base_url:, method:, path: nil)
10
+ stub_request(method, full_url(base_url, path))
11
+ end
12
+ end
13
+
14
+ WebMockRequestExpectations = WebMockRequestExpectationsSingleton.new
15
+ end
@@ -0,0 +1,18 @@
1
+ Gem::Specification.new do |s|
2
+ s.name = 'rest_api_builder'
3
+ s.version = '0.0.1'
4
+ s.summary = "A simple wrapper for rest-client"
5
+ s.description = "A simple wrapper for rest-client aiming to make creation and testing of API clients easier."
6
+ s.authors = ["Alexey D"]
7
+ s.email = 'ord.alwo@gmail.com'
8
+ s.files = Dir["LICENSE", "README.md", "rest_api_builder.gemspec", "lib/**/*"]
9
+ s.license = 'MIT'
10
+ s.homepage = 'https://github.com/alexeyds/rest_api_builder'
11
+
12
+ s.add_development_dependency('rubocop', '~> 0.8')
13
+ s.add_development_dependency('webmock', '~> 3.0')
14
+
15
+ s.add_dependency('rest-client', '~> 2.0')
16
+
17
+ s.required_ruby_version = '>= 2.4.0'
18
+ end
metadata ADDED
@@ -0,0 +1,93 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: rest_api_builder
3
+ version: !ruby/object:Gem::Version
4
+ version: 0.0.1
5
+ platform: ruby
6
+ authors:
7
+ - Alexey D
8
+ autorequire:
9
+ bindir: bin
10
+ cert_chain: []
11
+ date: 2020-07-16 00:00:00.000000000 Z
12
+ dependencies:
13
+ - !ruby/object:Gem::Dependency
14
+ name: rubocop
15
+ requirement: !ruby/object:Gem::Requirement
16
+ requirements:
17
+ - - "~>"
18
+ - !ruby/object:Gem::Version
19
+ version: '0.8'
20
+ type: :development
21
+ prerelease: false
22
+ version_requirements: !ruby/object:Gem::Requirement
23
+ requirements:
24
+ - - "~>"
25
+ - !ruby/object:Gem::Version
26
+ version: '0.8'
27
+ - !ruby/object:Gem::Dependency
28
+ name: webmock
29
+ requirement: !ruby/object:Gem::Requirement
30
+ requirements:
31
+ - - "~>"
32
+ - !ruby/object:Gem::Version
33
+ version: '3.0'
34
+ type: :development
35
+ prerelease: false
36
+ version_requirements: !ruby/object:Gem::Requirement
37
+ requirements:
38
+ - - "~>"
39
+ - !ruby/object:Gem::Version
40
+ version: '3.0'
41
+ - !ruby/object:Gem::Dependency
42
+ name: rest-client
43
+ requirement: !ruby/object:Gem::Requirement
44
+ requirements:
45
+ - - "~>"
46
+ - !ruby/object:Gem::Version
47
+ version: '2.0'
48
+ type: :runtime
49
+ prerelease: false
50
+ version_requirements: !ruby/object:Gem::Requirement
51
+ requirements:
52
+ - - "~>"
53
+ - !ruby/object:Gem::Version
54
+ version: '2.0'
55
+ description: A simple wrapper for rest-client aiming to make creation and testing
56
+ of API clients easier.
57
+ email: ord.alwo@gmail.com
58
+ executables: []
59
+ extensions: []
60
+ extra_rdoc_files: []
61
+ files:
62
+ - LICENSE
63
+ - README.md
64
+ - lib/rest_api_builder.rb
65
+ - lib/rest_api_builder/request.rb
66
+ - lib/rest_api_builder/rest_client_response_parser.rb
67
+ - lib/rest_api_builder/url_helper.rb
68
+ - lib/rest_api_builder/webmock_request_expectations.rb
69
+ - rest_api_builder.gemspec
70
+ homepage: https://github.com/alexeyds/rest_api_builder
71
+ licenses:
72
+ - MIT
73
+ metadata: {}
74
+ post_install_message:
75
+ rdoc_options: []
76
+ require_paths:
77
+ - lib
78
+ required_ruby_version: !ruby/object:Gem::Requirement
79
+ requirements:
80
+ - - ">="
81
+ - !ruby/object:Gem::Version
82
+ version: 2.4.0
83
+ required_rubygems_version: !ruby/object:Gem::Requirement
84
+ requirements:
85
+ - - ">="
86
+ - !ruby/object:Gem::Version
87
+ version: '0'
88
+ requirements: []
89
+ rubygems_version: 3.1.2
90
+ signing_key:
91
+ specification_version: 4
92
+ summary: A simple wrapper for rest-client
93
+ test_files: []