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:
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)
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.
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!
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With