Daniel Doubrovkine bio photo

Daniel Doubrovkine

aka dB., @awscloud, former CTO @artsy, +@vestris, NYC

Email Twitter LinkedIn Github Strava
Creative Commons License

Grape’s after blocks don’t allow you to modify response text or status code [#200]. So how can you wrap an API response?

Define a Rack middleware and mount it in the API. Here’s an example of a decorator that wraps any body and resets the status code to 200.

class ApiDecorator
    def initialize(app)
        @app = app
    end
    def call(env)
        status, headers, bodies = @app.call(env)
        bodies = bodies.map do |body|
            { :body => body, :status => status }
        end
        [200, headers, bodies]
    end
end

class MyApi < Grape::API
    use ApiDecorator
    get :ping do
        { :ping => "pong" }
    end
end

You can see a working sample with API_v4_Decorator mounted in API_v4 in https://github.com/dblock/grape-on-rack.

This works with all kinds of Rack applications, not just Grape.