IC Improve Code Recipes

Recipe 13.1 · Python

IHttpClientFactory and Typed Clients

The Python listings are conversions of the book's C# code to Python 3.12. Each file's header says what it needs to run. The explanations were written for the C# version, so some names in the text refer to .NET.

Problem

Your application calls a customer API from several places. Under load it starts failing with "Only one usage of each socket address is normally permitted", or it keeps calling an old IP address for hours after the partner moved their service. The base URL is copied into each class, and nobody knows which timeout applies.

The way it's often written

Anti-pattern: shown so you can recognize it. Don't copy this one.

HttpClient implements IDisposable, so wrapping it in using looks responsible. It is the wrong lifetime. Disposing the client closes its connection pool, and the closed sockets sit in the TIME_WAIT state for up to a few minutes. At a few hundred calls a second the server runs out of ports. The opposite fix, one static HttpClient for the life of the process, solves the sockets and creates a new problem: connections stay open forever and never see a DNS change. The .Result blocks a thread and can deadlock in classic ASP.NET.

Requirements: Python 3.12+. Install: pip install httpx pydantic

Python Fetch a customer with a brand-new HTTP client per call (p278_r13_1_new_http_client_per_call_before.py)
"""Fetch a customer with a brand-new HTTP client per call

Source: ImproveCode, Chapter 13, Recipe 13.1 "IHttpClientFactory and Typed Clients"
Section: The way it's often written
Book page: 278  -- original C# listing
Converted from C# to Python.
ANTI-PATTERN: kept deliberately faithful to the C# 'not to copy' example; do not use.
HttpClient -> httpx.Client created and disposed per call (no connection reuse);
.Result blocking -> a synchronous client; JsonConvert -> pydantic TypeAdapter.
"""

from __future__ import annotations

import httpx
from pydantic import TypeAdapter

from p278_r13_1_customer_api_options_dto import CustomerDto


# Not to copy: a new HttpClient per call exhausts sockets under load
def get_customer(id: int) -> CustomerDto:
    with httpx.Client() as client:
        client.base_url = httpx.URL("https://api.example.com/")
        response = client.get("customers/" + str(id))
        response.raise_for_status()  # GetStringAsync throws on non-success
        json = response.text
        return TypeAdapter(CustomerDto).validate_json(json)

The improved recipe

Let IHttpClientFactory manage handler lifetimes, and wrap each remote service in a typed client that receives a configured HttpClient through its constructor.

The configuration it binds to:

JSON
{
  "CustomerApi": {
    "BaseAddress": "https://api.example.com/v2/",
    "Timeout": "00:00:30"
  }
}

In Program.cs, one line registers it, and any class can then take CustomerApiClient in its constructor: builder.Services.AddCustomerApi(builder.Configuration);

Requirements: Python 3.12+. Install: pip install pydantic pydantic-settings

Python Validated customer API options and the customer DTO (p278_r13_1_customer_api_options_dto.py)
"""Validated customer API options and the customer DTO

Source: ImproveCode, Chapter 13, Recipe 13.1 "IHttpClientFactory and Typed Clients"
Section: The improved recipe
Book page: 278  -- original C# listing
Converted from C# to Python.
Options class with DataAnnotations -> pydantic-settings BaseSettings ([Required] is a
required field, [Range] on TimeSpan -> ge/le on timedelta); record -> frozen dataclass.
Settings bind from environment variables such as CustomerApi__base_address.
"""

from __future__ import annotations

from dataclasses import dataclass
from datetime import timedelta
from typing import ClassVar

from pydantic import AnyHttpUrl, Field
from pydantic_settings import BaseSettings, SettingsConfigDict


class CustomerApiOptions(BaseSettings):
    SECTION_NAME: ClassVar[str] = "CustomerApi"

    model_config = SettingsConfigDict(
        env_prefix="CustomerApi__", case_sensitive=False)

    # [Required]
    base_address: AnyHttpUrl

    # [Range(typeof(TimeSpan), "00:00:01", "00:05:00")]
    timeout: timedelta = Field(
        default=timedelta(seconds=30),
        ge=timedelta(seconds=1),
        le=timedelta(minutes=5))


@dataclass(frozen=True)
class CustomerDto:
    id: int
    name: str
    email: str

Requirements: Python 3.12+. Install: pip install httpx pydantic

Python Typed customer API client returning None on 404 (p278_r13_1_typed_customer_api_client.py)
"""Typed customer API client returning None on 404

Source: ImproveCode, Chapter 13, Recipe 13.1 "IHttpClientFactory and Typed Clients"
Section: The improved recipe
Book page: 278-279  -- original C# listing
Converted from C# to Python.
Typed HttpClient -> a class wrapping an injected, long-lived httpx.AsyncClient;
ReadFromJsonAsync -> pydantic TypeAdapter; CancellationToken -> asyncio task cancellation.
"""

from __future__ import annotations

import httpx
from pydantic import TypeAdapter

from p278_r13_1_customer_api_options_dto import CustomerDto

_customer = TypeAdapter(CustomerDto | None)


class CustomerApiClient:
    def __init__(self, http: httpx.AsyncClient) -> None:
        self._http = http

    async def get_customer(self, id: int) -> CustomerDto | None:
        response = await self._http.get(f"customers/{id}")

        if response.status_code == httpx.codes.NOT_FOUND:
            return None

        response.raise_for_status()
        return _customer.validate_json(response.content)

Requirements: Python 3.12+. Install: pip install httpx

Python Register the customer API client with validated options (p279_r13_1_register_customer_api_client.py)
"""Register the customer API client with validated options

Source: ImproveCode, Chapter 13, Recipe 13.1 "IHttpClientFactory and Typed Clients"
Section: The improved recipe
Book page: 279  -- original C# listing
Converted from C# to Python.
AddHttpClient<T> -> a small builder that creates one shared httpx.AsyncClient (its
connection pool plays the role of IHttpClientFactory); ValidateOnStart -> pydantic
validation when the options are built. The builder stands in for IHttpClientBuilder.
"""

from __future__ import annotations

from collections.abc import Mapping
from dataclasses import dataclass
from typing import Any

import httpx

from p278_r13_1_customer_api_options_dto import CustomerApiOptions
from p278_r13_1_typed_customer_api_client import CustomerApiClient


@dataclass
class CustomerApiClientBuilder:
    """Collects client configuration; later recipes add a transport or auth."""

    options: CustomerApiOptions
    transport: httpx.AsyncBaseTransport | None = None
    auth: httpx.Auth | None = None

    def build(self) -> CustomerApiClient:
        http = httpx.AsyncClient(
            base_url=str(self.options.base_address),
            timeout=self.options.timeout.total_seconds(),
            headers={"User-Agent": "ImproveCode-CustomerSync/1.0"},
            transport=self.transport,
            auth=self.auth)
        return CustomerApiClient(http)


def add_customer_api(
        configuration: Mapping[str, Any] | None = None) -> CustomerApiClientBuilder:
    # Bind + ValidateDataAnnotations + ValidateOnStart: fails here, at startup.
    section = (configuration or {}).get(CustomerApiOptions.SECTION_NAME, {})
    options = CustomerApiOptions(**section)
    return CustomerApiClientBuilder(options)

How it works

The factory keeps a pool of HttpMessageHandler instances, the objects that own the actual connections. Each HttpClient it hands out is a cheap wrapper over a pooled handler. Handlers are recycled after two minutes by default, so connections are eventually reopened and pick up DNS changes, while the pool keeps sockets from piling up. You get the benefit of a shared client without its staleness.

AddHttpClient<CustomerApiClient> registers the typed client as transient and configures each HttpClient it receives with the base address, timeout and headers. All the knowledge about the remote service lives in two places: the options class and the client class. Callers see GetCustomerAsync, not URLs.

ValidateOnStart makes the application fail at start-up if BaseAddress is missing, instead of on the first call at three in the morning. Chapter 6 covers the options pattern in detail.

Two small details save hours. BaseAddress must end with a slash, and relative paths must not start with one. https://api.example.com/v2/ plus customers/7 gives /v2/customers/7, while /customers/7 would silently drop the /v2. And the 404 check comes before EnsureSuccessStatusCode, because "customer does not exist" is an expected answer, not an error.

Variations and pitfalls

  • Don't capture a typed client in a singleton. A singleton that takes CustomerApiClient in its constructor holds one handler forever, which brings back the DNS problem. Inject IHttpClientFactory into singletons and create clients when needed.
  • Console tools without dependency injection. Use one static client with a pooled-connection lifetime: new HttpClient(new SocketsHttpHandler { PooledConnectionLifetime = TimeSpan.FromMinutes(2) }). That gives the same behavior as the factory in one line.
  • Named clients. services.AddHttpClient("rates", ...) and factory.CreateClient("rates") work when a typed class would be overkill. I prefer typed clients because the compiler checks the name.
  • Testing. A typed client takes an HttpClient, so a test can pass one built over a stub HttpMessageHandler that returns canned responses. No mocking library is needed.

On .NET Framework

Microsoft.Extensions.Http supports .NET Framework 4.6.2 and later, so the factory works in older apps that use Microsoft.Extensions.DependencyInjection. Without dependency injection, use one static HttpClient and set ServicePointManager.FindServicePoint(uri).ConnectionLeaseTimeout to a few minutes so connections are recycled.