Skip to content

Instantly share code, notes, and snippets.

@Integralist
Created January 13, 2025 16:26
Show Gist options
  • Save Integralist/12a6f901da071120d3a45e41b3eb0f12 to your computer and use it in GitHub Desktop.
Save Integralist/12a6f901da071120d3a45e41b3eb0f12 to your computer and use it in GitHub Desktop.
[OpenAPI feature flags use different schemas] #schemas #openapi #api #design

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."
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment