ヘッダーとステータスコード

Pythonを使ったAPI入門

Chris Ramakers

Engineering Manager

リクエストメッセージとレスポンスメッセージの構成

An example of a request and response message. Request: GET /users/42 with headers. Response: 200 OK with JSON body containing user info.

Pythonを使ったAPI入門

先頭行

Example of three distinct parts of a request or response message, with the start line highlighted

  • サーバーはレスポンスメッセージに必ず数値のステータスコードを含めます
Pythonを使ったAPI入門

ステータスコード

ステータスコードのカテゴリ

  • 1XX: 情報レスポンス
  • 2XX: 成功レスポンス
  • 3XX: リダイレクトメッセージ
  • 4XX: クライアントエラーレスポンス
  • 5XX: サーバーエラーレスポンス

よく使われるステータスコード

  • 200: OK
  • 404: Not Found
  • 500: Internal Server Error
1 For a full list of all response codes you can refer to the MDN page on status-codes via https://developer.mozilla.org/en-US/docs/Web/HTTP/Status
Pythonを使ったAPI入門

ヘッダー

Example of three distinct parts of a request or response message, with the headers highlighted

key1: Value 1
key2: Value 2
Pythonを使ったAPI入門

例: ヘッダーによるコンテンツネゴシエーション

Example of three distinct parts of a request or response message, with the headers highlighted

  • クライアントがリクエストにaccept: application/jsonヘッダーを追加する
  • サーバーがcontent-type: application/jsonヘッダーを含むレスポンスを返す
Pythonを使ったAPI入門

requestsでヘッダーを扱う

# Adding headers to a request
response = requests.get(
  'https://api.datacamp.com', 
  headers={'accept':'application/json'}
)
# Reading response headers
response.headers['content-type']
'application/json'
response.headers.get('content-type')
'application/json'
Pythonを使ったAPI入門

requestsでステータスコードを扱う

# Accessing the status code
response = requests.get('https://api.datacamp.com/users/12')

response.status_code == 200
True
# Looking up status codes using requests.codes
response = requests.get('https://api.datacamp.com/this/is/the/wrong/path')

response.status_code == requests.codes.not_found
True
Pythonを使ったAPI入門

練習しましょう!

Pythonを使ったAPI入門

Preparing Video For Download...