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 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!