Creating fake model in djanago rest framework without migrating it for using in swagger
I am trying to implement swagger ui using in Django Rest Framework using drf-spectacular. I don't have any database insatlled yet and in this phase I don't want to implement or create any database or table. I only want to create an API Contract with different Endpoints and showing required and response data types in swagger ui.
My question is, that how can I create a model (fake model) without implementing it and without migration?
You can create a serializer and implement all required fields there. If you need different serializers for request and response just pass them in swagger_auto_schema decorator. Use request_body parameter for request one and responses for response. Here's an example:
class MyRequestSerializer(serializers.Serializer):
first_name = serializers.Charfield(max_length=128)
last_name = serializers.Charfield(max_length=128, allow_blank=True)
class MyResponseSerializer(serializer.Serializer):
my_custom_response_field = serializers.IntegerField()
class MyAPIView(APIView):
@swagger_auto_schema(request_body=MyRequestSerializer(), responses={200: MyResponseSerializer()})
def get(self, request, format=None):
request_data = MyRequestSerializer(request.data)
do_smth
response_serializer = MyResponseSerializer(request_data)
return Response(response_serializer.data)