Search code examples
pythonhttphttp-status-codes

HTTP status code to status message


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'

Solution

  • 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]