GraphQL Variables Help Please

Solved
AJ_MotorSport
Excursionist
34 0 4

Hello,

Being relatively new to GraphQL, I still have a bunch of basic questions.

 

How can I use variables in GraphQL when done via the Shopify Python API library?

Here is the documentation for variables in GraphQL.

 

In the github page for the python API library, there is an example for GraphQL

client = shopify.GraphQL()
  query = '''
    {
      shop {
        name
        id
      }
    }
  '''
  result = client.execute(query)

 

Yet how can I use pass variables to a query/API call?

 

AJ_MotorSport
Excursionist
34 0 4

Touching base here. 

I still haven't found how variables can be sent via the Shopify Python API library to the GraphQL endpoint.

 

Any ideas?

Thanks!

hassain
Shopify Staff (Retired)
Shopify Staff (Retired)
623 103 141

This is an accepted solution.

Hi @AJ_MotorSport ,

 

Yes you can send variables in GraphQL queries and mutations via the Shopify Python API library. This can be easily verified if you look at the GraphQL class defined within the Shopify Python API library: https://github.com/Shopify/shopify_python_api/blob/master/shopify/resources/graphql.py. You can see that the "execute" method also accepts an optional 'variables' parameter along with the expected 'query' parameter. 

 

Here is an example of how to use GraphQL variables in the Shopify Python API library. In this is an example, I am using the library to create a new product with the productCreate GraphQL mutation and the "productInput" object defined as a variable:

 

client = shopify.GraphQL()
query = '''
mutation productCreate($input: ProductInput!) {
			productCreate(input: $input) {
				product {
					id
				}
			}
		}
  '''
variables = { "input": { "title": "Variable Test", "productType": "product 7", "vendor": "999 Vendor", "variants": [{"price": "34.50"}]} }

result = client.execute(query, variables)
json_result = json.loads(result)
print("ID of the newly created product is: " + json_result["data"]["productCreate"]["product"]["id"])

Hassain | Developer Support Specialist @ Shopify
 - Was my reply helpful? Click Like to let me know! 
 - Was your question answered? Click Accept as Solution 

Hisham
Tourist
6 0 1

Take a look at this, it uses Python + GraphQL + Pagination to get orders, and dynamically builds the GraphQL query.

 

https://github.com/mardambey/shopify-python-graphql-pagination

0 Likes
YuriS
Tourist
14 0 3

Thanks for this! It's been two days that I'm looking for a working Shopify GQL example. It's unclear to me why this is not part of any documentation.

AJ_MotorSport
Excursionist
34 0 4

I'm glad Hassain's answer helped you.

 

I suspect that the variable example is not in the documentation because it's something so basic that it's flying over our heads (mine and yours).

 

0 Likes