Your first request with HTTPX

HTTPX · Essentials · 7 min

HTTPX is a drop-in modern client; the basics look like Requests, so you are productive immediately.

Install with pip install httpx and import it as import httpx. The top-level functions mirror HTTP methods: httpx.get, post, put, patch, delete, head, options, plus the generic httpx.request(method, url). Each returns an httpx.Response.

The API was deliberately designed to feel like Requests, so most simple code translates directly:

r = httpx.get("https://httpbin.org/get", params={"q": "httpx"})
r.status_code, r.json()

Under the hood every top-level call creates a temporary Client, sends one request and closes the connection. That is fine for scripts and one-off calls. For repeated calls you will use a Client (next module) to get connection pooling.

What HTTPX adds over Requests, as a preview:

  • an async API (httpx.AsyncClient) with the same methods,
  • timeouts by default (5 seconds),
  • optional HTTP/2,
  • transports that can route requests straight to a Python web app or a mock function, which makes testing easy,
  • full type annotations.

Like Requests, an error status such as 404 does not raise automatically; you get a normal response and decide what to do.

The current release line is 0.28. HTTPX is still pre-1.0, so a few APIs changed between minor versions (for example proxies= became proxy= and app= was removed in 0.28); check the changelog when upgrading.

Example

import httpx

r = httpx.get("https://httpbin.org/get", params={"q": "httpx"})
print(r.status_code)              # 200
print(r.json()["args"])           # {'q': 'httpx'}
print(r.http_version)             # HTTP/1.1

r = httpx.post("https://httpbin.org/post", json={"lang": "python"})
print(r.json()["json"])           # {'lang': 'python'}

r = httpx.get("https://httpbin.org/status/404")
print(r.status_code, r.is_success)  # 404 False  (no exception)

Remember

  • httpx.get/post/... mirror Requests and return a Response
  • Top-level calls open and close a client each time
  • Error statuses don't raise automatically

Check yourself

  1. What does httpx.get(url) do with connections?

Sign in to answer, see the explanations, and get this lesson back as a quick review later.

Official docs: www.python-httpx.org/quickstart/