Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you validate a GraphQL mutation in Python

Tags:

python

graphql

I am new to GraphQL. I am using Graphene-Django and have a mutation called CreateUser. It takes three arguments username, email, password.

How do I validate the data and return multiple errors back?

I want something like this returned.

{  
   "name":[  
      "Ensure this field has at least 2 characters."
   ],
   "email":[  
      "This field may not be blank."
   ],
   "password":[  
      "This field may not be blank."
   ]
}

So I can render the errors on the form like this:

enter image description here

My code so far:

from django.contrib.auth.models import User as UserModel
from graphene_django import DjangoObjectType
import graphene


class User(DjangoObjectType):
    class Meta:
        model = UserModel
        only_fields = 'id', 'username', 'email'


class Query(graphene.ObjectType):
    users = graphene.List(User)
    user = graphene.Field(User, id=graphene.Int())

    def resolve_users(self, info):
        return UserModel.objects.all()

    def resolve_user(self, info, **kwargs):
        try:
            return UserModel.objects.get(id=kwargs['id'])
        except (UserModel.DoesNotExist, KeyError):
            return None


class CreateUser(graphene.Mutation):

    class Arguments:
        username = graphene.String()
        email = graphene.String()
        password = graphene.String()

    user = graphene.Field(User)

    def mutate(self, info, username, email, password):
        user = UserModel.objects.create_user(username=username, email=email, password=password)
        return CreateUser(user=user)


class Mutation(graphene.ObjectType):
    create_user = CreateUser.Field()


schema = graphene.Schema(query=Query, mutation=Mutation)
like image 310
Neil Avatar asked Mar 14 '18 16:03

Neil


People also ask

Can we use GraphQL with Python?

And GraphQL APIs are very easy to work with using Python. In this tutorial, we will explore ActiveState's GraphQL API through the GQL 3 GraphQL Client for Python.


1 Answers

Model errors in the schema, primarily by using unions.

In SDL format:

type RegisterUserSuccess {
  user: User!
}

type FieldError {
  fieldName: String!
  errors: [String!]!
}

type RegisterUserError {
  fieldErrors: [FieldError!]!
  nonFieldErrors: [String!]!
}


union RegisterUserPayload = RegisterUserSuccess | RegisterUserError

mutation {
  registerUser(name: String, email: String, password: String): RegisterUserPayload!
}
like image 196
Andrew Ingram Avatar answered Oct 05 '22 23:10

Andrew Ingram