Making a graphQL mutation from my python code, getting error

◇◆丶佛笑我妖孽 提交于 2020-08-01 19:03:43

问题


I am trying to make a mutation to my Shopify store from python. I am new to graphQL, I have been able to make the mutation using graphiQL but I am not certain how to do it directly from my code.

This is my make query file, it has worked successfully for a simple query

`import requests 
 def make_query(self, query, url, headers):
    """
    Return query response
    """
    request = requests.post(url, json={'query': query}, headers=headers)
    if request.status_code == 200:
        return request.json()
    else:
        raise Exception("Query failed to run by returning code of {}. {}".format(request.status_code, query))`

Now an example of the mutation that worked in graphiQL is this:

"mutation {customerCreate(input: {email: 'wamblamkazam@send22u.info', password: 'password'}) {userErrors { field message}customer{id}}}"

But when I pass it into my make_query function it gives this error

{'errors': [{'message': 'Parse error on "\'" (error) at [1, 41]', 'locations': [{'line': 1, 'column': 41}]}]}

How do I fix this? Also one of the mutations I am making uses variables, and I haven't been able to find an example of how to do this directly from my code


回答1:


GraphQl gives a way to send data in JSON. You can use variables in the query, and send the JSON object as the variable value:

def make_query(self, query, variables, url, headers):
    """
    Make query response
    """
    request = request.post(url, json={'query': query, 'variables': variables}, headers=headers)
    if request.status_code == 200:
        return request.json()
    else:
        raise Exception("Query failed to run by returning code of {}. {}".format(request.status_code, query))

With the query looking like this:

query = """
    mutation CreateCustomer($input:CustomerInput){
        customerCreate(customerData: $input){
            customer{
                name
            }
        }
    }
"""
variables = {'input': customer}

You can also use a small library a just found to look like this:

client = GraphQLClient('http://127.0.0.1:5000/graphql')

query = """
mutation CreateCustomer($input:CustomerInput){
    customerCreate(customerData: $input){
        customer{
            name
        }
    }
}
"""

variables = {'input': customer}

client.execute(query, variables)


来源:https://stackoverflow.com/questions/48693825/making-a-graphql-mutation-from-my-python-code-getting-error

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!