I have an api written in rails which on each request responds with a JSON response.
The response could be huge, so i need to compress the JSON response using gzip.
Wondering how to do this in rails controller?
I have added the line
use Rack::Deflater
in config.ru
Should I also be changing something in the line which renders JSON?
render :json => response.to_json()
Also, how do i check if the response is in gzip format or not..??
I did a curl request from terminal, I see only the normal plain JSON.
My post Content Compression with Rack::Deflater describes a couple of ways to integrate Rack::Deflater. The easiest would be to just update
config/application.rb
with:and you'll automatically compress all controller responses with deflate / gzip if the client explicitly says they can handle it.
For the response to be in gzip format we don't have to change the
render
method call.If the request has the header
Accept-Encoding: gzip
, Rails will automatically compress the JSON response using gzip.If you don't want the user to send a request with preset header., you can add the header to the request manually in the controller before rendering the response:
In some cases you can consider to write huge response into a file and gzip it:
and update this file regularly
You can query Curl by setting a custom header to get gzipped response
then, then decompress it to view the actual response json
If it doesn't work. post back with output of
rake middlewares
to help us troubleshoot further.