Headers and representations

Content types and encodings

Use Content-Type, charset, and Content-Encoding to describe a message body accurately and avoid parsing or text-decoding errors.

Content-Type tells the recipient what the body contains. Without it, the client has to guess how to interpret the bytes.

Common values look like this:

Content-Type: application/json
Content-Type: text/html; charset=utf-8
Content-Type: image/webp

The media type determines which parser or renderer should handle the body. A JSON payload sent as text/plain may still look readable in a terminal, but clients cannot reliably treat it as JSON.

The charset parameter describes text encoding. UTF-8 is the normal choice for web text. If you omit it on HTML, browsers often assume UTF-8 anyway, but setting it explicitly avoids surprises with accented characters.

Content-Encoding is different. It describes a transformation applied for transport, such as gzip or br. The recipient decodes that layer first, then interprets the result according to Content-Type.

In short: type says what it is. Encoding says what happened to it on the way.

Let’s see the difference with curl. Request a compressed page:

curl -I -H 'Accept-Encoding: gzip' https://flaviocopes.com/

Look for content-encoding: gzip or content-encoding: br in the response. curl decompresses the body automatically, but the header still tells you the server compressed it before sending.

Now send JSON with the wrong type:

curl https://httpbin.org/post \
  -H 'Content-Type: text/plain' \
  -d '{"title":"Learn HTTP"}'

httpbin echoes your headers back. The body is JSON, but you told the server it was plain text. Many APIs would reject that or store it incorrectly.

My advice: always set Content-Type on requests with a body, and verify the response type before parsing. If you call response.json() in JavaScript on HTML, you get a syntax error. Match the parser to the declared type.

Try this on your own API: send the same JSON body once with application/json and once with text/plain. Watch how the server logs or stores the payload differently.

Lesson completed