So I am trying to write a graphql python script which will send mutations to my backend. I therefore created a "client" module (based on https://github.com/prisma-labs/python-graphql-client) to export a class GraphQLClient which looks like this:
import urllib.request
import json
class GraphQLClient:
def __init__(self, endpoint):
self.endpoint = endpoint
def execute(self, query, variables=None):
return self._send(query, variables)
def _send(self, query, variables):
data = {'query': query,
'variables': variables}
headers = {'Accept': 'application/json',
'Content-Type': 'application/json'}
req = urllib.request.Request(
self.endpoint, json.dumps(data).encode('utf-8'), headers)
try:
response = urllib.request.urlopen(req)
return response.read().decode('utf-8')
except urllib.error.HTTPError as e:
print((e.read()))
print('')
raise e
So far so good. My main code will look like this for now just to test if everything is working:
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import sys
from client import GraphQLClient
if __name__ == "__main__":
playerId = 3
_round = 3
number = 5
modifier = 3
client = GraphQLClient('http://localhost:4000/graphql')
result = client.execute('''
{
allPlayers {
id
name
nickname
}
}
''')
result2 = client.execute('''
mutation{
createThrow(playerId: {}, round: {}, number:{}, modifier:{}) {
id
round
number
modifier
}
}
'''.format(playerId, _round, number, modifier))
print(result)
print(result2)
Whereas the allPlayers query will in fact return data the mutation to insert a throw will not work and fail with the following error Traceback:
Traceback (most recent call last):
File "./input.py", line 25, in <module>
result2 = client.execute('''
KeyError: '\n createThrow(playerId'
I am trying this since hours I'd say but cannot figure how to do it. When I am hardcoding the variables into the query instead of formatting the multiline string it will work just fine. So the basic mutation will work. Problem has to be in formatting the string with variables.
I also tried f-strings, named formatting and any other trick I know.
So I will be grateful if anyone would point me in a general direction.