Defining different schema for both get and post request - AutoSchema Django Rest Framework

4.6k Views Asked by At

I am trying to define AutoSchema (to be shown in django rest framework swagger) for my REST API in Django REST framework. There's this class that extends APIView.

The class has both 'get' and 'post' methods. Like:

class Profile(APIView):
permission_classes = (permissions.AllowAny,)
schema = AutoSchema(
    manual_fields=[
        coreapi.Field("username",
                      required=True,
                      location='query',
                      description='Username of the user'),

    ]
)
def get(self, request):
    return
schema = AutoSchema(
    manual_fields=[
        coreapi.Field("username",
                      required=True,
                      location='form',
                      description='Username of the user '),
        coreapi.Field("bio",
                      required=True,
                      location='form',
                      description='Bio of the user'),

    ]
)
def post(self, request):
    return

The problem is I want different schema for both get and post request. How can I achieve this using AutoSchema?

2

There are 2 best solutions below

0
On

If I understand what is your problem correctly, you can define your schema in each method like this:

class Profile(APIView):
    def get(self, request):
         # your logic
         self.schema = AutoSchema(...) # your 'get' schema
         return

    def post(self, request):
        self.schema = AutoSchema(...) # your 'post' schema
        return
1
On

You can create custom Schema and override get_manual_fields method to provide custom manual_fields list based on the method:

class CustomProfileSchema(AutoSchema):
    manual_fields = []  # common fields

    def get_manual_fields(self, path, method):
        custom_fields = []
        if method.lower() == "get":
            custom_fields = [
                coreapi.Field(
                    "username",
                    required=True,
                    location='form',
                    description='Username of the user '
                ),
                coreapi.Field(
                    "bio",
                    required=True,
                    location='form',
                    description='Bio of the user'
                ),
            ]
        if method.lower() == "post":
            custom_fields = [
                coreapi.Field(
                    "username",
                    required=True,
                    location='query',
                    description='Username of the user'
                ),
            ]
        return self._manual_fields + custom_fields


class Profile(APIView):
    schema = CustomProfileSchema()
    ...