Unable to get all users inside a GraphQL query in Python

Viewed 24

I have the following code:

import graphene
import json
from datetime import datetime
import uuid

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):
    user = graphene.Field(User, username=graphene.String())
    users = graphene.List(User)

    def resolve_users(self, info):
      return [
        {
         "id":"b79b64e2-d391-4778-91b9-4d7496cbf418",
         "username":"dummy",
         "createdAt": "2022-09-03T20:07:35.611815"
        }
      ]
  
    def resolve_user(self, info, username):
      return User(username=username)


class CreateUser(graphene.Mutation):
    user = graphene.Field(User)

    class Arguments:
        username = graphene.String()

    def mutate(self, info, username):
        user = User(username=username)

        return CreateUser(user=user)


class Mutation(graphene.ObjectType):
    create_user = CreateUser.Field()


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

# Create new user.
result = schema.execute(
  '''
  mutation{
    createUser(username:"ayuse"){
      user{
        id
        username
        createdAt
        }
      }
    }
  '''
)

# Create new user.
result = schema.execute(
  '''
  mutation{
    createUser(username:"mahmud"){
      user{
        id
        username
        createdAt
        }
      }
    }
  '''
)

# Query the properties of a specific user.
result = schema.execute(
  '''
  {
    user(username: "ayuse") {
      username
      id
      createdAt
    }
  }
  '''
)

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

print("---")

# Request the ids for all of the users (This is not working).
result = schema.execute(
  '''
  {
    users {
      id
    }
  }
  '''
)

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

which, when executed yields the following output:

{
  "user": {
    "username": "ayuse",
    "id": "0c158313-f914-4276-8ff7-019f745e8d30",
    "createdAt": "2022-09-03T20:32:40.633433"
  }
}
---
{
  "users": [
    {
      "id": "b79b64e2-d391-4778-91b9-4d7496cbf418"
    }
  ]
}

Why I'm not able to see all of the users in my second query output? Right now, I'm returning a dummy user, cause I couldn't figure that bit out.

0 Answers
Related