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
