Reputation: 410
Is it possible to generate a swagger UI page (and redoc for that matter) that has examples for both application/json and x-www-form-urlencoded request bodies? I can get examples for application/json, but not when selecting x-www-form-urlencoded as the request type fro the swagger/redoc UIs.
I'm using the following decorator for the "create" method (in a ModelViewSet)
@extend_schema(request=MySerializer)
where MySerializer looks like the following...
@extend_schema_serializer(
examples=[
OpenApiExample(
'Example input',
description='Creation of an alias',
value={
'user_id': 1234567890,
'obj_id': 288,
'alias': 'my alias'
},
request_only=True,
response_only=False,
),
],
)
class MySerializer(serializers.Serializer):
user_id = serializers.IntegerField()
obj_id = serializers.IntegerField()
alias = serializers.CharField(max_length=50)
The swagger/redocs UIs will happily provide an example dropbox with "Example Input" for an application/json request body (whereby selecting the example will populate the json), but for x-www-form-urlencoded will just show a form to fill in, with no example dropbox in order to populate the fields.
I can get examples (and their selection drop boxes) for query strings, i.e. when making GET endpoints that use OpenApiParameter e.g.
@extend_schema(
parameters=[
OpenApiParameter(name='q', description='Query string to search for', required=True, type=str,
examples=[
OpenApiExample(
'Search query',
value='foobar'
),
]
),
...
]
)
where selecting a drop box entry will populate the text field.
However, for x-www-form-urlencoded, this doesn't seem to get generated?
Is this possible? Am I doing something wrong?
Upvotes: 1
Views: 3429
Reputation: 1881
When it comes to example data, Redoc is very manual in that there is very little automatic generation of examples based on the schema.
AFAIK SwaggerUI does generate a basic example from the schema, however also only for JSON.
If you want to have application/x-www-form-urlencoded
examples, you likely need to specify each one manually. Not sure if the juice is worth the squeeze there.
Now to drf-spectacular: OpenApiExample
are by default JSON, so if you want a different encoding you need to explicitly set it and also provide a properly encoded value string:
OpenApiExample(
'Form-encoded example 1',
value='YOUR HANDMADE FROM ENCODED DATA STRING',
media_type='application/x-www-form-urlencoded'
)
Upvotes: 1