Ruby on rails Rails葡萄API版本控制
我正在尝试使用Rails 4.0.4和Grape 0.7.0为REST API创建一个框架,其行为如下: 使用特定版本调用API:Ruby on rails Rails葡萄API版本控制,ruby-on-rails,grape-api,Ruby On Rails,Grape Api,我正在尝试使用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 ht
$ 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
对于上面的文件,我只获得默认行为,无论我在curl命令中指定哪个版本。-Grape(据我所知)不允许API类指定版本字符串数组,但我认为您不需要在这里这样做。此外,您的curl语法不正确
一旦我将app/api/api_v2.rb中的version
行更改为
version 'v2', using: :header, vendor: 'acme', cascade: true
并使用-H
参数的正确语法调用curl(注意冒号代替等号):
它工作了,我更改了curl调用,并按照您所说的删除了版本数组。尽管如此,我看不到对cascade:true
语句有任何影响,但我删除了它,它也起了作用。重要的是我们在app/API/API.rb中装载API版本的顺序。
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
...
mount API::Base => '/'
...
version 'v2', using: :header, vendor: 'acme', cascade: true
$ 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"