Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

rails json response with gzip compression

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.

like image 747
aBadAssCowboy Avatar asked May 27 '13 05:05

aBadAssCowboy


People also ask

Can JSON be compressed?

As text data, JSON data compresses nicely. That's why gzip is our first option to reduce the JSON data size. Moreover, it can be automatically applied in HTTP, the common protocol for sending and receiving JSON. Let's take the JSON produced with the default Jackson options and compress it with gzip.

Is Brotli better than gzip?

Brotli has a better compression ratio (i.e. it produces smaller compressed files) across every level of compression. While GZIP does beat Brotli on speed most of the time, the level you compress at factors into the results you'll see.


1 Answers

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:

module YourApp   class Application < Rails::Application     config.middleware.use Rack::Deflater   end end 

and you'll automatically compress all controller responses with deflate / gzip if the client explicitly says they can handle it.

like image 150
djcp Avatar answered Sep 18 '22 04:09

djcp