Responses
The core elements of an HTTP response are the status_code
, headers
and body
.
>>> resp = httpx.Response(200, headers={'Content-Type': 'text/plain'}, content=b'hello, world')
>>> resp
<Response [200 OK]>
>>> resp.status_code
200
>>> resp.headers
<Headers {'Content-Type': 'text/html'}>
>>> resp.body()
b'hello, world'
Working with the response headers
The following headers have automatic behavior with Response
instances...
Content-Length
- Responses including a response body must always include either aContent-Length
header or aTransfer-Encoding: chunked
header. This header is automatically populated ifcontent
is notNone
and the content is a known size.Transfer-Encoding
- Responses automatically include aTransfer-Encoding: chunked
header ifcontent
is notNone
and the content is an unkwown size.Content-Type
- Responses automatically include aContent-Type
header ifcontent
is set using the [Content Type] API.
Working with content types
Including HTML content...
>>> content = httpx.HTML('<html><head>...</head><body>...</body></html>')
>>> response = httpx.Response(200, content=content)
Including plain text content...
>>> content = httpx.Text('hello, world')
>>> response = httpx.Response(200, content=content)
Including JSON data...
>>> content = httpx.JSON({'message': 'hello, world'})
>>> response = httpx.Response(200, content=content)
Including content from a file...
>>> content = httpx.File('index.html')
>>> with httpx.Response(200, content=content) as response:
... pass
Accessing response content
...
>>> content = response.body()
...
>>> text = response.text()
...
...
>>> data = response.json()