Skip to content

Request context

Endpoint methods have no parameter for specifying HTTP headers. Default headers that should apply to every request can be set on the HTTP client. Some headers belong to a single call, though, (e.g., a correlation ID taken from the incoming request in a web service or an idempotency key).

Sometimes you need to see the raw responses behind a call, for example to write an audit log.

A request context covers both. You set it around one or more calls, and a hook on the entry endpoint's HTTP client applies it to every request sent while it is active:

  • Headers are added to each request.
  • A callback receives each response: method, URI, status, headers and body.

This tutorial extends the AddressBookClient from Build your first client, with the constructors from Authentication that take an HTTP client.

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.

1. Add the hook to the HTTP client

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. 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";

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; see Browsers below.

Requests sent without a context pass through unchanged.

2. Add headers to 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.

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 to requests sent on the same thread.

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 to requests sent on the same thread.

withRequestContext() makes a context current while a function runs, including asynchronous work it starts:

import { withRequestContext } from "typedrest/node";

const contact = await withRequestContext(
    { headers: { "X-Correlation-Id": correlationId } },
    () => client.contacts.get("1337").read());

3. Capture responses

Set a callback to receive each response:

var context = new RequestContext
{
    OnResponse = response => logger.LogInformation("{Method} {Uri} returned {Status}: {Body}",
        response.Method, response.Uri, (int)response.StatusCode, response.Body),
    MaxBodySize = 64 * 1024
};
using (RequestContext.Begin(context))
{
    await client.Contacts["1337"].Note.SetAsync(new Note { Content = "Call back on Monday" });
}
RequestContext context = new RequestContext(
    Map.of(),
    response -> logger.info("{} {} returned {}: {}", response.getMethod(), response.getUri(), response.getStatus(), response.getBody()),
    64 * 1024L);
RequestContext.use(context, () -> {
    client.getContacts().get("1337").getNote().set(new Note("Call back on Monday"));
    return null;
});
val context = RequestContext(
    onResponse = { logger.info("${it.method} ${it.uri} returned ${it.status}: ${it.body}") },
    maxBodySize = 64 * 1024L)
RequestContext.use(context) {
    client.contacts["1337"].note.set(Note("Call back on Monday"))
}
await withRequestContext({
    onResponse: response => console.log(`${response.method} ${response.uri} returned ${response.status}: ${response.body}`),
    maxBodySize: 64 * 1024
}, () => client.contacts.get("1337").note.set({ content: "Call back on Monday" }));

The callback may return a promise; the request completes only once it has resolved.

What the callback receives:

  • One call per HTTP request, not per endpoint method. A single method can send several requests, for example a lazy HEAD request to look up a link, or a GET followed by a PUT when you update an element with a callback.
  • Error responses. The callback runs before TypedRest turns a non-success status into an exception, so you can log the body the server sent along with the error.
  • The body as text, truncated to the maximum size (in bytes) if you set one. Capturing reads a copy, so TypedRest still sees the whole body.
  • No body (null/undefined) for binary content, for streams such as text/event-stream, and for requests from streaming endpoints and blob downloads, so capturing never buffers a stream.
  • No body for 304 Not Modified, even if TypedRest then returns an entity from its cache.

Response headers can contain secrets, such as session cookies, and bodies can contain personal data. Redact them before writing them to a log.

Where the context applies

The AsyncLocal reaches every request started inside the scope, including requests sent from background tasks such as the lazy link lookup and reconnecting Server-Sent Events.

The ThreadLocal reaches only requests sent on the thread that called use(). 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.

The ThreadLocal reaches only requests sent on the thread that called use(). 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.

TypedRest's endpoint methods are blocking, and the block passed to use() cannot suspend, so the context stays on one thread even in coroutines. Call use() inside the coroutine, around the TypedRest calls, rather than around code that switches dispatchers.

AsyncLocalStorage reaches every request started inside withRequestContext(), including reconnects of Server-Sent Events started there.

Browsers

Browsers have no way yet to carry a context across await. Use FixedRequestContextStorage instead, which applies the same context to every request of one HTTP client, and 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.

Next steps