Swap only the transport layer, and the same client can call the real API or run tests offline without changing a single line of code.

Key points at a glance

  • Following the httpx documentation's advice, keep a single httpx.Client inside the client; set base_url to make calls more concise; decide timeouts yourself instead of relying on the default 5 seconds.
  • Validate responses with Pydantic: bad payloads raise a ValidationError right at the client, and the error message points to the problematic field.
  • Let the client receive transport from the outside. With MockTransport, tests can run fully offline with no code changes.

In your first week on-site with a customer, what you encounter most often is often their internal API: incomplete documentation, slow responses, and JSON that occasionally doesn't match the description. If your code is littered with

resp.json()["total"]

, the demo crashes the moment a single field is missing. And the stack trace points to some line buried three layers deep.

This guide teaches you to write a small typed Python client with httpx and Pydantic, plus a set of tests that need no network, to avoid this pitfall. The example uses a hypothetical orders API with an

/orders/{id}

endpoint. The orders API is fictional, but every function and class used in the article comes from the official documentation of httpx, Pydantic, and pytest.

You need Python 3, a virtualenv, and a few minutes of setup:

pip install httpx pydantic pytest

Step 1: Write the data contract as a model

Before calling the network, write down what you believe the API will return. This model is the contract between your code and the customer's system.

# orders_client/models.py
from pydantic import BaseModel

class Order(BaseModel):
    id: int
    status: str
    total: float

According to the Pydantic documentation, whenever data doesn't match the model, the library raises a

ValidationError

. Conversely, once validation passes, Pydantic guarantees the object's fields conform to the declared types. The client in this guide relies on exactly this guarantee, so downstream code no longer needs to worry about whether

total

exists.

Check: In the REPL, call

Order.model_validate_json('{"id": 1, "status": "new"}')

. You should see a

ValidationError

with exactly one error, of type

missing

, with the message

Field required

,

loc

being

total

。

Step 2: Why only one httpx.Client?

Many people call

httpx.get()

directly in every function. It works, but the httpx documentation is clear: except for experiments, one-off scripts, or prototypes, you should use an

Client

instance. Therefore, a client for a customer API should hold only one

httpx.Client

and reuse it across all requests.

# orders_client/client.py
import httpx
from .models import Order

class CustomerApiError(Exception):
    def __init__(self, status_code: int, body: str):
        super().__init__(f"客户 API 返回 {status_code}:{body[:200]}")
        self.status_code = status_code
        self.body = body

class OrdersClient:
    def __init__(self, base_url: str, transport=None, timeout: float = 10.0):
        self._http = httpx.Client(
            base_url=base_url, timeout=timeout, transport=transport
        )

    def get_order(self, order_id: int) -> Order:
        resp = self._http.get(f"/orders/{order_id}")
        try:
            resp.raise_for_status()
        except httpx.HTTPStatusError as exc:
            raise CustomerApiError(exc.response.status_code, exc.response.text) from exc
        return Order.model_validate_json(resp.content)

    def close(self) -> None:
        self._http.close()

There are three decisions in this code worth noting. The first is

base_url

: httpx prepends this URL to every request, so each method only needs to pass a path. Switching from staging to production means changing one string.

The second is the timeout. By default, if the network is silent for more than 5 seconds, httpx raises a

TimeoutException

. For long-running reports this may be too short; for endpoints that should respond immediately, it may be too long.

Writing the timeout explicitly lets readers understand it's a deliberate choice, not a forgotten default. 10 seconds is just an example; for the actual value, ask the customer about that endpoint's SLA.

The last one is

raise_for_status()

. It converts any response outside the 2xx range into a

HTTPStatusError

, which carries both the request and the response. The client then converts it into

CustomerApiError

, so when an HTTP error occurs, upper layers catch the project's own error without needing to know httpx's error classes.

The limitations of this minimal version should also be stated clearly:

ValidationError

and

httpx.TimeoutException

are still raised directly to the caller. Not handling

ValidationError

is intentional, so that the tests in Step 4 clearly expose bad payloads. In a real project, you could wrap these two as your own errors as well; only then do upper layers truly need to catch only project errors.

Check:

get_order

returns a

Order

, not a

dict

. The editor can now autocomplete

.total

.

Step 3: What is the transport parameter for?

Note the

transport=None

parameter in the constructor—it's what makes the tests run offline. According to the httpx documentation,

MockTransport

takes a handler function that maps each request to a predefined response, so no real request ever leaves your machine.

Wiring it in is simple, because

httpx.Client

itself accepts a

transport

parameter: just pass in

httpx.MockTransport(handler)

. The code under test stays unchanged; only the transport layer underneath is swapped.

This is exactly the approach James Bennett recommends in his article "Don't mock Python's HTTPX": use HTTPX's built-in mock transport rather than mocking HTTPX itself or its internals, to reduce reliance on mock objects and save a lot of trouble.

# tests/test_client.py
import httpx
import pytest
from pydantic import ValidationError
from orders_client.client import OrdersClient, CustomerApiError

def handler(request: httpx.Request) -> httpx.Response:
    if request.url.path == "/orders/42":
        return httpx.Response(200, json={"id": 42, "status": "shipped", "total": 19.5})
    if request.url.path == "/orders/7":
        return httpx.Response(200, json={"id": 7, "status": "shipped"})
    return httpx.Response(404, json={"error": "not found"})

@pytest.fixture
def client():
    c = OrdersClient("https://api.customer.example", transport=httpx.MockTransport(handler))
    yield c
    c.close()

In pytest, a test function receives a fixture simply by declaring it as a parameter. So every test shares one client running on the mock, with no repeated setup.

Step 4: Test all three outcomes, not just the happy path

A client calling a customer's system has at least three possible outcomes: correct data, wrongly structured data, or an HTTP error. Each needs its own test.

def test_order_ok(client):
    order = client.get_order(42)
    assert order.total == 19.5

def test_payload_missing_field(client):
    with pytest.raises(ValidationError):
        client.get_order(7)

def test_404_becomes_custom_error(client):
    with pytest.raises(CustomerApiError) as exc:
        client.get_order(999)
    assert exc.value.status_code == 404

Look closely at order 7. The API returns status code 200, which looks like success, but

total

is missing. Without a model, the error wouldn't surface until some revenue function hits a

KeyError

.

With the model,

get_order(7)

stops immediately with

ValidationError

, and the error entry names the

total

field with the message

Field required

. Which field broke and at which endpoint is clear at a glance.

Check: Turn off Wi-Fi and run

pytest -q

. All three tests should still pass.

When should you switch to pytest-httpx?

Handwritten handlers are easy to understand, but they have a blind spot: if you prepare a response for a path the code never calls, the test still passes. pytest-httpx closes this gap. According to its documentation, if any registered response is never requested, the test fails during teardown.

By default, pytest-httpx also immediately raises a

httpx.TimeoutException

for any request that matches no registered response, so tests can't silently reach the real network. Redowan Delowar also mentions respx, a library that intercepts httpx requests during tests and returns preset responses. Both add a dependency; for a small client written in your first week, the built-in

MockTransport

is enough.

Common mistakes

The most common mistake is creating a new

httpx.Client

in every method or every loop iteration. This goes against the httpx documentation's advice,

base_url

and timeouts end up scattered everywhere, and switching environments or adjusting timeouts means changing many places.

The second is catching a broad

Exception

and returning

None

. This way the client swallows both

ValidationError

and

HTTPStatusError

, and you'll spend an afternoon wondering why the dashboard is empty.

The third mistake is making the model too strict on day one, before you've seen real data. Run the client against a few real payloads on staging first, then tighten the model gradually.

What's the use of this at a customer site?

Write this client as early as possible once deployment begins, because it determines where errors will surface later on.

If the customer changes the schema without notice,

ValidationError

the error logs from your tests and client let you point directly at the problem: "Since yesterday's release,

total

the field has been gone."

An offline test suite also lets you keep making progress when you don't yet have VPN access or credentials, or when the customer's staging environment is down.

If you're applying for a Forward Deployed Engineer (FDE) role, you can put a repository like this in your portfolio: a typed client written for some public API, with tests covering all three outcomes. Writing "typed client with offline tests, covering bad payloads and 4xx status codes" on your resume is more convincing than "has API integration experience."

The customer's system will keep changing. What you can control is where errors surface, and the best place is at the client's entry point.

Was this article helpful?

Thanks for your feedback!

10 sources

Next on the roadmap · Phase 1: Foundational Understanding A service that runs fine today may crash on its first restart. The problem usually lies in three lines of systemd configuration, and the evidence may vanish along with the restart.