httpx/docs/responses.md
2025-09-16 18:59:11 +01:00

3.7 KiB

Responses

The core elements of an HTTP response are the status_code, headers and body.

httpx ahttpx
>>> 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'
>>> resp = ahttpx.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 a Content-Length header or a Transfer-Encoding: chunked header. This header is automatically populated if content is not None and the content is a known size.
  • Transfer-Encoding - Responses automatically include a Transfer-Encoding: chunked header if content is not None and the content is an unkwown size.
  • Content-Type - Responses automatically include a Content-Type header if content is set using the [Content Type] API.

Working with content types

Including HTML content...

httpx ahttpx
>>> content = httpx.HTML('<html><head>...</head><body>...</body></html>')
>>> response = httpx.Response(200, content=content)
>>> content = ahttpx.HTML('<html><head>...</head><body>...</body></html>')
>>> response = ahttpx.Response(200, content=content)

Including plain text content...

httpx ahttpx
>>> content = httpx.Text('hello, world')
>>> response = httpx.Response(200, content=content)
>>> content = ahttpx.Text('hello, world')
>>> response = ahttpx.Response(200, content=content)

Including JSON data...

httpx ahttpx
>>> content = httpx.JSON({'message': 'hello, world'})
>>> response = httpx.Response(200, content=content)
>>> content = ahttpx.JSON({'message': 'hello, world'})
>>> response = ahttpx.Response(200, content=content)

Including content from a file...

httpx ahttpx
>>> content = httpx.File('index.html')
>>> with httpx.Response(200, content=content) as response:
...     pass
>>> content = ahttpx.File('index.html')
>>> async with ahttpx.Response(200, content=content) as response:
...     pass

Accessing response content

...

httpx ahttpx
>>> response.body
>>> response.body

...

httpx ahttpx
>>> response.text
...
>>> response.text
...

Requests URLs