HTTP and JSON
HTTP is text exchanged in pairs. A request has a method, a path, headers and an optional body. A response has a status code, headers and a body.
GETreads,POSTcreates,PUTreplaces,DELETEremoves.2xxmeans success,4xxa client mistake, and5xxa server failure.Content-Typesays how to interpret the body.
Most APIs send JSON. The json module converts between JSON text and Python values.
import json
text = json.dumps({"id": 1, "ok": True})
print(text) # {"id": 1, "ok": true}
data = json.loads(text)
print(data["ok"]) # TrueWhat changes on the way
Nonebecomesnull, and tuples become arrays.- Dict keys become strings, so
{1: "a"}returns as{"1": "a"}. - Types with no JSON form, such as a
set, raiseTypeError. - Bad input raises
json.JSONDecodeError, a subclass ofValueError.
Your task
Write make_response(data, status=200) returning a dict with status, headers ({"Content-Type": "application/json"}) and body as compact JSON text with sorted keys. Write read_response(response) returning the parsed body, raising ValueError for status 400 or above (including the body's error value if it has one) or for invalid JSON.
The explanation opens here once every check passes.