1

我正在尝试使用 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 应用程序中得到了以下文件:

应用程序/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

应用程序/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

应用程序/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

应用程序/配置/路由.rb

...
mount API::Base => '/'
...

使用上述文件,无论我在 curl 命令中指定哪个版本,我都会得到默认行为。-

4

1 回答 1

0

Grape (据我所知)不允许 API 类指定版本字符串数组,但我认为您无论如何都不需要在这里这样做。此外,您的 curl 语法不正确。

一旦我将version线路更改app/api/api_v2.rb

version 'v2', using: :header, vendor: 'acme', cascade: true

并使用-H参数的正确语法调用 curl (注意冒号代替等号):

$ 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"
$ curl http://localhost:3000/api/a
"a-v2"
$ curl http://localhost:3000/api/b
"b-v1"
$ curl http://localhost:3000/api/c
"c-v2"
于 2014-04-20T04:56:33.980 回答