【问题标题】:Rails Grape API versioningRails Grape API 版本控制
【发布时间】: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 命令中指定哪个版本,我都会得到默认行为。-

【问题讨论】:

    标签: ruby-on-rails grape-api


    【解决方案1】:

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

    一旦我将app/api/api_v2.rb 中的version 行更改为

    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"
    

    【讨论】:

    • 它工作,我改变了我的 curl 调用,我删除了你所说的版本数组。尽管如此,我看不到对cascade: true 语句的任何影响,但我删除了它,它也起作用了。重要的是我们在 app/api/api.rb 中挂载 API 版本的顺序。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-05-22
    • 2016-03-21
    • 2017-05-10
    • 2012-03-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多