API Design Pattern of the Week 16: Context Representation

A pattern from the book “Patterns of API Design: Simplifying Integration with Loosely Coupled Message Exchanges”

Doc SoC (aka ZIO)
ZIO’s Blog
5 min readNov 2, 2023

--

Pattern 15 in this series was Rate Limit, Pattern 17 is Version Identifier. All “API Design Patterns of the Week” are listed here.

Note: This online excerpt of the pattern predates its final version in the book.

Context

An API endpoint and its operations have been defined. Context information has to be exchanged between API client and provider. Examples of such context information are client location and other API user profile data, the preferences forming a Wish List, or Quality-of-Service (QoS) controls such as credentials used to authenticate, authorize, and bill clients. Such credentials may be API Keys or JSON Web Tokens (JWT) claims.

Problem

How can API consumers and providers exchange context information without relying on any particular remoting protocols?

How can identity information and quality properties in a request be handed over to subsequent ones in conversations?

Interactions between API client and API provider might be part of conversations and consist of multiple related operation calls. API providers can also act as API clients that consume services provided by other APIs (in their implementations) to create operation call sequences. Some parts of the context information might be local to single operations; others might be shared and handed over from operation invocation to operation invocation in such conversations.

Forces

In this context, these desired qualities make the problem hard to solve:

  • Interoperability and modifiability on the technology/technical level
  • Developer productivity (control versus convenience)
  • Diversity of clients and their requirements
  • End-to-end security (across services and protocols)
  • Logging and auditing on business domain level (across invocations)

To promote protocol independence and a platform-independent design, the default headers and header extension capabilities available in the underlying communication protocol cannot not be used sometimes.

Solution Sketch

Combine and group all Metadata Elements that carry the desired information into a custom representation element in request and/or response messages. Do not transport this single Context Representation in protocol headers, but place it in the message payload.

Separate global from local context in a conversation by structuring the Context Representation accordingly. Position and mark the consolidated Context Representation element so that it is easy to find and distinguish from other Data Elements.

A PlantUML sketch for this pattern (from pre-book times) is:

Example

The following service contract sketch introduces a custom Context Representation in the payload of the request message of the getCustomerAttributes operation (rather than a protocol header). The Context Representation is tagged and highlighted with a<<Context_Representation>> stereotype and therefore easily recognizable in the response payload (notation: MDSL, our DSL for service contracts):

API description ContextRepresentationExample

data type KeyValuePair P // not specified
data type CustomerDTO P // not specified

data type RequestContext {
"apiKey":ID<string>,
"sessionId":D<int>?,
"qosPropertiesThatShouldNotGoToProtocolHeader":KeyValuePair*}

endpoint type CustomerInformationHolderService
exposes
operation getCustomerAttributes
expecting payload {
<<Context_Representation>> {
"requestContextSharedByAllOperations": RequestContext,
<<Wish_List>>"desiredCustomerAttributes":ID<string>+
},
<<Data_Element>> "searchParameters":D<string>*
}
delivering payload {
<<Context_Representation>> {
<<Metadata_Element>> {
"billingInfo": D<int>,
"moreAnalytics":D},
<<Error_Report>> {
"errorCode":D<int>,
"errorMessage":D<string>}
}, {
<<Pagination>> {
"thisPageContent":CustomerDTO*,
"previousPage":ID?,
"nextPage":ID?}
}
}

When transformed into OpenAPI, the above example renders as YAML as shown in the Context Representation Example. The request payload of getCustomerAttributes contains a second use of the pattern: The SharedContext contains an API Key as well as a session Id Element (to be created by the provider upon successful authentication). Additional free-form headers can be added in the key-value part of it.

Note that the example also features three additional patterns: Wish List, Error Report and Pagination.

Consequences

The resolution of pattern forces and other consequences are discussed in our book.

Known Uses

See pattern coverage on our website.

Related Patterns

A Context Representation contains and bundles multiple Metadata Elements for a particular purpose (with specific semantics, context sharing). An Error Report can find its place in a Context Representation, for instance when reporting errors caused by a Request Bundle (because the required summary-details structure is difficult to model in protocol-level headers or status codes).

A similar pattern appears in several other pattern languages. For instance, the Context Object (Alur, Malks, and Crupi 2013) solves the problem of protocol-independent storage of state and system information in a Java programming context (rather than in a remoting context).

The Invocation Context pattern (Voelter, Kircher, and Zdun 2004) describes a solution for bundling contextual information in an extensible invocation context of a distributed invocation. An Invocation Context is transferred between client and remote object with every remote invocation.

The Envelope Wrapper pattern (Hohpe and Woolf 2003) solves a similar problem, making certain parts of a message visible to the messaging infrastructure that is responsible for a particular hop/leg. Systems management patterns such as be used to implement the required auditing and logging.

Related Reading

Chapter 3 in the RESTful Web Services Cookbook (Allamaraju 2010) discusses an alternative approach based on entity headers (in the context of HTTP) in two of its recipes.

Slide 7 in “Dimensions of Successful Web API Design and Evolution: Context, Contracts, Components” defines the term context and reports on its meaning(s) in different contexts. Cambridge Dictionary defines it as “the situation within which something exists or happens, and that can help explain it”. “On the Representation of Context.” (Stalnaker 1996) gives a good overview of context representation in linguistics.

References

Allamaraju, Subbu. 2010. RESTful Web Services Cookbook. O’Reilly.

Alur, Deepak, Dan Malks, and John Crupi. 2013. Core J2ee Patterns: Best Practices and Design Strategies. 2nd ed. Prentice Hall.

Hohpe, Gregor, and Bobby Woolf. 2003. Enterprise Integration Patterns: Designing, Building, and Deploying Messaging Solutions. Addison-Wesley.

Stalnaker, Robert. 1996. “On the Representation of Context.” In Semantics and Linguistic Theory, 6:279–94.Voelter, Markus, Michael Kircher, and Uwe Zdun. 2004. Remoting Patterns — Foundations of Enterprise, Internet, and Realtime Distributed Object Middleware. Wiley.

Zimmermann, Olaf and Stocker, Mirko and Lübke, Daniel and Zdun, Uwe and Pautasso, Cesare. 2022. Patterns for API Design: Simplifying Integration with Loosely Coupled Message Exchanges, Vaughn Vernon Signature Series, Addison-Wesley Professional.

This book features 44 patterns plus API domain model, decision models, pattern adoption stories, … .

This pattern originally appeared on https://api-patterns.org.

We follow the standard format for patterns, from context to forces, problem, solution, consequences and known uses. Find out why.

Copyright © 2019–2023 by the authors. All rights reserved.
See terms and conditions of use.

--

--

Doc SoC (aka ZIO)
ZIO’s Blog

Architectural Decision Maker, Domain-Driven Designer, Serviceorienteer. Co-author of "Patterns for API Design", "Design Practice Reference", Y-Statements, MADR