16

I'm looking for a way, in Python, to get the HTTP message from the status code. Is there a way that is better than building the dictionary yourself?

Something like:

>>> print http.codemap[404]
'Not found'

4 Answers 4

19

In Python 2.7, the httplib module has what you need:

>>> import httplib
>>> httplib.responses[400]
'Bad Request

Constants are also available:

httplib.responses[httplib.NOT_FOUND]
httplib.responses[httplib.OK]

Update

@shao.lo added a useful comment bellow. The http.client module can be used:

# For Python 3 use
import http.client
http.client.responses[http.client.NOT_FOUND]
Sign up to request clarification or add additional context in comments.

1 Comment

For python3 use import http.client and http.client.responses[http.client.NOT_FOUND]
17

This problem is solved in Python 3.5 onward. Python http library has a built-in module called HTTPStatus.

The HTTP status components such as numeric code (value), the phrase, and the description are all available from attributes.

The documentation provides this example:

>>> from http import HTTPStatus
>>> HTTPStatus.OK
HTTPStatus.OK
>>> HTTPStatus.OK == 200
True
>>> HTTPStatus.OK.value
200
>>> HTTPStatus.OK.phrase
'OK'
>>> HTTPStatus.OK.description
'Request fulfilled, document follows'
>>> list(HTTPStatus)
[HTTPStatus.CONTINUE, HTTPStatus.SWITCHING_PROTOCOLS, ...]

Comments

7

Python 3:

You could use HTTPStatus(<error-code>).phrase to obtain the description for a given code value. E.g. like this:

try:
    response = opener.open(url, 
except HTTPError as e:
    print(f'In func my_open got HTTP {e.code} {HTTPStatus(e.code).phrase}')

Would give for example:

In func my_open got HTTP 415 Unsupported Media Type

Which answers the question. However a much more direct solution can be obtained from HTTPError.reason:

try:
    response = opener.open(url, data)
except HTTPError as e:
    print(f'In func my_open got HTTP {e.code} {e.reason}')

1 Comment

@JSTL It was, but this answer gives usage examples.
-1

A 404 error indicates that the page may have been moved or taken offline. It differs from a 400 error which would indicate pointing at a page that never existed.

1 Comment

I changed the message

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.