1131
1131

Reputation: 407

Call GraphQL API with String variable

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.

Upvotes: 2

Views: 1239

Answers (1)

Daniel Rearden
Daniel Rearden

Reputation: 84857

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})

Upvotes: 2

Related Questions