how-to-perform-crud-operations-with-mutation-in-graphql

In our previous blog, we had seen a brief introduction about graphql and created some records using graphql queries. In this blog, we are going to continue with a mutation in graphql. We are going to see the importance of mutations in graphql.

Introduction

Mutation in graphql allows users to create, update and delete the data from your database. Mutation should return an object type for querying the nested field.

How to write a simple mutation?

  • define a class of the desired names and derive it from “graphene.Mutation”
  • list object type to return from mutation
  • define arguments that a user needs to pass
  • define a class with name mutate and add functionality inside this function

We are going to continue with the coding part of the previous tutorial of graphql. So, let’s start the tutorial

 

Mutation in GraphQL

Creating the new records

Open the Api > schema.py file and add the following code

#Adding new Book's details
class CreateBook(graphene.Mutation):
    message = graphene.String()
    book = graphene.Field(BookType)

    class Arguments:
        title = graphene.String(required = True, description="Title of Book")
        author = graphene.String(required = True, description="Author of Book")
        description = graphene.String(required = True, description="Overview of the Book")

    @classmethod
    def mutate(cls, root, info, **kwargs):
        try:
            book = Book.objects.create(
                title = kwargs.get('title'),
                author = kwargs.get('author'),
                description = kwargs.get('description')
            )
            book.save()
            return CreateBook(book=book, message="Successfully added new book details")
        except ObjectDoesNotExist:
            raise GraphQLError("Object doesn't exists.")

        except Exception as e:
            raise GraphQLError("Error " + str(e))

#overall mutations
class Mutation(graphene.ObjectType):
    create_book = CreateBook.Field()

 

Also, open Books > schema.py file

import graphene
import Api.schema

class Query(
    Api.schema.BookQuery
):
    pass

class Mutation(
    Api.schema.Mutation,
):
    pass

schema = graphene.Schema(query=Query, mutation=Mutation)

Elucidation

As mentioned in those steps earlier, at first, we created a class derived from “graphene.Mutation”. And then defined message and book as the return type of this mutation.

After that, we define a class with the name Arguments (remember that this should be the only name). Then we use a class method decorator and inside it, we define a mutate function (keep in mind that the function name should be “mutate”) and add the functionality that we need.

Output

Go to URL http://127.0.0.1:8000/graphql/ and write your schema as

Write schema for graphql

 

After this go to the admin panel and refresh and check the records under book, you will see

output of createbook

 

Editing the existing records

Open the Api > schema.py file and add the following

#Edit Book's details
class EditBook(graphene.Mutation):
    message = graphene.String()
    book = graphene.Field(BookType)

    class Arguments:
        id = graphene.Int(required=True, description="Id of the Book of which data is to be edited")
        title = graphene.String(description="Title of Book")
        author = graphene.String(description="Author of Book")
        description = graphene.String(description="Overview of the Book")

    @classmethod
    def mutate(cls, root, info, **kwargs):
        try:
            book = Book.objects.get(pk=kwargs.get('id'))
            book.title = kwargs.get('title', book.title)
            book.author = kwargs.get('author',book.author)
            book.description = kwargs.get('description', book.description)
            book.save()
            return EditBook(book=book, message="successfully updated the book")

        except ObjectDoesNotExist:
            raise GraphQLError("Object Doesn't exists")

        except Exception as e:
            raise GraphQLError("Error " + str(e))

#overall mutations
class Mutation(graphene.ObjectType):
    create_book = CreateBook.Field()

    #add this line
    edit_book = EditBook.Field()

Output

Go to URL http://127.0.0.1:8000/graphql/ and write your schema as

Edit book in django model

You will see a message that you return from your mutation. Now, go to the admin panel and you will see something like this

Edited book

Here, the arguments are id, title, author, and description of the book. If you observe closely, the user must provide the id which is compulsory (id of the book which is to be edited) while other arguments can be passed according to the user’s choice as these are not compulsory.

 

Deleting the records

Go to URL http://127.0.0.1:8000/graphql/ and write your schema as

delete data with mutation in graphql

 

Now, go to the admin panel and you will see the record with id 3 is no longer available in the database

deleted data with mutations in graphql

Conclusion

So, this is how we can perform CRUD operations with a mutation in graphql. If an API has an endpoint that inserts, updates, and deletes the records then it is very easy to implement the mutation as an endpoint with a mutation in graphql.

Leave a Reply

Your email address will not be published.