Making a graphQL mutation from my python code, getting error
Asked Answered
G

2

11

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: '[email protected]', 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

Grubb answered 8/2, 2018 at 20:0 Comment(2)
Try double quotes (") instead of single quotes for your strings, email and password.Tantalate
Same issue. Queries work but not mutations and i've tried naming the mutation and still same syntax error. Wondering if the requests lib is doing something funny with the string passed as the val.Magnuson
P
18

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 could also use a library such as python-graphql-client to make the same request:

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)
Parfleche answered 24/5, 2018 at 17:1 Comment(2)
what library is it?Brownell
@Brownell This answer features graphqlclient you can find it here: pypi.org/project/graphqlclientLegation
N
2

I tracked the mutation request through my browser and copied exactly the json that was being sent, removing the line breaks. In the code I added { "query": json } and it worked

Example I used sending 2 parameters and receiving a token:

mutation = """mutation {  
    login(    username: "myusername",    password: "mypassword",  ) 
        {   
            token 
        }
    }"""
    
res = requests.post(url, json={"query": mutation} )
Nidus answered 1/7, 2021 at 16:1 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.