Basic

Headers describe the body

The body arrived and I did not know how to read it. The headers say how. Content-Type is the instruction manual for the body, and it is a header, not a guess.

What you will see

400

About 1 min of reading

Try It

Send a Content-Type header and see the server read the body by it.

1

POST JSON with the right Content-Type. The server parses it and creates the record.

curl -s -X POST -H 'Content-Type: application/json' -d '{"name":"Ada"}' https://api.example/users

Before you run it, say out loud what it will print. Then open the answer.

What it prints
{"id": 2, "name": "Ada"}
2

Send the same body with no Content-Type. Many services answer 400 because they cannot read it.

curl -s -o /dev/null -w "%{http_code}" -X POST -d '{"name":"Ada"}' https://api.example/users

Before you run it, say out loud what it will print. Then open the answer.

What it prints
400
The body is identical, only the header is missing. That is why a 400 on a POST is often a missing Content-Type, not a bad payload. Check the header before the body.

Data Flow

Headers sit above the body and describe it: Content-Type names the format, Authorization names the caller, and the server reads the body accordingly.
1 Headers sit above the body
↓
2 Content-Type names the format
↓
3 Server reads body by the type
↓
4 Mismatch causes a 400
Why this works
Headers are metadata

A header is a key and a value that describes the request or response, above the body. Content-Type says the format, Content-Length says the size, Authorization says who you are. They are the contract around the data, not the data.

Match what you send

If you send JSON, say Content-Type: application/json. If you send a form, say application/x-www-form-urlencoded. A mismatch is a common 400: the server reads your bytes as the wrong format and fails to parse.

Examples

Content-Type

Content-Type: application/json

This header says the body is JSON. Change it to text/html and the same bytes mean a page. The header decides the reading.

Send your own

curl -H 'Content-Type: application/json' -d '{"a":1}' https://api.example/users

-H adds a header. Many services reject a POST whose Content-Type is missing, because they do not know how to read the body.

Authorization

Authorization: Bearer sk-abc123

Some headers carry credentials. A Bearer token proves who you are. This is how a private API knows you are allowed.

Words this lesson uses

Each one is defined here on this site. Open the entry for the full definition and the other words it points at.

← The status number
Previous Lesson
The status number
Next Lesson
JSON as the payload
JSON as the payload →