Tuan nguyen
Tuan nguyen

Reputation: 570

Django DRF: Schema for bulk creation api

I'm using django-rest-framework to build my API in which supports bulk create/update. In these cases, the api will accept a list of object like

[
    {"foo":"bar"},
    {"foo":"bar"}
]

The code I'm using to allow bulk apis is just a small modification to add option many=True for serializer if the data is a list. It's like:

class FooViewSet(views.ModelViewSet):
    def create(self, request, *args, **kwargs):
        many = isinstance(request.data, list)
        if many:
            serializer = self.get_serializer(data=request.data, many=True)
            serializer.is_valid(raise_exception=True)
            self.perform_bulk_create(serializer)
        else:
            ................

I'm using drf_yasg for api doc generation. But the problem is the schema generated keep detecting my request body just the single model only. Is there any config to make DRF schema generator knows that it will accept a list type?

Here is the schema which DRF generated

{
  "post": {
    "operationId": "foos_create",
    "description": "",
    "parameters": [
      {
        "name": "data",
        "in": "body",
        "required": true,
        "schema": {
          "$ref": "#/definitions/Foo"
        }
      }
    ],
    "responses": {
      "201": {
        "description": "",
        "schema": {
          "$ref": "#/definitions/Foo"
        }
      }
    },
    "tags": [
      "foos"
    ]
  }
}

My expectation is the schema would be the array type of Foo definition

Any help will be appreciated. Thanks for your time.

Upvotes: 1

Views: 586

Answers (1)

Sneha
Sneha

Reputation: 31

I know it very old post but I was facing a similar issue, and as a noob in DRF and python took a while to figure this stuff out. I just had to add a simple decorator. FYI I have used https://github.com/miki725/django-rest-framework-bulk for the bulk update.

@method_decorator(name='perform_bulk_create', decorator=swagger_auto_schema(
    request_body=ContactSerializer(many=True),
    operation_description="post list of contacts"
))

Upvotes: 3

Related Questions