drf swagger ui for json field

1.1k Views Asked by At

Not able to show json array fields in swagger-ui of post body parameter. I have django model with JsonField column, the column name is showing in swagger ui but not able to show inside json values. Request you to please give your suggestion.

#models
class Sample(models.Model):
    ApiUser = models.CharField(max_length=100)
    ApiKey = models.CharField(max_length=100)
    create_array = models.JSONField()
    UserName = models.CharField(max_length=100, blank=True, null=True)
    IPAddress = models.CharField(max_length=100, blank=True, null=True)

#serializers
class SampleSerializer(serializers.ModelSerializer):
    class Meta:
        model = Sample
        fields = ('ApiUser','ApiKey','create_array','UserName','IPAddress')

for using above model and serializer I have following request body,

{
  "ApiUser": "string",
  "ApiKey": "string",
  "create_array": {},
  "UserName": "string",
  "IPAddress": "string"
}

but expected output is,

{
  "ApiUser": "string",
  "ApiKey": "string",
  "create_array": [{
  "name": "string",
  "id": "string", 
}],
  "UserName": "string",
  "IPAddress": "string"
}

enter image description here

1

There are 1 best solutions below

0
On BEST ANSWER

You could extend the serializers.JSONField class (docs). This would make your serializer look something like this:

class SampleSerializer(serializers.ModelSerializer):
    class Meta:
        model = Sample
        fields = ('ApiUser','ApiKey','create_array','UserName','IPAddress')

    class createArrayJSONField(serializer.JSONField):
        class Meta:
            swagger_schema_fields = {
                "type": openapi.TYPE_OBJECT,
                "properties": {
                    "name": openapi.Schema(
                        type=openapi.TYPE_STRING,
                    ),
                    "id": openapi.Schema(
                        type=openapi.TYPE_STRING,
                    ),
                },
                "required": ["name", "id"],
             }

    create_array = createArrayJSONField()