Advanced Usage

Client Instances

Using a Client instance to make requests will give you HTTP connection pooling,will provide cookie persistence, and allows you to apply configuration acrossall outgoing requests.

  1. >>> client = httpx.Client()
  2. >>> r = client.get('https://example.org/')
  3. >>> r
  4. <Response [200 OK]>

Calling into Python Web Apps

You can configure an httpx client to call directly into a Python webapplication, using either the WSGI or ASGI protocol.

This is particularly useful for two main use-cases:

  • Using httpx as a client, inside test cases.
  • Mocking out external services, during tests or in dev/staging environments.

Here’s an example of integrating against a Flask application:

  1. from flask import Flask
  2. import httpx
  3. app = Flask(__name__)
  4. @app.route("/")
  5. def hello():
  6. return "Hello World!"
  7. client = httpx.Client(app=app)
  8. r = client.get('http://example/')
  9. assert r.status_code == 200
  10. assert r.text == "Hello World!"