Grape简介
什么是Grape
Grape是Ruby中的一个类REST API框架,被设计用于运行在Rack上或弥补已有的web应用框架(比如Rails或者Sinatra),Grape提供了一个简单的DSL用于方便的开发RESTful APIs。Grape支持common conventions,包括多种格式,子域/前缀限制,内容协商,版本控制等。
安装
通过gem安装:
gem install grape
基本用法
你的应用一般要继承自Grape::API,下面的例子暂时了Grape中常用的一些特性:
#config.ru 内容
require "grape"
module Twitter
class API < Grape::API
version 'v1', using: :header, vendor: 'twitter'
format :json
prefix :api
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
run Twitter::API
安装
Rack
上面的例子创建了一个简单的Rack应用,将上面的内容放在config.ru文件中,通过如下命令启动:
rackup -o 0.0.0.0
在我的环境中直接执行rackup之后,在其他机器上无法访问
现在可以访问如下路径:
GET /api/statuses/public_timeline
GET /api/statuses/home_timeline
GET /api/statuses/:id
POST /api/statuses
PUT /api/statuses/:id
DELETE /api/statuses/:id
所有的GET选项,Grape也会自动应答HEAD/OPTIONS选项,但是其他路径,只会应答OPTIONS选项。
脱离Rails使用ActiveRecord
如果你想在Grape中使用ActiveRecord,你要保证ActiveRecord的连接池处理正确。保证这一点的最简单的方式是在安装你的Grape应用前使用ActiveRecord的ConnectionManagement中间件:
use ActiveRecord::ConnectionAdapters::ConnectionManagement
run Twitter::API
结合Sinatra(或者其他框架)
如果使用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
把所有的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 => '/'
另外,如果使用的Rails是4.0+,并且使用了ActiveRecord默认的model层,你可能会想使用 hashie-forbidden_attributes gem包。该gem去使能model层strong_paras的安全特性,允许你使用Grape自己的参数校验。
# Gemfile
gem 'hashie-forbidden_attributes'
Modules
在一个应用内部你可以mount多个其他应用的API实现,它们不需要是不同的版本,但是可能是同一接口的组件:
class Twitter::API < Grape::API
mount Twitter::APIv1
mount Twitter::APIv2
end
你也可以挂在到一个路径上,就好像在被mount的API内部使用了prefix一样:
class Twitter::API < Grape::API
mount Twitter::APIv1 => '/v1'
end
版本控制
版本信息可以通过四种方式提供:
:path、:header、:accept_version_header、:param
默认的方式是:path。
path
version 'v1', using: :path
通过这种方式,URL中必须提供版本信息:
curl http://localhost:9292/v1/statuses/public_timeline
Header
version 'v1', using: :header, vendor: 'twitter'
现在,Grape仅支持如下格式的版本控制信息:
vnd.vendor-and-or-resource-v1234+format
最后的-和+之间的所有信息都会被解释为版本信息(上面的版本信息就是v1234)。
通过这种方式,用户必须通过HTTP的Accept头传递版本信息:
curl -H Accept:application/vnd.twitter-v1+json http://localhost:9292/statuses/public_timeline
默认的,如果没有提供Accept头信息,将会使用第一个匹配的版本,这种行为和Rails中的路径相似。为了规避这个默认的行为,可以使用:strict选项,该选项被设置为true时,如果没有提供正确的Accept头信息,会返回一个406错误。
当提供了一个无效的Accept头时,如果:cascade选项设置为false,会返回一个406错误。否则,如果没有其他的路径匹配,Rack会返回一个404错误。
Accept-Version Header
version 'v1', using: :accept_version_header
使用该方式时,用户必须在HTTP头中提供Accept-Version信息:
curl -H "Accept-Version:v1" http://localhost:9292/statuses/public_timeline
默认的,如果没有提供Accept头信息,将会使用第一个匹配的版本,这种行为和Rails中的路径相似。为了规避这个默认的行为,可以使用:strict选项,该选项被设置为true时,如果没有提供正确的Accept头信息,会返回一个406错误。
当提供了一个无效的Accept头时,如果:cascade选项设置为false,会返回一个406错误。否则,如果没有其他的路径匹配,Rack会返回一个404错误。
Param
version 'v1', using: :param
使用这种方式,用于必须在URL字符串或者请求的body中提供版本信息:
curl http://localhost:9292/statuses/public_timeline?apiver=v1
参数名称默认是“apiver”,你也可以通过:parameter 选项指定:
version 'v1', using: :param, parameter: 'v'
curl http://localhost:9292/statuses/public_timeline?v=v1
描述方法
你可以为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) The Entity to be used to present by default this route
- failure: (former http_codes) A definition of the used failure HTTP Codes and Entities
- named: A helper to give a route a name and find it with this name in the documentation Hash
- headers: A definition of the used Headers
Grape简介的更多相关文章
- REST简介
一说到REST,我想大家的第一反应就是“啊,就是那种前后台通信方式.”但是在要求详细讲述它所提出的各个约束,以及如何开始搭建REST服务时,却很少有人能够清晰地说出它到底是什么,需要遵守什么样的准则. ...
- [转]REST简介
转自:http://www.cnblogs.com/loveis715/p/4669091.html 一说到REST,我想大家的第一反应就是“啊,就是那种前后台通信方式.”但是在要求详细讲述它所提出的 ...
- HTTP的REST服务简介
REST简介 一说到REST,我想大家的第一反应就是“啊,就是那种前后台通信方式.”但是在要求详细讲述它所提出的各个约束,以及如何开始搭建REST服务时,却很少有人能够清晰地说出它到底是什么, ...
- php spl标准库简介(SPL是Standard PHP Library(PHP标准库)(直接看代码实例,特别方便)
php spl标准库简介(SPL是Standard PHP Library(PHP标准库)(直接看代码实例,特别方便) 一.总结 直接看代码实例,特别方便易懂 thinkphp控制器利眠宁不支持(说明 ...
- ASP.NET Core 1.1 简介
ASP.NET Core 1.1 于2016年11月16日发布.这个版本包括许多伟大的新功能以及许多错误修复和一般的增强.这个版本包含了多个新的中间件组件.针对Windows的WebListener服 ...
- MVVM模式和在WPF中的实现(一)MVVM模式简介
MVVM模式解析和在WPF中的实现(一) MVVM模式简介 系列目录: MVVM模式解析和在WPF中的实现(一)MVVM模式简介 MVVM模式解析和在WPF中的实现(二)数据绑定 MVVM模式解析和在 ...
- Cassandra简介
在前面的一篇文章<图形数据库Neo4J简介>中,我们介绍了一种非常流行的图形数据库Neo4J的使用方法.而在本文中,我们将对另外一种类型的NoSQL数据库——Cassandra进行简单地介 ...
- Microservice架构模式简介
在2014年,Sam Newman,Martin Fowler在ThoughtWorks的一位同事,出版了一本新书<Building Microservices>.该书描述了如何按照Mic ...
- const,static,extern 简介
const,static,extern 简介 一.const与宏的区别: const简介:之前常用的字符串常量,一般是抽成宏,但是苹果不推荐我们抽成宏,推荐我们使用const常量. 执行时刻:宏是预编 ...
随机推荐
- Sql Server用户名和登录名的关系总结
以前经常被SQL Server中的用户名和登录名搞迷糊,因为用sa(登录名)就搞定一切东西了,当然这会存在一些安全隐患.网上的文章也貌似讲得很好,但还是不明白.今天决心把这个问题弄明白.mashall ...
- ORA-06553: PLS-553: character set name is not recognized, while starting Content Store
Symptom CM-CFG-5029 Content Manager is unable to determine whether the content store is initialized. ...
- (转)MyEclipse10下创建web项目并发布到Tomcat
转自:http://blog.sina.com.cn/s/blog_699d3f1b01012spf.html MyEclipse10下创建web项目并发布到Tomcat 1.软件安装(不作详细描 ...
- zend studio 修改字体大小
第一步:进入设置窗口 windows -> preferences第二步:进入修改字体的选项卡. General -> Appearance -> Colors and ...
- 6、GNU makefile工程管理学习的一个例子
在之前我们已经学习了一个文件的编译过程,但是做过项目的都知道,一个工程中的源文件不计其数,其按类型.功能.模块会分别放在若干个目录中,而这些文件如何编译就需要有一个编译规则,虽然现在很多大型的项目都是 ...
- Scala_方法、函数、柯里化
方法.函数.柯里化 方法 声明方法: scala> def m1(x:Int,y:Int):Int = { | x + y | }m1: (x: Int, y: Int)Ints ...
- kettle学习
数据etl工具,主要用做数据采集和清洗 待续...
- flume遇到的问题
Caused by: java.lang.IllegalStateException: Unable to add FlumeEventPointer [fileID=, offset=]. Queu ...
- ASP.NET Web API 入门 (API接口、寄宿方式、HttpClient调用)
一.ASP.NET Web API接口定义 ASP.NET Web API默认实现了Action方法和HTTP方法的映射,Action方法方法名体现了其能处理的请求必须采用的HTTP方法 二.寄宿方式 ...
- RxSwift学习笔记5:Binder
使用 Binder 创建观察者 //Observable序列(每隔1秒钟发出一个索引数) let scheduleObservable = Observable<Int>.interval ...