Response Headers

We can view the server’s response headers using a Python dictionary:

  1. >>> r.headers
  2. {
  3. 'content-encoding': 'gzip',
  4. 'transfer-encoding': 'chunked',
  5. 'connection': 'close',
  6. 'server': 'nginx/1.0.4',
  7. 'x-runtime': '148ms',
  8. 'etag': '"e1ca502697e5c9317743dc078f67693f"',
  9. 'content-type': 'application/json'
  10. }

The dictionary is special, though: it’s made just for HTTP headers. According to RFC 7230, HTTP Header names are case-insensitive.

So, we can access the headers using any capitalization we want:

  1. >>> r.headers['Content-Type']
  2. 'application/json'
  3. >>> r.headers.get('content-type')
  4. 'application/json'

It is also special in that the server could have sent the same header multiple times with different values, but requests combines them so they can be represented in the dictionary within a single mapping, as per RFC 7230:

A recipient MAY combine multiple header fields with the same field name into one “field-name: field-value” pair, without changing the semantics of the message, by appending each subsequent field value to the combined field value in order, separated by a comma.