joe
joe

Reputation: 9503

GraphQL response error message from DRF serializer

I can make CRUD in GraphQL using Django as a backend. My Mutation is meta class is based on DRF serializer.

I had search with term DRF, GraphQL, serializer, ... etc. Most of the will be topic related to make the endpoint, but it does not go to detail of response the error message. And most of the time I found DRF without GraphQL answer

class Question(models.Model):
    question_text = models.CharField(max_length=50)

class QuestionSerializer(serializers.ModelSerializer):
    class Meta:
        model = Question
        fields = (
            'id',
            'question_text',
        )

class QuestionSerializerMutation(SerializerMutation):

    class Meta:
        serializer_class = QuestionSerializer
        model_operation = ['crated', 'update']
        lookup_field = 'id'


class Mutation(graphene.ObjectType):
    xxx = QuestionSerializerMutation.Field()

Body

mutation{
  xxx(input: {questionText: "a;lsfjkdsajfdsjf;sjfsajdfkd;lsafjl;asfdsjf;lajflsadjf;alsjf;lasfsj"}){
    id
    questionText
  }
}

Expected result:

GraphQL return the error message from Serializer because my payload is exceed 50 characters

As is:

No error message raises

{
  "data": {
    "xxx": {
      "id": null,
      "questionText": null
    }
  }
}

Question:
How response with serializer.error in GraphQL?

Upvotes: 1

Views: 597

Answers (1)

T. Opletal
T. Opletal

Reputation: 2294

you should query for errors that have field and messages

mutation{
 xxx(input: {questionText: "a;lsfjkdsajfdsjf;sjfsajdfkd;lsafjl;asfdsjf;lajflsadjf;alsjf;lasfsj"}){
   id
   questionText
   errors {
      field
      messages
  }
 }

I actually wrote a CRUD django-graphene rest serializers library here, can check out the examples as well: https://github.com/topletal/django-model-mutations, I believe the original serializers mutations work similar

Upvotes: 4

Related Questions