Image By Rawpixel on Pixabay

Introduction to GraphQL using Django

Nidhin P
Nidhin P
Sep 5 · 4 min read

As the web evolves, the responses from the servers are becoming less and less chatty. They transformed from gigantic SOAP responses to simple JSON responses. That doesn’t stop us from inventing new methods to simplifying it further. GraphQL gives more flexibility to front end developers where they can request only the details they need. This avoids the need for parsing unnecessary data on frontend.

GraphQL was invented on Facebook in 2015 and it’s already powering their mobile apps. If you are wondering what lead to the invention of GraphQL, please check out this amazing youtube documentary by Honeypot.

In this blog, I will develop a simple Django application called books. I intend to cover the basic stuff like queries and mutations. This can go little lengthy so grab your favorite coffee and let’s start.

Apart from Django, you need packages like psycopg2 and graphene-django. Install these packages in your virtual environment.

Our app has only two models Author and Book. Both the model fields are self-explanatory.

A bit of setup is needed to integrate graphene-django to the project. Add graphene_django to INSTALLED_APPS and specify the schema file that acts as a single entry point for all the queries and mutations.

The schema file should include two classes named Query and Mutation those extend all the schemas from your apps.

GraphQL only exposes a single endpoint called GraphQL where you can to send POST request to query or mutate. Queries allow you to fetch or get data from the server, but with more flexibility than traditional REST APIs. Mutations are used to write or post data to the server.

So the next step is the expose this URL by adding it to your root URL.

Integration part is over now. We can start writing some code that is specific to GraphQL. Create a directory called GraphQL in the app which will include all the files related to GraphQL. We need one query and one mutation file to separate all the queries and mutations related to this app. One schema file to export these queries and mutations.

Roll up your sleeves it’s time to write our first query called authors that will return all the authors in our DB.

You need to specify how Author database objects need to be presented. AuthorType class does that for us. If you worked with Django Rest Framework this look familiar to model serializer class. Query class extends ObjectType from graphene_django and its fields are the queries we can ask for. authors query returns a list, so we user graphene list field taking AuthrorType as a parameter. Each field name should have a matching method called resolve_(field name) that will determine how the query needs to be handled. resolve_authors function simply gets all author objects from DB and return them. That’s it your first graphQL query is ready and waiting for action…

Go to Postman, their latest update comes with GraphQL support. Specify POST request to GraphQL endpoint. Choose GraphQL inside body and sends the query. 🎉🎉🎉🎉

querying authors with all fields

Nobody clapped yet, so send a query with the only name. Your response changed accordingly, cheers you have just seen a glimpse of how powerful GraphQL can be 😱. Front-end developers will no longer bug you for missing fields in response.

querying author but only name field is requested

You can pass arguments to queries, for example, if you want to search authors by name. Note the second keyword argument of graphene list, which is the parameter.

While querying from postman use query name as authorSearch instead of author_search because underscore fields are automatically converted to camel case.

author search query

Now we will write a mutation to create an author in our database.

Create an input object type with all the fields that we will send to create a user. Next step is to create a graphene mutation named CreateAuthor. In the inner Arguments class specify the input. A field named author is placed to determine what will be the response of this create action, in our case this is an author. Finally, create a class named Mutation extending graphene ObjectType and add CreateAuthor as one of its fields. This mutation class was already exported to app schema.

create author mutation

Tada! We have successfully created an author.

The entire project is available in Github, with query and mutation of Book, a related model of Author

The app is deployed on Heroku in case someone wants to play around with the GraphQL Book application using GraphQL

The Startup

Medium's largest active publication, followed by +528K people. Follow to join our community.

Nidhin P

Written by

Nidhin P

Backend Lead at Becon LLC

The Startup

Medium's largest active publication, followed by +528K people. Follow to join our community.

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade