Skip to content

Instantly share code, notes, and snippets.

@priyaaank
Created October 21, 2012 09:32
Show Gist options
  • Save priyaaank/3926492 to your computer and use it in GitHub Desktop.
Save priyaaank/3926492 to your computer and use it in GitHub Desktop.
Modular APIs with Grape and Rails
class API < Grape::API
format :json
error_format :json
version 'v1', :using => :header, :vendor => "App"
rescue_from Mongoid::Errors::DocumentNotFound do |error|
rack_response({"error" => {"message" => "We didn't find what we were looking for"}}.to_json, 404)
end
mount Users::APIV1
end
module Users
class APIV1 < Grape::API
resource :user do
desc "Returns a user for a given user id"
get '/:id' do
user = User.find(params[:id])
present user, :with => Users::UserResponseEntity
end
end
end
end
module Users
class ContactInfoResponseEntity < Grape::Entity
expose :address_line
expose :city
expose :country
expose :zipcode
expose :state
expose :phone_numbers, :using => Users::PhoneNumberResponseEntity
end
end
module Users
class PhoneNumberResponseEntity < Grape::Entity
expose :country_code
expose :area_code
expose :number
expose :formatted_number
end
end
module Users
class UserResponseEntity < Grape::Entity
expose :first_name
expose :last_name
expose :formatted_name, :as => "full_name"
expose :username
expose :email
expose :contact_info, :using => Users::ContactInfoResponseEntity
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment