Polymorphism lets one common interface serve multiple concrete types while hiding type-specific implementation details. In an API, a generic resource carries an explicit type field that identifies its more specific form. section 16.1 section 16.2
Listing 16.1 Example of polymorphism in TypeScript
interface Shape {
countSides(): number; #1
}
class Triangle implements Shape { #2
countSides() { return 3; }
}
class Square implements Shape { #2
countSides() { return 4; }
}
A TypeScript example shows Shape defining countSides while Triangle and Square provide different implementations. section 16.1
Use polymorphic resources when clients reasonably expect to handle several related types together, such as different message types in one chat. A shared Shape resource can support one listing method instead of separate ListTriangles and ListSquares methods. section 16.2 section 16.6
The generic resource must accommodate fields required by its subtypes and validate them against the declared type. A square may need side length, while a triangle may need base and height. Store the type as a string, evolve its possible values carefully, and ignore irrelevant fields while still requiring relevant data. section 16.2 section 16.6
Counting sides through a resource
A POST method such as /{id=shapes/*}:countSides can accept a shape identifier and return { sides: 4 } for a square or { sides: 3 } for a triangle. The method remains attached to the generic Shape resource, while the result varies with its type. section 16.3.3
Apply these design rules:
- Choose polymorphism only when each concrete resource is genuinely a specialized form of the generic resource; otherwise, future separation may be difficult without breaking clients. section 16.4
- Prefer polymorphic resources over polymorphic methods. A shared method may reduce typing initially but restrict later behavioral differences. section 16.4
- Avoid a shared standard method such as UpdateResource when different resource types may eventually need different behavior. section 16.5








