Pythonのurllibでレスポンスステータス一覧

Pythonのurllibで送信したHTTPリクエストのレスポンスステータスコードは、HTTPサーバーからの応答を表す3桁の数字です。以下は一般的なHTTPステータスコードとその意味の一覧です。

1xx (情報)

  • 100: Continue
  • 101: Switching Protocols
  • 102: Processing

2xx (成功)

  • 200: OK
  • 201: Created
  • 202: Accepted
  • 204: No Content
  • 205: Reset Content
  • 206: Partial Content

3xx (リダイレクト)

  • 300: Multiple Choices
  • 301: Moved Permanently
  • 302: Found
  • 303: See Other
  • 304: Not Modified
  • 307: Temporary Redirect
  • 308: Permanent Redirect

4xx (クライアントエラー)

  • 400: Bad Request
  • 401: Unauthorized
  • 403: Forbidden
  • 404: Not Found
  • 405: Method Not Allowed
  • 406: Not Acceptable
  • 408: Request Timeout
  • 409: Conflict
  • 410: Gone
  • 422: Unprocessable Entity (WebDAV; RFC 4918)
  • 429: Too Many Requests

5xx (サーバーエラー)

  • 500: Internal Server Error
  • 501: Not Implemented
  • 502: Bad Gateway
  • 503: Service Unavailable
  • 504: Gateway Timeout
  • 505: HTTP Version Not Supported

これらのステータスコードは、HTTPリクエストが正常に処理されたか、何らかのエラーが発生したかを示すために使用されます。urllibを使用してHTTPリクエストを送信した後、レスポンスオブジェクトからステータスコードを取得できます。以下はサンプルコードです。

python
import urllib.request url = "https://example.com/api" try: response = urllib.request.urlopen(url) status_code = response.getcode() print(f"ステータスコード: {status_code}") except urllib.error.HTTPError as e: print(f"HTTPエラーが発生しました: {e.code} - {e.reason}") except urllib.error.URLError as e: print(f"URLErrorが発生しました: {e.reason}") except Exception as e: print(f"予期しないエラーが発生しました: {e}")

このコードでは、response.getcode()を使用してHTTPステータスコードを取得し、それを表示しています。ステータスコードを確認することにより、リクエストの結果を判別できます。