標籤:
1.Grape是運行在rack或與rails/sinatra配合使用的一種restful風格的ruby微架構,通過提供簡單的DSL(領特定領域語言)簡化APIs開發.它內建支援mutiple formats(),subdomain/prefix restriction, versioning等通用約束(ruby約束高於配置).詳見http://intridea.github.io/grape/.
2.安裝Grape
gem install grape
或者編輯Gemfile.
gem "grape"
然後
bundle install
3.基礎用法
Grape APIs和Rack應用繼承自Grape::API.
下面展示一段用Grape寫的簡單的twitter API:
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 endend
關於上面代碼的簡單解釋:
3.調用API
使用mount方法:
class Twitter::API < Grape::API mount Twitter::APIv1 mount Twitter::APIv2end
class Twitter::API < Grape::API mount Twitter::APIv1 => ‘/v1‘end
4.為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 } ]endget :public_timeline do Status.limit(20)end
details:更加詳細的描述
params:直接從實體定義參數
success:實體物件的預設使用路由
failure:請求失敗返回的http代碼
(====未完=====)
grape: A Ruby framework for rapid API development with great conventions.