Compress a JSON response

← All configuration scenarios

Your API returns several kilobytes of JSON. A client that accepts gzip can download fewer bytes. The bundled inspection handler echoes the request body in JSON, so you can try this without writing an endpoint.

Require gzip

Check php --ri zlib in the serving CLI. Save this profile as gzip.json in the application root. Explicit gzip mode makes a missing encoder a startup error.

JSON
{
  "listen": { "port": 9000 },
  "compression": { "mode": "gzip" }
}
Shell
php vendor/mini4work/webserver/examples/server.php gzip.json

Request a compressed response

Send 4 KiB of text to the handler and print just the response headers.

Shell
php -r 'echo str_repeat("a", 4096);' | \
  curl -sS -D - -o /dev/null --data-binary @- \
    -H 'Accept-Encoding: gzip' http://127.0.0.1:9000/echo

Expect HTTP 200, Content-Encoding: gzip and Vary: Accept-Encoding. Repeat without the Accept-Encoding header for the original JSON representation. With the default "auto", the server negotiates available encoders. Select "off" if your upstream proxy handles compression.

Eligible buffered text responses range from 1 KiB through 1 MiB. Streaming bodies, existing encodings and responses marked Cache-Control: no-transform pass through. For assets compressed by your build, see precompressed files.