Intercepting requests¶
Endpoint methods send HTTP requests for you, so you never see the requests or the responses behind them. That becomes a challenge when you need to:
- add a header to a single call, such as a correlation ID,
- log the raw responses, for example for an audit log, or
- refresh an expired OAuth token and retry.
Endpoint methods have no parameters for this. Instead, you add an interceptor to the entry endpoint's HTTP client. An interceptor sees each request before it is sent and each response before TypedRest processes it. Each language has its own kind of interceptor:
| Language | Interceptor |
|---|---|
| C# | DelegatingHandler |
| Java / Kotlin | OkHttp Interceptor |
| TypeScript | DelegatingHttpClient |
This tutorial shows two interceptors:
- Per-call headers uses the request context interceptor built into TypedRest.
- Capture responses shows how to write your own interceptor.
The authentication tutorial shows a third one, which refreshes OAuth tokens.
Per-call headers¶
Endpoint methods have no parameter for HTTP headers. You can set default headers on the HTTP client, but those apply to every request. Some headers belong to a single call, though, such as a correlation ID taken from the incoming request in a web service, or an idempotency key.
The request context covers these. You register its interceptor on the HTTP client once. Then you set a context around one or more calls, and the interceptor adds the context's headers to every request sent while it is active.
Distributed tracing
For W3C Trace Context (traceparent), you may not need a request context at all. In .NET, HttpClient sends traceparent for the current Activity, and TypedRest starts an Activity for each endpoint call (source name TypedRest). On the JVM and in TypeScript, the OpenTelemetry instrumentation for OkHttp and fetch does the same. Use a request context for headers that tracing does not cover.
Register the request context interceptor¶
Wrap the HttpClient's handler in a RequestContextHandler:
var client = new AddressBookClient(
new HttpClient(new RequestContextHandler(new HttpClientHandler())) { BaseAddress = new Uri("https://example.com/api/") });
With dependency injection, call .AddRequestContext() instead:
builder.Services.AddTypedRest<AddressBookClient>(new Uri("https://example.com/api/"))
.AddRequestContext();
Add a RequestContextInterceptor to the OkHttpClient:
OkHttpClient httpClient = new OkHttpClient.Builder()
.addInterceptor(new RequestContextInterceptor())
.build();
AddressBookClient client = new AddressBookClient(URI.create("https://example.com/api/"), httpClient);
withRequestContext() returns a copy of an OkHttpClient with a RequestContextInterceptor added:
val client = AddressBookClient(URI.create("https://example.com/api/"), OkHttpClient().withRequestContext())
Wrap the HTTP client in a RequestContextHttpClient. It needs a place to look up the current context, which depends on where your code runs.
On servers (Node.js, Bun, Deno, Cloudflare Workers with Node.js compatibility), use asyncLocalRequestContext, which is based on AsyncLocalStorage:
import { RequestContextHttpClient } from "typedrest/http";
import { asyncLocalRequestContext } from "typedrest/node";
// The HTTP client is the fifth argument of the entry endpoint constructor
const client = new AddressBookClient(
new URL("https://example.com/api/"), undefined, undefined, undefined,
new RequestContextHttpClient(asyncLocalRequestContext));
typedrest/node is a separate entry point, so browser bundles do not pull in node:async_hooks.
Browsers have no equivalent of AsyncLocalStorage yet, so they cannot carry a context across await. Use FixedRequestContextStorage instead, which applies the same context to every request of one HTTP client. Create a client for each context, for example for each user action:
import { FixedRequestContextStorage, RequestContextHttpClient } from "typedrest/http";
function clientFor(correlationId: string) {
return new AddressBookClient(
new URL("https://example.com/api/"), undefined, undefined, undefined,
new RequestContextHttpClient(new FixedRequestContextStorage({ headers: { "X-Correlation-Id": correlationId } })));
}
Creating endpoints sends no requests, but each client has its own caches for links and ETags. Reuse a client for as long as its context stays the same. In browsers, skip the next step: the context is already set.
Set a context for a call¶
RequestContext.Begin() makes a context current until the returned scope is disposed:
using (RequestContext.Begin(new() { Headers = { ["X-Correlation-Id"] = correlationId } }))
{
var contact = await client.Contacts["1337"].ReadAsync();
await client.Contacts["1337"].Note.SetAsync(new Note { Content = "Call back on Monday" });
}
The context is stored in an AsyncLocal, so it flows across await and into tasks started inside the scope. That includes requests TypedRest sends in the background, such as lazy link lookups and reconnects of Server-Sent Events.
RequestContext.use() makes a context current while a Callable runs:
Contact contact = RequestContext.use(
new RequestContext(Map.of("X-Correlation-Id", correlationId)),
() -> client.getContacts().get("1337").read());
The context is stored in a ThreadLocal, so it applies only to requests sent on the thread that called use().
Reactive endpoints
The endpoints in typedrest-reactive (polling, streaming, Server-Sent Events) send their requests on RxJava's I/O scheduler, so they do not see the context.
RequestContext.use() makes a context current while a block runs:
val contact = RequestContext.use(RequestContext(headers = mapOf("X-Correlation-Id" to correlationId))) {
client.contacts["1337"].read()
}
The context is stored in a ThreadLocal, so it applies only to requests sent on the thread that called use().
Reactive endpoints and coroutines
The endpoints in typedrest-reactive (polling, streaming, Server-Sent Events) send their requests on RxJava's I/O scheduler, so they do not see the context.
In coroutines, call use() inside the coroutine, around the TypedRest calls, rather than around code that switches dispatchers. TypedRest's endpoint methods are blocking and the block passed to use() cannot suspend, so the context then stays on one thread.
withRequestContext() makes a context current while a function runs:
import { withRequestContext } from "typedrest/node";
const contact = await withRequestContext(
{ headers: { "X-Correlation-Id": correlationId } },
() => client.contacts.get("1337").read());
AsyncLocalStorage carries the context into asynchronous work started inside the function. That includes reconnects of Server-Sent Events started there.
Capture responses¶
Sometimes you need the raw responses behind your calls, for example for an audit log. TypedRest has no built-in interceptor for this, so you write your own.
The interceptor is called for every response. It reads a copy of the body, so TypedRest still gets the whole body afterwards. Reading the body waits until all of it has arrived, though. That is why the examples only read JSON bodies and skip binary content such as blob downloads and streams such as text/event-stream.
Write the interceptor¶
Derive from DelegatingHandler. Buffer the content before reading it, so it can be read again:
public class ResponseLoggingHandler(ILogger logger) : DelegatingHandler
{
protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
{
var response = await base.SendAsync(request, cancellationToken);
if (response.Content.Headers.ContentType?.MediaType is "application/json")
{
await response.Content.LoadIntoBufferAsync();
logger.LogInformation("{Method} {Uri} returned {Status}: {Body}",
request.Method, request.RequestUri, (int)response.StatusCode, await response.Content.ReadAsStringAsync());
}
return response;
}
}
Implement an OkHttp Interceptor. peekBody() reads a copy of the body, up to a maximum number of bytes:
public class ResponseLoggingInterceptor implements Interceptor {
private final Logger logger;
public ResponseLoggingInterceptor(Logger logger) {
this.logger = logger;
}
@Override
public Response intercept(Chain chain) throws IOException {
Request request = chain.request();
Response response = chain.proceed(request);
MediaType contentType = response.body().contentType();
if (contentType != null && contentType.subtype().equals("json")) {
logger.info("{} {} returned {}: {}",
request.method(), request.url(), response.code(), response.peekBody(64 * 1024).string());
}
return response;
}
}
Implement an OkHttp Interceptor. peekBody() reads a copy of the body, up to a maximum number of bytes:
class ResponseLoggingInterceptor(private val logger: Logger) : Interceptor {
override fun intercept(chain: Interceptor.Chain): Response {
val request = chain.request()
val response = chain.proceed(request)
if (response.body.contentType()?.subtype == "json") {
logger.info("${request.method} ${request.url} returned ${response.code}: ${response.peekBody(64 * 1024).string()}")
}
return response
}
}
Derive from DelegatingHttpClient. clone() gives you a copy of the response to read:
import { DelegatingHttpClient, HttpMethod } from "typedrest/http";
class ResponseLoggingHttpClient extends DelegatingHttpClient {
override async send(uri: URL, method: HttpMethod, signal?: AbortSignal, headers?: HeadersInit, body?: BodyInit) {
const response = await super.send(uri, method, signal, headers, body);
if (response.headers.get("Content-Type")?.split(";")[0] === "application/json")
console.log(`${method} ${uri} returned ${response.status}: ${await response.clone().text()}`);
return response;
}
}
Register the interceptor¶
var client = new AddressBookClient(
new HttpClient(new ResponseLoggingHandler(logger) { InnerHandler = new HttpClientHandler() })
{
BaseAddress = new Uri("https://example.com/api/")
});
With dependency injection:
builder.Services.AddTypedRest<AddressBookClient>(new Uri("https://example.com/api/"))
.AddHttpMessageHandler(sp => new ResponseLoggingHandler(sp.GetRequiredService<ILogger<ResponseLoggingHandler>>()));
OkHttpClient httpClient = new OkHttpClient.Builder()
.addInterceptor(new ResponseLoggingInterceptor(logger))
.build();
AddressBookClient client = new AddressBookClient(URI.create("https://example.com/api/"), httpClient);
val httpClient = OkHttpClient.Builder()
.addInterceptor(ResponseLoggingInterceptor(logger))
.build()
val client = AddressBookClient(URI.create("https://example.com/api/"), httpClient)
DelegatingHttpClient sends requests with a FetchHttpClient unless you pass another inner client:
const client = new AddressBookClient(
new URL("https://example.com/api/"), undefined, undefined, undefined,
new ResponseLoggingHttpClient());
Combine with other interceptors¶
You can chain several interceptors on one client. The outermost interceptor sees each request first and each response last. To log requests including the headers the request context adds, put the request context interceptor outside the logging interceptor:
The handler you pass to HttpClient is the outermost one:
var client = new AddressBookClient(
new HttpClient(new RequestContextHandler(new ResponseLoggingHandler(logger) { InnerHandler = new HttpClientHandler() }))
{
BaseAddress = new Uri("https://example.com/api/")
});
With dependency injection, handlers added first are outermost:
builder.Services.AddTypedRest<AddressBookClient>(new Uri("https://example.com/api/"))
.AddRequestContext()
.AddHttpMessageHandler(sp => new ResponseLoggingHandler(sp.GetRequiredService<ILogger<ResponseLoggingHandler>>()));
Interceptors added first are outermost:
OkHttpClient httpClient = new OkHttpClient.Builder()
.addInterceptor(new RequestContextInterceptor())
.addInterceptor(new ResponseLoggingInterceptor(logger))
.build();
Interceptors added first are outermost:
val httpClient = OkHttpClient.Builder()
.addInterceptor(RequestContextInterceptor())
.addInterceptor(ResponseLoggingInterceptor(logger))
.build()
Pass the inner interceptor as the last constructor argument of the outer one:
const client = new AddressBookClient(
new URL("https://example.com/api/"), undefined, undefined, undefined,
new RequestContextHttpClient(asyncLocalRequestContext, new ResponseLoggingHttpClient()));
Things to keep in mind¶
- One call per HTTP request, not per endpoint method. A single method can send several requests, for example a lazy
HEADrequest to look up a link, or aGETfollowed by aPUTwhen you update an element with a callback. - Error responses pass through it too. The interceptor runs before TypedRest turns a non-success status into an exception, so you can log the body the server sent along with the error.
- Streaming endpoints that return JSON are read to the end. If you use streaming endpoints with JSON content, give them an HTTP client without this interceptor, or check the request URI in the interceptor.
304 Not Modifiedhas no body, even if TypedRest then returns an entity from its cache.- Every call is logged, not only those inside a request context. To log only some calls, keep a flag where the request context is kept (an
AsyncLocalin .NET, aThreadLocalon the JVM,AsyncLocalStoragein Node.js) and check it in the interceptor.
Sensitive data
Response bodies can contain personal data, and headers can contain secrets such as session cookies. Redact them before writing them to a log.
Next steps¶
- Authentication: an interceptor that adds OAuth tokens and refreshes them.
- Testing your client: test endpoints and the code that uses them.
- Error handling: the exceptions TypedRest throws for error responses.