关于Grape
缘起
近来,想要研究一下API编写的正确方式。
在学习gitlab源代码时,了解到其API是使用Grape编写的,恰好有想要编写API的任务,顺便研究一下如何编写RESTful的API。这年头,REST可是个时髦的词,最为一个年轻的程序员,当然是喜欢新的东西,新的思想,最新的框架,新的开放方式,新的Gem包。
下文是对Grape项目Readme文件的翻译。
目录
- What is Grape?
- Stable Release
- Project Resources
- Installation
- Basic Usage
- Mounting
- Versioning
- Describing Methods
- Parameters
- Parameter Validation and Coercion
- Headers
- Routes
- Helpers
- Parameter Documentation
- Cookies
- HTTP Status Code
- Redirecting
- Allowed Methods
- Raising Exceptions
- Exception Handling
- Logging
- API Formats
- Content-type
- API Data Formats
- RESTful Model Representations
- Authentication
- Describing and Inspecting an API
- Current Route and Endpoint
- Before and After
- Anchoring
- Writing Tests
- Reloading API Changes in Development
- Performance Monitoring
- Contributing to Grape
- Hacking on Grape
- License
- Copyright
What is Grape?
Grape是一个拥有类似REST API的Ruby微型框架。它设计运行在Rack或补充现有Web应用框架如Rails或Sinatra,提供一种简单DSL来简化RESTful APIs开发。它已经内置支持一些常见约束,包括多重格式(multiple formats), 子域/前缀约束(subdomain/prefix restriction), 内容导向(content negotiation), 版本(versioning)等。
Stable Release
You’re reading the documentation for the next release of Grape, which should be 0.9.1. Please read UPGRADING when upgrading from a previous version. The current stable release is 0.9.0.
本文档是Grape的0.9.1发布版本的,之前的发布版是0.9.0。在将grape升级到0.9.1之前,请阅读升级。
Project Resources
- Need help? Grape Google Group
- Grape Wiki
Installation
Grape是一个gem包,其安装命令如下:
gem install grape
如果使用Bundler,将其添加到Gemfile中:
gem 'grape'
然后运行bundle install
.
Basic Usage
Grape APIS是一个Rack应用程序(又是个啥玩意),通过子类化Grape::API
来实现。如下是模仿Twitter API的一个简单样例,其中展示了很多Grape的特性。
module Twitter
class API < Grape::API
# 这里是关于格式约束
version 'v1', using: :header, vendor: 'twitter'
format :json
prefix :api
# helper中定义的两个函数是关于权限认证的,需要考虑的是如何将其继承到现有的devise中。
helpers do
def current_user
@current_user ||= User.authorize!(env)
end
def authenticate!
error!('401 Unauthorized', 401) unless current_user
end
end
resource :statuses do
desc "Return a public timeline."
get :public_timeline do
Status.limit(20)
end
desc "Return a personal timeline."
get :home_timeline do
authenticate!
current_user.statuses.limit(20)
end
desc "Return a status."
params do
requires :id, type: Integer, desc: "Status id."
end
route_param :id do
get do
Status.find(params[:id])
end
end
desc "Create a status."
params do
requires :status, type: String, desc: "Your status."
end
post do
authenticate!
Status.create!({
user: current_user,
text: params[:status]
})
end
desc "Update a status."
params do
requires :id, type: String, desc: "Status ID."
requires :status, type: String, desc: "Your status."
end
put ':id' do
authenticate!
current_user.statuses.find(params[:id]).update({
user: current_user,
text: params[:status]
})
end
desc "Delete a status."
params do
requires :id, type: String, desc: "Status ID."
end
delete ':id' do
authenticate!
current_user.statuses.find(params[:id]).destroy
end
end
end
end
Mounting
Rack
The above sample creates a Rack application that can be run from a rackup config.ru
file
with rackup
:
上面的样例创建了一个Rack应用程序,可以使用rackup config.ru
运行程序,其中config.ru
中内容如下:
run Twitter::API
并且将响应如下的路由:
GET /statuses/public_timeline(.json)
GET /statuses/home_timeline(.json)
GET /statuses/:id(.json)
POST /statuses(.json)
PUT /statuses/:id(.json)
DELETE /statuses/:id(.json)
Grape will also automatically respond to HEAD and OPTIONS for all GET, and just OPTIONS for all other routes.
Grape将自动相应所有的GET请求的头部(HEAD)以及选项(OPTIONS),其他的路由仅响应选项(OPTIONS)。
Alongside Sinatra (or other frameworks)
If you wish to mount Grape alongside another Rack framework such as Sinatra, you can do so easily using
Rack::Cascade
:
如果你想要将Grape挂载到其他的Rack框架中(比如Sinatra),可以使用Rack::Cascade
:
# Example config.ru
require 'sinatra'
require 'grape'
class API < Grape::API
get :hello do
{ hello: "world" }
end
end
class Web < Sinatra::Base
get '/' do
"Hello world."
end
end
use Rack::Session::Cookie
run Rack::Cascade.new [API, Web]
Rails
Place API files into app/api
. Rails expects a subdirectory that matches the name of the Ruby module and a file name that matches the name of the class. In our example, the file name location and directory for Twitter::API
should be app/api/twitter/api.rb
.
Rails中,将API文件放置app/api
中。Rails希望子目录名可以匹配Ruby的模块名,文件名可以匹配类的名字。在上述例子中,Twitter::API
的文件名和位置因该是app/api/twitter/api.rb
。
修改application.rb
文件:
config.paths.add File.join('app', 'api'), glob: File.join('**', '*.rb')
config.autoload_paths += Dir[Rails.root.join('app', 'api', '*')]
修改config/routes
:
mount Twitter::API => '/'
Additionally, if the version of your Rails is 4.0+ and the application uses the default model layer of ActiveRecord, you will want to use the hashie_rails
gem. This gem disables the security feature of strong_params
at the model layer, allowing you the use of Grape’s own params validation instead.
此外,如果使用Rails 4.0+并且启动了ActiveRecord的默认模型层。可能需要使用hashie_rails
gem。该gem禁止了模型层strong_params
的默认安全属性,从而使用Grape自身的参数验证。
# Gemfile
gem "hashie_rails"
下文给出在开发环境中的附加代码,其启动修改API实现后重新加载。
Modules
可以将多个API实现挂载到同一个模块中,其中的模块不一定要是API的不同版本,也可以是相同API的不同组件。
class Twitter::API < Grape::API
mount Twitter::APIv1
mount Twitter::APIv2
end
You can also mount on a path, which is similar to using prefix
inside the mounted API itself.
也可以将其挂载到一个路径中,这和在API内部挂载使用前缀类似。
class Twitter::API < Grape::API
mount Twitter::APIv1 => '/v1'
end
Versioning
There are four strategies in which clients can reach your API’s endpoints: :path
,
:header
, :accept_version_header
and :param
. The default strategy is :path
.
存在四种不同的策略,使得客户端可以到达API的终端点: :path
, :header
, :accept_version_header
和:param
。老实说,不太明白为何称为四种策略。
Path
version 'v1', using: :path
使用版本策略,客户端可以在URL中传递想要版本号:
curl -H http://localhost:9292/v1/statuses/public_timeline
API的测试方法: Web中,测试API的方法存在很多中,比如POSTMan插件,RSpec,以及curl工具。其中,curl是一个非常灵活、强大的工具,可以定制HTTP头信息,User Agent,支持所有HTTP动词。难怪,原来curl是这么NB的工具啊。
Header
version 'v1', using: :header, vendor: 'twitter'
使用版本策略,客户端可以在HTTP的Accept
头部传递所需的版本,示例如下:
curl -H Accept:application/vnd.twitter-v1+json http://localhost:9292/statuses/public_timeline
默认情况下,如果没有Accept
头部,将会使用第一个匹配的版本。这中行为类似Rails中的路由。可使用:strict
选项覆盖默认行为,将其:strict
设置为true时,如果请求没提供正确的Accept
,就会返回406 Not Acceptable
错误。
提供非法的Accept
头部时,如果设置:cascade
为false时,就会返回406 Not Acceptable
错误; 否则,如果Rack找不到匹配的路由就会返回404 Not Found
错误。
HTTP Status Code
默认情况下,Grape对GET
请求返回200的状态码,POST
请求返回201的状态吗。可使用status
变量来查询并设置实际的HTTP状态码。
post do
status 202
if status == 200
# do some thing
end
end
Accept-Version Header
version 'v1', using: :accept_version_header
在使用版本策略时,客户端应该在HTTP的Accept-Version
头部包含所需的版本信息,示例如下:
curl -H "Accept-Version:v1" http://localhost:9292/statuses/public_timeline
默认情况下,如果没有提供Accept-Version
请求头提供,就使用第一个匹配的版本。其行为和Rails路由类似。可使用:strict
选项覆盖默认行为,将其:strict
设置为true时,如果请求没提供正确的Accept
,就会返回406 Not Acceptable
错误。
Param
version 'v1', using: :param
Using this versioning strategy, clients should pass the desired version as a request parameter, either in the URL query string or in the request body.
使用版本策略,客户端需要将版本信息放置在请求参数中,示例如下:
curl -H http://localhost:9292/statuses/public_timeline?apiver=v1
版本信息的请求参数的默认名为’apiver’, 但是可以使用:parameter
参数来指定。
version 'v1', using: :param, parameter: "v"
测试命令:
curl -H http://localhost:9292/statuses/public_timeline?v=v1
Describing Methods
可以在API方法和命名空间中添加一段描述。
desc "Returns your public timeline." do
detail 'more details'
params API::Entities::Status.documentation
success API::Entities::Entity
failure [[401, 'Unauthorized', "Entities::Error"]]
named 'My named route'
headers [XAuthToken: {
description: 'Valdates your identity',
required: true
},
XOptionalHeader: {
description: 'Not really needed',
required: false
}
]
end
get :public_timeline do
Status.limit(20)
end
detail
: 增强版的描述params
: 直接从Entity
中定义的参数success
: (former entity) TheEntity
to be used to present by default this routefailure
: (former http_codes) A definition of the used failure HTTP Codes and Entitiesnamed
: 辅助方法-在文档哈希中找出给定路由名的元素headers
: 使用头部的定义A definition of the used Headers
Parameters
Request parameters are available through the params
hash object. This includes GET
, POST
and PUT
parameters, along with any named parameters you specify in your route strings.
请求参数可通过params
hash对象获取。其中包含了GET
, POST
, PUT
参数,以及在路由字符串中指定的任何命名参数(比如,:id)。
get :public_timeline do
Status.order(params[:sort_by])
end
POST的请求体,PUT的表单输入、JSON数据以及XML内容类型都将自动解析成参数。
请求示例:
curl -d '{"text": "140 characters"}' 'http://localhost:9292/statuses' -H Content-Type:application/json -v
对应的Grape终端节点:
post '/statuses' do
Status.create!(text: params[:text])
end
Grape支持多个部分的POSTs和PUTs,话说,多部分的POSTs和PUTs是啥?
请求示例,其中,@image是一个Ruby示例变量,回想curl支持组合工具,irb中也可执行命令行。
curl --form image_file=@image.jpg http://localhost:9292/upload
Grape终端代码:
post "upload" do
# file in params[:image_file]
end
In the case of conflict between either of:
在引起冲突情况下,参数的优先级顺序如下,其中路由字符串(route string parameters)优先级最高:
- 路由字符串参数
GET
,POST
和PUT
参数POST
和PUT
的请求体中的内容
参数验证和强制 Parameter Validation and Coercion
You can define validations and coercion options for your parameters using a params
block.
可以在params
块定义验证和强制选项:
params do
requires :id, type: Integer
optional :text, type: String, regexp: /^[a-z]+$/
group :media do
requires :url
end
optional :audio do
requires :format, type: Symbol, values: [:mp3, :wav, :aac, :ogg], default: :mp3
end
mutually_exclusive :media, :audio # 两个参数相互排斥
end
put ':id' do
# params[:id] is an Integer
end
When a type is specified an implicit validation is done after the coercion to ensure the output type is the one declared.
类型指定是一种隐性的验证,从而强制输出类型为申明的类型。
可选参数可以具有默认值:
params do
optional :color, type: String, default: 'blue'
optional :random_number, type: Integer, default: -> { Random.rand(1..100) }
optional :non_random_number, type: Integer, default: Random.rand(1..100)
end
Note that default values will be passed through to any validation options specified.
The following example will always fail if :color
is not expliclity provided.
注意: 任何指定的验证选项都可以设置默认值。如下实例中,如果:color
没有显示指定,请求就总是返回失败。
params do
optional :color, type: String, default: 'blue', values: ['red', 'green']
end
The correct implementation is to ensure the default value passes all validations.
正确的做法是,确保默认值也要传递给所有的验证选项。
params do
optional :color, type: String, default: 'blue', values: ['blue', 'red', 'green']
end
Validation of Nested Parameters
Parameters can be nested using group
or by calling requires
or optional
with a block.
In the above example, this means params[:media][:url]
is required along with params[:id]
,
and params[:audio][:format]
is required only if params[:audio]
is present.
参数可以使用group
进行嵌套,或者以块为参数调用requires
或者optional
。例如,在上面例子中,params[:media][:url]
伴随着params[:id]
,当提供params[:audio]
时,才需要提供params[:audio][:format]
。
With a block, group
, requires
and optional
accept an additional option type
which can
be either Array
or Hash
, and defaults to Array
. Depending on the value, the nested
parameters will be treated either as values of a hash or as values of hashes in an array.
在代码块中,group
, requires
和optional
接受一个附加的type
选项,其值可以是Array
或Hash
,但默认是Array
。 根据该类型,嵌套的参数可被看作哈希中的哈希,或者数组中的哈希元素。
params do
optional :preferences, type: Array do
requires :key
requires :value
end
requires :name, type: Hash do
requires :first_name
requires :last_name
end
end
内建验证(Built-in Validators)
allow_blank
Parameters can be defined as allow_blank
, ensuring that they contain a value. By default, requires
only validates that a parameter was sent in the request, regardless its value. With allow_blank
,
empty values or whitespace only values are invalid.
参数可以定义为allow_blank
(允许为空),确保其总是包包含值。默认情况下,requires
仅仅验证参数否是包含在请求中,而不管其值。使用allow_blank
时,空值和空白被看作为非法。
allow_blank
can be combined with both requires
and optional
. If the parameter is required, it has to contain
a value. If it’s optional, it’s possible to not send it in the request, but if it’s being sent, it has to have
some value, and not an empty string/only whitespaces.
allow_blank
可以和requires
和optional
组合使用。如果提供了参数,就必须包含值。如果它是可选的,可能请求中没有提供相应的参数。一旦提供了相应的参数,就必须非空(即不是空字符串/空格)
params do
requires :username, allow_blank: false
optional :first_name, allow_blank: false
end
values
Parameters can be restricted to a specific set of values with the :values
option.
参数可以通过:values
选项设定的一组值来限定。
Default values are eagerly evaluated. Above :non_random_number
will evaluate to the same
number for each call to the endpoint of this params
block. To have the default evaluate
at calltime use a lambda, like :random_number
above.
params do
requires :status, type: Symbol, values: [:not_started, :processing, :done]
end
The :values
option can also be supplied with a Proc
to be evalutated at runtime. For example, given a status
model you may want to restrict by hashtags that you have previously defined in the HashTag
model.
:values
选项支持在运行时求值的Proc
。例如,对于给定的status模型,可能想要使用先前定义的HashTag
模型来限定。
params do
requires :hashtag, type: String, values: -> { Hashtag.all.map(&:tag) }
end
regexp
Parameters can be restricted to match a specific regular expression with the :regexp
option. If the value
is nil or does not match the regular expression an error will be returned. Note that this is true for both requires
and optional
parameters.
参数也可以通过:regexp
选项,通过匹配特定的正则表达式来限制。如果值为nil或者不能匹配正则表达式,就会返回为错误。该选项对requires
和optional
参数均有效。
params do
requires :email, regexp: /.+@.+/
end
mutually_exclusive
Parameters can be defined as mutually_exclusive
, ensuring that they aren’t present at the same time in a request.
params do
optional :beer
optional :wine
mutually_exclusive :beer, :wine
end
Multiple sets can be defined:
params do
optional :beer
optional :wine
mutually_exclusive :beer, :wine
optional :scotch
optional :aquavit
mutually_exclusive :scotch, :aquavit
end
警告: 不要对必须的参数定义互斥设置。两个互斥的必须参数,将表明params永远wuxiao,这使得API终端无效。必须参数和可选参数是互斥的,意味着可选参数总是无效的。
exactly_one_of
Parameters can be defined as ‘exactly_one_of’, ensuring that exactly one parameter gets selected.
params do
optional :beer
optional :wine
exactly_one_of :beer, :wine
end
at_least_one_of
Parameters can be defined as ‘at_least_one_of’, ensuring that at least one parameter gets selected.
params do
optional :beer
optional :wine
optional :juice
at_least_one_of :beer, :wine, :juice
end
Nested mutually_exclusive
, exactly_one_of
, at_least_one_of
All of these methods can be used at any nested level.
params do
requires :food do
optional :meat
optional :fish
optional :rice
at_least_one_of :meat, :fish, :rice
end
group :drink do
optional :beer
optional :wine
optional :juice
exactly_one_of :beer, :wine, :juice
end
optional :dessert do
optional :cake
optional :icecream
mutually_exclusive :cake, :icecream
end
end
名称空间的验证和约束(Namespace Validation and Coercion)
Namespaces allow parameter definitions and apply to every method within the namespace.
namespace :statuses do
params do
requires :user_id, type: Integer, desc: "A user ID."
end
namespace ":user_id" do
desc "Retrieve a user's status."
params do
requires :status_id, type: Integer, desc: "A status ID."
end
get ":status_id" do
User.find(params[:user_id]).statuses.find(params[:status_id])
end
end
end
The namespace
method has a number of aliases, including: group
, resource
,
resources
, and segment
. Use whichever reads the best for your API.
namespace
方法存在很多别名,包括group
, resource
,resources
和 segment
。在API中,使用读起来最顺畅的哪个。
You can conveniently define a route parameter as a namespace using route_param
.
使用route_param
选项,可以方便的将路由参数定义为名称空间。
namespace :statuses do
route_param :id do
desc "Returns all replies for a status."
get 'replies' do
Status.find(params[:id]).replies
end
desc "Returns a status."
get do
Status.find(params[:id])
end
end
end
定义验证器(Custom Validators)
class AlphaNumeric < Grape::Validations::Validator
def validate_param!(attr_name, params)
unless params[attr_name] =~ /^[[:alnum:]]+$/
raise Grape::Exceptions::Validation, params: [@scope.full_name(attr_name)], message: "must consist of alpha-numeric characters"
end
end
end
params do
requires :text, alpha_numeric: true
end
注意:上面的使用和定义的标准格式
You can also create custom classes that take parameters.
class Length < Grape::Validations::SingleOptionValidator
def validate_param!(attr_name, params)
unless params[attr_name].length <= @option
raise Grape::Exceptions::Validation, params: [@scope.full_name(attr_name)], message: "must be at the most #{@option} characters long"
end
end
end
params do
requires :text, length: 140
end
Validation Errors
Validation and coercion errors are collected and an exception of type Grape::Exceptions::ValidationErrors
is raised. If the exception goes uncaught it will respond with a status of 400 and an error message. The validation errors are grouped by parameter name and can be accessed via Grape::Exceptions::ValidationErrors#errors
.
验证和约束错误都可以被收集,然后抛出Grape::Exceptions::ValidationErrors
异常。如果异常没有被捕获,将会相应400状态码以及一个错误消息。验证错误以参数名作为分组,并且可以通过方法Grape::Exceptions::ValidationErrors#errors
来访问。
The default response from a Grape::Exceptions::ValidationErrors
is a humanly readable string, such as “beer, wine are mutually exclusive”, in the following example.
Grape::Exceptions::ValidationErrors
默认的相应格式是可读的。例如,如下的示例中,将会返回”beer, wine are mutually exclusive”这样的错误信息。
params do
optional :beer
optional :wine
optional :juice
exactly_one_of :beer, :wine, :juice
end
You can rescue a Grape::Exceptions::ValidationErrors
and respond with a custom response or turn the response into well-formatted JSON for a JSON API that separates individual parameters and the corresponding error messages. The following rescue_from
example produces [{"params":["beer","wine"],"messages":["are mutually exclusive"]}]
.
可以捕获异常Grape::Exceptions::ValidationErrors
,然后更改为特定的相应,或者将响应转换为JSON格式(即分离单个参数以及对应的错误消息)。下面的例子中,rescue_from
将会生成[{"params":["beer","wine"],"messages":["are mutually exclusive"]}]
格式的响应。
format :json
subject.rescue_from Grape::Exceptions::ValidationErrors do |e|
rack_response e.to_json, 400
end
I18n
Grape supports I18n for parameter-related error messages, but will fallback to English if translations for the default locale have not been provided. See en.yml for message keys.
Grape针对参数相关的错误详细支持I18n,但是如果对应的本土化的文件没有提供,就会回退为英语。更多键信息参考en.yml。
Headers
Request headers are available through the headers
helper or from env
in their original form.
请求头部可以通过headers
头部获取,或从env
获取其原本形式。
get do
error!('Unauthorized', 401) unless headers['Secret-Password'] == 'swordfish'
end
get do
error!('Unauthorized', 401) unless env['HTTP_SECRET_PASSWORD'] == 'swordfish'
end
You can set a response header with header
inside an API.
可以在API中,以header
参数设置响应头。
header 'X-Robots-Tag', 'noindex'
When raising error!
, pass additional headers as arguments.
当error!
抛出异常时,传递附加的头作为参数。
error! 'Unauthorized', 401, 'X-Error-Detail' => 'Invalid token.'
Routes
Optionally, you can define requirements for your named route parameters using regular expressions on namespace or endpoint. The route will match only if all requirements are met.
可选的,可以对命名路由参数使用正则表达式,从而定义相应的要求。路由将仅匹配那些满足要求的相应。
get ':id', requirements: { id: /[0-9]*/ } do
Status.find(params[:id])
end
namespace :outer, requirements: { id: /[0-9]*/ } do
get :id do
end
get ":id/edit" do
end
end
Helpers
You can define helper methods that your endpoints can use with the helpers
macro by either giving a block or a module.
将代码块或模块传递给helpers
宏,从而对endpoint定义辅助方法。
module StatusHelpers
def user_info(user)
"#{user} has statused #{user.statuses} status(s)"
end
end
class API < Grape::API
# define helpers with a block
helpers do
def current_user
User.find(params[:user_id])
end
end
# or mix in a module
helpers StatusHelpers
get 'info' do
# helpers available in your endpoint and filters
user_info(current_user)
end
end
You can define reusable params
using helpers
.
也可以通过helpers
定义可重用的params
。
class API < Grape::API
helpers do
params :pagination do
optional :page, type: Integer
optional :per_page, type: Integer
end
end
desc "Get collection"
params do
use :pagination # aliases: includes, use_scope
end
get do
Collection.page(params[:page]).per(params[:per_page])
end
end
You can also define reusable params
using shared helpers.
使用共享帮助方法,可以定义可重用的params
。
module SharedParams
extend Grape::API::Helpers
params :period do
optional :start_date
optional :end_date
end
params :pagination do
optional :page, type: Integer
optional :per_page, type: Integer
end
end
class API < Grape::API
helpers SharedParams
desc "Get collection."
params do
use :period, :pagination
end
get do
Collection
.from(params[:start_date])
.to(params[:end_date])
.page(params[:page])
.per(params[:per_page])
end
end
Helpers support blocks that can help set default values. The following API can return a collection sorted by id
or created_at
in asc
or desc
order.
Helpers支持可以设置默认值的块。如下的API将返回以id
或created_at
排序,或升序或降序的集合。
module SharedParams
extend Grape::API::Helpers
params :order do |options|
optional :order_by, type:Symbol, values:options[:order_by], default:options[:default_order_by]
optional :order, type:Symbol, values:%i(asc desc), default:options[:default_order]
end
end
class API < Grape::API
helpers SharedParams
desc "Get a sorted collection."
params do
use :order, order_by:%i(id created_at), default_order_by: :created_at, default_order: :asc
end
get do
Collection.send(params[:order], params[:order_by])
end
end
Parameter Documentation
使用documentation
哈希,可以添加附加的文档到params
对象中。
params do
optional :first_name, type: String, documentation: { example: 'Jim' }
requires :last_name, type: String, documentation: { example: 'Smith' }
end
Cookies
通过cookies方法,可以方便的获取,设置,删除cookies。
class API < Grape::API
get 'status_count' do
cookies[:status_count] ||= 0
cookies[:status_count] += 1
{ status_count: cookies[:status_count] }
end
delete 'status_count' do
{ status_count: cookies.delete(:status_count) }
end
end
使用基于哈希的语法,可以同时设置多个值。
cookies[:status_count] = {
value: 0,
expires: Time.tomorrow,
domain: '.twitter.com',
path: '/'
}
cookies[:status_count][:value] +=1
Delete a cookie with delete
.
cookies.delete :status_count
Specify an optional path.
cookies.delete :status_count, path: '/'
Redirecting
You can redirect to a new url temporarily (302) or permanently (301).
redirect
可以临时重定向到一个新的URL(302),或者永久的重定向到一个新的URL(301)。
redirect '/statuses'
redirect '/statuses', permanent: true
Allowed Methods
当为某个资源添加GET
路由时,HEAD
路由也会默认自动添加。可以通过do_not_route_head!
方法禁止该行为。
class API < Grape::API
do_not_route_head!
get '/example' do
# only responds to GET
end
end
当为资源添加路由时,路由的OPTIONS
方法也会自动添加。OPTIONS请求的相应将会包含所列出所有支持方法的Allow
头部。
class API < Grape::API
get '/rt_count' do
{ rt_count: current_user.rt_count }
end
params do
requires :value, type: Integer, desc: 'Value to add to the rt count.'
end
put '/rt_count' do
current_user.rt_count += params[:value].to_i
{ rt_count: current_user.rt_count }
end
end
curl -v -X OPTIONS http://localhost:3000/rt_count
> OPTIONS /rt_count HTTP/1.1
>
< HTTP/1.1 204 No Content
< Allow: OPTIONS, GET, PUT
同样,上述行为可以通过do_not_route_options!
方法禁止。
If a request for a resource is made with an unsupported HTTP method, an HTTP 405 (Method Not Allowed) response will be returned.
如果使用不支持的HTTP方法发送请求,则会返回HTTP 405(方法未找到)的响应。
curl -X DELETE -v http://localhost:3000/rt_count/
> DELETE /rt_count/ HTTP/1.1
> Host: localhost:3000
>
< HTTP/1.1 405 Method Not Allowed
< Allow: OPTIONS, GET, PUT
Raising Exceptions
使用error!
方法抛出错误,可以终端API方法的执行。
error! 'Access Denied', 401
You can also return JSON formatted objects by raising error! and passing a hash instead of a message.
抛出异常时,传递给error!方法一组哈希参数,可以返回JSON格式的对象。
error!({ error: "unexpected error", detail: "missing widget" }, 500)
You can present documented errors with a Grape entity using the the grape-entity gem.
使用grape-entity gem 包,可以Grape entity来呈现文档化的错误。
module API
class Error < Grape::Entity
expose :code
expose :message
end
end
The following example specifies the entity to use in the http_codes
definition.
下面的例子中,实体使用了http_codes
定义中的实体。
desc 'My Route' do
failure [[408, 'Unauthorized', API::Error]]
end
error!({ message: 'Unauthorized' }, 408)
The following example specifies the presented entity explicitly in the error message.
desc 'My Route' do
failure [[408, 'Unauthorized']]
end
error!({ message: 'Unauthorized', with: API::Error }, 408)
Default Error HTTP Status Code
By default Grape returns a 500 status code from error!
. You can change this with default_error_status
.
默认情况下,Grape中error!
方法返回500的状态码。可以通过default_error_status
选项修改默认行为。
class API < Grape::API
default_error_status 400
get '/example' do
error! "This should have http status code 400"
end
end
Handling 404
For Grape to handle all the 404s for your API, it can be useful to use a catch-all. In its simplest form, it can be like:
Grape自动为API处理所有的404请求,使用catch-all非常有用。其最简形式如下:
route :any, '*path' do
error! # or something else
end
It is very crucial to define this endpoint at the very end of your API, as it literally accepts every request.
在API最后定义这么一段代码非常有用,它确实可以接受每一个请求。
异常处理(Exception Handling)
Grape can be told to rescue all exceptions and return them in the API format.
Grape可以处理所有异常并以API形式返回。
class Twitter::API < Grape::API
rescue_from :all
end
也可以指定处理特定的异常。
class Twitter::API < Grape::API
rescue_from ArgumentError, UserDefinedError
end
上述情况下,UserDefinedError
必须继承自StandardError
。其错误的格式要匹配请求的格式,具体参考下面的”Content-Types”。
Custom error formatters for existing and additional types can be defined with a proc.
可以在proc中为已存的或附加的类型定制错误格式化器。
class Twitter::API < Grape::API
error_formatter :txt, lambda { |message, backtrace, options, env|
"error: #{message} from #{backtrace}"
}
end
除了proc,也可使用module或class。
module CustomFormatter
def self.call(message, backtrace, options, env)
{ message: message, backtrace: backtrace }
end
end
class Twitter::API < Grape::API
error_formatter :custom, CustomFormatter
end
可以在代码块中捕获所有的异常。error_response
包装方法将自动设置默认的错误代码和内容类型。
class Twitter::API < Grape::API
rescue_from :all do |e|
error_response({ message: "rescued from #{e.class.name}" })
end
end
You can also rescue specific exceptions with a code block and handle the Rack response at the lowest level.
也可以在代码块中捕获特定类型的异常,然后在低层次处理Rack的响应(response)。
class Twitter::API < Grape::API
rescue_from :all do |e|
Rack::Response.new([ e.message ], 500, { "Content-type" => "text/error" }).finish
end
end
或者捕获特定的异常:
class Twitter::API < Grape::API
rescue_from ArgumentError do |e|
Rack::Response.new([ "ArgumentError: #{e.message}" ], 500).finish
end
rescue_from NotImplementedError do |e|
Rack::Response.new([ "NotImplementedError: #{e.message}" ], 500).finish
end
end
默认情况下,rescue_from
将会捕获所有列出的异常及其子类。
Assume you have the following exception classes defined.
module APIErrors
class ParentError < StandardError; end
class ChildError < ParentError; end
end
Then the following rescue_from
clause will rescue exceptions of type APIErrors::ParentError
and its subclasses (in this case APIErrors::ChildError
).
rescue_from APIErrors::ParentError do |e|
Rack::Response.new({
error: "#{e.class} error",
message: e.message
}.to_json, e.status).finish
end
如果只想捕获基类异常,可设置rescue_subclasses: false
。如下的代码将仅捕获RuntimeError
类型的异常,但不包括其子类。
rescue_from RuntimeError, rescue_subclasses: false do |e|
Rack::Response.new({
status: e.status,
message: e.message,
errors: e.errors
}.to_json, e.status).finish
end
Rails 3.x
When mounted inside containers, such as Rails 3.x, errors like “404 Not Found” or
“406 Not Acceptable” will likely be handled and rendered by Rails handlers. For instance,
accessing a nonexistent route “/api/foo” raises a 404, which inside rails will ultimately
be translated to an ActionController::RoutingError
, which most likely will get rendered
to a HTML error page.
当将grape挂载到容器中时,比如,Rails 3.x。诸如”404 Not Found”或”406 Not Acceptable”这样的错误,将会被Rails处理器处理和渲染。例如,访问不存在的路由”/api/foo”将会抛出404错误,Rails内部将会被转换成ActionController::RoutingError
,然后准备渲染HTML的错误页面。
Most APIs will enjoy preventing downstream handlers from handling errors. You may set the
:cascade
option to false
for the entire API or separately on specific version
definitions,
which will remove the X-Cascade: true
header from API responses.
大多数的APIs
cascade false
version 'v1', using: :header, vendor: 'twitter', cascade: false
Logging
Grape::API
provides a logger
method which by default will return an instance of the Logger
class from Ruby’s standard library.
To log messages from within an endpoint, you need to define a helper to make the logger available in the endpoint context.
class API < Grape::API
helpers do
def logger
API.logger
end
end
post '/statuses' do
# ...
logger.info "#{current_user} has statused"
end
end
You can also set your own logger.
class MyLogger
def warning(message)
puts "this is a warning: #{message}"
end
end
class API < Grape::API
logger MyLogger.new
helpers do
def logger
API.logger
end
end
get '/statuses' do
logger.warning "#{current_user} has statused"
end
end
API Formats
By default, Grape supports XML, JSON, BINARY, and TXT content-types. The default format is :txt
.
默认情况下,Grape支持_XML_, JSON, BINARY 和 TXT 内容类型。默认格式是:txt
。
Serialization takes place automatically. For example, you do not have to call to_json
in each JSON API implementation.
序列化将自动运行。比如,不需要为每个JSON格式的API实现调用to_json
。
Your API can declare which types to support by using content_type
. Response format is determined by the request’s extension, an explicit format
parameter in the query string, or Accept
header.
通过content_type
申明API的支持的类型。响应格式取决于请求扩展名,查询参数中format
参数或者Accept
头。
The following API will only respond to the JSON content-type and will not parse any other input than application/json
,
application/x-www-form-urlencoded
, multipart/form-data
, multipart/related
and multipart/mixed
. All other requests
will fail with an HTTP 406 error code.
如下的API只响应JSON格式的内容,并且不解析来自application/json
,application/x-www-form-urlencoded
, multipart/form-data
, multipart/related
和multipart/mixed
的输入。所有其他的请求都会失败,并且返回HTTP 406错误码。
class Twitter::API < Grape::API
format :json
end
When the content-type is omitted, Grape will return a 406 error code unless default_format
is specified.
The following API will try to parse any data without a content-type using a JSON parser.
如果content-type被忽略,并且default_format
又没指定,Grape将返回406错误。如下的API将使用JSON解析器解析任何不包含content-type的数据。
class Twitter::API < Grape::API
format :json
default_format :json
end
如果组合rescue_from :all
和format
,错误将使用相同的格式渲染。如果不需要这个行为,使用default_error_formatter
来设置错误格式。
class Twitter::API < Grape::API
format :json
content_type :txt, "text/plain"
default_error_formatter :txt
end
Custom formatters for existing and additional types can be defined with a proc.
可以在proc中为已存的或附加的类型定制格式。
class Twitter::API < Grape::API
content_type :xls, "application/vnd.ms-excel"
formatter :xls, lambda { |object, env| object.to_xls }
end
You can also use a module or class.
当然,也可以使用模块或类,仔细理解一下这里的意思,模块、类以及proc的共同的特点。
module XlsFormatter
def self.call(object, env)
object.to_xls
end
end
class Twitter::API < Grape::API
content_type :xls, "application/vnd.ms-excel"
formatter :xls, XlsFormatter
end
一些内建的格式:
:json
: use object’sto_json
when available, otherwise callMultiJson.dump
:xml
: use object’sto_xml
when available, usually viaMultiXml
, otherwise callto_s
:txt
: use object’sto_txt
when available, otherwiseto_s
:serializable_hash
: use object’sserializable_hash
when available, otherwise fallback to:json
:binary
Use default_format
to set the fallback format when the format could not be determined from the Accept
header. See below for the order for choosing the API format.
当格式不能由Accept
决定时,使用default_format
设置回退的格式。如下给出选择API格式顺序:
class Twitter::API < Grape::API
default_format :json
end
The order for choosing the format is the following.
选择格式的顺序:
- 文件扩展名: Use the file extension, if specified. If the file is .json, choose the JSON format.
- 查询字符串中的
format
参数: Use the value of theformat
parameter in the query string, if specified. format
选项设置格式集合: Use the format set by theformat
option, if specified.Accept
头部指定的类型: Attempt to find an acceptable format from theAccept
header.default_format
选项指定类型: Use the default format, if specified by thedefault_format
option.- 默认为
:txt
.
可以在API中,显式设置env['api.format']
,从而覆盖上述过程。例如,下面的API将允许你上传任意文件,并以正确的MIME类型,将其内容返回为附件。
class Twitter::API < Grape::API
post "attachment" do
filename = params[:file][:filename]
content_type MIME::Types.type_for(filename)[0].to_s
env['api.format'] = :binary # there's no formatter for :binary, data will be returned "as is"
header "Content-Disposition", "attachment; filename*=UTF-8''#{URI.escape(filename)}"
params[:file][:tempfile].read
end
end
JSONP
Grape supports JSONP via Rack::JSONP, part of the
rack-contrib gem. Add rack-contrib
to your Gemfile
.
Grape通过Rack::JSONP支持JSONP。其中,Rack::JSONP
是rack-contribgem包的一部分。这需要将rack-contrib
添加到Gemfile
中。
require 'rack/contrib'
class API < Grape::API
use Rack::JSONP
format :json
get '/' do
'Hello World'
end
end
关于JSONP(JSON with Padding): Ajax的数据交互的核心问题: 交换格式和跨域请求的问题。JSON是数据交换格式,JSONP是非官方数据交互协议。Ajax跨域请求存在无权限的问题,具有src属性标签不存在跨域的问题(比如,script),使用js包装JSON数据。JSONP的要点: 允许用户传递一个callback参数给服务端,然后服务端返回数据时将callback参数作为函数名来包裹住JSON数据,可以随意定制函数自动处理返回数据。参考自:说说JSON和JSONP
ajax和jsonp是两码事: ajax的核心是通过XmlHttpRequest获取非本页内容,而jsonp的核心则是动态添加
CORS
Grape supports CORS via Rack::CORS, part of the
rack-cors gem. Add rack-cors
to your Gemfile
,
then use the middleware in your config.ru file.
Grape通过Rack::CORS支持CORS,Rack::CORS
是rack-cors gem包的一部分。将rack-cors
添加到Gemfile
文件中,然后在config.ru
文件中使用该中间件。
require 'rack/cors'
use Rack::Cors do
allow do
origins '*'
resource '*', headers: :any, methods: :get
end
end
run Twitter::API
CORS:全称Cross-Origin Resource Sharing(跨域资源共享)。原因: 原本Ajax(XMLHttpRequest)是禁止CORS, CORS是XMLHttpRequest Level 2功能。JSONP也可以解决CORS的问题。
CORS相关的资料:
Content-type
Content-type
(内容类型)由格式器设置的。可以通过设置Content-Type
头部,从而在运行时覆盖内容类型的响应。
class API < Grape::API
get '/home_timeline_js' do
content_type "application/javascript"
"var statuses = ...;"
end
end
注意: ruby中的头部的表示和HTTP请求中的表示似乎有些不同,小写+改-为_ 。
API Data Formats
Grape accepts and parses input data sent with the POST and PUT methods as described in the Parameters
section above. It also supports custom data formats. You must declare additional content-types via
content_type
and optionally supply a parser via parser
unless a parser is already available within
Grape to enable a custom format. Such a parser can be a function or a class.
Grape接受并解析以POST和PUT方法发送的输入数据,具体内容在上面的Parameters
章节中进行介绍。Grape同样接受定制化的数据格式,即可通过content_type
申明附加的内容类型,并且可通过parser
选项设置相应解析器(除非Grape已包含了对应的内容类型的解析器)。解析器一般是一个函数或类。
存在解析器时,解析参数通过env['api.request.body']
访问; 不存在解析器时,可通过env['api.request.input']
访问。
The following example is a trivial parser that will assign any input with the “text/custom” content-type
to :value
. The parameter will be available via params[:value]
inside the API call.
如下的例子是一个典型的解析器,并且可以赋值给任意:value
为”text/custom”类型的输入数据。参数在API 调用中,参数可以通过params[:value]
进行访问。
module CustomParser
def self.call(object, env)
{ value: object.to_s }
end
end
content_type :txt, "text/plain"
content_type :custom, "text/custom"
parser :custom, CustomParser
put "value" do
params[:value]
end
可以按照如下的方式调用API:
curl -X PUT -d 'data' 'http://localhost:9292/value' -H Content-Type:text/custom -v
You can disable parsing for a content-type with nil
. For example, parser :json, nil
will disable JSON parsing altogether. The request data is then available as-is in env['api.request.body']
.
可以精致解析带有nil
的内容类型(content-type)。例如,parser :json, nil
将会禁止空内容的JSON的解析。请求数据可以在env['api.request.body']
中获取。
RESTful Model Representations
Grape supports a range of ways to present your data with some help from a generic present
method,
which accepts two arguments: the object to be presented and the options associated with it. The options
hash may include :with
, which defines the entity to expose.
Grape的present
方法支持很多展现数据的方法。present
方法接受两个参数: 呈现的对象以及关联的选项。选项hash参数包含在:with
中,其中定义了显示的实体。
Grape Entities
Add the grape-entity gem to your Gemfile. Please refer to the grape-entity documentation for more details.
将grape-entitygem包添加到Gemfile中,然后,参考其文档grape-entity documentation。
The following example exposes statuses.
下面的例子揭示了状态:
module API
module Entities
class Status < Grape::Entity
expose :user_name
expose :text, documentation: { type: "string", desc: "Status update text." }
expose :ip, if: { type: :full }
expose :user_type, :user_id, if: lambda { |status, options| status.user.public? }
expose :digest { |status, options| Digest::MD5.hexdigest(status.txt) }
expose :replies, using: API::Status, as: :replies
end
end
class Statuses < Grape::API
version 'v1'
desc 'Statuses index' do
params: API::Entities::Status.documentation
end
get '/statuses' do
statuses = Status.all
type = current_user.admin? ? :full : :default
present statuses, with: API::Entities::Status, type: type
end
end
end
可以在参数块中设置using: Entity.documentation
,从而直接使用实体文档。
module API
class Statuses < Grape::API
version 'v1'
desc 'Create a status'
params do
requires :all, except: [:ip], using: API::Entities::Status.documentation.except(:id)
end
post '/status' do
Status.create! params
end
end
end
You can present with multiple entities using an optional Symbol argument.
可以使用可选的符号参数显示多个实体。
get '/statuses' do
statuses = Status.all.page(1).per(20)
present :total_page, 10
present :per_page, 20
present :statuses, statuses, with: API::Entities::Status
end
响应结果如下:
{
total_page: 10,
per_page: 20,
statuses: []
}
In addition to separately organizing entities, it may be useful to put them as namespaced classes underneath the model they represent.
为了分别组织实体,可将其设置为命名空间类下的模型。
class Status
def entity
Entity.new(self)
end
class Entity < Grape::Entity
expose :text, :user_id
end
end
If you organize your entities this way, Grape will automatically detect the Entity
class and
use it to present your models. In this example, if you added present Status.new
to your endpoint,
Grape will automatically detect that there is a Status::Entity
class and use that as the
representative entity. This can still be overridden by using the :with
option or an explicit
represents
call.
超媒体和Roar(Hypermedia and Roar)
You can use Roar to render HAL or Collection+JSON with the help of grape-roar, which defines a custom JSON formatter and enables presenting entities with Grape’s present
keyword.
可以使用Roar来渲染HAL,或使用grape-roar渲染集合+JSON。其中,定义了一个定制的JSON格式器,并使用Grape的present
关键字来呈现实体。
Rabl
You can use Rabl templates with the help of the grape-rabl gem, which defines a custom Grape Rabl formatter.
Active Model Serializers
You can use Active Model Serializers serializers with the help of the grape-active_model_serializers gem, which defines a custom Grape AMS formatter.
授权(Authentication)
Basic and Digest Auth
Grape has built-in Basic and Digest authentication (the given block
is executed in the context of the current Endpoint
). Authentication
applies to the current namespace and any children, but not parents.
http_basic do |username, password|
# verify user's password here
{ 'test' => 'password1' }[username] == password
end
http_digest({ realm: 'Test Api', opaque: 'app secret' }) do |username|
# lookup the user's password here
{ 'user1' => 'password1' }[username]
end
Register custom middleware for authentication
Grape can use custom Middleware for authentication. How to implement these
Middleware have a look at Rack::Auth::Basic
or similar implementations.
可通过定制化的中间件来实现授权。关于中间件如何实现,可以参考Rack::Auth::Basic
或者类似的实现。
为了注册一个中间件,需要如下的这些选项:
label
- the name for your authenticator to use it laterMiddlewareClass
- the MiddlewareClass to use for authenticationoption_lookup_proc
- A Proc with one Argument to lookup the options at runtime (return value is anArray
as Paramter for the Middleware).
Example:
Grape::Middleware::Auth::Strategies.add(:my_auth, AuthMiddleware, ->(options) { [options[:realm]] } )
auth :my_auth ,{ real: 'Test Api'} do |credentials|
# lookup the user's password here
{ 'user1' => 'password1' }[username]
end
Use warden-oauth2 or rack-oauth2 for OAuth2 support.
使用warden-oauth2或者rack-oauth2来获取OAuth2的支持。
Describing and Inspecting an API
Grape路由可在运行时反射,这在生成文档的时候非常的有用。
Grape探索API版本数组,并编译路由。每个路由都包含 route_prefix
, route_version
, route_namespace
, route_method
, route_path
和route_params
。API中的描述以及可选的hash中包含的任意数目的键值对可以通过动态生成的route_[name]
函数进行访问。
TwitterAPI::versions # yields [ 'v1', 'v2' ]
TwitterAPI::routes # yields an array of Grape::Route objects
TwitterAPI::routes[0].route_version # yields 'v1'
TwitterAPI::routes[0].route_description # etc.
当前路由和终端(Current Route and Endpoint)
It’s possible to retrieve the information about the current route from within an API
call with route
.
对API调用设置route
参数,可以检索当前路由中的信息。
class MyAPI < Grape::API
desc "Returns a description of a parameter."
params do
requires :id, type: Integer, desc: "Identity."
end
get "params/:id" do
route.route_params[params[:id]] # yields the parameter description
end
end
The current endpoint responding to the request is self
within the API block
or env['api.endpoint']
elsewhere. The endpoint has some interesting properties,
such as source
which gives you access to the original code block of the API
implementation. This can be particularly useful for building a logger middleware.
响应请求的当前endpoint对象是在API块或env['api.endpoint']
中的self
对象。 endpoint存在一些有趣的特性,比如source
属性-可以访问API实现的原始代码。这在构建记录中间件时非常的有用。
class ApiLogger < Grape::Middleware::Base
def before
file = env['api.endpoint'].source.source_location[0]
line = env['api.endpoint'].source.source_location[1]
logger.debug "[api] #{file}:#{line}"
end
end
Before and After
Blocks can be executed before or after every API call, using before
, after
,
before_validation
and after_validation
.
使用before
, after
,before_validation
和after_validation
代码块可在每个API调用的之前或之后执行。
Before and after callbacks execute in the following order:
Before和after回调函数执行顺序如下:
before
before_validation
- validations
after_validation
- the API call
after
当且仅当验证成狗之后,4,5,6步才会执行。
E.g. using before
:
before do
header "X-Robots-Tag", "noindex"
end
这里感觉有点类似Rails中的验证,回调之类的概念。语法上也很类似,可以使用代码块或者类及模块的定义。
The block applies to every API call within and below the current namespace:
应用到每个调用API中的代码块都位于如下的命名空间中, 具体感觉上就是嵌套名称空间而已。
class MyAPI < Grape::API
get '/' do
"root - #{@blah}"
end
namespace :foo do
before do
@blah = 'blah'
end
get '/' do
"root - foo - #{@blah}"
end
namespace :bar do
get '/' do
"root - foo - bar - #{@blah}"
end
end
end
end
具体的行为如下:
GET / # 'root - '
GET /foo # 'root - foo - blah'
GET /foo/bar # 'root - foo - bar - blah'
Params on a namespace
(or whatever alias you are using) also work when using
before_validation
or after_validation
:
当使用before_validation
或者after_validation
时,这对namespace
(或其其他的别名)的参数也会启作用:
class MyAPI < Grape::API
params do
requires :blah, type: Integer
end
resource ':blah' do
after_validation do
# if we reach this point validations will have passed
@blah = declared(params, include_missing: false)[:blah]
end
get '/' do
@blah.class
end
end
end
The behaviour is then:
GET /123 # 'Fixnum'
GET /foo # 400 error - 'blah is invalid'
锚定(Anchoring)
Grape默认锚定(anchoring)所有的请求路由,这意味着请求URL必须要从头到尾进行匹配,直到返回404 Not Found
。但是,有时,这不是我们想要的,因为API调用的返回并不总是可以预计的。由于Rack-mount默认从头到尾锚定请求。Ralis通过在路由中使用anchor: false
选项解决这个问题。Grape中,只要方法定义了,也就使用anchor: false
选项的。
例如,但API需要获取URL中的一部分是,实例如下
class TwitterAPI < Grape::API
namespace :statuses do
get '/(*:status)', anchor: false do
end
end
end
This will match all paths starting with ‘/statuses/’. There is one caveat though:
the params[:status]
parameter only holds the first part of the request url.
Luckily this can be circumvented by using the described above syntax for path
specification and using the PATH_INFO
Rack environment variable, using
env["PATH_INFO"]
. This will hold everything that comes after the ‘/statuses/’
part.
Writing Tests
You can test a Grape API with RSpec by making HTTP requests and examining the response.
可以使用RSpec设置HTTP请求,然后检查响应。curl也是可以设置HTTP请求的。
Writing Tests with Rack
使用了rack-test
,并且,将API定义为app
,测试示例如下:
require 'spec_helper'
describe Twitter::API do
include Rack::Test::Methods
def app
Twitter::API
end
describe Twitter::API do
describe "GET /api/statuses/public_timeline" do
it "returns an empty array of statuses" do
get "/api/statuses/public_timeline"
expect(last_response.status).to eq(200)
expect(JSON.parse(last_response.body)).to eq []
end
end
describe "GET /api/statuses/:id" do
it "returns a status by id" do
status = Status.create!
get "/api/statuses/#{status.id}"
expect(last_response.body).to eq status.to_json
end
end
end
end
Writing Tests with Rails
describe Twitter::API do
describe "GET /api/statuses/public_timeline" do
it "returns an empty array of statuses" do
get "/api/statuses/public_timeline"
expect(response.status).to eq(200)
expect(JSON.parse(response.body)).to eq []
end
end
describe "GET /api/statuses/:id" do
it "returns a status by id" do
status = Status.create!
get "/api/statuses/#{status.id}"
expect(response.body).to eq status.to_json
end
end
end
In Rails, HTTP request tests would go into the spec/requests
group. You may want your API code to go into
app/api
- you can match that layout under spec
by adding the following in spec/spec_helper.rb
.
在Rails中,HTTP请求测试将放置到spec/requests
中。你可能希望你的API代码放置到app/api
中,可以匹配位于spec
下的布局,然后在spec/spec_helper.rb
添加如下的代码:
RSpec.configure do |config|
config.include RSpec::Rails::RequestExampleGroup, type: :request, file_path: /spec\/api/
end
辅助方法的插桩(Stubbing Helpers)
Because helpers are mixed in based on the context when an endpoint is defined, it can
be difficult to stub or mock them for testing. The Grape::Endpoint.before_each
method
can help by allowing you to define behavior on the endpoint that will run before every
request.
由于辅助方法混合了endpoint定义的代码环境,很难插桩或模拟。Grape::Endpoint.before_each
方法可以模拟插桩辅助方法。
describe 'an endpoint that needs helpers stubbed' do
before do
Grape::Endpoint.before_each do |endpoint|
endpoint.stub(:helper_name).and_return('desired_value')
end
end
after do
Grape::Endpoint.before_each nil
end
it 'should properly stub the helper' do
# ...
end
end
Reloading API Changes in Development
Rails 3.x
Add API paths to config/application.rb
.
添加API路由到config/application.rb
中:
# Auto-load API and its subdirectories
config.paths.add File.join("app", "api"), glob: File.join("**", "*.rb")
config.autoload_paths += Dir[Rails.root.join("app", "api", "*")]
创建config/initializers/reload_api.rb
文件:
if Rails.env.development?
ActiveSupport::Dependencies.explicitly_unloadable_constants << "Twitter::API"
api_files = Dir[Rails.root.join('app', 'api', '**', '*.rb')]
api_reloader = ActiveSupport::FileUpdateChecker.new(api_files) do
Rails.application.reload_routes!
end
ActionDispatch::Callbacks.to_prepare do
api_reloader.execute_if_updated
end
end
See StackOverflow #3282655 for more information.
性能监视(Performance Monitoring)
Grape integrates with NewRelic via the newrelic-grape gem, and with Librato Metrics with the grape-librato gem.
Grape通过newrelic-grape gem包集成NewRelic,并且通过grape-librato gem包使用Librato Metrics。
关于Librato Metrics,好像最近流行什么度量驱动开发,新的名词层出不穷,TDD, BDD, MDD还有搞笑的PDD(短裤驱动开发)。
Contributing to Grape
Grape is work of hundreds of contributors. You’re encouraged to submit pull requests, propose features and discuss issues.
See CONTRIBUTING.
Hacking on Grape
You can start hacking on Grape on Nitrous.IO in a matter of seconds:
这里,接触到了一个有趣的东西,https://www.nitrous.io/,全特性的web IDE,感觉模式挺不错的,无缝的云端开发环境。
License
MIT License. See LICENSE for details.
后记
看完过后,果然,感觉没获得什么特别的认识。果然,光看不练没什么效果。
傲娇的使用Disqus