GraphQL tutorial with Python (`graphene`)

Page content

Original source

I followed the linke below.

https://hatemtayeb2.medium.com/hello-graphql-a-practical-guide-a2f7f9f70ab4

Install library

pip -U install graphene

Use it

scheme.py

import graphene
import json
class Query(graphene.ObjectType):
  hello = graphene.String()

  def resolve_hello(self, info):
    return "world"

schema = graphene.Schema(query=Query)
result = schema.execute(
'''
{
   hello
}
'''
)
data = dict(result.data.items())
print(json.dumps(data,indent=2))

Try the code.

$ python schema.py
{
  "hello": "world"
}

GraphQL concepts

  • Every GraphQL implementation needs a Query class that contains some fields, every field (not always) must have a resolver function that return data related to the field. Each filed is validated with a validation type system located on graphene.ObjectType.
  • graphene library has a naming convention that resolver of variable is resolve_variable.

Complex example

import graphene
import json
import uuid
from datetime import datetime

class User(graphene.ObjectType):
      id = graphene.ID(default_value=str(uuid.uuid4()))
      username = graphene.String()
      createdAt = graphene.DateTime(default_value=datetime.now())

class Query(graphene.ObjectType):
      users = graphene.List(User)
      def resolve_users(self,info,limit=None):
           return [
                   User(username="hatem"),
                   User(username="anouar"),
                   User(username="ines")
                  ]

schema = graphene.Schema(query=Query)
result = schema.execute(
'''
{
users{
   id
   username
   createdAt
   }
}

'''
)

data = dict(result.data.items())
print(json.dumps(data,indent=2))

Test the code.

$ python complex.py
{
  "users": [
    {
      "id": "2e0953a6-f1d1-4902-b786-f8bff032e291",
      "username": "hatem",
      "createdAt": "2021-02-27T17:06:39.591755"
    },
    {
      "id": "2e0953a6-f1d1-4902-b786-f8bff032e291",
      "username": "anouar",
      "createdAt": "2021-02-27T17:06:39.591755"
    },
    {
      "id": "2e0953a6-f1d1-4902-b786-f8bff032e291",
      "username": "ines",
      "createdAt": "2021-02-27T17:06:39.591755"
    }
  ]
}