什么是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简介的更多相关文章

  1. REST简介

    一说到REST,我想大家的第一反应就是“啊,就是那种前后台通信方式.”但是在要求详细讲述它所提出的各个约束,以及如何开始搭建REST服务时,却很少有人能够清晰地说出它到底是什么,需要遵守什么样的准则. ...

  2. [转]REST简介

    转自:http://www.cnblogs.com/loveis715/p/4669091.html 一说到REST,我想大家的第一反应就是“啊,就是那种前后台通信方式.”但是在要求详细讲述它所提出的 ...

  3. HTTP的REST服务简介

      REST简介   一说到REST,我想大家的第一反应就是“啊,就是那种前后台通信方式.”但是在要求详细讲述它所提出的各个约束,以及如何开始搭建REST服务时,却很少有人能够清晰地说出它到底是什么, ...

  4. php spl标准库简介(SPL是Standard PHP Library(PHP标准库)(直接看代码实例,特别方便)

    php spl标准库简介(SPL是Standard PHP Library(PHP标准库)(直接看代码实例,特别方便) 一.总结 直接看代码实例,特别方便易懂 thinkphp控制器利眠宁不支持(说明 ...

  5. ASP.NET Core 1.1 简介

    ASP.NET Core 1.1 于2016年11月16日发布.这个版本包括许多伟大的新功能以及许多错误修复和一般的增强.这个版本包含了多个新的中间件组件.针对Windows的WebListener服 ...

  6. MVVM模式和在WPF中的实现(一)MVVM模式简介

    MVVM模式解析和在WPF中的实现(一) MVVM模式简介 系列目录: MVVM模式解析和在WPF中的实现(一)MVVM模式简介 MVVM模式解析和在WPF中的实现(二)数据绑定 MVVM模式解析和在 ...

  7. Cassandra简介

    在前面的一篇文章<图形数据库Neo4J简介>中,我们介绍了一种非常流行的图形数据库Neo4J的使用方法.而在本文中,我们将对另外一种类型的NoSQL数据库——Cassandra进行简单地介 ...

  8. Microservice架构模式简介

    在2014年,Sam Newman,Martin Fowler在ThoughtWorks的一位同事,出版了一本新书<Building Microservices>.该书描述了如何按照Mic ...

  9. const,static,extern 简介

    const,static,extern 简介 一.const与宏的区别: const简介:之前常用的字符串常量,一般是抽成宏,但是苹果不推荐我们抽成宏,推荐我们使用const常量. 执行时刻:宏是预编 ...

随机推荐

  1. Go语言高级特性总结——Struct、Map与JSON之间的转化

    Struct与Map之间互相转换 // Struct2Map convert struct to map func Struct2Map(st interface{}) map[string]inte ...

  2. c#文件比较Code

    我想我们很多时候想比较一个文件里面是否有改动,比如一个dll库是新加了一个方法或修改了其中的方法实现,不能通过可视化的工具来比较的时候,可以用这个小工具来比较, 以下是比较文件的代码. using S ...

  3. (转)eclipse下配置tomcat7的几个重要问题,值得一看

    转自:http://jingyan.baidu.com/article/ab69b270ccc4792ca7189fd6.html 这段时间开始接触的servlet,今天尝试在eclipse下配置to ...

  4. css,jQuery,js部分注释

    注释:在开头加上<!--,以-->结尾 alt属性,也被称为alt text, 是当图片无法加载时显示的替代文本 action属性的值指定了表单提交到服务器的地址 除了分别指定元素的 pa ...

  5. noip第24课作业

    1.  马走日 [问题描述] 马在中国象棋以日子形规则移动.请编写一段程序给定n*m大小的棋盘,以及马的初始位置(x,y),要求不能重复经过棋盘上的同一个点,计算马可以有多少途径遍历棋盘上的所有点. ...

  6. CMUSphinx Learn - Before you start

    Before you start 开始之前 Before you start the development of the speech application, you need to consid ...

  7. 2.select查询用法

    1.定义查询接口 UserMapper.java package tk.mybatis.simple.mapper; import tk.mybatis.simple.model.SysRole; i ...

  8. applicationContext.xml 基本配置

    <!-- 头文件,主要注意一下编码 --><?xml version="1.0" encoding="UTF-8"?><beans ...

  9. Django:全文检索功能可参考博客

    https://blog.csdn.net/AC_hell/article/details/52875927 https://www.zmrenwu.com/courses/django-blog-t ...

  10. ovs-appctl 命令合集

    通用命令 exit 优雅关闭ovs-vswitchd进程 qos/show interface 查询内核中关于qos的配置以及和给出端口有关的状态 cfm/show [interface]显示在指定端 ...