Skip to content

Instantly share code, notes, and snippets.

@yorzi
Created March 29, 2011 12:33
Show Gist options
  • Star 5 You must be signed in to star a gist
  • Fork 5 You must be signed in to fork a gist
  • Save yorzi/892282 to your computer and use it in GitHub Desktop.
Save yorzi/892282 to your computer and use it in GitHub Desktop.
a well documented ruby api based on GrapeAPI.
require 'grape'
module My
class API < Grape::API
prefix 'api'
## params key list
#################################################################################################################
# 1. login
# 2. sign
# 3. title
##################################################################################################################
helpers do
def current_user
# auth/validation parts
@current_user ||= User.validation_on_client_user(params)
# add the below line if you use warden as your rack authentication filter
env["warden"].custom_failure! if @current_user.nil?
@current_user
end
def authenticate!
error!("You have no rights to access the API.", 401) if current_user.blank?
end
end
## question API
################################################################################################################
# method: POST
# url: /api/questions/update
# params: login, title, sign.
# response: success => question.to_json
# failure => message with status => 403
#################################################################################################################
resources :questions do
post "update" do
authenticate!
question = Question.create(:title => params[:title], :user => current_user)
if question.save!
question
else
error! "Unable to create your question.", 403
end
end
end
## profile API
################################################################################################################
# method: GET
# url: /api/users/profile
# params: login, sign.
# response: {"karma":36,"badges":0}
#################################################################################################################
resources :users do
get "profile" do
authenticate!
attr_hash = {
:badges => current_user.badgings_count,
:karma => current_user.karma_score,
}
attr_hash
end
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment