1.Grape is a restful-style ruby micro-framework that runs on rack or in conjunction with Rails/sinatra, simplifying the development of APIs by providing a simple DSL (domain-specific language). It has built-in support for mutiple formats (), Subdomain/prefix restriction, versioning, etc. general constraints (ruby constraints are higher than the configuration). See http://intridea.github.io/grape/.
2. Installing grape
gem install grape
Or edit the 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 in 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
A brief explanation about the above code:
3. Call the API
Use the mount method:
class Twitter :: API <Grape :: API
mount Twitter :: APIv1
mount Twitter :: APIv2
end
class Twitter :: API <Grape :: API
mount Twitter :: APIv1 => ‘/ v1’
end
4. Add a description to 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
}
]
end
get: public_timeline do
Status.limit (20)
end
details: more detailed description
params: define parameters directly from the entity
success: the default route of the entity object
failure: http code returned by request failure
(==== Unfinished =====)
grape: A Ruby framework for rapid API development with great conventions.