7

I want to return raw data/blob from my grape/rest api.

I followed the thread at : https://github.com/intridea/grape/issues/412

for a code like :

get 'foo' do
  content_type 'text/plain'
  "hello world"
end

1) I used : format 'txt' - I got quoted text like : "hello world" no error on the browser though, curl gives Content-Type: text/plain but the quotes are not removed

2) env['api.format'] = :txt gives error in browser

3) content_type :txt, 'text/plain' gives error in browser wrong number of args

Any other ways to fix this ?

Thanks.

Jay Prall
  • 5,295
  • 5
  • 49
  • 79
resultsway
  • 12,299
  • 7
  • 36
  • 43

4 Answers4

2

You don't need to use 'body', all that is left to do is to add one line in the API class (above this method):

content_type :txt, 'text/plain'

So that Grape uses :txt formatter for all endpoints that serve text/plain content

Denis Mysenko
  • 6,366
  • 1
  • 24
  • 33
2

Here's what worked for me:

get 'foo' do
  content_type 'text/plain'
  env['api.format'] = :binary
  body 'Stuff here'
end

The documentation says:

env['api.format'] = :binary # there's no formatter for :binary, data will be returned "as is"

So as long as you don't override the :binary formatter, you should be fine.

Francois
  • 1,367
  • 1
  • 15
  • 23
1

According to this you can do the following:

class API < Grape::API
  get 'foo' do
    content_type 'text/plain'
    body 'hello world'
  end
end
Kevin
  • 1,213
  • 10
  • 13
  • It's not the single quotes that should do the trick, its `body` that should do it according to the documentation. – Kevin May 07 '15 at 15:41
  • I previously included the incorrect URL. I've updated my answer with the URL I wanted to post, but apparently that didn't work out for you. There's a lot of documentation on that page btw. – Kevin May 07 '15 at 17:55
  • 1
    I have the same problem. Any progress on this? Why is such a simple thing so complicated? – Robert Reiz Jan 03 '17 at 15:42
1

Using content_type :txt, 'text/plain' above the method and using the body method worked for me. Here is my code snippet:

content_type :txt, "text/plain" desc "ping pong" get "/ping" do challenge = params["hub.challenge"] challenge = "pong" if challenge.to_s.empty? status 200 body challenge end

Robert Reiz
  • 4,243
  • 2
  • 30
  • 43