【发布时间】:2014-04-20 03:15:40
【问题描述】:
我正在尝试使用 Rails 4.0.4 和 Grape 0.7.0 为 REST API 创建一个框架,使其行为如下:
使用特定版本调用 API:
$ curl -H Accept=application/vnd.acme-v1+json http://localhost:3000/api/a
“a-v1”
$ curl -H Accept=application/vnd.acme-v1+json http://localhost:3000/api/b
“b-v1”
默认调用 API:
$ curl http://localhost:3000/api/a
“a-v2”
$ curl http://localhost:3000/api/b
“b-v1”
$ curl http://localhost:3000/api/c
“c-v2”
我一直在尝试,但无法获得所需的行为。我最终在我的 Rails 应用程序中得到了以下文件:
app/api/api.rb
require 'grape'
require 'api_v1.rb'
require 'api_v2.rb'
module API
class Base < Grape::API
mount API::V2
mount API::V1
end
end
app/api/api_v1.rb
require 'grape'
module API
class V1 < Grape::API
version 'v1', using: :header, vendor: 'acme', format: :json
prefix 'api'
format :json
get :a do
"a-v1"
end
get :b do
"b-v1"
end
end
end
app/api/api_v2.rb
require 'grape'
module API
class V2 < Grape::API
version ['v2', 'v1'], using: :header, vendor: 'acme', cascade: true
prefix 'api'
format :json
get :a do
"a-v2"
end
get :c do
"c-v2"
end
end
end
app/config/routes.rb
...
mount API::Base => '/'
...
使用上述文件,无论我在 curl 命令中指定哪个版本,我都会得到默认行为。-
【问题讨论】: