Claude Code for respx: Mock httpx in Python Tests — Claude Skills 360 Blog
Blog / AI / Claude Code for respx: Mock httpx in Python Tests
AI

Claude Code for respx: Mock httpx in Python Tests

Published: January 10, 2028
Read time: 5 min read
By: Claude Skills 360

respx mocks httpx HTTP calls in tests. pip install respx. Context manager: import respx; import httpx. with respx.mock: resp = httpx.get("https://api.example.com/users"); assert resp.status_code == 200. Route: respx.get("https://api.example.com/users").mock(return_value=httpx.Response(200, json=[{"id":1}])). Method shorthands: respx.get(url), respx.post(url), respx.put(url), respx.patch(url), respx.delete(url). Pattern match: respx.get(url__regex=r"/users/\d+"). respx.route(method="GET", url__startswith="https://api"). Headers match: respx.get(url, headers={"X-Token":"abc"}). Content match: respx.post(url, content=b"hello"). JSON match: respx.post(url, json={"email":"[email protected]"}). Response: httpx.Response(200, json={...}). httpx.Response(201, headers={"Location":"/items/1"}). httpx.Response(422, json={"detail":"validation error"}). side_effect: route.mock(side_effect=httpx.TimeoutException) — simulate timeout. side_effect=lambda req: httpx.Response(200, json={"path":str(req.url)}) — dynamic. Sequential: route.mock(side_effect=[resp1, resp2, httpx.ConnectError]) — cycle through responses. Async: async with respx.mock: resp = await async_client.get(url). @respx.mock async def test_async(...). Router: router = respx.Router(). router.get(url).mock(...). with router: .... pass_through: respx.mock(assert_all_called=False). respx.route(url__startswith="https://real").pass_through(). Decorator: @respx.mock def test_fn(respx_mock): respx_mock.get(url).mock(...). pytest: @pytest.fixture def mock_api(): with respx.mock: yield respx. Reset: respx.calls.reset(). assert: route.called → bool. route.call_count. route.calls.last.request.content. respx.calls — all calls. Claude Code generates respx mock routes, async test fixtures, and call assertion patterns.

CLAUDE.md for respx

## respx Stack
- Version: respx >= 0.21 | pip install respx
- Mock: with respx.mock: ... | @respx.mock decorator | respx.mock(assert_all_called=True)
- Route: respx.get(url).mock(return_value=httpx.Response(200, json={...}))
- Match: url__regex | url__startswith | headers | json for flexible matching
- Dynamic: route.mock(side_effect=lambda req: httpx.Response(...)) — inspect request
- Async: async with respx.mock — works with httpx.AsyncClient
- Assert: route.called | route.call_count | route.calls.last.request

respx HTTP Mocking Pipeline

# tests/test_api_client.py — respx mock usage
from __future__ import annotations

import json
from typing import Any

import httpx
import pytest
import respx


# ─────────────────────────────────────────────────────────────────────────────
# API client under test
# ─────────────────────────────────────────────────────────────────────────────

BASE_URL = "https://api.example.com"


class UserApiClient:
    """Synchronous httpx client wrapping a fictional User API."""

    def __init__(self, base_url: str = BASE_URL, token: str = "token-xyz") -> None:
        self._base_url = base_url.rstrip("/")
        self._headers  = {"Authorization": f"Bearer {token}"}

    def list_users(self, page: int = 1, page_size: int = 20) -> list[dict]:
        with httpx.Client() as client:
            r = client.get(
                f"{self._base_url}/users",
                params={"page": page, "page_size": page_size},
                headers=self._headers,
            )
            r.raise_for_status()
            return r.json()

    def get_user(self, user_id: int) -> dict:
        with httpx.Client() as client:
            r = client.get(
                f"{self._base_url}/users/{user_id}",
                headers=self._headers,
            )
            r.raise_for_status()
            return r.json()

    def create_user(self, payload: dict) -> dict:
        with httpx.Client() as client:
            r = client.post(
                f"{self._base_url}/users",
                json=payload,
                headers=self._headers,
            )
            r.raise_for_status()
            return r.json()

    def update_user(self, user_id: int, payload: dict) -> dict:
        with httpx.Client() as client:
            r = client.patch(
                f"{self._base_url}/users/{user_id}",
                json=payload,
                headers=self._headers,
            )
            r.raise_for_status()
            return r.json()

    def delete_user(self, user_id: int) -> None:
        with httpx.Client() as client:
            r = client.delete(
                f"{self._base_url}/users/{user_id}",
                headers=self._headers,
            )
            r.raise_for_status()


class AsyncUserApiClient:
    """Async httpx client for the same API."""

    def __init__(self, base_url: str = BASE_URL, token: str = "token-xyz") -> None:
        self._base_url = base_url.rstrip("/")
        self._headers  = {"Authorization": f"Bearer {token}"}

    async def list_users(self, page: int = 1) -> list[dict]:
        async with httpx.AsyncClient() as client:
            r = await client.get(
                f"{self._base_url}/users",
                params={"page": page},
                headers=self._headers,
            )
            r.raise_for_status()
            return r.json()

    async def create_user(self, payload: dict) -> dict:
        async with httpx.AsyncClient() as client:
            r = await client.post(
                f"{self._base_url}/users",
                json=payload,
                headers=self._headers,
            )
            r.raise_for_status()
            return r.json()


# ─────────────────────────────────────────────────────────────────────────────
# pytest fixtures
# ─────────────────────────────────────────────────────────────────────────────

@pytest.fixture
def client() -> UserApiClient:
    return UserApiClient(token="test-token")


@pytest.fixture
def async_client() -> AsyncUserApiClient:
    return AsyncUserApiClient(token="test-token")


@pytest.fixture
def mock_users() -> list[dict]:
    return [
        {"id": 1, "email": "[email protected]", "first_name": "Alice", "role": "admin"},
        {"id": 2, "email": "[email protected]",   "first_name": "Bob",   "role": "user"},
    ]


# ─────────────────────────────────────────────────────────────────────────────
# 1. Basic synchronous mocking — context manager
# ─────────────────────────────────────────────────────────────────────────────

class TestListUsers:

    def test_returns_user_list(self, client: UserApiClient, mock_users: list[dict]) -> None:
        with respx.mock:
            respx.get(f"{BASE_URL}/users").mock(
                return_value=httpx.Response(200, json=mock_users)
            )
            result = client.list_users()

        assert len(result) == 2
        assert result[0]["email"] == "[email protected]"

    def test_empty_list(self, client: UserApiClient) -> None:
        with respx.mock:
            respx.get(f"{BASE_URL}/users").mock(
                return_value=httpx.Response(200, json=[])
            )
            result = client.list_users()

        assert result == []

    def test_server_error_raises(self, client: UserApiClient) -> None:
        with respx.mock:
            respx.get(f"{BASE_URL}/users").mock(
                return_value=httpx.Response(500, json={"detail": "Internal error"})
            )
            with pytest.raises(httpx.HTTPStatusError):
                client.list_users()


class TestGetUser:

    def test_returns_user(self, client: UserApiClient) -> None:
        user = {"id": 1, "email": "[email protected]", "role": "admin"}
        with respx.mock:
            respx.get(f"{BASE_URL}/users/1").mock(
                return_value=httpx.Response(200, json=user)
            )
            result = client.get_user(1)

        assert result["email"] == "[email protected]"

    def test_not_found_raises(self, client: UserApiClient) -> None:
        with respx.mock:
            respx.get(f"{BASE_URL}/users/999").mock(
                return_value=httpx.Response(404, json={"detail": "User not found"})
            )
            with pytest.raises(httpx.HTTPStatusError) as exc_info:
                client.get_user(999)
            assert exc_info.value.response.status_code == 404


# ─────────────────────────────────────────────────────────────────────────────
# 2. POST with request body inspection
# ─────────────────────────────────────────────────────────────────────────────

class TestCreateUser:

    def test_creates_and_returns_user(self, client: UserApiClient) -> None:
        created = {"id": 3, "email": "[email protected]", "role": "user"}

        with respx.mock:
            route = respx.post(f"{BASE_URL}/users").mock(
                return_value=httpx.Response(201, json=created)
            )
            result = client.create_user({"email": "[email protected]", "role": "user"})

        assert result["id"] == 3
        # Verify request was made
        assert route.called
        assert route.call_count == 1
        # Inspect the request body
        sent = json.loads(route.calls.last.request.content)
        assert sent["email"] == "[email protected]"

    def test_validation_error_raises(self, client: UserApiClient) -> None:
        with respx.mock:
            respx.post(f"{BASE_URL}/users").mock(
                return_value=httpx.Response(422, json={"detail": [{"msg": "field required"}]})
            )
            with pytest.raises(httpx.HTTPStatusError):
                client.create_user({})


# ─────────────────────────────────────────────────────────────────────────────
# 3. side_effect — dynamic responses and error simulation
# ─────────────────────────────────────────────────────────────────────────────

class TestSideEffects:

    def test_network_timeout(self, client: UserApiClient) -> None:
        """Simulate a timeout exception."""
        with respx.mock:
            respx.get(f"{BASE_URL}/users").mock(
                side_effect=httpx.TimeoutException("Connection timed out")
            )
            with pytest.raises(httpx.TimeoutException):
                client.list_users()

    def test_connect_error(self, client: UserApiClient) -> None:
        with respx.mock:
            respx.get(f"{BASE_URL}/users").mock(
                side_effect=httpx.ConnectError("Connection refused")
            )
            with pytest.raises(httpx.ConnectError):
                client.list_users()

    def test_dynamic_response_from_request(self, client: UserApiClient) -> None:
        """side_effect callable receives the request — use it to echo request data."""
        def echo_params(request: httpx.Request) -> httpx.Response:
            page = request.url.params.get("page", "1")
            return httpx.Response(200, json={"page": int(page), "items": []})

        with respx.mock:
            respx.get(f"{BASE_URL}/users").mock(side_effect=echo_params)
            result = client.list_users(page=3)

        assert result["page"] == 3

    def test_sequential_responses(self, client: UserApiClient) -> None:
        """Return different responses on each call."""
        responses = [
            httpx.Response(503, json={"detail": "Service unavailable"}),
            httpx.Response(503, json={"detail": "Service unavailable"}),
            httpx.Response(200, json=[{"id": 1}]),
        ]
        calls = 0

        def side_effect(_: httpx.Request) -> httpx.Response:
            nonlocal calls
            resp = responses[min(calls, len(responses) - 1)]
            calls += 1
            return resp

        with respx.mock:
            respx.get(f"{BASE_URL}/users").mock(side_effect=side_effect)
            # First call — 503
            with pytest.raises(httpx.HTTPStatusError):
                client.list_users()


# ─────────────────────────────────────────────────────────────────────────────
# 4. Regex and pattern matching
# ─────────────────────────────────────────────────────────────────────────────

class TestPatternMatching:

    def test_regex_url_matching(self, client: UserApiClient) -> None:
        with respx.mock:
            respx.get(url__regex=rf"{BASE_URL}/users/\d+").mock(
                return_value=httpx.Response(200, json={"id": 42, "email": "[email protected]"})
            )
            result = client.get_user(42)

        assert result["id"] == 42


# ─────────────────────────────────────────────────────────────────────────────
# 5. Async client testing
# ─────────────────────────────────────────────────────────────────────────────

class TestAsyncClient:

    @pytest.mark.asyncio
    async def test_async_list_users(
        self, async_client: AsyncUserApiClient, mock_users: list[dict],
    ) -> None:
        async with respx.mock:
            respx.get(f"{BASE_URL}/users").mock(
                return_value=httpx.Response(200, json=mock_users)
            )
            result = await async_client.list_users()

        assert len(result) == 2

    @pytest.mark.asyncio
    async def test_async_create_user(self, async_client: AsyncUserApiClient) -> None:
        created = {"id": 5, "email": "[email protected]", "role": "user"}
        with respx.mock:
            route = respx.post(f"{BASE_URL}/users").mock(
                return_value=httpx.Response(201, json=created)
            )
            result = await async_client.create_user({"email": "[email protected]"})

        assert result["id"] == 5
        sent = json.loads(route.calls.last.request.content)
        assert sent["email"] == "[email protected]"


# ─────────────────────────────────────────────────────────────────────────────
# 6. @respx.mock decorator
# ─────────────────────────────────────────────────────────────────────────────

@respx.mock
def test_delete_user_with_decorator(respx_mock: respx.MockRouter) -> None:
    client = UserApiClient()
    route = respx_mock.delete(f"{BASE_URL}/users/1").mock(
        return_value=httpx.Response(204)
    )
    client.delete_user(1)
    assert route.called
    assert route.call_count == 1

For the responses library alternative — responses patches requests.get/post/... and only works with the synchronous requests library, while respx is purpose-built for httpx — both its sync httpx.Client and async httpx.AsyncClient — so async with respx.mock: result = await client.get(url) works without any extra patching, and route.calls.last.request exposes the full httpx.Request object (URL, headers, content, stream) rather than a simplified mock call record. For the pytest-httpx alternative — pytest-httpx is an official httpx test plugin providing a httpx_mock pytest fixture, while respx works as both a context manager and a decorator independent of pytest — useful when mocking outside of test functions or in production circuit-breaker logic — and respx’s url__regex and url__startswith matchers handle path-param routes more concisely than pytest-httpx’s match_ parameters. The Claude Skills 360 bundle includes respx skill sets covering respx.mock context manager and decorator, respx.get/post/put/patch/delete route registration, url__regex and url__startswith pattern matching, httpx.Response with JSON headers and status codes, side_effect for timeouts/errors/dynamic responses, sequential response cycling, route.called/call_count/calls.last.request for assertions, async with respx.mock for AsyncClient, Router for reusable mock sets, and pytest fixture integration. Start with the free tier to try httpx mocking code generation.

Keep Reading

AI

Claude Code for email.contentmanager: Python Email Content Accessors

Read and write EmailMessage body content with Python's email.contentmanager module and Claude Code — email contentmanager ContentManager for the class that maps content types to get and set handler functions allowing EmailMessage to support get_content and set_content with type-specific behaviour, email contentmanager raw_data_manager for the ContentManager instance that handles raw bytes and str payloads without any conversion, email contentmanager content_manager for the standard ContentManager instance used by email.policy.default that intelligently handles text plain text html multipart and binary content types, email contentmanager get_content_text for the handler that returns the decoded text payload of a text-star message part as a str, email contentmanager get_content_binary for the handler that returns the raw decoded bytes payload of a non-text message part, email contentmanager get_data_manager for the get-handler lookup used by EmailMessage get_content to find the right reader function for the content type, email contentmanager set_content text for the handler that creates and sets a text part correctly choosing charset and transfer encoding, email contentmanager set_content bytes for the handler that creates and sets a binary part with base64 encoding and optional filename Content-Disposition, email contentmanager EmailMessage get_content for the method that reads the message body using the registered content manager handlers, email contentmanager EmailMessage set_content for the method that sets the message body and MIME headers in one call, email contentmanager EmailMessage make_alternative make_mixed make_related for the methods that convert a simple message into a multipart container, email contentmanager EmailMessage add_attachment for the method that attaches a file or bytes to a multipart message, and email contentmanager integration with email.message and email.policy and email.mime and io for building high-level email readers attachment extractors text body accessors HTML readers and policy-aware MIME construction pipelines.

5 min read Feb 12, 2029
AI

Claude Code for email.charset: Python Email Charset Encoding

Control header and body encoding for international email with Python's email.charset module and Claude Code — email charset Charset for the class that wraps a character set name with the encoding rules for header encoding and body encoding describing how to encode text for that charset in email messages, email charset Charset header_encoding for the attribute specifying whether headers using this charset should use QP quoted-printable encoding BASE64 encoding or no encoding, email charset Charset body_encoding for the attribute specifying the Content-Transfer-Encoding to use for message bodies in this charset such as QP or BASE64, email charset Charset output_codec for the attribute giving the Python codec name used to encode the string to bytes for the wire format, email charset Charset input_codec for the attribute giving the Python codec name used to decode incoming bytes to str, email charset Charset get_output_charset for returning the output charset name, email charset Charset header_encode for encoding a header string using the charset's header_encoding method, email charset Charset body_encode for encoding body content using the charset's body_encoding, email charset Charset convert for converting a string from the input_codec to the output_codec, email charset add_charset for registering a new charset with custom encoding rules in the global charset registry, email charset add_alias for adding an alias name that maps to an existing registered charset, email charset add_codec for registering a codec name mapping for use by the charset machinery, and email charset integration with email.message and email.mime and email.policy and email.encoders for building international email senders non-ASCII header encoders Content-Transfer-Encoding selectors charset-aware message constructors and MIME encoding pipelines.

5 min read Feb 11, 2029
AI

Claude Code for email.utils: Python Email Address and Header Utilities

Parse and format RFC 2822 email addresses and dates with Python's email.utils module and Claude Code — email utils parseaddr for splitting a display-name plus angle-bracket address string into a realname and email address tuple, email utils formataddr for combining a realname and address string into a properly quoted RFC 2822 address with angle brackets, email utils getaddresses for parsing a list of raw address header strings each potentially containing multiple comma-separated addresses into a list of realname address tuples, email utils parsedate for parsing an RFC 2822 date string into a nine-tuple compatible with time.mktime, email utils parsedate_tz for parsing an RFC 2822 date string into a ten-tuple that includes the UTC offset timezone in seconds, email utils parsedate_to_datetime for parsing an RFC 2822 date string into an aware datetime object with timezone, email utils formatdate for formatting a POSIX timestamp or the current time as an RFC 2822 date string with optional usegmt and localtime flags, email utils format_datetime for formatting a datetime object as an RFC 2822 date string, email utils make_msgid for generating a globally unique Message-ID string with optional idstring and domain components, email utils decode_rfc2231 for decoding an RFC 2231 encoded parameter value into a tuple of charset language and value, email utils encode_rfc2231 for encoding a string as an RFC 2231 encoded parameter value, email utils collapse_rfc2231_value for collapsing a decoded RFC 2231 tuple to a Unicode string, and email utils integration with email.message and email.headerregistry and datetime and time for building address parsers date formatters message-id generators header extractors and RFC-compliant email construction utilities.

5 min read Feb 10, 2029

Put these ideas into practice

Claude Skills 360 gives you production-ready skills for everything in this article — and 2,350+ more. Start free or go all-in.

Back to Blog

Get 360 skills free