Skip to main content

Inheritance and Polymorphism with AllOf

APIMatic's SDKs support allOf types defined in OpenAPI specifications. This feature allows you to define schemas that inherit from multiple definitions, ensuring that an object adheres to all specified schemas simultaneously. This approach promotes modular and reusable schema definitions.

Configure AllOf in your OpenAPI Definition

Here is an example of an allOf type where discriminator is position defined in OpenAPI definition:

components:
schemas:
User:
type: object
properties:
position:
type: string
name:
type: string
email:
type: string
format: email
discriminator:
propertyName: position
mapping:
Empl: Employee
Adm: Admin
User: User
Admin:
allOf:
- $ref: '#/components/schemas/User'
- type: object
properties:
permissions:
type: array
items:
type: string
Employee:
allOf:
- $ref: '#/components/schemas/User'
- type: object
properties:
role:
type: string

In the above example:

  • The User schema defines common properties.
  • The Admin schema extends the User schema and adds permissions.
  • The Employee schema extends the User schema and adds role.

Model Definitions in SDKs

note
  • If allOf is used with a discriminator, the SDK handles type resolution for polymorphic schemas.
  • If allOf is used without a discriminator, the SDK merges all referenced properties into a single structure.

Here is how inheritance and polymorphism affects the models in APIMatic SDKs when the allOf construct is used.

export interface User {
name?: string;
email?: string;
}

export interface Admin extends User {
permissions?: string[];
}

export interface Employee extends User {
role?: string;
}

Any endpoint that takes in an argument of type User will also be compatible with types Admin and Employee. Take the following example of an endpoint CreateUser that takes in the argument of type User.

async () => {
const admin: Admin = { name: 'Alice', email: 'alice@example.com', permissions: ['read', 'write'] };
await apiController.createUser(admin);

const employee: Employee = { name: 'Bob', email: 'bob@example.com', role: 'Manager' };
await apiController.createUser(employee);
};

Key Benefits

  • Re-usability: Promotes schema reuse by allowing composition.
  • Clarity: Simplifies schema definitions by breaking down complex models into smaller components.