How do I generate OpenAPI schema oneOf value using DRF spectacular PolymorphicProxySerializer?

94 Views Asked by At

I'm trying to use PolymorphicProxySerializer to generate the OpenAPI schema for a view that responds differently depending on the status of a downstream service. Here's my call to extend_schema_view.

device_service_get_schema = extend_schema_view(
    get=extend_schema(
        description="Get information about the status of the device driver service.",
        responses={
            200: PolymorphicProxySerializer(
                component_name="MetaDeviceService",
                serializers=[
                    inline_serializer(
                        name="DeviceServiceFailurePayload",
                        fields={
                            "timestamp": OpenApiTypes.NONE,
                            "message": OpenApiTypes.STR,
                        },
                    ),
                    inline_serializer(
                        name="DeviceServiceSuccessPayload",
                        fields={
                            "timestamp": OpenApiTypes.DATETIME,
                            "devices": OpenApiTypes.OBJECT,
                        },
                    ),
                ],
                resource_type_field_name="timestamp",
            )
        },
    )
)

When I run OpenAPI generation, there are no errors or warnings and the endpoint definition is generated.

  /api/device-service:
    get:
      operationId: device_service_retrieve
      description: Get information about the status of the device driver service.
      tags:
      - device-service
      security:
      - cookieAuth: []
      - jwtAuth: []
      responses:
        '200':
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/MetaDeviceService'
          description: ''

This looks OK, no obvious problems here. But when I check the generated schema ref, the inline serializer definitions are missing.

    MetaDeviceService:
      oneOf: []
      discriminator:
        propertyName: timestamp
        mapping: {}

Notice oneOf is empty. How do I get DRF to populate oneOf with the inline serializer schemas I defined?

1

There are 1 best solutions below

1
fredkisss On

I think you could use a polymorphic serializer from drf-spectacular.