> ## Documentation Index
> Fetch the complete documentation index at: https://docs.deepinfra.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Request Compression

> Compress large request bodies with gzip to cut upload bandwidth and latency.

DeepInfra accepts **gzip-compressed request bodies**. For large payloads — long chat
histories, big embeddings batches, sizable inputs — compressing the request shrinks the
bytes you upload (JSON and text typically compress 4–8×), which lowers your egress and can
speed up requests over slower or metered connections.

To use it, gzip the request body and set the `Content-Encoding: gzip` header. It works on
**every** HTTP API endpoint (chat completions, embeddings, files, and the rest), including
requests whose response streams back — the request body is a single upload regardless of how
the response is returned.

## With the OpenAI SDK

The OpenAI SDKs don't compress requests on their own, but a small hook gzips every JSON
request body they send. Responses, retries, and streaming are unaffected.

```python Python theme={null}
import gzip
import os

from openai import DefaultHttpxClient, OpenAI


def gzip_request_body(request):
    is_json = request.headers.get("Content-Type", "").startswith("application/json")
    if not is_json or "Content-Encoding" in request.headers:
        return
    body = request.read()
    if not body:
        return
    compressed = gzip.compress(body)
    request.headers["Content-Encoding"] = "gzip"
    request.headers["Content-Length"] = str(len(compressed))
    request.stream = type(request.stream)(compressed)


client = OpenAI(
    api_key=os.environ["DEEPINFRA_API_KEY"],
    base_url="https://api.deepinfra.com/v1/openai",
    http_client=DefaultHttpxClient(event_hooks={"request": [gzip_request_body]}),
)

response = client.chat.completions.create(
    model="deepseek-ai/DeepSeek-V4-Flash-0731",
    messages=[{"role": "user", "content": "Hello!"}],
)
print(response.choices[0].message.content)
```

```javascript JavaScript theme={null}
import OpenAI from "openai";

const openai = new OpenAI({
  apiKey: process.env.DEEPINFRA_API_KEY,
  baseURL: "https://api.deepinfra.com/v1/openai",
  fetch: async (url, init = {}) => {
    if (typeof init.body !== "string") return fetch(url, init);
    const headers = new Headers(init.headers);
    headers.set("Content-Encoding", "gzip");
    headers.delete("Content-Length");
    const gzipped = new Blob([init.body]).stream().pipeThrough(new CompressionStream("gzip"));
    return fetch(url, { ...init, headers, body: await new Response(gzipped).blob() });
  },
});

const response = await openai.chat.completions.create({
  model: "deepseek-ai/DeepSeek-V4-Flash-0731",
  messages: [{ role: "user", content: "Hello!" }],
});
console.log(response.choices[0].message.content);
```

Both hooks leave file uploads as they are.

* **Python** needs `openai` 1.17 or later.
* **JavaScript** needs `openai` 5 or later, on Node.js, Bun, or Deno.

With `AsyncOpenAI`, wrap the Python hook in an `async def` and pass it to
`DefaultAsyncHttpxClient`:

```python theme={null}
# gzip_request_body is defined in the example above.
from openai import AsyncOpenAI, DefaultAsyncHttpxClient


async def gzip_request_body_async(request):
    gzip_request_body(request)


client = AsyncOpenAI(
    api_key=os.environ["DEEPINFRA_API_KEY"],
    base_url="https://api.deepinfra.com/v1/openai",
    http_client=DefaultAsyncHttpxClient(event_hooks={"request": [gzip_request_body_async]}),
)
```

## Without an SDK

Gzip the JSON body yourself and send it with `Content-Encoding: gzip`:

```bash cURL theme={null}
# Pipe the JSON body through gzip and send it with Content-Encoding: gzip
echo '{
  "model": "deepseek-ai/DeepSeek-V4-Flash-0731",
  "messages": [{"role": "user", "content": "Hello!"}]
}' | gzip | curl "https://api.deepinfra.com/v1/openai/chat/completions" \
  -H "Content-Type: application/json" \
  -H "Content-Encoding: gzip" \
  -H "Authorization: Bearer $DEEPINFRA_API_KEY" \
  --data-binary @-
```

```python Python theme={null}
import gzip
import json
import os

import requests

payload = json.dumps({
    "model": "deepseek-ai/DeepSeek-V4-Flash-0731",
    "messages": [{"role": "user", "content": "Hello!"}],
}).encode("utf-8")

response = requests.post(
    "https://api.deepinfra.com/v1/openai/chat/completions",
    data=gzip.compress(payload),
    headers={
        "Content-Type": "application/json",
        "Content-Encoding": "gzip",
        "Authorization": f"Bearer {os.environ['DEEPINFRA_API_KEY']}",
    },
)
print(response.json())
```

```javascript JavaScript theme={null}
const payload = JSON.stringify({
  model: "deepseek-ai/DeepSeek-V4-Flash-0731",
  messages: [{ role: "user", content: "Hello!" }],
});
const gzipped = new Blob([payload]).stream().pipeThrough(new CompressionStream("gzip"));

const response = await fetch("https://api.deepinfra.com/v1/openai/chat/completions", {
  method: "POST",
  headers: {
    "Content-Type": "application/json",
    "Content-Encoding": "gzip",
    Authorization: `Bearer ${process.env.DEEPINFRA_API_KEY}`,
  },
  body: await new Response(gzipped).blob(),
});
console.log(await response.json());
```

## When it helps

The savings grow with the size of the request: long conversations, large embeddings batches,
and big inputs upload a fraction of the bytes. For a tiny body like a one-word prompt, gzip
adds a few bytes, which is harmless, so the hooks above simply compress everything.

> [!NOTE]
>
> **gzip only.** `Content-Encoding: gzip` is the only supported request compression. Other
> codings (`deflate`, `br`, `zstd`) are not decompressed — a body compressed with those will
> fail to parse. Use `gzip`.


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.