HTTP responses: status codes and JSON
A server answers every request with a response: a status code saying how it went, headers, and a body. Read the status code before trusting anything else.
import httpx2
response = httpx2.Response(200, json={"id": 2, "category": "shipping"})
print(response.status_code)
print(response.is_success)
print(response.text)
print(response.json()["category"])response.text is the body as it arrived, a string. response.json() reads that JSON into a dictionary, like json.loads. Here the response is made by hand so you can see its parts; from lesson 3 they come from a server.
What the first digit says
- 2xx: it worked. 200 is OK, 201 is created.
- 4xx: the request was wrong, so sending it again unchanged will fail again. 401 means no valid key, 404 means not found, 422 means the data did not pass the server's checks, 429 means too many requests.
- 5xx: the server failed. The same request may work later. 500 is a crash, 502 means a server it depended on gave a bad answer.
A response that is an error
request = httpx2.Request("GET", "https://api.example.com/tickets/9")
response = httpx2.Response(404, json={"detail": "ticket not found"}, request=request)
print(response.status_code, response.reason_phrase)
print(response.is_success)
print(response.json())A 404 still has a body, often with a useful message. Nothing went wrong in Python: an error response is a normal response, and it is your code's job to look at the status code.
response.raise_for_status()raise_for_status turns any 4xx or 5xx into an httpx2.HTTPStatusError. Call it when an error status means your code should stop, instead of carrying on with a body that is not what you expected.
- Make a response with status 201 and call
raise_for_status(). What happens? - Make a 429 response with
headers={"Retry-After": "2"}and printresponse.headers["retry-after"]. - Give a response
text="not json"and callresponse.json().
You understood something today that you didn't yesterday.