Grape entry, grapeseed
1. grape is a restful ruby microframework running in rack or used in combination with rails/sinatra. It simplifies APIs development by providing simple DSL (domain-specific language. it supports built-in general constraints such as mutiple formats (), subdomain/prefix restriction, and versioning (ruby constraints are higher than the configuration ). see http://intridea.github.io/grape/ for details.
2. Install Grape
gem install grape
Or edit Gemfile.
gem "grape"
Then
bundle install
3. Basic usage
Grape APIs and Rack applications inherit from Grape: API.
The following shows a simple twitter API written using 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 endend
A simple explanation of the above Code:
3. Call an API
Use the mount method:
class Twitter::API < Grape::API mount Twitter::APIv1 mount Twitter::APIv2end
class Twitter::API < Grape::API mount Twitter::APIv1 => '/v1'end
4. Add a description for the 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: More detailed description
Params: Define parameters directly from the object
Success: default route used for Object
Failure: http code returned when the request fails
(==== Unfinished ====)