2

I want to execute a simple GraphQL query in which I pass a variable.

import requests
import json

var = "whatever"

query = """
    query ($var: String!){
        styles(locale: "en", styleNumbers: [ $var] ) {
            styleOptions {
    parms {
        parm1
        parm2
            }
        }
        }
    }
"""

url = 'https://sth_random.io/graphql?'
response = requests.get(url, json={'query': query, '$var': var})
response = response.json()

print(response)

but I am getting the following error:

{'errors': [{'message': 'Variable "$var" of required type "String!" was not provided.', 'locations': [{'line': 2, 'column': 12}]}]}

What am I missing?

Thank you in advance.

1 Answer 1

2

The request body should include a variables key that is itself a dictionary of the variable values:

variables = {'var': var}
response = requests.post(url, json={'query': query, 'variables': variables})
Sign up to request clarification or add additional context in comments.

5 Comments

Actually this is what I tried but I thought it wasn't very important and I tried to simplify my example. Although the error remains exactly the same.
I changed that but the error remains. As I understand it is not that the call is rejected. The variable is not passed in the query.
My bad. While you prepend a $ to the variable names in the query itself, you omit the $ inside the variables object. Please see the edited answer.
We do have progress as I do not get an error, but the response is: {'data': {'styles': []}} so I understand that it doesn't point to the element of the dictionary. The variables = {'var': var} pair has a value which should return a full response.
If the server you're querying exposes a GraphiQL or GraphQL Playground interface, you can use that to test the same query. If you get the same response, then the issue is not with the client code above.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.