HTTP / LESSON 08

Bodies and JSON

Send data to an API, and learn how APIs respond when that data is wrong.

The body holds the data of a message. Most APIs today use JSON for it, so that's what we'll use here. But HTTP itself doesn't care about the format.

JSON in five minutes

JSON has six kinds of values:

{
  "string": "Asha Rao",
  "number": 42.5,
  "boolean": true,
  "nothing": null,
  "list": [1, 2, 3],
  "object": {"city": "Hyderabad"}
}

Strings and object keys must use double quotes. Trailing commas aren't allowed, and neither are comments.

Sending JSON

To send a body, you need the data and a Content-Type that describes it.

Request headers 1

Your turn: Change the numbers. Then change the URL to /average, and then to /sort.

In curl, -H sets the header, and -d sets the body and makes the method POST.

Newer versions of curl have a shortcut: --json sets the body, along with Content-Type and Accept.

When the data is wrong

A good API tells you what's wrong. Try each of these, and read the error in the body.

A required field is missing:

The JSON is malformed. The closing brace is missing:

A field has the wrong type. Here, mobile is a number, but the API expects a string:

The body isn't valid for this operation. An empty list has no average:

All of these return 400, along with a message. A client can use the status code to detect the failure, and a person can read the message to fix it.

Think: Why would an API store a mobile number as a string, not a number? Think about leading zeros and country codes, like +91.

Other formats

JSON isn't the only format. HTML forms send their data like this by default:

POST /subscribe HTTP/1.1
Host: example.com
Content-Type: application/x-www-form-urlencoded

name=Asha%20Rao&mobile=9800000001

It looks like a query string, and it's encoded in the same way. File uploads use multipart/form-data. Older enterprise APIs often use XML.

Which messages have a body?

Message Body?
GET, HEAD, DELETE requests Usually not
POST, PUT, PATCH requests Usually yes
204 No Content responses Never
Responses to HEAD Never

Summary

  • A body needs a Content-Type that says how to read it.
  • Errors should use a status code to say what kind of failure it was, and the body to explain it.
  • JSON has strict rules, so small mistakes make it invalid.

Next, we'll look at one of the most important properties of HTTP: it has no memory.