What is GraphQL and how to use GraphQL in Django? #01

What is GraphQL and how to use GraphQL in Django? #01

Subscribe to my newsletter and never miss my upcoming articles

What is GraphQL?

A query language for your API

Before we start, let's get to know what is GraphQL? If we refer to its docs, GraphQL is a query language for APIs and a runtime for fulfilling those queries with your existing data. GraphQL provides a complete and understandable description of the data in your API, gives clients the power to ask for exactly what they need and nothing more, makes it easier to evolve APIs over time, and enables powerful developer tools. In a simple way, get the specific data that is described in scheme, not much, not less.

Ask for what you need, get exactly that

Send a GraphQL query to your API and get exactly what you need, nothing more and nothing less. GraphQL queries always return predictable results. With the help of GraphQL, we get complete control over data.

graphql

Let's consider examples below to differentiate REST and GraphQL:

// We made simpe api call here
fetch('https://jsonplaceholder.typicode.com/users/')
  .then(response => response.json())
  .then(json => console.log(json))
# Result data

[
  {
    "id": 1,
    "name": "Leanne Graham",
    "username": "Bret",
    "email": "Sincere@april.biz",
    "address": {
      "street": "Kulas Light",
      .....
      }
    },
    "phone": "1-770-736-8031 x56442",
    "website": "hildegard.org",
    "company": {
      "name": "Romaguera-Crona",
      .....
    }
  },
....

In the GraphQL way:

// We have defined Query and User type
type Query {
  me: User
}

type User {
  id: ID
  name: String
  email: String
  address: String
}

We can get specific data with the GraphQL query:

{
  me {
    name
  }
}

The result doesn't return all the data like REST, instead return particular fields:

{
  "me": {
    "name": "Luke Skywalker"
  }
}

What is Graphene?

Graphene is a Python library we can integrate GraphQL to our python applications simply. Graphene is an extensible framework that will work out of the box with the current stack. Also, graphene offers some integrations to fasten our development process:

We'll be using Graphene-Django to integrate GraphQL with the Django application.

Installation

Graphene-Django currently supports the following versions of Django:

  • >= Django 1.11
pip install graphene-django

In the next part of the series, we will go through creating the Django GraphQL application more deeply.

 
Share this