liveBook · Manning

Polymorphic resource

As explained in API Design Patterns

A polymorphic resource is an API resource whose generic interface can represent multiple specific resource implementations with implementation-dependent behavior.

A polymorphic resource uses one generic API interface to represent several specific resource types, distinguished by an explicit type field. It centralizes shared methods such as listing and creating resources instead of duplicating them for every subtype. section 16.2

Choose polymorphism by comparing how the resources behave and how users retrieve them:

  • Use one resource when users reasonably need mixed lists, such as text, photo, audio, and video messages in one chat. section 16.3.1
  • Keep concepts independent when their access patterns differ substantially, even if they share some data; broadcast groups should not be forced into ChatRoom. section 16.3.1
  • Represent type as a validated string rather than an enumeration, and avoid changing an existing resource's type because references may depend on it. section 16.3.2
  • Validate that fields required by the selected type exist, while ignoring irrelevant fields rather than rejecting the request. section 16.6
  • Prefer polymorphic resources over polymorphic methods; a shared method can impose compatibility limits when subtype behavior later diverges. section 16.4

Messages with type-dependent content

A Message resource can expose id, sender, type, and content. The type might be text, photo, audio, or video, while content may be a string or media object. A single ListMessages operation can return every message, and a type filter can select only photos. section 16.3.2 section 16.3.3

Listing 16.3 Example of polymorphic resource with type field
interface Message {
  id: string;
  sender: string;
  type: 'text' | 'photo' | 'audio' | 'video';   #1
  // ...
}

Use the type field to make the generic interface explicit and constrain its supported variants. section 16.3.2

How API Design Patterns covers it

How deep it goes
Explains selection, type representation, validation, storage alternatives, behavior, and compatibility trade-offs, while discouraging polymorphic methods.
Examples
Uses Shape subtypes, mixed Message resources, ChatRoom listings, type filters, and a count-sides method.
What it assumes
Assumes familiarity with API resources and standard methods, while translating object-oriented inheritance into resource-oriented API design.
What you can do after
Apply it via a validated type field, shared resource methods, type-aware data validation, and deliberately stable subtype choices.
How it connects
Connects API resources with resource-oriented API design, validation, standard methods, filtering, and backward compatibility.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of API Design Patterns. The section links point to the parts of the book it draws on.