Anthropic::Middleware
HTTP middleware system for inspecting, rewriting, or short-circuiting requests and responses around the SDK's terminal HTTP send.
A middleware is any type that includes Anthropic::Middleware and
implements #call(request, nxt). The chain runs once per HTTP attempt,
inside the SDK's retry loop, so a middleware observes every retry and may
call nxt multiple times to implement custom retry logic.
nxt.call(request) returns an APIResponse for every HTTP status
(4xx/5xx do not raise inside the chain — typed error raising happens
after the chain returns). Connection-level failures (APITimeoutError,
APIConnectionError) do raise from nxt.call.
Limitation: only buffered JSON requests (GET/POST/DELETE) run through
the chain. Streaming (messages.stream / open_stream / SSE endpoints),
raw downloads, and multipart uploads bypass middleware entirely.
Registration: Anthropic::Client.new(middleware: [my_mw]) (outermost first).
class LoggingMiddleware
include Anthropic::Middleware
def call(request : Anthropic::APIRequest, nxt : Anthropic::MiddlewareNext) : Anthropic::APIResponse
puts "-> #{request.method} #{request.path}"
response = nxt.call(request)
puts "<- #{response.status}"
response
end
end
client = Anthropic::Client.new(middleware: [LoggingMiddleware.new])