Response Status Codes

We can check the response status code:

  1. >>> r = requests.get('http://httpbin.org/get')
  2. >>> r.status_code
  3. 200

Requests also comes with a built-in status code lookup object for easy reference:

  1. >>> r.status_code == requests.codes.ok
  2. True

If we made a bad request (a 4XX client error or 5XX server error response), we can raise it with Response.raise_for_status():

  1. >>> bad_r = requests.get('http://httpbin.org/status/404')
  2. >>> bad_r.status_code
  3. 404
  4. >>> bad_r.raise_for_status()
  5. Traceback (most recent call last):
  6. File "requests/models.py", line 832, in raise_for_status
  7. raise http_error
  8. requests.exceptions.HTTPError: 404 Client Error

But, since our status_code for r was 200, when we call raise_for_status() we get:

  1. >>> r.raise_for_status()
  2. None

All is well.