versionable_api 0.0.1

Sign up to get free protection for your applications and to get access to all the features.
data/MIT-LICENSE ADDED
@@ -0,0 +1,20 @@
1
+ Copyright 2013 Chris TenHarmsel
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.
data/README.md ADDED
@@ -0,0 +1,110 @@
1
+ # VersionableApi
2
+
3
+ VersionableApi is a small gem that helps you create versionable apis (initially in Rails).
4
+
5
+ # The Problem
6
+
7
+ The most common way to start trying to version APIs is to create URIs (and routes and controllers) that look somewhat like this:
8
+ ```
9
+ /api/v1/person.json
10
+ ```
11
+ and route that to a controller in `app/controllers/api/v1/people_controller.rb`
12
+
13
+ Then, when you want to make a change to the person API, you create:
14
+ ```
15
+ /api/v2/person.json
16
+ ```
17
+ and you create `app/controllers/api/v2/people_controller.rb`.
18
+
19
+ But do you make `Api::V2::PeopleController` inherit from `Api::V1::PeopleController`? Or do you copy/paste every method in the Version 1 controller to the Version 2 controller?
20
+
21
+ # How VersionableApi tries to solve this problem
22
+
23
+ `VersionableApi` proposes that you create tiny controllers and then put version-specific behavior in modules that are included in that controller. `VersionableApi` provides a module that does a tiny bit of magic to determine which "versioned" method gets called based on an HTTP Accept header and will look for lower versions of the methods in case a particular method on a controller hasn't revved yet.
24
+
25
+ Instead of putting the version of the API you want to call in the request URI, it's specified in the Accept Header by adding `;version=X` to one of the acceptable types. The easiest way is to specify an accept type of `*/*;version=X` (where X is the version you want).
26
+
27
+ # Maintaining backwards compatibility with clients who are already using the "old" URI style
28
+
29
+ If you're transitioning an existing API to using VersionableApi and you need to be able to handle 'old' style routes (like `/api/v2/something.json`) VersionableApi provides a simple piece of Rack middleware that can help.
30
+
31
+ The `VersionableApi::ApiVersionInterceptor` can intercept requests to the 'old' api style and massage them to fit your new style. You can include it by adding the following line inside your `config/application.rb` class:
32
+ ```
33
+ config.middleware.use "VersionableApi::ApiVersionInterceptor"
34
+ ```
35
+
36
+ By default, it will look for requests to paths that look like `/api/v#/something` and transform them into `/api/something` with `*/*;version=#` prepended to the HTTP_ACCEPT header and then forward the request on to your Rails app. You can configure most of how it behaves via initialization parameters if you don't like the defaults, for example:
37
+ ```
38
+ config.middleware.use "VersionableApi::ApiVersionInterceptor", {version_regex: /\/API\/version-(?<version>\d+)\/(?<path>.*)/}
39
+ ```
40
+ would cause it to match paths like: `/API/version-10/something` instead. See documentation in `lib/versionable_api/api_version_interceptor.rb` for details.
41
+
42
+ # Example
43
+ `PeopleController` with support for 2 versions of API
44
+ ```ruby
45
+ class Api::PeopleController < ::ApplicationController
46
+ respond_to :json
47
+ include VersionableApi::ApiVersioning
48
+ include Api::V1::People
49
+ include Api::V2::People
50
+ end
51
+ ```
52
+ The first version:
53
+ ```ruby
54
+ module Api::V1::People
55
+ def show_v1
56
+ respond_with People.first
57
+ end
58
+ def index_v1
59
+ respond_with People.all
60
+ end
61
+ end
62
+ ```
63
+
64
+ And the second version
65
+ ```ruby
66
+ module Api::V2::People
67
+ def show_v2
68
+ respond_with People.where(email: "foo@bar.com")
69
+ end
70
+ end
71
+ ```
72
+
73
+ **An explicit version 2 request comes in:**
74
+ ```
75
+ GET /api/people/1234.json {HTTP_ACCEPT: text/json;version=2}
76
+ ```
77
+ the `Api::V2::People#show_v2` method will handle the request.
78
+
79
+ **An explicit version 1 request comes in:**
80
+ ```
81
+ GET /api/people/1234.json {HTTP_ACCEPT: text/json;version=1}
82
+ ```
83
+ the `Api::V1::People#show_v1` method will handle the request.
84
+
85
+
86
+ **However, if a request comes in that looks like this:**
87
+ ```
88
+ GET /api/people.json {HTTP_ACCEPT: text/json;version=2}
89
+ ```
90
+ the request will get handled by the `Api::V1::People#index_v1` action. Even though the request specified that it's using Version 2, since there isn't an explicit Version 2 of the `index` action, control will fall back to the Version 1 version.
91
+
92
+
93
+ # How to use it
94
+ 1. Add it to your `Gemfile`:
95
+
96
+ ```
97
+ gem 'versionable_api'
98
+ ```
99
+ 2. Create API controllers that are not versioned: `Api::PeopleController` should be in `app/controllers/api/people_controller.rb`
100
+ 3. Include the `VersionableApi::ApiVersioning` module in your controller
101
+ 4. Add version identifiers to your action method names. Instead of `def index; ... end;` you do `def index_v1; ... end;`. You can put these in named modules to keep things tidy if you want, or just put them all in the base controller.
102
+ 5. Set up routes like there's no versioning:
103
+
104
+ ```
105
+ namespace :api do
106
+ resources :people
107
+ end
108
+ ```
109
+
110
+ This project rocks and uses MIT-LICENSE.
data/Rakefile ADDED
@@ -0,0 +1,34 @@
1
+ #!/usr/bin/env rake
2
+ begin
3
+ require 'bundler/setup'
4
+ rescue LoadError
5
+ puts 'You must `gem install bundler` and `bundle install` to run rake tasks'
6
+ end
7
+ begin
8
+ require 'rdoc/task'
9
+ rescue LoadError
10
+ require 'rdoc/rdoc'
11
+ require 'rake/rdoctask'
12
+ RDoc::Task = Rake::RDocTask
13
+ end
14
+
15
+ RDoc::Task.new(:rdoc) do |rdoc|
16
+ rdoc.rdoc_dir = 'rdoc'
17
+ rdoc.title = 'VersionableApi'
18
+ rdoc.options << '--line-numbers'
19
+ rdoc.rdoc_files.include('README.rdoc')
20
+ rdoc.rdoc_files.include('lib/**/*.rb')
21
+ end
22
+
23
+ Bundler::GemHelper.install_tasks
24
+
25
+ require 'rake/testtask'
26
+
27
+ Rake::TestTask.new(:test) do |t|
28
+ t.libs << 'lib'
29
+ t.libs << 'test'
30
+ t.pattern = 'test/**/*_test.rb'
31
+ t.verbose = false
32
+ end
33
+
34
+ task :default => :test
@@ -0,0 +1,48 @@
1
+ # Public: Rack Middleware for massaging URIs with the version in the path into
2
+ # bare resource URIs with the version specified in an Accept header.
3
+ module VersionableApi
4
+ class ApiVersionInterceptor
5
+
6
+ # Public: Initialize the ApiVersionInterceptor
7
+ #
8
+ # app - Next Rack middleware app in the chain
9
+ # options - Options hash with these keys:
10
+ # version_regex - Regular Expression that matches API requests in the "old"
11
+ # format, should contain two named captures:
12
+ # 1. 'version' - The version number
13
+ # 2. 'path' - The API endpoint path
14
+ # api_prefix - Prefix for resulting URIs, the API endpoint path from the matcher
15
+ # will be appended to this to build the "real" uri
16
+ # accept_header - The accept header that will have the version appended to it and
17
+ # then will be prepended to the existing Accept headers on the request
18
+ #
19
+ # Example:
20
+ # Incoming URI we want to massage: "/api/v1/thing.json"
21
+ # Resulting URI we want to handle: "/api/thing.json", Accept Header: "*/*;version=1"
22
+ #
23
+ # version_regex = /^\/api\/v(?<version>\d+)\/(?<path>.+)/
24
+ # api_prefix = "/api"
25
+ # accept_header = "*/*;version="
26
+ #
27
+ def initialize(app, options={})
28
+ options = {
29
+ version_regex: /^\/api\/v(?<version>\d+)\/(?<path>.+)/,
30
+ api_prefix: "/api",
31
+ accept_header: "*/*;version="
32
+ }.merge(options)
33
+
34
+ @app = app
35
+ @version_regex = options[:version_regex]
36
+ @api_prefix = options[:api_prefix]
37
+ @accept_header = options[:accept_header]
38
+ end
39
+
40
+ def call(env)
41
+ if m = env["PATH_INFO"].match(@version_regex)
42
+ env["PATH_INFO"] = "#{@api_prefix}/#{m[:path]}"
43
+ env["HTTP_ACCEPT"] = "#{@accept_header}#{m[:version]}, #{env['HTTP_ACCEPT']}"
44
+ end
45
+ @app.call env
46
+ end
47
+ end
48
+ end
@@ -0,0 +1,49 @@
1
+ module VersionableApi
2
+ module ApiVersioning
3
+
4
+ # Public: The default version, classes including ApiVersioning should specify
5
+ # this themselves if they don't want the default version to be 1
6
+ #
7
+ # Returns the duplicated String.
8
+ def default_version
9
+ 1
10
+ end
11
+
12
+ # Public: Returns a versioned action name based on the requested action name
13
+ # and an optional version specification on the request. If no versioned
14
+ # action matching what we think the request is trying to access is defined on
15
+ # the containing class then this will behave in one of two ways:
16
+ # 1. If #action_missing is defined, this method will return "_handle_aciton_missing"
17
+ # to stay in line with how the default Rails implementation works
18
+ # 2. If #action_missiong is not defined, then this will return nil (preserves)
19
+ # default rails behavior)
20
+ #
21
+ # action - The name of the action to look up, a String
22
+ #
23
+ # Returns a versioned action name, "_handle_action_missing", or nil
24
+ def method_for_action(action)
25
+ version = (requested_version || self.default_version || 1).to_i
26
+ method = nil
27
+ version.downto(1) do |v|
28
+ name = "#{action}_v#{v}"
29
+ method ||= self.respond_to?(name) ? name : nil
30
+ end
31
+
32
+ method ||= self.respond_to?("action_missing") ? "_handle_action_missing" : nil
33
+
34
+ end
35
+
36
+
37
+ # Public: Finds the API version requested in the request
38
+ #
39
+ # Returns the requested version, or nil if no version was specifically requested
40
+ def requested_version
41
+ accept_headers = request.headers["HTTP_ACCEPT"]
42
+ return nil if accept_headers.nil?
43
+ parts = accept_headers.split(",").map(&:strip)
44
+ requested = parts.map{|part| part.match(/version=(\d+)/)[1] if part.match(/version=\d+/)}.detect{|i| !i.nil?}
45
+ requested.to_i unless requested.nil?
46
+ end
47
+
48
+ end
49
+ end
@@ -0,0 +1,3 @@
1
+ module VersionableApi
2
+ VERSION = "0.0.1"
3
+ end
@@ -0,0 +1,4 @@
1
+ require "versionable_api/api_versioning"
2
+ require "versionable_api/api_version_interceptor"
3
+ module VersionableApi
4
+ end
@@ -0,0 +1,56 @@
1
+ require 'test_helper'
2
+
3
+ describe VersionableApi::ApiVersionInterceptor do
4
+ describe "With defaults" do
5
+ before do
6
+ @app = MiniTest::Mock.new
7
+ @test_me = VersionableApi::ApiVersionInterceptor.new(@app)
8
+ end
9
+
10
+ it "should forward the request to the next app as-is if it doesn't match the default API path setup" do
11
+ env = {"PATH_INFO" => "/something/foo.json", "HTTP_ACCEPT" => "*/*"}
12
+ @app.expect :call, true, [env]
13
+ @test_me.call(env)
14
+ @app.verify
15
+ end
16
+
17
+ it "should change an old API path to a new path with version specified in the header" do
18
+ in_env = {"PATH_INFO" => "/api/v3/foo.json", "HTTP_ACCEPT" => "*/*"}
19
+ expected_env = {"PATH_INFO" => "/api/foo.json", "HTTP_ACCEPT" => "*/*;version=3, */*"}
20
+ @app.expect :call, true, [expected_env]
21
+ @test_me.call(in_env)
22
+ @app.verify
23
+ end
24
+
25
+ it "should not modify 'new' style API requests" do
26
+ env = {"PATH_INFO" => "/api/foo.json", "HTTP_ACCEPT" => "*/*;version=3"}
27
+ @app.expect :call, true, [env]
28
+ @test_me.call(env)
29
+ @app.verify
30
+ end
31
+ end
32
+
33
+ describe "With modified options" do
34
+ before do
35
+ @app = MiniTest::Mock.new
36
+ end
37
+
38
+ it "should allow a user to specify the regular expression used to identify API requests" do
39
+ @test_me = VersionableApi::ApiVersionInterceptor.new(@app, {version_regex: /version_(?<version>\d+)\/(?<path>.+)/})
40
+ in_env = {"PATH_INFO" => "/version_3/foo.json", "HTTP_ACCEPT" => "*/*"}
41
+ expected_env = {"PATH_INFO" => "/api/foo.json", "HTTP_ACCEPT" => "*/*;version=3, */*"}
42
+ @app.expect :call, true, [expected_env]
43
+ @test_me.call(in_env)
44
+ @app.verify
45
+ end
46
+
47
+ it "should allow a user to specify old-stype API structure, new path and accept header structure" do
48
+ @test_me = VersionableApi::ApiVersionInterceptor.new(@app, {version_regex: /version_(?<version>\d+)\/(?<path>.+)/, api_prefix: "/get_data", accept_header: "*/*;v="})
49
+ in_env = {"PATH_INFO" => "/version_3/foo.json", "HTTP_ACCEPT" => "*/*"}
50
+ expected_env = {"PATH_INFO" => "/get_data/foo.json", "HTTP_ACCEPT" => "*/*;v=3, */*"}
51
+ @app.expect :call, true, [expected_env]
52
+ @test_me.call(in_env)
53
+ @app.verify
54
+ end
55
+ end
56
+ end
@@ -0,0 +1,74 @@
1
+ require 'test_helper'
2
+ require 'ostruct'
3
+
4
+ describe VersionableApi::ApiVersioning do
5
+ class Testable
6
+ include VersionableApi::ApiVersioning
7
+ attr_accessor :request
8
+ def initialize
9
+ @request = OpenStruct.new
10
+ @request.headers = {}
11
+ end
12
+ end
13
+
14
+ before do
15
+ @test_me = Testable.new
16
+ end
17
+
18
+ it "should have a default version of 1" do
19
+ assert_equal 1, @test_me.default_version
20
+ end
21
+
22
+ describe "#requested_version" do
23
+ it "should determine the requested version from the request headers" do
24
+ @test_me.request.headers["HTTP_ACCEPT"] = "*/*;version=10"
25
+ assert_equal 10, @test_me.requested_version
26
+ end
27
+
28
+ it "should return nil if no explicit version is requested" do
29
+ assert_nil @test_me.requested_version
30
+ end
31
+
32
+ it "should return nil if the version requested is non-numeric" do
33
+ @test_me.request.headers["HTTP_ACCEPT"] = "*/*;version=FOO"
34
+ assert_nil @test_me.requested_version
35
+ end
36
+ end
37
+
38
+ describe "#method_for_action" do
39
+ before do
40
+ def @test_me.show_v1; 1; end;
41
+ def @test_me.show_v2; 2; end;
42
+ def @test_me.index_v1; 1; end;
43
+ end
44
+
45
+ it "should return the default version when no version is requested" do
46
+ assert_equal "show_v1", @test_me.method_for_action("show")
47
+ end
48
+
49
+ it "should return the requested version if specified and available" do
50
+ @test_me.request.headers["HTTP_ACCEPT"] = "*/*;version=2"
51
+ assert_equal "show_v2", @test_me.method_for_action("show")
52
+ @test_me.request.headers["HTTP_ACCEPT"] = "*/*;version=1"
53
+ assert_equal "show_v1", @test_me.method_for_action("show")
54
+ end
55
+
56
+ it "should return the highest available version if the version specified is higher than the available versions" do
57
+ @test_me.request.headers["HTTP_ACCEPT"] = "*/*;version=10"
58
+ assert_equal "show_v2", @test_me.method_for_action("show")
59
+ @test_me.request.headers["HTTP_ACCEPT"] = "*/*;version=2"
60
+ assert_equal "index_v1", @test_me.method_for_action("index")
61
+ end
62
+
63
+ it "should return _handle_action_missing if #action_missing is defined and unkown action is called for" do
64
+ def @test_me.action_missing; true; end;
65
+ @test_me.request.headers["HTTP_ACCEPT"] = "*/*;version=2"
66
+ assert_equal "_handle_action_missing", @test_me.method_for_action("foobar")
67
+ end
68
+
69
+ it "should return nil if #action_missing is not defined and an unkown action is specified" do
70
+ @test_me.request.headers["HTTP_ACCEPT"] = "*/*;version=2"
71
+ assert_nil @test_me.method_for_action("foobar")
72
+ end
73
+ end
74
+ end
@@ -0,0 +1,2 @@
1
+ require 'minitest/autorun'
2
+ require 'versionable_api'
metadata ADDED
@@ -0,0 +1,74 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: versionable_api
3
+ version: !ruby/object:Gem::Version
4
+ version: 0.0.1
5
+ prerelease:
6
+ platform: ruby
7
+ authors:
8
+ - Chris TenHarmsel
9
+ autorequire:
10
+ bindir: bin
11
+ cert_chain: []
12
+ date: 2013-08-28 00:00:00.000000000 Z
13
+ dependencies:
14
+ - !ruby/object:Gem::Dependency
15
+ name: rake
16
+ requirement: !ruby/object:Gem::Requirement
17
+ none: false
18
+ requirements:
19
+ - - ! '>='
20
+ - !ruby/object:Gem::Version
21
+ version: '0'
22
+ type: :development
23
+ prerelease: false
24
+ version_requirements: !ruby/object:Gem::Requirement
25
+ none: false
26
+ requirements:
27
+ - - ! '>='
28
+ - !ruby/object:Gem::Version
29
+ version: '0'
30
+ description: Simple Gem that provides a framework for sane versionable APIs
31
+ email:
32
+ - chris.tenharmsel@centro.net
33
+ executables: []
34
+ extensions: []
35
+ extra_rdoc_files: []
36
+ files:
37
+ - lib/versionable_api/api_version_interceptor.rb
38
+ - lib/versionable_api/api_versioning.rb
39
+ - lib/versionable_api/version.rb
40
+ - lib/versionable_api.rb
41
+ - MIT-LICENSE
42
+ - Rakefile
43
+ - README.md
44
+ - test/spec/api_version_interceptor_test.rb
45
+ - test/spec/versionable_api_test.rb
46
+ - test/test_helper.rb
47
+ homepage: http://www.github.com/centro/versionable_api
48
+ licenses: []
49
+ post_install_message:
50
+ rdoc_options: []
51
+ require_paths:
52
+ - lib
53
+ required_ruby_version: !ruby/object:Gem::Requirement
54
+ none: false
55
+ requirements:
56
+ - - ! '>='
57
+ - !ruby/object:Gem::Version
58
+ version: '0'
59
+ required_rubygems_version: !ruby/object:Gem::Requirement
60
+ none: false
61
+ requirements:
62
+ - - ! '>='
63
+ - !ruby/object:Gem::Version
64
+ version: '0'
65
+ requirements: []
66
+ rubyforge_project:
67
+ rubygems_version: 1.8.23
68
+ signing_key:
69
+ specification_version: 3
70
+ summary: Versionable APIs
71
+ test_files:
72
+ - test/spec/api_version_interceptor_test.rb
73
+ - test/spec/versionable_api_test.rb
74
+ - test/test_helper.rb