Responding with different formats and content-types

248 views
Skip to first unread message

Andrew Stewart

unread,
Nov 28, 2013, 6:02:25 AM11/28/13
to ruby-...@googlegroups.com
Hello!

I am confused about formats and content-types, and how different endpoints can respond with different kinds of data.

Here's my situation: my API has three endpoints.  Two should return PDF data and one should return JSON data:

    class API < Grape::API
      params do
        # a few HTTP params
      end
      post :foos
        # generates a PDF
      end
    
      params do
        # a few HTTP params
      end
      post :bars
        # generates a PDF
      end
    
      get :bazs
        # returns Baz instances' attributes as JSON
      end
    end

The only way I can get this to work is:

    class API < Grape::API
      content_type :pdf, 'application/pdf'
      format :pdf
    
      # :foos stuff as above
      # :bars stuff as above
    
      get :bazs
        content_type 'application/json'
        some_objects.to_json
      end
    end

In other words, make PDF the default then crowbar /bazs into returning JSON by overriding its content type and manually JSONifying my objects.

Is that the best way to do it?  It would be nice to do this instead but it won't work for me:

    get :bazs
      format :json
      some_objects
    end

Thanks in advance!

Yours,
Andy Stewart

Daniel Doubrovkine

unread,
Dec 2, 2013, 7:44:39 AM12/2/13
to ruby-...@googlegroups.com
When you declare content types, it clears the defaults, so you have to declare both of these: `content_type :pdf, 'application/pdf` and `content_type :json, `application/json`. Then you can do `content_type ...` in the API response for any of the declared content types. 

If you cannot get it to work, post a project with a test that fails and I can help you.



--
You received this message because you are subscribed to the Google Groups "Grape Framework Discussion" group.
To unsubscribe from this group and stop receiving emails from it, send an email to ruby-grape+...@googlegroups.com.
For more options, visit https://groups.google.com/groups/opt_out.



--

dB. | Moscow - Geneva - Seattle - New York
code.dblock.org - @dblockdotorg - artsy.net - github/dblock

Reply all
Reply to author
Forward
0 new messages