Search code examples
grape-api

Checking request body in Grape API


I have a line like this in my Grape endpoint to check the contents of the POST body, to provide a testing endpoint:

return 'OK' if request.body.string == 'TEST'

In my development environment on my laptop, this works just fine. In our staging and production environments, however, it throws an exception:

NoMethodError: undefined method `string' for #<Unicorn::TeeInput:0x0000000b0d0290>

From what I can find this has to do with Rack, but I'm pretty surprised to find different behavior from middleware between two environments. I wondered if anyone out there has run across this and might have a suggestion, because I see that Unicorn::TeeInput doesn't have an easy way to check the contents, seemingly. I'm hoping that perhaps there's an "official" way to directly access the request body in Grape, but I haven't found one yet.

Thanks for any ideas.


Solution

  • Try using env['rack.input'], which should return an input stream (actually a Rack::Lint::InputWrapper or workalike) from which you can read the request body:

    return 'OK' if env['rack.input'].gets.eql? 'TEST'
    

    I've tested this and it works locally using both WEBrick and Unicorn.