« Back to Index

OpenAPI: feature flags use different schemas

View original Gist on GitHub

Tags: #schemas #openapi #api #design

README.md

I don’t know if this actually works but apparently you can use a discriminator like this…

[!NOTE] In this example, your API has to return a type property that might have a value like "base" or "feature_x".

If the API response contains "type": "base", then the OpenAPI schema will use the BaseResponse schema. Otherwise, if it’s "type": "feature_x", the OpenAPI schema will use the eatureXResponse schema.

openapi: 3.1.0
info:
  title: Discriminator Example API
  version: 1.0.0
paths:
  /example:
    get:
      summary: Example endpoint with feature-flagged responses
      description: Returns different responses based on whether FeatureX is enabled.
      responses:
        '200':
          description: Successful response
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ApiResponse'

components:
  schemas:
    ApiResponse:
      type: object
      required:
        - type
      properties:
        type:
          type: string
          description: "Indicates the type of the response."
      discriminator:
        propertyName: type
        mapping:
          base: '#/components/schemas/BaseResponse'
          feature_x: '#/components/schemas/FeatureXResponse'
      oneOf:
        - $ref: '#/components/schemas/BaseResponse'
        - $ref: '#/components/schemas/FeatureXResponse'

    BaseResponse:
      type: object
      properties:
        type:
          type: string
          enum:
            - base
          description: "Base response type"
        message:
          type: string
          description: "A generic message."

    FeatureXResponse:
      type: object
      allOf:
        - $ref: '#/components/schemas/BaseResponse'
        - type: object
          properties:
            type:
              type: string
              enum:
                - feature_x
              description: "Indicates FeatureX response."
            feature_x_data:
              type: string
              description: "Additional data when FeatureX is enabled."