3

I use DRF-Spectacular to generate the OpenAPI specification for my DRF-based API. So far, I do not add examples but instead rely on SwaggerUI to show examples based on the type and regex patterns.

However, in same cases, I would like to add examples directly to the openapi.yml file. I would like to define examples for individual Model or Serializer fields, similar to generating descriptions based on the help_text parameters.

Unfortunately, so far I've only found ways to defining complete examples for views and serializers based on OpenApiExample with extend_schema and extend_schema_serializer, respectively.

This leads me to my question: Is it possible to define examples for individual Model or Serializer fields with DRF-Spectacular and, if yes, how?

Aecturus
  • 163
  • 1
  • 4
  • What kind of examples do you want to add to the fields? Is it a set of predefined choices? Or simply any data of a specific type? – Ersain Jul 11 '22 at 07:19
  • 1
    For example, if I have a `CharField` `FirstName`, I would like to add an example `Homer`. Or if we have a `UserId` field, I would like to add an example in addition to the regex pattern. – Aecturus Jul 11 '22 at 07:46

1 Answers1

0

Yes, I had trouble with this at first too.

Here's an example for a path parameter:

@extend_schema_view(
    retrieve=extend_schema(
        description='Return a given dataset',
        parameters=[
            OpenApiParameter(
                name='slug',
                description='The slug of the dataset to retrieve.',
                examples=[
                    OpenApiExample('Example dataset slug', value='GSE102725')
                ],
                required=True,
                type=OpenApiTypes.STR,
                location=OpenApiParameter.PATH
            )
        ],
        responses={
            200: DatasetSerializer(many=False),
        },
    )
)
jfunk
  • 7,176
  • 4
  • 37
  • 38