def get_reason(r):
    """Get reason, why an http request failed.

    r is response as returned by requests library
    """
    try:
        return r.json().get("error").get("message")
    except (ValueError, TypeError):
        maxlen = 200
        maxlines = 3
        lines = r.text[:maxlen].splitlines()[:maxlines]
        reason = "\n".join(lines).strip()
        if len(reason):
            return reason
        else:
            return r.reason