Grape - 拥有REST风格API的Ruby框架
Grape是一个拥有类似REST API的Ruby微型框架。它设计运行在Rack或补充现有Web应用框架如Rails或Sinatra,提供一种简单DSL来简化RESTful APIs开发。它已经内置支持一些常见约束,包括multiple formats, subdomain/prefix restriction, content negotiation, versioning等。下面是基本的用法:
class 推ter::API < Grape::API version 'v1', :using => :header, :vendor => '推ter' format :json 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 get ':id' do Status.find(params[:id]) 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
本文由用户 jopen 自行上传分享,仅供网友学习交流。所有权归原作者,若您的权利被侵害,请联系管理员。
转载本站原创文章,请注明出处,并保留原始链接、图片水印。
本站是一个以用户分享为主的开源技术平台,欢迎各类分享!