Skip to content

Instantly share code, notes, and snippets.

@Dakad
Created March 26, 2025 19:44
Show Gist options
  • Save Dakad/338e95077743b375c36549939b7a9bc2 to your computer and use it in GitHub Desktop.
Save Dakad/338e95077743b375c36549939b7a9bc2 to your computer and use it in GitHub Desktop.
Ruby Grape Entity JSON-over-HTTP API, custom JSON representation error
# Source: https://stackoverflow.com/a/15502829
require "grape"
require "grape-entity"
require "json"
module JSendSuccessFormatter
def self.call object, env
{ :status => 'success', :data => object }.to_json
end
end
module JSendErrorFormatter
def self.call message, backtrace, options, env
# This uses convention that a error! with a Hash param is a jsend "fail", otherwise we present an "error"
if message.is_a?(Hash)
{ :status => 'fail', :data => message }.to_json
else
{ :status => 'error', :message => message }.to_json
end
end
end
class Thing
def initialize llama_name
@llama_name = llama_name
end
attr_reader :llama_name
end
class ThingPresenter < Grape::Entity
expose :llama_name
end
class MainService < Grape::API
prefix 'api'
version 'v2'
format :json
rescue_from :all
formatter :json, JSendSuccessFormatter
error_formatter :json, JSendErrorFormatter
resource :thing do
get do
thing = Thing.new 'Henry'
present thing, :with => ThingPresenter
end
end
resource :borked do
get do
error! "You broke it! Yes, you!", 403
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment