GraphQL Variables Help Please

Solved
Highlighted
Excursionist
17 0 1

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?

 

0 Likes
Highlighted
Excursionist
17 0 1

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!

0 Likes
Highlighted
Shopify Staff (Retired)
Shopify Staff (Retired)
624 102 119

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 

2 Likes
Highlighted
New Member
5 0 0

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
Highlighted
Tourist
12 0 1

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.

1 Like
Highlighted
Excursionist
17 0 1

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